From 466d3a402970e1ffe989ce2a075926d4880f0d82 Mon Sep 17 00:00:00 2001 From: Sam Lantinga Date: Mon, 10 Jul 2006 21:04:37 +0000 Subject: [PATCH] SDL 1.2 is moving to a branch, and SDL 1.3 is becoming the head. --- .indent.pro | 1 + CWprojects.sea.bin | Bin 476160 -> 476160 bytes Makefile.dc | 1 + Makefile.in | 23 + README.OS2 | 16 +- TODO | 3 + UNDER_CONSTRUCTION.txt | 1 + VisualC.zip | Bin 42466 -> 42466 bytes Watcom-OS2.zip | Bin 63088 -> 63017 bytes WhatsNew | 10 +- configure.in | 78 +- docs.html | 58 - include/SDL.h | 62 +- include/SDL_active.h | 58 - include/SDL_audio.h | 130 +- include/SDL_cdrom.h | 81 +- include/SDL_compat.h | 186 + include/SDL_config.h.in | 9 +- include/SDL_config_amiga.h | 1 + include/SDL_config_dreamcast.h | 1 + include/SDL_config_macos.h | 19 +- include/SDL_config_os2.h | 20 +- include/SDL_config_win32.h | 34 +- include/SDL_copying.h | 1 - include/SDL_cpuinfo.h | 13 +- include/SDL_endian.h | 146 +- include/SDL_error.h | 28 +- include/SDL_events.h | 481 +- include/SDL_joystick.h | 40 +- include/SDL_keyboard.h | 151 +- include/SDL_keysym.h | 466 +- include/SDL_loadso.h | 46 +- include/SDL_main.h | 19 +- include/SDL_mouse.h | 177 +- include/SDL_mutex.h | 50 +- include/SDL_opengl.h | 27 +- include/SDL_pixels.h | 348 ++ include/SDL_quit.h | 6 +- include/SDL_rwops.h | 151 +- include/SDL_stdinc.h | 194 +- include/SDL_syswm.h | 197 +- include/SDL_thread.h | 62 +- include/SDL_timer.h | 27 +- include/SDL_version.h | 99 +- include/SDL_video.h | 1741 ++++-- include/begin_code.h | 4 +- include/close_code.h | 1 - include/doxyfile | 1229 +++++ sdl-config.in | 2 +- src/SDL.c | 367 +- src/SDL_compat.c | 1415 +++++ src/SDL_error.c | 345 +- src/SDL_error_c.h | 45 +- src/SDL_fatal.c | 126 +- src/SDL_fatal.h | 2 +- src/audio/SDL_audio.c | 1132 ++-- src/audio/SDL_audio_c.h | 3 +- src/audio/SDL_audiocvt.c | 2762 +++++----- src/audio/SDL_audiodev.c | 198 +- src/audio/SDL_audiodev_c.h | 2 +- src/audio/SDL_audiomem.h | 1 + src/audio/SDL_mixer.c | 371 +- src/audio/SDL_mixer_MMX.c | 226 +- src/audio/SDL_mixer_MMX.h | 6 +- src/audio/SDL_mixer_MMX_VC.c | 13 +- src/audio/SDL_mixer_MMX_VC.h | 5 +- src/audio/SDL_mixer_m68k.c | 267 +- src/audio/SDL_mixer_m68k.h | 10 +- src/audio/SDL_sysaudio.h | 123 +- src/audio/SDL_wave.c | 1077 ++-- src/audio/SDL_wave.h | 38 +- src/audio/alsa/SDL_alsa_audio.c | 879 +-- src/audio/alsa/SDL_alsa_audio.h | 18 +- src/audio/amigaos/SDL_ahiaudio.c | 527 +- src/audio/amigaos/SDL_ahiaudio.h | 18 +- src/audio/arts/SDL_artsaudio.c | 454 +- src/audio/arts/SDL_artsaudio.h | 27 +- src/audio/baudio/SDL_beaudio.cc | 332 +- src/audio/baudio/SDL_beaudio.h | 6 +- src/audio/bsd/SDL_bsdaudio.c | 418 +- src/audio/bsd/SDL_bsdaudio.h | 5 +- src/audio/dart/SDL_dart.c | 648 +-- src/audio/dart/SDL_dart.h | 31 +- src/audio/dc/SDL_dcaudio.c | 327 +- src/audio/dc/SDL_dcaudio.h | 16 +- src/audio/dc/aica.c | 310 +- src/audio/dc/aica.h | 10 +- src/audio/disk/SDL_diskaudio.c | 191 +- src/audio/disk/SDL_diskaudio.h | 14 +- src/audio/dma/SDL_dmaaudio.c | 694 +-- src/audio/dma/SDL_dmaaudio.h | 34 +- src/audio/dmedia/SDL_irixaudio.c | 271 +- src/audio/dmedia/SDL_irixaudio.h | 10 +- src/audio/dsp/SDL_dspaudio.c | 453 +- src/audio/dsp/SDL_dspaudio.h | 20 +- src/audio/dummy/SDL_dummyaudio.c | 175 +- src/audio/dummy/SDL_dummyaudio.h | 14 +- src/audio/esd/SDL_esdaudio.c | 434 +- src/audio/esd/SDL_esdaudio.h | 26 +- src/audio/macosx/SDL_coreaudio.c | 160 +- src/audio/macosx/SDL_coreaudio.h | 12 +- src/audio/macrom/SDL_romaudio.c | 417 +- src/audio/macrom/SDL_romaudio.h | 14 +- src/audio/mint/SDL_mintaudio.c | 257 +- src/audio/mint/SDL_mintaudio.h | 116 +- src/audio/mint/SDL_mintaudio_dma8.c | 400 +- src/audio/mint/SDL_mintaudio_dma8.h | 98 +- src/audio/mint/SDL_mintaudio_gsxb.c | 518 +- src/audio/mint/SDL_mintaudio_gsxb.h | 15 +- src/audio/mint/SDL_mintaudio_mcsn.c | 510 +- src/audio/mint/SDL_mintaudio_mcsn.h | 49 +- src/audio/mint/SDL_mintaudio_stfa.c | 340 +- src/audio/mint/SDL_mintaudio_stfa.h | 93 +- src/audio/mint/SDL_mintaudio_xbios.c | 659 +-- src/audio/mme/SDL_mmeaudio.c | 240 +- src/audio/mme/SDL_mmeaudio.h | 9 +- src/audio/nas/SDL_nasaudio.c | 411 +- src/audio/nas/SDL_nasaudio.h | 37 +- src/audio/nto/SDL_nto_audio.c | 371 +- src/audio/nto/SDL_nto_audio.h | 7 +- src/audio/paudio/SDL_paudio.c | 734 +-- src/audio/paudio/SDL_paudio.h | 26 +- src/audio/sun/SDL_sunaudio.c | 602 ++- src/audio/sun/SDL_sunaudio.h | 24 +- src/audio/ums/SDL_umsaudio.c | 450 +- src/audio/ums/SDL_umsaudio.h | 4 +- src/audio/windib/SDL_dibaudio.c | 426 +- src/audio/windib/SDL_dibaudio.h | 18 +- src/audio/windx5/SDL_dx5audio.c | 1124 ++-- src/audio/windx5/SDL_dx5audio.h | 19 +- src/audio/windx5/directx.h | 1 + src/cdrom/SDL_cdrom.c | 521 +- src/cdrom/SDL_syscdrom.h | 57 +- src/cdrom/aix/SDL_syscdrom.c | 756 +-- src/cdrom/beos/SDL_syscdrom.cc | 570 +- src/cdrom/bsdi/SDL_syscdrom.c | 829 +-- src/cdrom/dc/SDL_syscdrom.c | 190 +- src/cdrom/dummy/SDL_syscdrom.c | 11 +- src/cdrom/freebsd/SDL_syscdrom.c | 597 ++- src/cdrom/linux/SDL_syscdrom.c | 766 +-- src/cdrom/macos/SDL_syscdrom.c | 858 +-- src/cdrom/macos/SDL_syscdrom_c.h | 170 +- src/cdrom/macosx/AudioFilePlayer.c | 286 +- src/cdrom/macosx/AudioFilePlayer.h | 167 +- src/cdrom/macosx/AudioFileReaderThread.c | 536 +- src/cdrom/macosx/CDPlayer.c | 702 +-- src/cdrom/macosx/CDPlayer.h | 29 +- src/cdrom/macosx/SDLOSXCAGuard.c | 58 +- src/cdrom/macosx/SDLOSXCAGuard.h | 18 +- src/cdrom/macosx/SDL_syscdrom.c | 468 +- src/cdrom/macosx/SDL_syscdrom_c.h | 2 +- src/cdrom/mint/SDL_syscdrom.c | 426 +- src/cdrom/openbsd/SDL_syscdrom.c | 600 ++- src/cdrom/os2/SDL_syscdrom.c | 559 +- src/cdrom/osf/SDL_syscdrom.c | 511 +- src/cdrom/qnx/SDL_syscdrom.c | 472 +- src/cdrom/win32/SDL_syscdrom.c | 537 +- src/cpuinfo/SDL_cpuinfo.c | 317 +- src/events/SDL_active.c | 91 - src/events/SDL_events.c | 734 +-- src/events/SDL_events_c.h | 44 +- src/events/SDL_expose.c | 51 - src/events/SDL_keyboard.c | 1197 +++-- src/events/SDL_keyboard_c.h | 96 + src/events/SDL_mouse.c | 800 ++- src/events/SDL_mouse_c.h | 112 + src/events/SDL_quit.c | 82 +- src/events/SDL_resize.c | 75 - src/events/SDL_sysevents.h | 11 +- src/events/SDL_windowevents.c | 132 + src/events/SDL_windowevents_c.h | 32 + src/{video => events}/blank_cursor.h | 1 + src/{video => events}/default_cursor.h | 141 +- src/file/SDL_rwops.c | 850 +-- src/hermes/HeadMMX.h | 71 +- src/hermes/HeadX86.h | 177 +- src/joystick/SDL_joystick.c | 811 +-- src/joystick/SDL_joystick_c.h | 11 +- src/joystick/SDL_sysjoystick.h | 54 +- src/joystick/amigaos/SDL_sysjoystick.c | 246 +- src/joystick/beos/SDL_bejoystick.cc | 337 +- src/joystick/bsd/SDL_sysjoystick.c | 796 +-- src/joystick/darwin/SDL_sysjoystick.c | 1251 ++--- src/joystick/dc/SDL_sysjoystick.c | 237 +- src/joystick/dummy/SDL_sysjoystick.c | 37 +- src/joystick/linux/SDL_sysjoystick.c | 1768 +++--- src/joystick/macos/SDL_sysjoystick.c | 237 +- src/joystick/mint/SDL_sysjoystick.c | 999 ++-- src/joystick/os2/SDL_sysjoystick.c | 938 ++-- src/joystick/os2/joyos2.h | 98 +- src/joystick/riscos/SDL_sysjoystick.c | 172 +- src/joystick/win32/SDL_dxjoystick.c | 579 ++ src/joystick/win32/SDL_mmjoystick.c | 629 +-- src/loadso/beos/SDL_sysloadso.c | 66 +- src/loadso/dlopen/SDL_sysloadso.c | 55 +- src/loadso/dummy/SDL_sysloadso.c | 22 +- src/loadso/macos/SDL_sysloadso.c | 116 +- src/loadso/macosx/SDL_dlcompat.c | 1882 ++++--- src/loadso/mint/SDL_sysloadso.c | 40 +- src/loadso/os2/SDL_sysloadso.c | 21 +- src/loadso/win32/SDL_sysloadso.c | 181 +- src/main/beos/SDL_BeApp.cc | 122 +- src/main/beos/SDL_BeApp.h | 1 + src/main/dummy/SDL_dummy_main.c | 6 +- src/main/macos/SDL_main.c | 799 +-- src/main/macos/exports/SDL.x | 3 - src/main/macosx/SDLMain.h | 4 +- src/main/qtopia/SDL_qtopia_main.cc | 45 +- src/main/win32/SDL_win32_main.c | 395 +- src/stdlib/SDL_getenv.c | 370 +- src/stdlib/SDL_iconv.c | 1485 +++--- src/stdlib/SDL_malloc.c | 4116 +++++++------- src/stdlib/SDL_qsort.c | 290 +- src/stdlib/SDL_stdlib.c | 1054 ++-- src/stdlib/SDL_string.c | 1005 ++-- src/thread/SDL_systhread.h | 11 +- src/thread/SDL_thread.c | 419 +- src/thread/SDL_thread_c.h | 14 +- src/thread/amigaos/SDL_syssem.c | 164 +- src/thread/amigaos/SDL_systhread.c | 168 +- src/thread/amigaos/SDL_systhread_c.h | 4 +- src/thread/amigaos/SDL_thread.c | 391 +- src/thread/beos/SDL_syssem.c | 176 +- src/thread/beos/SDL_systhread.c | 81 +- src/thread/beos/SDL_systhread_c.h | 6 +- src/thread/dc/SDL_syscond.c | 284 +- src/thread/dc/SDL_syscond_c.h | 2 +- src/thread/dc/SDL_sysmutex.c | 145 +- src/thread/dc/SDL_sysmutex_c.h | 2 +- src/thread/dc/SDL_syssem.c | 165 +- src/thread/dc/SDL_syssem_c.h | 2 +- src/thread/dc/SDL_systhread.c | 37 +- src/thread/dc/SDL_systhread_c.h | 3 +- src/thread/epoc/SDL_systhread_c.h | 2 +- src/thread/generic/SDL_syscond.c | 284 +- src/thread/generic/SDL_sysmutex.c | 161 +- src/thread/generic/SDL_sysmutex_c.h | 2 +- src/thread/generic/SDL_syssem.c | 265 +- src/thread/generic/SDL_systhread.c | 28 +- src/thread/generic/SDL_systhread_c.h | 1 + src/thread/irix/SDL_syssem.c | 261 +- src/thread/irix/SDL_systhread.c | 62 +- src/thread/irix/SDL_systhread_c.h | 2 +- src/thread/os2/SDL_syscond.c | 284 +- src/thread/os2/SDL_syscond_c.h | 2 +- src/thread/os2/SDL_sysmutex.c | 111 +- src/thread/os2/SDL_syssem.c | 234 +- src/thread/os2/SDL_systhread.c | 105 +- src/thread/os2/SDL_systhread_c.h | 2 +- src/thread/pth/SDL_syscond.c | 163 +- src/thread/pth/SDL_sysmutex.c | 72 +- src/thread/pth/SDL_sysmutex_c.h | 6 +- src/thread/pth/SDL_systhread.c | 98 +- src/thread/pth/SDL_systhread_c.h | 1 + src/thread/pthread/SDL_syscond.c | 196 +- src/thread/pthread/SDL_sysmutex.c | 179 +- src/thread/pthread/SDL_sysmutex_c.h | 6 +- src/thread/pthread/SDL_syssem.c | 199 +- src/thread/pthread/SDL_systhread.c | 106 +- src/thread/pthread/SDL_systhread_c.h | 1 + src/thread/riscos/SDL_syscond.c | 195 +- src/thread/riscos/SDL_sysmutex.c | 176 +- src/thread/riscos/SDL_sysmutex_c.h | 6 +- src/thread/riscos/SDL_syssem.c | 252 +- src/thread/riscos/SDL_systhread.c | 139 +- src/thread/riscos/SDL_systhread_c.h | 1 + src/thread/win32/SDL_sysmutex.c | 99 +- src/thread/win32/SDL_syssem.c | 186 +- src/thread/win32/SDL_systhread.c | 165 +- src/thread/win32/SDL_systhread_c.h | 2 +- src/thread/win32/win_ce_semaphore.c | 308 +- src/thread/win32/win_ce_semaphore.h | 27 +- src/timer/SDL_systimer.h | 1 + src/timer/SDL_timer.c | 397 +- src/timer/SDL_timer_c.h | 1 + src/timer/amigaos/SDL_systimer.c | 255 +- src/timer/beos/SDL_systimer.c | 73 +- src/timer/dc/SDL_systimer.c | 73 +- src/timer/dummy/SDL_systimer.c | 71 +- src/timer/macos/FastTimes.c | 432 +- src/timer/macos/FastTimes.h | 9 +- src/timer/macos/SDL_MPWtimer.c | 135 +- src/timer/macos/SDL_systimer.c | 141 +- src/timer/mint/SDL_systimer.c | 139 +- src/timer/mint/SDL_vbltimer_s.h | 1 + src/timer/os2/SDL_systimer.c | 282 +- src/timer/riscos/SDL_systimer.c | 202 +- src/timer/unix/SDL_systimer.c | 229 +- src/timer/win32/SDL_systimer.c | 147 +- src/timer/wince/SDL_systimer.c | 201 +- src/video/SDL_RLEaccel.c | 1283 ++--- src/video/SDL_RLEaccel_c.h | 13 +- src/video/SDL_blit.c | 522 +- src/video/SDL_blit.h | 70 +- src/video/SDL_blit_0.c | 822 +-- src/video/SDL_blit_1.c | 680 +-- src/video/SDL_blit_A.c | 2216 ++++---- src/video/SDL_blit_N.c | 3077 +++++------ src/video/SDL_bmp.c | 918 ++-- src/video/SDL_cursor.c | 751 --- src/video/SDL_cursor_c.h | 73 - src/video/SDL_gamma.c | 331 +- src/video/SDL_glfuncs.h | 785 +-- src/video/SDL_leaks.h | 1 + src/video/SDL_pixels.c | 1251 +++-- src/video/SDL_pixels_c.h | 25 +- src/video/SDL_rect.c | 189 + src/video/SDL_rect_c.h | 41 + src/video/SDL_renderer_sw.c | 533 ++ .../video/SDL_renderer_sw.h | 8 +- src/video/SDL_stretch.c | 447 +- src/video/SDL_stretch_c.h | 6 +- src/video/SDL_surface.c | 1643 +++--- src/video/SDL_sysvideo.h | 588 +- src/video/SDL_video.c | 3806 +++++++------ src/video/SDL_yuv.c | 137 - src/video/SDL_yuv_mmx.c | 587 +- src/video/SDL_yuv_sw.c | 1627 +++--- src/video/SDL_yuv_sw_c.h | 29 +- src/video/Xext/XME/xme.c | 492 +- src/video/Xext/Xinerama/Xinerama.c | 317 +- src/video/Xext/Xv/Xv.c | 1812 +++---- src/video/Xext/Xv/Xvlibint.h | 3 +- src/video/Xext/Xxf86dga/XF86DGA.c | 457 +- src/video/Xext/Xxf86dga/XF86DGA2.c | 875 ++- src/video/Xext/Xxf86vm/XF86VMode.c | 1365 ++--- src/video/Xext/extensions/Xext.h | 20 +- src/video/Xext/extensions/Xinerama.h | 37 +- src/video/Xext/extensions/Xv.h | 2 +- src/video/Xext/extensions/Xvlib.h | 578 +- src/video/Xext/extensions/Xvproto.h | 814 +-- src/video/Xext/extensions/extutil.h | 176 +- src/video/Xext/extensions/panoramiXext.h | 30 +- src/video/Xext/extensions/panoramiXproto.h | 238 +- src/video/Xext/extensions/xf86dga.h | 322 +- src/video/Xext/extensions/xf86dga1.h | 158 +- src/video/Xext/extensions/xf86dga1str.h | 274 +- src/video/Xext/extensions/xf86dgastr.h | 510 +- src/video/Xext/extensions/xf86vmode.h | 376 +- src/video/Xext/extensions/xf86vmstr.h | 817 +-- src/video/Xext/extensions/xme.h | 41 +- src/video/aalib/SDL_aaevents.c | 315 +- src/video/aalib/SDL_aaevents_c.h | 3 +- src/video/aalib/SDL_aamouse.c | 6 +- src/video/aalib/SDL_aamouse_c.h | 1 + src/video/aalib/SDL_aavideo.c | 549 +- src/video/aalib/SDL_aavideo.h | 14 +- src/video/ataricommon/SDL_ataric2p_s.h | 51 +- src/video/ataricommon/SDL_ataridevmouse.c | 211 +- src/video/ataricommon/SDL_ataridevmouse_c.h | 1 + src/video/ataricommon/SDL_atarieddi_s.h | 21 +- src/video/ataricommon/SDL_atarievents.c | 218 +- src/video/ataricommon/SDL_atarievents_c.h | 3 +- src/video/ataricommon/SDL_atarigl.c | 1841 +++---- src/video/ataricommon/SDL_atarigl_c.h | 78 +- src/video/ataricommon/SDL_atarikeys.h | 3 +- src/video/ataricommon/SDL_atarimxalloc.c | 28 +- src/video/ataricommon/SDL_atarimxalloc_c.h | 1 + src/video/ataricommon/SDL_biosevents.c | 269 +- src/video/ataricommon/SDL_biosevents_c.h | 1 + src/video/ataricommon/SDL_gemdosevents.c | 274 +- src/video/ataricommon/SDL_gemdosevents_c.h | 1 + src/video/ataricommon/SDL_ikbdevents.c | 361 +- src/video/ataricommon/SDL_ikbdevents_c.h | 1 + src/video/ataricommon/SDL_ikbdinterrupt_s.h | 15 +- src/video/ataricommon/SDL_xbiosevents.c | 170 +- src/video/ataricommon/SDL_xbiosevents_c.h | 1 + src/video/ataricommon/SDL_xbiosinterrupt_s.h | 16 +- src/video/bwindow/SDL_BView.h | 161 +- src/video/bwindow/SDL_BWin.h | 1013 ++-- src/video/bwindow/SDL_lowvideo.h | 24 +- src/video/bwindow/SDL_sysevents.cc | 19 +- src/video/bwindow/SDL_sysevents_c.h | 1 + src/video/bwindow/SDL_sysmouse.cc | 205 +- src/video/bwindow/SDL_sysmouse_c.h | 9 +- src/video/bwindow/SDL_sysvideo.cc | 1483 +++--- src/video/bwindow/SDL_syswm.cc | 40 +- src/video/bwindow/SDL_syswm_c.h | 3 +- src/video/bwindow/SDL_sysyuv.cc | 516 +- src/video/bwindow/SDL_sysyuv.h | 35 +- src/video/cybergfx/SDL_amigaevents.c | 750 +-- src/video/cybergfx/SDL_amigaevents_c.h | 2 +- src/video/cybergfx/SDL_amigamouse.c | 58 +- src/video/cybergfx/SDL_amigamouse_c.h | 8 +- src/video/cybergfx/SDL_cgxaccel.c | 414 +- src/video/cybergfx/SDL_cgxgl.c | 301 +- src/video/cybergfx/SDL_cgxgl_c.h | 8 +- src/video/cybergfx/SDL_cgximage.c | 1577 +++--- src/video/cybergfx/SDL_cgximage_c.h | 17 +- src/video/cybergfx/SDL_cgxmodes.c | 372 +- src/video/cybergfx/SDL_cgxmodes_c.h | 4 +- src/video/cybergfx/SDL_cgxvideo.c | 2357 ++++---- src/video/cybergfx/SDL_cgxvideo.h | 76 +- src/video/cybergfx/SDL_cgxwm.c | 34 +- src/video/cybergfx/SDL_cgxwm_c.h | 6 +- src/video/dc/SDL_dcevents.c | 217 +- src/video/dc/SDL_dcevents_c.h | 2 +- src/video/dc/SDL_dcmouse.c | 6 +- src/video/dc/SDL_dcmouse_c.h | 1 + src/video/dc/SDL_dcvideo.c | 604 ++- src/video/dc/SDL_dcvideo.h | 4 +- src/video/dga/SDL_dgaevents.c | 211 +- src/video/dga/SDL_dgaevents_c.h | 1 + src/video/dga/SDL_dgamouse.c | 6 +- src/video/dga/SDL_dgamouse_c.h | 1 + src/video/dga/SDL_dgavideo.c | 1840 +++---- src/video/dga/SDL_dgavideo.h | 81 +- src/video/directfb/SDL_DirectFB_events.c | 282 +- src/video/directfb/SDL_DirectFB_events.h | 2 +- src/video/directfb/SDL_DirectFB_keys.h | 14 +- src/video/directfb/SDL_DirectFB_video.c | 1647 +++--- src/video/directfb/SDL_DirectFB_video.h | 39 +- src/video/directfb/SDL_DirectFB_yuv.c | 340 +- src/video/directfb/SDL_DirectFB_yuv.h | 15 +- src/video/dummy/SDL_nullevents.c | 13 +- src/video/dummy/SDL_nullevents_c.h | 7 +- src/video/dummy/SDL_nullrender.c | 194 + .../video/dummy/SDL_nullrender_c.h | 8 +- src/video/dummy/SDL_nullvideo.c | 212 +- src/video/dummy/SDL_nullvideo.h | 13 +- src/video/e_log.h | 135 +- src/video/e_pow.h | 446 +- src/video/e_sqrt.h | 265 +- src/video/epoc/SDL_epocevents_c.h | 12 +- src/video/epoc/SDL_epocvideo.h | 68 +- src/video/fbcon/3dfx_mmio.h | 2 +- src/video/fbcon/3dfx_regs.h | 2 +- src/video/fbcon/SDL_fb3dfx.c | 341 +- src/video/fbcon/SDL_fb3dfx.h | 1 + src/video/fbcon/SDL_fbelo.c | 561 +- src/video/fbcon/SDL_fbelo.h | 11 +- src/video/fbcon/SDL_fbevents.c | 2248 ++++---- src/video/fbcon/SDL_fbevents_c.h | 1 + src/video/fbcon/SDL_fbkeys.h | 14 +- src/video/fbcon/SDL_fbmatrox.c | 450 +- src/video/fbcon/SDL_fbmatrox.h | 1 + src/video/fbcon/SDL_fbmouse.c | 6 +- src/video/fbcon/SDL_fbmouse_c.h | 1 + src/video/fbcon/SDL_fbriva.c | 321 +- src/video/fbcon/SDL_fbriva.h | 1 + src/video/fbcon/SDL_fbvideo.c | 2863 +++++----- src/video/fbcon/SDL_fbvideo.h | 147 +- src/video/fbcon/matrox_mmio.h | 2 +- src/video/fbcon/matrox_regs.h | 10 +- src/video/fbcon/riva_mmio.h | 98 +- src/video/fbcon/riva_regs.h | 2 +- src/video/gapi/SDL_gapivideo.c | 1983 +++---- src/video/gapi/SDL_gapivideo.h | 150 +- src/video/gem/SDL_gemevents.c | 736 +-- src/video/gem/SDL_gemevents_c.h | 2 +- src/video/gem/SDL_gemmouse.c | 207 +- src/video/gem/SDL_gemmouse_c.h | 8 +- src/video/gem/SDL_gemvideo.c | 2116 ++++---- src/video/gem/SDL_gemvideo.h | 111 +- src/video/gem/SDL_gemwm.c | 111 +- src/video/gem/SDL_gemwm_c.h | 3 +- src/video/ggi/SDL_ggievents.c | 406 +- src/video/ggi/SDL_ggievents_c.h | 2 +- src/video/ggi/SDL_ggikeys.h | 14 +- src/video/ggi/SDL_ggimouse.c | 6 +- src/video/ggi/SDL_ggimouse_c.h | 1 + src/video/ggi/SDL_ggivideo.c | 572 +- src/video/ggi/SDL_ggivideo.h | 5 +- src/video/glsdl/SDL_glsdl.c | 2465 +++++++++ src/video/glsdl/SDL_glsdl.h | 39 + src/video/ipod/SDL_ipodvideo.c | 892 ++-- src/video/ipod/SDL_ipodvideo.h | 4 +- src/video/maccommon/SDL_lowvideo.h | 46 +- src/video/maccommon/SDL_macevents.c | 1214 +++-- src/video/maccommon/SDL_macevents_c.h | 1 + src/video/maccommon/SDL_macgl.c | 262 +- src/video/maccommon/SDL_macgl_c.h | 8 +- src/video/maccommon/SDL_mackeys.h | 5 +- src/video/maccommon/SDL_macmouse.c | 137 +- src/video/maccommon/SDL_macmouse_c.h | 8 +- src/video/maccommon/SDL_macwm.c | 17 +- src/video/maccommon/SDL_macwm_c.h | 2 +- src/video/macdsp/SDL_dspvideo.c | 2180 ++++---- src/video/macdsp/SDL_dspvideo.h | 26 +- src/video/macrom/SDL_romvideo.c | 1152 ++-- src/video/macrom/SDL_romvideo.h | 1 + src/video/math_private.h | 43 +- src/video/mmx.h | 270 +- src/video/nanox/SDL_nxevents.c | 461 +- src/video/nanox/SDL_nxevents_c.h | 5 +- src/video/nanox/SDL_nximage.c | 221 +- src/video/nanox/SDL_nximage_c.h | 11 +- src/video/nanox/SDL_nxmodes.c | 62 +- src/video/nanox/SDL_nxmodes_c.h | 9 +- src/video/nanox/SDL_nxmouse.c | 64 +- src/video/nanox/SDL_nxmouse_c.h | 10 +- src/video/nanox/SDL_nxvideo.c | 641 +-- src/video/nanox/SDL_nxvideo.h | 49 +- src/video/nanox/SDL_nxwm.c | 38 +- src/video/nanox/SDL_nxwm_c.h | 5 +- src/video/os2fslib/SDL_os2fslib.c | 4723 +++++++++-------- src/video/os2fslib/SDL_os2fslib.h | 37 +- src/video/os2fslib/SDL_vkeys.h | 1 + src/video/photon/SDL_ph_events.c | 673 ++- src/video/photon/SDL_ph_events_c.h | 1 + src/video/photon/SDL_ph_gl.c | 356 +- src/video/photon/SDL_ph_gl.h | 16 +- src/video/photon/SDL_ph_image.c | 1057 ++-- src/video/photon/SDL_ph_image_c.h | 47 +- src/video/photon/SDL_ph_modes.c | 305 +- src/video/photon/SDL_ph_modes_c.h | 5 +- src/video/photon/SDL_ph_mouse.c | 152 +- src/video/photon/SDL_ph_mouse_c.h | 10 +- src/video/photon/SDL_ph_video.c | 569 +- src/video/photon/SDL_ph_video.h | 99 +- src/video/photon/SDL_ph_wm.c | 53 +- src/video/photon/SDL_ph_wm_c.h | 5 +- src/video/photon/SDL_phyuv.c | 308 +- src/video/photon/SDL_phyuv_c.h | 25 +- src/video/picogui/SDL_pgevents.c | 128 +- src/video/picogui/SDL_pgevents_c.h | 2 +- src/video/picogui/SDL_pgvideo.c | 520 +- src/video/picogui/SDL_pgvideo.h | 12 +- src/video/ps2gs/SDL_gsevents.c | 1776 ++++--- src/video/ps2gs/SDL_gsevents_c.h | 1 + src/video/ps2gs/SDL_gskeys.h | 14 +- src/video/ps2gs/SDL_gsmouse.c | 197 +- src/video/ps2gs/SDL_gsmouse_c.h | 12 +- src/video/ps2gs/SDL_gsvideo.c | 1146 ++-- src/video/ps2gs/SDL_gsvideo.h | 55 +- src/video/ps2gs/SDL_gsyuv.c | 792 +-- src/video/ps2gs/SDL_gsyuv_c.h | 13 +- src/video/qtopia/SDL_QPEApp.cc | 49 +- src/video/qtopia/SDL_QPEApp.h | 1 + src/video/qtopia/SDL_QWin.cc | 1030 ++-- src/video/qtopia/SDL_QWin.h | 144 +- src/video/qtopia/SDL_lowvideo.h | 32 +- src/video/qtopia/SDL_sysevents.cc | 427 +- src/video/qtopia/SDL_sysevents_c.h | 1 + src/video/qtopia/SDL_sysmouse.cc | 59 +- src/video/qtopia/SDL_sysmouse_c.h | 9 +- src/video/qtopia/SDL_sysvideo.cc | 695 +-- src/video/qtopia/SDL_syswm.cc | 14 +- src/video/qtopia/SDL_syswm_c.h | 2 +- src/video/quartz/CGS.h | 49 +- src/video/quartz/SDL_QuartzEvents.m | 959 ++-- src/video/quartz/SDL_QuartzGL.m | 198 +- src/video/quartz/SDL_QuartzKeys.h | 5 +- src/video/quartz/SDL_QuartzVideo.h | 261 +- src/video/quartz/SDL_QuartzVideo.m | 1301 +++-- src/video/quartz/SDL_QuartzWM.m | 472 +- src/video/quartz/SDL_QuartzWindow.h | 26 +- src/video/quartz/SDL_QuartzWindow.m | 219 +- src/video/quartz/SDL_QuartzYUV.m | 216 +- src/video/riscos/SDL_riscosFullScreenVideo.c | 1157 ++-- src/video/riscos/SDL_riscosevents.c | 866 +-- src/video/riscos/SDL_riscosevents_c.h | 2 +- src/video/riscos/SDL_riscosmouse.c | 485 +- src/video/riscos/SDL_riscosmouse_c.h | 24 +- src/video/riscos/SDL_riscossprite.c | 370 +- src/video/riscos/SDL_riscostask.c | 337 +- src/video/riscos/SDL_riscostask.h | 1 + src/video/riscos/SDL_riscosvideo.c | 372 +- src/video/riscos/SDL_riscosvideo.h | 22 +- src/video/riscos/SDL_wimppoll.c | 445 +- src/video/riscos/SDL_wimpvideo.c | 744 +-- src/video/svga/SDL_svgaevents.c | 631 +-- src/video/svga/SDL_svgaevents_c.h | 3 +- src/video/svga/SDL_svgamouse.c | 6 +- src/video/svga/SDL_svgamouse_c.h | 1 + src/video/svga/SDL_svgavideo.c | 936 ++-- src/video/svga/SDL_svgavideo.h | 29 +- src/video/vgl/SDL_vglevents.c | 435 +- src/video/vgl/SDL_vglevents_c.h | 13 +- src/video/vgl/SDL_vglmouse.c | 29 +- src/video/vgl/SDL_vglmouse_c.h | 9 +- src/video/vgl/SDL_vglvideo.c | 1030 ++-- src/video/vgl/SDL_vglvideo.h | 33 +- src/video/win32/SDL_d3drender.c | 385 ++ .../SDL_d3drender.h} | 6 +- src/video/win32/SDL_gdirender.c | 721 +++ src/video/win32/SDL_gdirender.h | 30 + src/video/win32/SDL_vkeys.h | 76 + src/video/win32/SDL_win32events.c | 954 ++++ .../SDL_win32events.h} | 29 +- src/video/win32/SDL_win32gamma.c | 63 + src/video/win32/SDL_win32gamma.h | 32 + src/video/win32/SDL_win32keyboard.c | 46 + src/video/win32/SDL_win32keyboard.h | 32 + src/video/win32/SDL_win32modes.c | 227 + src/video/win32/SDL_win32modes.h | 45 + src/video/win32/SDL_win32mouse.c | 46 + .../SDL_win32mouse.h} | 13 +- src/video/win32/SDL_win32video.c | 164 + src/video/win32/SDL_win32video.h | 67 + src/video/win32/SDL_win32window.c | 434 ++ src/video/win32/SDL_win32window.h | 58 + src/video/win32/wmmsg.h | 1032 ++++ src/video/wincommon/SDL_lowvideo.h | 29 +- src/video/wincommon/SDL_sysevents.c | 1272 ++--- src/video/wincommon/SDL_sysmouse.c | 340 +- src/video/wincommon/SDL_sysmouse_c.h | 8 +- src/video/wincommon/SDL_syswm.c | 448 +- src/video/wincommon/SDL_syswm_c.h | 6 +- src/video/wincommon/SDL_wingl.c | 1146 ++-- src/video/wincommon/SDL_wingl_c.h | 54 +- src/video/wincommon/wmmsg.h | 2052 +++---- src/video/windib/SDL_dibevents.c | 850 ++- src/video/windib/SDL_dibevents_c.h | 3 +- src/video/windib/SDL_dibvideo.c | 1704 +++--- src/video/windib/SDL_dibvideo.h | 24 +- src/video/windib/SDL_vkeys.h | 1 + src/video/windx5/SDL_dx5events.c | 1561 +++--- src/video/windx5/SDL_dx5events_c.h | 4 +- src/video/windx5/SDL_dx5video.c | 4375 +++++++-------- src/video/windx5/SDL_dx5video.h | 14 +- src/video/windx5/SDL_dx5yuv.c | 450 +- src/video/windx5/SDL_dx5yuv_c.h | 14 +- src/video/windx5/directx.h | 1 + src/video/wscons/SDL_wsconsevents.c | 338 +- src/video/wscons/SDL_wsconsevents_c.h | 2 +- src/video/wscons/SDL_wsconsmouse.c | 6 +- src/video/wscons/SDL_wsconsmouse_c.h | 1 + src/video/wscons/SDL_wsconsvideo.c | 964 ++-- src/video/wscons/SDL_wsconsvideo.h | 59 +- src/video/x11/SDL_x11dga.c | 38 +- src/video/x11/SDL_x11dga_c.h | 1 + src/video/x11/SDL_x11dyn.c | 187 +- src/video/x11/SDL_x11dyn.h | 21 +- src/video/x11/SDL_x11events.c | 1962 +++---- src/video/x11/SDL_x11events_c.h | 11 +- src/video/x11/SDL_x11gamma.c | 99 +- src/video/x11/SDL_x11gamma_c.h | 1 + src/video/x11/SDL_x11gl.c | 852 +-- src/video/x11/SDL_x11gl_c.h | 63 +- src/video/x11/SDL_x11image.c | 442 +- src/video/x11/SDL_x11image_c.h | 17 +- src/video/x11/SDL_x11modes.c | 879 ++- src/video/x11/SDL_x11modes_c.h | 5 +- src/video/x11/SDL_x11mouse.c | 457 +- src/video/x11/SDL_x11mouse_c.h | 8 +- src/video/x11/SDL_x11sym.h | 609 ++- src/video/x11/SDL_x11video.c | 2364 +++++---- src/video/x11/SDL_x11video.h | 85 +- src/video/x11/SDL_x11wm.c | 697 +-- src/video/x11/SDL_x11wm_c.h | 6 +- src/video/x11/SDL_x11yuv.c | 595 ++- src/video/x11/SDL_x11yuv_c.h | 14 +- src/video/xbios/SDL_xbios.c | 1502 +++--- src/video/xbios/SDL_xbios.h | 82 +- src/video/xbios/SDL_xbios_blowup.c | 62 +- src/video/xbios/SDL_xbios_blowup.h | 93 +- src/video/xbios/SDL_xbios_centscreen.c | 126 +- src/video/xbios/SDL_xbios_centscreen.h | 34 +- src/video/xbios/SDL_xbios_sb3.c | 77 +- src/video/xbios/SDL_xbios_sb3.h | 59 +- test/Makefile.in | 8 +- test/checkkeys.c | 226 +- test/configure.in | 2 +- test/graywin.c | 445 +- test/loopwave.c | 162 +- test/testalpha.c | 928 ++-- test/testbitmap.c | 324 +- test/testblitspeed.c | 238 +- test/testcdrom.c | 358 +- test/testcursor.c | 376 +- test/testdyngl.c | 303 +- test/testerror.c | 83 +- test/testfile.c | 348 +- test/testgamma.c | 339 +- test/testgl.c | 1446 +++-- test/testhread.c | 110 +- test/testiconv.c | 118 +- test/testjoystick.c | 320 +- test/testkeys.c | 24 +- test/testlock.c | 134 +- test/testoverlay.c | 980 ++-- test/testoverlay2.c | 867 +-- test/testpalette.c | 403 +- test/testplatform.c | 288 +- test/testsem.c | 108 +- test/testsprite.c | 526 +- test/testsprite2.c | 262 + test/testtimer.c | 133 +- test/testver.c | 38 +- test/testvidinfo.c | 934 ++-- test/testwin.c | 634 ++- test/testwm.c | 665 +-- test/testwm2.c | 99 + test/threadwin.c | 610 +-- test/torturethread.c | 125 +- 686 files changed, 121608 insertions(+), 102713 deletions(-) create mode 100644 .indent.pro create mode 100644 UNDER_CONSTRUCTION.txt delete mode 100644 include/SDL_active.h create mode 100644 include/SDL_compat.h create mode 100644 include/SDL_pixels.h create mode 100644 include/doxyfile create mode 100644 src/SDL_compat.c delete mode 100644 src/events/SDL_active.c delete mode 100644 src/events/SDL_expose.c create mode 100644 src/events/SDL_keyboard_c.h create mode 100644 src/events/SDL_mouse_c.h delete mode 100644 src/events/SDL_resize.c create mode 100644 src/events/SDL_windowevents.c create mode 100644 src/events/SDL_windowevents_c.h rename src/{video => events}/blank_cursor.h (97%) rename src/{video => events}/default_cursor.h (51%) create mode 100644 src/joystick/win32/SDL_dxjoystick.c delete mode 100644 src/video/SDL_cursor.c delete mode 100644 src/video/SDL_cursor_c.h create mode 100644 src/video/SDL_rect.c create mode 100644 src/video/SDL_rect_c.h create mode 100644 src/video/SDL_renderer_sw.c rename include/SDL_byteorder.h => src/video/SDL_renderer_sw.h (84%) delete mode 100644 src/video/SDL_yuv.c create mode 100644 src/video/dummy/SDL_nullrender.c rename include/SDL_getenv.h => src/video/dummy/SDL_nullrender_c.h (84%) create mode 100644 src/video/glsdl/SDL_glsdl.c create mode 100644 src/video/glsdl/SDL_glsdl.h create mode 100644 src/video/win32/SDL_d3drender.c rename src/video/{dummy/SDL_nullmouse_c.h => win32/SDL_d3drender.h} (89%) create mode 100644 src/video/win32/SDL_gdirender.c create mode 100644 src/video/win32/SDL_gdirender.h create mode 100644 src/video/win32/SDL_vkeys.h create mode 100644 src/video/win32/SDL_win32events.c rename src/video/{SDL_yuvfuncs.h => win32/SDL_win32events.h} (67%) create mode 100644 src/video/win32/SDL_win32gamma.c create mode 100644 src/video/win32/SDL_win32gamma.h create mode 100644 src/video/win32/SDL_win32keyboard.c create mode 100644 src/video/win32/SDL_win32keyboard.h create mode 100644 src/video/win32/SDL_win32modes.c create mode 100644 src/video/win32/SDL_win32modes.h create mode 100644 src/video/win32/SDL_win32mouse.c rename src/video/{dummy/SDL_nullmouse.c => win32/SDL_win32mouse.h} (82%) create mode 100644 src/video/win32/SDL_win32video.c create mode 100644 src/video/win32/SDL_win32video.h create mode 100644 src/video/win32/SDL_win32window.c create mode 100644 src/video/win32/SDL_win32window.h create mode 100644 src/video/win32/wmmsg.h create mode 100644 test/testsprite2.c create mode 100644 test/testwm2.c diff --git a/.indent.pro b/.indent.pro new file mode 100644 index 000000000..d95d15d95 --- /dev/null +++ b/.indent.pro @@ -0,0 +1 @@ +-i4 -nut -nsc -br -ce -cdw -npcs diff --git a/CWprojects.sea.bin b/CWprojects.sea.bin index fb458816eacd34c7d49c478707ac4efade9cd12a..c7348848ee619d6df9a86fa301d521dff7c947fa 100644 GIT binary patch delta 2361 zcmZuyc~}$I7M~e2H$(`Cghd4!UNtHpDiY+`=Yr6>Km`>Q6i|d(;1fkQwXcMwNGRoD zDaiE;Xwj-ADT2r{h!#+B0gJDq;M0e)lqi)4sY?Zu0PoDie(fLL@0*#-`7P(1JNMqC zX4$1?*?sM6ZAu#R8wS8LJwp@bPxF*1XAXz-lH!P8Q2wW=^ zEEeP6-XL*aou^R5>ABm{@hU_HA>IUx{BXWAMcRLn$7k~Rr83gWjnzh{(`82nA+ zsvkC+j$HFyAHCUFrn-~9wTQ>KeMY{|Tg(<=MKlp<0Urhicx_qpAxSi@_S@BzweTfD zkkFd-K43s@x{~xbSz^e2KAz3(uy}WZ{?=`^ev`XmfAfYctFof#;Vx;$v#WFFsJpD6 z^V37@aKGk`>d4jPg&PYLoASSnt}f}6kobv=d`-6EM=9hU@&eEimNBytzOjWOYwd1MIXsSH#v{F~;ayBhqV%1)7IraUQD|=^zlqhYA&nZ{fiaMkH zOScs|)R{ae&0k;P8GUTyRGTI`g^0;qN6_8B{ZqAD9_>%yH{(C!2<6*+J5V zVw+2QFFOn@X~SEuuJuyC_<@maa*Is${Ag*CAjnt0NH+aN_mp%J~mcE#Vp0qs<9#Zqij+#jirnXIanqqZrLvNJ& z*nE9oZM6S?L?b6XT=yhAztVp9bLo-Et=S_u`?nkQZpFWp9keux{UQ&Pl?9tDIF+(i_mR&D#fGoC{YJJ)55*Src}LY$FE0CZZ_=3+ z6?`XI)h}M-5{21b<-e1=E@^s$^~E!WUbnd%%+dY0d^B9`&U4x4l-$!g+*IHboX{8B zFOSY?&S(>EskL6ze^rWq{(biSS#7hn^bI{cZ9G$R(fRoHMK6CnJ}P%gGIP>o=I{p( zuUlC$#>Y5=bf*;rC7O%dGe|eeZ#!djhWQ#RfS+J3n73qAPi6K6Z{Vy zKtpG6w2qbvk^q9FpeWVR3#ePGxJ8e3I=Wr(gxd&!6)MpT>oxVCynSD0*dXlvcNe@& zhukJ>lip&8<-Ye$uG&N_rauk~_uH6fJ{>E@XbUI|Y3mI&k4516F(~ZPWIQkiHNPT| z(%#V0*gfnx4p5614jcz4fZ+B$2 zUf>VuVD`W#SPt>iy-cngRTvB4+<*abXxY}voqHotuFUX*y*m_OTQ!p4{TIgl)nYM!V?uBDCY1eXdij=vyUkN3=KE%$c1be8U zM0*1DALZs9DaUbu3OSptn-B{5;Ry$0KXHkS+8Kuzb|6c9N`)*0xdf^h0CFyFQbEz4 zyO|d%R8CJ;juWVMCkLp`0nlj5be%)Xkr2prrEI*i=X@_t?L*VBCxa{~X9+IvL(`d9 z20bT*psep?S?9%-Z&~sSz;d~1VAWng4@hJ1X|yr0unfew`XUlhvVBbJMa1U`!QgVJ z0sbS^NF$ior5H>kO^`|e2G?h@EG)hPg|0ixY`B8H;t4@{^E{{CVNly(>IT>wKQ^dc zZ=k9(0WqfIgBJGXFff&i zC_z29E+EdW&0$Z&>!Wn;$=w!rvujf-gwOcqAvnOdR~z9_HLQsf9XJOd0W5_#(d?4I zt!gkgImYPKXtqdTWN_<03g$ENGy>D-{eSu@_v274CuU>d`!3Sm0DPMz*>gHLx86nK zN!YW6-5uDwoS4Cc70C4G02?1PqEWDg;Fcawx|-h#(^F zMiAkv03jYBfr%{FN^=;Fh$z;^#REhzakzq_9Im??U^w=5k6Wf{{i?dV`n})#zxTfD zMCOtcnM<;_iHfKYf*VLxOb~AJmNw~E@YLn#i4Z2$J*1Y?H-Py}%ly z`w|ImDMgZ;x{ZtpAJ4yTx7Hx?6QoHHB$>NkU`-jPr{xIP909pFhAhUH6UmkOK?I@k z{IajiR2>%oJ+CRgLfDP$B`!n&Uz z-KmuI{T`j?(v(U62F!IT`uDrj!es;7x*oYB_WbZf^w8_|@`EJa27Gi(Tgx!sb zQMP{ABBJ!k-xPN%COw1B1WN_1ynOJ-2T3K`sRJF})d_`m2^V)S^7cw+@2ED^Zgyy^ z-;z@0mk^jZqTO6qE;e+&`TeTT|7;d?z4BjSxA9uEBaV9wvm!o0*~N1)9Z z^Wt&gm%rP$!fxH4|8BYtaaM_xkX(dSf$%J%HYqrd;D!D_xg z>!%xc8Z8EA1Xpr9BNj*k=cbd+bTL60+TgqCq$6e2&T5__d(Y7(1U+4V2MsAlD)icE zQzHr<4R|zJQzQEK!;B4_AzOaW(lc6k*9>i~{hotFf?Q=W`#y`x(Kp4VGqeFyK+v;O zoD@ONB;nhD>D*FEB!aC``wzz-2+h$q!6qu;w1CS52EH?+*hNKKQ(u_jFcs}2Oad2F z1L0q*XnU&Of!p)T@wAHW6pr%efb-3kA~QTTOKUNk)MtZxTZiJNQskfwz#CBOEok%` z@DFYh3GF4@@3S*UUySqT_=?a>le+S`a9leF4GtwkgFexrQEuC~2GKlVQv@oLs+*ka z!Itw-cz{3FRUk{8G*9a>;RHGl6EGJ}(DUv%AN)E;A{d62eR|k7JSG-Lt7sGa3n&SD z2*lh0vIkQO&}WyJbzGp`^n~sNa`NNt>AJ|C>h)u5b&-#i@D718ig~-PGuTHjvKyR{ z-VUK3WQ3^%on5EF?j6BqokkVfLbwrOaCVq0bG$bf37M0;jelLq#3sW~bwMuDW1yDO zYG9%ITxdQQSyPezcqkV+38CTAODQ?YFs zAIaH3^#6#8G+Yb>H(4{@{A8lC^H^C1X}^8OO{NngCD2e2Ki5b>;q3}=v9GWkTsr3o zRPhpA=c|-eSf)g#xJQ8usrgxUT!H>dYbhuK)rN5Z{-zR27JSO~RH6@&5Q6Hi@^%Re z_CywEE0Gx+$)ZV82Lc*;IcK$mR~6&5dSpNa}KsDMzi0gCa?R&exZrjaf zccB0z1oo+#pX>vBuN5nOf*dr3!1gz(c_r9~>{#gbDaimkWX;#0{9mIN2B3-+OVpjT z4IooW*reVAPzATejK?>s|9{Hhzx-?SAGvMj#K59W{|th#uERPwa2VDzu>xm;O9;z6 z9mOp-ZXbpkq*d(HFtRcf>ZsMg&K>rg38C(*XK#gDDekO0YQZky1}MK1D_N_?ATc-K zc6uk4+5YC{fZL1b;4*wy*7aUIr@>v8N)@tUep8X+9=4c8GB#xv&1|My`k&FCWBEow zKh+wCWt#*A;?}q#;`G9TgmAvXC&^e?SV1_~An+Tx3f||q9j*c?_l/dev/null; then \ + rm -f "$$file.indent"; \ + else \ + echo "$$file"; \ + mv -f "$$file.indent" "$$file"; \ + fi; \ + done + +# Run indent and then commit modified files +commit: indent + svn commit + # Create a SVN snapshot that people can run update on snapshot: svn co svn://libsdl.org/trunk/SDL diff --git a/README.OS2 b/README.OS2 index 424b3739c..7e462bf36 100644 --- a/README.OS2 +++ b/README.OS2 @@ -3,7 +3,7 @@ SDL on OS/2 =========== -Last updated on May. 17, 2006. +Last updated on May. 1, 2006. 1. How to compile? @@ -13,6 +13,8 @@ To compile this, you'll need the followings installed: - The OS/2 Developer's Toolkit - The OpenWatcom compiler (http://www.openwatcom.org) +- The FSLib library + (ftp://ftp.netlabs.org/pub/SDL) First of all, you have to unzip the Watcom-OS2.zip file. This will result in a file called "makefile" and a file called "setvars.cmd" in this folder (and some @@ -30,7 +32,7 @@ is full of printf()'s, so if something goes wrong, its output can help a lot for debugging. Then run "wmake". -This should create the SDL12.DLL and the corresponding SDL12.LIB file here. +This should create the SDL.DLL and the corresponding SDL.LIB file here. To test applications, it's a good idea to use the 'debug' build of SDL, and redirect the standard output and standard error output to files, to see what @@ -46,8 +48,8 @@ wmake 2. How to compile the testapps? ------------------------------- -Once you have SDL12.DLL compiled, navigate into the 'test' folder, copy in -there the newly built SDL12.DLL, and copy in there FSLib.DLL. +Once you have SDL.DLL compiled, navigate into the 'test' folder, copy in there +the newly built SDL.DLL, and copy in there FSLib.DLL. Then run "wmake" in there to compile some of the testapps. @@ -189,10 +191,6 @@ please, be our guest and contact us! 10. Changelog of the OS/2 port ------------------------------ -Version 1.2.10 - 2006-05-17 - Doodle - - Small modifications for v1.2.10 release - - Changed DLL name to include version info (currently SDL12.dll) - Version 1.2 - 2006-05-01 - Doodle - Modified makefile system to have only one makefile - Included FSLib headers, DLL and LIB file @@ -218,7 +216,7 @@ Version 1.2.7 - 2005-12-22 - Doodle SET SDL_USE_PROPORTIONAL_WINDOW=1 dosbox.exe ) - or, if you have the HOME environment variable set, then SDL12.DLL will + or, if you have the HOME environment variable set, then SDL.DLL will create a file in that directory called .sdl.proportionals, and you can put there the name of executable files that will be automatically made proportional. diff --git a/TODO b/TODO index 65bb01c17..38161e186 100644 --- a/TODO +++ b/TODO @@ -2,6 +2,9 @@ Wish list for the 1.3 development branch: http://bugzilla.libsdl.org/ + * Add a way to register custom events + * Add internal support for adding video modes and refresh rates + * Support querying and setting refresh rate with video modes * Add mousewheel events (new unified event architecture?) * DirectInput joystick support needs to be implemented * Be able to enumerate and select available audio and video drivers diff --git a/UNDER_CONSTRUCTION.txt b/UNDER_CONSTRUCTION.txt new file mode 100644 index 000000000..cf92fce06 --- /dev/null +++ b/UNDER_CONSTRUCTION.txt @@ -0,0 +1 @@ +WARNING: This code is under construction, may not build, and is unstable! diff --git a/VisualC.zip b/VisualC.zip index 030db1cdefd600b2b7be511ba3e099405fbd74ba..0ac67e16bcf583f46e8e6320aae1f49cb6662220 100644 GIT binary patch delta 1261 zcmaEKn(5JLrV09z*3$}HLMvDp-Y_#V1$Z;Fa4~>@w9nRw9!dgcKuKf;6RT`_UOwf9 zYnXWWyD*#gR+Gqw{>tas7#NNiF)#=-h)$j`RZN(Zfmvrtfr}xM`J2BnX0bB0)@)8< zU%|)%vT-vX=R$T4hE8RZo0YLeleY_~3%r-#?Tl>4=63=yjP-7(Cp@}nQQ%blsnJc6 zXT#G;3titGtax|sW1|iGSLf|~lN$OiZ8k~If5LXpI7Ev{^{r&v#luTeK3O;grM>$; z>2J`Ip5G_F)~uYkx}W*CoJmkei$0s@DI2@t{Qdmr(_g*0)xH1yyK@&M3T%?1laIej zW^v~Ynw=aibh>zE{1!W($%id2&O0Kk&w1^Y-|qO5s#E_u-h98Zk8zG1+x?j4RgeDE zPx~`@=lxpi@A`&MUYC4c^J9bBe+E#hn0#E=3KC(gA~MjZQx*Nj$b+0ZCaa5kK@^pW zZ)1kA^riJ#P!-M7keY1MBsBTHJjdjD@|*(5CV;JKoFOs!yu1lSKf8h>3xwsPGJyqC zao?U?r0svxF!28i{O9)s%y3YS-<@qG`b_iOF_G7I00QdyPz?8jhJwMsshf zbr8e>yRBWIikKZHp($GE5&}03=!CG%Nv?OHA>iye5l!&}Uq6^)sm(rq)=*QsgVv%c zbP11wSiLAb0IKL)^b|Bj(-IQIGd6Be>C1B;}|x26~{1Iwhzyi=1nVCBx_@~K9kl4kN6 Vpdh>?5u0Yp0xC&1`%jz94*-i0%P9Z= delta 1261 zcmaEKn(5JLrV09z9v9}hgjTRHd}aK~7~sv!!o>grQzLFp^iUG80!kt)m{?`YqlKhl z;^FVYnqGM(`yb`%oM&TTIAX-WAj}{-dBRjNVNM3-dB4P5Kp1BJ=5LHytW1|`Hz%>L zU}OQ=xS5Z0Av*`qHj~byzfVlwE}#y!6J#%3(>s9}#`?L_6pt=0e9-dk33IQJM8auR z=k7brAMeb4%v{O$sy$Cug;92Cdgi%%CwTXyuLxoBx@F9>xZV5YlfsrIXYRaL{k_yf z^83WsKZBIR<=Ma4W-JlljOUp&rLtyT=F)czs~vmi6{dfwlaBH&<_XEpdMMDCmcH8b zslHvT;ab*P!FN~HvjsQGZmaf4VHBBS@k3^p&QzzesDy0}lX#A4a`%h-6wG?}+2XOx zW>(*~Ie(QV9o-c0Ad9*Fpb3vKM=ayAJrjB^2InzlPCU_}6<*hItMBrcDJMNrKBk3* zSgNfqJ$1m7WwxlZn0g3XZQ>*0&-wz*HR;<|)}6ZKx6-1X^;CecV}0ekOPfMoy}EnS zV$$qcx8E**m9jIXKKAXb?K#gEe?R|u`9a$vy{k93ir3%2J9n|+gNh^Dj`dwV&e12e z#O(Msm1)n7_Gi@2P-`z-WZS78C$#43+_L>IzD)Tmc=P?rT4oDdo_#ynLXZCZuk%yA zc>nLRckxLluD^U1`7zP=A2?M^J}ztpi7-|X8EDk0ihg6{K~5c$)y2Iaib}<|F+*7T z()ui@isorZO}1$gntWfLWAZ$CP61>SKnZYi;|z((=jBZx`q>p6Ss*MQl?g1Eiu-0t zOlHwE11p*Am?b>9*GOb@s-_%NQ@d_I7EKFgNldmgvVd#a+-qbC)o{#gGMal+t%D#A z*lq0sRmAKt2~E*Lmk_vVKqrK4PIA2q4FPA*iD-%+`1-*VOKtY?vxb`59kdorp-Xra z#Og)i0Z>KXqNkuKnwAg&GfjLlcMs2I(L_zCVyD!pSbVRuP-61`Ogo6lj#++C#gp?6 zLs?P9GoVrYtwbKpHpNP~ZOWS$RBA!BoU5IP#U_Cz5|i7TATbGy9FX&*Hh*Xmf@)%G zpMYliqHcJ|h;QcZQHLrto3N0D8CXb6zBR>w8CW(<=AD|v0V{VVmrpeUl{Ayr00rSC RiP$t#7Emd&*?-z(egLz$2rB>p diff --git a/Watcom-OS2.zip b/Watcom-OS2.zip index b3d1a67a07e26feb2e68801243f72f078966a796..603210f4b5be271749d4188c5279495be0917c4b 100644 GIT binary patch delta 3084 zcmaKu2{e>@AIG1;*h-9TT4Z}=H?|p}B0~1;WVwu83{3_R^C;P}XAj8|A=}HHa7iR& zOA?9fTVvlz^v-a5>)zh`&NdD_83!vYLEO?%nb?djDQFGIP+rLXVnpT&fOtMQY@c%St#D0P0x)fZ=a0 z&IcZ9bj-?R5As>=n*fz2Wv`ypqi=#7jPgsin~Uu)*%isNT@Y|uB^PNlGjME_lvmA6 zehwIbLAyFQy0|$UNXket|0Z2BE+#4qW*Cn_8K(U%YpiNI>X;42t2|qM3=v&SP~N+* z+V;^#4SF@(w$HCfP|h3Ni%t;LC!lODDs+WK-I`e$`xM?bFe;}w8JVuMQ*IJTxi1In z09j53V5QC;+2Z4v6|wB7}H+t%`euSOXV?OD&)ba1sN zVjBdz_PL!5oVCVYyjT?(kP=OD9JUz6VW!hpn z19~oJE`%$5b>sE%AZ~W2e>9vZ!aIFKfx@a2)h@)og$&7h>8CX1!yR-&O$zoR^b{}% z3~I{12otB}MN7m+D4tUrpKm=fJ+ZIU5TyRGlrYe;WL97O&AFW+9*!KXMBmMBwNv16 zpW0ZX!6B}tA=Z;P@t3|j233bkf-~J~EYuhFY3pQjES^3Xe#h>YkmVYT^!u^`UbJXx zUpk_kK4d3(zxG8_Qf}zaVbQIZL2-03v^4l{9Z?t(gf_!vY8)w zFkh5Jk<^BM=WSAf?irt%7K)jh_<4y*%# zhG#>|irb7OjFsAOo1P_FVT9c6rd(6052*YTWvvW1VvfnfXU+@+gd!iR6BZFBclK>` zBhwboVf0UOzcPHbZPl7lw63f@mInx64Y{eYLU98H>lDeuYtYy;rlTgH6b0e_P>%Nt zVJtldn-ccs8N<;JHmru>MVcb=bQPN7o54d&Z411cxU{!n6|&=|4AjVVfT5I`J3_}( z$@69yCxW=&@}=HR%!al5wR^v1xbW)BTdoRy9vcHyPreEC2kdP!;P#)hVho1vbaR$_ ztcB^()E)KntmWL{e(Dzj_Q>;^V7+yjEW>w=v5NC;?~Ki`jJQMZ;fUv#(jc`<{(rdN^-$m{ zgx9IvTUhd0ikZk@3dn`&yoz9y^<@tYyB!hyJZP!}A9~*V)^rqC(^)QUtxSsOAe|BR z3w9kx+f!2euFLc^fIUljY@W07r*yq${dZN3X;r#TD8OI&%E%W+pbX^k68tq!TA}8g z)UO^^oi@*WbTj0kxC&+E$5uLTyk-o1m2civY*=q7`D3Nvo0YCD@oTj+?z+U8XGxNo z4VhaZ?!OD=zZ`@#<^}8aI7;<(zRl3@7T1wvU*1T495$Wc*8$!RuXvd~RNM1Kd{B9o zg)+w7`E;g5V)ML`?ravyts*sTJeEe>A?{op4QpsnDtf9}f39shesW_WP0#1$0{cSJyBhRi^U+K_cr0?*z<%K zVRX)N3-)?KBGxc_BhG}wE=!fD9#NY3n7v@4b=yL1`os>+kHzMR&q6*=Y*}g|?Uoy) z1#^V7B0L>%-sl^i2s@1Z!Irp(FgaL>)Ijr&^!tS9PWYv0W2Q@t<&NXqR`PwlPTA zPgj=XJC#wB9+-c>STr&VoF3d7gxoF9?vI*@fZc^Nl-{Nc09 z7@xP|8-CTlWD=SLZ$$erp3vZxGstJ5kNB4vA~i?L!0N(zLhWxhyfAqb3Ll0ERvFKrU0eUZ-C7yifbi;MNlN*Im8O zTa8I4Hy$`dIq%ko@@;5tP~KCG^Cv_*8_c52YVbxE&G8%!PP2??YJHp&%LxrwkRyE- z$iN>O8g=n9SAvSB>KJ>yyJDx4wfiQz(e12vd%l4I0PYXf;r~W70qx%#5n1F9eZ zVpqfg1d?q2KFY5M`12@QMBpbNB+1D@`12IM*253^x7)VM0I4j%pW1?CL2ijdi~s!s zpuqPBA-@2d72tbykhEm%{W<>E()bZixSepQ6~c-C=n#?#xjXcp z(?bCP4+)Af2!t*mdI_8!ocGVaGn?7Wcx_fe!uNSb9c`vImWNU*E@OinW$K2s9VRbyO^D9akU#Gcga)%BSYqUe9 zmgoqbGq#-tgzbZ~|mVTHrfX)l(1%8gc%oGUbDlXGjURt~*#b$XH6il$-3a!-& z{&t&s`c|n`n2%dh64G<0bz?lAk^W&x>B!Pj(#KY*kgk<;{vFQmUikJ4@R`4U{MHv&6GI{ZQ%3H)o6i#bXHVlFGvtXX!dDZwqh8%nV{V@2?GkDY z-z%zIdsd>SObbB+=-=eebI)6;E87mbXkU1tpHWBuDQ9>s)*pF_YW$=tVZ9J7m%^$# zA3c#Zzr`PS%oSpMh$eA zsbF#_J2A{Bdi4s`E}N_t*G?oFtK}-p6+9d+OVtsxs+VNJXP`15mw9p)MEsewu@lTi z{@s|{efrZh(Sk@O(~7*)s{`#N*Q}Vr*U86F+A^wubd7LFg7xUccr*pd(;@EE}o9}rH+{w z##`sd(n?R<*Ncy^t(nXgCQF`DHp0z2tVQtSpZASJ7bzT(LpCM)_OolhaPc_o*&-y^ zYwZe6}+G-10?oztnU{hEeg*){N$XTI?|Ht`QVDr6&5qF0(A7WVqv&%F?EtBw&1V{?oQS7Q7}PKRAi1859ElWdx1WddR->$Hn{HdLZ$Qm+Y| zIgb03#$C8w?ZjLDBgS zP#OLuNUsa4f|h=C#lDheZT^_$>vP+}s@$0Ocwy11M)sIN==0KZm`-M%2+mN+~{{GcPEx9%vQfQdnM{%CfU9 zdfL?A#-Q`yRk;!!@WL-hS?M@{?K_!3cCmUF12ZhTx&ZeCuU}f&)e{Td+cmV^_(e!= zhM>aHqs+6@1DsIw(jWQw<#2yBNOyOCBaGOt=W^Q|`WXpu<7I0Ryu#Vl4l5*-n zcI9pefKbEhyWahuTJ(1uP?)xMGnV*1p}1w9Dnw=BWQ{gWZ%U6&FQ+2az+S!~Q^4M9 zL^kr0!3T37Nv`e|>dffxkr$3PTi%i%8iDCqrXsxNcOmCb*PmqO>8_zC7HuUsvC`IEk*9uA`7{HE48m-burdXv!sZ>+~@7VCXtNlUYcB4 zX!5=*4*zIXS=79#xHT%Un3U4=iFj3TCD&Cr&ztmbG~XBLa)>FR*#D4|)u$Uz>BQ&rde>@qA|c3=1)kjUxR z3Wa6NTJL7Le2mBjDAZ@ipu;p)$%8mLdFuKaXbfe#=d@^`g}@NtOE;Q#RWQym%HjUp zih13=NU3!L>s=3JKy?t;Ft=?_@m2A&w|IxV2%(`{?CM)j%-aWqCucRvSX+%j;8L#c z_exK_zrDLB$D4C}=`O5pVXhO-n2Q{f+x~;uFl)6?VpC3yJz6bpi_vSu!T2d{e^~cTy+=JP9{_StxC@WD1z#Xndrdr?kD30Jv3-Df=VVf{dLn`+~qf)pLEfw zTw5g{ptY-QiHqht!TD%3k?uCgTs*57_N+NL&@HI7Lxazx!Znm@>X_ei&ruI#by5>} z5-p|+@wd5A-ix>+&^PKd!NID=eJ$Mk6Y6jY<}7B zB{4y^8l;0cmb3Srkd5oLcG`i;i- zID>0sriySvMlw`9{7pD|#G?usP-&fT%1Z?2>4E!0OHiad-3VhL)rWUX{nHg}fx1Jk zH*~f;0-<%a5IPgg1zDN=o2NHRd@$*tS%m^d^M^_AyLRvBZJf8o4QItdj zKRAdl%1=Fb1^B*jh=2osK03zFtLE?+b>H* API Documentation -

SDL 1.2.11 Release Notes

-

-SDL 1.2.11 is a minor bug fix release. -

- -

Unix Notes

- -
-

- Dynamic X11 loading is only enabled with gcc 4 supporting -fvisibility=hidden. This fixes crashes related to symbol collisions, and allows building on Solaris and IRIX. -

-

- Fixed building SDL with Xinerama disabled. -

-

- Fixed DRI OpenGL library loading, using RTLD_GLOBAL in dlopen(). -

-

- Added pkgconfig configuration support. -

-
- -

Windows Notes

- -
-

- Setting SDL_GL_SWAP_CONTROL now works with Windows OpenGL. -

-

- The Win32 window positioning code works properly for windows with menus. -

-

- DirectSound audio quality has been improved on certain sound cards. -

-

- Fixed 5.1 audio channel ordering on Windows and Mac OS X. -

-

- Plugged a couple of minor memory leaks in the windib video driver. -

-

- Fixed type collision with stdint.h when building with gcc on Win32. -

-

- Fixed building with the Digital Mars Compiler on Win32. -

-
- -

Mac OS X Notes

- -
-

- The Quartz video driver supports 32x32 cursors on Mac OS X 10.3 and above. -

-
- -[separator] -

SDL 1.2.10 Release Notes

SDL 1.2.10 is a major release, featuring a revamp of the build system and many API improvements and bug fixes. diff --git a/include/SDL.h b/include/SDL.h index 60ac26ce4..c57a2b4fb 100644 --- a/include/SDL.h +++ b/include/SDL.h @@ -20,7 +20,56 @@ slouken@libsdl.org */ -/* Main include header for the SDL library */ +/** + * \file SDL.h + * + * Main include header for the SDL library + */ +/** + * \mainpage Simple DirectMedia Layer (SDL) + +http://www.libsdl.org/ + +* \section intro_sec Introduction + +This is the Simple DirectMedia Layer, a general API that provides low +level access to audio, keyboard, mouse, joystick, 3D hardware via OpenGL, +and 2D framebuffer across multiple platforms. + +The current version supports Linux, Windows, Windows CE, BeOS, MacOS, +Mac OS X, FreeBSD, NetBSD, OpenBSD, BSD/OS, Solaris, IRIX, and QNX. +The code contains support for AmigaOS, Dreamcast, Atari, AIX, OSF/Tru64, +RISC OS, SymbianOS, and OS/2, but these are not officially supported. + +SDL is written in C, but works with C++ natively, and has bindings to +several other languages, including Ada, C#, Eiffel, Erlang, Euphoria, +Guile, Haskell, Java, Lisp, Lua, ML, Objective C, Pascal, Perl, PHP, +Pike, Pliant, Python, Ruby, and Smalltalk. + +This library is distributed under GNU LGPL version 2, which can be +found in the file "COPYING". This license allows you to use SDL +freely in commercial programs as long as you link with the dynamic +library. + +The best way to learn how to use SDL is to check out the header files in +the "include" subdirectory and the programs in the "test" subdirectory. +The header files and test programs are well commented and always up to date. +More documentation is available in HTML format in "docs/index.html", and +a documentation wiki is available online at: + http://www.libsdl.org/cgi/docwiki.cgi + +The test programs in the "test" subdirectory are in the public domain. + +Frequently asked questions are answered online: + http://www.libsdl.org/faq.php + +If you need help with the library, or just want to discuss SDL related +issues, you can join the developers mailing list: + http://www.libsdl.org/mailing-list.php + +Enjoy! + Sam Lantinga (slouken@libsdl.org) + */ #ifndef _SDL_H #define _SDL_H @@ -40,11 +89,14 @@ #include "SDL_timer.h" #include "SDL_video.h" #include "SDL_version.h" +#include "SDL_compat.h" #include "begin_code.h" /* Set up for C function definitions, even when using C++ */ #ifdef __cplusplus +/* *INDENT-OFF* */ extern "C" { +/* *INDENT-ON* */ #endif /* As of version 0.5, SDL is loaded dynamically into the application */ @@ -57,8 +109,8 @@ extern "C" { #define SDL_INIT_VIDEO 0x00000020 #define SDL_INIT_CDROM 0x00000100 #define SDL_INIT_JOYSTICK 0x00000200 -#define SDL_INIT_NOPARACHUTE 0x00100000 /* Don't catch fatal signals */ -#define SDL_INIT_EVENTTHREAD 0x01000000 /* Not supported on all OS's */ +#define SDL_INIT_NOPARACHUTE 0x00100000 /* Don't catch fatal signals */ +#define SDL_INIT_EVENTTHREAD 0x01000000 /* Not supported on all OS's */ #define SDL_INIT_EVERYTHING 0x0000FFFF /* This function loads the SDL dynamically linked library and initializes @@ -87,8 +139,12 @@ extern DECLSPEC void SDLCALL SDL_Quit(void); /* Ends C function definitions when using C++ */ #ifdef __cplusplus +/* *INDENT-OFF* */ } +/* *INDENT-ON* */ #endif #include "close_code.h" #endif /* _SDL_H */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/include/SDL_active.h b/include/SDL_active.h deleted file mode 100644 index 2cf474c5a..000000000 --- a/include/SDL_active.h +++ /dev/null @@ -1,58 +0,0 @@ -/* - SDL - Simple DirectMedia Layer - Copyright (C) 1997-2006 Sam Lantinga - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - - Sam Lantinga - slouken@libsdl.org -*/ - -/* Include file for SDL application focus event handling */ - -#ifndef _SDL_active_h -#define _SDL_active_h - -#include "SDL_stdinc.h" -#include "SDL_error.h" - -#include "begin_code.h" -/* Set up for C function definitions, even when using C++ */ -#ifdef __cplusplus -extern "C" { -#endif - -/* The available application states */ -#define SDL_APPMOUSEFOCUS 0x01 /* The app has mouse coverage */ -#define SDL_APPINPUTFOCUS 0x02 /* The app has input focus */ -#define SDL_APPACTIVE 0x04 /* The application is active */ - -/* Function prototypes */ -/* - * This function returns the current state of the application, which is a - * bitwise combination of SDL_APPMOUSEFOCUS, SDL_APPINPUTFOCUS, and - * SDL_APPACTIVE. If SDL_APPACTIVE is set, then the user is able to - * see your application, otherwise it has been iconified or disabled. - */ -extern DECLSPEC Uint8 SDLCALL SDL_GetAppState(void); - - -/* Ends C function definitions when using C++ */ -#ifdef __cplusplus -} -#endif -#include "close_code.h" - -#endif /* _SDL_active_h */ diff --git a/include/SDL_audio.h b/include/SDL_audio.h index 68ec4759d..d1c715fda 100644 --- a/include/SDL_audio.h +++ b/include/SDL_audio.h @@ -20,7 +20,11 @@ slouken@libsdl.org */ -/* Access to the raw audio mixing buffer for the SDL library */ +/** + * \file SDL_audio.h + * + * Access to the raw audio mixing buffer for the SDL library + */ #ifndef _SDL_audio_h #define _SDL_audio_h @@ -35,35 +39,38 @@ #include "begin_code.h" /* Set up for C function definitions, even when using C++ */ #ifdef __cplusplus +/* *INDENT-OFF* */ extern "C" { +/* *INDENT-ON* */ #endif /* The calculated values in this structure are calculated by SDL_OpenAudio() */ -typedef struct SDL_AudioSpec { - int freq; /* DSP frequency -- samples per second */ - Uint16 format; /* Audio data format */ - Uint8 channels; /* Number of channels: 1 mono, 2 stereo */ - Uint8 silence; /* Audio buffer silence value (calculated) */ - Uint16 samples; /* Audio buffer size in samples (power of 2) */ - Uint16 padding; /* Necessary for some compile environments */ - Uint32 size; /* Audio buffer size in bytes (calculated) */ - /* This function is called when the audio device needs more data. - 'stream' is a pointer to the audio data buffer - 'len' is the length of that buffer in bytes. - Once the callback returns, the buffer will no longer be valid. - Stereo samples are stored in a LRLRLR ordering. - */ - void (SDLCALL *callback)(void *userdata, Uint8 *stream, int len); - void *userdata; +typedef struct SDL_AudioSpec +{ + int freq; /* DSP frequency -- samples per second */ + Uint16 format; /* Audio data format */ + Uint8 channels; /* Number of channels: 1 mono, 2 stereo */ + Uint8 silence; /* Audio buffer silence value (calculated) */ + Uint16 samples; /* Audio buffer size in samples (power of 2) */ + Uint16 padding; /* Necessary for some compile environments */ + Uint32 size; /* Audio buffer size in bytes (calculated) */ + /* This function is called when the audio device needs more data. + 'stream' is a pointer to the audio data buffer + 'len' is the length of that buffer in bytes. + Once the callback returns, the buffer will no longer be valid. + Stereo samples are stored in a LRLRLR ordering. + */ + void (SDLCALL * callback) (void *userdata, Uint8 * stream, int len); + void *userdata; } SDL_AudioSpec; /* Audio format flags (defaults to LSB byte order) */ -#define AUDIO_U8 0x0008 /* Unsigned 8-bit samples */ -#define AUDIO_S8 0x8008 /* Signed 8-bit samples */ -#define AUDIO_U16LSB 0x0010 /* Unsigned 16-bit samples */ -#define AUDIO_S16LSB 0x8010 /* Signed 16-bit samples */ -#define AUDIO_U16MSB 0x1010 /* As above, but big-endian byte order */ -#define AUDIO_S16MSB 0x9010 /* As above, but big-endian byte order */ +#define AUDIO_U8 0x0008 /* Unsigned 8-bit samples */ +#define AUDIO_S8 0x8008 /* Signed 8-bit samples */ +#define AUDIO_U16LSB 0x0010 /* Unsigned 16-bit samples */ +#define AUDIO_S16LSB 0x8010 /* Signed 16-bit samples */ +#define AUDIO_U16MSB 0x1010 /* As above, but big-endian byte order */ +#define AUDIO_S16MSB 0x9010 /* As above, but big-endian byte order */ #define AUDIO_U16 AUDIO_U16LSB #define AUDIO_S16 AUDIO_S16LSB @@ -78,23 +85,30 @@ typedef struct SDL_AudioSpec { /* A structure to hold a set of audio conversion filters and buffers */ -typedef struct SDL_AudioCVT { - int needed; /* Set to 1 if conversion possible */ - Uint16 src_format; /* Source audio format */ - Uint16 dst_format; /* Target audio format */ - double rate_incr; /* Rate conversion increment */ - Uint8 *buf; /* Buffer to hold entire audio data */ - int len; /* Length of original audio buffer */ - int len_cvt; /* Length of converted audio buffer */ - int len_mult; /* buffer must be len*len_mult big */ - double len_ratio; /* Given len, final size is len*len_ratio */ - void (SDLCALL *filters[10])(struct SDL_AudioCVT *cvt, Uint16 format); - int filter_index; /* Current audio conversion function */ +typedef struct SDL_AudioCVT +{ + int needed; /* Set to 1 if conversion possible */ + Uint16 src_format; /* Source audio format */ + Uint16 dst_format; /* Target audio format */ + double rate_incr; /* Rate conversion increment */ + Uint8 *buf; /* Buffer to hold entire audio data */ + int len; /* Length of original audio buffer */ + int len_cvt; /* Length of converted audio buffer */ + int len_mult; /* buffer must be len*len_mult big */ + double len_ratio; /* Given len, final size is len*len_ratio */ + void (SDLCALL * filters[10]) (struct SDL_AudioCVT * cvt, Uint16 format); + int filter_index; /* Current audio conversion function */ } SDL_AudioCVT; /* Function prototypes */ +/* These functions return the list of built in video drivers, in the + * order that they are normally initialized by default. + */ +extern DECLSPEC int SDLCALL SDL_GetNumAudioDrivers(void); +extern DECLSPEC const char *SDLCALL SDL_GetAudioDriver(int index); + /* These functions are used internally, and should not be used unless you * have a specific need to specify the audio driver you want to use. * You should normally use SDL_Init() or SDL_InitSubSystem(). @@ -102,11 +116,10 @@ typedef struct SDL_AudioCVT { extern DECLSPEC int SDLCALL SDL_AudioInit(const char *driver_name); extern DECLSPEC void SDLCALL SDL_AudioQuit(void); -/* This function fills the given character buffer with the name of the - * current audio driver, and returns a pointer to it if the audio driver has - * been initialized. It returns NULL if no driver has been initialized. +/* This function returns the name of the current audio driver, or NULL + * if no driver has been initialized. */ -extern DECLSPEC char * SDLCALL SDL_AudioDriverName(char *namebuf, int maxlen); +extern DECLSPEC const char *SDLCALL SDL_GetCurrentAudioDriver(void); /* * This function opens the audio device with the desired parameters, and @@ -149,15 +162,17 @@ extern DECLSPEC char * SDLCALL SDL_AudioDriverName(char *namebuf, int maxlen); * may modify the requested size of the audio buffer, you should allocate * any local mixing buffers after you open the audio device. */ -extern DECLSPEC int SDLCALL SDL_OpenAudio(SDL_AudioSpec *desired, SDL_AudioSpec *obtained); +extern DECLSPEC int SDLCALL SDL_OpenAudio(SDL_AudioSpec * desired, + SDL_AudioSpec * obtained); /* * Get the current audio state: */ -typedef enum { - SDL_AUDIO_STOPPED = 0, - SDL_AUDIO_PLAYING, - SDL_AUDIO_PAUSED +typedef enum +{ + SDL_AUDIO_STOPPED = 0, + SDL_AUDIO_PLAYING, + SDL_AUDIO_PAUSED } SDL_audiostatus; extern DECLSPEC SDL_audiostatus SDLCALL SDL_GetAudioStatus(void); @@ -187,7 +202,11 @@ extern DECLSPEC void SDLCALL SDL_PauseAudio(int pause_on); * wave file cannot be opened, uses an unknown data format, or is * corrupt. Currently raw and MS-ADPCM WAVE files are supported. */ -extern DECLSPEC SDL_AudioSpec * SDLCALL SDL_LoadWAV_RW(SDL_RWops *src, int freesrc, SDL_AudioSpec *spec, Uint8 **audio_buf, Uint32 *audio_len); +extern DECLSPEC SDL_AudioSpec *SDLCALL SDL_LoadWAV_RW(SDL_RWops * src, + int freesrc, + SDL_AudioSpec * spec, + Uint8 ** audio_buf, + Uint32 * audio_len); /* Compatibility convenience function -- loads a WAV from a file */ #define SDL_LoadWAV(file, spec, audio_buf, audio_len) \ @@ -196,7 +215,7 @@ extern DECLSPEC SDL_AudioSpec * SDLCALL SDL_LoadWAV_RW(SDL_RWops *src, int frees /* * This function frees data previously allocated with SDL_LoadWAV_RW() */ -extern DECLSPEC void SDLCALL SDL_FreeWAV(Uint8 *audio_buf); +extern DECLSPEC void SDLCALL SDL_FreeWAV(Uint8 * audio_buf); /* * This function takes a source format and rate and a destination format @@ -205,9 +224,13 @@ extern DECLSPEC void SDLCALL SDL_FreeWAV(Uint8 *audio_buf); * to the other. * This function returns 0, or -1 if there was an error. */ -extern DECLSPEC int SDLCALL SDL_BuildAudioCVT(SDL_AudioCVT *cvt, - Uint16 src_format, Uint8 src_channels, int src_rate, - Uint16 dst_format, Uint8 dst_channels, int dst_rate); +extern DECLSPEC int SDLCALL SDL_BuildAudioCVT(SDL_AudioCVT * cvt, + Uint16 src_format, + Uint8 src_channels, + int src_rate, + Uint16 dst_format, + Uint8 dst_channels, + int dst_rate); /* Once you have initialized the 'cvt' structure using SDL_BuildAudioCVT(), * created an audio buffer cvt->buf, and filled it with cvt->len bytes of @@ -217,7 +240,7 @@ extern DECLSPEC int SDLCALL SDL_BuildAudioCVT(SDL_AudioCVT *cvt, * cvt->buf should be allocated after the cvt structure is initialized by * SDL_BuildAudioCVT(), and should be cvt->len*cvt->len_mult bytes long. */ -extern DECLSPEC int SDLCALL SDL_ConvertAudio(SDL_AudioCVT *cvt); +extern DECLSPEC int SDLCALL SDL_ConvertAudio(SDL_AudioCVT * cvt); /* * This takes two audio buffers of the playing audio format and mixes @@ -227,7 +250,8 @@ extern DECLSPEC int SDLCALL SDL_ConvertAudio(SDL_AudioCVT *cvt); * This is provided for convenience -- you can mix your own audio data. */ #define SDL_MIX_MAXVOLUME 128 -extern DECLSPEC void SDLCALL SDL_MixAudio(Uint8 *dst, const Uint8 *src, Uint32 len, int volume); +extern DECLSPEC void SDLCALL SDL_MixAudio(Uint8 * dst, const Uint8 * src, + Uint32 len, int volume); /* * The lock manipulated by these functions protects the callback function. @@ -246,8 +270,12 @@ extern DECLSPEC void SDLCALL SDL_CloseAudio(void); /* Ends C function definitions when using C++ */ #ifdef __cplusplus +/* *INDENT-OFF* */ } +/* *INDENT-ON* */ #endif #include "close_code.h" #endif /* _SDL_audio_h */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/include/SDL_cdrom.h b/include/SDL_cdrom.h index 5f8f0c62a..73f503e23 100644 --- a/include/SDL_cdrom.h +++ b/include/SDL_cdrom.h @@ -20,7 +20,11 @@ slouken@libsdl.org */ -/* This is the CD-audio control API for Simple DirectMedia Layer */ +/** + * \file SDL_cdrom.h + * + * This is the CD-audio control API for Simple DirectMedia Layer + */ #ifndef _SDL_cdrom_h #define _SDL_cdrom_h @@ -31,7 +35,9 @@ #include "begin_code.h" /* Set up for C function definitions, even when using C++ */ #ifdef __cplusplus +/* *INDENT-OFF* */ extern "C" { +/* *INDENT-ON* */ #endif /* In order to use these functions, SDL_Init() must have been called @@ -47,35 +53,38 @@ extern "C" { #define SDL_DATA_TRACK 0x04 /* The possible states which a CD-ROM drive can be in. */ -typedef enum { - CD_TRAYEMPTY, - CD_STOPPED, - CD_PLAYING, - CD_PAUSED, - CD_ERROR = -1 +typedef enum +{ + CD_TRAYEMPTY, + CD_STOPPED, + CD_PLAYING, + CD_PAUSED, + CD_ERROR = -1 } CDstatus; /* Given a status, returns true if there's a disk in the drive */ #define CD_INDRIVE(status) ((int)(status) > 0) -typedef struct SDL_CDtrack { - Uint8 id; /* Track number */ - Uint8 type; /* Data or audio track */ - Uint16 unused; - Uint32 length; /* Length, in frames, of this track */ - Uint32 offset; /* Offset, in frames, from start of disk */ +typedef struct SDL_CDtrack +{ + Uint8 id; /* Track number */ + Uint8 type; /* Data or audio track */ + Uint16 unused; + Uint32 length; /* Length, in frames, of this track */ + Uint32 offset; /* Offset, in frames, from start of disk */ } SDL_CDtrack; /* This structure is only current as of the last call to SDL_CDStatus() */ -typedef struct SDL_CD { - int id; /* Private drive identifier */ - CDstatus status; /* Current drive status */ - - /* The rest of this structure is only valid if there's a CD in drive */ - int numtracks; /* Number of tracks on disk */ - int cur_track; /* Current track position */ - int cur_frame; /* Current frame offset within current track */ - SDL_CDtrack track[SDL_MAX_TRACKS+1]; +typedef struct SDL_CD +{ + int id; /* Private drive identifier */ + CDstatus status; /* Current drive status */ + + /* The rest of this structure is only valid if there's a CD in drive */ + int numtracks; /* Number of tracks on disk */ + int cur_track; /* Current track position */ + int cur_frame; /* Current frame offset within current track */ + SDL_CDtrack track[SDL_MAX_TRACKS + 1]; } SDL_CD; /* Conversion functions from frames to Minute/Second/Frames and vice versa */ @@ -103,7 +112,7 @@ extern DECLSPEC int SDLCALL SDL_CDNumDrives(void); "E:" "/dev/disk/ide/1/master" */ -extern DECLSPEC const char * SDLCALL SDL_CDName(int drive); +extern DECLSPEC const char *SDLCALL SDL_CDName(int drive); /* Opens a CD-ROM drive for access. It returns a drive handle on success, or NULL if the drive was invalid or busy. This newly opened CD-ROM @@ -111,13 +120,13 @@ extern DECLSPEC const char * SDLCALL SDL_CDName(int drive); CD-ROM handle. Drives are numbered starting with 0. Drive 0 is the system default CD-ROM. */ -extern DECLSPEC SDL_CD * SDLCALL SDL_CDOpen(int drive); +extern DECLSPEC SDL_CD *SDLCALL SDL_CDOpen(int drive); /* This function returns the current status of the given drive. If the drive has a CD in it, the table of contents of the CD and current play position of the CD will be stored in the SDL_CD structure. */ -extern DECLSPEC CDstatus SDLCALL SDL_CDStatus(SDL_CD *cdrom); +extern DECLSPEC CDstatus SDLCALL SDL_CDStatus(SDL_CD * cdrom); /* Play the given CD starting at 'start_track' and 'start_frame' for 'ntracks' tracks and 'nframes' frames. If both 'ntrack' and 'nframe' are 0, play @@ -138,34 +147,40 @@ extern DECLSPEC CDstatus SDLCALL SDL_CDStatus(SDL_CD *cdrom); This function returns 0, or -1 if there was an error. */ -extern DECLSPEC int SDLCALL SDL_CDPlayTracks(SDL_CD *cdrom, - int start_track, int start_frame, int ntracks, int nframes); +extern DECLSPEC int SDLCALL SDL_CDPlayTracks(SDL_CD * cdrom, + int start_track, + int start_frame, int ntracks, + int nframes); /* Play the given CD starting at 'start' frame for 'length' frames. It returns 0, or -1 if there was an error. */ -extern DECLSPEC int SDLCALL SDL_CDPlay(SDL_CD *cdrom, int start, int length); +extern DECLSPEC int SDLCALL SDL_CDPlay(SDL_CD * cdrom, int start, int length); /* Pause play -- returns 0, or -1 on error */ -extern DECLSPEC int SDLCALL SDL_CDPause(SDL_CD *cdrom); +extern DECLSPEC int SDLCALL SDL_CDPause(SDL_CD * cdrom); /* Resume play -- returns 0, or -1 on error */ -extern DECLSPEC int SDLCALL SDL_CDResume(SDL_CD *cdrom); +extern DECLSPEC int SDLCALL SDL_CDResume(SDL_CD * cdrom); /* Stop play -- returns 0, or -1 on error */ -extern DECLSPEC int SDLCALL SDL_CDStop(SDL_CD *cdrom); +extern DECLSPEC int SDLCALL SDL_CDStop(SDL_CD * cdrom); /* Eject CD-ROM -- returns 0, or -1 on error */ -extern DECLSPEC int SDLCALL SDL_CDEject(SDL_CD *cdrom); +extern DECLSPEC int SDLCALL SDL_CDEject(SDL_CD * cdrom); /* Closes the handle for the CD-ROM drive */ -extern DECLSPEC void SDLCALL SDL_CDClose(SDL_CD *cdrom); +extern DECLSPEC void SDLCALL SDL_CDClose(SDL_CD * cdrom); /* Ends C function definitions when using C++ */ #ifdef __cplusplus +/* *INDENT-OFF* */ } +/* *INDENT-ON* */ #endif #include "close_code.h" #endif /* _SDL_video_h */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/include/SDL_compat.h b/include/SDL_compat.h new file mode 100644 index 000000000..520fbc85f --- /dev/null +++ b/include/SDL_compat.h @@ -0,0 +1,186 @@ +/* + SDL - Simple DirectMedia Layer + Copyright (C) 1997-2006 Sam Lantinga + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + Sam Lantinga + slouken@libsdl.org +*/ + +/* This file contains functions for backwards compatibility with SDL 1.2 */ + +#ifndef _SDL_compat_h +#define _SDL_compat_h + +#include "SDL_video.h" +#include "SDL_version.h" + +#include "begin_code.h" +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +/* *INDENT-OFF* */ +extern "C" { +/* *INDENT-ON* */ +#endif + +#define SDL_SWSURFACE 0x00000000 +#define SDL_ANYFORMAT 0x00100000 +#define SDL_HWPALETTE 0x00200000 +#define SDL_DOUBLEBUF 0x00400000 +#define SDL_FULLSCREEN 0x00800000 +#define SDL_RESIZABLE 0x01000000 +#define SDL_NOFRAME 0x02000000 +#define SDL_OPENGL 0x04000000 +#define SDL_ASYNCBLIT 0x08000000 /* Not used */ +#define SDL_HWACCEL 0x08000000 /* Not used */ + +#define SDL_APPMOUSEFOCUS 0x01 +#define SDL_APPINPUTFOCUS 0x02 +#define SDL_APPACTIVE 0x04 + +#define SDL_LOGPAL 0x01 +#define SDL_PHYSPAL 0x02 + +#define SDL_ACTIVEEVENT SDL_EVENT_RESERVED1 +#define SDL_VIDEORESIZE SDL_EVENT_RESERVED2 +#define SDL_VIDEOEXPOSE SDL_EVENT_RESERVED3 +#define SDL_ACTIVEEVENTMASK SDL_EVENTMASK(SDL_ACTIVEEVENT) +#define SDL_VIDEORESIZEMASK SDL_EVENTMASK(SDL_VIDEORESIZE) +#define SDL_VIDEOEXPOSEMASK SDL_EVENTMASK(SDL_VIDEOEXPOSE) + +#define SDL_BUTTON_WHEELUP 4 +#define SDL_BUTTON_WHEELDOWN 5 + +typedef struct SDL_VideoInfo +{ + Uint32 hw_available:1; + Uint32 wm_available:1; + Uint32 UnusedBits1:6; + Uint32 UnusedBits2:1; + Uint32 blit_hw:1; + Uint32 blit_hw_CC:1; + Uint32 blit_hw_A:1; + Uint32 blit_sw:1; + Uint32 blit_sw_CC:1; + Uint32 blit_sw_A:1; + Uint32 blit_fill:1; + Uint32 UnusedBits3:16; + Uint32 video_mem; + + SDL_PixelFormat *vfmt; +} SDL_VideoInfo; + +/* The most common video overlay formats. + For an explanation of these pixel formats, see: + http://www.webartz.com/fourcc/indexyuv.htm + + For information on the relationship between color spaces, see: + http://www.neuro.sfc.keio.ac.jp/~aly/polygon/info/color-space-faq.html + */ +#define SDL_YV12_OVERLAY 0x32315659 /* Planar mode: Y + V + U (3 planes) */ +#define SDL_IYUV_OVERLAY 0x56555949 /* Planar mode: Y + U + V (3 planes) */ +#define SDL_YUY2_OVERLAY 0x32595559 /* Packed mode: Y0+U0+Y1+V0 (1 plane) */ +#define SDL_UYVY_OVERLAY 0x59565955 /* Packed mode: U0+Y0+V0+Y1 (1 plane) */ +#define SDL_YVYU_OVERLAY 0x55595659 /* Packed mode: Y0+V0+Y1+U0 (1 plane) */ + +/* The YUV hardware video overlay */ +typedef struct SDL_Overlay +{ + Uint32 format; /* Read-only */ + int w, h; /* Read-only */ + int planes; /* Read-only */ + Uint16 *pitches; /* Read-only */ + Uint8 **pixels; /* Read-write */ + + /* Hardware-specific surface info */ + struct private_yuvhwfuncs *hwfuncs; + struct private_yuvhwdata *hwdata; + + /* Special flags */ + Uint32 hw_overlay:1; /* Flag: This overlay hardware accelerated? */ + Uint32 UnusedBits:31; +} SDL_Overlay; + +typedef enum +{ + SDL_GRAB_QUERY = -1, + SDL_GRAB_OFF = 0, + SDL_GRAB_ON = 1 +} SDL_GrabMode; + +struct SDL_SysWMinfo; + +#define SDL_SetModuleHandle(x) +#define SDL_AllocSurface SDL_CreateRGBSurface + +extern DECLSPEC const SDL_version *SDLCALL SDL_Linked_Version(void); +extern DECLSPEC char *SDLCALL SDL_AudioDriverName(char *namebuf, int maxlen); +extern DECLSPEC char *SDLCALL SDL_VideoDriverName(char *namebuf, int maxlen); +extern DECLSPEC const SDL_VideoInfo *SDLCALL SDL_GetVideoInfo(void); +extern DECLSPEC int SDLCALL SDL_VideoModeOK(int width, int height, int bpp, + Uint32 flags); +extern DECLSPEC SDL_Rect **SDLCALL SDL_ListModes(SDL_PixelFormat * format, + Uint32 flags); +extern DECLSPEC SDL_Surface *SDLCALL SDL_SetVideoMode(int width, int height, + int bpp, Uint32 flags); +extern DECLSPEC SDL_Surface *SDLCALL SDL_GetVideoSurface(void); +extern DECLSPEC void SDLCALL SDL_UpdateRects(SDL_Surface * screen, + int numrects, SDL_Rect * rects); +extern DECLSPEC void SDLCALL SDL_UpdateRect(SDL_Surface * screen, Sint32 x, + Sint32 y, Uint32 w, Uint32 h); +extern DECLSPEC int SDLCALL SDL_Flip(SDL_Surface * screen); +extern DECLSPEC SDL_Surface *SDLCALL SDL_DisplayFormat(SDL_Surface * surface); +extern DECLSPEC SDL_Surface *SDLCALL SDL_DisplayFormatAlpha(SDL_Surface * + surface); +extern DECLSPEC void SDLCALL SDL_WM_SetCaption(const char *title, + const char *icon); +extern DECLSPEC void SDLCALL SDL_WM_GetCaption(char **title, char **icon); +extern DECLSPEC void SDLCALL SDL_WM_SetIcon(SDL_Surface * icon, Uint8 * mask); +extern DECLSPEC int SDLCALL SDL_WM_IconifyWindow(void); +extern DECLSPEC int SDLCALL SDL_WM_ToggleFullScreen(SDL_Surface * surface); +extern DECLSPEC SDL_GrabMode SDLCALL SDL_WM_GrabInput(SDL_GrabMode mode); +extern DECLSPEC int SDLCALL SDL_SetPalette(SDL_Surface * surface, int flags, + const SDL_Color * colors, + int firstcolor, int ncolors); +extern DECLSPEC int SDLCALL SDL_SetColors(SDL_Surface * surface, + const SDL_Color * colors, + int firstcolor, int ncolors); +extern DECLSPEC int SDLCALL SDL_GetWMInfo(struct SDL_SysWMinfo *info); +extern DECLSPEC Uint8 SDLCALL SDL_GetAppState(void); +extern DECLSPEC void SDLCALL SDL_WarpMouse(Uint16 x, Uint16 y); +extern DECLSPEC SDL_Overlay *SDLCALL SDL_CreateYUVOverlay(int width, + int height, + Uint32 format, + SDL_Surface * + display); +extern DECLSPEC int SDLCALL SDL_LockYUVOverlay(SDL_Overlay * overlay); +extern DECLSPEC void SDLCALL SDL_UnlockYUVOverlay(SDL_Overlay * overlay); +extern DECLSPEC int SDLCALL SDL_DisplayYUVOverlay(SDL_Overlay * overlay, + SDL_Rect * dstrect); +extern DECLSPEC void SDLCALL SDL_FreeYUVOverlay(SDL_Overlay * overlay); +extern DECLSPEC int SDLCALL SDL_GL_GetAttribute(SDL_GLattr attr, int *value); + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +/* *INDENT-OFF* */ +} +/* *INDENT-ON* */ +#endif +#include "close_code.h" + +#endif /* _SDL_compat_h */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/include/SDL_config.h.in b/include/SDL_config.h.in index 6f89569c9..7435c8f7a 100644 --- a/include/SDL_config.h.in +++ b/include/SDL_config.h.in @@ -198,6 +198,7 @@ #undef SDL_JOYSTICK_AMIGA #undef SDL_JOYSTICK_BEOS #undef SDL_JOYSTICK_DC +#undef SDL_JOYSTICK_DINPUT #undef SDL_JOYSTICK_DUMMY #undef SDL_JOYSTICK_IOKIT #undef SDL_JOYSTICK_LINUX @@ -252,7 +253,6 @@ #undef SDL_VIDEO_DRIVER_BWINDOW #undef SDL_VIDEO_DRIVER_CYBERGRAPHICS #undef SDL_VIDEO_DRIVER_DC -#undef SDL_VIDEO_DRIVER_DDRAW #undef SDL_VIDEO_DRIVER_DGA #undef SDL_VIDEO_DRIVER_DIRECTFB #undef SDL_VIDEO_DRIVER_DRAWSPROCKET @@ -262,6 +262,7 @@ #undef SDL_VIDEO_DRIVER_GAPI #undef SDL_VIDEO_DRIVER_GEM #undef SDL_VIDEO_DRIVER_GGI +#undef SDL_VIDEO_DRIVER_GLSDL #undef SDL_VIDEO_DRIVER_IPOD #undef SDL_VIDEO_DRIVER_NANOX #undef SDL_VIDEO_DRIVER_OS2FS @@ -274,7 +275,7 @@ #undef SDL_VIDEO_DRIVER_SVGALIB #undef SDL_VIDEO_DRIVER_TOOLBOX #undef SDL_VIDEO_DRIVER_VGL -#undef SDL_VIDEO_DRIVER_WINDIB +#undef SDL_VIDEO_DRIVER_WIN32 #undef SDL_VIDEO_DRIVER_WSCONS #undef SDL_VIDEO_DRIVER_X11 #undef SDL_VIDEO_DRIVER_X11_DGAMOUSE @@ -290,6 +291,10 @@ #undef SDL_VIDEO_DRIVER_X11_XV #undef SDL_VIDEO_DRIVER_XBIOS +#undef SDL_VIDEO_RENDER_D3D +#undef SDL_VIDEO_RENDER_GDI +#undef SDL_VIDEO_RENDER_OGL + /* Enable OpenGL support */ #undef SDL_VIDEO_OPENGL #undef SDL_VIDEO_OPENGL_GLX diff --git a/include/SDL_config_amiga.h b/include/SDL_config_amiga.h index 23e086192..8daef6827 100644 --- a/include/SDL_config_amiga.h +++ b/include/SDL_config_amiga.h @@ -73,6 +73,7 @@ /* Enable various video drivers */ #define SDL_VIDEO_DRIVER_CYBERGRAPHICS 1 #define SDL_VIDEO_DRIVER_DUMMY 1 +#define SDL_VIDEO_DRIVER_GLSDL 1 /* Enable OpenGL support */ #define SDL_VIDEO_OPENGL 1 diff --git a/include/SDL_config_dreamcast.h b/include/SDL_config_dreamcast.h index 9cbeea316..cf76dabfb 100644 --- a/include/SDL_config_dreamcast.h +++ b/include/SDL_config_dreamcast.h @@ -102,5 +102,6 @@ typedef unsigned long uintptr_t; /* Enable various video drivers */ #define SDL_VIDEO_DRIVER_DC 1 #define SDL_VIDEO_DRIVER_DUMMY 1 +#define SDL_VIDEO_DRIVER_GLSDL 1 #endif /* _SDL_config_dreamcast_h */ diff --git a/include/SDL_config_macos.h b/include/SDL_config_macos.h index c4a1c5980..efc926645 100644 --- a/include/SDL_config_macos.h +++ b/include/SDL_config_macos.h @@ -29,15 +29,15 @@ #include -typedef SInt8 int8_t; -typedef UInt8 uint8_t; -typedef SInt16 int16_t; -typedef UInt16 uint16_t; -typedef SInt32 int32_t; -typedef UInt32 uint32_t; -typedef SInt64 int64_t; -typedef UInt64 uint64_t; -typedef unsigned long uintptr_t; +typedef SInt8 int8_t; +typedef UInt8 uint8_t; +typedef SInt16 int16_t; +typedef UInt16 uint16_t; +typedef SInt32 int32_t; +typedef UInt32 uint32_t; +typedef SInt64 int64_t; +typedef UInt64 uint64_t; +typedef unsigned long uintptr_t; #define SDL_HAS_64BIT_TYPE 1 @@ -104,6 +104,7 @@ typedef unsigned long uintptr_t; /* Enable various video drivers */ #define SDL_VIDEO_DRIVER_DUMMY 1 #define SDL_VIDEO_DRIVER_DRAWSPROCKET 1 +#define SDL_VIDEO_DRIVER_GLSDL 1 #define SDL_VIDEO_DRIVER_TOOLBOX 1 /* Enable OpenGL support */ diff --git a/include/SDL_config_os2.h b/include/SDL_config_os2.h index 8cdea9ff2..c7f576d24 100644 --- a/include/SDL_config_os2.h +++ b/include/SDL_config_os2.h @@ -27,16 +27,16 @@ /* This is a set of defines to configure the SDL features */ -typedef signed char int8_t; -typedef unsigned char uint8_t; -typedef signed short int16_t; -typedef unsigned short uint16_t; -typedef signed int int32_t; -typedef unsigned int uint32_t; -typedef unsigned int size_t; -typedef unsigned long uintptr_t; -typedef signed long long int64_t; -typedef unsigned long long uint64_t; +typedef signed char int8_t; +typedef unsigned char uint8_t; +typedef signed short int16_t; +typedef unsigned short uint16_t; +typedef signed int int32_t; +typedef unsigned int uint32_t; +typedef unsigned int size_t; +typedef unsigned long uintptr_t; +typedef signed long long int64_t; +typedef unsigned long long uint64_t; #define SDL_HAS_64BIT_TYPE 1 diff --git a/include/SDL_config_win32.h b/include/SDL_config_win32.h index 23e4868c2..9ef5784f1 100644 --- a/include/SDL_config_win32.h +++ b/include/SDL_config_win32.h @@ -30,23 +30,23 @@ #ifdef __GNUC__ #define HAVE_STDINT_H 1 #elif defined(_MSC_VER) -typedef signed __int8 int8_t; -typedef unsigned __int8 uint8_t; -typedef signed __int16 int16_t; -typedef unsigned __int16 uint16_t; -typedef signed __int32 int32_t; -typedef unsigned __int32 uint32_t; -typedef signed __int64 int64_t; -typedef unsigned __int64 uint64_t; +typedef signed __int8 int8_t; +typedef unsigned __int8 uint8_t; +typedef signed __int16 int16_t; +typedef unsigned __int16 uint16_t; +typedef signed __int32 int32_t; +typedef unsigned __int32 uint32_t; +typedef signed __int64 int64_t; +typedef unsigned __int64 uint64_t; #ifndef _UINTPTR_T_DEFINED #ifdef _WIN64 -typedef unsigned __int64 uintptr_t; +typedef unsigned __int64 uintptr_t; #else -typedef unsigned int uintptr_t; +typedef unsigned int uintptr_t; #endif #define _UINTPTR_T_DEFINED #endif -#else /* !__GNUC__ && !_MSC_VER */ +#else /* !__GNUC__ && !_MSC_VER */ typedef signed char int8_t; typedef unsigned char uint8_t; typedef signed short int16_t; @@ -150,19 +150,17 @@ typedef unsigned int uintptr_t; #endif /* Enable various video drivers */ -#ifdef _WIN32_WCE -#define SDL_VIDEO_DRIVER_GAPI 1 -#endif -#ifndef _WIN32_WCE -#define SDL_VIDEO_DRIVER_DDRAW 1 -#endif #define SDL_VIDEO_DRIVER_DUMMY 1 -#define SDL_VIDEO_DRIVER_WINDIB 1 +#define SDL_VIDEO_DRIVER_WIN32 1 + +#define SDL_VIDEO_RENDER_D3D 1 +#define SDL_VIDEO_RENDER_GDI 1 /* Enable OpenGL support */ #ifndef _WIN32_WCE #define SDL_VIDEO_OPENGL 1 #define SDL_VIDEO_OPENGL_WGL 1 +#define SDL_VIDEO_RENDER_OGL 1 #endif /* Enable assembly routines (Win64 doesn't have inline asm) */ diff --git a/include/SDL_copying.h b/include/SDL_copying.h index 39e122db7..2f0d27a66 100644 --- a/include/SDL_copying.h +++ b/include/SDL_copying.h @@ -19,4 +19,3 @@ Sam Lantinga slouken@libsdl.org */ - diff --git a/include/SDL_cpuinfo.h b/include/SDL_cpuinfo.h index 72acbdd8b..1c99c2e9b 100644 --- a/include/SDL_cpuinfo.h +++ b/include/SDL_cpuinfo.h @@ -20,8 +20,11 @@ slouken@libsdl.org */ -/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ -/* CPU feature detection for SDL */ +/** + * \file SDL_cpuinfo.h + * + * CPU feature detection for SDL + */ #ifndef _SDL_cpuinfo_h #define _SDL_cpuinfo_h @@ -31,7 +34,9 @@ #include "begin_code.h" /* Set up for C function definitions, even when using C++ */ #ifdef __cplusplus +/* *INDENT-OFF* */ extern "C" { +/* *INDENT-ON* */ #endif /* This function returns true if the CPU has the RDTSC instruction @@ -68,8 +73,12 @@ extern DECLSPEC SDL_bool SDLCALL SDL_HasAltiVec(void); /* Ends C function definitions when using C++ */ #ifdef __cplusplus +/* *INDENT-OFF* */ } +/* *INDENT-ON* */ #endif #include "close_code.h" #endif /* _SDL_cpuinfo_h */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/include/SDL_endian.h b/include/SDL_endian.h index 6257a649d..f3de7b2b8 100644 --- a/include/SDL_endian.h +++ b/include/SDL_endian.h @@ -20,7 +20,11 @@ slouken@libsdl.org */ -/* Functions for reading and writing endian-specific values */ +/** + * \file SDL_endian.h + * + * Functions for reading and writing endian-specific values + */ #ifndef _SDL_endian_h #define _SDL_endian_h @@ -31,7 +35,7 @@ #define SDL_LIL_ENDIAN 1234 #define SDL_BIG_ENDIAN 4321 -#ifndef SDL_BYTEORDER /* Not defined in SDL_config.h? */ +#ifndef SDL_BYTEORDER /* Not defined in SDL_config.h? */ #if defined(__hppa__) || \ defined(__m68k__) || defined(mc68000) || defined(_M_M68K) || \ (defined(__MIPS__) && defined(__MISPEB__)) || \ @@ -47,7 +51,9 @@ #include "begin_code.h" /* Set up for C function definitions, even when using C++ */ #ifdef __cplusplus +/* *INDENT-OFF* */ extern "C" { +/* *INDENT-ON* */ #endif /* Use inline functions for compilers that support them, and static @@ -57,104 +63,124 @@ extern "C" { */ #if defined(__GNUC__) && defined(__i386__) && \ !(__GNUC__ == 2 && __GNUC_MINOR__ == 95 /* broken gcc version */) -static __inline__ Uint16 SDL_Swap16(Uint16 x) +static __inline__ Uint16 +SDL_Swap16(Uint16 x) { - __asm__("xchgb %b0,%h0" : "=q" (x) : "0" (x)); - return x; + __asm__("xchgb %b0,%h0": "=q"(x):"0"(x)); + return x; } #elif defined(__GNUC__) && defined(__x86_64__) -static __inline__ Uint16 SDL_Swap16(Uint16 x) +static __inline__ Uint16 +SDL_Swap16(Uint16 x) { - __asm__("xchgb %b0,%h0" : "=Q" (x) : "0" (x)); - return x; + __asm__("xchgb %b0,%h0": "=Q"(x):"0"(x)); + return x; } #elif defined(__GNUC__) && (defined(__powerpc__) || defined(__ppc__)) -static __inline__ Uint16 SDL_Swap16(Uint16 x) +static __inline__ Uint16 +SDL_Swap16(Uint16 x) { - Uint16 result; + Uint16 result; - __asm__("rlwimi %0,%2,8,16,23" : "=&r" (result) : "0" (x >> 8), "r" (x)); - return result; + __asm__("rlwimi %0,%2,8,16,23": "=&r"(result):"0"(x >> 8), "r"(x)); + return result; } #elif defined(__GNUC__) && (defined(__M68000__) || defined(__M68020__)) -static __inline__ Uint16 SDL_Swap16(Uint16 x) +static __inline__ Uint16 +SDL_Swap16(Uint16 x) { - __asm__("rorw #8,%0" : "=d" (x) : "0" (x) : "cc"); - return x; + __asm__("rorw #8,%0": "=d"(x): "0"(x):"cc"); + return x; } #else -static __inline__ Uint16 SDL_Swap16(Uint16 x) { - return((x<<8)|(x>>8)); +static __inline__ Uint16 +SDL_Swap16(Uint16 x) +{ + return ((x << 8) | (x >> 8)); } #endif #if defined(__GNUC__) && defined(__i386__) -static __inline__ Uint32 SDL_Swap32(Uint32 x) +static __inline__ Uint32 +SDL_Swap32(Uint32 x) { - __asm__("bswap %0" : "=r" (x) : "0" (x)); - return x; + __asm__("bswap %0": "=r"(x):"0"(x)); + return x; } #elif defined(__GNUC__) && defined(__x86_64__) -static __inline__ Uint32 SDL_Swap32(Uint32 x) +static __inline__ Uint32 +SDL_Swap32(Uint32 x) { - __asm__("bswapl %0" : "=r" (x) : "0" (x)); - return x; + __asm__("bswapl %0": "=r"(x):"0"(x)); + return x; } #elif defined(__GNUC__) && (defined(__powerpc__) || defined(__ppc__)) -static __inline__ Uint32 SDL_Swap32(Uint32 x) +static __inline__ Uint32 +SDL_Swap32(Uint32 x) { - Uint32 result; + Uint32 result; - __asm__("rlwimi %0,%2,24,16,23" : "=&r" (result) : "0" (x>>24), "r" (x)); - __asm__("rlwimi %0,%2,8,8,15" : "=&r" (result) : "0" (result), "r" (x)); - __asm__("rlwimi %0,%2,24,0,7" : "=&r" (result) : "0" (result), "r" (x)); - return result; + __asm__("rlwimi %0,%2,24,16,23": "=&r"(result):"0"(x >> 24), "r"(x)); + __asm__("rlwimi %0,%2,8,8,15": "=&r"(result):"0"(result), "r"(x)); + __asm__("rlwimi %0,%2,24,0,7": "=&r"(result):"0"(result), "r"(x)); + return result; } #elif defined(__GNUC__) && (defined(__M68000__) || defined(__M68020__)) -static __inline__ Uint32 SDL_Swap32(Uint32 x) +static __inline__ Uint32 +SDL_Swap32(Uint32 x) { - __asm__("rorw #8,%0\n\tswap %0\n\trorw #8,%0" : "=d" (x) : "0" (x) : "cc"); - return x; + __asm__("rorw #8,%0\n\tswap %0\n\trorw #8,%0": "=d"(x): "0"(x):"cc"); + return x; } #else -static __inline__ Uint32 SDL_Swap32(Uint32 x) { - return((x<<24)|((x<<8)&0x00FF0000)|((x>>8)&0x0000FF00)|(x>>24)); +static __inline__ Uint32 +SDL_Swap32(Uint32 x) +{ + return ((x << 24) | ((x << 8) & 0x00FF0000) | ((x >> 8) & 0x0000FF00) | + (x >> 24)); } #endif #ifdef SDL_HAS_64BIT_TYPE #if defined(__GNUC__) && defined(__i386__) -static __inline__ Uint64 SDL_Swap64(Uint64 x) +static __inline__ Uint64 +SDL_Swap64(Uint64 x) { - union { - struct { Uint32 a,b; } s; - Uint64 u; - } v; - v.u = x; - __asm__("bswapl %0 ; bswapl %1 ; xchgl %0,%1" - : "=r" (v.s.a), "=r" (v.s.b) - : "0" (v.s.a), "1" (v.s.b)); - return v.u; + union + { + struct + { + Uint32 a, b; + } s; + Uint64 u; + } v; + v.u = x; + __asm__("bswapl %0 ; bswapl %1 ; xchgl %0,%1": "=r"(v.s.a), "=r"(v.s.b):"0"(v.s.a), + "1"(v.s. + b)); + return v.u; } #elif defined(__GNUC__) && defined(__x86_64__) -static __inline__ Uint64 SDL_Swap64(Uint64 x) +static __inline__ Uint64 +SDL_Swap64(Uint64 x) { - __asm__("bswapq %0" : "=r" (x) : "0" (x)); - return x; + __asm__("bswapq %0": "=r"(x):"0"(x)); + return x; } #else -static __inline__ Uint64 SDL_Swap64(Uint64 x) +static __inline__ Uint64 +SDL_Swap64(Uint64 x) { - Uint32 hi, lo; - - /* Separate into high and low 32-bit values and swap them */ - lo = (Uint32)(x&0xFFFFFFFF); - x >>= 32; - hi = (Uint32)(x&0xFFFFFFFF); - x = SDL_Swap32(lo); - x <<= 32; - x |= SDL_Swap32(hi); - return(x); + Uint32 hi, lo; + + /* Separate into high and low 32-bit values and swap them */ + lo = (Uint32) (x & 0xFFFFFFFF); + x >>= 32; + hi = (Uint32) (x & 0xFFFFFFFF); + x = SDL_Swap32(lo); + x <<= 32; + x |= SDL_Swap32(hi); + return (x); } #endif #else @@ -185,8 +211,12 @@ static __inline__ Uint64 SDL_Swap64(Uint64 x) /* Ends C function definitions when using C++ */ #ifdef __cplusplus +/* *INDENT-OFF* */ } +/* *INDENT-ON* */ #endif #include "close_code.h" #endif /* _SDL_endian_h */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/include/SDL_error.h b/include/SDL_error.h index 26d6bfaef..8e02150e8 100644 --- a/include/SDL_error.h +++ b/include/SDL_error.h @@ -20,7 +20,10 @@ slouken@libsdl.org */ -/* Simple error message routines for SDL */ +/** + * \file SDL_error.h + * Simple error message routines for SDL + */ #ifndef _SDL_error_h #define _SDL_error_h @@ -30,32 +33,39 @@ #include "begin_code.h" /* Set up for C function definitions, even when using C++ */ #ifdef __cplusplus +/* *INDENT-OFF* */ extern "C" { +/* *INDENT-ON* */ #endif /* Public functions */ extern DECLSPEC void SDLCALL SDL_SetError(const char *fmt, ...); -extern DECLSPEC char * SDLCALL SDL_GetError(void); +extern DECLSPEC char *SDLCALL SDL_GetError(void); extern DECLSPEC void SDLCALL SDL_ClearError(void); /* Private error message function - used internally */ #define SDL_OutOfMemory() SDL_Error(SDL_ENOMEM) #define SDL_Unsupported() SDL_Error(SDL_UNSUPPORTED) -typedef enum { - SDL_ENOMEM, - SDL_EFREAD, - SDL_EFWRITE, - SDL_EFSEEK, - SDL_UNSUPPORTED, - SDL_LASTERROR +typedef enum +{ + SDL_ENOMEM, + SDL_EFREAD, + SDL_EFWRITE, + SDL_EFSEEK, + SDL_UNSUPPORTED, + SDL_LASTERROR } SDL_errorcode; extern DECLSPEC void SDLCALL SDL_Error(SDL_errorcode code); /* Ends C function definitions when using C++ */ #ifdef __cplusplus +/* *INDENT-OFF* */ } +/* *INDENT-ON* */ #endif #include "close_code.h" #endif /* _SDL_error_h */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/include/SDL_events.h b/include/SDL_events.h index 9fe918c7b..bc2df3465 100644 --- a/include/SDL_events.h +++ b/include/SDL_events.h @@ -20,14 +20,18 @@ slouken@libsdl.org */ -/* Include file for SDL event handling */ +/** + * \file SDL_events.h + * + * Include file for SDL event handling + */ #ifndef _SDL_events_h #define _SDL_events_h #include "SDL_stdinc.h" #include "SDL_error.h" -#include "SDL_active.h" +#include "SDL_video.h" #include "SDL_keyboard.h" #include "SDL_mouse.h" #include "SDL_joystick.h" @@ -36,202 +40,304 @@ #include "begin_code.h" /* Set up for C function definitions, even when using C++ */ #ifdef __cplusplus +/* *INDENT-OFF* */ extern "C" { +/* *INDENT-ON* */ #endif /* General keyboard/mouse state definitions */ #define SDL_RELEASED 0 #define SDL_PRESSED 1 -/* Event enumerations */ -typedef enum { - SDL_NOEVENT = 0, /* Unused (do not remove) */ - SDL_ACTIVEEVENT, /* Application loses/gains visibility */ - SDL_KEYDOWN, /* Keys pressed */ - SDL_KEYUP, /* Keys released */ - SDL_MOUSEMOTION, /* Mouse moved */ - SDL_MOUSEBUTTONDOWN, /* Mouse button pressed */ - SDL_MOUSEBUTTONUP, /* Mouse button released */ - SDL_JOYAXISMOTION, /* Joystick axis motion */ - SDL_JOYBALLMOTION, /* Joystick trackball motion */ - SDL_JOYHATMOTION, /* Joystick hat position change */ - SDL_JOYBUTTONDOWN, /* Joystick button pressed */ - SDL_JOYBUTTONUP, /* Joystick button released */ - SDL_QUIT, /* User-requested quit */ - SDL_SYSWMEVENT, /* System specific event */ - SDL_EVENT_RESERVEDA, /* Reserved for future use.. */ - SDL_EVENT_RESERVEDB, /* Reserved for future use.. */ - SDL_VIDEORESIZE, /* User resized video mode */ - SDL_VIDEOEXPOSE, /* Screen needs to be redrawn */ - SDL_EVENT_RESERVED2, /* Reserved for future use.. */ - SDL_EVENT_RESERVED3, /* Reserved for future use.. */ - SDL_EVENT_RESERVED4, /* Reserved for future use.. */ - SDL_EVENT_RESERVED5, /* Reserved for future use.. */ - SDL_EVENT_RESERVED6, /* Reserved for future use.. */ - SDL_EVENT_RESERVED7, /* Reserved for future use.. */ - /* Events SDL_USEREVENT through SDL_MAXEVENTS-1 are for your use */ - SDL_USEREVENT = 24, - /* This last event is only for bounding internal arrays - It is the number of bits in the event mask datatype -- Uint32 - */ - SDL_NUMEVENTS = 32 +/** + * \enum SDL_EventType + * + * \brief The types of events that can be delivered + */ +typedef enum +{ + SDL_NOEVENT = 0, /**< Unused (do not remove) */ + SDL_WINDOWEVENT, /**< Window state change */ + SDL_KEYDOWN, /**< Keys pressed */ + SDL_KEYUP, /**< Keys released */ + SDL_TEXTINPUT, /**< Keyboard text input */ + SDL_MOUSEMOTION, /**< Mouse moved */ + SDL_MOUSEBUTTONDOWN, /**< Mouse button pressed */ + SDL_MOUSEBUTTONUP, /**< Mouse button released */ + SDL_MOUSEWHEEL, /**< Mouse wheel motion */ + SDL_JOYAXISMOTION, /**< Joystick axis motion */ + SDL_JOYBALLMOTION, /**< Joystick trackball motion */ + SDL_JOYHATMOTION, /**< Joystick hat position change */ + SDL_JOYBUTTONDOWN, /**< Joystick button pressed */ + SDL_JOYBUTTONUP, /**< Joystick button released */ + SDL_QUIT, /**< User-requested quit */ + SDL_SYSWMEVENT, /**< System specific event */ + SDL_EVENT_RESERVED1, /**< Reserved for future use... */ + SDL_EVENT_RESERVED2, /**< Reserved for future use... */ + SDL_EVENT_RESERVED3, /**< Reserved for future use... */ + /* Events SDL_USEREVENT through SDL_MAXEVENTS-1 are for your use */ + SDL_USEREVENT = 24, + /* This last event is only for bounding internal arrays + It is the number of bits in the event mask datatype -- Uint32 + */ + SDL_NUMEVENTS = 32 } SDL_EventType; -/* Predefined event masks */ +/** + * \enum SDL_EventMask + * + * \brief Predefined event masks + */ #define SDL_EVENTMASK(X) (1<<(X)) -typedef enum { - SDL_ACTIVEEVENTMASK = SDL_EVENTMASK(SDL_ACTIVEEVENT), - SDL_KEYDOWNMASK = SDL_EVENTMASK(SDL_KEYDOWN), - SDL_KEYUPMASK = SDL_EVENTMASK(SDL_KEYUP), - SDL_KEYEVENTMASK = SDL_EVENTMASK(SDL_KEYDOWN)| - SDL_EVENTMASK(SDL_KEYUP), - SDL_MOUSEMOTIONMASK = SDL_EVENTMASK(SDL_MOUSEMOTION), - SDL_MOUSEBUTTONDOWNMASK = SDL_EVENTMASK(SDL_MOUSEBUTTONDOWN), - SDL_MOUSEBUTTONUPMASK = SDL_EVENTMASK(SDL_MOUSEBUTTONUP), - SDL_MOUSEEVENTMASK = SDL_EVENTMASK(SDL_MOUSEMOTION)| - SDL_EVENTMASK(SDL_MOUSEBUTTONDOWN)| - SDL_EVENTMASK(SDL_MOUSEBUTTONUP), - SDL_JOYAXISMOTIONMASK = SDL_EVENTMASK(SDL_JOYAXISMOTION), - SDL_JOYBALLMOTIONMASK = SDL_EVENTMASK(SDL_JOYBALLMOTION), - SDL_JOYHATMOTIONMASK = SDL_EVENTMASK(SDL_JOYHATMOTION), - SDL_JOYBUTTONDOWNMASK = SDL_EVENTMASK(SDL_JOYBUTTONDOWN), - SDL_JOYBUTTONUPMASK = SDL_EVENTMASK(SDL_JOYBUTTONUP), - SDL_JOYEVENTMASK = SDL_EVENTMASK(SDL_JOYAXISMOTION)| - SDL_EVENTMASK(SDL_JOYBALLMOTION)| - SDL_EVENTMASK(SDL_JOYHATMOTION)| - SDL_EVENTMASK(SDL_JOYBUTTONDOWN)| - SDL_EVENTMASK(SDL_JOYBUTTONUP), - SDL_VIDEORESIZEMASK = SDL_EVENTMASK(SDL_VIDEORESIZE), - SDL_VIDEOEXPOSEMASK = SDL_EVENTMASK(SDL_VIDEOEXPOSE), - SDL_QUITMASK = SDL_EVENTMASK(SDL_QUIT), - SDL_SYSWMEVENTMASK = SDL_EVENTMASK(SDL_SYSWMEVENT) -} SDL_EventMask ; +typedef enum +{ + SDL_WINDOWEVENTMASK = SDL_EVENTMASK(SDL_WINDOWEVENT), + SDL_KEYDOWNMASK = SDL_EVENTMASK(SDL_KEYDOWN), + SDL_KEYUPMASK = SDL_EVENTMASK(SDL_KEYUP), + SDL_KEYEVENTMASK = SDL_EVENTMASK(SDL_KEYDOWN) | SDL_EVENTMASK(SDL_KEYUP), + SDL_TEXTINPUTMASK = SDL_EVENTMASK(SDL_TEXTINPUT), + SDL_MOUSEMOTIONMASK = SDL_EVENTMASK(SDL_MOUSEMOTION), + SDL_MOUSEBUTTONDOWNMASK = SDL_EVENTMASK(SDL_MOUSEBUTTONDOWN), + SDL_MOUSEBUTTONUPMASK = SDL_EVENTMASK(SDL_MOUSEBUTTONUP), + SDL_MOUSEWHEELMASK = SDL_EVENTMASK(SDL_MOUSEWHEEL), + SDL_MOUSEEVENTMASK = SDL_EVENTMASK(SDL_MOUSEMOTION) | + SDL_EVENTMASK(SDL_MOUSEBUTTONDOWN) | SDL_EVENTMASK(SDL_MOUSEBUTTONUP), + SDL_JOYAXISMOTIONMASK = SDL_EVENTMASK(SDL_JOYAXISMOTION), + SDL_JOYBALLMOTIONMASK = SDL_EVENTMASK(SDL_JOYBALLMOTION), + SDL_JOYHATMOTIONMASK = SDL_EVENTMASK(SDL_JOYHATMOTION), + SDL_JOYBUTTONDOWNMASK = SDL_EVENTMASK(SDL_JOYBUTTONDOWN), + SDL_JOYBUTTONUPMASK = SDL_EVENTMASK(SDL_JOYBUTTONUP), + SDL_JOYEVENTMASK = SDL_EVENTMASK(SDL_JOYAXISMOTION) | + SDL_EVENTMASK(SDL_JOYBALLMOTION) | + SDL_EVENTMASK(SDL_JOYHATMOTION) | + SDL_EVENTMASK(SDL_JOYBUTTONDOWN) | SDL_EVENTMASK(SDL_JOYBUTTONUP), + SDL_QUITMASK = SDL_EVENTMASK(SDL_QUIT), + SDL_SYSWMEVENTMASK = SDL_EVENTMASK(SDL_SYSWMEVENT) +} SDL_EventMask; #define SDL_ALLEVENTS 0xFFFFFFFF -/* Application visibility event structure */ -typedef struct SDL_ActiveEvent { - Uint8 type; /* SDL_ACTIVEEVENT */ - Uint8 gain; /* Whether given states were gained or lost (1/0) */ - Uint8 state; /* A mask of the focus states */ -} SDL_ActiveEvent; - -/* Keyboard event structure */ -typedef struct SDL_KeyboardEvent { - Uint8 type; /* SDL_KEYDOWN or SDL_KEYUP */ - Uint8 which; /* The keyboard device index */ - Uint8 state; /* SDL_PRESSED or SDL_RELEASED */ - SDL_keysym keysym; +/** + * \struct SDL_WindowEvent + * + * \brief Window state change event data + */ +typedef struct SDL_WindowEvent +{ + Uint8 type; /**< SDL_WINDOWEVENT */ + Uint8 event; /**< SDL_WindowEventID */ + int data1; /**< event dependent data */ + int data2; /**< event dependent data */ + SDL_WindowID windowID; /**< The associated window */ +} SDL_WindowEvent; + +/** + * \struct SDL_KeyboardEvent + * + * \brief Keyboard button event structure + */ +typedef struct SDL_KeyboardEvent +{ + Uint8 type; /**< SDL_KEYDOWN or SDL_KEYUP */ + Uint8 which; /**< The keyboard device index */ + Uint8 state; /**< SDL_PRESSED or SDL_RELEASED */ + SDL_keysym keysym; /**< The key that was pressed or released */ + SDL_WindowID windowID; /**< The window with keyboard focus, if any */ } SDL_KeyboardEvent; -/* Mouse motion event structure */ -typedef struct SDL_MouseMotionEvent { - Uint8 type; /* SDL_MOUSEMOTION */ - Uint8 which; /* The mouse device index */ - Uint8 state; /* The current button state */ - Uint16 x, y; /* The X/Y coordinates of the mouse */ - Sint16 xrel; /* The relative motion in the X direction */ - Sint16 yrel; /* The relative motion in the Y direction */ +/** + * \struct SDL_TextInputEvent + * + * \brief Keyboard text input event structure + */ +typedef struct SDL_TextInputEvent +{ + Uint8 type; /**< SDL_TEXTINPUT */ + Uint8 which; /**< The keyboard device index */ + char text[32]; /**< The input text */ + SDL_WindowID windowID; /**< The window with keyboard focus, if any */ +} SDL_TextInputEvent; + +/** + * \struct SDL_MouseMotionEvent + * + * \brief Mouse motion event structure + */ +typedef struct SDL_MouseMotionEvent +{ + Uint8 type; /**< SDL_MOUSEMOTION */ + Uint8 which; /**< The mouse device index */ + Uint8 state; /**< The current button state */ + int x; /**< X coordinate, relative to window */ + int y; /**< Y coordinate, relative to window */ + int xrel; /**< The relative motion in the X direction */ + int yrel; /**< The relative motion in the Y direction */ + SDL_WindowID windowID; /**< The window with mouse focus, if any */ } SDL_MouseMotionEvent; -/* Mouse button event structure */ -typedef struct SDL_MouseButtonEvent { - Uint8 type; /* SDL_MOUSEBUTTONDOWN or SDL_MOUSEBUTTONUP */ - Uint8 which; /* The mouse device index */ - Uint8 button; /* The mouse button index */ - Uint8 state; /* SDL_PRESSED or SDL_RELEASED */ - Uint16 x, y; /* The X/Y coordinates of the mouse at press time */ +/** + * \struct SDL_MouseButtonEvent + * + * \brief Mouse button event structure + */ +typedef struct SDL_MouseButtonEvent +{ + Uint8 type; /**< SDL_MOUSEBUTTONDOWN or SDL_MOUSEBUTTONUP */ + Uint8 which; /**< The mouse device index */ + Uint8 button; /**< The mouse button index */ + Uint8 state; /**< SDL_PRESSED or SDL_RELEASED */ + int x; /**< X coordinate, relative to window */ + int y; /**< Y coordinate, relative to window */ + SDL_WindowID windowID; /**< The window with mouse focus, if any */ } SDL_MouseButtonEvent; -/* Joystick axis motion event structure */ -typedef struct SDL_JoyAxisEvent { - Uint8 type; /* SDL_JOYAXISMOTION */ - Uint8 which; /* The joystick device index */ - Uint8 axis; /* The joystick axis index */ - Sint16 value; /* The axis value (range: -32768 to 32767) */ +/** + * \struct SDL_MouseWheelEvent + * + * \brief Mouse wheel event structure + */ +typedef struct SDL_MouseWheelEvent +{ + Uint8 type; /**< SDL_MOUSEWHEEL */ + Uint8 which; /**< The mouse device index */ + int motion; /**< The direction and distance scrolled */ + SDL_WindowID windowID; /**< The window with mouse focus, if any */ +} SDL_MouseWheelEvent; + +/** + * \struct SDL_JoyAxisEvent + * + * \brief Joystick axis motion event structure + */ +typedef struct SDL_JoyAxisEvent +{ + Uint8 type; /**< SDL_JOYAXISMOTION */ + Uint8 which; /**< The joystick device index */ + Uint8 axis; /**< The joystick axis index */ + int value; /**< The axis value (range: -32768 to 32767) */ } SDL_JoyAxisEvent; -/* Joystick trackball motion event structure */ -typedef struct SDL_JoyBallEvent { - Uint8 type; /* SDL_JOYBALLMOTION */ - Uint8 which; /* The joystick device index */ - Uint8 ball; /* The joystick trackball index */ - Sint16 xrel; /* The relative motion in the X direction */ - Sint16 yrel; /* The relative motion in the Y direction */ +/** + * \struct SDL_JoyBallEvent + * + * \brief Joystick trackball motion event structure + */ +typedef struct SDL_JoyBallEvent +{ + Uint8 type; /**< SDL_JOYBALLMOTION */ + Uint8 which; /**< The joystick device index */ + Uint8 ball; /**< The joystick trackball index */ + int xrel; /**< The relative motion in the X direction */ + int yrel; /**< The relative motion in the Y direction */ } SDL_JoyBallEvent; -/* Joystick hat position change event structure */ -typedef struct SDL_JoyHatEvent { - Uint8 type; /* SDL_JOYHATMOTION */ - Uint8 which; /* The joystick device index */ - Uint8 hat; /* The joystick hat index */ - Uint8 value; /* The hat position value: - SDL_HAT_LEFTUP SDL_HAT_UP SDL_HAT_RIGHTUP - SDL_HAT_LEFT SDL_HAT_CENTERED SDL_HAT_RIGHT - SDL_HAT_LEFTDOWN SDL_HAT_DOWN SDL_HAT_RIGHTDOWN - Note that zero means the POV is centered. - */ +/** + * \struct SDL_JoyHatEvent + * + * \brief Joystick hat position change event structure + */ +typedef struct SDL_JoyHatEvent +{ + Uint8 type; /**< SDL_JOYHATMOTION */ + Uint8 which; /**< The joystick device index */ + Uint8 hat; /**< The joystick hat index */ + Uint8 value; /**< The hat position value: + SDL_HAT_LEFTUP SDL_HAT_UP SDL_HAT_RIGHTUP + SDL_HAT_LEFT SDL_HAT_CENTERED SDL_HAT_RIGHT + SDL_HAT_LEFTDOWN SDL_HAT_DOWN SDL_HAT_RIGHTDOWN + Note that zero means the POV is centered. + */ } SDL_JoyHatEvent; -/* Joystick button event structure */ -typedef struct SDL_JoyButtonEvent { - Uint8 type; /* SDL_JOYBUTTONDOWN or SDL_JOYBUTTONUP */ - Uint8 which; /* The joystick device index */ - Uint8 button; /* The joystick button index */ - Uint8 state; /* SDL_PRESSED or SDL_RELEASED */ +/** + * \struct SDL_JoyButtonEvent + * + * \brief Joystick button event structure + */ +typedef struct SDL_JoyButtonEvent +{ + Uint8 type; /**< SDL_JOYBUTTONDOWN or SDL_JOYBUTTONUP */ + Uint8 which; /**< The joystick device index */ + Uint8 button; /**< The joystick button index */ + Uint8 state; /**< SDL_PRESSED or SDL_RELEASED */ } SDL_JoyButtonEvent; -/* The "window resized" event - When you get this event, you are responsible for setting a new video - mode with the new width and height. +/** + * \struct SDL_QuitEvent + * + * \brief The "quit requested" event */ -typedef struct SDL_ResizeEvent { - Uint8 type; /* SDL_VIDEORESIZE */ - int w; /* New width */ - int h; /* New height */ -} SDL_ResizeEvent; - -/* The "screen redraw" event */ -typedef struct SDL_ExposeEvent { - Uint8 type; /* SDL_VIDEOEXPOSE */ -} SDL_ExposeEvent; - -/* The "quit requested" event */ -typedef struct SDL_QuitEvent { - Uint8 type; /* SDL_QUIT */ +typedef struct SDL_QuitEvent +{ + Uint8 type; /**< SDL_QUIT */ } SDL_QuitEvent; -/* A user-defined event type */ -typedef struct SDL_UserEvent { - Uint8 type; /* SDL_USEREVENT through SDL_NUMEVENTS-1 */ - int code; /* User defined event code */ - void *data1; /* User defined data pointer */ - void *data2; /* User defined data pointer */ +/** + * \struct SDL_UserEvent + * + * \brief A user-defined event type + */ +typedef struct SDL_UserEvent +{ + Uint8 type; /**< SDL_USEREVENT through SDL_NUMEVENTS-1 */ + int code; /**< User defined event code */ + void *data1; /**< User defined data pointer */ + void *data2; /**< User defined data pointer */ } SDL_UserEvent; -/* If you want to use this event, you should include SDL_syswm.h */ +/** + * \struct SDL_SysWMEvent + * + * \brief A video driver dependent system event + * + * \note If you want to use this event, you should include SDL_syswm.h + */ struct SDL_SysWMmsg; typedef struct SDL_SysWMmsg SDL_SysWMmsg; -typedef struct SDL_SysWMEvent { - Uint8 type; - SDL_SysWMmsg *msg; +typedef struct SDL_SysWMEvent +{ + Uint8 type; /**< SDL_SYSWMEVENT */ + SDL_SysWMmsg *msg; /**< driver dependent data, defined in SDL_syswm.h */ } SDL_SysWMEvent; -/* General event structure */ -typedef union SDL_Event { - Uint8 type; - SDL_ActiveEvent active; - SDL_KeyboardEvent key; - SDL_MouseMotionEvent motion; - SDL_MouseButtonEvent button; - SDL_JoyAxisEvent jaxis; - SDL_JoyBallEvent jball; - SDL_JoyHatEvent jhat; - SDL_JoyButtonEvent jbutton; - SDL_ResizeEvent resize; - SDL_ExposeEvent expose; - SDL_QuitEvent quit; - SDL_UserEvent user; - SDL_SysWMEvent syswm; +/* Typedefs for backwards compatibility */ +typedef struct SDL_ActiveEvent +{ + Uint8 type; + Uint8 gain; + Uint8 state; +} SDL_ActiveEvent; +typedef struct SDL_ResizeEvent +{ + Uint8 type; + int w; + int h; +} SDL_ResizeEvent; + +/** + * \union SDL_Event + * + * \brief General event structure + */ +typedef union SDL_Event +{ + Uint8 type; /**< Event type, shared with all events */ + SDL_WindowEvent window; /**< Window event data */ + SDL_KeyboardEvent key; /**< Keyboard event data */ + SDL_TextInputEvent text; /**< Text input event data */ + SDL_MouseMotionEvent motion; /**< Mouse motion event data */ + SDL_MouseButtonEvent button; /**< Mouse button event data */ + SDL_MouseWheelEvent wheel; /**< Mouse wheel event data */ + SDL_JoyAxisEvent jaxis; /**< Joystick axis event data */ + SDL_JoyBallEvent jball; /**< Joystick ball event data */ + SDL_JoyHatEvent jhat; /**< Joystick hat event data */ + SDL_JoyButtonEvent jbutton; /**< Joystick button event data */ + SDL_QuitEvent quit; /**< Quit request event data */ + SDL_UserEvent user; /**< Custom event data */ + SDL_SysWMEvent syswm; /**< System dependent window event data */ + + /* Temporarily here for backwards compatibility */ + SDL_ActiveEvent active; + SDL_ResizeEvent resize; } SDL_Event; @@ -255,32 +361,38 @@ extern DECLSPEC void SDLCALL SDL_PumpEvents(void); This function returns the number of events actually stored, or -1 if there was an error. This function is thread-safe. */ -typedef enum { - SDL_ADDEVENT, - SDL_PEEKEVENT, - SDL_GETEVENT +typedef enum +{ + SDL_ADDEVENT, + SDL_PEEKEVENT, + SDL_GETEVENT } SDL_eventaction; /* */ -extern DECLSPEC int SDLCALL SDL_PeepEvents(SDL_Event *events, int numevents, - SDL_eventaction action, Uint32 mask); +extern DECLSPEC int SDLCALL SDL_PeepEvents(SDL_Event * events, int numevents, + SDL_eventaction action, + Uint32 mask); + +/* Checks to see if certain event types are in the event queue. + */ +extern DECLSPEC SDL_bool SDLCALL SDL_HasEvent(Uint32 mask); /* Polls for currently pending events, and returns 1 if there are any pending events, or 0 if there are none available. If 'event' is not NULL, the next event is removed from the queue and stored in that area. */ -extern DECLSPEC int SDLCALL SDL_PollEvent(SDL_Event *event); +extern DECLSPEC int SDLCALL SDL_PollEvent(SDL_Event * event); /* Waits indefinitely for the next available event, returning 1, or 0 if there was an error while waiting for events. If 'event' is not NULL, the next event is removed from the queue and stored in that area. */ -extern DECLSPEC int SDLCALL SDL_WaitEvent(SDL_Event *event); +extern DECLSPEC int SDLCALL SDL_WaitEvent(SDL_Event * event); /* Add an event to the event queue. - This function returns 0 on success, or -1 if the event queue was full - or there was some other error. + This function returns 1 on success, 0 if the event was filtered, + or -1 if the event queue was full or there was some other error. */ -extern DECLSPEC int SDLCALL SDL_PushEvent(SDL_Event *event); +extern DECLSPEC int SDLCALL SDL_PushEvent(SDL_Event * event); /* This function sets up a filter to process all events before they @@ -288,7 +400,7 @@ extern DECLSPEC int SDLCALL SDL_PushEvent(SDL_Event *event); The filter is protypted as: */ -typedef int (SDLCALL *SDL_EventFilter)(const SDL_Event *event); +typedef int (SDLCALL * SDL_EventFilter) (void *userdata, SDL_Event * event); /* If the filter returns 1, then the event will be added to the internal queue. If it returns 0, then the event will be dropped from the queue, but the @@ -305,13 +417,22 @@ typedef int (SDLCALL *SDL_EventFilter)(const SDL_Event *event); If the quit event is generated by an interrupt signal, it will bypass the internal queue and be delivered to the application at the next event poll. */ -extern DECLSPEC void SDLCALL SDL_SetEventFilter(SDL_EventFilter filter); +extern DECLSPEC void SDLCALL SDL_SetEventFilter(SDL_EventFilter filter, + void *userdata); /* Return the current event filter - can be used to "chain" filters. - If there is no event filter set, this function returns NULL. + If there is no event filter set, this function returns SDL_FALSE. */ -extern DECLSPEC SDL_EventFilter SDLCALL SDL_GetEventFilter(void); +extern DECLSPEC SDL_bool SDLCALL SDL_GetEventFilter(SDL_EventFilter * filter, + void **userdata); + +/* + Run the filter function on the current event queue, removing any + events for which the filter returns 0. +*/ +extern DECLSPEC void SDLCALL SDL_FilterEvents(SDL_EventFilter filter, + void *userdata); /* This function allows you to set the state of processing certain events. @@ -330,8 +451,12 @@ extern DECLSPEC Uint8 SDLCALL SDL_EventState(Uint8 type, int state); /* Ends C function definitions when using C++ */ #ifdef __cplusplus +/* *INDENT-OFF* */ } +/* *INDENT-ON* */ #endif #include "close_code.h" #endif /* _SDL_events_h */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/include/SDL_joystick.h b/include/SDL_joystick.h index e4f72f1a4..f33637ac4 100644 --- a/include/SDL_joystick.h +++ b/include/SDL_joystick.h @@ -20,7 +20,11 @@ slouken@libsdl.org */ -/* Include file for SDL joystick event handling */ +/** + * \file SDL_joystick.h + * + * Include file for SDL joystick event handling + */ #ifndef _SDL_joystick_h #define _SDL_joystick_h @@ -31,7 +35,9 @@ #include "begin_code.h" /* Set up for C function definitions, even when using C++ */ #ifdef __cplusplus +/* *INDENT-OFF* */ extern "C" { +/* *INDENT-ON* */ #endif /* In order to use these functions, SDL_Init() must have been called @@ -55,7 +61,7 @@ extern DECLSPEC int SDLCALL SDL_NumJoysticks(void); * This can be called before any joysticks are opened. * If no name can be found, this function returns NULL. */ -extern DECLSPEC const char * SDLCALL SDL_JoystickName(int device_index); +extern DECLSPEC const char *SDLCALL SDL_JoystickName(int device_index); /* * Open a joystick for use - the index passed as an argument refers to @@ -64,7 +70,7 @@ extern DECLSPEC const char * SDLCALL SDL_JoystickName(int device_index); * * This function returns a joystick identifier, or NULL if an error occurred. */ -extern DECLSPEC SDL_Joystick * SDLCALL SDL_JoystickOpen(int device_index); +extern DECLSPEC SDL_Joystick *SDLCALL SDL_JoystickOpen(int device_index); /* * Returns 1 if the joystick has been opened, or 0 if it has not. @@ -74,29 +80,29 @@ extern DECLSPEC int SDLCALL SDL_JoystickOpened(int device_index); /* * Get the device index of an opened joystick. */ -extern DECLSPEC int SDLCALL SDL_JoystickIndex(SDL_Joystick *joystick); +extern DECLSPEC int SDLCALL SDL_JoystickIndex(SDL_Joystick * joystick); /* * Get the number of general axis controls on a joystick */ -extern DECLSPEC int SDLCALL SDL_JoystickNumAxes(SDL_Joystick *joystick); +extern DECLSPEC int SDLCALL SDL_JoystickNumAxes(SDL_Joystick * joystick); /* * Get the number of trackballs on a joystick * Joystick trackballs have only relative motion events associated * with them and their state cannot be polled. */ -extern DECLSPEC int SDLCALL SDL_JoystickNumBalls(SDL_Joystick *joystick); +extern DECLSPEC int SDLCALL SDL_JoystickNumBalls(SDL_Joystick * joystick); /* * Get the number of POV hats on a joystick */ -extern DECLSPEC int SDLCALL SDL_JoystickNumHats(SDL_Joystick *joystick); +extern DECLSPEC int SDLCALL SDL_JoystickNumHats(SDL_Joystick * joystick); /* * Get the number of buttons on a joystick */ -extern DECLSPEC int SDLCALL SDL_JoystickNumButtons(SDL_Joystick *joystick); +extern DECLSPEC int SDLCALL SDL_JoystickNumButtons(SDL_Joystick * joystick); /* * Update the current state of the open joysticks. @@ -119,7 +125,8 @@ extern DECLSPEC int SDLCALL SDL_JoystickEventState(int state); * The state is a value ranging from -32768 to 32767. * The axis indices start at index 0. */ -extern DECLSPEC Sint16 SDLCALL SDL_JoystickGetAxis(SDL_Joystick *joystick, int axis); +extern DECLSPEC Sint16 SDLCALL SDL_JoystickGetAxis(SDL_Joystick * joystick, + int axis); /* * Get the current state of a POV hat on a joystick @@ -137,31 +144,38 @@ extern DECLSPEC Sint16 SDLCALL SDL_JoystickGetAxis(SDL_Joystick *joystick, int a /* * The hat indices start at index 0. */ -extern DECLSPEC Uint8 SDLCALL SDL_JoystickGetHat(SDL_Joystick *joystick, int hat); +extern DECLSPEC Uint8 SDLCALL SDL_JoystickGetHat(SDL_Joystick * joystick, + int hat); /* * Get the ball axis change since the last poll * This returns 0, or -1 if you passed it invalid parameters. * The ball indices start at index 0. */ -extern DECLSPEC int SDLCALL SDL_JoystickGetBall(SDL_Joystick *joystick, int ball, int *dx, int *dy); +extern DECLSPEC int SDLCALL SDL_JoystickGetBall(SDL_Joystick * joystick, + int ball, int *dx, int *dy); /* * Get the current state of a button on a joystick * The button indices start at index 0. */ -extern DECLSPEC Uint8 SDLCALL SDL_JoystickGetButton(SDL_Joystick *joystick, int button); +extern DECLSPEC Uint8 SDLCALL SDL_JoystickGetButton(SDL_Joystick * joystick, + int button); /* * Close a joystick previously opened with SDL_JoystickOpen() */ -extern DECLSPEC void SDLCALL SDL_JoystickClose(SDL_Joystick *joystick); +extern DECLSPEC void SDLCALL SDL_JoystickClose(SDL_Joystick * joystick); /* Ends C function definitions when using C++ */ #ifdef __cplusplus +/* *INDENT-OFF* */ } +/* *INDENT-ON* */ #endif #include "close_code.h" #endif /* _SDL_joystick_h */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/include/SDL_keyboard.h b/include/SDL_keyboard.h index 1ad7dcaa4..9652dfb4f 100644 --- a/include/SDL_keyboard.h +++ b/include/SDL_keyboard.h @@ -20,7 +20,11 @@ slouken@libsdl.org */ -/* Include file for SDL keyboard event handling */ +/** + * \file SDL_keyboard.h + * + * Include file for SDL keyboard event handling + */ #ifndef _SDL_keyboard_h #define _SDL_keyboard_h @@ -32,90 +36,133 @@ #include "begin_code.h" /* Set up for C function definitions, even when using C++ */ #ifdef __cplusplus +/* *INDENT-OFF* */ extern "C" { +/* *INDENT-ON* */ #endif -/* Keysym structure - - The scancode is hardware dependent, and should not be used by general - applications. If no hardware scancode is available, it will be 0. - - - The 'unicode' translated character is only available when character - translation is enabled by the SDL_EnableUNICODE() API. If non-zero, - this is a UNICODE character corresponding to the keypress. If the - high 9 bits of the character are 0, then this maps to the equivalent - ASCII character: - char ch; - if ( (keysym.unicode & 0xFF80) == 0 ) { - ch = keysym.unicode & 0x7F; - } else { - An international character.. - } +/** + * \struct SDL_keysym + * + * \brief The SDL keysym structure, used in key events. */ -typedef struct SDL_keysym { - Uint8 scancode; /* hardware specific scancode */ - SDLKey sym; /* SDL virtual keysym */ - SDLMod mod; /* current key modifiers */ - Uint16 unicode; /* translated character */ +typedef struct SDL_keysym +{ + Uint8 scancode; /**< keyboard specific scancode */ + Uint8 padding[3]; /**< alignment padding */ + Uint16 sym; /**< SDL virtual keysym */ + Uint16 mod; /**< current key modifiers */ + Uint32 unicode; /**< OBSOLETE, use SDL_TextInputEvent instead */ } SDL_keysym; -/* This is the mask which refers to all hotkey bindings */ -#define SDL_ALL_HOTKEYS 0xFFFFFFFF - /* Function prototypes */ -/* - * Enable/Disable UNICODE translation of keyboard input. - * This translation has some overhead, so translation defaults off. - * If 'enable' is 1, translation is enabled. - * If 'enable' is 0, translation is disabled. - * If 'enable' is -1, the translation state is not changed. - * It returns the previous state of keyboard translation. + +/** + * \fn int SDL_GetNumKeyboards(void) + * + * \brief Get the number of keyboard input devices available. + * + * \sa SDL_SelectKeyboard() + */ +extern DECLSPEC int SDLCALL SDL_GetNumKeyboards(void); + +/** + * \fn int SDL_SelectKeyboard(int index) + * + * \brief Set the index of the currently selected keyboard. + * + * \return The index of the previously selected keyboard. + * + * \note You can query the currently selected keyboard by passing an index of -1. + * + * \sa SDL_GetNumKeyboards() + */ +extern DECLSPEC int SDLCALL SDL_SelectKeyboard(int index); + +/** + * \fn int SDL_EnableUNICODE(int enable) + * + * \brief Enable/Disable UNICODE translation of keyboard input. + * + * \param enable 1 to enable translation, 0 to disable translation, -1 to query translation + * + * \return The previous state of keyboard translation + * + * \note This translation has some overhead, so translation defaults off. */ extern DECLSPEC int SDLCALL SDL_EnableUNICODE(int enable); -/* - * Enable/Disable keyboard repeat. Keyboard repeat defaults to off. - * 'delay' is the initial delay in ms between the time when a key is - * pressed, and keyboard repeat begins. - * 'interval' is the time in ms between keyboard repeat events. +/** + * \fn int SDL_EnableKeyRepeat(int delay, int interval) + * + * \brief Enable keyboard repeat for the selected keyboard. + * + * \param delay The initial delay in milliseconds between the time when a + * key is pressed and keyboard repeat begins. Setting a delay + * of 0 will disable keyboard repeat. + * \param interval The time in milliseconds between keyboard repeat events. + * + * \return 0 on success, or -1 if there was an error. + * + * \note Keyboard repeat defaults to off. */ #define SDL_DEFAULT_REPEAT_DELAY 500 #define SDL_DEFAULT_REPEAT_INTERVAL 30 -/* - * If 'delay' is set to 0, keyboard repeat is disabled. + /**/ + extern DECLSPEC int SDLCALL SDL_EnableKeyRepeat(int delay, int interval); + +/** + * \fn void SDL_GetKeyRepeat(int *delay, int *interval) + * + * \brief Get the current keyboard repeat setting for the selected keyboard. */ -extern DECLSPEC int SDLCALL SDL_EnableKeyRepeat(int delay, int interval); extern DECLSPEC void SDLCALL SDL_GetKeyRepeat(int *delay, int *interval); -/* - * Get a snapshot of the current state of the keyboard. - * Returns an array of keystates, indexed by the SDLK_* syms. - * Used: +/** + * \fn Uint8 *SDL_GetKeyState(int *numkeys) + * + * \brief Get a snapshot of the current state of the selected keyboard. + * + * \return An array of keystates, indexed by the SDLK_* syms. + * + * Example: * Uint8 *keystate = SDL_GetKeyState(NULL); * if ( keystate[SDLK_RETURN] ) ... is pressed. */ -extern DECLSPEC Uint8 * SDLCALL SDL_GetKeyState(int *numkeys); +extern DECLSPEC Uint8 *SDLCALL SDL_GetKeyState(int *numkeys); -/* - * Get the current key modifier state +/** + * \fn SDLMod SDL_GetModState(void) + * + * \brief Get the current key modifier state for the selected keyboard. */ extern DECLSPEC SDLMod SDLCALL SDL_GetModState(void); -/* - * Set the current key modifier state - * This does not change the keyboard state, only the key modifier flags. +/** + * \fn void SDL_SetModState(SDLMod modstate) + * + * \brief Set the current key modifier state for the selected keyboard. + * + * \note This does not change the keyboard state, only the key modifier flags. */ extern DECLSPEC void SDLCALL SDL_SetModState(SDLMod modstate); -/* - * Get the name of an SDL virtual keysym +/** + * \fn const char *SDL_GetKeyName(SDLKey key) + * + * \brief Get the name of an SDL virtual keysym */ -extern DECLSPEC char * SDLCALL SDL_GetKeyName(SDLKey key); +extern DECLSPEC const char *SDLCALL SDL_GetKeyName(SDLKey key); /* Ends C function definitions when using C++ */ #ifdef __cplusplus +/* *INDENT-OFF* */ } +/* *INDENT-ON* */ #endif #include "close_code.h" #endif /* _SDL_keyboard_h */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/include/SDL_keysym.h b/include/SDL_keysym.h index ff44a035f..35554db17 100644 --- a/include/SDL_keysym.h +++ b/include/SDL_keysym.h @@ -20,287 +20,203 @@ slouken@libsdl.org */ +/** + * \file SDL_keysym.h + */ + #ifndef _SDL_keysym_h #define _SDL_keysym_h -/* What we really want is a mapping of every raw key on the keyboard. - To support international keyboards, we use the range 0xA1 - 0xFF - as international virtual keycodes. We'll follow in the footsteps of X11... - The names of the keys +/** + * \enum SDLKey + * + * \brief The SDL virtual key representation + * + * The SDLKey represents the unmodified character printed on the key + * for the current keyboard layout. The first 255 characters are used + * unchanged from Latin-1, e.g. a key with 'a' on it will have the value "a". + * The rest of the keys are named below, and fall into the range above 255. */ - -typedef enum { - /* The keyboard syms have been cleverly chosen to map to ASCII */ - SDLK_UNKNOWN = 0, - SDLK_FIRST = 0, - SDLK_BACKSPACE = 8, - SDLK_TAB = 9, - SDLK_CLEAR = 12, - SDLK_RETURN = 13, - SDLK_PAUSE = 19, - SDLK_ESCAPE = 27, - SDLK_SPACE = 32, - SDLK_EXCLAIM = 33, - SDLK_QUOTEDBL = 34, - SDLK_HASH = 35, - SDLK_DOLLAR = 36, - SDLK_AMPERSAND = 38, - SDLK_QUOTE = 39, - SDLK_LEFTPAREN = 40, - SDLK_RIGHTPAREN = 41, - SDLK_ASTERISK = 42, - SDLK_PLUS = 43, - SDLK_COMMA = 44, - SDLK_MINUS = 45, - SDLK_PERIOD = 46, - SDLK_SLASH = 47, - SDLK_0 = 48, - SDLK_1 = 49, - SDLK_2 = 50, - SDLK_3 = 51, - SDLK_4 = 52, - SDLK_5 = 53, - SDLK_6 = 54, - SDLK_7 = 55, - SDLK_8 = 56, - SDLK_9 = 57, - SDLK_COLON = 58, - SDLK_SEMICOLON = 59, - SDLK_LESS = 60, - SDLK_EQUALS = 61, - SDLK_GREATER = 62, - SDLK_QUESTION = 63, - SDLK_AT = 64, - /* - Skip uppercase letters - */ - SDLK_LEFTBRACKET = 91, - SDLK_BACKSLASH = 92, - SDLK_RIGHTBRACKET = 93, - SDLK_CARET = 94, - SDLK_UNDERSCORE = 95, - SDLK_BACKQUOTE = 96, - SDLK_a = 97, - SDLK_b = 98, - SDLK_c = 99, - SDLK_d = 100, - SDLK_e = 101, - SDLK_f = 102, - SDLK_g = 103, - SDLK_h = 104, - SDLK_i = 105, - SDLK_j = 106, - SDLK_k = 107, - SDLK_l = 108, - SDLK_m = 109, - SDLK_n = 110, - SDLK_o = 111, - SDLK_p = 112, - SDLK_q = 113, - SDLK_r = 114, - SDLK_s = 115, - SDLK_t = 116, - SDLK_u = 117, - SDLK_v = 118, - SDLK_w = 119, - SDLK_x = 120, - SDLK_y = 121, - SDLK_z = 122, - SDLK_DELETE = 127, - /* End of ASCII mapped keysyms */ - - /* International keyboard syms */ - SDLK_WORLD_0 = 160, /* 0xA0 */ - SDLK_WORLD_1 = 161, - SDLK_WORLD_2 = 162, - SDLK_WORLD_3 = 163, - SDLK_WORLD_4 = 164, - SDLK_WORLD_5 = 165, - SDLK_WORLD_6 = 166, - SDLK_WORLD_7 = 167, - SDLK_WORLD_8 = 168, - SDLK_WORLD_9 = 169, - SDLK_WORLD_10 = 170, - SDLK_WORLD_11 = 171, - SDLK_WORLD_12 = 172, - SDLK_WORLD_13 = 173, - SDLK_WORLD_14 = 174, - SDLK_WORLD_15 = 175, - SDLK_WORLD_16 = 176, - SDLK_WORLD_17 = 177, - SDLK_WORLD_18 = 178, - SDLK_WORLD_19 = 179, - SDLK_WORLD_20 = 180, - SDLK_WORLD_21 = 181, - SDLK_WORLD_22 = 182, - SDLK_WORLD_23 = 183, - SDLK_WORLD_24 = 184, - SDLK_WORLD_25 = 185, - SDLK_WORLD_26 = 186, - SDLK_WORLD_27 = 187, - SDLK_WORLD_28 = 188, - SDLK_WORLD_29 = 189, - SDLK_WORLD_30 = 190, - SDLK_WORLD_31 = 191, - SDLK_WORLD_32 = 192, - SDLK_WORLD_33 = 193, - SDLK_WORLD_34 = 194, - SDLK_WORLD_35 = 195, - SDLK_WORLD_36 = 196, - SDLK_WORLD_37 = 197, - SDLK_WORLD_38 = 198, - SDLK_WORLD_39 = 199, - SDLK_WORLD_40 = 200, - SDLK_WORLD_41 = 201, - SDLK_WORLD_42 = 202, - SDLK_WORLD_43 = 203, - SDLK_WORLD_44 = 204, - SDLK_WORLD_45 = 205, - SDLK_WORLD_46 = 206, - SDLK_WORLD_47 = 207, - SDLK_WORLD_48 = 208, - SDLK_WORLD_49 = 209, - SDLK_WORLD_50 = 210, - SDLK_WORLD_51 = 211, - SDLK_WORLD_52 = 212, - SDLK_WORLD_53 = 213, - SDLK_WORLD_54 = 214, - SDLK_WORLD_55 = 215, - SDLK_WORLD_56 = 216, - SDLK_WORLD_57 = 217, - SDLK_WORLD_58 = 218, - SDLK_WORLD_59 = 219, - SDLK_WORLD_60 = 220, - SDLK_WORLD_61 = 221, - SDLK_WORLD_62 = 222, - SDLK_WORLD_63 = 223, - SDLK_WORLD_64 = 224, - SDLK_WORLD_65 = 225, - SDLK_WORLD_66 = 226, - SDLK_WORLD_67 = 227, - SDLK_WORLD_68 = 228, - SDLK_WORLD_69 = 229, - SDLK_WORLD_70 = 230, - SDLK_WORLD_71 = 231, - SDLK_WORLD_72 = 232, - SDLK_WORLD_73 = 233, - SDLK_WORLD_74 = 234, - SDLK_WORLD_75 = 235, - SDLK_WORLD_76 = 236, - SDLK_WORLD_77 = 237, - SDLK_WORLD_78 = 238, - SDLK_WORLD_79 = 239, - SDLK_WORLD_80 = 240, - SDLK_WORLD_81 = 241, - SDLK_WORLD_82 = 242, - SDLK_WORLD_83 = 243, - SDLK_WORLD_84 = 244, - SDLK_WORLD_85 = 245, - SDLK_WORLD_86 = 246, - SDLK_WORLD_87 = 247, - SDLK_WORLD_88 = 248, - SDLK_WORLD_89 = 249, - SDLK_WORLD_90 = 250, - SDLK_WORLD_91 = 251, - SDLK_WORLD_92 = 252, - SDLK_WORLD_93 = 253, - SDLK_WORLD_94 = 254, - SDLK_WORLD_95 = 255, /* 0xFF */ - - /* Numeric keypad */ - SDLK_KP0 = 256, - SDLK_KP1 = 257, - SDLK_KP2 = 258, - SDLK_KP3 = 259, - SDLK_KP4 = 260, - SDLK_KP5 = 261, - SDLK_KP6 = 262, - SDLK_KP7 = 263, - SDLK_KP8 = 264, - SDLK_KP9 = 265, - SDLK_KP_PERIOD = 266, - SDLK_KP_DIVIDE = 267, - SDLK_KP_MULTIPLY = 268, - SDLK_KP_MINUS = 269, - SDLK_KP_PLUS = 270, - SDLK_KP_ENTER = 271, - SDLK_KP_EQUALS = 272, - - /* Arrows + Home/End pad */ - SDLK_UP = 273, - SDLK_DOWN = 274, - SDLK_RIGHT = 275, - SDLK_LEFT = 276, - SDLK_INSERT = 277, - SDLK_HOME = 278, - SDLK_END = 279, - SDLK_PAGEUP = 280, - SDLK_PAGEDOWN = 281, - - /* Function keys */ - SDLK_F1 = 282, - SDLK_F2 = 283, - SDLK_F3 = 284, - SDLK_F4 = 285, - SDLK_F5 = 286, - SDLK_F6 = 287, - SDLK_F7 = 288, - SDLK_F8 = 289, - SDLK_F9 = 290, - SDLK_F10 = 291, - SDLK_F11 = 292, - SDLK_F12 = 293, - SDLK_F13 = 294, - SDLK_F14 = 295, - SDLK_F15 = 296, - - /* Key state modifier keys */ - SDLK_NUMLOCK = 300, - SDLK_CAPSLOCK = 301, - SDLK_SCROLLOCK = 302, - SDLK_RSHIFT = 303, - SDLK_LSHIFT = 304, - SDLK_RCTRL = 305, - SDLK_LCTRL = 306, - SDLK_RALT = 307, - SDLK_LALT = 308, - SDLK_RMETA = 309, - SDLK_LMETA = 310, - SDLK_LSUPER = 311, /* Left "Windows" key */ - SDLK_RSUPER = 312, /* Right "Windows" key */ - SDLK_MODE = 313, /* "Alt Gr" key */ - SDLK_COMPOSE = 314, /* Multi-key compose key */ - - /* Miscellaneous function keys */ - SDLK_HELP = 315, - SDLK_PRINT = 316, - SDLK_SYSREQ = 317, - SDLK_BREAK = 318, - SDLK_MENU = 319, - SDLK_POWER = 320, /* Power Macintosh power key */ - SDLK_EURO = 321, /* Some european keyboards */ - SDLK_UNDO = 322, /* Atari keyboard has Undo */ - - /* Add any other keys here */ - - SDLK_LAST +typedef enum +{ + /* The keyboard syms have been cleverly chosen to map to ASCII */ + SDLK_UNKNOWN = 0, + SDLK_FIRST = 0, + SDLK_BACKSPACE = 8, + SDLK_TAB = 9, + SDLK_CLEAR = 12, + SDLK_RETURN = 13, + SDLK_PAUSE = 19, + SDLK_ESCAPE = 27, + SDLK_SPACE = 32, + SDLK_EXCLAIM = 33, + SDLK_QUOTEDBL = 34, + SDLK_HASH = 35, + SDLK_DOLLAR = 36, + SDLK_AMPERSAND = 38, + SDLK_QUOTE = 39, + SDLK_LEFTPAREN = 40, + SDLK_RIGHTPAREN = 41, + SDLK_ASTERISK = 42, + SDLK_PLUS = 43, + SDLK_COMMA = 44, + SDLK_MINUS = 45, + SDLK_PERIOD = 46, + SDLK_SLASH = 47, + SDLK_0 = 48, + SDLK_1 = 49, + SDLK_2 = 50, + SDLK_3 = 51, + SDLK_4 = 52, + SDLK_5 = 53, + SDLK_6 = 54, + SDLK_7 = 55, + SDLK_8 = 56, + SDLK_9 = 57, + SDLK_COLON = 58, + SDLK_SEMICOLON = 59, + SDLK_LESS = 60, + SDLK_EQUALS = 61, + SDLK_GREATER = 62, + SDLK_QUESTION = 63, + SDLK_AT = 64, + /* + Skip uppercase letters + */ + SDLK_LEFTBRACKET = 91, + SDLK_BACKSLASH = 92, + SDLK_RIGHTBRACKET = 93, + SDLK_CARET = 94, + SDLK_UNDERSCORE = 95, + SDLK_BACKQUOTE = 96, + SDLK_a = 97, + SDLK_b = 98, + SDLK_c = 99, + SDLK_d = 100, + SDLK_e = 101, + SDLK_f = 102, + SDLK_g = 103, + SDLK_h = 104, + SDLK_i = 105, + SDLK_j = 106, + SDLK_k = 107, + SDLK_l = 108, + SDLK_m = 109, + SDLK_n = 110, + SDLK_o = 111, + SDLK_p = 112, + SDLK_q = 113, + SDLK_r = 114, + SDLK_s = 115, + SDLK_t = 116, + SDLK_u = 117, + SDLK_v = 118, + SDLK_w = 119, + SDLK_x = 120, + SDLK_y = 121, + SDLK_z = 122, + SDLK_DELETE = 127, + /* End of ASCII mapped keysyms */ + + /* Numeric keypad */ + SDLK_KP0 = 256, + SDLK_KP1 = 257, + SDLK_KP2 = 258, + SDLK_KP3 = 259, + SDLK_KP4 = 260, + SDLK_KP5 = 261, + SDLK_KP6 = 262, + SDLK_KP7 = 263, + SDLK_KP8 = 264, + SDLK_KP9 = 265, + SDLK_KP_PERIOD = 266, + SDLK_KP_DIVIDE = 267, + SDLK_KP_MULTIPLY = 268, + SDLK_KP_MINUS = 269, + SDLK_KP_PLUS = 270, + SDLK_KP_ENTER = 271, + SDLK_KP_EQUALS = 272, + + /* Arrows + Home/End pad */ + SDLK_UP = 273, + SDLK_DOWN = 274, + SDLK_RIGHT = 275, + SDLK_LEFT = 276, + SDLK_INSERT = 277, + SDLK_HOME = 278, + SDLK_END = 279, + SDLK_PAGEUP = 280, + SDLK_PAGEDOWN = 281, + + /* Function keys */ + SDLK_F1 = 282, + SDLK_F2 = 283, + SDLK_F3 = 284, + SDLK_F4 = 285, + SDLK_F5 = 286, + SDLK_F6 = 287, + SDLK_F7 = 288, + SDLK_F8 = 289, + SDLK_F9 = 290, + SDLK_F10 = 291, + SDLK_F11 = 292, + SDLK_F12 = 293, + SDLK_F13 = 294, + SDLK_F14 = 295, + SDLK_F15 = 296, + + /* Key state modifier keys */ + SDLK_NUMLOCK = 300, + SDLK_CAPSLOCK = 301, + SDLK_SCROLLOCK = 302, + SDLK_RSHIFT = 303, + SDLK_LSHIFT = 304, + SDLK_RCTRL = 305, + SDLK_LCTRL = 306, + SDLK_RALT = 307, + SDLK_LALT = 308, + SDLK_RMETA = 309, + SDLK_LMETA = 310, + SDLK_LSUPER = 311, /**< Left "Windows" key */ + SDLK_RSUPER = 312, /**< Right "Windows" key */ + SDLK_MODE = 313, /**< "Alt Gr" key */ + SDLK_COMPOSE = 314, /**< Multi-key compose key */ + + /* Miscellaneous function keys */ + SDLK_HELP = 315, + SDLK_PRINT = 316, + SDLK_SYSREQ = 317, + SDLK_BREAK = 318, + SDLK_MENU = 319, + SDLK_POWER = 320, /**< Power Macintosh power key */ + SDLK_EURO = 321, /**< Some european keyboards */ + SDLK_UNDO = 322, /**< Atari keyboard has Undo */ + + /* Add any other keys here */ + + SDLK_LAST } SDLKey; -/* Enumeration of valid key mods (possibly OR'd together) */ -typedef enum { - KMOD_NONE = 0x0000, - KMOD_LSHIFT= 0x0001, - KMOD_RSHIFT= 0x0002, - KMOD_LCTRL = 0x0040, - KMOD_RCTRL = 0x0080, - KMOD_LALT = 0x0100, - KMOD_RALT = 0x0200, - KMOD_LMETA = 0x0400, - KMOD_RMETA = 0x0800, - KMOD_NUM = 0x1000, - KMOD_CAPS = 0x2000, - KMOD_MODE = 0x4000, - KMOD_RESERVED = 0x8000 +/** + * \enum SDLMod + * + * \brief Enumeration of valid key mods (possibly OR'd together) + */ +typedef enum +{ + KMOD_NONE = 0x0000, + KMOD_LSHIFT = 0x0001, + KMOD_RSHIFT = 0x0002, + KMOD_LCTRL = 0x0040, + KMOD_RCTRL = 0x0080, + KMOD_LALT = 0x0100, + KMOD_RALT = 0x0200, + KMOD_LMETA = 0x0400, + KMOD_RMETA = 0x0800, + KMOD_NUM = 0x1000, + KMOD_CAPS = 0x2000, + KMOD_MODE = 0x4000, + KMOD_RESERVED = 0x8000 } SDLMod; #define KMOD_CTRL (KMOD_LCTRL|KMOD_RCTRL) diff --git a/include/SDL_loadso.h b/include/SDL_loadso.h index ce9644949..fbf566ce7 100644 --- a/include/SDL_loadso.h +++ b/include/SDL_loadso.h @@ -20,23 +20,24 @@ slouken@libsdl.org */ -/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ -/* System dependent library loading routines */ - -/* Some things to keep in mind: - - These functions only work on C function names. Other languages may - have name mangling and intrinsic language support that varies from - compiler to compiler. - - Make sure you declare your function pointers with the same calling - convention as the actual library function. Your code will crash - mysteriously if you do not do this. - - Avoid namespace collisions. If you load a symbol from the library, - it is not defined whether or not it goes into the global symbol - namespace for the application. If it does and it conflicts with - symbols in your code or other shared libraries, you will not get - the results you expect. :) -*/ - +/** + * \file SDL_loadso.h + * + * System dependent library loading routines + * + * Some things to keep in mind: + * - These functions only work on C function names. Other languages may + * have name mangling and intrinsic language support that varies from + * compiler to compiler. + * - Make sure you declare your function pointers with the same calling + * convention as the actual library function. Your code will crash + * mysteriously if you do not do this. + * - Avoid namespace collisions. If you load a symbol from the library, + * it is not defined whether or not it goes into the global symbol + * namespace for the application. If it does and it conflicts with + * symbols in your code or other shared libraries, you will not get + * the results you expect. :) + */ #ifndef _SDL_loadso_h #define _SDL_loadso_h @@ -47,28 +48,35 @@ #include "begin_code.h" /* Set up for C function definitions, even when using C++ */ #ifdef __cplusplus +/* *INDENT-OFF* */ extern "C" { +/* *INDENT-ON* */ #endif /* This function dynamically loads a shared object and returns a pointer * to the object handle (or NULL if there was an error). * The 'sofile' parameter is a system dependent name of the object file. */ -extern DECLSPEC void * SDLCALL SDL_LoadObject(const char *sofile); +extern DECLSPEC void *SDLCALL SDL_LoadObject(const char *sofile); /* Given an object handle, this function looks up the address of the * named function in the shared object and returns it. This address * is no longer valid after calling SDL_UnloadObject(). */ -extern DECLSPEC void * SDLCALL SDL_LoadFunction(void *handle, const char *name); +extern DECLSPEC void *SDLCALL SDL_LoadFunction(void *handle, + const char *name); /* Unload a shared object from memory */ extern DECLSPEC void SDLCALL SDL_UnloadObject(void *handle); /* Ends C function definitions when using C++ */ #ifdef __cplusplus +/* *INDENT-OFF* */ } +/* *INDENT-ON* */ #endif #include "close_code.h" #endif /* _SDL_loadso_h */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/include/SDL_main.h b/include/SDL_main.h index cf8b728dc..13b677d3a 100644 --- a/include/SDL_main.h +++ b/include/SDL_main.h @@ -58,17 +58,20 @@ extern C_LINKAGE int SDL_main(int argc, char *argv[]); #include "begin_code.h" #ifdef __cplusplus +/* *INDENT-OFF* */ extern "C" { +/* *INDENT-ON* */ #endif -/* This should be called from your WinMain() function, if any */ -extern DECLSPEC void SDLCALL SDL_SetModuleHandle(void *hInst); -/* This can also be called, but is no longer necessary */ -extern DECLSPEC int SDLCALL SDL_RegisterApp(char *name, Uint32 style, void *hInst); -/* This can also be called, but is no longer necessary (SDL_Quit calls it) */ +/* This can be called to set the application class at startup */ +extern DECLSPEC int SDLCALL SDL_RegisterApp(char *name, Uint32 style, + void *hInst); extern DECLSPEC void SDLCALL SDL_UnregisterApp(void); + #ifdef __cplusplus +/* *INDENT-OFF* */ } +/* *INDENT-ON* */ #endif #include "close_code.h" #endif @@ -78,7 +81,9 @@ extern DECLSPEC void SDLCALL SDL_UnregisterApp(void); #include "begin_code.h" #ifdef __cplusplus +/* *INDENT-OFF* */ extern "C" { +/* *INDENT-ON* */ #endif /* Forward declaration so we don't need to include QuickDraw.h */ @@ -88,7 +93,9 @@ struct QDGlobals; extern DECLSPEC void SDLCALL SDL_InitQuickDraw(struct QDGlobals *the_qd); #ifdef __cplusplus +/* *INDENT-OFF* */ } +/* *INDENT-ON* */ #endif #include "close_code.h" #endif @@ -96,3 +103,5 @@ extern DECLSPEC void SDLCALL SDL_InitQuickDraw(struct QDGlobals *the_qd); #endif /* Need to redefine main()? */ #endif /* _SDL_main_h */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/include/SDL_mouse.h b/include/SDL_mouse.h index c2364d859..5c7728a82 100644 --- a/include/SDL_mouse.h +++ b/include/SDL_mouse.h @@ -20,7 +20,11 @@ slouken@libsdl.org */ -/* Include file for SDL mouse event handling */ +/** + * \file SDL_mouse.h + * + * Include file for SDL mouse event handling + */ #ifndef _SDL_mouse_h #define _SDL_mouse_h @@ -32,43 +36,116 @@ #include "begin_code.h" /* Set up for C function definitions, even when using C++ */ #ifdef __cplusplus +/* *INDENT-OFF* */ extern "C" { +/* *INDENT-ON* */ #endif -typedef struct WMcursor WMcursor; /* Implementation dependent */ -typedef struct SDL_Cursor { - SDL_Rect area; /* The area of the mouse cursor */ - Sint16 hot_x, hot_y; /* The "tip" of the cursor */ - Uint8 *data; /* B/W cursor data */ - Uint8 *mask; /* B/W cursor mask */ - Uint8 *save[2]; /* Place to save cursor area */ - WMcursor *wm_cursor; /* Window-manager cursor */ -} SDL_Cursor; +typedef struct SDL_Cursor SDL_Cursor; /* Implementation dependent */ /* Function prototypes */ -/* - * Retrieve the current state of the mouse. + +/** + * \fn int SDL_GetNumMice(void) + * + * \brief Get the number of mouse input devices available. + * + * \sa SDL_SelectMouse() + */ +extern DECLSPEC int SDLCALL SDL_GetNumMice(void); + +/** + * \fn int SDL_SelectMouse(int index) + * + * \brief Set the index of the currently selected mouse. + * + * \return The index of the previously selected mouse. + * + * \note You can query the currently selected mouse by passing an index of -1. + * + * \sa SDL_GetNumMice() + */ +extern DECLSPEC int SDLCALL SDL_SelectMouse(int index); + +/** + * \fn SDL_WindowID SDL_GetMouseFocusWindow(void) + * + * \brief Get the window which currently has focus for the currently selected mouse. + */ +extern DECLSPEC SDL_WindowID SDLCALL SDL_GetMouseFocusWindow(void); + +/** + * \fn int SDL_SetRelativeMouseMode(SDL_bool enabled) + * + * \brief Set relative mouse mode for the currently selected mouse. + * + * \param enabled Whether or not to enable relative mode + * + * \return 0 on success, or -1 if relative mode is not supported. + * + * While the mouse is in relative mode, the cursor is hidden, and the + * driver will try to report continuous motion in the current window. + * Only relative motion events will be delivered, the mouse position + * will not change. + * + * \note This function will flush any pending mouse motion. + * + * \sa SDL_GetRelativeMouseMode() + */ +extern DECLSPEC int SDLCALL SDL_SetRelativeMouseMode(SDL_bool enabled); + +/** + * \fn SDL_bool SDL_GetRelativeMouseMode() + * + * \brief Query whether relative mouse mode is enabled for the currently selected mouse. + * + * \sa SDL_SetRelativeMouseMode() + */ +extern DECLSPEC SDL_bool SDLCALL SDL_GetRelativeMouseMode(); + +/** + * \fn Uint8 SDL_GetMouseState(int *x, int *y) + * + * \brief Retrieve the current state of the currently selected mouse. + * * The current button state is returned as a button bitmask, which can * be tested using the SDL_BUTTON(X) macros, and x and y are set to the - * current mouse cursor position. You can pass NULL for either x or y. + * mouse cursor position relative to the focus window for the currently + * selected mouse. You can pass NULL for either x or y. */ extern DECLSPEC Uint8 SDLCALL SDL_GetMouseState(int *x, int *y); -/* - * Retrieve the current state of the mouse. +/** + * \fn Uint8 SDL_GetRelativeMouseState(int *x, int *y) + * + * \brief Retrieve the state of the currently selected mouse. + * * The current button state is returned as a button bitmask, which can * be tested using the SDL_BUTTON(X) macros, and x and y are set to the * mouse deltas since the last call to SDL_GetRelativeMouseState(). */ extern DECLSPEC Uint8 SDLCALL SDL_GetRelativeMouseState(int *x, int *y); -/* - * Set the position of the mouse cursor (generates a mouse motion event) +/** + * \fn void SDL_WarpMouseInWindow(SDL_WindowID windowID, int x, int y) + * + * \brief Moves the currently selected mouse to the given position within the window. + * + * \param windowID The window to move the mouse into, or 0 for the current mouse focus + * \param x The x coordinate within the window + * \param y The y coordinate within the window + * + * \note This function generates a mouse motion event */ -extern DECLSPEC void SDLCALL SDL_WarpMouse(Uint16 x, Uint16 y); +extern DECLSPEC void SDLCALL SDL_WarpMouseInWindow(SDL_WindowID windowID, + int x, int y); -/* - * Create a cursor using the specified data and mask (in MSB format). +/** + * \fn SDL_Cursor *SDL_CreateCursor (const Uint8 * data, const Uint8 * mask, int w, int h, int hot_x, int hot_y) + * + * \brief Create a cursor for the currently selected mouse, using the + * specified bitmap data and mask (in MSB format). + * * The cursor width must be a multiple of 8 bits. * * The cursor is created in black and white according to the following: @@ -78,34 +155,46 @@ extern DECLSPEC void SDLCALL SDL_WarpMouse(Uint16 x, Uint16 y); * 0 0 Transparent * 1 0 Inverted color if possible, black if not. * - * Cursors created with this function must be freed with SDL_FreeCursor(). + * \sa SDL_FreeCursor() */ -extern DECLSPEC SDL_Cursor * SDLCALL SDL_CreateCursor - (Uint8 *data, Uint8 *mask, int w, int h, int hot_x, int hot_y); +extern DECLSPEC SDL_Cursor *SDLCALL SDL_CreateCursor(const Uint8 * data, + const Uint8 * mask, + int w, int h, int hot_x, + int hot_y); -/* - * Set the currently active cursor to the specified one. - * If the cursor is currently visible, the change will be immediately - * represented on the display. +/** + * \fn void SDL_SetCursor(SDL_Cursor * cursor) + * + * \brief Set the active cursor for the currently selected mouse. + * + * \note The cursor must have been created for the selected mouse. */ -extern DECLSPEC void SDLCALL SDL_SetCursor(SDL_Cursor *cursor); +extern DECLSPEC void SDLCALL SDL_SetCursor(SDL_Cursor * cursor); -/* - * Returns the currently active cursor. +/** + * \fn SDL_Cursor *SDL_GetCursor(void) + * + * \brief Return the active cursor for the currently selected mouse. */ -extern DECLSPEC SDL_Cursor * SDLCALL SDL_GetCursor(void); +extern DECLSPEC SDL_Cursor *SDLCALL SDL_GetCursor(void); -/* - * Deallocates a cursor created with SDL_CreateCursor(). +/** + * \fn void SDL_FreeCursor(SDL_Cursor * cursor) + * + * \brief Frees a cursor created with SDL_CreateCursor(). + * + * \sa SDL_CreateCursor() */ -extern DECLSPEC void SDLCALL SDL_FreeCursor(SDL_Cursor *cursor); +extern DECLSPEC void SDLCALL SDL_FreeCursor(SDL_Cursor * cursor); -/* - * Toggle whether or not the cursor is shown on the screen. - * The cursor start off displayed, but can be turned off. - * SDL_ShowCursor() returns 1 if the cursor was being displayed - * before the call, or 0 if it was not. You can query the current - * state by passing a 'toggle' value of -1. +/** + * \fn int SDL_ShowCursor(int toggle) + * + * \brief Toggle whether or not the cursor is shown for the currently selected mouse. + * + * \param toggle 1 to show the cursor, 0 to hide it, -1 to query the current state. + * + * \return 1 if the cursor is shown, or 0 if the cursor is hidden. */ extern DECLSPEC int SDLCALL SDL_ShowCursor(int toggle); @@ -113,15 +202,11 @@ extern DECLSPEC int SDLCALL SDL_ShowCursor(int toggle); Button 1: Left mouse button Button 2: Middle mouse button Button 3: Right mouse button - Button 4: Mouse wheel up (may also be a real button) - Button 5: Mouse wheel down (may also be a real button) */ #define SDL_BUTTON(X) (1 << ((X)-1)) #define SDL_BUTTON_LEFT 1 #define SDL_BUTTON_MIDDLE 2 #define SDL_BUTTON_RIGHT 3 -#define SDL_BUTTON_WHEELUP 4 -#define SDL_BUTTON_WHEELDOWN 5 #define SDL_BUTTON_LMASK SDL_BUTTON(SDL_BUTTON_LEFT) #define SDL_BUTTON_MMASK SDL_BUTTON(SDL_BUTTON_MIDDLE) #define SDL_BUTTON_RMASK SDL_BUTTON(SDL_BUTTON_RIGHT) @@ -129,8 +214,12 @@ extern DECLSPEC int SDLCALL SDL_ShowCursor(int toggle); /* Ends C function definitions when using C++ */ #ifdef __cplusplus +/* *INDENT-OFF* */ } +/* *INDENT-ON* */ #endif #include "close_code.h" #endif /* _SDL_mouse_h */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/include/SDL_mutex.h b/include/SDL_mutex.h index 00165281d..da8435d96 100644 --- a/include/SDL_mutex.h +++ b/include/SDL_mutex.h @@ -23,10 +23,11 @@ #ifndef _SDL_mutex_h #define _SDL_mutex_h -/* Functions to provide thread synchronization primitives - - These are independent of the other SDL routines. -*/ +/** + * \file SDL_mutex.h + * + * Functions to provide thread synchronization primitives + */ #include "SDL_stdinc.h" #include "SDL_error.h" @@ -34,7 +35,9 @@ #include "begin_code.h" /* Set up for C function definitions, even when using C++ */ #ifdef __cplusplus +/* *INDENT-OFF* */ extern "C" { +/* *INDENT-ON* */ #endif /* Synchronization functions which can time out return this value @@ -55,21 +58,21 @@ struct SDL_mutex; typedef struct SDL_mutex SDL_mutex; /* Create a mutex, initialized unlocked */ -extern DECLSPEC SDL_mutex * SDLCALL SDL_CreateMutex(void); +extern DECLSPEC SDL_mutex *SDLCALL SDL_CreateMutex(void); /* Lock the mutex (Returns 0, or -1 on error) */ #define SDL_LockMutex(m) SDL_mutexP(m) -extern DECLSPEC int SDLCALL SDL_mutexP(SDL_mutex *mutex); +extern DECLSPEC int SDLCALL SDL_mutexP(SDL_mutex * mutex); /* Unlock the mutex (Returns 0, or -1 on error) It is an error to unlock a mutex that has not been locked by the current thread, and doing so results in undefined behavior. */ #define SDL_UnlockMutex(m) SDL_mutexV(m) -extern DECLSPEC int SDLCALL SDL_mutexV(SDL_mutex *mutex); +extern DECLSPEC int SDLCALL SDL_mutexV(SDL_mutex * mutex); /* Destroy a mutex */ -extern DECLSPEC void SDLCALL SDL_DestroyMutex(SDL_mutex *mutex); +extern DECLSPEC void SDLCALL SDL_DestroyMutex(SDL_mutex * mutex); /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ @@ -81,21 +84,21 @@ struct SDL_semaphore; typedef struct SDL_semaphore SDL_sem; /* Create a semaphore, initialized with value, returns NULL on failure. */ -extern DECLSPEC SDL_sem * SDLCALL SDL_CreateSemaphore(Uint32 initial_value); +extern DECLSPEC SDL_sem *SDLCALL SDL_CreateSemaphore(Uint32 initial_value); /* Destroy a semaphore */ -extern DECLSPEC void SDLCALL SDL_DestroySemaphore(SDL_sem *sem); +extern DECLSPEC void SDLCALL SDL_DestroySemaphore(SDL_sem * sem); /* This function suspends the calling thread until the semaphore pointed * to by sem has a positive count. It then atomically decreases the semaphore * count. */ -extern DECLSPEC int SDLCALL SDL_SemWait(SDL_sem *sem); +extern DECLSPEC int SDLCALL SDL_SemWait(SDL_sem * sem); /* Non-blocking variant of SDL_SemWait(), returns 0 if the wait succeeds, SDL_MUTEX_TIMEDOUT if the wait would block, and -1 on error. */ -extern DECLSPEC int SDLCALL SDL_SemTryWait(SDL_sem *sem); +extern DECLSPEC int SDLCALL SDL_SemTryWait(SDL_sem * sem); /* Variant of SDL_SemWait() with a timeout in milliseconds, returns 0 if the wait succeeds, SDL_MUTEX_TIMEDOUT if the wait does not succeed in @@ -103,15 +106,15 @@ extern DECLSPEC int SDLCALL SDL_SemTryWait(SDL_sem *sem); On some platforms this function is implemented by looping with a delay of 1 ms, and so should be avoided if possible. */ -extern DECLSPEC int SDLCALL SDL_SemWaitTimeout(SDL_sem *sem, Uint32 ms); +extern DECLSPEC int SDLCALL SDL_SemWaitTimeout(SDL_sem * sem, Uint32 ms); /* Atomically increases the semaphore's count (not blocking), returns 0, or -1 on error. */ -extern DECLSPEC int SDLCALL SDL_SemPost(SDL_sem *sem); +extern DECLSPEC int SDLCALL SDL_SemPost(SDL_sem * sem); /* Returns the current count of the semaphore */ -extern DECLSPEC Uint32 SDLCALL SDL_SemValue(SDL_sem *sem); +extern DECLSPEC Uint32 SDLCALL SDL_SemValue(SDL_sem * sem); /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ @@ -123,27 +126,27 @@ struct SDL_cond; typedef struct SDL_cond SDL_cond; /* Create a condition variable */ -extern DECLSPEC SDL_cond * SDLCALL SDL_CreateCond(void); +extern DECLSPEC SDL_cond *SDLCALL SDL_CreateCond(void); /* Destroy a condition variable */ -extern DECLSPEC void SDLCALL SDL_DestroyCond(SDL_cond *cond); +extern DECLSPEC void SDLCALL SDL_DestroyCond(SDL_cond * cond); /* Restart one of the threads that are waiting on the condition variable, returns 0 or -1 on error. */ -extern DECLSPEC int SDLCALL SDL_CondSignal(SDL_cond *cond); +extern DECLSPEC int SDLCALL SDL_CondSignal(SDL_cond * cond); /* Restart all threads that are waiting on the condition variable, returns 0 or -1 on error. */ -extern DECLSPEC int SDLCALL SDL_CondBroadcast(SDL_cond *cond); +extern DECLSPEC int SDLCALL SDL_CondBroadcast(SDL_cond * cond); /* Wait on the condition variable, unlocking the provided mutex. The mutex must be locked before entering this function! The mutex is re-locked once the condition variable is signaled. Returns 0 when it is signaled, or -1 on error. */ -extern DECLSPEC int SDLCALL SDL_CondWait(SDL_cond *cond, SDL_mutex *mut); +extern DECLSPEC int SDLCALL SDL_CondWait(SDL_cond * cond, SDL_mutex * mut); /* Waits for at most 'ms' milliseconds, and returns 0 if the condition variable is signaled, SDL_MUTEX_TIMEDOUT if the condition is not @@ -151,12 +154,17 @@ extern DECLSPEC int SDLCALL SDL_CondWait(SDL_cond *cond, SDL_mutex *mut); On some platforms this function is implemented by looping with a delay of 1 ms, and so should be avoided if possible. */ -extern DECLSPEC int SDLCALL SDL_CondWaitTimeout(SDL_cond *cond, SDL_mutex *mutex, Uint32 ms); +extern DECLSPEC int SDLCALL SDL_CondWaitTimeout(SDL_cond * cond, + SDL_mutex * mutex, Uint32 ms); /* Ends C function definitions when using C++ */ #ifdef __cplusplus +/* *INDENT-OFF* */ } +/* *INDENT-ON* */ #endif #include "close_code.h" #endif /* _SDL_mutex_h */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/include/SDL_opengl.h b/include/SDL_opengl.h index 36c0a3099..32535473a 100644 --- a/include/SDL_opengl.h +++ b/include/SDL_opengl.h @@ -27,33 +27,35 @@ #ifdef __WIN32__ #define WIN32_LEAN_AND_MEAN #ifndef NOMINMAX -#define NOMINMAX /* Don't defined min() and max() */ +#define NOMINMAX /* Don't defined min() and max() */ #endif #include #endif #ifndef NO_SDL_GLEXT -#define __glext_h_ /* Don't let gl.h include glext.h */ +#define __glext_h_ /* Don't let gl.h include glext.h */ #endif #if defined(__MACOSX__) -#include /* Header File For The OpenGL Library */ -#include /* Header File For The GLU Library */ +#include /* Header File For The OpenGL Library */ +#include /* Header File For The GLU Library */ #elif defined(__MACOS__) -#include /* Header File For The OpenGL Library */ -#include /* Header File For The GLU Library */ +#include /* Header File For The OpenGL Library */ +#include /* Header File For The GLU Library */ #else -#include /* Header File For The OpenGL Library */ -#include /* Header File For The GLU Library */ +#include /* Header File For The OpenGL Library */ +#include /* Header File For The GLU Library */ #endif #ifndef NO_SDL_GLEXT #undef __glext_h_ #endif -/* This file taken from "GLext.h" from the Jeff Molofee OpenGL tutorials. - It is included here because glext.h is not available on some systems. +/* This file is included because glext.h is not available on some systems. If you don't want this version included, simply define "NO_SDL_GLEXT" + The latest version is available from: + http://oss.sgi.com/projects/ogl-sample/registry/ */ -#ifndef NO_SDL_GLEXT -#if !defined(__glext_h_) && !defined(GL_GLEXT_LEGACY) +#if !defined(NO_SDL_GLEXT) && !defined(GL_GLEXT_LEGACY) +/* *INDENT-OFF* */ +#ifndef __glext_h_ #define __glext_h_ #ifdef __cplusplus @@ -6548,4 +6550,5 @@ typedef void (APIENTRYP PFNGLSTRINGMARKERGREMEDYPROC) (GLsizei len, const GLvoid #endif #endif +/* *INDENT-ON* */ #endif /* NO_SDL_GLEXT */ diff --git a/include/SDL_pixels.h b/include/SDL_pixels.h new file mode 100644 index 000000000..6ca2581a8 --- /dev/null +++ b/include/SDL_pixels.h @@ -0,0 +1,348 @@ +/* + SDL - Simple DirectMedia Layer + Copyright (C) 1997-2006 Sam Lantinga + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + Sam Lantinga + slouken@libsdl.org +*/ + +/** + * \file SDL_pixels.h + * + * Header for the enumerated pixel format definitions + */ + +#ifndef _SDL_pixels_h +#define _SDL_pixels_h + +#include "begin_code.h" +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +/* *INDENT-OFF* */ +extern "C" { +/* *INDENT-ON* */ +#endif + +enum +{ /* Pixel type */ + SDL_PixelType_Unknown, + SDL_PixelType_Index1, + SDL_PixelType_Index4, + SDL_PixelType_Index8, + SDL_PixelType_Packed8, + SDL_PixelType_Packed16, + SDL_PixelType_Packed32, + SDL_PixelType_ArrayU8, + SDL_PixelType_ArrayU16, + SDL_PixelType_ArrayU32, + SDL_PixelType_ArrayF16, + SDL_PixelType_ArrayF32, +}; + +enum +{ /* bitmap pixel order, high bit -> low bit */ + SDL_BitmapOrder_None, + SDL_BitmapOrder_4321, + SDL_BitmapOrder_1234, +}; +enum +{ /* packed component order, high bit -> low bit */ + SDL_PackedOrder_None, + SDL_PackedOrder_XRGB, + SDL_PackedOrder_RGBX, + SDL_PackedOrder_ARGB, + SDL_PackedOrder_RGBA, + SDL_PackedOrder_XBGR, + SDL_PackedOrder_BGRX, + SDL_PackedOrder_ABGR, + SDL_PackedOrder_BGRA, +}; +enum +{ /* array component order, low byte -> high byte */ + SDL_ArrayOrder_None, + SDL_ArrayOrder_RGB, + SDL_ArrayOrder_RGBA, + SDL_ArrayOrder_ARGB, + SDL_ArrayOrder_BGR, + SDL_ArrayOrder_BGRA, + SDL_ArrayOrder_ABGR, +}; + +enum +{ /* Packed component layout */ + SDL_PackedLayout_None, + SDL_PackedLayout_332, + SDL_PackedLayout_4444, + SDL_PackedLayout_1555, + SDL_PackedLayout_5551, + SDL_PackedLayout_565, + SDL_PackedLayout_8888, + SDL_PackedLayout_2101010, + SDL_PackedLayout_1010102, +}; + +#define SDL_DEFINE_PIXELFOURCC(A, B, C, D) \ + ((A) | ((B) << 8) | ((C) << 16) | ((D) << 24)) + +#define SDL_DEFINE_PIXELFORMAT(type, order, layout, bits, bytes) \ + ((1 << 31) | ((type) << 24) | ((order) << 20) | ((layout) << 16) | \ + ((bits) << 8) | ((bytes) << 0)) + +#define SDL_PIXELTYPE(X) (((X) >> 24) & 0x0F) +#define SDL_PIXELORDER(X) (((X) >> 20) & 0x0F) +#define SDL_PIXELLAYOUT(X) (((X) >> 16) & 0x0F) +#define SDL_BITSPERPIXEL(X) (((X) >> 8) & 0xFF) +#define SDL_BYTESPERPIXEL(X) (((X) >> 0) & 0xFF) + +#define SDL_ISPIXELFORMAT_INDEXED(format) \ + ((SDL_PIXELTYPE(format) == SDL_PixelType_Index1) || \ + (SDL_PIXELTYPE(format) == SDL_PixelType_Index4) || \ + (SDL_PIXELTYPE(format) == SDL_PixelType_Index8)) + +#define SDL_ISPIXELFORMAT_FOURCC(format) \ + ((format) && !((format) & 0x80000000)) + +enum +{ + SDL_PixelFormat_Unknown, + SDL_PixelFormat_Index1LSB = + SDL_DEFINE_PIXELFORMAT(SDL_PixelType_Index1, SDL_BitmapOrder_1234, 0, + 1, 0), + SDL_PixelFormat_Index1MSB = + SDL_DEFINE_PIXELFORMAT(SDL_PixelType_Index1, SDL_BitmapOrder_4321, 0, + 1, 0), + SDL_PixelFormat_Index4LSB = + SDL_DEFINE_PIXELFORMAT(SDL_PixelType_Index4, SDL_BitmapOrder_1234, 0, + 2, 0), + SDL_PixelFormat_Index4MSB = + SDL_DEFINE_PIXELFORMAT(SDL_PixelType_Index4, SDL_BitmapOrder_4321, 0, + 2, 0), + SDL_PixelFormat_Index8 = + SDL_DEFINE_PIXELFORMAT(SDL_PixelType_Index8, 0, 0, 8, 1), + SDL_PixelFormat_RGB332 = + SDL_DEFINE_PIXELFORMAT(SDL_PixelType_Packed8, SDL_PackedOrder_XRGB, + SDL_PackedLayout_332, 8, 1), + SDL_PixelFormat_RGB444 = + SDL_DEFINE_PIXELFORMAT(SDL_PixelType_Packed16, SDL_PackedOrder_XRGB, + SDL_PackedLayout_4444, 12, 2), + SDL_PixelFormat_RGB555 = + SDL_DEFINE_PIXELFORMAT(SDL_PixelType_Packed16, SDL_PackedOrder_XRGB, + SDL_PackedLayout_1555, 15, 2), + SDL_PixelFormat_ARGB4444 = + SDL_DEFINE_PIXELFORMAT(SDL_PixelType_Packed16, SDL_PackedOrder_ARGB, + SDL_PackedLayout_4444, 16, 2), + SDL_PixelFormat_ARGB1555 = + SDL_DEFINE_PIXELFORMAT(SDL_PixelType_Packed16, SDL_PackedOrder_ARGB, + SDL_PackedLayout_1555, 16, 2), + SDL_PixelFormat_RGB565 = + SDL_DEFINE_PIXELFORMAT(SDL_PixelType_Packed16, SDL_PackedOrder_XRGB, + SDL_PackedLayout_565, 16, 2), + SDL_PixelFormat_RGB24 = + SDL_DEFINE_PIXELFORMAT(SDL_PixelType_ArrayU8, SDL_ArrayOrder_RGB, 0, + 24, 3), + SDL_PixelFormat_BGR24 = + SDL_DEFINE_PIXELFORMAT(SDL_PixelType_ArrayU8, SDL_ArrayOrder_BGR, 0, + 24, 3), + SDL_PixelFormat_RGB888 = + SDL_DEFINE_PIXELFORMAT(SDL_PixelType_Packed32, SDL_PackedOrder_XRGB, + SDL_PackedLayout_8888, 24, 4), + SDL_PixelFormat_BGR888 = + SDL_DEFINE_PIXELFORMAT(SDL_PixelType_Packed32, SDL_PackedOrder_XBGR, + SDL_PackedLayout_8888, 24, 4), + SDL_PixelFormat_ARGB8888 = + SDL_DEFINE_PIXELFORMAT(SDL_PixelType_Packed32, SDL_PackedOrder_ARGB, + SDL_PackedLayout_8888, 32, 4), + SDL_PixelFormat_RGBA8888 = + SDL_DEFINE_PIXELFORMAT(SDL_PixelType_Packed32, SDL_PackedOrder_RGBA, + SDL_PackedLayout_8888, 32, 4), + SDL_PixelFormat_ABGR8888 = + SDL_DEFINE_PIXELFORMAT(SDL_PixelType_Packed32, SDL_PackedOrder_ABGR, + SDL_PackedLayout_8888, 32, 4), + SDL_PixelFormat_BGRA8888 = + SDL_DEFINE_PIXELFORMAT(SDL_PixelType_Packed32, SDL_PackedOrder_BGRA, + SDL_PackedLayout_8888, 32, 4), + SDL_PixelFormat_ARGB2101010 = + SDL_DEFINE_PIXELFORMAT(SDL_PixelType_Packed32, SDL_PackedOrder_ARGB, + SDL_PackedLayout_2101010, 32, 4), + + SDL_PixelFormat_YV12 = /* Planar mode: Y + V + U (3 planes) */ + SDL_DEFINE_PIXELFOURCC('Y', 'V', '1', '2'), + SDL_PixelFormat_IYUV = /* Planar mode: Y + U + V (3 planes) */ + SDL_DEFINE_PIXELFOURCC('I', 'Y', 'U', 'V'), + SDL_PixelFormat_YUY2 = /* Packed mode: Y0+U0+Y1+V0 (1 plane) */ + SDL_DEFINE_PIXELFOURCC('Y', 'U', 'Y', '2'), + SDL_PixelFormat_UYVY = /* Packed mode: U0+Y0+V0+Y1 (1 plane) */ + SDL_DEFINE_PIXELFOURCC('U', 'Y', 'V', 'Y'), + SDL_PixelFormat_YVYU = /* Packed mode: Y0+V0+Y1+U0 (1 plane) */ + SDL_DEFINE_PIXELFOURCC('Y', 'V', 'Y', 'U'), +}; + +typedef struct SDL_Color +{ + Uint8 r; + Uint8 g; + Uint8 b; + Uint8 unused; +} SDL_Color; +#define SDL_Colour SDL_Color + +typedef struct SDL_Palette SDL_Palette; +typedef int (*SDL_PaletteChangedFunc) (void *userdata, SDL_Palette * palette); + +typedef struct SDL_PaletteWatch +{ + SDL_PaletteChangedFunc callback; + void *userdata; + struct SDL_PaletteWatch *next; +} SDL_PaletteWatch; + +struct SDL_Palette +{ + int ncolors; + SDL_Color *colors; + + int refcount; + SDL_PaletteWatch *watch; +}; + +/* Everything in the pixel format structure is read-only */ +typedef struct SDL_PixelFormat +{ + SDL_Palette *palette; + Uint8 BitsPerPixel; + Uint8 BytesPerPixel; + Uint8 Rloss; + Uint8 Gloss; + Uint8 Bloss; + Uint8 Aloss; + Uint8 Rshift; + Uint8 Gshift; + Uint8 Bshift; + Uint8 Ashift; + Uint32 Rmask; + Uint32 Gmask; + Uint32 Bmask; + Uint32 Amask; + + /* RGB color key information */ + Uint32 colorkey; + /* Alpha value information (per-surface alpha) */ + Uint8 alpha; +} SDL_PixelFormat; + +/** + * \fn SDL_bool SDL_PixelFormatEnumToMasks(Uint32 format, int *bpp, Uint32 * Rmask, Uint32 * Gmask, Uint32 * Bmask, Uint32 * Amask) + * + * \brief Convert one of the enumerated pixel formats to a bpp and RGBA masks. + * + * \return SDL_TRUE, or SDL_FALSE if the conversion wasn't possible. + * + * \sa SDL_MasksToPixelFormatEnum() + */ +extern DECLSPEC SDL_bool SDLCALL SDL_PixelFormatEnumToMasks(Uint32 format, + int *bpp, + Uint32 * Rmask, + Uint32 * Gmask, + Uint32 * Bmask, + Uint32 * Amask); + +/** + * \fn Uint32 SDL_MasksToPixelFormatEnum(int bpp, Uint32 Rmask, Uint32 Gmask, Uint32 Bmask, Uint32 Amask) + * + * \brief Convert a bpp and RGBA masks to an enumerated pixel format. + * + * \return The pixel format, or SDL_PixelFormat_Unknown if the conversion wasn't possible. + * + * \sa SDL_PixelFormatEnumToMasks() + */ +extern DECLSPEC Uint32 SDLCALL SDL_MasksToPixelFormatEnum(int bpp, + Uint32 Rmask, + Uint32 Gmask, + Uint32 Bmask, + Uint32 Amask); + +/** + * \fn SDL_Palette *SDL_AllocPalette(int ncolors) + * + * \brief Create a palette structure with the specified number of color entries. + * + * \return A new palette, or NULL if there wasn't enough memory + * + * \note The palette entries are initialized to white. + * + * \sa SDL_FreePalette() + */ +extern DECLSPEC SDL_Palette *SDLCALL SDL_AllocPalette(int ncolors); + +/** + * \fn int SDL_AddPaletteWatch(SDL_Palette *palette, SDL_PaletteChangedFunc callback, void *userdata) + * + * \brief Add a callback function which is called when the palette changes. + * + * \sa SDL_DelPaletteWatch() + */ +extern DECLSPEC int SDLCALL SDL_AddPaletteWatch(SDL_Palette * palette, + SDL_PaletteChangedFunc + callback, void *userdata); + +/** + * \fn void SDL_DelPaletteWatch(SDL_Palette *palette, SDL_PaletteChangedFunc callback, void *userdata) + * + * \brief Remove a callback function previously added with SDL_AddPaletteWatch() + * + * \sa SDL_AddPaletteWatch() + */ +extern DECLSPEC void SDLCALL SDL_DelPaletteWatch(SDL_Palette * palette, + SDL_PaletteChangedFunc + callback, void *userdata); + +/** + * \fn int SDL_SetPaletteColors(SDL_Palette *palette, const SDL_Colors *colors, int firstcolor, int numcolors) + * + * \brief Set a range of colors in a palette. + * + * \param palette The palette to modify + * \param colors An array of colors to copy into the palette + * \param firstcolor The index of the first palette entry to modify + * \param ncolors The number of entries to modify + * + * \return 0 on success, or -1 if not all of the colors could be set + */ +extern DECLSPEC int SDLCALL SDL_SetPaletteColors(SDL_Palette * palette, + const SDL_Color * colors, + int firstcolor, int ncolors); + +/** + * \fn void SDL_FreePalette(SDL_Palette *palette) + * + * \brief Free a palette created with SDL_AllocPalette() + * + * \sa SDL_AllocPalette() + */ +extern DECLSPEC void SDLCALL SDL_FreePalette(SDL_Palette * palette); + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +/* *INDENT-OFF* */ +} +/* *INDENT-ON* */ +#endif +#include "close_code.h" + +#endif /* _SDL_pixels_h */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/include/SDL_quit.h b/include/SDL_quit.h index fcf40fbdd..5eedb4c34 100644 --- a/include/SDL_quit.h +++ b/include/SDL_quit.h @@ -20,7 +20,11 @@ slouken@libsdl.org */ -/* Include file for SDL quit event handling */ +/** + * \file SDL_quit.h + * + * Include file for SDL quit event handling + */ #ifndef _SDL_quit_h #define _SDL_quit_h diff --git a/include/SDL_rwops.h b/include/SDL_rwops.h index d7e01d8fd..d9d600026 100644 --- a/include/SDL_rwops.h +++ b/include/SDL_rwops.h @@ -20,9 +20,12 @@ slouken@libsdl.org */ -/* This file provides a general interface for SDL to read and write - data sources. It can easily be extended to files, memory, etc. -*/ +/** + * \file SDL_rwops.h + * + * This file provides a general interface for SDL to read and write + * data sources. It can easily be extended to files, memory, etc. + */ #ifndef _SDL_rwops_h #define _SDL_rwops_h @@ -33,77 +36,89 @@ #include "begin_code.h" /* Set up for C function definitions, even when using C++ */ #ifdef __cplusplus +/* *INDENT-OFF* */ extern "C" { +/* *INDENT-ON* */ #endif /* This is the read/write operation structure -- very basic */ -typedef struct SDL_RWops { - /* Seek to 'offset' relative to whence, one of stdio's whence values: - SEEK_SET, SEEK_CUR, SEEK_END - Returns the final offset in the data source. - */ - int (SDLCALL *seek)(struct SDL_RWops *context, int offset, int whence); - - /* Read up to 'num' objects each of size 'objsize' from the data - source to the area pointed at by 'ptr'. - Returns the number of objects read, or -1 if the read failed. - */ - int (SDLCALL *read)(struct SDL_RWops *context, void *ptr, int size, int maxnum); - - /* Write exactly 'num' objects each of size 'objsize' from the area - pointed at by 'ptr' to data source. - Returns 'num', or -1 if the write failed. - */ - int (SDLCALL *write)(struct SDL_RWops *context, const void *ptr, int size, int num); - - /* Close and free an allocated SDL_FSops structure */ - int (SDLCALL *close)(struct SDL_RWops *context); - - Uint32 type; - union { +typedef struct SDL_RWops +{ + /* Seek to 'offset' relative to whence, one of stdio's whence values: + SEEK_SET, SEEK_CUR, SEEK_END + Returns the final offset in the data source. + */ + int (SDLCALL * seek) (struct SDL_RWops * context, int offset, int whence); + + /* Read up to 'num' objects each of size 'objsize' from the data + source to the area pointed at by 'ptr'. + Returns the number of objects read, or -1 if the read failed. + */ + int (SDLCALL * read) (struct SDL_RWops * context, void *ptr, int size, + int maxnum); + + /* Write exactly 'num' objects each of size 'objsize' from the area + pointed at by 'ptr' to data source. + Returns 'num', or -1 if the write failed. + */ + int (SDLCALL * write) (struct SDL_RWops * context, const void *ptr, + int size, int num); + + /* Close and free an allocated SDL_FSops structure */ + int (SDLCALL * close) (struct SDL_RWops * context); + + Uint32 type; + union + { #ifdef __WIN32__ - struct { - int append; - void* h; - } win32io; + struct + { + int append; + void *h; + } win32io; #endif -#ifdef HAVE_STDIO_H - struct { - int autoclose; - FILE *fp; - } stdio; +#ifdef HAVE_STDIO_H + struct + { + int autoclose; + FILE *fp; + } stdio; #endif - struct { - Uint8 *base; - Uint8 *here; - Uint8 *stop; - } mem; - struct { - void *data1; - } unknown; - } hidden; + struct + { + Uint8 *base; + Uint8 *here; + Uint8 *stop; + } mem; + struct + { + void *data1; + } unknown; + } hidden; } SDL_RWops; /* Functions to create SDL_RWops structures from various data sources */ -extern DECLSPEC SDL_RWops * SDLCALL SDL_RWFromFile(const char *file, const char *mode); +extern DECLSPEC SDL_RWops *SDLCALL SDL_RWFromFile(const char *file, + const char *mode); #ifdef HAVE_STDIO_H -extern DECLSPEC SDL_RWops * SDLCALL SDL_RWFromFP(FILE *fp, int autoclose); +extern DECLSPEC SDL_RWops *SDLCALL SDL_RWFromFP(FILE * fp, int autoclose); #endif -extern DECLSPEC SDL_RWops * SDLCALL SDL_RWFromMem(void *mem, int size); -extern DECLSPEC SDL_RWops * SDLCALL SDL_RWFromConstMem(const void *mem, int size); +extern DECLSPEC SDL_RWops *SDLCALL SDL_RWFromMem(void *mem, int size); +extern DECLSPEC SDL_RWops *SDLCALL SDL_RWFromConstMem(const void *mem, + int size); -extern DECLSPEC SDL_RWops * SDLCALL SDL_AllocRW(void); -extern DECLSPEC void SDLCALL SDL_FreeRW(SDL_RWops *area); +extern DECLSPEC SDL_RWops *SDLCALL SDL_AllocRW(void); +extern DECLSPEC void SDLCALL SDL_FreeRW(SDL_RWops * area); -#define RW_SEEK_SET 0 /* Seek from the beginning of data */ -#define RW_SEEK_CUR 1 /* Seek relative to current read point */ -#define RW_SEEK_END 2 /* Seek relative to the end of data */ +#define RW_SEEK_SET 0 /* Seek from the beginning of data */ +#define RW_SEEK_CUR 1 /* Seek relative to current read point */ +#define RW_SEEK_END 2 /* Seek relative to the end of data */ /* Macros to easily read and write from an SDL_RWops structure */ #define SDL_RWseek(ctx, offset, whence) (ctx)->seek(ctx, offset, whence) @@ -114,26 +129,30 @@ extern DECLSPEC void SDLCALL SDL_FreeRW(SDL_RWops *area); /* Read an item of the specified endianness and return in native format */ -extern DECLSPEC Uint16 SDLCALL SDL_ReadLE16(SDL_RWops *src); -extern DECLSPEC Uint16 SDLCALL SDL_ReadBE16(SDL_RWops *src); -extern DECLSPEC Uint32 SDLCALL SDL_ReadLE32(SDL_RWops *src); -extern DECLSPEC Uint32 SDLCALL SDL_ReadBE32(SDL_RWops *src); -extern DECLSPEC Uint64 SDLCALL SDL_ReadLE64(SDL_RWops *src); -extern DECLSPEC Uint64 SDLCALL SDL_ReadBE64(SDL_RWops *src); +extern DECLSPEC Uint16 SDLCALL SDL_ReadLE16(SDL_RWops * src); +extern DECLSPEC Uint16 SDLCALL SDL_ReadBE16(SDL_RWops * src); +extern DECLSPEC Uint32 SDLCALL SDL_ReadLE32(SDL_RWops * src); +extern DECLSPEC Uint32 SDLCALL SDL_ReadBE32(SDL_RWops * src); +extern DECLSPEC Uint64 SDLCALL SDL_ReadLE64(SDL_RWops * src); +extern DECLSPEC Uint64 SDLCALL SDL_ReadBE64(SDL_RWops * src); /* Write an item of native format to the specified endianness */ -extern DECLSPEC int SDLCALL SDL_WriteLE16(SDL_RWops *dst, Uint16 value); -extern DECLSPEC int SDLCALL SDL_WriteBE16(SDL_RWops *dst, Uint16 value); -extern DECLSPEC int SDLCALL SDL_WriteLE32(SDL_RWops *dst, Uint32 value); -extern DECLSPEC int SDLCALL SDL_WriteBE32(SDL_RWops *dst, Uint32 value); -extern DECLSPEC int SDLCALL SDL_WriteLE64(SDL_RWops *dst, Uint64 value); -extern DECLSPEC int SDLCALL SDL_WriteBE64(SDL_RWops *dst, Uint64 value); +extern DECLSPEC int SDLCALL SDL_WriteLE16(SDL_RWops * dst, Uint16 value); +extern DECLSPEC int SDLCALL SDL_WriteBE16(SDL_RWops * dst, Uint16 value); +extern DECLSPEC int SDLCALL SDL_WriteLE32(SDL_RWops * dst, Uint32 value); +extern DECLSPEC int SDLCALL SDL_WriteBE32(SDL_RWops * dst, Uint32 value); +extern DECLSPEC int SDLCALL SDL_WriteLE64(SDL_RWops * dst, Uint64 value); +extern DECLSPEC int SDLCALL SDL_WriteBE64(SDL_RWops * dst, Uint64 value); /* Ends C function definitions when using C++ */ #ifdef __cplusplus +/* *INDENT-OFF* */ } +/* *INDENT-ON* */ #endif #include "close_code.h" #endif /* _SDL_rwops_h */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/include/SDL_stdinc.h b/include/SDL_stdinc.h index 62535629f..83c8ef272 100644 --- a/include/SDL_stdinc.h +++ b/include/SDL_stdinc.h @@ -20,7 +20,11 @@ slouken@libsdl.org */ -/* This is a general header that includes C language support */ +/** + * \file SDL_stdinc.h + * + * This is a general header that includes C language support + */ #ifndef _SDL_stdinc_h #define _SDL_stdinc_h @@ -77,33 +81,66 @@ #define SDL_TABLESIZE(table) SDL_arraysize(table) /* Basic data types */ -typedef enum SDL_bool { - SDL_FALSE = 0, - SDL_TRUE = 1 +typedef enum SDL_bool +{ + SDL_FALSE = 0, + SDL_TRUE = 1 } SDL_bool; -typedef int8_t Sint8; -typedef uint8_t Uint8; -typedef int16_t Sint16; -typedef uint16_t Uint16; -typedef int32_t Sint32; -typedef uint32_t Uint32; +/** + * \typedef Sint8 + * \brief A signed 8-bit integer type. + */ +typedef int8_t Sint8; +/** + * \typedef Uint8 + * \brief An unsigned 8-bit integer type. + */ +typedef uint8_t Uint8; +/** + * \typedef Sint16 + * \brief A signed 16-bit integer type. + */ +typedef int16_t Sint16; +/** + * \typedef Uint16 + * \brief An unsigned 16-bit integer type. + */ +typedef uint16_t Uint16; +/** + * \typedef Sint32 + * \brief A signed 32-bit integer type. + */ +typedef int32_t Sint32; +/** + * \typedef Uint32 + * \brief An unsigned 32-bit integer type. + */ +typedef uint32_t Uint32; #ifdef SDL_HAS_64BIT_TYPE -typedef int64_t Sint64; -typedef uint64_t Uint64; +/** + * \typedef Sint64 + * \brief A signed 64-bit integer type. + * \warning On platforms without any sort of 64-bit datatype, this is equivalent to Sint32! + */ +typedef int64_t Sint64; +/** + * \typedef Uint64 + * \brief An unsigned 64-bit integer type. + * \warning On platforms without any sort of 64-bit datatype, this is equivalent to Uint32! + */ +typedef uint64_t Uint64; #else /* This is really just a hack to prevent the compiler from complaining */ -typedef struct { - Uint32 hi; - Uint32 lo; -} Uint64, Sint64; +typdef Sint32 Sint64; +typdef Uint32 Uint32; #endif /* Make sure the types really have the right sizes */ #define SDL_COMPILE_TIME_ASSERT(name, x) \ typedef int SDL_dummy_ ## name[(x) * 2 - 1] - +#ifndef DOXYGEN_SHOULD_IGNORE_THIS SDL_COMPILE_TIME_ASSERT(uint8, sizeof(Uint8) == 1); SDL_COMPILE_TIME_ASSERT(sint8, sizeof(Sint8) == 1); SDL_COMPILE_TIME_ASSERT(uint16, sizeof(Uint16) == 2); @@ -112,6 +149,7 @@ SDL_COMPILE_TIME_ASSERT(uint32, sizeof(Uint32) == 4); SDL_COMPILE_TIME_ASSERT(sint32, sizeof(Sint32) == 4); SDL_COMPILE_TIME_ASSERT(uint64, sizeof(Uint64) == 8); SDL_COMPILE_TIME_ASSERT(sint64, sizeof(Sint64) == 8); +#endif /* DOXYGEN_SHOULD_IGNORE_THIS */ /* Check to make sure enums are the size of ints, for structure packing. For both Watcom C/C++ and Borland C/C++ the compiler option that makes @@ -123,35 +161,39 @@ SDL_COMPILE_TIME_ASSERT(sint64, sizeof(Sint64) == 8); #pragma enumsalwaysint on #endif -typedef enum { - DUMMY_ENUM_VALUE +#ifndef DOXYGEN_SHOULD_IGNORE_THIS +typedef enum +{ + DUMMY_ENUM_VALUE } SDL_DUMMY_ENUM; SDL_COMPILE_TIME_ASSERT(enum, sizeof(SDL_DUMMY_ENUM) == sizeof(int)); - +#endif /* DOXYGEN_SHOULD_IGNORE_THIS */ #include "begin_code.h" /* Set up for C function definitions, even when using C++ */ #ifdef __cplusplus +/* *INDENT-OFF* */ extern "C" { +/* *INDENT-ON* */ #endif #ifdef HAVE_MALLOC #define SDL_malloc malloc #else -extern DECLSPEC void * SDLCALL SDL_malloc(size_t size); +extern DECLSPEC void *SDLCALL SDL_malloc(size_t size); #endif #ifdef HAVE_CALLOC #define SDL_calloc calloc #else -extern DECLSPEC void * SDLCALL SDL_calloc(size_t nmemb, size_t size); +extern DECLSPEC void *SDLCALL SDL_calloc(size_t nmemb, size_t size); #endif #ifdef HAVE_REALLOC #define SDL_realloc realloc #else -extern DECLSPEC void * SDLCALL SDL_realloc(void *mem, size_t size); +extern DECLSPEC void *SDLCALL SDL_realloc(void *mem, size_t size); #endif #ifdef HAVE_FREE @@ -173,11 +215,11 @@ extern DECLSPEC void SDLCALL SDL_free(void *mem); # elif defined(__DMC__) # include # elif defined(__AIX__) - #pragma alloca +#pragma alloca # elif defined(__MRC__) - void *alloca (unsigned); +void *alloca(unsigned); # else - char *alloca (); +char *alloca(); # endif #endif #ifdef HAVE_ALLOCA @@ -191,7 +233,7 @@ extern DECLSPEC void SDLCALL SDL_free(void *mem); #ifdef HAVE_GETENV #define SDL_getenv getenv #else -extern DECLSPEC char * SDLCALL SDL_getenv(const char *name); +extern DECLSPEC char *SDLCALL SDL_getenv(const char *name); #endif #ifdef HAVE_PUTENV @@ -204,7 +246,8 @@ extern DECLSPEC int SDLCALL SDL_putenv(const char *variable); #define SDL_qsort qsort #else extern DECLSPEC void SDLCALL SDL_qsort(void *base, size_t nmemb, size_t size, - int (*compare)(const void *, const void *)); + int (*compare) (const void *, + const void *)); #endif #ifdef HAVE_ABS @@ -231,8 +274,10 @@ extern DECLSPEC void SDLCALL SDL_qsort(void *base, size_t nmemb, size_t size, #ifdef HAVE_MEMSET #define SDL_memset memset #else -extern DECLSPEC void * SDLCALL SDL_memset(void *dst, int c, size_t len); +extern DECLSPEC void *SDLCALL SDL_memset(void *dst, int c, size_t len); #endif +#define SDL_zero(x) SDL_memset(&(x), 0, sizeof((x))) +#define SDL_zerop(x) SDL_memset((x), 0, sizeof(*(x))) #if defined(__GNUC__) && defined(i386) #define SDL_memset4(dst, val, len) \ @@ -288,7 +333,8 @@ do { \ #elif defined(HAVE_BCOPY) #define SDL_memcpy(d, s, n) bcopy((s), (d), (n)) #else -extern DECLSPEC void * SDLCALL SDL_memcpy(void *dst, const void *src, size_t len); +extern DECLSPEC void *SDLCALL SDL_memcpy(void *dst, const void *src, + size_t len); #endif #endif @@ -335,7 +381,8 @@ do { \ } while(0) #endif #ifndef SDL_revcpy -extern DECLSPEC void * SDLCALL SDL_revcpy(void *dst, const void *src, size_t len); +extern DECLSPEC void *SDLCALL SDL_revcpy(void *dst, const void *src, + size_t len); #endif #ifdef HAVE_MEMMOVE @@ -356,7 +403,8 @@ do { \ #ifdef HAVE_MEMCMP #define SDL_memcmp memcmp #else -extern DECLSPEC int SDLCALL SDL_memcmp(const void *s1, const void *s2, size_t len); +extern DECLSPEC int SDLCALL SDL_memcmp(const void *s1, const void *s2, + size_t len); #endif #ifdef HAVE_STRLEN @@ -368,37 +416,39 @@ extern DECLSPEC size_t SDLCALL SDL_strlen(const char *string); #ifdef HAVE_STRLCPY #define SDL_strlcpy strlcpy #else -extern DECLSPEC size_t SDLCALL SDL_strlcpy(char *dst, const char *src, size_t maxlen); +extern DECLSPEC size_t SDLCALL SDL_strlcpy(char *dst, const char *src, + size_t maxlen); #endif #ifdef HAVE_STRLCAT #define SDL_strlcat strlcat #else -extern DECLSPEC size_t SDLCALL SDL_strlcat(char *dst, const char *src, size_t maxlen); +extern DECLSPEC size_t SDLCALL SDL_strlcat(char *dst, const char *src, + size_t maxlen); #endif #ifdef HAVE_STRDUP #define SDL_strdup strdup #else -extern DECLSPEC char * SDLCALL SDL_strdup(const char *string); +extern DECLSPEC char *SDLCALL SDL_strdup(const char *string); #endif #ifdef HAVE__STRREV #define SDL_strrev _strrev #else -extern DECLSPEC char * SDLCALL SDL_strrev(char *string); +extern DECLSPEC char *SDLCALL SDL_strrev(char *string); #endif #ifdef HAVE__STRUPR #define SDL_strupr _strupr #else -extern DECLSPEC char * SDLCALL SDL_strupr(char *string); +extern DECLSPEC char *SDLCALL SDL_strupr(char *string); #endif #ifdef HAVE__STRLWR #define SDL_strlwr _strlwr #else -extern DECLSPEC char * SDLCALL SDL_strlwr(char *string); +extern DECLSPEC char *SDLCALL SDL_strlwr(char *string); #endif #ifdef HAVE_STRCHR @@ -406,7 +456,7 @@ extern DECLSPEC char * SDLCALL SDL_strlwr(char *string); #elif defined(HAVE_INDEX) #define SDL_strchr index #else -extern DECLSPEC char * SDLCALL SDL_strchr(const char *string, int c); +extern DECLSPEC char *SDLCALL SDL_strchr(const char *string, int c); #endif #ifdef HAVE_STRRCHR @@ -414,13 +464,14 @@ extern DECLSPEC char * SDLCALL SDL_strchr(const char *string, int c); #elif defined(HAVE_RINDEX) #define SDL_strrchr rindex #else -extern DECLSPEC char * SDLCALL SDL_strrchr(const char *string, int c); +extern DECLSPEC char *SDLCALL SDL_strrchr(const char *string, int c); #endif #ifdef HAVE_STRSTR #define SDL_strstr strstr #else -extern DECLSPEC char * SDLCALL SDL_strstr(const char *haystack, const char *needle); +extern DECLSPEC char *SDLCALL SDL_strstr(const char *haystack, + const char *needle); #endif #ifdef HAVE_ITOA @@ -432,7 +483,7 @@ extern DECLSPEC char * SDLCALL SDL_strstr(const char *haystack, const char *need #ifdef HAVE__LTOA #define SDL_ltoa _ltoa #else -extern DECLSPEC char * SDLCALL SDL_ltoa(long value, char *string, int radix); +extern DECLSPEC char *SDLCALL SDL_ltoa(long value, char *string, int radix); #endif #ifdef HAVE__UITOA @@ -444,19 +495,22 @@ extern DECLSPEC char * SDLCALL SDL_ltoa(long value, char *string, int radix); #ifdef HAVE__ULTOA #define SDL_ultoa _ultoa #else -extern DECLSPEC char * SDLCALL SDL_ultoa(unsigned long value, char *string, int radix); +extern DECLSPEC char *SDLCALL SDL_ultoa(unsigned long value, char *string, + int radix); #endif #ifdef HAVE_STRTOL #define SDL_strtol strtol #else -extern DECLSPEC long SDLCALL SDL_strtol(const char *string, char **endp, int base); +extern DECLSPEC long SDLCALL SDL_strtol(const char *string, char **endp, + int base); #endif #ifdef HAVE_STRTOUL #define SDL_strtoul strtoul #else -extern DECLSPEC unsigned long SDLCALL SDL_strtoul(const char *string, char **endp, int base); +extern DECLSPEC unsigned long SDLCALL SDL_strtoul(const char *string, + char **endp, int base); #endif #ifdef SDL_HAS_64BIT_TYPE @@ -464,25 +518,29 @@ extern DECLSPEC unsigned long SDLCALL SDL_strtoul(const char *string, char **end #ifdef HAVE__I64TOA #define SDL_lltoa _i64toa #else -extern DECLSPEC char* SDLCALL SDL_lltoa(Sint64 value, char *string, int radix); +extern DECLSPEC char *SDLCALL SDL_lltoa(Sint64 value, char *string, + int radix); #endif #ifdef HAVE__UI64TOA #define SDL_ulltoa _ui64toa #else -extern DECLSPEC char* SDLCALL SDL_ulltoa(Uint64 value, char *string, int radix); +extern DECLSPEC char *SDLCALL SDL_ulltoa(Uint64 value, char *string, + int radix); #endif #ifdef HAVE_STRTOLL #define SDL_strtoll strtoll #else -extern DECLSPEC Sint64 SDLCALL SDL_strtoll(const char *string, char **endp, int base); +extern DECLSPEC Sint64 SDLCALL SDL_strtoll(const char *string, char **endp, + int base); #endif #ifdef HAVE_STRTOULL #define SDL_strtoull strtoull #else -extern DECLSPEC Uint64 SDLCALL SDL_strtoull(const char *string, char **endp, int base); +extern DECLSPEC Uint64 SDLCALL SDL_strtoull(const char *string, char **endp, + int base); #endif #endif /* SDL_HAS_64BIT_TYPE */ @@ -514,7 +572,8 @@ extern DECLSPEC int SDLCALL SDL_strcmp(const char *str1, const char *str2); #ifdef HAVE_STRNCMP #define SDL_strncmp strncmp #else -extern DECLSPEC int SDLCALL SDL_strncmp(const char *str1, const char *str2, size_t maxlen); +extern DECLSPEC int SDLCALL SDL_strncmp(const char *str1, const char *str2, + size_t maxlen); #endif #ifdef HAVE_STRCASECMP @@ -522,7 +581,8 @@ extern DECLSPEC int SDLCALL SDL_strncmp(const char *str1, const char *str2, size #elif defined(HAVE__STRICMP) #define SDL_strcasecmp _stricmp #else -extern DECLSPEC int SDLCALL SDL_strcasecmp(const char *str1, const char *str2); +extern DECLSPEC int SDLCALL SDL_strcasecmp(const char *str1, + const char *str2); #endif #ifdef HAVE_STRNCASECMP @@ -530,25 +590,29 @@ extern DECLSPEC int SDLCALL SDL_strcasecmp(const char *str1, const char *str2); #elif defined(HAVE__STRNICMP) #define SDL_strncasecmp _strnicmp #else -extern DECLSPEC int SDLCALL SDL_strncasecmp(const char *str1, const char *str2, size_t maxlen); +extern DECLSPEC int SDLCALL SDL_strncasecmp(const char *str1, + const char *str2, size_t maxlen); #endif #ifdef HAVE_SSCANF #define SDL_sscanf sscanf #else -extern DECLSPEC int SDLCALL SDL_sscanf(const char *text, const char *fmt, ...); +extern DECLSPEC int SDLCALL SDL_sscanf(const char *text, const char *fmt, + ...); #endif #ifdef HAVE_SNPRINTF #define SDL_snprintf snprintf #else -extern DECLSPEC int SDLCALL SDL_snprintf(char *text, size_t maxlen, const char *fmt, ...); +extern DECLSPEC int SDLCALL SDL_snprintf(char *text, size_t maxlen, + const char *fmt, ...); #endif #ifdef HAVE_VSNPRINTF #define SDL_vsnprintf vsnprintf #else -extern DECLSPEC int SDLCALL SDL_vsnprintf(char *text, size_t maxlen, const char *fmt, va_list ap); +extern DECLSPEC int SDLCALL SDL_vsnprintf(char *text, size_t maxlen, + const char *fmt, va_list ap); #endif /* The SDL implementation of iconv() returns these error codes */ @@ -561,17 +625,25 @@ extern DECLSPEC int SDLCALL SDL_vsnprintf(char *text, size_t maxlen, const char #define SDL_iconv_t iconv_t #define SDL_iconv_open iconv_open #define SDL_iconv_close iconv_close -extern DECLSPEC size_t SDLCALL SDL_iconv(SDL_iconv_t cd, char **inbuf, size_t *inbytesleft, char **outbuf, size_t *outbytesleft); +extern DECLSPEC size_t SDLCALL SDL_iconv(SDL_iconv_t cd, char **inbuf, + size_t * inbytesleft, char **outbuf, + size_t * outbytesleft); #else typedef struct _SDL_iconv_t *SDL_iconv_t; -extern DECLSPEC SDL_iconv_t SDLCALL SDL_iconv_open(const char *tocode, const char *fromcode); +extern DECLSPEC SDL_iconv_t SDLCALL SDL_iconv_open(const char *tocode, + const char *fromcode); extern DECLSPEC int SDLCALL SDL_iconv_close(SDL_iconv_t cd); -extern DECLSPEC size_t SDLCALL SDL_iconv(SDL_iconv_t cd, char **inbuf, size_t *inbytesleft, char **outbuf, size_t *outbytesleft); +extern DECLSPEC size_t SDLCALL SDL_iconv(SDL_iconv_t cd, char **inbuf, + size_t * inbytesleft, char **outbuf, + size_t * outbytesleft); #endif /* This function converts a string between encodings in one pass, returning a string that must be freed with SDL_free() or NULL on error. */ -extern DECLSPEC char * SDLCALL SDL_iconv_string(const char *tocode, const char *fromcode, char *inbuf, size_t inbytesleft); +extern DECLSPEC char *SDLCALL SDL_iconv_string(const char *tocode, + const char *fromcode, + char *inbuf, + size_t inbytesleft); #define SDL_iconv_utf8_ascii(S) SDL_iconv_string("ASCII", "UTF-8", S, SDL_strlen(S)+1) #define SDL_iconv_utf8_latin1(S) SDL_iconv_string("LATIN1", "UTF-8", S, SDL_strlen(S)+1) #define SDL_iconv_utf8_ucs2(S) (Uint16 *)SDL_iconv_string("UCS-2", "UTF-8", S, SDL_strlen(S)+1) @@ -579,8 +651,12 @@ extern DECLSPEC char * SDLCALL SDL_iconv_string(const char *tocode, const char * /* Ends C function definitions when using C++ */ #ifdef __cplusplus +/* *INDENT-OFF* */ } +/* *INDENT-ON* */ #endif #include "close_code.h" #endif /* _SDL_stdinc_h */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/include/SDL_syswm.h b/include/SDL_syswm.h index e7f35139a..ee7b817e0 100644 --- a/include/SDL_syswm.h +++ b/include/SDL_syswm.h @@ -20,19 +20,26 @@ slouken@libsdl.org */ -/* Include file for SDL custom system window manager hooks */ +/** + * \file SDL_syswm.h + * + * Include file for SDL custom system window manager hooks + */ #ifndef _SDL_syswm_h #define _SDL_syswm_h #include "SDL_stdinc.h" #include "SDL_error.h" +#include "SDL_video.h" #include "SDL_version.h" #include "begin_code.h" /* Set up for C function definitions, even when using C++ */ #ifdef __cplusplus +/* *INDENT-OFF* */ extern "C" { +/* *INDENT-ON* */ #endif /* Your application has access to a special type of event 'SDL_SYSWMEVENT', @@ -42,7 +49,6 @@ extern "C" { */ #ifdef SDL_PROTOTYPES_ONLY struct SDL_SysWMinfo; -typedef struct SDL_SysWMinfo SDL_SysWMinfo; #else /* This is the structure for custom window manager events */ @@ -61,150 +67,179 @@ typedef struct SDL_SysWMinfo SDL_SysWMinfo; #endif /* These are the various supported subsystems under UNIX */ -typedef enum { - SDL_SYSWM_X11 +typedef enum +{ + SDL_SYSWM_X11 } SDL_SYSWM_TYPE; /* The UNIX custom event structure */ -struct SDL_SysWMmsg { - SDL_version version; - SDL_SYSWM_TYPE subsystem; - union { - XEvent xevent; - } event; +struct SDL_SysWMmsg +{ + SDL_version version; + SDL_SYSWM_TYPE subsystem; + union + { + XEvent xevent; + } event; }; /* The UNIX custom window manager information structure. When this structure is returned, it holds information about which low level system it is using, and will be one of SDL_SYSWM_TYPE. */ -typedef struct SDL_SysWMinfo { - SDL_version version; - SDL_SYSWM_TYPE subsystem; - union { - struct { - Display *display; /* The X11 display */ - Window window; /* The X11 display window */ - /* These locking functions should be called around - any X11 functions using the display variable. - They lock the event thread, so should not be - called around event functions or from event filters. - */ - void (*lock_func)(void); - void (*unlock_func)(void); - - /* Introduced in SDL 1.0.2 */ - Window fswindow; /* The X11 fullscreen window */ - Window wmwindow; /* The X11 managed input window */ - } x11; - } info; -} SDL_SysWMinfo; +struct SDL_SysWMinfo +{ + SDL_version version; + SDL_SYSWM_TYPE subsystem; + union + { + struct + { + Display *display; /* The X11 display */ + Window window; /* The X11 display window */ + /* These locking functions should be called around + any X11 functions using the display variable. + They lock the event thread, so should not be + called around event functions or from event filters. + */ + void (*lock_func) (void); + void (*unlock_func) (void); + + /* Introduced in SDL 1.0.2 */ + Window fswindow; /* The X11 fullscreen window */ + Window wmwindow; /* The X11 managed input window */ + } x11; + } info; +}; #elif defined(SDL_VIDEO_DRIVER_NANOX) #include /* The generic custom event structure */ -struct SDL_SysWMmsg { - SDL_version version; - int data; +struct SDL_SysWMmsg +{ + SDL_version version; + int data; }; /* The windows custom window manager information structure */ -typedef struct SDL_SysWMinfo { - SDL_version version ; - GR_WINDOW_ID window ; /* The display window */ -} SDL_SysWMinfo; +struct SDL_SysWMinfo +{ + SDL_version version; + GR_WINDOW_ID window; /* The display window */ +}; -#elif defined(SDL_VIDEO_DRIVER_WINDIB) || defined(SDL_VIDEO_DRIVER_DDRAW) || defined(SDL_VIDEO_DRIVER_GAPI) +#elif defined(SDL_VIDEO_DRIVER_WIN32) #define WIN32_LEAN_AND_MEAN #include /* The windows custom event structure */ -struct SDL_SysWMmsg { - SDL_version version; - HWND hwnd; /* The window for the message */ - UINT msg; /* The type of message */ - WPARAM wParam; /* WORD message parameter */ - LPARAM lParam; /* LONG message parameter */ +struct SDL_SysWMmsg +{ + SDL_version version; + HWND hwnd; /* The window for the message */ + UINT msg; /* The type of message */ + WPARAM wParam; /* WORD message parameter */ + LPARAM lParam; /* LONG message parameter */ }; /* The windows custom window manager information structure */ -typedef struct SDL_SysWMinfo { - SDL_version version; - HWND window; /* The Win32 display window */ - HGLRC hglrc; /* The OpenGL context, if any */ -} SDL_SysWMinfo; +struct SDL_SysWMinfo +{ + SDL_version version; + HWND window; /* The Win32 display window */ + HGLRC hglrc; /* The OpenGL context, if any */ +}; #elif defined(SDL_VIDEO_DRIVER_RISCOS) /* RISC OS custom event structure */ -struct SDL_SysWMmsg { - SDL_version version; - int eventCode; /* The window for the message */ - int pollBlock[64]; +struct SDL_SysWMmsg +{ + SDL_version version; + int eventCode; /* The window for the message */ + int pollBlock[64]; }; /* The RISC OS custom window manager information structure */ -typedef struct SDL_SysWMinfo { - SDL_version version; - int wimpVersion; /* Wimp version running under */ - int taskHandle; /* The RISC OS task handle */ - int window; /* The RISC OS display window */ -} SDL_SysWMinfo; +struct SDL_SysWMinfo +{ + SDL_version version; + int wimpVersion; /* Wimp version running under */ + int taskHandle; /* The RISC OS task handle */ + int window; /* The RISC OS display window */ +}; #elif defined(SDL_VIDEO_DRIVER_PHOTON) #include #include /* The QNX custom event structure */ -struct SDL_SysWMmsg { - SDL_version version; - int data; +struct SDL_SysWMmsg +{ + SDL_version version; + int data; }; /* The QNX custom window manager information structure */ -typedef struct SDL_SysWMinfo { - SDL_version version; - int data; -} SDL_SysWMinfo; +struct SDL_SysWMinfo +{ + SDL_version version; + int data; +}; #else /* The generic custom event structure */ -struct SDL_SysWMmsg { - SDL_version version; - int data; +struct SDL_SysWMmsg +{ + SDL_version version; + int data; }; /* The generic custom window manager information structure */ -typedef struct SDL_SysWMinfo { - SDL_version version; - int data; -} SDL_SysWMinfo; +struct SDL_SysWMinfo +{ + SDL_version version; + int data; +}; #endif /* video driver type */ #endif /* SDL_PROTOTYPES_ONLY */ +typedef struct SDL_SysWMinfo SDL_SysWMinfo; + /* Function prototypes */ -/* - * This function gives you custom hooks into the window manager information. - * It fills the structure pointed to by 'info' with custom information and - * returns 1 if the function is implemented. If it's not implemented, or - * the version member of the 'info' structure is invalid, it returns 0. +/** + * \fn SDL_bool SDL_GetWindowWMInfo (SDL_WindowID windowID, SDL_SysWMinfo * info) + * + * \brief This function allows access to driver-dependent window information. + * + * \param windowID The window about which information is being requested + * \param info This structure must be initialized with the SDL version, and is then filled in with information about the given window. + * + * \return SDL_TRUE if the function is implemented and the version member of the 'info' struct is valid, SDL_FALSE otherwise. * * You typically use this function like this: + * \code * SDL_SysWMInfo info; * SDL_VERSION(&info.version); - * if ( SDL_GetWMInfo(&info) ) { ... } + * if ( SDL_GetWindowWMInfo(&info) ) { ... } + * \endcode */ -extern DECLSPEC int SDLCALL SDL_GetWMInfo(SDL_SysWMinfo *info); +extern DECLSPEC SDL_bool SDLCALL SDL_GetWindowWMInfo(SDL_WindowID windowID, + SDL_SysWMinfo * info); /* Ends C function definitions when using C++ */ #ifdef __cplusplus +/* *INDENT-OFF* */ } +/* *INDENT-ON* */ #endif #include "close_code.h" #endif /* _SDL_syswm_h */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/include/SDL_thread.h b/include/SDL_thread.h index e0a35b1ab..e0731b5e2 100644 --- a/include/SDL_thread.h +++ b/include/SDL_thread.h @@ -23,10 +23,11 @@ #ifndef _SDL_thread_h #define _SDL_thread_h -/* Header for the SDL thread management routines - - These are independent of the other SDL routines. -*/ +/** + * \file SDL_thread.h + * + * Header for the SDL thread management routines + */ #include "SDL_stdinc.h" #include "SDL_error.h" @@ -37,7 +38,9 @@ #include "begin_code.h" /* Set up for C function definitions, even when using C++ */ #ifdef __cplusplus +/* *INDENT-OFF* */ extern "C" { +/* *INDENT-ON* */ #endif /* The SDL thread structure, defined in SDL_thread.c */ @@ -61,25 +64,39 @@ typedef struct SDL_Thread SDL_Thread; */ #define SDL_PASSED_BEGINTHREAD_ENDTHREAD #ifndef _WIN32_WCE -#include /* This has _beginthread() and _endthread() defined! */ +#include /* This has _beginthread() and _endthread() defined! */ #endif #ifdef __OS2__ -typedef int (*pfnSDL_CurrentBeginThread)(void (*func)(void *), void *, unsigned, void *arg); -typedef void (*pfnSDL_CurrentEndThread)(void); +typedef int (*pfnSDL_CurrentBeginThread) (void (*func) (void *), void *, + unsigned, void *arg); +typedef void (*pfnSDL_CurrentEndThread) (void); #elif __GNUC__ -typedef unsigned long (__cdecl *pfnSDL_CurrentBeginThread) (void *, unsigned, - unsigned (__stdcall *func)(void *), void *arg, - unsigned, unsigned *threadID); -typedef void (__cdecl *pfnSDL_CurrentEndThread)(unsigned code); +typedef unsigned long (__cdecl * pfnSDL_CurrentBeginThread) (void *, unsigned, + unsigned + (__stdcall * + func) (void *), + void *arg, + unsigned, + unsigned + *threadID); +typedef void (__cdecl * pfnSDL_CurrentEndThread) (unsigned code); #else -typedef uintptr_t (__cdecl *pfnSDL_CurrentBeginThread) (void *, unsigned, - unsigned (__stdcall *func)(void *), void *arg, - unsigned, unsigned *threadID); -typedef void (__cdecl *pfnSDL_CurrentEndThread)(unsigned code); +typedef uintptr_t(__cdecl * pfnSDL_CurrentBeginThread) (void *, unsigned, + unsigned (__stdcall * + func) (void + *), + void *arg, unsigned, + unsigned *threadID); +typedef void (__cdecl * pfnSDL_CurrentEndThread) (unsigned code); #endif -extern DECLSPEC SDL_Thread * SDLCALL SDL_CreateThread(int (SDLCALL *fn)(void *), void *data, pfnSDL_CurrentBeginThread pfnBeginThread, pfnSDL_CurrentEndThread pfnEndThread); +extern DECLSPEC SDL_Thread *SDLCALL SDL_CreateThread(int (*fn) (void *), + void *data, + pfnSDL_CurrentBeginThread + pfnBeginThread, + pfnSDL_CurrentEndThread + pfnEndThread); #ifdef __OS2__ #define SDL_CreateThread(fn, data) SDL_CreateThread(fn, data, _beginthread, _endthread) @@ -89,7 +106,8 @@ extern DECLSPEC SDL_Thread * SDLCALL SDL_CreateThread(int (SDLCALL *fn)(void *), #define SDL_CreateThread(fn, data) SDL_CreateThread(fn, data, _beginthreadex, _endthreadex) #endif #else -extern DECLSPEC SDL_Thread * SDLCALL SDL_CreateThread(int (SDLCALL *fn)(void *), void *data); +extern DECLSPEC SDL_Thread *SDLCALL +SDL_CreateThread(int (SDLCALL * fn) (void *), void *data); #endif /* Get the 32-bit thread identifier for the current thread */ @@ -98,22 +116,26 @@ extern DECLSPEC Uint32 SDLCALL SDL_ThreadID(void); /* Get the 32-bit thread identifier for the specified thread, equivalent to SDL_ThreadID() if the specified thread is NULL. */ -extern DECLSPEC Uint32 SDLCALL SDL_GetThreadID(SDL_Thread *thread); +extern DECLSPEC Uint32 SDLCALL SDL_GetThreadID(SDL_Thread * thread); /* Wait for a thread to finish. The return code for the thread function is placed in the area pointed to by 'status', if 'status' is not NULL. */ -extern DECLSPEC void SDLCALL SDL_WaitThread(SDL_Thread *thread, int *status); +extern DECLSPEC void SDLCALL SDL_WaitThread(SDL_Thread * thread, int *status); /* Forcefully kill a thread without worrying about its state */ -extern DECLSPEC void SDLCALL SDL_KillThread(SDL_Thread *thread); +extern DECLSPEC void SDLCALL SDL_KillThread(SDL_Thread * thread); /* Ends C function definitions when using C++ */ #ifdef __cplusplus +/* *INDENT-OFF* */ } +/* *INDENT-ON* */ #endif #include "close_code.h" #endif /* _SDL_thread_h */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/include/SDL_timer.h b/include/SDL_timer.h index d21159fed..6c95ea48f 100644 --- a/include/SDL_timer.h +++ b/include/SDL_timer.h @@ -23,7 +23,11 @@ #ifndef _SDL_timer_h #define _SDL_timer_h -/* Header for the SDL time management routines */ +/** + * \file SDL_timer.h + * + * Header for the SDL time management routines + */ #include "SDL_stdinc.h" #include "SDL_error.h" @@ -31,25 +35,27 @@ #include "begin_code.h" /* Set up for C function definitions, even when using C++ */ #ifdef __cplusplus +/* *INDENT-OFF* */ extern "C" { +/* *INDENT-ON* */ #endif /* This is the OS scheduler timeslice, in milliseconds */ #define SDL_TIMESLICE 10 /* This is the maximum resolution of the SDL timer on all platforms */ -#define TIMER_RESOLUTION 10 /* Experimentally determined */ +#define TIMER_RESOLUTION 10 /* Experimentally determined */ /* Get the number of milliseconds since the SDL library initialization. * Note that this value wraps if the program runs for more than ~49 days. - */ + */ extern DECLSPEC Uint32 SDLCALL SDL_GetTicks(void); /* Wait a specified number of milliseconds before returning */ extern DECLSPEC void SDLCALL SDL_Delay(Uint32 ms); /* Function prototype for the timer callback function */ -typedef Uint32 (SDLCALL *SDL_TimerCallback)(Uint32 interval); +typedef Uint32(SDLCALL * SDL_TimerCallback) (Uint32 interval); /* Set a callback to run after the specified number of milliseconds has * elapsed. The callback function is passed the current timer interval @@ -79,7 +85,8 @@ typedef Uint32 (SDLCALL *SDL_TimerCallback)(Uint32 interval); * * This function returns 0 if successful, or -1 if there was an error. */ -extern DECLSPEC int SDLCALL SDL_SetTimer(Uint32 interval, SDL_TimerCallback callback); +extern DECLSPEC int SDLCALL SDL_SetTimer(Uint32 interval, + SDL_TimerCallback callback); /* New timer API, supports multiple timers * Written by Stephane Peter @@ -91,7 +98,7 @@ extern DECLSPEC int SDLCALL SDL_SetTimer(Uint32 interval, SDL_TimerCallback call * passed in, the periodic alarm continues, otherwise a new alarm is * scheduled. If the callback returns 0, the periodic alarm is cancelled. */ -typedef Uint32 (SDLCALL *SDL_NewTimerCallback)(Uint32 interval, void *param); +typedef Uint32(SDLCALL * SDL_NewTimerCallback) (Uint32 interval, void *param); /* Definition of the timer ID type */ typedef struct _SDL_TimerID *SDL_TimerID; @@ -99,7 +106,9 @@ typedef struct _SDL_TimerID *SDL_TimerID; /* Add a new timer to the pool of timers already running. Returns a timer ID, or NULL when an error occurs. */ -extern DECLSPEC SDL_TimerID SDLCALL SDL_AddTimer(Uint32 interval, SDL_NewTimerCallback callback, void *param); +extern DECLSPEC SDL_TimerID SDLCALL SDL_AddTimer(Uint32 interval, + SDL_NewTimerCallback + callback, void *param); /* Remove one of the multiple timers knowing its ID. * Returns a boolean value indicating success. @@ -108,8 +117,12 @@ extern DECLSPEC SDL_bool SDLCALL SDL_RemoveTimer(SDL_TimerID t); /* Ends C function definitions when using C++ */ #ifdef __cplusplus +/* *INDENT-OFF* */ } +/* *INDENT-ON* */ #endif #include "close_code.h" #endif /* _SDL_timer_h */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/include/SDL_version.h b/include/SDL_version.h index 262aa7b5e..fd53d0b22 100644 --- a/include/SDL_version.h +++ b/include/SDL_version.h @@ -20,7 +20,11 @@ slouken@libsdl.org */ -/* This header defines the current SDL version */ +/** + * \file SDL_version.h + * + * This header defines the current SDL version + */ #ifndef _SDL_version_h #define _SDL_version_h @@ -30,29 +34,58 @@ #include "begin_code.h" /* Set up for C function definitions, even when using C++ */ #ifdef __cplusplus +/* *INDENT-OFF* */ extern "C" { +/* *INDENT-ON* */ #endif +/** + * \struct SDL_version + * \brief Information the version of SDL in use. + * + * Represents the library's version as three levels: major revision + * (increments with massive changes, additions, and enhancements), + * minor revision (increments with backwards-compatible changes to the + * major revision), and patchlevel (increments with fixes to the minor + * revision). + * + * \sa SDL_VERSION + * \sa SDL_GetVersion + */ +typedef struct SDL_version +{ + Uint8 major; /**< major version */ + Uint8 minor; /**< minor version */ + Uint8 patch; /**< update version */ +} SDL_version; + /* Printable format: "%d.%d.%d", MAJOR, MINOR, PATCHLEVEL */ #define SDL_MAJOR_VERSION 1 -#define SDL_MINOR_VERSION 2 -#define SDL_PATCHLEVEL 11 - -typedef struct SDL_version { - Uint8 major; - Uint8 minor; - Uint8 patch; -} SDL_version; - -/* This macro can be used to fill a version structure with the compile-time - * version of the SDL library. +#define SDL_MINOR_VERSION 3 +#define SDL_PATCHLEVEL 0 + +/** + * \def SDL_VERSION(x) + * \brief Macro to determine SDL version program was compiled against. + * + * This macro fills in a SDL_version structure with the version of the + * library you compiled against. This is determined by what header the + * compiler uses. Note that if you dynamically linked the library, you might + * have a slightly newer or older version at runtime. That version can be + * determined with SDL_GetVersion(), which, unlike SDL_VERSION, + * is not a macro. + * + * \param x A pointer to a SDL_version struct to initialize. + * + * \sa SDL_version + * \sa SDL_GetVersion */ -#define SDL_VERSION(X) \ +#define SDL_VERSION(x) \ { \ - (X)->major = SDL_MAJOR_VERSION; \ - (X)->minor = SDL_MINOR_VERSION; \ - (X)->patch = SDL_PATCHLEVEL; \ + (x)->major = SDL_MAJOR_VERSION; \ + (x)->minor = SDL_MINOR_VERSION; \ + (x)->patch = SDL_PATCHLEVEL; \ } /* This macro turns the version numbers into a numeric value: @@ -70,16 +103,42 @@ typedef struct SDL_version { #define SDL_VERSION_ATLEAST(X, Y, Z) \ (SDL_COMPILEDVERSION >= SDL_VERSIONNUM(X, Y, Z)) -/* This function gets the version of the dynamically linked SDL library. - it should NOT be used to fill a version structure, instead you should - use the SDL_Version() macro. +/** + * \fn void SDL_GetVersion(SDL_version *ver) + * \brief Get the version of SDL that is linked against your program. + * + * If you are using a shared library (DLL) version of SDL, then it is + * possible that it will be different than the version you compiled against. + * + * This is a real function; the macro SDL_VERSION tells you what version + * of SDL you compiled against: + * + * \code + * SDL_version compiled; + * SDL_version linked; + * + * SDL_VERSION(&compiled); + * SDL_GetVersion(&linked); + * printf("We compiled against SDL version %d.%d.%d ...\n", + * compiled.major, compiled.minor, compiled.patch); + * printf("But we linked against SDL version %d.%d.%d.\n", + * linked.major, linked.minor, linked.patch); + * \endcode + * + * This function may be called safely at any time, even before SDL_Init(). + * + * \sa SDL_VERSION */ -extern DECLSPEC const SDL_version * SDLCALL SDL_Linked_Version(void); +extern DECLSPEC void SDLCALL SDL_GetVersion(SDL_version * ver); /* Ends C function definitions when using C++ */ #ifdef __cplusplus +/* *INDENT-OFF* */ } +/* *INDENT-ON* */ #endif #include "close_code.h" #endif /* _SDL_version_h */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/include/SDL_video.h b/include/SDL_video.h index 720022e36..a42187638 100644 --- a/include/SDL_video.h +++ b/include/SDL_video.h @@ -20,185 +20,293 @@ slouken@libsdl.org */ -/* Header file for access to the SDL raw framebuffer window */ +/** + * \file SDL_video.h + * + * Header file for access to the SDL raw framebuffer window + */ #ifndef _SDL_video_h #define _SDL_video_h #include "SDL_stdinc.h" #include "SDL_error.h" +#include "SDL_pixels.h" #include "SDL_rwops.h" #include "begin_code.h" /* Set up for C function definitions, even when using C++ */ #ifdef __cplusplus +/* *INDENT-OFF* */ extern "C" { +/* *INDENT-ON* */ #endif /* Transparency definitions: These define alpha as the opacity of a surface */ #define SDL_ALPHA_OPAQUE 255 #define SDL_ALPHA_TRANSPARENT 0 -/* Useful data types */ -typedef struct SDL_Rect { - Sint16 x, y; - Uint16 w, h; +/** + * \struct SDL_Rect + * + * \brief A rectangle, with the origin at the upper left. + */ +typedef struct SDL_Rect +{ + int x, y; + int w, h; } SDL_Rect; -typedef struct SDL_Color { - Uint8 r; - Uint8 g; - Uint8 b; - Uint8 unused; -} SDL_Color; -#define SDL_Colour SDL_Color - -typedef struct SDL_Palette { - int ncolors; - SDL_Color *colors; -} SDL_Palette; - -/* Everything in the pixel format structure is read-only */ -typedef struct SDL_PixelFormat { - SDL_Palette *palette; - Uint8 BitsPerPixel; - Uint8 BytesPerPixel; - Uint8 Rloss; - Uint8 Gloss; - Uint8 Bloss; - Uint8 Aloss; - Uint8 Rshift; - Uint8 Gshift; - Uint8 Bshift; - Uint8 Ashift; - Uint32 Rmask; - Uint32 Gmask; - Uint32 Bmask; - Uint32 Amask; - - /* RGB color key information */ - Uint32 colorkey; - /* Alpha value information (per-surface alpha) */ - Uint8 alpha; -} SDL_PixelFormat; +/** + * \struct SDL_DisplayMode + * + * \brief The structure that defines a display mode + * + * \sa SDL_GetNumDisplayModes() + * \sa SDL_GetDisplayMode() + * \sa SDL_GetDesktopDisplayMode() + * \sa SDL_GetCurrentDisplayMode() + * \sa SDL_GetClosestDisplayMode() + * \sa SDL_SetDisplayMode() + */ +typedef struct +{ + Uint32 format; /**< pixel format */ + int w; /**< width */ + int h; /**< height */ + int refresh_rate; /**< refresh rate (or zero for unspecified) */ + void *driverdata; /**< driver-specific data, initialize to 0 */ +} SDL_DisplayMode; + +/** + * \typedef SDL_WindowID + * + * \brief The type used to identify a window + * + * \sa SDL_CreateWindow() + * \sa SDL_CreateWindowFrom() + * \sa SDL_DestroyWindow() + * \sa SDL_GetWindowData() + * \sa SDL_GetWindowFlags() + * \sa SDL_GetWindowGrab() + * \sa SDL_GetWindowPosition() + * \sa SDL_GetWindowSize() + * \sa SDL_GetWindowTitle() + * \sa SDL_HideWindow() + * \sa SDL_MaximizeWindow() + * \sa SDL_MinimizeWindow() + * \sa SDL_RaiseWindow() + * \sa SDL_RestoreWindow() + * \sa SDL_SetWindowData() + * \sa SDL_SetWindowFullscreen() + * \sa SDL_SetWindowGrab() + * \sa SDL_SetWindowIcon() + * \sa SDL_SetWindowPosition() + * \sa SDL_SetWindowSize() + * \sa SDL_SetWindowTitle() + * \sa SDL_ShowWindow() + */ +typedef Uint32 SDL_WindowID; + +/** + * \enum SDL_WindowFlags + * + * \brief The flags on a window + * + * \sa SDL_GetWindowFlags() + */ +typedef enum +{ + SDL_WINDOW_FULLSCREEN = 0x00000001, /**< fullscreen window, implies borderless */ + SDL_WINDOW_OPENGL = 0x00000002, /**< window usable with OpenGL context */ + SDL_WINDOW_SHOWN = 0x00000004, /**< window is visible */ + SDL_WINDOW_BORDERLESS = 0x00000008, /**< no window decoration */ + SDL_WINDOW_RESIZABLE = 0x00000010, /**< window can be resized */ + SDL_WINDOW_MINIMIZED = 0x00000020, /**< minimized */ + SDL_WINDOW_MAXIMIZED = 0x00000040, /**< maximized */ + SDL_WINDOW_INPUT_GRABBED = 0x00000100, /**< window has grabbed input focus */ + SDL_WINDOW_INPUT_FOCUS = 0x00000200, /**< window has input focus */ + SDL_WINDOW_MOUSE_FOCUS = 0x00000400, /**< window has mouse focus */ +} SDL_WindowFlags; + +/** + * \def SDL_WINDOWPOS_UNDEFINED + * \brief Used to indicate that you don't care what the window position is. + */ +#define SDL_WINDOWPOS_UNDEFINED 0x7FFFFFF +/** + * \def SDL_WINDOWPOS_CENTERED + * \brief Used to indicate that the window position should be centered. + */ +#define SDL_WINDOWPOS_CENTERED 0x7FFFFFE + +/** + * \enum SDL_WindowEventID + * + * \brief Event subtype for window events + */ +typedef enum +{ + SDL_WINDOWEVENT_NONE, /**< Never used */ + SDL_WINDOWEVENT_SHOWN, /**< Window has been shown */ + SDL_WINDOWEVENT_HIDDEN, /**< Window has been hidden */ + SDL_WINDOWEVENT_EXPOSED, /**< Window has been exposed and should be redrawn */ + SDL_WINDOWEVENT_MOVED, /**< Window has been moved to data1,data2 */ + SDL_WINDOWEVENT_RESIZED, /**< Window size changed to data1xdata2 */ + SDL_WINDOWEVENT_MINIMIZED, /**< Window has been minimized */ + SDL_WINDOWEVENT_MAXIMIZED, /**< Window has been maximized */ + SDL_WINDOWEVENT_RESTORED, /**< Window has been restored to normal size and position */ + SDL_WINDOWEVENT_ENTER, /**< The window has gained mouse focus */ + SDL_WINDOWEVENT_LEAVE, /**< The window has lost mouse focus */ + SDL_WINDOWEVENT_FOCUS_GAINED, /**< The window has gained keyboard focus */ + SDL_WINDOWEVENT_FOCUS_LOST, /**< The window has lost keyboard focus */ + SDL_WINDOWEVENT_CLOSE, /**< The window manager requests that the window be closed */ +} SDL_WindowEventID; + +/** + * \enum SDL_RendererFlags + * + * \brief Flags used when initializing a render manager. + */ +typedef enum +{ + SDL_Renderer_PresentDiscard = 0x00000001, /**< Present leaves the contents of the backbuffer undefined */ + SDL_Renderer_PresentCopy = 0x00000002, /**< Present uses a copy from back buffer to the front buffer */ + SDL_Renderer_PresentFlip2 = 0x00000004, /**< Present uses a flip, swapping back buffer and front buffer */ + SDL_Renderer_PresentFlip3 = 0x00000008, /**< Present uses a flip, rotating between two back buffers and a front buffer */ + SDL_Renderer_PresentVSync = 0x00000010, /**< Present is synchronized with the refresh rate */ + SDL_Renderer_RenderTarget = 0x00000020, /**< The renderer can create texture render targets */ + SDL_Renderer_Accelerated = 0x00000040, /**< The renderer uses hardware acceleration */ + SDL_Renderer_ = 0x00000080, /**< The renderer uses hardware acceleration */ + SDL_Renderer_Minimal = 0x00000100, /**< The renderer only supports the read/write pixel and present functions */ +} SDL_RendererFlags; + +/** + * \struct SDL_RendererInfo + * + * \brief Information on the capabilities of a render manager. + */ +typedef struct SDL_RendererInfo +{ + const char *name; /**< The name of the renderer */ + Uint32 flags; /**< Supported SDL_RendererFlags */ + Uint32 blend_modes; /**< A mask of supported blend modes */ + Uint32 scale_modes; /**< A mask of supported scale modes */ + Uint32 num_texture_formats; /**< The number of available texture formats */ + Uint32 texture_formats[32]; /**< The available texture formats */ + int max_texture_width; /**< The maximimum texture width */ + int max_texture_height; /**< The maximimum texture height */ +} SDL_RendererInfo; + +/** + * \enum SDL_TextureAccess + * + * \brief The access pattern allowed for a texture + */ +typedef enum +{ + SDL_TextureAccess_Render, /**< Unlockable video memory, rendering allowed */ + SDL_TextureAccess_Remote, /**< Unlockable video memory */ + SDL_TextureAccess_Local, /**< Lockable system memory */ +} SDL_TextureAccess; + +/** + * \enum SDL_TextureBlendMode + * + * \brief The blend mode used in SDL_RenderCopy() + */ +typedef enum +{ + SDL_TextureBlendMode_None = 0x00000000, /**< No blending */ + SDL_TextureBlendMode_Mask = 0x00000001, /**< dst = A ? src : dst (alpha is mask) */ + SDL_TextureBlendMode_Blend = 0x00000002, /**< dst = (src * A) + (dst * (1-A)) */ + SDL_TextureBlendMode_Add = 0x00000004, /**< dst = (src * A) + dst */ + SDL_TextureBlendMode_Mod = 0x00000008, /**< dst = src * dst */ +} SDL_TextureBlendMode; + +/** + * \enum SDL_TextureScaleMode + * + * \brief The scale mode used in SDL_RenderCopy() + */ +typedef enum +{ + SDL_TextureScaleMode_None = 0x00000000, /**< No scaling, rectangles must match dimensions */ + SDL_TextureScaleMode_Fast = 0x00000001, /**< Point sampling or equivalent algorithm */ + SDL_TextureScaleMode_Slow = 0x00000002, /**< Linear filtering or equivalent algorithm */ + SDL_TextureScaleMode_Best = 0x00000004, /**< Bicubic filtering or equivalent algorithm */ +} SDL_TextureScaleMode; + +/** + * \typedef SDL_TextureID + * + * \brief An efficient driver-specific representation of pixel data + */ +typedef Uint32 SDL_TextureID; + +/** + * \typedef SDL_GLContext + * + * \brief An opaque handle to an OpenGL context. + */ +typedef void *SDL_GLContext; + + +/* These are the currently supported flags for the SDL_surface */ +/* Used internally (read-only) */ +#define SDL_HWSURFACE 0x00000001 /* Surface represents a texture */ +#define SDL_PREALLOC 0x00000002 /* Surface uses preallocated memory */ +#define SDL_SRCALPHA 0x00000004 /* Blit uses source alpha blending */ +#define SDL_SRCCOLORKEY 0x00000008 /* Blit uses a source color key */ +#define SDL_RLEACCELOK 0x00000010 /* Private flag */ +#define SDL_RLEACCEL 0x00000020 /* Surface is RLE encoded */ + +/* Evaluates to true if the surface needs to be locked before access */ +#define SDL_MUSTLOCK(S) (((S)->flags & (SDL_HWSURFACE|SDL_RLEACCEL)) != 0) /* This structure should be treated as read-only, except for 'pixels', which, if not NULL, contains the raw pixel data for the surface. */ -typedef struct SDL_Surface { - Uint32 flags; /* Read-only */ - SDL_PixelFormat *format; /* Read-only */ - int w, h; /* Read-only */ - Uint16 pitch; /* Read-only */ - void *pixels; /* Read-write */ - int offset; /* Private */ +typedef struct SDL_Surface +{ + Uint32 flags; /* Read-only */ + SDL_PixelFormat *format; /* Read-only */ + int w, h; /* Read-only */ + int pitch; /* Read-only */ + void *pixels; /* Read-write */ - /* Hardware-specific surface info */ - struct private_hwdata *hwdata; + /* texture associated with the surface, if any */ + SDL_TextureID textureID; - /* clipping information */ - SDL_Rect clip_rect; /* Read-only */ - Uint32 unused1; /* for binary compatibility */ + /* information needed for surfaces requiring locks */ + int locked; + void *lock_data; - /* Allow recursive locks */ - Uint32 locked; /* Private */ + /* clipping information */ + SDL_Rect clip_rect; /* Read-only */ - /* info for fast blit mapping to other surfaces */ - struct SDL_BlitMap *map; /* Private */ + /* info for fast blit mapping to other surfaces */ + struct SDL_BlitMap *map; /* Private */ - /* format version, bumped at every change to invalidate blit maps */ - unsigned int format_version; /* Private */ + /* format version, bumped at every change to invalidate blit maps */ + unsigned int format_version; /* Private */ - /* Reference count -- used when freeing surface */ - int refcount; /* Read-mostly */ + /* Reference count -- used when freeing surface */ + int refcount; /* Read-mostly */ } SDL_Surface; -/* These are the currently supported flags for the SDL_surface */ -/* Available for SDL_CreateRGBSurface() or SDL_SetVideoMode() */ -#define SDL_SWSURFACE 0x00000000 /* Surface is in system memory */ -#define SDL_HWSURFACE 0x00000001 /* Surface is in video memory */ -#define SDL_ASYNCBLIT 0x00000004 /* Use asynchronous blits if possible */ -/* Available for SDL_SetVideoMode() */ -#define SDL_ANYFORMAT 0x10000000 /* Allow any video depth/pixel-format */ -#define SDL_HWPALETTE 0x20000000 /* Surface has exclusive palette */ -#define SDL_DOUBLEBUF 0x40000000 /* Set up double-buffered video mode */ -#define SDL_FULLSCREEN 0x80000000 /* Surface is a full screen display */ -#define SDL_OPENGL 0x00000002 /* Create an OpenGL rendering context */ -#define SDL_OPENGLBLIT 0x0000000A /* Create an OpenGL rendering context and use it for blitting */ -#define SDL_RESIZABLE 0x00000010 /* This video mode may be resized */ -#define SDL_NOFRAME 0x00000020 /* No window caption or edge frame */ -/* Used internally (read-only) */ -#define SDL_HWACCEL 0x00000100 /* Blit uses hardware acceleration */ -#define SDL_SRCCOLORKEY 0x00001000 /* Blit uses a source color key */ -#define SDL_RLEACCELOK 0x00002000 /* Private flag */ -#define SDL_RLEACCEL 0x00004000 /* Surface is RLE encoded */ -#define SDL_SRCALPHA 0x00010000 /* Blit uses source alpha blending */ -#define SDL_PREALLOC 0x01000000 /* Surface uses preallocated memory */ +/* typedef for private surface blitting functions */ +typedef int (*SDL_blit) (struct SDL_Surface * src, SDL_Rect * srcrect, + struct SDL_Surface * dst, SDL_Rect * dstrect); -/* Evaluates to true if the surface needs to be locked before access */ -#define SDL_MUSTLOCK(surface) \ - (surface->offset || \ - ((surface->flags & (SDL_HWSURFACE|SDL_ASYNCBLIT|SDL_RLEACCEL)) != 0)) -/* typedef for private surface blitting functions */ -typedef int (*SDL_blit)(struct SDL_Surface *src, SDL_Rect *srcrect, - struct SDL_Surface *dst, SDL_Rect *dstrect); - - -/* Useful for determining the video hardware capabilities */ -typedef struct SDL_VideoInfo { - Uint32 hw_available :1; /* Flag: Can you create hardware surfaces? */ - Uint32 wm_available :1; /* Flag: Can you talk to a window manager? */ - Uint32 UnusedBits1 :6; - Uint32 UnusedBits2 :1; - Uint32 blit_hw :1; /* Flag: Accelerated blits HW --> HW */ - Uint32 blit_hw_CC :1; /* Flag: Accelerated blits with Colorkey */ - Uint32 blit_hw_A :1; /* Flag: Accelerated blits with Alpha */ - Uint32 blit_sw :1; /* Flag: Accelerated blits SW --> HW */ - Uint32 blit_sw_CC :1; /* Flag: Accelerated blits with Colorkey */ - Uint32 blit_sw_A :1; /* Flag: Accelerated blits with Alpha */ - Uint32 blit_fill :1; /* Flag: Accelerated color fill */ - Uint32 UnusedBits3 :16; - Uint32 video_mem; /* The total amount of video memory (in K) */ - SDL_PixelFormat *vfmt; /* Value: The format of the video surface */ - int current_w; /* Value: The current video mode width */ - int current_h; /* Value: The current video mode height */ -} SDL_VideoInfo; - - -/* The most common video overlay formats. - For an explanation of these pixel formats, see: - http://www.webartz.com/fourcc/indexyuv.htm - - For information on the relationship between color spaces, see: - http://www.neuro.sfc.keio.ac.jp/~aly/polygon/info/color-space-faq.html - */ -#define SDL_YV12_OVERLAY 0x32315659 /* Planar mode: Y + V + U (3 planes) */ -#define SDL_IYUV_OVERLAY 0x56555949 /* Planar mode: Y + U + V (3 planes) */ -#define SDL_YUY2_OVERLAY 0x32595559 /* Packed mode: Y0+U0+Y1+V0 (1 plane) */ -#define SDL_UYVY_OVERLAY 0x59565955 /* Packed mode: U0+Y0+V0+Y1 (1 plane) */ -#define SDL_YVYU_OVERLAY 0x55595659 /* Packed mode: Y0+V0+Y1+U0 (1 plane) */ - -/* The YUV hardware video overlay */ -typedef struct SDL_Overlay { - Uint32 format; /* Read-only */ - int w, h; /* Read-only */ - int planes; /* Read-only */ - Uint16 *pitches; /* Read-only */ - Uint8 **pixels; /* Read-write */ - - /* Hardware-specific surface info */ - struct private_yuvhwfuncs *hwfuncs; - struct private_yuvhwdata *hwdata; - - /* Special flags */ - Uint32 hw_overlay :1; /* Flag: This overlay hardware accelerated? */ - Uint32 UnusedBits :31; -} SDL_Overlay; - - -/* Public enumeration for setting the OpenGL window attributes. */ -typedef enum { +/** + * \enum SDL_GLattr + * + * \brief OpenGL configuration attributes + */ +typedef enum +{ SDL_GL_RED_SIZE, SDL_GL_GREEN_SIZE, SDL_GL_BLUE_SIZE, @@ -214,258 +322,854 @@ typedef enum { SDL_GL_STEREO, SDL_GL_MULTISAMPLEBUFFERS, SDL_GL_MULTISAMPLESAMPLES, - SDL_GL_ACCELERATED_VISUAL, - SDL_GL_SWAP_CONTROL + SDL_GL_ACCELERATED_VISUAL } SDL_GLattr; -/* flags for SDL_SetPalette() */ -#define SDL_LOGPAL 0x01 -#define SDL_PHYSPAL 0x02 /* Function prototypes */ -/* These functions are used internally, and should not be used unless you - * have a specific need to specify the video driver you want to use. - * You should normally use SDL_Init() or SDL_InitSubSystem(). +/** + * \fn int SDL_GetNumVideoDrivers(void) + * + * \brief Get the number of video drivers compiled into SDL + * + * \sa SDL_GetVideoDriver() + */ +extern DECLSPEC int SDLCALL SDL_GetNumVideoDrivers(void); + +/** + * \fn const char *SDL_GetVideoDriver(int index) + * + * \brief Get the name of a built in video driver. + * + * \note The video drivers are presented in the order in which they are + * normally checked during initialization. + * + * \sa SDL_GetNumVideoDrivers() + */ +extern DECLSPEC const char *SDLCALL SDL_GetVideoDriver(int index); + +/** + * \fn int SDL_VideoInit(const char *driver_name, Uint32 flags) + * + * \brief Initialize the video subsystem, optionally specifying a video driver. + * + * \param driver_name Initialize a specific driver by name, or NULL for the default video driver. + * \param flags FIXME: Still needed? + * + * \return 0 on success, -1 on error * - * SDL_VideoInit() initializes the video subsystem -- sets up a connection - * to the window manager, etc, and determines the current video mode and - * pixel format, but does not initialize a window or graphics mode. - * Note that event handling is activated by this routine. + * This function initializes the video subsystem; setting up a connection + * to the window manager, etc, and determines the available display modes + * and pixel formats, but does not initialize a window or graphics mode. * - * If you use both sound and video in your application, you need to call - * SDL_Init() before opening the sound device, otherwise under Win32 DirectX, - * you won't be able to set full-screen display modes. + * \sa SDL_VideoQuit() + */ +extern DECLSPEC int SDLCALL SDL_VideoInit(const char *driver_name, + Uint32 flags); + +/** + * \fn void SDL_VideoQuit(void) + * + * \brief Shuts down the video subsystem. + * + * This function closes all windows, and restores the original video mode. + * + * \sa SDL_VideoInit() */ -extern DECLSPEC int SDLCALL SDL_VideoInit(const char *driver_name, Uint32 flags); extern DECLSPEC void SDLCALL SDL_VideoQuit(void); -/* This function fills the given character buffer with the name of the - * video driver, and returns a pointer to it if the video driver has - * been initialized. It returns NULL if no driver has been initialized. +/** + * \fn const char *SDL_GetCurrentVideoDriver(void) + * + * \brief Returns the name of the currently initialized video driver. + * + * \return The name of the current video driver or NULL if no driver + * has been initialized + * + * \sa SDL_GetNumVideoDrivers() + * \sa SDL_GetVideoDriver() */ -extern DECLSPEC char * SDLCALL SDL_VideoDriverName(char *namebuf, int maxlen); +extern DECLSPEC const char *SDLCALL SDL_GetCurrentVideoDriver(void); -/* - * This function returns a pointer to the current display surface. - * If SDL is doing format conversion on the display surface, this - * function returns the publicly visible surface, not the real video - * surface. +/** + * \fn int SDL_GetNumVideoDisplays(void) + * + * \brief Returns the number of available video displays. + * + * \sa SDL_SelectVideoDisplay() */ -extern DECLSPEC SDL_Surface * SDLCALL SDL_GetVideoSurface(void); +extern DECLSPEC int SDLCALL SDL_GetNumVideoDisplays(void); -/* - * This function returns a read-only pointer to information about the - * video hardware. If this is called before SDL_SetVideoMode(), the 'vfmt' - * member of the returned structure will contain the pixel format of the - * "best" video mode. +/** + * \fn int SDL_SelectVideoDisplay(int index) + * + * \brief Set the index of the currently selected display. + * + * \return The index of the currently selected display. + * + * \note You can query the currently selected display by passing an index of -1. + * + * \sa SDL_GetNumVideoDisplays() */ -extern DECLSPEC const SDL_VideoInfo * SDLCALL SDL_GetVideoInfo(void); +extern DECLSPEC int SDLCALL SDL_SelectVideoDisplay(int index); -/* - * Check to see if a particular video mode is supported. - * It returns 0 if the requested mode is not supported under any bit depth, - * or returns the bits-per-pixel of the closest available mode with the - * given width and height. If this bits-per-pixel is different from the - * one used when setting the video mode, SDL_SetVideoMode() will succeed, - * but will emulate the requested bits-per-pixel with a shadow surface. +/** + * \fn int SDL_GetNumDisplayModes(void) + * + * \brief Returns the number of available display modes for the current display. * - * The arguments to SDL_VideoModeOK() are the same ones you would pass to - * SDL_SetVideoMode() + * \sa SDL_GetDisplayMode() */ -extern DECLSPEC int SDLCALL SDL_VideoModeOK(int width, int height, int bpp, Uint32 flags); +extern DECLSPEC int SDLCALL SDL_GetNumDisplayModes(void); -/* - * Return a pointer to an array of available screen dimensions for the - * given format and video flags, sorted largest to smallest. Returns - * NULL if there are no dimensions available for a particular format, - * or (SDL_Rect **)-1 if any dimension is okay for the given format. +/** + * \fn const SDL_DisplayMode *SDL_GetDisplayMode(int index) * - * If 'format' is NULL, the mode list will be for the format given - * by SDL_GetVideoInfo()->vfmt + * \brief Retrieve information about a specific display mode. + * + * \note The display modes are sorted in this priority: + * \li bits per pixel -> more colors to fewer colors + * \li width -> largest to smallest + * \li height -> largest to smallest + * \li refresh rate -> highest to lowest + * + * \sa SDL_GetNumDisplayModes() */ -extern DECLSPEC SDL_Rect ** SDLCALL SDL_ListModes(SDL_PixelFormat *format, Uint32 flags); +extern DECLSPEC const SDL_DisplayMode *SDLCALL SDL_GetDisplayMode(int index); -/* - * Set up a video mode with the specified width, height and bits-per-pixel. - * - * If 'bpp' is 0, it is treated as the current display bits per pixel. - * - * If SDL_ANYFORMAT is set in 'flags', the SDL library will try to set the - * requested bits-per-pixel, but will return whatever video pixel format is - * available. The default is to emulate the requested pixel format if it - * is not natively available. - * - * If SDL_HWSURFACE is set in 'flags', the video surface will be placed in - * video memory, if possible, and you may have to call SDL_LockSurface() - * in order to access the raw framebuffer. Otherwise, the video surface - * will be created in system memory. - * - * If SDL_ASYNCBLIT is set in 'flags', SDL will try to perform rectangle - * updates asynchronously, but you must always lock before accessing pixels. - * SDL will wait for updates to complete before returning from the lock. - * - * If SDL_HWPALETTE is set in 'flags', the SDL library will guarantee - * that the colors set by SDL_SetColors() will be the colors you get. - * Otherwise, in 8-bit mode, SDL_SetColors() may not be able to set all - * of the colors exactly the way they are requested, and you should look - * at the video surface structure to determine the actual palette. - * If SDL cannot guarantee that the colors you request can be set, - * i.e. if the colormap is shared, then the video surface may be created - * under emulation in system memory, overriding the SDL_HWSURFACE flag. - * - * If SDL_FULLSCREEN is set in 'flags', the SDL library will try to set - * a fullscreen video mode. The default is to create a windowed mode - * if the current graphics system has a window manager. - * If the SDL library is able to set a fullscreen video mode, this flag - * will be set in the surface that is returned. - * - * If SDL_DOUBLEBUF is set in 'flags', the SDL library will try to set up - * two surfaces in video memory and swap between them when you call - * SDL_Flip(). This is usually slower than the normal single-buffering - * scheme, but prevents "tearing" artifacts caused by modifying video - * memory while the monitor is refreshing. It should only be used by - * applications that redraw the entire screen on every update. - * - * If SDL_RESIZABLE is set in 'flags', the SDL library will allow the - * window manager, if any, to resize the window at runtime. When this - * occurs, SDL will send a SDL_VIDEORESIZE event to you application, - * and you must respond to the event by re-calling SDL_SetVideoMode() - * with the requested size (or another size that suits the application). - * - * If SDL_NOFRAME is set in 'flags', the SDL library will create a window - * without any title bar or frame decoration. Fullscreen video modes have - * this flag set automatically. - * - * This function returns the video framebuffer surface, or NULL if it fails. - * - * If you rely on functionality provided by certain video flags, check the - * flags of the returned surface to make sure that functionality is available. - * SDL will fall back to reduced functionality if the exact flags you wanted - * are not available. - */ -extern DECLSPEC SDL_Surface * SDLCALL SDL_SetVideoMode - (int width, int height, int bpp, Uint32 flags); +/** + * \fn const SDL_DisplayMode *SDL_GetDesktopDisplayMode(void) + * + * \brief Retrieve information about the desktop display mode for the current display. + */ +extern DECLSPEC const SDL_DisplayMode *SDLCALL +SDL_GetDesktopDisplayMode(void); -/* - * Makes sure the given list of rectangles is updated on the given screen. - * If 'x', 'y', 'w' and 'h' are all 0, SDL_UpdateRect will update the entire - * screen. - * These functions should not be called while 'screen' is locked. +/** + * \fn const SDL_DisplayMode *SDL_GetCurrentDisplayMode(void) + * + * \brief Retrieve information about the current display mode. */ -extern DECLSPEC void SDLCALL SDL_UpdateRects - (SDL_Surface *screen, int numrects, SDL_Rect *rects); -extern DECLSPEC void SDLCALL SDL_UpdateRect - (SDL_Surface *screen, Sint32 x, Sint32 y, Uint32 w, Uint32 h); +extern DECLSPEC const SDL_DisplayMode *SDLCALL +SDL_GetCurrentDisplayMode(void); -/* - * On hardware that supports double-buffering, this function sets up a flip - * and returns. The hardware will wait for vertical retrace, and then swap - * video buffers before the next video surface blit or lock will return. - * On hardware that doesn not support double-buffering, this is equivalent - * to calling SDL_UpdateRect(screen, 0, 0, 0, 0); - * The SDL_DOUBLEBUF flag must have been passed to SDL_SetVideoMode() when - * setting the video mode for this function to perform hardware flipping. - * This function returns 0 if successful, or -1 if there was an error. +/** + * \fn SDL_DisplayMode *SDL_GetClosestDisplayMode(const SDL_DisplayMode *mode, SDL_DisplayMode *closest) + * + * \brief Get the closest match to the requested display mode. + * + * \param mode The desired display mode + * \param closest A pointer to a display mode to be filled in with the closest match of the available display modes. + * + * \return The passed in value 'closest', or NULL if no matching video mode was available. + * + * The available display modes are scanned, and 'closest' is filled in with the closest mode matching the requested mode and returned. The mode format and refresh_rate default to the desktop mode if they are 0. The modes are scanned with size being first priority, format being second priority, and finally checking the refresh_rate. If all the available modes are too small, then NULL is returned. + * + * \sa SDL_GetNumDisplayModes() + * \sa SDL_GetDisplayMode() */ -extern DECLSPEC int SDLCALL SDL_Flip(SDL_Surface *screen); +extern DECLSPEC SDL_DisplayMode *SDLCALL SDL_GetClosestDisplayMode(const + SDL_DisplayMode + * mode, + SDL_DisplayMode + * closest); + +/** + * \fn int SDL_SetFullscreenDisplayMode(const SDL_DisplayMode *mode) + * + * \brief Set the display mode used when a fullscreen window is visible + * on the currently selected display. + * + * \param mode The mode to use, or NULL for the desktop mode. + * + * \return 0 on success, or -1 if setting the display mode failed. + * + * \sa SDL_SetWindowFullscreen() + */ +extern DECLSPEC int SDLCALL SDL_SetFullscreenDisplayMode(const SDL_DisplayMode + * mode); -/* - * Set the gamma correction for each of the color channels. - * The gamma values range (approximately) between 0.1 and 10.0 - * - * If this function isn't supported directly by the hardware, it will - * be emulated using gamma ramps, if available. If successful, this - * function returns 0, otherwise it returns -1. +/** + * \fn const SDL_DisplayMode *SDL_GetFullscreenDisplayMode(void) + * + * \brief Query the display mode used when a fullscreen window is visible + * on the currently selected display. + */ +extern DECLSPEC const SDL_DisplayMode *SDLCALL +SDL_GetFullscreenDisplayMode(void); + +/** + * \fn int SDL_SetDisplayPalette(const SDL_Color *colors, int firstcolor, int ncolors) + * + * \brief Set the palette entries for indexed display modes. + * + * \return 0 on success, or -1 if the display mode isn't palettized or the colors couldn't be set. + */ +extern DECLSPEC int SDLCALL SDL_SetDisplayPalette(const SDL_Color * colors, + int firstcolor, + int ncolors); + +/** + * \fn int SDL_GetDisplayPalette(SDL_Color *colors, int firstcolor, int ncolors) + * + * \brief Gets the palette entries for indexed display modes. + * + * \return 0 on success, or -1 if the display mode isn't palettized + */ +extern DECLSPEC int SDLCALL SDL_GetDisplayPalette(SDL_Color * colors, + int firstcolor, + int ncolors); + +/** + * \fn int SDL_SetGamma(float red, float green, float blue) + * + * \brief Set the gamma correction for each of the color channels on the currently selected display. + * + * \return 0 on success, or -1 if setting the gamma isn't supported. + * + * \sa SDL_SetGammaRamp() */ extern DECLSPEC int SDLCALL SDL_SetGamma(float red, float green, float blue); -/* +/** + * \fn int SDL_SetGammaRamp(const Uint16 * red, const Uint16 * green, const Uint16 * blue) + * + * \brief Set the gamma ramp for the currently selected display. + * + * \param red The translation table for the red channel, or NULL + * \param green The translation table for the green channel, or NULL + * \param blue The translation table for the blue channel, or NULL + * + * \return 0 on success, or -1 if gamma ramps are unsupported. + * * Set the gamma translation table for the red, green, and blue channels * of the video hardware. Each table is an array of 256 16-bit quantities, * representing a mapping between the input and output for that channel. * The input is the index into the array, and the output is the 16-bit * gamma value at that index, scaled to the output color precision. * - * You may pass NULL for any of the channels to leave it unchanged. - * If the call succeeds, it will return 0. If the display driver or - * hardware does not support gamma translation, or otherwise fails, - * this function will return -1. + * \sa SDL_GetGammaRamp() */ -extern DECLSPEC int SDLCALL SDL_SetGammaRamp(const Uint16 *red, const Uint16 *green, const Uint16 *blue); +extern DECLSPEC int SDLCALL SDL_SetGammaRamp(const Uint16 * red, + const Uint16 * green, + const Uint16 * blue); -/* - * Retrieve the current values of the gamma translation tables. +/** + * \fn int SDL_GetGammaRamp(Uint16 * red, Uint16 * green, Uint16 * blue) + * + * \brief Get the gamma ramp for the currently selected display. + * + * \param red A pointer to a 256 element array of 16-bit quantities to hold the translation table for the red channel, or NULL. + * \param green A pointer to a 256 element array of 16-bit quantities to hold the translation table for the green channel, or NULL. + * \param blue A pointer to a 256 element array of 16-bit quantities to hold the translation table for the blue channel, or NULL. * - * You must pass in valid pointers to arrays of 256 16-bit quantities. - * Any of the pointers may be NULL to ignore that channel. - * If the call succeeds, it will return 0. If the display driver or - * hardware does not support gamma translation, or otherwise fails, - * this function will return -1. + * \return 0 on success, or -1 if gamma ramps are unsupported. + * + * \sa SDL_SetGammaRamp() */ -extern DECLSPEC int SDLCALL SDL_GetGammaRamp(Uint16 *red, Uint16 *green, Uint16 *blue); +extern DECLSPEC int SDLCALL SDL_GetGammaRamp(Uint16 * red, Uint16 * green, + Uint16 * blue); -/* - * Sets a portion of the colormap for the given 8-bit surface. If 'surface' - * is not a palettized surface, this function does nothing, returning 0. - * If all of the colors were set as passed to SDL_SetColors(), it will - * return 1. If not all the color entries were set exactly as given, - * it will return 0, and you should look at the surface palette to - * determine the actual color palette. - * - * When 'surface' is the surface associated with the current display, the - * display colormap will be updated with the requested colors. If - * SDL_HWPALETTE was set in SDL_SetVideoMode() flags, SDL_SetColors() - * will always return 1, and the palette is guaranteed to be set the way - * you desire, even if the window colormap has to be warped or run under - * emulation. - */ -extern DECLSPEC int SDLCALL SDL_SetColors(SDL_Surface *surface, - SDL_Color *colors, int firstcolor, int ncolors); -/* - * Sets a portion of the colormap for a given 8-bit surface. - * 'flags' is one or both of: - * SDL_LOGPAL -- set logical palette, which controls how blits are mapped - * to/from the surface, - * SDL_PHYSPAL -- set physical palette, which controls how pixels look on - * the screen - * Only screens have physical palettes. Separate change of physical/logical - * palettes is only possible if the screen has SDL_HWPALETTE set. +/** + * \fn SDL_WindowID SDL_CreateWindow(const char *title, int x, int y, int w, int h, Uint32 flags) + * + * \brief Create a window with the specified position, dimensions, and flags. + * + * \param title The title of the window + * \param x The x position of the window + * \param y The y position of the window + * \param w The width of the window + * \param h The height of the window + * \param flags The flags for the window, a mask of any of the following: SDL_WINDOW_FULLSCREEN, SDL_WINDOW_OPENGL, SDL_WINDOW_SHOWN, SDL_WINDOW_BORDERLESS, SDL_WINDOW_RESIZABLE, SDL_WINDOW_MAXIMIZED, SDL_WINDOW_MINIMIZED, SDL_WINDOW_INPUT_GRABBED + * + * \return The id of the window created, or zero if window creation failed. + * + * \note Setting the position to -1, -1, indicates any position is fine. + * + * \sa SDL_DestroyWindow() + */ +extern DECLSPEC SDL_WindowID SDLCALL SDL_CreateWindow(const char *title, + int x, int y, int w, + int h, Uint32 flags); + +/** + * \fn SDL_WindowID SDL_CreateWindowFrom(void *data) + * + * \brief Create an SDL window struct from an existing native window. + * + * \param data A pointer to driver-dependent window creation data + * + * \return The id of the window created, or zero if window creation failed. + * + * \warning This function is NOT SUPPORTED, use at your own risk! + * + * \sa SDL_DestroyWindow() + */ +extern DECLSPEC SDL_WindowID SDLCALL SDL_CreateWindowFrom(const void *data); + +/** + * \fn Uint32 SDL_GetWindowFlags(SDL_WindowID windowID) + * + * \brief Get the window flags. + */ +extern DECLSPEC Uint32 SDLCALL SDL_GetWindowFlags(SDL_WindowID windowID); + +/** + * \fn void SDL_SetWindowTitle(SDL_WindowID windowID, const char *title) + * + * \brief Set the title of the window, in UTF-8 format. + * + * \sa SDL_GetWindowTitle() + */ +extern DECLSPEC void SDLCALL SDL_SetWindowTitle(SDL_WindowID windowID, + const char *title); + +/** + * \fn const char *SDL_GetWindowTitle(SDL_WindowID windowID) + * + * \brief Get the title of the window, in UTF-8 format. + * + * \sa SDL_SetWindowTitle() + */ +extern DECLSPEC const char *SDLCALL SDL_GetWindowTitle(SDL_WindowID windowID); + +/** + * \fn void SDL_SetWindowIcon(SDL_Surface *icon) + * + * \brief Set the icon of the window. + * + * \param icon The icon for the window + * + * FIXME: The icon needs to be set before the window is first shown. Should some icon representation be part of the window creation data? + */ +extern DECLSPEC void SDLCALL SDL_SetWindowIcon(SDL_Surface * icon); + +/** + * \fn void SDL_SetWindowData(SDL_WindowID windowID, void *userdata) + * + * \brief Associate an arbitrary pointer with the window. + * + * \sa SDL_GetWindowData() + */ +extern DECLSPEC void SDLCALL SDL_SetWindowData(SDL_WindowID windowID, + void *userdata); + +/** + * \fn void *SDL_GetWindowData(SDL_WindowID windowID) + * + * \brief Retrieve the data pointer associated with the window. + * + * \sa SDL_SetWindowData() + */ +extern DECLSPEC void *SDLCALL SDL_GetWindowData(SDL_WindowID windowID); + +/** + * \fn void SDL_SetWindowPosition(SDL_WindowID windowID, int x, int y) + * + * \brief Set the position of the window. + * + * \param windowID The window to reposition + * \param x The x coordinate of the window, SDL_WINDOWPOS_CENTERED, or SDL_WINDOWPOS_UNDEFINED + * \param y The y coordinate of the window, SDL_WINDOWPOS_CENTERED, or SDL_WINDOWPOS_UNDEFINED + * + * \note The window coordinate origin is the upper left of the display. + * + * \sa SDL_GetWindowPosition() + */ +extern DECLSPEC void SDLCALL SDL_SetWindowPosition(SDL_WindowID windowID, + int x, int y); + +/** + * \fn void SDL_GetWindowPosition(SDL_WindowID windowID, int *x, int *y) + * + * \brief Get the position of the window. + * + * \sa SDL_SetWindowPosition() + */ +extern DECLSPEC void SDLCALL SDL_GetWindowPosition(SDL_WindowID windowID, + int *x, int *y); + +/** + * \fn void SDL_SetWindowSize(SDL_WindowID windowID, int w, int w) + * + * \brief Set the size of the window's client area. + * + * \note You can't change the size of a fullscreen window, it automatically + * matches the size of the display mode. + * + * \sa SDL_GetWindowSize() + */ +extern DECLSPEC void SDLCALL SDL_SetWindowSize(SDL_WindowID windowID, int w, + int h); + +/** + * \fn void SDL_GetWindowSize(SDL_WindowID windowID, int *w, int *w) + * + * \brief Get the size of the window's client area. + * + * \sa SDL_SetWindowSize() + */ +extern DECLSPEC void SDLCALL SDL_GetWindowSize(SDL_WindowID windowID, int *w, + int *h); + +/** + * \fn void SDL_ShowWindow(SDL_WindowID windowID) + * + * \brief Show the window + * + * \sa SDL_HideWindow() + */ +extern DECLSPEC void SDLCALL SDL_ShowWindow(SDL_WindowID windowID); + +/** + * \fn void SDL_HideWindow(SDL_WindowID windowID) + * + * \brief Hide the window + * + * \sa SDL_ShowWindow() + */ +extern DECLSPEC void SDLCALL SDL_HideWindow(SDL_WindowID windowID); + +/** + * \fn void SDL_RaiseWindow(SDL_WindowID windowID) + * + * \brief Raise the window above other windows and set the input focus. + */ +extern DECLSPEC void SDLCALL SDL_RaiseWindow(SDL_WindowID windowID); + +/** + * \fn void SDL_MaximizeWindow(SDL_WindowID windowID) + * + * \brief Make the window as large as possible. + * + * \sa SDL_RestoreWindow() + */ +extern DECLSPEC void SDLCALL SDL_MaximizeWindow(SDL_WindowID windowID); + +/** + * \fn void SDL_MinimizeWindow(SDL_WindowID windowID) + * + * \brief Minimize the window to an iconic representation. + * + * \sa SDL_RestoreWindow() + */ +extern DECLSPEC void SDLCALL SDL_MinimizeWindow(SDL_WindowID windowID); + +/** + * \fn void SDL_RestoreWindow(SDL_WindowID windowID) + * + * \brief Restore the size and position of a minimized or maximized window. + * + * \sa SDL_MaximizeWindow() + * \sa SDL_MinimizeWindow() + */ +extern DECLSPEC void SDLCALL SDL_RestoreWindow(SDL_WindowID windowID); + +/** + * \fn int SDL_SetWindowFullscreen(SDL_WindowID windowID, int fullscreen) + * + * \brief Set the window's fullscreen state. + * + * \return 0 on success, or -1 if setting the display mode failed. + * + * \sa SDL_SetFullscreenDisplayMode() + */ +extern DECLSPEC int SDLCALL SDL_SetWindowFullscreen(SDL_WindowID windowID, + int fullscreen); + +/** + * \fn void SDL_SetWindowGrab(SDL_WindowID windowID, int mode) * - * The return value is 1 if all colours could be set as requested, and 0 - * otherwise. + * \brief Set the window's input grab mode. * - * SDL_SetColors() is equivalent to calling this function with - * flags = (SDL_LOGPAL|SDL_PHYSPAL). + * \param mode This is 1 to grab input, and 0 to release input. + * + * \sa SDL_GetWindowGrab() + */ +extern DECLSPEC void SDLCALL SDL_SetWindowGrab(SDL_WindowID windowID, + int mode); + +/** + * \fn int SDL_GetWindowGrab(SDL_WindowID windowID) + * + * \brief Get the window's input grab mode. + * + * \return This returns 1 if input is grabbed, and 0 otherwise. + * + * \sa SDL_SetWindowGrab() + */ +extern DECLSPEC int SDLCALL SDL_GetWindowGrab(SDL_WindowID windowID); + +/** + * \fn SDL_bool SDL_GetWindowWMInfo(SDL_WindowID windowID, struct SDL_SysWMinfo * info) + * + * \brief Get driver specific information about a window. + * + * \note Include SDL_syswm.h for the declaration of SDL_SysWMinfo. + */ +struct SDL_SysWMinfo; +extern DECLSPEC SDL_bool SDLCALL SDL_GetWindowWMInfo(SDL_WindowID windowID, + struct SDL_SysWMinfo + *info); + +/** + * \fn void SDL_DestroyWindow(SDL_WindowID windowID) + * + * \brief Destroy a window. + */ +extern DECLSPEC void SDLCALL SDL_DestroyWindow(SDL_WindowID windowID); + +/** + * \fn int SDL_GetNumRenderers(void) + * + * \brief Get the number of render managers on the current display. + * + * A render manager is a set of code that handles rendering and texture + * management on a particular display. Normally there is only one, but + * some drivers may have several available with different capabilities. + * + * \sa SDL_GetRendererInfo() + * \sa SDL_CreateRenderer() + */ +extern DECLSPEC int SDLCALL SDL_GetNumRenderers(void); + +/** + * \fn SDL_RendererInfo *SDL_GetRendererInfo(int index) + * + * \brief Get information about a specific render manager on the current + * display. + * + * \sa SDL_CreateRenderer() + */ +extern DECLSPEC int SDLCALL SDL_GetRendererInfo(int index, + SDL_RendererInfo * info); + +/** + * \fn int SDL_CreateRenderer(SDL_WindowID window, int index, Uint32 flags) + * + * \brief Create and make active a 2D rendering context for a window. + * + * \param windowID The window used for rendering + * \param index The index of the render manager to initialize, or -1 to initialize the first one supporting the requested flags. + * \param flags SDL_RendererFlags + * + * \return 0 on success, -1 if the flags were not supported, or -2 if + * there isn't enough memory to support the requested flags + * + * \sa SDL_SelectRenderer() + * \sa SDL_DestroyRenderer() + */ +extern DECLSPEC int SDLCALL SDL_CreateRenderer(SDL_WindowID windowID, + int index, Uint32 flags); + +/** + * \fn int SDL_SelectRenderer(SDL_WindowID windowID) + * + * \brief Select the rendering context for a particular window. + * + * \return 0 on success, -1 if the selected window doesn't have a + * rendering context. + */ +extern DECLSPEC int SDLCALL SDL_SelectRenderer(SDL_WindowID windowID); + +/** + * \fn SDL_TextureID SDL_CreateTexture(Uint32 format, int access, int w, int h) + * + * \brief Create a texture for the current rendering context. + * + * \param format The format of the texture + * \param access One of the enumerated values in SDL_TextureAccess + * \param w The width of the texture in pixels + * \param h The height of the texture in pixels + * + * \return The created texture is returned, or 0 if no render manager was active, the format was unsupported, or the width or height were out of range. + * + * \sa SDL_QueryTexture() + * \sa SDL_DestroyTexture() + */ +extern DECLSPEC SDL_TextureID SDLCALL SDL_CreateTexture(Uint32 format, + int access, int w, + int h); + +/** + * \fn SDL_TextureID SDL_CreateTextureFromSurface(Uint32 format, int access, SDL_Surface *surface) + * + * \brief Create a texture from an existing surface. + * + * \param format The format of the texture, or 0 to pick an appropriate format + * \param access One of the enumerated values in SDL_TextureAccess + * \param surface The surface containing pixel data used to fill the texture + * + * \return The created texture is returned, or 0 if no render manager was active, the format was unsupported, or the surface width or height were out of range. + * + * \note The surface is not modified or freed by this function. + * + * \sa SDL_QueryTexture() + * \sa SDL_DestroyTexture() + */ +extern DECLSPEC SDL_TextureID SDLCALL SDL_CreateTextureFromSurface(Uint32 + format, + int access, + SDL_Surface + * surface); + +/** + * \fn int SDL_QueryTexture(SDL_TextureID textureID, Uint32 *format, int *access, int *w, int *h) + * + * \brief Query the attributes of a texture + * + * \param texture A texture to be queried + * \param format A pointer filled in with the raw format of the texture. The actual format may differ, but pixel transfers will use this format. + * \param access A pointer filled in with the actual access to the texture. + * \param w A pointer filled in with the width of the texture in pixels + * \param h A pointer filled in with the height of the texture in pixels + * + * \return 0 on success, or -1 if the texture is not valid + */ +extern DECLSPEC int SDLCALL SDL_QueryTexture(SDL_TextureID textureID, + Uint32 * format, int *access, + int *w, int *h); + +/** + * \fn int SDL_QueryTexturePixels(SDL_TextureID textureID, void **pixels, int pitch) + * + * \brief Query the pixels of a texture, if the texture does not need to be locked for pixel access. + * + * \param texture A texture to be queried, which was created with SDL_TextureAccess_Local + * \param pixels A pointer filled with a pointer to the pixels for the texture + * \param pitch A pointer filled in with the pitch of the pixel data + * + * \return 0 on success, or -1 if the texture is not valid, or must be locked for pixel access. + */ +extern DECLSPEC int SDLCALL SDL_QueryTexturePixels(SDL_TextureID textureID, + void **pixels, int *pitch); + +/** + * \fn int SDL_SetTexturePalette(SDL_TextureID textureID, const SDL_Color * colors, int firstcolor, int ncolors) + * + * \brief Update an indexed texture with a color palette + * + * \param texture The texture to update + * \param colors The array of RGB color data + * \param firstcolor The first index to update + * \param ncolors The number of palette entries to fill with the color data + * + * \return 0 on success, or -1 if the texture is not valid or not an indexed texture + */ +extern DECLSPEC int SDLCALL SDL_SetTexturePalette(SDL_TextureID textureID, + const SDL_Color * colors, + int firstcolor, + int ncolors); + +/** + * \fn int SDL_GetTexturePalette(SDL_TextureID textureID, SDL_Color * colors, int firstcolor, int ncolors) + * + * \brief Update an indexed texture with a color palette + * + * \param texture The texture to update + * \param colors The array to fill with RGB color data + * \param firstcolor The first index to retrieve + * \param ncolors The number of palette entries to retrieve + * + * \return 0 on success, or -1 if the texture is not valid or not an indexed texture + */ +extern DECLSPEC int SDLCALL SDL_GetTexturePalette(SDL_TextureID textureID, + SDL_Color * colors, + int firstcolor, + int ncolors); + +/** + * \fn int SDL_UpdateTexture(SDL_TextureID textureID, const SDL_Rect *rect, const void *pixels, int pitch) + * + * \brief Update the given texture rectangle with new pixel data. + * + * \param texture The texture to update + * \param rect A pointer to the rectangle of pixels to update, or NULL to update the entire texture. + * \param pixels The raw pixel data + * \param pitch The number of bytes between rows of pixel data + * + * \return 0 on success, or -1 if the texture is not valid + * + * \note This is a very slow function for textures not created with SDL_TextureAccess_Local. + */ +extern DECLSPEC int SDLCALL SDL_UpdateTexture(SDL_TextureID textureID, + const SDL_Rect * rect, + const void *pixels, int pitch); + +/** + * \fn void SDL_LockTexture(SDL_TextureID textureID, const SDL_Rect *rect, int markDirty, void **pixels, int *pitch) + * + * \brief Lock a portion of the texture for pixel access. + * + * \param texture The texture to lock for access, which must have been created with SDL_TextureAccess_Local. + * \param rect A pointer to the rectangle to lock for access. If the rect is NULL, the entire texture will be locked. + * \param markDirty If this is nonzero, the locked area will be marked dirty when the texture is unlocked. + * \param pixels This is filled in with a pointer to the locked pixels, appropriately offset by the locked area. + * \param pitch This is filled in with the pitch of the locked pixels. + * + * \return 0 on success, or -1 if the texture is not valid or was created with SDL_TextureAccess_Remote + * + * \sa SDL_DirtyTexture() + * \sa SDL_UnlockTexture() + */ +extern DECLSPEC int SDLCALL SDL_LockTexture(SDL_TextureID textureID, + const SDL_Rect * rect, + int markDirty, void **pixels, + int *pitch); + +/** + * \fn void SDL_UnlockTexture(SDL_TextureID textureID) + * + * \brief Unlock a texture, uploading the changes to video memory, if needed. + * + * \sa SDL_LockTexture() + * \sa SDL_DirtyTexture() + */ +extern DECLSPEC void SDLCALL SDL_UnlockTexture(SDL_TextureID textureID); + +/** + * \fn void SDL_DirtyTexture(SDL_TextureID textureID, int numrects, const SDL_Rect * rects) + * + * \brief Mark the specified rectangles of the texture as dirty. + * + * \note The texture must have been created with SDL_TextureAccess_Local. + * + * \sa SDL_LockTexture() + * \sa SDL_UnlockTexture() + */ +extern DECLSPEC void SDLCALL SDL_DirtyTexture(SDL_TextureID textureID, + int numrects, + const SDL_Rect * rects); + +/** + * \fn void SDL_SelectRenderTexture(SDL_TextureID textureID) + * + * \brief Select a texture as the rendering target, or 0 to reselect the current window. + * + * \note The texture must have been created with SDL_TextureAccess_Render. + */ +extern DECLSPEC void SDLCALL SDL_SelectRenderTexture(SDL_TextureID textureID); + +/** + * \fn void SDL_RenderFill(const SDL_Rect *rect, Uint32 color) + * + * \brief Fill the current rendering target with the specified color. + * + * \param rect A pointer to the destination rectangle, or NULL for the entire rendering target. + * \param color An ARGB color value. + * + * \return 0 on success, or -1 if there is no renderer current + */ +extern DECLSPEC int SDLCALL SDL_RenderFill(const SDL_Rect * rect, + Uint32 color); + +/** + * \fn int SDL_RenderCopy(SDL_TextureID textureID, const SDL_Rect *srcrect, const SDL_Rect *dstrect, Uint32 blendMode, Uint32 scaleMode) + * + * \brief Copy a portion of the texture to the current rendering target. + * + * \param texture The source texture. + * \param srcrect A pointer to the source rectangle, or NULL for the entire texture. + * \param dstrect A pointer to the destination rectangle, or NULL for the entire rendering target. + * \param blendMode SDL_TextureBlendMode to be used if the source texture has an alpha channel. + * \param scaleMode SDL_TextureScaleMode to be used if the source and destination rectangles don't have the same width and height. + * + * \return 0 on success, or -1 if there is no renderer current, or the driver doesn't support the requested operation. + * + * \note You can check the video driver info to see what operations are supported. + */ +extern DECLSPEC int SDLCALL SDL_RenderCopy(SDL_TextureID textureID, + const SDL_Rect * srcrect, + const SDL_Rect * dstrect, + int blendMode, int scaleMode); + +/** + * \fn int SDL_RenderReadPixels(const SDL_Rect *rect, void *pixels, int pitch) + * + * \brief Read pixels from the current rendering target. + * + * \param rect A pointer to the rectangle to read, or NULL for the entire render target + * \param pixels A pointer to be filled in with the pixel data + * \param pitch The pitch of the pixels parameter + * + * \return 0 on success, or -1 if pixel reading is not supported. + * + * \warning This is a very slow operation, and should not be used frequently. + */ +extern DECLSPEC int SDLCALL SDL_RenderReadPixels(const SDL_Rect * rect, + void *pixels, int pitch); + +/** + * \fn int SDL_RenderWritePixels(const SDL_Rect *rect, const void *pixels, int pitch) + * + * \brief Write pixels to the current rendering target. + * + * \param rect A pointer to the rectangle to write, or NULL for the entire render target + * \param pixels A pointer to the pixel data to write + * \param pitch The pitch of the pixels parameter + * + * \return 0 on success, or -1 if pixel writing is not supported. + * + * \warning This is a very slow operation, and should not be used frequently. + */ +extern DECLSPEC int SDLCALL SDL_RenderWritePixels(const SDL_Rect * rect, + const void *pixels, + int pitch); + +/** + * \fn void SDL_RenderPresent(void) + * + * \brief Update the screen with rendering performed. + */ +extern DECLSPEC void SDLCALL SDL_RenderPresent(void); + +/** + * \fn void SDL_DestroyTexture(SDL_TextureID textureID); + * + * \brief Destroy the specified texture. + * + * \sa SDL_CreateTexture() + * \sa SDL_CreateTextureFromSurface() */ -extern DECLSPEC int SDLCALL SDL_SetPalette(SDL_Surface *surface, int flags, - SDL_Color *colors, int firstcolor, - int ncolors); +extern DECLSPEC void SDLCALL SDL_DestroyTexture(SDL_TextureID textureID); + +/** + * \fn void SDL_DestroyRenderer(SDL_WindowID windowID); + * + * \brief Destroy the rendering context for a window and free associated + * textures. + * + * \sa SDL_CreateRenderer() + */ +extern DECLSPEC void SDLCALL SDL_DestroyRenderer(SDL_WindowID windowID); /* * Maps an RGB triple to an opaque pixel value for a given pixel format */ extern DECLSPEC Uint32 SDLCALL SDL_MapRGB - (SDL_PixelFormat *format, Uint8 r, Uint8 g, Uint8 b); + (SDL_PixelFormat * format, Uint8 r, Uint8 g, Uint8 b); /* * Maps an RGBA quadruple to a pixel value for a given pixel format */ -extern DECLSPEC Uint32 SDLCALL SDL_MapRGBA(SDL_PixelFormat *format, - Uint8 r, Uint8 g, Uint8 b, Uint8 a); +extern DECLSPEC Uint32 SDLCALL SDL_MapRGBA(SDL_PixelFormat * format, + Uint8 r, Uint8 g, Uint8 b, + Uint8 a); /* * Maps a pixel value into the RGB components for a given pixel format */ -extern DECLSPEC void SDLCALL SDL_GetRGB(Uint32 pixel, SDL_PixelFormat *fmt, - Uint8 *r, Uint8 *g, Uint8 *b); +extern DECLSPEC void SDLCALL SDL_GetRGB(Uint32 pixel, SDL_PixelFormat * fmt, + Uint8 * r, Uint8 * g, Uint8 * b); /* * Maps a pixel value into the RGBA components for a given pixel format */ -extern DECLSPEC void SDLCALL SDL_GetRGBA(Uint32 pixel, SDL_PixelFormat *fmt, - Uint8 *r, Uint8 *g, Uint8 *b, Uint8 *a); +extern DECLSPEC void SDLCALL SDL_GetRGBA(Uint32 pixel, SDL_PixelFormat * fmt, + Uint8 * r, Uint8 * g, Uint8 * b, + Uint8 * a); /* * Allocate and free an RGB surface (must be called after SDL_SetVideoMode) @@ -475,40 +1179,36 @@ extern DECLSPEC void SDLCALL SDL_GetRGBA(Uint32 pixel, SDL_PixelFormat *fmt, * If the function runs out of memory, it will return NULL. * * The 'flags' tell what kind of surface to create. - * SDL_SWSURFACE means that the surface should be created in system memory. - * SDL_HWSURFACE means that the surface should be created in video memory, - * with the same format as the display surface. This is useful for surfaces - * that will not change much, to take advantage of hardware acceleration - * when being blitted to the display surface. - * SDL_ASYNCBLIT means that SDL will try to perform asynchronous blits with - * this surface, but you must always lock it before accessing the pixels. - * SDL will wait for current blits to finish before returning from the lock. * SDL_SRCCOLORKEY indicates that the surface will be used for colorkey blits. - * If the hardware supports acceleration of colorkey blits between - * two surfaces in video memory, SDL will try to place the surface in - * video memory. If this isn't possible or if there is no hardware - * acceleration available, the surface will be placed in system memory. - * SDL_SRCALPHA means that the surface will be used for alpha blits and - * if the hardware supports hardware acceleration of alpha blits between - * two surfaces in video memory, to place the surface in video memory - * if possible, otherwise it will be placed in system memory. - * If the surface is created in video memory, blits will be _much_ faster, - * but the surface format must be identical to the video surface format, - * and the only way to access the pixels member of the surface is to use - * the SDL_LockSurface() and SDL_UnlockSurface() calls. - * If the requested surface actually resides in video memory, SDL_HWSURFACE - * will be set in the flags member of the returned surface. If for some - * reason the surface could not be placed in video memory, it will not have - * the SDL_HWSURFACE flag set, and will be created in system memory instead. - */ -#define SDL_AllocSurface SDL_CreateRGBSurface -extern DECLSPEC SDL_Surface * SDLCALL SDL_CreateRGBSurface - (Uint32 flags, int width, int height, int depth, - Uint32 Rmask, Uint32 Gmask, Uint32 Bmask, Uint32 Amask); -extern DECLSPEC SDL_Surface * SDLCALL SDL_CreateRGBSurfaceFrom(void *pixels, - int width, int height, int depth, int pitch, - Uint32 Rmask, Uint32 Gmask, Uint32 Bmask, Uint32 Amask); -extern DECLSPEC void SDLCALL SDL_FreeSurface(SDL_Surface *surface); + * SDL_SRCALPHA means that the surface will be used for alpha blits. + */ +extern DECLSPEC SDL_Surface *SDLCALL SDL_CreateRGBSurface + (Uint32 flags, int width, int height, int depth, + Uint32 Rmask, Uint32 Gmask, Uint32 Bmask, Uint32 Amask); +extern DECLSPEC SDL_Surface *SDLCALL SDL_CreateRGBSurfaceFrom(void *pixels, + int width, + int height, + int depth, + int pitch, + Uint32 Rmask, + Uint32 Gmask, + Uint32 Bmask, + Uint32 Amask); +extern DECLSPEC SDL_Surface *SDLCALL +SDL_CreateRGBSurfaceFromTexture(SDL_TextureID textureID); +extern DECLSPEC void SDLCALL SDL_FreeSurface(SDL_Surface * surface); + +/** + * \fn int SDL_SetSurfacePalette(SDL_Surface *surface, SDL_Palette *palette) + * + * \brief Set the palette used by a surface. + * + * \return 0, or -1 if the surface format doesn't use a palette. + * + * \note A single palette can be shared with many surfaces. + */ +extern DECLSPEC int SDLCALL SDL_SetSurfacePalette(SDL_Surface * surface, + SDL_Palette * palette); /* * SDL_LockSurface() sets up a surface for directly accessing the pixels. @@ -519,17 +1219,15 @@ extern DECLSPEC void SDLCALL SDL_FreeSurface(SDL_Surface *surface); * * Not all surfaces require locking. If SDL_MUSTLOCK(surface) evaluates * to 0, then you can read and write to the surface at any time, and the - * pixel format of the surface will not change. In particular, if the - * SDL_HWSURFACE flag is not given when calling SDL_SetVideoMode(), you - * will not need to lock the display surface before accessing it. + * pixel format of the surface will not change. * * No operating system or library calls should be made between lock/unlock * pairs, as critical system locks may be held during this time. * * SDL_LockSurface() returns 0, or -1 if the surface couldn't be locked. */ -extern DECLSPEC int SDLCALL SDL_LockSurface(SDL_Surface *surface); -extern DECLSPEC void SDLCALL SDL_UnlockSurface(SDL_Surface *surface); +extern DECLSPEC int SDLCALL SDL_LockSurface(SDL_Surface * surface); +extern DECLSPEC void SDLCALL SDL_UnlockSurface(SDL_Surface * surface); /* * Load a surface from a seekable SDL data source (memory or file.) @@ -537,7 +1235,8 @@ extern DECLSPEC void SDLCALL SDL_UnlockSurface(SDL_Surface *surface); * Returns the new surface, or NULL if there was an error. * The new surface should be freed with SDL_FreeSurface(). */ -extern DECLSPEC SDL_Surface * SDLCALL SDL_LoadBMP_RW(SDL_RWops *src, int freesrc); +extern DECLSPEC SDL_Surface *SDLCALL SDL_LoadBMP_RW(SDL_RWops * src, + int freesrc); /* Convenience macro -- load a surface from a file */ #define SDL_LoadBMP(file) SDL_LoadBMP_RW(SDL_RWFromFile(file, "rb"), 1) @@ -548,7 +1247,7 @@ extern DECLSPEC SDL_Surface * SDLCALL SDL_LoadBMP_RW(SDL_RWops *src, int freesrc * Returns 0 if successful or -1 if there was an error. */ extern DECLSPEC int SDLCALL SDL_SaveBMP_RW - (SDL_Surface *surface, SDL_RWops *dst, int freedst); + (SDL_Surface * surface, SDL_RWops * dst, int freedst); /* Convenience macro -- save a surface to a file */ #define SDL_SaveBMP(surface, file) \ @@ -564,7 +1263,7 @@ extern DECLSPEC int SDLCALL SDL_SaveBMP_RW * This function returns 0, or -1 if there was an error. */ extern DECLSPEC int SDLCALL SDL_SetColorKey - (SDL_Surface *surface, Uint32 flag, Uint32 key); + (SDL_Surface * surface, Uint32 flag, Uint32 key); /* * This function sets the alpha value for the entire surface, as opposed to @@ -581,7 +1280,8 @@ extern DECLSPEC int SDLCALL SDL_SetColorKey * * The 'alpha' parameter is ignored for surfaces that have an alpha channel. */ -extern DECLSPEC int SDLCALL SDL_SetAlpha(SDL_Surface *surface, Uint32 flag, Uint8 alpha); +extern DECLSPEC int SDLCALL SDL_SetAlpha(SDL_Surface * surface, Uint32 flag, + Uint8 alpha); /* * Sets the clipping rectangle for the destination surface in a blit. @@ -595,14 +1295,16 @@ extern DECLSPEC int SDLCALL SDL_SetAlpha(SDL_Surface *surface, Uint32 flag, Uint * Note that blits are automatically clipped to the edges of the source * and destination surfaces. */ -extern DECLSPEC SDL_bool SDLCALL SDL_SetClipRect(SDL_Surface *surface, const SDL_Rect *rect); +extern DECLSPEC SDL_bool SDLCALL SDL_SetClipRect(SDL_Surface * surface, + const SDL_Rect * rect); /* * Gets the clipping rectangle for the destination surface in a blit. * 'rect' must be a pointer to a valid rectangle which will be filled * with the correct values. */ -extern DECLSPEC void SDLCALL SDL_GetClipRect(SDL_Surface *surface, SDL_Rect *rect); +extern DECLSPEC void SDLCALL SDL_GetClipRect(SDL_Surface * surface, + SDL_Rect * rect); /* * Creates a new surface of the specified format, and then copies and maps @@ -616,8 +1318,20 @@ extern DECLSPEC void SDLCALL SDL_GetClipRect(SDL_Surface *surface, SDL_Rect *rec * * This function is used internally by SDL_DisplayFormat(). */ -extern DECLSPEC SDL_Surface * SDLCALL SDL_ConvertSurface - (SDL_Surface *src, SDL_PixelFormat *fmt, Uint32 flags); +extern DECLSPEC SDL_Surface *SDLCALL SDL_ConvertSurface + (SDL_Surface * src, SDL_PixelFormat * fmt, Uint32 flags); + +/* + * This function performs a fast fill of the given rectangle with 'color' + * The given rectangle is clipped to the destination surface clip area + * and the final fill rectangle is saved in the passed in pointer. + * If 'dstrect' is NULL, the whole surface will be filled with 'color' + * The color should be a pixel of the format used by the surface, and + * can be generated by the SDL_MapRGB() function. + * This function returns 0 on success, or -1 on error. + */ +extern DECLSPEC int SDLCALL SDL_FillRect + (SDL_Surface * dst, SDL_Rect * dstrect, Uint32 color); /* * This performs a fast blit from the source surface to the destination @@ -694,196 +1408,177 @@ extern DECLSPEC SDL_Surface * SDLCALL SDL_ConvertSurface rectangle validation and clipping before passing it to SDL_LowerBlit() */ extern DECLSPEC int SDLCALL SDL_UpperBlit - (SDL_Surface *src, SDL_Rect *srcrect, - SDL_Surface *dst, SDL_Rect *dstrect); + (SDL_Surface * src, SDL_Rect * srcrect, + SDL_Surface * dst, SDL_Rect * dstrect); /* This is a semi-private blit function and it performs low-level surface blitting only. */ extern DECLSPEC int SDLCALL SDL_LowerBlit - (SDL_Surface *src, SDL_Rect *srcrect, - SDL_Surface *dst, SDL_Rect *dstrect); - -/* - * This function performs a fast fill of the given rectangle with 'color' - * The given rectangle is clipped to the destination surface clip area - * and the final fill rectangle is saved in the passed in pointer. - * If 'dstrect' is NULL, the whole surface will be filled with 'color' - * The color should be a pixel of the format used by the surface, and - * can be generated by the SDL_MapRGB() function. - * This function returns 0 on success, or -1 on error. - */ -extern DECLSPEC int SDLCALL SDL_FillRect - (SDL_Surface *dst, SDL_Rect *dstrect, Uint32 color); + (SDL_Surface * src, SDL_Rect * srcrect, + SDL_Surface * dst, SDL_Rect * dstrect); -/* - * This function takes a surface and copies it to a new surface of the - * pixel format and colors of the video framebuffer, suitable for fast - * blitting onto the display surface. It calls SDL_ConvertSurface() +/** + * \fn int SDL_SoftStretch(SDL_Surface * src, SDL_Rect * srcrect, SDL_Surface * dst, SDL_Rect * dstrect) * - * If you want to take advantage of hardware colorkey or alpha blit - * acceleration, you should set the colorkey and alpha value before - * calling this function. + * \brief Perform a fast, low quality, stretch blit between two surfaces of the same pixel format. * - * If the conversion fails or runs out of memory, it returns NULL + * \note This function uses a static buffer, and is not thread-safe. */ -extern DECLSPEC SDL_Surface * SDLCALL SDL_DisplayFormat(SDL_Surface *surface); - -/* - * This function takes a surface and copies it to a new surface of the - * pixel format and colors of the video framebuffer (if possible), - * suitable for fast alpha blitting onto the display surface. - * The new surface will always have an alpha channel. - * - * If you want to take advantage of hardware colorkey or alpha blit - * acceleration, you should set the colorkey and alpha value before - * calling this function. - * - * If the conversion fails or runs out of memory, it returns NULL - */ -extern DECLSPEC SDL_Surface * SDLCALL SDL_DisplayFormatAlpha(SDL_Surface *surface); - +extern DECLSPEC int SDLCALL SDL_SoftStretch(SDL_Surface * src, + SDL_Rect * srcrect, + SDL_Surface * dst, + SDL_Rect * dstrect); /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ -/* YUV video surface overlay functions */ +/* OpenGL support functions. */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ -/* This function creates a video output overlay - Calling the returned surface an overlay is something of a misnomer because - the contents of the display surface underneath the area where the overlay - is shown is undefined - it may be overwritten with the converted YUV data. -*/ -extern DECLSPEC SDL_Overlay * SDLCALL SDL_CreateYUVOverlay(int width, int height, - Uint32 format, SDL_Surface *display); - -/* Lock an overlay for direct access, and unlock it when you are done */ -extern DECLSPEC int SDLCALL SDL_LockYUVOverlay(SDL_Overlay *overlay); -extern DECLSPEC void SDLCALL SDL_UnlockYUVOverlay(SDL_Overlay *overlay); - -/* Blit a video overlay to the display surface. - The contents of the video surface underneath the blit destination are - not defined. - The width and height of the destination rectangle may be different from - that of the overlay, but currently only 2x scaling is supported. -*/ -extern DECLSPEC int SDLCALL SDL_DisplayYUVOverlay(SDL_Overlay *overlay, SDL_Rect *dstrect); +/** + * \fn int SDL_GL_LoadLibrary(const char *path) + * + * \brief Dynamically load an OpenGL library. + * + * \param path The platform dependent OpenGL library name, or NULL to open the default OpenGL library + * + * \return 0 on success, or -1 if the library couldn't be loaded + * + * \note If you do this, you need to retrieve all of the GL functions used in + * your program from the dynamic library using SDL_GL_GetProcAddress(). + * + * \sa SDL_GL_GetProcAddress() + */ +extern DECLSPEC int SDLCALL SDL_GL_LoadLibrary(const char *path); -/* Free a video overlay */ -extern DECLSPEC void SDLCALL SDL_FreeYUVOverlay(SDL_Overlay *overlay); +/** + * \fn void *SDL_GL_GetProcAddress(const char *proc) + * + * \brief Get the address of an OpenGL function. + */ +extern DECLSPEC void *SDLCALL SDL_GL_GetProcAddress(const char *proc); +/** + * \fn int SDL_GL_SetAttribute(SDL_GLattr attr, int value) + * + * \brief Set an OpenGL window attribute before window creation. + */ +extern DECLSPEC int SDLCALL SDL_GL_SetAttribute(SDL_GLattr attr, int value); -/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ -/* OpenGL support functions. */ -/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +/** + * \fn int SDL_GL_GetWindowAttribute(SDL_WindowID windowID, SDL_GLattr attr, int *value) + * + * \brief Get the actual value for an OpenGL window attribute. + */ +extern DECLSPEC int SDLCALL SDL_GL_GetWindowAttribute(SDL_WindowID windowID, + SDL_GLattr attr, + int *value); -/* - * Dynamically load an OpenGL library, or the default one if path is NULL +/** + * \fn SDL_GLContext SDL_GL_CreateContext(SDL_WindowID windowID) * - * If you do this, you need to retrieve all of the GL functions used in - * your program from the dynamic library using SDL_GL_GetProcAddress(). + * \brief Create an OpenGL context for use with an OpenGL window, and make it current. + * + * \sa SDL_GL_DeleteContext() */ -extern DECLSPEC int SDLCALL SDL_GL_LoadLibrary(const char *path); +extern DECLSPEC SDL_GLContext SDLCALL SDL_GL_CreateContext(SDL_WindowID + windowID); -/* - * Get the address of a GL function +/** + * \fn int SDL_GL_MakeCurrent(SDL_WindowID windowID, SDL_GLContext context) + * + * \brief Set up an OpenGL context for rendering into an OpenGL window. + * + * \note The context must have been created with a compatible window. */ -extern DECLSPEC void * SDLCALL SDL_GL_GetProcAddress(const char* proc); +extern DECLSPEC int SDLCALL SDL_GL_MakeCurrent(SDL_WindowID windowID, + SDL_GLContext context); -/* - * Set an attribute of the OpenGL subsystem before intialization. +/** + * \fn int SDL_GL_SetSwapInterval(int interval) + * + * \brief Set the swap interval for the current OpenGL context. + * + * \sa SDL_GL_GetSwapInterval() */ -extern DECLSPEC int SDLCALL SDL_GL_SetAttribute(SDL_GLattr attr, int value); +extern DECLSPEC int SDLCALL SDL_GL_SetSwapInterval(int interval); -/* - * Get an attribute of the OpenGL subsystem from the windowing - * interface, such as glX. This is of course different from getting - * the values from SDL's internal OpenGL subsystem, which only - * stores the values you request before initialization. +/** + * \fn int SDL_GL_GetSwapInterval(void) * - * Developers should track the values they pass into SDL_GL_SetAttribute - * themselves if they want to retrieve these values. + * \brief Get the swap interval for the current OpenGL context. + * + * \sa SDL_GL_SetSwapInterval() */ -extern DECLSPEC int SDLCALL SDL_GL_GetAttribute(SDL_GLattr attr, int* value); +extern DECLSPEC int SDLCALL SDL_GL_GetSwapInterval(void); -/* +/** + * \fn void SDL_GL_SwapBuffers(void) + * * Swap the OpenGL buffers, if double-buffering is supported. */ extern DECLSPEC void SDLCALL SDL_GL_SwapBuffers(void); -/* - * Internal functions that should not be called unless you have read - * and understood the source code for these functions. +/** + * \fn void SDL_GL_DeleteContext(SDL_GLContext context) + * + * \brief Delete an OpenGL context. + * + * \sa SDL_GL_CreateContext() */ -extern DECLSPEC void SDLCALL SDL_GL_UpdateRects(int numrects, SDL_Rect* rects); -extern DECLSPEC void SDLCALL SDL_GL_Lock(void); -extern DECLSPEC void SDLCALL SDL_GL_Unlock(void); - -/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ -/* These functions allow interaction with the window manager, if any. */ -/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +extern DECLSPEC void SDLCALL SDL_GL_DeleteContext(SDL_GLContext context); -/* - * Sets/Gets the title and icon text of the display window (UTF-8 encoded) +/** + * \def SDL_RectEmpty() + * + * \brief Returns true if the rectangle has no area. */ -extern DECLSPEC void SDLCALL SDL_WM_SetCaption(const char *title, const char *icon); -extern DECLSPEC void SDLCALL SDL_WM_GetCaption(char **title, char **icon); +#define SDL_RectEmpty(X) (((X)->w <= 0) || ((X)->h <= 0)) -/* - * Sets the icon for the display window. - * This function must be called before the first call to SDL_SetVideoMode(). - * It takes an icon surface, and a mask in MSB format. - * If 'mask' is NULL, the entire icon surface will be used as the icon. +/** + * \def SDL_RectEquals() + * + * \brief Returns true if the two rectangles are equal. */ -extern DECLSPEC void SDLCALL SDL_WM_SetIcon(SDL_Surface *icon, Uint8 *mask); +#define SDL_RectEquals(A, B) (((A)->x == (B)->x) && ((A)->y == (B)->y) && \ + ((A)->w == (B)->w) && ((A)->h == (B)->h)) -/* - * This function iconifies the window, and returns 1 if it succeeded. - * If the function succeeds, it generates an SDL_APPACTIVE loss event. - * This function is a noop and returns 0 in non-windowed environments. +/** + * \fn SDL_bool SDL_HasIntersection(const SDL_Rect * A, const SDL_Rect * B); + * + * \brief Determine whether two rectangles intersect. + * + * \return SDL_TRUE if there is an intersection, SDL_FALSE otherwise. */ -extern DECLSPEC int SDLCALL SDL_WM_IconifyWindow(void); +extern DECLSPEC SDL_bool SDLCALL SDL_HasIntersection(const SDL_Rect * A, + const SDL_Rect * B); -/* - * Toggle fullscreen mode without changing the contents of the screen. - * If the display surface does not require locking before accessing - * the pixel information, then the memory pointers will not change. - * - * If this function was able to toggle fullscreen mode (change from - * running in a window to fullscreen, or vice-versa), it will return 1. - * If it is not implemented, or fails, it returns 0. +/** + * \fn SDL_bool SDL_IntersectRect(const SDL_Rect * A, const SDL_Rect * B, SDL_Rect * result) * - * The next call to SDL_SetVideoMode() will set the mode fullscreen - * attribute based on the flags parameter - if SDL_FULLSCREEN is not - * set, then the display will be windowed by default where supported. + * \brief Calculate the intersection of two rectangles. * - * This is currently only implemented in the X11 video driver. + * \return SDL_TRUE if there is an intersection, SDL_FALSE otherwise. */ -extern DECLSPEC int SDLCALL SDL_WM_ToggleFullScreen(SDL_Surface *surface); +extern DECLSPEC SDL_bool SDLCALL SDL_IntersectRect(const SDL_Rect * A, + const SDL_Rect * B, + SDL_Rect * result); -/* - * This function allows you to set and query the input grab state of - * the application. It returns the new input grab state. - */ -typedef enum { - SDL_GRAB_QUERY = -1, - SDL_GRAB_OFF = 0, - SDL_GRAB_ON = 1, - SDL_GRAB_FULLSCREEN /* Used internally */ -} SDL_GrabMode; -/* - * Grabbing means that the mouse is confined to the application window, - * and nearly all keyboard input is passed directly to the application, - * and not interpreted by a window manager, if any. +/** + * \fn void SDL_UnionRect(const SDL_Rect * A, const SDL_Rect * B, SDL_Rect * result) + * + * \brief Calculate the union of two rectangles */ -extern DECLSPEC SDL_GrabMode SDLCALL SDL_WM_GrabInput(SDL_GrabMode mode); +extern DECLSPEC void SDLCALL SDL_UnionRect(const SDL_Rect * A, + const SDL_Rect * B, + SDL_Rect * result); -/* Not in public API at the moment - do not use! */ -extern DECLSPEC int SDLCALL SDL_SoftStretch(SDL_Surface *src, SDL_Rect *srcrect, - SDL_Surface *dst, SDL_Rect *dstrect); - /* Ends C function definitions when using C++ */ #ifdef __cplusplus +/* *INDENT-OFF* */ } +/* *INDENT-ON* */ #endif #include "close_code.h" #endif /* _SDL_video_h */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/include/begin_code.h b/include/begin_code.h index 40279337f..01f4088de 100644 --- a/include/begin_code.h +++ b/include/begin_code.h @@ -42,7 +42,7 @@ # elif defined(__WIN32__) # ifdef __BORLANDC__ # ifdef BUILD_SDL -# define DECLSPEC +# define DECLSPEC # else # define DECLSPEC __declspec(dllimport) # endif @@ -84,7 +84,7 @@ #endif /* SDLCALL */ /* Removed DECLSPEC on Symbian OS because SDL cannot be a DLL in EPOC */ -#ifdef __SYMBIAN32__ +#ifdef __SYMBIAN32__ #undef DECLSPEC #define DECLSPEC #endif /* __SYMBIAN32__ */ diff --git a/include/close_code.h b/include/close_code.h index afbb65047..bf609d88a 100644 --- a/include/close_code.h +++ b/include/close_code.h @@ -38,4 +38,3 @@ #pragma pack(pop) #endif #endif /* Compiler needs structure packing set */ - diff --git a/include/doxyfile b/include/doxyfile new file mode 100644 index 000000000..e53097f4b --- /dev/null +++ b/include/doxyfile @@ -0,0 +1,1229 @@ +# Doxyfile 1.4.4 + +# This file describes the settings to be used by the documentation system +# doxygen (www.doxygen.org) for a project +# +# All text after a hash (#) is considered a comment and will be ignored +# The format is: +# TAG = value [value, ...] +# For lists items can also be appended using: +# TAG += value [value, ...] +# Values that contain spaces should be placed between quotes (" ") + +#--------------------------------------------------------------------------- +# Project related configuration options +#--------------------------------------------------------------------------- + +# The PROJECT_NAME tag is a single word (or a sequence of words surrounded +# by quotes) that should identify the project. + +PROJECT_NAME = SDL + +# The PROJECT_NUMBER tag can be used to enter a project or revision number. +# This could be handy for archiving the generated documentation or +# if some version control system is used. + +PROJECT_NUMBER = 1.3.0 + +# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) +# base path where the generated documentation will be put. +# If a relative path is entered, it will be relative to the location +# where doxygen was started. If left blank the current directory will be used. + +OUTPUT_DIRECTORY = docs + +# If the CREATE_SUBDIRS tag is set to YES, then doxygen will create +# 4096 sub-directories (in 2 levels) under the output directory of each output +# format and will distribute the generated files over these directories. +# Enabling this option can be useful when feeding doxygen a huge amount of +# source files, where putting all generated files in the same directory would +# otherwise cause performance problems for the file system. + +CREATE_SUBDIRS = NO + +# The OUTPUT_LANGUAGE tag is used to specify the language in which all +# documentation generated by doxygen is written. Doxygen will use this +# information to generate all constant output in the proper language. +# The default language is English, other supported languages are: +# Brazilian, Catalan, Chinese, Chinese-Traditional, Croatian, Czech, Danish, +# Dutch, Finnish, French, German, Greek, Hungarian, Italian, Japanese, +# Japanese-en (Japanese with English messages), Korean, Korean-en, Norwegian, +# Polish, Portuguese, Romanian, Russian, Serbian, Slovak, Slovene, Spanish, +# Swedish, and Ukrainian. + +OUTPUT_LANGUAGE = English + +# This tag can be used to specify the encoding used in the generated output. +# The encoding is not always determined by the language that is chosen, +# but also whether or not the output is meant for Windows or non-Windows users. +# In case there is a difference, setting the USE_WINDOWS_ENCODING tag to YES +# forces the Windows encoding (this is the default for the Windows binary), +# whereas setting the tag to NO uses a Unix-style encoding (the default for +# all platforms other than Windows). + +USE_WINDOWS_ENCODING = NO + +# If the BRIEF_MEMBER_DESC tag is set to YES (the default) Doxygen will +# include brief member descriptions after the members that are listed in +# the file and class documentation (similar to JavaDoc). +# Set to NO to disable this. + +BRIEF_MEMBER_DESC = YES + +# If the REPEAT_BRIEF tag is set to YES (the default) Doxygen will prepend +# the brief description of a member or function before the detailed description. +# Note: if both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the +# brief descriptions will be completely suppressed. + +REPEAT_BRIEF = YES + +# This tag implements a quasi-intelligent brief description abbreviator +# that is used to form the text in various listings. Each string +# in this list, if found as the leading text of the brief description, will be +# stripped from the text and the result after processing the whole list, is +# used as the annotated text. Otherwise, the brief description is used as-is. +# If left blank, the following values are used ("$name" is automatically +# replaced with the name of the entity): "The $name class" "The $name widget" +# "The $name file" "is" "provides" "specifies" "contains" +# "represents" "a" "an" "the" + +ABBREVIATE_BRIEF = + +# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then +# Doxygen will generate a detailed section even if there is only a brief +# description. + +ALWAYS_DETAILED_SEC = NO + +# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all +# inherited members of a class in the documentation of that class as if those +# members were ordinary class members. Constructors, destructors and assignment +# operators of the base classes will not be shown. + +INLINE_INHERITED_MEMB = NO + +# If the FULL_PATH_NAMES tag is set to YES then Doxygen will prepend the full +# path before files name in the file list and in the header files. If set +# to NO the shortest path that makes the file name unique will be used. + +FULL_PATH_NAMES = YES + +# If the FULL_PATH_NAMES tag is set to YES then the STRIP_FROM_PATH tag +# can be used to strip a user-defined part of the path. Stripping is +# only done if one of the specified strings matches the left-hand part of +# the path. The tag can be used to show relative paths in the file list. +# If left blank the directory from which doxygen is run is used as the +# path to strip. + +STRIP_FROM_PATH = + +# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of +# the path mentioned in the documentation of a class, which tells +# the reader which header file to include in order to use a class. +# If left blank only the name of the header file containing the class +# definition is used. Otherwise one should specify the include paths that +# are normally passed to the compiler using the -I flag. + +STRIP_FROM_INC_PATH = + +# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter +# (but less readable) file names. This can be useful is your file systems +# doesn't support long names like on DOS, Mac, or CD-ROM. + +SHORT_NAMES = NO + +# If the JAVADOC_AUTOBRIEF tag is set to YES then Doxygen +# will interpret the first line (until the first dot) of a JavaDoc-style +# comment as the brief description. If set to NO, the JavaDoc +# comments will behave just like the Qt-style comments (thus requiring an +# explicit @brief command for a brief description. + +JAVADOC_AUTOBRIEF = NO + +# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make Doxygen +# treat a multi-line C++ special comment block (i.e. a block of //! or /// +# comments) as a brief description. This used to be the default behaviour. +# The new default is to treat a multi-line C++ comment block as a detailed +# description. Set this tag to YES if you prefer the old behaviour instead. + +MULTILINE_CPP_IS_BRIEF = NO + +# If the DETAILS_AT_TOP tag is set to YES then Doxygen +# will output the detailed description near the top, like JavaDoc. +# If set to NO, the detailed description appears after the member +# documentation. + +DETAILS_AT_TOP = NO + +# If the INHERIT_DOCS tag is set to YES (the default) then an undocumented +# member inherits the documentation from any documented member that it +# re-implements. + +INHERIT_DOCS = YES + +# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC +# tag is set to YES, then doxygen will reuse the documentation of the first +# member in the group (if any) for the other members of the group. By default +# all members of a group must be documented explicitly. + +DISTRIBUTE_GROUP_DOC = NO + +# If the SEPARATE_MEMBER_PAGES tag is set to YES, then doxygen will produce +# a new page for each member. If set to NO, the documentation of a member will +# be part of the file/class/namespace that contains it. + +SEPARATE_MEMBER_PAGES = NO + +# The TAB_SIZE tag can be used to set the number of spaces in a tab. +# Doxygen uses this value to replace tabs by spaces in code fragments. + +TAB_SIZE = 8 + +# This tag can be used to specify a number of aliases that acts +# as commands in the documentation. An alias has the form "name=value". +# For example adding "sideeffect=\par Side Effects:\n" will allow you to +# put the command \sideeffect (or @sideeffect) in the documentation, which +# will result in a user-defined paragraph with heading "Side Effects:". +# You can put \n's in the value part of an alias to insert newlines. + +ALIASES = + +# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C +# sources only. Doxygen will then generate output that is more tailored for C. +# For instance, some of the names that are used will be different. The list +# of all members will be omitted, etc. + +OPTIMIZE_OUTPUT_FOR_C = YES + +# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java sources +# only. Doxygen will then generate output that is more tailored for Java. +# For instance, namespaces will be presented as packages, qualified scopes +# will look different, etc. + +OPTIMIZE_OUTPUT_JAVA = NO + +# Set the SUBGROUPING tag to YES (the default) to allow class member groups of +# the same type (for instance a group of public functions) to be put as a +# subgroup of that type (e.g. under the Public Functions section). Set it to +# NO to prevent subgrouping. Alternatively, this can be done per class using +# the \nosubgrouping command. + +SUBGROUPING = YES + +#--------------------------------------------------------------------------- +# Build related configuration options +#--------------------------------------------------------------------------- + +# If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in +# documentation are documented, even if no documentation was available. +# Private class members and static file members will be hidden unless +# the EXTRACT_PRIVATE and EXTRACT_STATIC tags are set to YES + +EXTRACT_ALL = NO + +# If the EXTRACT_PRIVATE tag is set to YES all private members of a class +# will be included in the documentation. + +EXTRACT_PRIVATE = NO + +# If the EXTRACT_STATIC tag is set to YES all static members of a file +# will be included in the documentation. + +EXTRACT_STATIC = NO + +# If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs) +# defined locally in source files will be included in the documentation. +# If set to NO only classes defined in header files are included. + +EXTRACT_LOCAL_CLASSES = YES + +# This flag is only useful for Objective-C code. When set to YES local +# methods, which are defined in the implementation section but not in +# the interface are included in the documentation. +# If set to NO (the default) only methods in the interface are included. + +EXTRACT_LOCAL_METHODS = NO + +# If the HIDE_UNDOC_MEMBERS tag is set to YES, Doxygen will hide all +# undocumented members of documented classes, files or namespaces. +# If set to NO (the default) these members will be included in the +# various overviews, but no documentation section is generated. +# This option has no effect if EXTRACT_ALL is enabled. + +HIDE_UNDOC_MEMBERS = NO + +# If the HIDE_UNDOC_CLASSES tag is set to YES, Doxygen will hide all +# undocumented classes that are normally visible in the class hierarchy. +# If set to NO (the default) these classes will be included in the various +# overviews. This option has no effect if EXTRACT_ALL is enabled. + +HIDE_UNDOC_CLASSES = NO + +# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, Doxygen will hide all +# friend (class|struct|union) declarations. +# If set to NO (the default) these declarations will be included in the +# documentation. + +HIDE_FRIEND_COMPOUNDS = NO + +# If the HIDE_IN_BODY_DOCS tag is set to YES, Doxygen will hide any +# documentation blocks found inside the body of a function. +# If set to NO (the default) these blocks will be appended to the +# function's detailed documentation block. + +HIDE_IN_BODY_DOCS = NO + +# The INTERNAL_DOCS tag determines if documentation +# that is typed after a \internal command is included. If the tag is set +# to NO (the default) then the documentation will be excluded. +# Set it to YES to include the internal documentation. + +INTERNAL_DOCS = NO + +# If the CASE_SENSE_NAMES tag is set to NO then Doxygen will only generate +# file names in lower-case letters. If set to YES upper-case letters are also +# allowed. This is useful if you have classes or files whose names only differ +# in case and if your file system supports case sensitive file names. Windows +# and Mac users are advised to set this option to NO. + +CASE_SENSE_NAMES = YES + +# If the HIDE_SCOPE_NAMES tag is set to NO (the default) then Doxygen +# will show members with their full class and namespace scopes in the +# documentation. If set to YES the scope will be hidden. + +HIDE_SCOPE_NAMES = NO + +# If the SHOW_INCLUDE_FILES tag is set to YES (the default) then Doxygen +# will put a list of the files that are included by a file in the documentation +# of that file. + +SHOW_INCLUDE_FILES = YES + +# If the INLINE_INFO tag is set to YES (the default) then a tag [inline] +# is inserted in the documentation for inline members. + +INLINE_INFO = YES + +# If the SORT_MEMBER_DOCS tag is set to YES (the default) then doxygen +# will sort the (detailed) documentation of file and class members +# alphabetically by member name. If set to NO the members will appear in +# declaration order. + +SORT_MEMBER_DOCS = YES + +# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the +# brief documentation of file, namespace and class members alphabetically +# by member name. If set to NO (the default) the members will appear in +# declaration order. + +SORT_BRIEF_DOCS = NO + +# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be +# sorted by fully-qualified names, including namespaces. If set to +# NO (the default), the class list will be sorted only by class name, +# not including the namespace part. +# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES. +# Note: This option applies only to the class list, not to the +# alphabetical list. + +SORT_BY_SCOPE_NAME = NO + +# The GENERATE_TODOLIST tag can be used to enable (YES) or +# disable (NO) the todo list. This list is created by putting \todo +# commands in the documentation. + +GENERATE_TODOLIST = YES + +# The GENERATE_TESTLIST tag can be used to enable (YES) or +# disable (NO) the test list. This list is created by putting \test +# commands in the documentation. + +GENERATE_TESTLIST = YES + +# The GENERATE_BUGLIST tag can be used to enable (YES) or +# disable (NO) the bug list. This list is created by putting \bug +# commands in the documentation. + +GENERATE_BUGLIST = YES + +# The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or +# disable (NO) the deprecated list. This list is created by putting +# \deprecated commands in the documentation. + +GENERATE_DEPRECATEDLIST= YES + +# The ENABLED_SECTIONS tag can be used to enable conditional +# documentation sections, marked by \if sectionname ... \endif. + +ENABLED_SECTIONS = + +# The MAX_INITIALIZER_LINES tag determines the maximum number of lines +# the initial value of a variable or define consists of for it to appear in +# the documentation. If the initializer consists of more lines than specified +# here it will be hidden. Use a value of 0 to hide initializers completely. +# The appearance of the initializer of individual variables and defines in the +# documentation can be controlled using \showinitializer or \hideinitializer +# command in the documentation regardless of this setting. + +MAX_INITIALIZER_LINES = 30 + +# Set the SHOW_USED_FILES tag to NO to disable the list of files generated +# at the bottom of the documentation of classes and structs. If set to YES the +# list will mention the files that were used to generate the documentation. + +SHOW_USED_FILES = YES + +# If the sources in your project are distributed over multiple directories +# then setting the SHOW_DIRECTORIES tag to YES will show the directory hierarchy +# in the documentation. The default is YES. + +SHOW_DIRECTORIES = YES + +# The FILE_VERSION_FILTER tag can be used to specify a program or script that +# doxygen should invoke to get the current version for each file (typically from the +# version control system). Doxygen will invoke the program by executing (via +# popen()) the command , where is the value of +# the FILE_VERSION_FILTER tag, and is the name of an input file +# provided by doxygen. Whatever the progam writes to standard output +# is used as the file version. See the manual for examples. + +FILE_VERSION_FILTER = + +#--------------------------------------------------------------------------- +# configuration options related to warning and progress messages +#--------------------------------------------------------------------------- + +# The QUIET tag can be used to turn on/off the messages that are generated +# by doxygen. Possible values are YES and NO. If left blank NO is used. + +QUIET = NO + +# The WARNINGS tag can be used to turn on/off the warning messages that are +# generated by doxygen. Possible values are YES and NO. If left blank +# NO is used. + +WARNINGS = YES + +# If WARN_IF_UNDOCUMENTED is set to YES, then doxygen will generate warnings +# for undocumented members. If EXTRACT_ALL is set to YES then this flag will +# automatically be disabled. + +WARN_IF_UNDOCUMENTED = YES + +# If WARN_IF_DOC_ERROR is set to YES, doxygen will generate warnings for +# potential errors in the documentation, such as not documenting some +# parameters in a documented function, or documenting parameters that +# don't exist or using markup commands wrongly. + +WARN_IF_DOC_ERROR = YES + +# This WARN_NO_PARAMDOC option can be abled to get warnings for +# functions that are documented, but have no documentation for their parameters +# or return value. If set to NO (the default) doxygen will only warn about +# wrong or incomplete parameter documentation, but not about the absence of +# documentation. + +WARN_NO_PARAMDOC = NO + +# The WARN_FORMAT tag determines the format of the warning messages that +# doxygen can produce. The string should contain the $file, $line, and $text +# tags, which will be replaced by the file and line number from which the +# warning originated and the warning text. Optionally the format may contain +# $version, which will be replaced by the version of the file (if it could +# be obtained via FILE_VERSION_FILTER) + +WARN_FORMAT = "$file:$line: $text" + +# The WARN_LOGFILE tag can be used to specify a file to which warning +# and error messages should be written. If left blank the output is written +# to stderr. + +WARN_LOGFILE = + +#--------------------------------------------------------------------------- +# configuration options related to the input files +#--------------------------------------------------------------------------- + +# The INPUT tag can be used to specify the files and/or directories that contain +# documented source files. You may enter file names like "myfile.cpp" or +# directories like "/usr/src/myproject". Separate the files or directories +# with spaces. + +INPUT = + +# If the value of the INPUT tag contains directories, you can use the +# FILE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp +# and *.h) to filter out the source-files in the directories. If left +# blank the following patterns are tested: +# *.c *.cc *.cxx *.cpp *.c++ *.java *.ii *.ixx *.ipp *.i++ *.inl *.h *.hh *.hxx +# *.hpp *.h++ *.idl *.odl *.cs *.php *.php3 *.inc *.m *.mm + +FILE_PATTERNS = + +# The RECURSIVE tag can be used to turn specify whether or not subdirectories +# should be searched for input files as well. Possible values are YES and NO. +# If left blank NO is used. + +RECURSIVE = NO + +# The EXCLUDE tag can be used to specify files and/or directories that should +# excluded from the INPUT source files. This way you can easily exclude a +# subdirectory from a directory tree whose root is specified with the INPUT tag. + +EXCLUDE = + +# The EXCLUDE_SYMLINKS tag can be used select whether or not files or +# directories that are symbolic links (a Unix filesystem feature) are excluded +# from the input. + +EXCLUDE_SYMLINKS = NO + +# If the value of the INPUT tag contains directories, you can use the +# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude +# certain files from those directories. Note that the wildcards are matched +# against the file with absolute path, so to exclude all test directories +# for example use the pattern */test/* + +EXCLUDE_PATTERNS = + +# The EXAMPLE_PATH tag can be used to specify one or more files or +# directories that contain example code fragments that are included (see +# the \include command). + +EXAMPLE_PATH = + +# If the value of the EXAMPLE_PATH tag contains directories, you can use the +# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp +# and *.h) to filter out the source-files in the directories. If left +# blank all files are included. + +EXAMPLE_PATTERNS = + +# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be +# searched for input files to be used with the \include or \dontinclude +# commands irrespective of the value of the RECURSIVE tag. +# Possible values are YES and NO. If left blank NO is used. + +EXAMPLE_RECURSIVE = NO + +# The IMAGE_PATH tag can be used to specify one or more files or +# directories that contain image that are included in the documentation (see +# the \image command). + +IMAGE_PATH = + +# The INPUT_FILTER tag can be used to specify a program that doxygen should +# invoke to filter for each input file. Doxygen will invoke the filter program +# by executing (via popen()) the command , where +# is the value of the INPUT_FILTER tag, and is the name of an +# input file. Doxygen will then use the output that the filter program writes +# to standard output. If FILTER_PATTERNS is specified, this tag will be +# ignored. + +INPUT_FILTER = + +# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern +# basis. Doxygen will compare the file name with each pattern and apply the +# filter if there is a match. The filters are a list of the form: +# pattern=filter (like *.cpp=my_cpp_filter). See INPUT_FILTER for further +# info on how filters are used. If FILTER_PATTERNS is empty, INPUT_FILTER +# is applied to all files. + +FILTER_PATTERNS = + +# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using +# INPUT_FILTER) will be used to filter the input files when producing source +# files to browse (i.e. when SOURCE_BROWSER is set to YES). + +FILTER_SOURCE_FILES = NO + +#--------------------------------------------------------------------------- +# configuration options related to source browsing +#--------------------------------------------------------------------------- + +# If the SOURCE_BROWSER tag is set to YES then a list of source files will +# be generated. Documented entities will be cross-referenced with these sources. +# Note: To get rid of all source code in the generated output, make sure also +# VERBATIM_HEADERS is set to NO. + +SOURCE_BROWSER = NO + +# Setting the INLINE_SOURCES tag to YES will include the body +# of functions and classes directly in the documentation. + +INLINE_SOURCES = NO + +# Setting the STRIP_CODE_COMMENTS tag to YES (the default) will instruct +# doxygen to hide any special comment blocks from generated source code +# fragments. Normal C and C++ comments will always remain visible. + +STRIP_CODE_COMMENTS = YES + +# If the REFERENCED_BY_RELATION tag is set to YES (the default) +# then for each documented function all documented +# functions referencing it will be listed. + +REFERENCED_BY_RELATION = YES + +# If the REFERENCES_RELATION tag is set to YES (the default) +# then for each documented function all documented entities +# called/used by that function will be listed. + +REFERENCES_RELATION = YES + +# If the USE_HTAGS tag is set to YES then the references to source code +# will point to the HTML generated by the htags(1) tool instead of doxygen +# built-in source browser. The htags tool is part of GNU's global source +# tagging system (see http://www.gnu.org/software/global/global.html). You +# will need version 4.8.6 or higher. + +USE_HTAGS = NO + +# If the VERBATIM_HEADERS tag is set to YES (the default) then Doxygen +# will generate a verbatim copy of the header file for each class for +# which an include is specified. Set to NO to disable this. + +VERBATIM_HEADERS = YES + +#--------------------------------------------------------------------------- +# configuration options related to the alphabetical class index +#--------------------------------------------------------------------------- + +# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index +# of all compounds will be generated. Enable this if the project +# contains a lot of classes, structs, unions or interfaces. + +ALPHABETICAL_INDEX = NO + +# If the alphabetical index is enabled (see ALPHABETICAL_INDEX) then +# the COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns +# in which this list will be split (can be a number in the range [1..20]) + +COLS_IN_ALPHA_INDEX = 5 + +# In case all classes in a project start with a common prefix, all +# classes will be put under the same header in the alphabetical index. +# The IGNORE_PREFIX tag can be used to specify one or more prefixes that +# should be ignored while generating the index headers. + +IGNORE_PREFIX = + +#--------------------------------------------------------------------------- +# configuration options related to the HTML output +#--------------------------------------------------------------------------- + +# If the GENERATE_HTML tag is set to YES (the default) Doxygen will +# generate HTML output. + +GENERATE_HTML = YES + +# The HTML_OUTPUT tag is used to specify where the HTML docs will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `html' will be used as the default path. + +HTML_OUTPUT = html + +# The HTML_FILE_EXTENSION tag can be used to specify the file extension for +# each generated HTML page (for example: .htm,.php,.asp). If it is left blank +# doxygen will generate files with .html extension. + +HTML_FILE_EXTENSION = .html + +# The HTML_HEADER tag can be used to specify a personal HTML header for +# each generated HTML page. If it is left blank doxygen will generate a +# standard header. + +HTML_HEADER = + +# The HTML_FOOTER tag can be used to specify a personal HTML footer for +# each generated HTML page. If it is left blank doxygen will generate a +# standard footer. + +HTML_FOOTER = + +# The HTML_STYLESHEET tag can be used to specify a user-defined cascading +# style sheet that is used by each HTML page. It can be used to +# fine-tune the look of the HTML output. If the tag is left blank doxygen +# will generate a default style sheet. Note that doxygen will try to copy +# the style sheet file to the HTML output directory, so don't put your own +# stylesheet in the HTML output directory as well, or it will be erased! + +HTML_STYLESHEET = + +# If the HTML_ALIGN_MEMBERS tag is set to YES, the members of classes, +# files or namespaces will be aligned in HTML using tables. If set to +# NO a bullet list will be used. + +HTML_ALIGN_MEMBERS = YES + +# If the GENERATE_HTMLHELP tag is set to YES, additional index files +# will be generated that can be used as input for tools like the +# Microsoft HTML help workshop to generate a compressed HTML help file (.chm) +# of the generated HTML documentation. + +GENERATE_HTMLHELP = NO + +# If the GENERATE_HTMLHELP tag is set to YES, the CHM_FILE tag can +# be used to specify the file name of the resulting .chm file. You +# can add a path in front of the file if the result should not be +# written to the html output directory. + +CHM_FILE = + +# If the GENERATE_HTMLHELP tag is set to YES, the HHC_LOCATION tag can +# be used to specify the location (absolute path including file name) of +# the HTML help compiler (hhc.exe). If non-empty doxygen will try to run +# the HTML help compiler on the generated index.hhp. + +HHC_LOCATION = + +# If the GENERATE_HTMLHELP tag is set to YES, the GENERATE_CHI flag +# controls if a separate .chi index file is generated (YES) or that +# it should be included in the master .chm file (NO). + +GENERATE_CHI = NO + +# If the GENERATE_HTMLHELP tag is set to YES, the BINARY_TOC flag +# controls whether a binary table of contents is generated (YES) or a +# normal table of contents (NO) in the .chm file. + +BINARY_TOC = NO + +# The TOC_EXPAND flag can be set to YES to add extra items for group members +# to the contents of the HTML help documentation and to the tree view. + +TOC_EXPAND = NO + +# The DISABLE_INDEX tag can be used to turn on/off the condensed index at +# top of each HTML page. The value NO (the default) enables the index and +# the value YES disables it. + +DISABLE_INDEX = NO + +# This tag can be used to set the number of enum values (range [1..20]) +# that doxygen will group on one line in the generated HTML documentation. + +ENUM_VALUES_PER_LINE = 4 + +# If the GENERATE_TREEVIEW tag is set to YES, a side panel will be +# generated containing a tree-like index structure (just like the one that +# is generated for HTML Help). For this to work a browser that supports +# JavaScript, DHTML, CSS and frames is required (for instance Mozilla 1.0+, +# Netscape 6.0+, Internet explorer 5.0+, or Konqueror). Windows users are +# probably better off using the HTML help feature. + +GENERATE_TREEVIEW = NO + +# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be +# used to set the initial width (in pixels) of the frame in which the tree +# is shown. + +TREEVIEW_WIDTH = 250 + +#--------------------------------------------------------------------------- +# configuration options related to the LaTeX output +#--------------------------------------------------------------------------- + +# If the GENERATE_LATEX tag is set to YES (the default) Doxygen will +# generate Latex output. + +GENERATE_LATEX = YES + +# The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `latex' will be used as the default path. + +LATEX_OUTPUT = latex + +# The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be +# invoked. If left blank `latex' will be used as the default command name. + +LATEX_CMD_NAME = latex + +# The MAKEINDEX_CMD_NAME tag can be used to specify the command name to +# generate index for LaTeX. If left blank `makeindex' will be used as the +# default command name. + +MAKEINDEX_CMD_NAME = makeindex + +# If the COMPACT_LATEX tag is set to YES Doxygen generates more compact +# LaTeX documents. This may be useful for small projects and may help to +# save some trees in general. + +COMPACT_LATEX = NO + +# The PAPER_TYPE tag can be used to set the paper type that is used +# by the printer. Possible values are: a4, a4wide, letter, legal and +# executive. If left blank a4wide will be used. + +PAPER_TYPE = a4wide + +# The EXTRA_PACKAGES tag can be to specify one or more names of LaTeX +# packages that should be included in the LaTeX output. + +EXTRA_PACKAGES = + +# The LATEX_HEADER tag can be used to specify a personal LaTeX header for +# the generated latex document. The header should contain everything until +# the first chapter. If it is left blank doxygen will generate a +# standard header. Notice: only use this tag if you know what you are doing! + +LATEX_HEADER = + +# If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated +# is prepared for conversion to pdf (using ps2pdf). The pdf file will +# contain links (just like the HTML output) instead of page references +# This makes the output suitable for online browsing using a pdf viewer. + +PDF_HYPERLINKS = NO + +# If the USE_PDFLATEX tag is set to YES, pdflatex will be used instead of +# plain latex in the generated Makefile. Set this option to YES to get a +# higher quality PDF documentation. + +USE_PDFLATEX = NO + +# If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \\batchmode. +# command to the generated LaTeX files. This will instruct LaTeX to keep +# running if errors occur, instead of asking the user for help. +# This option is also used when generating formulas in HTML. + +LATEX_BATCHMODE = NO + +# If LATEX_HIDE_INDICES is set to YES then doxygen will not +# include the index chapters (such as File Index, Compound Index, etc.) +# in the output. + +LATEX_HIDE_INDICES = NO + +#--------------------------------------------------------------------------- +# configuration options related to the RTF output +#--------------------------------------------------------------------------- + +# If the GENERATE_RTF tag is set to YES Doxygen will generate RTF output +# The RTF output is optimized for Word 97 and may not look very pretty with +# other RTF readers or editors. + +GENERATE_RTF = NO + +# The RTF_OUTPUT tag is used to specify where the RTF docs will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `rtf' will be used as the default path. + +RTF_OUTPUT = rtf + +# If the COMPACT_RTF tag is set to YES Doxygen generates more compact +# RTF documents. This may be useful for small projects and may help to +# save some trees in general. + +COMPACT_RTF = NO + +# If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated +# will contain hyperlink fields. The RTF file will +# contain links (just like the HTML output) instead of page references. +# This makes the output suitable for online browsing using WORD or other +# programs which support those fields. +# Note: wordpad (write) and others do not support links. + +RTF_HYPERLINKS = NO + +# Load stylesheet definitions from file. Syntax is similar to doxygen's +# config file, i.e. a series of assignments. You only have to provide +# replacements, missing definitions are set to their default value. + +RTF_STYLESHEET_FILE = + +# Set optional variables used in the generation of an rtf document. +# Syntax is similar to doxygen's config file. + +RTF_EXTENSIONS_FILE = + +#--------------------------------------------------------------------------- +# configuration options related to the man page output +#--------------------------------------------------------------------------- + +# If the GENERATE_MAN tag is set to YES (the default) Doxygen will +# generate man pages + +GENERATE_MAN = YES + +# The MAN_OUTPUT tag is used to specify where the man pages will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `man' will be used as the default path. + +MAN_OUTPUT = man + +# The MAN_EXTENSION tag determines the extension that is added to +# the generated man pages (default is the subroutine's section .3) + +MAN_EXTENSION = .3 + +# If the MAN_LINKS tag is set to YES and Doxygen generates man output, +# then it will generate one additional man file for each entity +# documented in the real man page(s). These additional files +# only source the real man page, but without them the man command +# would be unable to find the correct page. The default is NO. + +MAN_LINKS = NO + +#--------------------------------------------------------------------------- +# configuration options related to the XML output +#--------------------------------------------------------------------------- + +# If the GENERATE_XML tag is set to YES Doxygen will +# generate an XML file that captures the structure of +# the code including all documentation. + +GENERATE_XML = NO + +# The XML_OUTPUT tag is used to specify where the XML pages will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `xml' will be used as the default path. + +XML_OUTPUT = xml + +# The XML_SCHEMA tag can be used to specify an XML schema, +# which can be used by a validating XML parser to check the +# syntax of the XML files. + +XML_SCHEMA = + +# The XML_DTD tag can be used to specify an XML DTD, +# which can be used by a validating XML parser to check the +# syntax of the XML files. + +XML_DTD = + +# If the XML_PROGRAMLISTING tag is set to YES Doxygen will +# dump the program listings (including syntax highlighting +# and cross-referencing information) to the XML output. Note that +# enabling this will significantly increase the size of the XML output. + +XML_PROGRAMLISTING = YES + +#--------------------------------------------------------------------------- +# configuration options for the AutoGen Definitions output +#--------------------------------------------------------------------------- + +# If the GENERATE_AUTOGEN_DEF tag is set to YES Doxygen will +# generate an AutoGen Definitions (see autogen.sf.net) file +# that captures the structure of the code including all +# documentation. Note that this feature is still experimental +# and incomplete at the moment. + +GENERATE_AUTOGEN_DEF = NO + +#--------------------------------------------------------------------------- +# configuration options related to the Perl module output +#--------------------------------------------------------------------------- + +# If the GENERATE_PERLMOD tag is set to YES Doxygen will +# generate a Perl module file that captures the structure of +# the code including all documentation. Note that this +# feature is still experimental and incomplete at the +# moment. + +GENERATE_PERLMOD = NO + +# If the PERLMOD_LATEX tag is set to YES Doxygen will generate +# the necessary Makefile rules, Perl scripts and LaTeX code to be able +# to generate PDF and DVI output from the Perl module output. + +PERLMOD_LATEX = NO + +# If the PERLMOD_PRETTY tag is set to YES the Perl module output will be +# nicely formatted so it can be parsed by a human reader. This is useful +# if you want to understand what is going on. On the other hand, if this +# tag is set to NO the size of the Perl module output will be much smaller +# and Perl will parse it just the same. + +PERLMOD_PRETTY = YES + +# The names of the make variables in the generated doxyrules.make file +# are prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX. +# This is useful so different doxyrules.make files included by the same +# Makefile don't overwrite each other's variables. + +PERLMOD_MAKEVAR_PREFIX = + +#--------------------------------------------------------------------------- +# Configuration options related to the preprocessor +#--------------------------------------------------------------------------- + +# If the ENABLE_PREPROCESSING tag is set to YES (the default) Doxygen will +# evaluate all C-preprocessor directives found in the sources and include +# files. + +ENABLE_PREPROCESSING = YES + +# If the MACRO_EXPANSION tag is set to YES Doxygen will expand all macro +# names in the source code. If set to NO (the default) only conditional +# compilation will be performed. Macro expansion can be done in a controlled +# way by setting EXPAND_ONLY_PREDEF to YES. + +MACRO_EXPANSION = YES + +# If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES +# then the macro expansion is limited to the macros specified with the +# PREDEFINED and EXPAND_AS_PREDEFINED tags. + +EXPAND_ONLY_PREDEF = YES + +# If the SEARCH_INCLUDES tag is set to YES (the default) the includes files +# in the INCLUDE_PATH (see below) will be search if a #include is found. + +SEARCH_INCLUDES = YES + +# The INCLUDE_PATH tag can be used to specify one or more directories that +# contain include files that are not input files but should be processed by +# the preprocessor. + +INCLUDE_PATH = + +# You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard +# patterns (like *.h and *.hpp) to filter out the header-files in the +# directories. If left blank, the patterns specified with FILE_PATTERNS will +# be used. + +INCLUDE_FILE_PATTERNS = + +# The PREDEFINED tag can be used to specify one or more macro names that +# are defined before the preprocessor is started (similar to the -D option of +# gcc). The argument of the tag is a list of macros of the form: name +# or name=definition (no spaces). If the definition and the = are +# omitted =1 is assumed. To prevent a macro definition from being +# undefined via #undef or recursively expanded use the := operator +# instead of the = operator. + +PREDEFINED = DOXYGEN_SHOULD_IGNORE_THIS=1 \ + DECLSPEC= SDLCALL= + +# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then +# this tag can be used to specify a list of macro names that should be expanded. +# The macro definition that is found in the sources will be used. +# Use the PREDEFINED tag if you want to use a different macro definition. + +EXPAND_AS_DEFINED = + +# If the SKIP_FUNCTION_MACROS tag is set to YES (the default) then +# doxygen's preprocessor will remove all function-like macros that are alone +# on a line, have an all uppercase name, and do not end with a semicolon. Such +# function macros are typically used for boiler-plate code, and will confuse +# the parser if not removed. + +SKIP_FUNCTION_MACROS = YES + +#--------------------------------------------------------------------------- +# Configuration::additions related to external references +#--------------------------------------------------------------------------- + +# The TAGFILES option can be used to specify one or more tagfiles. +# Optionally an initial location of the external documentation +# can be added for each tagfile. The format of a tag file without +# this location is as follows: +# TAGFILES = file1 file2 ... +# Adding location for the tag files is done as follows: +# TAGFILES = file1=loc1 "file2 = loc2" ... +# where "loc1" and "loc2" can be relative or absolute paths or +# URLs. If a location is present for each tag, the installdox tool +# does not have to be run to correct the links. +# Note that each tag file must have a unique name +# (where the name does NOT include the path) +# If a tag file is not located in the directory in which doxygen +# is run, you must also specify the path to the tagfile here. + +TAGFILES = + +# When a file name is specified after GENERATE_TAGFILE, doxygen will create +# a tag file that is based on the input files it reads. + +GENERATE_TAGFILE = + +# If the ALLEXTERNALS tag is set to YES all external classes will be listed +# in the class index. If set to NO only the inherited external classes +# will be listed. + +ALLEXTERNALS = NO + +# If the EXTERNAL_GROUPS tag is set to YES all external groups will be listed +# in the modules index. If set to NO, only the current project's groups will +# be listed. + +EXTERNAL_GROUPS = YES + +# The PERL_PATH should be the absolute path and name of the perl script +# interpreter (i.e. the result of `which perl'). + +PERL_PATH = /usr/bin/perl + +#--------------------------------------------------------------------------- +# Configuration options related to the dot tool +#--------------------------------------------------------------------------- + +# If the CLASS_DIAGRAMS tag is set to YES (the default) Doxygen will +# generate a inheritance diagram (in HTML, RTF and LaTeX) for classes with base +# or super classes. Setting the tag to NO turns the diagrams off. Note that +# this option is superseded by the HAVE_DOT option below. This is only a +# fallback. It is recommended to install and use dot, since it yields more +# powerful graphs. + +CLASS_DIAGRAMS = NO + +# If set to YES, the inheritance and collaboration graphs will hide +# inheritance and usage relations if the target is undocumented +# or is not a class. + +HIDE_UNDOC_RELATIONS = YES + +# If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is +# available from the path. This tool is part of Graphviz, a graph visualization +# toolkit from AT&T and Lucent Bell Labs. The other options in this section +# have no effect if this option is set to NO (the default) + +HAVE_DOT = NO + +# If the CLASS_GRAPH and HAVE_DOT tags are set to YES then doxygen +# will generate a graph for each documented class showing the direct and +# indirect inheritance relations. Setting this tag to YES will force the +# the CLASS_DIAGRAMS tag to NO. + +CLASS_GRAPH = YES + +# If the COLLABORATION_GRAPH and HAVE_DOT tags are set to YES then doxygen +# will generate a graph for each documented class showing the direct and +# indirect implementation dependencies (inheritance, containment, and +# class references variables) of the class with other documented classes. + +COLLABORATION_GRAPH = YES + +# If the GROUP_GRAPHS and HAVE_DOT tags are set to YES then doxygen +# will generate a graph for groups, showing the direct groups dependencies + +GROUP_GRAPHS = YES + +# If the UML_LOOK tag is set to YES doxygen will generate inheritance and +# collaboration diagrams in a style similar to the OMG's Unified Modeling +# Language. + +UML_LOOK = NO + +# If set to YES, the inheritance and collaboration graphs will show the +# relations between templates and their instances. + +TEMPLATE_RELATIONS = NO + +# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDE_GRAPH, and HAVE_DOT +# tags are set to YES then doxygen will generate a graph for each documented +# file showing the direct and indirect include dependencies of the file with +# other documented files. + +INCLUDE_GRAPH = NO + +# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDED_BY_GRAPH, and +# HAVE_DOT tags are set to YES then doxygen will generate a graph for each +# documented header file showing the documented files that directly or +# indirectly include this file. + +INCLUDED_BY_GRAPH = YES + +# If the CALL_GRAPH and HAVE_DOT tags are set to YES then doxygen will +# generate a call dependency graph for every global function or class method. +# Note that enabling this option will significantly increase the time of a run. +# So in most cases it will be better to enable call graphs for selected +# functions only using the \callgraph command. + +CALL_GRAPH = NO + +# If the GRAPHICAL_HIERARCHY and HAVE_DOT tags are set to YES then doxygen +# will graphical hierarchy of all classes instead of a textual one. + +GRAPHICAL_HIERARCHY = YES + +# If the DIRECTORY_GRAPH, SHOW_DIRECTORIES and HAVE_DOT tags are set to YES +# then doxygen will show the dependencies a directory has on other directories +# in a graphical way. The dependency relations are determined by the #include +# relations between the files in the directories. + +DIRECTORY_GRAPH = YES + +# The DOT_IMAGE_FORMAT tag can be used to set the image format of the images +# generated by dot. Possible values are png, jpg, or gif +# If left blank png will be used. + +DOT_IMAGE_FORMAT = png + +# The tag DOT_PATH can be used to specify the path where the dot tool can be +# found. If left blank, it is assumed the dot tool can be found in the path. + +DOT_PATH = + +# The DOTFILE_DIRS tag can be used to specify one or more directories that +# contain dot files that are included in the documentation (see the +# \dotfile command). + +DOTFILE_DIRS = + +# The MAX_DOT_GRAPH_WIDTH tag can be used to set the maximum allowed width +# (in pixels) of the graphs generated by dot. If a graph becomes larger than +# this value, doxygen will try to truncate the graph, so that it fits within +# the specified constraint. Beware that most browsers cannot cope with very +# large images. + +MAX_DOT_GRAPH_WIDTH = 1024 + +# The MAX_DOT_GRAPH_HEIGHT tag can be used to set the maximum allows height +# (in pixels) of the graphs generated by dot. If a graph becomes larger than +# this value, doxygen will try to truncate the graph, so that it fits within +# the specified constraint. Beware that most browsers cannot cope with very +# large images. + +MAX_DOT_GRAPH_HEIGHT = 1024 + +# The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the +# graphs generated by dot. A depth value of 3 means that only nodes reachable +# from the root by following a path via at most 3 edges will be shown. Nodes +# that lay further from the root node will be omitted. Note that setting this +# option to 1 or 2 may greatly reduce the computation time needed for large +# code bases. Also note that a graph may be further truncated if the graph's +# image dimensions are not sufficient to fit the graph (see MAX_DOT_GRAPH_WIDTH +# and MAX_DOT_GRAPH_HEIGHT). If 0 is used for the depth value (the default), +# the graph is not depth-constrained. + +MAX_DOT_GRAPH_DEPTH = 0 + +# Set the DOT_TRANSPARENT tag to YES to generate images with a transparent +# background. This is disabled by default, which results in a white background. +# Warning: Depending on the platform used, enabling this option may lead to +# badly anti-aliased labels on the edges of a graph (i.e. they become hard to +# read). + +DOT_TRANSPARENT = NO + +# Set the DOT_MULTI_TARGETS tag to YES allow dot to generate multiple output +# files in one run (i.e. multiple -o and -T options on the command line). This +# makes dot run faster, but since only newer versions of dot (>1.8.10) +# support this, this feature is disabled by default. + +DOT_MULTI_TARGETS = NO + +# If the GENERATE_LEGEND tag is set to YES (the default) Doxygen will +# generate a legend page explaining the meaning of the various boxes and +# arrows in the dot generated graphs. + +GENERATE_LEGEND = YES + +# If the DOT_CLEANUP tag is set to YES (the default) Doxygen will +# remove the intermediate dot files that are used to generate +# the various graphs. + +DOT_CLEANUP = YES + +#--------------------------------------------------------------------------- +# Configuration::additions related to the search engine +#--------------------------------------------------------------------------- + +# The SEARCHENGINE tag specifies whether or not a search engine should be +# used. If set to NO the values of all tags below this one will be ignored. + +SEARCHENGINE = NO diff --git a/sdl-config.in b/sdl-config.in index ef278fd6c..95f4c9e8a 100644 --- a/sdl-config.in +++ b/sdl-config.in @@ -16,7 +16,7 @@ fi while test $# -gt 0; do case "$1" in - -*=*) optarg=`echo "$1" | LC_ALL="C" sed 's/[-_a-zA-Z0-9]*=//'` ;; + -*=*) optarg=`echo "$1" | sed 's/[-_a-zA-Z0-9]*=//'` ;; *) optarg= ;; esac diff --git a/src/SDL.c b/src/SDL.c index 64a3e93dc..05076c924 100644 --- a/src/SDL.c +++ b/src/SDL.c @@ -35,23 +35,19 @@ /* Initialization/Cleanup routines */ #if !SDL_JOYSTICK_DISABLED -extern int SDL_JoystickInit(void); +extern int SDL_JoystickInit(void); extern void SDL_JoystickQuit(void); #endif #if !SDL_CDROM_DISABLED -extern int SDL_CDROMInit(void); +extern int SDL_CDROMInit(void); extern void SDL_CDROMQuit(void); #endif #if !SDL_TIMERS_DISABLED extern void SDL_StartTicks(void); -extern int SDL_TimerInit(void); +extern int SDL_TimerInit(void); extern void SDL_TimerQuit(void); #endif -/* The current SDL version */ -static SDL_version version = - { SDL_MAJOR_VERSION, SDL_MINOR_VERSION, SDL_PATCHLEVEL }; - /* The initialized subsystems */ static Uint32 SDL_initialized = 0; static Uint32 ticks_started = 0; @@ -60,196 +56,205 @@ static Uint32 ticks_started = 0; int surfaces_allocated = 0; #endif -int SDL_InitSubSystem(Uint32 flags) +int +SDL_InitSubSystem(Uint32 flags) { #if !SDL_VIDEO_DISABLED - /* Initialize the video/event subsystem */ - if ( (flags & SDL_INIT_VIDEO) && !(SDL_initialized & SDL_INIT_VIDEO) ) { - if ( SDL_VideoInit(SDL_getenv("SDL_VIDEODRIVER"), - (flags&SDL_INIT_EVENTTHREAD)) < 0 ) { - return(-1); - } - SDL_initialized |= SDL_INIT_VIDEO; - } + /* Initialize the video/event subsystem */ + if ((flags & SDL_INIT_VIDEO) && !(SDL_initialized & SDL_INIT_VIDEO)) { + if (SDL_VideoInit(SDL_getenv("SDL_VIDEODRIVER"), + (flags & SDL_INIT_EVENTTHREAD)) < 0) { + return (-1); + } + SDL_initialized |= SDL_INIT_VIDEO; + } #else - if ( flags & SDL_INIT_VIDEO ) { - SDL_SetError("SDL not built with video support"); - return(-1); - } + if (flags & SDL_INIT_VIDEO) { + SDL_SetError("SDL not built with video support"); + return (-1); + } #endif #if !SDL_AUDIO_DISABLED - /* Initialize the audio subsystem */ - if ( (flags & SDL_INIT_AUDIO) && !(SDL_initialized & SDL_INIT_AUDIO) ) { - if ( SDL_AudioInit(SDL_getenv("SDL_AUDIODRIVER")) < 0 ) { - return(-1); - } - SDL_initialized |= SDL_INIT_AUDIO; - } + /* Initialize the audio subsystem */ + if ((flags & SDL_INIT_AUDIO) && !(SDL_initialized & SDL_INIT_AUDIO)) { + if (SDL_AudioInit(SDL_getenv("SDL_AUDIODRIVER")) < 0) { + return (-1); + } + SDL_initialized |= SDL_INIT_AUDIO; + } #else - if ( flags & SDL_INIT_AUDIO ) { - SDL_SetError("SDL not built with audio support"); - return(-1); - } + if (flags & SDL_INIT_AUDIO) { + SDL_SetError("SDL not built with audio support"); + return (-1); + } #endif #if !SDL_TIMERS_DISABLED - /* Initialize the timer subsystem */ - if ( ! ticks_started ) { - SDL_StartTicks(); - ticks_started = 1; - } - if ( (flags & SDL_INIT_TIMER) && !(SDL_initialized & SDL_INIT_TIMER) ) { - if ( SDL_TimerInit() < 0 ) { - return(-1); - } - SDL_initialized |= SDL_INIT_TIMER; - } + /* Initialize the timer subsystem */ + if (!ticks_started) { + SDL_StartTicks(); + ticks_started = 1; + } + if ((flags & SDL_INIT_TIMER) && !(SDL_initialized & SDL_INIT_TIMER)) { + if (SDL_TimerInit() < 0) { + return (-1); + } + SDL_initialized |= SDL_INIT_TIMER; + } #else - if ( flags & SDL_INIT_TIMER ) { - SDL_SetError("SDL not built with timer support"); - return(-1); - } + if (flags & SDL_INIT_TIMER) { + SDL_SetError("SDL not built with timer support"); + return (-1); + } #endif #if !SDL_JOYSTICK_DISABLED - /* Initialize the joystick subsystem */ - if ( (flags & SDL_INIT_JOYSTICK) && - !(SDL_initialized & SDL_INIT_JOYSTICK) ) { - if ( SDL_JoystickInit() < 0 ) { - return(-1); - } - SDL_initialized |= SDL_INIT_JOYSTICK; - } + /* Initialize the joystick subsystem */ + if ((flags & SDL_INIT_JOYSTICK) && !(SDL_initialized & SDL_INIT_JOYSTICK)) { + if (SDL_JoystickInit() < 0) { + return (-1); + } + SDL_initialized |= SDL_INIT_JOYSTICK; + } #else - if ( flags & SDL_INIT_JOYSTICK ) { - SDL_SetError("SDL not built with joystick support"); - return(-1); - } + if (flags & SDL_INIT_JOYSTICK) { + SDL_SetError("SDL not built with joystick support"); + return (-1); + } #endif #if !SDL_CDROM_DISABLED - /* Initialize the CD-ROM subsystem */ - if ( (flags & SDL_INIT_CDROM) && !(SDL_initialized & SDL_INIT_CDROM) ) { - if ( SDL_CDROMInit() < 0 ) { - return(-1); - } - SDL_initialized |= SDL_INIT_CDROM; - } + /* Initialize the CD-ROM subsystem */ + if ((flags & SDL_INIT_CDROM) && !(SDL_initialized & SDL_INIT_CDROM)) { + if (SDL_CDROMInit() < 0) { + return (-1); + } + SDL_initialized |= SDL_INIT_CDROM; + } #else - if ( flags & SDL_INIT_CDROM ) { - SDL_SetError("SDL not built with cdrom support"); - return(-1); - } + if (flags & SDL_INIT_CDROM) { + SDL_SetError("SDL not built with cdrom support"); + return (-1); + } #endif - return(0); + return (0); } -int SDL_Init(Uint32 flags) +int +SDL_Init(Uint32 flags) { #if !SDL_THREADS_DISABLED && SDL_THREAD_PTH - if (!pth_init()) { - return -1; - } + if (!pth_init()) { + return -1; + } #endif - /* Clear the error message */ - SDL_ClearError(); + /* Clear the error message */ + SDL_ClearError(); - /* Initialize the desired subsystems */ - if ( SDL_InitSubSystem(flags) < 0 ) { - return(-1); - } + /* Initialize the desired subsystems */ + if (SDL_InitSubSystem(flags) < 0) { + return (-1); + } - /* Everything is initialized */ - if ( !(flags & SDL_INIT_NOPARACHUTE) ) { - SDL_InstallParachute(); - } - return(0); + /* Everything is initialized */ + if (!(flags & SDL_INIT_NOPARACHUTE)) { + SDL_InstallParachute(); + } + return (0); } -void SDL_QuitSubSystem(Uint32 flags) +void +SDL_QuitSubSystem(Uint32 flags) { - /* Shut down requested initialized subsystems */ + /* Shut down requested initialized subsystems */ #if !SDL_CDROM_DISABLED - if ( (flags & SDL_initialized & SDL_INIT_CDROM) ) { - SDL_CDROMQuit(); - SDL_initialized &= ~SDL_INIT_CDROM; - } + if ((flags & SDL_initialized & SDL_INIT_CDROM)) { + SDL_CDROMQuit(); + SDL_initialized &= ~SDL_INIT_CDROM; + } #endif #if !SDL_JOYSTICK_DISABLED - if ( (flags & SDL_initialized & SDL_INIT_JOYSTICK) ) { - SDL_JoystickQuit(); - SDL_initialized &= ~SDL_INIT_JOYSTICK; - } + if ((flags & SDL_initialized & SDL_INIT_JOYSTICK)) { + SDL_JoystickQuit(); + SDL_initialized &= ~SDL_INIT_JOYSTICK; + } #endif #if !SDL_TIMERS_DISABLED - if ( (flags & SDL_initialized & SDL_INIT_TIMER) ) { - SDL_TimerQuit(); - SDL_initialized &= ~SDL_INIT_TIMER; - } + if ((flags & SDL_initialized & SDL_INIT_TIMER)) { + SDL_TimerQuit(); + SDL_initialized &= ~SDL_INIT_TIMER; + } #endif #if !SDL_AUDIO_DISABLED - if ( (flags & SDL_initialized & SDL_INIT_AUDIO) ) { - SDL_AudioQuit(); - SDL_initialized &= ~SDL_INIT_AUDIO; - } + if ((flags & SDL_initialized & SDL_INIT_AUDIO)) { + SDL_AudioQuit(); + SDL_initialized &= ~SDL_INIT_AUDIO; + } #endif #if !SDL_VIDEO_DISABLED - if ( (flags & SDL_initialized & SDL_INIT_VIDEO) ) { - SDL_VideoQuit(); - SDL_initialized &= ~SDL_INIT_VIDEO; - } + if ((flags & SDL_initialized & SDL_INIT_VIDEO)) { + SDL_VideoQuit(); + SDL_initialized &= ~SDL_INIT_VIDEO; + } #endif } -Uint32 SDL_WasInit(Uint32 flags) +Uint32 +SDL_WasInit(Uint32 flags) { - if ( ! flags ) { - flags = SDL_INIT_EVERYTHING; - } - return (SDL_initialized&flags); + if (!flags) { + flags = SDL_INIT_EVERYTHING; + } + return (SDL_initialized & flags); } -void SDL_Quit(void) +void +SDL_Quit(void) { - /* Quit all subsystems */ + /* Quit all subsystems */ #ifdef DEBUG_BUILD - printf("[SDL_Quit] : Enter! Calling QuitSubSystem()\n"); fflush(stdout); + printf("[SDL_Quit] : Enter! Calling QuitSubSystem()\n"); + fflush(stdout); #endif - SDL_QuitSubSystem(SDL_INIT_EVERYTHING); + SDL_QuitSubSystem(SDL_INIT_EVERYTHING); #ifdef CHECK_LEAKS #ifdef DEBUG_BUILD - printf("[SDL_Quit] : CHECK_LEAKS\n"); fflush(stdout); + printf("[SDL_Quit] : CHECK_LEAKS\n"); + fflush(stdout); #endif - /* Print the number of surfaces not freed */ - if ( surfaces_allocated != 0 ) { - fprintf(stderr, "SDL Warning: %d SDL surfaces extant\n", - surfaces_allocated); - } + /* Print the number of surfaces not freed */ + if (surfaces_allocated != 0) { + fprintf(stderr, "SDL Warning: %d SDL surfaces extant\n", + surfaces_allocated); + } #endif #ifdef DEBUG_BUILD - printf("[SDL_Quit] : SDL_UninstallParachute()\n"); fflush(stdout); + printf("[SDL_Quit] : SDL_UninstallParachute()\n"); + fflush(stdout); #endif - /* Uninstall any parachute signal handlers */ - SDL_UninstallParachute(); + /* Uninstall any parachute signal handlers */ + SDL_UninstallParachute(); #if !SDL_THREADS_DISABLED && SDL_THREAD_PTH - pth_kill(); + pth_kill(); #endif #ifdef DEBUG_BUILD - printf("[SDL_Quit] : Returning!\n"); fflush(stdout); + printf("[SDL_Quit] : Returning!\n"); + fflush(stdout); #endif } -/* Return the library version number */ -const SDL_version * SDL_Linked_Version(void) +/* Get the library version number */ +void +SDL_GetVersion(SDL_version * ver) { - return(&version); + SDL_VERSION(ver); } #if defined(__OS2__) @@ -261,65 +266,63 @@ const SDL_version * SDL_Linked_Version(void) #include /* Exception handler to prevent the Audio thread hanging, making a zombie process! */ -ULONG _System SDL_Main_ExceptionHandler(PEXCEPTIONREPORTRECORD pERepRec, - PEXCEPTIONREGISTRATIONRECORD pERegRec, - PCONTEXTRECORD pCtxRec, - PVOID p) +ULONG _System +SDL_Main_ExceptionHandler(PEXCEPTIONREPORTRECORD pERepRec, + PEXCEPTIONREGISTRATIONRECORD pERegRec, + PCONTEXTRECORD pCtxRec, PVOID p) { - if (pERepRec->fHandlerFlags & EH_EXIT_UNWIND) - return XCPT_CONTINUE_SEARCH; - if (pERepRec->fHandlerFlags & EH_UNWINDING) - return XCPT_CONTINUE_SEARCH; - if (pERepRec->fHandlerFlags & EH_NESTED_CALL) - return XCPT_CONTINUE_SEARCH; - - /* Do cleanup at every fatal exception! */ - if (((pERepRec->ExceptionNum & XCPT_SEVERITY_CODE) == XCPT_FATAL_EXCEPTION) && - (pERepRec->ExceptionNum != XCPT_BREAKPOINT) && - (pERepRec->ExceptionNum != XCPT_SINGLE_STEP) - ) - { - if (SDL_initialized & SDL_INIT_AUDIO) - { - /* This removes the zombie audio thread in case of emergency. */ + if (pERepRec->fHandlerFlags & EH_EXIT_UNWIND) + return XCPT_CONTINUE_SEARCH; + if (pERepRec->fHandlerFlags & EH_UNWINDING) + return XCPT_CONTINUE_SEARCH; + if (pERepRec->fHandlerFlags & EH_NESTED_CALL) + return XCPT_CONTINUE_SEARCH; + + /* Do cleanup at every fatal exception! */ + if (((pERepRec->ExceptionNum & XCPT_SEVERITY_CODE) == + XCPT_FATAL_EXCEPTION) && (pERepRec->ExceptionNum != XCPT_BREAKPOINT) + && (pERepRec->ExceptionNum != XCPT_SINGLE_STEP)) { + if (SDL_initialized & SDL_INIT_AUDIO) { + /* This removes the zombie audio thread in case of emergency. */ #ifdef DEBUG_BUILD - printf("[SDL_Main_ExceptionHandler] : Calling SDL_CloseAudio()!\n"); + printf + ("[SDL_Main_ExceptionHandler] : Calling SDL_CloseAudio()!\n"); #endif - SDL_CloseAudio(); + SDL_CloseAudio(); + } } - } - return (XCPT_CONTINUE_SEARCH); + return (XCPT_CONTINUE_SEARCH); } -EXCEPTIONREGISTRATIONRECORD SDL_Main_xcpthand = {0, SDL_Main_ExceptionHandler}; +EXCEPTIONREGISTRATIONRECORD SDL_Main_xcpthand = + { 0, SDL_Main_ExceptionHandler }; /* The main DLL entry for DLL Initialization and Uninitialization: */ -unsigned _System LibMain(unsigned hmod, unsigned termination) +unsigned _System +LibMain(unsigned hmod, unsigned termination) { - if (termination) - { + if (termination) { #ifdef DEBUG_BUILD /* printf("[SDL DLL Unintialization] : Removing exception handler\n"); */ #endif - DosUnsetExceptionHandler(&SDL_Main_xcpthand); - return 1; - } else - { + DosUnsetExceptionHandler(&SDL_Main_xcpthand); + return 1; + } else { #ifdef DEBUG_BUILD - /* Make stdout and stderr unbuffered! */ - setbuf(stdout, NULL); - setbuf(stderr, NULL); + /* Make stdout and stderr unbuffered! */ + setbuf(stdout, NULL); + setbuf(stderr, NULL); #endif - /* Fire up exception handler */ + /* Fire up exception handler */ #ifdef DEBUG_BUILD /* printf("[SDL DLL Initialization] : Setting exception handler\n"); */ #endif - /* Set exception handler */ - DosSetExceptionHandler(&SDL_Main_xcpthand); + /* Set exception handler */ + DosSetExceptionHandler(&SDL_Main_xcpthand); - return 1; - } + return 1; + } } #endif /* __WATCOMC__ */ @@ -330,19 +333,21 @@ unsigned _System LibMain(unsigned hmod, unsigned termination) #define WIN32_LEAN_AND_MEAN #include -BOOL APIENTRY _DllMainCRTStartup( HANDLE hModule, - DWORD ul_reason_for_call, - LPVOID lpReserved ) +BOOL APIENTRY +_DllMainCRTStartup(HANDLE hModule, + DWORD ul_reason_for_call, LPVOID lpReserved) { - switch (ul_reason_for_call) { - case DLL_PROCESS_ATTACH: - case DLL_THREAD_ATTACH: - case DLL_THREAD_DETACH: - case DLL_PROCESS_DETACH: - break; - } - return TRUE; + switch (ul_reason_for_call) { + case DLL_PROCESS_ATTACH: + case DLL_THREAD_ATTACH: + case DLL_THREAD_DETACH: + case DLL_PROCESS_DETACH: + break; + } + return TRUE; } #endif /* building DLL with Watcom C */ #endif /* OS/2 elif __WIN32__ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/SDL_compat.c b/src/SDL_compat.c new file mode 100644 index 000000000..a9b7d7a66 --- /dev/null +++ b/src/SDL_compat.c @@ -0,0 +1,1415 @@ +/* + SDL - Simple DirectMedia Layer + Copyright (C) 1997-2006 Sam Lantinga + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + Sam Lantinga + slouken@libsdl.org +*/ +#include "SDL_config.h" + +/* This file contains functions for backwards compatibility with SDL 1.2 */ + +#include "SDL.h" +#include "SDL_syswm.h" + +#include "video/SDL_sysvideo.h" +#include "video/SDL_pixels_c.h" + + +static SDL_WindowID SDL_VideoWindow; +static SDL_TextureID SDL_VideoTexture; +static SDL_Surface *SDL_VideoSurface; +static SDL_Surface *SDL_ShadowSurface; +static SDL_Surface *SDL_PublicSurface; +static char *wm_title; + +char * +SDL_AudioDriverName(char *namebuf, int maxlen) +{ + const char *name = SDL_GetCurrentAudioDriver(); + if (name) { + SDL_strlcpy(namebuf, name, maxlen); + return namebuf; + } + return NULL; +} + +char * +SDL_VideoDriverName(char *namebuf, int maxlen) +{ + const char *name = SDL_GetCurrentVideoDriver(); + if (name) { + SDL_strlcpy(namebuf, name, maxlen); + return namebuf; + } + return NULL; +} + +const SDL_VideoInfo * +SDL_GetVideoInfo(void) +{ + static SDL_VideoInfo info; + + /* Memory leak, compatibility code, who cares? */ + if (!info.vfmt && SDL_GetDesktopDisplayMode()) { + int bpp; + Uint32 Rmask, Gmask, Bmask, Amask; + + SDL_PixelFormatEnumToMasks(SDL_GetDesktopDisplayMode()->format, &bpp, + &Rmask, &Gmask, &Bmask, &Amask); + info.vfmt = SDL_AllocFormat(bpp, Rmask, Gmask, Bmask, Amask); + } + return &info; +} + +int +SDL_VideoModeOK(int width, int height, int bpp, Uint32 flags) +{ + int i, actual_bpp = 0; + + if (!SDL_GetVideoDevice()) { + return 0; + } + + if (!(flags & SDL_FULLSCREEN)) { + return SDL_BITSPERPIXEL(SDL_GetDesktopDisplayMode()->format); + } + + for (i = 0; i < SDL_GetNumDisplayModes(); ++i) { + const SDL_DisplayMode *mode = SDL_GetDisplayMode(i); + if (!mode->w || !mode->h || (width == mode->w && height == mode->h)) { + if (!mode->format) { + return bpp; + } + if (SDL_BITSPERPIXEL(mode->format) >= (Uint32) bpp) { + actual_bpp = SDL_BITSPERPIXEL(mode->format); + } + } + } + return actual_bpp; +} + +SDL_Rect ** +SDL_ListModes(SDL_PixelFormat * format, Uint32 flags) +{ + int i, nmodes; + SDL_Rect **modes; + + if (!SDL_GetVideoDevice()) { + return NULL; + } + + if (!(flags & SDL_FULLSCREEN)) { + return (SDL_Rect **) (-1); + } + + /* Memory leak, but this is a compatibility function, who cares? */ + nmodes = 0; + modes = NULL; + for (i = 0; i < SDL_GetNumDisplayModes(); ++i) { + const SDL_DisplayMode *mode = SDL_GetDisplayMode(i); + if (!mode->w || !mode->h) { + return (SDL_Rect **) (-1); + } + if (SDL_BITSPERPIXEL(mode->format) != format->BitsPerPixel) { + continue; + } + if (nmodes > 0 && modes[nmodes - 1]->w == mode->w + && modes[nmodes - 1]->h == mode->h) { + continue; + } + + modes = SDL_realloc(modes, (nmodes + 2) * sizeof(*modes)); + if (!modes) { + return NULL; + } + modes[nmodes] = (SDL_Rect *) SDL_malloc(sizeof(SDL_Rect)); + if (!modes[nmodes]) { + return NULL; + } + modes[nmodes]->x = 0; + modes[nmodes]->y = 0; + modes[nmodes]->w = mode->w; + modes[nmodes]->h = mode->h; + ++nmodes; + } + if (modes) { + modes[nmodes] = NULL; + } + return modes; +} + +static int +SDL_CompatEventFilter(void *userdata, SDL_Event * event) +{ + SDL_Event fake; + + switch (event->type) { + case SDL_WINDOWEVENT: + switch (event->window.event) { + case SDL_WINDOWEVENT_EXPOSED: + if (!SDL_HasEvent(SDL_VIDEOEXPOSEMASK)) { + fake.type = SDL_VIDEOEXPOSE; + SDL_PushEvent(&fake); + } + break; + case SDL_WINDOWEVENT_RESIZED: + fake.type = SDL_VIDEORESIZE; + fake.resize.w = event->window.data1; + fake.resize.h = event->window.data2; + SDL_PushEvent(&fake); + break; + case SDL_WINDOWEVENT_MINIMIZED: + fake.type = SDL_ACTIVEEVENT; + fake.active.gain = 0; + fake.active.state = SDL_APPACTIVE; + SDL_PushEvent(&fake); + break; + case SDL_WINDOWEVENT_RESTORED: + fake.type = SDL_ACTIVEEVENT; + fake.active.gain = 1; + fake.active.state = SDL_APPACTIVE; + SDL_PushEvent(&fake); + break; + case SDL_WINDOWEVENT_ENTER: + fake.type = SDL_ACTIVEEVENT; + fake.active.gain = 1; + fake.active.state = SDL_APPMOUSEFOCUS; + SDL_PushEvent(&fake); + break; + case SDL_WINDOWEVENT_LEAVE: + fake.type = SDL_ACTIVEEVENT; + fake.active.gain = 0; + fake.active.state = SDL_APPMOUSEFOCUS; + SDL_PushEvent(&fake); + break; + case SDL_WINDOWEVENT_FOCUS_GAINED: + fake.type = SDL_ACTIVEEVENT; + fake.active.gain = 1; + fake.active.state = SDL_APPINPUTFOCUS; + SDL_PushEvent(&fake); + break; + case SDL_WINDOWEVENT_FOCUS_LOST: + fake.type = SDL_ACTIVEEVENT; + fake.active.gain = 1; + fake.active.state = SDL_APPINPUTFOCUS; + SDL_PushEvent(&fake); + break; + case SDL_WINDOWEVENT_CLOSE: + fake.type = SDL_QUIT; + SDL_PushEvent(&fake); + break; + } + case SDL_KEYDOWN: + case SDL_KEYUP: + { + Uint32 unicode = 0; + if (event->key.type == SDL_KEYDOWN && event->key.keysym.sym < 256) { + unicode = event->key.keysym.sym; + if (unicode >= 'a' && unicode <= 'z') { + int shifted = !!(event->key.keysym.mod & KMOD_SHIFT); + int capslock = !!(event->key.keysym.mod & KMOD_CAPS); + if ((shifted ^ capslock) != 0) { + unicode = SDL_toupper(unicode); + } + } + } + if (unicode) { + event->key.keysym.unicode = unicode; + } + break; + } + case SDL_MOUSEWHEEL: + { + Uint8 button; + int selected; + int x, y; + + selected = SDL_SelectMouse(event->wheel.which); + SDL_GetMouseState(&x, &y); + SDL_SelectMouse(selected); + + if (event->wheel.motion > 0) { + button = SDL_BUTTON_WHEELUP; + } else { + button = SDL_BUTTON_WHEELDOWN; + } + + fake.button.which = event->wheel.windowID; + fake.button.button = button; + fake.button.x = x; + fake.button.y = y; + fake.button.windowID = event->wheel.windowID; + + fake.type = SDL_MOUSEBUTTONDOWN; + fake.button.state = SDL_PRESSED; + SDL_PushEvent(&fake); + + fake.type = SDL_MOUSEBUTTONUP; + fake.button.state = SDL_RELEASED; + SDL_PushEvent(&fake); + break; + } + + } + return 1; +} + +static int +SDL_VideoPaletteChanged(void *userdata, SDL_Palette * palette) +{ + if (userdata == SDL_ShadowSurface) { + /* If the shadow palette changed, make the changes visible */ + if (!SDL_VideoSurface->format->palette) { + SDL_UpdateRect(SDL_ShadowSurface, 0, 0, 0, 0); + } + } + if (userdata == SDL_VideoSurface) { + return SDL_SetDisplayPalette(palette->colors, 0, palette->ncolors); + } + return 0; +} + +static void +GetEnvironmentWindowPosition(int w, int h, int *x, int *y) +{ + const char *window = SDL_getenv("SDL_VIDEO_WINDOW_POS"); + const char *center = SDL_getenv("SDL_VIDEO_CENTERED"); + if (window) { + if (SDL_sscanf(window, "%d,%d", x, y) == 2) { + return; + } + if (SDL_strcmp(window, "center") == 0) { + center = window; + } + } + if (center) { + const SDL_DisplayMode *current = SDL_GetDesktopDisplayMode(); + *x = (current->w - w) / 2; + *y = (current->h - h) / 2; + } +} + +SDL_Surface * +SDL_SetVideoMode(int width, int height, int bpp, Uint32 flags) +{ + const SDL_DisplayMode *desktop_mode; + SDL_DisplayMode mode; + int window_x = SDL_WINDOWPOS_UNDEFINED; + int window_y = SDL_WINDOWPOS_UNDEFINED; + Uint32 window_flags; + Uint32 desktop_format; + Uint32 desired_format; + Uint32 surface_flags; + + if (!SDL_GetVideoDevice()) { + if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_NOPARACHUTE) < 0) { + return NULL; + } + } + + /* Destroy existing window */ + SDL_PublicSurface = NULL; + if (SDL_ShadowSurface) { + SDL_FreeSurface(SDL_ShadowSurface); + SDL_ShadowSurface = NULL; + } + if (SDL_VideoSurface) { + SDL_DelPaletteWatch(SDL_VideoSurface->format->palette, + SDL_VideoPaletteChanged, NULL); + SDL_FreeSurface(SDL_VideoSurface); + SDL_VideoSurface = NULL; + } + if (SDL_VideoWindow) { + SDL_GetWindowPosition(SDL_VideoWindow, &window_x, &window_y); + } + SDL_DestroyWindow(SDL_VideoWindow); + + /* Set up the event filter */ + if (!SDL_GetEventFilter(NULL, NULL)) { + SDL_SetEventFilter(SDL_CompatEventFilter, NULL); + } + + /* Create a new window */ + window_flags = SDL_WINDOW_SHOWN; + if (flags & SDL_FULLSCREEN) { + window_flags |= SDL_WINDOW_FULLSCREEN; + } + if (flags & SDL_OPENGL) { + window_flags |= SDL_WINDOW_OPENGL; + } + if (flags & SDL_RESIZABLE) { + window_flags |= SDL_WINDOW_RESIZABLE; + } + if (flags & SDL_NOFRAME) { + window_flags |= SDL_WINDOW_BORDERLESS; + } + GetEnvironmentWindowPosition(width, height, &window_x, &window_y); + SDL_SetFullscreenDisplayMode(NULL); + SDL_VideoWindow = + SDL_CreateWindow(wm_title, window_x, window_y, width, height, + window_flags); + if (!SDL_VideoWindow) { + return NULL; + } + + window_flags = SDL_GetWindowFlags(SDL_VideoWindow); + surface_flags = 0; + if (window_flags & SDL_WINDOW_FULLSCREEN) { + surface_flags |= SDL_FULLSCREEN; + } + if (window_flags & SDL_WINDOW_OPENGL) { + surface_flags |= SDL_OPENGL; + } + if (window_flags & SDL_WINDOW_RESIZABLE) { + surface_flags |= SDL_RESIZABLE; + } + if (window_flags & SDL_WINDOW_BORDERLESS) { + surface_flags |= SDL_NOFRAME; + } + + /* Set up the desired display mode */ + desktop_mode = SDL_GetDesktopDisplayMode(); + desktop_format = desktop_mode->format; + if (desktop_format && ((flags & SDL_ANYFORMAT) + || (bpp == SDL_BITSPERPIXEL(desktop_format)))) { + desired_format = desktop_format; + } else { + switch (bpp) { + case 0: + if (desktop_format) { + desired_format = desktop_format; + } else { + desired_format = SDL_PixelFormat_RGB888; + } + break; + case 8: + desired_format = SDL_PixelFormat_Index8; + break; + case 15: + desired_format = SDL_PixelFormat_RGB555; + break; + case 16: + desired_format = SDL_PixelFormat_RGB565; + break; + case 24: + desired_format = SDL_PixelFormat_RGB24; + break; + case 32: + desired_format = SDL_PixelFormat_RGB888; + break; + default: + SDL_SetError("Unsupported bpp in SDL_SetVideoMode()"); + return NULL; + } + } + mode.format = desired_format; + mode.w = width; + mode.h = height; + mode.refresh_rate = 0; + + /* Set the desired display mode */ + if (flags & SDL_FULLSCREEN) { + if (SDL_SetFullscreenDisplayMode(&mode) < 0) { + return NULL; + } + } + + /* If we're in OpenGL mode, just create a stub surface and we're done! */ + if (flags & SDL_OPENGL) { + SDL_VideoSurface = + SDL_CreateRGBSurfaceFrom(NULL, width, height, bpp, 0, 0, 0, 0, 0); + if (!SDL_VideoSurface) { + return NULL; + } + SDL_VideoSurface->flags |= surface_flags; + SDL_PublicSurface = SDL_VideoSurface; + return SDL_PublicSurface; + } + + /* Create a renderer for the window */ + if (SDL_CreateRenderer(SDL_VideoWindow, -1, 0) < 0) { + return NULL; + } + + /* Create a texture for the screen surface */ + SDL_VideoTexture = + SDL_CreateTexture(desired_format, SDL_TextureAccess_Local, width, + height); + if (!SDL_VideoTexture) { + SDL_VideoTexture = + SDL_CreateTexture(0, SDL_TextureAccess_Local, width, height); + } + if (!SDL_VideoTexture) { + return NULL; + } + + /* Create the screen surface */ + SDL_VideoSurface = SDL_CreateRGBSurfaceFromTexture(SDL_VideoTexture); + if (!SDL_VideoSurface) { + return NULL; + } + SDL_VideoSurface->flags |= surface_flags; + + /* Set a default screen palette */ + if (SDL_VideoSurface->format->palette) { + SDL_VideoSurface->flags |= SDL_HWPALETTE; + SDL_DitherColors(SDL_VideoSurface->format->palette->colors, + SDL_VideoSurface->format->BitsPerPixel); + SDL_AddPaletteWatch(SDL_VideoSurface->format->palette, + SDL_VideoPaletteChanged, NULL); + SDL_SetPaletteColors(SDL_VideoSurface->format->palette, + SDL_VideoSurface->format->palette->colors, 0, + SDL_VideoSurface->format->palette->ncolors); + } + + /* Create a shadow surface if necessary */ + if (((bpp != SDL_VideoSurface->format->BitsPerPixel) + && !(flags & SDL_ANYFORMAT)) + || ((SDL_VideoSurface->flags & SDL_HWSURFACE) + && !(flags & SDL_HWSURFACE))) { + if ((bpp == SDL_VideoSurface->format->BitsPerPixel) + || (flags & SDL_ANYFORMAT)) { + SDL_ShadowSurface = + SDL_CreateRGBSurface(0, width, height, + SDL_VideoSurface->format->BitsPerPixel, + SDL_VideoSurface->format->Rmask, + SDL_VideoSurface->format->Gmask, + SDL_VideoSurface->format->Bmask, + SDL_VideoSurface->format->Amask); + } else { + SDL_ShadowSurface = + SDL_CreateRGBSurface(0, width, height, bpp, 0, 0, 0, 0); + } + if (!SDL_ShadowSurface) { + return NULL; + } + SDL_ShadowSurface->flags |= surface_flags; + + /* 8-bit SDL_ShadowSurface surfaces report that they have exclusive palette */ + if (SDL_ShadowSurface->format->palette) { + SDL_ShadowSurface->flags |= SDL_HWPALETTE; + if (SDL_VideoSurface->format->palette) { + SDL_SetSurfacePalette(SDL_ShadowSurface, + SDL_VideoSurface->format->palette); + } else { + SDL_DitherColors(SDL_ShadowSurface->format->palette->colors, + SDL_ShadowSurface->format->BitsPerPixel); + } + } + } + SDL_PublicSurface = + (SDL_ShadowSurface ? SDL_ShadowSurface : SDL_VideoSurface); + + /* Clear the surface for display */ + SDL_FillRect(SDL_PublicSurface, NULL, 0); + + /* We're finally done! */ + return SDL_PublicSurface; +} + +SDL_Surface * +SDL_GetVideoSurface(void) +{ + return SDL_PublicSurface; +} + +SDL_Surface * +SDL_DisplayFormat(SDL_Surface * surface) +{ + Uint32 flags; + + if (!SDL_PublicSurface) { + SDL_SetError("No video mode has been set"); + return NULL; + } + + /* Set the flags appropriate for copying to display surface */ + flags = SDL_SWSURFACE; +#ifdef AUTORLE_DISPLAYFORMAT + flags |= (surface->flags & (SDL_SRCCOLORKEY | SDL_SRCALPHA)); + flags |= SDL_RLEACCELOK; +#else + flags |= + surface->flags & (SDL_SRCCOLORKEY | SDL_SRCALPHA | SDL_RLEACCELOK); +#endif + return SDL_ConvertSurface(surface, SDL_PublicSurface->format, flags); +} + +SDL_Surface * +SDL_DisplayFormatAlpha(SDL_Surface * surface) +{ + SDL_PixelFormat *vf; + SDL_PixelFormat *format; + SDL_Surface *converted; + Uint32 flags; + /* default to ARGB8888 */ + Uint32 amask = 0xff000000; + Uint32 rmask = 0x00ff0000; + Uint32 gmask = 0x0000ff00; + Uint32 bmask = 0x000000ff; + + if (!SDL_PublicSurface) { + SDL_SetError("No video mode has been set"); + return NULL; + } + vf = SDL_PublicSurface->format; + + switch (vf->BytesPerPixel) { + case 2: + /* For XGY5[56]5, use, AXGY8888, where {X, Y} = {R, B}. + For anything else (like ARGB4444) it doesn't matter + since we have no special code for it anyway */ + if ((vf->Rmask == 0x1f) && + (vf->Bmask == 0xf800 || vf->Bmask == 0x7c00)) { + rmask = 0xff; + bmask = 0xff0000; + } + break; + + case 3: + case 4: + /* Keep the video format, as long as the high 8 bits are + unused or alpha */ + if ((vf->Rmask == 0xff) && (vf->Bmask == 0xff0000)) { + rmask = 0xff; + bmask = 0xff0000; + } + break; + + default: + /* We have no other optimised formats right now. When/if a new + optimised alpha format is written, add the converter here */ + break; + } + format = SDL_AllocFormat(32, rmask, gmask, bmask, amask); + flags = SDL_PublicSurface->flags & SDL_HWSURFACE; + flags |= surface->flags & (SDL_SRCALPHA | SDL_RLEACCELOK); + converted = SDL_ConvertSurface(surface, format, flags); + SDL_FreeFormat(format); + return converted; +} + +int +SDL_Flip(SDL_Surface * screen) +{ + SDL_UpdateRect(screen, 0, 0, 0, 0); + return 0; +} + +void +SDL_UpdateRect(SDL_Surface * screen, Sint32 x, Sint32 y, Uint32 w, Uint32 h) +{ + if (screen) { + SDL_Rect rect; + + /* Perform some checking */ + if (w == 0) + w = screen->w; + if (h == 0) + h = screen->h; + if ((int) (x + w) > screen->w) + return; + if ((int) (y + h) > screen->h) + return; + + /* Fill the rectangle */ + rect.x = (Sint16) x; + rect.y = (Sint16) y; + rect.w = (Uint16) w; + rect.h = (Uint16) h; + SDL_UpdateRects(screen, 1, &rect); + } +} +void +SDL_UpdateRects(SDL_Surface * screen, int numrects, SDL_Rect * rects) +{ + int i; + + if (screen == SDL_ShadowSurface) { + for (i = 0; i < numrects; ++i) { + SDL_LowerBlit(SDL_ShadowSurface, &rects[i], SDL_VideoSurface, + &rects[i]); + } + + /* Fall through to video surface update */ + screen = SDL_VideoSurface; + } + if (screen == SDL_VideoSurface) { + for (i = 0; i < numrects; ++i) { + SDL_RenderCopy(SDL_VideoTexture, &rects[i], &rects[i], + SDL_TextureBlendMode_None, + SDL_TextureScaleMode_None); + } + SDL_RenderPresent(); + } +} + +void +SDL_WM_SetCaption(const char *title, const char *icon) +{ + if (wm_title) { + SDL_free(wm_title); + } else { + wm_title = SDL_strdup(title); + } + SDL_SetWindowTitle(SDL_VideoWindow, wm_title); +} + +void +SDL_WM_GetCaption(char **title, char **icon) +{ + if (title) { + *title = wm_title; + } + if (icon) { + *icon = ""; + } +} + +void +SDL_WM_SetIcon(SDL_Surface * icon, Uint8 * mask) +{ + /* FIXME */ +} + +int +SDL_WM_IconifyWindow(void) +{ + SDL_MinimizeWindow(SDL_VideoWindow); + return 0; +} + +int +SDL_WM_ToggleFullScreen(SDL_Surface * surface) +{ + if (SDL_GetWindowFlags(SDL_VideoWindow) & SDL_WINDOW_FULLSCREEN) { + if (SDL_SetWindowFullscreen(SDL_VideoWindow, 0) < 0) { + return 0; + } + SDL_PublicSurface->flags &= ~SDL_FULLSCREEN; + } else { + if (SDL_SetWindowFullscreen(SDL_VideoWindow, 1) < 0) { + return 0; + } + SDL_PublicSurface->flags |= SDL_FULLSCREEN; + } + return 1; +} + +SDL_GrabMode +SDL_WM_GrabInput(SDL_GrabMode mode) +{ + if (mode != SDL_GRAB_QUERY) { + SDL_SetWindowGrab(SDL_VideoWindow, mode); + } + return (SDL_GrabMode) SDL_GetWindowGrab(SDL_VideoWindow); +} + +void +SDL_WarpMouse(Uint16 x, Uint16 y) +{ + SDL_WarpMouseInWindow(SDL_VideoWindow, x, y); +} + +Uint8 +SDL_GetAppState(void) +{ + Uint8 state = 0; + Uint32 flags = 0; + + flags = SDL_GetWindowFlags(SDL_VideoWindow); + if ((flags & SDL_WINDOW_SHOWN) && !(flags & SDL_WINDOW_MINIMIZED)) { + state |= SDL_APPACTIVE; + } + if (flags & SDL_WINDOW_INPUT_FOCUS) { + state |= SDL_APPINPUTFOCUS; + } + if (flags & SDL_WINDOW_MOUSE_FOCUS) { + state |= SDL_APPMOUSEFOCUS; + } + return state; +} + +const SDL_version * +SDL_Linked_Version(void) +{ + static SDL_version version; + SDL_VERSION(&version); + return &version; +} + +int +SDL_SetPalette(SDL_Surface * surface, int flags, const SDL_Color * colors, + int firstcolor, int ncolors) +{ + return SDL_SetColors(surface, colors, firstcolor, ncolors); +} + +int +SDL_SetColors(SDL_Surface * surface, const SDL_Color * colors, int firstcolor, + int ncolors) +{ + if (SDL_SetPaletteColors + (surface->format->palette, colors, firstcolor, ncolors) == 0) { + return 1; + } else { + return 0; + } +} + +int +SDL_GetWMInfo(SDL_SysWMinfo * info) +{ + return SDL_GetWindowWMInfo(SDL_VideoWindow, info); +} + +#if 0 +void +SDL_MoveCursor(int x, int y) +{ + SDL_VideoDevice *_this = SDL_GetVideoDevice(); + + /* Erase and update the current mouse position */ + if (SHOULD_DRAWCURSOR(SDL_cursorstate)) { + /* Erase and redraw mouse cursor in new position */ + SDL_LockCursor(); + SDL_EraseCursor(SDL_VideoSurface); + SDL_cursor->area.x = (x - SDL_cursor->hot_x); + SDL_cursor->area.y = (y - SDL_cursor->hot_y); + SDL_DrawCursor(SDL_VideoSurface); + SDL_UnlockCursor(); + } else if (_this->MoveWMCursor) { + _this->MoveWMCursor(_this, x, y); + } +} + +/* Keep track of the current cursor colors */ +static int palette_changed = 1; +static Uint8 pixels8[2]; + +void +SDL_CursorPaletteChanged(void) +{ + palette_changed = 1; +} + +void +SDL_MouseRect(SDL_Rect * area) +{ + SDL_VideoDevice *_this = SDL_GetVideoDevice(); + int clip_diff; + + *area = SDL_cursor->area; + if (area->x < 0) { + area->w += area->x; + area->x = 0; + } + if (area->y < 0) { + area->h += area->y; + area->y = 0; + } + clip_diff = (area->x + area->w) - SDL_VideoSurface->w; + if (clip_diff > 0) { + area->w = area->w < clip_diff ? 0 : area->w - clip_diff; + } + clip_diff = (area->y + area->h) - SDL_VideoSurface->h; + if (clip_diff > 0) { + area->h = area->h < clip_diff ? 0 : area->h - clip_diff; + } +} + +static void +SDL_DrawCursorFast(SDL_Surface * screen, SDL_Rect * area) +{ + const Uint32 pixels[2] = { 0xFFFFFFFF, 0x00000000 }; + int i, w, h; + Uint8 *data, datab; + Uint8 *mask, maskb; + + data = SDL_cursor->data + area->y * SDL_cursor->area.w / 8; + mask = SDL_cursor->mask + area->y * SDL_cursor->area.w / 8; + switch (screen->format->BytesPerPixel) { + + case 1: + { + Uint8 *dst; + int dstskip; + + if (palette_changed) { + pixels8[0] = + (Uint8) SDL_MapRGB(screen->format, 255, 255, 255); + pixels8[1] = (Uint8) SDL_MapRGB(screen->format, 0, 0, 0); + palette_changed = 0; + } + dst = (Uint8 *) screen->pixels + + (SDL_cursor->area.y + area->y) * screen->pitch + + SDL_cursor->area.x; + dstskip = screen->pitch - area->w; + + for (h = area->h; h; h--) { + for (w = area->w / 8; w; w--) { + maskb = *mask++; + datab = *data++; + for (i = 0; i < 8; ++i) { + if (maskb & 0x80) { + *dst = pixels8[datab >> 7]; + } + maskb <<= 1; + datab <<= 1; + dst++; + } + } + dst += dstskip; + } + } + break; + + case 2: + { + Uint16 *dst; + int dstskip; + + dst = (Uint16 *) screen->pixels + + (SDL_cursor->area.y + area->y) * screen->pitch / 2 + + SDL_cursor->area.x; + dstskip = (screen->pitch / 2) - area->w; + + for (h = area->h; h; h--) { + for (w = area->w / 8; w; w--) { + maskb = *mask++; + datab = *data++; + for (i = 0; i < 8; ++i) { + if (maskb & 0x80) { + *dst = (Uint16) pixels[datab >> 7]; + } + maskb <<= 1; + datab <<= 1; + dst++; + } + } + dst += dstskip; + } + } + break; + + case 3: + { + Uint8 *dst; + int dstskip; + + dst = (Uint8 *) screen->pixels + + (SDL_cursor->area.y + area->y) * screen->pitch + + SDL_cursor->area.x * 3; + dstskip = screen->pitch - area->w * 3; + + for (h = area->h; h; h--) { + for (w = area->w / 8; w; w--) { + maskb = *mask++; + datab = *data++; + for (i = 0; i < 8; ++i) { + if (maskb & 0x80) { + SDL_memset(dst, pixels[datab >> 7], 3); + } + maskb <<= 1; + datab <<= 1; + dst += 3; + } + } + dst += dstskip; + } + } + break; + + case 4: + { + Uint32 *dst; + int dstskip; + + dst = (Uint32 *) screen->pixels + + (SDL_cursor->area.y + area->y) * screen->pitch / 4 + + SDL_cursor->area.x; + dstskip = (screen->pitch / 4) - area->w; + + for (h = area->h; h; h--) { + for (w = area->w / 8; w; w--) { + maskb = *mask++; + datab = *data++; + for (i = 0; i < 8; ++i) { + if (maskb & 0x80) { + *dst = pixels[datab >> 7]; + } + maskb <<= 1; + datab <<= 1; + dst++; + } + } + dst += dstskip; + } + } + break; + } +} + +static void +SDL_DrawCursorSlow(SDL_Surface * screen, SDL_Rect * area) +{ + const Uint32 pixels[2] = { 0xFFFFFF, 0x000000 }; + int h; + int x, minx, maxx; + Uint8 *data, datab = 0; + Uint8 *mask, maskb = 0; + Uint8 *dst; + int dstbpp, dstskip; + + data = SDL_cursor->data + area->y * SDL_cursor->area.w / 8; + mask = SDL_cursor->mask + area->y * SDL_cursor->area.w / 8; + dstbpp = screen->format->BytesPerPixel; + dst = (Uint8 *) screen->pixels + + (SDL_cursor->area.y + area->y) * screen->pitch + + SDL_cursor->area.x * dstbpp; + dstskip = screen->pitch - SDL_cursor->area.w * dstbpp; + + minx = area->x; + maxx = area->x + area->w; + if (screen->format->BytesPerPixel == 1) { + if (palette_changed) { + pixels8[0] = (Uint8) SDL_MapRGB(screen->format, 255, 255, 255); + pixels8[1] = (Uint8) SDL_MapRGB(screen->format, 0, 0, 0); + palette_changed = 0; + } + for (h = area->h; h; h--) { + for (x = 0; x < SDL_cursor->area.w; ++x) { + if ((x % 8) == 0) { + maskb = *mask++; + datab = *data++; + } + if ((x >= minx) && (x < maxx)) { + if (maskb & 0x80) { + SDL_memset(dst, pixels8[datab >> 7], dstbpp); + } + } + maskb <<= 1; + datab <<= 1; + dst += dstbpp; + } + dst += dstskip; + } + } else { + for (h = area->h; h; h--) { + for (x = 0; x < SDL_cursor->area.w; ++x) { + if ((x % 8) == 0) { + maskb = *mask++; + datab = *data++; + } + if ((x >= minx) && (x < maxx)) { + if (maskb & 0x80) { + SDL_memset(dst, pixels[datab >> 7], dstbpp); + } + } + maskb <<= 1; + datab <<= 1; + dst += dstbpp; + } + dst += dstskip; + } + } +} + +/* This handles the ugly work of converting the saved cursor background from + the pixel format of the shadow surface to that of the video surface. + This is only necessary when blitting from a shadow surface of a different + pixel format than the video surface, and using a software rendered cursor. +*/ +static void +SDL_ConvertCursorSave(SDL_Surface * screen, int w, int h) +{ + SDL_VideoDevice *_this = SDL_GetVideoDevice(); + SDL_BlitInfo info; + SDL_loblit RunBlit; + + /* Make sure we can steal the blit mapping */ + if (screen->map->dst != SDL_VideoSurface) { + return; + } + + /* Set up the blit information */ + info.s_pixels = SDL_cursor->save[1]; + info.s_width = w; + info.s_height = h; + info.s_skip = 0; + info.d_pixels = SDL_cursor->save[0]; + info.d_width = w; + info.d_height = h; + info.d_skip = 0; + info.aux_data = screen->map->sw_data->aux_data; + info.src = screen->format; + info.table = screen->map->table; + info.dst = SDL_VideoSurface->format; + RunBlit = screen->map->sw_data->blit; + + /* Run the actual software blit */ + RunBlit(&info); +} + +void +SDL_DrawCursorNoLock(SDL_Surface * screen) +{ + SDL_VideoDevice *_this = SDL_GetVideoDevice(); + SDL_Rect area; + + /* Get the mouse rectangle, clipped to the screen */ + SDL_MouseRect(&area); + if ((area.w == 0) || (area.h == 0)) { + return; + } + + /* Copy mouse background */ + { + int w, h, screenbpp; + Uint8 *src, *dst; + + /* Set up the copy pointers */ + screenbpp = screen->format->BytesPerPixel; + if ((screen == SDL_VideoSurface) || + FORMAT_EQUAL(screen->format, SDL_VideoSurface->format)) { + dst = SDL_cursor->save[0]; + } else { + dst = SDL_cursor->save[1]; + } + src = (Uint8 *) screen->pixels + area.y * screen->pitch + + area.x * screenbpp; + + /* Perform the copy */ + w = area.w * screenbpp; + h = area.h; + while (h--) { + SDL_memcpy(dst, src, w); + dst += w; + src += screen->pitch; + } + } + + /* Draw the mouse cursor */ + area.x -= SDL_cursor->area.x; + area.y -= SDL_cursor->area.y; + if ((area.x == 0) && (area.w == SDL_cursor->area.w)) { + SDL_DrawCursorFast(screen, &area); + } else { + SDL_DrawCursorSlow(screen, &area); + } +} + +void +SDL_DrawCursor(SDL_Surface * screen) +{ + /* Lock the screen if necessary */ + if (screen == NULL) { + return; + } + if (SDL_MUSTLOCK(screen)) { + if (SDL_LockSurface(screen) < 0) { + return; + } + } + + SDL_DrawCursorNoLock(screen); + + /* Unlock the screen and update if necessary */ + if (SDL_MUSTLOCK(screen)) { + SDL_UnlockSurface(screen); + } + if ((screen->flags & SDL_SCREEN_SURFACE) && + !(screen->flags & SDL_HWSURFACE)) { + SDL_VideoDevice *_this = SDL_GetVideoDevice(); + SDL_Window *window; + SDL_Rect area; + + window = SDL_GetWindowFromSurface(screen); + if (!window) { + return; + } + + SDL_MouseRect(&area); + + if (_this->UpdateWindowSurface) { + _this->UpdateWindowSurface(_this, window, 1, &area); + } + } +} + +void +SDL_EraseCursorNoLock(SDL_Surface * screen) +{ + SDL_VideoDevice *_this = SDL_GetVideoDevice(); + SDL_Window *window; + SDL_Rect area; + + /* Get the window associated with the surface */ + window = SDL_GetWindowFromSurface(screen); + if (!window || !window->surface) { + return; + } + + /* Get the mouse rectangle, clipped to the screen */ + SDL_MouseRect(&area); + if ((area.w == 0) || (area.h == 0)) { + return; + } + + /* Copy mouse background */ + { + int w, h, screenbpp; + Uint8 *src, *dst; + + /* Set up the copy pointers */ + screenbpp = screen->format->BytesPerPixel; + if ((screen->flags & SDL_SCREEN_SURFACE) || + FORMAT_EQUAL(screen->format, window->surface->format)) { + src = SDL_cursor->save[0]; + } else { + src = SDL_cursor->save[1]; + } + dst = (Uint8 *) screen->pixels + area.y * screen->pitch + + area.x * screenbpp; + + /* Perform the copy */ + w = area.w * screenbpp; + h = area.h; + while (h--) { + SDL_memcpy(dst, src, w); + src += w; + dst += screen->pitch; + } + + /* Perform pixel conversion on cursor background */ + if (src > SDL_cursor->save[1]) { + SDL_ConvertCursorSave(screen, area.w, area.h); + } + } +} + +void +SDL_EraseCursor(SDL_Surface * screen) +{ + /* Lock the screen if necessary */ + if (screen == NULL) { + return; + } + if (SDL_MUSTLOCK(screen)) { + if (SDL_LockSurface(screen) < 0) { + return; + } + } + + SDL_EraseCursorNoLock(screen); + + /* Unlock the screen and update if necessary */ + if (SDL_MUSTLOCK(screen)) { + SDL_UnlockSurface(screen); + } + if ((screen->flags & SDL_SCREEN_SURFACE) && + !(screen->flags & SDL_HWSURFACE)) { + SDL_VideoDevice *_this = SDL_GetVideoDevice(); + SDL_Window *window; + SDL_Rect area; + + window = SDL_GetWindowFromSurface(screen); + if (!window) { + return; + } + + SDL_MouseRect(&area); + + if (_this->UpdateWindowSurface) { + _this->UpdateWindowSurface(_this, window, 1, &area); + } + } +} + +/* Reset the cursor on video mode change + FIXME: Keep track of all cursors, and reset them all. + */ +void +SDL_ResetCursor(void) +{ + int savelen; + + if (SDL_cursor) { + savelen = SDL_cursor->area.w * 4 * SDL_cursor->area.h; + SDL_cursor->area.x = 0; + SDL_cursor->area.y = 0; + SDL_memset(SDL_cursor->save[0], 0, savelen); + } +} +#endif + +struct private_yuvhwdata +{ + Uint16 pitches[3]; + Uint8 *planes[3]; + + SDL_TextureID textureID; +}; + +SDL_Overlay * +SDL_CreateYUVOverlay(int w, int h, Uint32 format, SDL_Surface * display) +{ + SDL_Overlay *overlay; + Uint32 texture_format; + + if ((display->flags & SDL_OPENGL) == SDL_OPENGL) { + SDL_SetError("YUV overlays are not supported in OpenGL mode"); + return NULL; + } + + if (display != SDL_PublicSurface) { + SDL_SetError("YUV display is only supported on the screen surface"); + return NULL; + } + + switch (format) { + case SDL_YV12_OVERLAY: + texture_format = SDL_PixelFormat_YV12; + break; + case SDL_IYUV_OVERLAY: + texture_format = SDL_PixelFormat_IYUV; + break; + case SDL_YUY2_OVERLAY: + texture_format = SDL_PixelFormat_YUY2; + break; + case SDL_UYVY_OVERLAY: + texture_format = SDL_PixelFormat_UYVY; + break; + case SDL_YVYU_OVERLAY: + texture_format = SDL_PixelFormat_YVYU; + break; + default: + SDL_SetError("Unknown YUV format"); + return NULL; + } + + overlay = (SDL_Overlay *) SDL_malloc(sizeof(*overlay)); + if (!overlay) { + SDL_OutOfMemory(); + return NULL; + } + SDL_zerop(overlay); + + overlay->hwdata = + (struct private_yuvhwdata *) SDL_malloc(sizeof(*overlay->hwdata)); + if (!overlay->hwdata) { + SDL_free(overlay); + SDL_OutOfMemory(); + return NULL; + } + + overlay->format = format; + overlay->w = w; + overlay->h = h; + if (format == SDL_YV12_OVERLAY || format == SDL_IYUV_OVERLAY) { + overlay->planes = 3; + } else { + overlay->planes = 1; + } + overlay->pitches = overlay->hwdata->pitches; + overlay->pixels = overlay->hwdata->planes; + + switch (format) { + case SDL_YV12_OVERLAY: + case SDL_IYUV_OVERLAY: + overlay->pitches[0] = overlay->w; + overlay->pitches[1] = overlay->w / 2; + overlay->pitches[2] = overlay->w / 2; + break; + case SDL_YUY2_OVERLAY: + case SDL_UYVY_OVERLAY: + case SDL_YVYU_OVERLAY: + overlay->pitches[0] = overlay->w * 2; + break; + } + + overlay->hwdata->textureID = + SDL_CreateTexture(texture_format, SDL_TextureAccess_Local, w, h); + if (!overlay->hwdata->textureID) { + SDL_FreeYUVOverlay(overlay); + return NULL; + } + + return overlay; +} + +int +SDL_LockYUVOverlay(SDL_Overlay * overlay) +{ + void *pixels; + int pitch; + if (SDL_LockTexture(overlay->hwdata->textureID, NULL, 1, &pixels, &pitch) + < 0) { + return -1; + } + switch (overlay->format) { + case SDL_YV12_OVERLAY: + case SDL_IYUV_OVERLAY: + overlay->pixels[0] = (Uint8 *) pixels; + overlay->pixels[1] = + overlay->pixels[0] + overlay->pitches[0] * overlay->h; + overlay->pixels[2] = + overlay->pixels[1] + overlay->pitches[1] * overlay->h; + break; + case SDL_YUY2_OVERLAY: + case SDL_UYVY_OVERLAY: + case SDL_YVYU_OVERLAY: + overlay->pixels[0] = (Uint8 *) pixels; + break; + } + return 0; +} + +void +SDL_UnlockYUVOverlay(SDL_Overlay * overlay) +{ + SDL_UnlockTexture(overlay->hwdata->textureID); +} + +int +SDL_DisplayYUVOverlay(SDL_Overlay * overlay, SDL_Rect * dstrect) +{ + if (SDL_RenderCopy(overlay->hwdata->textureID, NULL, dstrect, + SDL_TextureBlendMode_None, + SDL_TextureScaleMode_Fast) < 0) { + return -1; + } + SDL_RenderPresent(); + return 0; +} + +void +SDL_FreeYUVOverlay(SDL_Overlay * overlay) +{ + if (overlay) { + if (overlay->hwdata) { + if (overlay->hwdata->textureID) { + SDL_DestroyTexture(overlay->hwdata->textureID); + } + SDL_free(overlay->hwdata); + } + SDL_free(overlay); + } +} + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/SDL_error.c b/src/SDL_error.c index 11632f281..bb1b2555a 100644 --- a/src/SDL_error.c +++ b/src/SDL_error.c @@ -39,200 +39,217 @@ extern SDL_error *SDL_GetErrBuf(void); /* Private functions */ -static const char *SDL_LookupString(const char *key) +static const char * +SDL_LookupString(const char *key) { - /* FIXME: Add code to lookup key in language string hash-table */ - return key; + /* FIXME: Add code to lookup key in language string hash-table */ + return key; } /* Public functions */ -void SDL_SetError (const char *fmt, ...) +void +SDL_SetError(const char *fmt, ...) { - va_list ap; - SDL_error *error; - - /* Copy in the key, mark error as valid */ - error = SDL_GetErrBuf(); - error->error = 1; - SDL_strlcpy((char *)error->key, fmt, sizeof(error->key)); - - va_start(ap, fmt); - error->argc = 0; - while ( *fmt ) { - if ( *fmt++ == '%' ) { - while ( *fmt == '.' || (*fmt >= '0' && *fmt <= '9') ) { - ++fmt; - } - switch (*fmt++) { - case 0: /* Malformed format string.. */ - --fmt; - break; - case 'c': - case 'i': - case 'd': - case 'u': - case 'o': - case 'x': - case 'X': - error->args[error->argc++].value_i = - va_arg(ap, int); - break; - case 'f': - error->args[error->argc++].value_f = - va_arg(ap, double); - break; - case 'p': - error->args[error->argc++].value_ptr = - va_arg(ap, void *); - break; - case 's': - { - int i = error->argc; - const char *str = va_arg(ap, const char *); - if (str == NULL) - str = "(null)"; - SDL_strlcpy((char *)error->args[i].buf, str, ERR_MAX_STRLEN); - error->argc++; - } - break; - default: - break; - } - if ( error->argc >= ERR_MAX_ARGS ) { - break; - } - } - } - va_end(ap); - - /* If we are in debug mode, print out an error message */ + va_list ap; + SDL_error *error; + + /* Copy in the key, mark error as valid */ + error = SDL_GetErrBuf(); + error->error = 1; + SDL_strlcpy((char *) error->key, fmt, sizeof(error->key)); + + va_start(ap, fmt); + error->argc = 0; + while (*fmt) { + if (*fmt++ == '%') { + while (*fmt == '.' || (*fmt >= '0' && *fmt <= '9')) { + ++fmt; + } + switch (*fmt++) { + case 0: /* Malformed format string.. */ + --fmt; + break; + case 'c': + case 'i': + case 'd': + case 'u': + case 'o': + case 'x': + case 'X': + error->args[error->argc++].value_i = va_arg(ap, int); + break; + case 'f': + error->args[error->argc++].value_f = va_arg(ap, double); + break; + case 'p': + error->args[error->argc++].value_ptr = va_arg(ap, void *); + break; + case 's': + { + int i = error->argc; + const char *str = va_arg(ap, const char *); + if (str == NULL) + str = "(null)"; + SDL_strlcpy((char *) error->args[i].buf, str, + ERR_MAX_STRLEN); + error->argc++; + } + break; + default: + break; + } + if (error->argc >= ERR_MAX_ARGS) { + break; + } + } + } + va_end(ap); + + /* If we are in debug mode, print out an error message */ #ifdef DEBUG_ERROR - fprintf(stderr, "SDL_SetError: %s\n", SDL_GetError()); + fprintf(stderr, "SDL_SetError: %s\n", SDL_GetError()); #endif } /* This function has a bit more overhead than most error functions so that it supports internationalization and thread-safe errors. */ -char *SDL_GetErrorMsg(char *errstr, unsigned int maxlen) +char * +SDL_GetErrorMsg(char *errstr, unsigned int maxlen) { - SDL_error *error; - - /* Clear the error string */ - *errstr = '\0'; --maxlen; - - /* Get the thread-safe error, and print it out */ - error = SDL_GetErrBuf(); - if ( error->error ) { - const char *fmt; - char *msg = errstr; - int len; - int argi; - - fmt = SDL_LookupString(error->key); - argi = 0; - while ( *fmt && (maxlen > 0) ) { - if ( *fmt == '%' ) { - char tmp[32], *spot = tmp; - *spot++ = *fmt++; - while ( (*fmt == '.' || (*fmt >= '0' && *fmt <= '9')) && spot < (tmp+SDL_arraysize(tmp)-2) ) { - *spot++ = *fmt++; - } - *spot++ = *fmt++; - *spot++ = '\0'; - switch (spot[-2]) { - case '%': - *msg++ = '%'; - maxlen -= 1; - break; - case 'c': - case 'i': - case 'd': - case 'u': - case 'o': - case 'x': - case 'X': - len = SDL_snprintf(msg, maxlen, tmp, error->args[argi++].value_i); - msg += len; - maxlen -= len; - break; - case 'f': - len = SDL_snprintf(msg, maxlen, tmp, error->args[argi++].value_f); - msg += len; - maxlen -= len; - break; - case 'p': - len = SDL_snprintf(msg, maxlen, tmp, error->args[argi++].value_ptr); - msg += len; - maxlen -= len; - break; - case 's': - len = SDL_snprintf(msg, maxlen, tmp, SDL_LookupString(error->args[argi++].buf)); - msg += len; - maxlen -= len; - break; - } - } else { - *msg++ = *fmt++; - maxlen -= 1; - } - } - *msg = 0; /* NULL terminate the string */ - } - return(errstr); + SDL_error *error; + + /* Clear the error string */ + *errstr = '\0'; + --maxlen; + + /* Get the thread-safe error, and print it out */ + error = SDL_GetErrBuf(); + if (error->error) { + const char *fmt; + char *msg = errstr; + int len; + int argi; + + fmt = SDL_LookupString(error->key); + argi = 0; + while (*fmt && (maxlen > 0)) { + if (*fmt == '%') { + char tmp[32], *spot = tmp; + *spot++ = *fmt++; + while ((*fmt == '.' || (*fmt >= '0' && *fmt <= '9')) + && spot < (tmp + SDL_arraysize(tmp) - 2)) { + *spot++ = *fmt++; + } + *spot++ = *fmt++; + *spot++ = '\0'; + switch (spot[-2]) { + case '%': + *msg++ = '%'; + maxlen -= 1; + break; + case 'c': + case 'i': + case 'd': + case 'u': + case 'o': + case 'x': + case 'X': + len = + SDL_snprintf(msg, maxlen, tmp, + error->args[argi++].value_i); + msg += len; + maxlen -= len; + break; + case 'f': + len = + SDL_snprintf(msg, maxlen, tmp, + error->args[argi++].value_f); + msg += len; + maxlen -= len; + break; + case 'p': + len = + SDL_snprintf(msg, maxlen, tmp, + error->args[argi++].value_ptr); + msg += len; + maxlen -= len; + break; + case 's': + len = + SDL_snprintf(msg, maxlen, tmp, + SDL_LookupString(error-> + args[argi++].buf)); + msg += len; + maxlen -= len; + break; + } + } else { + *msg++ = *fmt++; + maxlen -= 1; + } + } + *msg = 0; /* NULL terminate the string */ + } + return (errstr); } /* Available for backwards compatibility */ -char *SDL_GetError (void) +char * +SDL_GetError(void) { - static char errmsg[SDL_ERRBUFIZE]; + static char errmsg[SDL_ERRBUFIZE]; - return((char *)SDL_GetErrorMsg(errmsg, SDL_ERRBUFIZE)); + return ((char *) SDL_GetErrorMsg(errmsg, SDL_ERRBUFIZE)); } -void SDL_ClearError(void) +void +SDL_ClearError(void) { - SDL_error *error; + SDL_error *error; - error = SDL_GetErrBuf(); - error->error = 0; + error = SDL_GetErrBuf(); + error->error = 0; } /* Very common errors go here */ -void SDL_Error(SDL_errorcode code) +void +SDL_Error(SDL_errorcode code) { - switch (code) { - case SDL_ENOMEM: - SDL_SetError("Out of memory"); - break; - case SDL_EFREAD: - SDL_SetError("Error reading from datastream"); - break; - case SDL_EFWRITE: - SDL_SetError("Error writing to datastream"); - break; - case SDL_EFSEEK: - SDL_SetError("Error seeking in datastream"); - break; - default: - SDL_SetError("Unknown SDL error"); - break; - } + switch (code) { + case SDL_ENOMEM: + SDL_SetError("Out of memory"); + break; + case SDL_EFREAD: + SDL_SetError("Error reading from datastream"); + break; + case SDL_EFWRITE: + SDL_SetError("Error writing to datastream"); + break; + case SDL_EFSEEK: + SDL_SetError("Error seeking in datastream"); + break; + default: + SDL_SetError("Unknown SDL error"); + break; + } } #ifdef TEST_ERROR -int main(int argc, char *argv[]) +int +main(int argc, char *argv[]) { - char buffer[BUFSIZ+1]; - - SDL_SetError("Hi there!"); - printf("Error 1: %s\n", SDL_GetError()); - SDL_ClearError(); - SDL_memset(buffer, '1', BUFSIZ); - buffer[BUFSIZ] = 0; - SDL_SetError("This is the error: %s (%f)", buffer, 1.0); - printf("Error 2: %s\n", SDL_GetError()); - exit(0); + char buffer[BUFSIZ + 1]; + + SDL_SetError("Hi there!"); + printf("Error 1: %s\n", SDL_GetError()); + SDL_ClearError(); + SDL_memset(buffer, '1', BUFSIZ); + buffer[BUFSIZ] = 0; + SDL_SetError("This is the error: %s (%f)", buffer, 1.0); + printf("Error 2: %s\n", SDL_GetError()); + exit(0); } #endif +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/SDL_error_c.h b/src/SDL_error_c.h index 990acb56b..f0afff10a 100644 --- a/src/SDL_error_c.h +++ b/src/SDL_error_c.h @@ -31,28 +31,31 @@ #define ERR_MAX_STRLEN 128 #define ERR_MAX_ARGS 5 -typedef struct SDL_error { - /* This is a numeric value corresponding to the current error */ - int error; - - /* This is a key used to index into a language hashtable containing - internationalized versions of the SDL error messages. If the key - is not in the hashtable, or no hashtable is available, the key is - used directly as an error message format string. - */ - char key[ERR_MAX_STRLEN]; - - /* These are the arguments for the error functions */ - int argc; - union { - void *value_ptr; -#if 0 /* What is a character anyway? (UNICODE issues) */ - unsigned char value_c; +typedef struct SDL_error +{ + /* This is a numeric value corresponding to the current error */ + int error; + + /* This is a key used to index into a language hashtable containing + internationalized versions of the SDL error messages. If the key + is not in the hashtable, or no hashtable is available, the key is + used directly as an error message format string. + */ + char key[ERR_MAX_STRLEN]; + + /* These are the arguments for the error functions */ + int argc; + union + { + void *value_ptr; +#if 0 /* What is a character anyway? (UNICODE issues) */ + unsigned char value_c; #endif - int value_i; - double value_f; - char buf[ERR_MAX_STRLEN]; - } args[ERR_MAX_ARGS]; + int value_i; + double value_f; + char buf[ERR_MAX_STRLEN]; + } args[ERR_MAX_ARGS]; } SDL_error; #endif /* _SDL_error_c_h */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/SDL_fatal.c b/src/SDL_fatal.c index 784836b9f..ccd6b87ab 100644 --- a/src/SDL_fatal.c +++ b/src/SDL_fatal.c @@ -35,85 +35,88 @@ the program crashes. */ -static void SDL_Parachute(int sig) +static void +SDL_Parachute(int sig) { - signal(sig, SIG_DFL); - SDL_Quit(); - raise(sig); + signal(sig, SIG_DFL); + SDL_Quit(); + raise(sig); } static int SDL_fatal_signals[] = { - SIGSEGV, + SIGSEGV, #ifdef SIGBUS - SIGBUS, + SIGBUS, #endif #ifdef SIGFPE - SIGFPE, + SIGFPE, #endif #ifdef SIGQUIT - SIGQUIT, + SIGQUIT, #endif - 0 + 0 }; -void SDL_InstallParachute(void) +void +SDL_InstallParachute(void) { - /* Set a handler for any fatal signal not already handled */ - int i; + /* Set a handler for any fatal signal not already handled */ + int i; #ifdef HAVE_SIGACTION - struct sigaction action; - - for ( i=0; SDL_fatal_signals[i]; ++i ) { - sigaction(SDL_fatal_signals[i], NULL, &action); - if ( action.sa_handler == SIG_DFL ) { - action.sa_handler = SDL_Parachute; - sigaction(SDL_fatal_signals[i], &action, NULL); - } - } + struct sigaction action; + + for (i = 0; SDL_fatal_signals[i]; ++i) { + sigaction(SDL_fatal_signals[i], NULL, &action); + if (action.sa_handler == SIG_DFL) { + action.sa_handler = SDL_Parachute; + sigaction(SDL_fatal_signals[i], &action, NULL); + } + } #ifdef SIGALRM - /* Set SIGALRM to be ignored -- necessary on Solaris */ - sigaction(SIGALRM, NULL, &action); - if ( action.sa_handler == SIG_DFL ) { - action.sa_handler = SIG_IGN; - sigaction(SIGALRM, &action, NULL); - } + /* Set SIGALRM to be ignored -- necessary on Solaris */ + sigaction(SIGALRM, NULL, &action); + if (action.sa_handler == SIG_DFL) { + action.sa_handler = SIG_IGN; + sigaction(SIGALRM, &action, NULL); + } #endif #else - void (*ohandler)(int); - - for ( i=0; SDL_fatal_signals[i]; ++i ) { - ohandler = signal(SDL_fatal_signals[i], SDL_Parachute); - if ( ohandler != SIG_DFL ) { - signal(SDL_fatal_signals[i], ohandler); - } - } + void (*ohandler) (int); + + for (i = 0; SDL_fatal_signals[i]; ++i) { + ohandler = signal(SDL_fatal_signals[i], SDL_Parachute); + if (ohandler != SIG_DFL) { + signal(SDL_fatal_signals[i], ohandler); + } + } #endif /* HAVE_SIGACTION */ - return; + return; } -void SDL_UninstallParachute(void) +void +SDL_UninstallParachute(void) { - /* Remove a handler for any fatal signal handled */ - int i; + /* Remove a handler for any fatal signal handled */ + int i; #ifdef HAVE_SIGACTION - struct sigaction action; - - for ( i=0; SDL_fatal_signals[i]; ++i ) { - sigaction(SDL_fatal_signals[i], NULL, &action); - if ( action.sa_handler == SDL_Parachute ) { - action.sa_handler = SIG_DFL; - sigaction(SDL_fatal_signals[i], &action, NULL); - } - } + struct sigaction action; + + for (i = 0; SDL_fatal_signals[i]; ++i) { + sigaction(SDL_fatal_signals[i], NULL, &action); + if (action.sa_handler == SDL_Parachute) { + action.sa_handler = SIG_DFL; + sigaction(SDL_fatal_signals[i], &action, NULL); + } + } #else - void (*ohandler)(int); - - for ( i=0; SDL_fatal_signals[i]; ++i ) { - ohandler = signal(SDL_fatal_signals[i], SIG_DFL); - if ( ohandler != SDL_Parachute ) { - signal(SDL_fatal_signals[i], ohandler); - } - } + void (*ohandler) (int); + + for (i = 0; SDL_fatal_signals[i]; ++i) { + ohandler = signal(SDL_fatal_signals[i], SIG_DFL); + if (ohandler != SDL_Parachute) { + signal(SDL_fatal_signals[i], ohandler); + } + } #endif /* HAVE_SIGACTION */ } @@ -121,14 +124,17 @@ void SDL_UninstallParachute(void) /* No signals on this platform, nothing to do.. */ -void SDL_InstallParachute(void) +void +SDL_InstallParachute(void) { - return; + return; } -void SDL_UninstallParachute(void) +void +SDL_UninstallParachute(void) { - return; + return; } #endif /* HAVE_SIGNAL_H */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/SDL_fatal.h b/src/SDL_fatal.h index 34b60690c..4d0d256be 100644 --- a/src/SDL_fatal.h +++ b/src/SDL_fatal.h @@ -25,4 +25,4 @@ extern void SDL_InstallParachute(void); extern void SDL_UninstallParachute(void); - +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/audio/SDL_audio.c b/src/audio/SDL_audio.c index 84a5e0742..4fd9d57e7 100644 --- a/src/audio/SDL_audio.c +++ b/src/audio/SDL_audio.c @@ -37,77 +37,77 @@ /* Available audio drivers */ static AudioBootStrap *bootstrap[] = { #if SDL_AUDIO_DRIVER_BSD - &BSD_AUDIO_bootstrap, + &BSD_AUDIO_bootstrap, #endif #if SDL_AUDIO_DRIVER_OSS - &DSP_bootstrap, - &DMA_bootstrap, + &DSP_bootstrap, + &DMA_bootstrap, #endif #if SDL_AUDIO_DRIVER_ALSA - &ALSA_bootstrap, + &ALSA_bootstrap, #endif #if SDL_AUDIO_DRIVER_QNXNTO - &QNXNTOAUDIO_bootstrap, + &QNXNTOAUDIO_bootstrap, #endif #if SDL_AUDIO_DRIVER_SUNAUDIO - &SUNAUDIO_bootstrap, + &SUNAUDIO_bootstrap, #endif #if SDL_AUDIO_DRIVER_DMEDIA - &DMEDIA_bootstrap, + &DMEDIA_bootstrap, #endif #if SDL_AUDIO_DRIVER_ARTS - &ARTS_bootstrap, + &ARTS_bootstrap, #endif #if SDL_AUDIO_DRIVER_ESD - &ESD_bootstrap, + &ESD_bootstrap, #endif #if SDL_AUDIO_DRIVER_NAS - &NAS_bootstrap, + &NAS_bootstrap, #endif #if SDL_AUDIO_DRIVER_DSOUND - &DSOUND_bootstrap, + &DSOUND_bootstrap, #endif #if SDL_AUDIO_DRIVER_WAVEOUT - &WAVEOUT_bootstrap, + &WAVEOUT_bootstrap, #endif #if SDL_AUDIO_DRIVER_PAUD - &Paud_bootstrap, + &Paud_bootstrap, #endif #if SDL_AUDIO_DRIVER_BAUDIO - &BAUDIO_bootstrap, + &BAUDIO_bootstrap, #endif #if SDL_AUDIO_DRIVER_COREAUDIO - &COREAUDIO_bootstrap, + &COREAUDIO_bootstrap, #endif #if SDL_AUDIO_DRIVER_SNDMGR - &SNDMGR_bootstrap, + &SNDMGR_bootstrap, #endif #if SDL_AUDIO_DRIVER_AHI - &AHI_bootstrap, + &AHI_bootstrap, #endif #if SDL_AUDIO_DRIVER_MINT - &MINTAUDIO_GSXB_bootstrap, - &MINTAUDIO_MCSN_bootstrap, - &MINTAUDIO_STFA_bootstrap, - &MINTAUDIO_XBIOS_bootstrap, - &MINTAUDIO_DMA8_bootstrap, + &MINTAUDIO_GSXB_bootstrap, + &MINTAUDIO_MCSN_bootstrap, + &MINTAUDIO_STFA_bootstrap, + &MINTAUDIO_XBIOS_bootstrap, + &MINTAUDIO_DMA8_bootstrap, #endif #if SDL_AUDIO_DRIVER_DISK - &DISKAUD_bootstrap, + &DISKAUD_bootstrap, #endif #if SDL_AUDIO_DRIVER_DUMMY - &DUMMYAUD_bootstrap, + &DUMMYAUD_bootstrap, #endif #if SDL_AUDIO_DRIVER_DC - &DCAUD_bootstrap, + &DCAUD_bootstrap, #endif #if SDL_AUDIO_DRIVER_MMEAUDIO - &MMEAUDIO_bootstrap, + &MMEAUDIO_bootstrap, #endif #if SDL_AUDIO_DRIVER_DART - &DART_bootstrap, + &DART_bootstrap, #endif - NULL + NULL }; SDL_AudioDevice *current_audio = NULL; @@ -120,642 +120,684 @@ static int audio_configured = 0; #endif /* The general mixing thread function */ -int SDLCALL SDL_RunAudio(void *audiop) +int SDLCALL +SDL_RunAudio(void *audiop) { - SDL_AudioDevice *audio = (SDL_AudioDevice *)audiop; - Uint8 *stream; - int stream_len; - void *udata; - void (SDLCALL *fill)(void *userdata,Uint8 *stream, int len); - int silence; + SDL_AudioDevice *audio = (SDL_AudioDevice *) audiop; + Uint8 *stream; + int stream_len; + void *udata; + void (SDLCALL * fill) (void *userdata, Uint8 * stream, int len); + int silence; #if SDL_AUDIO_DRIVER_AHI - int started = 0; + int started = 0; /* AmigaOS NEEDS that the audio driver is opened in the thread that uses it! */ - D(bug("Task audio started audio struct:<%lx>...\n",audiop)); + D(bug("Task audio started audio struct:<%lx>...\n", audiop)); - D(bug("Before Openaudio...")); - if(audio->OpenAudio(audio, &audio->spec)==-1) - { - D(bug("Open audio failed...\n")); - return(-1); - } - D(bug("OpenAudio...OK\n")); + D(bug("Before Openaudio...")); + if (audio->OpenAudio(audio, &audio->spec) == -1) { + D(bug("Open audio failed...\n")); + return (-1); + } + D(bug("OpenAudio...OK\n")); #endif - /* Perform any thread setup */ - if ( audio->ThreadInit ) { - audio->ThreadInit(audio); - } - audio->threadid = SDL_ThreadID(); + /* Perform any thread setup */ + if (audio->ThreadInit) { + audio->ThreadInit(audio); + } + audio->threadid = SDL_ThreadID(); - /* Set up the mixing function */ - fill = audio->spec.callback; - udata = audio->spec.userdata; + /* Set up the mixing function */ + fill = audio->spec.callback; + udata = audio->spec.userdata; #if SDL_AUDIO_DRIVER_AHI - audio_configured = 1; + audio_configured = 1; - D(bug("Audio configured... Checking for conversion\n")); - SDL_mutexP(audio->mixer_lock); - D(bug("Semaphore obtained...\n")); + D(bug("Audio configured... Checking for conversion\n")); + SDL_mutexP(audio->mixer_lock); + D(bug("Semaphore obtained...\n")); #endif - if ( audio->convert.needed ) { - if ( audio->convert.src_format == AUDIO_U8 ) { - silence = 0x80; - } else { - silence = 0; - } - stream_len = audio->convert.len; - } else { - silence = audio->spec.silence; - stream_len = audio->spec.size; - } + if (audio->convert.needed) { + if (audio->convert.src_format == AUDIO_U8) { + silence = 0x80; + } else { + silence = 0; + } + stream_len = audio->convert.len; + } else { + silence = audio->spec.silence; + stream_len = audio->spec.size; + } #if SDL_AUDIO_DRIVER_AHI - SDL_mutexV(audio->mixer_lock); - D(bug("Entering audio loop...\n")); + SDL_mutexV(audio->mixer_lock); + D(bug("Entering audio loop...\n")); #endif #ifdef __OS2__ - /* Increase the priority of this thread to make sure that - the audio will be continuous all the time! */ + /* Increase the priority of this thread to make sure that + the audio will be continuous all the time! */ #ifdef USE_DOSSETPRIORITY - if (SDL_getenv("SDL_USE_TIMECRITICAL_AUDIO")) - { + if (SDL_getenv("SDL_USE_TIMECRITICAL_AUDIO")) { #ifdef DEBUG_BUILD - printf("[SDL_RunAudio] : Setting priority to TimeCritical+0! (TID%d)\n", SDL_ThreadID()); + printf + ("[SDL_RunAudio] : Setting priority to TimeCritical+0! (TID%d)\n", + SDL_ThreadID()); #endif - DosSetPriority(PRTYS_THREAD, PRTYC_TIMECRITICAL, 0, 0); - } - else - { + DosSetPriority(PRTYS_THREAD, PRTYC_TIMECRITICAL, 0, 0); + } else { #ifdef DEBUG_BUILD - printf("[SDL_RunAudio] : Setting priority to ForegroundServer+0! (TID%d)\n", SDL_ThreadID()); -#endif - DosSetPriority(PRTYS_THREAD, PRTYC_FOREGROUNDSERVER, 0, 0); + printf + ("[SDL_RunAudio] : Setting priority to ForegroundServer+0! (TID%d)\n", + SDL_ThreadID()); +#endif + DosSetPriority(PRTYS_THREAD, PRTYC_FOREGROUNDSERVER, 0, 0); + } +#endif +#endif + + /* Loop, filling the audio buffers */ + while (audio->enabled) { + + /* Fill the current buffer with sound */ + if (audio->convert.needed) { + if (audio->convert.buf) { + stream = audio->convert.buf; + } else { + continue; + } + } else { + stream = audio->GetAudioBuf(audio); + if (stream == NULL) { + stream = audio->fake_stream; + } } -#endif -#endif + SDL_memset(stream, silence, stream_len); - /* Loop, filling the audio buffers */ - while ( audio->enabled ) { - - /* Fill the current buffer with sound */ - if ( audio->convert.needed ) { - if ( audio->convert.buf ) { - stream = audio->convert.buf; - } else { - continue; - } - } else { - stream = audio->GetAudioBuf(audio); - if ( stream == NULL ) { - stream = audio->fake_stream; - } - } - SDL_memset(stream, silence, stream_len); - - if ( ! audio->paused ) { - SDL_mutexP(audio->mixer_lock); - (*fill)(udata, stream, stream_len); - SDL_mutexV(audio->mixer_lock); - } - - /* Convert the audio if necessary */ - if ( audio->convert.needed ) { - SDL_ConvertAudio(&audio->convert); - stream = audio->GetAudioBuf(audio); - if ( stream == NULL ) { - stream = audio->fake_stream; - } - SDL_memcpy(stream, audio->convert.buf, - audio->convert.len_cvt); - } - - /* Ready current buffer for play and change current buffer */ - if ( stream != audio->fake_stream ) { - audio->PlayAudio(audio); - } - - /* Wait for an audio buffer to become available */ - if ( stream == audio->fake_stream ) { - SDL_Delay((audio->spec.samples*1000)/audio->spec.freq); - } else { - audio->WaitAudio(audio); - } - } - - /* Wait for the audio to drain.. */ - if ( audio->WaitDone ) { - audio->WaitDone(audio); - } + if (!audio->paused) { + SDL_mutexP(audio->mixer_lock); + (*fill) (udata, stream, stream_len); + SDL_mutexV(audio->mixer_lock); + } + /* Convert the audio if necessary */ + if (audio->convert.needed) { + SDL_ConvertAudio(&audio->convert); + stream = audio->GetAudioBuf(audio); + if (stream == NULL) { + stream = audio->fake_stream; + } + SDL_memcpy(stream, audio->convert.buf, audio->convert.len_cvt); + } + + /* Ready current buffer for play and change current buffer */ + if (stream != audio->fake_stream) { + audio->PlayAudio(audio); + } + + /* Wait for an audio buffer to become available */ + if (stream == audio->fake_stream) { + SDL_Delay((audio->spec.samples * 1000) / audio->spec.freq); + } else { + audio->WaitAudio(audio); + } + } + + /* Wait for the audio to drain.. */ + if (audio->WaitDone) { + audio->WaitDone(audio); + } #if SDL_AUDIO_DRIVER_AHI - D(bug("WaitAudio...Done\n")); + D(bug("WaitAudio...Done\n")); - audio->CloseAudio(audio); + audio->CloseAudio(audio); - D(bug("CloseAudio..Done, subtask exiting...\n")); - audio_configured = 0; + D(bug("CloseAudio..Done, subtask exiting...\n")); + audio_configured = 0; #endif #ifdef __OS2__ #ifdef DEBUG_BUILD - printf("[SDL_RunAudio] : Task exiting. (TID%d)\n", SDL_ThreadID()); + printf("[SDL_RunAudio] : Task exiting. (TID%d)\n", SDL_ThreadID()); #endif #endif - return(0); + return (0); } -static void SDL_LockAudio_Default(SDL_AudioDevice *audio) +static void +SDL_LockAudio_Default(SDL_AudioDevice * audio) { - if ( audio->thread && (SDL_ThreadID() == audio->threadid) ) { - return; - } - SDL_mutexP(audio->mixer_lock); + if (audio->thread && (SDL_ThreadID() == audio->threadid)) { + return; + } + SDL_mutexP(audio->mixer_lock); } -static void SDL_UnlockAudio_Default(SDL_AudioDevice *audio) +static void +SDL_UnlockAudio_Default(SDL_AudioDevice * audio) { - if ( audio->thread && (SDL_ThreadID() == audio->threadid) ) { - return; - } - SDL_mutexV(audio->mixer_lock); + if (audio->thread && (SDL_ThreadID() == audio->threadid)) { + return; + } + SDL_mutexV(audio->mixer_lock); } -static Uint16 SDL_ParseAudioFormat(const char *string) +static Uint16 +SDL_ParseAudioFormat(const char *string) { - Uint16 format = 0; - - switch (*string) { - case 'U': - ++string; - format |= 0x0000; - break; - case 'S': - ++string; - format |= 0x8000; - break; - default: - return 0; - } - switch (SDL_atoi(string)) { - case 8: - string += 1; - format |= 8; - break; - case 16: - string += 2; - format |= 16; - if ( SDL_strcmp(string, "LSB") == 0 + Uint16 format = 0; + + switch (*string) { + case 'U': + ++string; + format |= 0x0000; + break; + case 'S': + ++string; + format |= 0x8000; + break; + default: + return 0; + } + switch (SDL_atoi(string)) { + case 8: + string += 1; + format |= 8; + break; + case 16: + string += 2; + format |= 16; + if (SDL_strcmp(string, "LSB") == 0 #if SDL_BYTEORDER == SDL_LIL_ENDIAN - || SDL_strcmp(string, "SYS") == 0 + || SDL_strcmp(string, "SYS") == 0 #endif - ) { - format |= 0x0000; - } - if ( SDL_strcmp(string, "MSB") == 0 + ) { + format |= 0x0000; + } + if (SDL_strcmp(string, "MSB") == 0 #if SDL_BYTEORDER == SDL_BIG_ENDIAN - || SDL_strcmp(string, "SYS") == 0 -#endif - ) { - format |= 0x1000; - } - break; - default: - return 0; - } - return format; + || SDL_strcmp(string, "SYS") == 0 +#endif + ) { + format |= 0x1000; + } + break; + default: + return 0; + } + return format; } -int SDL_AudioInit(const char *driver_name) +int +SDL_GetNumAudioDrivers(void) { - SDL_AudioDevice *audio; - int i = 0, idx; + return (SDL_arraysize(bootstrap) - 1); +} - /* Check to make sure we don't overwrite 'current_audio' */ - if ( current_audio != NULL ) { - SDL_AudioQuit(); - } +const char * +SDL_GetAudioDriver(int index) +{ + if (index >= 0 && index < SDL_GetNumAudioDrivers()) { + return (bootstrap[index]->name); + } + return (NULL); +} + +int +SDL_AudioInit(const char *driver_name) +{ + SDL_AudioDevice *audio; + int i = 0, idx; - /* Select the proper audio driver */ - audio = NULL; - idx = 0; + /* Check to make sure we don't overwrite 'current_audio' */ + if (current_audio != NULL) { + SDL_AudioQuit(); + } + + /* Select the proper audio driver */ + audio = NULL; + idx = 0; #if SDL_AUDIO_DRIVER_ESD - if ( (driver_name == NULL) && (SDL_getenv("ESPEAKER") != NULL) ) { - /* Ahem, we know that if ESPEAKER is set, user probably wants - to use ESD, but don't start it if it's not already running. - This probably isn't the place to do this, but... Shh! :) - */ - for ( i=0; bootstrap[i]; ++i ) { - if ( SDL_strcmp(bootstrap[i]->name, "esd") == 0 ) { + if ((driver_name == NULL) && (SDL_getenv("ESPEAKER") != NULL)) { + /* Ahem, we know that if ESPEAKER is set, user probably wants + to use ESD, but don't start it if it's not already running. + This probably isn't the place to do this, but... Shh! :) + */ + for (i = 0; bootstrap[i]; ++i) { + if (SDL_strcmp(bootstrap[i]->name, "esd") == 0) { #ifdef HAVE_PUTENV - const char *esd_no_spawn; - - /* Don't start ESD if it's not running */ - esd_no_spawn = getenv("ESD_NO_SPAWN"); - if ( esd_no_spawn == NULL ) { - putenv("ESD_NO_SPAWN=1"); - } -#endif - if ( bootstrap[i]->available() ) { - audio = bootstrap[i]->create(0); - break; - } + const char *esd_no_spawn; + + /* Don't start ESD if it's not running */ + esd_no_spawn = getenv("ESD_NO_SPAWN"); + if (esd_no_spawn == NULL) { + putenv("ESD_NO_SPAWN=1"); + } +#endif + if (bootstrap[i]->available()) { + audio = bootstrap[i]->create(0); + break; + } #ifdef HAVE_UNSETENV - if ( esd_no_spawn == NULL ) { - unsetenv("ESD_NO_SPAWN"); - } + if (esd_no_spawn == NULL) { + unsetenv("ESD_NO_SPAWN"); + } #endif - } - } - } + } + } + } #endif /* SDL_AUDIO_DRIVER_ESD */ - if ( audio == NULL ) { - if ( driver_name != NULL ) { -#if 0 /* This will be replaced with a better driver selection API */ - if ( SDL_strrchr(driver_name, ':') != NULL ) { - idx = atoi(SDL_strrchr(driver_name, ':')+1); - } -#endif - for ( i=0; bootstrap[i]; ++i ) { - if (SDL_strncmp(bootstrap[i]->name, driver_name, - SDL_strlen(bootstrap[i]->name)) == 0) { - if ( bootstrap[i]->available() ) { - audio=bootstrap[i]->create(idx); - break; - } - } - } - } else { - for ( i=0; bootstrap[i]; ++i ) { - if ( bootstrap[i]->available() ) { - audio = bootstrap[i]->create(idx); - if ( audio != NULL ) { - break; - } - } - } - } - if ( audio == NULL ) { - SDL_SetError("No available audio device"); -#if 0 /* Don't fail SDL_Init() if audio isn't available. - SDL_OpenAudio() will handle it at that point. *sigh* - */ - return(-1); -#endif - } - } - current_audio = audio; - if ( current_audio ) { - current_audio->name = bootstrap[i]->name; - if ( !current_audio->LockAudio && !current_audio->UnlockAudio ) { - current_audio->LockAudio = SDL_LockAudio_Default; - current_audio->UnlockAudio = SDL_UnlockAudio_Default; - } - } - return(0); + if (audio == NULL) { + if (driver_name != NULL) { +#if 0 /* This will be replaced with a better driver selection API */ + if (SDL_strrchr(driver_name, ':') != NULL) { + idx = atoi(SDL_strrchr(driver_name, ':') + 1); + } +#endif + for (i = 0; bootstrap[i]; ++i) { + if (SDL_strncmp(bootstrap[i]->name, driver_name, + SDL_strlen(bootstrap[i]->name)) == 0) { + if (bootstrap[i]->available()) { + audio = bootstrap[i]->create(idx); + } + break; + } + } + } else { + for (i = 0; bootstrap[i]; ++i) { + if (bootstrap[i]->available()) { + audio = bootstrap[i]->create(idx); + if (audio != NULL) { + break; + } + } + } + } + if (audio == NULL) { + if (driver_name) { + SDL_SetError("%s not available", driver_name); + } else { + SDL_SetError("No available audio device"); + } +#if 0 /* Don't fail SDL_Init() if audio isn't available. + SDL_OpenAudio() will handle it at that point. *sigh* + */ + return (-1); +#endif + } + } + current_audio = audio; + if (current_audio) { + current_audio->name = bootstrap[i]->name; + if (!current_audio->LockAudio && !current_audio->UnlockAudio) { + current_audio->LockAudio = SDL_LockAudio_Default; + current_audio->UnlockAudio = SDL_UnlockAudio_Default; + } + } + return (0); } -char *SDL_AudioDriverName(char *namebuf, int maxlen) +/* + * Get the current audio driver name + */ +const char * +SDL_GetCurrentAudioDriver() { - if ( current_audio != NULL ) { - SDL_strlcpy(namebuf, current_audio->name, maxlen); - return(namebuf); - } - return(NULL); + if (current_audio) { + return current_audio->name; + } + return (NULL); } -int SDL_OpenAudio(SDL_AudioSpec *desired, SDL_AudioSpec *obtained) +int +SDL_OpenAudio(SDL_AudioSpec * desired, SDL_AudioSpec * obtained) { - SDL_AudioDevice *audio; - const char *env; - - /* Start up the audio driver, if necessary */ - if ( ! current_audio ) { - if ( (SDL_InitSubSystem(SDL_INIT_AUDIO) < 0) || - (current_audio == NULL) ) { - return(-1); - } - } - audio = current_audio; - - if (audio->opened) { - SDL_SetError("Audio device is already opened"); - return(-1); - } - - /* Verify some parameters */ - if ( desired->freq == 0 ) { - env = SDL_getenv("SDL_AUDIO_FREQUENCY"); - if ( env ) { - desired->freq = SDL_atoi(env); - } - } - if ( desired->freq == 0 ) { - /* Pick some default audio frequency */ - desired->freq = 22050; - } - if ( desired->format == 0 ) { - env = SDL_getenv("SDL_AUDIO_FORMAT"); - if ( env ) { - desired->format = SDL_ParseAudioFormat(env); - } - } - if ( desired->format == 0 ) { - /* Pick some default audio format */ - desired->format = AUDIO_S16; - } - if ( desired->channels == 0 ) { - env = SDL_getenv("SDL_AUDIO_CHANNELS"); - if ( env ) { - desired->channels = SDL_atoi(env); - } - } - if ( desired->channels == 0 ) { - /* Pick a default number of channels */ - desired->channels = 2; - } - switch ( desired->channels ) { - case 1: /* Mono */ - case 2: /* Stereo */ - case 4: /* surround */ - case 6: /* surround with center and lfe */ - break; - default: - SDL_SetError("1 (mono) and 2 (stereo) channels supported"); - return(-1); - } - if ( desired->samples == 0 ) { - env = SDL_getenv("SDL_AUDIO_SAMPLES"); - if ( env ) { - desired->samples = SDL_atoi(env); - } - } - if ( desired->samples == 0 ) { - /* Pick a default of ~46 ms at desired frequency */ - int samples = (desired->freq / 1000) * 46; - int power2 = 1; - while ( power2 < samples ) { - power2 *= 2; - } - desired->samples = power2; - } - if ( desired->callback == NULL ) { - SDL_SetError("SDL_OpenAudio() passed a NULL callback"); - return(-1); - } - + SDL_AudioDevice *audio; + const char *env; + + /* Start up the audio driver, if necessary */ + if (!current_audio) { + if ((SDL_InitSubSystem(SDL_INIT_AUDIO) < 0) || + (current_audio == NULL)) { + return (-1); + } + } + audio = current_audio; + + if (audio->opened) { + SDL_SetError("Audio device is already opened"); + return (-1); + } + + /* Verify some parameters */ + if (desired->freq == 0) { + env = SDL_getenv("SDL_AUDIO_FREQUENCY"); + if (env) { + desired->freq = SDL_atoi(env); + } + } + if (desired->freq == 0) { + /* Pick some default audio frequency */ + desired->freq = 22050; + } + if (desired->format == 0) { + env = SDL_getenv("SDL_AUDIO_FORMAT"); + if (env) { + desired->format = SDL_ParseAudioFormat(env); + } + } + if (desired->format == 0) { + /* Pick some default audio format */ + desired->format = AUDIO_S16; + } + if (desired->channels == 0) { + env = SDL_getenv("SDL_AUDIO_CHANNELS"); + if (env) { + desired->channels = SDL_atoi(env); + } + } + if (desired->channels == 0) { + /* Pick a default number of channels */ + desired->channels = 2; + } + switch (desired->channels) { + case 1: /* Mono */ + case 2: /* Stereo */ + case 4: /* surround */ + case 6: /* surround with center and lfe */ + break; + default: + SDL_SetError("1 (mono) and 2 (stereo) channels supported"); + return (-1); + } + if (desired->samples == 0) { + env = SDL_getenv("SDL_AUDIO_SAMPLES"); + if (env) { + desired->samples = SDL_atoi(env); + } + } + if (desired->samples == 0) { + /* Pick a default of ~46 ms at desired frequency */ + int samples = (desired->freq / 1000) * 46; + int power2 = 1; + while (power2 < samples) { + power2 *= 2; + } + desired->samples = power2; + } + if (desired->callback == NULL) { + SDL_SetError("SDL_OpenAudio() passed a NULL callback"); + return (-1); + } #if defined(__MACOS__) || (defined(__RISCOS__) && SDL_THREADS_DISABLED) - /* FIXME: Need to implement PPC interrupt asm for SDL_LockAudio() */ + /* FIXME: Need to implement PPC interrupt asm for SDL_LockAudio() */ #else #if defined(__MINT__) && SDL_THREADS_DISABLED - /* Uses interrupt driven audio, without thread */ + /* Uses interrupt driven audio, without thread */ #else - /* Create a semaphore for locking the sound buffers */ - audio->mixer_lock = SDL_CreateMutex(); - if ( audio->mixer_lock == NULL ) { - SDL_SetError("Couldn't create mixer lock"); - SDL_CloseAudio(); - return(-1); - } + /* Create a semaphore for locking the sound buffers */ + audio->mixer_lock = SDL_CreateMutex(); + if (audio->mixer_lock == NULL) { + SDL_SetError("Couldn't create mixer lock"); + SDL_CloseAudio(); + return (-1); + } #endif /* __MINT__ */ #endif /* __MACOS__ */ - /* Calculate the silence and size of the audio specification */ - SDL_CalculateAudioSpec(desired); + /* Calculate the silence and size of the audio specification */ + SDL_CalculateAudioSpec(desired); - /* Open the audio subsystem */ - SDL_memcpy(&audio->spec, desired, sizeof(audio->spec)); - audio->convert.needed = 0; - audio->enabled = 1; - audio->paused = 1; + /* Open the audio subsystem */ + SDL_memcpy(&audio->spec, desired, sizeof(audio->spec)); + audio->convert.needed = 0; + audio->enabled = 1; + audio->paused = 1; #if !SDL_AUDIO_DRIVER_AHI /* AmigaOS opens audio inside the main loop */ - audio->opened = audio->OpenAudio(audio, &audio->spec)+1; + audio->opened = audio->OpenAudio(audio, &audio->spec) + 1; - if ( ! audio->opened ) { - SDL_CloseAudio(); - return(-1); - } + if (!audio->opened) { + SDL_CloseAudio(); + return (-1); + } #else - D(bug("Locking semaphore...")); - SDL_mutexP(audio->mixer_lock); - - - audio->thread = SDL_CreateThread(SDL_RunAudio, audio); - D(bug("Created thread...\n")); - - if ( audio->thread == NULL ) { - SDL_mutexV(audio->mixer_lock); - SDL_CloseAudio(); - SDL_SetError("Couldn't create audio thread"); - return(-1); - } - - while(!audio_configured) - SDL_Delay(100); -#endif - - /* If the audio driver changes the buffer size, accept it */ - if ( audio->spec.samples != desired->samples ) { - desired->samples = audio->spec.samples; - SDL_CalculateAudioSpec(desired); - } - - /* Allocate a fake audio memory buffer */ - audio->fake_stream = SDL_AllocAudioMem(audio->spec.size); - if ( audio->fake_stream == NULL ) { - SDL_CloseAudio(); - SDL_OutOfMemory(); - return(-1); - } - - /* See if we need to do any conversion */ - if ( obtained != NULL ) { - SDL_memcpy(obtained, &audio->spec, sizeof(audio->spec)); - } else if ( desired->freq != audio->spec.freq || - desired->format != audio->spec.format || - desired->channels != audio->spec.channels ) { - /* Build an audio conversion block */ - if ( SDL_BuildAudioCVT(&audio->convert, - desired->format, desired->channels, - desired->freq, - audio->spec.format, audio->spec.channels, - audio->spec.freq) < 0 ) { - SDL_CloseAudio(); - return(-1); - } - if ( audio->convert.needed ) { - audio->convert.len = desired->size; - audio->convert.buf =(Uint8 *)SDL_AllocAudioMem( - audio->convert.len*audio->convert.len_mult); - if ( audio->convert.buf == NULL ) { - SDL_CloseAudio(); - SDL_OutOfMemory(); - return(-1); - } - } - } - + D(bug("Locking semaphore...")); + SDL_mutexP(audio->mixer_lock); + + + audio->thread = SDL_CreateThread(SDL_RunAudio, audio); + D(bug("Created thread...\n")); + + if (audio->thread == NULL) { + SDL_mutexV(audio->mixer_lock); + SDL_CloseAudio(); + SDL_SetError("Couldn't create audio thread"); + return (-1); + } + + while (!audio_configured) + SDL_Delay(100); +#endif + + /* If the audio driver changes the buffer size, accept it */ + if (audio->spec.samples != desired->samples) { + desired->samples = audio->spec.samples; + SDL_CalculateAudioSpec(desired); + } + + /* Allocate a fake audio memory buffer */ + audio->fake_stream = SDL_AllocAudioMem(audio->spec.size); + if (audio->fake_stream == NULL) { + SDL_CloseAudio(); + SDL_OutOfMemory(); + return (-1); + } + + /* See if we need to do any conversion */ + if (obtained != NULL) { + SDL_memcpy(obtained, &audio->spec, sizeof(audio->spec)); + } else if (desired->freq != audio->spec.freq || + desired->format != audio->spec.format || + desired->channels != audio->spec.channels) { + /* Build an audio conversion block */ + if (SDL_BuildAudioCVT(&audio->convert, + desired->format, desired->channels, + desired->freq, + audio->spec.format, audio->spec.channels, + audio->spec.freq) < 0) { + SDL_CloseAudio(); + return (-1); + } + if (audio->convert.needed) { + audio->convert.len = desired->size; + audio->convert.buf = + (Uint8 *) SDL_AllocAudioMem(audio->convert.len * + audio->convert.len_mult); + if (audio->convert.buf == NULL) { + SDL_CloseAudio(); + SDL_OutOfMemory(); + return (-1); + } + } + } #if !SDL_AUDIO_DRIVER_AHI - /* Start the audio thread if necessary */ - switch (audio->opened) { - case 1: - /* Start the audio thread */ + /* Start the audio thread if necessary */ + switch (audio->opened) { + case 1: + /* Start the audio thread */ #if (defined(__WIN32__) && !defined(_WIN32_WCE)) && !defined(HAVE_LIBC) #undef SDL_CreateThread - audio->thread = SDL_CreateThread(SDL_RunAudio, audio, NULL, NULL); + audio->thread = SDL_CreateThread(SDL_RunAudio, audio, NULL, NULL); #else - audio->thread = SDL_CreateThread(SDL_RunAudio, audio); -#endif - if ( audio->thread == NULL ) { - SDL_CloseAudio(); - SDL_SetError("Couldn't create audio thread"); - return(-1); - } - break; - - default: - /* The audio is now playing */ - break; - } + audio->thread = SDL_CreateThread(SDL_RunAudio, audio); +#endif + if (audio->thread == NULL) { + SDL_CloseAudio(); + SDL_SetError("Couldn't create audio thread"); + return (-1); + } + break; + + default: + /* The audio is now playing */ + break; + } #else - SDL_mutexV(audio->mixer_lock); - D(bug("SDL_OpenAudio USCITA...\n")); + SDL_mutexV(audio->mixer_lock); + D(bug("SDL_OpenAudio USCITA...\n")); #endif - return(0); + return (0); } -SDL_audiostatus SDL_GetAudioStatus(void) +SDL_audiostatus +SDL_GetAudioStatus(void) { - SDL_AudioDevice *audio = current_audio; - SDL_audiostatus status; - - status = SDL_AUDIO_STOPPED; - if ( audio && audio->enabled ) { - if ( audio->paused ) { - status = SDL_AUDIO_PAUSED; - } else { - status = SDL_AUDIO_PLAYING; - } - } - return(status); + SDL_AudioDevice *audio = current_audio; + SDL_audiostatus status; + + status = SDL_AUDIO_STOPPED; + if (audio && audio->enabled) { + if (audio->paused) { + status = SDL_AUDIO_PAUSED; + } else { + status = SDL_AUDIO_PLAYING; + } + } + return (status); } -void SDL_PauseAudio (int pause_on) +void +SDL_PauseAudio(int pause_on) { - SDL_AudioDevice *audio = current_audio; + SDL_AudioDevice *audio = current_audio; - if ( audio ) { - audio->paused = pause_on; - } + if (audio) { + audio->paused = pause_on; + } } -void SDL_LockAudio (void) +void +SDL_LockAudio(void) { - SDL_AudioDevice *audio = current_audio; + SDL_AudioDevice *audio = current_audio; - /* Obtain a lock on the mixing buffers */ - if ( audio && audio->LockAudio ) { - audio->LockAudio(audio); - } + /* Obtain a lock on the mixing buffers */ + if (audio && audio->LockAudio) { + audio->LockAudio(audio); + } } -void SDL_UnlockAudio (void) +void +SDL_UnlockAudio(void) { - SDL_AudioDevice *audio = current_audio; + SDL_AudioDevice *audio = current_audio; - /* Release lock on the mixing buffers */ - if ( audio && audio->UnlockAudio ) { - audio->UnlockAudio(audio); - } + /* Release lock on the mixing buffers */ + if (audio && audio->UnlockAudio) { + audio->UnlockAudio(audio); + } } -void SDL_CloseAudio (void) +void +SDL_CloseAudio(void) { - SDL_QuitSubSystem(SDL_INIT_AUDIO); + SDL_QuitSubSystem(SDL_INIT_AUDIO); } -void SDL_AudioQuit(void) +void +SDL_AudioQuit(void) { - SDL_AudioDevice *audio = current_audio; - - if ( audio ) { - audio->enabled = 0; - if ( audio->thread != NULL ) { - SDL_WaitThread(audio->thread, NULL); - } - if ( audio->mixer_lock != NULL ) { - SDL_DestroyMutex(audio->mixer_lock); - } - if ( audio->fake_stream != NULL ) { - SDL_FreeAudioMem(audio->fake_stream); - } - if ( audio->convert.needed ) { - SDL_FreeAudioMem(audio->convert.buf); - - } + SDL_AudioDevice *audio = current_audio; + + if (audio) { + audio->enabled = 0; + if (audio->thread != NULL) { + SDL_WaitThread(audio->thread, NULL); + } + if (audio->mixer_lock != NULL) { + SDL_DestroyMutex(audio->mixer_lock); + } + if (audio->fake_stream != NULL) { + SDL_FreeAudioMem(audio->fake_stream); + } + if (audio->convert.needed) { + SDL_FreeAudioMem(audio->convert.buf); + + } #if !SDL_AUDIO_DRIVER_AHI - if ( audio->opened ) { - audio->CloseAudio(audio); - audio->opened = 0; - } -#endif - /* Free the driver data */ - audio->free(audio); - current_audio = NULL; - } + if (audio->opened) { + audio->CloseAudio(audio); + audio->opened = 0; + } +#endif + /* Free the driver data */ + audio->free(audio); + current_audio = NULL; + } } #define NUM_FORMATS 6 static int format_idx; static int format_idx_sub; static Uint16 format_list[NUM_FORMATS][NUM_FORMATS] = { - { AUDIO_U8, AUDIO_S8, AUDIO_S16LSB, AUDIO_S16MSB, AUDIO_U16LSB, AUDIO_U16MSB }, - { AUDIO_S8, AUDIO_U8, AUDIO_S16LSB, AUDIO_S16MSB, AUDIO_U16LSB, AUDIO_U16MSB }, - { AUDIO_S16LSB, AUDIO_S16MSB, AUDIO_U16LSB, AUDIO_U16MSB, AUDIO_U8, AUDIO_S8 }, - { AUDIO_S16MSB, AUDIO_S16LSB, AUDIO_U16MSB, AUDIO_U16LSB, AUDIO_U8, AUDIO_S8 }, - { AUDIO_U16LSB, AUDIO_U16MSB, AUDIO_S16LSB, AUDIO_S16MSB, AUDIO_U8, AUDIO_S8 }, - { AUDIO_U16MSB, AUDIO_U16LSB, AUDIO_S16MSB, AUDIO_S16LSB, AUDIO_U8, AUDIO_S8 }, + {AUDIO_U8, AUDIO_S8, AUDIO_S16LSB, AUDIO_S16MSB, AUDIO_U16LSB, + AUDIO_U16MSB}, + {AUDIO_S8, AUDIO_U8, AUDIO_S16LSB, AUDIO_S16MSB, AUDIO_U16LSB, + AUDIO_U16MSB}, + {AUDIO_S16LSB, AUDIO_S16MSB, AUDIO_U16LSB, AUDIO_U16MSB, AUDIO_U8, + AUDIO_S8}, + {AUDIO_S16MSB, AUDIO_S16LSB, AUDIO_U16MSB, AUDIO_U16LSB, AUDIO_U8, + AUDIO_S8}, + {AUDIO_U16LSB, AUDIO_U16MSB, AUDIO_S16LSB, AUDIO_S16MSB, AUDIO_U8, + AUDIO_S8}, + {AUDIO_U16MSB, AUDIO_U16LSB, AUDIO_S16MSB, AUDIO_S16LSB, AUDIO_U8, + AUDIO_S8}, }; -Uint16 SDL_FirstAudioFormat(Uint16 format) +Uint16 +SDL_FirstAudioFormat(Uint16 format) { - for ( format_idx=0; format_idx < NUM_FORMATS; ++format_idx ) { - if ( format_list[format_idx][0] == format ) { - break; - } - } - format_idx_sub = 0; - return(SDL_NextAudioFormat()); + for (format_idx = 0; format_idx < NUM_FORMATS; ++format_idx) { + if (format_list[format_idx][0] == format) { + break; + } + } + format_idx_sub = 0; + return (SDL_NextAudioFormat()); } -Uint16 SDL_NextAudioFormat(void) +Uint16 +SDL_NextAudioFormat(void) { - if ( (format_idx == NUM_FORMATS) || (format_idx_sub == NUM_FORMATS) ) { - return(0); - } - return(format_list[format_idx][format_idx_sub++]); + if ((format_idx == NUM_FORMATS) || (format_idx_sub == NUM_FORMATS)) { + return (0); + } + return (format_list[format_idx][format_idx_sub++]); } -void SDL_CalculateAudioSpec(SDL_AudioSpec *spec) +void +SDL_CalculateAudioSpec(SDL_AudioSpec * spec) { - switch (spec->format) { - case AUDIO_U8: - spec->silence = 0x80; - break; - default: - spec->silence = 0x00; - break; - } - spec->size = (spec->format&0xFF)/8; - spec->size *= spec->channels; - spec->size *= spec->samples; + switch (spec->format) { + case AUDIO_U8: + spec->silence = 0x80; + break; + default: + spec->silence = 0x00; + break; + } + spec->size = (spec->format & 0xFF) / 8; + spec->size *= spec->channels; + spec->size *= spec->samples; } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/audio/SDL_audio_c.h b/src/audio/SDL_audio_c.h index f5848959e..3aa181204 100644 --- a/src/audio/SDL_audio_c.h +++ b/src/audio/SDL_audio_c.h @@ -28,7 +28,8 @@ extern Uint16 SDL_FirstAudioFormat(Uint16 format); extern Uint16 SDL_NextAudioFormat(void); /* Function to calculate the size and silence for a SDL_AudioSpec */ -extern void SDL_CalculateAudioSpec(SDL_AudioSpec *spec); +extern void SDL_CalculateAudioSpec(SDL_AudioSpec * spec); /* The actual mixing thread function */ extern int SDLCALL SDL_RunAudio(void *audiop); +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/audio/SDL_audiocvt.c b/src/audio/SDL_audiocvt.c index 3c361155e..bf310e484 100644 --- a/src/audio/SDL_audiocvt.c +++ b/src/audio/SDL_audiocvt.c @@ -27,1519 +27,1569 @@ /* Effectively mix right and left channels into a single channel */ -void SDLCALL SDL_ConvertMono(SDL_AudioCVT *cvt, Uint16 format) +void SDLCALL +SDL_ConvertMono(SDL_AudioCVT * cvt, Uint16 format) { - int i; - Sint32 sample; + int i; + Sint32 sample; #ifdef DEBUG_CONVERT - fprintf(stderr, "Converting to mono\n"); + fprintf(stderr, "Converting to mono\n"); #endif - switch (format&0x8018) { - - case AUDIO_U8: { - Uint8 *src, *dst; - - src = cvt->buf; - dst = cvt->buf; - for ( i=cvt->len_cvt/2; i; --i ) { - sample = src[0] + src[1]; - if ( sample > 255 ) { - *dst = 255; - } else { - *dst = (Uint8)sample; - } - src += 2; - dst += 1; - } - } - break; - - case AUDIO_S8: { - Sint8 *src, *dst; - - src = (Sint8 *)cvt->buf; - dst = (Sint8 *)cvt->buf; - for ( i=cvt->len_cvt/2; i; --i ) { - sample = src[0] + src[1]; - if ( sample > 127 ) { - *dst = 127; - } else - if ( sample < -128 ) { - *dst = -128; - } else { - *dst = (Sint8)sample; - } - src += 2; - dst += 1; - } - } - break; - - case AUDIO_U16: { - Uint8 *src, *dst; - - src = cvt->buf; - dst = cvt->buf; - if ( (format & 0x1000) == 0x1000 ) { - for ( i=cvt->len_cvt/4; i; --i ) { - sample = (Uint16)((src[0]<<8)|src[1])+ - (Uint16)((src[2]<<8)|src[3]); - if ( sample > 65535 ) { - dst[0] = 0xFF; - dst[1] = 0xFF; - } else { - dst[1] = (sample&0xFF); - sample >>= 8; - dst[0] = (sample&0xFF); - } - src += 4; - dst += 2; - } - } else { - for ( i=cvt->len_cvt/4; i; --i ) { - sample = (Uint16)((src[1]<<8)|src[0])+ - (Uint16)((src[3]<<8)|src[2]); - if ( sample > 65535 ) { - dst[0] = 0xFF; - dst[1] = 0xFF; - } else { - dst[0] = (sample&0xFF); - sample >>= 8; - dst[1] = (sample&0xFF); - } - src += 4; - dst += 2; - } - } - } - break; - - case AUDIO_S16: { - Uint8 *src, *dst; - - src = cvt->buf; - dst = cvt->buf; - if ( (format & 0x1000) == 0x1000 ) { - for ( i=cvt->len_cvt/4; i; --i ) { - sample = (Sint16)((src[0]<<8)|src[1])+ - (Sint16)((src[2]<<8)|src[3]); - if ( sample > 32767 ) { - dst[0] = 0x7F; - dst[1] = 0xFF; - } else - if ( sample < -32768 ) { - dst[0] = 0x80; - dst[1] = 0x00; - } else { - dst[1] = (sample&0xFF); - sample >>= 8; - dst[0] = (sample&0xFF); - } - src += 4; - dst += 2; - } - } else { - for ( i=cvt->len_cvt/4; i; --i ) { - sample = (Sint16)((src[1]<<8)|src[0])+ - (Sint16)((src[3]<<8)|src[2]); - if ( sample > 32767 ) { - dst[1] = 0x7F; - dst[0] = 0xFF; - } else - if ( sample < -32768 ) { - dst[1] = 0x80; - dst[0] = 0x00; - } else { - dst[0] = (sample&0xFF); - sample >>= 8; - dst[1] = (sample&0xFF); - } - src += 4; - dst += 2; - } - } - } - break; - } - cvt->len_cvt /= 2; - if ( cvt->filters[++cvt->filter_index] ) { - cvt->filters[cvt->filter_index](cvt, format); - } + switch (format & 0x8018) { + + case AUDIO_U8: + { + Uint8 *src, *dst; + + src = cvt->buf; + dst = cvt->buf; + for (i = cvt->len_cvt / 2; i; --i) { + sample = src[0] + src[1]; + if (sample > 255) { + *dst = 255; + } else { + *dst = (Uint8) sample; + } + src += 2; + dst += 1; + } + } + break; + + case AUDIO_S8: + { + Sint8 *src, *dst; + + src = (Sint8 *) cvt->buf; + dst = (Sint8 *) cvt->buf; + for (i = cvt->len_cvt / 2; i; --i) { + sample = src[0] + src[1]; + if (sample > 127) { + *dst = 127; + } else if (sample < -128) { + *dst = -128; + } else { + *dst = (Sint8) sample; + } + src += 2; + dst += 1; + } + } + break; + + case AUDIO_U16: + { + Uint8 *src, *dst; + + src = cvt->buf; + dst = cvt->buf; + if ((format & 0x1000) == 0x1000) { + for (i = cvt->len_cvt / 4; i; --i) { + sample = (Uint16) ((src[0] << 8) | src[1]) + + (Uint16) ((src[2] << 8) | src[3]); + if (sample > 65535) { + dst[0] = 0xFF; + dst[1] = 0xFF; + } else { + dst[1] = (sample & 0xFF); + sample >>= 8; + dst[0] = (sample & 0xFF); + } + src += 4; + dst += 2; + } + } else { + for (i = cvt->len_cvt / 4; i; --i) { + sample = (Uint16) ((src[1] << 8) | src[0]) + + (Uint16) ((src[3] << 8) | src[2]); + if (sample > 65535) { + dst[0] = 0xFF; + dst[1] = 0xFF; + } else { + dst[0] = (sample & 0xFF); + sample >>= 8; + dst[1] = (sample & 0xFF); + } + src += 4; + dst += 2; + } + } + } + break; + + case AUDIO_S16: + { + Uint8 *src, *dst; + + src = cvt->buf; + dst = cvt->buf; + if ((format & 0x1000) == 0x1000) { + for (i = cvt->len_cvt / 4; i; --i) { + sample = (Sint16) ((src[0] << 8) | src[1]) + + (Sint16) ((src[2] << 8) | src[3]); + if (sample > 32767) { + dst[0] = 0x7F; + dst[1] = 0xFF; + } else if (sample < -32768) { + dst[0] = 0x80; + dst[1] = 0x00; + } else { + dst[1] = (sample & 0xFF); + sample >>= 8; + dst[0] = (sample & 0xFF); + } + src += 4; + dst += 2; + } + } else { + for (i = cvt->len_cvt / 4; i; --i) { + sample = (Sint16) ((src[1] << 8) | src[0]) + + (Sint16) ((src[3] << 8) | src[2]); + if (sample > 32767) { + dst[1] = 0x7F; + dst[0] = 0xFF; + } else if (sample < -32768) { + dst[1] = 0x80; + dst[0] = 0x00; + } else { + dst[0] = (sample & 0xFF); + sample >>= 8; + dst[1] = (sample & 0xFF); + } + src += 4; + dst += 2; + } + } + } + break; + } + cvt->len_cvt /= 2; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index] (cvt, format); + } } /* Discard top 4 channels */ -void SDLCALL SDL_ConvertStrip(SDL_AudioCVT *cvt, Uint16 format) +void SDLCALL +SDL_ConvertStrip(SDL_AudioCVT * cvt, Uint16 format) { - int i; - Sint32 lsample, rsample; + int i; + Sint32 lsample, rsample; #ifdef DEBUG_CONVERT - fprintf(stderr, "Converting down to stereo\n"); + fprintf(stderr, "Converting down to stereo\n"); #endif - switch (format&0x8018) { - - case AUDIO_U8: { - Uint8 *src, *dst; - - src = cvt->buf; - dst = cvt->buf; - for ( i=cvt->len_cvt/6; i; --i ) { - dst[0] = src[0]; - dst[1] = src[1]; - src += 6; - dst += 2; - } - } - break; - - case AUDIO_S8: { - Sint8 *src, *dst; - - src = (Sint8 *)cvt->buf; - dst = (Sint8 *)cvt->buf; - for ( i=cvt->len_cvt/6; i; --i ) { - dst[0] = src[0]; - dst[1] = src[1]; - src += 6; - dst += 2; - } - } - break; - - case AUDIO_U16: { - Uint8 *src, *dst; - - src = cvt->buf; - dst = cvt->buf; - if ( (format & 0x1000) == 0x1000 ) { - for ( i=cvt->len_cvt/12; i; --i ) { - lsample = (Uint16)((src[0]<<8)|src[1]); - rsample = (Uint16)((src[2]<<8)|src[3]); - dst[1] = (lsample&0xFF); - lsample >>= 8; - dst[0] = (lsample&0xFF); - dst[3] = (rsample&0xFF); - rsample >>= 8; - dst[2] = (rsample&0xFF); - src += 12; - dst += 4; - } - } else { - for ( i=cvt->len_cvt/12; i; --i ) { - lsample = (Uint16)((src[1]<<8)|src[0]); - rsample = (Uint16)((src[3]<<8)|src[2]); - dst[0] = (lsample&0xFF); - lsample >>= 8; - dst[1] = (lsample&0xFF); - dst[2] = (rsample&0xFF); - rsample >>= 8; - dst[3] = (rsample&0xFF); - src += 12; - dst += 4; - } - } - } - break; - - case AUDIO_S16: { - Uint8 *src, *dst; - - src = cvt->buf; - dst = cvt->buf; - if ( (format & 0x1000) == 0x1000 ) { - for ( i=cvt->len_cvt/12; i; --i ) { - lsample = (Sint16)((src[0]<<8)|src[1]); - rsample = (Sint16)((src[2]<<8)|src[3]); - dst[1] = (lsample&0xFF); - lsample >>= 8; - dst[0] = (lsample&0xFF); - dst[3] = (rsample&0xFF); - rsample >>= 8; - dst[2] = (rsample&0xFF); - src += 12; - dst += 4; - } - } else { - for ( i=cvt->len_cvt/12; i; --i ) { - lsample = (Sint16)((src[1]<<8)|src[0]); - rsample = (Sint16)((src[3]<<8)|src[2]); - dst[0] = (lsample&0xFF); - lsample >>= 8; - dst[1] = (lsample&0xFF); - dst[2] = (rsample&0xFF); - rsample >>= 8; - dst[3] = (rsample&0xFF); - src += 12; - dst += 4; - } - } - } - break; - } - cvt->len_cvt /= 3; - if ( cvt->filters[++cvt->filter_index] ) { - cvt->filters[cvt->filter_index](cvt, format); - } + switch (format & 0x8018) { + + case AUDIO_U8: + { + Uint8 *src, *dst; + + src = cvt->buf; + dst = cvt->buf; + for (i = cvt->len_cvt / 6; i; --i) { + dst[0] = src[0]; + dst[1] = src[1]; + src += 6; + dst += 2; + } + } + break; + + case AUDIO_S8: + { + Sint8 *src, *dst; + + src = (Sint8 *) cvt->buf; + dst = (Sint8 *) cvt->buf; + for (i = cvt->len_cvt / 6; i; --i) { + dst[0] = src[0]; + dst[1] = src[1]; + src += 6; + dst += 2; + } + } + break; + + case AUDIO_U16: + { + Uint8 *src, *dst; + + src = cvt->buf; + dst = cvt->buf; + if ((format & 0x1000) == 0x1000) { + for (i = cvt->len_cvt / 12; i; --i) { + lsample = (Uint16) ((src[0] << 8) | src[1]); + rsample = (Uint16) ((src[2] << 8) | src[3]); + dst[1] = (lsample & 0xFF); + lsample >>= 8; + dst[0] = (lsample & 0xFF); + dst[3] = (rsample & 0xFF); + rsample >>= 8; + dst[2] = (rsample & 0xFF); + src += 12; + dst += 4; + } + } else { + for (i = cvt->len_cvt / 12; i; --i) { + lsample = (Uint16) ((src[1] << 8) | src[0]); + rsample = (Uint16) ((src[3] << 8) | src[2]); + dst[0] = (lsample & 0xFF); + lsample >>= 8; + dst[1] = (lsample & 0xFF); + dst[2] = (rsample & 0xFF); + rsample >>= 8; + dst[3] = (rsample & 0xFF); + src += 12; + dst += 4; + } + } + } + break; + + case AUDIO_S16: + { + Uint8 *src, *dst; + + src = cvt->buf; + dst = cvt->buf; + if ((format & 0x1000) == 0x1000) { + for (i = cvt->len_cvt / 12; i; --i) { + lsample = (Sint16) ((src[0] << 8) | src[1]); + rsample = (Sint16) ((src[2] << 8) | src[3]); + dst[1] = (lsample & 0xFF); + lsample >>= 8; + dst[0] = (lsample & 0xFF); + dst[3] = (rsample & 0xFF); + rsample >>= 8; + dst[2] = (rsample & 0xFF); + src += 12; + dst += 4; + } + } else { + for (i = cvt->len_cvt / 12; i; --i) { + lsample = (Sint16) ((src[1] << 8) | src[0]); + rsample = (Sint16) ((src[3] << 8) | src[2]); + dst[0] = (lsample & 0xFF); + lsample >>= 8; + dst[1] = (lsample & 0xFF); + dst[2] = (rsample & 0xFF); + rsample >>= 8; + dst[3] = (rsample & 0xFF); + src += 12; + dst += 4; + } + } + } + break; + } + cvt->len_cvt /= 3; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index] (cvt, format); + } } /* Discard top 2 channels of 6 */ -void SDLCALL SDL_ConvertStrip_2(SDL_AudioCVT *cvt, Uint16 format) +void SDLCALL +SDL_ConvertStrip_2(SDL_AudioCVT * cvt, Uint16 format) { - int i; - Sint32 lsample, rsample; + int i; + Sint32 lsample, rsample; #ifdef DEBUG_CONVERT - fprintf(stderr, "Converting 6 down to quad\n"); + fprintf(stderr, "Converting 6 down to quad\n"); #endif - switch (format&0x8018) { - - case AUDIO_U8: { - Uint8 *src, *dst; - - src = cvt->buf; - dst = cvt->buf; - for ( i=cvt->len_cvt/4; i; --i ) { - dst[0] = src[0]; - dst[1] = src[1]; - src += 4; - dst += 2; - } - } - break; - - case AUDIO_S8: { - Sint8 *src, *dst; - - src = (Sint8 *)cvt->buf; - dst = (Sint8 *)cvt->buf; - for ( i=cvt->len_cvt/4; i; --i ) { - dst[0] = src[0]; - dst[1] = src[1]; - src += 4; - dst += 2; - } - } - break; - - case AUDIO_U16: { - Uint8 *src, *dst; - - src = cvt->buf; - dst = cvt->buf; - if ( (format & 0x1000) == 0x1000 ) { - for ( i=cvt->len_cvt/8; i; --i ) { - lsample = (Uint16)((src[0]<<8)|src[1]); - rsample = (Uint16)((src[2]<<8)|src[3]); - dst[1] = (lsample&0xFF); - lsample >>= 8; - dst[0] = (lsample&0xFF); - dst[3] = (rsample&0xFF); - rsample >>= 8; - dst[2] = (rsample&0xFF); - src += 8; - dst += 4; - } - } else { - for ( i=cvt->len_cvt/8; i; --i ) { - lsample = (Uint16)((src[1]<<8)|src[0]); - rsample = (Uint16)((src[3]<<8)|src[2]); - dst[0] = (lsample&0xFF); - lsample >>= 8; - dst[1] = (lsample&0xFF); - dst[2] = (rsample&0xFF); - rsample >>= 8; - dst[3] = (rsample&0xFF); - src += 8; - dst += 4; - } - } - } - break; - - case AUDIO_S16: { - Uint8 *src, *dst; - - src = cvt->buf; - dst = cvt->buf; - if ( (format & 0x1000) == 0x1000 ) { - for ( i=cvt->len_cvt/8; i; --i ) { - lsample = (Sint16)((src[0]<<8)|src[1]); - rsample = (Sint16)((src[2]<<8)|src[3]); - dst[1] = (lsample&0xFF); - lsample >>= 8; - dst[0] = (lsample&0xFF); - dst[3] = (rsample&0xFF); - rsample >>= 8; - dst[2] = (rsample&0xFF); - src += 8; - dst += 4; - } - } else { - for ( i=cvt->len_cvt/8; i; --i ) { - lsample = (Sint16)((src[1]<<8)|src[0]); - rsample = (Sint16)((src[3]<<8)|src[2]); - dst[0] = (lsample&0xFF); - lsample >>= 8; - dst[1] = (lsample&0xFF); - dst[2] = (rsample&0xFF); - rsample >>= 8; - dst[3] = (rsample&0xFF); - src += 8; - dst += 4; - } - } - } - break; - } - cvt->len_cvt /= 2; - if ( cvt->filters[++cvt->filter_index] ) { - cvt->filters[cvt->filter_index](cvt, format); - } + switch (format & 0x8018) { + + case AUDIO_U8: + { + Uint8 *src, *dst; + + src = cvt->buf; + dst = cvt->buf; + for (i = cvt->len_cvt / 4; i; --i) { + dst[0] = src[0]; + dst[1] = src[1]; + src += 4; + dst += 2; + } + } + break; + + case AUDIO_S8: + { + Sint8 *src, *dst; + + src = (Sint8 *) cvt->buf; + dst = (Sint8 *) cvt->buf; + for (i = cvt->len_cvt / 4; i; --i) { + dst[0] = src[0]; + dst[1] = src[1]; + src += 4; + dst += 2; + } + } + break; + + case AUDIO_U16: + { + Uint8 *src, *dst; + + src = cvt->buf; + dst = cvt->buf; + if ((format & 0x1000) == 0x1000) { + for (i = cvt->len_cvt / 8; i; --i) { + lsample = (Uint16) ((src[0] << 8) | src[1]); + rsample = (Uint16) ((src[2] << 8) | src[3]); + dst[1] = (lsample & 0xFF); + lsample >>= 8; + dst[0] = (lsample & 0xFF); + dst[3] = (rsample & 0xFF); + rsample >>= 8; + dst[2] = (rsample & 0xFF); + src += 8; + dst += 4; + } + } else { + for (i = cvt->len_cvt / 8; i; --i) { + lsample = (Uint16) ((src[1] << 8) | src[0]); + rsample = (Uint16) ((src[3] << 8) | src[2]); + dst[0] = (lsample & 0xFF); + lsample >>= 8; + dst[1] = (lsample & 0xFF); + dst[2] = (rsample & 0xFF); + rsample >>= 8; + dst[3] = (rsample & 0xFF); + src += 8; + dst += 4; + } + } + } + break; + + case AUDIO_S16: + { + Uint8 *src, *dst; + + src = cvt->buf; + dst = cvt->buf; + if ((format & 0x1000) == 0x1000) { + for (i = cvt->len_cvt / 8; i; --i) { + lsample = (Sint16) ((src[0] << 8) | src[1]); + rsample = (Sint16) ((src[2] << 8) | src[3]); + dst[1] = (lsample & 0xFF); + lsample >>= 8; + dst[0] = (lsample & 0xFF); + dst[3] = (rsample & 0xFF); + rsample >>= 8; + dst[2] = (rsample & 0xFF); + src += 8; + dst += 4; + } + } else { + for (i = cvt->len_cvt / 8; i; --i) { + lsample = (Sint16) ((src[1] << 8) | src[0]); + rsample = (Sint16) ((src[3] << 8) | src[2]); + dst[0] = (lsample & 0xFF); + lsample >>= 8; + dst[1] = (lsample & 0xFF); + dst[2] = (rsample & 0xFF); + rsample >>= 8; + dst[3] = (rsample & 0xFF); + src += 8; + dst += 4; + } + } + } + break; + } + cvt->len_cvt /= 2; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index] (cvt, format); + } } /* Duplicate a mono channel to both stereo channels */ -void SDLCALL SDL_ConvertStereo(SDL_AudioCVT *cvt, Uint16 format) +void SDLCALL +SDL_ConvertStereo(SDL_AudioCVT * cvt, Uint16 format) { - int i; + int i; #ifdef DEBUG_CONVERT - fprintf(stderr, "Converting to stereo\n"); + fprintf(stderr, "Converting to stereo\n"); #endif - if ( (format & 0xFF) == 16 ) { - Uint16 *src, *dst; - - src = (Uint16 *)(cvt->buf+cvt->len_cvt); - dst = (Uint16 *)(cvt->buf+cvt->len_cvt*2); - for ( i=cvt->len_cvt/2; i; --i ) { - dst -= 2; - src -= 1; - dst[0] = src[0]; - dst[1] = src[0]; - } - } else { - Uint8 *src, *dst; - - src = cvt->buf+cvt->len_cvt; - dst = cvt->buf+cvt->len_cvt*2; - for ( i=cvt->len_cvt; i; --i ) { - dst -= 2; - src -= 1; - dst[0] = src[0]; - dst[1] = src[0]; - } - } - cvt->len_cvt *= 2; - if ( cvt->filters[++cvt->filter_index] ) { - cvt->filters[cvt->filter_index](cvt, format); - } + if ((format & 0xFF) == 16) { + Uint16 *src, *dst; + + src = (Uint16 *) (cvt->buf + cvt->len_cvt); + dst = (Uint16 *) (cvt->buf + cvt->len_cvt * 2); + for (i = cvt->len_cvt / 2; i; --i) { + dst -= 2; + src -= 1; + dst[0] = src[0]; + dst[1] = src[0]; + } + } else { + Uint8 *src, *dst; + + src = cvt->buf + cvt->len_cvt; + dst = cvt->buf + cvt->len_cvt * 2; + for (i = cvt->len_cvt; i; --i) { + dst -= 2; + src -= 1; + dst[0] = src[0]; + dst[1] = src[0]; + } + } + cvt->len_cvt *= 2; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index] (cvt, format); + } } /* Duplicate a stereo channel to a pseudo-5.1 stream */ -void SDLCALL SDL_ConvertSurround(SDL_AudioCVT *cvt, Uint16 format) +void SDLCALL +SDL_ConvertSurround(SDL_AudioCVT * cvt, Uint16 format) { - int i; + int i; #ifdef DEBUG_CONVERT - fprintf(stderr, "Converting stereo to surround\n"); + fprintf(stderr, "Converting stereo to surround\n"); #endif - switch (format&0x8018) { - - case AUDIO_U8: { - Uint8 *src, *dst, lf, rf, ce; - - src = (Uint8 *)(cvt->buf+cvt->len_cvt); - dst = (Uint8 *)(cvt->buf+cvt->len_cvt*3); - for ( i=cvt->len_cvt; i; --i ) { - dst -= 6; - src -= 2; - lf = src[0]; - rf = src[1]; - ce = (lf/2) + (rf/2); - dst[0] = lf; - dst[1] = rf; - dst[2] = lf - ce; - dst[3] = rf - ce; - dst[4] = ce; - dst[5] = ce; - } - } - break; - - case AUDIO_S8: { - Sint8 *src, *dst, lf, rf, ce; - - src = (Sint8 *)cvt->buf+cvt->len_cvt; - dst = (Sint8 *)cvt->buf+cvt->len_cvt*3; - for ( i=cvt->len_cvt; i; --i ) { - dst -= 6; - src -= 2; - lf = src[0]; - rf = src[1]; - ce = (lf/2) + (rf/2); - dst[0] = lf; - dst[1] = rf; - dst[2] = lf - ce; - dst[3] = rf - ce; - dst[4] = ce; - dst[5] = ce; - } - } - break; - - case AUDIO_U16: { - Uint8 *src, *dst; - Uint16 lf, rf, ce, lr, rr; - - src = cvt->buf+cvt->len_cvt; - dst = cvt->buf+cvt->len_cvt*3; - - if ( (format & 0x1000) == 0x1000 ) { - for ( i=cvt->len_cvt/4; i; --i ) { - dst -= 12; - src -= 4; - lf = (Uint16)((src[0]<<8)|src[1]); - rf = (Uint16)((src[2]<<8)|src[3]); - ce = (lf/2) + (rf/2); - rr = lf - ce; - lr = rf - ce; - dst[1] = (lf&0xFF); - dst[0] = ((lf>>8)&0xFF); - dst[3] = (rf&0xFF); - dst[2] = ((rf>>8)&0xFF); - - dst[1+4] = (lr&0xFF); - dst[0+4] = ((lr>>8)&0xFF); - dst[3+4] = (rr&0xFF); - dst[2+4] = ((rr>>8)&0xFF); - - dst[1+8] = (ce&0xFF); - dst[0+8] = ((ce>>8)&0xFF); - dst[3+8] = (ce&0xFF); - dst[2+8] = ((ce>>8)&0xFF); - } - } else { - for ( i=cvt->len_cvt/4; i; --i ) { - dst -= 12; - src -= 4; - lf = (Uint16)((src[1]<<8)|src[0]); - rf = (Uint16)((src[3]<<8)|src[2]); - ce = (lf/2) + (rf/2); - rr = lf - ce; - lr = rf - ce; - dst[0] = (lf&0xFF); - dst[1] = ((lf>>8)&0xFF); - dst[2] = (rf&0xFF); - dst[3] = ((rf>>8)&0xFF); - - dst[0+4] = (lr&0xFF); - dst[1+4] = ((lr>>8)&0xFF); - dst[2+4] = (rr&0xFF); - dst[3+4] = ((rr>>8)&0xFF); - - dst[0+8] = (ce&0xFF); - dst[1+8] = ((ce>>8)&0xFF); - dst[2+8] = (ce&0xFF); - dst[3+8] = ((ce>>8)&0xFF); - } - } - } - break; - - case AUDIO_S16: { - Uint8 *src, *dst; - Sint16 lf, rf, ce, lr, rr; - - src = cvt->buf+cvt->len_cvt; - dst = cvt->buf+cvt->len_cvt*3; - - if ( (format & 0x1000) == 0x1000 ) { - for ( i=cvt->len_cvt/4; i; --i ) { - dst -= 12; - src -= 4; - lf = (Sint16)((src[0]<<8)|src[1]); - rf = (Sint16)((src[2]<<8)|src[3]); - ce = (lf/2) + (rf/2); - rr = lf - ce; - lr = rf - ce; - dst[1] = (lf&0xFF); - dst[0] = ((lf>>8)&0xFF); - dst[3] = (rf&0xFF); - dst[2] = ((rf>>8)&0xFF); - - dst[1+4] = (lr&0xFF); - dst[0+4] = ((lr>>8)&0xFF); - dst[3+4] = (rr&0xFF); - dst[2+4] = ((rr>>8)&0xFF); - - dst[1+8] = (ce&0xFF); - dst[0+8] = ((ce>>8)&0xFF); - dst[3+8] = (ce&0xFF); - dst[2+8] = ((ce>>8)&0xFF); - } - } else { - for ( i=cvt->len_cvt/4; i; --i ) { - dst -= 12; - src -= 4; - lf = (Sint16)((src[1]<<8)|src[0]); - rf = (Sint16)((src[3]<<8)|src[2]); - ce = (lf/2) + (rf/2); - rr = lf - ce; - lr = rf - ce; - dst[0] = (lf&0xFF); - dst[1] = ((lf>>8)&0xFF); - dst[2] = (rf&0xFF); - dst[3] = ((rf>>8)&0xFF); - - dst[0+4] = (lr&0xFF); - dst[1+4] = ((lr>>8)&0xFF); - dst[2+4] = (rr&0xFF); - dst[3+4] = ((rr>>8)&0xFF); - - dst[0+8] = (ce&0xFF); - dst[1+8] = ((ce>>8)&0xFF); - dst[2+8] = (ce&0xFF); - dst[3+8] = ((ce>>8)&0xFF); - } - } - } - break; - } - cvt->len_cvt *= 3; - if ( cvt->filters[++cvt->filter_index] ) { - cvt->filters[cvt->filter_index](cvt, format); - } + switch (format & 0x8018) { + + case AUDIO_U8: + { + Uint8 *src, *dst, lf, rf, ce; + + src = (Uint8 *) (cvt->buf + cvt->len_cvt); + dst = (Uint8 *) (cvt->buf + cvt->len_cvt * 3); + for (i = cvt->len_cvt; i; --i) { + dst -= 6; + src -= 2; + lf = src[0]; + rf = src[1]; + ce = (lf / 2) + (rf / 2); + dst[0] = lf; + dst[1] = rf; + dst[2] = lf - ce; + dst[3] = rf - ce; + dst[4] = ce; + dst[5] = ce; + } + } + break; + + case AUDIO_S8: + { + Sint8 *src, *dst, lf, rf, ce; + + src = (Sint8 *) cvt->buf + cvt->len_cvt; + dst = (Sint8 *) cvt->buf + cvt->len_cvt * 3; + for (i = cvt->len_cvt; i; --i) { + dst -= 6; + src -= 2; + lf = src[0]; + rf = src[1]; + ce = (lf / 2) + (rf / 2); + dst[0] = lf; + dst[1] = rf; + dst[2] = lf - ce; + dst[3] = rf - ce; + dst[4] = ce; + dst[5] = ce; + } + } + break; + + case AUDIO_U16: + { + Uint8 *src, *dst; + Uint16 lf, rf, ce, lr, rr; + + src = cvt->buf + cvt->len_cvt; + dst = cvt->buf + cvt->len_cvt * 3; + + if ((format & 0x1000) == 0x1000) { + for (i = cvt->len_cvt / 4; i; --i) { + dst -= 12; + src -= 4; + lf = (Uint16) ((src[0] << 8) | src[1]); + rf = (Uint16) ((src[2] << 8) | src[3]); + ce = (lf / 2) + (rf / 2); + rr = lf - ce; + lr = rf - ce; + dst[1] = (lf & 0xFF); + dst[0] = ((lf >> 8) & 0xFF); + dst[3] = (rf & 0xFF); + dst[2] = ((rf >> 8) & 0xFF); + + dst[1 + 4] = (lr & 0xFF); + dst[0 + 4] = ((lr >> 8) & 0xFF); + dst[3 + 4] = (rr & 0xFF); + dst[2 + 4] = ((rr >> 8) & 0xFF); + + dst[1 + 8] = (ce & 0xFF); + dst[0 + 8] = ((ce >> 8) & 0xFF); + dst[3 + 8] = (ce & 0xFF); + dst[2 + 8] = ((ce >> 8) & 0xFF); + } + } else { + for (i = cvt->len_cvt / 4; i; --i) { + dst -= 12; + src -= 4; + lf = (Uint16) ((src[1] << 8) | src[0]); + rf = (Uint16) ((src[3] << 8) | src[2]); + ce = (lf / 2) + (rf / 2); + rr = lf - ce; + lr = rf - ce; + dst[0] = (lf & 0xFF); + dst[1] = ((lf >> 8) & 0xFF); + dst[2] = (rf & 0xFF); + dst[3] = ((rf >> 8) & 0xFF); + + dst[0 + 4] = (lr & 0xFF); + dst[1 + 4] = ((lr >> 8) & 0xFF); + dst[2 + 4] = (rr & 0xFF); + dst[3 + 4] = ((rr >> 8) & 0xFF); + + dst[0 + 8] = (ce & 0xFF); + dst[1 + 8] = ((ce >> 8) & 0xFF); + dst[2 + 8] = (ce & 0xFF); + dst[3 + 8] = ((ce >> 8) & 0xFF); + } + } + } + break; + + case AUDIO_S16: + { + Uint8 *src, *dst; + Sint16 lf, rf, ce, lr, rr; + + src = cvt->buf + cvt->len_cvt; + dst = cvt->buf + cvt->len_cvt * 3; + + if ((format & 0x1000) == 0x1000) { + for (i = cvt->len_cvt / 4; i; --i) { + dst -= 12; + src -= 4; + lf = (Sint16) ((src[0] << 8) | src[1]); + rf = (Sint16) ((src[2] << 8) | src[3]); + ce = (lf / 2) + (rf / 2); + rr = lf - ce; + lr = rf - ce; + dst[1] = (lf & 0xFF); + dst[0] = ((lf >> 8) & 0xFF); + dst[3] = (rf & 0xFF); + dst[2] = ((rf >> 8) & 0xFF); + + dst[1 + 4] = (lr & 0xFF); + dst[0 + 4] = ((lr >> 8) & 0xFF); + dst[3 + 4] = (rr & 0xFF); + dst[2 + 4] = ((rr >> 8) & 0xFF); + + dst[1 + 8] = (ce & 0xFF); + dst[0 + 8] = ((ce >> 8) & 0xFF); + dst[3 + 8] = (ce & 0xFF); + dst[2 + 8] = ((ce >> 8) & 0xFF); + } + } else { + for (i = cvt->len_cvt / 4; i; --i) { + dst -= 12; + src -= 4; + lf = (Sint16) ((src[1] << 8) | src[0]); + rf = (Sint16) ((src[3] << 8) | src[2]); + ce = (lf / 2) + (rf / 2); + rr = lf - ce; + lr = rf - ce; + dst[0] = (lf & 0xFF); + dst[1] = ((lf >> 8) & 0xFF); + dst[2] = (rf & 0xFF); + dst[3] = ((rf >> 8) & 0xFF); + + dst[0 + 4] = (lr & 0xFF); + dst[1 + 4] = ((lr >> 8) & 0xFF); + dst[2 + 4] = (rr & 0xFF); + dst[3 + 4] = ((rr >> 8) & 0xFF); + + dst[0 + 8] = (ce & 0xFF); + dst[1 + 8] = ((ce >> 8) & 0xFF); + dst[2 + 8] = (ce & 0xFF); + dst[3 + 8] = ((ce >> 8) & 0xFF); + } + } + } + break; + } + cvt->len_cvt *= 3; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index] (cvt, format); + } } /* Duplicate a stereo channel to a pseudo-4.0 stream */ -void SDLCALL SDL_ConvertSurround_4(SDL_AudioCVT *cvt, Uint16 format) +void SDLCALL +SDL_ConvertSurround_4(SDL_AudioCVT * cvt, Uint16 format) { - int i; + int i; #ifdef DEBUG_CONVERT - fprintf(stderr, "Converting stereo to quad\n"); + fprintf(stderr, "Converting stereo to quad\n"); #endif - switch (format&0x8018) { - - case AUDIO_U8: { - Uint8 *src, *dst, lf, rf, ce; - - src = (Uint8 *)(cvt->buf+cvt->len_cvt); - dst = (Uint8 *)(cvt->buf+cvt->len_cvt*2); - for ( i=cvt->len_cvt; i; --i ) { - dst -= 4; - src -= 2; - lf = src[0]; - rf = src[1]; - ce = (lf/2) + (rf/2); - dst[0] = lf; - dst[1] = rf; - dst[2] = lf - ce; - dst[3] = rf - ce; - } - } - break; - - case AUDIO_S8: { - Sint8 *src, *dst, lf, rf, ce; - - src = (Sint8 *)cvt->buf+cvt->len_cvt; - dst = (Sint8 *)cvt->buf+cvt->len_cvt*2; - for ( i=cvt->len_cvt; i; --i ) { - dst -= 4; - src -= 2; - lf = src[0]; - rf = src[1]; - ce = (lf/2) + (rf/2); - dst[0] = lf; - dst[1] = rf; - dst[2] = lf - ce; - dst[3] = rf - ce; - } - } - break; - - case AUDIO_U16: { - Uint8 *src, *dst; - Uint16 lf, rf, ce, lr, rr; - - src = cvt->buf+cvt->len_cvt; - dst = cvt->buf+cvt->len_cvt*2; - - if ( (format & 0x1000) == 0x1000 ) { - for ( i=cvt->len_cvt/4; i; --i ) { - dst -= 8; - src -= 4; - lf = (Uint16)((src[0]<<8)|src[1]); - rf = (Uint16)((src[2]<<8)|src[3]); - ce = (lf/2) + (rf/2); - rr = lf - ce; - lr = rf - ce; - dst[1] = (lf&0xFF); - dst[0] = ((lf>>8)&0xFF); - dst[3] = (rf&0xFF); - dst[2] = ((rf>>8)&0xFF); - - dst[1+4] = (lr&0xFF); - dst[0+4] = ((lr>>8)&0xFF); - dst[3+4] = (rr&0xFF); - dst[2+4] = ((rr>>8)&0xFF); - } - } else { - for ( i=cvt->len_cvt/4; i; --i ) { - dst -= 8; - src -= 4; - lf = (Uint16)((src[1]<<8)|src[0]); - rf = (Uint16)((src[3]<<8)|src[2]); - ce = (lf/2) + (rf/2); - rr = lf - ce; - lr = rf - ce; - dst[0] = (lf&0xFF); - dst[1] = ((lf>>8)&0xFF); - dst[2] = (rf&0xFF); - dst[3] = ((rf>>8)&0xFF); - - dst[0+4] = (lr&0xFF); - dst[1+4] = ((lr>>8)&0xFF); - dst[2+4] = (rr&0xFF); - dst[3+4] = ((rr>>8)&0xFF); - } - } - } - break; - - case AUDIO_S16: { - Uint8 *src, *dst; - Sint16 lf, rf, ce, lr, rr; - - src = cvt->buf+cvt->len_cvt; - dst = cvt->buf+cvt->len_cvt*2; - - if ( (format & 0x1000) == 0x1000 ) { - for ( i=cvt->len_cvt/4; i; --i ) { - dst -= 8; - src -= 4; - lf = (Sint16)((src[0]<<8)|src[1]); - rf = (Sint16)((src[2]<<8)|src[3]); - ce = (lf/2) + (rf/2); - rr = lf - ce; - lr = rf - ce; - dst[1] = (lf&0xFF); - dst[0] = ((lf>>8)&0xFF); - dst[3] = (rf&0xFF); - dst[2] = ((rf>>8)&0xFF); - - dst[1+4] = (lr&0xFF); - dst[0+4] = ((lr>>8)&0xFF); - dst[3+4] = (rr&0xFF); - dst[2+4] = ((rr>>8)&0xFF); - } - } else { - for ( i=cvt->len_cvt/4; i; --i ) { - dst -= 8; - src -= 4; - lf = (Sint16)((src[1]<<8)|src[0]); - rf = (Sint16)((src[3]<<8)|src[2]); - ce = (lf/2) + (rf/2); - rr = lf - ce; - lr = rf - ce; - dst[0] = (lf&0xFF); - dst[1] = ((lf>>8)&0xFF); - dst[2] = (rf&0xFF); - dst[3] = ((rf>>8)&0xFF); - - dst[0+4] = (lr&0xFF); - dst[1+4] = ((lr>>8)&0xFF); - dst[2+4] = (rr&0xFF); - dst[3+4] = ((rr>>8)&0xFF); - } - } - } - break; - } - cvt->len_cvt *= 2; - if ( cvt->filters[++cvt->filter_index] ) { - cvt->filters[cvt->filter_index](cvt, format); - } + switch (format & 0x8018) { + + case AUDIO_U8: + { + Uint8 *src, *dst, lf, rf, ce; + + src = (Uint8 *) (cvt->buf + cvt->len_cvt); + dst = (Uint8 *) (cvt->buf + cvt->len_cvt * 2); + for (i = cvt->len_cvt; i; --i) { + dst -= 4; + src -= 2; + lf = src[0]; + rf = src[1]; + ce = (lf / 2) + (rf / 2); + dst[0] = lf; + dst[1] = rf; + dst[2] = lf - ce; + dst[3] = rf - ce; + } + } + break; + + case AUDIO_S8: + { + Sint8 *src, *dst, lf, rf, ce; + + src = (Sint8 *) cvt->buf + cvt->len_cvt; + dst = (Sint8 *) cvt->buf + cvt->len_cvt * 2; + for (i = cvt->len_cvt; i; --i) { + dst -= 4; + src -= 2; + lf = src[0]; + rf = src[1]; + ce = (lf / 2) + (rf / 2); + dst[0] = lf; + dst[1] = rf; + dst[2] = lf - ce; + dst[3] = rf - ce; + } + } + break; + + case AUDIO_U16: + { + Uint8 *src, *dst; + Uint16 lf, rf, ce, lr, rr; + + src = cvt->buf + cvt->len_cvt; + dst = cvt->buf + cvt->len_cvt * 2; + + if ((format & 0x1000) == 0x1000) { + for (i = cvt->len_cvt / 4; i; --i) { + dst -= 8; + src -= 4; + lf = (Uint16) ((src[0] << 8) | src[1]); + rf = (Uint16) ((src[2] << 8) | src[3]); + ce = (lf / 2) + (rf / 2); + rr = lf - ce; + lr = rf - ce; + dst[1] = (lf & 0xFF); + dst[0] = ((lf >> 8) & 0xFF); + dst[3] = (rf & 0xFF); + dst[2] = ((rf >> 8) & 0xFF); + + dst[1 + 4] = (lr & 0xFF); + dst[0 + 4] = ((lr >> 8) & 0xFF); + dst[3 + 4] = (rr & 0xFF); + dst[2 + 4] = ((rr >> 8) & 0xFF); + } + } else { + for (i = cvt->len_cvt / 4; i; --i) { + dst -= 8; + src -= 4; + lf = (Uint16) ((src[1] << 8) | src[0]); + rf = (Uint16) ((src[3] << 8) | src[2]); + ce = (lf / 2) + (rf / 2); + rr = lf - ce; + lr = rf - ce; + dst[0] = (lf & 0xFF); + dst[1] = ((lf >> 8) & 0xFF); + dst[2] = (rf & 0xFF); + dst[3] = ((rf >> 8) & 0xFF); + + dst[0 + 4] = (lr & 0xFF); + dst[1 + 4] = ((lr >> 8) & 0xFF); + dst[2 + 4] = (rr & 0xFF); + dst[3 + 4] = ((rr >> 8) & 0xFF); + } + } + } + break; + + case AUDIO_S16: + { + Uint8 *src, *dst; + Sint16 lf, rf, ce, lr, rr; + + src = cvt->buf + cvt->len_cvt; + dst = cvt->buf + cvt->len_cvt * 2; + + if ((format & 0x1000) == 0x1000) { + for (i = cvt->len_cvt / 4; i; --i) { + dst -= 8; + src -= 4; + lf = (Sint16) ((src[0] << 8) | src[1]); + rf = (Sint16) ((src[2] << 8) | src[3]); + ce = (lf / 2) + (rf / 2); + rr = lf - ce; + lr = rf - ce; + dst[1] = (lf & 0xFF); + dst[0] = ((lf >> 8) & 0xFF); + dst[3] = (rf & 0xFF); + dst[2] = ((rf >> 8) & 0xFF); + + dst[1 + 4] = (lr & 0xFF); + dst[0 + 4] = ((lr >> 8) & 0xFF); + dst[3 + 4] = (rr & 0xFF); + dst[2 + 4] = ((rr >> 8) & 0xFF); + } + } else { + for (i = cvt->len_cvt / 4; i; --i) { + dst -= 8; + src -= 4; + lf = (Sint16) ((src[1] << 8) | src[0]); + rf = (Sint16) ((src[3] << 8) | src[2]); + ce = (lf / 2) + (rf / 2); + rr = lf - ce; + lr = rf - ce; + dst[0] = (lf & 0xFF); + dst[1] = ((lf >> 8) & 0xFF); + dst[2] = (rf & 0xFF); + dst[3] = ((rf >> 8) & 0xFF); + + dst[0 + 4] = (lr & 0xFF); + dst[1 + 4] = ((lr >> 8) & 0xFF); + dst[2 + 4] = (rr & 0xFF); + dst[3 + 4] = ((rr >> 8) & 0xFF); + } + } + } + break; + } + cvt->len_cvt *= 2; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index] (cvt, format); + } } /* Convert 8-bit to 16-bit - LSB */ -void SDLCALL SDL_Convert16LSB(SDL_AudioCVT *cvt, Uint16 format) +void SDLCALL +SDL_Convert16LSB(SDL_AudioCVT * cvt, Uint16 format) { - int i; - Uint8 *src, *dst; + int i; + Uint8 *src, *dst; #ifdef DEBUG_CONVERT - fprintf(stderr, "Converting to 16-bit LSB\n"); + fprintf(stderr, "Converting to 16-bit LSB\n"); #endif - src = cvt->buf+cvt->len_cvt; - dst = cvt->buf+cvt->len_cvt*2; - for ( i=cvt->len_cvt; i; --i ) { - src -= 1; - dst -= 2; - dst[1] = *src; - dst[0] = 0; - } - format = ((format & ~0x0008) | AUDIO_U16LSB); - cvt->len_cvt *= 2; - if ( cvt->filters[++cvt->filter_index] ) { - cvt->filters[cvt->filter_index](cvt, format); - } + src = cvt->buf + cvt->len_cvt; + dst = cvt->buf + cvt->len_cvt * 2; + for (i = cvt->len_cvt; i; --i) { + src -= 1; + dst -= 2; + dst[1] = *src; + dst[0] = 0; + } + format = ((format & ~0x0008) | AUDIO_U16LSB); + cvt->len_cvt *= 2; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index] (cvt, format); + } } + /* Convert 8-bit to 16-bit - MSB */ -void SDLCALL SDL_Convert16MSB(SDL_AudioCVT *cvt, Uint16 format) +void SDLCALL +SDL_Convert16MSB(SDL_AudioCVT * cvt, Uint16 format) { - int i; - Uint8 *src, *dst; + int i; + Uint8 *src, *dst; #ifdef DEBUG_CONVERT - fprintf(stderr, "Converting to 16-bit MSB\n"); + fprintf(stderr, "Converting to 16-bit MSB\n"); #endif - src = cvt->buf+cvt->len_cvt; - dst = cvt->buf+cvt->len_cvt*2; - for ( i=cvt->len_cvt; i; --i ) { - src -= 1; - dst -= 2; - dst[0] = *src; - dst[1] = 0; - } - format = ((format & ~0x0008) | AUDIO_U16MSB); - cvt->len_cvt *= 2; - if ( cvt->filters[++cvt->filter_index] ) { - cvt->filters[cvt->filter_index](cvt, format); - } + src = cvt->buf + cvt->len_cvt; + dst = cvt->buf + cvt->len_cvt * 2; + for (i = cvt->len_cvt; i; --i) { + src -= 1; + dst -= 2; + dst[0] = *src; + dst[1] = 0; + } + format = ((format & ~0x0008) | AUDIO_U16MSB); + cvt->len_cvt *= 2; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index] (cvt, format); + } } /* Convert 16-bit to 8-bit */ -void SDLCALL SDL_Convert8(SDL_AudioCVT *cvt, Uint16 format) +void SDLCALL +SDL_Convert8(SDL_AudioCVT * cvt, Uint16 format) { - int i; - Uint8 *src, *dst; + int i; + Uint8 *src, *dst; #ifdef DEBUG_CONVERT - fprintf(stderr, "Converting to 8-bit\n"); + fprintf(stderr, "Converting to 8-bit\n"); #endif - src = cvt->buf; - dst = cvt->buf; - if ( (format & 0x1000) != 0x1000 ) { /* Little endian */ - ++src; - } - for ( i=cvt->len_cvt/2; i; --i ) { - *dst = *src; - src += 2; - dst += 1; - } - format = ((format & ~0x9010) | AUDIO_U8); - cvt->len_cvt /= 2; - if ( cvt->filters[++cvt->filter_index] ) { - cvt->filters[cvt->filter_index](cvt, format); - } + src = cvt->buf; + dst = cvt->buf; + if ((format & 0x1000) != 0x1000) { /* Little endian */ + ++src; + } + for (i = cvt->len_cvt / 2; i; --i) { + *dst = *src; + src += 2; + dst += 1; + } + format = ((format & ~0x9010) | AUDIO_U8); + cvt->len_cvt /= 2; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index] (cvt, format); + } } /* Toggle signed/unsigned */ -void SDLCALL SDL_ConvertSign(SDL_AudioCVT *cvt, Uint16 format) +void SDLCALL +SDL_ConvertSign(SDL_AudioCVT * cvt, Uint16 format) { - int i; - Uint8 *data; + int i; + Uint8 *data; #ifdef DEBUG_CONVERT - fprintf(stderr, "Converting audio signedness\n"); + fprintf(stderr, "Converting audio signedness\n"); #endif - data = cvt->buf; - if ( (format & 0xFF) == 16 ) { - if ( (format & 0x1000) != 0x1000 ) { /* Little endian */ - ++data; - } - for ( i=cvt->len_cvt/2; i; --i ) { - *data ^= 0x80; - data += 2; - } - } else { - for ( i=cvt->len_cvt; i; --i ) { - *data++ ^= 0x80; - } - } - format = (format ^ 0x8000); - if ( cvt->filters[++cvt->filter_index] ) { - cvt->filters[cvt->filter_index](cvt, format); - } + data = cvt->buf; + if ((format & 0xFF) == 16) { + if ((format & 0x1000) != 0x1000) { /* Little endian */ + ++data; + } + for (i = cvt->len_cvt / 2; i; --i) { + *data ^= 0x80; + data += 2; + } + } else { + for (i = cvt->len_cvt; i; --i) { + *data++ ^= 0x80; + } + } + format = (format ^ 0x8000); + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index] (cvt, format); + } } /* Toggle endianness */ -void SDLCALL SDL_ConvertEndian(SDL_AudioCVT *cvt, Uint16 format) +void SDLCALL +SDL_ConvertEndian(SDL_AudioCVT * cvt, Uint16 format) { - int i; - Uint8 *data, tmp; + int i; + Uint8 *data, tmp; #ifdef DEBUG_CONVERT - fprintf(stderr, "Converting audio endianness\n"); + fprintf(stderr, "Converting audio endianness\n"); #endif - data = cvt->buf; - for ( i=cvt->len_cvt/2; i; --i ) { - tmp = data[0]; - data[0] = data[1]; - data[1] = tmp; - data += 2; - } - format = (format ^ 0x1000); - if ( cvt->filters[++cvt->filter_index] ) { - cvt->filters[cvt->filter_index](cvt, format); - } + data = cvt->buf; + for (i = cvt->len_cvt / 2; i; --i) { + tmp = data[0]; + data[0] = data[1]; + data[1] = tmp; + data += 2; + } + format = (format ^ 0x1000); + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index] (cvt, format); + } } /* Convert rate up by multiple of 2 */ -void SDLCALL SDL_RateMUL2(SDL_AudioCVT *cvt, Uint16 format) +void SDLCALL +SDL_RateMUL2(SDL_AudioCVT * cvt, Uint16 format) { - int i; - Uint8 *src, *dst; + int i; + Uint8 *src, *dst; #ifdef DEBUG_CONVERT - fprintf(stderr, "Converting audio rate * 2\n"); + fprintf(stderr, "Converting audio rate * 2\n"); #endif - src = cvt->buf+cvt->len_cvt; - dst = cvt->buf+cvt->len_cvt*2; - switch (format & 0xFF) { - case 8: - for ( i=cvt->len_cvt; i; --i ) { - src -= 1; - dst -= 2; - dst[0] = src[0]; - dst[1] = src[0]; - } - break; - case 16: - for ( i=cvt->len_cvt/2; i; --i ) { - src -= 2; - dst -= 4; - dst[0] = src[0]; - dst[1] = src[1]; - dst[2] = src[0]; - dst[3] = src[1]; - } - break; - } - cvt->len_cvt *= 2; - if ( cvt->filters[++cvt->filter_index] ) { - cvt->filters[cvt->filter_index](cvt, format); - } + src = cvt->buf + cvt->len_cvt; + dst = cvt->buf + cvt->len_cvt * 2; + switch (format & 0xFF) { + case 8: + for (i = cvt->len_cvt; i; --i) { + src -= 1; + dst -= 2; + dst[0] = src[0]; + dst[1] = src[0]; + } + break; + case 16: + for (i = cvt->len_cvt / 2; i; --i) { + src -= 2; + dst -= 4; + dst[0] = src[0]; + dst[1] = src[1]; + dst[2] = src[0]; + dst[3] = src[1]; + } + break; + } + cvt->len_cvt *= 2; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index] (cvt, format); + } } /* Convert rate up by multiple of 2, for stereo */ -void SDLCALL SDL_RateMUL2_c2(SDL_AudioCVT *cvt, Uint16 format) +void SDLCALL +SDL_RateMUL2_c2(SDL_AudioCVT * cvt, Uint16 format) { - int i; - Uint8 *src, *dst; + int i; + Uint8 *src, *dst; #ifdef DEBUG_CONVERT - fprintf(stderr, "Converting audio rate * 2\n"); + fprintf(stderr, "Converting audio rate * 2\n"); #endif - src = cvt->buf+cvt->len_cvt; - dst = cvt->buf+cvt->len_cvt*2; - switch (format & 0xFF) { - case 8: - for ( i=cvt->len_cvt/2; i; --i ) { - src -= 2; - dst -= 4; - dst[0] = src[0]; - dst[1] = src[1]; - dst[2] = src[0]; - dst[3] = src[1]; - } - break; - case 16: - for ( i=cvt->len_cvt/4; i; --i ) { - src -= 4; - dst -= 8; - dst[0] = src[0]; - dst[1] = src[1]; - dst[2] = src[2]; - dst[3] = src[3]; - dst[4] = src[0]; - dst[5] = src[1]; - dst[6] = src[2]; - dst[7] = src[3]; - } - break; - } - cvt->len_cvt *= 2; - if ( cvt->filters[++cvt->filter_index] ) { - cvt->filters[cvt->filter_index](cvt, format); - } + src = cvt->buf + cvt->len_cvt; + dst = cvt->buf + cvt->len_cvt * 2; + switch (format & 0xFF) { + case 8: + for (i = cvt->len_cvt / 2; i; --i) { + src -= 2; + dst -= 4; + dst[0] = src[0]; + dst[1] = src[1]; + dst[2] = src[0]; + dst[3] = src[1]; + } + break; + case 16: + for (i = cvt->len_cvt / 4; i; --i) { + src -= 4; + dst -= 8; + dst[0] = src[0]; + dst[1] = src[1]; + dst[2] = src[2]; + dst[3] = src[3]; + dst[4] = src[0]; + dst[5] = src[1]; + dst[6] = src[2]; + dst[7] = src[3]; + } + break; + } + cvt->len_cvt *= 2; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index] (cvt, format); + } } /* Convert rate up by multiple of 2, for quad */ -void SDLCALL SDL_RateMUL2_c4(SDL_AudioCVT *cvt, Uint16 format) +void SDLCALL +SDL_RateMUL2_c4(SDL_AudioCVT * cvt, Uint16 format) { - int i; - Uint8 *src, *dst; + int i; + Uint8 *src, *dst; #ifdef DEBUG_CONVERT - fprintf(stderr, "Converting audio rate * 2\n"); + fprintf(stderr, "Converting audio rate * 2\n"); #endif - src = cvt->buf+cvt->len_cvt; - dst = cvt->buf+cvt->len_cvt*2; - switch (format & 0xFF) { - case 8: - for ( i=cvt->len_cvt/4; i; --i ) { - src -= 4; - dst -= 8; - dst[0] = src[0]; - dst[1] = src[1]; - dst[2] = src[2]; - dst[3] = src[3]; - dst[4] = src[0]; - dst[5] = src[1]; - dst[6] = src[2]; - dst[7] = src[3]; - } - break; - case 16: - for ( i=cvt->len_cvt/8; i; --i ) { - src -= 8; - dst -= 16; - dst[0] = src[0]; - dst[1] = src[1]; - dst[2] = src[2]; - dst[3] = src[3]; - dst[4] = src[4]; - dst[5] = src[5]; - dst[6] = src[6]; - dst[7] = src[7]; - dst[8] = src[0]; - dst[9] = src[1]; - dst[10] = src[2]; - dst[11] = src[3]; - dst[12] = src[4]; - dst[13] = src[5]; - dst[14] = src[6]; - dst[15] = src[7]; - } - break; - } - cvt->len_cvt *= 2; - if ( cvt->filters[++cvt->filter_index] ) { - cvt->filters[cvt->filter_index](cvt, format); - } + src = cvt->buf + cvt->len_cvt; + dst = cvt->buf + cvt->len_cvt * 2; + switch (format & 0xFF) { + case 8: + for (i = cvt->len_cvt / 4; i; --i) { + src -= 4; + dst -= 8; + dst[0] = src[0]; + dst[1] = src[1]; + dst[2] = src[2]; + dst[3] = src[3]; + dst[4] = src[0]; + dst[5] = src[1]; + dst[6] = src[2]; + dst[7] = src[3]; + } + break; + case 16: + for (i = cvt->len_cvt / 8; i; --i) { + src -= 8; + dst -= 16; + dst[0] = src[0]; + dst[1] = src[1]; + dst[2] = src[2]; + dst[3] = src[3]; + dst[4] = src[4]; + dst[5] = src[5]; + dst[6] = src[6]; + dst[7] = src[7]; + dst[8] = src[0]; + dst[9] = src[1]; + dst[10] = src[2]; + dst[11] = src[3]; + dst[12] = src[4]; + dst[13] = src[5]; + dst[14] = src[6]; + dst[15] = src[7]; + } + break; + } + cvt->len_cvt *= 2; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index] (cvt, format); + } } /* Convert rate up by multiple of 2, for 5.1 */ -void SDLCALL SDL_RateMUL2_c6(SDL_AudioCVT *cvt, Uint16 format) +void SDLCALL +SDL_RateMUL2_c6(SDL_AudioCVT * cvt, Uint16 format) { - int i; - Uint8 *src, *dst; + int i; + Uint8 *src, *dst; #ifdef DEBUG_CONVERT - fprintf(stderr, "Converting audio rate * 2\n"); + fprintf(stderr, "Converting audio rate * 2\n"); #endif - src = cvt->buf+cvt->len_cvt; - dst = cvt->buf+cvt->len_cvt*2; - switch (format & 0xFF) { - case 8: - for ( i=cvt->len_cvt/6; i; --i ) { - src -= 6; - dst -= 12; - dst[0] = src[0]; - dst[1] = src[1]; - dst[2] = src[2]; - dst[3] = src[3]; - dst[4] = src[4]; - dst[5] = src[5]; - dst[6] = src[0]; - dst[7] = src[1]; - dst[8] = src[2]; - dst[9] = src[3]; - dst[10] = src[4]; - dst[11] = src[5]; - } - break; - case 16: - for ( i=cvt->len_cvt/12; i; --i ) { - src -= 12; - dst -= 24; - dst[0] = src[0]; - dst[1] = src[1]; - dst[2] = src[2]; - dst[3] = src[3]; - dst[4] = src[4]; - dst[5] = src[5]; - dst[6] = src[6]; - dst[7] = src[7]; - dst[8] = src[8]; - dst[9] = src[9]; - dst[10] = src[10]; - dst[11] = src[11]; - dst[12] = src[0]; - dst[13] = src[1]; - dst[14] = src[2]; - dst[15] = src[3]; - dst[16] = src[4]; - dst[17] = src[5]; - dst[18] = src[6]; - dst[19] = src[7]; - dst[20] = src[8]; - dst[21] = src[9]; - dst[22] = src[10]; - dst[23] = src[11]; - } - break; - } - cvt->len_cvt *= 2; - if ( cvt->filters[++cvt->filter_index] ) { - cvt->filters[cvt->filter_index](cvt, format); - } + src = cvt->buf + cvt->len_cvt; + dst = cvt->buf + cvt->len_cvt * 2; + switch (format & 0xFF) { + case 8: + for (i = cvt->len_cvt / 6; i; --i) { + src -= 6; + dst -= 12; + dst[0] = src[0]; + dst[1] = src[1]; + dst[2] = src[2]; + dst[3] = src[3]; + dst[4] = src[4]; + dst[5] = src[5]; + dst[6] = src[0]; + dst[7] = src[1]; + dst[8] = src[2]; + dst[9] = src[3]; + dst[10] = src[4]; + dst[11] = src[5]; + } + break; + case 16: + for (i = cvt->len_cvt / 12; i; --i) { + src -= 12; + dst -= 24; + dst[0] = src[0]; + dst[1] = src[1]; + dst[2] = src[2]; + dst[3] = src[3]; + dst[4] = src[4]; + dst[5] = src[5]; + dst[6] = src[6]; + dst[7] = src[7]; + dst[8] = src[8]; + dst[9] = src[9]; + dst[10] = src[10]; + dst[11] = src[11]; + dst[12] = src[0]; + dst[13] = src[1]; + dst[14] = src[2]; + dst[15] = src[3]; + dst[16] = src[4]; + dst[17] = src[5]; + dst[18] = src[6]; + dst[19] = src[7]; + dst[20] = src[8]; + dst[21] = src[9]; + dst[22] = src[10]; + dst[23] = src[11]; + } + break; + } + cvt->len_cvt *= 2; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index] (cvt, format); + } } /* Convert rate down by multiple of 2 */ -void SDLCALL SDL_RateDIV2(SDL_AudioCVT *cvt, Uint16 format) +void SDLCALL +SDL_RateDIV2(SDL_AudioCVT * cvt, Uint16 format) { - int i; - Uint8 *src, *dst; + int i; + Uint8 *src, *dst; #ifdef DEBUG_CONVERT - fprintf(stderr, "Converting audio rate / 2\n"); + fprintf(stderr, "Converting audio rate / 2\n"); #endif - src = cvt->buf; - dst = cvt->buf; - switch (format & 0xFF) { - case 8: - for ( i=cvt->len_cvt/2; i; --i ) { - dst[0] = src[0]; - src += 2; - dst += 1; - } - break; - case 16: - for ( i=cvt->len_cvt/4; i; --i ) { - dst[0] = src[0]; - dst[1] = src[1]; - src += 4; - dst += 2; - } - break; - } - cvt->len_cvt /= 2; - if ( cvt->filters[++cvt->filter_index] ) { - cvt->filters[cvt->filter_index](cvt, format); - } + src = cvt->buf; + dst = cvt->buf; + switch (format & 0xFF) { + case 8: + for (i = cvt->len_cvt / 2; i; --i) { + dst[0] = src[0]; + src += 2; + dst += 1; + } + break; + case 16: + for (i = cvt->len_cvt / 4; i; --i) { + dst[0] = src[0]; + dst[1] = src[1]; + src += 4; + dst += 2; + } + break; + } + cvt->len_cvt /= 2; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index] (cvt, format); + } } /* Convert rate down by multiple of 2, for stereo */ -void SDLCALL SDL_RateDIV2_c2(SDL_AudioCVT *cvt, Uint16 format) +void SDLCALL +SDL_RateDIV2_c2(SDL_AudioCVT * cvt, Uint16 format) { - int i; - Uint8 *src, *dst; + int i; + Uint8 *src, *dst; #ifdef DEBUG_CONVERT - fprintf(stderr, "Converting audio rate / 2\n"); + fprintf(stderr, "Converting audio rate / 2\n"); #endif - src = cvt->buf; - dst = cvt->buf; - switch (format & 0xFF) { - case 8: - for ( i=cvt->len_cvt/4; i; --i ) { - dst[0] = src[0]; - dst[1] = src[1]; - src += 4; - dst += 2; - } - break; - case 16: - for ( i=cvt->len_cvt/8; i; --i ) { - dst[0] = src[0]; - dst[1] = src[1]; - dst[2] = src[2]; - dst[3] = src[3]; - src += 8; - dst += 4; - } - break; - } - cvt->len_cvt /= 2; - if ( cvt->filters[++cvt->filter_index] ) { - cvt->filters[cvt->filter_index](cvt, format); - } + src = cvt->buf; + dst = cvt->buf; + switch (format & 0xFF) { + case 8: + for (i = cvt->len_cvt / 4; i; --i) { + dst[0] = src[0]; + dst[1] = src[1]; + src += 4; + dst += 2; + } + break; + case 16: + for (i = cvt->len_cvt / 8; i; --i) { + dst[0] = src[0]; + dst[1] = src[1]; + dst[2] = src[2]; + dst[3] = src[3]; + src += 8; + dst += 4; + } + break; + } + cvt->len_cvt /= 2; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index] (cvt, format); + } } /* Convert rate down by multiple of 2, for quad */ -void SDLCALL SDL_RateDIV2_c4(SDL_AudioCVT *cvt, Uint16 format) +void SDLCALL +SDL_RateDIV2_c4(SDL_AudioCVT * cvt, Uint16 format) { - int i; - Uint8 *src, *dst; + int i; + Uint8 *src, *dst; #ifdef DEBUG_CONVERT - fprintf(stderr, "Converting audio rate / 2\n"); + fprintf(stderr, "Converting audio rate / 2\n"); #endif - src = cvt->buf; - dst = cvt->buf; - switch (format & 0xFF) { - case 8: - for ( i=cvt->len_cvt/8; i; --i ) { - dst[0] = src[0]; - dst[1] = src[1]; - dst[2] = src[2]; - dst[3] = src[3]; - src += 8; - dst += 4; - } - break; - case 16: - for ( i=cvt->len_cvt/16; i; --i ) { - dst[0] = src[0]; - dst[1] = src[1]; - dst[2] = src[2]; - dst[3] = src[3]; - dst[4] = src[4]; - dst[5] = src[5]; - dst[6] = src[6]; - dst[7] = src[7]; - src += 16; - dst += 8; - } - break; - } - cvt->len_cvt /= 2; - if ( cvt->filters[++cvt->filter_index] ) { - cvt->filters[cvt->filter_index](cvt, format); - } + src = cvt->buf; + dst = cvt->buf; + switch (format & 0xFF) { + case 8: + for (i = cvt->len_cvt / 8; i; --i) { + dst[0] = src[0]; + dst[1] = src[1]; + dst[2] = src[2]; + dst[3] = src[3]; + src += 8; + dst += 4; + } + break; + case 16: + for (i = cvt->len_cvt / 16; i; --i) { + dst[0] = src[0]; + dst[1] = src[1]; + dst[2] = src[2]; + dst[3] = src[3]; + dst[4] = src[4]; + dst[5] = src[5]; + dst[6] = src[6]; + dst[7] = src[7]; + src += 16; + dst += 8; + } + break; + } + cvt->len_cvt /= 2; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index] (cvt, format); + } } /* Convert rate down by multiple of 2, for 5.1 */ -void SDLCALL SDL_RateDIV2_c6(SDL_AudioCVT *cvt, Uint16 format) +void SDLCALL +SDL_RateDIV2_c6(SDL_AudioCVT * cvt, Uint16 format) { - int i; - Uint8 *src, *dst; + int i; + Uint8 *src, *dst; #ifdef DEBUG_CONVERT - fprintf(stderr, "Converting audio rate / 2\n"); + fprintf(stderr, "Converting audio rate / 2\n"); #endif - src = cvt->buf; - dst = cvt->buf; - switch (format & 0xFF) { - case 8: - for ( i=cvt->len_cvt/12; i; --i ) { - dst[0] = src[0]; - dst[1] = src[1]; - dst[2] = src[2]; - dst[3] = src[3]; - dst[4] = src[4]; - dst[5] = src[5]; - src += 12; - dst += 6; - } - break; - case 16: - for ( i=cvt->len_cvt/24; i; --i ) { - dst[0] = src[0]; - dst[1] = src[1]; - dst[2] = src[2]; - dst[3] = src[3]; - dst[4] = src[4]; - dst[5] = src[5]; - dst[6] = src[6]; - dst[7] = src[7]; - dst[8] = src[8]; - dst[9] = src[9]; - dst[10] = src[10]; - dst[11] = src[11]; - src += 24; - dst += 12; - } - break; - } - cvt->len_cvt /= 2; - if ( cvt->filters[++cvt->filter_index] ) { - cvt->filters[cvt->filter_index](cvt, format); - } + src = cvt->buf; + dst = cvt->buf; + switch (format & 0xFF) { + case 8: + for (i = cvt->len_cvt / 12; i; --i) { + dst[0] = src[0]; + dst[1] = src[1]; + dst[2] = src[2]; + dst[3] = src[3]; + dst[4] = src[4]; + dst[5] = src[5]; + src += 12; + dst += 6; + } + break; + case 16: + for (i = cvt->len_cvt / 24; i; --i) { + dst[0] = src[0]; + dst[1] = src[1]; + dst[2] = src[2]; + dst[3] = src[3]; + dst[4] = src[4]; + dst[5] = src[5]; + dst[6] = src[6]; + dst[7] = src[7]; + dst[8] = src[8]; + dst[9] = src[9]; + dst[10] = src[10]; + dst[11] = src[11]; + src += 24; + dst += 12; + } + break; + } + cvt->len_cvt /= 2; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index] (cvt, format); + } } /* Very slow rate conversion routine */ -void SDLCALL SDL_RateSLOW(SDL_AudioCVT *cvt, Uint16 format) +void SDLCALL +SDL_RateSLOW(SDL_AudioCVT * cvt, Uint16 format) { - double ipos; - int i, clen; + double ipos; + int i, clen; #ifdef DEBUG_CONVERT - fprintf(stderr, "Converting audio rate * %4.4f\n", 1.0/cvt->rate_incr); + fprintf(stderr, "Converting audio rate * %4.4f\n", 1.0 / cvt->rate_incr); #endif - clen = (int)((double)cvt->len_cvt / cvt->rate_incr); - if ( cvt->rate_incr > 1.0 ) { - switch (format & 0xFF) { - case 8: { - Uint8 *output; - - output = cvt->buf; - ipos = 0.0; - for ( i=clen; i; --i ) { - *output = cvt->buf[(int)ipos]; - ipos += cvt->rate_incr; - output += 1; - } - } - break; - - case 16: { - Uint16 *output; - - clen &= ~1; - output = (Uint16 *)cvt->buf; - ipos = 0.0; - for ( i=clen/2; i; --i ) { - *output=((Uint16 *)cvt->buf)[(int)ipos]; - ipos += cvt->rate_incr; - output += 1; - } - } - break; - } - } else { - switch (format & 0xFF) { - case 8: { - Uint8 *output; - - output = cvt->buf+clen; - ipos = (double)cvt->len_cvt; - for ( i=clen; i; --i ) { - ipos -= cvt->rate_incr; - output -= 1; - *output = cvt->buf[(int)ipos]; - } - } - break; - - case 16: { - Uint16 *output; - - clen &= ~1; - output = (Uint16 *)(cvt->buf+clen); - ipos = (double)cvt->len_cvt/2; - for ( i=clen/2; i; --i ) { - ipos -= cvt->rate_incr; - output -= 1; - *output=((Uint16 *)cvt->buf)[(int)ipos]; - } - } - break; - } - } - cvt->len_cvt = clen; - if ( cvt->filters[++cvt->filter_index] ) { - cvt->filters[cvt->filter_index](cvt, format); - } + clen = (int) ((double) cvt->len_cvt / cvt->rate_incr); + if (cvt->rate_incr > 1.0) { + switch (format & 0xFF) { + case 8: + { + Uint8 *output; + + output = cvt->buf; + ipos = 0.0; + for (i = clen; i; --i) { + *output = cvt->buf[(int) ipos]; + ipos += cvt->rate_incr; + output += 1; + } + } + break; + + case 16: + { + Uint16 *output; + + clen &= ~1; + output = (Uint16 *) cvt->buf; + ipos = 0.0; + for (i = clen / 2; i; --i) { + *output = ((Uint16 *) cvt->buf)[(int) ipos]; + ipos += cvt->rate_incr; + output += 1; + } + } + break; + } + } else { + switch (format & 0xFF) { + case 8: + { + Uint8 *output; + + output = cvt->buf + clen; + ipos = (double) cvt->len_cvt; + for (i = clen; i; --i) { + ipos -= cvt->rate_incr; + output -= 1; + *output = cvt->buf[(int) ipos]; + } + } + break; + + case 16: + { + Uint16 *output; + + clen &= ~1; + output = (Uint16 *) (cvt->buf + clen); + ipos = (double) cvt->len_cvt / 2; + for (i = clen / 2; i; --i) { + ipos -= cvt->rate_incr; + output -= 1; + *output = ((Uint16 *) cvt->buf)[(int) ipos]; + } + } + break; + } + } + cvt->len_cvt = clen; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index] (cvt, format); + } } -int SDL_ConvertAudio(SDL_AudioCVT *cvt) +int +SDL_ConvertAudio(SDL_AudioCVT * cvt) { - /* Make sure there's data to convert */ - if ( cvt->buf == NULL ) { - SDL_SetError("No buffer allocated for conversion"); - return(-1); - } - /* Return okay if no conversion is necessary */ - cvt->len_cvt = cvt->len; - if ( cvt->filters[0] == NULL ) { - return(0); - } - - /* Set up the conversion and go! */ - cvt->filter_index = 0; - cvt->filters[0](cvt, cvt->src_format); - return(0); + /* Make sure there's data to convert */ + if (cvt->buf == NULL) { + SDL_SetError("No buffer allocated for conversion"); + return (-1); + } + /* Return okay if no conversion is necessary */ + cvt->len_cvt = cvt->len; + if (cvt->filters[0] == NULL) { + return (0); + } + + /* Set up the conversion and go! */ + cvt->filter_index = 0; + cvt->filters[0] (cvt, cvt->src_format); + return (0); } /* Creates a set of audio filters to convert from one format to another. Returns -1 if the format conversion is not supported, or 1 if the audio filter is set up. */ - -int SDL_BuildAudioCVT(SDL_AudioCVT *cvt, - Uint16 src_format, Uint8 src_channels, int src_rate, - Uint16 dst_format, Uint8 dst_channels, int dst_rate) + +int +SDL_BuildAudioCVT(SDL_AudioCVT * cvt, + Uint16 src_format, Uint8 src_channels, int src_rate, + Uint16 dst_format, Uint8 dst_channels, int dst_rate) { /*printf("Build format %04x->%04x, channels %u->%u, rate %d->%d\n", src_format, dst_format, src_channels, dst_channels, src_rate, dst_rate);*/ - /* Start off with no conversion necessary */ - cvt->needed = 0; - cvt->filter_index = 0; - cvt->filters[0] = NULL; - cvt->len_mult = 1; - cvt->len_ratio = 1.0; - - /* First filter: Endian conversion from src to dst */ - if ( (src_format & 0x1000) != (dst_format & 0x1000) - && ((src_format & 0xff) != 8) ) { - cvt->filters[cvt->filter_index++] = SDL_ConvertEndian; - } - - /* Second filter: Sign conversion -- signed/unsigned */ - if ( (src_format & 0x8000) != (dst_format & 0x8000) ) { - cvt->filters[cvt->filter_index++] = SDL_ConvertSign; - } - - /* Next filter: Convert 16 bit <--> 8 bit PCM */ - if ( (src_format & 0xFF) != (dst_format & 0xFF) ) { - switch (dst_format&0x10FF) { - case AUDIO_U8: - cvt->filters[cvt->filter_index++] = - SDL_Convert8; - cvt->len_ratio /= 2; - break; - case AUDIO_U16LSB: - cvt->filters[cvt->filter_index++] = - SDL_Convert16LSB; - cvt->len_mult *= 2; - cvt->len_ratio *= 2; - break; - case AUDIO_U16MSB: - cvt->filters[cvt->filter_index++] = - SDL_Convert16MSB; - cvt->len_mult *= 2; - cvt->len_ratio *= 2; - break; - } - } - - /* Last filter: Mono/Stereo conversion */ - if ( src_channels != dst_channels ) { - if ( (src_channels == 1) && (dst_channels > 1) ) { - cvt->filters[cvt->filter_index++] = - SDL_ConvertStereo; - cvt->len_mult *= 2; - src_channels = 2; - cvt->len_ratio *= 2; - } - if ( (src_channels == 2) && - (dst_channels == 6) ) { - cvt->filters[cvt->filter_index++] = - SDL_ConvertSurround; - src_channels = 6; - cvt->len_mult *= 3; - cvt->len_ratio *= 3; - } - if ( (src_channels == 2) && - (dst_channels == 4) ) { - cvt->filters[cvt->filter_index++] = - SDL_ConvertSurround_4; - src_channels = 4; - cvt->len_mult *= 2; - cvt->len_ratio *= 2; - } - while ( (src_channels*2) <= dst_channels ) { - cvt->filters[cvt->filter_index++] = - SDL_ConvertStereo; - cvt->len_mult *= 2; - src_channels *= 2; - cvt->len_ratio *= 2; - } - if ( (src_channels == 6) && - (dst_channels <= 2) ) { - cvt->filters[cvt->filter_index++] = - SDL_ConvertStrip; - src_channels = 2; - cvt->len_ratio /= 3; - } - if ( (src_channels == 6) && - (dst_channels == 4) ) { - cvt->filters[cvt->filter_index++] = - SDL_ConvertStrip_2; - src_channels = 4; - cvt->len_ratio /= 2; - } - /* This assumes that 4 channel audio is in the format: - Left {front/back} + Right {front/back} - so converting to L/R stereo works properly. - */ - while ( ((src_channels%2) == 0) && - ((src_channels/2) >= dst_channels) ) { - cvt->filters[cvt->filter_index++] = - SDL_ConvertMono; - src_channels /= 2; - cvt->len_ratio /= 2; - } - if ( src_channels != dst_channels ) { - /* Uh oh.. */; - } - } - - /* Do rate conversion */ - cvt->rate_incr = 0.0; - if ( (src_rate/100) != (dst_rate/100) ) { - Uint32 hi_rate, lo_rate; - int len_mult; - double len_ratio; - void (SDLCALL *rate_cvt)(SDL_AudioCVT *cvt, Uint16 format); - - if ( src_rate > dst_rate ) { - hi_rate = src_rate; - lo_rate = dst_rate; - switch (src_channels) { - case 1: rate_cvt = SDL_RateDIV2; break; - case 2: rate_cvt = SDL_RateDIV2_c2; break; - case 4: rate_cvt = SDL_RateDIV2_c4; break; - case 6: rate_cvt = SDL_RateDIV2_c6; break; - default: return -1; - } - len_mult = 1; - len_ratio = 0.5; - } else { - hi_rate = dst_rate; - lo_rate = src_rate; - switch (src_channels) { - case 1: rate_cvt = SDL_RateMUL2; break; - case 2: rate_cvt = SDL_RateMUL2_c2; break; - case 4: rate_cvt = SDL_RateMUL2_c4; break; - case 6: rate_cvt = SDL_RateMUL2_c6; break; - default: return -1; - } - len_mult = 2; - len_ratio = 2.0; - } - /* If hi_rate = lo_rate*2^x then conversion is easy */ - while ( ((lo_rate*2)/100) <= (hi_rate/100) ) { - cvt->filters[cvt->filter_index++] = rate_cvt; - cvt->len_mult *= len_mult; - lo_rate *= 2; - cvt->len_ratio *= len_ratio; - } - /* We may need a slow conversion here to finish up */ - if ( (lo_rate/100) != (hi_rate/100) ) { + /* Start off with no conversion necessary */ + cvt->needed = 0; + cvt->filter_index = 0; + cvt->filters[0] = NULL; + cvt->len_mult = 1; + cvt->len_ratio = 1.0; + + /* First filter: Endian conversion from src to dst */ + if ((src_format & 0x1000) != (dst_format & 0x1000) + && ((src_format & 0xff) != 8)) { + cvt->filters[cvt->filter_index++] = SDL_ConvertEndian; + } + + /* Second filter: Sign conversion -- signed/unsigned */ + if ((src_format & 0x8000) != (dst_format & 0x8000)) { + cvt->filters[cvt->filter_index++] = SDL_ConvertSign; + } + + /* Next filter: Convert 16 bit <--> 8 bit PCM */ + if ((src_format & 0xFF) != (dst_format & 0xFF)) { + switch (dst_format & 0x10FF) { + case AUDIO_U8: + cvt->filters[cvt->filter_index++] = SDL_Convert8; + cvt->len_ratio /= 2; + break; + case AUDIO_U16LSB: + cvt->filters[cvt->filter_index++] = SDL_Convert16LSB; + cvt->len_mult *= 2; + cvt->len_ratio *= 2; + break; + case AUDIO_U16MSB: + cvt->filters[cvt->filter_index++] = SDL_Convert16MSB; + cvt->len_mult *= 2; + cvt->len_ratio *= 2; + break; + } + } + + /* Last filter: Mono/Stereo conversion */ + if (src_channels != dst_channels) { + if ((src_channels == 1) && (dst_channels > 1)) { + cvt->filters[cvt->filter_index++] = SDL_ConvertStereo; + cvt->len_mult *= 2; + src_channels = 2; + cvt->len_ratio *= 2; + } + if ((src_channels == 2) && (dst_channels == 6)) { + cvt->filters[cvt->filter_index++] = SDL_ConvertSurround; + src_channels = 6; + cvt->len_mult *= 3; + cvt->len_ratio *= 3; + } + if ((src_channels == 2) && (dst_channels == 4)) { + cvt->filters[cvt->filter_index++] = SDL_ConvertSurround_4; + src_channels = 4; + cvt->len_mult *= 2; + cvt->len_ratio *= 2; + } + while ((src_channels * 2) <= dst_channels) { + cvt->filters[cvt->filter_index++] = SDL_ConvertStereo; + cvt->len_mult *= 2; + src_channels *= 2; + cvt->len_ratio *= 2; + } + if ((src_channels == 6) && (dst_channels <= 2)) { + cvt->filters[cvt->filter_index++] = SDL_ConvertStrip; + src_channels = 2; + cvt->len_ratio /= 3; + } + if ((src_channels == 6) && (dst_channels == 4)) { + cvt->filters[cvt->filter_index++] = SDL_ConvertStrip_2; + src_channels = 4; + cvt->len_ratio /= 2; + } + /* This assumes that 4 channel audio is in the format: + Left {front/back} + Right {front/back} + so converting to L/R stereo works properly. + */ + while (((src_channels % 2) == 0) && + ((src_channels / 2) >= dst_channels)) { + cvt->filters[cvt->filter_index++] = SDL_ConvertMono; + src_channels /= 2; + cvt->len_ratio /= 2; + } + if (src_channels != dst_channels) { + /* Uh oh.. */ ; + } + } + + /* Do rate conversion */ + cvt->rate_incr = 0.0; + if ((src_rate / 100) != (dst_rate / 100)) { + Uint32 hi_rate, lo_rate; + int len_mult; + double len_ratio; + void (SDLCALL * rate_cvt) (SDL_AudioCVT * cvt, Uint16 format); + + if (src_rate > dst_rate) { + hi_rate = src_rate; + lo_rate = dst_rate; + switch (src_channels) { + case 1: + rate_cvt = SDL_RateDIV2; + break; + case 2: + rate_cvt = SDL_RateDIV2_c2; + break; + case 4: + rate_cvt = SDL_RateDIV2_c4; + break; + case 6: + rate_cvt = SDL_RateDIV2_c6; + break; + default: + return -1; + } + len_mult = 1; + len_ratio = 0.5; + } else { + hi_rate = dst_rate; + lo_rate = src_rate; + switch (src_channels) { + case 1: + rate_cvt = SDL_RateMUL2; + break; + case 2: + rate_cvt = SDL_RateMUL2_c2; + break; + case 4: + rate_cvt = SDL_RateMUL2_c4; + break; + case 6: + rate_cvt = SDL_RateMUL2_c6; + break; + default: + return -1; + } + len_mult = 2; + len_ratio = 2.0; + } + /* If hi_rate = lo_rate*2^x then conversion is easy */ + while (((lo_rate * 2) / 100) <= (hi_rate / 100)) { + cvt->filters[cvt->filter_index++] = rate_cvt; + cvt->len_mult *= len_mult; + lo_rate *= 2; + cvt->len_ratio *= len_ratio; + } + /* We may need a slow conversion here to finish up */ + if ((lo_rate / 100) != (hi_rate / 100)) { #if 1 - /* The problem with this is that if the input buffer is - say 1K, and the conversion rate is say 1.1, then the - output buffer is 1.1K, which may not be an acceptable - buffer size for the audio driver (not a power of 2) - */ - /* For now, punt and hope the rate distortion isn't great. - */ + /* The problem with this is that if the input buffer is + say 1K, and the conversion rate is say 1.1, then the + output buffer is 1.1K, which may not be an acceptable + buffer size for the audio driver (not a power of 2) + */ + /* For now, punt and hope the rate distortion isn't great. + */ #else - if ( src_rate < dst_rate ) { - cvt->rate_incr = (double)lo_rate/hi_rate; - cvt->len_mult *= 2; - cvt->len_ratio /= cvt->rate_incr; - } else { - cvt->rate_incr = (double)hi_rate/lo_rate; - cvt->len_ratio *= cvt->rate_incr; - } - cvt->filters[cvt->filter_index++] = SDL_RateSLOW; + if (src_rate < dst_rate) { + cvt->rate_incr = (double) lo_rate / hi_rate; + cvt->len_mult *= 2; + cvt->len_ratio /= cvt->rate_incr; + } else { + cvt->rate_incr = (double) hi_rate / lo_rate; + cvt->len_ratio *= cvt->rate_incr; + } + cvt->filters[cvt->filter_index++] = SDL_RateSLOW; #endif - } - } - - /* Set up the filter information */ - if ( cvt->filter_index != 0 ) { - cvt->needed = 1; - cvt->src_format = src_format; - cvt->dst_format = dst_format; - cvt->len = 0; - cvt->buf = NULL; - cvt->filters[cvt->filter_index] = NULL; - } - return(cvt->needed); + } + } + + /* Set up the filter information */ + if (cvt->filter_index != 0) { + cvt->needed = 1; + cvt->src_format = src_format; + cvt->dst_format = dst_format; + cvt->len = 0; + cvt->buf = NULL; + cvt->filters[cvt->filter_index] = NULL; + } + return (cvt->needed); } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/audio/SDL_audiodev.c b/src/audio/SDL_audiodev.c index 90671f971..4db9ff47e 100644 --- a/src/audio/SDL_audiodev.c +++ b/src/audio/SDL_audiodev.c @@ -47,53 +47,56 @@ #endif -int SDL_OpenAudioPath(char *path, int maxlen, int flags, int classic) +int +SDL_OpenAudioPath(char *path, int maxlen, int flags, int classic) { - const char *audiodev; - int audio_fd; - char audiopath[1024]; - - /* Figure out what our audio device is */ - if ( ((audiodev=SDL_getenv("SDL_PATH_DSP")) == NULL) && - ((audiodev=SDL_getenv("AUDIODEV")) == NULL) ) { - if ( classic ) { - audiodev = _PATH_DEV_AUDIO; - } else { - struct stat sb; - - /* Added support for /dev/sound/\* in Linux 2.4 */ - if ( ((stat("/dev/sound", &sb) == 0) && S_ISDIR(sb.st_mode)) && - ((stat(_PATH_DEV_DSP24, &sb) == 0) && S_ISCHR(sb.st_mode)) ) { - audiodev = _PATH_DEV_DSP24; - } else { - audiodev = _PATH_DEV_DSP; - } - } - } - audio_fd = open(audiodev, flags, 0); - - /* If the first open fails, look for other devices */ - if ( (audio_fd < 0) && (SDL_strlen(audiodev) < (sizeof(audiopath)-3)) ) { - int exists, instance; - struct stat sb; - - instance = 1; - do { /* Don't use errno ENOENT - it may not be thread-safe */ - SDL_snprintf(audiopath, SDL_arraysize(audiopath), - "%s%d", audiodev, instance++); - exists = 0; - if ( stat(audiopath, &sb) == 0 ) { - exists = 1; - audio_fd = open(audiopath, flags, 0); - } - } while ( exists && (audio_fd < 0) ); - audiodev = audiopath; - } - if ( path != NULL ) { - SDL_strlcpy(path, audiodev, maxlen); - path[maxlen-1] = '\0'; - } - return(audio_fd); + const char *audiodev; + int audio_fd; + char audiopath[1024]; + + /* Figure out what our audio device is */ + if (((audiodev = SDL_getenv("SDL_PATH_DSP")) == NULL) && + ((audiodev = SDL_getenv("AUDIODEV")) == NULL)) { + if (classic) { + audiodev = _PATH_DEV_AUDIO; + } else { + struct stat sb; + + /* Added support for /dev/sound/\* in Linux 2.4 */ + if (((stat("/dev/sound", &sb) == 0) && S_ISDIR(sb.st_mode)) + && ((stat(_PATH_DEV_DSP24, &sb) == 0) + && S_ISCHR(sb.st_mode))) { + audiodev = _PATH_DEV_DSP24; + } else { + audiodev = _PATH_DEV_DSP; + } + } + } + audio_fd = open(audiodev, flags, 0); + + /* If the first open fails, look for other devices */ + if ((audio_fd < 0) && (SDL_strlen(audiodev) < (sizeof(audiopath) - 3))) { + int exists, instance; + struct stat sb; + + instance = 1; + do { /* Don't use errno ENOENT - it may not be thread-safe */ + SDL_snprintf(audiopath, SDL_arraysize(audiopath), + "%s%d", audiodev, instance++); + exists = 0; + if (stat(audiopath, &sb) == 0) { + exists = 1; + audio_fd = open(audiopath, flags, 0); + } + } + while (exists && (audio_fd < 0)); + audiodev = audiopath; + } + if (path != NULL) { + SDL_strlcpy(path, audiodev, maxlen); + path[maxlen - 1] = '\0'; + } + return (audio_fd); } #elif SDL_AUDIO_DRIVER_PAUD @@ -110,70 +113,71 @@ int SDL_OpenAudioPath(char *path, int maxlen, int flags, int classic) #define _PATH_DEV_DSP "/dev/%caud%c/%c" #endif -char devsettings[][3] = -{ - { 'p', '0', '1' }, { 'p', '0', '2' }, { 'p', '0', '3' }, { 'p', '0', '4' }, - { 'p', '1', '1' }, { 'p', '1', '2' }, { 'p', '1', '3' }, { 'p', '1', '4' }, - { 'p', '2', '1' }, { 'p', '2', '2' }, { 'p', '2', '3' }, { 'p', '2', '4' }, - { 'p', '3', '1' }, { 'p', '3', '2' }, { 'p', '3', '3' }, { 'p', '3', '4' }, - { 'b', '0', '1' }, { 'b', '0', '2' }, { 'b', '0', '3' }, { 'b', '0', '4' }, - { 'b', '1', '1' }, { 'b', '1', '2' }, { 'b', '1', '3' }, { 'b', '1', '4' }, - { 'b', '2', '1' }, { 'b', '2', '2' }, { 'b', '2', '3' }, { 'b', '2', '4' }, - { 'b', '3', '1' }, { 'b', '3', '2' }, { 'b', '3', '3' }, { 'b', '3', '4' }, - { '\0', '\0', '\0' } +char devsettings[][3] = { + {'p', '0', '1'}, {'p', '0', '2'}, {'p', '0', '3'}, {'p', '0', '4'}, + {'p', '1', '1'}, {'p', '1', '2'}, {'p', '1', '3'}, {'p', '1', '4'}, + {'p', '2', '1'}, {'p', '2', '2'}, {'p', '2', '3'}, {'p', '2', '4'}, + {'p', '3', '1'}, {'p', '3', '2'}, {'p', '3', '3'}, {'p', '3', '4'}, + {'b', '0', '1'}, {'b', '0', '2'}, {'b', '0', '3'}, {'b', '0', '4'}, + {'b', '1', '1'}, {'b', '1', '2'}, {'b', '1', '3'}, {'b', '1', '4'}, + {'b', '2', '1'}, {'b', '2', '2'}, {'b', '2', '3'}, {'b', '2', '4'}, + {'b', '3', '1'}, {'b', '3', '2'}, {'b', '3', '3'}, {'b', '3', '4'}, + {'\0', '\0', '\0'} }; -static int OpenUserDefinedDevice(char *path, int maxlen, int flags) +static int +OpenUserDefinedDevice(char *path, int maxlen, int flags) { - const char *audiodev; - int audio_fd; - - /* Figure out what our audio device is */ - if ((audiodev=SDL_getenv("SDL_PATH_DSP")) == NULL) { - audiodev=SDL_getenv("AUDIODEV"); - } - if ( audiodev == NULL ) { - return -1; - } - audio_fd = open(audiodev, flags, 0); - if ( path != NULL ) { - SDL_strlcpy(path, audiodev, maxlen); - path[maxlen-1] = '\0'; - } - return audio_fd; + const char *audiodev; + int audio_fd; + + /* Figure out what our audio device is */ + if ((audiodev = SDL_getenv("SDL_PATH_DSP")) == NULL) { + audiodev = SDL_getenv("AUDIODEV"); + } + if (audiodev == NULL) { + return -1; + } + audio_fd = open(audiodev, flags, 0); + if (path != NULL) { + SDL_strlcpy(path, audiodev, maxlen); + path[maxlen - 1] = '\0'; + } + return audio_fd; } -int SDL_OpenAudioPath(char *path, int maxlen, int flags, int classic) +int +SDL_OpenAudioPath(char *path, int maxlen, int flags, int classic) { struct stat sb; - int audio_fd; - char audiopath[1024]; - int cycle; + int audio_fd; + char audiopath[1024]; + int cycle; - audio_fd = OpenUserDefinedDevice(path,maxlen,flags); - if ( audio_fd != -1 ) { + audio_fd = OpenUserDefinedDevice(path, maxlen, flags); + if (audio_fd != -1) { return audio_fd; } - cycle = 0; - while( devsettings[cycle][0] != '\0' ) { - SDL_snprintf( audiopath, SDL_arraysize(audiopath), - _PATH_DEV_DSP, - devsettings[cycle][0], - devsettings[cycle][1], - devsettings[cycle][2]); - - if ( stat(audiopath, &sb) == 0 ) { - audio_fd = open(audiopath, flags, 0); - if ( audio_fd > 0 ) { - if ( path != NULL ) { - SDL_strlcpy( path, audiopath, maxlen ); - } - return audio_fd; - } - } + cycle = 0; + while (devsettings[cycle][0] != '\0') { + SDL_snprintf(audiopath, SDL_arraysize(audiopath), + _PATH_DEV_DSP, + devsettings[cycle][0], + devsettings[cycle][1], devsettings[cycle][2]); + + if (stat(audiopath, &sb) == 0) { + audio_fd = open(audiopath, flags, 0); + if (audio_fd > 0) { + if (path != NULL) { + SDL_strlcpy(path, audiopath, maxlen); + } + return audio_fd; + } + } } return -1; } #endif /* Audio driver selection */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/audio/SDL_audiodev_c.h b/src/audio/SDL_audiodev_c.h index 055fd6541..8e4809408 100644 --- a/src/audio/SDL_audiodev_c.h +++ b/src/audio/SDL_audiodev_c.h @@ -23,4 +23,4 @@ /* Open the audio device, storing the pathname in 'path' */ extern int SDL_OpenAudioPath(char *path, int maxlen, int flags, int classic); - +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/audio/SDL_audiomem.h b/src/audio/SDL_audiomem.h index 3d759eb3f..b611de884 100644 --- a/src/audio/SDL_audiomem.h +++ b/src/audio/SDL_audiomem.h @@ -23,3 +23,4 @@ #define SDL_AllocAudioMem SDL_malloc #define SDL_FreeAudioMem SDL_free +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/audio/SDL_mixer.c b/src/audio/SDL_mixer.c index 5e07a0720..a8dec88ff 100644 --- a/src/audio/SDL_mixer.c +++ b/src/audio/SDL_mixer.c @@ -35,224 +35,227 @@ * the value to avoid overflow. (used with permission from ARDI) * Changed to use 0xFE instead of 0xFF for better sound quality. */ -static const Uint8 mix8[] = -{ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03, - 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, - 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, - 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, - 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, - 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, - 0x3B, 0x3C, 0x3D, 0x3E, 0x3F, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, - 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, 0x50, - 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x5B, - 0x5C, 0x5D, 0x5E, 0x5F, 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, - 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F, 0x70, 0x71, - 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0x7B, 0x7C, - 0x7D, 0x7E, 0x7F, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, - 0x88, 0x89, 0x8A, 0x8B, 0x8C, 0x8D, 0x8E, 0x8F, 0x90, 0x91, 0x92, - 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9A, 0x9B, 0x9C, 0x9D, - 0x9E, 0x9F, 0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7, 0xA8, - 0xA9, 0xAA, 0xAB, 0xAC, 0xAD, 0xAE, 0xAF, 0xB0, 0xB1, 0xB2, 0xB3, - 0xB4, 0xB5, 0xB6, 0xB7, 0xB8, 0xB9, 0xBA, 0xBB, 0xBC, 0xBD, 0xBE, - 0xBF, 0xC0, 0xC1, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, - 0xCA, 0xCB, 0xCC, 0xCD, 0xCE, 0xCF, 0xD0, 0xD1, 0xD2, 0xD3, 0xD4, - 0xD5, 0xD6, 0xD7, 0xD8, 0xD9, 0xDA, 0xDB, 0xDC, 0xDD, 0xDE, 0xDF, - 0xE0, 0xE1, 0xE2, 0xE3, 0xE4, 0xE5, 0xE6, 0xE7, 0xE8, 0xE9, 0xEA, - 0xEB, 0xEC, 0xED, 0xEE, 0xEF, 0xF0, 0xF1, 0xF2, 0xF3, 0xF4, 0xF5, - 0xF6, 0xF7, 0xF8, 0xF9, 0xFA, 0xFB, 0xFC, 0xFD, 0xFE, 0xFE, 0xFE, - 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, - 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, - 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, - 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, - 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, - 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, - 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, - 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, - 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, - 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, - 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, - 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE +static const Uint8 mix8[] = { + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03, + 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, + 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, + 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, + 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, + 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, + 0x3B, 0x3C, 0x3D, 0x3E, 0x3F, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, + 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, 0x50, + 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x5B, + 0x5C, 0x5D, 0x5E, 0x5F, 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, + 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F, 0x70, 0x71, + 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0x7B, 0x7C, + 0x7D, 0x7E, 0x7F, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, + 0x88, 0x89, 0x8A, 0x8B, 0x8C, 0x8D, 0x8E, 0x8F, 0x90, 0x91, 0x92, + 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9A, 0x9B, 0x9C, 0x9D, + 0x9E, 0x9F, 0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7, 0xA8, + 0xA9, 0xAA, 0xAB, 0xAC, 0xAD, 0xAE, 0xAF, 0xB0, 0xB1, 0xB2, 0xB3, + 0xB4, 0xB5, 0xB6, 0xB7, 0xB8, 0xB9, 0xBA, 0xBB, 0xBC, 0xBD, 0xBE, + 0xBF, 0xC0, 0xC1, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, + 0xCA, 0xCB, 0xCC, 0xCD, 0xCE, 0xCF, 0xD0, 0xD1, 0xD2, 0xD3, 0xD4, + 0xD5, 0xD6, 0xD7, 0xD8, 0xD9, 0xDA, 0xDB, 0xDC, 0xDD, 0xDE, 0xDF, + 0xE0, 0xE1, 0xE2, 0xE3, 0xE4, 0xE5, 0xE6, 0xE7, 0xE8, 0xE9, 0xEA, + 0xEB, 0xEC, 0xED, 0xEE, 0xEF, 0xF0, 0xF1, 0xF2, 0xF3, 0xF4, 0xF5, + 0xF6, 0xF7, 0xF8, 0xF9, 0xFA, 0xFB, 0xFC, 0xFD, 0xFE, 0xFE, 0xFE, + 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, + 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, + 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, + 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, + 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, + 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, + 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, + 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, + 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, + 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, + 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, + 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE }; /* The volume ranges from 0 - 128 */ #define ADJUST_VOLUME(s, v) (s = (s*v)/SDL_MIX_MAXVOLUME) #define ADJUST_VOLUME_U8(s, v) (s = (((s-128)*v)/SDL_MIX_MAXVOLUME)+128) -void SDL_MixAudio (Uint8 *dst, const Uint8 *src, Uint32 len, int volume) +void +SDL_MixAudio(Uint8 * dst, const Uint8 * src, Uint32 len, int volume) { - Uint16 format; + Uint16 format; - if ( volume == 0 ) { - return; - } - /* Mix the user-level audio format */ - if ( current_audio ) { - if ( current_audio->convert.needed ) { - format = current_audio->convert.src_format; - } else { - format = current_audio->spec.format; - } - } else { - /* HACK HACK HACK */ - format = AUDIO_S16; - } - switch (format) { + if (volume == 0) { + return; + } + /* Mix the user-level audio format */ + if (current_audio) { + if (current_audio->convert.needed) { + format = current_audio->convert.src_format; + } else { + format = current_audio->spec.format; + } + } else { + /* HACK HACK HACK */ + format = AUDIO_S16; + } + switch (format) { - case AUDIO_U8: { + case AUDIO_U8: + { #if defined(__GNUC__) && defined(__M68000__) && defined(SDL_ASSEMBLY_ROUTINES) - SDL_MixAudio_m68k_U8((char*)dst,(char*)src,(unsigned long)len,(long)volume,(char *)mix8); + SDL_MixAudio_m68k_U8((char *) dst, (char *) src, + (unsigned long) len, (long) volume, + (char *) mix8); #else - Uint8 src_sample; + Uint8 src_sample; - while ( len-- ) { - src_sample = *src; - ADJUST_VOLUME_U8(src_sample, volume); - *dst = mix8[*dst+src_sample]; - ++dst; - ++src; - } + while (len--) { + src_sample = *src; + ADJUST_VOLUME_U8(src_sample, volume); + *dst = mix8[*dst + src_sample]; + ++dst; + ++src; + } #endif - } - break; + } + break; - case AUDIO_S8: { + case AUDIO_S8: + { #if defined(__GNUC__) && defined(__i386__) && defined(SDL_ASSEMBLY_ROUTINES) - if (SDL_HasMMX()) - { - SDL_MixAudio_MMX_S8((char*)dst,(char*)src,(unsigned int)len,(int)volume); - } - else + if (SDL_HasMMX()) { + SDL_MixAudio_MMX_S8((char *) dst, (char *) src, + (unsigned int) len, (int) volume); + } else #elif ((defined(_MSC_VER) && defined(_M_IX86)) || defined(__WATCOMC__)) && defined(SDL_ASSEMBLY_ROUTINES) - if (SDL_HasMMX()) - { - SDL_MixAudio_MMX_S8_VC((char*)dst,(char*)src,(unsigned int)len,(int)volume); - } - else + if (SDL_HasMMX()) { + SDL_MixAudio_MMX_S8_VC((char *) dst, (char *) src, + (unsigned int) len, (int) volume); + } else #endif #if defined(__GNUC__) && defined(__M68000__) && defined(SDL_ASSEMBLY_ROUTINES) - SDL_MixAudio_m68k_S8((char*)dst,(char*)src,(unsigned long)len,(long)volume); + SDL_MixAudio_m68k_S8((char *) dst, (char *) src, + (unsigned long) len, (long) volume); #else - { - Sint8 *dst8, *src8; - Sint8 src_sample; - int dst_sample; - const int max_audioval = ((1<<(8-1))-1); - const int min_audioval = -(1<<(8-1)); + { + Sint8 *dst8, *src8; + Sint8 src_sample; + int dst_sample; + const int max_audioval = ((1 << (8 - 1)) - 1); + const int min_audioval = -(1 << (8 - 1)); - src8 = (Sint8 *)src; - dst8 = (Sint8 *)dst; - while ( len-- ) { - src_sample = *src8; - ADJUST_VOLUME(src_sample, volume); - dst_sample = *dst8 + src_sample; - if ( dst_sample > max_audioval ) { - *dst8 = max_audioval; - } else - if ( dst_sample < min_audioval ) { - *dst8 = min_audioval; - } else { - *dst8 = dst_sample; - } - ++dst8; - ++src8; - } - } + src8 = (Sint8 *) src; + dst8 = (Sint8 *) dst; + while (len--) { + src_sample = *src8; + ADJUST_VOLUME(src_sample, volume); + dst_sample = *dst8 + src_sample; + if (dst_sample > max_audioval) { + *dst8 = max_audioval; + } else if (dst_sample < min_audioval) { + *dst8 = min_audioval; + } else { + *dst8 = dst_sample; + } + ++dst8; + ++src8; + } + } #endif - } - break; + } + break; - case AUDIO_S16LSB: { + case AUDIO_S16LSB: + { #if defined(__GNUC__) && defined(__i386__) && defined(SDL_ASSEMBLY_ROUTINES) - if (SDL_HasMMX()) - { - SDL_MixAudio_MMX_S16((char*)dst,(char*)src,(unsigned int)len,(int)volume); - } - else + if (SDL_HasMMX()) { + SDL_MixAudio_MMX_S16((char *) dst, (char *) src, + (unsigned int) len, (int) volume); + } else #elif ((defined(_MSC_VER) && defined(_M_IX86)) || defined(__WATCOMC__)) && defined(SDL_ASSEMBLY_ROUTINES) - if (SDL_HasMMX()) - { - SDL_MixAudio_MMX_S16_VC((char*)dst,(char*)src,(unsigned int)len,(int)volume); - } - else + if (SDL_HasMMX()) { + SDL_MixAudio_MMX_S16_VC((char *) dst, (char *) src, + (unsigned int) len, (int) volume); + } else #endif #if defined(__GNUC__) && defined(__M68000__) && defined(SDL_ASSEMBLY_ROUTINES) - SDL_MixAudio_m68k_S16LSB((short*)dst,(short*)src,(unsigned long)len,(long)volume); + SDL_MixAudio_m68k_S16LSB((short *) dst, (short *) src, + (unsigned long) len, (long) volume); #else - { - Sint16 src1, src2; - int dst_sample; - const int max_audioval = ((1<<(16-1))-1); - const int min_audioval = -(1<<(16-1)); + { + Sint16 src1, src2; + int dst_sample; + const int max_audioval = ((1 << (16 - 1)) - 1); + const int min_audioval = -(1 << (16 - 1)); - len /= 2; - while ( len-- ) { - src1 = ((src[1])<<8|src[0]); - ADJUST_VOLUME(src1, volume); - src2 = ((dst[1])<<8|dst[0]); - src += 2; - dst_sample = src1+src2; - if ( dst_sample > max_audioval ) { - dst_sample = max_audioval; - } else - if ( dst_sample < min_audioval ) { - dst_sample = min_audioval; - } - dst[0] = dst_sample&0xFF; - dst_sample >>= 8; - dst[1] = dst_sample&0xFF; - dst += 2; - } - } + len /= 2; + while (len--) { + src1 = ((src[1]) << 8 | src[0]); + ADJUST_VOLUME(src1, volume); + src2 = ((dst[1]) << 8 | dst[0]); + src += 2; + dst_sample = src1 + src2; + if (dst_sample > max_audioval) { + dst_sample = max_audioval; + } else if (dst_sample < min_audioval) { + dst_sample = min_audioval; + } + dst[0] = dst_sample & 0xFF; + dst_sample >>= 8; + dst[1] = dst_sample & 0xFF; + dst += 2; + } + } #endif - } - break; + } + break; - case AUDIO_S16MSB: { + case AUDIO_S16MSB: + { #if defined(__GNUC__) && defined(__M68000__) && defined(SDL_ASSEMBLY_ROUTINES) - SDL_MixAudio_m68k_S16MSB((short*)dst,(short*)src,(unsigned long)len,(long)volume); + SDL_MixAudio_m68k_S16MSB((short *) dst, (short *) src, + (unsigned long) len, (long) volume); #else - Sint16 src1, src2; - int dst_sample; - const int max_audioval = ((1<<(16-1))-1); - const int min_audioval = -(1<<(16-1)); + Sint16 src1, src2; + int dst_sample; + const int max_audioval = ((1 << (16 - 1)) - 1); + const int min_audioval = -(1 << (16 - 1)); - len /= 2; - while ( len-- ) { - src1 = ((src[0])<<8|src[1]); - ADJUST_VOLUME(src1, volume); - src2 = ((dst[0])<<8|dst[1]); - src += 2; - dst_sample = src1+src2; - if ( dst_sample > max_audioval ) { - dst_sample = max_audioval; - } else - if ( dst_sample < min_audioval ) { - dst_sample = min_audioval; - } - dst[1] = dst_sample&0xFF; - dst_sample >>= 8; - dst[0] = dst_sample&0xFF; - dst += 2; - } + len /= 2; + while (len--) { + src1 = ((src[0]) << 8 | src[1]); + ADJUST_VOLUME(src1, volume); + src2 = ((dst[0]) << 8 | dst[1]); + src += 2; + dst_sample = src1 + src2; + if (dst_sample > max_audioval) { + dst_sample = max_audioval; + } else if (dst_sample < min_audioval) { + dst_sample = min_audioval; + } + dst[1] = dst_sample & 0xFF; + dst_sample >>= 8; + dst[0] = dst_sample & 0xFF; + dst += 2; + } #endif - } - break; + } + break; - default: /* If this happens... FIXME! */ - SDL_SetError("SDL_MixAudio(): unknown audio format"); - return; - } + default: /* If this happens... FIXME! */ + SDL_SetError("SDL_MixAudio(): unknown audio format"); + return; + } } +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/audio/SDL_mixer_MMX.c b/src/audio/SDL_mixer_MMX.c index 9d24ba054..b20adad58 100644 --- a/src/audio/SDL_mixer_MMX.c +++ b/src/audio/SDL_mixer_MMX.c @@ -36,100 +36,50 @@ ***********************************************/ #if defined(__GNUC__) && defined(__i386__) && defined(SDL_ASSEMBLY_ROUTINES) -void SDL_MixAudio_MMX_S16(char* dst,char* src,unsigned int size,int volume) +void +SDL_MixAudio_MMX_S16(char *dst, char *src, unsigned int size, int volume) { - __asm__ __volatile__ ( - -" movl %3,%%eax\n" /* eax = volume */ - -" movl %2,%%edx\n" /* edx = size */ - -" shrl $4,%%edx\n" /* process 16 bytes per iteration = 8 samples */ - -" jz .endS16\n" - -" pxor %%mm0,%%mm0\n" - -" movd %%eax,%%mm0\n" -" movq %%mm0,%%mm1\n" -" psllq $16,%%mm0\n" -" por %%mm1,%%mm0\n" -" psllq $16,%%mm0\n" -" por %%mm1,%%mm0\n" -" psllq $16,%%mm0\n" -" por %%mm1,%%mm0\n" /* mm0 = vol|vol|vol|vol */ - -".align 8\n" -" .mixloopS16:\n" - -" movq (%1),%%mm1\n" /* mm1 = a|b|c|d */ - -" movq %%mm1,%%mm2\n" /* mm2 = a|b|c|d */ - -" movq 8(%1),%%mm4\n" /* mm4 = e|f|g|h */ - - /* pré charger le buffer dst dans mm7 */ -" movq (%0),%%mm7\n" /* mm7 = dst[0] */ - - /* multiplier par le volume */ -" pmullw %%mm0,%%mm1\n" /* mm1 = l(a*v)|l(b*v)|l(c*v)|l(d*v) */ - -" pmulhw %%mm0,%%mm2\n" /* mm2 = h(a*v)|h(b*v)|h(c*v)|h(d*v) */ -" movq %%mm4,%%mm5\n" /* mm5 = e|f|g|h */ - -" pmullw %%mm0,%%mm4\n" /* mm4 = l(e*v)|l(f*v)|l(g*v)|l(h*v) */ - -" pmulhw %%mm0,%%mm5\n" /* mm5 = h(e*v)|h(f*v)|h(g*v)|h(h*v) */ -" movq %%mm1,%%mm3\n" /* mm3 = l(a*v)|l(b*v)|l(c*v)|l(d*v) */ - -" punpckhwd %%mm2,%%mm1\n" /* mm1 = a*v|b*v */ - -" movq %%mm4,%%mm6\n" /* mm6 = l(e*v)|l(f*v)|l(g*v)|l(h*v) */ -" punpcklwd %%mm2,%%mm3\n" /* mm3 = c*v|d*v */ - -" punpckhwd %%mm5,%%mm4\n" /* mm4 = e*f|f*v */ - -" punpcklwd %%mm5,%%mm6\n" /* mm6 = g*v|h*v */ - - /* pré charger le buffer dst dans mm5 */ -" movq 8(%0),%%mm5\n" /* mm5 = dst[1] */ - - /* diviser par 128 */ -" psrad $7,%%mm1\n" /* mm1 = a*v/128|b*v/128 , 128 = SDL_MIX_MAXVOLUME */ -" add $16,%1\n" - -" psrad $7,%%mm3\n" /* mm3 = c*v/128|d*v/128 */ - -" psrad $7,%%mm4\n" /* mm4 = e*v/128|f*v/128 */ - - /* mm1 = le sample avec le volume modifié */ -" packssdw %%mm1,%%mm3\n" /* mm3 = s(a*v|b*v|c*v|d*v) */ - -" psrad $7,%%mm6\n" /* mm6= g*v/128|h*v/128 */ -" paddsw %%mm7,%%mm3\n" /* mm3 = adjust_volume(src)+dst */ - - /* mm4 = le sample avec le volume modifié */ -" packssdw %%mm4,%%mm6\n" /* mm6 = s(e*v|f*v|g*v|h*v) */ -" movq %%mm3,(%0)\n" - -" paddsw %%mm5,%%mm6\n" /* mm6 = adjust_volume(src)+dst */ - -" movq %%mm6,8(%0)\n" - -" add $16,%0\n" - -" dec %%edx\n" - -" jnz .mixloopS16\n" - -" emms\n" - -".endS16:\n" - : - : "r" (dst), "r"(src),"m"(size), - "m"(volume) - : "eax","edx","memory" - ); + __asm__ __volatile__(" movl %3,%%eax\n" /* eax = volume */ + " movl %2,%%edx\n" /* edx = size */ + " shrl $4,%%edx\n" /* process 16 bytes per iteration = 8 samples */ + " jz .endS16\n" " pxor %%mm0,%%mm0\n" " movd %%eax,%%mm0\n" " movq %%mm0,%%mm1\n" " psllq $16,%%mm0\n" " por %%mm1,%%mm0\n" " psllq $16,%%mm0\n" " por %%mm1,%%mm0\n" " psllq $16,%%mm0\n" " por %%mm1,%%mm0\n" /* mm0 = vol|vol|vol|vol */ + ".align 8\n" " .mixloopS16:\n" " movq (%1),%%mm1\n" /* mm1 = a|b|c|d */ + " movq %%mm1,%%mm2\n" /* mm2 = a|b|c|d */ + " movq 8(%1),%%mm4\n" /* mm4 = e|f|g|h */ + /* pré charger le buffer dst dans mm7 */ + " movq (%0),%%mm7\n" /* mm7 = dst[0] */ + /* multiplier par le volume */ + " pmullw %%mm0,%%mm1\n" /* mm1 = l(a*v)|l(b*v)|l(c*v)|l(d*v) */ + " pmulhw %%mm0,%%mm2\n" /* mm2 = h(a*v)|h(b*v)|h(c*v)|h(d*v) */ + " movq %%mm4,%%mm5\n" /* mm5 = e|f|g|h */ + " pmullw %%mm0,%%mm4\n" /* mm4 = l(e*v)|l(f*v)|l(g*v)|l(h*v) */ + " pmulhw %%mm0,%%mm5\n" /* mm5 = h(e*v)|h(f*v)|h(g*v)|h(h*v) */ + " movq %%mm1,%%mm3\n" /* mm3 = l(a*v)|l(b*v)|l(c*v)|l(d*v) */ + " punpckhwd %%mm2,%%mm1\n" /* mm1 = a*v|b*v */ + " movq %%mm4,%%mm6\n" /* mm6 = l(e*v)|l(f*v)|l(g*v)|l(h*v) */ + " punpcklwd %%mm2,%%mm3\n" /* mm3 = c*v|d*v */ + " punpckhwd %%mm5,%%mm4\n" /* mm4 = e*f|f*v */ + " punpcklwd %%mm5,%%mm6\n" /* mm6 = g*v|h*v */ + /* pré charger le buffer dst dans mm5 */ + " movq 8(%0),%%mm5\n" /* mm5 = dst[1] */ + /* diviser par 128 */ + " psrad $7,%%mm1\n" /* mm1 = a*v/128|b*v/128 , 128 = SDL_MIX_MAXVOLUME */ + " add $16,%1\n" " psrad $7,%%mm3\n" /* mm3 = c*v/128|d*v/128 */ + " psrad $7,%%mm4\n" /* mm4 = e*v/128|f*v/128 */ + /* mm1 = le sample avec le volume modifié */ + " packssdw %%mm1,%%mm3\n" /* mm3 = s(a*v|b*v|c*v|d*v) */ + " psrad $7,%%mm6\n" /* mm6= g*v/128|h*v/128 */ + " paddsw %%mm7,%%mm3\n" /* mm3 = adjust_volume(src)+dst */ + /* mm4 = le sample avec le volume modifié */ + " packssdw %%mm4,%%mm6\n" /* mm6 = s(e*v|f*v|g*v|h*v) */ + " movq %%mm3,(%0)\n" " paddsw %%mm5,%%mm6\n" /* mm6 = adjust_volume(src)+dst */ + " movq %%mm6,8(%0)\n" + " add $16,%0\n" + " dec %%edx\n" + " jnz .mixloopS16\n" + " emms\n" + ".endS16:\n"::"r"(dst), "r"(src), + "m"(size), "m"(volume):"eax", "edx", "memory"); } @@ -138,69 +88,33 @@ void SDL_MixAudio_MMX_S16(char* dst,char* src,unsigned int size,int volume) /* Mixing for 8 bit signed buffers */ /*////////////////////////////////////////////// */ -void SDL_MixAudio_MMX_S8(char* dst,char* src,unsigned int size,int volume) +void +SDL_MixAudio_MMX_S8(char *dst, char *src, unsigned int size, int volume) { - __asm__ __volatile__ ( - -" movl %3,%%eax\n" /* eax = volume */ - -" movd %%eax,%%mm0\n" -" movq %%mm0,%%mm1\n" -" psllq $16,%%mm0\n" -" por %%mm1,%%mm0\n" -" psllq $16,%%mm0\n" -" por %%mm1,%%mm0\n" -" psllq $16,%%mm0\n" -" por %%mm1,%%mm0\n" - -" movl %2,%%edx\n" /* edx = size */ -" shr $3,%%edx\n" /* process 8 bytes per iteration = 8 samples */ - -" cmp $0,%%edx\n" -" je .endS8\n" - -".align 8\n" -" .mixloopS8:\n" - -" pxor %%mm2,%%mm2\n" /* mm2 = 0 */ -" movq (%1),%%mm1\n" /* mm1 = a|b|c|d|e|f|g|h */ - -" movq %%mm1,%%mm3\n" /* mm3 = a|b|c|d|e|f|g|h */ - - /* on va faire le "sign extension" en faisant un cmp avec 0 qui retourne 1 si <0, 0 si >0 */ -" pcmpgtb %%mm1,%%mm2\n" /* mm2 = 11111111|00000000|00000000.... */ - -" punpckhbw %%mm2,%%mm1\n" /* mm1 = 0|a|0|b|0|c|0|d */ - -" punpcklbw %%mm2,%%mm3\n" /* mm3 = 0|e|0|f|0|g|0|h */ -" movq (%0),%%mm2\n" /* mm2 = destination */ - -" pmullw %%mm0,%%mm1\n" /* mm1 = v*a|v*b|v*c|v*d */ -" add $8,%1\n" - -" pmullw %%mm0,%%mm3\n" /* mm3 = v*e|v*f|v*g|v*h */ -" psraw $7,%%mm1\n" /* mm1 = v*a/128|v*b/128|v*c/128|v*d/128 */ - -" psraw $7,%%mm3\n" /* mm3 = v*e/128|v*f/128|v*g/128|v*h/128 */ - -" packsswb %%mm1,%%mm3\n" /* mm1 = v*a/128|v*b/128|v*c/128|v*d/128|v*e/128|v*f/128|v*g/128|v*h/128 */ - -" paddsb %%mm2,%%mm3\n" /* add to destination buffer */ - -" movq %%mm3,(%0)\n" /* store back to ram */ -" add $8,%0\n" - -" dec %%edx\n" - -" jnz .mixloopS8\n" - -".endS8:\n" -" emms\n" - : - : "r" (dst), "r"(src),"m"(size), - "m"(volume) - : "eax","edx","memory" - ); + __asm__ __volatile__(" movl %3,%%eax\n" /* eax = volume */ + " movd %%eax,%%mm0\n" " movq %%mm0,%%mm1\n" " psllq $16,%%mm0\n" " por %%mm1,%%mm0\n" " psllq $16,%%mm0\n" " por %%mm1,%%mm0\n" " psllq $16,%%mm0\n" " por %%mm1,%%mm0\n" " movl %2,%%edx\n" /* edx = size */ + " shr $3,%%edx\n" /* process 8 bytes per iteration = 8 samples */ + " cmp $0,%%edx\n" " je .endS8\n" ".align 8\n" " .mixloopS8:\n" " pxor %%mm2,%%mm2\n" /* mm2 = 0 */ + " movq (%1),%%mm1\n" /* mm1 = a|b|c|d|e|f|g|h */ + " movq %%mm1,%%mm3\n" /* mm3 = a|b|c|d|e|f|g|h */ + /* on va faire le "sign extension" en faisant un cmp avec 0 qui retourne 1 si <0, 0 si >0 */ + " pcmpgtb %%mm1,%%mm2\n" /* mm2 = 11111111|00000000|00000000.... */ + " punpckhbw %%mm2,%%mm1\n" /* mm1 = 0|a|0|b|0|c|0|d */ + " punpcklbw %%mm2,%%mm3\n" /* mm3 = 0|e|0|f|0|g|0|h */ + " movq (%0),%%mm2\n" /* mm2 = destination */ + " pmullw %%mm0,%%mm1\n" /* mm1 = v*a|v*b|v*c|v*d */ + " add $8,%1\n" " pmullw %%mm0,%%mm3\n" /* mm3 = v*e|v*f|v*g|v*h */ + " psraw $7,%%mm1\n" /* mm1 = v*a/128|v*b/128|v*c/128|v*d/128 */ + " psraw $7,%%mm3\n" /* mm3 = v*e/128|v*f/128|v*g/128|v*h/128 */ + " packsswb %%mm1,%%mm3\n" /* mm1 = v*a/128|v*b/128|v*c/128|v*d/128|v*e/128|v*f/128|v*g/128|v*h/128 */ + " paddsb %%mm2,%%mm3\n" /* add to destination buffer */ + " movq %%mm3,(%0)\n" /* store back to ram */ + " add $8,%0\n" + " dec %%edx\n" + " jnz .mixloopS8\n" + ".endS8:\n" + " emms\n"::"r"(dst), "r"(src), "m"(size), + "m"(volume):"eax", "edx", "memory"); } #endif - +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/audio/SDL_mixer_MMX.h b/src/audio/SDL_mixer_MMX.h index 5a62683b2..7d9b27cf8 100644 --- a/src/audio/SDL_mixer_MMX.h +++ b/src/audio/SDL_mixer_MMX.h @@ -9,7 +9,7 @@ #include "SDL_config.h" #if defined(__GNUC__) && defined(__i386__) && defined(SDL_ASSEMBLY_ROUTINES) -void SDL_MixAudio_MMX_S16(char* ,char* ,unsigned int ,int ); -void SDL_MixAudio_MMX_S8(char* ,char* ,unsigned int ,int ); +void SDL_MixAudio_MMX_S16(char *, char *, unsigned int, int); +void SDL_MixAudio_MMX_S8(char *, char *, unsigned int, int); #endif - +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/audio/SDL_mixer_MMX_VC.c b/src/audio/SDL_mixer_MMX_VC.c index 89b646a05..cb7f3e39c 100644 --- a/src/audio/SDL_mixer_MMX_VC.c +++ b/src/audio/SDL_mixer_MMX_VC.c @@ -37,8 +37,10 @@ // Mixing for 16 bit signed buffers //////////////////////////////////////////////// -void SDL_MixAudio_MMX_S16_VC(char* dst,char* src,unsigned int nSize,int volume) +void +SDL_MixAudio_MMX_S16_VC(char *dst, char *src, unsigned int nSize, int volume) { + /* *INDENT-OFF* */ __asm { @@ -111,15 +113,17 @@ void SDL_MixAudio_MMX_S16_VC(char* dst,char* src,unsigned int nSize,int volume) pop esi pop edi } - + /* *INDENT-ON* */ } //////////////////////////////////////////////// // Mixing for 8 bit signed buffers //////////////////////////////////////////////// -void SDL_MixAudio_MMX_S8_VC(char* dst,char* src,unsigned int nSize,int volume) +void +SDL_MixAudio_MMX_S8_VC(char *dst, char *src, unsigned int nSize, int volume) { + /* *INDENT-OFF* */ _asm { @@ -176,6 +180,9 @@ void SDL_MixAudio_MMX_S8_VC(char* dst,char* src,unsigned int nSize,int volume) pop esi pop edi } + /* *INDENT-ON* */ } #endif /* SDL_ASSEMBLY_ROUTINES */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/audio/SDL_mixer_MMX_VC.h b/src/audio/SDL_mixer_MMX_VC.h index bfe02a988..4b673d593 100644 --- a/src/audio/SDL_mixer_MMX_VC.h +++ b/src/audio/SDL_mixer_MMX_VC.h @@ -31,6 +31,7 @@ Assumes buffer size in bytes is a multiple of 16 Assumes SDL_MIX_MAXVOLUME = 128 */ -void SDL_MixAudio_MMX_S16_VC(char* ,char* ,unsigned int ,int ); -void SDL_MixAudio_MMX_S8_VC(char* ,char* ,unsigned int ,int ); +void SDL_MixAudio_MMX_S16_VC(char *, char *, unsigned int, int); +void SDL_MixAudio_MMX_S8_VC(char *, char *, unsigned int, int); #endif +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/audio/SDL_mixer_m68k.c b/src/audio/SDL_mixer_m68k.c index f8786da24..35823b66d 100644 --- a/src/audio/SDL_mixer_m68k.c +++ b/src/audio/SDL_mixer_m68k.c @@ -28,184 +28,113 @@ */ #if defined(__M68000__) && defined(__GNUC__) -void SDL_MixAudio_m68k_U8(char* dst, char* src, long len, long volume, char* mix8) +void +SDL_MixAudio_m68k_U8(char *dst, char *src, long len, long volume, char *mix8) { - __asm__ __volatile__ ( - - "tstl %2\n" -" beqs stoploop_u8\n" -"mixloop_u8:\n" - - /* Mix a sample */ - -" moveq #0,%%d0\n" -" moveq #0,%%d1\n" - -" moveb %1@+,%%d0\n" /* d0 = *src++ */ -" sub #128,%%d0\n" /* d0 -= 128 */ -" muls %3,%%d0\n" /* d0 *= volume (0<=volume<=128) */ -" moveb %0@,%%d1\n" /* d1 = *dst */ -" asr #7,%%d0\n" /* d0 /= 128 (SDL_MIX_MAXVOLUME) */ -" add #128,%%d0\n" /* d0 += 128 */ - -" add %%d1,%%d0\n" - -" moveb %4@(%%d0:w),%0@+\n" - - /* Loop till done */ - -" subql #1,%2\n" -" bhis mixloop_u8\n" -"stoploop_u8:\n" - - : /* no return value */ - : /* input */ - "a"(dst), "a"(src), "d"(len), "d"(volume), "a"(mix8) - : /* clobbered registers */ - "d0", "d1", "cc", "memory" - ); + __asm__ __volatile__("tstl %2\n" " beqs stoploop_u8\n" "mixloop_u8:\n" + /* Mix a sample */ + " moveq #0,%%d0\n" " moveq #0,%%d1\n" " moveb %1@+,%%d0\n" /* d0 = *src++ */ + " sub #128,%%d0\n" /* d0 -= 128 */ + " muls %3,%%d0\n" /* d0 *= volume (0<=volume<=128) */ + " moveb %0@,%%d1\n" /* d1 = *dst */ + " asr #7,%%d0\n" /* d0 /= 128 (SDL_MIX_MAXVOLUME) */ + " add #128,%%d0\n" /* d0 += 128 */ + " add %%d1,%%d0\n" + " moveb %4@(%%d0:w),%0@+\n" + /* Loop till done */ + " subql #1,%2\n" " bhis mixloop_u8\n" "stoploop_u8:\n": /* no return value */ + : /* input */ + "a"(dst), "a"(src), "d"(len), "d"(volume), "a"(mix8): /* clobbered registers */ + "d0", "d1", "cc", "memory"); } -void SDL_MixAudio_m68k_S8(char* dst, char* src, long len, long volume) +void +SDL_MixAudio_m68k_S8(char *dst, char *src, long len, long volume) { - __asm__ __volatile__ ( - - "tstl %2\n" -" beqs stoploop_s8\n" -" moveq #-128,%%d2\n" -" moveq #127,%%d3\n" -"mixloop_s8:\n" - - /* Mix a sample */ - -" moveq #0,%%d0\n" -" moveq #0,%%d1\n" - -" moveb %1@+,%%d0\n" /* d0 = *src++ */ -" muls %3,%%d0\n" /* d0 *= volume (0<=volume<=128) */ -" moveb %0@,%%d1\n" /* d1 = *dst */ -" asr #7,%%d0\n" /* d0 /= 128 (SDL_MIX_MAXVOLUME) */ - -" add %%d1,%%d0\n" - -" cmp %%d2,%%d0\n" -" bges lower_limit_s8\n" -" move %%d2,%%d0\n" -"lower_limit_s8:\n" - -" cmp %%d3,%%d0\n" -" bles upper_limit_s8\n" -" move %%d3,%%d0\n" -"upper_limit_s8:\n" -" moveb %%d0,%0@+\n" - - /* Loop till done */ - -" subql #1,%2\n" -" bhis mixloop_s8\n" -"stoploop_s8:\n" - - : /* no return value */ - : /* input */ - "a"(dst), "a"(src), "d"(len), "d"(volume) - : /* clobbered registers */ - "d0", "d1", "d2", "d3", "cc", "memory" - ); + __asm__ __volatile__("tstl %2\n" + " beqs stoploop_s8\n" + " moveq #-128,%%d2\n" + " moveq #127,%%d3\n" "mixloop_s8:\n" + /* Mix a sample */ + " moveq #0,%%d0\n" " moveq #0,%%d1\n" " moveb %1@+,%%d0\n" /* d0 = *src++ */ + " muls %3,%%d0\n" /* d0 *= volume (0<=volume<=128) */ + " moveb %0@,%%d1\n" /* d1 = *dst */ + " asr #7,%%d0\n" /* d0 /= 128 (SDL_MIX_MAXVOLUME) */ + " add %%d1,%%d0\n" + " cmp %%d2,%%d0\n" + " bges lower_limit_s8\n" + " move %%d2,%%d0\n" + "lower_limit_s8:\n" + " cmp %%d3,%%d0\n" + " bles upper_limit_s8\n" + " move %%d3,%%d0\n" + "upper_limit_s8:\n" " moveb %%d0,%0@+\n" + /* Loop till done */ + " subql #1,%2\n" " bhis mixloop_s8\n" "stoploop_s8:\n": /* no return value */ + : /* input */ + "a"(dst), "a"(src), "d"(len), "d"(volume): /* clobbered registers */ + "d0", "d1", "d2", "d3", "cc", "memory"); } -void SDL_MixAudio_m68k_S16MSB(short* dst, short* src, long len, long volume) +void +SDL_MixAudio_m68k_S16MSB(short *dst, short *src, long len, long volume) { - __asm__ __volatile__ ( - - "tstl %2\n" -" beqs stoploop_s16msb\n" -" movel #-32768,%%d2\n" -" movel #32767,%%d3\n" -" lsrl #1,%2\n" -"mixloop_s16msb:\n" - - /* Mix a sample */ - -" move %1@+,%%d0\n" /* d0 = *src++ */ -" muls %3,%%d0\n" /* d0 *= volume (0<=volume<=128) */ -" move %0@,%%d1\n" /* d1 = *dst */ -" extl %%d1\n" /* extend d1 to 32 bits */ -" asrl #7,%%d0\n" /* d0 /= 128 (SDL_MIX_MAXVOLUME) */ - -" addl %%d1,%%d0\n" - -" cmpl %%d2,%%d0\n" -" bges lower_limit_s16msb\n" -" move %%d2,%%d0\n" -"lower_limit_s16msb:\n" - -" cmpl %%d3,%%d0\n" -" bles upper_limit_s16msb\n" -" move %%d3,%%d0\n" -"upper_limit_s16msb:\n" -" move %%d0,%0@+\n" - - /* Loop till done */ - -" subql #1,%2\n" -" bhis mixloop_s16msb\n" -"stoploop_s16msb:\n" - - : /* no return value */ - : /* input */ - "a"(dst), "a"(src), "d"(len), "d"(volume) - : /* clobbered registers */ - "d0", "d1", "d2", "d3", "cc", "memory" - ); + __asm__ __volatile__("tstl %2\n" + " beqs stoploop_s16msb\n" + " movel #-32768,%%d2\n" + " movel #32767,%%d3\n" + " lsrl #1,%2\n" "mixloop_s16msb:\n" + /* Mix a sample */ + " move %1@+,%%d0\n" /* d0 = *src++ */ + " muls %3,%%d0\n" /* d0 *= volume (0<=volume<=128) */ + " move %0@,%%d1\n" /* d1 = *dst */ + " extl %%d1\n" /* extend d1 to 32 bits */ + " asrl #7,%%d0\n" /* d0 /= 128 (SDL_MIX_MAXVOLUME) */ + " addl %%d1,%%d0\n" + " cmpl %%d2,%%d0\n" + " bges lower_limit_s16msb\n" + " move %%d2,%%d0\n" + "lower_limit_s16msb:\n" + " cmpl %%d3,%%d0\n" + " bles upper_limit_s16msb\n" + " move %%d3,%%d0\n" + "upper_limit_s16msb:\n" " move %%d0,%0@+\n" + /* Loop till done */ + " subql #1,%2\n" " bhis mixloop_s16msb\n" "stoploop_s16msb:\n": /* no return value */ + : /* input */ + "a"(dst), "a"(src), "d"(len), "d"(volume): /* clobbered registers */ + "d0", "d1", "d2", "d3", "cc", "memory"); } -void SDL_MixAudio_m68k_S16LSB(short* dst, short* src, long len, long volume) +void +SDL_MixAudio_m68k_S16LSB(short *dst, short *src, long len, long volume) { - __asm__ __volatile__ ( - - "tstl %2\n" -" beqs stoploop_s16lsb\n" -" movel #-32768,%%d2\n" -" movel #32767,%%d3\n" -" lsrl #1,%2\n" -"mixloop_s16lsb:\n" - - /* Mix a sample */ - -" move %1@+,%%d0\n" /* d0 = *src++ */ -" rorw #8,%%d0\n" -" muls %3,%%d0\n" /* d0 *= volume (0<=volume<=128) */ -" move %0@,%%d1\n" /* d1 = *dst */ -" rorw #8,%%d1\n" -" extl %%d1\n" /* extend d1 to 32 bits */ -" asrl #7,%%d0\n" /* d0 /= 128 (SDL_MIX_MAXVOLUME) */ - -" addl %%d1,%%d0\n" - -" cmpl %%d2,%%d0\n" -" bges lower_limit_s16lsb\n" -" move %%d2,%%d0\n" -"lower_limit_s16lsb:\n" - -" cmpl %%d3,%%d0\n" -" bles upper_limit_s16lsb\n" -" move %%d3,%%d0\n" -"upper_limit_s16lsb:\n" -" rorw #8,%%d0\n" -" move %%d0,%0@+\n" - - /* Loop till done */ - -" subql #1,%2\n" -" bhis mixloop_s16lsb\n" -"stoploop_s16lsb:\n" - - : /* no return value */ - : /* input */ - "a"(dst), "a"(src), "d"(len), "d"(volume) - : /* clobbered registers */ - "d0", "d1", "d2", "d3", "cc", "memory" - ); + __asm__ __volatile__("tstl %2\n" + " beqs stoploop_s16lsb\n" + " movel #-32768,%%d2\n" + " movel #32767,%%d3\n" + " lsrl #1,%2\n" "mixloop_s16lsb:\n" + /* Mix a sample */ + " move %1@+,%%d0\n" /* d0 = *src++ */ + " rorw #8,%%d0\n" " muls %3,%%d0\n" /* d0 *= volume (0<=volume<=128) */ + " move %0@,%%d1\n" /* d1 = *dst */ + " rorw #8,%%d1\n" " extl %%d1\n" /* extend d1 to 32 bits */ + " asrl #7,%%d0\n" /* d0 /= 128 (SDL_MIX_MAXVOLUME) */ + " addl %%d1,%%d0\n" + " cmpl %%d2,%%d0\n" + " bges lower_limit_s16lsb\n" + " move %%d2,%%d0\n" + "lower_limit_s16lsb:\n" + " cmpl %%d3,%%d0\n" + " bles upper_limit_s16lsb\n" + " move %%d3,%%d0\n" + "upper_limit_s16lsb:\n" + " rorw #8,%%d0\n" " move %%d0,%0@+\n" + /* Loop till done */ + " subql #1,%2\n" " bhis mixloop_s16lsb\n" "stoploop_s16lsb:\n": /* no return value */ + : /* input */ + "a"(dst), "a"(src), "d"(len), "d"(volume): /* clobbered registers */ + "d0", "d1", "d2", "d3", "cc", "memory"); } #endif - +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/audio/SDL_mixer_m68k.h b/src/audio/SDL_mixer_m68k.h index d451dc43b..035ca2aab 100644 --- a/src/audio/SDL_mixer_m68k.h +++ b/src/audio/SDL_mixer_m68k.h @@ -28,9 +28,11 @@ */ #if defined(__M68000__) && defined(__GNUC__) -void SDL_MixAudio_m68k_U8(char* dst,char* src, long len, long volume, char* mix8); -void SDL_MixAudio_m68k_S8(char* dst,char* src, long len, long volume); +void SDL_MixAudio_m68k_U8(char *dst, char *src, long len, long volume, + char *mix8); +void SDL_MixAudio_m68k_S8(char *dst, char *src, long len, long volume); -void SDL_MixAudio_m68k_S16MSB(short* dst,short* src, long len, long volume); -void SDL_MixAudio_m68k_S16LSB(short* dst,short* src, long len, long volume); +void SDL_MixAudio_m68k_S16MSB(short *dst, short *src, long len, long volume); +void SDL_MixAudio_m68k_S16LSB(short *dst, short *src, long len, long volume); #endif +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/audio/SDL_sysaudio.h b/src/audio/SDL_sysaudio.h index 13e2dd516..00d814b4a 100644 --- a/src/audio/SDL_sysaudio.h +++ b/src/audio/SDL_sysaudio.h @@ -35,69 +35,71 @@ typedef struct SDL_AudioDevice SDL_AudioDevice; #ifndef _STATUS #define _STATUS SDL_status *status #endif -struct SDL_AudioDevice { - /* * * */ - /* The name of this audio driver */ - const char *name; - - /* * * */ - /* The description of this audio driver */ - const char *desc; - - /* * * */ - /* Public driver functions */ - int (*OpenAudio)(_THIS, SDL_AudioSpec *spec); - void (*ThreadInit)(_THIS); /* Called by audio thread at start */ - void (*WaitAudio)(_THIS); - void (*PlayAudio)(_THIS); - Uint8 *(*GetAudioBuf)(_THIS); - void (*WaitDone)(_THIS); - void (*CloseAudio)(_THIS); - - /* * * */ - /* Lock / Unlock functions added for the Mac port */ - void (*LockAudio)(_THIS); - void (*UnlockAudio)(_THIS); - - /* * * */ - /* Data common to all devices */ - - /* The current audio specification (shared with audio thread) */ - SDL_AudioSpec spec; - - /* An audio conversion block for audio format emulation */ - SDL_AudioCVT convert; - - /* Current state flags */ - int enabled; - int paused; - int opened; - - /* Fake audio buffer for when the audio hardware is busy */ - Uint8 *fake_stream; - - /* A semaphore for locking the mixing buffers */ - SDL_mutex *mixer_lock; - - /* A thread to feed the audio device */ - SDL_Thread *thread; - Uint32 threadid; - - /* * * */ - /* Data private to this driver */ - struct SDL_PrivateAudioData *hidden; - - /* * * */ - /* The function used to dispose of this structure */ - void (*free)(_THIS); +struct SDL_AudioDevice +{ + /* * * */ + /* The name of this audio driver */ + const char *name; + + /* * * */ + /* The description of this audio driver */ + const char *desc; + + /* * * */ + /* Public driver functions */ + int (*OpenAudio) (_THIS, SDL_AudioSpec * spec); + void (*ThreadInit) (_THIS); /* Called by audio thread at start */ + void (*WaitAudio) (_THIS); + void (*PlayAudio) (_THIS); + Uint8 *(*GetAudioBuf) (_THIS); + void (*WaitDone) (_THIS); + void (*CloseAudio) (_THIS); + + /* * * */ + /* Lock / Unlock functions added for the Mac port */ + void (*LockAudio) (_THIS); + void (*UnlockAudio) (_THIS); + + /* * * */ + /* Data common to all devices */ + + /* The current audio specification (shared with audio thread) */ + SDL_AudioSpec spec; + + /* An audio conversion block for audio format emulation */ + SDL_AudioCVT convert; + + /* Current state flags */ + int enabled; + int paused; + int opened; + + /* Fake audio buffer for when the audio hardware is busy */ + Uint8 *fake_stream; + + /* A semaphore for locking the mixing buffers */ + SDL_mutex *mixer_lock; + + /* A thread to feed the audio device */ + SDL_Thread *thread; + Uint32 threadid; + + /* * * */ + /* Data private to this driver */ + struct SDL_PrivateAudioData *hidden; + + /* * * */ + /* The function used to dispose of this structure */ + void (*free) (_THIS); }; #undef _THIS -typedef struct AudioBootStrap { - const char *name; - const char *desc; - int (*available)(void); - SDL_AudioDevice *(*create)(int devindex); +typedef struct AudioBootStrap +{ + const char *name; + const char *desc; + int (*available) (void); + SDL_AudioDevice *(*create) (int devindex); } AudioBootStrap; #if SDL_AUDIO_DRIVER_BSD @@ -176,3 +178,4 @@ extern AudioBootStrap DART_bootstrap; extern SDL_AudioDevice *current_audio; #endif /* _SDL_sysaudio_h */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/audio/SDL_wave.c b/src/audio/SDL_wave.c index 465195eb8..9eff53bfd 100644 --- a/src/audio/SDL_wave.c +++ b/src/audio/SDL_wave.c @@ -27,571 +27,592 @@ #include "SDL_wave.h" -static int ReadChunk(SDL_RWops *src, Chunk *chunk); +static int ReadChunk(SDL_RWops * src, Chunk * chunk); -struct MS_ADPCM_decodestate { - Uint8 hPredictor; - Uint16 iDelta; - Sint16 iSamp1; - Sint16 iSamp2; +struct MS_ADPCM_decodestate +{ + Uint8 hPredictor; + Uint16 iDelta; + Sint16 iSamp1; + Sint16 iSamp2; }; -static struct MS_ADPCM_decoder { - WaveFMT wavefmt; - Uint16 wSamplesPerBlock; - Uint16 wNumCoef; - Sint16 aCoeff[7][2]; - /* * * */ - struct MS_ADPCM_decodestate state[2]; +static struct MS_ADPCM_decoder +{ + WaveFMT wavefmt; + Uint16 wSamplesPerBlock; + Uint16 wNumCoef; + Sint16 aCoeff[7][2]; + /* * * */ + struct MS_ADPCM_decodestate state[2]; } MS_ADPCM_state; -static int InitMS_ADPCM(WaveFMT *format) +static int +InitMS_ADPCM(WaveFMT * format) { - Uint8 *rogue_feel; - Uint16 extra_info; - int i; - - /* Set the rogue pointer to the MS_ADPCM specific data */ - MS_ADPCM_state.wavefmt.encoding = SDL_SwapLE16(format->encoding); - MS_ADPCM_state.wavefmt.channels = SDL_SwapLE16(format->channels); - MS_ADPCM_state.wavefmt.frequency = SDL_SwapLE32(format->frequency); - MS_ADPCM_state.wavefmt.byterate = SDL_SwapLE32(format->byterate); - MS_ADPCM_state.wavefmt.blockalign = SDL_SwapLE16(format->blockalign); - MS_ADPCM_state.wavefmt.bitspersample = - SDL_SwapLE16(format->bitspersample); - rogue_feel = (Uint8 *)format+sizeof(*format); - if ( sizeof(*format) == 16 ) { - extra_info = ((rogue_feel[1]<<8)|rogue_feel[0]); - rogue_feel += sizeof(Uint16); - } - MS_ADPCM_state.wSamplesPerBlock = ((rogue_feel[1]<<8)|rogue_feel[0]); - rogue_feel += sizeof(Uint16); - MS_ADPCM_state.wNumCoef = ((rogue_feel[1]<<8)|rogue_feel[0]); - rogue_feel += sizeof(Uint16); - if ( MS_ADPCM_state.wNumCoef != 7 ) { - SDL_SetError("Unknown set of MS_ADPCM coefficients"); - return(-1); - } - for ( i=0; iencoding); + MS_ADPCM_state.wavefmt.channels = SDL_SwapLE16(format->channels); + MS_ADPCM_state.wavefmt.frequency = SDL_SwapLE32(format->frequency); + MS_ADPCM_state.wavefmt.byterate = SDL_SwapLE32(format->byterate); + MS_ADPCM_state.wavefmt.blockalign = SDL_SwapLE16(format->blockalign); + MS_ADPCM_state.wavefmt.bitspersample = + SDL_SwapLE16(format->bitspersample); + rogue_feel = (Uint8 *) format + sizeof(*format); + if (sizeof(*format) == 16) { + extra_info = ((rogue_feel[1] << 8) | rogue_feel[0]); + rogue_feel += sizeof(Uint16); + } + MS_ADPCM_state.wSamplesPerBlock = ((rogue_feel[1] << 8) | rogue_feel[0]); + rogue_feel += sizeof(Uint16); + MS_ADPCM_state.wNumCoef = ((rogue_feel[1] << 8) | rogue_feel[0]); + rogue_feel += sizeof(Uint16); + if (MS_ADPCM_state.wNumCoef != 7) { + SDL_SetError("Unknown set of MS_ADPCM coefficients"); + return (-1); + } + for (i = 0; i < MS_ADPCM_state.wNumCoef; ++i) { + MS_ADPCM_state.aCoeff[i][0] = ((rogue_feel[1] << 8) | rogue_feel[0]); + rogue_feel += sizeof(Uint16); + MS_ADPCM_state.aCoeff[i][1] = ((rogue_feel[1] << 8) | rogue_feel[0]); + rogue_feel += sizeof(Uint16); + } + return (0); } -static Sint32 MS_ADPCM_nibble(struct MS_ADPCM_decodestate *state, - Uint8 nybble, Sint16 *coeff) +static Sint32 +MS_ADPCM_nibble(struct MS_ADPCM_decodestate *state, + Uint8 nybble, Sint16 * coeff) { - const Sint32 max_audioval = ((1<<(16-1))-1); - const Sint32 min_audioval = -(1<<(16-1)); - const Sint32 adaptive[] = { - 230, 230, 230, 230, 307, 409, 512, 614, - 768, 614, 512, 409, 307, 230, 230, 230 - }; - Sint32 new_sample, delta; - - new_sample = ((state->iSamp1 * coeff[0]) + - (state->iSamp2 * coeff[1]))/256; - if ( nybble & 0x08 ) { - new_sample += state->iDelta * (nybble-0x10); - } else { - new_sample += state->iDelta * nybble; - } - if ( new_sample < min_audioval ) { - new_sample = min_audioval; - } else - if ( new_sample > max_audioval ) { - new_sample = max_audioval; - } - delta = ((Sint32)state->iDelta * adaptive[nybble])/256; - if ( delta < 16 ) { - delta = 16; - } - state->iDelta = (Uint16)delta; - state->iSamp2 = state->iSamp1; - state->iSamp1 = (Sint16)new_sample; - return(new_sample); + const Sint32 max_audioval = ((1 << (16 - 1)) - 1); + const Sint32 min_audioval = -(1 << (16 - 1)); + const Sint32 adaptive[] = { + 230, 230, 230, 230, 307, 409, 512, 614, + 768, 614, 512, 409, 307, 230, 230, 230 + }; + Sint32 new_sample, delta; + + new_sample = ((state->iSamp1 * coeff[0]) + + (state->iSamp2 * coeff[1])) / 256; + if (nybble & 0x08) { + new_sample += state->iDelta * (nybble - 0x10); + } else { + new_sample += state->iDelta * nybble; + } + if (new_sample < min_audioval) { + new_sample = min_audioval; + } else if (new_sample > max_audioval) { + new_sample = max_audioval; + } + delta = ((Sint32) state->iDelta * adaptive[nybble]) / 256; + if (delta < 16) { + delta = 16; + } + state->iDelta = (Uint16) delta; + state->iSamp2 = state->iSamp1; + state->iSamp1 = (Sint16) new_sample; + return (new_sample); } -static int MS_ADPCM_decode(Uint8 **audio_buf, Uint32 *audio_len) +static int +MS_ADPCM_decode(Uint8 ** audio_buf, Uint32 * audio_len) { - struct MS_ADPCM_decodestate *state[2]; - Uint8 *freeable, *encoded, *decoded; - Sint32 encoded_len, samplesleft; - Sint8 nybble, stereo; - Sint16 *coeff[2]; - Sint32 new_sample; - - /* Allocate the proper sized output buffer */ - encoded_len = *audio_len; - encoded = *audio_buf; - freeable = *audio_buf; - *audio_len = (encoded_len/MS_ADPCM_state.wavefmt.blockalign) * - MS_ADPCM_state.wSamplesPerBlock* - MS_ADPCM_state.wavefmt.channels*sizeof(Sint16); - *audio_buf = (Uint8 *)SDL_malloc(*audio_len); - if ( *audio_buf == NULL ) { - SDL_Error(SDL_ENOMEM); - return(-1); - } - decoded = *audio_buf; - - /* Get ready... Go! */ - stereo = (MS_ADPCM_state.wavefmt.channels == 2); - state[0] = &MS_ADPCM_state.state[0]; - state[1] = &MS_ADPCM_state.state[stereo]; - while ( encoded_len >= MS_ADPCM_state.wavefmt.blockalign ) { - /* Grab the initial information for this block */ - state[0]->hPredictor = *encoded++; - if ( stereo ) { - state[1]->hPredictor = *encoded++; - } - state[0]->iDelta = ((encoded[1]<<8)|encoded[0]); - encoded += sizeof(Sint16); - if ( stereo ) { - state[1]->iDelta = ((encoded[1]<<8)|encoded[0]); - encoded += sizeof(Sint16); - } - state[0]->iSamp1 = ((encoded[1]<<8)|encoded[0]); - encoded += sizeof(Sint16); - if ( stereo ) { - state[1]->iSamp1 = ((encoded[1]<<8)|encoded[0]); - encoded += sizeof(Sint16); - } - state[0]->iSamp2 = ((encoded[1]<<8)|encoded[0]); - encoded += sizeof(Sint16); - if ( stereo ) { - state[1]->iSamp2 = ((encoded[1]<<8)|encoded[0]); - encoded += sizeof(Sint16); - } - coeff[0] = MS_ADPCM_state.aCoeff[state[0]->hPredictor]; - coeff[1] = MS_ADPCM_state.aCoeff[state[1]->hPredictor]; - - /* Store the two initial samples we start with */ - decoded[0] = state[0]->iSamp2&0xFF; - decoded[1] = state[0]->iSamp2>>8; - decoded += 2; - if ( stereo ) { - decoded[0] = state[1]->iSamp2&0xFF; - decoded[1] = state[1]->iSamp2>>8; - decoded += 2; - } - decoded[0] = state[0]->iSamp1&0xFF; - decoded[1] = state[0]->iSamp1>>8; - decoded += 2; - if ( stereo ) { - decoded[0] = state[1]->iSamp1&0xFF; - decoded[1] = state[1]->iSamp1>>8; - decoded += 2; - } - - /* Decode and store the other samples in this block */ - samplesleft = (MS_ADPCM_state.wSamplesPerBlock-2)* - MS_ADPCM_state.wavefmt.channels; - while ( samplesleft > 0 ) { - nybble = (*encoded)>>4; - new_sample = MS_ADPCM_nibble(state[0],nybble,coeff[0]); - decoded[0] = new_sample&0xFF; - new_sample >>= 8; - decoded[1] = new_sample&0xFF; - decoded += 2; - - nybble = (*encoded)&0x0F; - new_sample = MS_ADPCM_nibble(state[1],nybble,coeff[1]); - decoded[0] = new_sample&0xFF; - new_sample >>= 8; - decoded[1] = new_sample&0xFF; - decoded += 2; - - ++encoded; - samplesleft -= 2; - } - encoded_len -= MS_ADPCM_state.wavefmt.blockalign; - } - SDL_free(freeable); - return(0); + struct MS_ADPCM_decodestate *state[2]; + Uint8 *freeable, *encoded, *decoded; + Sint32 encoded_len, samplesleft; + Sint8 nybble, stereo; + Sint16 *coeff[2]; + Sint32 new_sample; + + /* Allocate the proper sized output buffer */ + encoded_len = *audio_len; + encoded = *audio_buf; + freeable = *audio_buf; + *audio_len = (encoded_len / MS_ADPCM_state.wavefmt.blockalign) * + MS_ADPCM_state.wSamplesPerBlock * + MS_ADPCM_state.wavefmt.channels * sizeof(Sint16); + *audio_buf = (Uint8 *) SDL_malloc(*audio_len); + if (*audio_buf == NULL) { + SDL_Error(SDL_ENOMEM); + return (-1); + } + decoded = *audio_buf; + + /* Get ready... Go! */ + stereo = (MS_ADPCM_state.wavefmt.channels == 2); + state[0] = &MS_ADPCM_state.state[0]; + state[1] = &MS_ADPCM_state.state[stereo]; + while (encoded_len >= MS_ADPCM_state.wavefmt.blockalign) { + /* Grab the initial information for this block */ + state[0]->hPredictor = *encoded++; + if (stereo) { + state[1]->hPredictor = *encoded++; + } + state[0]->iDelta = ((encoded[1] << 8) | encoded[0]); + encoded += sizeof(Sint16); + if (stereo) { + state[1]->iDelta = ((encoded[1] << 8) | encoded[0]); + encoded += sizeof(Sint16); + } + state[0]->iSamp1 = ((encoded[1] << 8) | encoded[0]); + encoded += sizeof(Sint16); + if (stereo) { + state[1]->iSamp1 = ((encoded[1] << 8) | encoded[0]); + encoded += sizeof(Sint16); + } + state[0]->iSamp2 = ((encoded[1] << 8) | encoded[0]); + encoded += sizeof(Sint16); + if (stereo) { + state[1]->iSamp2 = ((encoded[1] << 8) | encoded[0]); + encoded += sizeof(Sint16); + } + coeff[0] = MS_ADPCM_state.aCoeff[state[0]->hPredictor]; + coeff[1] = MS_ADPCM_state.aCoeff[state[1]->hPredictor]; + + /* Store the two initial samples we start with */ + decoded[0] = state[0]->iSamp2 & 0xFF; + decoded[1] = state[0]->iSamp2 >> 8; + decoded += 2; + if (stereo) { + decoded[0] = state[1]->iSamp2 & 0xFF; + decoded[1] = state[1]->iSamp2 >> 8; + decoded += 2; + } + decoded[0] = state[0]->iSamp1 & 0xFF; + decoded[1] = state[0]->iSamp1 >> 8; + decoded += 2; + if (stereo) { + decoded[0] = state[1]->iSamp1 & 0xFF; + decoded[1] = state[1]->iSamp1 >> 8; + decoded += 2; + } + + /* Decode and store the other samples in this block */ + samplesleft = (MS_ADPCM_state.wSamplesPerBlock - 2) * + MS_ADPCM_state.wavefmt.channels; + while (samplesleft > 0) { + nybble = (*encoded) >> 4; + new_sample = MS_ADPCM_nibble(state[0], nybble, coeff[0]); + decoded[0] = new_sample & 0xFF; + new_sample >>= 8; + decoded[1] = new_sample & 0xFF; + decoded += 2; + + nybble = (*encoded) & 0x0F; + new_sample = MS_ADPCM_nibble(state[1], nybble, coeff[1]); + decoded[0] = new_sample & 0xFF; + new_sample >>= 8; + decoded[1] = new_sample & 0xFF; + decoded += 2; + + ++encoded; + samplesleft -= 2; + } + encoded_len -= MS_ADPCM_state.wavefmt.blockalign; + } + SDL_free(freeable); + return (0); } -struct IMA_ADPCM_decodestate { - Sint32 sample; - Sint8 index; +struct IMA_ADPCM_decodestate +{ + Sint32 sample; + Sint8 index; }; -static struct IMA_ADPCM_decoder { - WaveFMT wavefmt; - Uint16 wSamplesPerBlock; - /* * * */ - struct IMA_ADPCM_decodestate state[2]; +static struct IMA_ADPCM_decoder +{ + WaveFMT wavefmt; + Uint16 wSamplesPerBlock; + /* * * */ + struct IMA_ADPCM_decodestate state[2]; } IMA_ADPCM_state; -static int InitIMA_ADPCM(WaveFMT *format) +static int +InitIMA_ADPCM(WaveFMT * format) { - Uint8 *rogue_feel; - Uint16 extra_info; - - /* Set the rogue pointer to the IMA_ADPCM specific data */ - IMA_ADPCM_state.wavefmt.encoding = SDL_SwapLE16(format->encoding); - IMA_ADPCM_state.wavefmt.channels = SDL_SwapLE16(format->channels); - IMA_ADPCM_state.wavefmt.frequency = SDL_SwapLE32(format->frequency); - IMA_ADPCM_state.wavefmt.byterate = SDL_SwapLE32(format->byterate); - IMA_ADPCM_state.wavefmt.blockalign = SDL_SwapLE16(format->blockalign); - IMA_ADPCM_state.wavefmt.bitspersample = - SDL_SwapLE16(format->bitspersample); - rogue_feel = (Uint8 *)format+sizeof(*format); - if ( sizeof(*format) == 16 ) { - extra_info = ((rogue_feel[1]<<8)|rogue_feel[0]); - rogue_feel += sizeof(Uint16); - } - IMA_ADPCM_state.wSamplesPerBlock = ((rogue_feel[1]<<8)|rogue_feel[0]); - return(0); + Uint8 *rogue_feel; + Uint16 extra_info; + + /* Set the rogue pointer to the IMA_ADPCM specific data */ + IMA_ADPCM_state.wavefmt.encoding = SDL_SwapLE16(format->encoding); + IMA_ADPCM_state.wavefmt.channels = SDL_SwapLE16(format->channels); + IMA_ADPCM_state.wavefmt.frequency = SDL_SwapLE32(format->frequency); + IMA_ADPCM_state.wavefmt.byterate = SDL_SwapLE32(format->byterate); + IMA_ADPCM_state.wavefmt.blockalign = SDL_SwapLE16(format->blockalign); + IMA_ADPCM_state.wavefmt.bitspersample = + SDL_SwapLE16(format->bitspersample); + rogue_feel = (Uint8 *) format + sizeof(*format); + if (sizeof(*format) == 16) { + extra_info = ((rogue_feel[1] << 8) | rogue_feel[0]); + rogue_feel += sizeof(Uint16); + } + IMA_ADPCM_state.wSamplesPerBlock = ((rogue_feel[1] << 8) | rogue_feel[0]); + return (0); } -static Sint32 IMA_ADPCM_nibble(struct IMA_ADPCM_decodestate *state,Uint8 nybble) +static Sint32 +IMA_ADPCM_nibble(struct IMA_ADPCM_decodestate *state, Uint8 nybble) { - const Sint32 max_audioval = ((1<<(16-1))-1); - const Sint32 min_audioval = -(1<<(16-1)); - const int index_table[16] = { - -1, -1, -1, -1, - 2, 4, 6, 8, - -1, -1, -1, -1, - 2, 4, 6, 8 - }; - const Sint32 step_table[89] = { - 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 19, 21, 23, 25, 28, 31, - 34, 37, 41, 45, 50, 55, 60, 66, 73, 80, 88, 97, 107, 118, 130, - 143, 157, 173, 190, 209, 230, 253, 279, 307, 337, 371, 408, - 449, 494, 544, 598, 658, 724, 796, 876, 963, 1060, 1166, 1282, - 1411, 1552, 1707, 1878, 2066, 2272, 2499, 2749, 3024, 3327, - 3660, 4026, 4428, 4871, 5358, 5894, 6484, 7132, 7845, 8630, - 9493, 10442, 11487, 12635, 13899, 15289, 16818, 18500, 20350, - 22385, 24623, 27086, 29794, 32767 - }; - Sint32 delta, step; - - /* Compute difference and new sample value */ - step = step_table[state->index]; - delta = step >> 3; - if ( nybble & 0x04 ) delta += step; - if ( nybble & 0x02 ) delta += (step >> 1); - if ( nybble & 0x01 ) delta += (step >> 2); - if ( nybble & 0x08 ) delta = -delta; - state->sample += delta; - - /* Update index value */ - state->index += index_table[nybble]; - if ( state->index > 88 ) { - state->index = 88; - } else - if ( state->index < 0 ) { - state->index = 0; - } - - /* Clamp output sample */ - if ( state->sample > max_audioval ) { - state->sample = max_audioval; - } else - if ( state->sample < min_audioval ) { - state->sample = min_audioval; - } - return(state->sample); + const Sint32 max_audioval = ((1 << (16 - 1)) - 1); + const Sint32 min_audioval = -(1 << (16 - 1)); + const int index_table[16] = { + -1, -1, -1, -1, + 2, 4, 6, 8, + -1, -1, -1, -1, + 2, 4, 6, 8 + }; + const Sint32 step_table[89] = { + 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 19, 21, 23, 25, 28, 31, + 34, 37, 41, 45, 50, 55, 60, 66, 73, 80, 88, 97, 107, 118, 130, + 143, 157, 173, 190, 209, 230, 253, 279, 307, 337, 371, 408, + 449, 494, 544, 598, 658, 724, 796, 876, 963, 1060, 1166, 1282, + 1411, 1552, 1707, 1878, 2066, 2272, 2499, 2749, 3024, 3327, + 3660, 4026, 4428, 4871, 5358, 5894, 6484, 7132, 7845, 8630, + 9493, 10442, 11487, 12635, 13899, 15289, 16818, 18500, 20350, + 22385, 24623, 27086, 29794, 32767 + }; + Sint32 delta, step; + + /* Compute difference and new sample value */ + step = step_table[state->index]; + delta = step >> 3; + if (nybble & 0x04) + delta += step; + if (nybble & 0x02) + delta += (step >> 1); + if (nybble & 0x01) + delta += (step >> 2); + if (nybble & 0x08) + delta = -delta; + state->sample += delta; + + /* Update index value */ + state->index += index_table[nybble]; + if (state->index > 88) { + state->index = 88; + } else if (state->index < 0) { + state->index = 0; + } + + /* Clamp output sample */ + if (state->sample > max_audioval) { + state->sample = max_audioval; + } else if (state->sample < min_audioval) { + state->sample = min_audioval; + } + return (state->sample); } /* Fill the decode buffer with a channel block of data (8 samples) */ -static void Fill_IMA_ADPCM_block(Uint8 *decoded, Uint8 *encoded, - int channel, int numchannels, struct IMA_ADPCM_decodestate *state) +static void +Fill_IMA_ADPCM_block(Uint8 * decoded, Uint8 * encoded, + int channel, int numchannels, + struct IMA_ADPCM_decodestate *state) { - int i; - Sint8 nybble; - Sint32 new_sample; - - decoded += (channel * 2); - for ( i=0; i<4; ++i ) { - nybble = (*encoded)&0x0F; - new_sample = IMA_ADPCM_nibble(state, nybble); - decoded[0] = new_sample&0xFF; - new_sample >>= 8; - decoded[1] = new_sample&0xFF; - decoded += 2 * numchannels; - - nybble = (*encoded)>>4; - new_sample = IMA_ADPCM_nibble(state, nybble); - decoded[0] = new_sample&0xFF; - new_sample >>= 8; - decoded[1] = new_sample&0xFF; - decoded += 2 * numchannels; - - ++encoded; - } + int i; + Sint8 nybble; + Sint32 new_sample; + + decoded += (channel * 2); + for (i = 0; i < 4; ++i) { + nybble = (*encoded) & 0x0F; + new_sample = IMA_ADPCM_nibble(state, nybble); + decoded[0] = new_sample & 0xFF; + new_sample >>= 8; + decoded[1] = new_sample & 0xFF; + decoded += 2 * numchannels; + + nybble = (*encoded) >> 4; + new_sample = IMA_ADPCM_nibble(state, nybble); + decoded[0] = new_sample & 0xFF; + new_sample >>= 8; + decoded[1] = new_sample & 0xFF; + decoded += 2 * numchannels; + + ++encoded; + } } -static int IMA_ADPCM_decode(Uint8 **audio_buf, Uint32 *audio_len) +static int +IMA_ADPCM_decode(Uint8 ** audio_buf, Uint32 * audio_len) { - struct IMA_ADPCM_decodestate *state; - Uint8 *freeable, *encoded, *decoded; - Sint32 encoded_len, samplesleft; - unsigned int c, channels; - - /* Check to make sure we have enough variables in the state array */ - channels = IMA_ADPCM_state.wavefmt.channels; - if ( channels > SDL_arraysize(IMA_ADPCM_state.state) ) { - SDL_SetError("IMA ADPCM decoder can only handle %d channels", - SDL_arraysize(IMA_ADPCM_state.state)); - return(-1); - } - state = IMA_ADPCM_state.state; - - /* Allocate the proper sized output buffer */ - encoded_len = *audio_len; - encoded = *audio_buf; - freeable = *audio_buf; - *audio_len = (encoded_len/IMA_ADPCM_state.wavefmt.blockalign) * - IMA_ADPCM_state.wSamplesPerBlock* - IMA_ADPCM_state.wavefmt.channels*sizeof(Sint16); - *audio_buf = (Uint8 *)SDL_malloc(*audio_len); - if ( *audio_buf == NULL ) { - SDL_Error(SDL_ENOMEM); - return(-1); - } - decoded = *audio_buf; - - /* Get ready... Go! */ - while ( encoded_len >= IMA_ADPCM_state.wavefmt.blockalign ) { - /* Grab the initial information for this block */ - for ( c=0; c>8); - decoded += 2; - } - - /* Decode and store the other samples in this block */ - samplesleft = (IMA_ADPCM_state.wSamplesPerBlock-1)*channels; - while ( samplesleft > 0 ) { - for ( c=0; c SDL_arraysize(IMA_ADPCM_state.state)) { + SDL_SetError("IMA ADPCM decoder can only handle %d channels", + SDL_arraysize(IMA_ADPCM_state.state)); + return (-1); + } + state = IMA_ADPCM_state.state; + + /* Allocate the proper sized output buffer */ + encoded_len = *audio_len; + encoded = *audio_buf; + freeable = *audio_buf; + *audio_len = (encoded_len / IMA_ADPCM_state.wavefmt.blockalign) * + IMA_ADPCM_state.wSamplesPerBlock * + IMA_ADPCM_state.wavefmt.channels * sizeof(Sint16); + *audio_buf = (Uint8 *) SDL_malloc(*audio_len); + if (*audio_buf == NULL) { + SDL_Error(SDL_ENOMEM); + return (-1); + } + decoded = *audio_buf; + + /* Get ready... Go! */ + while (encoded_len >= IMA_ADPCM_state.wavefmt.blockalign) { + /* Grab the initial information for this block */ + for (c = 0; c < channels; ++c) { + /* Fill the state information for this block */ + state[c].sample = ((encoded[1] << 8) | encoded[0]); + encoded += 2; + if (state[c].sample & 0x8000) { + state[c].sample -= 0x10000; + } + state[c].index = *encoded++; + /* Reserved byte in buffer header, should be 0 */ + if (*encoded++ != 0) { + /* Uh oh, corrupt data? Buggy code? */ ; + } + + /* Store the initial sample we start with */ + decoded[0] = (Uint8) (state[c].sample & 0xFF); + decoded[1] = (Uint8) (state[c].sample >> 8); + decoded += 2; + } + + /* Decode and store the other samples in this block */ + samplesleft = (IMA_ADPCM_state.wSamplesPerBlock - 1) * channels; + while (samplesleft > 0) { + for (c = 0; c < channels; ++c) { + Fill_IMA_ADPCM_block(decoded, encoded, + c, channels, &state[c]); + encoded += 4; + samplesleft -= 8; + } + decoded += (channels * 8 * 2); + } + encoded_len -= IMA_ADPCM_state.wavefmt.blockalign; + } + SDL_free(freeable); + return (0); } -SDL_AudioSpec * SDL_LoadWAV_RW (SDL_RWops *src, int freesrc, - SDL_AudioSpec *spec, Uint8 **audio_buf, Uint32 *audio_len) +SDL_AudioSpec * +SDL_LoadWAV_RW(SDL_RWops * src, int freesrc, + SDL_AudioSpec * spec, Uint8 ** audio_buf, Uint32 * audio_len) { - int was_error; - Chunk chunk; - int lenread; - int MS_ADPCM_encoded, IMA_ADPCM_encoded; - int samplesize; - - /* WAV magic header */ - Uint32 RIFFchunk; - Uint32 wavelen = 0; - Uint32 WAVEmagic; - Uint32 headerDiff = 0; - - /* FMT chunk */ - WaveFMT *format = NULL; - - /* Make sure we are passed a valid data source */ - was_error = 0; - if ( src == NULL ) { - was_error = 1; - goto done; - } - - /* Check the magic header */ - RIFFchunk = SDL_ReadLE32(src); - wavelen = SDL_ReadLE32(src); - if ( wavelen == WAVE ) { /* The RIFFchunk has already been read */ - WAVEmagic = wavelen; - wavelen = RIFFchunk; - RIFFchunk = RIFF; - } else { - WAVEmagic = SDL_ReadLE32(src); - } - if ( (RIFFchunk != RIFF) || (WAVEmagic != WAVE) ) { - SDL_SetError("Unrecognized file type (not WAVE)"); - was_error = 1; - goto done; - } - headerDiff += sizeof(Uint32); /* for WAVE */ - - /* Read the audio data format chunk */ - chunk.data = NULL; - do { - if ( chunk.data != NULL ) { - SDL_free(chunk.data); - } - lenread = ReadChunk(src, &chunk); - if ( lenread < 0 ) { - was_error = 1; - goto done; - } - /* 2 Uint32's for chunk header+len, plus the lenread */ - headerDiff += lenread + 2 * sizeof(Uint32); - } while ( (chunk.magic == FACT) || (chunk.magic == LIST) ); - - /* Decode the audio data format */ - format = (WaveFMT *)chunk.data; - if ( chunk.magic != FMT ) { - SDL_SetError("Complex WAVE files not supported"); - was_error = 1; - goto done; - } - MS_ADPCM_encoded = IMA_ADPCM_encoded = 0; - switch (SDL_SwapLE16(format->encoding)) { - case PCM_CODE: - /* We can understand this */ - break; - case MS_ADPCM_CODE: - /* Try to understand this */ - if ( InitMS_ADPCM(format) < 0 ) { - was_error = 1; - goto done; - } - MS_ADPCM_encoded = 1; - break; - case IMA_ADPCM_CODE: - /* Try to understand this */ - if ( InitIMA_ADPCM(format) < 0 ) { - was_error = 1; - goto done; - } - IMA_ADPCM_encoded = 1; - break; - case MP3_CODE: - SDL_SetError("MPEG Layer 3 data not supported", - SDL_SwapLE16(format->encoding)); - was_error = 1; - goto done; - default: - SDL_SetError("Unknown WAVE data format: 0x%.4x", - SDL_SwapLE16(format->encoding)); - was_error = 1; - goto done; - } - SDL_memset(spec, 0, (sizeof *spec)); - spec->freq = SDL_SwapLE32(format->frequency); - switch (SDL_SwapLE16(format->bitspersample)) { - case 4: - if ( MS_ADPCM_encoded || IMA_ADPCM_encoded ) { - spec->format = AUDIO_S16; - } else { - was_error = 1; - } - break; - case 8: - spec->format = AUDIO_U8; - break; - case 16: - spec->format = AUDIO_S16; - break; - default: - was_error = 1; - break; - } - if ( was_error ) { - SDL_SetError("Unknown %d-bit PCM data format", - SDL_SwapLE16(format->bitspersample)); - goto done; - } - spec->channels = (Uint8)SDL_SwapLE16(format->channels); - spec->samples = 4096; /* Good default buffer size */ - - /* Read the audio data chunk */ - *audio_buf = NULL; - do { - if ( *audio_buf != NULL ) { - SDL_free(*audio_buf); - } - lenread = ReadChunk(src, &chunk); - if ( lenread < 0 ) { - was_error = 1; - goto done; - } - *audio_len = lenread; - *audio_buf = chunk.data; - if(chunk.magic != DATA) headerDiff += lenread + 2 * sizeof(Uint32); - } while ( chunk.magic != DATA ); - headerDiff += 2 * sizeof(Uint32); /* for the data chunk and len */ - - if ( MS_ADPCM_encoded ) { - if ( MS_ADPCM_decode(audio_buf, audio_len) < 0 ) { - was_error = 1; - goto done; - } - } - if ( IMA_ADPCM_encoded ) { - if ( IMA_ADPCM_decode(audio_buf, audio_len) < 0 ) { - was_error = 1; - goto done; - } - } - - /* Don't return a buffer that isn't a multiple of samplesize */ - samplesize = ((spec->format & 0xFF)/8)*spec->channels; - *audio_len &= ~(samplesize-1); - -done: - if ( format != NULL ) { - SDL_free(format); - } - if ( src ) { - if ( freesrc ) { - SDL_RWclose(src); - } else { - /* seek to the end of the file (given by the RIFF chunk) */ - SDL_RWseek(src, wavelen - chunk.length - headerDiff, RW_SEEK_CUR); - } - } - if ( was_error ) { - spec = NULL; - } - return(spec); + int was_error; + Chunk chunk; + int lenread; + int MS_ADPCM_encoded, IMA_ADPCM_encoded; + int samplesize; + + /* WAV magic header */ + Uint32 RIFFchunk; + Uint32 wavelen = 0; + Uint32 WAVEmagic; + Uint32 headerDiff = 0; + + /* FMT chunk */ + WaveFMT *format = NULL; + + /* Make sure we are passed a valid data source */ + was_error = 0; + if (src == NULL) { + was_error = 1; + goto done; + } + + /* Check the magic header */ + RIFFchunk = SDL_ReadLE32(src); + wavelen = SDL_ReadLE32(src); + if (wavelen == WAVE) { /* The RIFFchunk has already been read */ + WAVEmagic = wavelen; + wavelen = RIFFchunk; + RIFFchunk = RIFF; + } else { + WAVEmagic = SDL_ReadLE32(src); + } + if ((RIFFchunk != RIFF) || (WAVEmagic != WAVE)) { + SDL_SetError("Unrecognized file type (not WAVE)"); + was_error = 1; + goto done; + } + headerDiff += sizeof(Uint32); /* for WAVE */ + + /* Read the audio data format chunk */ + chunk.data = NULL; + do { + if (chunk.data != NULL) { + SDL_free(chunk.data); + } + lenread = ReadChunk(src, &chunk); + if (lenread < 0) { + was_error = 1; + goto done; + } + /* 2 Uint32's for chunk header+len, plus the lenread */ + headerDiff += lenread + 2 * sizeof(Uint32); + } + while ((chunk.magic == FACT) || (chunk.magic == LIST)); + + /* Decode the audio data format */ + format = (WaveFMT *) chunk.data; + if (chunk.magic != FMT) { + SDL_SetError("Complex WAVE files not supported"); + was_error = 1; + goto done; + } + MS_ADPCM_encoded = IMA_ADPCM_encoded = 0; + switch (SDL_SwapLE16(format->encoding)) { + case PCM_CODE: + /* We can understand this */ + break; + case MS_ADPCM_CODE: + /* Try to understand this */ + if (InitMS_ADPCM(format) < 0) { + was_error = 1; + goto done; + } + MS_ADPCM_encoded = 1; + break; + case IMA_ADPCM_CODE: + /* Try to understand this */ + if (InitIMA_ADPCM(format) < 0) { + was_error = 1; + goto done; + } + IMA_ADPCM_encoded = 1; + break; + case MP3_CODE: + SDL_SetError("MPEG Layer 3 data not supported", + SDL_SwapLE16(format->encoding)); + was_error = 1; + goto done; + default: + SDL_SetError("Unknown WAVE data format: 0x%.4x", + SDL_SwapLE16(format->encoding)); + was_error = 1; + goto done; + } + SDL_memset(spec, 0, (sizeof *spec)); + spec->freq = SDL_SwapLE32(format->frequency); + switch (SDL_SwapLE16(format->bitspersample)) { + case 4: + if (MS_ADPCM_encoded || IMA_ADPCM_encoded) { + spec->format = AUDIO_S16; + } else { + was_error = 1; + } + break; + case 8: + spec->format = AUDIO_U8; + break; + case 16: + spec->format = AUDIO_S16; + break; + default: + was_error = 1; + break; + } + if (was_error) { + SDL_SetError("Unknown %d-bit PCM data format", + SDL_SwapLE16(format->bitspersample)); + goto done; + } + spec->channels = (Uint8) SDL_SwapLE16(format->channels); + spec->samples = 4096; /* Good default buffer size */ + + /* Read the audio data chunk */ + *audio_buf = NULL; + do { + if (*audio_buf != NULL) { + SDL_free(*audio_buf); + } + lenread = ReadChunk(src, &chunk); + if (lenread < 0) { + was_error = 1; + goto done; + } + *audio_len = lenread; + *audio_buf = chunk.data; + if (chunk.magic != DATA) + headerDiff += lenread + 2 * sizeof(Uint32); + } + while (chunk.magic != DATA); + headerDiff += 2 * sizeof(Uint32); /* for the data chunk and len */ + + if (MS_ADPCM_encoded) { + if (MS_ADPCM_decode(audio_buf, audio_len) < 0) { + was_error = 1; + goto done; + } + } + if (IMA_ADPCM_encoded) { + if (IMA_ADPCM_decode(audio_buf, audio_len) < 0) { + was_error = 1; + goto done; + } + } + + /* Don't return a buffer that isn't a multiple of samplesize */ + samplesize = ((spec->format & 0xFF) / 8) * spec->channels; + *audio_len &= ~(samplesize - 1); + + done: + if (format != NULL) { + SDL_free(format); + } + if (src) { + if (freesrc) { + SDL_RWclose(src); + } else { + /* seek to the end of the file (given by the RIFF chunk) */ + SDL_RWseek(src, wavelen - chunk.length - headerDiff, RW_SEEK_CUR); + } + } + if (was_error) { + spec = NULL; + } + return (spec); } /* Since the WAV memory is allocated in the shared library, it must also be freed here. (Necessary under Win32, VC++) */ -void SDL_FreeWAV(Uint8 *audio_buf) +void +SDL_FreeWAV(Uint8 * audio_buf) { - if ( audio_buf != NULL ) { - SDL_free(audio_buf); - } + if (audio_buf != NULL) { + SDL_free(audio_buf); + } } -static int ReadChunk(SDL_RWops *src, Chunk *chunk) +static int +ReadChunk(SDL_RWops * src, Chunk * chunk) { - chunk->magic = SDL_ReadLE32(src); - chunk->length = SDL_ReadLE32(src); - chunk->data = (Uint8 *)SDL_malloc(chunk->length); - if ( chunk->data == NULL ) { - SDL_Error(SDL_ENOMEM); - return(-1); - } - if ( SDL_RWread(src, chunk->data, chunk->length, 1) != 1 ) { - SDL_Error(SDL_EFREAD); - SDL_free(chunk->data); - return(-1); - } - return(chunk->length); + chunk->magic = SDL_ReadLE32(src); + chunk->length = SDL_ReadLE32(src); + chunk->data = (Uint8 *) SDL_malloc(chunk->length); + if (chunk->data == NULL) { + SDL_Error(SDL_ENOMEM); + return (-1); + } + if (SDL_RWread(src, chunk->data, chunk->length, 1) != 1) { + SDL_Error(SDL_EFREAD); + SDL_free(chunk->data); + return (-1); + } + return (chunk->length); } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/audio/SDL_wave.h b/src/audio/SDL_wave.h index a0af6ebd8..036a0c839 100644 --- a/src/audio/SDL_wave.h +++ b/src/audio/SDL_wave.h @@ -26,12 +26,12 @@ /*******************************************/ /* Define values for Microsoft WAVE format */ /*******************************************/ -#define RIFF 0x46464952 /* "RIFF" */ -#define WAVE 0x45564157 /* "WAVE" */ -#define FACT 0x74636166 /* "fact" */ -#define LIST 0x5453494c /* "LIST" */ -#define FMT 0x20746D66 /* "fmt " */ -#define DATA 0x61746164 /* "data" */ +#define RIFF 0x46464952 /* "RIFF" */ +#define WAVE 0x45564157 /* "WAVE" */ +#define FACT 0x74636166 /* "fact" */ +#define LIST 0x5453494c /* "LIST" */ +#define FMT 0x20746D66 /* "fmt " */ +#define DATA 0x61746164 /* "data" */ #define PCM_CODE 0x0001 #define MS_ADPCM_CODE 0x0002 #define IMA_ADPCM_CODE 0x0011 @@ -40,23 +40,25 @@ #define WAVE_STEREO 2 /* Normally, these three chunks come consecutively in a WAVE file */ -typedef struct WaveFMT { +typedef struct WaveFMT +{ /* Not saved in the chunk we read: Uint32 FMTchunk; Uint32 fmtlen; */ - Uint16 encoding; - Uint16 channels; /* 1 = mono, 2 = stereo */ - Uint32 frequency; /* One of 11025, 22050, or 44100 Hz */ - Uint32 byterate; /* Average bytes per second */ - Uint16 blockalign; /* Bytes per sample block */ - Uint16 bitspersample; /* One of 8, 12, 16, or 4 for ADPCM */ + Uint16 encoding; + Uint16 channels; /* 1 = mono, 2 = stereo */ + Uint32 frequency; /* One of 11025, 22050, or 44100 Hz */ + Uint32 byterate; /* Average bytes per second */ + Uint16 blockalign; /* Bytes per sample block */ + Uint16 bitspersample; /* One of 8, 12, 16, or 4 for ADPCM */ } WaveFMT; /* The general chunk found in the WAVE file */ -typedef struct Chunk { - Uint32 magic; - Uint32 length; - Uint8 *data; +typedef struct Chunk +{ + Uint32 magic; + Uint32 length; + Uint8 *data; } Chunk; - +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/audio/alsa/SDL_alsa_audio.c b/src/audio/alsa/SDL_alsa_audio.c index a5138d158..f0e4655bd 100644 --- a/src/audio/alsa/SDL_alsa_audio.c +++ b/src/audio/alsa/SDL_alsa_audio.c @@ -24,7 +24,7 @@ /* Allow access to a raw mixing buffer */ #include -#include /* For kill() */ +#include /* For kill() */ #include "SDL_timer.h" #include "SDL_audio.h" @@ -48,7 +48,7 @@ #define DEFAULT_DEVICE "default" /* Audio driver functions */ -static int ALSA_OpenAudio(_THIS, SDL_AudioSpec *spec); +static int ALSA_OpenAudio(_THIS, SDL_AudioSpec * spec); static void ALSA_WaitAudio(_THIS); static void ALSA_PlayAudio(_THIS); static Uint8 *ALSA_GetAudioBuf(_THIS); @@ -60,208 +60,295 @@ static const char *alsa_library = SDL_AUDIO_DRIVER_ALSA_DYNAMIC; static void *alsa_handle = NULL; static int alsa_loaded = 0; -static int (*SDL_snd_pcm_open)(snd_pcm_t **pcm, const char *name, snd_pcm_stream_t stream, int mode); -static int (*SDL_NAME(snd_pcm_open))(snd_pcm_t **pcm, const char *name, snd_pcm_stream_t stream, int mode); -static int (*SDL_NAME(snd_pcm_close))(snd_pcm_t *pcm); -static snd_pcm_sframes_t (*SDL_NAME(snd_pcm_writei))(snd_pcm_t *pcm, const void *buffer, snd_pcm_uframes_t size); -static int (*SDL_NAME(snd_pcm_resume))(snd_pcm_t *pcm); -static int (*SDL_NAME(snd_pcm_prepare))(snd_pcm_t *pcm); -static int (*SDL_NAME(snd_pcm_drain))(snd_pcm_t *pcm); -static const char *(*SDL_NAME(snd_strerror))(int errnum); -static size_t (*SDL_NAME(snd_pcm_hw_params_sizeof))(void); -static size_t (*SDL_NAME(snd_pcm_sw_params_sizeof))(void); -static int (*SDL_NAME(snd_pcm_hw_params_any))(snd_pcm_t *pcm, snd_pcm_hw_params_t *params); -static int (*SDL_NAME(snd_pcm_hw_params_set_access))(snd_pcm_t *pcm, snd_pcm_hw_params_t *params, snd_pcm_access_t access); -static int (*SDL_NAME(snd_pcm_hw_params_set_format))(snd_pcm_t *pcm, snd_pcm_hw_params_t *params, snd_pcm_format_t val); -static int (*SDL_NAME(snd_pcm_hw_params_set_channels))(snd_pcm_t *pcm, snd_pcm_hw_params_t *params, unsigned int val); -static int (*SDL_NAME(snd_pcm_hw_params_get_channels))(const snd_pcm_hw_params_t *params); -static unsigned int (*SDL_NAME(snd_pcm_hw_params_set_rate_near))(snd_pcm_t *pcm, snd_pcm_hw_params_t *params, unsigned int val, int *dir); -static snd_pcm_uframes_t (*SDL_NAME(snd_pcm_hw_params_set_period_size_near))(snd_pcm_t *pcm, snd_pcm_hw_params_t *params, snd_pcm_uframes_t val, int *dir); -static snd_pcm_sframes_t (*SDL_NAME(snd_pcm_hw_params_get_period_size))(const snd_pcm_hw_params_t *params); -static unsigned int (*SDL_NAME(snd_pcm_hw_params_set_periods_near))(snd_pcm_t *pcm, snd_pcm_hw_params_t *params, unsigned int val, int *dir); -static int (*SDL_NAME(snd_pcm_hw_params_get_periods))(snd_pcm_hw_params_t *params); -static int (*SDL_NAME(snd_pcm_hw_params))(snd_pcm_t *pcm, snd_pcm_hw_params_t *params); +static int (*SDL_snd_pcm_open) (snd_pcm_t ** pcm, const char *name, + snd_pcm_stream_t stream, int mode); +static int (*SDL_NAME(snd_pcm_open)) (snd_pcm_t ** pcm, const char *name, + snd_pcm_stream_t stream, int mode); +static int (*SDL_NAME(snd_pcm_close)) (snd_pcm_t * pcm); +static snd_pcm_sframes_t(*SDL_NAME(snd_pcm_writei)) (snd_pcm_t * pcm, + const void *buffer, + snd_pcm_uframes_t size); +static int (*SDL_NAME(snd_pcm_resume)) (snd_pcm_t * pcm); +static int (*SDL_NAME(snd_pcm_prepare)) (snd_pcm_t * pcm); +static int (*SDL_NAME(snd_pcm_drain)) (snd_pcm_t * pcm); +static const char *(*SDL_NAME(snd_strerror)) (int errnum); +static size_t(*SDL_NAME(snd_pcm_hw_params_sizeof)) (void); +static size_t(*SDL_NAME(snd_pcm_sw_params_sizeof)) (void); +static int (*SDL_NAME(snd_pcm_hw_params_any)) (snd_pcm_t * pcm, + snd_pcm_hw_params_t * params); +static int (*SDL_NAME(snd_pcm_hw_params_set_access)) (snd_pcm_t * pcm, + snd_pcm_hw_params_t * + params, + snd_pcm_access_t + access); +static int (*SDL_NAME(snd_pcm_hw_params_set_format)) (snd_pcm_t * pcm, + snd_pcm_hw_params_t * + params, + snd_pcm_format_t val); +static int (*SDL_NAME(snd_pcm_hw_params_set_channels)) (snd_pcm_t * pcm, + snd_pcm_hw_params_t * + params, + unsigned int val); +static int (*SDL_NAME(snd_pcm_hw_params_get_channels)) (const + snd_pcm_hw_params_t * + params); +static unsigned int + (*SDL_NAME(snd_pcm_hw_params_set_rate_near)) (snd_pcm_t * + pcm, + snd_pcm_hw_params_t + * params, + unsigned int val, int *dir); +static snd_pcm_uframes_t + (*SDL_NAME(snd_pcm_hw_params_set_period_size_near)) (snd_pcm_t * pcm, + snd_pcm_hw_params_t + * params, + snd_pcm_uframes_t + val, int *dir); +static snd_pcm_sframes_t + (*SDL_NAME(snd_pcm_hw_params_get_period_size)) (const + snd_pcm_hw_params_t + * params); +static unsigned int + (*SDL_NAME(snd_pcm_hw_params_set_periods_near)) (snd_pcm_t * pcm, + snd_pcm_hw_params_t + * params, + unsigned int val, + int *dir); +static int (*SDL_NAME(snd_pcm_hw_params_get_periods)) (snd_pcm_hw_params_t * + params); +static int (*SDL_NAME(snd_pcm_hw_params)) (snd_pcm_t * pcm, + snd_pcm_hw_params_t * params); /* */ -static int (*SDL_NAME(snd_pcm_sw_params_current))(snd_pcm_t *pcm, snd_pcm_sw_params_t *swparams); -static int (*SDL_NAME(snd_pcm_sw_params_set_start_threshold))(snd_pcm_t *pcm, snd_pcm_sw_params_t *params, snd_pcm_uframes_t val); -static int (*SDL_NAME(snd_pcm_sw_params_set_avail_min))(snd_pcm_t *pcm, snd_pcm_sw_params_t *params, snd_pcm_uframes_t val); -static int (*SDL_NAME(snd_pcm_sw_params))(snd_pcm_t *pcm, snd_pcm_sw_params_t *params); -static int (*SDL_NAME(snd_pcm_nonblock))(snd_pcm_t *pcm, int nonblock); +static int (*SDL_NAME(snd_pcm_sw_params_current)) (snd_pcm_t * pcm, + snd_pcm_sw_params_t * + swparams); +static int (*SDL_NAME(snd_pcm_sw_params_set_start_threshold)) (snd_pcm_t * + pcm, + snd_pcm_sw_params_t + * params, + snd_pcm_uframes_t + val); +static int (*SDL_NAME(snd_pcm_sw_params_set_avail_min)) (snd_pcm_t * pcm, + snd_pcm_sw_params_t + * params, + snd_pcm_uframes_t + val); +static int (*SDL_NAME(snd_pcm_sw_params)) (snd_pcm_t * pcm, + snd_pcm_sw_params_t * params); +static int (*SDL_NAME(snd_pcm_nonblock)) (snd_pcm_t * pcm, int nonblock); #define snd_pcm_hw_params_sizeof SDL_NAME(snd_pcm_hw_params_sizeof) #define snd_pcm_sw_params_sizeof SDL_NAME(snd_pcm_sw_params_sizeof) /* cast funcs to char* first, to please GCC's strict aliasing rules. */ -static struct { - const char *name; - void **func; +static struct +{ + const char *name; + void **func; } alsa_functions[] = { - { "snd_pcm_open", (void**)(char*)&SDL_NAME(snd_pcm_open) }, - { "snd_pcm_close", (void**)(char*)&SDL_NAME(snd_pcm_close) }, - { "snd_pcm_writei", (void**)(char*)&SDL_NAME(snd_pcm_writei) }, - { "snd_pcm_resume", (void**)(char*)&SDL_NAME(snd_pcm_resume) }, - { "snd_pcm_prepare", (void**)(char*)&SDL_NAME(snd_pcm_prepare) }, - { "snd_pcm_drain", (void**)(char*)&SDL_NAME(snd_pcm_drain) }, - { "snd_strerror", (void**)(char*)&SDL_NAME(snd_strerror) }, - { "snd_pcm_hw_params_sizeof", (void**)(char*)&SDL_NAME(snd_pcm_hw_params_sizeof) }, - { "snd_pcm_sw_params_sizeof", (void**)(char*)&SDL_NAME(snd_pcm_sw_params_sizeof) }, - { "snd_pcm_hw_params_any", (void**)(char*)&SDL_NAME(snd_pcm_hw_params_any) }, - { "snd_pcm_hw_params_set_access", (void**)(char*)&SDL_NAME(snd_pcm_hw_params_set_access) }, - { "snd_pcm_hw_params_set_format", (void**)(char*)&SDL_NAME(snd_pcm_hw_params_set_format) }, - { "snd_pcm_hw_params_set_channels", (void**)(char*)&SDL_NAME(snd_pcm_hw_params_set_channels) }, - { "snd_pcm_hw_params_get_channels", (void**)(char*)&SDL_NAME(snd_pcm_hw_params_get_channels) }, - { "snd_pcm_hw_params_set_rate_near", (void**)(char*)&SDL_NAME(snd_pcm_hw_params_set_rate_near) }, - { "snd_pcm_hw_params_set_period_size_near", (void**)(char*)&SDL_NAME(snd_pcm_hw_params_set_period_size_near) }, - { "snd_pcm_hw_params_get_period_size", (void**)(char*)&SDL_NAME(snd_pcm_hw_params_get_period_size) }, - { "snd_pcm_hw_params_set_periods_near", (void**)(char*)&SDL_NAME(snd_pcm_hw_params_set_periods_near) }, - { "snd_pcm_hw_params_get_periods", (void**)(char*)&SDL_NAME(snd_pcm_hw_params_get_periods) }, - { "snd_pcm_hw_params", (void**)(char*)&SDL_NAME(snd_pcm_hw_params) }, - { "snd_pcm_sw_params_current", (void**)(char*)&SDL_NAME(snd_pcm_sw_params_current) }, - { "snd_pcm_sw_params_set_start_threshold", (void**)(char*)&SDL_NAME(snd_pcm_sw_params_set_start_threshold) }, - { "snd_pcm_sw_params_set_avail_min", (void**)(char*)&SDL_NAME(snd_pcm_sw_params_set_avail_min) }, - { "snd_pcm_sw_params", (void**)(char*)&SDL_NAME(snd_pcm_sw_params) }, - { "snd_pcm_nonblock", (void**)(char*)&SDL_NAME(snd_pcm_nonblock) }, -}; - -static void UnloadALSALibrary(void) { - if (alsa_loaded) { + { + "snd_pcm_open", (void **) (char *) &SDL_NAME(snd_pcm_open)}, { + "snd_pcm_close", (void **) (char *) &SDL_NAME(snd_pcm_close)}, { + "snd_pcm_writei", (void **) (char *) &SDL_NAME(snd_pcm_writei)}, { + "snd_pcm_resume", (void **) (char *) &SDL_NAME(snd_pcm_resume)}, { + "snd_pcm_prepare", (void **) (char *) &SDL_NAME(snd_pcm_prepare)}, { + "snd_pcm_drain", (void **) (char *) &SDL_NAME(snd_pcm_drain)}, { + "snd_strerror", (void **) (char *) &SDL_NAME(snd_strerror)}, { + "snd_pcm_hw_params_sizeof", + (void **) (char *) &SDL_NAME(snd_pcm_hw_params_sizeof)}, { + "snd_pcm_sw_params_sizeof", + (void **) (char *) &SDL_NAME(snd_pcm_sw_params_sizeof)}, { + "snd_pcm_hw_params_any", + (void **) (char *) &SDL_NAME(snd_pcm_hw_params_any)}, { + "snd_pcm_hw_params_set_access", + (void **) (char *) &SDL_NAME(snd_pcm_hw_params_set_access)}, { + "snd_pcm_hw_params_set_format", + (void **) (char *) &SDL_NAME(snd_pcm_hw_params_set_format)}, { + "snd_pcm_hw_params_set_channels", + (void **) (char *) &SDL_NAME(snd_pcm_hw_params_set_channels)}, { + "snd_pcm_hw_params_get_channels", + (void **) (char *) &SDL_NAME(snd_pcm_hw_params_get_channels)}, { + "snd_pcm_hw_params_set_rate_near", + (void **) (char *) &SDL_NAME(snd_pcm_hw_params_set_rate_near)}, { + "snd_pcm_hw_params_set_period_size_near", (void **) (char *) + &SDL_NAME(snd_pcm_hw_params_set_period_size_near)}, { + "snd_pcm_hw_params_get_period_size", + (void **) (char *) &SDL_NAME(snd_pcm_hw_params_get_period_size)}, + { + "snd_pcm_hw_params_set_periods_near", (void **) (char *) + &SDL_NAME(snd_pcm_hw_params_set_periods_near)}, { + "snd_pcm_hw_params_get_periods", + (void **) (char *) &SDL_NAME(snd_pcm_hw_params_get_periods)}, { + "snd_pcm_hw_params", (void **) (char *) &SDL_NAME(snd_pcm_hw_params)}, { + "snd_pcm_sw_params_current", + (void **) (char *) &SDL_NAME(snd_pcm_sw_params_current)}, { + "snd_pcm_sw_params_set_start_threshold", (void **) (char *) + &SDL_NAME(snd_pcm_sw_params_set_start_threshold)}, { + "snd_pcm_sw_params_set_avail_min", + (void **) (char *) &SDL_NAME(snd_pcm_sw_params_set_avail_min)}, { + "snd_pcm_sw_params", (void **) (char *) &SDL_NAME(snd_pcm_sw_params)}, { +"snd_pcm_nonblock", (void **) (char *) &SDL_NAME(snd_pcm_nonblock)},}; + +static void +UnloadALSALibrary(void) +{ + if (alsa_loaded) { /* SDL_UnloadObject(alsa_handle);*/ - dlclose(alsa_handle); - alsa_handle = NULL; - alsa_loaded = 0; - } + dlclose(alsa_handle); + alsa_handle = NULL; + alsa_loaded = 0; + } } -static int LoadALSALibrary(void) { - int i, retval = -1; +static int +LoadALSALibrary(void) +{ + int i, retval = -1; /* alsa_handle = SDL_LoadObject(alsa_library);*/ - alsa_handle = dlopen(alsa_library,RTLD_NOW); - if (alsa_handle) { - alsa_loaded = 1; - retval = 0; - for (i = 0; i < SDL_arraysize(alsa_functions); i++) { + alsa_handle = dlopen(alsa_library, RTLD_NOW); + if (alsa_handle) { + alsa_loaded = 1; + retval = 0; + for (i = 0; i < SDL_arraysize(alsa_functions); i++) { /* *alsa_functions[i].func = SDL_LoadFunction(alsa_handle,alsa_functions[i].name);*/ #if HAVE_DLVSYM - *alsa_functions[i].func = dlvsym(alsa_handle,alsa_functions[i].name,"ALSA_0.9"); - if (!*alsa_functions[i].func) + *alsa_functions[i].func = + dlvsym(alsa_handle, alsa_functions[i].name, "ALSA_0.9"); + if (!*alsa_functions[i].func) #endif - *alsa_functions[i].func = dlsym(alsa_handle,alsa_functions[i].name); - if (!*alsa_functions[i].func) { - retval = -1; - UnloadALSALibrary(); - break; - } - } - } - return retval; + *alsa_functions[i].func = + dlsym(alsa_handle, alsa_functions[i].name); + if (!*alsa_functions[i].func) { + retval = -1; + UnloadALSALibrary(); + break; + } + } + } + return retval; } #else -static void UnloadALSALibrary(void) { - return; +static void +UnloadALSALibrary(void) +{ + return; } -static int LoadALSALibrary(void) { - return 0; +static int +LoadALSALibrary(void) +{ + return 0; } #endif /* SDL_AUDIO_DRIVER_ALSA_DYNAMIC */ -static const char *get_audio_device(int channels) +static const char * +get_audio_device(int channels) { - const char *device; - - device = SDL_getenv("AUDIODEV"); /* Is there a standard variable name? */ - if ( device == NULL ) { - if (channels == 6) device = "surround51"; - else if (channels == 4) device = "surround40"; - else device = DEFAULT_DEVICE; - } - return device; + const char *device; + + device = SDL_getenv("AUDIODEV"); /* Is there a standard variable name? */ + if (device == NULL) { + if (channels == 6) + device = "surround51"; + else if (channels == 4) + device = "surround40"; + else + device = DEFAULT_DEVICE; + } + return device; } /* Audio driver bootstrap functions */ -static int Audio_Available(void) +static int +Audio_Available(void) { - int available; - int status; - snd_pcm_t *handle; - - available = 0; - if (LoadALSALibrary() < 0) { - return available; - } - status = SDL_NAME(snd_pcm_open)(&handle, get_audio_device(2), SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK); - if ( status >= 0 ) { - available = 1; - SDL_NAME(snd_pcm_close)(handle); - } - UnloadALSALibrary(); - return(available); + int available; + int status; + snd_pcm_t *handle; + + available = 0; + if (LoadALSALibrary() < 0) { + return available; + } + status = + SDL_NAME(snd_pcm_open) (&handle, get_audio_device(2), + SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK); + if (status >= 0) { + available = 1; + SDL_NAME(snd_pcm_close) (handle); + } + UnloadALSALibrary(); + return (available); } -static void Audio_DeleteDevice(SDL_AudioDevice *device) +static void +Audio_DeleteDevice(SDL_AudioDevice * device) { - SDL_free(device->hidden); - SDL_free(device); - UnloadALSALibrary(); + SDL_free(device->hidden); + SDL_free(device); + UnloadALSALibrary(); } -static SDL_AudioDevice *Audio_CreateDevice(int devindex) +static SDL_AudioDevice * +Audio_CreateDevice(int devindex) { - SDL_AudioDevice *this; - - /* Initialize all variables that we clean on shutdown */ - LoadALSALibrary(); - this = (SDL_AudioDevice *)SDL_malloc(sizeof(SDL_AudioDevice)); - if ( this ) { - SDL_memset(this, 0, (sizeof *this)); - this->hidden = (struct SDL_PrivateAudioData *) - SDL_malloc((sizeof *this->hidden)); - } - if ( (this == NULL) || (this->hidden == NULL) ) { - SDL_OutOfMemory(); - if ( this ) { - SDL_free(this); - } - return(0); - } - SDL_memset(this->hidden, 0, (sizeof *this->hidden)); - - /* Set the function pointers */ - this->OpenAudio = ALSA_OpenAudio; - this->WaitAudio = ALSA_WaitAudio; - this->PlayAudio = ALSA_PlayAudio; - this->GetAudioBuf = ALSA_GetAudioBuf; - this->CloseAudio = ALSA_CloseAudio; - - this->free = Audio_DeleteDevice; - - return this; + SDL_AudioDevice *this; + + /* Initialize all variables that we clean on shutdown */ + LoadALSALibrary(); + this = (SDL_AudioDevice *) SDL_malloc(sizeof(SDL_AudioDevice)); + if (this) { + SDL_memset(this, 0, (sizeof *this)); + this->hidden = (struct SDL_PrivateAudioData *) + SDL_malloc((sizeof *this->hidden)); + } + if ((this == NULL) || (this->hidden == NULL)) { + SDL_OutOfMemory(); + if (this) { + SDL_free(this); + } + return (0); + } + SDL_memset(this->hidden, 0, (sizeof *this->hidden)); + + /* Set the function pointers */ + this->OpenAudio = ALSA_OpenAudio; + this->WaitAudio = ALSA_WaitAudio; + this->PlayAudio = ALSA_PlayAudio; + this->GetAudioBuf = ALSA_GetAudioBuf; + this->CloseAudio = ALSA_CloseAudio; + + this->free = Audio_DeleteDevice; + + return this; } AudioBootStrap ALSA_bootstrap = { - DRIVER_NAME, "ALSA 0.9 PCM audio", - Audio_Available, Audio_CreateDevice + DRIVER_NAME, "ALSA 0.9 PCM audio", + Audio_Available, Audio_CreateDevice }; /* This function waits until it is possible to write a full sound buffer */ -static void ALSA_WaitAudio(_THIS) +static void +ALSA_WaitAudio(_THIS) { - /* Check to see if the thread-parent process is still alive */ - { static int cnt = 0; - /* Note that this only works with thread implementations - that use a different process id for each thread. - */ - if (parent && (((++cnt)%10) == 0)) { /* Check every 10 loops */ - if ( kill(parent, 0) < 0 ) { - this->enabled = 0; - } - } - } + /* Check to see if the thread-parent process is still alive */ + { + static int cnt = 0; + /* Note that this only works with thread implementations + that use a different process id for each thread. + */ + if (parent && (((++cnt) % 10) == 0)) { /* Check every 10 loops */ + if (kill(parent, 0) < 0) { + this->enabled = 0; + } + } + } } @@ -280,10 +367,26 @@ static void ALSA_WaitAudio(_THIS) tmp = ptr[3]; ptr[3] = ptr[5]; ptr[5] = tmp; \ } -static __inline__ void swizzle_alsa_channels_6_64bit(_THIS) { SWIZ6(Uint64); } -static __inline__ void swizzle_alsa_channels_6_32bit(_THIS) { SWIZ6(Uint32); } -static __inline__ void swizzle_alsa_channels_6_16bit(_THIS) { SWIZ6(Uint16); } -static __inline__ void swizzle_alsa_channels_6_8bit(_THIS) { SWIZ6(Uint8); } +static __inline__ void +swizzle_alsa_channels_6_64bit(_THIS) +{ + SWIZ6(Uint64); +} +static __inline__ void +swizzle_alsa_channels_6_32bit(_THIS) +{ + SWIZ6(Uint32); +} +static __inline__ void +swizzle_alsa_channels_6_16bit(_THIS) +{ + SWIZ6(Uint16); +} +static __inline__ void +swizzle_alsa_channels_6_8bit(_THIS) +{ + SWIZ6(Uint8); +} #undef SWIZ6 @@ -292,10 +395,11 @@ static __inline__ void swizzle_alsa_channels_6_8bit(_THIS) { SWIZ6(Uint8); } * Called right before feeding this->mixbuf to the hardware. Swizzle channels * from Windows/Mac order to the format alsalib will want. */ -static __inline__ void swizzle_alsa_channels(_THIS) +static __inline__ void +swizzle_alsa_channels(_THIS) { if (this->spec.channels == 6) { - const Uint16 fmtsize = (this->spec.format & 0xFF); /* bits/channel. */ + const Uint16 fmtsize = (this->spec.format & 0xFF); /* bits/channel. */ if (fmtsize == 16) swizzle_alsa_channels_6_16bit(this); else if (fmtsize == 8) @@ -310,173 +414,198 @@ static __inline__ void swizzle_alsa_channels(_THIS) } -static void ALSA_PlayAudio(_THIS) +static void +ALSA_PlayAudio(_THIS) { - int status; - int sample_len; - signed short *sample_buf; - - swizzle_alsa_channels(this); - - sample_len = this->spec.samples; - sample_buf = (signed short *)mixbuf; - - while ( sample_len > 0 ) { - status = SDL_NAME(snd_pcm_writei)(pcm_handle, sample_buf, sample_len); - if ( status < 0 ) { - if ( status == -EAGAIN ) { - SDL_Delay(1); - continue; - } - if ( status == -ESTRPIPE ) { - do { - SDL_Delay(1); - status = SDL_NAME(snd_pcm_resume)(pcm_handle); - } while ( status == -EAGAIN ); - } - if ( status < 0 ) { - status = SDL_NAME(snd_pcm_prepare)(pcm_handle); - } - if ( status < 0 ) { - /* Hmm, not much we can do - abort */ - this->enabled = 0; - return; - } - continue; - } - sample_buf += status * this->spec.channels; - sample_len -= status; - } + int status; + int sample_len; + signed short *sample_buf; + + swizzle_alsa_channels(this); + + sample_len = this->spec.samples; + sample_buf = (signed short *) mixbuf; + + while (sample_len > 0) { + status = + SDL_NAME(snd_pcm_writei) (pcm_handle, sample_buf, sample_len); + if (status < 0) { + if (status == -EAGAIN) { + SDL_Delay(1); + continue; + } + if (status == -ESTRPIPE) { + do { + SDL_Delay(1); + status = SDL_NAME(snd_pcm_resume) (pcm_handle); + } while (status == -EAGAIN); + } + if (status < 0) { + status = SDL_NAME(snd_pcm_prepare) (pcm_handle); + } + if (status < 0) { + /* Hmm, not much we can do - abort */ + this->enabled = 0; + return; + } + continue; + } + sample_buf += status * this->spec.channels; + sample_len -= status; + } } -static Uint8 *ALSA_GetAudioBuf(_THIS) +static Uint8 * +ALSA_GetAudioBuf(_THIS) { - return(mixbuf); + return (mixbuf); } -static void ALSA_CloseAudio(_THIS) +static void +ALSA_CloseAudio(_THIS) { - if ( mixbuf != NULL ) { - SDL_FreeAudioMem(mixbuf); - mixbuf = NULL; - } - if ( pcm_handle ) { - SDL_NAME(snd_pcm_drain)(pcm_handle); - SDL_NAME(snd_pcm_close)(pcm_handle); - pcm_handle = NULL; - } + if (mixbuf != NULL) { + SDL_FreeAudioMem(mixbuf); + mixbuf = NULL; + } + if (pcm_handle) { + SDL_NAME(snd_pcm_drain) (pcm_handle); + SDL_NAME(snd_pcm_close) (pcm_handle); + pcm_handle = NULL; + } } -static int ALSA_OpenAudio(_THIS, SDL_AudioSpec *spec) +static int +ALSA_OpenAudio(_THIS, SDL_AudioSpec * spec) { - int status; - snd_pcm_hw_params_t *hwparams; - snd_pcm_sw_params_t *swparams; - snd_pcm_format_t format; - snd_pcm_uframes_t frames; - Uint16 test_format; - - /* Open the audio device */ - /* Name of device should depend on # channels in spec */ - status = SDL_NAME(snd_pcm_open)(&pcm_handle, get_audio_device(spec->channels), SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK); - - if ( status < 0 ) { - SDL_SetError("Couldn't open audio device: %s", SDL_NAME(snd_strerror)(status)); - return(-1); - } - - /* Figure out what the hardware is capable of */ - snd_pcm_hw_params_alloca(&hwparams); - status = SDL_NAME(snd_pcm_hw_params_any)(pcm_handle, hwparams); - if ( status < 0 ) { - SDL_SetError("Couldn't get hardware config: %s", SDL_NAME(snd_strerror)(status)); - ALSA_CloseAudio(this); - return(-1); - } - - /* SDL only uses interleaved sample output */ - status = SDL_NAME(snd_pcm_hw_params_set_access)(pcm_handle, hwparams, SND_PCM_ACCESS_RW_INTERLEAVED); - if ( status < 0 ) { - SDL_SetError("Couldn't set interleaved access: %s", SDL_NAME(snd_strerror)(status)); - ALSA_CloseAudio(this); - return(-1); - } - - /* Try for a closest match on audio format */ - status = -1; - for ( test_format = SDL_FirstAudioFormat(spec->format); - test_format && (status < 0); ) { - switch ( test_format ) { - case AUDIO_U8: - format = SND_PCM_FORMAT_U8; - break; - case AUDIO_S8: - format = SND_PCM_FORMAT_S8; - break; - case AUDIO_S16LSB: - format = SND_PCM_FORMAT_S16_LE; - break; - case AUDIO_S16MSB: - format = SND_PCM_FORMAT_S16_BE; - break; - case AUDIO_U16LSB: - format = SND_PCM_FORMAT_U16_LE; - break; - case AUDIO_U16MSB: - format = SND_PCM_FORMAT_U16_BE; - break; - default: - format = 0; - break; - } - if ( format != 0 ) { - status = SDL_NAME(snd_pcm_hw_params_set_format)(pcm_handle, hwparams, format); - } - if ( status < 0 ) { - test_format = SDL_NextAudioFormat(); - } - } - if ( status < 0 ) { - SDL_SetError("Couldn't find any hardware audio formats"); - ALSA_CloseAudio(this); - return(-1); - } - spec->format = test_format; - - /* Set the number of channels */ - status = SDL_NAME(snd_pcm_hw_params_set_channels)(pcm_handle, hwparams, spec->channels); - if ( status < 0 ) { - status = SDL_NAME(snd_pcm_hw_params_get_channels)(hwparams); - if ( (status <= 0) || (status > 2) ) { - SDL_SetError("Couldn't set audio channels"); - ALSA_CloseAudio(this); - return(-1); - } - spec->channels = status; - } - - /* Set the audio rate */ - status = SDL_NAME(snd_pcm_hw_params_set_rate_near)(pcm_handle, hwparams, spec->freq, NULL); - if ( status < 0 ) { - SDL_SetError("Couldn't set audio frequency: %s", SDL_NAME(snd_strerror)(status)); - ALSA_CloseAudio(this); - return(-1); - } - spec->freq = status; - - /* Set the buffer size, in samples */ - frames = spec->samples; - frames = SDL_NAME(snd_pcm_hw_params_set_period_size_near)(pcm_handle, hwparams, frames, NULL); - spec->samples = frames; - SDL_NAME(snd_pcm_hw_params_set_periods_near)(pcm_handle, hwparams, 2, NULL); - - /* "set" the hardware with the desired parameters */ - status = SDL_NAME(snd_pcm_hw_params)(pcm_handle, hwparams); - if ( status < 0 ) { - SDL_SetError("Couldn't set hardware audio parameters: %s", SDL_NAME(snd_strerror)(status)); - ALSA_CloseAudio(this); - return(-1); - } + int status; + snd_pcm_hw_params_t *hwparams; + snd_pcm_sw_params_t *swparams; + snd_pcm_format_t format; + snd_pcm_uframes_t frames; + Uint16 test_format; + + /* Open the audio device */ + /* Name of device should depend on # channels in spec */ + status = + SDL_NAME(snd_pcm_open) (&pcm_handle, + get_audio_device(spec->channels), + SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK); + + if (status < 0) { + SDL_SetError("Couldn't open audio device: %s", + SDL_NAME(snd_strerror) (status)); + return (-1); + } + + /* Figure out what the hardware is capable of */ + snd_pcm_hw_params_alloca(&hwparams); + status = SDL_NAME(snd_pcm_hw_params_any) (pcm_handle, hwparams); + if (status < 0) { + SDL_SetError("Couldn't get hardware config: %s", + SDL_NAME(snd_strerror) (status)); + ALSA_CloseAudio(this); + return (-1); + } + + /* SDL only uses interleaved sample output */ + status = + SDL_NAME(snd_pcm_hw_params_set_access) (pcm_handle, hwparams, + SND_PCM_ACCESS_RW_INTERLEAVED); + if (status < 0) { + SDL_SetError("Couldn't set interleaved access: %s", + SDL_NAME(snd_strerror) (status)); + ALSA_CloseAudio(this); + return (-1); + } + + /* Try for a closest match on audio format */ + status = -1; + for (test_format = SDL_FirstAudioFormat(spec->format); + test_format && (status < 0);) { + switch (test_format) { + case AUDIO_U8: + format = SND_PCM_FORMAT_U8; + break; + case AUDIO_S8: + format = SND_PCM_FORMAT_S8; + break; + case AUDIO_S16LSB: + format = SND_PCM_FORMAT_S16_LE; + break; + case AUDIO_S16MSB: + format = SND_PCM_FORMAT_S16_BE; + break; + case AUDIO_U16LSB: + format = SND_PCM_FORMAT_U16_LE; + break; + case AUDIO_U16MSB: + format = SND_PCM_FORMAT_U16_BE; + break; + default: + format = 0; + break; + } + if (format != 0) { + status = + SDL_NAME(snd_pcm_hw_params_set_format) (pcm_handle, + hwparams, format); + } + if (status < 0) { + test_format = SDL_NextAudioFormat(); + } + } + if (status < 0) { + SDL_SetError("Couldn't find any hardware audio formats"); + ALSA_CloseAudio(this); + return (-1); + } + spec->format = test_format; + + /* Set the number of channels */ + status = + SDL_NAME(snd_pcm_hw_params_set_channels) (pcm_handle, hwparams, + spec->channels); + if (status < 0) { + status = SDL_NAME(snd_pcm_hw_params_get_channels) (hwparams); + if ((status <= 0) || (status > 2)) { + SDL_SetError("Couldn't set audio channels"); + ALSA_CloseAudio(this); + return (-1); + } + spec->channels = status; + } + + /* Set the audio rate */ + status = + SDL_NAME(snd_pcm_hw_params_set_rate_near) (pcm_handle, hwparams, + spec->freq, NULL); + if (status < 0) { + SDL_SetError("Couldn't set audio frequency: %s", + SDL_NAME(snd_strerror) (status)); + ALSA_CloseAudio(this); + return (-1); + } + spec->freq = status; + + /* Set the buffer size, in samples */ + frames = spec->samples; + frames = + SDL_NAME(snd_pcm_hw_params_set_period_size_near) (pcm_handle, + hwparams, frames, + NULL); + spec->samples = frames; + SDL_NAME(snd_pcm_hw_params_set_periods_near) (pcm_handle, hwparams, 2, + NULL); + + /* "set" the hardware with the desired parameters */ + status = SDL_NAME(snd_pcm_hw_params) (pcm_handle, hwparams); + if (status < 0) { + SDL_SetError("Couldn't set hardware audio parameters: %s", + SDL_NAME(snd_strerror) (status)); + ALSA_CloseAudio(this); + return (-1); + } /* This is useful for debugging... */ /* @@ -488,51 +617,61 @@ static int ALSA_OpenAudio(_THIS, SDL_AudioSpec *spec) } */ - /* Set the software parameters */ - snd_pcm_sw_params_alloca(&swparams); - status = SDL_NAME(snd_pcm_sw_params_current)(pcm_handle, swparams); - if ( status < 0 ) { - SDL_SetError("Couldn't get software config: %s", SDL_NAME(snd_strerror)(status)); - ALSA_CloseAudio(this); - return(-1); - } - status = SDL_NAME(snd_pcm_sw_params_set_start_threshold)(pcm_handle, swparams, 0); - if ( status < 0 ) { - SDL_SetError("Couldn't set start threshold: %s", SDL_NAME(snd_strerror)(status)); - ALSA_CloseAudio(this); - return(-1); - } - status = SDL_NAME(snd_pcm_sw_params_set_avail_min)(pcm_handle, swparams, frames); - if ( status < 0 ) { - SDL_SetError("Couldn't set avail min: %s", SDL_NAME(snd_strerror)(status)); - ALSA_CloseAudio(this); - return(-1); - } - status = SDL_NAME(snd_pcm_sw_params)(pcm_handle, swparams); - if ( status < 0 ) { - SDL_SetError("Couldn't set software audio parameters: %s", SDL_NAME(snd_strerror)(status)); - ALSA_CloseAudio(this); - return(-1); - } - - /* Calculate the final parameters for this audio specification */ - SDL_CalculateAudioSpec(spec); - - /* Allocate mixing buffer */ - mixlen = spec->size; - mixbuf = (Uint8 *)SDL_AllocAudioMem(mixlen); - if ( mixbuf == NULL ) { - ALSA_CloseAudio(this); - return(-1); - } - SDL_memset(mixbuf, spec->silence, spec->size); - - /* Get the parent process id (we're the parent of the audio thread) */ - parent = getpid(); - - /* Switch to blocking mode for playback */ - SDL_NAME(snd_pcm_nonblock)(pcm_handle, 0); - - /* We're ready to rock and roll. :-) */ - return(0); + /* Set the software parameters */ + snd_pcm_sw_params_alloca(&swparams); + status = SDL_NAME(snd_pcm_sw_params_current) (pcm_handle, swparams); + if (status < 0) { + SDL_SetError("Couldn't get software config: %s", + SDL_NAME(snd_strerror) (status)); + ALSA_CloseAudio(this); + return (-1); + } + status = + SDL_NAME(snd_pcm_sw_params_set_start_threshold) (pcm_handle, + swparams, 0); + if (status < 0) { + SDL_SetError("Couldn't set start threshold: %s", + SDL_NAME(snd_strerror) (status)); + ALSA_CloseAudio(this); + return (-1); + } + status = + SDL_NAME(snd_pcm_sw_params_set_avail_min) (pcm_handle, swparams, + frames); + if (status < 0) { + SDL_SetError("Couldn't set avail min: %s", + SDL_NAME(snd_strerror) (status)); + ALSA_CloseAudio(this); + return (-1); + } + status = SDL_NAME(snd_pcm_sw_params) (pcm_handle, swparams); + if (status < 0) { + SDL_SetError("Couldn't set software audio parameters: %s", + SDL_NAME(snd_strerror) (status)); + ALSA_CloseAudio(this); + return (-1); + } + + /* Calculate the final parameters for this audio specification */ + SDL_CalculateAudioSpec(spec); + + /* Allocate mixing buffer */ + mixlen = spec->size; + mixbuf = (Uint8 *) SDL_AllocAudioMem(mixlen); + if (mixbuf == NULL) { + ALSA_CloseAudio(this); + return (-1); + } + SDL_memset(mixbuf, spec->silence, spec->size); + + /* Get the parent process id (we're the parent of the audio thread) */ + parent = getpid(); + + /* Switch to blocking mode for playback */ + SDL_NAME(snd_pcm_nonblock) (pcm_handle, 0); + + /* We're ready to rock and roll. :-) */ + return (0); } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/audio/alsa/SDL_alsa_audio.h b/src/audio/alsa/SDL_alsa_audio.h index fd9ac0381..aa2eb786a 100644 --- a/src/audio/alsa/SDL_alsa_audio.h +++ b/src/audio/alsa/SDL_alsa_audio.h @@ -33,16 +33,17 @@ /* Hidden "this" pointer for the video functions */ #define _THIS SDL_AudioDevice *this -struct SDL_PrivateAudioData { - /* The audio device handle */ - snd_pcm_t *pcm_handle; +struct SDL_PrivateAudioData +{ + /* The audio device handle */ + snd_pcm_t *pcm_handle; - /* The parent process id, to detect when application quits */ - pid_t parent; + /* The parent process id, to detect when application quits */ + pid_t parent; - /* Raw mixing buffer */ - Uint8 *mixbuf; - int mixlen; + /* Raw mixing buffer */ + Uint8 *mixbuf; + int mixlen; }; /* Old variable names */ @@ -52,3 +53,4 @@ struct SDL_PrivateAudioData { #define mixlen (this->hidden->mixlen) #endif /* _ALSA_PCM_audio_h */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/audio/amigaos/SDL_ahiaudio.c b/src/audio/amigaos/SDL_ahiaudio.c index c9a4c1a4f..47f6f5220 100644 --- a/src/audio/amigaos/SDL_ahiaudio.c +++ b/src/audio/amigaos/SDL_ahiaudio.c @@ -28,310 +28,321 @@ #include "SDL_ahiaudio.h" /* Audio driver functions */ -static int AHI_OpenAudio(_THIS, SDL_AudioSpec *spec); +static int AHI_OpenAudio(_THIS, SDL_AudioSpec * spec); static void AHI_WaitAudio(_THIS); static void AHI_PlayAudio(_THIS); static Uint8 *AHI_GetAudioBuf(_THIS); static void AHI_CloseAudio(_THIS); #ifndef __SASC - #define mymalloc(x) AllocVec(x,MEMF_PUBLIC) - #define myfree FreeVec +#define mymalloc(x) AllocVec(x,MEMF_PUBLIC) +#define myfree FreeVec #else - #define mymalloc malloc - #define myfree free +#define mymalloc malloc +#define myfree free #endif /* Audio driver bootstrap functions */ -static int Audio_Available(void) +static int +Audio_Available(void) { - int ok=0; - struct MsgPort *p; - struct AHIRequest *req; - - if(p=CreateMsgPort()) - { - if(req=(struct AHIRequest *)CreateIORequest(p,sizeof(struct AHIRequest))) - { - req->ahir_Version=4; - - if(!OpenDevice(AHINAME,0,(struct IORequest *)req,NULL)) - { - D(bug("AHI available.\n")); - ok=1; - CloseDevice((struct IORequest *)req); - } - DeleteIORequest((struct IORequest *)req); - } - DeleteMsgPort(p); - } - - D(if(!ok) bug("AHI not available\n")); - return ok; + int ok = 0; + struct MsgPort *p; + struct AHIRequest *req; + + if (p = CreateMsgPort()) { + if (req = + (struct AHIRequest *) CreateIORequest(p, + sizeof(struct + AHIRequest))) { + req->ahir_Version = 4; + + if (!OpenDevice(AHINAME, 0, (struct IORequest *) req, NULL)) { + D(bug("AHI available.\n")); + ok = 1; + CloseDevice((struct IORequest *) req); + } + DeleteIORequest((struct IORequest *) req); + } + DeleteMsgPort(p); + } + + D(if (!ok) bug("AHI not available\n")); + return ok; } -static void Audio_DeleteDevice(SDL_AudioDevice *device) +static void +Audio_DeleteDevice(SDL_AudioDevice * device) { - SDL_free(device->hidden); - SDL_free(device); + SDL_free(device->hidden); + SDL_free(device); } -static SDL_AudioDevice *Audio_CreateDevice(int devindex) +static SDL_AudioDevice * +Audio_CreateDevice(int devindex) { - SDL_AudioDevice *this; + SDL_AudioDevice *this; #ifndef NO_AMIGADEBUG - D(bug("AHI created...\n")); + D(bug("AHI created...\n")); #endif - /* Initialize all variables that we clean on shutdown */ - this = (SDL_AudioDevice *)SDL_malloc(sizeof(SDL_AudioDevice)); - if ( this ) { - SDL_memset(this, 0, (sizeof *this)); - this->hidden = (struct SDL_PrivateAudioData *) - SDL_malloc((sizeof *this->hidden)); - } - if ( (this == NULL) || (this->hidden == NULL) ) { - SDL_OutOfMemory(); - if ( this ) { - SDL_free(this); - } - return(0); - } - SDL_memset(this->hidden, 0, (sizeof *this->hidden)); - - /* Set the function pointers */ - this->OpenAudio = AHI_OpenAudio; - this->WaitAudio = AHI_WaitAudio; - this->PlayAudio = AHI_PlayAudio; - this->GetAudioBuf = AHI_GetAudioBuf; - this->CloseAudio = AHI_CloseAudio; - - this->free = Audio_DeleteDevice; - - return this; + /* Initialize all variables that we clean on shutdown */ + this = (SDL_AudioDevice *) SDL_malloc(sizeof(SDL_AudioDevice)); + if (this) { + SDL_memset(this, 0, (sizeof *this)); + this->hidden = (struct SDL_PrivateAudioData *) + SDL_malloc((sizeof *this->hidden)); + } + if ((this == NULL) || (this->hidden == NULL)) { + SDL_OutOfMemory(); + if (this) { + SDL_free(this); + } + return (0); + } + SDL_memset(this->hidden, 0, (sizeof *this->hidden)); + + /* Set the function pointers */ + this->OpenAudio = AHI_OpenAudio; + this->WaitAudio = AHI_WaitAudio; + this->PlayAudio = AHI_PlayAudio; + this->GetAudioBuf = AHI_GetAudioBuf; + this->CloseAudio = AHI_CloseAudio; + + this->free = Audio_DeleteDevice; + + return this; } AudioBootStrap AHI_bootstrap = { - "AHI", Audio_Available, Audio_CreateDevice + "AHI", Audio_Available, Audio_CreateDevice }; -void static AHI_WaitAudio(_THIS) +void static +AHI_WaitAudio(_THIS) { - if(!CheckIO((struct IORequest *)audio_req[current_buffer])) - { - WaitIO((struct IORequest *)audio_req[current_buffer]); -// AbortIO((struct IORequest *)audio_req[current_buffer]); - } + if (!CheckIO((struct IORequest *) audio_req[current_buffer])) { + WaitIO((struct IORequest *) audio_req[current_buffer]); +// AbortIO((struct IORequest *)audio_req[current_buffer]); + } } -static void AHI_PlayAudio(_THIS) +static void +AHI_PlayAudio(_THIS) { - if(playing>1) - WaitIO((struct IORequest *)audio_req[current_buffer]); - - /* Write the audio data out */ - audio_req[current_buffer] -> ahir_Std. io_Message.mn_Node.ln_Pri = 60; - audio_req[current_buffer] -> ahir_Std. io_Data = mixbuf[current_buffer]; - audio_req[current_buffer] -> ahir_Std. io_Length = this->hidden->size; - audio_req[current_buffer] -> ahir_Std. io_Offset = 0; - audio_req[current_buffer] -> ahir_Std . io_Command = CMD_WRITE; - audio_req[current_buffer] -> ahir_Frequency = this->hidden->freq; - audio_req[current_buffer] -> ahir_Volume = 0x10000; - audio_req[current_buffer] -> ahir_Type = this->hidden->type; - audio_req[current_buffer] -> ahir_Position = 0x8000; - audio_req[current_buffer] -> ahir_Link = (playing>0 ? audio_req[current_buffer^1] : NULL); - - SendIO((struct IORequest *)audio_req[current_buffer]); - current_buffer^=1; - - playing++; + if (playing > 1) + WaitIO((struct IORequest *) audio_req[current_buffer]); + + /* Write the audio data out */ + audio_req[current_buffer]->ahir_Std.io_Message.mn_Node.ln_Pri = 60; + audio_req[current_buffer]->ahir_Std.io_Data = mixbuf[current_buffer]; + audio_req[current_buffer]->ahir_Std.io_Length = this->hidden->size; + audio_req[current_buffer]->ahir_Std.io_Offset = 0; + audio_req[current_buffer]->ahir_Std.io_Command = CMD_WRITE; + audio_req[current_buffer]->ahir_Frequency = this->hidden->freq; + audio_req[current_buffer]->ahir_Volume = 0x10000; + audio_req[current_buffer]->ahir_Type = this->hidden->type; + audio_req[current_buffer]->ahir_Position = 0x8000; + audio_req[current_buffer]->ahir_Link = + (playing > 0 ? audio_req[current_buffer ^ 1] : NULL); + + SendIO((struct IORequest *) audio_req[current_buffer]); + current_buffer ^= 1; + + playing++; } -static Uint8 *AHI_GetAudioBuf(_THIS) +static Uint8 * +AHI_GetAudioBuf(_THIS) { - return(mixbuf[current_buffer]); + return (mixbuf[current_buffer]); } -static void AHI_CloseAudio(_THIS) +static void +AHI_CloseAudio(_THIS) { - D(bug("Closing audio...\n")); + D(bug("Closing audio...\n")); - playing=0; + playing = 0; - if(audio_req[0]) - { - if(audio_req[1]) - { - D(bug("Break req[1]...\n")); + if (audio_req[0]) { + if (audio_req[1]) { + D(bug("Break req[1]...\n")); - AbortIO((struct IORequest *)audio_req[1]); - WaitIO((struct IORequest *)audio_req[1]); - } + AbortIO((struct IORequest *) audio_req[1]); + WaitIO((struct IORequest *) audio_req[1]); + } - D(bug("Break req[0]...\n")); + D(bug("Break req[0]...\n")); - AbortIO((struct IORequest *)audio_req[0]); - WaitIO((struct IORequest *)audio_req[0]); + AbortIO((struct IORequest *) audio_req[0]); + WaitIO((struct IORequest *) audio_req[0]); - if(audio_req[1]) - { - D(bug("Break AGAIN req[1]...\n")); - AbortIO((struct IORequest *)audio_req[1]); - WaitIO((struct IORequest *)audio_req[1]); - } + if (audio_req[1]) { + D(bug("Break AGAIN req[1]...\n")); + AbortIO((struct IORequest *) audio_req[1]); + WaitIO((struct IORequest *) audio_req[1]); + } // Double abort to be sure to break the dbuffering process. - SDL_Delay(200); - - D(bug("Reqs breaked, closing device...\n")); - CloseDevice((struct IORequest *)audio_req[0]); - D(bug("Device closed, freeing memory...\n")); - myfree(audio_req[1]); - D(bug("Memory freed, deleting IOReq...\n")); - DeleteIORequest((struct IORequest *)audio_req[0]); - audio_req[0]=audio_req[1]=NULL; - } - - D(bug("Freeing mixbuf[0]...\n")); - if ( mixbuf[0] != NULL ) { - myfree(mixbuf[0]); -// SDL_FreeAudioMem(mixbuf[0]); - mixbuf[0] = NULL; - } - - D(bug("Freeing mixbuf[1]...\n")); - if ( mixbuf[1] != NULL ) { - myfree(mixbuf[1]); -// SDL_FreeAudioMem(mixbuf[1]); - mixbuf[1] = NULL; - } - - D(bug("Freeing audio_port...\n")); - - if ( audio_port != NULL ) { - DeleteMsgPort(audio_port); - audio_port = NULL; - } - D(bug("...done!\n")); + SDL_Delay(200); + + D(bug("Reqs breaked, closing device...\n")); + CloseDevice((struct IORequest *) audio_req[0]); + D(bug("Device closed, freeing memory...\n")); + myfree(audio_req[1]); + D(bug("Memory freed, deleting IOReq...\n")); + DeleteIORequest((struct IORequest *) audio_req[0]); + audio_req[0] = audio_req[1] = NULL; + } + + D(bug("Freeing mixbuf[0]...\n")); + if (mixbuf[0] != NULL) { + myfree(mixbuf[0]); +// SDL_FreeAudioMem(mixbuf[0]); + mixbuf[0] = NULL; + } + + D(bug("Freeing mixbuf[1]...\n")); + if (mixbuf[1] != NULL) { + myfree(mixbuf[1]); +// SDL_FreeAudioMem(mixbuf[1]); + mixbuf[1] = NULL; + } + + D(bug("Freeing audio_port...\n")); + + if (audio_port != NULL) { + DeleteMsgPort(audio_port); + audio_port = NULL; + } + D(bug("...done!\n")); } -static int AHI_OpenAudio(_THIS, SDL_AudioSpec *spec) -{ -// int width; - - D(bug("AHI opening...\n")); - - /* Determine the audio parameters from the AudioSpec */ - switch ( spec->format & 0xFF ) { - - case 8: { /* Signed 8 bit audio data */ - D(bug("Samples a 8 bit...\n")); - spec->format = AUDIO_S8; - this->hidden->bytespersample=1; - if(spec->channels<2) - this->hidden->type = AHIST_M8S; - else - this->hidden->type = AHIST_S8S; - } - break; - - case 16: { /* Signed 16 bit audio data */ - D(bug("Samples a 16 bit...\n")); - spec->format = AUDIO_S16MSB; - this->hidden->bytespersample=2; - if(spec->channels<2) - this->hidden->type = AHIST_M16S; - else - this->hidden->type = AHIST_S16S; - } - break; - - default: { - SDL_SetError("Unsupported audio format"); - return(-1); - } - } - - if(spec->channels!=1 && spec->channels!=2) - { - D(bug("Wrong channel number!\n")); - SDL_SetError("Channel number non supported"); - return -1; - } - - D(bug("Before CalculateAudioSpec\n")); - /* Update the fragment size as size in bytes */ - SDL_CalculateAudioSpec(spec); - - D(bug("Before CreateMsgPort\n")); - - if(!(audio_port=CreateMsgPort())) - { - SDL_SetError("Unable to create a MsgPort"); - return -1; - } - - D(bug("Before CreateIORequest\n")); - - if(!(audio_req[0]=(struct AHIRequest *)CreateIORequest(audio_port,sizeof(struct AHIRequest)))) - { - SDL_SetError("Unable to create an AHIRequest"); - DeleteMsgPort(audio_port); - return -1; - } - - audio_req[0]->ahir_Version = 4; - - if(OpenDevice(AHINAME,0,(struct IORequest *)audio_req[0],NULL)) - { - SDL_SetError("Unable to open AHI device!\n"); - DeleteIORequest((struct IORequest *)audio_req[0]); - DeleteMsgPort(audio_port); - return -1; - } - - D(bug("AFTER opendevice\n")); - - /* Set output frequency and size */ - this->hidden->freq = spec->freq; - this->hidden->size = spec->size; - - D(bug("Before buffer allocation\n")); - - /* Allocate mixing buffer */ - mixbuf[0] = (Uint8 *)mymalloc(spec->size); - mixbuf[1] = (Uint8 *)mymalloc(spec->size); - - D(bug("Before audio_req allocation\n")); - - if(!(audio_req[1]=mymalloc(sizeof(struct AHIRequest)))) - { - SDL_OutOfMemory(); - return(-1); - } - - D(bug("Before audio_req memcpy\n")); - - SDL_memcpy(audio_req[1],audio_req[0],sizeof(struct AHIRequest)); - - if ( mixbuf[0] == NULL || mixbuf[1] == NULL ) { - SDL_OutOfMemory(); - return(-1); - } - - D(bug("Before mixbuf memset\n")); - - SDL_memset(mixbuf[0], spec->silence, spec->size); - SDL_memset(mixbuf[1], spec->silence, spec->size); - - current_buffer=0; - playing=0; - - D(bug("AHI opened: freq:%ld mixbuf:%lx/%lx buflen:%ld bits:%ld channels:%ld\n",spec->freq,mixbuf[0],mixbuf[1],spec->size,this->hidden->bytespersample*8,spec->channels)); - - /* We're ready to rock and roll. :-) */ - return(0); +static int +AHI_OpenAudio(_THIS, SDL_AudioSpec * spec) +{ +// int width; + + D(bug("AHI opening...\n")); + + /* Determine the audio parameters from the AudioSpec */ + switch (spec->format & 0xFF) { + + case 8: + { /* Signed 8 bit audio data */ + D(bug("Samples a 8 bit...\n")); + spec->format = AUDIO_S8; + this->hidden->bytespersample = 1; + if (spec->channels < 2) + this->hidden->type = AHIST_M8S; + else + this->hidden->type = AHIST_S8S; + } + break; + + case 16: + { /* Signed 16 bit audio data */ + D(bug("Samples a 16 bit...\n")); + spec->format = AUDIO_S16MSB; + this->hidden->bytespersample = 2; + if (spec->channels < 2) + this->hidden->type = AHIST_M16S; + else + this->hidden->type = AHIST_S16S; + } + break; + + default: + { + SDL_SetError("Unsupported audio format"); + return (-1); + } + } + + if (spec->channels != 1 && spec->channels != 2) { + D(bug("Wrong channel number!\n")); + SDL_SetError("Channel number non supported"); + return -1; + } + + D(bug("Before CalculateAudioSpec\n")); + /* Update the fragment size as size in bytes */ + SDL_CalculateAudioSpec(spec); + + D(bug("Before CreateMsgPort\n")); + + if (!(audio_port = CreateMsgPort())) { + SDL_SetError("Unable to create a MsgPort"); + return -1; + } + + D(bug("Before CreateIORequest\n")); + + if (! + (audio_req[0] = + (struct AHIRequest *) CreateIORequest(audio_port, + sizeof(struct AHIRequest)))) { + SDL_SetError("Unable to create an AHIRequest"); + DeleteMsgPort(audio_port); + return -1; + } + + audio_req[0]->ahir_Version = 4; + + if (OpenDevice(AHINAME, 0, (struct IORequest *) audio_req[0], NULL)) { + SDL_SetError("Unable to open AHI device!\n"); + DeleteIORequest((struct IORequest *) audio_req[0]); + DeleteMsgPort(audio_port); + return -1; + } + + D(bug("AFTER opendevice\n")); + + /* Set output frequency and size */ + this->hidden->freq = spec->freq; + this->hidden->size = spec->size; + + D(bug("Before buffer allocation\n")); + + /* Allocate mixing buffer */ + mixbuf[0] = (Uint8 *) mymalloc(spec->size); + mixbuf[1] = (Uint8 *) mymalloc(spec->size); + + D(bug("Before audio_req allocation\n")); + + if (!(audio_req[1] = mymalloc(sizeof(struct AHIRequest)))) { + SDL_OutOfMemory(); + return (-1); + } + + D(bug("Before audio_req memcpy\n")); + + SDL_memcpy(audio_req[1], audio_req[0], sizeof(struct AHIRequest)); + + if (mixbuf[0] == NULL || mixbuf[1] == NULL) { + SDL_OutOfMemory(); + return (-1); + } + + D(bug("Before mixbuf memset\n")); + + SDL_memset(mixbuf[0], spec->silence, spec->size); + SDL_memset(mixbuf[1], spec->silence, spec->size); + + current_buffer = 0; + playing = 0; + + D(bug + ("AHI opened: freq:%ld mixbuf:%lx/%lx buflen:%ld bits:%ld channels:%ld\n", + spec->freq, mixbuf[0], mixbuf[1], spec->size, + this->hidden->bytespersample * 8, spec->channels)); + + /* We're ready to rock and roll. :-) */ + return (0); } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/audio/amigaos/SDL_ahiaudio.h b/src/audio/amigaos/SDL_ahiaudio.h index b9ef339c6..7e311daa6 100644 --- a/src/audio/amigaos/SDL_ahiaudio.h +++ b/src/audio/amigaos/SDL_ahiaudio.h @@ -40,14 +40,15 @@ /* Hidden "this" pointer for the audio functions */ #define _THIS SDL_AudioDevice *this -struct SDL_PrivateAudioData { - /* The handle for the audio device */ - struct AHIRequest *audio_req[2]; - struct MsgPort *audio_port; - Sint32 freq,type,bytespersample,size; - Uint8 *mixbuf[2]; /* The app mixing buffer */ - int current_buffer; - Uint32 playing; +struct SDL_PrivateAudioData +{ + /* The handle for the audio device */ + struct AHIRequest *audio_req[2]; + struct MsgPort *audio_port; + Sint32 freq, type, bytespersample, size; + Uint8 *mixbuf[2]; /* The app mixing buffer */ + int current_buffer; + Uint32 playing; }; /* Old variable names */ @@ -58,3 +59,4 @@ struct SDL_PrivateAudioData { #define playing (this->hidden->playing) #endif /* _SDL_ahiaudio_h */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/audio/arts/SDL_artsaudio.c b/src/audio/arts/SDL_artsaudio.c index 59949a52f..e70252f69 100644 --- a/src/audio/arts/SDL_artsaudio.c +++ b/src/audio/arts/SDL_artsaudio.c @@ -41,7 +41,7 @@ #define ARTS_DRIVER_NAME "arts" /* Audio driver functions */ -static int ARTS_OpenAudio(_THIS, SDL_AudioSpec *spec); +static int ARTS_OpenAudio(_THIS, SDL_AudioSpec * spec); static void ARTS_WaitAudio(_THIS); static void ARTS_PlayAudio(_THIS); static Uint8 *ARTS_GetAudioBuf(_THIS); @@ -53,281 +53,305 @@ static const char *arts_library = SDL_AUDIO_DRIVER_ARTS_DYNAMIC; static void *arts_handle = NULL; static int arts_loaded = 0; -static int (*SDL_NAME(arts_init))(void); -static void (*SDL_NAME(arts_free))(void); -static arts_stream_t (*SDL_NAME(arts_play_stream))(int rate, int bits, int channels, const char *name); -static int (*SDL_NAME(arts_stream_set))(arts_stream_t s, arts_parameter_t param, int value); -static int (*SDL_NAME(arts_stream_get))(arts_stream_t s, arts_parameter_t param); -static int (*SDL_NAME(arts_write))(arts_stream_t s, const void *buffer, int count); -static void (*SDL_NAME(arts_close_stream))(arts_stream_t s); - -static struct { - const char *name; - void **func; +static int (*SDL_NAME(arts_init)) (void); +static void (*SDL_NAME(arts_free)) (void); +static arts_stream_t(*SDL_NAME(arts_play_stream)) (int rate, int bits, + int channels, + const char *name); +static int (*SDL_NAME(arts_stream_set)) (arts_stream_t s, + arts_parameter_t param, int value); +static int (*SDL_NAME(arts_stream_get)) (arts_stream_t s, + arts_parameter_t param); +static int (*SDL_NAME(arts_write)) (arts_stream_t s, const void *buffer, + int count); +static void (*SDL_NAME(arts_close_stream)) (arts_stream_t s); + +static struct +{ + const char *name; + void **func; } arts_functions[] = { - { "arts_init", (void **)&SDL_NAME(arts_init) }, - { "arts_free", (void **)&SDL_NAME(arts_free) }, - { "arts_play_stream", (void **)&SDL_NAME(arts_play_stream) }, - { "arts_stream_set", (void **)&SDL_NAME(arts_stream_set) }, - { "arts_stream_get", (void **)&SDL_NAME(arts_stream_get) }, - { "arts_write", (void **)&SDL_NAME(arts_write) }, - { "arts_close_stream", (void **)&SDL_NAME(arts_close_stream) }, -}; - -static void UnloadARTSLibrary() + { + "arts_init", (void **) &SDL_NAME(arts_init)}, { + "arts_free", (void **) &SDL_NAME(arts_free)}, { + "arts_play_stream", (void **) &SDL_NAME(arts_play_stream)}, { + "arts_stream_set", (void **) &SDL_NAME(arts_stream_set)}, { + "arts_stream_get", (void **) &SDL_NAME(arts_stream_get)}, { + "arts_write", (void **) &SDL_NAME(arts_write)}, { +"arts_close_stream", (void **) &SDL_NAME(arts_close_stream)},}; + +static void +UnloadARTSLibrary() { - if ( arts_loaded ) { - SDL_UnloadObject(arts_handle); - arts_handle = NULL; - arts_loaded = 0; - } + if (arts_loaded) { + SDL_UnloadObject(arts_handle); + arts_handle = NULL; + arts_loaded = 0; + } } -static int LoadARTSLibrary(void) +static int +LoadARTSLibrary(void) { - int i, retval = -1; - - arts_handle = SDL_LoadObject(arts_library); - if ( arts_handle ) { - arts_loaded = 1; - retval = 0; - for ( i=0; ihidden); - SDL_free(device); - UnloadARTSLibrary(); + SDL_free(device->hidden); + SDL_free(device); + UnloadARTSLibrary(); } -static SDL_AudioDevice *Audio_CreateDevice(int devindex) +static SDL_AudioDevice * +Audio_CreateDevice(int devindex) { - SDL_AudioDevice *this; - - /* Initialize all variables that we clean on shutdown */ - LoadARTSLibrary(); - this = (SDL_AudioDevice *)SDL_malloc(sizeof(SDL_AudioDevice)); - if ( this ) { - SDL_memset(this, 0, (sizeof *this)); - this->hidden = (struct SDL_PrivateAudioData *) - SDL_malloc((sizeof *this->hidden)); - } - if ( (this == NULL) || (this->hidden == NULL) ) { - SDL_OutOfMemory(); - if ( this ) { - SDL_free(this); - } - return(0); - } - SDL_memset(this->hidden, 0, (sizeof *this->hidden)); - stream = 0; - - /* Set the function pointers */ - this->OpenAudio = ARTS_OpenAudio; - this->WaitAudio = ARTS_WaitAudio; - this->PlayAudio = ARTS_PlayAudio; - this->GetAudioBuf = ARTS_GetAudioBuf; - this->CloseAudio = ARTS_CloseAudio; - - this->free = Audio_DeleteDevice; - - return this; + SDL_AudioDevice *this; + + /* Initialize all variables that we clean on shutdown */ + LoadARTSLibrary(); + this = (SDL_AudioDevice *) SDL_malloc(sizeof(SDL_AudioDevice)); + if (this) { + SDL_memset(this, 0, (sizeof *this)); + this->hidden = (struct SDL_PrivateAudioData *) + SDL_malloc((sizeof *this->hidden)); + } + if ((this == NULL) || (this->hidden == NULL)) { + SDL_OutOfMemory(); + if (this) { + SDL_free(this); + } + return (0); + } + SDL_memset(this->hidden, 0, (sizeof *this->hidden)); + stream = 0; + + /* Set the function pointers */ + this->OpenAudio = ARTS_OpenAudio; + this->WaitAudio = ARTS_WaitAudio; + this->PlayAudio = ARTS_PlayAudio; + this->GetAudioBuf = ARTS_GetAudioBuf; + this->CloseAudio = ARTS_CloseAudio; + + this->free = Audio_DeleteDevice; + + return this; } AudioBootStrap ARTS_bootstrap = { - ARTS_DRIVER_NAME, "Analog Realtime Synthesizer", - Audio_Available, Audio_CreateDevice + ARTS_DRIVER_NAME, "Analog Realtime Synthesizer", + Audio_Available, Audio_CreateDevice }; /* This function waits until it is possible to write a full sound buffer */ -static void ARTS_WaitAudio(_THIS) +static void +ARTS_WaitAudio(_THIS) { - Sint32 ticks; - - /* Check to see if the thread-parent process is still alive */ - { static int cnt = 0; - /* Note that this only works with thread implementations - that use a different process id for each thread. - */ - if (parent && (((++cnt)%10) == 0)) { /* Check every 10 loops */ - if ( kill(parent, 0) < 0 ) { - this->enabled = 0; - } - } - } - - /* Use timer for general audio synchronization */ - ticks = ((Sint32)(next_frame - SDL_GetTicks()))-FUDGE_TICKS; - if ( ticks > 0 ) { - SDL_Delay(ticks); - } + Sint32 ticks; + + /* Check to see if the thread-parent process is still alive */ + { + static int cnt = 0; + /* Note that this only works with thread implementations + that use a different process id for each thread. + */ + if (parent && (((++cnt) % 10) == 0)) { /* Check every 10 loops */ + if (kill(parent, 0) < 0) { + this->enabled = 0; + } + } + } + + /* Use timer for general audio synchronization */ + ticks = ((Sint32) (next_frame - SDL_GetTicks())) - FUDGE_TICKS; + if (ticks > 0) { + SDL_Delay(ticks); + } } -static void ARTS_PlayAudio(_THIS) +static void +ARTS_PlayAudio(_THIS) { - int written; - - /* Write the audio data */ - written = SDL_NAME(arts_write)(stream, mixbuf, mixlen); - - /* If timer synchronization is enabled, set the next write frame */ - if ( frame_ticks ) { - next_frame += frame_ticks; - } - - /* If we couldn't write, assume fatal error for now */ - if ( written < 0 ) { - this->enabled = 0; - } + int written; + + /* Write the audio data */ + written = SDL_NAME(arts_write) (stream, mixbuf, mixlen); + + /* If timer synchronization is enabled, set the next write frame */ + if (frame_ticks) { + next_frame += frame_ticks; + } + + /* If we couldn't write, assume fatal error for now */ + if (written < 0) { + this->enabled = 0; + } #ifdef DEBUG_AUDIO - fprintf(stderr, "Wrote %d bytes of audio data\n", written); + fprintf(stderr, "Wrote %d bytes of audio data\n", written); #endif } -static Uint8 *ARTS_GetAudioBuf(_THIS) +static Uint8 * +ARTS_GetAudioBuf(_THIS) { - return(mixbuf); + return (mixbuf); } -static void ARTS_CloseAudio(_THIS) +static void +ARTS_CloseAudio(_THIS) { - if ( mixbuf != NULL ) { - SDL_FreeAudioMem(mixbuf); - mixbuf = NULL; - } - if ( stream ) { - SDL_NAME(arts_close_stream)(stream); - stream = 0; - } - SDL_NAME(arts_free)(); + if (mixbuf != NULL) { + SDL_FreeAudioMem(mixbuf); + mixbuf = NULL; + } + if (stream) { + SDL_NAME(arts_close_stream) (stream); + stream = 0; + } + SDL_NAME(arts_free) (); } -static int ARTS_OpenAudio(_THIS, SDL_AudioSpec *spec) +static int +ARTS_OpenAudio(_THIS, SDL_AudioSpec * spec) { - int bits, frag_spec; - Uint16 test_format, format; + int bits, frag_spec; + Uint16 test_format, format; - /* Reset the timer synchronization flag */ - frame_ticks = 0.0; + /* Reset the timer synchronization flag */ + frame_ticks = 0.0; - mixbuf = NULL; + mixbuf = NULL; - /* Try for a closest match on audio format */ - format = 0; - bits = 0; - for ( test_format = SDL_FirstAudioFormat(spec->format); - ! format && test_format; ) { + /* Try for a closest match on audio format */ + format = 0; + bits = 0; + for (test_format = SDL_FirstAudioFormat(spec->format); + !format && test_format;) { #ifdef DEBUG_AUDIO - fprintf(stderr, "Trying format 0x%4.4x\n", test_format); + fprintf(stderr, "Trying format 0x%4.4x\n", test_format); #endif - switch ( test_format ) { - case AUDIO_U8: - bits = 8; - format = 1; - break; - case AUDIO_S16LSB: - bits = 16; - format = 1; - break; - default: - format = 0; - break; - } - if ( ! format ) { - test_format = SDL_NextAudioFormat(); - } - } - if ( format == 0 ) { - SDL_SetError("Couldn't find any hardware audio formats"); - return(-1); - } - spec->format = test_format; - - if ( SDL_NAME(arts_init)() != 0 ) { - SDL_SetError("Unable to initialize ARTS"); - return(-1); - } - stream = SDL_NAME(arts_play_stream)(spec->freq, bits, spec->channels, "SDL"); - - /* Calculate the final parameters for this audio specification */ - SDL_CalculateAudioSpec(spec); - - /* Determine the power of two of the fragment size */ - for ( frag_spec = 0; (0x01<size; ++frag_spec ); - if ( (0x01<size ) { - SDL_SetError("Fragment size must be a power of two"); - return(-1); - } - frag_spec |= 0x00020000; /* two fragments, for low latency */ + switch (test_format) { + case AUDIO_U8: + bits = 8; + format = 1; + break; + case AUDIO_S16LSB: + bits = 16; + format = 1; + break; + default: + format = 0; + break; + } + if (!format) { + test_format = SDL_NextAudioFormat(); + } + } + if (format == 0) { + SDL_SetError("Couldn't find any hardware audio formats"); + return (-1); + } + spec->format = test_format; + + if (SDL_NAME(arts_init) () != 0) { + SDL_SetError("Unable to initialize ARTS"); + return (-1); + } + stream = + SDL_NAME(arts_play_stream) (spec->freq, bits, spec->channels, "SDL"); + + /* Calculate the final parameters for this audio specification */ + SDL_CalculateAudioSpec(spec); + + /* Determine the power of two of the fragment size */ + for (frag_spec = 0; (0x01 << frag_spec) < spec->size; ++frag_spec); + if ((0x01 << frag_spec) != spec->size) { + SDL_SetError("Fragment size must be a power of two"); + return (-1); + } + frag_spec |= 0x00020000; /* two fragments, for low latency */ #ifdef ARTS_P_PACKET_SETTINGS - SDL_NAME(arts_stream_set)(stream, ARTS_P_PACKET_SETTINGS, frag_spec); + SDL_NAME(arts_stream_set) (stream, ARTS_P_PACKET_SETTINGS, frag_spec); #else - SDL_NAME(arts_stream_set)(stream, ARTS_P_PACKET_SIZE, frag_spec&0xffff); - SDL_NAME(arts_stream_set)(stream, ARTS_P_PACKET_COUNT, frag_spec>>16); + SDL_NAME(arts_stream_set) (stream, ARTS_P_PACKET_SIZE, + frag_spec & 0xffff); + SDL_NAME(arts_stream_set) (stream, ARTS_P_PACKET_COUNT, frag_spec >> 16); #endif - spec->size = SDL_NAME(arts_stream_get)(stream, ARTS_P_PACKET_SIZE); + spec->size = SDL_NAME(arts_stream_get) (stream, ARTS_P_PACKET_SIZE); - /* Allocate mixing buffer */ - mixlen = spec->size; - mixbuf = (Uint8 *)SDL_AllocAudioMem(mixlen); - if ( mixbuf == NULL ) { - return(-1); - } - SDL_memset(mixbuf, spec->silence, spec->size); + /* Allocate mixing buffer */ + mixlen = spec->size; + mixbuf = (Uint8 *) SDL_AllocAudioMem(mixlen); + if (mixbuf == NULL) { + return (-1); + } + SDL_memset(mixbuf, spec->silence, spec->size); - /* Get the parent process id (we're the parent of the audio thread) */ - parent = getpid(); + /* Get the parent process id (we're the parent of the audio thread) */ + parent = getpid(); - /* We're ready to rock and roll. :-) */ - return(0); + /* We're ready to rock and roll. :-) */ + return (0); } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/audio/arts/SDL_artsaudio.h b/src/audio/arts/SDL_artsaudio.h index 5569a3d49..3f0c68c63 100644 --- a/src/audio/arts/SDL_artsaudio.h +++ b/src/audio/arts/SDL_artsaudio.h @@ -31,22 +31,23 @@ /* Hidden "this" pointer for the video functions */ #define _THIS SDL_AudioDevice *this -struct SDL_PrivateAudioData { - /* The stream descriptor for the audio device */ - arts_stream_t stream; +struct SDL_PrivateAudioData +{ + /* The stream descriptor for the audio device */ + arts_stream_t stream; - /* The parent process id, to detect when application quits */ - pid_t parent; + /* The parent process id, to detect when application quits */ + pid_t parent; - /* Raw mixing buffer */ - Uint8 *mixbuf; - int mixlen; + /* Raw mixing buffer */ + Uint8 *mixbuf; + int mixlen; - /* Support for audio timing using a timer, in addition to select() */ - float frame_ticks; - float next_frame; + /* Support for audio timing using a timer, in addition to select() */ + float frame_ticks; + float next_frame; }; -#define FUDGE_TICKS 10 /* The scheduler overhead ticks per frame */ +#define FUDGE_TICKS 10 /* The scheduler overhead ticks per frame */ /* Old variable names */ #define stream (this->hidden->stream) @@ -57,4 +58,4 @@ struct SDL_PrivateAudioData { #define next_frame (this->hidden->next_frame) #endif /* _SDL_artscaudio_h */ - +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/audio/baudio/SDL_beaudio.cc b/src/audio/baudio/SDL_beaudio.cc index b074f9c2b..5b72932d6 100644 --- a/src/audio/baudio/SDL_beaudio.cc +++ b/src/audio/baudio/SDL_beaudio.cc @@ -27,7 +27,8 @@ #include "../../main/beos/SDL_BeApp.h" -extern "C" { +extern "C" +{ #include "SDL_audio.h" #include "../SDL_audio_c.h" @@ -37,172 +38,177 @@ extern "C" { /* Audio driver functions */ -static int BE_OpenAudio(_THIS, SDL_AudioSpec *spec); -static void BE_WaitAudio(_THIS); -static void BE_PlayAudio(_THIS); -static Uint8 *BE_GetAudioBuf(_THIS); -static void BE_CloseAudio(_THIS); + static int BE_OpenAudio(_THIS, SDL_AudioSpec * spec); + static void BE_WaitAudio(_THIS); + static void BE_PlayAudio(_THIS); + static Uint8 *BE_GetAudioBuf(_THIS); + static void BE_CloseAudio(_THIS); /* Audio driver bootstrap functions */ -static int Audio_Available(void) -{ - return(1); -} - -static void Audio_DeleteDevice(SDL_AudioDevice *device) -{ - SDL_free(device->hidden); - SDL_free(device); -} - -static SDL_AudioDevice *Audio_CreateDevice(int devindex) -{ - SDL_AudioDevice *device; - - /* Initialize all variables that we clean on shutdown */ - device = (SDL_AudioDevice *)SDL_malloc(sizeof(SDL_AudioDevice)); - if ( device ) { - SDL_memset(device, 0, (sizeof *device)); - device->hidden = (struct SDL_PrivateAudioData *) - SDL_malloc((sizeof *device->hidden)); - } - if ( (device == NULL) || (device->hidden == NULL) ) { - SDL_OutOfMemory(); - if ( device ) { - SDL_free(device); - } - return(0); - } - SDL_memset(device->hidden, 0, (sizeof *device->hidden)); - - /* Set the function pointers */ - device->OpenAudio = BE_OpenAudio; - device->WaitAudio = BE_WaitAudio; - device->PlayAudio = BE_PlayAudio; - device->GetAudioBuf = BE_GetAudioBuf; - device->CloseAudio = BE_CloseAudio; - - device->free = Audio_DeleteDevice; - - return device; -} - -AudioBootStrap BAUDIO_bootstrap = { - "baudio", "BeOS BSoundPlayer", - Audio_Available, Audio_CreateDevice -}; + static int Audio_Available(void) + { + return (1); + } + + static void Audio_DeleteDevice(SDL_AudioDevice * device) + { + SDL_free(device->hidden); + SDL_free(device); + } + + static SDL_AudioDevice *Audio_CreateDevice(int devindex) + { + SDL_AudioDevice *device; + + /* Initialize all variables that we clean on shutdown */ + device = (SDL_AudioDevice *) SDL_malloc(sizeof(SDL_AudioDevice)); + if (device) { + SDL_memset(device, 0, (sizeof *device)); + device->hidden = (struct SDL_PrivateAudioData *) + SDL_malloc((sizeof *device->hidden)); + } + if ((device == NULL) || (device->hidden == NULL)) { + SDL_OutOfMemory(); + if (device) { + SDL_free(device); + } + return (0); + } + SDL_memset(device->hidden, 0, (sizeof *device->hidden)); + + /* Set the function pointers */ + device->OpenAudio = BE_OpenAudio; + device->WaitAudio = BE_WaitAudio; + device->PlayAudio = BE_PlayAudio; + device->GetAudioBuf = BE_GetAudioBuf; + device->CloseAudio = BE_CloseAudio; + + device->free = Audio_DeleteDevice; + + return device; + } + + AudioBootStrap BAUDIO_bootstrap = { + "baudio", "BeOS BSoundPlayer", + Audio_Available, Audio_CreateDevice + }; /* The BeOS callback for handling the audio buffer */ -static void FillSound(void *device, void *stream, size_t len, - const media_raw_audio_format &format) -{ - SDL_AudioDevice *audio = (SDL_AudioDevice *)device; - - /* Silence the buffer, since it's ours */ - SDL_memset(stream, audio->spec.silence, len); - - /* Only do soemthing if audio is enabled */ - if ( ! audio->enabled ) - return; - - if ( ! audio->paused ) { - if ( audio->convert.needed ) { - SDL_mutexP(audio->mixer_lock); - (*audio->spec.callback)(audio->spec.userdata, - (Uint8 *)audio->convert.buf,audio->convert.len); - SDL_mutexV(audio->mixer_lock); - SDL_ConvertAudio(&audio->convert); - SDL_memcpy(stream,audio->convert.buf,audio->convert.len_cvt); - } else { - SDL_mutexP(audio->mixer_lock); - (*audio->spec.callback)(audio->spec.userdata, - (Uint8 *)stream, len); - SDL_mutexV(audio->mixer_lock); - } - } - return; -} + static void FillSound(void *device, void *stream, size_t len, + const media_raw_audio_format & format) + { + SDL_AudioDevice *audio = (SDL_AudioDevice *) device; + + /* Silence the buffer, since it's ours */ + SDL_memset(stream, audio->spec.silence, len); + + /* Only do soemthing if audio is enabled */ + if (!audio->enabled) + return; + + if (!audio->paused) { + if (audio->convert.needed) { + SDL_mutexP(audio->mixer_lock); + (*audio->spec.callback) (audio->spec.userdata, + (Uint8 *) audio->convert.buf, + audio->convert.len); + SDL_mutexV(audio->mixer_lock); + SDL_ConvertAudio(&audio->convert); + SDL_memcpy(stream, audio->convert.buf, + audio->convert.len_cvt); + } else { + SDL_mutexP(audio->mixer_lock); + (*audio->spec.callback) (audio->spec.userdata, + (Uint8 *) stream, len); + SDL_mutexV(audio->mixer_lock); + } + } + return; + } /* Dummy functions -- we don't use thread-based audio */ -void BE_WaitAudio(_THIS) -{ - return; -} -void BE_PlayAudio(_THIS) -{ - return; -} -Uint8 *BE_GetAudioBuf(_THIS) -{ - return(NULL); -} - -void BE_CloseAudio(_THIS) -{ - if ( audio_obj ) { - audio_obj->Stop(); - delete audio_obj; - audio_obj = NULL; - } - - /* Quit the Be Application, if there's nothing left to do */ - SDL_QuitBeApp(); -} - -int BE_OpenAudio(_THIS, SDL_AudioSpec *spec) -{ - media_raw_audio_format format; - - /* Initialize the Be Application, if it's not already started */ - if ( SDL_InitBeApp() < 0 ) { - return(-1); - } - - /* Parse the audio format and fill the Be raw audio format */ - format.frame_rate = (float)spec->freq; - format.channel_count = spec->channels; - switch (spec->format&~0x1000) { - case AUDIO_S8: - /* Signed 8-bit audio unsupported, convert to U8 */ - spec->format = AUDIO_U8; - case AUDIO_U8: - format.format = media_raw_audio_format::B_AUDIO_UCHAR; - format.byte_order = 0; - break; - case AUDIO_U16: - /* Unsigned 16-bit audio unsupported, convert to S16 */ - spec->format ^= 0x8000; - case AUDIO_S16: - format.format = media_raw_audio_format::B_AUDIO_SHORT; - if ( spec->format & 0x1000 ) { - format.byte_order = 1; /* Big endian */ - } else { - format.byte_order = 2; /* Little endian */ - } - break; - } - format.buffer_size = spec->samples; - - /* Calculate the final parameters for this audio specification */ - SDL_CalculateAudioSpec(spec); - - /* Subscribe to the audio stream (creates a new thread) */ - { sigset_t omask; - SDL_MaskSignals(&omask); - audio_obj = new BSoundPlayer(&format, "SDL Audio", FillSound, - NULL, _this); - SDL_UnmaskSignals(&omask); - } - if ( audio_obj->Start() == B_NO_ERROR ) { - audio_obj->SetHasData(true); - } else { - SDL_SetError("Unable to start Be audio"); - return(-1); - } - - /* We're running! */ - return(1); -} - -}; /* Extern C */ + void BE_WaitAudio(_THIS) + { + return; + } + void BE_PlayAudio(_THIS) + { + return; + } + Uint8 *BE_GetAudioBuf(_THIS) + { + return (NULL); + } + + void BE_CloseAudio(_THIS) + { + if (audio_obj) { + audio_obj->Stop(); + delete audio_obj; + audio_obj = NULL; + } + + /* Quit the Be Application, if there's nothing left to do */ + SDL_QuitBeApp(); + } + + int BE_OpenAudio(_THIS, SDL_AudioSpec * spec) + { + media_raw_audio_format format; + + /* Initialize the Be Application, if it's not already started */ + if (SDL_InitBeApp() < 0) { + return (-1); + } + + /* Parse the audio format and fill the Be raw audio format */ + format.frame_rate = (float) spec->freq; + format.channel_count = spec->channels; + switch (spec->format & ~0x1000) { + case AUDIO_S8: + /* Signed 8-bit audio unsupported, convert to U8 */ + spec->format = AUDIO_U8; + case AUDIO_U8: + format.format = media_raw_audio_format::B_AUDIO_UCHAR; + format.byte_order = 0; + break; + case AUDIO_U16: + /* Unsigned 16-bit audio unsupported, convert to S16 */ + spec->format ^= 0x8000; + case AUDIO_S16: + format.format = media_raw_audio_format::B_AUDIO_SHORT; + if (spec->format & 0x1000) { + format.byte_order = 1; /* Big endian */ + } else { + format.byte_order = 2; /* Little endian */ + } + break; + } + format.buffer_size = spec->samples; + + /* Calculate the final parameters for this audio specification */ + SDL_CalculateAudioSpec(spec); + + /* Subscribe to the audio stream (creates a new thread) */ + { + sigset_t omask; + SDL_MaskSignals(&omask); + audio_obj = new BSoundPlayer(&format, "SDL Audio", FillSound, + NULL, _this); + SDL_UnmaskSignals(&omask); + } + if (audio_obj->Start() == B_NO_ERROR) { + audio_obj->SetHasData(true); + } else { + SDL_SetError("Unable to start Be audio"); + return (-1); + } + + /* We're running! */ + return (1); + } + +}; /* Extern C */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/audio/baudio/SDL_beaudio.h b/src/audio/baudio/SDL_beaudio.h index 942c60ea3..fc8d52bb4 100644 --- a/src/audio/baudio/SDL_beaudio.h +++ b/src/audio/baudio/SDL_beaudio.h @@ -29,11 +29,13 @@ /* Hidden "this" pointer for the video functions */ #define _THIS SDL_AudioDevice *_this -struct SDL_PrivateAudioData { - BSoundPlayer *audio_obj; +struct SDL_PrivateAudioData +{ + BSoundPlayer *audio_obj; }; /* Old variable names */ #define audio_obj (_this->hidden->audio_obj) #endif /* _SDL_lowaudio_h */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/audio/bsd/SDL_bsdaudio.c b/src/audio/bsd/SDL_bsdaudio.c index f1946c055..89e1e14ad 100644 --- a/src/audio/bsd/SDL_bsdaudio.c +++ b/src/audio/bsd/SDL_bsdaudio.c @@ -68,7 +68,7 @@ /* Audio driver functions */ static void OBSD_WaitAudio(_THIS); -static int OBSD_OpenAudio(_THIS, SDL_AudioSpec *spec); +static int OBSD_OpenAudio(_THIS, SDL_AudioSpec * spec); static void OBSD_PlayAudio(_THIS); static Uint8 *OBSD_GetAudioBuf(_THIS); static void OBSD_CloseAudio(_THIS); @@ -87,36 +87,37 @@ Audio_Available(void) available = 0; fd = SDL_OpenAudioPath(NULL, 0, OPEN_FLAGS, 0); - if(fd >= 0) { - available = 1; - close(fd); + if (fd >= 0) { + available = 1; + close(fd); } - return(available); + return (available); } static void -Audio_DeleteDevice(SDL_AudioDevice *device) +Audio_DeleteDevice(SDL_AudioDevice * device) { SDL_free(device->hidden); SDL_free(device); } -static SDL_AudioDevice -*Audio_CreateDevice(int devindex) +static SDL_AudioDevice * +Audio_CreateDevice(int devindex) { SDL_AudioDevice *this; /* Initialize all variables that we clean on shutdown */ - this = (SDL_AudioDevice*)SDL_malloc(sizeof(SDL_AudioDevice)); - if(this) { - SDL_memset(this, 0, (sizeof *this)); - this->hidden = - (struct SDL_PrivateAudioData*)SDL_malloc((sizeof *this->hidden)); + this = (SDL_AudioDevice *) SDL_malloc(sizeof(SDL_AudioDevice)); + if (this) { + SDL_memset(this, 0, (sizeof *this)); + this->hidden = (struct SDL_PrivateAudioData *) + SDL_malloc((sizeof *this->hidden)); } - if((this == NULL) || (this->hidden == NULL)) { - SDL_OutOfMemory(); - if(this) SDL_free(this); - return(0); + if ((this == NULL) || (this->hidden == NULL)) { + SDL_OutOfMemory(); + if (this) + SDL_free(this); + return (0); } SDL_memset(this->hidden, 0, (sizeof *this->hidden)); audio_fd = -1; @@ -129,115 +130,116 @@ static SDL_AudioDevice this->CloseAudio = OBSD_CloseAudio; this->free = Audio_DeleteDevice; - + return this; } AudioBootStrap BSD_AUDIO_bootstrap = { - BSD_AUDIO_DRIVER_NAME, BSD_AUDIO_DRIVER_DESC, - Audio_Available, Audio_CreateDevice + BSD_AUDIO_DRIVER_NAME, BSD_AUDIO_DRIVER_DESC, + Audio_Available, Audio_CreateDevice }; /* This function waits until it is possible to write a full sound buffer */ static void OBSD_WaitAudio(_THIS) { -#ifndef USE_BLOCKING_WRITES /* Not necessary when using blocking writes */ - /* See if we need to use timed audio synchronization */ - if ( frame_ticks ) { - /* Use timer for general audio synchronization */ - Sint32 ticks; - - ticks = ((Sint32)(next_frame - SDL_GetTicks()))-FUDGE_TICKS; - if ( ticks > 0 ) { - SDL_Delay(ticks); - } - } else { - /* Use select() for audio synchronization */ - fd_set fdset; - struct timeval timeout; - - FD_ZERO(&fdset); - FD_SET(audio_fd, &fdset); - timeout.tv_sec = 10; - timeout.tv_usec = 0; +#ifndef USE_BLOCKING_WRITES /* Not necessary when using blocking writes */ + /* See if we need to use timed audio synchronization */ + if (frame_ticks) { + /* Use timer for general audio synchronization */ + Sint32 ticks; + + ticks = ((Sint32) (next_frame - SDL_GetTicks())) - FUDGE_TICKS; + if (ticks > 0) { + SDL_Delay(ticks); + } + } else { + /* Use select() for audio synchronization */ + fd_set fdset; + struct timeval timeout; + + FD_ZERO(&fdset); + FD_SET(audio_fd, &fdset); + timeout.tv_sec = 10; + timeout.tv_usec = 0; #ifdef DEBUG_AUDIO - fprintf(stderr, "Waiting for audio to get ready\n"); + fprintf(stderr, "Waiting for audio to get ready\n"); #endif - if ( select(audio_fd+1, NULL, &fdset, NULL, &timeout) <= 0 ) { - const char *message = - "Audio timeout - buggy audio driver? (disabled)"; - /* In general we should never print to the screen, - but in this case we have no other way of letting - the user know what happened. - */ - fprintf(stderr, "SDL: %s\n", message); - this->enabled = 0; - /* Don't try to close - may hang */ - audio_fd = -1; + if (select(audio_fd + 1, NULL, &fdset, NULL, &timeout) <= 0) { + const char *message = + "Audio timeout - buggy audio driver? (disabled)"; + /* In general we should never print to the screen, + but in this case we have no other way of letting + the user know what happened. + */ + fprintf(stderr, "SDL: %s\n", message); + this->enabled = 0; + /* Don't try to close - may hang */ + audio_fd = -1; #ifdef DEBUG_AUDIO - fprintf(stderr, "Done disabling audio\n"); + fprintf(stderr, "Done disabling audio\n"); #endif - } + } #ifdef DEBUG_AUDIO - fprintf(stderr, "Ready!\n"); + fprintf(stderr, "Ready!\n"); #endif - } + } #endif /* !USE_BLOCKING_WRITES */ } static void OBSD_PlayAudio(_THIS) { - int written, p=0; - - /* Write the audio data, checking for EAGAIN on broken audio drivers */ - do { - written = write(audio_fd, &mixbuf[p], mixlen-p); - if (written>0) - p += written; - if (written == -1 && errno != 0 && errno != EAGAIN && errno != EINTR) - { - /* Non recoverable error has occurred. It should be reported!!! */ - perror("audio"); - break; - } - - if ( p < written || ((written < 0) && ((errno == 0) || (errno == EAGAIN))) ) { - SDL_Delay(1); /* Let a little CPU time go by */ - } - } while ( p < written ); - - /* If timer synchronization is enabled, set the next write frame */ - if ( frame_ticks ) { - next_frame += frame_ticks; - } - - /* If we couldn't write, assume fatal error for now */ - if ( written < 0 ) { - this->enabled = 0; - } + int written, p = 0; + + /* Write the audio data, checking for EAGAIN on broken audio drivers */ + do { + written = write(audio_fd, &mixbuf[p], mixlen - p); + if (written > 0) + p += written; + if (written == -1 && errno != 0 && errno != EAGAIN && errno != EINTR) { + /* Non recoverable error has occurred. It should be reported!!! */ + perror("audio"); + break; + } + + if (p < written + || ((written < 0) && ((errno == 0) || (errno == EAGAIN)))) { + SDL_Delay(1); /* Let a little CPU time go by */ + } + } + while (p < written); + + /* If timer synchronization is enabled, set the next write frame */ + if (frame_ticks) { + next_frame += frame_ticks; + } + + /* If we couldn't write, assume fatal error for now */ + if (written < 0) { + this->enabled = 0; + } #ifdef DEBUG_AUDIO - fprintf(stderr, "Wrote %d bytes of audio data\n", written); + fprintf(stderr, "Wrote %d bytes of audio data\n", written); #endif } -static Uint8 -*OBSD_GetAudioBuf(_THIS) +static Uint8 * +OBSD_GetAudioBuf(_THIS) { - return(mixbuf); + return (mixbuf); } static void OBSD_CloseAudio(_THIS) { - if(mixbuf != NULL) { - SDL_FreeAudioMem(mixbuf); - mixbuf = NULL; + if (mixbuf != NULL) { + SDL_FreeAudioMem(mixbuf); + mixbuf = NULL; } - if(audio_fd >= 0) { - close(audio_fd); - audio_fd = -1; + if (audio_fd >= 0) { + close(audio_fd); + audio_fd = -1; } } @@ -247,66 +249,93 @@ OBSD_Status(_THIS) { audio_info_t info; - if(ioctl(audio_fd, AUDIO_GETINFO, &info) < 0) { - fprintf(stderr,"AUDIO_GETINFO failed.\n"); - return; + if (ioctl(audio_fd, AUDIO_GETINFO, &info) < 0) { + fprintf(stderr, "AUDIO_GETINFO failed.\n"); + return; } - fprintf(stderr,"\n" -"[play/record info]\n" -"buffer size : %d bytes\n" -"sample rate : %i Hz\n" -"channels : %i\n" -"precision : %i-bit\n" -"encoding : 0x%x\n" -"seek : %i\n" -"sample count : %i\n" -"EOF count : %i\n" -"paused : %s\n" -"error occured : %s\n" -"waiting : %s\n" -"active : %s\n" -"", - info.play.buffer_size, - info.play.sample_rate, - info.play.channels, - info.play.precision, - info.play.encoding, - info.play.seek, - info.play.samples, - info.play.eof, - info.play.pause ? "yes" : "no", - info.play.error ? "yes" : "no", - info.play.waiting ? "yes" : "no", - info.play.active ? "yes": "no"); - - fprintf(stderr,"\n" -"[audio info]\n" -"monitor_gain : %i\n" -"hw block size : %d bytes\n" -"hi watermark : %i\n" -"lo watermark : %i\n" -"audio mode : %s\n" -"", - info.monitor_gain, - info.blocksize, - info.hiwat, info.lowat, - (info.mode == AUMODE_PLAY) ? "PLAY" - : (info.mode = AUMODE_RECORD) ? "RECORD" - : (info.mode == AUMODE_PLAY_ALL ? "PLAY_ALL" - : "?")); + fprintf(stderr, "\n" + "[play/record info]\n" + "buffer size : %d bytes\n" + "sample rate : %i Hz\n" + "channels : %i\n" + "precision : %i-bit\n" + "encoding : 0x%x\n" + "seek : %i\n" + "sample count : %i\n" + "EOF count : %i\n" + "paused : %s\n" + "error occured : %s\n" + "waiting : %s\n" + "active : %s\n" + "", + info. + play. + buffer_size, + info. + play. + sample_rate, + info. + play. + channels, + info. + play. + precision, + info. + play. + encoding, + info. + play. + seek, + info. + play. + samples, + info. + play. + eof, + info. + play. + pause + ? + "yes" + : + "no", + info. + play. + error + ? + "yes" + : + "no", + info. + play.waiting ? "yes" : "no", info.play.active ? "yes" : "no"); + + fprintf(stderr, "\n" + "[audio info]\n" + "monitor_gain : %i\n" + "hw block size : %d bytes\n" + "hi watermark : %i\n" + "lo watermark : %i\n" + "audio mode : %s\n" + "", + info.monitor_gain, + info.blocksize, + info.hiwat, info.lowat, + (info.mode == AUMODE_PLAY) ? "PLAY" + : (info.mode = AUMODE_RECORD) ? "RECORD" + : (info.mode == AUMODE_PLAY_ALL ? "PLAY_ALL" : "?")); } #endif /* DEBUG_AUDIO */ static int -OBSD_OpenAudio(_THIS, SDL_AudioSpec *spec) +OBSD_OpenAudio(_THIS, SDL_AudioSpec * spec) { char audiodev[64]; Uint16 format; audio_info_t info; AUDIO_INITINFO(&info); - + /* Calculate the final parameters for this audio specification */ SDL_CalculateAudioSpec(spec); @@ -316,58 +345,57 @@ OBSD_OpenAudio(_THIS, SDL_AudioSpec *spec) /* Open the audio device */ audio_fd = SDL_OpenAudioPath(audiodev, sizeof(audiodev), OPEN_FLAGS, 0); - if(audio_fd < 0) { - SDL_SetError("Couldn't open %s: %s", audiodev, strerror(errno)); - return(-1); + if (audio_fd < 0) { + SDL_SetError("Couldn't open %s: %s", audiodev, strerror(errno)); + return (-1); } - + /* Set to play mode */ info.mode = AUMODE_PLAY; - if(ioctl(audio_fd, AUDIO_SETINFO, &info) < 0) { - SDL_SetError("Couldn't put device into play mode"); - return(-1); + if (ioctl(audio_fd, AUDIO_SETINFO, &info) < 0) { + SDL_SetError("Couldn't put device into play mode"); + return (-1); } - + mixbuf = NULL; AUDIO_INITINFO(&info); - for (format = SDL_FirstAudioFormat(spec->format); - format; format = SDL_NextAudioFormat()) - { - switch(format) { - case AUDIO_U8: - info.play.encoding = AUDIO_ENCODING_ULINEAR; - info.play.precision = 8; - break; - case AUDIO_S8: - info.play.encoding = AUDIO_ENCODING_SLINEAR; - info.play.precision = 8; - break; - case AUDIO_S16LSB: - info.play.encoding = AUDIO_ENCODING_SLINEAR_LE; - info.play.precision = 16; - break; - case AUDIO_S16MSB: - info.play.encoding = AUDIO_ENCODING_SLINEAR_BE; - info.play.precision = 16; - break; - case AUDIO_U16LSB: - info.play.encoding = AUDIO_ENCODING_ULINEAR_LE; - info.play.precision = 16; - break; - case AUDIO_U16MSB: - info.play.encoding = AUDIO_ENCODING_ULINEAR_BE; - info.play.precision = 16; - break; - default: - continue; - } - if (ioctl(audio_fd, AUDIO_SETINFO, &info) == 0) - break; + for (format = SDL_FirstAudioFormat(spec->format); + format; format = SDL_NextAudioFormat()) { + switch (format) { + case AUDIO_U8: + info.play.encoding = AUDIO_ENCODING_ULINEAR; + info.play.precision = 8; + break; + case AUDIO_S8: + info.play.encoding = AUDIO_ENCODING_SLINEAR; + info.play.precision = 8; + break; + case AUDIO_S16LSB: + info.play.encoding = AUDIO_ENCODING_SLINEAR_LE; + info.play.precision = 16; + break; + case AUDIO_S16MSB: + info.play.encoding = AUDIO_ENCODING_SLINEAR_BE; + info.play.precision = 16; + break; + case AUDIO_U16LSB: + info.play.encoding = AUDIO_ENCODING_ULINEAR_LE; + info.play.precision = 16; + break; + case AUDIO_U16MSB: + info.play.encoding = AUDIO_ENCODING_ULINEAR_BE; + info.play.precision = 16; + break; + default: + continue; + } + if (ioctl(audio_fd, AUDIO_SETINFO, &info) == 0) + break; } - if(!format) { - SDL_SetError("No supported encoding for 0x%x", spec->format); - return(-1); + if (!format) { + SDL_SetError("No supported encoding for 0x%x", spec->format); + return (-1); } spec->format = format; @@ -375,23 +403,23 @@ OBSD_OpenAudio(_THIS, SDL_AudioSpec *spec) AUDIO_INITINFO(&info); info.play.channels = spec->channels; if (ioctl(audio_fd, AUDIO_SETINFO, &info) == -1) - spec->channels = 1; + spec->channels = 1; AUDIO_INITINFO(&info); info.play.sample_rate = spec->freq; info.blocksize = spec->size; info.hiwat = 5; info.lowat = 3; - (void)ioctl(audio_fd, AUDIO_SETINFO, &info); - (void)ioctl(audio_fd, AUDIO_GETINFO, &info); - spec->freq = info.play.sample_rate; + (void) ioctl(audio_fd, AUDIO_SETINFO, &info); + (void) ioctl(audio_fd, AUDIO_GETINFO, &info); + spec->freq = info.play.sample_rate; /* Allocate mixing buffer */ mixlen = spec->size; - mixbuf = (Uint8*)SDL_AllocAudioMem(mixlen); - if(mixbuf == NULL) { - return(-1); + mixbuf = (Uint8 *) SDL_AllocAudioMem(mixlen); + if (mixbuf == NULL) { + return (-1); } SDL_memset(mixbuf, spec->silence, spec->size); - + /* Get the parent process id (we're the parent of the audio thread) */ parent = getpid(); @@ -400,5 +428,7 @@ OBSD_OpenAudio(_THIS, SDL_AudioSpec *spec) #endif /* We're ready to rock and roll. :-) */ - return(0); + return (0); } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/audio/bsd/SDL_bsdaudio.h b/src/audio/bsd/SDL_bsdaudio.h index 8e8db89e9..618401d90 100644 --- a/src/audio/bsd/SDL_bsdaudio.h +++ b/src/audio/bsd/SDL_bsdaudio.h @@ -38,14 +38,14 @@ struct SDL_PrivateAudioData /* Raw mixing buffer */ Uint8 *mixbuf; - int mixlen; + int mixlen; /* Support for audio timing using a timer, in addition to select() */ float frame_ticks; float next_frame; }; -#define FUDGE_TICKS 10 /* The scheduler overhead ticks per frame */ +#define FUDGE_TICKS 10 /* The scheduler overhead ticks per frame */ /* Old variable names */ #define audio_fd (this->hidden->audio_fd) @@ -56,3 +56,4 @@ struct SDL_PrivateAudioData #define next_frame (this->hidden->next_frame) #endif /* _SDL_openbsdaudio_h */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/audio/dart/SDL_dart.c b/src/audio/dart/SDL_dart.c index 6381de161..fbb3be0fb 100644 --- a/src/audio/dart/SDL_dart.c +++ b/src/audio/dart/SDL_dart.c @@ -32,9 +32,10 @@ #define BUFFER_EMPTY 0 #define BUFFER_USED 1 -typedef struct _tMixBufferDesc { - int iBufferUsage; // BUFFER_EMPTY or BUFFER_USED - SDL_AudioDevice *pSDLAudioDevice; +typedef struct _tMixBufferDesc +{ + int iBufferUsage; // BUFFER_EMPTY or BUFFER_USED + SDL_AudioDevice *pSDLAudioDevice; } tMixBufferDesc, *pMixBufferDesc; @@ -44,70 +45,67 @@ typedef struct _tMixBufferDesc { // This function is called by DART, when an event occures, like end of // playback of a buffer, etc... //--------------------------------------------------------------------- -LONG APIENTRY DARTEventFunc(ULONG ulStatus, - PMCI_MIX_BUFFER pBuffer, - ULONG ulFlags) +LONG APIENTRY +DARTEventFunc(ULONG ulStatus, PMCI_MIX_BUFFER pBuffer, ULONG ulFlags) { - if (ulFlags && MIX_WRITE_COMPLETE) - { // Playback of buffer completed! - - // Get pointer to buffer description - pMixBufferDesc pBufDesc; - - if (pBuffer) - { - pBufDesc = (pMixBufferDesc) (*pBuffer).ulUserParm; - - if (pBufDesc) - { - SDL_AudioDevice *pSDLAudioDevice = pBufDesc->pSDLAudioDevice; - // Set the buffer to be empty - pBufDesc->iBufferUsage = BUFFER_EMPTY; - // And notify DART feeder thread that it will have to work a bit. - if (pSDLAudioDevice) - DosPostEventSem(pSDLAudioDevice->hidden->hevAudioBufferPlayed); - } + if (ulFlags && MIX_WRITE_COMPLETE) { // Playback of buffer completed! + + // Get pointer to buffer description + pMixBufferDesc pBufDesc; + + if (pBuffer) { + pBufDesc = (pMixBufferDesc) (*pBuffer).ulUserParm; + + if (pBufDesc) { + SDL_AudioDevice *pSDLAudioDevice = pBufDesc->pSDLAudioDevice; + // Set the buffer to be empty + pBufDesc->iBufferUsage = BUFFER_EMPTY; + // And notify DART feeder thread that it will have to work a bit. + if (pSDLAudioDevice) + DosPostEventSem(pSDLAudioDevice->hidden-> + hevAudioBufferPlayed); + } + } } - } - return TRUE; + return TRUE; } -int DART_OpenAudio(_THIS, SDL_AudioSpec *spec) +int +DART_OpenAudio(_THIS, SDL_AudioSpec * spec) { - MCI_AMP_OPEN_PARMS AmpOpenParms; - MCI_GENERIC_PARMS GenericParms; - int iDeviceOrd = 0; // Default device to be used - int bOpenShared = 1; // Try opening it shared - int iBits = 16; // Default is 16 bits signed - int iFreq = 44100; // Default is 44KHz - int iChannels = 2; // Default is 2 channels (Stereo) - int iNumBufs = 2; // Number of audio buffers: 2 - int iBufSize; - int iOpenMode; - int iSilence; - int rc; - - // First thing is to try to open a given DART device! - SDL_memset(&AmpOpenParms, 0, sizeof(MCI_AMP_OPEN_PARMS)); - // pszDeviceType should contain the device type in low word, and device ordinal in high word! - AmpOpenParms.pszDeviceType = (PSZ) (MCI_DEVTYPE_AUDIO_AMPMIX | (iDeviceOrd << 16)); - - iOpenMode = MCI_WAIT | MCI_OPEN_TYPE_ID; - if (bOpenShared) iOpenMode |= MCI_OPEN_SHAREABLE; - - rc = mciSendCommand( 0, MCI_OPEN, - iOpenMode, - (PVOID) &AmpOpenParms, 0); - if (rc!=MCIERR_SUCCESS) // No audio available?? - return (-1); - // Save the device ID we got from DART! - // We will use this in the next calls! - iDeviceOrd = AmpOpenParms.usDeviceID; - - // Determine the audio parameters from the AudioSpec - switch ( spec->format & 0xFF ) - { + MCI_AMP_OPEN_PARMS AmpOpenParms; + MCI_GENERIC_PARMS GenericParms; + int iDeviceOrd = 0; // Default device to be used + int bOpenShared = 1; // Try opening it shared + int iBits = 16; // Default is 16 bits signed + int iFreq = 44100; // Default is 44KHz + int iChannels = 2; // Default is 2 channels (Stereo) + int iNumBufs = 2; // Number of audio buffers: 2 + int iBufSize; + int iOpenMode; + int iSilence; + int rc; + + // First thing is to try to open a given DART device! + SDL_memset(&AmpOpenParms, 0, sizeof(MCI_AMP_OPEN_PARMS)); + // pszDeviceType should contain the device type in low word, and device ordinal in high word! + AmpOpenParms.pszDeviceType = + (PSZ) (MCI_DEVTYPE_AUDIO_AMPMIX | (iDeviceOrd << 16)); + + iOpenMode = MCI_WAIT | MCI_OPEN_TYPE_ID; + if (bOpenShared) + iOpenMode |= MCI_OPEN_SHAREABLE; + + rc = mciSendCommand(0, MCI_OPEN, iOpenMode, (PVOID) & AmpOpenParms, 0); + if (rc != MCIERR_SUCCESS) // No audio available?? + return (-1); + // Save the device ID we got from DART! + // We will use this in the next calls! + iDeviceOrd = AmpOpenParms.usDeviceID; + + // Determine the audio parameters from the AudioSpec + switch (spec->format & 0xFF) { case 8: /* Unsigned 8 bit audio data */ spec->format = AUDIO_U8; @@ -124,303 +122,333 @@ int DART_OpenAudio(_THIS, SDL_AudioSpec *spec) // Close DART, and exit with error code! mciSendCommand(iDeviceOrd, MCI_CLOSE, MCI_WAIT, &GenericParms, 0); SDL_SetError("Unsupported audio format"); - return(-1); - } - iFreq = spec->freq; - iChannels = spec->channels; - /* Update the fragment size as size in bytes */ - SDL_CalculateAudioSpec(spec); - iBufSize = spec->size; - - // Now query this device if it supports the given freq/bits/channels! - SDL_memset(&(_this->hidden->MixSetupParms), 0, sizeof(MCI_MIXSETUP_PARMS)); - _this->hidden->MixSetupParms.ulBitsPerSample = iBits; - _this->hidden->MixSetupParms.ulFormatTag = MCI_WAVE_FORMAT_PCM; - _this->hidden->MixSetupParms.ulSamplesPerSec = iFreq; - _this->hidden->MixSetupParms.ulChannels = iChannels; - _this->hidden->MixSetupParms.ulFormatMode = MCI_PLAY; - _this->hidden->MixSetupParms.ulDeviceType = MCI_DEVTYPE_WAVEFORM_AUDIO; - _this->hidden->MixSetupParms.pmixEvent = DARTEventFunc; - rc = mciSendCommand (iDeviceOrd, MCI_MIXSETUP, - MCI_WAIT | MCI_MIXSETUP_QUERYMODE, - &(_this->hidden->MixSetupParms), 0); - if (rc!=MCIERR_SUCCESS) - { // The device cannot handle this format! - // Close DART, and exit with error code! - mciSendCommand(iDeviceOrd, MCI_CLOSE, MCI_WAIT, &GenericParms, 0); - SDL_SetError("Audio device doesn't support requested audio format"); - return(-1); - } - // The device can handle this format, so initialize! - rc = mciSendCommand(iDeviceOrd, MCI_MIXSETUP, - MCI_WAIT | MCI_MIXSETUP_INIT, - &(_this->hidden->MixSetupParms), 0); - if (rc!=MCIERR_SUCCESS) - { // The device could not be opened! - // Close DART, and exit with error code! - mciSendCommand(iDeviceOrd, MCI_CLOSE, MCI_WAIT, &GenericParms, 0); - SDL_SetError("Audio device could not be set up"); - return(-1); - } - // Ok, the device is initialized. - // Now we should allocate buffers. For this, we need a place where - // the buffer descriptors will be: - _this->hidden->pMixBuffers = (MCI_MIX_BUFFER *) SDL_malloc(sizeof(MCI_MIX_BUFFER)*iNumBufs); - if (!(_this->hidden->pMixBuffers)) - { // Not enough memory! - // Close DART, and exit with error code! - mciSendCommand(iDeviceOrd, MCI_CLOSE, MCI_WAIT, &GenericParms, 0); - SDL_SetError("Not enough memory for audio buffer descriptors"); - return(-1); - } - // Now that we have the place for buffer list, we can ask DART for the - // buffers! - _this->hidden->BufferParms.ulNumBuffers = iNumBufs; // Number of buffers - _this->hidden->BufferParms.ulBufferSize = iBufSize; // each with this size - _this->hidden->BufferParms.pBufList = _this->hidden->pMixBuffers; // getting descriptorts into this list - // Allocate buffers! - rc = mciSendCommand(iDeviceOrd, MCI_BUFFER, - MCI_WAIT | MCI_ALLOCATE_MEMORY, - &(_this->hidden->BufferParms), 0); - if ((rc!=MCIERR_SUCCESS) || (iNumBufs != _this->hidden->BufferParms.ulNumBuffers) || (_this->hidden->BufferParms.ulBufferSize==0)) - { // Could not allocate memory! - // Close DART, and exit with error code! - SDL_free(_this->hidden->pMixBuffers); _this->hidden->pMixBuffers = NULL; - mciSendCommand(iDeviceOrd, MCI_CLOSE, MCI_WAIT, &GenericParms, 0); - SDL_SetError("DART could not allocate buffers"); - return(-1); - } - // Ok, we have all the buffers allocated, let's mark them! - { - int i; - for (i=0; ihidden->pMixBuffers[i].pBuffer)) || (!pBufferDesc)) - { // Wrong buffer! + return (-1); + } + iFreq = spec->freq; + iChannels = spec->channels; + /* Update the fragment size as size in bytes */ + SDL_CalculateAudioSpec(spec); + iBufSize = spec->size; + + // Now query this device if it supports the given freq/bits/channels! + SDL_memset(&(_this->hidden->MixSetupParms), 0, + sizeof(MCI_MIXSETUP_PARMS)); + _this->hidden->MixSetupParms.ulBitsPerSample = iBits; + _this->hidden->MixSetupParms.ulFormatTag = MCI_WAVE_FORMAT_PCM; + _this->hidden->MixSetupParms.ulSamplesPerSec = iFreq; + _this->hidden->MixSetupParms.ulChannels = iChannels; + _this->hidden->MixSetupParms.ulFormatMode = MCI_PLAY; + _this->hidden->MixSetupParms.ulDeviceType = MCI_DEVTYPE_WAVEFORM_AUDIO; + _this->hidden->MixSetupParms.pmixEvent = DARTEventFunc; + rc = mciSendCommand(iDeviceOrd, MCI_MIXSETUP, + MCI_WAIT | MCI_MIXSETUP_QUERYMODE, + &(_this->hidden->MixSetupParms), 0); + if (rc != MCIERR_SUCCESS) { // The device cannot handle this format! + // Close DART, and exit with error code! + mciSendCommand(iDeviceOrd, MCI_CLOSE, MCI_WAIT, &GenericParms, 0); + SDL_SetError("Audio device doesn't support requested audio format"); + return (-1); + } + // The device can handle this format, so initialize! + rc = mciSendCommand(iDeviceOrd, MCI_MIXSETUP, + MCI_WAIT | MCI_MIXSETUP_INIT, + &(_this->hidden->MixSetupParms), 0); + if (rc != MCIERR_SUCCESS) { // The device could not be opened! // Close DART, and exit with error code! - // Free buffer descriptions - { int j; - for (j=0; jhidden->pMixBuffers[j].ulUserParm)); - } - // and cleanup - mciSendCommand(iDeviceOrd, MCI_BUFFER, MCI_WAIT | MCI_DEALLOCATE_MEMORY, &(_this->hidden->BufferParms), 0); - SDL_free(_this->hidden->pMixBuffers); _this->hidden->pMixBuffers = NULL; mciSendCommand(iDeviceOrd, MCI_CLOSE, MCI_WAIT, &GenericParms, 0); - SDL_SetError("Error at internal buffer check"); - return(-1); - } - pBufferDesc->iBufferUsage = BUFFER_EMPTY; - pBufferDesc->pSDLAudioDevice = _this; - - _this->hidden->pMixBuffers[i].ulBufferLength = _this->hidden->BufferParms.ulBufferSize; - _this->hidden->pMixBuffers[i].ulUserParm = (ULONG) pBufferDesc; // User parameter: Description of buffer - _this->hidden->pMixBuffers[i].ulFlags = 0; // Some stuff should be flagged here for DART, like end of - // audio data, but as we will continously send - // audio data, there will be no end.:) - SDL_memset(_this->hidden->pMixBuffers[i].pBuffer, iSilence, iBufSize); + SDL_SetError("Audio device could not be set up"); + return (-1); } - } - _this->hidden->iNextFreeBuffer = 0; - _this->hidden->iLastPlayedBuf = -1; - // Create event semaphore - if (DosCreateEventSem(NULL, &(_this->hidden->hevAudioBufferPlayed), 0, FALSE)!=NO_ERROR) - { - // Could not create event semaphore! + // Ok, the device is initialized. + // Now we should allocate buffers. For this, we need a place where + // the buffer descriptors will be: + _this->hidden->pMixBuffers = + (MCI_MIX_BUFFER *) SDL_malloc(sizeof(MCI_MIX_BUFFER) * iNumBufs); + if (!(_this->hidden->pMixBuffers)) { // Not enough memory! + // Close DART, and exit with error code! + mciSendCommand(iDeviceOrd, MCI_CLOSE, MCI_WAIT, &GenericParms, 0); + SDL_SetError("Not enough memory for audio buffer descriptors"); + return (-1); + } + // Now that we have the place for buffer list, we can ask DART for the + // buffers! + _this->hidden->BufferParms.ulNumBuffers = iNumBufs; // Number of buffers + _this->hidden->BufferParms.ulBufferSize = iBufSize; // each with this size + _this->hidden->BufferParms.pBufList = _this->hidden->pMixBuffers; // getting descriptorts into this list + // Allocate buffers! + rc = mciSendCommand(iDeviceOrd, MCI_BUFFER, + MCI_WAIT | MCI_ALLOCATE_MEMORY, + &(_this->hidden->BufferParms), 0); + if ((rc != MCIERR_SUCCESS) + || (iNumBufs != _this->hidden->BufferParms.ulNumBuffers) + || (_this->hidden->BufferParms.ulBufferSize == 0)) { // Could not allocate memory! + // Close DART, and exit with error code! + SDL_free(_this->hidden->pMixBuffers); + _this->hidden->pMixBuffers = NULL; + mciSendCommand(iDeviceOrd, MCI_CLOSE, MCI_WAIT, &GenericParms, 0); + SDL_SetError("DART could not allocate buffers"); + return (-1); + } + // Ok, we have all the buffers allocated, let's mark them! { - int i; - for (i=0; ihidden->pMixBuffers[i].ulUserParm)); + int i; + for (i = 0; i < iNumBufs; i++) { + pMixBufferDesc pBufferDesc = + (pMixBufferDesc) SDL_malloc(sizeof(tMixBufferDesc));; + // Check if this buffer was really allocated by DART + if ((!(_this->hidden->pMixBuffers[i].pBuffer)) + || (!pBufferDesc)) { // Wrong buffer! + // Close DART, and exit with error code! + // Free buffer descriptions + { + int j; + for (j = 0; j < i; j++) + SDL_free((void *) (_this->hidden->pMixBuffers[j]. + ulUserParm)); + } + // and cleanup + mciSendCommand(iDeviceOrd, MCI_BUFFER, + MCI_WAIT | MCI_DEALLOCATE_MEMORY, + &(_this->hidden->BufferParms), 0); + SDL_free(_this->hidden->pMixBuffers); + _this->hidden->pMixBuffers = NULL; + mciSendCommand(iDeviceOrd, MCI_CLOSE, MCI_WAIT, + &GenericParms, 0); + SDL_SetError("Error at internal buffer check"); + return (-1); + } + pBufferDesc->iBufferUsage = BUFFER_EMPTY; + pBufferDesc->pSDLAudioDevice = _this; + + _this->hidden->pMixBuffers[i].ulBufferLength = + _this->hidden->BufferParms.ulBufferSize; + _this->hidden->pMixBuffers[i].ulUserParm = (ULONG) pBufferDesc; // User parameter: Description of buffer + _this->hidden->pMixBuffers[i].ulFlags = 0; // Some stuff should be flagged here for DART, like end of + // audio data, but as we will continously send + // audio data, there will be no end.:) + SDL_memset(_this->hidden->pMixBuffers[i].pBuffer, iSilence, + iBufSize); + } } - mciSendCommand(iDeviceOrd, MCI_BUFFER, MCI_WAIT | MCI_DEALLOCATE_MEMORY, &(_this->hidden->BufferParms), 0); - SDL_free(_this->hidden->pMixBuffers); _this->hidden->pMixBuffers = NULL; - mciSendCommand(iDeviceOrd, MCI_CLOSE, MCI_WAIT, &GenericParms, 0); - SDL_SetError("Could not create event semaphore"); - return(-1); - } - - // Store the new settings in global variables - _this->hidden->iCurrDeviceOrd = iDeviceOrd; - _this->hidden->iCurrFreq = iFreq; - _this->hidden->iCurrBits = iBits; - _this->hidden->iCurrChannels = iChannels; - _this->hidden->iCurrNumBufs = iNumBufs; - _this->hidden->iCurrBufSize = iBufSize; - - return (0); + _this->hidden->iNextFreeBuffer = 0; + _this->hidden->iLastPlayedBuf = -1; + // Create event semaphore + if (DosCreateEventSem + (NULL, &(_this->hidden->hevAudioBufferPlayed), 0, FALSE) != NO_ERROR) + { + // Could not create event semaphore! + { + int i; + for (i = 0; i < iNumBufs; i++) + SDL_free((void *) (_this->hidden->pMixBuffers[i].ulUserParm)); + } + mciSendCommand(iDeviceOrd, MCI_BUFFER, + MCI_WAIT | MCI_DEALLOCATE_MEMORY, + &(_this->hidden->BufferParms), 0); + SDL_free(_this->hidden->pMixBuffers); + _this->hidden->pMixBuffers = NULL; + mciSendCommand(iDeviceOrd, MCI_CLOSE, MCI_WAIT, &GenericParms, 0); + SDL_SetError("Could not create event semaphore"); + return (-1); + } + // Store the new settings in global variables + _this->hidden->iCurrDeviceOrd = iDeviceOrd; + _this->hidden->iCurrFreq = iFreq; + _this->hidden->iCurrBits = iBits; + _this->hidden->iCurrChannels = iChannels; + _this->hidden->iCurrNumBufs = iNumBufs; + _this->hidden->iCurrBufSize = iBufSize; + + return (0); } -void DART_ThreadInit(_THIS) +void +DART_ThreadInit(_THIS) { - return; + return; } /* This function waits until it is possible to write a full sound buffer */ -void DART_WaitAudio(_THIS) +void +DART_WaitAudio(_THIS) { - int i; - pMixBufferDesc pBufDesc; - ULONG ulPostCount; - - DosResetEventSem(_this->hidden->hevAudioBufferPlayed, &ulPostCount); - // If there is already an empty buffer, then return now! - for (i=0; i<_this->hidden->iCurrNumBufs; i++) - { - pBufDesc = (pMixBufferDesc) _this->hidden->pMixBuffers[i].ulUserParm; - if (pBufDesc->iBufferUsage == BUFFER_EMPTY) - return; - } - // If there is no empty buffer, wait for one to be empty! - DosWaitEventSem(_this->hidden->hevAudioBufferPlayed, 1000); // Wait max 1 sec!!! Important! - return; + int i; + pMixBufferDesc pBufDesc; + ULONG ulPostCount; + + DosResetEventSem(_this->hidden->hevAudioBufferPlayed, &ulPostCount); + // If there is already an empty buffer, then return now! + for (i = 0; i < _this->hidden->iCurrNumBufs; i++) { + pBufDesc = (pMixBufferDesc) _this->hidden->pMixBuffers[i].ulUserParm; + if (pBufDesc->iBufferUsage == BUFFER_EMPTY) + return; + } + // If there is no empty buffer, wait for one to be empty! + DosWaitEventSem(_this->hidden->hevAudioBufferPlayed, 1000); // Wait max 1 sec!!! Important! + return; } -void DART_PlayAudio(_THIS) +void +DART_PlayAudio(_THIS) { - int iFreeBuf = _this->hidden->iNextFreeBuffer; - pMixBufferDesc pBufDesc; - - pBufDesc = (pMixBufferDesc) _this->hidden->pMixBuffers[iFreeBuf].ulUserParm; - pBufDesc->iBufferUsage = BUFFER_USED; - // Send it to DART to be queued - _this->hidden->MixSetupParms.pmixWrite(_this->hidden->MixSetupParms.ulMixHandle, - &(_this->hidden->pMixBuffers[iFreeBuf]), 1); - - _this->hidden->iLastPlayedBuf = iFreeBuf; - iFreeBuf = (iFreeBuf+1) % _this->hidden->iCurrNumBufs; - _this->hidden->iNextFreeBuffer = iFreeBuf; + int iFreeBuf = _this->hidden->iNextFreeBuffer; + pMixBufferDesc pBufDesc; + + pBufDesc = + (pMixBufferDesc) _this->hidden->pMixBuffers[iFreeBuf].ulUserParm; + pBufDesc->iBufferUsage = BUFFER_USED; + // Send it to DART to be queued + _this->hidden->MixSetupParms.pmixWrite(_this->hidden->MixSetupParms. + ulMixHandle, + &(_this->hidden-> + pMixBuffers[iFreeBuf]), 1); + + _this->hidden->iLastPlayedBuf = iFreeBuf; + iFreeBuf = (iFreeBuf + 1) % _this->hidden->iCurrNumBufs; + _this->hidden->iNextFreeBuffer = iFreeBuf; } -Uint8 *DART_GetAudioBuf(_THIS) +Uint8 * +DART_GetAudioBuf(_THIS) { - int iFreeBuf; - Uint8 *pResult; - pMixBufferDesc pBufDesc; + int iFreeBuf; + Uint8 *pResult; + pMixBufferDesc pBufDesc; - if (_this) - { - if (_this->hidden) - { - iFreeBuf = _this->hidden->iNextFreeBuffer; - pBufDesc = (pMixBufferDesc) _this->hidden->pMixBuffers[iFreeBuf].ulUserParm; - - if (pBufDesc) - { - if (pBufDesc->iBufferUsage == BUFFER_EMPTY) - { - pResult = _this->hidden->pMixBuffers[iFreeBuf].pBuffer; - return pResult; - } - } else - printf("[DART_GetAudioBuf] : ERROR! pBufDesc = %p\n", pBufDesc); + if (_this) { + if (_this->hidden) { + iFreeBuf = _this->hidden->iNextFreeBuffer; + pBufDesc = + (pMixBufferDesc) _this->hidden->pMixBuffers[iFreeBuf]. + ulUserParm; + + if (pBufDesc) { + if (pBufDesc->iBufferUsage == BUFFER_EMPTY) { + pResult = _this->hidden->pMixBuffers[iFreeBuf].pBuffer; + return pResult; + } + } else + printf("[DART_GetAudioBuf] : ERROR! pBufDesc = %p\n", + pBufDesc); + } else + printf("[DART_GetAudioBuf] : ERROR! _this->hidden = %p\n", + _this->hidden); } else - printf("[DART_GetAudioBuf] : ERROR! _this->hidden = %p\n", _this->hidden); - } else - printf("[DART_GetAudioBuf] : ERROR! _this = %p\n", _this); - return NULL; + printf("[DART_GetAudioBuf] : ERROR! _this = %p\n", _this); + return NULL; } -void DART_WaitDone(_THIS) +void +DART_WaitDone(_THIS) { - pMixBufferDesc pBufDesc; - ULONG ulPostCount; - APIRET rc; - - pBufDesc = (pMixBufferDesc) _this->hidden->pMixBuffers[_this->hidden->iLastPlayedBuf].ulUserParm; - rc = NO_ERROR; - while ((pBufDesc->iBufferUsage != BUFFER_EMPTY) && (rc==NO_ERROR)) - { - DosResetEventSem(_this->hidden->hevAudioBufferPlayed, &ulPostCount); - rc = DosWaitEventSem(_this->hidden->hevAudioBufferPlayed, 1000); // 1 sec timeout! Important! - } + pMixBufferDesc pBufDesc; + ULONG ulPostCount; + APIRET rc; + + pBufDesc = + (pMixBufferDesc) _this->hidden->pMixBuffers[_this->hidden-> + iLastPlayedBuf]. + ulUserParm; + rc = NO_ERROR; + while ((pBufDesc->iBufferUsage != BUFFER_EMPTY) && (rc == NO_ERROR)) { + DosResetEventSem(_this->hidden->hevAudioBufferPlayed, &ulPostCount); + rc = DosWaitEventSem(_this->hidden->hevAudioBufferPlayed, 1000); // 1 sec timeout! Important! + } } -void DART_CloseAudio(_THIS) +void +DART_CloseAudio(_THIS) { - MCI_GENERIC_PARMS GenericParms; - int rc; + MCI_GENERIC_PARMS GenericParms; + int rc; - // Stop DART playback - rc = mciSendCommand(_this->hidden->iCurrDeviceOrd, MCI_STOP, MCI_WAIT, &GenericParms, 0); - if (rc!=MCIERR_SUCCESS) - { + // Stop DART playback + rc = mciSendCommand(_this->hidden->iCurrDeviceOrd, MCI_STOP, MCI_WAIT, + &GenericParms, 0); + if (rc != MCIERR_SUCCESS) { #ifdef SFX_DEBUG_BUILD - printf("Could not stop DART playback!\n"); - fflush(stdout); + printf("Could not stop DART playback!\n"); + fflush(stdout); #endif - } - - // Close event semaphore - DosCloseEventSem(_this->hidden->hevAudioBufferPlayed); + } + // Close event semaphore + DosCloseEventSem(_this->hidden->hevAudioBufferPlayed); - // Free memory of buffer descriptions - { - int i; - for (i=0; i<_this->hidden->iCurrNumBufs; i++) SDL_free((void *)(_this->hidden->pMixBuffers[i].ulUserParm)); - } + // Free memory of buffer descriptions + { + int i; + for (i = 0; i < _this->hidden->iCurrNumBufs; i++) + SDL_free((void *) (_this->hidden->pMixBuffers[i].ulUserParm)); + } - // Deallocate buffers - rc = mciSendCommand(_this->hidden->iCurrDeviceOrd, MCI_BUFFER, MCI_WAIT | MCI_DEALLOCATE_MEMORY, &(_this->hidden->BufferParms), 0); + // Deallocate buffers + rc = mciSendCommand(_this->hidden->iCurrDeviceOrd, MCI_BUFFER, + MCI_WAIT | MCI_DEALLOCATE_MEMORY, + &(_this->hidden->BufferParms), 0); - // Free bufferlist - SDL_free(_this->hidden->pMixBuffers); _this->hidden->pMixBuffers = NULL; + // Free bufferlist + SDL_free(_this->hidden->pMixBuffers); + _this->hidden->pMixBuffers = NULL; - // Close dart - rc = mciSendCommand(_this->hidden->iCurrDeviceOrd, MCI_CLOSE, MCI_WAIT, &(GenericParms), 0); + // Close dart + rc = mciSendCommand(_this->hidden->iCurrDeviceOrd, MCI_CLOSE, MCI_WAIT, + &(GenericParms), 0); } /* Audio driver bootstrap functions */ -int Audio_Available(void) +int +Audio_Available(void) { - return(1); + return (1); } -void Audio_DeleteDevice(SDL_AudioDevice *device) +void +Audio_DeleteDevice(SDL_AudioDevice * device) { - SDL_free(device->hidden); - SDL_free(device); + SDL_free(device->hidden); + SDL_free(device); } -SDL_AudioDevice *Audio_CreateDevice(int devindex) +SDL_AudioDevice * +Audio_CreateDevice(int devindex) { - SDL_AudioDevice *this; - - /* Initialize all variables that we clean on shutdown */ - this = (SDL_AudioDevice *)SDL_malloc(sizeof(SDL_AudioDevice)); - if ( this ) - { - SDL_memset(this, 0, (sizeof *this)); - this->hidden = (struct SDL_PrivateAudioData *) - SDL_malloc((sizeof *this->hidden)); - } - if ( (this == NULL) || (this->hidden == NULL) ) - { - SDL_OutOfMemory(); - if ( this ) - SDL_free(this); - return(0); - } - SDL_memset(this->hidden, 0, (sizeof *this->hidden)); - - /* Set the function pointers */ - this->OpenAudio = DART_OpenAudio; - this->ThreadInit = DART_ThreadInit; - this->WaitAudio = DART_WaitAudio; - this->PlayAudio = DART_PlayAudio; - this->GetAudioBuf = DART_GetAudioBuf; - this->WaitDone = DART_WaitDone; - this->CloseAudio = DART_CloseAudio; - - this->free = Audio_DeleteDevice; - - return this; + SDL_AudioDevice *this; + + /* Initialize all variables that we clean on shutdown */ + this = (SDL_AudioDevice *) SDL_malloc(sizeof(SDL_AudioDevice)); + if (this) { + SDL_memset(this, 0, (sizeof *this)); + this->hidden = (struct SDL_PrivateAudioData *) + SDL_malloc((sizeof *this->hidden)); + } + if ((this == NULL) || (this->hidden == NULL)) { + SDL_OutOfMemory(); + if (this) + SDL_free(this); + return (0); + } + SDL_memset(this->hidden, 0, (sizeof *this->hidden)); + + /* Set the function pointers */ + this->OpenAudio = DART_OpenAudio; + this->ThreadInit = DART_ThreadInit; + this->WaitAudio = DART_WaitAudio; + this->PlayAudio = DART_PlayAudio; + this->GetAudioBuf = DART_GetAudioBuf; + this->WaitDone = DART_WaitDone; + this->CloseAudio = DART_CloseAudio; + + this->free = Audio_DeleteDevice; + + return this; } AudioBootStrap DART_bootstrap = { - "dart", "OS/2 Direct Audio RouTines (DART)", - Audio_Available, Audio_CreateDevice + "dart", "OS/2 Direct Audio RouTines (DART)", + Audio_Available, Audio_CreateDevice }; +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/audio/dart/SDL_dart.h b/src/audio/dart/SDL_dart.h index 895da0040..a58eda3f0 100644 --- a/src/audio/dart/SDL_dart.h +++ b/src/audio/dart/SDL_dart.h @@ -34,7 +34,7 @@ #define INCL_MMIOOS2 #define INCL_MCIOS2 #include -#include // DART stuff and MMIO stuff +#include // DART stuff and MMIO stuff #include "../SDL_sysaudio.h" @@ -44,20 +44,21 @@ /* The DirectSound objects */ struct SDL_PrivateAudioData { - int iCurrDeviceOrd; - int iCurrFreq; - int iCurrBits; - int iCurrChannels; - int iCurrNumBufs; - int iCurrBufSize; - - int iLastPlayedBuf; - int iNextFreeBuffer; - - MCI_BUFFER_PARMS BufferParms; // Sound buffer parameters - MCI_MIX_BUFFER *pMixBuffers; // Sound buffers - MCI_MIXSETUP_PARMS MixSetupParms; // Mixer setup parameters - HEV hevAudioBufferPlayed; // Event semaphore to indicate that an audio buffer has been played by DART + int iCurrDeviceOrd; + int iCurrFreq; + int iCurrBits; + int iCurrChannels; + int iCurrNumBufs; + int iCurrBufSize; + + int iLastPlayedBuf; + int iNextFreeBuffer; + + MCI_BUFFER_PARMS BufferParms; // Sound buffer parameters + MCI_MIX_BUFFER *pMixBuffers; // Sound buffers + MCI_MIXSETUP_PARMS MixSetupParms; // Mixer setup parameters + HEV hevAudioBufferPlayed; // Event semaphore to indicate that an audio buffer has been played by DART }; #endif /* _SDL_lowaudio_h */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/audio/dc/SDL_dcaudio.c b/src/audio/dc/SDL_dcaudio.c index 8715376fa..b47acaefb 100644 --- a/src/audio/dc/SDL_dcaudio.c +++ b/src/audio/dc/SDL_dcaudio.c @@ -35,195 +35,220 @@ #include /* Audio driver functions */ -static int DCAUD_OpenAudio(_THIS, SDL_AudioSpec *spec); +static int DCAUD_OpenAudio(_THIS, SDL_AudioSpec * spec); static void DCAUD_WaitAudio(_THIS); static void DCAUD_PlayAudio(_THIS); static Uint8 *DCAUD_GetAudioBuf(_THIS); static void DCAUD_CloseAudio(_THIS); /* Audio driver bootstrap functions */ -static int DCAUD_Available(void) +static int +DCAUD_Available(void) { - return 1; + return 1; } -static void DCAUD_DeleteDevice(SDL_AudioDevice *device) +static void +DCAUD_DeleteDevice(SDL_AudioDevice * device) { - SDL_free(device->hidden); - SDL_free(device); + SDL_free(device->hidden); + SDL_free(device); } -static SDL_AudioDevice *DCAUD_CreateDevice(int devindex) +static SDL_AudioDevice * +DCAUD_CreateDevice(int devindex) { - SDL_AudioDevice *this; - - /* Initialize all variables that we clean on shutdown */ - this = (SDL_AudioDevice *)SDL_malloc(sizeof(SDL_AudioDevice)); - if ( this ) { - SDL_memset(this, 0, (sizeof *this)); - this->hidden = (struct SDL_PrivateAudioData *) - SDL_malloc((sizeof *this->hidden)); - } - if ( (this == NULL) || (this->hidden == NULL) ) { - SDL_OutOfMemory(); - if ( this ) { - SDL_free(this); - } - return(0); - } - SDL_memset(this->hidden, 0, (sizeof *this->hidden)); - - /* Set the function pointers */ - this->OpenAudio = DCAUD_OpenAudio; - this->WaitAudio = DCAUD_WaitAudio; - this->PlayAudio = DCAUD_PlayAudio; - this->GetAudioBuf = DCAUD_GetAudioBuf; - this->CloseAudio = DCAUD_CloseAudio; - - this->free = DCAUD_DeleteDevice; - - spu_init(); - - return this; + SDL_AudioDevice *this; + + /* Initialize all variables that we clean on shutdown */ + this = (SDL_AudioDevice *) SDL_malloc(sizeof(SDL_AudioDevice)); + if (this) { + SDL_memset(this, 0, (sizeof *this)); + this->hidden = (struct SDL_PrivateAudioData *) + SDL_malloc((sizeof *this->hidden)); + } + if ((this == NULL) || (this->hidden == NULL)) { + SDL_OutOfMemory(); + if (this) { + SDL_free(this); + } + return (0); + } + SDL_memset(this->hidden, 0, (sizeof *this->hidden)); + + /* Set the function pointers */ + this->OpenAudio = DCAUD_OpenAudio; + this->WaitAudio = DCAUD_WaitAudio; + this->PlayAudio = DCAUD_PlayAudio; + this->GetAudioBuf = DCAUD_GetAudioBuf; + this->CloseAudio = DCAUD_CloseAudio; + + this->free = DCAUD_DeleteDevice; + + spu_init(); + + return this; } AudioBootStrap DCAUD_bootstrap = { - "dcaudio", "Dreamcast AICA audio", - DCAUD_Available, DCAUD_CreateDevice + "dcaudio", "Dreamcast AICA audio", + DCAUD_Available, DCAUD_CreateDevice }; /* This function waits until it is possible to write a full sound buffer */ -static void DCAUD_WaitAudio(_THIS) +static void +DCAUD_WaitAudio(_THIS) { - if (this->hidden->playing) { - /* wait */ - while(aica_get_pos(0)/this->spec.samples == this->hidden->nextbuf) { - thd_pass(); - } - } + if (this->hidden->playing) { + /* wait */ + while (aica_get_pos(0) / this->spec.samples == this->hidden->nextbuf) { + thd_pass(); + } + } } #define SPU_RAM_BASE 0xa0800000 -static void spu_memload_stereo8(int leftpos,int rightpos,void *src0,size_t size) +static void +spu_memload_stereo8(int leftpos, int rightpos, void *src0, size_t size) { - uint8 *src = src0; - uint32 *left = (uint32*)(leftpos +SPU_RAM_BASE); - uint32 *right = (uint32*)(rightpos+SPU_RAM_BASE); - size = (size+7)/8; - while(size--) { - unsigned lval,rval; - lval = *src++; - rval = *src++; - lval|= (*src++)<<8; - rval|= (*src++)<<8; - lval|= (*src++)<<16; - rval|= (*src++)<<16; - lval|= (*src++)<<24; - rval|= (*src++)<<24; - g2_write_32(left++,lval); - g2_write_32(right++,rval); - g2_fifo_wait(); - } + uint8 *src = src0; + uint32 *left = (uint32 *) (leftpos + SPU_RAM_BASE); + uint32 *right = (uint32 *) (rightpos + SPU_RAM_BASE); + size = (size + 7) / 8; + while (size--) { + unsigned lval, rval; + lval = *src++; + rval = *src++; + lval |= (*src++) << 8; + rval |= (*src++) << 8; + lval |= (*src++) << 16; + rval |= (*src++) << 16; + lval |= (*src++) << 24; + rval |= (*src++) << 24; + g2_write_32(left++, lval); + g2_write_32(right++, rval); + g2_fifo_wait(); + } } -static void spu_memload_stereo16(int leftpos,int rightpos,void *src0,size_t size) +static void +spu_memload_stereo16(int leftpos, int rightpos, void *src0, size_t size) { - uint16 *src = src0; - uint32 *left = (uint32*)(leftpos +SPU_RAM_BASE); - uint32 *right = (uint32*)(rightpos+SPU_RAM_BASE); - size = (size+7)/8; - while(size--) { - unsigned lval,rval; - lval = *src++; - rval = *src++; - lval|= (*src++)<<16; - rval|= (*src++)<<16; - g2_write_32(left++,lval); - g2_write_32(right++,rval); - g2_fifo_wait(); - } + uint16 *src = src0; + uint32 *left = (uint32 *) (leftpos + SPU_RAM_BASE); + uint32 *right = (uint32 *) (rightpos + SPU_RAM_BASE); + size = (size + 7) / 8; + while (size--) { + unsigned lval, rval; + lval = *src++; + rval = *src++; + lval |= (*src++) << 16; + rval |= (*src++) << 16; + g2_write_32(left++, lval); + g2_write_32(right++, rval); + g2_fifo_wait(); + } } -static void DCAUD_PlayAudio(_THIS) +static void +DCAUD_PlayAudio(_THIS) { - SDL_AudioSpec *spec = &this->spec; - unsigned int offset; - - if (this->hidden->playing) { - /* wait */ - while(aica_get_pos(0)/spec->samples == this->hidden->nextbuf) { - thd_pass(); - } - } - - offset = this->hidden->nextbuf*spec->size; - this->hidden->nextbuf^=1; - /* Write the audio data, checking for EAGAIN on broken audio drivers */ - if (spec->channels==1) { - spu_memload(this->hidden->leftpos+offset,this->hidden->mixbuf,this->hidden->mixlen); - } else { - offset/=2; - if ((this->spec.format&255)==8) { - spu_memload_stereo8(this->hidden->leftpos+offset,this->hidden->rightpos+offset,this->hidden->mixbuf,this->hidden->mixlen); - } else { - spu_memload_stereo16(this->hidden->leftpos+offset,this->hidden->rightpos+offset,this->hidden->mixbuf,this->hidden->mixlen); - } - } - - if (!this->hidden->playing) { - int mode; - this->hidden->playing = 1; - mode = (spec->format==AUDIO_S8)?SM_8BIT:SM_16BIT; - if (spec->channels==1) { - aica_play(0,mode,this->hidden->leftpos,0,spec->samples*2,spec->freq,255,128,1); - } else { - aica_play(0,mode,this->hidden->leftpos ,0,spec->samples*2,spec->freq,255,0,1); - aica_play(1,mode,this->hidden->rightpos,0,spec->samples*2,spec->freq,255,255,1); - } - } + SDL_AudioSpec *spec = &this->spec; + unsigned int offset; + + if (this->hidden->playing) { + /* wait */ + while (aica_get_pos(0) / spec->samples == this->hidden->nextbuf) { + thd_pass(); + } + } + + offset = this->hidden->nextbuf * spec->size; + this->hidden->nextbuf ^= 1; + /* Write the audio data, checking for EAGAIN on broken audio drivers */ + if (spec->channels == 1) { + spu_memload(this->hidden->leftpos + offset, this->hidden->mixbuf, + this->hidden->mixlen); + } else { + offset /= 2; + if ((this->spec.format & 255) == 8) { + spu_memload_stereo8(this->hidden->leftpos + offset, + this->hidden->rightpos + offset, + this->hidden->mixbuf, this->hidden->mixlen); + } else { + spu_memload_stereo16(this->hidden->leftpos + offset, + this->hidden->rightpos + offset, + this->hidden->mixbuf, this->hidden->mixlen); + } + } + + if (!this->hidden->playing) { + int mode; + this->hidden->playing = 1; + mode = (spec->format == AUDIO_S8) ? SM_8BIT : SM_16BIT; + if (spec->channels == 1) { + aica_play(0, mode, this->hidden->leftpos, 0, + spec->samples * 2, spec->freq, 255, 128, 1); + } else { + aica_play(0, mode, this->hidden->leftpos, 0, + spec->samples * 2, spec->freq, 255, 0, 1); + aica_play(1, mode, this->hidden->rightpos, 0, + spec->samples * 2, spec->freq, 255, 255, 1); + } + } } -static Uint8 *DCAUD_GetAudioBuf(_THIS) +static Uint8 * +DCAUD_GetAudioBuf(_THIS) { - return(this->hidden->mixbuf); + return (this->hidden->mixbuf); } -static void DCAUD_CloseAudio(_THIS) +static void +DCAUD_CloseAudio(_THIS) { - aica_stop(0); - if (this->spec.channels==2) aica_stop(1); - if ( this->hidden->mixbuf != NULL ) { - SDL_FreeAudioMem(this->hidden->mixbuf); - this->hidden->mixbuf = NULL; - } + aica_stop(0); + if (this->spec.channels == 2) + aica_stop(1); + if (this->hidden->mixbuf != NULL) { + SDL_FreeAudioMem(this->hidden->mixbuf); + this->hidden->mixbuf = NULL; + } } -static int DCAUD_OpenAudio(_THIS, SDL_AudioSpec *spec) +static int +DCAUD_OpenAudio(_THIS, SDL_AudioSpec * spec) { - switch(spec->format&0xff) { - case 8: spec->format = AUDIO_S8; break; - case 16: spec->format = AUDIO_S16LSB; break; - default: - SDL_SetError("Unsupported audio format"); - return(-1); - } - - /* Update the fragment size as size in bytes */ - SDL_CalculateAudioSpec(spec); - - /* Allocate mixing buffer */ - this->hidden->mixlen = spec->size; - this->hidden->mixbuf = (Uint8 *) SDL_AllocAudioMem(this->hidden->mixlen); - if ( this->hidden->mixbuf == NULL ) { - return(-1); - } - SDL_memset(this->hidden->mixbuf, spec->silence, spec->size); - this->hidden->leftpos = 0x11000; - this->hidden->rightpos = 0x11000+spec->size; - this->hidden->playing = 0; - this->hidden->nextbuf = 0; - - /* We're ready to rock and roll. :-) */ - return(0); + switch (spec->format & 0xff) { + case 8: + spec->format = AUDIO_S8; + break; + case 16: + spec->format = AUDIO_S16LSB; + break; + default: + SDL_SetError("Unsupported audio format"); + return (-1); + } + + /* Update the fragment size as size in bytes */ + SDL_CalculateAudioSpec(spec); + + /* Allocate mixing buffer */ + this->hidden->mixlen = spec->size; + this->hidden->mixbuf = (Uint8 *) SDL_AllocAudioMem(this->hidden->mixlen); + if (this->hidden->mixbuf == NULL) { + return (-1); + } + SDL_memset(this->hidden->mixbuf, spec->silence, spec->size); + this->hidden->leftpos = 0x11000; + this->hidden->rightpos = 0x11000 + spec->size; + this->hidden->playing = 0; + this->hidden->nextbuf = 0; + + /* We're ready to rock and roll. :-) */ + return (0); } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/audio/dc/SDL_dcaudio.h b/src/audio/dc/SDL_dcaudio.h index a5b01d3fc..4020f5119 100644 --- a/src/audio/dc/SDL_dcaudio.h +++ b/src/audio/dc/SDL_dcaudio.h @@ -29,13 +29,15 @@ /* Hidden "this" pointer for the video functions */ #define _THIS SDL_AudioDevice *this -struct SDL_PrivateAudioData { - /* The file descriptor for the audio device */ - Uint8 *mixbuf; - Uint32 mixlen; - int playing; - int leftpos,rightpos; - int nextbuf; +struct SDL_PrivateAudioData +{ + /* The file descriptor for the audio device */ + Uint8 *mixbuf; + Uint32 mixlen; + int playing; + int leftpos, rightpos; + int nextbuf; }; #endif /* _SDL_dcaudio_h */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/audio/dc/aica.c b/src/audio/dc/aica.c index b6a1c9364..c6abdfe94 100644 --- a/src/audio/dc/aica.c +++ b/src/audio/dc/aica.c @@ -9,8 +9,10 @@ #include #include -/* #define dc_snd_base ((volatile unsigned char *)0x00800000) */ /* arm side */ -#define dc_snd_base ((volatile unsigned char *)0xa0700000) /* dc side */ +#if 0 +#define dc_snd_base ((volatile unsigned char *)0x00800000) /* arm side */ +#endif +#define dc_snd_base ((volatile unsigned char *)0xa0700000) /* dc side */ /* Some convienence macros */ #define SNDREGADDR(x) (0xa0700000 + (x)) @@ -39,26 +41,29 @@ } while(0) -void aica_init() { - int i, j, old = 0; - - /* Initialize AICA channels */ - G2_LOCK(old); - SNDREG32(0x2800) = 0x0000; - - for (i=0; i<64; i++) { - for (j=0; j<0x80; j+=4) { - if ((j&31)==0) g2_fifo_wait(); - CHNREG32(i, j) = 0; - } - g2_fifo_wait(); - CHNREG32(i,0) = 0x8000; - CHNREG32(i,20) = 0x1f; - } +void +aica_init() +{ + int i, j, old = 0; + + /* Initialize AICA channels */ + G2_LOCK(old); + SNDREG32(0x2800) = 0x0000; + + for (i = 0; i < 64; i++) { + for (j = 0; j < 0x80; j += 4) { + if ((j & 31) == 0) + g2_fifo_wait(); + CHNREG32(i, j) = 0; + } + g2_fifo_wait(); + CHNREG32(i, 0) = 0x8000; + CHNREG32(i, 20) = 0x1f; + } - SNDREG32(0x2800) = 0x000f; - g2_fifo_wait(); - G2_UNLOCK(old); + SNDREG32(0x2800) = 0x000f; + g2_fifo_wait(); + G2_UNLOCK(old); } /* Translates a volume from linear form to logarithmic form (required by @@ -86,25 +91,25 @@ void aica_init() { }; */ const static unsigned char logs[] = { - 0, 15, 22, 27, 31, 35, 39, 42, 45, 47, 50, 52, 55, 57, 59, 61, - 63, 65, 67, 69, 71, 73, 74, 76, 78, 79, 81, 82, 84, 85, 87, 88, - 90, 91, 92, 94, 95, 96, 98, 99, 100, 102, 103, 104, 105, 106, - 108, 109, 110, 111, 112, 113, 114, 116, 117, 118, 119, 120, 121, - 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, - 135, 136, 137, 138, 138, 139, 140, 141, 142, 143, 144, 145, 146, - 146, 147, 148, 149, 150, 151, 152, 152, 153, 154, 155, 156, 156, - 157, 158, 159, 160, 160, 161, 162, 163, 164, 164, 165, 166, 167, - 167, 168, 169, 170, 170, 171, 172, 173, 173, 174, 175, 176, 176, - 177, 178, 178, 179, 180, 181, 181, 182, 183, 183, 184, 185, 185, - 186, 187, 187, 188, 189, 189, 190, 191, 191, 192, 193, 193, 194, - 195, 195, 196, 197, 197, 198, 199, 199, 200, 200, 201, 202, 202, - 203, 204, 204, 205, 205, 206, 207, 207, 208, 209, 209, 210, 210, - 211, 212, 212, 213, 213, 214, 215, 215, 216, 216, 217, 217, 218, - 219, 219, 220, 220, 221, 221, 222, 223, 223, 224, 224, 225, 225, - 226, 227, 227, 228, 228, 229, 229, 230, 230, 231, 232, 232, 233, - 233, 234, 234, 235, 235, 236, 236, 237, 237, 238, 239, 239, 240, - 240, 241, 241, 242, 242, 243, 243, 244, 244, 245, 245, 246, 246, - 247, 247, 248, 248, 249, 249, 250, 250, 251, 251, 252, 252, 253, 254, 255 + 0, 15, 22, 27, 31, 35, 39, 42, 45, 47, 50, 52, 55, 57, 59, 61, + 63, 65, 67, 69, 71, 73, 74, 76, 78, 79, 81, 82, 84, 85, 87, 88, + 90, 91, 92, 94, 95, 96, 98, 99, 100, 102, 103, 104, 105, 106, + 108, 109, 110, 111, 112, 113, 114, 116, 117, 118, 119, 120, 121, + 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, + 135, 136, 137, 138, 138, 139, 140, 141, 142, 143, 144, 145, 146, + 146, 147, 148, 149, 150, 151, 152, 152, 153, 154, 155, 156, 156, + 157, 158, 159, 160, 160, 161, 162, 163, 164, 164, 165, 166, 167, + 167, 168, 169, 170, 170, 171, 172, 173, 173, 174, 175, 176, 176, + 177, 178, 178, 179, 180, 181, 181, 182, 183, 183, 184, 185, 185, + 186, 187, 187, 188, 189, 189, 190, 191, 191, 192, 193, 193, 194, + 195, 195, 196, 197, 197, 198, 199, 199, 200, 200, 201, 202, 202, + 203, 204, 204, 205, 205, 206, 207, 207, 208, 209, 209, 210, 210, + 211, 212, 212, 213, 213, 214, 215, 215, 216, 216, 217, 217, 218, + 219, 219, 220, 220, 221, 221, 222, 223, 223, 224, 224, 225, 225, + 226, 227, 227, 228, 228, 229, 229, 230, 230, 231, 232, 232, 233, + 233, 234, 234, 235, 235, 236, 236, 237, 237, 238, 239, 239, 240, + 240, 241, 241, 242, 242, 243, 243, 244, 244, 245, 245, 246, 246, + 247, 247, 248, 248, 249, 249, 250, 250, 251, 251, 252, 252, 253, 254, 255 }; /* For the moment this is going to have to suffice, until we really @@ -113,23 +118,25 @@ const static unsigned char logs[] = { #define AICA_VOL(x) (0xff - logs[128 + (((x) & 0xff) / 2)]) //#define AICA_VOL(x) (0xff - logs[x&255]) -static inline unsigned AICA_FREQ(unsigned freq) { - unsigned long freq_lo, freq_base = 5644800; - int freq_hi = 7; +static inline unsigned +AICA_FREQ(unsigned freq) +{ + unsigned long freq_lo, freq_base = 5644800; + int freq_hi = 7; - /* Need to convert frequency to floating point format - (freq_hi is exponent, freq_lo is mantissa) - Formula is ferq = 44100*2^freq_hi*(1+freq_lo/1024) */ - while (freq < freq_base && freq_hi > -8) { - freq_base >>= 1; - --freq_hi; - } - while (freq < freq_base && freq_hi > -8) { - freq_base >>= 1; - freq_hi--; - } - freq_lo = (freq<<10) / freq_base; - return (freq_hi << 11) | (freq_lo & 1023); + /* Need to convert frequency to floating point format + (freq_hi is exponent, freq_lo is mantissa) + Formula is ferq = 44100*2^freq_hi*(1+freq_lo/1024) */ + while (freq < freq_base && freq_hi > -8) { + freq_base >>= 1; + --freq_hi; + } + while (freq < freq_base && freq_hi > -8) { + freq_base >>= 1; + freq_hi--; + } + freq_lo = (freq << 10) / freq_base; + return (freq_hi << 11) | (freq_lo & 1023); } /* Sets up a sound channel completely. This is generally good if you want @@ -148,15 +155,18 @@ static inline unsigned AICA_FREQ(unsigned freq) { This routine (and the similar ones) owe a lot to Marcus' sound example -- I hadn't gotten quite this far into dissecting the individual regs yet. */ -void aica_play(int ch,int mode,unsigned long smpptr,int loopst,int loopend,int freq,int vol,int pan,int loopflag) { +void +aica_play(int ch, int mode, unsigned long smpptr, int loopst, int loopend, + int freq, int vol, int pan, int loopflag) +{ /* int i; */ - int val; - int old = 0; + int val; + int old = 0; - /* Stop the channel (if it's already playing) */ - aica_stop(ch); - /* doesn't seem to be needed, but it's here just in case */ + /* Stop the channel (if it's already playing) */ + aica_stop(ch); + /* doesn't seem to be needed, but it's here just in case */ /* for (i=0; i<256; i++) { asm("nop"); @@ -165,107 +175,127 @@ void aica_play(int ch,int mode,unsigned long smpptr,int loopst,int loopend,int f asm("nop"); } */ - G2_LOCK(old); - /* Envelope setup. The first of these is the loop point, - e.g., where the sample starts over when it loops. The second - is the loop end. This is the full length of the sample when - you are not looping, or the loop end point when you are (though - storing more than that is a waste of memory if you're not doing - volume enveloping). */ - CHNREG32(ch, 8) = loopst & 0xffff; - CHNREG32(ch, 12) = loopend & 0xffff; - - /* Write resulting values */ - CHNREG32(ch, 24) = AICA_FREQ(freq); - - /* Set volume, pan, and some other things that we don't know what - they do =) */ - CHNREG32(ch, 36) = AICA_PAN(pan) | (0xf<<8); - /* Convert the incoming volume and pan into hardware values */ - /* Vol starts at zero so we can ramp */ - vol = AICA_VOL(vol); - CHNREG32(ch, 40) = 0x24 | (vol<<8); - /* Convert the incoming volume and pan into hardware values */ - /* Vol starts at zero so we can ramp */ - - /* If we supported volume envelopes (which we don't yet) then - this value would set that up. The top 4 bits determine the - envelope speed. f is the fastest, 1 is the slowest, and 0 - seems to be an invalid value and does weird things). The - default (below) sets it into normal mode (play and terminate/loop). - CHNREG32(ch, 16) = 0xf010; - */ - CHNREG32(ch, 16) = 0x1f; /* No volume envelope */ - - - /* Set sample format, buffer address, and looping control. If - 0x0200 mask is set on reg 0, the sample loops infinitely. If - it's not set, the sample plays once and terminates. We'll - also set the bits to start playback here. */ - CHNREG32(ch, 4) = smpptr & 0xffff; - val = 0xc000 | 0x0000 | (mode<<7) | (smpptr >> 16); - if (loopflag) val|=0x200; - - CHNREG32(ch, 0) = val; - - G2_UNLOCK(old); - - /* Enable playback */ - /* CHNREG32(ch, 0) |= 0xc000; */ - g2_fifo_wait(); + G2_LOCK(old); + /* Envelope setup. The first of these is the loop point, + e.g., where the sample starts over when it loops. The second + is the loop end. This is the full length of the sample when + you are not looping, or the loop end point when you are (though + storing more than that is a waste of memory if you're not doing + volume enveloping). */ + CHNREG32(ch, 8) = loopst & 0xffff; + CHNREG32(ch, 12) = loopend & 0xffff; + + /* Write resulting values */ + CHNREG32(ch, 24) = AICA_FREQ(freq); + + /* Set volume, pan, and some other things that we don't know what + they do =) */ + CHNREG32(ch, 36) = AICA_PAN(pan) | (0xf << 8); + /* Convert the incoming volume and pan into hardware values */ + /* Vol starts at zero so we can ramp */ + vol = AICA_VOL(vol); + CHNREG32(ch, 40) = 0x24 | (vol << 8); + /* Convert the incoming volume and pan into hardware values */ + /* Vol starts at zero so we can ramp */ + + /* If we supported volume envelopes (which we don't yet) then + this value would set that up. The top 4 bits determine the + envelope speed. f is the fastest, 1 is the slowest, and 0 + seems to be an invalid value and does weird things). The + default (below) sets it into normal mode (play and terminate/loop). + CHNREG32(ch, 16) = 0xf010; + */ + CHNREG32(ch, 16) = 0x1f; /* No volume envelope */ + + + /* Set sample format, buffer address, and looping control. If + 0x0200 mask is set on reg 0, the sample loops infinitely. If + it's not set, the sample plays once and terminates. We'll + also set the bits to start playback here. */ + CHNREG32(ch, 4) = smpptr & 0xffff; + val = 0xc000 | 0x0000 | (mode << 7) | (smpptr >> 16); + if (loopflag) + val |= 0x200; + + CHNREG32(ch, 0) = val; + + G2_UNLOCK(old); + + /* Enable playback */ + /* CHNREG32(ch, 0) |= 0xc000; */ + g2_fifo_wait(); #if 0 - for (i=0xff; i>=vol; i--) { - if ((i&7)==0) g2_fifo_wait(); - CHNREG32(ch, 40) = 0x24 | (i<<8);; - } + for (i = 0xff; i >= vol; i--) { + if ((i & 7) == 0) + g2_fifo_wait(); + CHNREG32(ch, 40) = 0x24 | (i << 8);; + } - g2_fifo_wait(); + g2_fifo_wait(); #endif } /* Stop the sound on a given channel */ -void aica_stop(int ch) { - g2_write_32(CHNREGADDR(ch, 0),(g2_read_32(CHNREGADDR(ch, 0)) & ~0x4000) | 0x8000); - g2_fifo_wait(); +void +aica_stop(int ch) +{ + g2_write_32(CHNREGADDR(ch, 0), + (g2_read_32(CHNREGADDR(ch, 0)) & ~0x4000) | 0x8000); + g2_fifo_wait(); } /* The rest of these routines can change the channel in mid-stride so you can do things like vibrato and panning effects. */ - + /* Set channel volume */ -void aica_vol(int ch,int vol) { -// g2_write_8(CHNREGADDR(ch, 41),AICA_VOL(vol)); - g2_write_32(CHNREGADDR(ch, 40),(g2_read_32(CHNREGADDR(ch, 40))&0xffff00ff)|(AICA_VOL(vol)<<8) ); - g2_fifo_wait(); +void +aica_vol(int ch, int vol) +{ +// g2_write_8(CHNREGADDR(ch, 41),AICA_VOL(vol)); + g2_write_32(CHNREGADDR(ch, 40), + (g2_read_32(CHNREGADDR(ch, 40)) & 0xffff00ff) | + (AICA_VOL(vol) << 8)); + g2_fifo_wait(); } /* Set channel pan */ -void aica_pan(int ch,int pan) { -// g2_write_8(CHNREGADDR(ch, 36),AICA_PAN(pan)); - g2_write_32(CHNREGADDR(ch, 36),(g2_read_32(CHNREGADDR(ch, 36))&0xffffff00)|(AICA_PAN(pan)) ); - g2_fifo_wait(); +void +aica_pan(int ch, int pan) +{ +// g2_write_8(CHNREGADDR(ch, 36),AICA_PAN(pan)); + g2_write_32(CHNREGADDR(ch, 36), + (g2_read_32(CHNREGADDR(ch, 36)) & 0xffffff00) | + (AICA_PAN(pan))); + g2_fifo_wait(); } /* Set channel frequency */ -void aica_freq(int ch,int freq) { - g2_write_32(CHNREGADDR(ch, 24),AICA_FREQ(freq)); - g2_fifo_wait(); +void +aica_freq(int ch, int freq) +{ + g2_write_32(CHNREGADDR(ch, 24), AICA_FREQ(freq)); + g2_fifo_wait(); } /* Get channel position */ -int aica_get_pos(int ch) { +int +aica_get_pos(int ch) +{ #if 1 - /* Observe channel ch */ - g2_write_32(SNDREGADDR(0x280c),(g2_read_32(SNDREGADDR(0x280c))&0xffff00ff) | (ch<<8)); - g2_fifo_wait(); - /* Update position counters */ - return g2_read_32(SNDREGADDR(0x2814)) & 0xffff; + /* Observe channel ch */ + g2_write_32(SNDREGADDR(0x280c), + (g2_read_32(SNDREGADDR(0x280c)) & 0xffff00ff) | (ch << 8)); + g2_fifo_wait(); + /* Update position counters */ + return g2_read_32(SNDREGADDR(0x2814)) & 0xffff; #else - /* Observe channel ch */ - g2_write_8(SNDREGADDR(0x280d),ch); - /* Update position counters */ - return g2_read_32(SNDREGADDR(0x2814)) & 0xffff; + /* Observe channel ch */ + g2_write_8(SNDREGADDR(0x280d), ch); + /* Update position counters */ + return g2_read_32(SNDREGADDR(0x2814)) & 0xffff; #endif } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/audio/dc/aica.h b/src/audio/dc/aica.h index 93155d281..fc51108a3 100644 --- a/src/audio/dc/aica.h +++ b/src/audio/dc/aica.h @@ -30,11 +30,13 @@ #define SM_16BIT 0 #define SM_ADPCM 2 -void aica_play(int ch,int mode,unsigned long smpptr,int looptst,int loopend,int freq,int vol,int pan,int loopflag); +void aica_play(int ch, int mode, unsigned long smpptr, int looptst, + int loopend, int freq, int vol, int pan, int loopflag); void aica_stop(int ch); -void aica_vol(int ch,int vol); -void aica_pan(int ch,int pan); -void aica_freq(int ch,int freq); +void aica_vol(int ch, int vol); +void aica_pan(int ch, int pan); +void aica_freq(int ch, int freq); int aica_get_pos(int ch); #endif +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/audio/disk/SDL_diskaudio.c b/src/audio/disk/SDL_diskaudio.c index d896d9da3..52e237555 100644 --- a/src/audio/disk/SDL_diskaudio.c +++ b/src/audio/disk/SDL_diskaudio.c @@ -47,140 +47,149 @@ #define DISKDEFAULT_WRITEDELAY 150 /* Audio driver functions */ -static int DISKAUD_OpenAudio(_THIS, SDL_AudioSpec *spec); +static int DISKAUD_OpenAudio(_THIS, SDL_AudioSpec * spec); static void DISKAUD_WaitAudio(_THIS); static void DISKAUD_PlayAudio(_THIS); static Uint8 *DISKAUD_GetAudioBuf(_THIS); static void DISKAUD_CloseAudio(_THIS); -static const char *DISKAUD_GetOutputFilename(void) +static const char * +DISKAUD_GetOutputFilename(void) { - const char *envr = SDL_getenv(DISKENVR_OUTFILE); - return((envr != NULL) ? envr : DISKDEFAULT_OUTFILE); + const char *envr = SDL_getenv(DISKENVR_OUTFILE); + return ((envr != NULL) ? envr : DISKDEFAULT_OUTFILE); } /* Audio driver bootstrap functions */ -static int DISKAUD_Available(void) +static int +DISKAUD_Available(void) { - const char *envr = SDL_getenv("SDL_AUDIODRIVER"); - if (envr && (SDL_strcmp(envr, DISKAUD_DRIVER_NAME) == 0)) { - return(1); - } - return(0); + const char *envr = SDL_getenv("SDL_AUDIODRIVER"); + if (envr && (SDL_strcmp(envr, DISKAUD_DRIVER_NAME) == 0)) { + return (1); + } + return (0); } -static void DISKAUD_DeleteDevice(SDL_AudioDevice *device) +static void +DISKAUD_DeleteDevice(SDL_AudioDevice * device) { - SDL_free(device->hidden); - SDL_free(device); + SDL_free(device->hidden); + SDL_free(device); } -static SDL_AudioDevice *DISKAUD_CreateDevice(int devindex) +static SDL_AudioDevice * +DISKAUD_CreateDevice(int devindex) { - SDL_AudioDevice *this; - const char *envr; - - /* Initialize all variables that we clean on shutdown */ - this = (SDL_AudioDevice *)SDL_malloc(sizeof(SDL_AudioDevice)); - if ( this ) { - SDL_memset(this, 0, (sizeof *this)); - this->hidden = (struct SDL_PrivateAudioData *) - SDL_malloc((sizeof *this->hidden)); - } - if ( (this == NULL) || (this->hidden == NULL) ) { - SDL_OutOfMemory(); - if ( this ) { - SDL_free(this); - } - return(0); - } - SDL_memset(this->hidden, 0, (sizeof *this->hidden)); - - envr = SDL_getenv(DISKENVR_WRITEDELAY); - this->hidden->write_delay = (envr) ? SDL_atoi(envr) : DISKDEFAULT_WRITEDELAY; - - /* Set the function pointers */ - this->OpenAudio = DISKAUD_OpenAudio; - this->WaitAudio = DISKAUD_WaitAudio; - this->PlayAudio = DISKAUD_PlayAudio; - this->GetAudioBuf = DISKAUD_GetAudioBuf; - this->CloseAudio = DISKAUD_CloseAudio; - - this->free = DISKAUD_DeleteDevice; - - return this; + SDL_AudioDevice *this; + const char *envr; + + /* Initialize all variables that we clean on shutdown */ + this = (SDL_AudioDevice *) SDL_malloc(sizeof(SDL_AudioDevice)); + if (this) { + SDL_memset(this, 0, (sizeof *this)); + this->hidden = (struct SDL_PrivateAudioData *) + SDL_malloc((sizeof *this->hidden)); + } + if ((this == NULL) || (this->hidden == NULL)) { + SDL_OutOfMemory(); + if (this) { + SDL_free(this); + } + return (0); + } + SDL_memset(this->hidden, 0, (sizeof *this->hidden)); + + envr = SDL_getenv(DISKENVR_WRITEDELAY); + this->hidden->write_delay = + (envr) ? SDL_atoi(envr) : DISKDEFAULT_WRITEDELAY; + + /* Set the function pointers */ + this->OpenAudio = DISKAUD_OpenAudio; + this->WaitAudio = DISKAUD_WaitAudio; + this->PlayAudio = DISKAUD_PlayAudio; + this->GetAudioBuf = DISKAUD_GetAudioBuf; + this->CloseAudio = DISKAUD_CloseAudio; + + this->free = DISKAUD_DeleteDevice; + + return this; } AudioBootStrap DISKAUD_bootstrap = { - DISKAUD_DRIVER_NAME, "direct-to-disk audio", - DISKAUD_Available, DISKAUD_CreateDevice + DISKAUD_DRIVER_NAME, "direct-to-disk audio", + DISKAUD_Available, DISKAUD_CreateDevice }; /* This function waits until it is possible to write a full sound buffer */ -static void DISKAUD_WaitAudio(_THIS) +static void +DISKAUD_WaitAudio(_THIS) { - SDL_Delay(this->hidden->write_delay); + SDL_Delay(this->hidden->write_delay); } -static void DISKAUD_PlayAudio(_THIS) +static void +DISKAUD_PlayAudio(_THIS) { - int written; + int written; - /* Write the audio data */ - written = SDL_RWwrite(this->hidden->output, - this->hidden->mixbuf, 1, - this->hidden->mixlen); + /* Write the audio data */ + written = SDL_RWwrite(this->hidden->output, + this->hidden->mixbuf, 1, this->hidden->mixlen); - /* If we couldn't write, assume fatal error for now */ - if ( (Uint32)written != this->hidden->mixlen ) { - this->enabled = 0; - } + /* If we couldn't write, assume fatal error for now */ + if ((Uint32) written != this->hidden->mixlen) { + this->enabled = 0; + } #ifdef DEBUG_AUDIO - fprintf(stderr, "Wrote %d bytes of audio data\n", written); + fprintf(stderr, "Wrote %d bytes of audio data\n", written); #endif } -static Uint8 *DISKAUD_GetAudioBuf(_THIS) +static Uint8 * +DISKAUD_GetAudioBuf(_THIS) { - return(this->hidden->mixbuf); + return (this->hidden->mixbuf); } -static void DISKAUD_CloseAudio(_THIS) +static void +DISKAUD_CloseAudio(_THIS) { - if ( this->hidden->mixbuf != NULL ) { - SDL_FreeAudioMem(this->hidden->mixbuf); - this->hidden->mixbuf = NULL; - } - if ( this->hidden->output != NULL ) { - SDL_RWclose(this->hidden->output); - this->hidden->output = NULL; - } + if (this->hidden->mixbuf != NULL) { + SDL_FreeAudioMem(this->hidden->mixbuf); + this->hidden->mixbuf = NULL; + } + if (this->hidden->output != NULL) { + SDL_RWclose(this->hidden->output); + this->hidden->output = NULL; + } } -static int DISKAUD_OpenAudio(_THIS, SDL_AudioSpec *spec) +static int +DISKAUD_OpenAudio(_THIS, SDL_AudioSpec * spec) { - const char *fname = DISKAUD_GetOutputFilename(); - - /* Open the audio device */ - this->hidden->output = SDL_RWFromFile(fname, "wb"); - if ( this->hidden->output == NULL ) { - return(-1); - } + const char *fname = DISKAUD_GetOutputFilename(); + /* Open the audio device */ + this->hidden->output = SDL_RWFromFile(fname, "wb"); + if (this->hidden->output == NULL) { + return (-1); + } #if HAVE_STDIO_H - fprintf(stderr, "WARNING: You are using the SDL disk writer" - " audio driver!\n Writing to file [%s].\n", fname); + fprintf(stderr, "WARNING: You are using the SDL disk writer" + " audio driver!\n Writing to file [%s].\n", fname); #endif - /* Allocate mixing buffer */ - this->hidden->mixlen = spec->size; - this->hidden->mixbuf = (Uint8 *) SDL_AllocAudioMem(this->hidden->mixlen); - if ( this->hidden->mixbuf == NULL ) { - return(-1); - } - SDL_memset(this->hidden->mixbuf, spec->silence, spec->size); + /* Allocate mixing buffer */ + this->hidden->mixlen = spec->size; + this->hidden->mixbuf = (Uint8 *) SDL_AllocAudioMem(this->hidden->mixlen); + if (this->hidden->mixbuf == NULL) { + return (-1); + } + SDL_memset(this->hidden->mixbuf, spec->silence, spec->size); - /* We're ready to rock and roll. :-) */ - return(0); + /* We're ready to rock and roll. :-) */ + return (0); } +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/audio/disk/SDL_diskaudio.h b/src/audio/disk/SDL_diskaudio.h index 2ddd68f95..231c55337 100644 --- a/src/audio/disk/SDL_diskaudio.h +++ b/src/audio/disk/SDL_diskaudio.h @@ -30,12 +30,14 @@ /* Hidden "this" pointer for the video functions */ #define _THIS SDL_AudioDevice *this -struct SDL_PrivateAudioData { - /* The file descriptor for the audio device */ - SDL_RWops *output; - Uint8 *mixbuf; - Uint32 mixlen; - Uint32 write_delay; +struct SDL_PrivateAudioData +{ + /* The file descriptor for the audio device */ + SDL_RWops *output; + Uint8 *mixbuf; + Uint32 mixlen; + Uint32 write_delay; }; #endif /* _SDL_diskaudio_h */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/audio/dma/SDL_dmaaudio.c b/src/audio/dma/SDL_dmaaudio.c index 84734a3da..820d23b71 100644 --- a/src/audio/dma/SDL_dmaaudio.c +++ b/src/audio/dma/SDL_dmaaudio.c @@ -24,7 +24,7 @@ /* Allow access to a raw mixing buffer */ #include -#include /* For strerror() */ +#include /* For strerror() */ #include #include #include @@ -60,7 +60,7 @@ #define OPEN_FLAGS (O_RDWR|O_NONBLOCK) /* Audio driver functions */ -static int DMA_OpenAudio(_THIS, SDL_AudioSpec *spec); +static int DMA_OpenAudio(_THIS, SDL_AudioSpec * spec); static void DMA_WaitAudio(_THIS); static void DMA_PlayAudio(_THIS); static Uint8 *DMA_GetAudioBuf(_THIS); @@ -68,388 +68,400 @@ static void DMA_CloseAudio(_THIS); /* Audio driver bootstrap functions */ -static int Audio_Available(void) +static int +Audio_Available(void) { - int available; - int fd; - - available = 0; - - fd = SDL_OpenAudioPath(NULL, 0, OPEN_FLAGS, 0); - if ( fd >= 0 ) { - int caps; - struct audio_buf_info info; - - if ( (ioctl(fd, SNDCTL_DSP_GETCAPS, &caps) == 0) && - (caps & DSP_CAP_TRIGGER) && (caps & DSP_CAP_MMAP) && - (ioctl(fd, SNDCTL_DSP_GETOSPACE, &info) == 0) ) { - available = 1; - } - close(fd); - } - return(available); + int available; + int fd; + + available = 0; + + fd = SDL_OpenAudioPath(NULL, 0, OPEN_FLAGS, 0); + if (fd >= 0) { + int caps; + struct audio_buf_info info; + + if ((ioctl(fd, SNDCTL_DSP_GETCAPS, &caps) == 0) && + (caps & DSP_CAP_TRIGGER) && (caps & DSP_CAP_MMAP) && + (ioctl(fd, SNDCTL_DSP_GETOSPACE, &info) == 0)) { + available = 1; + } + close(fd); + } + return (available); } -static void Audio_DeleteDevice(SDL_AudioDevice *device) +static void +Audio_DeleteDevice(SDL_AudioDevice * device) { - SDL_free(device->hidden); - SDL_free(device); + SDL_free(device->hidden); + SDL_free(device); } -static SDL_AudioDevice *Audio_CreateDevice(int devindex) +static SDL_AudioDevice * +Audio_CreateDevice(int devindex) { - SDL_AudioDevice *this; - - /* Initialize all variables that we clean on shutdown */ - this = (SDL_AudioDevice *)SDL_malloc(sizeof(SDL_AudioDevice)); - if ( this ) { - SDL_memset(this, 0, (sizeof *this)); - this->hidden = (struct SDL_PrivateAudioData *) - SDL_malloc((sizeof *this->hidden)); - } - if ( (this == NULL) || (this->hidden == NULL) ) { - SDL_OutOfMemory(); - if ( this ) { - SDL_free(this); - } - return(0); - } - SDL_memset(this->hidden, 0, (sizeof *this->hidden)); - audio_fd = -1; - - /* Set the function pointers */ - this->OpenAudio = DMA_OpenAudio; - this->WaitAudio = DMA_WaitAudio; - this->PlayAudio = DMA_PlayAudio; - this->GetAudioBuf = DMA_GetAudioBuf; - this->CloseAudio = DMA_CloseAudio; - - this->free = Audio_DeleteDevice; - - return this; + SDL_AudioDevice *this; + + /* Initialize all variables that we clean on shutdown */ + this = (SDL_AudioDevice *) SDL_malloc(sizeof(SDL_AudioDevice)); + if (this) { + SDL_memset(this, 0, (sizeof *this)); + this->hidden = (struct SDL_PrivateAudioData *) + SDL_malloc((sizeof *this->hidden)); + } + if ((this == NULL) || (this->hidden == NULL)) { + SDL_OutOfMemory(); + if (this) { + SDL_free(this); + } + return (0); + } + SDL_memset(this->hidden, 0, (sizeof *this->hidden)); + audio_fd = -1; + + /* Set the function pointers */ + this->OpenAudio = DMA_OpenAudio; + this->WaitAudio = DMA_WaitAudio; + this->PlayAudio = DMA_PlayAudio; + this->GetAudioBuf = DMA_GetAudioBuf; + this->CloseAudio = DMA_CloseAudio; + + this->free = Audio_DeleteDevice; + + return this; } AudioBootStrap DMA_bootstrap = { - DMA_DRIVER_NAME, "OSS /dev/dsp DMA audio", - Audio_Available, Audio_CreateDevice + DMA_DRIVER_NAME, "OSS /dev/dsp DMA audio", + Audio_Available, Audio_CreateDevice }; /* This function waits until it is possible to write a full sound buffer */ -static void DMA_WaitAudio(_THIS) +static void +DMA_WaitAudio(_THIS) { - fd_set fdset; - - /* Check to see if the thread-parent process is still alive */ - { static int cnt = 0; - /* Note that this only works with thread implementations - that use a different process id for each thread. - */ - if (parent && (((++cnt)%10) == 0)) { /* Check every 10 loops */ - if ( kill(parent, 0) < 0 ) { - this->enabled = 0; - } - } - } - - /* See if we need to use timed audio synchronization */ - if ( frame_ticks ) { - /* Use timer for general audio synchronization */ - Sint32 ticks; - - ticks = ((Sint32)(next_frame - SDL_GetTicks()))-FUDGE_TICKS; - if ( ticks > 0 ) { - SDL_Delay(ticks); - } - } else { - /* Use select() for audio synchronization */ - struct timeval timeout; - FD_ZERO(&fdset); - FD_SET(audio_fd, &fdset); - timeout.tv_sec = 10; - timeout.tv_usec = 0; + fd_set fdset; + + /* Check to see if the thread-parent process is still alive */ + { + static int cnt = 0; + /* Note that this only works with thread implementations + that use a different process id for each thread. + */ + if (parent && (((++cnt) % 10) == 0)) { /* Check every 10 loops */ + if (kill(parent, 0) < 0) { + this->enabled = 0; + } + } + } + + /* See if we need to use timed audio synchronization */ + if (frame_ticks) { + /* Use timer for general audio synchronization */ + Sint32 ticks; + + ticks = ((Sint32) (next_frame - SDL_GetTicks())) - FUDGE_TICKS; + if (ticks > 0) { + SDL_Delay(ticks); + } + } else { + /* Use select() for audio synchronization */ + struct timeval timeout; + FD_ZERO(&fdset); + FD_SET(audio_fd, &fdset); + timeout.tv_sec = 10; + timeout.tv_usec = 0; #ifdef DEBUG_AUDIO - fprintf(stderr, "Waiting for audio to get ready\n"); + fprintf(stderr, "Waiting for audio to get ready\n"); #endif - if ( select(audio_fd+1, NULL, &fdset, NULL, &timeout) <= 0 ) { - const char *message = + if (select(audio_fd + 1, NULL, &fdset, NULL, &timeout) <= 0) { + const char *message = #ifdef AUDIO_OSPACE_HACK - "Audio timeout - buggy audio driver? (trying ospace)"; + "Audio timeout - buggy audio driver? (trying ospace)"; #else - "Audio timeout - buggy audio driver? (disabled)"; + "Audio timeout - buggy audio driver? (disabled)"; #endif - /* In general we should never print to the screen, - but in this case we have no other way of letting - the user know what happened. - */ - fprintf(stderr, "SDL: %s\n", message); + /* In general we should never print to the screen, + but in this case we have no other way of letting + the user know what happened. + */ + fprintf(stderr, "SDL: %s\n", message); #ifdef AUDIO_OSPACE_HACK - /* We may be able to use GET_OSPACE trick */ - frame_ticks = (float)(this->spec->samples*1000) / - this->spec->freq; - next_frame = SDL_GetTicks()+frame_ticks; + /* We may be able to use GET_OSPACE trick */ + frame_ticks = (float) (this->spec->samples * 1000) / + this->spec->freq; + next_frame = SDL_GetTicks() + frame_ticks; #else - this->enabled = 0; - /* Don't try to close - may hang */ - audio_fd = -1; + this->enabled = 0; + /* Don't try to close - may hang */ + audio_fd = -1; #ifdef DEBUG_AUDIO - fprintf(stderr, "Done disabling audio\n"); + fprintf(stderr, "Done disabling audio\n"); #endif #endif /* AUDIO_OSPACE_HACK */ - } + } #ifdef DEBUG_AUDIO - fprintf(stderr, "Ready!\n"); + fprintf(stderr, "Ready!\n"); #endif - } + } } -static void DMA_PlayAudio(_THIS) +static void +DMA_PlayAudio(_THIS) { - /* If timer synchronization is enabled, set the next write frame */ - if ( frame_ticks ) { - next_frame += frame_ticks; - } - return; + /* If timer synchronization is enabled, set the next write frame */ + if (frame_ticks) { + next_frame += frame_ticks; + } + return; } -static Uint8 *DMA_GetAudioBuf(_THIS) +static Uint8 * +DMA_GetAudioBuf(_THIS) { - count_info info; - int playing; - int filling; - - /* Get number of blocks, looping if we're not using select() */ - do { - if ( ioctl(audio_fd, SNDCTL_DSP_GETOPTR, &info) < 0 ) { - /* Uh oh... */ - this->enabled = 0; - return(NULL); - } - } while ( frame_ticks && (info.blocks < 1) ); + count_info info; + int playing; + int filling; + + /* Get number of blocks, looping if we're not using select() */ + do { + if (ioctl(audio_fd, SNDCTL_DSP_GETOPTR, &info) < 0) { + /* Uh oh... */ + this->enabled = 0; + return (NULL); + } + } + while (frame_ticks && (info.blocks < 1)); #ifdef DEBUG_AUDIO - if ( info.blocks > 1 ) { - printf("Warning: audio underflow (%d frags)\n", info.blocks-1); - } + if (info.blocks > 1) { + printf("Warning: audio underflow (%d frags)\n", info.blocks - 1); + } #endif - playing = info.ptr / this->spec.size; - filling = (playing + 1)%num_buffers; - return (dma_buf + (filling * this->spec.size)); + playing = info.ptr / this->spec.size; + filling = (playing + 1) % num_buffers; + return (dma_buf + (filling * this->spec.size)); } -static void DMA_CloseAudio(_THIS) +static void +DMA_CloseAudio(_THIS) { - if ( dma_buf != NULL ) { - munmap(dma_buf, dma_len); - dma_buf = NULL; - } - if ( audio_fd >= 0 ) { - close(audio_fd); - audio_fd = -1; - } + if (dma_buf != NULL) { + munmap(dma_buf, dma_len); + dma_buf = NULL; + } + if (audio_fd >= 0) { + close(audio_fd); + audio_fd = -1; + } } -static int DMA_ReopenAudio(_THIS, const char *audiodev, int format, int stereo, - SDL_AudioSpec *spec) +static int +DMA_ReopenAudio(_THIS, const char *audiodev, int format, int stereo, + SDL_AudioSpec * spec) { - int frag_spec; - int value; - - /* Close and then reopen the audio device */ - close(audio_fd); - audio_fd = open(audiodev, O_RDWR, 0); - if ( audio_fd < 0 ) { - SDL_SetError("Couldn't open %s: %s", audiodev, strerror(errno)); - return(-1); - } - - /* Calculate the final parameters for this audio specification */ - SDL_CalculateAudioSpec(spec); - - /* Determine the power of two of the fragment size */ - for ( frag_spec = 0; (0x01<size; ++frag_spec ); - if ( (0x01<size ) { - SDL_SetError("Fragment size must be a power of two"); - return(-1); - } - - /* Set the audio buffering parameters */ - if ( ioctl(audio_fd, SNDCTL_DSP_SETFRAGMENT, &frag_spec) < 0 ) { - SDL_SetError("Couldn't set audio fragment spec"); - return(-1); - } - - /* Set the audio format */ - value = format; - if ( (ioctl(audio_fd, SNDCTL_DSP_SETFMT, &value) < 0) || - (value != format) ) { - SDL_SetError("Couldn't set audio format"); - return(-1); - } - - /* Set mono or stereo audio */ - value = (spec->channels > 1); - if ( (ioctl(audio_fd, SNDCTL_DSP_STEREO, &stereo) < 0) || - (value != stereo) ) { - SDL_SetError("Couldn't set audio channels"); - return(-1); - } - - /* Set the DSP frequency */ - value = spec->freq; - if ( ioctl(audio_fd, SNDCTL_DSP_SPEED, &value) < 0 ) { - SDL_SetError("Couldn't set audio frequency"); - return(-1); - } - spec->freq = value; - - /* We successfully re-opened the audio */ - return(0); + int frag_spec; + int value; + + /* Close and then reopen the audio device */ + close(audio_fd); + audio_fd = open(audiodev, O_RDWR, 0); + if (audio_fd < 0) { + SDL_SetError("Couldn't open %s: %s", audiodev, strerror(errno)); + return (-1); + } + + /* Calculate the final parameters for this audio specification */ + SDL_CalculateAudioSpec(spec); + + /* Determine the power of two of the fragment size */ + for (frag_spec = 0; (0x01 << frag_spec) < spec->size; ++frag_spec); + if ((0x01 << frag_spec) != spec->size) { + SDL_SetError("Fragment size must be a power of two"); + return (-1); + } + + /* Set the audio buffering parameters */ + if (ioctl(audio_fd, SNDCTL_DSP_SETFRAGMENT, &frag_spec) < 0) { + SDL_SetError("Couldn't set audio fragment spec"); + return (-1); + } + + /* Set the audio format */ + value = format; + if ((ioctl(audio_fd, SNDCTL_DSP_SETFMT, &value) < 0) || (value != format)) { + SDL_SetError("Couldn't set audio format"); + return (-1); + } + + /* Set mono or stereo audio */ + value = (spec->channels > 1); + if ((ioctl(audio_fd, SNDCTL_DSP_STEREO, &stereo) < 0) || + (value != stereo)) { + SDL_SetError("Couldn't set audio channels"); + return (-1); + } + + /* Set the DSP frequency */ + value = spec->freq; + if (ioctl(audio_fd, SNDCTL_DSP_SPEED, &value) < 0) { + SDL_SetError("Couldn't set audio frequency"); + return (-1); + } + spec->freq = value; + + /* We successfully re-opened the audio */ + return (0); } -static int DMA_OpenAudio(_THIS, SDL_AudioSpec *spec) +static int +DMA_OpenAudio(_THIS, SDL_AudioSpec * spec) { - char audiodev[1024]; - int format; - int stereo; - int value; - Uint16 test_format; - struct audio_buf_info info; - - /* Reset the timer synchronization flag */ - frame_ticks = 0.0; - - /* Open the audio device */ - audio_fd = SDL_OpenAudioPath(audiodev, sizeof(audiodev), OPEN_FLAGS, 0); - if ( audio_fd < 0 ) { - SDL_SetError("Couldn't open %s: %s", audiodev, strerror(errno)); - return(-1); - } - dma_buf = NULL; - ioctl(audio_fd, SNDCTL_DSP_RESET, 0); - - /* Get a list of supported hardware formats */ - if ( ioctl(audio_fd, SNDCTL_DSP_GETFMTS, &value) < 0 ) { - SDL_SetError("Couldn't get audio format list"); - return(-1); - } - - /* Try for a closest match on audio format */ - format = 0; - for ( test_format = SDL_FirstAudioFormat(spec->format); - ! format && test_format; ) { + char audiodev[1024]; + int format; + int stereo; + int value; + Uint16 test_format; + struct audio_buf_info info; + + /* Reset the timer synchronization flag */ + frame_ticks = 0.0; + + /* Open the audio device */ + audio_fd = SDL_OpenAudioPath(audiodev, sizeof(audiodev), OPEN_FLAGS, 0); + if (audio_fd < 0) { + SDL_SetError("Couldn't open %s: %s", audiodev, strerror(errno)); + return (-1); + } + dma_buf = NULL; + ioctl(audio_fd, SNDCTL_DSP_RESET, 0); + + /* Get a list of supported hardware formats */ + if (ioctl(audio_fd, SNDCTL_DSP_GETFMTS, &value) < 0) { + SDL_SetError("Couldn't get audio format list"); + return (-1); + } + + /* Try for a closest match on audio format */ + format = 0; + for (test_format = SDL_FirstAudioFormat(spec->format); + !format && test_format;) { #ifdef DEBUG_AUDIO - fprintf(stderr, "Trying format 0x%4.4x\n", test_format); + fprintf(stderr, "Trying format 0x%4.4x\n", test_format); #endif - switch ( test_format ) { - case AUDIO_U8: - if ( value & AFMT_U8 ) { - format = AFMT_U8; - } - break; - case AUDIO_S8: - if ( value & AFMT_S8 ) { - format = AFMT_S8; - } - break; - case AUDIO_S16LSB: - if ( value & AFMT_S16_LE ) { - format = AFMT_S16_LE; - } - break; - case AUDIO_S16MSB: - if ( value & AFMT_S16_BE ) { - format = AFMT_S16_BE; - } - break; - case AUDIO_U16LSB: - if ( value & AFMT_U16_LE ) { - format = AFMT_U16_LE; - } - break; - case AUDIO_U16MSB: - if ( value & AFMT_U16_BE ) { - format = AFMT_U16_BE; - } - break; - default: - format = 0; - break; - } - if ( ! format ) { - test_format = SDL_NextAudioFormat(); - } - } - if ( format == 0 ) { - SDL_SetError("Couldn't find any hardware audio formats"); - return(-1); - } - spec->format = test_format; - - /* Set the audio format */ - value = format; - if ( (ioctl(audio_fd, SNDCTL_DSP_SETFMT, &value) < 0) || - (value != format) ) { - SDL_SetError("Couldn't set audio format"); - return(-1); - } - - /* Set mono or stereo audio (currently only two channels supported) */ - stereo = (spec->channels > 1); - ioctl(audio_fd, SNDCTL_DSP_STEREO, &stereo); - if ( stereo ) { - spec->channels = 2; - } else { - spec->channels = 1; - } - - /* Because some drivers don't allow setting the buffer size - after setting the format, we must re-open the audio device - once we know what format and channels are supported - */ - if ( DMA_ReopenAudio(this, audiodev, format, stereo, spec) < 0 ) { - /* Error is set by DMA_ReopenAudio() */ - return(-1); - } - - /* Memory map the audio buffer */ - if ( ioctl(audio_fd, SNDCTL_DSP_GETOSPACE, &info) < 0 ) { - SDL_SetError("Couldn't get OSPACE parameters"); - return(-1); - } - spec->size = info.fragsize; - spec->samples = spec->size / ((spec->format & 0xFF) / 8); - spec->samples /= spec->channels; - num_buffers = info.fragstotal; - dma_len = num_buffers*spec->size; - dma_buf = (Uint8 *)mmap(NULL, dma_len, PROT_WRITE, MAP_SHARED, - audio_fd, 0); - if ( dma_buf == MAP_FAILED ) { - SDL_SetError("DMA memory map failed"); - dma_buf = NULL; - return(-1); - } - SDL_memset(dma_buf, spec->silence, dma_len); - - /* Check to see if we need to use select() workaround */ - { char *workaround; - workaround = SDL_getenv("SDL_DSP_NOSELECT"); - if ( workaround ) { - frame_ticks = (float)(spec->samples*1000)/spec->freq; - next_frame = SDL_GetTicks()+frame_ticks; - } - } - - /* Trigger audio playback */ - value = 0; - ioctl(audio_fd, SNDCTL_DSP_SETTRIGGER, &value); - value = PCM_ENABLE_OUTPUT; - if ( ioctl(audio_fd, SNDCTL_DSP_SETTRIGGER, &value) < 0 ) { - SDL_SetError("Couldn't trigger audio output"); - return(-1); - } - - /* Get the parent process id (we're the parent of the audio thread) */ - parent = getpid(); - - /* We're ready to rock and roll. :-) */ - return(0); + switch (test_format) { + case AUDIO_U8: + if (value & AFMT_U8) { + format = AFMT_U8; + } + break; + case AUDIO_S8: + if (value & AFMT_S8) { + format = AFMT_S8; + } + break; + case AUDIO_S16LSB: + if (value & AFMT_S16_LE) { + format = AFMT_S16_LE; + } + break; + case AUDIO_S16MSB: + if (value & AFMT_S16_BE) { + format = AFMT_S16_BE; + } + break; + case AUDIO_U16LSB: + if (value & AFMT_U16_LE) { + format = AFMT_U16_LE; + } + break; + case AUDIO_U16MSB: + if (value & AFMT_U16_BE) { + format = AFMT_U16_BE; + } + break; + default: + format = 0; + break; + } + if (!format) { + test_format = SDL_NextAudioFormat(); + } + } + if (format == 0) { + SDL_SetError("Couldn't find any hardware audio formats"); + return (-1); + } + spec->format = test_format; + + /* Set the audio format */ + value = format; + if ((ioctl(audio_fd, SNDCTL_DSP_SETFMT, &value) < 0) || (value != format)) { + SDL_SetError("Couldn't set audio format"); + return (-1); + } + + /* Set mono or stereo audio (currently only two channels supported) */ + stereo = (spec->channels > 1); + ioctl(audio_fd, SNDCTL_DSP_STEREO, &stereo); + if (stereo) { + spec->channels = 2; + } else { + spec->channels = 1; + } + + /* Because some drivers don't allow setting the buffer size + after setting the format, we must re-open the audio device + once we know what format and channels are supported + */ + if (DMA_ReopenAudio(this, audiodev, format, stereo, spec) < 0) { + /* Error is set by DMA_ReopenAudio() */ + return (-1); + } + + /* Memory map the audio buffer */ + if (ioctl(audio_fd, SNDCTL_DSP_GETOSPACE, &info) < 0) { + SDL_SetError("Couldn't get OSPACE parameters"); + return (-1); + } + spec->size = info.fragsize; + spec->samples = spec->size / ((spec->format & 0xFF) / 8); + spec->samples /= spec->channels; + num_buffers = info.fragstotal; + dma_len = num_buffers * spec->size; + dma_buf = (Uint8 *) mmap(NULL, dma_len, PROT_WRITE, MAP_SHARED, + audio_fd, 0); + if (dma_buf == MAP_FAILED) { + SDL_SetError("DMA memory map failed"); + dma_buf = NULL; + return (-1); + } + SDL_memset(dma_buf, spec->silence, dma_len); + + /* Check to see if we need to use select() workaround */ + { + char *workaround; + workaround = SDL_getenv("SDL_DSP_NOSELECT"); + if (workaround) { + frame_ticks = (float) (spec->samples * 1000) / spec->freq; + next_frame = SDL_GetTicks() + frame_ticks; + } + } + + /* Trigger audio playback */ + value = 0; + ioctl(audio_fd, SNDCTL_DSP_SETTRIGGER, &value); + value = PCM_ENABLE_OUTPUT; + if (ioctl(audio_fd, SNDCTL_DSP_SETTRIGGER, &value) < 0) { + SDL_SetError("Couldn't trigger audio output"); + return (-1); + } + + /* Get the parent process id (we're the parent of the audio thread) */ + parent = getpid(); + + /* We're ready to rock and roll. :-) */ + return (0); } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/audio/dma/SDL_dmaaudio.h b/src/audio/dma/SDL_dmaaudio.h index ca8c05ad7..1d851bd9f 100644 --- a/src/audio/dma/SDL_dmaaudio.h +++ b/src/audio/dma/SDL_dmaaudio.h @@ -29,23 +29,24 @@ /* Hidden "this" pointer for the video functions */ #define _THIS SDL_AudioDevice *this -struct SDL_PrivateAudioData { - /* The file descriptor for the audio device */ - int audio_fd; - - /* The parent process id, to detect when application quits */ - pid_t parent; - - /* Raw mixing buffer */ - Uint8 *dma_buf; - int dma_len; - int num_buffers; - - /* Support for audio timing using a timer, in addition to select() */ - float frame_ticks; - float next_frame; +struct SDL_PrivateAudioData +{ + /* The file descriptor for the audio device */ + int audio_fd; + + /* The parent process id, to detect when application quits */ + pid_t parent; + + /* Raw mixing buffer */ + Uint8 *dma_buf; + int dma_len; + int num_buffers; + + /* Support for audio timing using a timer, in addition to select() */ + float frame_ticks; + float next_frame; }; -#define FUDGE_TICKS 10 /* The scheduler overhead ticks per frame */ +#define FUDGE_TICKS 10 /* The scheduler overhead ticks per frame */ /* Old variable names */ #define audio_fd (this->hidden->audio_fd) @@ -57,3 +58,4 @@ struct SDL_PrivateAudioData { #define next_frame (this->hidden->next_frame) #endif /* _SDL_dspaudio_h */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/audio/dmedia/SDL_irixaudio.c b/src/audio/dmedia/SDL_irixaudio.c index 96cbaef67..81e09f947 100644 --- a/src/audio/dmedia/SDL_irixaudio.c +++ b/src/audio/dmedia/SDL_irixaudio.c @@ -31,7 +31,7 @@ #include "SDL_irixaudio.h" -#ifndef AL_RESOURCE /* as a test whether we use the old IRIX audio libraries */ +#ifndef AL_RESOURCE /* as a test whether we use the old IRIX audio libraries */ #define OLD_IRIX_AUDIO #define alClosePort(x) ALcloseport(x) #define alFreeConfig(x) ALfreeconfig(x) @@ -45,7 +45,7 @@ #endif /* Audio driver functions */ -static int AL_OpenAudio(_THIS, SDL_AudioSpec *spec); +static int AL_OpenAudio(_THIS, SDL_AudioSpec * spec); static void AL_WaitAudio(_THIS); static void AL_PlayAudio(_THIS); static Uint8 *AL_GetAudioBuf(_THIS); @@ -53,164 +53,177 @@ static void AL_CloseAudio(_THIS); /* Audio driver bootstrap functions */ -static int Audio_Available(void) +static int +Audio_Available(void) { - return 1; + return 1; } -static void Audio_DeleteDevice(SDL_AudioDevice *device) +static void +Audio_DeleteDevice(SDL_AudioDevice * device) { - SDL_free(device->hidden); - SDL_free(device); + SDL_free(device->hidden); + SDL_free(device); } -static SDL_AudioDevice *Audio_CreateDevice(int devindex) +static SDL_AudioDevice * +Audio_CreateDevice(int devindex) { - SDL_AudioDevice *this; - - /* Initialize all variables that we clean on shutdown */ - this = (SDL_AudioDevice *)SDL_malloc(sizeof(SDL_AudioDevice)); - if ( this ) { - SDL_memset(this, 0, (sizeof *this)); - this->hidden = (struct SDL_PrivateAudioData *) - SDL_malloc((sizeof *this->hidden)); - } - if ( (this == NULL) || (this->hidden == NULL) ) { - SDL_OutOfMemory(); - if ( this ) { - SDL_free(this); - } - return(0); - } - SDL_memset(this->hidden, 0, (sizeof *this->hidden)); - - /* Set the function pointers */ - this->OpenAudio = AL_OpenAudio; - this->WaitAudio = AL_WaitAudio; - this->PlayAudio = AL_PlayAudio; - this->GetAudioBuf = AL_GetAudioBuf; - this->CloseAudio = AL_CloseAudio; - - this->free = Audio_DeleteDevice; - - return this; + SDL_AudioDevice *this; + + /* Initialize all variables that we clean on shutdown */ + this = (SDL_AudioDevice *) SDL_malloc(sizeof(SDL_AudioDevice)); + if (this) { + SDL_memset(this, 0, (sizeof *this)); + this->hidden = (struct SDL_PrivateAudioData *) + SDL_malloc((sizeof *this->hidden)); + } + if ((this == NULL) || (this->hidden == NULL)) { + SDL_OutOfMemory(); + if (this) { + SDL_free(this); + } + return (0); + } + SDL_memset(this->hidden, 0, (sizeof *this->hidden)); + + /* Set the function pointers */ + this->OpenAudio = AL_OpenAudio; + this->WaitAudio = AL_WaitAudio; + this->PlayAudio = AL_PlayAudio; + this->GetAudioBuf = AL_GetAudioBuf; + this->CloseAudio = AL_CloseAudio; + + this->free = Audio_DeleteDevice; + + return this; } AudioBootStrap DMEDIA_bootstrap = { - "AL", "IRIX DMedia audio", - Audio_Available, Audio_CreateDevice + "AL", "IRIX DMedia audio", + Audio_Available, Audio_CreateDevice }; -void static AL_WaitAudio(_THIS) +void static +AL_WaitAudio(_THIS) { - Sint32 timeleft; + Sint32 timeleft; - timeleft = this->spec.samples - alGetFillable(audio_port); - if ( timeleft > 0 ) { - timeleft /= (this->spec.freq/1000); - SDL_Delay((Uint32)timeleft); - } + timeleft = this->spec.samples - alGetFillable(audio_port); + if (timeleft > 0) { + timeleft /= (this->spec.freq / 1000); + SDL_Delay((Uint32) timeleft); + } } -static void AL_PlayAudio(_THIS) +static void +AL_PlayAudio(_THIS) { - /* Write the audio data out */ - if ( alWriteFrames(audio_port, mixbuf, this->spec.samples) < 0 ) { - /* Assume fatal error, for now */ - this->enabled = 0; - } + /* Write the audio data out */ + if (alWriteFrames(audio_port, mixbuf, this->spec.samples) < 0) { + /* Assume fatal error, for now */ + this->enabled = 0; + } } -static Uint8 *AL_GetAudioBuf(_THIS) +static Uint8 * +AL_GetAudioBuf(_THIS) { - return(mixbuf); + return (mixbuf); } -static void AL_CloseAudio(_THIS) +static void +AL_CloseAudio(_THIS) { - if ( mixbuf != NULL ) { - SDL_FreeAudioMem(mixbuf); - mixbuf = NULL; - } - if ( audio_port != NULL ) { - alClosePort(audio_port); - audio_port = NULL; - } + if (mixbuf != NULL) { + SDL_FreeAudioMem(mixbuf); + mixbuf = NULL; + } + if (audio_port != NULL) { + alClosePort(audio_port); + audio_port = NULL; + } } -static int AL_OpenAudio(_THIS, SDL_AudioSpec *spec) +static int +AL_OpenAudio(_THIS, SDL_AudioSpec * spec) { - ALconfig audio_config; + ALconfig audio_config; #ifdef OLD_IRIX_AUDIO - long audio_param[2]; + long audio_param[2]; #else - ALpv audio_param; + ALpv audio_param; #endif - int width; - - /* Determine the audio parameters from the AudioSpec */ - switch ( spec->format & 0xFF ) { - - case 8: { /* Signed 8 bit audio data */ - spec->format = AUDIO_S8; - width = AL_SAMPLE_8; - } - break; - - case 16: { /* Signed 16 bit audio data */ - spec->format = AUDIO_S16MSB; - width = AL_SAMPLE_16; - } - break; - - default: { - SDL_SetError("Unsupported audio format"); - return(-1); - } - } - - /* Update the fragment size as size in bytes */ - SDL_CalculateAudioSpec(spec); - - /* Set output frequency */ + int width; + + /* Determine the audio parameters from the AudioSpec */ + switch (spec->format & 0xFF) { + + case 8: + { /* Signed 8 bit audio data */ + spec->format = AUDIO_S8; + width = AL_SAMPLE_8; + } + break; + + case 16: + { /* Signed 16 bit audio data */ + spec->format = AUDIO_S16MSB; + width = AL_SAMPLE_16; + } + break; + + default: + { + SDL_SetError("Unsupported audio format"); + return (-1); + } + } + + /* Update the fragment size as size in bytes */ + SDL_CalculateAudioSpec(spec); + + /* Set output frequency */ #ifdef OLD_IRIX_AUDIO - audio_param[0] = AL_OUTPUT_RATE; - audio_param[1] = spec->freq; - if( ALsetparams(AL_DEFAULT_DEVICE, audio_param, 2) < 0 ) { + audio_param[0] = AL_OUTPUT_RATE; + audio_param[1] = spec->freq; + if (ALsetparams(AL_DEFAULT_DEVICE, audio_param, 2) < 0) { #else - audio_param.param = AL_RATE; - audio_param.value.i = spec->freq; - if( alSetParams(AL_DEFAULT_OUTPUT, &audio_param, 1) < 0 ) { + audio_param.param = AL_RATE; + audio_param.value.i = spec->freq; + if (alSetParams(AL_DEFAULT_OUTPUT, &audio_param, 1) < 0) { #endif - SDL_SetError("alSetParams failed"); - return(-1); - } - - /* Open the audio port with the requested frequency */ - audio_port = NULL; - audio_config = alNewConfig(); - if ( audio_config && - (alSetSampFmt(audio_config, AL_SAMPFMT_TWOSCOMP) >= 0) && - (alSetWidth(audio_config, width) >= 0) && - (alSetQueueSize(audio_config, spec->samples*2) >= 0) && - (alSetChannels(audio_config, spec->channels) >= 0) ) { - audio_port = alOpenPort("SDL audio", "w", audio_config); - } - alFreeConfig(audio_config); - if( audio_port == NULL ) { - SDL_SetError("Unable to open audio port"); - return(-1); - } - - /* Allocate mixing buffer */ - mixbuf = (Uint8 *)SDL_AllocAudioMem(spec->size); - if ( mixbuf == NULL ) { - SDL_OutOfMemory(); - return(-1); - } - SDL_memset(mixbuf, spec->silence, spec->size); - - /* We're ready to rock and roll. :-) */ - return(0); + SDL_SetError("alSetParams failed"); + return (-1); + } + + /* Open the audio port with the requested frequency */ + audio_port = NULL; + audio_config = alNewConfig(); + if (audio_config && + (alSetSampFmt(audio_config, AL_SAMPFMT_TWOSCOMP) >= 0) && + (alSetWidth(audio_config, width) >= 0) && + (alSetQueueSize(audio_config, spec->samples * 2) >= 0) && + (alSetChannels(audio_config, spec->channels) >= 0)) { + audio_port = alOpenPort("SDL audio", "w", audio_config); + } + alFreeConfig(audio_config); + if (audio_port == NULL) { + SDL_SetError("Unable to open audio port"); + return (-1); + } + + /* Allocate mixing buffer */ + mixbuf = (Uint8 *) SDL_AllocAudioMem(spec->size); + if (mixbuf == NULL) { + SDL_OutOfMemory(); + return (-1); + } + SDL_memset(mixbuf, spec->silence, spec->size); + + /* We're ready to rock and roll. :-) */ + return (0); } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/audio/dmedia/SDL_irixaudio.h b/src/audio/dmedia/SDL_irixaudio.h index 751de41f0..41d6b31cb 100644 --- a/src/audio/dmedia/SDL_irixaudio.h +++ b/src/audio/dmedia/SDL_irixaudio.h @@ -31,11 +31,12 @@ /* Hidden "this" pointer for the audio functions */ #define _THIS SDL_AudioDevice *this -struct SDL_PrivateAudioData { - /* The handle for the audio device */ - ALport audio_port; +struct SDL_PrivateAudioData +{ + /* The handle for the audio device */ + ALport audio_port; - Uint8 *mixbuf; /* The app mixing buffer */ + Uint8 *mixbuf; /* The app mixing buffer */ }; /* Old variable names */ @@ -43,3 +44,4 @@ struct SDL_PrivateAudioData { #define mixbuf (this->hidden->mixbuf) #endif /* _SDL_lowaudio_h */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/audio/dsp/SDL_dspaudio.c b/src/audio/dsp/SDL_dspaudio.c index 183cdd170..b933b2956 100644 --- a/src/audio/dsp/SDL_dspaudio.c +++ b/src/audio/dsp/SDL_dspaudio.c @@ -26,8 +26,8 @@ /* Allow access to a raw mixing buffer */ -#include /* For perror() */ -#include /* For strerror() */ +#include /* For perror() */ +#include /* For strerror() */ #include #include #include @@ -58,7 +58,7 @@ #define OPEN_FLAGS (O_WRONLY|O_NONBLOCK) /* Audio driver functions */ -static int DSP_OpenAudio(_THIS, SDL_AudioSpec *spec); +static int DSP_OpenAudio(_THIS, SDL_AudioSpec * spec); static void DSP_WaitAudio(_THIS); static void DSP_PlayAudio(_THIS); static Uint8 *DSP_GetAudioBuf(_THIS); @@ -66,266 +66,275 @@ static void DSP_CloseAudio(_THIS); /* Audio driver bootstrap functions */ -static int Audio_Available(void) +static int +Audio_Available(void) { - int fd; - int available; - - available = 0; - fd = SDL_OpenAudioPath(NULL, 0, OPEN_FLAGS, 0); - if ( fd >= 0 ) { - available = 1; - close(fd); - } - return(available); + int fd; + int available; + + available = 0; + fd = SDL_OpenAudioPath(NULL, 0, OPEN_FLAGS, 0); + if (fd >= 0) { + available = 1; + close(fd); + } + return (available); } -static void Audio_DeleteDevice(SDL_AudioDevice *device) +static void +Audio_DeleteDevice(SDL_AudioDevice * device) { - SDL_free(device->hidden); - SDL_free(device); + SDL_free(device->hidden); + SDL_free(device); } -static SDL_AudioDevice *Audio_CreateDevice(int devindex) +static SDL_AudioDevice * +Audio_CreateDevice(int devindex) { - SDL_AudioDevice *this; - - /* Initialize all variables that we clean on shutdown */ - this = (SDL_AudioDevice *)SDL_malloc(sizeof(SDL_AudioDevice)); - if ( this ) { - SDL_memset(this, 0, (sizeof *this)); - this->hidden = (struct SDL_PrivateAudioData *) - SDL_malloc((sizeof *this->hidden)); - } - if ( (this == NULL) || (this->hidden == NULL) ) { - SDL_OutOfMemory(); - if ( this ) { - SDL_free(this); - } - return(0); - } - SDL_memset(this->hidden, 0, (sizeof *this->hidden)); - audio_fd = -1; - - /* Set the function pointers */ - this->OpenAudio = DSP_OpenAudio; - this->WaitAudio = DSP_WaitAudio; - this->PlayAudio = DSP_PlayAudio; - this->GetAudioBuf = DSP_GetAudioBuf; - this->CloseAudio = DSP_CloseAudio; - - this->free = Audio_DeleteDevice; - - return this; + SDL_AudioDevice *this; + + /* Initialize all variables that we clean on shutdown */ + this = (SDL_AudioDevice *) SDL_malloc(sizeof(SDL_AudioDevice)); + if (this) { + SDL_memset(this, 0, (sizeof *this)); + this->hidden = (struct SDL_PrivateAudioData *) + SDL_malloc((sizeof *this->hidden)); + } + if ((this == NULL) || (this->hidden == NULL)) { + SDL_OutOfMemory(); + if (this) { + SDL_free(this); + } + return (0); + } + SDL_memset(this->hidden, 0, (sizeof *this->hidden)); + audio_fd = -1; + + /* Set the function pointers */ + this->OpenAudio = DSP_OpenAudio; + this->WaitAudio = DSP_WaitAudio; + this->PlayAudio = DSP_PlayAudio; + this->GetAudioBuf = DSP_GetAudioBuf; + this->CloseAudio = DSP_CloseAudio; + + this->free = Audio_DeleteDevice; + + return this; } AudioBootStrap DSP_bootstrap = { - DSP_DRIVER_NAME, "OSS /dev/dsp standard audio", - Audio_Available, Audio_CreateDevice + DSP_DRIVER_NAME, "OSS /dev/dsp standard audio", + Audio_Available, Audio_CreateDevice }; /* This function waits until it is possible to write a full sound buffer */ -static void DSP_WaitAudio(_THIS) +static void +DSP_WaitAudio(_THIS) { - /* Not needed at all since OSS handles waiting automagically */ + /* Not needed at all since OSS handles waiting automagically */ } -static void DSP_PlayAudio(_THIS) +static void +DSP_PlayAudio(_THIS) { - if (write(audio_fd, mixbuf, mixlen)==-1) - { - perror("Audio write"); - this->enabled = 0; - } - + if (write(audio_fd, mixbuf, mixlen) == -1) { + perror("Audio write"); + this->enabled = 0; + } #ifdef DEBUG_AUDIO - fprintf(stderr, "Wrote %d bytes of audio data\n", mixlen); + fprintf(stderr, "Wrote %d bytes of audio data\n", mixlen); #endif } -static Uint8 *DSP_GetAudioBuf(_THIS) +static Uint8 * +DSP_GetAudioBuf(_THIS) { - return(mixbuf); + return (mixbuf); } -static void DSP_CloseAudio(_THIS) +static void +DSP_CloseAudio(_THIS) { - if ( mixbuf != NULL ) { - SDL_FreeAudioMem(mixbuf); - mixbuf = NULL; - } - if ( audio_fd >= 0 ) { - close(audio_fd); - audio_fd = -1; - } + if (mixbuf != NULL) { + SDL_FreeAudioMem(mixbuf); + mixbuf = NULL; + } + if (audio_fd >= 0) { + close(audio_fd); + audio_fd = -1; + } } -static int DSP_OpenAudio(_THIS, SDL_AudioSpec *spec) +static int +DSP_OpenAudio(_THIS, SDL_AudioSpec * spec) { - char audiodev[1024]; - int format; - int value; - int frag_spec; - Uint16 test_format; - - /* Open the audio device */ - audio_fd = SDL_OpenAudioPath(audiodev, sizeof(audiodev), OPEN_FLAGS, 0); - if ( audio_fd < 0 ) { - SDL_SetError("Couldn't open %s: %s", audiodev, strerror(errno)); - return(-1); - } - mixbuf = NULL; - - /* Make the file descriptor use blocking writes with fcntl() */ - { long flags; - flags = fcntl(audio_fd, F_GETFL); - flags &= ~O_NONBLOCK; - if ( fcntl(audio_fd, F_SETFL, flags) < 0 ) { - SDL_SetError("Couldn't set audio blocking mode"); - DSP_CloseAudio(this); - return(-1); - } - } - - /* Get a list of supported hardware formats */ - if ( ioctl(audio_fd, SNDCTL_DSP_GETFMTS, &value) < 0 ) { - perror("SNDCTL_DSP_GETFMTS"); - SDL_SetError("Couldn't get audio format list"); - DSP_CloseAudio(this); - return(-1); - } - - /* Try for a closest match on audio format */ - format = 0; - for ( test_format = SDL_FirstAudioFormat(spec->format); - ! format && test_format; ) { + char audiodev[1024]; + int format; + int value; + int frag_spec; + Uint16 test_format; + + /* Open the audio device */ + audio_fd = SDL_OpenAudioPath(audiodev, sizeof(audiodev), OPEN_FLAGS, 0); + if (audio_fd < 0) { + SDL_SetError("Couldn't open %s: %s", audiodev, strerror(errno)); + return (-1); + } + mixbuf = NULL; + + /* Make the file descriptor use blocking writes with fcntl() */ + { + long flags; + flags = fcntl(audio_fd, F_GETFL); + flags &= ~O_NONBLOCK; + if (fcntl(audio_fd, F_SETFL, flags) < 0) { + SDL_SetError("Couldn't set audio blocking mode"); + DSP_CloseAudio(this); + return (-1); + } + } + + /* Get a list of supported hardware formats */ + if (ioctl(audio_fd, SNDCTL_DSP_GETFMTS, &value) < 0) { + perror("SNDCTL_DSP_GETFMTS"); + SDL_SetError("Couldn't get audio format list"); + DSP_CloseAudio(this); + return (-1); + } + + /* Try for a closest match on audio format */ + format = 0; + for (test_format = SDL_FirstAudioFormat(spec->format); + !format && test_format;) { #ifdef DEBUG_AUDIO - fprintf(stderr, "Trying format 0x%4.4x\n", test_format); + fprintf(stderr, "Trying format 0x%4.4x\n", test_format); #endif - switch ( test_format ) { - case AUDIO_U8: - if ( value & AFMT_U8 ) { - format = AFMT_U8; - } - break; - case AUDIO_S16LSB: - if ( value & AFMT_S16_LE ) { - format = AFMT_S16_LE; - } - break; - case AUDIO_S16MSB: - if ( value & AFMT_S16_BE ) { - format = AFMT_S16_BE; - } - break; + switch (test_format) { + case AUDIO_U8: + if (value & AFMT_U8) { + format = AFMT_U8; + } + break; + case AUDIO_S16LSB: + if (value & AFMT_S16_LE) { + format = AFMT_S16_LE; + } + break; + case AUDIO_S16MSB: + if (value & AFMT_S16_BE) { + format = AFMT_S16_BE; + } + break; #if 0 /* * These formats are not used by any real life systems so they are not * needed here. */ - case AUDIO_S8: - if ( value & AFMT_S8 ) { - format = AFMT_S8; - } - break; - case AUDIO_U16LSB: - if ( value & AFMT_U16_LE ) { - format = AFMT_U16_LE; - } - break; - case AUDIO_U16MSB: - if ( value & AFMT_U16_BE ) { - format = AFMT_U16_BE; - } - break; + case AUDIO_S8: + if (value & AFMT_S8) { + format = AFMT_S8; + } + break; + case AUDIO_U16LSB: + if (value & AFMT_U16_LE) { + format = AFMT_U16_LE; + } + break; + case AUDIO_U16MSB: + if (value & AFMT_U16_BE) { + format = AFMT_U16_BE; + } + break; #endif - default: - format = 0; - break; - } - if ( ! format ) { - test_format = SDL_NextAudioFormat(); - } - } - if ( format == 0 ) { - SDL_SetError("Couldn't find any hardware audio formats"); - DSP_CloseAudio(this); - return(-1); - } - spec->format = test_format; - - /* Set the audio format */ - value = format; - if ( (ioctl(audio_fd, SNDCTL_DSP_SETFMT, &value) < 0) || - (value != format) ) { - perror("SNDCTL_DSP_SETFMT"); - SDL_SetError("Couldn't set audio format"); - DSP_CloseAudio(this); - return(-1); - } - - /* Set the number of channels of output */ - value = spec->channels; - if ( ioctl(audio_fd, SNDCTL_DSP_CHANNELS, &value) < 0 ) { - perror("SNDCTL_DSP_CHANNELS"); - SDL_SetError("Cannot set the number of channels"); - DSP_CloseAudio(this); - return(-1); - } - spec->channels = value; - - /* Set the DSP frequency */ - value = spec->freq; - if ( ioctl(audio_fd, SNDCTL_DSP_SPEED, &value) < 0 ) { - perror("SNDCTL_DSP_SPEED"); - SDL_SetError("Couldn't set audio frequency"); - DSP_CloseAudio(this); - return(-1); - } - spec->freq = value; - - /* Calculate the final parameters for this audio specification */ - SDL_CalculateAudioSpec(spec); - - /* Determine the power of two of the fragment size */ - for ( frag_spec = 0; (0x01U<size; ++frag_spec ); - if ( (0x01U<size ) { - SDL_SetError("Fragment size must be a power of two"); - DSP_CloseAudio(this); - return(-1); - } - frag_spec |= 0x00020000; /* two fragments, for low latency */ - - /* Set the audio buffering parameters */ + default: + format = 0; + break; + } + if (!format) { + test_format = SDL_NextAudioFormat(); + } + } + if (format == 0) { + SDL_SetError("Couldn't find any hardware audio formats"); + DSP_CloseAudio(this); + return (-1); + } + spec->format = test_format; + + /* Set the audio format */ + value = format; + if ((ioctl(audio_fd, SNDCTL_DSP_SETFMT, &value) < 0) || (value != format)) { + perror("SNDCTL_DSP_SETFMT"); + SDL_SetError("Couldn't set audio format"); + DSP_CloseAudio(this); + return (-1); + } + + /* Set the number of channels of output */ + value = spec->channels; + if (ioctl(audio_fd, SNDCTL_DSP_CHANNELS, &value) < 0) { + perror("SNDCTL_DSP_CHANNELS"); + SDL_SetError("Cannot set the number of channels"); + DSP_CloseAudio(this); + return (-1); + } + spec->channels = value; + + /* Set the DSP frequency */ + value = spec->freq; + if (ioctl(audio_fd, SNDCTL_DSP_SPEED, &value) < 0) { + perror("SNDCTL_DSP_SPEED"); + SDL_SetError("Couldn't set audio frequency"); + DSP_CloseAudio(this); + return (-1); + } + spec->freq = value; + + /* Calculate the final parameters for this audio specification */ + SDL_CalculateAudioSpec(spec); + + /* Determine the power of two of the fragment size */ + for (frag_spec = 0; (0x01U << frag_spec) < spec->size; ++frag_spec); + if ((0x01U << frag_spec) != spec->size) { + SDL_SetError("Fragment size must be a power of two"); + DSP_CloseAudio(this); + return (-1); + } + frag_spec |= 0x00020000; /* two fragments, for low latency */ + + /* Set the audio buffering parameters */ #ifdef DEBUG_AUDIO - fprintf(stderr, "Requesting %d fragments of size %d\n", - (frag_spec >> 16), 1<<(frag_spec&0xFFFF)); + fprintf(stderr, "Requesting %d fragments of size %d\n", + (frag_spec >> 16), 1 << (frag_spec & 0xFFFF)); #endif - if ( ioctl(audio_fd, SNDCTL_DSP_SETFRAGMENT, &frag_spec) < 0 ) { - perror("SNDCTL_DSP_SETFRAGMENT"); - } + if (ioctl(audio_fd, SNDCTL_DSP_SETFRAGMENT, &frag_spec) < 0) { + perror("SNDCTL_DSP_SETFRAGMENT"); + } #ifdef DEBUG_AUDIO - { audio_buf_info info; - ioctl(audio_fd, SNDCTL_DSP_GETOSPACE, &info); - fprintf(stderr, "fragments = %d\n", info.fragments); - fprintf(stderr, "fragstotal = %d\n", info.fragstotal); - fprintf(stderr, "fragsize = %d\n", info.fragsize); - fprintf(stderr, "bytes = %d\n", info.bytes); - } + { + audio_buf_info info; + ioctl(audio_fd, SNDCTL_DSP_GETOSPACE, &info); + fprintf(stderr, "fragments = %d\n", info.fragments); + fprintf(stderr, "fragstotal = %d\n", info.fragstotal); + fprintf(stderr, "fragsize = %d\n", info.fragsize); + fprintf(stderr, "bytes = %d\n", info.bytes); + } #endif - /* Allocate mixing buffer */ - mixlen = spec->size; - mixbuf = (Uint8 *)SDL_AllocAudioMem(mixlen); - if ( mixbuf == NULL ) { - DSP_CloseAudio(this); - return(-1); - } - SDL_memset(mixbuf, spec->silence, spec->size); + /* Allocate mixing buffer */ + mixlen = spec->size; + mixbuf = (Uint8 *) SDL_AllocAudioMem(mixlen); + if (mixbuf == NULL) { + DSP_CloseAudio(this); + return (-1); + } + SDL_memset(mixbuf, spec->silence, spec->size); - /* Get the parent process id (we're the parent of the audio thread) */ - parent = getpid(); + /* Get the parent process id (we're the parent of the audio thread) */ + parent = getpid(); - /* We're ready to rock and roll. :-) */ - return(0); + /* We're ready to rock and roll. :-) */ + return (0); } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/audio/dsp/SDL_dspaudio.h b/src/audio/dsp/SDL_dspaudio.h index 0bf803fc8..3f1af967b 100644 --- a/src/audio/dsp/SDL_dspaudio.h +++ b/src/audio/dsp/SDL_dspaudio.h @@ -29,18 +29,19 @@ /* Hidden "this" pointer for the video functions */ #define _THIS SDL_AudioDevice *this -struct SDL_PrivateAudioData { - /* The file descriptor for the audio device */ - int audio_fd; +struct SDL_PrivateAudioData +{ + /* The file descriptor for the audio device */ + int audio_fd; - /* The parent process id, to detect when application quits */ - pid_t parent; + /* The parent process id, to detect when application quits */ + pid_t parent; - /* Raw mixing buffer */ - Uint8 *mixbuf; - int mixlen; + /* Raw mixing buffer */ + Uint8 *mixbuf; + int mixlen; }; -#define FUDGE_TICKS 10 /* The scheduler overhead ticks per frame */ +#define FUDGE_TICKS 10 /* The scheduler overhead ticks per frame */ /* Old variable names */ #define audio_fd (this->hidden->audio_fd) @@ -51,3 +52,4 @@ struct SDL_PrivateAudioData { #define next_frame (this->hidden->next_frame) #endif /* _SDL_dspaudio_h */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/audio/dummy/SDL_dummyaudio.c b/src/audio/dummy/SDL_dummyaudio.c index 6e9a3f06e..b8b9c96bf 100644 --- a/src/audio/dummy/SDL_dummyaudio.c +++ b/src/audio/dummy/SDL_dummyaudio.c @@ -37,120 +37,129 @@ #define DUMMYAUD_DRIVER_NAME "dummy" /* Audio driver functions */ -static int DUMMYAUD_OpenAudio(_THIS, SDL_AudioSpec *spec); +static int DUMMYAUD_OpenAudio(_THIS, SDL_AudioSpec * spec); static void DUMMYAUD_WaitAudio(_THIS); static void DUMMYAUD_PlayAudio(_THIS); static Uint8 *DUMMYAUD_GetAudioBuf(_THIS); static void DUMMYAUD_CloseAudio(_THIS); /* Audio driver bootstrap functions */ -static int DUMMYAUD_Available(void) +static int +DUMMYAUD_Available(void) { - const char *envr = SDL_getenv("SDL_AUDIODRIVER"); - if (envr && (SDL_strcmp(envr, DUMMYAUD_DRIVER_NAME) == 0)) { - return(1); - } - return(0); + const char *envr = SDL_getenv("SDL_AUDIODRIVER"); + if (envr && (SDL_strcmp(envr, DUMMYAUD_DRIVER_NAME) == 0)) { + return (1); + } + return (0); } -static void DUMMYAUD_DeleteDevice(SDL_AudioDevice *device) +static void +DUMMYAUD_DeleteDevice(SDL_AudioDevice * device) { - SDL_free(device->hidden); - SDL_free(device); + SDL_free(device->hidden); + SDL_free(device); } -static SDL_AudioDevice *DUMMYAUD_CreateDevice(int devindex) +static SDL_AudioDevice * +DUMMYAUD_CreateDevice(int devindex) { - SDL_AudioDevice *this; - - /* Initialize all variables that we clean on shutdown */ - this = (SDL_AudioDevice *)SDL_malloc(sizeof(SDL_AudioDevice)); - if ( this ) { - SDL_memset(this, 0, (sizeof *this)); - this->hidden = (struct SDL_PrivateAudioData *) - SDL_malloc((sizeof *this->hidden)); - } - if ( (this == NULL) || (this->hidden == NULL) ) { - SDL_OutOfMemory(); - if ( this ) { - SDL_free(this); - } - return(0); - } - SDL_memset(this->hidden, 0, (sizeof *this->hidden)); - - /* Set the function pointers */ - this->OpenAudio = DUMMYAUD_OpenAudio; - this->WaitAudio = DUMMYAUD_WaitAudio; - this->PlayAudio = DUMMYAUD_PlayAudio; - this->GetAudioBuf = DUMMYAUD_GetAudioBuf; - this->CloseAudio = DUMMYAUD_CloseAudio; - - this->free = DUMMYAUD_DeleteDevice; - - return this; + SDL_AudioDevice *this; + + /* Initialize all variables that we clean on shutdown */ + this = (SDL_AudioDevice *) SDL_malloc(sizeof(SDL_AudioDevice)); + if (this) { + SDL_memset(this, 0, (sizeof *this)); + this->hidden = (struct SDL_PrivateAudioData *) + SDL_malloc((sizeof *this->hidden)); + } + if ((this == NULL) || (this->hidden == NULL)) { + SDL_OutOfMemory(); + if (this) { + SDL_free(this); + } + return (0); + } + SDL_memset(this->hidden, 0, (sizeof *this->hidden)); + + /* Set the function pointers */ + this->OpenAudio = DUMMYAUD_OpenAudio; + this->WaitAudio = DUMMYAUD_WaitAudio; + this->PlayAudio = DUMMYAUD_PlayAudio; + this->GetAudioBuf = DUMMYAUD_GetAudioBuf; + this->CloseAudio = DUMMYAUD_CloseAudio; + + this->free = DUMMYAUD_DeleteDevice; + + return this; } AudioBootStrap DUMMYAUD_bootstrap = { - DUMMYAUD_DRIVER_NAME, "SDL dummy audio driver", - DUMMYAUD_Available, DUMMYAUD_CreateDevice + DUMMYAUD_DRIVER_NAME, "SDL dummy audio driver", + DUMMYAUD_Available, DUMMYAUD_CreateDevice }; /* This function waits until it is possible to write a full sound buffer */ -static void DUMMYAUD_WaitAudio(_THIS) +static void +DUMMYAUD_WaitAudio(_THIS) { - /* Don't block on first calls to simulate initial fragment filling. */ - if (this->hidden->initial_calls) - this->hidden->initial_calls--; - else - SDL_Delay(this->hidden->write_delay); + /* Don't block on first calls to simulate initial fragment filling. */ + if (this->hidden->initial_calls) + this->hidden->initial_calls--; + else + SDL_Delay(this->hidden->write_delay); } -static void DUMMYAUD_PlayAudio(_THIS) +static void +DUMMYAUD_PlayAudio(_THIS) { - /* no-op...this is a null driver. */ + /* no-op...this is a null driver. */ } -static Uint8 *DUMMYAUD_GetAudioBuf(_THIS) +static Uint8 * +DUMMYAUD_GetAudioBuf(_THIS) { - return(this->hidden->mixbuf); + return (this->hidden->mixbuf); } -static void DUMMYAUD_CloseAudio(_THIS) +static void +DUMMYAUD_CloseAudio(_THIS) { - if ( this->hidden->mixbuf != NULL ) { - SDL_FreeAudioMem(this->hidden->mixbuf); - this->hidden->mixbuf = NULL; - } + if (this->hidden->mixbuf != NULL) { + SDL_FreeAudioMem(this->hidden->mixbuf); + this->hidden->mixbuf = NULL; + } } -static int DUMMYAUD_OpenAudio(_THIS, SDL_AudioSpec *spec) +static int +DUMMYAUD_OpenAudio(_THIS, SDL_AudioSpec * spec) { - float bytes_per_sec = 0.0f; - - /* Allocate mixing buffer */ - this->hidden->mixlen = spec->size; - this->hidden->mixbuf = (Uint8 *) SDL_AllocAudioMem(this->hidden->mixlen); - if ( this->hidden->mixbuf == NULL ) { - return(-1); - } - SDL_memset(this->hidden->mixbuf, spec->silence, spec->size); - - bytes_per_sec = (float) (((spec->format & 0xFF) / 8) * - spec->channels * spec->freq); - - /* - * We try to make this request more audio at the correct rate for - * a given audio spec, so timing stays fairly faithful. - * Also, we have it not block at all for the first two calls, so - * it seems like we're filling two audio fragments right out of the - * gate, like other SDL drivers tend to do. - */ - this->hidden->initial_calls = 2; - this->hidden->write_delay = - (Uint32) ((((float) spec->size) / bytes_per_sec) * 1000.0f); - - /* We're ready to rock and roll. :-) */ - return(0); + float bytes_per_sec = 0.0f; + + /* Allocate mixing buffer */ + this->hidden->mixlen = spec->size; + this->hidden->mixbuf = (Uint8 *) SDL_AllocAudioMem(this->hidden->mixlen); + if (this->hidden->mixbuf == NULL) { + return (-1); + } + SDL_memset(this->hidden->mixbuf, spec->silence, spec->size); + + bytes_per_sec = (float) (((spec->format & 0xFF) / 8) * + spec->channels * spec->freq); + + /* + * We try to make this request more audio at the correct rate for + * a given audio spec, so timing stays fairly faithful. + * Also, we have it not block at all for the first two calls, so + * it seems like we're filling two audio fragments right out of the + * gate, like other SDL drivers tend to do. + */ + this->hidden->initial_calls = 2; + this->hidden->write_delay = + (Uint32) ((((float) spec->size) / bytes_per_sec) * 1000.0f); + + /* We're ready to rock and roll. :-) */ + return (0); } +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/audio/dummy/SDL_dummyaudio.h b/src/audio/dummy/SDL_dummyaudio.h index ff16cc7d9..58adcf802 100644 --- a/src/audio/dummy/SDL_dummyaudio.h +++ b/src/audio/dummy/SDL_dummyaudio.h @@ -29,12 +29,14 @@ /* Hidden "this" pointer for the video functions */ #define _THIS SDL_AudioDevice *this -struct SDL_PrivateAudioData { - /* The file descriptor for the audio device */ - Uint8 *mixbuf; - Uint32 mixlen; - Uint32 write_delay; - Uint32 initial_calls; +struct SDL_PrivateAudioData +{ + /* The file descriptor for the audio device */ + Uint8 *mixbuf; + Uint32 mixlen; + Uint32 write_delay; + Uint32 initial_calls; }; #endif /* _SDL_dummyaudio_h */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/audio/esd/SDL_esdaudio.c b/src/audio/esd/SDL_esdaudio.c index d35e89aa4..ade0e47e8 100644 --- a/src/audio/esd/SDL_esdaudio.c +++ b/src/audio/esd/SDL_esdaudio.c @@ -47,7 +47,7 @@ #define ESD_DRIVER_NAME "esd" /* Audio driver functions */ -static int ESD_OpenAudio(_THIS, SDL_AudioSpec *spec); +static int ESD_OpenAudio(_THIS, SDL_AudioSpec * spec); static void ESD_WaitAudio(_THIS); static void ESD_PlayAudio(_THIS); static Uint8 *ESD_GetAudioBuf(_THIS); @@ -59,265 +59,285 @@ static const char *esd_library = SDL_AUDIO_DRIVER_ESD_DYNAMIC; static void *esd_handle = NULL; static int esd_loaded = 0; -static int (*SDL_NAME(esd_open_sound))( const char *host ); -static int (*SDL_NAME(esd_close))( int esd ); -static int (*SDL_NAME(esd_play_stream))( esd_format_t format, int rate, - const char *host, const char *name ); -static struct { - const char *name; - void **func; +static int (*SDL_NAME(esd_open_sound)) (const char *host); +static int (*SDL_NAME(esd_close)) (int esd); +static int (*SDL_NAME(esd_play_stream)) (esd_format_t format, int rate, + const char *host, const char *name); +static struct +{ + const char *name; + void **func; } esd_functions[] = { - { "esd_open_sound", (void **)&SDL_NAME(esd_open_sound) }, - { "esd_close", (void **)&SDL_NAME(esd_close) }, - { "esd_play_stream", (void **)&SDL_NAME(esd_play_stream) }, -}; + { + "esd_open_sound", (void **) &SDL_NAME(esd_open_sound)}, { + "esd_close", (void **) &SDL_NAME(esd_close)}, { +"esd_play_stream", (void **) &SDL_NAME(esd_play_stream)},}; -static void UnloadESDLibrary() +static void +UnloadESDLibrary() { - if ( esd_loaded ) { - SDL_UnloadObject(esd_handle); - esd_handle = NULL; - esd_loaded = 0; - } + if (esd_loaded) { + SDL_UnloadObject(esd_handle); + esd_handle = NULL; + esd_loaded = 0; + } } -static int LoadESDLibrary(void) +static int +LoadESDLibrary(void) { - int i, retval = -1; - - esd_handle = SDL_LoadObject(esd_library); - if ( esd_handle ) { - esd_loaded = 1; - retval = 0; - for ( i=0; i= 0 ) { - available = 1; - SDL_NAME(esd_close)(connection); - } - UnloadESDLibrary(); - return(available); + int connection; + int available; + + available = 0; + if (LoadESDLibrary() < 0) { + return available; + } + connection = SDL_NAME(esd_open_sound) (NULL); + if (connection >= 0) { + available = 1; + SDL_NAME(esd_close) (connection); + } + UnloadESDLibrary(); + return (available); } -static void Audio_DeleteDevice(SDL_AudioDevice *device) +static void +Audio_DeleteDevice(SDL_AudioDevice * device) { - SDL_free(device->hidden); - SDL_free(device); - UnloadESDLibrary(); + SDL_free(device->hidden); + SDL_free(device); + UnloadESDLibrary(); } -static SDL_AudioDevice *Audio_CreateDevice(int devindex) +static SDL_AudioDevice * +Audio_CreateDevice(int devindex) { - SDL_AudioDevice *this; - - /* Initialize all variables that we clean on shutdown */ - LoadESDLibrary(); - this = (SDL_AudioDevice *)SDL_malloc(sizeof(SDL_AudioDevice)); - if ( this ) { - SDL_memset(this, 0, (sizeof *this)); - this->hidden = (struct SDL_PrivateAudioData *) - SDL_malloc((sizeof *this->hidden)); - } - if ( (this == NULL) || (this->hidden == NULL) ) { - SDL_OutOfMemory(); - if ( this ) { - SDL_free(this); - } - return(0); - } - SDL_memset(this->hidden, 0, (sizeof *this->hidden)); - audio_fd = -1; - - /* Set the function pointers */ - this->OpenAudio = ESD_OpenAudio; - this->WaitAudio = ESD_WaitAudio; - this->PlayAudio = ESD_PlayAudio; - this->GetAudioBuf = ESD_GetAudioBuf; - this->CloseAudio = ESD_CloseAudio; - - this->free = Audio_DeleteDevice; - - return this; + SDL_AudioDevice *this; + + /* Initialize all variables that we clean on shutdown */ + LoadESDLibrary(); + this = (SDL_AudioDevice *) SDL_malloc(sizeof(SDL_AudioDevice)); + if (this) { + SDL_memset(this, 0, (sizeof *this)); + this->hidden = (struct SDL_PrivateAudioData *) + SDL_malloc((sizeof *this->hidden)); + } + if ((this == NULL) || (this->hidden == NULL)) { + SDL_OutOfMemory(); + if (this) { + SDL_free(this); + } + return (0); + } + SDL_memset(this->hidden, 0, (sizeof *this->hidden)); + audio_fd = -1; + + /* Set the function pointers */ + this->OpenAudio = ESD_OpenAudio; + this->WaitAudio = ESD_WaitAudio; + this->PlayAudio = ESD_PlayAudio; + this->GetAudioBuf = ESD_GetAudioBuf; + this->CloseAudio = ESD_CloseAudio; + + this->free = Audio_DeleteDevice; + + return this; } AudioBootStrap ESD_bootstrap = { - ESD_DRIVER_NAME, "Enlightened Sound Daemon", - Audio_Available, Audio_CreateDevice + ESD_DRIVER_NAME, "Enlightened Sound Daemon", + Audio_Available, Audio_CreateDevice }; /* This function waits until it is possible to write a full sound buffer */ -static void ESD_WaitAudio(_THIS) +static void +ESD_WaitAudio(_THIS) { - Sint32 ticks; - - /* Check to see if the thread-parent process is still alive */ - { static int cnt = 0; - /* Note that this only works with thread implementations - that use a different process id for each thread. - */ - if (parent && (((++cnt)%10) == 0)) { /* Check every 10 loops */ - if ( kill(parent, 0) < 0 ) { - this->enabled = 0; - } - } - } - - /* Use timer for general audio synchronization */ - ticks = ((Sint32)(next_frame - SDL_GetTicks()))-FUDGE_TICKS; - if ( ticks > 0 ) { - SDL_Delay(ticks); - } + Sint32 ticks; + + /* Check to see if the thread-parent process is still alive */ + { + static int cnt = 0; + /* Note that this only works with thread implementations + that use a different process id for each thread. + */ + if (parent && (((++cnt) % 10) == 0)) { /* Check every 10 loops */ + if (kill(parent, 0) < 0) { + this->enabled = 0; + } + } + } + + /* Use timer for general audio synchronization */ + ticks = ((Sint32) (next_frame - SDL_GetTicks())) - FUDGE_TICKS; + if (ticks > 0) { + SDL_Delay(ticks); + } } -static void ESD_PlayAudio(_THIS) +static void +ESD_PlayAudio(_THIS) { - int written; - - /* Write the audio data, checking for EAGAIN on broken audio drivers */ - do { - written = write(audio_fd, mixbuf, mixlen); - if ( (written < 0) && ((errno == 0) || (errno == EAGAIN)) ) { - SDL_Delay(1); /* Let a little CPU time go by */ - } - } while ( (written < 0) && - ((errno == 0) || (errno == EAGAIN) || (errno == EINTR)) ); - - /* Set the next write frame */ - next_frame += frame_ticks; - - /* If we couldn't write, assume fatal error for now */ - if ( written < 0 ) { - this->enabled = 0; - } + int written; + + /* Write the audio data, checking for EAGAIN on broken audio drivers */ + do { + written = write(audio_fd, mixbuf, mixlen); + if ((written < 0) && ((errno == 0) || (errno == EAGAIN))) { + SDL_Delay(1); /* Let a little CPU time go by */ + } + } + while ((written < 0) && + ((errno == 0) || (errno == EAGAIN) || (errno == EINTR))); + + /* Set the next write frame */ + next_frame += frame_ticks; + + /* If we couldn't write, assume fatal error for now */ + if (written < 0) { + this->enabled = 0; + } } -static Uint8 *ESD_GetAudioBuf(_THIS) +static Uint8 * +ESD_GetAudioBuf(_THIS) { - return(mixbuf); + return (mixbuf); } -static void ESD_CloseAudio(_THIS) +static void +ESD_CloseAudio(_THIS) { - if ( mixbuf != NULL ) { - SDL_FreeAudioMem(mixbuf); - mixbuf = NULL; - } - if ( audio_fd >= 0 ) { - SDL_NAME(esd_close)(audio_fd); - audio_fd = -1; - } + if (mixbuf != NULL) { + SDL_FreeAudioMem(mixbuf); + mixbuf = NULL; + } + if (audio_fd >= 0) { + SDL_NAME(esd_close) (audio_fd); + audio_fd = -1; + } } /* Try to get the name of the program */ -static char *get_progname(void) +static char * +get_progname(void) { - char *progname = NULL; + char *progname = NULL; #ifdef __LINUX__ - FILE *fp; - static char temp[BUFSIZ]; - - SDL_snprintf(temp, SDL_arraysize(temp), "/proc/%d/cmdline", getpid()); - fp = fopen(temp, "r"); - if ( fp != NULL ) { - if ( fgets(temp, sizeof(temp)-1, fp) ) { - progname = SDL_strrchr(temp, '/'); - if ( progname == NULL ) { - progname = temp; - } else { - progname = progname+1; - } - } - fclose(fp); - } + FILE *fp; + static char temp[BUFSIZ]; + + SDL_snprintf(temp, SDL_arraysize(temp), "/proc/%d/cmdline", getpid()); + fp = fopen(temp, "r"); + if (fp != NULL) { + if (fgets(temp, sizeof(temp) - 1, fp)) { + progname = SDL_strrchr(temp, '/'); + if (progname == NULL) { + progname = temp; + } else { + progname = progname + 1; + } + } + fclose(fp); + } #endif - return(progname); + return (progname); } -static int ESD_OpenAudio(_THIS, SDL_AudioSpec *spec) +static int +ESD_OpenAudio(_THIS, SDL_AudioSpec * spec) { - esd_format_t format; - - /* Convert audio spec to the ESD audio format */ - format = (ESD_STREAM | ESD_PLAY); - switch ( spec->format & 0xFF ) { - case 8: - format |= ESD_BITS8; - break; - case 16: - format |= ESD_BITS16; - break; - default: - SDL_SetError("Unsupported ESD audio format"); - return(-1); - } - if ( spec->channels == 1 ) { - format |= ESD_MONO; - } else { - format |= ESD_STEREO; - } + esd_format_t format; + + /* Convert audio spec to the ESD audio format */ + format = (ESD_STREAM | ESD_PLAY); + switch (spec->format & 0xFF) { + case 8: + format |= ESD_BITS8; + break; + case 16: + format |= ESD_BITS16; + break; + default: + SDL_SetError("Unsupported ESD audio format"); + return (-1); + } + if (spec->channels == 1) { + format |= ESD_MONO; + } else { + format |= ESD_STEREO; + } #if 0 - spec->samples = ESD_BUF_SIZE; /* Darn, no way to change this yet */ + spec->samples = ESD_BUF_SIZE; /* Darn, no way to change this yet */ #endif - /* Open a connection to the ESD audio server */ - audio_fd = SDL_NAME(esd_play_stream)(format, spec->freq, NULL, get_progname()); - if ( audio_fd < 0 ) { - SDL_SetError("Couldn't open ESD connection"); - return(-1); - } - - /* Calculate the final parameters for this audio specification */ - SDL_CalculateAudioSpec(spec); - frame_ticks = (float)(spec->samples*1000)/spec->freq; - next_frame = SDL_GetTicks()+frame_ticks; - - /* Allocate mixing buffer */ - mixlen = spec->size; - mixbuf = (Uint8 *)SDL_AllocAudioMem(mixlen); - if ( mixbuf == NULL ) { - return(-1); - } - SDL_memset(mixbuf, spec->silence, spec->size); - - /* Get the parent process id (we're the parent of the audio thread) */ - parent = getpid(); - - /* We're ready to rock and roll. :-) */ - return(0); + /* Open a connection to the ESD audio server */ + audio_fd = + SDL_NAME(esd_play_stream) (format, spec->freq, NULL, get_progname()); + if (audio_fd < 0) { + SDL_SetError("Couldn't open ESD connection"); + return (-1); + } + + /* Calculate the final parameters for this audio specification */ + SDL_CalculateAudioSpec(spec); + frame_ticks = (float) (spec->samples * 1000) / spec->freq; + next_frame = SDL_GetTicks() + frame_ticks; + + /* Allocate mixing buffer */ + mixlen = spec->size; + mixbuf = (Uint8 *) SDL_AllocAudioMem(mixlen); + if (mixbuf == NULL) { + return (-1); + } + SDL_memset(mixbuf, spec->silence, spec->size); + + /* Get the parent process id (we're the parent of the audio thread) */ + parent = getpid(); + + /* We're ready to rock and roll. :-) */ + return (0); } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/audio/esd/SDL_esdaudio.h b/src/audio/esd/SDL_esdaudio.h index cffb2768a..b3abeca7d 100644 --- a/src/audio/esd/SDL_esdaudio.h +++ b/src/audio/esd/SDL_esdaudio.h @@ -29,22 +29,23 @@ /* Hidden "this" pointer for the video functions */ #define _THIS SDL_AudioDevice *this -struct SDL_PrivateAudioData { - /* The file descriptor for the audio device */ - int audio_fd; +struct SDL_PrivateAudioData +{ + /* The file descriptor for the audio device */ + int audio_fd; - /* The parent process id, to detect when application quits */ - pid_t parent; + /* The parent process id, to detect when application quits */ + pid_t parent; - /* Raw mixing buffer */ - Uint8 *mixbuf; - int mixlen; + /* Raw mixing buffer */ + Uint8 *mixbuf; + int mixlen; - /* Support for audio timing using a timer */ - float frame_ticks; - float next_frame; + /* Support for audio timing using a timer */ + float frame_ticks; + float next_frame; }; -#define FUDGE_TICKS 10 /* The scheduler overhead ticks per frame */ +#define FUDGE_TICKS 10 /* The scheduler overhead ticks per frame */ /* Old variable names */ #define audio_fd (this->hidden->audio_fd) @@ -55,3 +56,4 @@ struct SDL_PrivateAudioData { #define next_frame (this->hidden->next_frame) #endif /* _SDL_esdaudio_h */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/audio/macosx/SDL_coreaudio.c b/src/audio/macosx/SDL_coreaudio.c index 2cae95813..9ae88d8a0 100644 --- a/src/audio/macosx/SDL_coreaudio.c +++ b/src/audio/macosx/SDL_coreaudio.c @@ -31,7 +31,7 @@ /* Audio driver functions */ -static int Core_OpenAudio(_THIS, SDL_AudioSpec *spec); +static int Core_OpenAudio(_THIS, SDL_AudioSpec * spec); static void Core_WaitAudio(_THIS); static void Core_PlayAudio(_THIS); static Uint8 *Core_GetAudioBuf(_THIS); @@ -39,34 +39,37 @@ static void Core_CloseAudio(_THIS); /* Audio driver bootstrap functions */ -static int Audio_Available(void) +static int +Audio_Available(void) { - return(1); + return (1); } -static void Audio_DeleteDevice(SDL_AudioDevice *device) +static void +Audio_DeleteDevice(SDL_AudioDevice * device) { SDL_free(device->hidden); SDL_free(device); } -static SDL_AudioDevice *Audio_CreateDevice(int devindex) +static SDL_AudioDevice * +Audio_CreateDevice(int devindex) { SDL_AudioDevice *this; /* Initialize all variables that we clean on shutdown */ - this = (SDL_AudioDevice *)SDL_malloc(sizeof(SDL_AudioDevice)); - if ( this ) { + this = (SDL_AudioDevice *) SDL_malloc(sizeof(SDL_AudioDevice)); + if (this) { SDL_memset(this, 0, (sizeof *this)); this->hidden = (struct SDL_PrivateAudioData *) - SDL_malloc((sizeof *this->hidden)); + SDL_malloc((sizeof *this->hidden)); } - if ( (this == NULL) || (this->hidden == NULL) ) { + if ((this == NULL) || (this->hidden == NULL)) { SDL_OutOfMemory(); - if ( this ) { + if (this) { SDL_free(this); } - return(0); + return (0); } SDL_memset(this->hidden, 0, (sizeof *this->hidden)); @@ -88,30 +91,30 @@ AudioBootStrap COREAUDIO_bootstrap = { }; /* The CoreAudio callback */ -static OSStatus audioCallback (void *inRefCon, - AudioUnitRenderActionFlags inActionFlags, - const AudioTimeStamp *inTimeStamp, - UInt32 inBusNumber, - AudioBuffer *ioData) +static OSStatus +audioCallback(void *inRefCon, + AudioUnitRenderActionFlags inActionFlags, + const AudioTimeStamp * inTimeStamp, + UInt32 inBusNumber, AudioBuffer * ioData) { - SDL_AudioDevice *this = (SDL_AudioDevice *)inRefCon; + SDL_AudioDevice *this = (SDL_AudioDevice *) inRefCon; UInt32 remaining, len; void *ptr; /* Only do anything if audio is enabled and not paused */ - if ( ! this->enabled || this->paused ) { + if (!this->enabled || this->paused) { SDL_memset(ioData->mData, this->spec.silence, ioData->mDataByteSize); return 0; } - + /* No SDL conversion should be needed here, ever, since we accept any input format in OpenAudio, and leave the conversion to CoreAudio. */ /* - assert(!this->convert.needed); - assert(this->spec.channels == ioData->mNumberChannels); + assert(!this->convert.needed); + assert(this->spec.channels == ioData->mNumberChannels); */ - + remaining = ioData->mDataByteSize; ptr = ioData->mData; while (remaining > 0) { @@ -119,47 +122,50 @@ static OSStatus audioCallback (void *inRefCon, /* Generate the data */ SDL_memset(buffer, this->spec.silence, bufferSize); SDL_mutexP(this->mixer_lock); - (*this->spec.callback)(this->spec.userdata, - buffer, bufferSize); + (*this->spec.callback) (this->spec.userdata, buffer, bufferSize); SDL_mutexV(this->mixer_lock); bufferOffset = 0; } - + len = bufferSize - bufferOffset; if (len > remaining) len = remaining; - SDL_memcpy(ptr, (char *)buffer + bufferOffset, len); - ptr = (char *)ptr + len; + SDL_memcpy(ptr, (char *) buffer + bufferOffset, len); + ptr = (char *) ptr + len; remaining -= len; bufferOffset += len; } - + return 0; } /* Dummy functions -- we don't use thread-based audio */ -void Core_WaitAudio(_THIS) +void +Core_WaitAudio(_THIS) { return; } -void Core_PlayAudio(_THIS) +void +Core_PlayAudio(_THIS) { return; } -Uint8 *Core_GetAudioBuf(_THIS) +Uint8 * +Core_GetAudioBuf(_THIS) { - return(NULL); + return (NULL); } -void Core_CloseAudio(_THIS) +void +Core_CloseAudio(_THIS) { OSStatus result; struct AudioUnitInputCallback callback; /* stop processing the audio unit */ - result = AudioOutputUnitStop (outputAudioUnit); + result = AudioOutputUnitStop(outputAudioUnit); if (result != noErr) { SDL_SetError("Core_CloseAudio: AudioOutputUnitStop"); return; @@ -168,14 +174,13 @@ void Core_CloseAudio(_THIS) /* Remove the input callback */ callback.inputProc = 0; callback.inputProcRefCon = 0; - result = AudioUnitSetProperty (outputAudioUnit, - kAudioUnitProperty_SetInputCallback, - kAudioUnitScope_Input, - 0, - &callback, - sizeof(callback)); + result = AudioUnitSetProperty(outputAudioUnit, + kAudioUnitProperty_SetInputCallback, + kAudioUnitScope_Input, + 0, &callback, sizeof(callback)); if (result != noErr) { - SDL_SetError("Core_CloseAudio: AudioUnitSetProperty (kAudioUnitProperty_SetInputCallback)"); + SDL_SetError + ("Core_CloseAudio: AudioUnitSetProperty (kAudioUnitProperty_SetInputCallback)"); return; } @@ -184,7 +189,7 @@ void Core_CloseAudio(_THIS) SDL_SetError("Core_CloseAudio: CloseComponent"); return; } - + SDL_free(buffer); } @@ -195,7 +200,8 @@ void Core_CloseAudio(_THIS) } -int Core_OpenAudio(_THIS, SDL_AudioSpec *spec) +int +Core_OpenAudio(_THIS, SDL_AudioSpec * spec) { OSStatus result = noErr; Component comp; @@ -208,7 +214,7 @@ int Core_OpenAudio(_THIS, SDL_AudioSpec *spec) requestedDesc.mFormatFlags = kLinearPCMFormatFlagIsPacked; requestedDesc.mChannelsPerFrame = spec->channels; requestedDesc.mSampleRate = spec->freq; - + requestedDesc.mBitsPerChannel = spec->format & 0xFF; if (spec->format & 0x8000) requestedDesc.mFormatFlags |= kLinearPCMFormatFlagIsSignedInteger; @@ -216,8 +222,10 @@ int Core_OpenAudio(_THIS, SDL_AudioSpec *spec) requestedDesc.mFormatFlags |= kLinearPCMFormatFlagIsBigEndian; requestedDesc.mFramesPerPacket = 1; - requestedDesc.mBytesPerFrame = requestedDesc.mBitsPerChannel * requestedDesc.mChannelsPerFrame / 8; - requestedDesc.mBytesPerPacket = requestedDesc.mBytesPerFrame * requestedDesc.mFramesPerPacket; + requestedDesc.mBytesPerFrame = + requestedDesc.mBitsPerChannel * requestedDesc.mChannelsPerFrame / 8; + requestedDesc.mBytesPerPacket = + requestedDesc.mBytesPerFrame * requestedDesc.mFramesPerPacket; /* Locate the default output audio unit */ @@ -226,52 +234,46 @@ int Core_OpenAudio(_THIS, SDL_AudioSpec *spec) desc.componentManufacturer = kAudioUnitID_DefaultOutput; desc.componentFlags = 0; desc.componentFlagsMask = 0; - - comp = FindNextComponent (NULL, &desc); + + comp = FindNextComponent(NULL, &desc); if (comp == NULL) { - SDL_SetError ("Failed to start CoreAudio: FindNextComponent returned NULL"); + SDL_SetError + ("Failed to start CoreAudio: FindNextComponent returned NULL"); return -1; } - + /* Open & initialize the default output audio unit */ - result = OpenAComponent (comp, &outputAudioUnit); + result = OpenAComponent(comp, &outputAudioUnit); CHECK_RESULT("OpenAComponent") - - result = AudioUnitInitialize (outputAudioUnit); + result = AudioUnitInitialize(outputAudioUnit); CHECK_RESULT("AudioUnitInitialize") - - /* Set the input format of the audio unit. */ - result = AudioUnitSetProperty (outputAudioUnit, - kAudioUnitProperty_StreamFormat, - kAudioUnitScope_Input, - 0, - &requestedDesc, - sizeof (requestedDesc)); + /* Set the input format of the audio unit. */ + result = AudioUnitSetProperty(outputAudioUnit, + kAudioUnitProperty_StreamFormat, + kAudioUnitScope_Input, + 0, + &requestedDesc, sizeof(requestedDesc)); CHECK_RESULT("AudioUnitSetProperty (kAudioUnitProperty_StreamFormat)") - - /* Set the audio callback */ - callback.inputProc = audioCallback; + /* Set the audio callback */ + callback.inputProc = audioCallback; callback.inputProcRefCon = this; - result = AudioUnitSetProperty (outputAudioUnit, - kAudioUnitProperty_SetInputCallback, - kAudioUnitScope_Input, - 0, - &callback, - sizeof(callback)); + result = AudioUnitSetProperty(outputAudioUnit, + kAudioUnitProperty_SetInputCallback, + kAudioUnitScope_Input, + 0, &callback, sizeof(callback)); CHECK_RESULT("AudioUnitSetProperty (kAudioUnitProperty_SetInputCallback)") + /* Calculate the final parameters for this audio specification */ + SDL_CalculateAudioSpec(spec); - /* Calculate the final parameters for this audio specification */ - SDL_CalculateAudioSpec(spec); - /* Allocate a sample buffer */ bufferOffset = bufferSize = this->spec.size; buffer = SDL_malloc(bufferSize); /* Finally, start processing of the audio unit */ - result = AudioOutputUnitStart (outputAudioUnit); - CHECK_RESULT("AudioOutputUnitStart") - - - /* We're running! */ - return(1); + result = AudioOutputUnitStart(outputAudioUnit); + CHECK_RESULT("AudioOutputUnitStart") + /* We're running! */ + return (1); } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/audio/macosx/SDL_coreaudio.h b/src/audio/macosx/SDL_coreaudio.h index 0902deddf..8167ace1e 100644 --- a/src/audio/macosx/SDL_coreaudio.h +++ b/src/audio/macosx/SDL_coreaudio.h @@ -29,11 +29,12 @@ /* Hidden "this" pointer for the video functions */ #define _THIS SDL_AudioDevice *this -struct SDL_PrivateAudioData { - AudioUnit outputAudioUnit; - void *buffer; - UInt32 bufferOffset; - UInt32 bufferSize; +struct SDL_PrivateAudioData +{ + AudioUnit outputAudioUnit; + void *buffer; + UInt32 bufferOffset; + UInt32 bufferSize; }; /* Old variable names */ @@ -43,3 +44,4 @@ struct SDL_PrivateAudioData { #define bufferSize (this->hidden->bufferSize) #endif /* _SDL_coreaudio_h */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/audio/macrom/SDL_romaudio.c b/src/audio/macrom/SDL_romaudio.c index 140c0338c..0bf1d0dcd 100644 --- a/src/audio/macrom/SDL_romaudio.c +++ b/src/audio/macrom/SDL_romaudio.c @@ -26,13 +26,13 @@ #elif TARGET_API_MAC_CARBON && (UNIVERSAL_INTERFACES_VERSION > 0x0335) # include #else -# include /* SoundManager interface */ +# include /* SoundManager interface */ # include # include #endif #if !defined(NewSndCallBackUPP) && (UNIVERSAL_INTERFACES_VERSION < 0x0335) -#if !defined(NewSndCallBackProc) /* avoid circular redefinition... */ +#if !defined(NewSndCallBackProc) /* avoid circular redefinition... */ #define NewSndCallBackUPP NewSndCallBackProc #endif #if !defined(NewSndCallBackUPP) @@ -48,61 +48,64 @@ /* Audio driver functions */ static void Mac_CloseAudio(_THIS); -static int Mac_OpenAudio(_THIS, SDL_AudioSpec *spec); +static int Mac_OpenAudio(_THIS, SDL_AudioSpec * spec); static void Mac_LockAudio(_THIS); static void Mac_UnlockAudio(_THIS); /* Audio driver bootstrap functions */ -static int Audio_Available(void) +static int +Audio_Available(void) { - return(1); + return (1); } -static void Audio_DeleteDevice(SDL_AudioDevice *device) +static void +Audio_DeleteDevice(SDL_AudioDevice * device) { SDL_free(device->hidden); SDL_free(device); } -static SDL_AudioDevice *Audio_CreateDevice(int devindex) +static SDL_AudioDevice * +Audio_CreateDevice(int devindex) { SDL_AudioDevice *this; /* Initialize all variables that we clean on shutdown */ - this = (SDL_AudioDevice *)SDL_malloc(sizeof(SDL_AudioDevice)); - if ( this ) { + this = (SDL_AudioDevice *) SDL_malloc(sizeof(SDL_AudioDevice)); + if (this) { SDL_memset(this, 0, (sizeof *this)); this->hidden = (struct SDL_PrivateAudioData *) - SDL_malloc((sizeof *this->hidden)); + SDL_malloc((sizeof *this->hidden)); } - if ( (this == NULL) || (this->hidden == NULL) ) { + if ((this == NULL) || (this->hidden == NULL)) { SDL_OutOfMemory(); - if ( this ) { + if (this) { SDL_free(this); } - return(0); + return (0); } SDL_memset(this->hidden, 0, (sizeof *this->hidden)); /* Set the function pointers */ - this->OpenAudio = Mac_OpenAudio; - this->CloseAudio = Mac_CloseAudio; - this->LockAudio = Mac_LockAudio; + this->OpenAudio = Mac_OpenAudio; + this->CloseAudio = Mac_CloseAudio; + this->LockAudio = Mac_LockAudio; this->UnlockAudio = Mac_UnlockAudio; - this->free = Audio_DeleteDevice; + this->free = Audio_DeleteDevice; -#ifdef __MACOSX__ /* Mac OS X uses threaded audio, so normal thread code is okay */ - this->LockAudio = NULL; +#ifdef __MACOSX__ /* Mac OS X uses threaded audio, so normal thread code is okay */ + this->LockAudio = NULL; this->UnlockAudio = NULL; #endif return this; } AudioBootStrap SNDMGR_bootstrap = { - "sndmgr", "MacOS SoundManager 3.0", - Audio_Available, Audio_CreateDevice + "sndmgr", "MacOS SoundManager 3.0", + Audio_Available, Audio_CreateDevice }; #if defined(TARGET_API_MAC_CARBON) || defined(USE_RYANS_SOUNDCODE) @@ -113,200 +116,211 @@ AudioBootStrap SNDMGR_bootstrap = { static volatile SInt32 audio_is_locked = 0; static volatile SInt32 need_to_mix = 0; -static UInt8 *buffer[2]; +static UInt8 *buffer[2]; static volatile UInt32 running = 0; static CmpSoundHeader header; static volatile Uint32 fill_me = 0; -static void mix_buffer(SDL_AudioDevice *audio, UInt8 *buffer) +static void +mix_buffer(SDL_AudioDevice * audio, UInt8 * buffer) { - if ( ! audio->paused ) { + if (!audio->paused) { #ifdef __MACOSX__ SDL_mutexP(audio->mixer_lock); #endif - if ( audio->convert.needed ) { + if (audio->convert.needed) { audio->spec.callback(audio->spec.userdata, - (Uint8 *)audio->convert.buf,audio->convert.len); + (Uint8 *) audio->convert.buf, + audio->convert.len); SDL_ConvertAudio(&audio->convert); - if ( audio->convert.len_cvt != audio->spec.size ) { - /* Uh oh... probably crashes here */; + if (audio->convert.len_cvt != audio->spec.size) { + /* Uh oh... probably crashes here */ ; } SDL_memcpy(buffer, audio->convert.buf, audio->convert.len_cvt); } else { - audio->spec.callback(audio->spec.userdata, buffer, audio->spec.size); + audio->spec.callback(audio->spec.userdata, buffer, + audio->spec.size); } #ifdef __MACOSX__ SDL_mutexV(audio->mixer_lock); #endif } - DecrementAtomic((SInt32 *) &need_to_mix); + DecrementAtomic((SInt32 *) & need_to_mix); } -static void Mac_LockAudio(_THIS) +static void +Mac_LockAudio(_THIS) { - IncrementAtomic((SInt32 *) &audio_is_locked); + IncrementAtomic((SInt32 *) & audio_is_locked); } -static void Mac_UnlockAudio(_THIS) +static void +Mac_UnlockAudio(_THIS) { SInt32 oldval; - - oldval = DecrementAtomic((SInt32 *) &audio_is_locked); - if ( oldval != 1 ) /* != 1 means audio is still locked. */ + + oldval = DecrementAtomic((SInt32 *) & audio_is_locked); + if (oldval != 1) /* != 1 means audio is still locked. */ return; /* Did we miss the chance to mix in an interrupt? Do it now. */ - if ( BitAndAtomic (0xFFFFFFFF, (UInt32 *) &need_to_mix) ) { + if (BitAndAtomic(0xFFFFFFFF, (UInt32 *) & need_to_mix)) { /* * Note that this could be a problem if you missed an interrupt * while the audio was locked, and get preempted by a second * interrupt here, but that means you locked for way too long anyhow. */ - mix_buffer (this, buffer[fill_me]); + mix_buffer(this, buffer[fill_me]); } } -static void callBackProc (SndChannel *chan, SndCommand *cmd_passed ) { - UInt32 play_me; - SndCommand cmd; - SDL_AudioDevice *audio = (SDL_AudioDevice *)chan->userInfo; - - IncrementAtomic((SInt32 *) &need_to_mix); - - fill_me = cmd_passed->param2; /* buffer that has just finished playing, so fill it */ - play_me = ! fill_me; /* filled buffer to play _now_ */ - - if ( ! audio->enabled ) { - return; - } - - /* queue previously mixed buffer for playback. */ - header.samplePtr = (Ptr)buffer[play_me]; - cmd.cmd = bufferCmd; - cmd.param1 = 0; - cmd.param2 = (long)&header; - SndDoCommand (chan, &cmd, 0); - - memset (buffer[fill_me], 0, audio->spec.size); - - /* - * if audio device isn't locked, mix the next buffer to be queued in - * the memory block that just finished playing. - */ - if ( ! BitAndAtomic(0xFFFFFFFF, (UInt32 *) &audio_is_locked) ) { - mix_buffer (audio, buffer[fill_me]); - } - - /* set this callback to run again when current buffer drains. */ - if ( running ) { - cmd.cmd = callBackCmd; - cmd.param1 = 0; - cmd.param2 = play_me; - - SndDoCommand (chan, &cmd, 0); - } +static void +callBackProc(SndChannel * chan, SndCommand * cmd_passed) +{ + UInt32 play_me; + SndCommand cmd; + SDL_AudioDevice *audio = (SDL_AudioDevice *) chan->userInfo; + + IncrementAtomic((SInt32 *) & need_to_mix); + + fill_me = cmd_passed->param2; /* buffer that has just finished playing, so fill it */ + play_me = !fill_me; /* filled buffer to play _now_ */ + + if (!audio->enabled) { + return; + } + + /* queue previously mixed buffer for playback. */ + header.samplePtr = (Ptr) buffer[play_me]; + cmd.cmd = bufferCmd; + cmd.param1 = 0; + cmd.param2 = (long) &header; + SndDoCommand(chan, &cmd, 0); + + memset(buffer[fill_me], 0, audio->spec.size); + + /* + * if audio device isn't locked, mix the next buffer to be queued in + * the memory block that just finished playing. + */ + if (!BitAndAtomic(0xFFFFFFFF, (UInt32 *) & audio_is_locked)) { + mix_buffer(audio, buffer[fill_me]); + } + + /* set this callback to run again when current buffer drains. */ + if (running) { + cmd.cmd = callBackCmd; + cmd.param1 = 0; + cmd.param2 = play_me; + + SndDoCommand(chan, &cmd, 0); + } } -static int Mac_OpenAudio(_THIS, SDL_AudioSpec *spec) { +static int +Mac_OpenAudio(_THIS, SDL_AudioSpec * spec) +{ + + SndCallBackUPP callback; + int sample_bits; + int i; + long initOptions; - SndCallBackUPP callback; - int sample_bits; - int i; - long initOptions; - - /* Very few conversions are required, but... */ + /* Very few conversions are required, but... */ switch (spec->format) { - case AUDIO_S8: + case AUDIO_S8: spec->format = AUDIO_U8; break; - case AUDIO_U16LSB: + case AUDIO_U16LSB: spec->format = AUDIO_S16LSB; break; - case AUDIO_U16MSB: + case AUDIO_U16MSB: spec->format = AUDIO_S16MSB; break; } SDL_CalculateAudioSpec(spec); - + /* initialize bufferCmd header */ - memset (&header, 0, sizeof(header)); - callback = (SndCallBackUPP) NewSndCallBackUPP (callBackProc); + memset(&header, 0, sizeof(header)); + callback = (SndCallBackUPP) NewSndCallBackUPP(callBackProc); sample_bits = spec->size / spec->samples / spec->channels * 8; #ifdef DEBUG_AUDIO fprintf(stderr, - "Audio format 0x%x, channels = %d, sample_bits = %d, frequency = %d\n", - spec->format, spec->channels, sample_bits, spec->freq); + "Audio format 0x%x, channels = %d, sample_bits = %d, frequency = %d\n", + spec->format, spec->channels, sample_bits, spec->freq); #endif /* DEBUG_AUDIO */ - + header.numChannels = spec->channels; - header.sampleSize = sample_bits; - header.sampleRate = spec->freq << 16; - header.numFrames = spec->samples; - header.encode = cmpSH; - + header.sampleSize = sample_bits; + header.sampleRate = spec->freq << 16; + header.numFrames = spec->samples; + header.encode = cmpSH; + /* Note that we install the 16bitLittleEndian Converter if needed. */ - if ( spec->format == 0x8010 ) { + if (spec->format == 0x8010) { header.compressionID = fixedCompression; header.format = k16BitLittleEndianFormat; } - + /* allocate 2 buffers */ - for (i=0; i<2; i++) { - buffer[i] = (UInt8*)malloc (sizeof(UInt8) * spec->size); - if (buffer[i] == NULL) { - SDL_OutOfMemory(); - return (-1); - } - memset (buffer[i], 0, spec->size); - } - - /* Create the sound manager channel */ - channel = (SndChannelPtr)SDL_malloc(sizeof(*channel)); - if ( channel == NULL ) { + for (i = 0; i < 2; i++) { + buffer[i] = (UInt8 *) malloc(sizeof(UInt8) * spec->size); + if (buffer[i] == NULL) { + SDL_OutOfMemory(); + return (-1); + } + memset(buffer[i], 0, spec->size); + } + + /* Create the sound manager channel */ + channel = (SndChannelPtr) SDL_malloc(sizeof(*channel)); + if (channel == NULL) { SDL_OutOfMemory(); - return(-1); + return (-1); } - if ( spec->channels >= 2 ) { + if (spec->channels >= 2) { initOptions = initStereo; } else { initOptions = initMono; } - channel->userInfo = (long)this; + channel->userInfo = (long) this; channel->qLength = 128; - if ( SndNewChannel(&channel, sampledSynth, initOptions, callback) != noErr ) { + if (SndNewChannel(&channel, sampledSynth, initOptions, callback) != noErr) { SDL_SetError("Unable to create audio channel"); SDL_free(channel); channel = NULL; - return(-1); + return (-1); } - - /* start playback */ - { - SndCommand cmd; - cmd.cmd = callBackCmd; - cmd.param2 = 0; - running = 1; - SndDoCommand (channel, &cmd, 0); - } - - return 1; + + /* start playback */ + { + SndCommand cmd; + cmd.cmd = callBackCmd; + cmd.param2 = 0; + running = 1; + SndDoCommand(channel, &cmd, 0); + } + + return 1; } -static void Mac_CloseAudio(_THIS) { - - int i; - - running = 0; - - if (channel) { - SndDisposeChannel (channel, true); - channel = NULL; - } - - for ( i=0; i<2; ++i ) { - if ( buffer[i] ) { +static void +Mac_CloseAudio(_THIS) +{ + + int i; + + running = 0; + + if (channel) { + SndDisposeChannel(channel, true); + channel = NULL; + } + + for (i = 0; i < 2; ++i) { + if (buffer[i]) { SDL_free(buffer[i]); buffer[i] = NULL; } @@ -315,12 +329,14 @@ static void Mac_CloseAudio(_THIS) { #else /* !TARGET_API_MAC_CARBON && !USE_RYANS_SOUNDCODE */ -static void Mac_LockAudio(_THIS) +static void +Mac_LockAudio(_THIS) { /* no-op. */ } -static void Mac_UnlockAudio(_THIS) +static void +Mac_UnlockAudio(_THIS) { /* no-op. */ } @@ -330,38 +346,41 @@ static void Mac_UnlockAudio(_THIS) the buffers, so we'll zero it to silence and fill it with audio if we're not paused. */ -static pascal -void sndDoubleBackProc (SndChannelPtr chan, SndDoubleBufferPtr newbuf) +static pascal void +sndDoubleBackProc(SndChannelPtr chan, SndDoubleBufferPtr newbuf) { - SDL_AudioDevice *audio = (SDL_AudioDevice *)newbuf->dbUserInfo[0]; + SDL_AudioDevice *audio = (SDL_AudioDevice *) newbuf->dbUserInfo[0]; /* If audio is quitting, don't do anything */ - if ( ! audio->enabled ) { + if (!audio->enabled) { return; } - memset (newbuf->dbSoundData, 0, audio->spec.size); + memset(newbuf->dbSoundData, 0, audio->spec.size); newbuf->dbNumFrames = audio->spec.samples; - if ( ! audio->paused ) { - if ( audio->convert.needed ) { + if (!audio->paused) { + if (audio->convert.needed) { audio->spec.callback(audio->spec.userdata, - (Uint8 *)audio->convert.buf,audio->convert.len); + (Uint8 *) audio->convert.buf, + audio->convert.len); SDL_ConvertAudio(&audio->convert); #if 0 - if ( audio->convert.len_cvt != audio->spec.size ) { - /* Uh oh... probably crashes here */; + if (audio->convert.len_cvt != audio->spec.size) { + /* Uh oh... probably crashes here */ ; } #endif SDL_memcpy(newbuf->dbSoundData, audio->convert.buf, - audio->convert.len_cvt); + audio->convert.len_cvt); } else { audio->spec.callback(audio->spec.userdata, - (Uint8 *)newbuf->dbSoundData, audio->spec.size); + (Uint8 *) newbuf->dbSoundData, + audio->spec.size); } } - newbuf->dbFlags |= dbBufferReady; + newbuf->dbFlags |= dbBufferReady; } -static int DoubleBufferAudio_Available(void) +static int +DoubleBufferAudio_Available(void) { int available; NumVersion sndversion; @@ -369,40 +388,42 @@ static int DoubleBufferAudio_Available(void) available = 0; sndversion = SndSoundManagerVersion(); - if ( sndversion.majorRev >= 3 ) { - if ( Gestalt(gestaltSoundAttr, &response) == noErr ) { - if ( (response & (1 << gestaltSndPlayDoubleBuffer)) ) { + if (sndversion.majorRev >= 3) { + if (Gestalt(gestaltSoundAttr, &response) == noErr) { + if ((response & (1 << gestaltSndPlayDoubleBuffer))) { available = 1; } } } else { - if ( Gestalt(gestaltSoundAttr, &response) == noErr ) { - if ( (response & (1 << gestaltHasASC)) ) { + if (Gestalt(gestaltSoundAttr, &response) == noErr) { + if ((response & (1 << gestaltHasASC))) { available = 1; } } } - return(available); + return (available); } -static void Mac_CloseAudio(_THIS) +static void +Mac_CloseAudio(_THIS) { int i; - if ( channel != NULL ) { + if (channel != NULL) { /* Clean up the audio channel */ SndDisposeChannel(channel, true); channel = NULL; } - for ( i=0; i<2; ++i ) { - if ( audio_buf[i] ) { + for (i = 0; i < 2; ++i) { + if (audio_buf[i]) { SDL_free(audio_buf[i]); audio_buf[i] = NULL; } } } -static int Mac_OpenAudio(_THIS, SDL_AudioSpec *spec) +static int +Mac_OpenAudio(_THIS, SDL_AudioSpec * spec) { SndDoubleBufferHeader2 audio_dbh; int i; @@ -411,20 +432,20 @@ static int Mac_OpenAudio(_THIS, SDL_AudioSpec *spec) SndDoubleBackUPP doubleBackProc; /* Check to make sure double-buffered audio is available */ - if ( ! DoubleBufferAudio_Available() ) { + if (!DoubleBufferAudio_Available()) { SDL_SetError("Sound manager doesn't support double-buffering"); - return(-1); + return (-1); } /* Very few conversions are required, but... */ switch (spec->format) { - case AUDIO_S8: + case AUDIO_S8: spec->format = AUDIO_U8; break; - case AUDIO_U16LSB: + case AUDIO_U16LSB: spec->format = AUDIO_S16LSB; break; - case AUDIO_U16MSB: + case AUDIO_U16MSB: spec->format = AUDIO_S16MSB; break; } @@ -432,65 +453,65 @@ static int Mac_OpenAudio(_THIS, SDL_AudioSpec *spec) /* initialize the double-back header */ SDL_memset(&audio_dbh, 0, sizeof(audio_dbh)); - doubleBackProc = NewSndDoubleBackProc (sndDoubleBackProc); + doubleBackProc = NewSndDoubleBackProc(sndDoubleBackProc); sample_bits = spec->size / spec->samples / spec->channels * 8; - + audio_dbh.dbhNumChannels = spec->channels; - audio_dbh.dbhSampleSize = sample_bits; + audio_dbh.dbhSampleSize = sample_bits; audio_dbh.dbhCompressionID = 0; - audio_dbh.dbhPacketSize = 0; - audio_dbh.dbhSampleRate = spec->freq << 16; - audio_dbh.dbhDoubleBack = doubleBackProc; - audio_dbh.dbhFormat = 0; + audio_dbh.dbhPacketSize = 0; + audio_dbh.dbhSampleRate = spec->freq << 16; + audio_dbh.dbhDoubleBack = doubleBackProc; + audio_dbh.dbhFormat = 0; /* Note that we install the 16bitLittleEndian Converter if needed. */ - if ( spec->format == 0x8010 ) { + if (spec->format == 0x8010) { audio_dbh.dbhCompressionID = fixedCompression; audio_dbh.dbhFormat = k16BitLittleEndianFormat; } /* allocate the 2 double-back buffers */ - for ( i=0; i<2; ++i ) { - audio_buf[i] = SDL_calloc(1, sizeof(SndDoubleBuffer)+spec->size); - if ( audio_buf[i] == NULL ) { + for (i = 0; i < 2; ++i) { + audio_buf[i] = SDL_calloc(1, sizeof(SndDoubleBuffer) + spec->size); + if (audio_buf[i] == NULL) { SDL_OutOfMemory(); - return(-1); + return (-1); } audio_buf[i]->dbNumFrames = spec->samples; audio_buf[i]->dbFlags = dbBufferReady; - audio_buf[i]->dbUserInfo[0] = (long)this; + audio_buf[i]->dbUserInfo[0] = (long) this; audio_dbh.dbhBufferPtr[i] = audio_buf[i]; } /* Create the sound manager channel */ - channel = (SndChannelPtr)SDL_malloc(sizeof(*channel)); - if ( channel == NULL ) { + channel = (SndChannelPtr) SDL_malloc(sizeof(*channel)); + if (channel == NULL) { SDL_OutOfMemory(); - return(-1); + return (-1); } - if ( spec->channels >= 2 ) { + if (spec->channels >= 2) { initOptions = initStereo; } else { initOptions = initMono; } channel->userInfo = 0; channel->qLength = 128; - if ( SndNewChannel(&channel, sampledSynth, initOptions, 0L) != noErr ) { + if (SndNewChannel(&channel, sampledSynth, initOptions, 0L) != noErr) { SDL_SetError("Unable to create audio channel"); SDL_free(channel); channel = NULL; - return(-1); + return (-1); } - + /* Start playback */ - if ( SndPlayDoubleBuffer(channel, (SndDoubleBufferHeaderPtr)&audio_dbh) - != noErr ) { + if (SndPlayDoubleBuffer(channel, (SndDoubleBufferHeaderPtr) & audio_dbh) + != noErr) { SDL_SetError("Unable to play double buffered audio"); - return(-1); + return (-1); } - + return 1; } #endif /* TARGET_API_MAC_CARBON || USE_RYANS_SOUNDCODE */ - +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/audio/macrom/SDL_romaudio.h b/src/audio/macrom/SDL_romaudio.h index be5dc6961..23633182f 100644 --- a/src/audio/macrom/SDL_romaudio.h +++ b/src/audio/macrom/SDL_romaudio.h @@ -32,14 +32,15 @@ /* Hidden "this" pointer for the video functions */ #define _THIS SDL_AudioDevice *this -struct SDL_PrivateAudioData { - /* Sound manager audio channel */ - SndChannelPtr channel; +struct SDL_PrivateAudioData +{ + /* Sound manager audio channel */ + SndChannelPtr channel; #if defined(TARGET_API_MAC_CARBON) || defined(USE_RYANS_SOUNDCODE) - /* FIXME: Add Ryan's static data here */ + /* FIXME: Add Ryan's static data here */ #else - /* Double buffering variables */ - SndDoubleBufferPtr audio_buf[2]; + /* Double buffering variables */ + SndDoubleBufferPtr audio_buf[2]; #endif }; @@ -48,3 +49,4 @@ struct SDL_PrivateAudioData { #define audio_buf (this->hidden->audio_buf) #endif /* _SDL_romaudio_h */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/audio/mint/SDL_mintaudio.c b/src/audio/mint/SDL_mintaudio.c index b98bb3242..515b07393 100644 --- a/src/audio/mint/SDL_mintaudio.c +++ b/src/audio/mint/SDL_mintaudio.c @@ -40,12 +40,12 @@ /* The audio device */ SDL_AudioDevice *SDL_MintAudio_device; -Uint8 *SDL_MintAudio_audiobuf[2]; /* Pointers to buffers */ -unsigned long SDL_MintAudio_audiosize; /* Length of audio buffer=spec->size */ -volatile unsigned short SDL_MintAudio_numbuf; /* Buffer to play */ +Uint8 *SDL_MintAudio_audiobuf[2]; /* Pointers to buffers */ +unsigned long SDL_MintAudio_audiosize; /* Length of audio buffer=spec->size */ +volatile unsigned short SDL_MintAudio_numbuf; /* Buffer to play */ volatile unsigned short SDL_MintAudio_mutex; volatile unsigned long SDL_MintAudio_clocktics; -cookie_stfa_t *SDL_MintAudio_stfa; +cookie_stfa_t *SDL_MintAudio_stfa; /* MiNT thread variables */ SDL_bool SDL_MintAudio_mint_present; @@ -55,139 +55,154 @@ long SDL_MintAudio_thread_pid; /* The callback function, called by each driver whenever needed */ -void SDL_MintAudio_Callback(void) +void +SDL_MintAudio_Callback(void) { - Uint8 *buffer; - SDL_AudioDevice *audio = SDL_MintAudio_device; - - buffer = SDL_MintAudio_audiobuf[SDL_MintAudio_numbuf]; - SDL_memset(buffer, audio->spec.silence, audio->spec.size); - - if (audio->paused) - return; - - if (audio->convert.needed) { - int silence; - - if ( audio->convert.src_format == AUDIO_U8 ) { - silence = 0x80; - } else { - silence = 0; - } - SDL_memset(audio->convert.buf, silence, audio->convert.len); - audio->spec.callback(audio->spec.userdata, - (Uint8 *)audio->convert.buf,audio->convert.len); - SDL_ConvertAudio(&audio->convert); - SDL_memcpy(buffer, audio->convert.buf, audio->convert.len_cvt); - } else { - audio->spec.callback(audio->spec.userdata, buffer, audio->spec.size); - } + Uint8 *buffer; + SDL_AudioDevice *audio = SDL_MintAudio_device; + + buffer = SDL_MintAudio_audiobuf[SDL_MintAudio_numbuf]; + SDL_memset(buffer, audio->spec.silence, audio->spec.size); + + if (audio->paused) + return; + + if (audio->convert.needed) { + int silence; + + if (audio->convert.src_format == AUDIO_U8) { + silence = 0x80; + } else { + silence = 0; + } + SDL_memset(audio->convert.buf, silence, audio->convert.len); + audio->spec.callback(audio->spec.userdata, + (Uint8 *) audio->convert.buf, + audio->convert.len); + SDL_ConvertAudio(&audio->convert); + SDL_memcpy(buffer, audio->convert.buf, audio->convert.len_cvt); + } else { + audio->spec.callback(audio->spec.userdata, buffer, audio->spec.size); + } } /* Add a new frequency/clock/predivisor to the current list */ -void SDL_MintAudio_AddFrequency(_THIS, Uint32 frequency, Uint32 clock, - Uint32 prediv, int gpio_bits) +void +SDL_MintAudio_AddFrequency(_THIS, Uint32 frequency, Uint32 clock, + Uint32 prediv, int gpio_bits) { - int i, p; - - if (MINTAUDIO_freqcount==MINTAUDIO_maxfreqs) { - return; - } - - /* Search where to insert the frequency (highest first) */ - for (p=0; p MINTAUDIO_frequencies[p].frequency) { - break; - } - } - - /* Put all following ones farer */ - if (MINTAUDIO_freqcount>0) { - for (i=MINTAUDIO_freqcount; i>p; i--) { - SDL_memcpy(&MINTAUDIO_frequencies[i], &MINTAUDIO_frequencies[i-1], sizeof(mint_frequency_t)); - } - } - - /* And insert new one */ - MINTAUDIO_frequencies[p].frequency = frequency; - MINTAUDIO_frequencies[p].masterclock = clock; - MINTAUDIO_frequencies[p].predivisor = prediv; - MINTAUDIO_frequencies[p].gpio_bits = gpio_bits; - - MINTAUDIO_freqcount++; + int i, p; + + if (MINTAUDIO_freqcount == MINTAUDIO_maxfreqs) { + return; + } + + /* Search where to insert the frequency (highest first) */ + for (p = 0; p < MINTAUDIO_freqcount; p++) { + if (frequency > MINTAUDIO_frequencies[p].frequency) { + break; + } + } + + /* Put all following ones farer */ + if (MINTAUDIO_freqcount > 0) { + for (i = MINTAUDIO_freqcount; i > p; i--) { + SDL_memcpy(&MINTAUDIO_frequencies[i], + &MINTAUDIO_frequencies[i - 1], + sizeof(mint_frequency_t)); + } + } + + /* And insert new one */ + MINTAUDIO_frequencies[p].frequency = frequency; + MINTAUDIO_frequencies[p].masterclock = clock; + MINTAUDIO_frequencies[p].predivisor = prediv; + MINTAUDIO_frequencies[p].gpio_bits = gpio_bits; + + MINTAUDIO_freqcount++; } /* Search for the nearest frequency */ -int SDL_MintAudio_SearchFrequency(_THIS, int desired_freq) +int +SDL_MintAudio_SearchFrequency(_THIS, int desired_freq) { - int i; - - /* Only 1 freq ? */ - if (MINTAUDIO_freqcount==1) { - return 0; - } - - /* Check the array */ - for (i=0; i= ((MINTAUDIO_frequencies[i].frequency+ - MINTAUDIO_frequencies[i+1].frequency)>>1)) { - return i; - } - } - - /* Not in the array, give the latest */ - return MINTAUDIO_freqcount-1; + int i; + + /* Only 1 freq ? */ + if (MINTAUDIO_freqcount == 1) { + return 0; + } + + /* Check the array */ + for (i = 0; i < MINTAUDIO_freqcount; i++) { + if (desired_freq >= ((MINTAUDIO_frequencies[i].frequency + + MINTAUDIO_frequencies[i + 1].frequency) >> 1)) { + return i; + } + } + + /* Not in the array, give the latest */ + return MINTAUDIO_freqcount - 1; } /* The thread function, used under MiNT with xbios */ -int SDL_MintAudio_Thread(long param) +int +SDL_MintAudio_Thread(long param) { - SndBufPtr pointers; - SDL_bool buffers_filled[2] = {SDL_FALSE, SDL_FALSE}; - - SDL_MintAudio_thread_finished = SDL_FALSE; - while (!SDL_MintAudio_quit_thread) { - if (Buffptr(&pointers)!=0) - continue; - - if (( (unsigned long)pointers.play>=(unsigned long)SDL_MintAudio_audiobuf[0]) - && ( (unsigned long)pointers.play<=(unsigned long)SDL_MintAudio_audiobuf[1])) - { - /* DMA is reading buffer #0, setup buffer #1 if not already done */ - if (!buffers_filled[1]) { - SDL_MintAudio_numbuf = 1; - SDL_MintAudio_Callback(); - Setbuffer(0, SDL_MintAudio_audiobuf[1], SDL_MintAudio_audiobuf[1] + SDL_MintAudio_audiosize); - buffers_filled[1]=SDL_TRUE; - buffers_filled[0]=SDL_FALSE; - } - } else { - /* DMA is reading buffer #1, setup buffer #0 if not already done */ - if (!buffers_filled[0]) { - SDL_MintAudio_numbuf = 0; - SDL_MintAudio_Callback(); - Setbuffer(0, SDL_MintAudio_audiobuf[0], SDL_MintAudio_audiobuf[0] + SDL_MintAudio_audiosize); - buffers_filled[0]=SDL_TRUE; - buffers_filled[1]=SDL_FALSE; - } - } - - usleep(100); - } - SDL_MintAudio_thread_finished = SDL_TRUE; - return 0; + SndBufPtr pointers; + SDL_bool buffers_filled[2] = { SDL_FALSE, SDL_FALSE }; + + SDL_MintAudio_thread_finished = SDL_FALSE; + while (!SDL_MintAudio_quit_thread) { + if (Buffptr(&pointers) != 0) + continue; + + if (((unsigned long) pointers.play >= + (unsigned long) SDL_MintAudio_audiobuf[0]) + && ((unsigned long) pointers.play <= + (unsigned long) SDL_MintAudio_audiobuf[1])) { + /* DMA is reading buffer #0, setup buffer #1 if not already done */ + if (!buffers_filled[1]) { + SDL_MintAudio_numbuf = 1; + SDL_MintAudio_Callback(); + Setbuffer(0, SDL_MintAudio_audiobuf[1], + SDL_MintAudio_audiobuf[1] + + SDL_MintAudio_audiosize); + buffers_filled[1] = SDL_TRUE; + buffers_filled[0] = SDL_FALSE; + } + } else { + /* DMA is reading buffer #1, setup buffer #0 if not already done */ + if (!buffers_filled[0]) { + SDL_MintAudio_numbuf = 0; + SDL_MintAudio_Callback(); + Setbuffer(0, SDL_MintAudio_audiobuf[0], + SDL_MintAudio_audiobuf[0] + + SDL_MintAudio_audiosize); + buffers_filled[0] = SDL_TRUE; + buffers_filled[1] = SDL_FALSE; + } + } + + usleep(100); + } + SDL_MintAudio_thread_finished = SDL_TRUE; + return 0; } -void SDL_MintAudio_WaitThread(void) +void +SDL_MintAudio_WaitThread(void) { - if (!SDL_MintAudio_mint_present) - return; + if (!SDL_MintAudio_mint_present) + return; - if (SDL_MintAudio_thread_finished) - return; + if (SDL_MintAudio_thread_finished) + return; - SDL_MintAudio_quit_thread = SDL_TRUE; - while (!SDL_MintAudio_thread_finished) { - Syield(); - } + SDL_MintAudio_quit_thread = SDL_TRUE; + while (!SDL_MintAudio_thread_finished) { + Syield(); + } } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/audio/mint/SDL_mintaudio.h b/src/audio/mint/SDL_mintaudio.h index 970169c17..5a95f5189 100644 --- a/src/audio/mint/SDL_mintaudio.h +++ b/src/audio/mint/SDL_mintaudio.h @@ -37,19 +37,21 @@ #define _THIS SDL_AudioDevice *this /* 16 predivisors with 3 clocks max. */ -#define MINTAUDIO_maxfreqs (16*3) - -typedef struct { - Uint32 frequency; - Uint32 masterclock; - Uint32 predivisor; - int gpio_bits; /* in case of external clock */ +#define MINTAUDIO_maxfreqs (16*3) + +typedef struct +{ + Uint32 frequency; + Uint32 masterclock; + Uint32 predivisor; + int gpio_bits; /* in case of external clock */ } mint_frequency_t; -struct SDL_PrivateAudioData { - mint_frequency_t frequencies[MINTAUDIO_maxfreqs]; - int freq_count; /* Number of frequencies in the array */ - int numfreq; /* Number of selected frequency */ +struct SDL_PrivateAudioData +{ + mint_frequency_t frequencies[MINTAUDIO_maxfreqs]; + int freq_count; /* Number of frequencies in the array */ + int numfreq; /* Number of selected frequency */ }; /* Old variable names */ @@ -59,23 +61,24 @@ struct SDL_PrivateAudioData { #define MINTAUDIO_numfreq (this->hidden->numfreq) /* _MCH cookie (values>>16) */ -enum { - MCH_ST=0, - MCH_STE, - MCH_TT, - MCH_F30, - MCH_CLONE, - MCH_ARANYM +enum +{ + MCH_ST = 0, + MCH_STE, + MCH_TT, + MCH_F30, + MCH_CLONE, + MCH_ARANYM }; /* Master clocks for replay frequencies */ -#define MASTERCLOCK_STE 8010666 /* Not sure of this one */ -#define MASTERCLOCK_TT 16107953 /* Not sure of this one */ +#define MASTERCLOCK_STE 8010666 /* Not sure of this one */ +#define MASTERCLOCK_TT 16107953 /* Not sure of this one */ #define MASTERCLOCK_FALCON1 25175000 -#define MASTERCLOCK_FALCON2 32000000 /* Only usable for DSP56K */ -#define MASTERCLOCK_FALCONEXT -1 /* Clock on DSP56K port, unknown */ -#define MASTERCLOCK_44K 22579200 /* Standard clock for 44.1 Khz */ -#define MASTERCLOCK_48K 24576000 /* Standard clock for 48 Khz */ +#define MASTERCLOCK_FALCON2 32000000 /* Only usable for DSP56K */ +#define MASTERCLOCK_FALCONEXT -1 /* Clock on DSP56K port, unknown */ +#define MASTERCLOCK_44K 22579200 /* Standard clock for 44.1 Khz */ +#define MASTERCLOCK_48K 24576000 /* Standard clock for 48 Khz */ /* Master clock predivisors */ #define MASTERPREDIV_STE 160 @@ -84,48 +87,50 @@ enum { #define MASTERPREDIV_MILAN 256 /* MFP 68901 interrupt sources */ -enum { - MFP_PARALLEL=0, - MFP_DCD, - MFP_CTS, - MFP_BITBLT, - MFP_TIMERD, - MFP_BAUDRATE=MFP_TIMERD, - MFP_TIMERC, - MFP_200HZ=MFP_TIMERC, - MFP_ACIA, - MFP_DISK, - MFP_TIMERB, - MFP_HBLANK=MFP_TIMERB, - MFP_TERR, - MFP_TBE, - MFP_RERR, - MFP_RBF, - MFP_TIMERA, - MFP_DMASOUND=MFP_TIMERA, - MFP_RING, - MFP_MONODETECT +enum +{ + MFP_PARALLEL = 0, + MFP_DCD, + MFP_CTS, + MFP_BITBLT, + MFP_TIMERD, + MFP_BAUDRATE = MFP_TIMERD, + MFP_TIMERC, + MFP_200HZ = MFP_TIMERC, + MFP_ACIA, + MFP_DISK, + MFP_TIMERB, + MFP_HBLANK = MFP_TIMERB, + MFP_TERR, + MFP_TBE, + MFP_RERR, + MFP_RBF, + MFP_TIMERA, + MFP_DMASOUND = MFP_TIMERA, + MFP_RING, + MFP_MONODETECT }; /* Xbtimer() timers */ -enum { - XB_TIMERA=0, - XB_TIMERB, - XB_TIMERC, - XB_TIMERD +enum +{ + XB_TIMERA = 0, + XB_TIMERB, + XB_TIMERC, + XB_TIMERD }; /* Variables */ extern SDL_AudioDevice *SDL_MintAudio_device; -extern Uint8 *SDL_MintAudio_audiobuf[2]; /* Pointers to buffers */ -extern unsigned long SDL_MintAudio_audiosize; /* Length of audio buffer=spec->size */ -extern volatile unsigned short SDL_MintAudio_numbuf; /* Buffer to play */ +extern Uint8 *SDL_MintAudio_audiobuf[2]; /* Pointers to buffers */ +extern unsigned long SDL_MintAudio_audiosize; /* Length of audio buffer=spec->size */ +extern volatile unsigned short SDL_MintAudio_numbuf; /* Buffer to play */ extern volatile unsigned short SDL_MintAudio_mutex; extern cookie_stfa_t *SDL_MintAudio_stfa; extern volatile unsigned long SDL_MintAudio_clocktics; /* MiNT thread variables */ -extern SDL_bool SDL_MintAudio_mint_present; +extern SDL_bool SDL_MintAudio_mint_present; extern SDL_bool SDL_MintAudio_quit_thread; extern SDL_bool SDL_MintAudio_thread_finished; extern long SDL_MintAudio_thread_pid; @@ -133,7 +138,7 @@ extern long SDL_MintAudio_thread_pid; /* Functions */ void SDL_MintAudio_Callback(void); void SDL_MintAudio_AddFrequency(_THIS, Uint32 frequency, Uint32 clock, - Uint32 prediv, int gpio_bits); + Uint32 prediv, int gpio_bits); int SDL_MintAudio_SearchFrequency(_THIS, int desired_freq); /* MiNT thread functions */ @@ -149,3 +154,4 @@ void SDL_MintAudio_Dma8Interrupt(void); void SDL_MintAudio_StfaInterrupt(void); #endif /* _SDL_mintaudio_h */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/audio/mint/SDL_mintaudio_dma8.c b/src/audio/mint/SDL_mintaudio_dma8.c index 39e7a6d22..a6c6bec09 100644 --- a/src/audio/mint/SDL_mintaudio_dma8.c +++ b/src/audio/mint/SDL_mintaudio_dma8.c @@ -64,293 +64,307 @@ static unsigned long cookie_snd, cookie_mch; /*--- Audio driver functions ---*/ static void Mint_CloseAudio(_THIS); -static int Mint_OpenAudio(_THIS, SDL_AudioSpec *spec); +static int Mint_OpenAudio(_THIS, SDL_AudioSpec * spec); static void Mint_LockAudio(_THIS); static void Mint_UnlockAudio(_THIS); /* To check/init hardware audio */ -static int Mint_CheckAudio(_THIS, SDL_AudioSpec *spec); -static void Mint_InitAudio(_THIS, SDL_AudioSpec *spec); +static int Mint_CheckAudio(_THIS, SDL_AudioSpec * spec); +static void Mint_InitAudio(_THIS, SDL_AudioSpec * spec); /*--- Audio driver bootstrap functions ---*/ -static int Audio_Available(void) +static int +Audio_Available(void) { - const char *envr = SDL_getenv("SDL_AUDIODRIVER"); + const char *envr = SDL_getenv("SDL_AUDIODRIVER"); - /* Check if user asked a different audio driver */ - if ((envr) && (SDL_strcmp(envr, MINT_AUDIO_DRIVER_NAME)!=0)) { - DEBUG_PRINT((DEBUG_NAME "user asked a different audio driver\n")); - return 0; - } + /* Check if user asked a different audio driver */ + if ((envr) && (SDL_strcmp(envr, MINT_AUDIO_DRIVER_NAME) != 0)) { + DEBUG_PRINT((DEBUG_NAME "user asked a different audio driver\n")); + return 0; + } - /* Cookie _MCH present ? if not, assume ST machine */ - if (Getcookie(C__MCH, &cookie_mch) == C_NOTFOUND) { - cookie_mch = MCH_ST; - } + /* Cookie _MCH present ? if not, assume ST machine */ + if (Getcookie(C__MCH, &cookie_mch) == C_NOTFOUND) { + cookie_mch = MCH_ST; + } - /* Cookie _SND present ? if not, assume ST machine */ - if (Getcookie(C__SND, &cookie_snd) == C_NOTFOUND) { - cookie_snd = SND_PSG; - } + /* Cookie _SND present ? if not, assume ST machine */ + if (Getcookie(C__SND, &cookie_snd) == C_NOTFOUND) { + cookie_snd = SND_PSG; + } - /* Check if we have 8 bits audio */ - if ((cookie_snd & SND_8BIT)==0) { - DEBUG_PRINT((DEBUG_NAME "no 8 bits sound\n")); - return(0); - } + /* Check if we have 8 bits audio */ + if ((cookie_snd & SND_8BIT) == 0) { + DEBUG_PRINT((DEBUG_NAME "no 8 bits sound\n")); + return (0); + } - /* Check if audio is lockable */ - if (cookie_snd & SND_16BIT) { - if (Locksnd()!=1) { - DEBUG_PRINT((DEBUG_NAME "audio locked by other application\n")); - return(0); - } + /* Check if audio is lockable */ + if (cookie_snd & SND_16BIT) { + if (Locksnd() != 1) { + DEBUG_PRINT((DEBUG_NAME "audio locked by other application\n")); + return (0); + } - Unlocksnd(); - } + Unlocksnd(); + } - DEBUG_PRINT((DEBUG_NAME "8 bits audio available!\n")); - return(1); + DEBUG_PRINT((DEBUG_NAME "8 bits audio available!\n")); + return (1); } -static void Audio_DeleteDevice(SDL_AudioDevice *device) +static void +Audio_DeleteDevice(SDL_AudioDevice * device) { SDL_free(device->hidden); SDL_free(device); } -static SDL_AudioDevice *Audio_CreateDevice(int devindex) +static SDL_AudioDevice * +Audio_CreateDevice(int devindex) { - SDL_AudioDevice *this; + SDL_AudioDevice *this; - /* Initialize all variables that we clean on shutdown */ - this = (SDL_AudioDevice *)SDL_malloc(sizeof(SDL_AudioDevice)); - if ( this ) { + /* Initialize all variables that we clean on shutdown */ + this = (SDL_AudioDevice *) SDL_malloc(sizeof(SDL_AudioDevice)); + if (this) { SDL_memset(this, 0, (sizeof *this)); this->hidden = (struct SDL_PrivateAudioData *) - SDL_malloc((sizeof *this->hidden)); + SDL_malloc((sizeof *this->hidden)); } - if ( (this == NULL) || (this->hidden == NULL) ) { + if ((this == NULL) || (this->hidden == NULL)) { SDL_OutOfMemory(); - if ( this ) { + if (this) { SDL_free(this); } - return(0); + return (0); } SDL_memset(this->hidden, 0, (sizeof *this->hidden)); /* Set the function pointers */ - this->OpenAudio = Mint_OpenAudio; - this->CloseAudio = Mint_CloseAudio; - this->LockAudio = Mint_LockAudio; + this->OpenAudio = Mint_OpenAudio; + this->CloseAudio = Mint_CloseAudio; + this->LockAudio = Mint_LockAudio; this->UnlockAudio = Mint_UnlockAudio; - this->free = Audio_DeleteDevice; + this->free = Audio_DeleteDevice; return this; } AudioBootStrap MINTAUDIO_DMA8_bootstrap = { - MINT_AUDIO_DRIVER_NAME, "MiNT DMA 8 bits audio driver", - Audio_Available, Audio_CreateDevice + MINT_AUDIO_DRIVER_NAME, "MiNT DMA 8 bits audio driver", + Audio_Available, Audio_CreateDevice }; -static void Mint_LockAudio(_THIS) +static void +Mint_LockAudio(_THIS) { - void *oldpile; + void *oldpile; - /* Stop replay */ - oldpile=(void *)Super(0); - DMAAUDIO_IO.control=0; - Super(oldpile); + /* Stop replay */ + oldpile = (void *) Super(0); + DMAAUDIO_IO.control = 0; + Super(oldpile); } -static void Mint_UnlockAudio(_THIS) +static void +Mint_UnlockAudio(_THIS) { - void *oldpile; + void *oldpile; - /* Restart replay */ - oldpile=(void *)Super(0); - DMAAUDIO_IO.control=3; - Super(oldpile); + /* Restart replay */ + oldpile = (void *) Super(0); + DMAAUDIO_IO.control = 3; + Super(oldpile); } -static void Mint_CloseAudio(_THIS) +static void +Mint_CloseAudio(_THIS) { - void *oldpile; + void *oldpile; - /* Stop replay */ - oldpile=(void *)Super(0); - DMAAUDIO_IO.control=0; - Super(oldpile); + /* Stop replay */ + oldpile = (void *) Super(0); + DMAAUDIO_IO.control = 0; + Super(oldpile); - DEBUG_PRINT((DEBUG_NAME "closeaudio: replay stopped\n")); + DEBUG_PRINT((DEBUG_NAME "closeaudio: replay stopped\n")); - /* Disable interrupt */ - Jdisint(MFP_DMASOUND); + /* Disable interrupt */ + Jdisint(MFP_DMASOUND); - DEBUG_PRINT((DEBUG_NAME "closeaudio: interrupt disabled\n")); + DEBUG_PRINT((DEBUG_NAME "closeaudio: interrupt disabled\n")); - /* Wait if currently playing sound */ - while (SDL_MintAudio_mutex != 0) { - } + /* Wait if currently playing sound */ + while (SDL_MintAudio_mutex != 0) { + } - DEBUG_PRINT((DEBUG_NAME "closeaudio: no more interrupt running\n")); + DEBUG_PRINT((DEBUG_NAME "closeaudio: no more interrupt running\n")); - /* Clear buffers */ - if (SDL_MintAudio_audiobuf[0]) { - Mfree(SDL_MintAudio_audiobuf[0]); - SDL_MintAudio_audiobuf[0] = SDL_MintAudio_audiobuf[1] = NULL; - } + /* Clear buffers */ + if (SDL_MintAudio_audiobuf[0]) { + Mfree(SDL_MintAudio_audiobuf[0]); + SDL_MintAudio_audiobuf[0] = SDL_MintAudio_audiobuf[1] = NULL; + } - DEBUG_PRINT((DEBUG_NAME "closeaudio: buffers freed\n")); + DEBUG_PRINT((DEBUG_NAME "closeaudio: buffers freed\n")); } -static int Mint_CheckAudio(_THIS, SDL_AudioSpec *spec) +static int +Mint_CheckAudio(_THIS, SDL_AudioSpec * spec) { - int i, masterprediv, sfreq; - unsigned long masterclock; - - DEBUG_PRINT((DEBUG_NAME "asked: %d bits, ",spec->format & 0x00ff)); - DEBUG_PRINT(("signed=%d, ", ((spec->format & 0x8000)!=0))); - DEBUG_PRINT(("big endian=%d, ", ((spec->format & 0x1000)!=0))); - DEBUG_PRINT(("channels=%d, ", spec->channels)); - DEBUG_PRINT(("freq=%d\n", spec->freq)); - - /* Check formats available */ - spec->format = AUDIO_S8; - - /* Calculate and select the closest frequency */ - sfreq=0; - masterclock=MASTERCLOCK_STE; - masterprediv=MASTERPREDIV_STE; - switch(cookie_mch>>16) { + int i, masterprediv, sfreq; + unsigned long masterclock; + + DEBUG_PRINT((DEBUG_NAME "asked: %d bits, ", spec->format & 0x00ff)); + DEBUG_PRINT(("signed=%d, ", ((spec->format & 0x8000) != 0))); + DEBUG_PRINT(("big endian=%d, ", ((spec->format & 0x1000) != 0))); + DEBUG_PRINT(("channels=%d, ", spec->channels)); + DEBUG_PRINT(("freq=%d\n", spec->freq)); + + /* Check formats available */ + spec->format = AUDIO_S8; + + /* Calculate and select the closest frequency */ + sfreq = 0; + masterclock = MASTERCLOCK_STE; + masterprediv = MASTERPREDIV_STE; + switch (cookie_mch >> 16) { /* case MCH_STE: masterclock=MASTERCLOCK_STE; masterprediv=MASTERPREDIV_STE; break; */ - case MCH_TT: - masterclock=MASTERCLOCK_TT; - masterprediv=MASTERPREDIV_TT; - break; - case MCH_F30: - case MCH_ARANYM: - masterclock=MASTERCLOCK_FALCON1; - masterprediv=MASTERPREDIV_FALCON; - sfreq=1; - break; - } - - MINTAUDIO_freqcount=0; - for (i=sfreq;i<4;i++) { - SDL_MintAudio_AddFrequency(this, masterclock/(masterprediv*(1<freq); - spec->freq=MINTAUDIO_frequencies[MINTAUDIO_numfreq].frequency; + MINTAUDIO_numfreq = SDL_MintAudio_SearchFrequency(this, spec->freq); + spec->freq = MINTAUDIO_frequencies[MINTAUDIO_numfreq].frequency; - DEBUG_PRINT((DEBUG_NAME "obtained: %d bits, ",spec->format & 0x00ff)); - DEBUG_PRINT(("signed=%d, ", ((spec->format & 0x8000)!=0))); - DEBUG_PRINT(("big endian=%d, ", ((spec->format & 0x1000)!=0))); - DEBUG_PRINT(("channels=%d, ", spec->channels)); - DEBUG_PRINT(("freq=%d\n", spec->freq)); + DEBUG_PRINT((DEBUG_NAME "obtained: %d bits, ", spec->format & 0x00ff)); + DEBUG_PRINT(("signed=%d, ", ((spec->format & 0x8000) != 0))); + DEBUG_PRINT(("big endian=%d, ", ((spec->format & 0x1000) != 0))); + DEBUG_PRINT(("channels=%d, ", spec->channels)); + DEBUG_PRINT(("freq=%d\n", spec->freq)); - return 0; + return 0; } -static void Mint_InitAudio(_THIS, SDL_AudioSpec *spec) +static void +Mint_InitAudio(_THIS, SDL_AudioSpec * spec) { - void *oldpile; - unsigned long buffer; - unsigned char mode; - - /* Set replay tracks */ - if (cookie_snd & SND_16BIT) { - Settracks(0,0); - Setmontracks(0); - } + void *oldpile; + unsigned long buffer; + unsigned char mode; + + /* Set replay tracks */ + if (cookie_snd & SND_16BIT) { + Settracks(0, 0); + Setmontracks(0); + } - oldpile=(void *)Super(0); + oldpile = (void *) Super(0); - /* Stop currently playing sound */ - DMAAUDIO_IO.control=0; + /* Stop currently playing sound */ + DMAAUDIO_IO.control = 0; - /* Set buffer */ - buffer = (unsigned long) SDL_MintAudio_audiobuf[SDL_MintAudio_numbuf]; - DMAAUDIO_IO.start_high = (buffer>>16) & 255; - DMAAUDIO_IO.start_mid = (buffer>>8) & 255; - DMAAUDIO_IO.start_low = buffer & 255; + /* Set buffer */ + buffer = (unsigned long) SDL_MintAudio_audiobuf[SDL_MintAudio_numbuf]; + DMAAUDIO_IO.start_high = (buffer >> 16) & 255; + DMAAUDIO_IO.start_mid = (buffer >> 8) & 255; + DMAAUDIO_IO.start_low = buffer & 255; - buffer += SDL_MintAudio_audiosize; - DMAAUDIO_IO.end_high = (buffer>>16) & 255; - DMAAUDIO_IO.end_mid = (buffer>>8) & 255; - DMAAUDIO_IO.end_low = buffer & 255; + buffer += SDL_MintAudio_audiosize; + DMAAUDIO_IO.end_high = (buffer >> 16) & 255; + DMAAUDIO_IO.end_mid = (buffer >> 8) & 255; + DMAAUDIO_IO.end_low = buffer & 255; - mode = 3-MINTAUDIO_frequencies[MINTAUDIO_numfreq].predivisor; - if (spec->channels==1) { - mode |= 1<<7; - } - DMAAUDIO_IO.sound_ctrl = mode; + mode = 3 - MINTAUDIO_frequencies[MINTAUDIO_numfreq].predivisor; + if (spec->channels == 1) { + mode |= 1 << 7; + } + DMAAUDIO_IO.sound_ctrl = mode; - /* Set interrupt */ - Jdisint(MFP_DMASOUND); - Xbtimer(XB_TIMERA, 8, 1, SDL_MintAudio_Dma8Interrupt); - Jenabint(MFP_DMASOUND); + /* Set interrupt */ + Jdisint(MFP_DMASOUND); + Xbtimer(XB_TIMERA, 8, 1, SDL_MintAudio_Dma8Interrupt); + Jenabint(MFP_DMASOUND); - if (cookie_snd & SND_16BIT) { - if (Setinterrupt(SI_TIMERA, SI_PLAY)<0) { - DEBUG_PRINT((DEBUG_NAME "Setinterrupt() failed\n")); - } - } + if (cookie_snd & SND_16BIT) { + if (Setinterrupt(SI_TIMERA, SI_PLAY) < 0) { + DEBUG_PRINT((DEBUG_NAME "Setinterrupt() failed\n")); + } + } - /* Go */ - DMAAUDIO_IO.control = 3; /* playback + repeat */ + /* Go */ + DMAAUDIO_IO.control = 3; /* playback + repeat */ - Super(oldpile); + Super(oldpile); } -static int Mint_OpenAudio(_THIS, SDL_AudioSpec *spec) +static int +Mint_OpenAudio(_THIS, SDL_AudioSpec * spec) { - SDL_MintAudio_device = this; + SDL_MintAudio_device = this; - /* Check audio capabilities */ - if (Mint_CheckAudio(this, spec)==-1) { - return -1; - } + /* Check audio capabilities */ + if (Mint_CheckAudio(this, spec) == -1) { + return -1; + } - SDL_CalculateAudioSpec(spec); + SDL_CalculateAudioSpec(spec); - /* Allocate memory for audio buffers in DMA-able RAM */ - DEBUG_PRINT((DEBUG_NAME "buffer size=%d\n", spec->size)); + /* Allocate memory for audio buffers in DMA-able RAM */ + DEBUG_PRINT((DEBUG_NAME "buffer size=%d\n", spec->size)); - SDL_MintAudio_audiobuf[0] = Atari_SysMalloc(spec->size *2, MX_STRAM); - if (SDL_MintAudio_audiobuf[0]==NULL) { - SDL_SetError("MINT_OpenAudio: Not enough memory for audio buffer"); - return (-1); - } - SDL_MintAudio_audiobuf[1] = SDL_MintAudio_audiobuf[0] + spec->size ; - SDL_MintAudio_numbuf=0; - SDL_memset(SDL_MintAudio_audiobuf[0], spec->silence, spec->size *2); - SDL_MintAudio_audiosize = spec->size; - SDL_MintAudio_mutex = 0; + SDL_MintAudio_audiobuf[0] = Atari_SysMalloc(spec->size * 2, MX_STRAM); + if (SDL_MintAudio_audiobuf[0] == NULL) { + SDL_SetError("MINT_OpenAudio: Not enough memory for audio buffer"); + return (-1); + } + SDL_MintAudio_audiobuf[1] = SDL_MintAudio_audiobuf[0] + spec->size; + SDL_MintAudio_numbuf = 0; + SDL_memset(SDL_MintAudio_audiobuf[0], spec->silence, spec->size * 2); + SDL_MintAudio_audiosize = spec->size; + SDL_MintAudio_mutex = 0; - DEBUG_PRINT((DEBUG_NAME "buffer 0 at 0x%08x\n", SDL_MintAudio_audiobuf[0])); - DEBUG_PRINT((DEBUG_NAME "buffer 1 at 0x%08x\n", SDL_MintAudio_audiobuf[1])); + DEBUG_PRINT((DEBUG_NAME "buffer 0 at 0x%08x\n", + SDL_MintAudio_audiobuf[0])); + DEBUG_PRINT((DEBUG_NAME "buffer 1 at 0x%08x\n", + SDL_MintAudio_audiobuf[1])); - /* Setup audio hardware */ - Mint_InitAudio(this, spec); + /* Setup audio hardware */ + Mint_InitAudio(this, spec); - return(1); /* We don't use threaded audio */ + return (1); /* We don't use threaded audio */ } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/audio/mint/SDL_mintaudio_dma8.h b/src/audio/mint/SDL_mintaudio_dma8.h index 698fed4e5..2bc9a86c9 100644 --- a/src/audio/mint/SDL_mintaudio_dma8.h +++ b/src/audio/mint/SDL_mintaudio_dma8.h @@ -31,55 +31,57 @@ #define _SDL_mintaudio_dma8_h #define DMAAUDIO_IO_BASE (0xffff8900) -struct DMAAUDIO_IO_S { - unsigned char int_ctrl; - unsigned char control; - - unsigned char dummy1; - unsigned char start_high; - unsigned char dummy2; - unsigned char start_mid; - unsigned char dummy3; - unsigned char start_low; - - unsigned char dummy4; - unsigned char cur_high; - unsigned char dummy5; - unsigned char cur_mid; - unsigned char dummy6; - unsigned char cur_low; - - unsigned char dummy7; - unsigned char end_high; - unsigned char dummy8; - unsigned char end_mid; - unsigned char dummy9; - unsigned char end_low; - - unsigned char dummy10[12]; - - unsigned char track_ctrl; /* CODEC only */ - unsigned char sound_ctrl; - unsigned short sound_data; - unsigned short sound_mask; - - unsigned char dummy11[10]; - - unsigned short dev_ctrl; - unsigned short dest_ctrl; - unsigned short sync_div; - unsigned char track_rec; - unsigned char adderin_input; - unsigned char channel_input; - unsigned char channel_amplification; - unsigned char channel_reduction; - - unsigned char dummy12[6]; - - unsigned char data_direction; - unsigned char dummy13; - unsigned char dev_data; +struct DMAAUDIO_IO_S +{ + unsigned char int_ctrl; + unsigned char control; + + unsigned char dummy1; + unsigned char start_high; + unsigned char dummy2; + unsigned char start_mid; + unsigned char dummy3; + unsigned char start_low; + + unsigned char dummy4; + unsigned char cur_high; + unsigned char dummy5; + unsigned char cur_mid; + unsigned char dummy6; + unsigned char cur_low; + + unsigned char dummy7; + unsigned char end_high; + unsigned char dummy8; + unsigned char end_mid; + unsigned char dummy9; + unsigned char end_low; + + unsigned char dummy10[12]; + + unsigned char track_ctrl; /* CODEC only */ + unsigned char sound_ctrl; + unsigned short sound_data; + unsigned short sound_mask; + + unsigned char dummy11[10]; + + unsigned short dev_ctrl; + unsigned short dest_ctrl; + unsigned short sync_div; + unsigned char track_rec; + unsigned char adderin_input; + unsigned char channel_input; + unsigned char channel_amplification; + unsigned char channel_reduction; + + unsigned char dummy12[6]; + + unsigned char data_direction; + unsigned char dummy13; + unsigned char dev_data; }; #define DMAAUDIO_IO ((*(volatile struct DMAAUDIO_IO_S *)DMAAUDIO_IO_BASE)) #endif /* _SDL_mintaudio_dma8_h */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/audio/mint/SDL_mintaudio_gsxb.c b/src/audio/mint/SDL_mintaudio_gsxb.c index de35debf5..4cad66b8f 100644 --- a/src/audio/mint/SDL_mintaudio_gsxb.c +++ b/src/audio/mint/SDL_mintaudio_gsxb.c @@ -64,13 +64,13 @@ static unsigned long cookie_snd, cookie_gsxb; /*--- Audio driver functions ---*/ static void Mint_CloseAudio(_THIS); -static int Mint_OpenAudio(_THIS, SDL_AudioSpec *spec); +static int Mint_OpenAudio(_THIS, SDL_AudioSpec * spec); static void Mint_LockAudio(_THIS); static void Mint_UnlockAudio(_THIS); /* To check/init hardware audio */ -static int Mint_CheckAudio(_THIS, SDL_AudioSpec *spec); -static void Mint_InitAudio(_THIS, SDL_AudioSpec *spec); +static int Mint_CheckAudio(_THIS, SDL_AudioSpec * spec); +static void Mint_InitAudio(_THIS, SDL_AudioSpec * spec); /* GSXB callbacks */ static void Mint_GsxbInterrupt(void); @@ -78,337 +78,353 @@ static void Mint_GsxbNullInterrupt(void); /*--- Audio driver bootstrap functions ---*/ -static int Audio_Available(void) +static int +Audio_Available(void) { - const char *envr = SDL_getenv("SDL_AUDIODRIVER"); + const char *envr = SDL_getenv("SDL_AUDIODRIVER"); - /* Check if user asked a different audio driver */ - if ((envr) && (SDL_strcmp(envr, MINT_AUDIO_DRIVER_NAME)!=0)) { - DEBUG_PRINT((DEBUG_NAME "user asked a different audio driver\n")); - return(0); - } + /* Check if user asked a different audio driver */ + if ((envr) && (SDL_strcmp(envr, MINT_AUDIO_DRIVER_NAME) != 0)) { + DEBUG_PRINT((DEBUG_NAME "user asked a different audio driver\n")); + return (0); + } - /* Cookie _SND present ? if not, assume ST machine */ - if (Getcookie(C__SND, &cookie_snd) == C_NOTFOUND) { - cookie_snd = SND_PSG; - } + /* Cookie _SND present ? if not, assume ST machine */ + if (Getcookie(C__SND, &cookie_snd) == C_NOTFOUND) { + cookie_snd = SND_PSG; + } - /* Check if we have 16 bits audio */ - if ((cookie_snd & SND_16BIT)==0) { - DEBUG_PRINT((DEBUG_NAME "no 16 bits sound\n")); - return(0); - } + /* Check if we have 16 bits audio */ + if ((cookie_snd & SND_16BIT) == 0) { + DEBUG_PRINT((DEBUG_NAME "no 16 bits sound\n")); + return (0); + } - /* Cookie GSXB present ? */ - cookie_gsxb = (Getcookie(C_GSXB, &cookie_gsxb) == C_FOUND); + /* Cookie GSXB present ? */ + cookie_gsxb = (Getcookie(C_GSXB, &cookie_gsxb) == C_FOUND); - /* Is it GSXB ? */ - if (((cookie_snd & SND_GSXB)==0) || (cookie_gsxb==0)) { - DEBUG_PRINT((DEBUG_NAME "no GSXB audio\n")); - return(0); - } + /* Is it GSXB ? */ + if (((cookie_snd & SND_GSXB) == 0) || (cookie_gsxb == 0)) { + DEBUG_PRINT((DEBUG_NAME "no GSXB audio\n")); + return (0); + } - /* Check if audio is lockable */ - if (Locksnd()!=1) { - DEBUG_PRINT((DEBUG_NAME "audio locked by other application\n")); - return(0); - } + /* Check if audio is lockable */ + if (Locksnd() != 1) { + DEBUG_PRINT((DEBUG_NAME "audio locked by other application\n")); + return (0); + } - Unlocksnd(); + Unlocksnd(); - DEBUG_PRINT((DEBUG_NAME "GSXB audio available!\n")); - return(1); + DEBUG_PRINT((DEBUG_NAME "GSXB audio available!\n")); + return (1); } -static void Audio_DeleteDevice(SDL_AudioDevice *device) +static void +Audio_DeleteDevice(SDL_AudioDevice * device) { SDL_free(device->hidden); SDL_free(device); } -static SDL_AudioDevice *Audio_CreateDevice(int devindex) +static SDL_AudioDevice * +Audio_CreateDevice(int devindex) { - SDL_AudioDevice *this; + SDL_AudioDevice *this; - /* Initialize all variables that we clean on shutdown */ - this = (SDL_AudioDevice *)SDL_malloc(sizeof(SDL_AudioDevice)); - if ( this ) { + /* Initialize all variables that we clean on shutdown */ + this = (SDL_AudioDevice *) SDL_malloc(sizeof(SDL_AudioDevice)); + if (this) { SDL_memset(this, 0, (sizeof *this)); this->hidden = (struct SDL_PrivateAudioData *) - SDL_malloc((sizeof *this->hidden)); + SDL_malloc((sizeof *this->hidden)); } - if ( (this == NULL) || (this->hidden == NULL) ) { + if ((this == NULL) || (this->hidden == NULL)) { SDL_OutOfMemory(); - if ( this ) { + if (this) { SDL_free(this); } - return(0); + return (0); } SDL_memset(this->hidden, 0, (sizeof *this->hidden)); /* Set the function pointers */ - this->OpenAudio = Mint_OpenAudio; - this->CloseAudio = Mint_CloseAudio; - this->LockAudio = Mint_LockAudio; + this->OpenAudio = Mint_OpenAudio; + this->CloseAudio = Mint_CloseAudio; + this->LockAudio = Mint_LockAudio; this->UnlockAudio = Mint_UnlockAudio; - this->free = Audio_DeleteDevice; + this->free = Audio_DeleteDevice; return this; } AudioBootStrap MINTAUDIO_GSXB_bootstrap = { - MINT_AUDIO_DRIVER_NAME, "MiNT GSXB audio driver", - Audio_Available, Audio_CreateDevice + MINT_AUDIO_DRIVER_NAME, "MiNT GSXB audio driver", + Audio_Available, Audio_CreateDevice }; -static void Mint_LockAudio(_THIS) +static void +Mint_LockAudio(_THIS) { - /* Stop replay */ - Buffoper(0); + /* Stop replay */ + Buffoper(0); } -static void Mint_UnlockAudio(_THIS) +static void +Mint_UnlockAudio(_THIS) { - /* Restart replay */ - Buffoper(SB_PLA_ENA|SB_PLA_RPT); + /* Restart replay */ + Buffoper(SB_PLA_ENA | SB_PLA_RPT); } -static void Mint_CloseAudio(_THIS) +static void +Mint_CloseAudio(_THIS) { - /* Stop replay */ - Buffoper(0); + /* Stop replay */ + Buffoper(0); - /* Uninstall interrupt */ - if (NSetinterrupt(2, SI_NONE, Mint_GsxbNullInterrupt)<0) { - DEBUG_PRINT((DEBUG_NAME "NSetinterrupt() failed in close\n")); - } + /* Uninstall interrupt */ + if (NSetinterrupt(2, SI_NONE, Mint_GsxbNullInterrupt) < 0) { + DEBUG_PRINT((DEBUG_NAME "NSetinterrupt() failed in close\n")); + } - /* Wait if currently playing sound */ - while (SDL_MintAudio_mutex != 0) { - } + /* Wait if currently playing sound */ + while (SDL_MintAudio_mutex != 0) { + } - /* Clear buffers */ - if (SDL_MintAudio_audiobuf[0]) { - Mfree(SDL_MintAudio_audiobuf[0]); - SDL_MintAudio_audiobuf[0] = SDL_MintAudio_audiobuf[1] = NULL; - } + /* Clear buffers */ + if (SDL_MintAudio_audiobuf[0]) { + Mfree(SDL_MintAudio_audiobuf[0]); + SDL_MintAudio_audiobuf[0] = SDL_MintAudio_audiobuf[1] = NULL; + } - /* Unlock sound system */ - Unlocksnd(); + /* Unlock sound system */ + Unlocksnd(); } -static int Mint_CheckAudio(_THIS, SDL_AudioSpec *spec) +static int +Mint_CheckAudio(_THIS, SDL_AudioSpec * spec) { - long snd_format; - int i, resolution, format_signed, format_bigendian; - - resolution = spec->format & 0x00ff; - format_signed = ((spec->format & 0x8000)!=0); - format_bigendian = ((spec->format & 0x1000)!=0); - - DEBUG_PRINT((DEBUG_NAME "asked: %d bits, ",spec->format & 0x00ff)); - DEBUG_PRINT(("signed=%d, ", ((spec->format & 0x8000)!=0))); - DEBUG_PRINT(("big endian=%d, ", ((spec->format & 0x1000)!=0))); - DEBUG_PRINT(("channels=%d, ", spec->channels)); - DEBUG_PRINT(("freq=%d\n", spec->freq)); - - /* Check formats available */ - snd_format = Sndstatus(SND_QUERYFORMATS); - switch (resolution) { - case 8: - if ((snd_format & SND_FORMAT8)==0) { - SDL_SetError("Mint_CheckAudio: 8 bits samples not supported"); - return -1; - } - snd_format = Sndstatus(SND_QUERY8BIT); - break; - case 16: - if ((snd_format & SND_FORMAT16)==0) { - SDL_SetError("Mint_CheckAudio: 16 bits samples not supported"); - return -1; - } - snd_format = Sndstatus(SND_QUERY16BIT); - break; - default: - SDL_SetError("Mint_CheckAudio: Unsupported sample resolution"); - return -1; - break; - } + long snd_format; + int i, resolution, format_signed, format_bigendian; + + resolution = spec->format & 0x00ff; + format_signed = ((spec->format & 0x8000) != 0); + format_bigendian = ((spec->format & 0x1000) != 0); + + DEBUG_PRINT((DEBUG_NAME "asked: %d bits, ", spec->format & 0x00ff)); + DEBUG_PRINT(("signed=%d, ", ((spec->format & 0x8000) != 0))); + DEBUG_PRINT(("big endian=%d, ", ((spec->format & 0x1000) != 0))); + DEBUG_PRINT(("channels=%d, ", spec->channels)); + DEBUG_PRINT(("freq=%d\n", spec->freq)); + + /* Check formats available */ + snd_format = Sndstatus(SND_QUERYFORMATS); + switch (resolution) { + case 8: + if ((snd_format & SND_FORMAT8) == 0) { + SDL_SetError("Mint_CheckAudio: 8 bits samples not supported"); + return -1; + } + snd_format = Sndstatus(SND_QUERY8BIT); + break; + case 16: + if ((snd_format & SND_FORMAT16) == 0) { + SDL_SetError("Mint_CheckAudio: 16 bits samples not supported"); + return -1; + } + snd_format = Sndstatus(SND_QUERY16BIT); + break; + default: + SDL_SetError("Mint_CheckAudio: Unsupported sample resolution"); + return -1; + break; + } - /* Check signed/unsigned format */ - if (format_signed) { - if (snd_format & SND_FORMATSIGNED) { - /* Ok */ - } else if (snd_format & SND_FORMATUNSIGNED) { - /* Give unsigned format */ - spec->format = spec->format & (~0x8000); - } - } else { - if (snd_format & SND_FORMATUNSIGNED) { - /* Ok */ - } else if (snd_format & SND_FORMATSIGNED) { - /* Give signed format */ - spec->format |= 0x8000; - } - } + /* Check signed/unsigned format */ + if (format_signed) { + if (snd_format & SND_FORMATSIGNED) { + /* Ok */ + } else if (snd_format & SND_FORMATUNSIGNED) { + /* Give unsigned format */ + spec->format = spec->format & (~0x8000); + } + } else { + if (snd_format & SND_FORMATUNSIGNED) { + /* Ok */ + } else if (snd_format & SND_FORMATSIGNED) { + /* Give signed format */ + spec->format |= 0x8000; + } + } - if (format_bigendian) { - if (snd_format & SND_FORMATBIGENDIAN) { - /* Ok */ - } else if (snd_format & SND_FORMATLITTLEENDIAN) { - /* Give little endian format */ - spec->format = spec->format & (~0x1000); - } - } else { - if (snd_format & SND_FORMATLITTLEENDIAN) { - /* Ok */ - } else if (snd_format & SND_FORMATBIGENDIAN) { - /* Give big endian format */ - spec->format |= 0x1000; - } - } - - /* Calculate and select the closest frequency */ - MINTAUDIO_freqcount=0; - for (i=1;i<4;i++) { - SDL_MintAudio_AddFrequency(this, - MASTERCLOCK_44K/(MASTERPREDIV_MILAN*(1<format = spec->format & (~0x1000); + } + } else { + if (snd_format & SND_FORMATLITTLEENDIAN) { + /* Ok */ + } else if (snd_format & SND_FORMATBIGENDIAN) { + /* Give big endian format */ + spec->format |= 0x1000; + } + } + + /* Calculate and select the closest frequency */ + MINTAUDIO_freqcount = 0; + for (i = 1; i < 4; i++) { + SDL_MintAudio_AddFrequency(this, + MASTERCLOCK_44K / (MASTERPREDIV_MILAN * + (1 << i)), + MASTERCLOCK_44K, (1 << i) - 1, -1); + } #if 1 - for (i=0; ifreq); - spec->freq=MINTAUDIO_frequencies[MINTAUDIO_numfreq].frequency; + MINTAUDIO_numfreq = SDL_MintAudio_SearchFrequency(this, spec->freq); + spec->freq = MINTAUDIO_frequencies[MINTAUDIO_numfreq].frequency; - DEBUG_PRINT((DEBUG_NAME "obtained: %d bits, ",spec->format & 0x00ff)); - DEBUG_PRINT(("signed=%d, ", ((spec->format & 0x8000)!=0))); - DEBUG_PRINT(("big endian=%d, ", ((spec->format & 0x1000)!=0))); - DEBUG_PRINT(("channels=%d, ", spec->channels)); - DEBUG_PRINT(("freq=%d\n", spec->freq)); + DEBUG_PRINT((DEBUG_NAME "obtained: %d bits, ", spec->format & 0x00ff)); + DEBUG_PRINT(("signed=%d, ", ((spec->format & 0x8000) != 0))); + DEBUG_PRINT(("big endian=%d, ", ((spec->format & 0x1000) != 0))); + DEBUG_PRINT(("channels=%d, ", spec->channels)); + DEBUG_PRINT(("freq=%d\n", spec->freq)); - return 0; + return 0; } -static void Mint_InitAudio(_THIS, SDL_AudioSpec *spec) +static void +Mint_InitAudio(_THIS, SDL_AudioSpec * spec) { - int channels_mode, prediv; - void *buffer; - - /* Stop currently playing sound */ - Buffoper(0); - - /* Set replay tracks */ - Settracks(0,0); - Setmontracks(0); - - /* Select replay format */ - switch (spec->format & 0xff) { - case 8: - if (spec->channels==2) { - channels_mode=STEREO8; - } else { - channels_mode=MONO8; - } - break; - case 16: - if (spec->channels==2) { - channels_mode=STEREO16; - } else { - channels_mode=MONO16; - } - break; - default: - channels_mode=STEREO16; - break; - } - if (Setmode(channels_mode)<0) { - DEBUG_PRINT((DEBUG_NAME "Setmode() failed\n")); - } + int channels_mode, prediv; + void *buffer; + + /* Stop currently playing sound */ + Buffoper(0); + + /* Set replay tracks */ + Settracks(0, 0); + Setmontracks(0); + + /* Select replay format */ + switch (spec->format & 0xff) { + case 8: + if (spec->channels == 2) { + channels_mode = STEREO8; + } else { + channels_mode = MONO8; + } + break; + case 16: + if (spec->channels == 2) { + channels_mode = STEREO16; + } else { + channels_mode = MONO16; + } + break; + default: + channels_mode = STEREO16; + break; + } + if (Setmode(channels_mode) < 0) { + DEBUG_PRINT((DEBUG_NAME "Setmode() failed\n")); + } - prediv = MINTAUDIO_frequencies[MINTAUDIO_numfreq].predivisor; - Devconnect(DMAPLAY, DAC, CLKEXT, prediv, 1); + prediv = MINTAUDIO_frequencies[MINTAUDIO_numfreq].predivisor; + Devconnect(DMAPLAY, DAC, CLKEXT, prediv, 1); - /* Set buffer */ - buffer = SDL_MintAudio_audiobuf[SDL_MintAudio_numbuf]; - if (Setbuffer(0, buffer, buffer + spec->size)<0) { - DEBUG_PRINT((DEBUG_NAME "Setbuffer() failed\n")); - } - - /* Install interrupt */ - if (NSetinterrupt(2, SI_PLAY, Mint_GsxbInterrupt)<0) { - DEBUG_PRINT((DEBUG_NAME "NSetinterrupt() failed\n")); - } + /* Set buffer */ + buffer = SDL_MintAudio_audiobuf[SDL_MintAudio_numbuf]; + if (Setbuffer(0, buffer, buffer + spec->size) < 0) { + DEBUG_PRINT((DEBUG_NAME "Setbuffer() failed\n")); + } - /* Go */ - Buffoper(SB_PLA_ENA|SB_PLA_RPT); - DEBUG_PRINT((DEBUG_NAME "hardware initialized\n")); + /* Install interrupt */ + if (NSetinterrupt(2, SI_PLAY, Mint_GsxbInterrupt) < 0) { + DEBUG_PRINT((DEBUG_NAME "NSetinterrupt() failed\n")); + } + + /* Go */ + Buffoper(SB_PLA_ENA | SB_PLA_RPT); + DEBUG_PRINT((DEBUG_NAME "hardware initialized\n")); } -static int Mint_OpenAudio(_THIS, SDL_AudioSpec *spec) +static int +Mint_OpenAudio(_THIS, SDL_AudioSpec * spec) { - /* Lock sound system */ - if (Locksnd()!=1) { - SDL_SetError("Mint_OpenAudio: Audio system already in use"); - return(-1); - } + /* Lock sound system */ + if (Locksnd() != 1) { + SDL_SetError("Mint_OpenAudio: Audio system already in use"); + return (-1); + } - SDL_MintAudio_device = this; + SDL_MintAudio_device = this; - /* Check audio capabilities */ - if (Mint_CheckAudio(this, spec)==-1) { - return -1; - } + /* Check audio capabilities */ + if (Mint_CheckAudio(this, spec) == -1) { + return -1; + } - SDL_CalculateAudioSpec(spec); + SDL_CalculateAudioSpec(spec); - /* Allocate memory for audio buffers in DMA-able RAM */ - DEBUG_PRINT((DEBUG_NAME "buffer size=%d\n", spec->size)); + /* Allocate memory for audio buffers in DMA-able RAM */ + DEBUG_PRINT((DEBUG_NAME "buffer size=%d\n", spec->size)); - SDL_MintAudio_audiobuf[0] = Atari_SysMalloc(spec->size *2, MX_STRAM); - if (SDL_MintAudio_audiobuf[0]==NULL) { - SDL_SetError("MINT_OpenAudio: Not enough memory for audio buffer"); - return (-1); - } - SDL_MintAudio_audiobuf[1] = SDL_MintAudio_audiobuf[0] + spec->size ; - SDL_MintAudio_numbuf=0; - SDL_memset(SDL_MintAudio_audiobuf[0], spec->silence, spec->size *2); - SDL_MintAudio_audiosize = spec->size; - SDL_MintAudio_mutex = 0; + SDL_MintAudio_audiobuf[0] = Atari_SysMalloc(spec->size * 2, MX_STRAM); + if (SDL_MintAudio_audiobuf[0] == NULL) { + SDL_SetError("MINT_OpenAudio: Not enough memory for audio buffer"); + return (-1); + } + SDL_MintAudio_audiobuf[1] = SDL_MintAudio_audiobuf[0] + spec->size; + SDL_MintAudio_numbuf = 0; + SDL_memset(SDL_MintAudio_audiobuf[0], spec->silence, spec->size * 2); + SDL_MintAudio_audiosize = spec->size; + SDL_MintAudio_mutex = 0; - DEBUG_PRINT((DEBUG_NAME "buffer 0 at 0x%08x\n", SDL_MintAudio_audiobuf[0])); - DEBUG_PRINT((DEBUG_NAME "buffer 1 at 0x%08x\n", SDL_MintAudio_audiobuf[1])); + DEBUG_PRINT((DEBUG_NAME "buffer 0 at 0x%08x\n", + SDL_MintAudio_audiobuf[0])); + DEBUG_PRINT((DEBUG_NAME "buffer 1 at 0x%08x\n", + SDL_MintAudio_audiobuf[1])); - /* Setup audio hardware */ - Mint_InitAudio(this, spec); + /* Setup audio hardware */ + Mint_InitAudio(this, spec); - return(1); /* We don't use threaded audio */ + return (1); /* We don't use threaded audio */ } -static void Mint_GsxbInterrupt(void) +static void +Mint_GsxbInterrupt(void) { - Uint8 *newbuf; + Uint8 *newbuf; - if (SDL_MintAudio_mutex) - return; + if (SDL_MintAudio_mutex) + return; - SDL_MintAudio_mutex=1; + SDL_MintAudio_mutex = 1; - SDL_MintAudio_numbuf ^= 1; - SDL_MintAudio_Callback(); - newbuf = SDL_MintAudio_audiobuf[SDL_MintAudio_numbuf]; - Setbuffer(0, newbuf, newbuf + SDL_MintAudio_audiosize); + SDL_MintAudio_numbuf ^= 1; + SDL_MintAudio_Callback(); + newbuf = SDL_MintAudio_audiobuf[SDL_MintAudio_numbuf]; + Setbuffer(0, newbuf, newbuf + SDL_MintAudio_audiosize); - SDL_MintAudio_mutex=0; + SDL_MintAudio_mutex = 0; } -static void Mint_GsxbNullInterrupt(void) +static void +Mint_GsxbNullInterrupt(void) { } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/audio/mint/SDL_mintaudio_gsxb.h b/src/audio/mint/SDL_mintaudio_gsxb.h index 595e313db..4e84d5ed0 100644 --- a/src/audio/mint/SDL_mintaudio_gsxb.h +++ b/src/audio/mint/SDL_mintaudio_gsxb.h @@ -30,7 +30,7 @@ #ifndef _SDL_mintaudio_gsxb_h #define _SDL_mintaudio_gsxb_h -#include /* for trap_14_xxx macros */ +#include /* for trap_14_xxx macros */ /* GSXB Cookie */ @@ -42,12 +42,12 @@ /* NSoundcmd modes */ -#define SETRATE 7 /* Set sample rate */ -#define SET8BITFORMAT 8 /* 8 bits format */ -#define SET16BITFORMAT 9 /* 16 bits format */ -#define SET24BITFORMAT 10 /* 24 bits format */ -#define SET32BITFORMAT 11 /* 32 bits format */ -#define LTATTEN_MASTER 12 /* Attenuation */ +#define SETRATE 7 /* Set sample rate */ +#define SET8BITFORMAT 8 /* 8 bits format */ +#define SET16BITFORMAT 9 /* 16 bits format */ +#define SET24BITFORMAT 10 /* 24 bits format */ +#define SET32BITFORMAT 11 /* 32 bits format */ +#define LTATTEN_MASTER 12 /* Attenuation */ #define RTATTEN_MASTER 13 #define LTATTEN_MICIN 14 #define RTATTEN_MICIN 15 @@ -106,3 +106,4 @@ (long)(inth_addr)) #endif /* _SDL_mintaudio_gsxb_h */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/audio/mint/SDL_mintaudio_mcsn.c b/src/audio/mint/SDL_mintaudio_mcsn.c index 9741a3bea..64e2cf7d0 100644 --- a/src/audio/mint/SDL_mintaudio_mcsn.c +++ b/src/audio/mint/SDL_mintaudio_mcsn.c @@ -67,332 +67,352 @@ static cookie_mcsn_t *cookie_mcsn; /*--- Audio driver functions ---*/ static void Mint_CloseAudio(_THIS); -static int Mint_OpenAudio(_THIS, SDL_AudioSpec *spec); +static int Mint_OpenAudio(_THIS, SDL_AudioSpec * spec); static void Mint_LockAudio(_THIS); static void Mint_UnlockAudio(_THIS); /* To check/init hardware audio */ -static int Mint_CheckAudio(_THIS, SDL_AudioSpec *spec); -static void Mint_InitAudio(_THIS, SDL_AudioSpec *spec); +static int Mint_CheckAudio(_THIS, SDL_AudioSpec * spec); +static void Mint_InitAudio(_THIS, SDL_AudioSpec * spec); /*--- Audio driver bootstrap functions ---*/ -static int Audio_Available(void) +static int +Audio_Available(void) { - unsigned long dummy; - const char *envr = SDL_getenv("SDL_AUDIODRIVER"); + unsigned long dummy; + const char *envr = SDL_getenv("SDL_AUDIODRIVER"); - SDL_MintAudio_mint_present = (Getcookie(C_MiNT, &dummy) == C_FOUND); + SDL_MintAudio_mint_present = (Getcookie(C_MiNT, &dummy) == C_FOUND); - /* We can't use XBIOS in interrupt with Magic, don't know about thread */ - if (Getcookie(C_MagX, &dummy) == C_FOUND) { - return(0); - } + /* We can't use XBIOS in interrupt with Magic, don't know about thread */ + if (Getcookie(C_MagX, &dummy) == C_FOUND) { + return (0); + } - /* Check if user asked a different audio driver */ - if ((envr) && (SDL_strcmp(envr, MINT_AUDIO_DRIVER_NAME)!=0)) { - DEBUG_PRINT((DEBUG_NAME "user asked a different audio driver\n")); - return(0); - } + /* Check if user asked a different audio driver */ + if ((envr) && (SDL_strcmp(envr, MINT_AUDIO_DRIVER_NAME) != 0)) { + DEBUG_PRINT((DEBUG_NAME "user asked a different audio driver\n")); + return (0); + } - /* Cookie _MCH present ? if not, assume ST machine */ - if (Getcookie(C__MCH, &cookie_mch) == C_NOTFOUND) { - cookie_mch = MCH_ST; - } + /* Cookie _MCH present ? if not, assume ST machine */ + if (Getcookie(C__MCH, &cookie_mch) == C_NOTFOUND) { + cookie_mch = MCH_ST; + } - /* Cookie _SND present ? if not, assume ST machine */ - if (Getcookie(C__SND, &cookie_snd) == C_NOTFOUND) { - cookie_snd = SND_PSG; - } + /* Cookie _SND present ? if not, assume ST machine */ + if (Getcookie(C__SND, &cookie_snd) == C_NOTFOUND) { + cookie_snd = SND_PSG; + } - /* Check if we have 16 bits audio */ - if ((cookie_snd & SND_16BIT)==0) { - DEBUG_PRINT((DEBUG_NAME "no 16 bits sound\n")); - return(0); - } + /* Check if we have 16 bits audio */ + if ((cookie_snd & SND_16BIT) == 0) { + DEBUG_PRINT((DEBUG_NAME "no 16 bits sound\n")); + return (0); + } - /* Cookie MCSN present ? */ - if (Getcookie(C_McSn, (long *) &cookie_mcsn) != C_FOUND) { - DEBUG_PRINT((DEBUG_NAME "no MCSN audio\n")); - return(0); - } + /* Cookie MCSN present ? */ + if (Getcookie(C_McSn, (long *) &cookie_mcsn) != C_FOUND) { + DEBUG_PRINT((DEBUG_NAME "no MCSN audio\n")); + return (0); + } - /* Check if interrupt at end of replay */ - if (cookie_mcsn->pint == 0) { - DEBUG_PRINT((DEBUG_NAME "no interrupt at end of replay\n")); - return(0); - } + /* Check if interrupt at end of replay */ + if (cookie_mcsn->pint == 0) { + DEBUG_PRINT((DEBUG_NAME "no interrupt at end of replay\n")); + return (0); + } - /* Check if audio is lockable */ - if (Locksnd()!=1) { - DEBUG_PRINT((DEBUG_NAME "audio locked by other application\n")); - return(0); - } + /* Check if audio is lockable */ + if (Locksnd() != 1) { + DEBUG_PRINT((DEBUG_NAME "audio locked by other application\n")); + return (0); + } - Unlocksnd(); + Unlocksnd(); - DEBUG_PRINT((DEBUG_NAME "MCSN audio available!\n")); - return(1); + DEBUG_PRINT((DEBUG_NAME "MCSN audio available!\n")); + return (1); } -static void Audio_DeleteDevice(SDL_AudioDevice *device) +static void +Audio_DeleteDevice(SDL_AudioDevice * device) { SDL_free(device->hidden); SDL_free(device); } -static SDL_AudioDevice *Audio_CreateDevice(int devindex) +static SDL_AudioDevice * +Audio_CreateDevice(int devindex) { - SDL_AudioDevice *this; + SDL_AudioDevice *this; - /* Initialize all variables that we clean on shutdown */ - this = (SDL_AudioDevice *)SDL_malloc(sizeof(SDL_AudioDevice)); - if ( this ) { + /* Initialize all variables that we clean on shutdown */ + this = (SDL_AudioDevice *) SDL_malloc(sizeof(SDL_AudioDevice)); + if (this) { SDL_memset(this, 0, (sizeof *this)); this->hidden = (struct SDL_PrivateAudioData *) - SDL_malloc((sizeof *this->hidden)); + SDL_malloc((sizeof *this->hidden)); } - if ( (this == NULL) || (this->hidden == NULL) ) { + if ((this == NULL) || (this->hidden == NULL)) { SDL_OutOfMemory(); - if ( this ) { + if (this) { SDL_free(this); } - return(0); + return (0); } SDL_memset(this->hidden, 0, (sizeof *this->hidden)); /* Set the function pointers */ - this->OpenAudio = Mint_OpenAudio; - this->CloseAudio = Mint_CloseAudio; - this->LockAudio = Mint_LockAudio; + this->OpenAudio = Mint_OpenAudio; + this->CloseAudio = Mint_CloseAudio; + this->LockAudio = Mint_LockAudio; this->UnlockAudio = Mint_UnlockAudio; - this->free = Audio_DeleteDevice; + this->free = Audio_DeleteDevice; return this; } AudioBootStrap MINTAUDIO_MCSN_bootstrap = { - MINT_AUDIO_DRIVER_NAME, "MiNT MCSN audio driver", - Audio_Available, Audio_CreateDevice + MINT_AUDIO_DRIVER_NAME, "MiNT MCSN audio driver", + Audio_Available, Audio_CreateDevice }; -static void Mint_LockAudio(_THIS) +static void +Mint_LockAudio(_THIS) { - /* Stop replay */ - Buffoper(0); + /* Stop replay */ + Buffoper(0); } -static void Mint_UnlockAudio(_THIS) +static void +Mint_UnlockAudio(_THIS) { - /* Restart replay */ - Buffoper(SB_PLA_ENA|SB_PLA_RPT); + /* Restart replay */ + Buffoper(SB_PLA_ENA | SB_PLA_RPT); } -static void Mint_CloseAudio(_THIS) +static void +Mint_CloseAudio(_THIS) { - /* Stop replay */ - SDL_MintAudio_WaitThread(); - Buffoper(0); + /* Stop replay */ + SDL_MintAudio_WaitThread(); + Buffoper(0); - if (!SDL_MintAudio_mint_present) { - /* Uninstall interrupt */ - Jdisint(MFP_DMASOUND); - } + if (!SDL_MintAudio_mint_present) { + /* Uninstall interrupt */ + Jdisint(MFP_DMASOUND); + } - /* Wait if currently playing sound */ - while (SDL_MintAudio_mutex != 0) { - } + /* Wait if currently playing sound */ + while (SDL_MintAudio_mutex != 0) { + } - /* Clear buffers */ - if (SDL_MintAudio_audiobuf[0]) { - Mfree(SDL_MintAudio_audiobuf[0]); - SDL_MintAudio_audiobuf[0] = SDL_MintAudio_audiobuf[1] = NULL; - } + /* Clear buffers */ + if (SDL_MintAudio_audiobuf[0]) { + Mfree(SDL_MintAudio_audiobuf[0]); + SDL_MintAudio_audiobuf[0] = SDL_MintAudio_audiobuf[1] = NULL; + } - /* Unlock sound system */ - Unlocksnd(); + /* Unlock sound system */ + Unlocksnd(); } -static int Mint_CheckAudio(_THIS, SDL_AudioSpec *spec) +static int +Mint_CheckAudio(_THIS, SDL_AudioSpec * spec) { - int i; - unsigned long masterclock, masterprediv; - - DEBUG_PRINT((DEBUG_NAME "asked: %d bits, ",spec->format & 0x00ff)); - DEBUG_PRINT(("signed=%d, ", ((spec->format & 0x8000)!=0))); - DEBUG_PRINT(("big endian=%d, ", ((spec->format & 0x1000)!=0))); - DEBUG_PRINT(("channels=%d, ", spec->channels)); - DEBUG_PRINT(("freq=%d\n", spec->freq)); - - /* Check formats available */ - MINTAUDIO_freqcount=0; - switch(cookie_mcsn->play) { - case MCSN_ST: - spec->channels=1; - spec->format=8; /* FIXME: is it signed or unsigned ? */ - SDL_MintAudio_AddFrequency(this, 12500, 0, 0, -1); - break; - case MCSN_TT: /* Also STE, Mega STE */ - spec->format=AUDIO_S8; - masterclock=MASTERCLOCK_STE; - masterprediv=MASTERPREDIV_STE; - if ((cookie_mch>>16)==MCH_TT) { - masterclock=MASTERCLOCK_TT; - masterprediv=MASTERPREDIV_TT; - } - for (i=0; i<4; i++) { - SDL_MintAudio_AddFrequency(this, masterclock/(masterprediv*(1<res1 != 0) { - for (i=1; i<4; i++) { - SDL_MintAudio_AddFrequency(this, (cookie_mcsn->res1)/(MASTERPREDIV_FALCON*(1<format |= 0x8000; /* Audio is always signed */ - if ((spec->format & 0x00ff)==16) { - spec->format |= 0x1000; /* Audio is always big endian */ - spec->channels=2; /* 16 bits always stereo */ - } - break; - } + int i; + unsigned long masterclock, masterprediv; + + DEBUG_PRINT((DEBUG_NAME "asked: %d bits, ", spec->format & 0x00ff)); + DEBUG_PRINT(("signed=%d, ", ((spec->format & 0x8000) != 0))); + DEBUG_PRINT(("big endian=%d, ", ((spec->format & 0x1000) != 0))); + DEBUG_PRINT(("channels=%d, ", spec->channels)); + DEBUG_PRINT(("freq=%d\n", spec->freq)); + + /* Check formats available */ + MINTAUDIO_freqcount = 0; + switch (cookie_mcsn->play) { + case MCSN_ST: + spec->channels = 1; + spec->format = 8; /* FIXME: is it signed or unsigned ? */ + SDL_MintAudio_AddFrequency(this, 12500, 0, 0, -1); + break; + case MCSN_TT: /* Also STE, Mega STE */ + spec->format = AUDIO_S8; + masterclock = MASTERCLOCK_STE; + masterprediv = MASTERPREDIV_STE; + if ((cookie_mch >> 16) == MCH_TT) { + masterclock = MASTERCLOCK_TT; + masterprediv = MASTERPREDIV_TT; + } + for (i = 0; i < 4; i++) { + SDL_MintAudio_AddFrequency(this, + masterclock / (masterprediv * + (1 << i)), + masterclock, 3 - i, -1); + } + break; + case MCSN_FALCON: /* Also Mac */ + for (i = 1; i < 12; i++) { + /* Remove unusable Falcon codec predivisors */ + if ((i == 6) || (i == 8) || (i == 10)) { + continue; + } + SDL_MintAudio_AddFrequency(this, + MASTERCLOCK_FALCON1 / + (MASTERPREDIV_FALCON * (i + 1)), + CLK25M, i + 1, -1); + } + if (cookie_mcsn->res1 != 0) { + for (i = 1; i < 4; i++) { + SDL_MintAudio_AddFrequency(this, + (cookie_mcsn->res1) / + (MASTERPREDIV_FALCON * + (1 << i)), CLKEXT, + (1 << i) - 1, -1); + } + } + spec->format |= 0x8000; /* Audio is always signed */ + if ((spec->format & 0x00ff) == 16) { + spec->format |= 0x1000; /* Audio is always big endian */ + spec->channels = 2; /* 16 bits always stereo */ + } + break; + } #if 1 - for (i=0; ifreq); - spec->freq=MINTAUDIO_frequencies[MINTAUDIO_numfreq].frequency; + MINTAUDIO_numfreq = SDL_MintAudio_SearchFrequency(this, spec->freq); + spec->freq = MINTAUDIO_frequencies[MINTAUDIO_numfreq].frequency; - DEBUG_PRINT((DEBUG_NAME "obtained: %d bits, ",spec->format & 0x00ff)); - DEBUG_PRINT(("signed=%d, ", ((spec->format & 0x8000)!=0))); - DEBUG_PRINT(("big endian=%d, ", ((spec->format & 0x1000)!=0))); - DEBUG_PRINT(("channels=%d, ", spec->channels)); - DEBUG_PRINT(("freq=%d\n", spec->freq)); + DEBUG_PRINT((DEBUG_NAME "obtained: %d bits, ", spec->format & 0x00ff)); + DEBUG_PRINT(("signed=%d, ", ((spec->format & 0x8000) != 0))); + DEBUG_PRINT(("big endian=%d, ", ((spec->format & 0x1000) != 0))); + DEBUG_PRINT(("channels=%d, ", spec->channels)); + DEBUG_PRINT(("freq=%d\n", spec->freq)); - return 0; + return 0; } -static void Mint_InitAudio(_THIS, SDL_AudioSpec *spec) +static void +Mint_InitAudio(_THIS, SDL_AudioSpec * spec) { - int channels_mode, prediv, dmaclock; - void *buffer; - - /* Stop currently playing sound */ - SDL_MintAudio_quit_thread = SDL_FALSE; - SDL_MintAudio_thread_finished = SDL_TRUE; - SDL_MintAudio_WaitThread(); - Buffoper(0); - - /* Set replay tracks */ - Settracks(0,0); - Setmontracks(0); - - /* Select replay format */ - channels_mode=STEREO16; - switch (spec->format & 0xff) { - case 8: - if (spec->channels==2) { - channels_mode=STEREO8; - } else { - channels_mode=MONO8; - } - break; - } - if (Setmode(channels_mode)<0) { - DEBUG_PRINT((DEBUG_NAME "Setmode() failed\n")); - } + int channels_mode, prediv, dmaclock; + void *buffer; + + /* Stop currently playing sound */ + SDL_MintAudio_quit_thread = SDL_FALSE; + SDL_MintAudio_thread_finished = SDL_TRUE; + SDL_MintAudio_WaitThread(); + Buffoper(0); + + /* Set replay tracks */ + Settracks(0, 0); + Setmontracks(0); + + /* Select replay format */ + channels_mode = STEREO16; + switch (spec->format & 0xff) { + case 8: + if (spec->channels == 2) { + channels_mode = STEREO8; + } else { + channels_mode = MONO8; + } + break; + } + if (Setmode(channels_mode) < 0) { + DEBUG_PRINT((DEBUG_NAME "Setmode() failed\n")); + } - dmaclock = MINTAUDIO_frequencies[MINTAUDIO_numfreq].masterclock; - prediv = MINTAUDIO_frequencies[MINTAUDIO_numfreq].predivisor; - switch(cookie_mcsn->play) { - case MCSN_TT: - Devconnect(DMAPLAY, DAC, CLK25M, CLKOLD, 1); - Soundcmd(SETPRESCALE, prediv); - DEBUG_PRINT((DEBUG_NAME "STE/TT prescaler selected\n")); - break; - case MCSN_FALCON: - Devconnect(DMAPLAY, DAC, dmaclock, prediv, 1); - DEBUG_PRINT((DEBUG_NAME "Falcon prescaler selected\n")); - break; - } + dmaclock = MINTAUDIO_frequencies[MINTAUDIO_numfreq].masterclock; + prediv = MINTAUDIO_frequencies[MINTAUDIO_numfreq].predivisor; + switch (cookie_mcsn->play) { + case MCSN_TT: + Devconnect(DMAPLAY, DAC, CLK25M, CLKOLD, 1); + Soundcmd(SETPRESCALE, prediv); + DEBUG_PRINT((DEBUG_NAME "STE/TT prescaler selected\n")); + break; + case MCSN_FALCON: + Devconnect(DMAPLAY, DAC, dmaclock, prediv, 1); + DEBUG_PRINT((DEBUG_NAME "Falcon prescaler selected\n")); + break; + } - /* Set buffer */ - buffer = SDL_MintAudio_audiobuf[SDL_MintAudio_numbuf]; - if (Setbuffer(0, buffer, buffer + spec->size)<0) { - DEBUG_PRINT((DEBUG_NAME "Setbuffer() failed\n")); - } - - if (SDL_MintAudio_mint_present) { - SDL_MintAudio_thread_pid = tfork(SDL_MintAudio_Thread, 0); - } else { - /* Install interrupt */ - Jdisint(MFP_DMASOUND); - Xbtimer(XB_TIMERA, 8, 1, SDL_MintAudio_XbiosInterrupt); - Jenabint(MFP_DMASOUND); - - if (Setinterrupt(SI_TIMERA, SI_PLAY)<0) { - DEBUG_PRINT((DEBUG_NAME "Setinterrupt() failed\n")); - } - } + /* Set buffer */ + buffer = SDL_MintAudio_audiobuf[SDL_MintAudio_numbuf]; + if (Setbuffer(0, buffer, buffer + spec->size) < 0) { + DEBUG_PRINT((DEBUG_NAME "Setbuffer() failed\n")); + } - /* Go */ - Buffoper(SB_PLA_ENA|SB_PLA_RPT); - DEBUG_PRINT((DEBUG_NAME "hardware initialized\n")); + if (SDL_MintAudio_mint_present) { + SDL_MintAudio_thread_pid = tfork(SDL_MintAudio_Thread, 0); + } else { + /* Install interrupt */ + Jdisint(MFP_DMASOUND); + Xbtimer(XB_TIMERA, 8, 1, SDL_MintAudio_XbiosInterrupt); + Jenabint(MFP_DMASOUND); + + if (Setinterrupt(SI_TIMERA, SI_PLAY) < 0) { + DEBUG_PRINT((DEBUG_NAME "Setinterrupt() failed\n")); + } + } + + /* Go */ + Buffoper(SB_PLA_ENA | SB_PLA_RPT); + DEBUG_PRINT((DEBUG_NAME "hardware initialized\n")); } -static int Mint_OpenAudio(_THIS, SDL_AudioSpec *spec) +static int +Mint_OpenAudio(_THIS, SDL_AudioSpec * spec) { - /* Lock sound system */ - if (Locksnd()!=1) { - SDL_SetError("Mint_OpenAudio: Audio system already in use"); - return(-1); - } + /* Lock sound system */ + if (Locksnd() != 1) { + SDL_SetError("Mint_OpenAudio: Audio system already in use"); + return (-1); + } - SDL_MintAudio_device = this; + SDL_MintAudio_device = this; - /* Check audio capabilities */ - if (Mint_CheckAudio(this, spec)==-1) { - return -1; - } + /* Check audio capabilities */ + if (Mint_CheckAudio(this, spec) == -1) { + return -1; + } - SDL_CalculateAudioSpec(spec); + SDL_CalculateAudioSpec(spec); - /* Allocate memory for audio buffers in DMA-able RAM */ - DEBUG_PRINT((DEBUG_NAME "buffer size=%d\n", spec->size)); + /* Allocate memory for audio buffers in DMA-able RAM */ + DEBUG_PRINT((DEBUG_NAME "buffer size=%d\n", spec->size)); - SDL_MintAudio_audiobuf[0] = Atari_SysMalloc(spec->size *2, MX_STRAM); - if (SDL_MintAudio_audiobuf[0]==NULL) { - SDL_SetError("MINT_OpenAudio: Not enough memory for audio buffer"); - return (-1); - } - SDL_MintAudio_audiobuf[1] = SDL_MintAudio_audiobuf[0] + spec->size ; - SDL_MintAudio_numbuf=0; - SDL_memset(SDL_MintAudio_audiobuf[0], spec->silence, spec->size *2); - SDL_MintAudio_audiosize = spec->size; - SDL_MintAudio_mutex = 0; + SDL_MintAudio_audiobuf[0] = Atari_SysMalloc(spec->size * 2, MX_STRAM); + if (SDL_MintAudio_audiobuf[0] == NULL) { + SDL_SetError("MINT_OpenAudio: Not enough memory for audio buffer"); + return (-1); + } + SDL_MintAudio_audiobuf[1] = SDL_MintAudio_audiobuf[0] + spec->size; + SDL_MintAudio_numbuf = 0; + SDL_memset(SDL_MintAudio_audiobuf[0], spec->silence, spec->size * 2); + SDL_MintAudio_audiosize = spec->size; + SDL_MintAudio_mutex = 0; - DEBUG_PRINT((DEBUG_NAME "buffer 0 at 0x%08x\n", SDL_MintAudio_audiobuf[0])); - DEBUG_PRINT((DEBUG_NAME "buffer 1 at 0x%08x\n", SDL_MintAudio_audiobuf[1])); + DEBUG_PRINT((DEBUG_NAME "buffer 0 at 0x%08x\n", + SDL_MintAudio_audiobuf[0])); + DEBUG_PRINT((DEBUG_NAME "buffer 1 at 0x%08x\n", + SDL_MintAudio_audiobuf[1])); - /* Setup audio hardware */ - Mint_InitAudio(this, spec); + /* Setup audio hardware */ + Mint_InitAudio(this, spec); - return(1); /* We don't use SDL threaded audio */ + return (1); /* We don't use SDL threaded audio */ } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/audio/mint/SDL_mintaudio_mcsn.h b/src/audio/mint/SDL_mintaudio_mcsn.h index f253ddd88..c7b5e4de6 100644 --- a/src/audio/mint/SDL_mintaudio_mcsn.h +++ b/src/audio/mint/SDL_mintaudio_mcsn.h @@ -30,30 +30,33 @@ #ifndef _SDL_mintaudio_mcsh_h #define _SDL_mintaudio_mcsh_h -typedef struct { - unsigned short version; /* Version */ - unsigned short size; /* Size of structure */ - - unsigned short play; /* Replay capability */ - unsigned short record; /* Record capability */ - unsigned short dsp; /* DSP56K present */ - unsigned short pint; /* Interrupt at end of replay */ - unsigned short rint; /* Interrupt at end of record */ - - unsigned long res1; /* Frequency of external clock */ - unsigned long res2; - unsigned long res3; - unsigned long res4; -} cookie_mcsn_t __attribute__((packed)); - -enum { - MCSN_ST=0, - MCSN_TT, - MCSN_STE=MCSN_TT, - MCSN_FALCON, - MCSN_MAC=MCSN_FALCON +typedef struct +{ + unsigned short version; /* Version */ + unsigned short size; /* Size of structure */ + + unsigned short play; /* Replay capability */ + unsigned short record; /* Record capability */ + unsigned short dsp; /* DSP56K present */ + unsigned short pint; /* Interrupt at end of replay */ + unsigned short rint; /* Interrupt at end of record */ + + unsigned long res1; /* Frequency of external clock */ + unsigned long res2; + unsigned long res3; + unsigned long res4; +} cookie_mcsn_t __attribute__ ((packed)); + +enum +{ + MCSN_ST = 0, + MCSN_TT, + MCSN_STE = MCSN_TT, + MCSN_FALCON, + MCSN_MAC = MCSN_FALCON }; -#define SETSMPFREQ 7 /* Set sample frequency */ +#define SETSMPFREQ 7 /* Set sample frequency */ #endif /* _SDL_mintaudio_mcsh_h */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/audio/mint/SDL_mintaudio_stfa.c b/src/audio/mint/SDL_mintaudio_stfa.c index 552a7b224..393cfb1e5 100644 --- a/src/audio/mint/SDL_mintaudio_stfa.c +++ b/src/audio/mint/SDL_mintaudio_stfa.c @@ -62,256 +62,270 @@ static unsigned long cookie_snd, cookie_mch; static cookie_stfa_t *cookie_stfa; -static const int freqs[16]={ - 4995, 6269, 7493, 8192, - 9830, 10971, 12538, 14985, - 16384, 19819, 21943, 24576, - 30720, 32336, 43885, 49152 +static const int freqs[16] = { + 4995, 6269, 7493, 8192, + 9830, 10971, 12538, 14985, + 16384, 19819, 21943, 24576, + 30720, 32336, 43885, 49152 }; /*--- Audio driver functions ---*/ static void Mint_CloseAudio(_THIS); -static int Mint_OpenAudio(_THIS, SDL_AudioSpec *spec); +static int Mint_OpenAudio(_THIS, SDL_AudioSpec * spec); static void Mint_LockAudio(_THIS); static void Mint_UnlockAudio(_THIS); /* To check/init hardware audio */ -static int Mint_CheckAudio(_THIS, SDL_AudioSpec *spec); -static void Mint_InitAudio(_THIS, SDL_AudioSpec *spec); +static int Mint_CheckAudio(_THIS, SDL_AudioSpec * spec); +static void Mint_InitAudio(_THIS, SDL_AudioSpec * spec); /*--- Audio driver bootstrap functions ---*/ -static int Audio_Available(void) +static int +Audio_Available(void) { - const char *envr = SDL_getenv("SDL_AUDIODRIVER"); + const char *envr = SDL_getenv("SDL_AUDIODRIVER"); - /* Check if user asked a different audio driver */ - if ((envr) && (SDL_strcmp(envr, MINT_AUDIO_DRIVER_NAME)!=0)) { - DEBUG_PRINT((DEBUG_NAME "user asked a different audio driver\n")); - return(0); - } + /* Check if user asked a different audio driver */ + if ((envr) && (SDL_strcmp(envr, MINT_AUDIO_DRIVER_NAME) != 0)) { + DEBUG_PRINT((DEBUG_NAME "user asked a different audio driver\n")); + return (0); + } - /* Cookie _MCH present ? if not, assume ST machine */ - if (Getcookie(C__MCH, &cookie_mch) == C_NOTFOUND) { - cookie_mch = MCH_ST; - } + /* Cookie _MCH present ? if not, assume ST machine */ + if (Getcookie(C__MCH, &cookie_mch) == C_NOTFOUND) { + cookie_mch = MCH_ST; + } - /* Cookie _SND present ? if not, assume ST machine */ - if (Getcookie(C__SND, &cookie_snd) == C_NOTFOUND) { - cookie_snd = SND_PSG; - } + /* Cookie _SND present ? if not, assume ST machine */ + if (Getcookie(C__SND, &cookie_snd) == C_NOTFOUND) { + cookie_snd = SND_PSG; + } - /* Cookie STFA present ? */ - if (Getcookie(C_STFA, (long *) &cookie_stfa) != C_FOUND) { - DEBUG_PRINT((DEBUG_NAME "no STFA audio\n")); - return(0); - } + /* Cookie STFA present ? */ + if (Getcookie(C_STFA, (long *) &cookie_stfa) != C_FOUND) { + DEBUG_PRINT((DEBUG_NAME "no STFA audio\n")); + return (0); + } - SDL_MintAudio_stfa = cookie_stfa; + SDL_MintAudio_stfa = cookie_stfa; - DEBUG_PRINT((DEBUG_NAME "STFA audio available!\n")); - return(1); + DEBUG_PRINT((DEBUG_NAME "STFA audio available!\n")); + return (1); } -static void Audio_DeleteDevice(SDL_AudioDevice *device) +static void +Audio_DeleteDevice(SDL_AudioDevice * device) { SDL_free(device->hidden); SDL_free(device); } -static SDL_AudioDevice *Audio_CreateDevice(int devindex) +static SDL_AudioDevice * +Audio_CreateDevice(int devindex) { - SDL_AudioDevice *this; + SDL_AudioDevice *this; - /* Initialize all variables that we clean on shutdown */ - this = (SDL_AudioDevice *)SDL_malloc(sizeof(SDL_AudioDevice)); - if ( this ) { + /* Initialize all variables that we clean on shutdown */ + this = (SDL_AudioDevice *) SDL_malloc(sizeof(SDL_AudioDevice)); + if (this) { SDL_memset(this, 0, (sizeof *this)); this->hidden = (struct SDL_PrivateAudioData *) - SDL_malloc((sizeof *this->hidden)); + SDL_malloc((sizeof *this->hidden)); } - if ( (this == NULL) || (this->hidden == NULL) ) { + if ((this == NULL) || (this->hidden == NULL)) { SDL_OutOfMemory(); - if ( this ) { + if (this) { SDL_free(this); } - return(0); + return (0); } SDL_memset(this->hidden, 0, (sizeof *this->hidden)); /* Set the function pointers */ - this->OpenAudio = Mint_OpenAudio; - this->CloseAudio = Mint_CloseAudio; - this->LockAudio = Mint_LockAudio; + this->OpenAudio = Mint_OpenAudio; + this->CloseAudio = Mint_CloseAudio; + this->LockAudio = Mint_LockAudio; this->UnlockAudio = Mint_UnlockAudio; - this->free = Audio_DeleteDevice; + this->free = Audio_DeleteDevice; return this; } AudioBootStrap MINTAUDIO_STFA_bootstrap = { - MINT_AUDIO_DRIVER_NAME, "MiNT STFA audio driver", - Audio_Available, Audio_CreateDevice + MINT_AUDIO_DRIVER_NAME, "MiNT STFA audio driver", + Audio_Available, Audio_CreateDevice }; -static void Mint_LockAudio(_THIS) +static void +Mint_LockAudio(_THIS) { - void *oldpile; + void *oldpile; - /* Stop replay */ - oldpile=(void *)Super(0); - cookie_stfa->sound_enable=STFA_PLAY_DISABLE; - Super(oldpile); + /* Stop replay */ + oldpile = (void *) Super(0); + cookie_stfa->sound_enable = STFA_PLAY_DISABLE; + Super(oldpile); } -static void Mint_UnlockAudio(_THIS) +static void +Mint_UnlockAudio(_THIS) { - void *oldpile; + void *oldpile; - /* Restart replay */ - oldpile=(void *)Super(0); - cookie_stfa->sound_enable=STFA_PLAY_ENABLE|STFA_PLAY_REPEAT; - Super(oldpile); + /* Restart replay */ + oldpile = (void *) Super(0); + cookie_stfa->sound_enable = STFA_PLAY_ENABLE | STFA_PLAY_REPEAT; + Super(oldpile); } -static void Mint_CloseAudio(_THIS) +static void +Mint_CloseAudio(_THIS) { - void *oldpile; + void *oldpile; - /* Stop replay */ - oldpile=(void *)Super(0); - cookie_stfa->sound_enable=STFA_PLAY_DISABLE; - Super(oldpile); + /* Stop replay */ + oldpile = (void *) Super(0); + cookie_stfa->sound_enable = STFA_PLAY_DISABLE; + Super(oldpile); - /* Wait if currently playing sound */ - while (SDL_MintAudio_mutex != 0) { - } + /* Wait if currently playing sound */ + while (SDL_MintAudio_mutex != 0) { + } - /* Clear buffers */ - if (SDL_MintAudio_audiobuf[0]) { - Mfree(SDL_MintAudio_audiobuf[0]); - SDL_MintAudio_audiobuf[0] = SDL_MintAudio_audiobuf[1] = NULL; - } + /* Clear buffers */ + if (SDL_MintAudio_audiobuf[0]) { + Mfree(SDL_MintAudio_audiobuf[0]); + SDL_MintAudio_audiobuf[0] = SDL_MintAudio_audiobuf[1] = NULL; + } } -static int Mint_CheckAudio(_THIS, SDL_AudioSpec *spec) +static int +Mint_CheckAudio(_THIS, SDL_AudioSpec * spec) { - int i; - - DEBUG_PRINT((DEBUG_NAME "asked: %d bits, ",spec->format & 0x00ff)); - DEBUG_PRINT(("signed=%d, ", ((spec->format & 0x8000)!=0))); - DEBUG_PRINT(("big endian=%d, ", ((spec->format & 0x1000)!=0))); - DEBUG_PRINT(("channels=%d, ", spec->channels)); - DEBUG_PRINT(("freq=%d\n", spec->freq)); - - /* Check formats available */ - MINTAUDIO_freqcount=0; - for (i=0;i<16;i++) { - SDL_MintAudio_AddFrequency(this, freqs[i], 0, i, -1); - } + int i; + + DEBUG_PRINT((DEBUG_NAME "asked: %d bits, ", spec->format & 0x00ff)); + DEBUG_PRINT(("signed=%d, ", ((spec->format & 0x8000) != 0))); + DEBUG_PRINT(("big endian=%d, ", ((spec->format & 0x1000) != 0))); + DEBUG_PRINT(("channels=%d, ", spec->channels)); + DEBUG_PRINT(("freq=%d\n", spec->freq)); + + /* Check formats available */ + MINTAUDIO_freqcount = 0; + for (i = 0; i < 16; i++) { + SDL_MintAudio_AddFrequency(this, freqs[i], 0, i, -1); + } #if 1 - for (i=0; ifreq); - spec->freq=MINTAUDIO_frequencies[MINTAUDIO_numfreq].frequency; + MINTAUDIO_numfreq = SDL_MintAudio_SearchFrequency(this, spec->freq); + spec->freq = MINTAUDIO_frequencies[MINTAUDIO_numfreq].frequency; - DEBUG_PRINT((DEBUG_NAME "obtained: %d bits, ",spec->format & 0x00ff)); - DEBUG_PRINT(("signed=%d, ", ((spec->format & 0x8000)!=0))); - DEBUG_PRINT(("big endian=%d, ", ((spec->format & 0x1000)!=0))); - DEBUG_PRINT(("channels=%d, ", spec->channels)); - DEBUG_PRINT(("freq=%d\n", spec->freq)); + DEBUG_PRINT((DEBUG_NAME "obtained: %d bits, ", spec->format & 0x00ff)); + DEBUG_PRINT(("signed=%d, ", ((spec->format & 0x8000) != 0))); + DEBUG_PRINT(("big endian=%d, ", ((spec->format & 0x1000) != 0))); + DEBUG_PRINT(("channels=%d, ", spec->channels)); + DEBUG_PRINT(("freq=%d\n", spec->freq)); - return 0; + return 0; } -static void Mint_InitAudio(_THIS, SDL_AudioSpec *spec) +static void +Mint_InitAudio(_THIS, SDL_AudioSpec * spec) { - void *buffer; - void *oldpile; + void *buffer; + void *oldpile; - buffer = SDL_MintAudio_audiobuf[SDL_MintAudio_numbuf]; + buffer = SDL_MintAudio_audiobuf[SDL_MintAudio_numbuf]; - oldpile=(void *)Super(0); + oldpile = (void *) Super(0); - /* Stop replay */ - cookie_stfa->sound_enable=STFA_PLAY_DISABLE; + /* Stop replay */ + cookie_stfa->sound_enable = STFA_PLAY_DISABLE; - /* Select replay format */ - cookie_stfa->sound_control = MINTAUDIO_frequencies[MINTAUDIO_numfreq].predivisor; - if ((spec->format & 0xff)==8) { - cookie_stfa->sound_control |= STFA_FORMAT_8BIT; - } else { - cookie_stfa->sound_control |= STFA_FORMAT_16BIT; - } - if (spec->channels==2) { - cookie_stfa->sound_control |= STFA_FORMAT_STEREO; - } else { - cookie_stfa->sound_control |= STFA_FORMAT_MONO; - } - if ((spec->format & 0x8000)!=0) { - cookie_stfa->sound_control |= STFA_FORMAT_SIGNED; - } else { - cookie_stfa->sound_control |= STFA_FORMAT_UNSIGNED; - } - if ((spec->format & 0x1000)!=0) { - cookie_stfa->sound_control |= STFA_FORMAT_BIGENDIAN; - } else { - cookie_stfa->sound_control |= STFA_FORMAT_LITENDIAN; - } + /* Select replay format */ + cookie_stfa->sound_control = + MINTAUDIO_frequencies[MINTAUDIO_numfreq].predivisor; + if ((spec->format & 0xff) == 8) { + cookie_stfa->sound_control |= STFA_FORMAT_8BIT; + } else { + cookie_stfa->sound_control |= STFA_FORMAT_16BIT; + } + if (spec->channels == 2) { + cookie_stfa->sound_control |= STFA_FORMAT_STEREO; + } else { + cookie_stfa->sound_control |= STFA_FORMAT_MONO; + } + if ((spec->format & 0x8000) != 0) { + cookie_stfa->sound_control |= STFA_FORMAT_SIGNED; + } else { + cookie_stfa->sound_control |= STFA_FORMAT_UNSIGNED; + } + if ((spec->format & 0x1000) != 0) { + cookie_stfa->sound_control |= STFA_FORMAT_BIGENDIAN; + } else { + cookie_stfa->sound_control |= STFA_FORMAT_LITENDIAN; + } - /* Set buffer */ - cookie_stfa->sound_start = (unsigned long) buffer; - cookie_stfa->sound_end = (unsigned long) (buffer + spec->size); + /* Set buffer */ + cookie_stfa->sound_start = (unsigned long) buffer; + cookie_stfa->sound_end = (unsigned long) (buffer + spec->size); - /* Set interrupt */ - cookie_stfa->stfa_it = SDL_MintAudio_StfaInterrupt; + /* Set interrupt */ + cookie_stfa->stfa_it = SDL_MintAudio_StfaInterrupt; - /* Restart replay */ - cookie_stfa->sound_enable=STFA_PLAY_ENABLE|STFA_PLAY_REPEAT; + /* Restart replay */ + cookie_stfa->sound_enable = STFA_PLAY_ENABLE | STFA_PLAY_REPEAT; - Super(oldpile); + Super(oldpile); - DEBUG_PRINT((DEBUG_NAME "hardware initialized\n")); + DEBUG_PRINT((DEBUG_NAME "hardware initialized\n")); } -static int Mint_OpenAudio(_THIS, SDL_AudioSpec *spec) +static int +Mint_OpenAudio(_THIS, SDL_AudioSpec * spec) { - SDL_MintAudio_device = this; + SDL_MintAudio_device = this; - /* Check audio capabilities */ - if (Mint_CheckAudio(this, spec)==-1) { - return -1; - } + /* Check audio capabilities */ + if (Mint_CheckAudio(this, spec) == -1) { + return -1; + } - SDL_CalculateAudioSpec(spec); + SDL_CalculateAudioSpec(spec); - /* Allocate memory for audio buffers in DMA-able RAM */ - DEBUG_PRINT((DEBUG_NAME "buffer size=%d\n", spec->size)); + /* Allocate memory for audio buffers in DMA-able RAM */ + DEBUG_PRINT((DEBUG_NAME "buffer size=%d\n", spec->size)); - SDL_MintAudio_audiobuf[0] = Atari_SysMalloc(spec->size *2, MX_STRAM); - if (SDL_MintAudio_audiobuf[0]==NULL) { - SDL_SetError("MINT_OpenAudio: Not enough memory for audio buffer"); - return (-1); - } - SDL_MintAudio_audiobuf[1] = SDL_MintAudio_audiobuf[0] + spec->size ; - SDL_MintAudio_numbuf=0; - SDL_memset(SDL_MintAudio_audiobuf[0], spec->silence, spec->size *2); - SDL_MintAudio_audiosize = spec->size; - SDL_MintAudio_mutex = 0; + SDL_MintAudio_audiobuf[0] = Atari_SysMalloc(spec->size * 2, MX_STRAM); + if (SDL_MintAudio_audiobuf[0] == NULL) { + SDL_SetError("MINT_OpenAudio: Not enough memory for audio buffer"); + return (-1); + } + SDL_MintAudio_audiobuf[1] = SDL_MintAudio_audiobuf[0] + spec->size; + SDL_MintAudio_numbuf = 0; + SDL_memset(SDL_MintAudio_audiobuf[0], spec->silence, spec->size * 2); + SDL_MintAudio_audiosize = spec->size; + SDL_MintAudio_mutex = 0; - DEBUG_PRINT((DEBUG_NAME "buffer 0 at 0x%08x\n", SDL_MintAudio_audiobuf[0])); - DEBUG_PRINT((DEBUG_NAME "buffer 1 at 0x%08x\n", SDL_MintAudio_audiobuf[1])); + DEBUG_PRINT((DEBUG_NAME "buffer 0 at 0x%08x\n", + SDL_MintAudio_audiobuf[0])); + DEBUG_PRINT((DEBUG_NAME "buffer 1 at 0x%08x\n", + SDL_MintAudio_audiobuf[1])); - /* Setup audio hardware */ - Mint_InitAudio(this, spec); + /* Setup audio hardware */ + Mint_InitAudio(this, spec); - return(1); /* We don't use threaded audio */ + return (1); /* We don't use threaded audio */ } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/audio/mint/SDL_mintaudio_stfa.h b/src/audio/mint/SDL_mintaudio_stfa.h index d4bf2d6b4..abf6c3af7 100644 --- a/src/audio/mint/SDL_mintaudio_stfa.h +++ b/src/audio/mint/SDL_mintaudio_stfa.h @@ -32,7 +32,7 @@ /*--- Defines ---*/ -#define C_STFA 0x53544641L /* Sound treiber für atari (seb/The removers) */ +#define C_STFA 0x53544641L /* Sound treiber für atari (seb/The removers) */ #define STFA_PLAY_ENABLE (1<<0) #define STFA_PLAY_DISABLE (0<<0) @@ -48,53 +48,56 @@ #define STFA_FORMAT_LITENDIAN (1<<9) #define STFA_FORMAT_BIGENDIAN (0<<9) #define STFA_FORMAT_FREQ_MASK 0x0f -enum { - STFA_FORMAT_F4995=0, - STFA_FORMAT_F6269, - STFA_FORMAT_F7493, - STFA_FORMAT_F8192, - - STFA_FORMAT_F9830, - STFA_FORMAT_F10971, - STFA_FORMAT_F12538, - STFA_FORMAT_F14985, - - STFA_FORMAT_F16384, - STFA_FORMAT_F19819, - STFA_FORMAT_F21943, - STFA_FORMAT_F24576, - - STFA_FORMAT_F30720, - STFA_FORMAT_F32336, - STFA_FORMAT_F43885, - STFA_FORMAT_F49152 +enum +{ + STFA_FORMAT_F4995 = 0, + STFA_FORMAT_F6269, + STFA_FORMAT_F7493, + STFA_FORMAT_F8192, + + STFA_FORMAT_F9830, + STFA_FORMAT_F10971, + STFA_FORMAT_F12538, + STFA_FORMAT_F14985, + + STFA_FORMAT_F16384, + STFA_FORMAT_F19819, + STFA_FORMAT_F21943, + STFA_FORMAT_F24576, + + STFA_FORMAT_F30720, + STFA_FORMAT_F32336, + STFA_FORMAT_F43885, + STFA_FORMAT_F49152 }; /*--- Types ---*/ -typedef struct { - unsigned short sound_enable; - unsigned short sound_control; - unsigned short sound_output; - unsigned long sound_start; - unsigned long sound_current; - unsigned long sound_end; - unsigned short version; - void *old_vbl; - void *old_timera; - unsigned long old_mfp_status; - void *new_vbl; - void *drivers_list; - void *play_stop; - unsigned short frequency; - void *set_frequency; - - unsigned short frequency_threshold; - unsigned short *custom_freq_table; - unsigned short stfa_on_off; - void *new_drivers_list; - unsigned long old_bit_2_of_cookie_snd; - void (*stfa_it)(void); -} cookie_stfa_t __attribute__((packed)); +typedef struct +{ + unsigned short sound_enable; + unsigned short sound_control; + unsigned short sound_output; + unsigned long sound_start; + unsigned long sound_current; + unsigned long sound_end; + unsigned short version; + void *old_vbl; + void *old_timera; + unsigned long old_mfp_status; + void *new_vbl; + void *drivers_list; + void *play_stop; + unsigned short frequency; + void *set_frequency; + + unsigned short frequency_threshold; + unsigned short *custom_freq_table; + unsigned short stfa_on_off; + void *new_drivers_list; + unsigned long old_bit_2_of_cookie_snd; + void (*stfa_it) (void); +} cookie_stfa_t __attribute__ ((packed)); #endif /* _SDL_mintaudio_stfa_h */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/audio/mint/SDL_mintaudio_xbios.c b/src/audio/mint/SDL_mintaudio_xbios.c index 016d4fa59..c7e7f0b3b 100644 --- a/src/audio/mint/SDL_mintaudio_xbios.c +++ b/src/audio/mint/SDL_mintaudio_xbios.c @@ -67,421 +67,454 @@ static unsigned long cookie_snd; /*--- Audio driver functions ---*/ static void Mint_CloseAudio(_THIS); -static int Mint_OpenAudio(_THIS, SDL_AudioSpec *spec); +static int Mint_OpenAudio(_THIS, SDL_AudioSpec * spec); static void Mint_LockAudio(_THIS); static void Mint_UnlockAudio(_THIS); /* To check/init hardware audio */ -static int Mint_CheckAudio(_THIS, SDL_AudioSpec *spec); -static void Mint_InitAudio(_THIS, SDL_AudioSpec *spec); +static int Mint_CheckAudio(_THIS, SDL_AudioSpec * spec); +static void Mint_InitAudio(_THIS, SDL_AudioSpec * spec); /*--- Audio driver bootstrap functions ---*/ -static int Audio_Available(void) +static int +Audio_Available(void) { - unsigned long dummy; - const char *envr = SDL_getenv("SDL_AUDIODRIVER"); + unsigned long dummy; + const char *envr = SDL_getenv("SDL_AUDIODRIVER"); - SDL_MintAudio_mint_present = (Getcookie(C_MiNT, &dummy) == C_FOUND); + SDL_MintAudio_mint_present = (Getcookie(C_MiNT, &dummy) == C_FOUND); - /* We can't use XBIOS in interrupt with Magic, don't know about thread */ - if (Getcookie(C_MagX, &dummy) == C_FOUND) { - return(0); - } + /* We can't use XBIOS in interrupt with Magic, don't know about thread */ + if (Getcookie(C_MagX, &dummy) == C_FOUND) { + return (0); + } - /* Check if user asked a different audio driver */ - if ((envr) && (SDL_strcmp(envr, MINT_AUDIO_DRIVER_NAME)!=0)) { - DEBUG_PRINT((DEBUG_NAME "user asked a different audio driver\n")); - return(0); - } + /* Check if user asked a different audio driver */ + if ((envr) && (SDL_strcmp(envr, MINT_AUDIO_DRIVER_NAME) != 0)) { + DEBUG_PRINT((DEBUG_NAME "user asked a different audio driver\n")); + return (0); + } - /* Cookie _SND present ? if not, assume ST machine */ - if (Getcookie(C__SND, &cookie_snd) == C_NOTFOUND) { - cookie_snd = SND_PSG; - } + /* Cookie _SND present ? if not, assume ST machine */ + if (Getcookie(C__SND, &cookie_snd) == C_NOTFOUND) { + cookie_snd = SND_PSG; + } - /* Check if we have 16 bits audio */ - if ((cookie_snd & SND_16BIT)==0) { - DEBUG_PRINT((DEBUG_NAME "no 16 bits sound\n")); - return(0); - } + /* Check if we have 16 bits audio */ + if ((cookie_snd & SND_16BIT) == 0) { + DEBUG_PRINT((DEBUG_NAME "no 16 bits sound\n")); + return (0); + } - /* Check if audio is lockable */ - if (Locksnd()!=1) { - DEBUG_PRINT((DEBUG_NAME "audio locked by other application\n")); - return(0); - } + /* Check if audio is lockable */ + if (Locksnd() != 1) { + DEBUG_PRINT((DEBUG_NAME "audio locked by other application\n")); + return (0); + } - Unlocksnd(); + Unlocksnd(); - DEBUG_PRINT((DEBUG_NAME "XBIOS audio available!\n")); - return(1); + DEBUG_PRINT((DEBUG_NAME "XBIOS audio available!\n")); + return (1); } -static void Audio_DeleteDevice(SDL_AudioDevice *device) +static void +Audio_DeleteDevice(SDL_AudioDevice * device) { SDL_free(device->hidden); SDL_free(device); } -static SDL_AudioDevice *Audio_CreateDevice(int devindex) +static SDL_AudioDevice * +Audio_CreateDevice(int devindex) { - SDL_AudioDevice *this; + SDL_AudioDevice *this; - /* Initialize all variables that we clean on shutdown */ - this = (SDL_AudioDevice *)SDL_malloc(sizeof(SDL_AudioDevice)); - if ( this ) { + /* Initialize all variables that we clean on shutdown */ + this = (SDL_AudioDevice *) SDL_malloc(sizeof(SDL_AudioDevice)); + if (this) { SDL_memset(this, 0, (sizeof *this)); this->hidden = (struct SDL_PrivateAudioData *) - SDL_malloc((sizeof *this->hidden)); + SDL_malloc((sizeof *this->hidden)); } - if ( (this == NULL) || (this->hidden == NULL) ) { + if ((this == NULL) || (this->hidden == NULL)) { SDL_OutOfMemory(); - if ( this ) { + if (this) { SDL_free(this); } - return(0); + return (0); } SDL_memset(this->hidden, 0, (sizeof *this->hidden)); /* Set the function pointers */ - this->OpenAudio = Mint_OpenAudio; - this->CloseAudio = Mint_CloseAudio; - this->LockAudio = Mint_LockAudio; + this->OpenAudio = Mint_OpenAudio; + this->CloseAudio = Mint_CloseAudio; + this->LockAudio = Mint_LockAudio; this->UnlockAudio = Mint_UnlockAudio; - this->free = Audio_DeleteDevice; + this->free = Audio_DeleteDevice; return this; } AudioBootStrap MINTAUDIO_XBIOS_bootstrap = { - MINT_AUDIO_DRIVER_NAME, "MiNT XBIOS audio driver", - Audio_Available, Audio_CreateDevice + MINT_AUDIO_DRIVER_NAME, "MiNT XBIOS audio driver", + Audio_Available, Audio_CreateDevice }; -static void Mint_LockAudio(_THIS) +static void +Mint_LockAudio(_THIS) { - /* Stop replay */ - Buffoper(0); + /* Stop replay */ + Buffoper(0); } -static void Mint_UnlockAudio(_THIS) +static void +Mint_UnlockAudio(_THIS) { - /* Restart replay */ - Buffoper(SB_PLA_ENA|SB_PLA_RPT); + /* Restart replay */ + Buffoper(SB_PLA_ENA | SB_PLA_RPT); } -static void Mint_CloseAudio(_THIS) +static void +Mint_CloseAudio(_THIS) { - /* Stop replay */ - SDL_MintAudio_WaitThread(); - Buffoper(0); + /* Stop replay */ + SDL_MintAudio_WaitThread(); + Buffoper(0); - if (!SDL_MintAudio_mint_present) { - /* Uninstall interrupt */ - Jdisint(MFP_DMASOUND); - } + if (!SDL_MintAudio_mint_present) { + /* Uninstall interrupt */ + Jdisint(MFP_DMASOUND); + } - /* Wait if currently playing sound */ - while (SDL_MintAudio_mutex != 0) { - } + /* Wait if currently playing sound */ + while (SDL_MintAudio_mutex != 0) { + } - /* Clear buffers */ - if (SDL_MintAudio_audiobuf[0]) { - Mfree(SDL_MintAudio_audiobuf[0]); - SDL_MintAudio_audiobuf[0] = SDL_MintAudio_audiobuf[1] = NULL; - } + /* Clear buffers */ + if (SDL_MintAudio_audiobuf[0]) { + Mfree(SDL_MintAudio_audiobuf[0]); + SDL_MintAudio_audiobuf[0] = SDL_MintAudio_audiobuf[1] = NULL; + } - /* Unlock sound system */ - Unlocksnd(); + /* Unlock sound system */ + Unlocksnd(); } /* Falcon XBIOS implementation of Devconnect() is buggy with external clock */ -static void Devconnect2(int src, int dst, int sclk, int pre) -{ - static const unsigned short MASK1[3] = { 0, 0x6000, 0 }; - static const unsigned short MASK2[4] = { 0xFFF0, 0xFF8F, 0xF0FF, 0x0FFF }; - static const unsigned short INDEX1[4] = { 1, 3, 5, 7 }; - static const unsigned short INDEX2[4] = { 0, 2, 4, 6 }; - unsigned short sync_div,dev_ctrl,dest_ctrl; - void *oldstack; - - if (dst==0) { - return; - } +static void +Devconnect2(int src, int dst, int sclk, int pre) +{ + static const unsigned short MASK1[3] = { 0, 0x6000, 0 }; + static const unsigned short MASK2[4] = { 0xFFF0, 0xFF8F, 0xF0FF, 0x0FFF }; + static const unsigned short INDEX1[4] = { 1, 3, 5, 7 }; + static const unsigned short INDEX2[4] = { 0, 2, 4, 6 }; + unsigned short sync_div, dev_ctrl, dest_ctrl; + void *oldstack; + + if (dst == 0) { + return; + } - oldstack=(void *)Super(0); + oldstack = (void *) Super(0); - dev_ctrl = DMAAUDIO_IO.dev_ctrl; - dest_ctrl = DMAAUDIO_IO.dest_ctrl; - dev_ctrl &= MASK2[src]; + dev_ctrl = DMAAUDIO_IO.dev_ctrl; + dest_ctrl = DMAAUDIO_IO.dest_ctrl; + dev_ctrl &= MASK2[src]; - if (src==ADC) { - dev_ctrl |= MASK1[sclk]; - } else { - dev_ctrl |= (INDEX1[sclk] << (src<<4)); - } + if (src == ADC) { + dev_ctrl |= MASK1[sclk]; + } else { + dev_ctrl |= (INDEX1[sclk] << (src << 4)); + } - if (dst & DMAREC) { - dest_ctrl &= 0xFFF0; - dest_ctrl |= INDEX1[src]; - } + if (dst & DMAREC) { + dest_ctrl &= 0xFFF0; + dest_ctrl |= INDEX1[src]; + } - if (dst & DSPRECV) { - dest_ctrl &= 0xFF8F; - dest_ctrl |= (INDEX1[src]<<4); - } + if (dst & DSPRECV) { + dest_ctrl &= 0xFF8F; + dest_ctrl |= (INDEX1[src] << 4); + } - if (dst & EXTOUT) { - dest_ctrl &= 0xF0FF; - dest_ctrl |= (INDEX1[src]<<8); - } + if (dst & EXTOUT) { + dest_ctrl &= 0xF0FF; + dest_ctrl |= (INDEX1[src] << 8); + } - if (dst & DAC) { - dev_ctrl &= 0x0FFF; - dev_ctrl |= MASK1[sclk]; - dest_ctrl &= 0x0FFF; - dest_ctrl |= (INDEX2[src]<<12); - } + if (dst & DAC) { + dev_ctrl &= 0x0FFF; + dev_ctrl |= MASK1[sclk]; + dest_ctrl &= 0x0FFF; + dest_ctrl |= (INDEX2[src] << 12); + } - sync_div = DMAAUDIO_IO.sync_div; - if (sclk==CLKEXT) { - pre<<=8; - sync_div &= 0xF0FF; - } else { - sync_div &= 0xFFF0; - } - sync_div |= pre; + sync_div = DMAAUDIO_IO.sync_div; + if (sclk == CLKEXT) { + pre <<= 8; + sync_div &= 0xF0FF; + } else { + sync_div &= 0xFFF0; + } + sync_div |= pre; - DMAAUDIO_IO.dev_ctrl = dev_ctrl; - DMAAUDIO_IO.dest_ctrl = dest_ctrl; - DMAAUDIO_IO.sync_div = sync_div; + DMAAUDIO_IO.dev_ctrl = dev_ctrl; + DMAAUDIO_IO.dest_ctrl = dest_ctrl; + DMAAUDIO_IO.sync_div = sync_div; - Super(oldstack); + Super(oldstack); } -static void Mint_CheckExternalClock(_THIS) +static void +Mint_CheckExternalClock(_THIS) { #define SIZE_BUF_CLOCK_MEASURE (44100/10) - unsigned long cookie_snd; - char *buffer; - int i, j; + unsigned long cookie_snd; + char *buffer; + int i, j; - /* DSP present with its GPIO port ? */ - if (Getcookie(C__SND, &cookie_snd) == C_NOTFOUND) { - return; - } - if ((cookie_snd & SND_DSP)==0) { - return; - } + /* DSP present with its GPIO port ? */ + if (Getcookie(C__SND, &cookie_snd) == C_NOTFOUND) { + return; + } + if ((cookie_snd & SND_DSP) == 0) { + return; + } - buffer = Atari_SysMalloc(SIZE_BUF_CLOCK_MEASURE, MX_STRAM); - if (buffer==NULL) { - DEBUG_PRINT((DEBUG_NAME "Not enough memory for the measure\n")); - return; - } - SDL_memset(buffer, 0, SIZE_BUF_CLOCK_MEASURE); - - Buffoper(0); - Settracks(0,0); - Setmontracks(0); - Setmode(MONO8); - Jdisint(MFP_TIMERA); - - for (i=0; i<2; i++) { - Gpio(GPIO_SET,7); /* DSP port gpio outputs */ - Gpio(GPIO_WRITE,2+i); /* 22.5792/24.576 MHz for 44.1/48KHz */ - Devconnect2(DMAPLAY, DAC, CLKEXT, CLK50K); /* Matrix and clock source */ - Setbuffer(0, buffer, buffer + SIZE_BUF_CLOCK_MEASURE); /* Set buffer */ - Xbtimer(XB_TIMERA, 5, 38, SDL_MintAudio_XbiosInterruptMeasureClock); /* delay mode timer A, prediv /64, 1KHz */ - Jenabint(MFP_TIMERA); - SDL_MintAudio_clocktics = 0; - Buffoper(SB_PLA_ENA); - usleep(110000); - - if((Buffoper(-1) & 1)==0) { - if (SDL_MintAudio_clocktics) { - unsigned long khz; - - khz = ((SIZE_BUF_CLOCK_MEASURE/SDL_MintAudio_clocktics) +1) & 0xFFFFFFFE; - DEBUG_PRINT((DEBUG_NAME "measure %d: freq=%lu KHz\n", i+1, khz)); - - if(khz==44) { - for (j=1; j<4; j++) { - SDL_MintAudio_AddFrequency(this, MASTERCLOCK_44K/(MASTERPREDIV_FALCON*(1<format & 0x00ff)); - DEBUG_PRINT(("signed=%d, ", ((spec->format & 0x8000)!=0))); - DEBUG_PRINT(("big endian=%d, ", ((spec->format & 0x1000)!=0))); - DEBUG_PRINT(("channels=%d, ", spec->channels)); - DEBUG_PRINT(("freq=%d\n", spec->freq)); - - spec->format |= 0x8000; /* Audio is always signed */ - if ((spec->format & 0x00ff)==16) { - spec->format |= 0x1000; /* Audio is always big endian */ - spec->channels=2; /* 16 bits always stereo */ - } + int i; + Uint32 extclock; + + DEBUG_PRINT((DEBUG_NAME "asked: %d bits, ", spec->format & 0x00ff)); + DEBUG_PRINT(("signed=%d, ", ((spec->format & 0x8000) != 0))); + DEBUG_PRINT(("big endian=%d, ", ((spec->format & 0x1000) != 0))); + DEBUG_PRINT(("channels=%d, ", spec->channels)); + DEBUG_PRINT(("freq=%d\n", spec->freq)); + + spec->format |= 0x8000; /* Audio is always signed */ + if ((spec->format & 0x00ff) == 16) { + spec->format |= 0x1000; /* Audio is always big endian */ + spec->channels = 2; /* 16 bits always stereo */ + } - MINTAUDIO_freqcount=0; + MINTAUDIO_freqcount = 0; - /* Add external clocks if present */ - Mint_CheckExternalClock(this); + /* Add external clocks if present */ + Mint_CheckExternalClock(this); - /* Standard clocks */ - for (i=1;i<12;i++) { - /* Remove unusable Falcon codec predivisors */ - if ((i==6) || (i==8) || (i==10)) { - continue; - } - SDL_MintAudio_AddFrequency(this, MASTERCLOCK_FALCON1/(MASTERPREDIV_FALCON*(i+1)), MASTERCLOCK_FALCON1, i, -1); - } + /* Standard clocks */ + for (i = 1; i < 12; i++) { + /* Remove unusable Falcon codec predivisors */ + if ((i == 6) || (i == 8) || (i == 10)) { + continue; + } + SDL_MintAudio_AddFrequency(this, + MASTERCLOCK_FALCON1 / + (MASTERPREDIV_FALCON * (i + 1)), + MASTERCLOCK_FALCON1, i, -1); + } #if 1 - for (i=0; ifreq); - spec->freq=MINTAUDIO_frequencies[MINTAUDIO_numfreq].frequency; + MINTAUDIO_numfreq = SDL_MintAudio_SearchFrequency(this, spec->freq); + spec->freq = MINTAUDIO_frequencies[MINTAUDIO_numfreq].frequency; - DEBUG_PRINT((DEBUG_NAME "obtained: %d bits, ",spec->format & 0x00ff)); - DEBUG_PRINT(("signed=%d, ", ((spec->format & 0x8000)!=0))); - DEBUG_PRINT(("big endian=%d, ", ((spec->format & 0x1000)!=0))); - DEBUG_PRINT(("channels=%d, ", spec->channels)); - DEBUG_PRINT(("freq=%d\n", spec->freq)); + DEBUG_PRINT((DEBUG_NAME "obtained: %d bits, ", spec->format & 0x00ff)); + DEBUG_PRINT(("signed=%d, ", ((spec->format & 0x8000) != 0))); + DEBUG_PRINT(("big endian=%d, ", ((spec->format & 0x1000) != 0))); + DEBUG_PRINT(("channels=%d, ", spec->channels)); + DEBUG_PRINT(("freq=%d\n", spec->freq)); - return 0; + return 0; } -static void Mint_InitAudio(_THIS, SDL_AudioSpec *spec) +static void +Mint_InitAudio(_THIS, SDL_AudioSpec * spec) { - int channels_mode, dmaclock, prediv; - void *buffer; - - /* Stop currently playing sound */ - SDL_MintAudio_quit_thread = SDL_FALSE; - SDL_MintAudio_thread_finished = SDL_TRUE; - SDL_MintAudio_WaitThread(); - Buffoper(0); - - /* Set replay tracks */ - Settracks(0,0); - Setmontracks(0); - - /* Select replay format */ - channels_mode=STEREO16; - switch (spec->format & 0xff) { - case 8: - if (spec->channels==2) { - channels_mode=STEREO8; - } else { - channels_mode=MONO8; - } - break; - } - if (Setmode(channels_mode)<0) { - DEBUG_PRINT((DEBUG_NAME "Setmode() failed\n")); - } + int channels_mode, dmaclock, prediv; + void *buffer; + + /* Stop currently playing sound */ + SDL_MintAudio_quit_thread = SDL_FALSE; + SDL_MintAudio_thread_finished = SDL_TRUE; + SDL_MintAudio_WaitThread(); + Buffoper(0); + + /* Set replay tracks */ + Settracks(0, 0); + Setmontracks(0); + + /* Select replay format */ + channels_mode = STEREO16; + switch (spec->format & 0xff) { + case 8: + if (spec->channels == 2) { + channels_mode = STEREO8; + } else { + channels_mode = MONO8; + } + break; + } + if (Setmode(channels_mode) < 0) { + DEBUG_PRINT((DEBUG_NAME "Setmode() failed\n")); + } - dmaclock = MINTAUDIO_frequencies[MINTAUDIO_numfreq].masterclock; - prediv = MINTAUDIO_frequencies[MINTAUDIO_numfreq].predivisor; - if (MINTAUDIO_frequencies[MINTAUDIO_numfreq].gpio_bits != -1) { - Gpio(GPIO_SET,7); /* DSP port gpio outputs */ - Gpio(GPIO_WRITE, MINTAUDIO_frequencies[MINTAUDIO_numfreq].gpio_bits); - Devconnect2(DMAPLAY, DAC|EXTOUT, CLKEXT, prediv); - } else { - Devconnect2(DMAPLAY, DAC, CLK25M, prediv); - } + dmaclock = MINTAUDIO_frequencies[MINTAUDIO_numfreq].masterclock; + prediv = MINTAUDIO_frequencies[MINTAUDIO_numfreq].predivisor; + if (MINTAUDIO_frequencies[MINTAUDIO_numfreq].gpio_bits != -1) { + Gpio(GPIO_SET, 7); /* DSP port gpio outputs */ + Gpio(GPIO_WRITE, MINTAUDIO_frequencies[MINTAUDIO_numfreq].gpio_bits); + Devconnect2(DMAPLAY, DAC | EXTOUT, CLKEXT, prediv); + } else { + Devconnect2(DMAPLAY, DAC, CLK25M, prediv); + } - /* Set buffer */ - buffer = SDL_MintAudio_audiobuf[SDL_MintAudio_numbuf]; - if (Setbuffer(0, buffer, buffer + spec->size)<0) { - DEBUG_PRINT((DEBUG_NAME "Setbuffer() failed\n")); - } - - if (SDL_MintAudio_mint_present) { - SDL_MintAudio_thread_pid = tfork(SDL_MintAudio_Thread, 0); - } else { - /* Install interrupt */ - Jdisint(MFP_DMASOUND); - Xbtimer(XB_TIMERA, 8, 1, SDL_MintAudio_XbiosInterrupt); - Jenabint(MFP_DMASOUND); - - if (Setinterrupt(SI_TIMERA, SI_PLAY)<0) { - DEBUG_PRINT((DEBUG_NAME "Setinterrupt() failed\n")); - } - } + /* Set buffer */ + buffer = SDL_MintAudio_audiobuf[SDL_MintAudio_numbuf]; + if (Setbuffer(0, buffer, buffer + spec->size) < 0) { + DEBUG_PRINT((DEBUG_NAME "Setbuffer() failed\n")); + } + + if (SDL_MintAudio_mint_present) { + SDL_MintAudio_thread_pid = tfork(SDL_MintAudio_Thread, 0); + } else { + /* Install interrupt */ + Jdisint(MFP_DMASOUND); + Xbtimer(XB_TIMERA, 8, 1, SDL_MintAudio_XbiosInterrupt); + Jenabint(MFP_DMASOUND); - /* Go */ - Buffoper(SB_PLA_ENA|SB_PLA_RPT); - DEBUG_PRINT((DEBUG_NAME "hardware initialized\n")); + if (Setinterrupt(SI_TIMERA, SI_PLAY) < 0) { + DEBUG_PRINT((DEBUG_NAME "Setinterrupt() failed\n")); + } + } + + /* Go */ + Buffoper(SB_PLA_ENA | SB_PLA_RPT); + DEBUG_PRINT((DEBUG_NAME "hardware initialized\n")); } -static int Mint_OpenAudio(_THIS, SDL_AudioSpec *spec) +static int +Mint_OpenAudio(_THIS, SDL_AudioSpec * spec) { - /* Lock sound system */ - if (Locksnd()!=1) { - SDL_SetError("Mint_OpenAudio: Audio system already in use"); - return(-1); - } + /* Lock sound system */ + if (Locksnd() != 1) { + SDL_SetError("Mint_OpenAudio: Audio system already in use"); + return (-1); + } - SDL_MintAudio_device = this; + SDL_MintAudio_device = this; - /* Check audio capabilities */ - if (Mint_CheckAudio(this, spec)==-1) { - return -1; - } + /* Check audio capabilities */ + if (Mint_CheckAudio(this, spec) == -1) { + return -1; + } - SDL_CalculateAudioSpec(spec); + SDL_CalculateAudioSpec(spec); - /* Allocate memory for audio buffers in DMA-able RAM */ - DEBUG_PRINT((DEBUG_NAME "buffer size=%d\n", spec->size)); + /* Allocate memory for audio buffers in DMA-able RAM */ + DEBUG_PRINT((DEBUG_NAME "buffer size=%d\n", spec->size)); - SDL_MintAudio_audiobuf[0] = Atari_SysMalloc(spec->size *2, MX_STRAM); - if (SDL_MintAudio_audiobuf[0]==NULL) { - SDL_SetError("MINT_OpenAudio: Not enough memory for audio buffer"); - return (-1); - } - SDL_MintAudio_audiobuf[1] = SDL_MintAudio_audiobuf[0] + spec->size ; - SDL_MintAudio_numbuf=0; - SDL_memset(SDL_MintAudio_audiobuf[0], spec->silence, spec->size *2); - SDL_MintAudio_audiosize = spec->size; - SDL_MintAudio_mutex = 0; + SDL_MintAudio_audiobuf[0] = Atari_SysMalloc(spec->size * 2, MX_STRAM); + if (SDL_MintAudio_audiobuf[0] == NULL) { + SDL_SetError("MINT_OpenAudio: Not enough memory for audio buffer"); + return (-1); + } + SDL_MintAudio_audiobuf[1] = SDL_MintAudio_audiobuf[0] + spec->size; + SDL_MintAudio_numbuf = 0; + SDL_memset(SDL_MintAudio_audiobuf[0], spec->silence, spec->size * 2); + SDL_MintAudio_audiosize = spec->size; + SDL_MintAudio_mutex = 0; - DEBUG_PRINT((DEBUG_NAME "buffer 0 at 0x%08x\n", SDL_MintAudio_audiobuf[0])); - DEBUG_PRINT((DEBUG_NAME "buffer 1 at 0x%08x\n", SDL_MintAudio_audiobuf[1])); + DEBUG_PRINT((DEBUG_NAME "buffer 0 at 0x%08x\n", + SDL_MintAudio_audiobuf[0])); + DEBUG_PRINT((DEBUG_NAME "buffer 1 at 0x%08x\n", + SDL_MintAudio_audiobuf[1])); - /* Setup audio hardware */ - Mint_InitAudio(this, spec); + /* Setup audio hardware */ + Mint_InitAudio(this, spec); - return(1); /* We don't use SDL threaded audio */ + return (1); /* We don't use SDL threaded audio */ } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/audio/mme/SDL_mmeaudio.c b/src/audio/mme/SDL_mmeaudio.c index cb4d2bed4..2bc801a92 100644 --- a/src/audio/mme/SDL_mmeaudio.c +++ b/src/audio/mme/SDL_mmeaudio.c @@ -32,7 +32,7 @@ static BOOL inUse[NUM_BUFFERS]; /* Audio driver functions */ -static int MME_OpenAudio(_THIS, SDL_AudioSpec *spec); +static int MME_OpenAudio(_THIS, SDL_AudioSpec * spec); static void MME_WaitAudio(_THIS); static Uint8 *MME_GetAudioBuf(_THIS); static void MME_PlayAudio(_THIS); @@ -40,49 +40,52 @@ static void MME_WaitDone(_THIS); static void MME_CloseAudio(_THIS); /* Audio driver bootstrap functions */ -static int Audio_Available(void) +static int +Audio_Available(void) { - return(1); + return (1); } -static void Audio_DeleteDevice(SDL_AudioDevice *device) +static void +Audio_DeleteDevice(SDL_AudioDevice * device) { - if ( device ) { - if ( device->hidden ) { - SDL_free(device->hidden); - device->hidden = NULL; - } - SDL_free(device); - device = NULL; + if (device) { + if (device->hidden) { + SDL_free(device->hidden); + device->hidden = NULL; + } + SDL_free(device); + device = NULL; } } -static SDL_AudioDevice *Audio_CreateDevice(int devindex) +static SDL_AudioDevice * +Audio_CreateDevice(int devindex) { SDL_AudioDevice *this; /* Initialize all variables that we clean on shutdown */ this = SDL_malloc(sizeof(SDL_AudioDevice)); - if ( this ) { - SDL_memset(this, 0, (sizeof *this)); - this->hidden = SDL_malloc((sizeof *this->hidden)); + if (this) { + SDL_memset(this, 0, (sizeof *this)); + this->hidden = SDL_malloc((sizeof *this->hidden)); } - if ( (this == NULL) || (this->hidden == NULL) ) { - SDL_OutOfMemory(); - if ( this ) { - SDL_free(this); - } - return(0); + if ((this == NULL) || (this->hidden == NULL)) { + SDL_OutOfMemory(); + if (this) { + SDL_free(this); + } + return (0); } SDL_memset(this->hidden, 0, (sizeof *this->hidden)); /* Set the function pointers */ - this->OpenAudio = MME_OpenAudio; - this->WaitAudio = MME_WaitAudio; - this->PlayAudio = MME_PlayAudio; - this->GetAudioBuf = MME_GetAudioBuf; - this->WaitDone = MME_WaitDone; - this->CloseAudio = MME_CloseAudio; - this->free = Audio_DeleteDevice; + this->OpenAudio = MME_OpenAudio; + this->WaitAudio = MME_WaitAudio; + this->PlayAudio = MME_PlayAudio; + this->GetAudioBuf = MME_GetAudioBuf; + this->WaitDone = MME_WaitDone; + this->CloseAudio = MME_CloseAudio; + this->free = Audio_DeleteDevice; return this; } @@ -92,30 +95,30 @@ AudioBootStrap MMEAUDIO_bootstrap = { Audio_Available, Audio_CreateDevice }; -static void SetMMerror(char *function, MMRESULT code) +static void +SetMMerror(char *function, MMRESULT code) { int len; char errbuf[MAXERRORLENGTH]; SDL_snprintf(errbuf, SDL_arraysize(errbuf), "%s: ", function); len = SDL_strlen(errbuf); - waveOutGetErrorText(code, errbuf+len, MAXERRORLENGTH-len); - SDL_SetError("%s",errbuf); + waveOutGetErrorText(code, errbuf + len, MAXERRORLENGTH - len); + SDL_SetError("%s", errbuf); } -static void CALLBACK MME_CALLBACK(HWAVEOUT hwo, - UINT uMsg, - DWORD dwInstance, - LPARAM dwParam1, - LPARAM dwParam2) +static void CALLBACK +MME_CALLBACK(HWAVEOUT hwo, + UINT uMsg, DWORD dwInstance, LPARAM dwParam1, LPARAM dwParam2) { WAVEHDR *wp = (WAVEHDR *) dwParam1; - if ( uMsg == WOM_DONE ) - inUse[wp->dwUser] = FALSE; + if (uMsg == WOM_DONE) + inUse[wp->dwUser] = FALSE; } -static int MME_OpenAudio(_THIS, SDL_AudioSpec *spec) +static int +MME_OpenAudio(_THIS, SDL_AudioSpec * spec) { MMRESULT result; int i; @@ -124,141 +127,146 @@ static int MME_OpenAudio(_THIS, SDL_AudioSpec *spec) /* Set basic WAVE format parameters */ shm = mmeAllocMem(sizeof(*shm)); - if ( shm == NULL ) { - SDL_SetError("Out of memory: shm"); - return(-1); + if (shm == NULL) { + SDL_SetError("Out of memory: shm"); + return (-1); } shm->sound = 0; shm->wFmt.wf.wFormatTag = WAVE_FORMAT_PCM; /* Determine the audio parameters from the AudioSpec */ - switch ( spec->format & 0xFF ) { - case 8: - /* Unsigned 8 bit audio data */ - spec->format = AUDIO_U8; - shm->wFmt.wBitsPerSample = 8; - break; - case 16: - /* Signed 16 bit audio data */ - spec->format = AUDIO_S16; - shm->wFmt.wBitsPerSample = 16; - break; - default: - SDL_SetError("Unsupported audio format"); - return(-1); + switch (spec->format & 0xFF) { + case 8: + /* Unsigned 8 bit audio data */ + spec->format = AUDIO_U8; + shm->wFmt.wBitsPerSample = 8; + break; + case 16: + /* Signed 16 bit audio data */ + spec->format = AUDIO_S16; + shm->wFmt.wBitsPerSample = 16; + break; + default: + SDL_SetError("Unsupported audio format"); + return (-1); } shm->wFmt.wf.nChannels = spec->channels; shm->wFmt.wf.nSamplesPerSec = spec->freq; shm->wFmt.wf.nBlockAlign = - shm->wFmt.wf.nChannels * shm->wFmt.wBitsPerSample / 8; + shm->wFmt.wf.nChannels * shm->wFmt.wBitsPerSample / 8; shm->wFmt.wf.nAvgBytesPerSec = - shm->wFmt.wf.nSamplesPerSec * shm->wFmt.wf.nBlockAlign; + shm->wFmt.wf.nSamplesPerSec * shm->wFmt.wf.nBlockAlign; /* Check the buffer size -- minimum of 1/4 second (word aligned) */ - if ( spec->samples < (spec->freq/4) ) - spec->samples = ((spec->freq/4)+3)&~3; + if (spec->samples < (spec->freq / 4)) + spec->samples = ((spec->freq / 4) + 3) & ~3; /* Update the fragment size as size in bytes */ SDL_CalculateAudioSpec(spec); /* Open the audio device */ result = waveOutOpen(&(shm->sound), - WAVE_MAPPER, - &(shm->wFmt.wf), - MME_CALLBACK, - NULL, - (CALLBACK_FUNCTION|WAVE_OPEN_SHAREABLE)); - if ( result != MMSYSERR_NOERROR ) { - SetMMerror("waveOutOpen()", result); - return(-1); + WAVE_MAPPER, + &(shm->wFmt.wf), + MME_CALLBACK, + NULL, (CALLBACK_FUNCTION | WAVE_OPEN_SHAREABLE)); + if (result != MMSYSERR_NOERROR) { + SetMMerror("waveOutOpen()", result); + return (-1); } /* Create the sound buffers */ - mixbuf = (Uint8 *)mmeAllocBuffer(NUM_BUFFERS * (spec->size)); - if ( mixbuf == NULL ) { - SDL_SetError("Out of memory: mixbuf"); - return(-1); + mixbuf = (Uint8 *) mmeAllocBuffer(NUM_BUFFERS * (spec->size)); + if (mixbuf == NULL) { + SDL_SetError("Out of memory: mixbuf"); + return (-1); } for (i = 0; i < NUM_BUFFERS; i++) { - shm->wHdr[i].lpData = &mixbuf[i * (spec->size)]; - shm->wHdr[i].dwBufferLength = spec->size; - shm->wHdr[i].dwFlags = 0; - shm->wHdr[i].dwUser = i; - shm->wHdr[i].dwLoops = 0; /* loop control counter */ - shm->wHdr[i].lpNext = NULL; /* reserved for driver */ - shm->wHdr[i].reserved = 0; - inUse[i] = FALSE; + shm->wHdr[i].lpData = &mixbuf[i * (spec->size)]; + shm->wHdr[i].dwBufferLength = spec->size; + shm->wHdr[i].dwFlags = 0; + shm->wHdr[i].dwUser = i; + shm->wHdr[i].dwLoops = 0; /* loop control counter */ + shm->wHdr[i].lpNext = NULL; /* reserved for driver */ + shm->wHdr[i].reserved = 0; + inUse[i] = FALSE; } next_buffer = 0; return 0; } -static void MME_WaitAudio(_THIS) +static void +MME_WaitAudio(_THIS) { - while ( inUse[next_buffer] ) { - mmeWaitForCallbacks(); - mmeProcessCallbacks(); + while (inUse[next_buffer]) { + mmeWaitForCallbacks(); + mmeProcessCallbacks(); } } -static Uint8 *MME_GetAudioBuf(_THIS) +static Uint8 * +MME_GetAudioBuf(_THIS) { Uint8 *retval; inUse[next_buffer] = TRUE; - retval = (Uint8 *)(shm->wHdr[next_buffer].lpData); + retval = (Uint8 *) (shm->wHdr[next_buffer].lpData); return retval; } -static void MME_PlayAudio(_THIS) +static void +MME_PlayAudio(_THIS) { /* Queue it up */ waveOutWrite(shm->sound, &(shm->wHdr[next_buffer]), sizeof(WAVEHDR)); - next_buffer = (next_buffer+1)%NUM_BUFFERS; + next_buffer = (next_buffer + 1) % NUM_BUFFERS; } -static void MME_WaitDone(_THIS) +static void +MME_WaitDone(_THIS) { MMRESULT result; int i; - if ( shm->sound ) { - for (i = 0; i < NUM_BUFFERS; i++) - while ( inUse[i] ) { - mmeWaitForCallbacks(); - mmeProcessCallbacks(); - } - result = waveOutReset(shm->sound); - if ( result != MMSYSERR_NOERROR ) - SetMMerror("waveOutReset()", result); - mmeProcessCallbacks(); + if (shm->sound) { + for (i = 0; i < NUM_BUFFERS; i++) + while (inUse[i]) { + mmeWaitForCallbacks(); + mmeProcessCallbacks(); + } + result = waveOutReset(shm->sound); + if (result != MMSYSERR_NOERROR) + SetMMerror("waveOutReset()", result); + mmeProcessCallbacks(); } } -static void MME_CloseAudio(_THIS) +static void +MME_CloseAudio(_THIS) { MMRESULT result; - if ( mixbuf ) { - result = mmeFreeBuffer(mixbuf); - if (result != MMSYSERR_NOERROR ) - SetMMerror("mmeFreeBuffer", result); - mixbuf = NULL; + if (mixbuf) { + result = mmeFreeBuffer(mixbuf); + if (result != MMSYSERR_NOERROR) + SetMMerror("mmeFreeBuffer", result); + mixbuf = NULL; } - if ( shm ) { - if ( shm->sound ) { - result = waveOutClose(shm->sound); - if (result != MMSYSERR_NOERROR ) - SetMMerror("waveOutClose()", result); - mmeProcessCallbacks(); - } - result = mmeFreeMem(shm); - if (result != MMSYSERR_NOERROR ) - SetMMerror("mmeFreeMem()", result); - shm = NULL; + if (shm) { + if (shm->sound) { + result = waveOutClose(shm->sound); + if (result != MMSYSERR_NOERROR) + SetMMerror("waveOutClose()", result); + mmeProcessCallbacks(); + } + result = mmeFreeMem(shm); + if (result != MMSYSERR_NOERROR) + SetMMerror("mmeFreeMem()", result); + shm = NULL; } } +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/audio/mme/SDL_mmeaudio.h b/src/audio/mme/SDL_mmeaudio.h index 06d9d8385..3d6d86b5e 100644 --- a/src/audio/mme/SDL_mmeaudio.h +++ b/src/audio/mme/SDL_mmeaudio.h @@ -32,14 +32,16 @@ #define _THIS SDL_AudioDevice *this #define NUM_BUFFERS 2 -struct SharedMem { +struct SharedMem +{ HWAVEOUT sound; WAVEHDR wHdr[NUM_BUFFERS]; PCMWAVEFORMAT wFmt; }; -struct SDL_PrivateAudioData { - Uint8 *mixbuf; /* The raw allocated mixing buffer */ +struct SDL_PrivateAudioData +{ + Uint8 *mixbuf; /* The raw allocated mixing buffer */ struct SharedMem *shm; int next_buffer; }; @@ -49,3 +51,4 @@ struct SDL_PrivateAudioData { #define next_buffer (this->hidden->next_buffer) /* Old variable names */ #endif /* _SDL_lowaudio_h */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/audio/nas/SDL_nasaudio.c b/src/audio/nas/SDL_nasaudio.c index b5d2a3bcf..ba4cecf33 100644 --- a/src/audio/nas/SDL_nasaudio.c +++ b/src/audio/nas/SDL_nasaudio.c @@ -43,7 +43,7 @@ static struct SDL_PrivateAudioData *this2 = NULL; /* Audio driver functions */ -static int NAS_OpenAudio(_THIS, SDL_AudioSpec *spec); +static int NAS_OpenAudio(_THIS, SDL_AudioSpec * spec); static void NAS_WaitAudio(_THIS); static void NAS_PlayAudio(_THIS); static Uint8 *NAS_GetAudioBuf(_THIS); @@ -51,249 +51,264 @@ static void NAS_CloseAudio(_THIS); /* Audio driver bootstrap functions */ -static int Audio_Available(void) +static int +Audio_Available(void) { - AuServer *aud = AuOpenServer("", 0, NULL, 0, NULL, NULL); - if (!aud) return 0; + AuServer *aud = AuOpenServer("", 0, NULL, 0, NULL, NULL); + if (!aud) + return 0; - AuCloseServer(aud); - return 1; + AuCloseServer(aud); + return 1; } -static void Audio_DeleteDevice(SDL_AudioDevice *device) +static void +Audio_DeleteDevice(SDL_AudioDevice * device) { - SDL_free(device->hidden); - SDL_free(device); + SDL_free(device->hidden); + SDL_free(device); } -static SDL_AudioDevice *Audio_CreateDevice(int devindex) +static SDL_AudioDevice * +Audio_CreateDevice(int devindex) { - SDL_AudioDevice *this; - - /* Initialize all variables that we clean on shutdown */ - this = (SDL_AudioDevice *)SDL_malloc(sizeof(SDL_AudioDevice)); - if ( this ) { - SDL_memset(this, 0, (sizeof *this)); - this->hidden = (struct SDL_PrivateAudioData *) - SDL_malloc((sizeof *this->hidden)); - } - if ( (this == NULL) || (this->hidden == NULL) ) { - SDL_OutOfMemory(); - if ( this ) { - SDL_free(this); - } - return(0); - } - SDL_memset(this->hidden, 0, (sizeof *this->hidden)); - - /* Set the function pointers */ - this->OpenAudio = NAS_OpenAudio; - this->WaitAudio = NAS_WaitAudio; - this->PlayAudio = NAS_PlayAudio; - this->GetAudioBuf = NAS_GetAudioBuf; - this->CloseAudio = NAS_CloseAudio; - - this->free = Audio_DeleteDevice; - - return this; + SDL_AudioDevice *this; + + /* Initialize all variables that we clean on shutdown */ + this = (SDL_AudioDevice *) SDL_malloc(sizeof(SDL_AudioDevice)); + if (this) { + SDL_memset(this, 0, (sizeof *this)); + this->hidden = (struct SDL_PrivateAudioData *) + SDL_malloc((sizeof *this->hidden)); + } + if ((this == NULL) || (this->hidden == NULL)) { + SDL_OutOfMemory(); + if (this) { + SDL_free(this); + } + return (0); + } + SDL_memset(this->hidden, 0, (sizeof *this->hidden)); + + /* Set the function pointers */ + this->OpenAudio = NAS_OpenAudio; + this->WaitAudio = NAS_WaitAudio; + this->PlayAudio = NAS_PlayAudio; + this->GetAudioBuf = NAS_GetAudioBuf; + this->CloseAudio = NAS_CloseAudio; + + this->free = Audio_DeleteDevice; + + return this; } AudioBootStrap NAS_bootstrap = { - NAS_DRIVER_NAME, "Network Audio System", - Audio_Available, Audio_CreateDevice + NAS_DRIVER_NAME, "Network Audio System", + Audio_Available, Audio_CreateDevice }; /* This function waits until it is possible to write a full sound buffer */ -static void NAS_WaitAudio(_THIS) +static void +NAS_WaitAudio(_THIS) { - while ( this->hidden->buf_free < this->hidden->mixlen ) { - AuEvent ev; - AuNextEvent(this->hidden->aud, AuTrue, &ev); - AuDispatchEvent(this->hidden->aud, &ev); - } + while (this->hidden->buf_free < this->hidden->mixlen) { + AuEvent ev; + AuNextEvent(this->hidden->aud, AuTrue, &ev); + AuDispatchEvent(this->hidden->aud, &ev); + } } -static void NAS_PlayAudio(_THIS) +static void +NAS_PlayAudio(_THIS) { - while (this->hidden->mixlen > this->hidden->buf_free) { /* We think the buffer is full? Yikes! Ask the server for events, - in the hope that some of them is LowWater events telling us more - of the buffer is free now than what we think. */ - AuEvent ev; - AuNextEvent(this->hidden->aud, AuTrue, &ev); - AuDispatchEvent(this->hidden->aud, &ev); - } - this->hidden->buf_free -= this->hidden->mixlen; - - /* Write the audio data */ - AuWriteElement(this->hidden->aud, this->hidden->flow, 0, this->hidden->mixlen, this->hidden->mixbuf, AuFalse, NULL); - - this->hidden->written += this->hidden->mixlen; - + while (this->hidden->mixlen > this->hidden->buf_free) { /* We think the buffer is full? Yikes! Ask the server for events, + in the hope that some of them is LowWater events telling us more + of the buffer is free now than what we think. */ + AuEvent ev; + AuNextEvent(this->hidden->aud, AuTrue, &ev); + AuDispatchEvent(this->hidden->aud, &ev); + } + this->hidden->buf_free -= this->hidden->mixlen; + + /* Write the audio data */ + AuWriteElement(this->hidden->aud, this->hidden->flow, 0, + this->hidden->mixlen, this->hidden->mixbuf, AuFalse, NULL); + + this->hidden->written += this->hidden->mixlen; + #ifdef DEBUG_AUDIO - fprintf(stderr, "Wrote %d bytes of audio data\n", this->hidden->mixlen); + fprintf(stderr, "Wrote %d bytes of audio data\n", this->hidden->mixlen); #endif } -static Uint8 *NAS_GetAudioBuf(_THIS) +static Uint8 * +NAS_GetAudioBuf(_THIS) { - return(this->hidden->mixbuf); + return (this->hidden->mixbuf); } -static void NAS_CloseAudio(_THIS) +static void +NAS_CloseAudio(_THIS) { - if ( this->hidden->mixbuf != NULL ) { - SDL_FreeAudioMem(this->hidden->mixbuf); - this->hidden->mixbuf = NULL; - } - if ( this->hidden->aud ) { - AuCloseServer(this->hidden->aud); - this->hidden->aud = 0; - } + if (this->hidden->mixbuf != NULL) { + SDL_FreeAudioMem(this->hidden->mixbuf); + this->hidden->mixbuf = NULL; + } + if (this->hidden->aud) { + AuCloseServer(this->hidden->aud); + this->hidden->aud = 0; + } } -static unsigned char sdlformat_to_auformat(unsigned int fmt) +static unsigned char +sdlformat_to_auformat(unsigned int fmt) { - switch (fmt) - { + switch (fmt) { case AUDIO_U8: - return AuFormatLinearUnsigned8; + return AuFormatLinearUnsigned8; case AUDIO_S8: - return AuFormatLinearSigned8; + return AuFormatLinearSigned8; case AUDIO_U16LSB: - return AuFormatLinearUnsigned16LSB; + return AuFormatLinearUnsigned16LSB; case AUDIO_U16MSB: - return AuFormatLinearUnsigned16MSB; + return AuFormatLinearUnsigned16MSB; case AUDIO_S16LSB: - return AuFormatLinearSigned16LSB; + return AuFormatLinearSigned16LSB; case AUDIO_S16MSB: - return AuFormatLinearSigned16MSB; + return AuFormatLinearSigned16MSB; } - return AuNone; + return AuNone; } static AuBool -event_handler(AuServer* aud, AuEvent* ev, AuEventHandlerRec* hnd) +event_handler(AuServer * aud, AuEvent * ev, AuEventHandlerRec * hnd) { - switch (ev->type) { - case AuEventTypeElementNotify: { - AuElementNotifyEvent* event = (AuElementNotifyEvent *)ev; - - switch (event->kind) { - case AuElementNotifyKindLowWater: - if (this2->buf_free >= 0) { - this2->really += event->num_bytes; - gettimeofday(&this2->last_tv, 0); - this2->buf_free += event->num_bytes; - } else { - this2->buf_free = event->num_bytes; - } - break; - case AuElementNotifyKindState: - switch (event->cur_state) { - case AuStatePause: - if (event->reason != AuReasonUser) { - if (this2->buf_free >= 0) { - this2->really += event->num_bytes; - gettimeofday(&this2->last_tv, 0); - this2->buf_free += event->num_bytes; - } else { - this2->buf_free = event->num_bytes; - } - } - break; - } - } - } - } - return AuTrue; + switch (ev->type) { + case AuEventTypeElementNotify: + { + AuElementNotifyEvent *event = (AuElementNotifyEvent *) ev; + + switch (event->kind) { + case AuElementNotifyKindLowWater: + if (this2->buf_free >= 0) { + this2->really += event->num_bytes; + gettimeofday(&this2->last_tv, 0); + this2->buf_free += event->num_bytes; + } else { + this2->buf_free = event->num_bytes; + } + break; + case AuElementNotifyKindState: + switch (event->cur_state) { + case AuStatePause: + if (event->reason != AuReasonUser) { + if (this2->buf_free >= 0) { + this2->really += event->num_bytes; + gettimeofday(&this2->last_tv, 0); + this2->buf_free += event->num_bytes; + } else { + this2->buf_free = event->num_bytes; + } + } + break; + } + } + } + } + return AuTrue; } static AuDeviceID find_device(_THIS, int nch) { - int i; - for (i = 0; i < AuServerNumDevices(this->hidden->aud); i++) { - if ((AuDeviceKind(AuServerDevice(this->hidden->aud, i)) == - AuComponentKindPhysicalOutput) && - AuDeviceNumTracks(AuServerDevice(this->hidden->aud, i)) == nch) { - return AuDeviceIdentifier(AuServerDevice(this->hidden->aud, i)); - } - } - return AuNone; + int i; + for (i = 0; i < AuServerNumDevices(this->hidden->aud); i++) { + if ((AuDeviceKind(AuServerDevice(this->hidden->aud, i)) == + AuComponentKindPhysicalOutput) && + AuDeviceNumTracks(AuServerDevice(this->hidden->aud, i)) == nch) { + return AuDeviceIdentifier(AuServerDevice(this->hidden->aud, i)); + } + } + return AuNone; } -static int NAS_OpenAudio(_THIS, SDL_AudioSpec *spec) +static int +NAS_OpenAudio(_THIS, SDL_AudioSpec * spec) { - AuElement elms[3]; - int buffer_size; - Uint16 test_format, format; - - this->hidden->mixbuf = NULL; - - /* Try for a closest match on audio format */ - format = 0; - for ( test_format = SDL_FirstAudioFormat(spec->format); - ! format && test_format; ) { - format = sdlformat_to_auformat(test_format); - - if (format == AuNone) { - test_format = SDL_NextAudioFormat(); - } - } - if ( format == 0 ) { - SDL_SetError("Couldn't find any hardware audio formats"); - return(-1); - } - spec->format = test_format; - - this->hidden->aud = AuOpenServer("", 0, NULL, 0, NULL, NULL); - if (this->hidden->aud == 0) - { - SDL_SetError("Couldn't open connection to NAS server"); - return (-1); - } - - this->hidden->dev = find_device(this, spec->channels); - if ((this->hidden->dev == AuNone) || (!(this->hidden->flow = AuCreateFlow(this->hidden->aud, NULL)))) { - AuCloseServer(this->hidden->aud); - this->hidden->aud = 0; - SDL_SetError("Couldn't find a fitting playback device on NAS server"); - return (-1); - } - - buffer_size = spec->freq; - if (buffer_size < 4096) - buffer_size = 4096; - - if (buffer_size > 32768) - buffer_size = 32768; /* So that the buffer won't get unmanageably big. */ - - /* Calculate the final parameters for this audio specification */ - SDL_CalculateAudioSpec(spec); - - this2 = this->hidden; - - AuMakeElementImportClient(elms, spec->freq, format, spec->channels, AuTrue, - buffer_size, buffer_size / 4, 0, NULL); - AuMakeElementExportDevice(elms+1, 0, this->hidden->dev, spec->freq, - AuUnlimitedSamples, 0, NULL); - AuSetElements(this->hidden->aud, this->hidden->flow, AuTrue, 2, elms, NULL); - AuRegisterEventHandler(this->hidden->aud, AuEventHandlerIDMask, 0, this->hidden->flow, - event_handler, (AuPointer) NULL); - - AuStartFlow(this->hidden->aud, this->hidden->flow, NULL); - - /* Allocate mixing buffer */ - this->hidden->mixlen = spec->size; - this->hidden->mixbuf = (Uint8 *)SDL_AllocAudioMem(this->hidden->mixlen); - if ( this->hidden->mixbuf == NULL ) { - return(-1); - } - SDL_memset(this->hidden->mixbuf, spec->silence, spec->size); - - /* Get the parent process id (we're the parent of the audio thread) */ - this->hidden->parent = getpid(); - - /* We're ready to rock and roll. :-) */ - return(0); + AuElement elms[3]; + int buffer_size; + Uint16 test_format, format; + + this->hidden->mixbuf = NULL; + + /* Try for a closest match on audio format */ + format = 0; + for (test_format = SDL_FirstAudioFormat(spec->format); + !format && test_format;) { + format = sdlformat_to_auformat(test_format); + + if (format == AuNone) { + test_format = SDL_NextAudioFormat(); + } + } + if (format == 0) { + SDL_SetError("Couldn't find any hardware audio formats"); + return (-1); + } + spec->format = test_format; + + this->hidden->aud = AuOpenServer("", 0, NULL, 0, NULL, NULL); + if (this->hidden->aud == 0) { + SDL_SetError("Couldn't open connection to NAS server"); + return (-1); + } + + this->hidden->dev = find_device(this, spec->channels); + if ((this->hidden->dev == AuNone) + || (!(this->hidden->flow = AuCreateFlow(this->hidden->aud, NULL)))) { + AuCloseServer(this->hidden->aud); + this->hidden->aud = 0; + SDL_SetError("Couldn't find a fitting playback device on NAS server"); + return (-1); + } + + buffer_size = spec->freq; + if (buffer_size < 4096) + buffer_size = 4096; + + if (buffer_size > 32768) + buffer_size = 32768; /* So that the buffer won't get unmanageably big. */ + + /* Calculate the final parameters for this audio specification */ + SDL_CalculateAudioSpec(spec); + + this2 = this->hidden; + + AuMakeElementImportClient(elms, spec->freq, format, spec->channels, + AuTrue, buffer_size, buffer_size / 4, 0, NULL); + AuMakeElementExportDevice(elms + 1, 0, this->hidden->dev, spec->freq, + AuUnlimitedSamples, 0, NULL); + AuSetElements(this->hidden->aud, this->hidden->flow, AuTrue, 2, elms, + NULL); + AuRegisterEventHandler(this->hidden->aud, AuEventHandlerIDMask, 0, + this->hidden->flow, event_handler, + (AuPointer) NULL); + + AuStartFlow(this->hidden->aud, this->hidden->flow, NULL); + + /* Allocate mixing buffer */ + this->hidden->mixlen = spec->size; + this->hidden->mixbuf = (Uint8 *) SDL_AllocAudioMem(this->hidden->mixlen); + if (this->hidden->mixbuf == NULL) { + return (-1); + } + SDL_memset(this->hidden->mixbuf, spec->silence, spec->size); + + /* Get the parent process id (we're the parent of the audio thread) */ + this->hidden->parent = getpid(); + + /* We're ready to rock and roll. :-) */ + return (0); } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/audio/nas/SDL_nasaudio.h b/src/audio/nas/SDL_nasaudio.h index 390d6698b..fc1c73d92 100644 --- a/src/audio/nas/SDL_nasaudio.h +++ b/src/audio/nas/SDL_nasaudio.h @@ -40,23 +40,24 @@ /* Hidden "this" pointer for the video functions */ #define _THIS SDL_AudioDevice *this -struct SDL_PrivateAudioData { - AuServer* aud; - AuFlowID flow; - AuDeviceID dev; - - /* The parent process id, to detect when application quits */ - pid_t parent; - - /* Raw mixing buffer */ - Uint8 *mixbuf; - int mixlen; - - int written; - int really; - int bps; - struct timeval last_tv; - int buf_free; +struct SDL_PrivateAudioData +{ + AuServer *aud; + AuFlowID flow; + AuDeviceID dev; + + /* The parent process id, to detect when application quits */ + pid_t parent; + + /* Raw mixing buffer */ + Uint8 *mixbuf; + int mixlen; + + int written; + int really; + int bps; + struct timeval last_tv; + int buf_free; }; #endif /* _SDL_nasaudio_h */ - +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/audio/nto/SDL_nto_audio.c b/src/audio/nto/SDL_nto_audio.c index db86bae27..ee97f0cdb 100644 --- a/src/audio/nto/SDL_nto_audio.c +++ b/src/audio/nto/SDL_nto_audio.c @@ -57,72 +57,70 @@ struct BuggyCards { - char* cardname; - unsigned long bugtype; + char *cardname; + unsigned long bugtype; }; #define QSA_WA_CARDS 3 -struct BuggyCards buggycards[QSA_WA_CARDS]= -{ - {"Sound Blaster Live!", QSA_MMAP_WORKAROUND}, - {"Vortex 8820", QSA_MMAP_WORKAROUND}, - {"Vortex 8830", QSA_MMAP_WORKAROUND}, +struct BuggyCards buggycards[QSA_WA_CARDS] = { + {"Sound Blaster Live!", QSA_MMAP_WORKAROUND}, + {"Vortex 8820", QSA_MMAP_WORKAROUND}, + {"Vortex 8830", QSA_MMAP_WORKAROUND}, }; /* Audio driver functions */ static void NTO_ThreadInit(_THIS); -static int NTO_OpenAudio(_THIS, SDL_AudioSpec* spec); +static int NTO_OpenAudio(_THIS, SDL_AudioSpec * spec); static void NTO_WaitAudio(_THIS); static void NTO_PlayAudio(_THIS); -static Uint8* NTO_GetAudioBuf(_THIS); +static Uint8 *NTO_GetAudioBuf(_THIS); static void NTO_CloseAudio(_THIS); /* card names check to apply the workarounds */ -static int NTO_CheckBuggyCards(_THIS, unsigned long checkfor) +static int +NTO_CheckBuggyCards(_THIS, unsigned long checkfor) { char scardname[33]; int it; - - if (snd_card_get_name(cardno, scardname, 32)<0) - { + + if (snd_card_get_name(cardno, scardname, 32) < 0) { return 0; } - for (it=0; itchannel = SND_PCM_CHANNEL_PLAYBACK; cpars->mode = SND_PCM_MODE_BLOCK; cpars->start_mode = SND_PCM_START_DATA; - cpars->stop_mode = SND_PCM_STOP_STOP; + cpars->stop_mode = SND_PCM_STOP_STOP; cpars->format.format = SND_PCM_SFMT_S16_LE; cpars->format.interleave = 1; cpars->format.rate = DEFAULT_CPARAMS_RATE; @@ -132,69 +130,67 @@ static void NTO_InitAudioParams(snd_pcm_channel_params_t* cpars) cpars->buf.block.frags_max = DEFAULT_CPARAMS_FRAGS_MAX; } -static int NTO_AudioAvailable(void) +static int +NTO_AudioAvailable(void) { /* See if we can open a nonblocking channel. - Return value '1' means we can. - Return value '0' means we cannot. */ + Return value '1' means we can. + Return value '0' means we cannot. */ int available; int rval; - snd_pcm_t* handle; + snd_pcm_t *handle; available = 0; handle = NULL; rval = snd_pcm_open_preferred(&handle, NULL, NULL, OPEN_FLAGS); - if (rval >= 0) - { + if (rval >= 0) { available = 1; - if ((rval = snd_pcm_close(handle)) < 0) - { - SDL_SetError("NTO_AudioAvailable(): snd_pcm_close failed: %s\n", snd_strerror(rval)); + if ((rval = snd_pcm_close(handle)) < 0) { + SDL_SetError + ("NTO_AudioAvailable(): snd_pcm_close failed: %s\n", + snd_strerror(rval)); available = 0; } - } - else - { - SDL_SetError("NTO_AudioAvailable(): there are no available audio devices.\n"); + } else { + SDL_SetError + ("NTO_AudioAvailable(): there are no available audio devices.\n"); } return (available); } -static void NTO_DeleteAudioDevice(SDL_AudioDevice *device) +static void +NTO_DeleteAudioDevice(SDL_AudioDevice * device) { - if ((device)&&(device->hidden)) - { + if ((device) && (device->hidden)) { SDL_free(device->hidden); } - if (device) - { + if (device) { SDL_free(device); } } -static SDL_AudioDevice* NTO_CreateAudioDevice(int devindex) +static SDL_AudioDevice * +NTO_CreateAudioDevice(int devindex) { SDL_AudioDevice *this; /* Initialize all variables that we clean on shutdown */ - this = (SDL_AudioDevice *)SDL_malloc(sizeof(SDL_AudioDevice)); - if (this) - { + this = (SDL_AudioDevice *) SDL_malloc(sizeof(SDL_AudioDevice)); + if (this) { SDL_memset(this, 0, sizeof(SDL_AudioDevice)); - this->hidden = (struct SDL_PrivateAudioData *)SDL_malloc(sizeof(struct SDL_PrivateAudioData)); + this->hidden = (struct SDL_PrivateAudioData *) + SDL_malloc(sizeof(struct SDL_PrivateAudioData)); } - if ((this == NULL) || (this->hidden == NULL)) - { + if ((this == NULL) || (this->hidden == NULL)) { SDL_OutOfMemory(); - if (this) - { + if (this) { SDL_free(this); - } + } return (0); } SDL_memset(this->hidden, 0, sizeof(struct SDL_PrivateAudioData)); @@ -213,15 +209,15 @@ static SDL_AudioDevice* NTO_CreateAudioDevice(int devindex) return this; } -AudioBootStrap QNXNTOAUDIO_bootstrap = -{ +AudioBootStrap QNXNTOAUDIO_bootstrap = { DRIVER_NAME, "QNX6 QSA-NTO Audio", NTO_AudioAvailable, NTO_CreateAudioDevice }; /* This function waits until it is possible to write a full sound buffer */ -static void NTO_WaitAudio(_THIS) +static void +NTO_WaitAudio(_THIS) { fd_set wfds; int selectret; @@ -230,121 +226,125 @@ static void NTO_WaitAudio(_THIS) FD_SET(audio_fd, &wfds); do { - selectret=select(audio_fd + 1, NULL, &wfds, NULL, NULL); - switch (selectret) - { - case -1: - case 0: SDL_SetError("NTO_WaitAudio(): select() failed: %s\n", strerror(errno)); - return; - default: if (FD_ISSET(audio_fd, &wfds)) - { - return; - } - break; + selectret = select(audio_fd + 1, NULL, &wfds, NULL, NULL); + switch (selectret) { + case -1: + case 0: + SDL_SetError("NTO_WaitAudio(): select() failed: %s\n", + strerror(errno)); + return; + default: + if (FD_ISSET(audio_fd, &wfds)) { + return; + } + break; } - } while(1); + } + while (1); } -static void NTO_PlayAudio(_THIS) +static void +NTO_PlayAudio(_THIS) { int written, rval; int towrite; - void* pcmbuffer; + void *pcmbuffer; - if (!this->enabled) - { + if (!this->enabled) { return; } - + towrite = this->spec.size; pcmbuffer = pcm_buf; /* Write the audio data, checking for EAGAIN (buffer full) and underrun */ do { written = snd_pcm_plugin_write(audio_handle, pcm_buf, towrite); - if (written != towrite) - { - if ((errno == EAGAIN) || (errno == EWOULDBLOCK)) - { + if (written != towrite) { + if ((errno == EAGAIN) || (errno == EWOULDBLOCK)) { /* Let a little CPU time go by and try to write again */ SDL_Delay(1); /* if we wrote some data */ towrite -= written; pcmbuffer += written * this->spec.channels; continue; - } - else - { - if ((errno == EINVAL) || (errno == EIO)) - { + } else { + if ((errno == EINVAL) || (errno == EIO)) { SDL_memset(&cstatus, 0, sizeof(cstatus)); cstatus.channel = SND_PCM_CHANNEL_PLAYBACK; - if ((rval = snd_pcm_plugin_status(audio_handle, &cstatus)) < 0) - { - SDL_SetError("NTO_PlayAudio(): snd_pcm_plugin_status failed: %s\n", snd_strerror(rval)); + if ((rval = + snd_pcm_plugin_status(audio_handle, &cstatus)) < 0) { + SDL_SetError + ("NTO_PlayAudio(): snd_pcm_plugin_status failed: %s\n", + snd_strerror(rval)); return; - } - if ((cstatus.status == SND_PCM_STATUS_UNDERRUN) || (cstatus.status == SND_PCM_STATUS_READY)) - { - if ((rval = snd_pcm_plugin_prepare(audio_handle, SND_PCM_CHANNEL_PLAYBACK)) < 0) - { - SDL_SetError("NTO_PlayAudio(): snd_pcm_plugin_prepare failed: %s\n", snd_strerror(rval)); + } + if ((cstatus.status == SND_PCM_STATUS_UNDERRUN) + || (cstatus.status == SND_PCM_STATUS_READY)) { + if ((rval = + snd_pcm_plugin_prepare(audio_handle, + SND_PCM_CHANNEL_PLAYBACK)) + < 0) { + SDL_SetError + ("NTO_PlayAudio(): snd_pcm_plugin_prepare failed: %s\n", + snd_strerror(rval)); return; } - } + } continue; - } - else - { + } else { return; } } - } - else - { + } else { /* we wrote all remaining data */ towrite -= written; pcmbuffer += written * this->spec.channels; } - } while ((towrite > 0) && (this->enabled)); + } + while ((towrite > 0) && (this->enabled)); /* If we couldn't write, assume fatal error for now */ - if (towrite != 0) - { + if (towrite != 0) { this->enabled = 0; } return; } -static Uint8* NTO_GetAudioBuf(_THIS) +static Uint8 * +NTO_GetAudioBuf(_THIS) { return pcm_buf; } -static void NTO_CloseAudio(_THIS) +static void +NTO_CloseAudio(_THIS) { int rval; this->enabled = 0; - if (audio_handle != NULL) - { - if ((rval = snd_pcm_plugin_flush(audio_handle, SND_PCM_CHANNEL_PLAYBACK)) < 0) - { - SDL_SetError("NTO_CloseAudio(): snd_pcm_plugin_flush failed: %s\n", snd_strerror(rval)); + if (audio_handle != NULL) { + if ((rval = + snd_pcm_plugin_flush(audio_handle, + SND_PCM_CHANNEL_PLAYBACK)) < 0) { + SDL_SetError + ("NTO_CloseAudio(): snd_pcm_plugin_flush failed: %s\n", + snd_strerror(rval)); return; } - if ((rval = snd_pcm_close(audio_handle)) < 0) - { - SDL_SetError("NTO_CloseAudio(): snd_pcm_close failed: %s\n",snd_strerror(rval)); + if ((rval = snd_pcm_close(audio_handle)) < 0) { + SDL_SetError("NTO_CloseAudio(): snd_pcm_close failed: %s\n", + snd_strerror(rval)); return; } audio_handle = NULL; } } -static int NTO_OpenAudio(_THIS, SDL_AudioSpec* spec) +static int +NTO_OpenAudio(_THIS, SDL_AudioSpec * spec) { int rval; int format; @@ -354,9 +354,8 @@ static int NTO_OpenAudio(_THIS, SDL_AudioSpec* spec) audio_handle = NULL; this->enabled = 0; - if (pcm_buf != NULL) - { - SDL_FreeAudioMem(pcm_buf); + if (pcm_buf != NULL) { + SDL_FreeAudioMem(pcm_buf); pcm_buf = NULL; } @@ -364,19 +363,21 @@ static int NTO_OpenAudio(_THIS, SDL_AudioSpec* spec) NTO_InitAudioParams(&cparams); /* Open the audio device */ - rval = snd_pcm_open_preferred(&audio_handle, &cardno, &deviceno, OPEN_FLAGS); - if (rval < 0) - { - SDL_SetError("NTO_OpenAudio(): snd_pcm_open failed: %s\n", snd_strerror(rval)); + rval = + snd_pcm_open_preferred(&audio_handle, &cardno, &deviceno, OPEN_FLAGS); + if (rval < 0) { + SDL_SetError("NTO_OpenAudio(): snd_pcm_open failed: %s\n", + snd_strerror(rval)); return (-1); } - if (!NTO_CheckBuggyCards(this, QSA_MMAP_WORKAROUND)) - { + if (!NTO_CheckBuggyCards(this, QSA_MMAP_WORKAROUND)) { /* enable count status parameter */ - if ((rval = snd_pcm_plugin_set_disable(audio_handle, PLUGIN_DISABLE_MMAP)) < 0) - { - SDL_SetError("snd_pcm_plugin_set_disable failed: %s\n", snd_strerror(rval)); + if ((rval = + snd_pcm_plugin_set_disable(audio_handle, + PLUGIN_DISABLE_MMAP)) < 0) { + SDL_SetError("snd_pcm_plugin_set_disable failed: %s\n", + snd_strerror(rval)); return (-1); } } @@ -386,49 +387,46 @@ static int NTO_OpenAudio(_THIS, SDL_AudioSpec* spec) /* can't use format as SND_PCM_SFMT_U8 = 0 in nto */ found = 0; - for (test_format=SDL_FirstAudioFormat(spec->format); !found ;) - { + for (test_format = SDL_FirstAudioFormat(spec->format); !found;) { /* if match found set format to equivalent ALSA format */ - switch (test_format) - { - case AUDIO_U8: - format = SND_PCM_SFMT_U8; - found = 1; - break; - case AUDIO_S8: - format = SND_PCM_SFMT_S8; - found = 1; - break; - case AUDIO_S16LSB: - format = SND_PCM_SFMT_S16_LE; - found = 1; - break; - case AUDIO_S16MSB: - format = SND_PCM_SFMT_S16_BE; - found = 1; - break; - case AUDIO_U16LSB: - format = SND_PCM_SFMT_U16_LE; - found = 1; - break; - case AUDIO_U16MSB: - format = SND_PCM_SFMT_U16_BE; - found = 1; - break; - default: - break; + switch (test_format) { + case AUDIO_U8: + format = SND_PCM_SFMT_U8; + found = 1; + break; + case AUDIO_S8: + format = SND_PCM_SFMT_S8; + found = 1; + break; + case AUDIO_S16LSB: + format = SND_PCM_SFMT_S16_LE; + found = 1; + break; + case AUDIO_S16MSB: + format = SND_PCM_SFMT_S16_BE; + found = 1; + break; + case AUDIO_U16LSB: + format = SND_PCM_SFMT_U16_LE; + found = 1; + break; + case AUDIO_U16MSB: + format = SND_PCM_SFMT_U16_BE; + found = 1; + break; + default: + break; } - if (!found) - { + if (!found) { test_format = SDL_NextAudioFormat(); } } /* assumes test_format not 0 on success */ - if (test_format == 0) - { - SDL_SetError("NTO_OpenAudio(): Couldn't find any hardware audio formats"); + if (test_format == 0) { + SDL_SetError + ("NTO_OpenAudio(): Couldn't find any hardware audio formats"); return (-1); } @@ -439,23 +437,23 @@ static int NTO_OpenAudio(_THIS, SDL_AudioSpec* spec) /* Set mono or stereo audio (currently only two channels supported) */ cparams.format.voices = spec->channels; - + /* Set rate */ cparams.format.rate = spec->freq; /* Setup the transfer parameters according to cparams */ rval = snd_pcm_plugin_params(audio_handle, &cparams); - if (rval < 0) - { - SDL_SetError("NTO_OpenAudio(): snd_pcm_channel_params failed: %s\n", snd_strerror(rval)); + if (rval < 0) { + SDL_SetError + ("NTO_OpenAudio(): snd_pcm_channel_params failed: %s\n", + snd_strerror(rval)); return (-1); } /* Make sure channel is setup right one last time */ SDL_memset(&csetup, 0x00, sizeof(csetup)); csetup.channel = SND_PCM_CHANNEL_PLAYBACK; - if (snd_pcm_plugin_setup(audio_handle, &csetup) < 0) - { + if (snd_pcm_plugin_setup(audio_handle, &csetup) < 0) { SDL_SetError("NTO_OpenAudio(): Unable to setup playback channel\n"); return -1; } @@ -466,34 +464,37 @@ static int NTO_OpenAudio(_THIS, SDL_AudioSpec* spec) pcm_len = spec->size; - if (pcm_len==0) - { - pcm_len = csetup.buf.block.frag_size * spec->channels * (snd_pcm_format_width(format)/8); + if (pcm_len == 0) { + pcm_len = + csetup.buf.block.frag_size * spec->channels * + (snd_pcm_format_width(format) / 8); } /* Allocate memory to the audio buffer and initialize with silence (Note that buffer size must be a multiple of fragment size, so find closest multiple) - */ - pcm_buf = (Uint8*)SDL_AllocAudioMem(pcm_len); - if (pcm_buf == NULL) - { + */ + pcm_buf = (Uint8 *) SDL_AllocAudioMem(pcm_len); + if (pcm_buf == NULL) { SDL_SetError("NTO_OpenAudio(): pcm buffer allocation failed\n"); return (-1); } SDL_memset(pcm_buf, spec->silence, pcm_len); /* get the file descriptor */ - if ((audio_fd = snd_pcm_file_descriptor(audio_handle, SND_PCM_CHANNEL_PLAYBACK)) < 0) - { - SDL_SetError("NTO_OpenAudio(): snd_pcm_file_descriptor failed with error code: %s\n", snd_strerror(rval)); + if ((audio_fd = + snd_pcm_file_descriptor(audio_handle, + SND_PCM_CHANNEL_PLAYBACK)) < 0) { + SDL_SetError + ("NTO_OpenAudio(): snd_pcm_file_descriptor failed with error code: %s\n", + snd_strerror(rval)); return (-1); } /* Trigger audio playback */ rval = snd_pcm_plugin_prepare(audio_handle, SND_PCM_CHANNEL_PLAYBACK); - if (rval < 0) - { - SDL_SetError("snd_pcm_plugin_prepare failed: %s\n", snd_strerror(rval)); + if (rval < 0) { + SDL_SetError("snd_pcm_plugin_prepare failed: %s\n", + snd_strerror(rval)); return (-1); } @@ -505,3 +506,5 @@ static int NTO_OpenAudio(_THIS, SDL_AudioSpec* spec) /* We're really ready to rock and roll. :-) */ return (0); } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/audio/nto/SDL_nto_audio.h b/src/audio/nto/SDL_nto_audio.h index 14fd00d47..ed4a8b25b 100644 --- a/src/audio/nto/SDL_nto_audio.h +++ b/src/audio/nto/SDL_nto_audio.h @@ -36,7 +36,7 @@ struct SDL_PrivateAudioData /* The audio device handle */ int cardno; int deviceno; - snd_pcm_t* audio_handle; + snd_pcm_t *audio_handle; /* The audio file descriptor */ int audio_fd; @@ -45,13 +45,13 @@ struct SDL_PrivateAudioData pid_t parent; /* Raw mixing buffer */ - Uint8* pcm_buf; + Uint8 *pcm_buf; Uint32 pcm_len; /* QSA parameters */ snd_pcm_channel_status_t cstatus; snd_pcm_channel_params_t cparams; - snd_pcm_channel_setup_t csetup; + snd_pcm_channel_setup_t csetup; }; #define cardno (this->hidden->cardno) @@ -66,3 +66,4 @@ struct SDL_PrivateAudioData #define csetup (this->hidden->csetup) #endif /* __SDL_NTO_AUDIO_H__ */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/audio/paudio/SDL_paudio.c b/src/audio/paudio/SDL_paudio.c index 7b07b5981..5276426f4 100644 --- a/src/audio/paudio/SDL_paudio.c +++ b/src/audio/paudio/SDL_paudio.c @@ -55,7 +55,7 @@ #define OPEN_FLAGS O_WRONLY /* Audio driver functions */ -static int Paud_OpenAudio(_THIS, SDL_AudioSpec *spec); +static int Paud_OpenAudio(_THIS, SDL_AudioSpec * spec); static void Paud_WaitAudio(_THIS); static void Paud_PlayAudio(_THIS); static Uint8 *Paud_GetAudioBuf(_THIS); @@ -63,112 +63,116 @@ static void Paud_CloseAudio(_THIS); /* Audio driver bootstrap functions */ -static int Audio_Available(void) +static int +Audio_Available(void) { - int fd; - int available; - - available = 0; - fd = SDL_OpenAudioPath(NULL, 0, OPEN_FLAGS, 0); - if ( fd >= 0 ) { - available = 1; - close(fd); - } - return(available); + int fd; + int available; + + available = 0; + fd = SDL_OpenAudioPath(NULL, 0, OPEN_FLAGS, 0); + if (fd >= 0) { + available = 1; + close(fd); + } + return (available); } -static void Audio_DeleteDevice(SDL_AudioDevice *device) +static void +Audio_DeleteDevice(SDL_AudioDevice * device) { - SDL_free(device->hidden); - SDL_free(device); + SDL_free(device->hidden); + SDL_free(device); } -static SDL_AudioDevice *Audio_CreateDevice(int devindex) +static SDL_AudioDevice * +Audio_CreateDevice(int devindex) { - SDL_AudioDevice *this; - - /* Initialize all variables that we clean on shutdown */ - this = (SDL_AudioDevice *)SDL_malloc(sizeof(SDL_AudioDevice)); - if ( this ) { - SDL_memset(this, 0, (sizeof *this)); - this->hidden = (struct SDL_PrivateAudioData *) - SDL_malloc((sizeof *this->hidden)); - } - if ( (this == NULL) || (this->hidden == NULL) ) { - SDL_OutOfMemory(); - if ( this ) { - SDL_free(this); - } - return(0); - } - SDL_memset(this->hidden, 0, (sizeof *this->hidden)); - audio_fd = -1; - - /* Set the function pointers */ - this->OpenAudio = Paud_OpenAudio; - this->WaitAudio = Paud_WaitAudio; - this->PlayAudio = Paud_PlayAudio; - this->GetAudioBuf = Paud_GetAudioBuf; - this->CloseAudio = Paud_CloseAudio; - - this->free = Audio_DeleteDevice; - - return this; + SDL_AudioDevice *this; + + /* Initialize all variables that we clean on shutdown */ + this = (SDL_AudioDevice *) SDL_malloc(sizeof(SDL_AudioDevice)); + if (this) { + SDL_memset(this, 0, (sizeof *this)); + this->hidden = (struct SDL_PrivateAudioData *) + SDL_malloc((sizeof *this->hidden)); + } + if ((this == NULL) || (this->hidden == NULL)) { + SDL_OutOfMemory(); + if (this) { + SDL_free(this); + } + return (0); + } + SDL_memset(this->hidden, 0, (sizeof *this->hidden)); + audio_fd = -1; + + /* Set the function pointers */ + this->OpenAudio = Paud_OpenAudio; + this->WaitAudio = Paud_WaitAudio; + this->PlayAudio = Paud_PlayAudio; + this->GetAudioBuf = Paud_GetAudioBuf; + this->CloseAudio = Paud_CloseAudio; + + this->free = Audio_DeleteDevice; + + return this; } AudioBootStrap Paud_bootstrap = { - Paud_DRIVER_NAME, "AIX Paudio", - Audio_Available, Audio_CreateDevice + Paud_DRIVER_NAME, "AIX Paudio", + Audio_Available, Audio_CreateDevice }; /* This function waits until it is possible to write a full sound buffer */ -static void Paud_WaitAudio(_THIS) +static void +Paud_WaitAudio(_THIS) { fd_set fdset; /* See if we need to use timed audio synchronization */ - if ( frame_ticks ) { + if (frame_ticks) { /* Use timer for general audio synchronization */ Sint32 ticks; - ticks = ((Sint32)(next_frame - SDL_GetTicks()))-FUDGE_TICKS; - if ( ticks > 0 ) { - SDL_Delay(ticks); + ticks = ((Sint32) (next_frame - SDL_GetTicks())) - FUDGE_TICKS; + if (ticks > 0) { + SDL_Delay(ticks); } } else { - audio_buffer paud_bufinfo; + audio_buffer paud_bufinfo; /* Use select() for audio synchronization */ struct timeval timeout; FD_ZERO(&fdset); FD_SET(audio_fd, &fdset); - if ( ioctl(audio_fd, AUDIO_BUFFER, &paud_bufinfo) < 0 ) { + if (ioctl(audio_fd, AUDIO_BUFFER, &paud_bufinfo) < 0) { #ifdef DEBUG_AUDIO fprintf(stderr, "Couldn't get audio buffer information\n"); #endif - timeout.tv_sec = 10; + timeout.tv_sec = 10; timeout.tv_usec = 0; } else { - long ms_in_buf = paud_bufinfo.write_buf_time; - timeout.tv_sec = ms_in_buf/1000; - ms_in_buf = ms_in_buf - timeout.tv_sec*1000; - timeout.tv_usec = ms_in_buf*1000; + long ms_in_buf = paud_bufinfo.write_buf_time; + timeout.tv_sec = ms_in_buf / 1000; + ms_in_buf = ms_in_buf - timeout.tv_sec * 1000; + timeout.tv_usec = ms_in_buf * 1000; #ifdef DEBUG_AUDIO - fprintf( stderr, - "Waiting for write_buf_time=%ld,%ld\n", - timeout.tv_sec, - timeout.tv_usec ); + fprintf(stderr, + "Waiting for write_buf_time=%ld,%ld\n", + timeout.tv_sec, timeout.tv_usec); #endif - } + } #ifdef DEBUG_AUDIO fprintf(stderr, "Waiting for audio to get ready\n"); #endif - if ( select(audio_fd+1, NULL, &fdset, NULL, &timeout) <= 0 ) { - const char *message = "Audio timeout - buggy audio driver? (disabled)"; + if (select(audio_fd + 1, NULL, &fdset, NULL, &timeout) <= 0) { + const char *message = + "Audio timeout - buggy audio driver? (disabled)"; /* - * In general we should never print to the screen, + * In general we should never print to the screen, * but in this case we have no other way of letting * the user know what happened. */ @@ -186,326 +190,326 @@ static void Paud_WaitAudio(_THIS) } } -static void Paud_PlayAudio(_THIS) +static void +Paud_PlayAudio(_THIS) { - int written; - - /* Write the audio data, checking for EAGAIN on broken audio drivers */ - do { - written = write(audio_fd, mixbuf, mixlen); - if ( (written < 0) && ((errno == 0) || (errno == EAGAIN)) ) { - SDL_Delay(1); /* Let a little CPU time go by */ - } - } while ( (written < 0) && - ((errno == 0) || (errno == EAGAIN) || (errno == EINTR)) ); - - /* If timer synchronization is enabled, set the next write frame */ - if ( frame_ticks ) { - next_frame += frame_ticks; - } - - /* If we couldn't write, assume fatal error for now */ - if ( written < 0 ) { - this->enabled = 0; - } + int written; + + /* Write the audio data, checking for EAGAIN on broken audio drivers */ + do { + written = write(audio_fd, mixbuf, mixlen); + if ((written < 0) && ((errno == 0) || (errno == EAGAIN))) { + SDL_Delay(1); /* Let a little CPU time go by */ + } + } + while ((written < 0) && + ((errno == 0) || (errno == EAGAIN) || (errno == EINTR))); + + /* If timer synchronization is enabled, set the next write frame */ + if (frame_ticks) { + next_frame += frame_ticks; + } + + /* If we couldn't write, assume fatal error for now */ + if (written < 0) { + this->enabled = 0; + } #ifdef DEBUG_AUDIO - fprintf(stderr, "Wrote %d bytes of audio data\n", written); + fprintf(stderr, "Wrote %d bytes of audio data\n", written); #endif } -static Uint8 *Paud_GetAudioBuf(_THIS) +static Uint8 * +Paud_GetAudioBuf(_THIS) { - return mixbuf; + return mixbuf; } -static void Paud_CloseAudio(_THIS) +static void +Paud_CloseAudio(_THIS) { - if ( mixbuf != NULL ) { - SDL_FreeAudioMem(mixbuf); - mixbuf = NULL; - } - if ( audio_fd >= 0 ) { - close(audio_fd); - audio_fd = -1; - } + if (mixbuf != NULL) { + SDL_FreeAudioMem(mixbuf); + mixbuf = NULL; + } + if (audio_fd >= 0) { + close(audio_fd); + audio_fd = -1; + } } -static int Paud_OpenAudio(_THIS, SDL_AudioSpec *spec) +static int +Paud_OpenAudio(_THIS, SDL_AudioSpec * spec) { - char audiodev[1024]; - int format; - int bytes_per_sample; - Uint16 test_format; - audio_init paud_init; - audio_buffer paud_bufinfo; - audio_status paud_status; - audio_control paud_control; - audio_change paud_change; - - /* Reset the timer synchronization flag */ - frame_ticks = 0.0; - - /* Open the audio device */ - audio_fd = SDL_OpenAudioPath(audiodev, sizeof(audiodev), OPEN_FLAGS, 0); - if ( audio_fd < 0 ) { - SDL_SetError("Couldn't open %s: %s", audiodev, strerror(errno)); - return -1; - } - - /* - * We can't set the buffer size - just ask the device for the maximum - * that we can have. - */ - if ( ioctl(audio_fd, AUDIO_BUFFER, &paud_bufinfo) < 0 ) { - SDL_SetError("Couldn't get audio buffer information"); - return -1; - } - - mixbuf = NULL; - - if ( spec->channels > 1 ) - spec->channels = 2; - else - spec->channels = 1; - - /* - * Fields in the audio_init structure: - * - * Ignored by us: - * - * paud.loadpath[LOAD_PATH]; * DSP code to load, MWave chip only? - * paud.slot_number; * slot number of the adapter - * paud.device_id; * adapter identification number - * - * Input: - * - * paud.srate; * the sampling rate in Hz - * paud.bits_per_sample; * 8, 16, 32, ... - * paud.bsize; * block size for this rate - * paud.mode; * ADPCM, PCM, MU_LAW, A_LAW, SOURCE_MIX - * paud.channels; * 1=mono, 2=stereo - * paud.flags; * FIXED - fixed length data - * * LEFT_ALIGNED, RIGHT_ALIGNED (var len only) - * * TWOS_COMPLEMENT - 2's complement data - * * SIGNED - signed? comment seems wrong in sys/audio.h - * * BIG_ENDIAN - * paud.operation; * PLAY, RECORD - * - * Output: - * - * paud.flags; * PITCH - pitch is supported - * * INPUT - input is supported - * * OUTPUT - output is supported - * * MONITOR - monitor is supported - * * VOLUME - volume is supported - * * VOLUME_DELAY - volume delay is supported - * * BALANCE - balance is supported - * * BALANCE_DELAY - balance delay is supported - * * TREBLE - treble control is supported - * * BASS - bass control is supported - * * BESTFIT_PROVIDED - best fit returned - * * LOAD_CODE - DSP load needed - * paud.rc; * NO_PLAY - DSP code can't do play requests - * * NO_RECORD - DSP code can't do record requests - * * INVALID_REQUEST - request was invalid - * * CONFLICT - conflict with open's flags - * * OVERLOADED - out of DSP MIPS or memory - * paud.position_resolution; * smallest increment for position - */ - - paud_init.srate = spec->freq; - paud_init.mode = PCM; - paud_init.operation = PLAY; - paud_init.channels = spec->channels; - - /* Try for a closest match on audio format */ - format = 0; - for ( test_format = SDL_FirstAudioFormat(spec->format); - ! format && test_format; ) { + char audiodev[1024]; + int format; + int bytes_per_sample; + Uint16 test_format; + audio_init paud_init; + audio_buffer paud_bufinfo; + audio_status paud_status; + audio_control paud_control; + audio_change paud_change; + + /* Reset the timer synchronization flag */ + frame_ticks = 0.0; + + /* Open the audio device */ + audio_fd = SDL_OpenAudioPath(audiodev, sizeof(audiodev), OPEN_FLAGS, 0); + if (audio_fd < 0) { + SDL_SetError("Couldn't open %s: %s", audiodev, strerror(errno)); + return -1; + } + + /* + * We can't set the buffer size - just ask the device for the maximum + * that we can have. + */ + if (ioctl(audio_fd, AUDIO_BUFFER, &paud_bufinfo) < 0) { + SDL_SetError("Couldn't get audio buffer information"); + return -1; + } + + mixbuf = NULL; + + if (spec->channels > 1) + spec->channels = 2; + else + spec->channels = 1; + + /* + * Fields in the audio_init structure: + * + * Ignored by us: + * + * paud.loadpath[LOAD_PATH]; * DSP code to load, MWave chip only? + * paud.slot_number; * slot number of the adapter + * paud.device_id; * adapter identification number + * + * Input: + * + * paud.srate; * the sampling rate in Hz + * paud.bits_per_sample; * 8, 16, 32, ... + * paud.bsize; * block size for this rate + * paud.mode; * ADPCM, PCM, MU_LAW, A_LAW, SOURCE_MIX + * paud.channels; * 1=mono, 2=stereo + * paud.flags; * FIXED - fixed length data + * * LEFT_ALIGNED, RIGHT_ALIGNED (var len only) + * * TWOS_COMPLEMENT - 2's complement data + * * SIGNED - signed? comment seems wrong in sys/audio.h + * * BIG_ENDIAN + * paud.operation; * PLAY, RECORD + * + * Output: + * + * paud.flags; * PITCH - pitch is supported + * * INPUT - input is supported + * * OUTPUT - output is supported + * * MONITOR - monitor is supported + * * VOLUME - volume is supported + * * VOLUME_DELAY - volume delay is supported + * * BALANCE - balance is supported + * * BALANCE_DELAY - balance delay is supported + * * TREBLE - treble control is supported + * * BASS - bass control is supported + * * BESTFIT_PROVIDED - best fit returned + * * LOAD_CODE - DSP load needed + * paud.rc; * NO_PLAY - DSP code can't do play requests + * * NO_RECORD - DSP code can't do record requests + * * INVALID_REQUEST - request was invalid + * * CONFLICT - conflict with open's flags + * * OVERLOADED - out of DSP MIPS or memory + * paud.position_resolution; * smallest increment for position + */ + + paud_init.srate = spec->freq; + paud_init.mode = PCM; + paud_init.operation = PLAY; + paud_init.channels = spec->channels; + + /* Try for a closest match on audio format */ + format = 0; + for (test_format = SDL_FirstAudioFormat(spec->format); + !format && test_format;) { #ifdef DEBUG_AUDIO - fprintf(stderr, "Trying format 0x%4.4x\n", test_format); + fprintf(stderr, "Trying format 0x%4.4x\n", test_format); #endif - switch ( test_format ) { - case AUDIO_U8: - bytes_per_sample = 1; - paud_init.bits_per_sample = 8; - paud_init.flags = TWOS_COMPLEMENT | FIXED; - format = 1; - break; - case AUDIO_S8: - bytes_per_sample = 1; - paud_init.bits_per_sample = 8; - paud_init.flags = SIGNED | - TWOS_COMPLEMENT | FIXED; - format = 1; - break; - case AUDIO_S16LSB: - bytes_per_sample = 2; - paud_init.bits_per_sample = 16; - paud_init.flags = SIGNED | - TWOS_COMPLEMENT | FIXED; - format = 1; - break; - case AUDIO_S16MSB: - bytes_per_sample = 2; - paud_init.bits_per_sample = 16; - paud_init.flags = BIG_ENDIAN | - SIGNED | - TWOS_COMPLEMENT | FIXED; - format = 1; - break; - case AUDIO_U16LSB: - bytes_per_sample = 2; - paud_init.bits_per_sample = 16; - paud_init.flags = TWOS_COMPLEMENT | FIXED; - format = 1; - break; - case AUDIO_U16MSB: - bytes_per_sample = 2; - paud_init.bits_per_sample = 16; - paud_init.flags = BIG_ENDIAN | - TWOS_COMPLEMENT | FIXED; - format = 1; - break; - default: - break; - } - if ( ! format ) { - test_format = SDL_NextAudioFormat(); - } - } - if ( format == 0 ) { + switch (test_format) { + case AUDIO_U8: + bytes_per_sample = 1; + paud_init.bits_per_sample = 8; + paud_init.flags = TWOS_COMPLEMENT | FIXED; + format = 1; + break; + case AUDIO_S8: + bytes_per_sample = 1; + paud_init.bits_per_sample = 8; + paud_init.flags = SIGNED | TWOS_COMPLEMENT | FIXED; + format = 1; + break; + case AUDIO_S16LSB: + bytes_per_sample = 2; + paud_init.bits_per_sample = 16; + paud_init.flags = SIGNED | TWOS_COMPLEMENT | FIXED; + format = 1; + break; + case AUDIO_S16MSB: + bytes_per_sample = 2; + paud_init.bits_per_sample = 16; + paud_init.flags = BIG_ENDIAN | SIGNED | TWOS_COMPLEMENT | FIXED; + format = 1; + break; + case AUDIO_U16LSB: + bytes_per_sample = 2; + paud_init.bits_per_sample = 16; + paud_init.flags = TWOS_COMPLEMENT | FIXED; + format = 1; + break; + case AUDIO_U16MSB: + bytes_per_sample = 2; + paud_init.bits_per_sample = 16; + paud_init.flags = BIG_ENDIAN | TWOS_COMPLEMENT | FIXED; + format = 1; + break; + default: + break; + } + if (!format) { + test_format = SDL_NextAudioFormat(); + } + } + if (format == 0) { #ifdef DEBUG_AUDIO - fprintf(stderr, "Couldn't find any hardware audio formats\n"); + fprintf(stderr, "Couldn't find any hardware audio formats\n"); #endif - SDL_SetError("Couldn't find any hardware audio formats"); - return -1; - } - spec->format = test_format; - - /* - * We know the buffer size and the max number of subsequent writes - * that can be pending. If more than one can pend, allow the application - * to do something like double buffering between our write buffer and - * the device's own buffer that we are filling with write() anyway. - * - * We calculate spec->samples like this because SDL_CalculateAudioSpec() - * will give put paud_bufinfo.write_buf_cap (or paud_bufinfo.write_buf_cap/2) - * into spec->size in return. - */ - if ( paud_bufinfo.request_buf_cap == 1 ) - { - spec->samples = paud_bufinfo.write_buf_cap - / bytes_per_sample - / spec->channels; - } - else - { - spec->samples = paud_bufinfo.write_buf_cap - / bytes_per_sample - / spec->channels - / 2; - } - paud_init.bsize = bytes_per_sample * spec->channels; - - SDL_CalculateAudioSpec(spec); - - /* - * The AIX paud device init can't modify the values of the audio_init - * structure that we pass to it. So we don't need any recalculation - * of this stuff and no reinit call as in linux dsp and dma code. - * - * /dev/paud supports all of the encoding formats, so we don't need - * to do anything like reopening the device, either. - */ - if ( ioctl(audio_fd, AUDIO_INIT, &paud_init) < 0 ) { - switch ( paud_init.rc ) - { - case 1 : - SDL_SetError("Couldn't set audio format: DSP can't do play requests"); - return -1; - break; - case 2 : - SDL_SetError("Couldn't set audio format: DSP can't do record requests"); - return -1; - break; - case 4 : - SDL_SetError("Couldn't set audio format: request was invalid"); - return -1; - break; - case 5 : - SDL_SetError("Couldn't set audio format: conflict with open's flags"); - return -1; - break; - case 6 : - SDL_SetError("Couldn't set audio format: out of DSP MIPS or memory"); - return -1; - break; - default : - SDL_SetError("Couldn't set audio format: not documented in sys/audio.h"); - return -1; - break; - } - } - - /* Allocate mixing buffer */ - mixlen = spec->size; - mixbuf = (Uint8 *)SDL_AllocAudioMem(mixlen); - if ( mixbuf == NULL ) { - return -1; - } - SDL_memset(mixbuf, spec->silence, spec->size); - - /* - * Set some paramters: full volume, first speaker that we can find. - * Ignore the other settings for now. - */ - paud_change.input = AUDIO_IGNORE; /* the new input source */ - paud_change.output = OUTPUT_1; /* EXTERNAL_SPEAKER,INTERNAL_SPEAKER,OUTPUT_1 */ - paud_change.monitor = AUDIO_IGNORE; /* the new monitor state */ - paud_change.volume = 0x7fffffff; /* volume level [0-0x7fffffff] */ - paud_change.volume_delay = AUDIO_IGNORE; /* the new volume delay */ - paud_change.balance = 0x3fffffff; /* the new balance */ - paud_change.balance_delay = AUDIO_IGNORE; /* the new balance delay */ - paud_change.treble = AUDIO_IGNORE; /* the new treble state */ - paud_change.bass = AUDIO_IGNORE; /* the new bass state */ - paud_change.pitch = AUDIO_IGNORE; /* the new pitch state */ - - paud_control.ioctl_request = AUDIO_CHANGE; - paud_control.request_info = (char*)&paud_change; - if ( ioctl(audio_fd, AUDIO_CONTROL, &paud_control) < 0 ) { + SDL_SetError("Couldn't find any hardware audio formats"); + return -1; + } + spec->format = test_format; + + /* + * We know the buffer size and the max number of subsequent writes + * that can be pending. If more than one can pend, allow the application + * to do something like double buffering between our write buffer and + * the device's own buffer that we are filling with write() anyway. + * + * We calculate spec->samples like this because SDL_CalculateAudioSpec() + * will give put paud_bufinfo.write_buf_cap (or paud_bufinfo.write_buf_cap/2) + * into spec->size in return. + */ + if (paud_bufinfo.request_buf_cap == 1) { + spec->samples = paud_bufinfo.write_buf_cap + / bytes_per_sample / spec->channels; + } else { + spec->samples = paud_bufinfo.write_buf_cap + / bytes_per_sample / spec->channels / 2; + } + paud_init.bsize = bytes_per_sample * spec->channels; + + SDL_CalculateAudioSpec(spec); + + /* + * The AIX paud device init can't modify the values of the audio_init + * structure that we pass to it. So we don't need any recalculation + * of this stuff and no reinit call as in linux dsp and dma code. + * + * /dev/paud supports all of the encoding formats, so we don't need + * to do anything like reopening the device, either. + */ + if (ioctl(audio_fd, AUDIO_INIT, &paud_init) < 0) { + switch (paud_init.rc) { + case 1: + SDL_SetError + ("Couldn't set audio format: DSP can't do play requests"); + return -1; + break; + case 2: + SDL_SetError + ("Couldn't set audio format: DSP can't do record requests"); + return -1; + break; + case 4: + SDL_SetError("Couldn't set audio format: request was invalid"); + return -1; + break; + case 5: + SDL_SetError + ("Couldn't set audio format: conflict with open's flags"); + return -1; + break; + case 6: + SDL_SetError + ("Couldn't set audio format: out of DSP MIPS or memory"); + return -1; + break; + default: + SDL_SetError + ("Couldn't set audio format: not documented in sys/audio.h"); + return -1; + break; + } + } + + /* Allocate mixing buffer */ + mixlen = spec->size; + mixbuf = (Uint8 *) SDL_AllocAudioMem(mixlen); + if (mixbuf == NULL) { + return -1; + } + SDL_memset(mixbuf, spec->silence, spec->size); + + /* + * Set some paramters: full volume, first speaker that we can find. + * Ignore the other settings for now. + */ + paud_change.input = AUDIO_IGNORE; /* the new input source */ + paud_change.output = OUTPUT_1; /* EXTERNAL_SPEAKER,INTERNAL_SPEAKER,OUTPUT_1 */ + paud_change.monitor = AUDIO_IGNORE; /* the new monitor state */ + paud_change.volume = 0x7fffffff; /* volume level [0-0x7fffffff] */ + paud_change.volume_delay = AUDIO_IGNORE; /* the new volume delay */ + paud_change.balance = 0x3fffffff; /* the new balance */ + paud_change.balance_delay = AUDIO_IGNORE; /* the new balance delay */ + paud_change.treble = AUDIO_IGNORE; /* the new treble state */ + paud_change.bass = AUDIO_IGNORE; /* the new bass state */ + paud_change.pitch = AUDIO_IGNORE; /* the new pitch state */ + + paud_control.ioctl_request = AUDIO_CHANGE; + paud_control.request_info = (char *) &paud_change; + if (ioctl(audio_fd, AUDIO_CONTROL, &paud_control) < 0) { #ifdef DEBUG_AUDIO - fprintf(stderr, "Can't change audio display settings\n" ); + fprintf(stderr, "Can't change audio display settings\n"); #endif - } - - /* - * Tell the device to expect data. Actual start will wait for - * the first write() call. - */ - paud_control.ioctl_request = AUDIO_START; - paud_control.position = 0; - if ( ioctl(audio_fd, AUDIO_CONTROL, &paud_control) < 0 ) { + } + + /* + * Tell the device to expect data. Actual start will wait for + * the first write() call. + */ + paud_control.ioctl_request = AUDIO_START; + paud_control.position = 0; + if (ioctl(audio_fd, AUDIO_CONTROL, &paud_control) < 0) { #ifdef DEBUG_AUDIO - fprintf(stderr, "Can't start audio play\n" ); + fprintf(stderr, "Can't start audio play\n"); #endif - SDL_SetError("Can't start audio play"); - return -1; - } - - /* Check to see if we need to use select() workaround */ - { char *workaround; - workaround = SDL_getenv("SDL_DSP_NOSELECT"); - if ( workaround ) { - frame_ticks = (float)(spec->samples*1000)/spec->freq; - next_frame = SDL_GetTicks()+frame_ticks; - } + SDL_SetError("Can't start audio play"); + return -1; + } + + /* Check to see if we need to use select() workaround */ + { + char *workaround; + workaround = SDL_getenv("SDL_DSP_NOSELECT"); + if (workaround) { + frame_ticks = (float) (spec->samples * 1000) / spec->freq; + next_frame = SDL_GetTicks() + frame_ticks; } + } - /* Get the parent process id (we're the parent of the audio thread) */ - parent = getpid(); + /* Get the parent process id (we're the parent of the audio thread) */ + parent = getpid(); - /* We're ready to rock and roll. :-) */ - return 0; + /* We're ready to rock and roll. :-) */ + return 0; } +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/audio/paudio/SDL_paudio.h b/src/audio/paudio/SDL_paudio.h index a3f22edae..757dadd55 100644 --- a/src/audio/paudio/SDL_paudio.h +++ b/src/audio/paudio/SDL_paudio.h @@ -29,22 +29,23 @@ /* Hidden "this" pointer for the video functions */ #define _THIS SDL_AudioDevice *this -struct SDL_PrivateAudioData { - /* The file descriptor for the audio device */ - int audio_fd; +struct SDL_PrivateAudioData +{ + /* The file descriptor for the audio device */ + int audio_fd; - /* The parent process id, to detect when application quits */ - pid_t parent; + /* The parent process id, to detect when application quits */ + pid_t parent; - /* Raw mixing buffer */ - Uint8 *mixbuf; - int mixlen; + /* Raw mixing buffer */ + Uint8 *mixbuf; + int mixlen; - /* Support for audio timing using a timer, in addition to select() */ - float frame_ticks; - float next_frame; + /* Support for audio timing using a timer, in addition to select() */ + float frame_ticks; + float next_frame; }; -#define FUDGE_TICKS 10 /* The scheduler overhead ticks per frame */ +#define FUDGE_TICKS 10 /* The scheduler overhead ticks per frame */ /* Old variable names */ #define audio_fd (this->hidden->audio_fd) @@ -55,3 +56,4 @@ struct SDL_PrivateAudioData { #define next_frame (this->hidden->next_frame) #endif /* _SDL_paudaudio_h */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/audio/sun/SDL_sunaudio.c b/src/audio/sun/SDL_sunaudio.c index 5ddaba108..30527149b 100644 --- a/src/audio/sun/SDL_sunaudio.c +++ b/src/audio/sun/SDL_sunaudio.c @@ -48,7 +48,7 @@ #define OPEN_FLAGS (O_WRONLY|O_NONBLOCK) /* Audio driver functions */ -static int DSP_OpenAudio(_THIS, SDL_AudioSpec *spec); +static int DSP_OpenAudio(_THIS, SDL_AudioSpec * spec); static void DSP_WaitAudio(_THIS); static void DSP_PlayAudio(_THIS); static Uint8 *DSP_GetAudioBuf(_THIS); @@ -58,325 +58,338 @@ static Uint8 snd2au(int sample); /* Audio driver bootstrap functions */ -static int Audio_Available(void) +static int +Audio_Available(void) { - int fd; - int available; - - available = 0; - fd = SDL_OpenAudioPath(NULL, 0, OPEN_FLAGS, 1); - if ( fd >= 0 ) { - available = 1; - close(fd); - } - return(available); + int fd; + int available; + + available = 0; + fd = SDL_OpenAudioPath(NULL, 0, OPEN_FLAGS, 1); + if (fd >= 0) { + available = 1; + close(fd); + } + return (available); } -static void Audio_DeleteDevice(SDL_AudioDevice *device) +static void +Audio_DeleteDevice(SDL_AudioDevice * device) { - SDL_free(device->hidden); - SDL_free(device); + SDL_free(device->hidden); + SDL_free(device); } -static SDL_AudioDevice *Audio_CreateDevice(int devindex) +static SDL_AudioDevice * +Audio_CreateDevice(int devindex) { - SDL_AudioDevice *this; - - /* Initialize all variables that we clean on shutdown */ - this = (SDL_AudioDevice *)SDL_malloc(sizeof(SDL_AudioDevice)); - if ( this ) { - SDL_memset(this, 0, (sizeof *this)); - this->hidden = (struct SDL_PrivateAudioData *) - SDL_malloc((sizeof *this->hidden)); - } - if ( (this == NULL) || (this->hidden == NULL) ) { - SDL_OutOfMemory(); - if ( this ) { - SDL_free(this); - } - return(0); - } - SDL_memset(this->hidden, 0, (sizeof *this->hidden)); - audio_fd = -1; - - /* Set the function pointers */ - this->OpenAudio = DSP_OpenAudio; - this->WaitAudio = DSP_WaitAudio; - this->PlayAudio = DSP_PlayAudio; - this->GetAudioBuf = DSP_GetAudioBuf; - this->CloseAudio = DSP_CloseAudio; - - this->free = Audio_DeleteDevice; - - return this; + SDL_AudioDevice *this; + + /* Initialize all variables that we clean on shutdown */ + this = (SDL_AudioDevice *) SDL_malloc(sizeof(SDL_AudioDevice)); + if (this) { + SDL_memset(this, 0, (sizeof *this)); + this->hidden = (struct SDL_PrivateAudioData *) + SDL_malloc((sizeof *this->hidden)); + } + if ((this == NULL) || (this->hidden == NULL)) { + SDL_OutOfMemory(); + if (this) { + SDL_free(this); + } + return (0); + } + SDL_memset(this->hidden, 0, (sizeof *this->hidden)); + audio_fd = -1; + + /* Set the function pointers */ + this->OpenAudio = DSP_OpenAudio; + this->WaitAudio = DSP_WaitAudio; + this->PlayAudio = DSP_PlayAudio; + this->GetAudioBuf = DSP_GetAudioBuf; + this->CloseAudio = DSP_CloseAudio; + + this->free = Audio_DeleteDevice; + + return this; } AudioBootStrap SUNAUDIO_bootstrap = { - "audio", "UNIX /dev/audio interface", - Audio_Available, Audio_CreateDevice + "audio", "UNIX /dev/audio interface", + Audio_Available, Audio_CreateDevice }; #ifdef DEBUG_AUDIO -void CheckUnderflow(_THIS) +void +CheckUnderflow(_THIS) { #ifdef AUDIO_GETINFO - audio_info_t info; - int left; - - ioctl(audio_fd, AUDIO_GETINFO, &info); - left = (written - info.play.samples); - if ( written && (left == 0) ) { - fprintf(stderr, "audio underflow!\n"); - } + audio_info_t info; + int left; + + ioctl(audio_fd, AUDIO_GETINFO, &info); + left = (written - info.play.samples); + if (written && (left == 0)) { + fprintf(stderr, "audio underflow!\n"); + } #endif } #endif -void DSP_WaitAudio(_THIS) +void +DSP_WaitAudio(_THIS) { #ifdef AUDIO_GETINFO -#define SLEEP_FUDGE 10 /* 10 ms scheduling fudge factor */ - audio_info_t info; - Sint32 left; - - ioctl(audio_fd, AUDIO_GETINFO, &info); - left = (written - info.play.samples); - if ( left > fragsize ) { - Sint32 sleepy; - - sleepy = ((left - fragsize)/frequency); - sleepy -= SLEEP_FUDGE; - if ( sleepy > 0 ) { - SDL_Delay(sleepy); - } - } +#define SLEEP_FUDGE 10 /* 10 ms scheduling fudge factor */ + audio_info_t info; + Sint32 left; + + ioctl(audio_fd, AUDIO_GETINFO, &info); + left = (written - info.play.samples); + if (left > fragsize) { + Sint32 sleepy; + + sleepy = ((left - fragsize) / frequency); + sleepy -= SLEEP_FUDGE; + if (sleepy > 0) { + SDL_Delay(sleepy); + } + } #else - fd_set fdset; + fd_set fdset; - FD_ZERO(&fdset); - FD_SET(audio_fd, &fdset); - select(audio_fd+1, NULL, &fdset, NULL, NULL); + FD_ZERO(&fdset); + FD_SET(audio_fd, &fdset); + select(audio_fd + 1, NULL, &fdset, NULL, NULL); #endif } -void DSP_PlayAudio(_THIS) +void +DSP_PlayAudio(_THIS) { - /* Write the audio data */ - if ( ulaw_only ) { - /* Assuming that this->spec.freq >= 8000 Hz */ - int accum, incr, pos; - Uint8 *aubuf; - - accum = 0; - incr = this->spec.freq/8; - aubuf = ulaw_buf; - switch (audio_fmt & 0xFF) { - case 8: { - Uint8 *sndbuf; - - sndbuf = mixbuf; - for ( pos=0; pos < fragsize; ++pos ) { - *aubuf = snd2au((0x80-*sndbuf)*64); - accum += incr; - while ( accum > 0 ) { - accum -= 1000; - sndbuf += 1; - } - aubuf += 1; - } - } - break; - case 16: { - Sint16 *sndbuf; - - sndbuf = (Sint16 *)mixbuf; - for ( pos=0; pos < fragsize; ++pos ) { - *aubuf = snd2au(*sndbuf/4); - accum += incr; - while ( accum > 0 ) { - accum -= 1000; - sndbuf += 1; - } - aubuf += 1; - } - } - break; - } + /* Write the audio data */ + if (ulaw_only) { + /* Assuming that this->spec.freq >= 8000 Hz */ + int accum, incr, pos; + Uint8 *aubuf; + + accum = 0; + incr = this->spec.freq / 8; + aubuf = ulaw_buf; + switch (audio_fmt & 0xFF) { + case 8: + { + Uint8 *sndbuf; + + sndbuf = mixbuf; + for (pos = 0; pos < fragsize; ++pos) { + *aubuf = snd2au((0x80 - *sndbuf) * 64); + accum += incr; + while (accum > 0) { + accum -= 1000; + sndbuf += 1; + } + aubuf += 1; + } + } + break; + case 16: + { + Sint16 *sndbuf; + + sndbuf = (Sint16 *) mixbuf; + for (pos = 0; pos < fragsize; ++pos) { + *aubuf = snd2au(*sndbuf / 4); + accum += incr; + while (accum > 0) { + accum -= 1000; + sndbuf += 1; + } + aubuf += 1; + } + } + break; + } #ifdef DEBUG_AUDIO - CheckUnderflow(this); + CheckUnderflow(this); #endif - if ( write(audio_fd, ulaw_buf, fragsize) < 0 ) { - /* Assume fatal error, for now */ - this->enabled = 0; - } - written += fragsize; - } else { + if (write(audio_fd, ulaw_buf, fragsize) < 0) { + /* Assume fatal error, for now */ + this->enabled = 0; + } + written += fragsize; + } else { #ifdef DEBUG_AUDIO - CheckUnderflow(this); + CheckUnderflow(this); #endif - if ( write(audio_fd, mixbuf, this->spec.size) < 0 ) { - /* Assume fatal error, for now */ - this->enabled = 0; - } - written += fragsize; - } + if (write(audio_fd, mixbuf, this->spec.size) < 0) { + /* Assume fatal error, for now */ + this->enabled = 0; + } + written += fragsize; + } } -Uint8 *DSP_GetAudioBuf(_THIS) +Uint8 * +DSP_GetAudioBuf(_THIS) { - return(mixbuf); + return (mixbuf); } -void DSP_CloseAudio(_THIS) +void +DSP_CloseAudio(_THIS) { - if ( mixbuf != NULL ) { - SDL_FreeAudioMem(mixbuf); - mixbuf = NULL; - } - if ( ulaw_buf != NULL ) { - SDL_free(ulaw_buf); - ulaw_buf = NULL; - } - close(audio_fd); + if (mixbuf != NULL) { + SDL_FreeAudioMem(mixbuf); + mixbuf = NULL; + } + if (ulaw_buf != NULL) { + SDL_free(ulaw_buf); + ulaw_buf = NULL; + } + close(audio_fd); } -int DSP_OpenAudio(_THIS, SDL_AudioSpec *spec) +int +DSP_OpenAudio(_THIS, SDL_AudioSpec * spec) { - char audiodev[1024]; + char audiodev[1024]; #ifdef AUDIO_SETINFO - int enc; + int enc; #endif - int desired_freq = spec->freq; + int desired_freq = spec->freq; - /* Initialize our freeable variables, in case we fail*/ - audio_fd = -1; - mixbuf = NULL; - ulaw_buf = NULL; + /* Initialize our freeable variables, in case we fail */ + audio_fd = -1; + mixbuf = NULL; + ulaw_buf = NULL; - /* Determine the audio parameters from the AudioSpec */ - switch ( spec->format & 0xFF ) { + /* Determine the audio parameters from the AudioSpec */ + switch (spec->format & 0xFF) { - case 8: { /* Unsigned 8 bit audio data */ - spec->format = AUDIO_U8; + case 8: + { /* Unsigned 8 bit audio data */ + spec->format = AUDIO_U8; #ifdef AUDIO_SETINFO - enc = AUDIO_ENCODING_LINEAR8; + enc = AUDIO_ENCODING_LINEAR8; #endif - } - break; + } + break; - case 16: { /* Signed 16 bit audio data */ - spec->format = AUDIO_S16SYS; + case 16: + { /* Signed 16 bit audio data */ + spec->format = AUDIO_S16SYS; #ifdef AUDIO_SETINFO - enc = AUDIO_ENCODING_LINEAR; + enc = AUDIO_ENCODING_LINEAR; #endif - } - break; - - default: { - SDL_SetError("Unsupported audio format"); - return(-1); - } - } - audio_fmt = spec->format; - - /* Open the audio device */ - audio_fd = SDL_OpenAudioPath(audiodev, sizeof(audiodev), OPEN_FLAGS, 1); - if ( audio_fd < 0 ) { - SDL_SetError("Couldn't open %s: %s", audiodev, - strerror(errno)); - return(-1); - } - - ulaw_only = 0; /* modern Suns do support linear audio */ + } + break; + + default: + { + SDL_SetError("Unsupported audio format"); + return (-1); + } + } + audio_fmt = spec->format; + + /* Open the audio device */ + audio_fd = SDL_OpenAudioPath(audiodev, sizeof(audiodev), OPEN_FLAGS, 1); + if (audio_fd < 0) { + SDL_SetError("Couldn't open %s: %s", audiodev, strerror(errno)); + return (-1); + } + + ulaw_only = 0; /* modern Suns do support linear audio */ #ifdef AUDIO_SETINFO - for(;;) { - audio_info_t info; - AUDIO_INITINFO(&info); /* init all fields to "no change" */ - - /* Try to set the requested settings */ - info.play.sample_rate = spec->freq; - info.play.channels = spec->channels; - info.play.precision = (enc == AUDIO_ENCODING_ULAW) - ? 8 : spec->format & 0xff; - info.play.encoding = enc; - if( ioctl(audio_fd, AUDIO_SETINFO, &info) == 0 ) { - - /* Check to be sure we got what we wanted */ - if(ioctl(audio_fd, AUDIO_GETINFO, &info) < 0) { - SDL_SetError("Error getting audio parameters: %s", - strerror(errno)); - return -1; - } - if(info.play.encoding == enc - && info.play.precision == (spec->format & 0xff) - && info.play.channels == spec->channels) { - /* Yow! All seems to be well! */ - spec->freq = info.play.sample_rate; - break; - } - } - - switch(enc) { - case AUDIO_ENCODING_LINEAR8: - /* unsigned 8bit apparently not supported here */ - enc = AUDIO_ENCODING_LINEAR; - spec->format = AUDIO_S16SYS; - break; /* try again */ - - case AUDIO_ENCODING_LINEAR: - /* linear 16bit didn't work either, resort to µ-law */ - enc = AUDIO_ENCODING_ULAW; - spec->channels = 1; - spec->freq = 8000; - spec->format = AUDIO_U8; - ulaw_only = 1; - break; - - default: - /* oh well... */ - SDL_SetError("Error setting audio parameters: %s", - strerror(errno)); - return -1; - } - } + for (;;) { + audio_info_t info; + AUDIO_INITINFO(&info); /* init all fields to "no change" */ + + /* Try to set the requested settings */ + info.play.sample_rate = spec->freq; + info.play.channels = spec->channels; + info.play.precision = (enc == AUDIO_ENCODING_ULAW) + ? 8 : spec->format & 0xff; + info.play.encoding = enc; + if (ioctl(audio_fd, AUDIO_SETINFO, &info) == 0) { + + /* Check to be sure we got what we wanted */ + if (ioctl(audio_fd, AUDIO_GETINFO, &info) < 0) { + SDL_SetError("Error getting audio parameters: %s", + strerror(errno)); + return -1; + } + if (info.play.encoding == enc + && info.play.precision == (spec->format & 0xff) + && info.play.channels == spec->channels) { + /* Yow! All seems to be well! */ + spec->freq = info.play.sample_rate; + break; + } + } + + switch (enc) { + case AUDIO_ENCODING_LINEAR8: + /* unsigned 8bit apparently not supported here */ + enc = AUDIO_ENCODING_LINEAR; + spec->format = AUDIO_S16SYS; + break; /* try again */ + + case AUDIO_ENCODING_LINEAR: + /* linear 16bit didn't work either, resort to µ-law */ + enc = AUDIO_ENCODING_ULAW; + spec->channels = 1; + spec->freq = 8000; + spec->format = AUDIO_U8; + ulaw_only = 1; + break; + + default: + /* oh well... */ + SDL_SetError("Error setting audio parameters: %s", + strerror(errno)); + return -1; + } + } #endif /* AUDIO_SETINFO */ - written = 0; - - /* We can actually convert on-the-fly to U-Law */ - if ( ulaw_only ) { - spec->freq = desired_freq; - fragsize = (spec->samples*1000)/(spec->freq/8); - frequency = 8; - ulaw_buf = (Uint8 *)SDL_malloc(fragsize); - if ( ulaw_buf == NULL ) { - SDL_OutOfMemory(); - return(-1); - } - spec->channels = 1; - } else { - fragsize = spec->samples; - frequency = spec->freq/1000; - } + written = 0; + + /* We can actually convert on-the-fly to U-Law */ + if (ulaw_only) { + spec->freq = desired_freq; + fragsize = (spec->samples * 1000) / (spec->freq / 8); + frequency = 8; + ulaw_buf = (Uint8 *) SDL_malloc(fragsize); + if (ulaw_buf == NULL) { + SDL_OutOfMemory(); + return (-1); + } + spec->channels = 1; + } else { + fragsize = spec->samples; + frequency = spec->freq / 1000; + } #ifdef DEBUG_AUDIO - fprintf(stderr, "Audio device %s U-Law only\n", - ulaw_only ? "is" : "is not"); - fprintf(stderr, "format=0x%x chan=%d freq=%d\n", - spec->format, spec->channels, spec->freq); + fprintf(stderr, "Audio device %s U-Law only\n", + ulaw_only ? "is" : "is not"); + fprintf(stderr, "format=0x%x chan=%d freq=%d\n", + spec->format, spec->channels, spec->freq); #endif - /* Update the fragment size as size in bytes */ - SDL_CalculateAudioSpec(spec); + /* Update the fragment size as size in bytes */ + SDL_CalculateAudioSpec(spec); - /* Allocate mixing buffer */ - mixbuf = (Uint8 *)SDL_AllocAudioMem(spec->size); - if ( mixbuf == NULL ) { - SDL_OutOfMemory(); - return(-1); - } - SDL_memset(mixbuf, spec->silence, spec->size); + /* Allocate mixing buffer */ + mixbuf = (Uint8 *) SDL_AllocAudioMem(spec->size); + if (mixbuf == NULL) { + SDL_OutOfMemory(); + return (-1); + } + SDL_memset(mixbuf, spec->silence, spec->size); - /* We're ready to rock and roll. :-) */ - return(0); + /* We're ready to rock and roll. :-) */ + return (0); } /************************************************************************/ @@ -397,36 +410,39 @@ int DSP_OpenAudio(_THIS, SDL_AudioSpec *spec) /* provided "as is" without express or implied warranty. */ /************************************************************************/ -static Uint8 snd2au(int sample) +static Uint8 +snd2au(int sample) { - int mask; - - if (sample < 0) { - sample = -sample; - mask = 0x7f; - } else { - mask = 0xff; - } - - if (sample < 32) { - sample = 0xF0 | (15 - sample / 2); - } else if (sample < 96) { - sample = 0xE0 | (15 - (sample - 32) / 4); - } else if (sample < 224) { - sample = 0xD0 | (15 - (sample - 96) / 8); - } else if (sample < 480) { - sample = 0xC0 | (15 - (sample - 224) / 16); - } else if (sample < 992) { - sample = 0xB0 | (15 - (sample - 480) / 32); - } else if (sample < 2016) { - sample = 0xA0 | (15 - (sample - 992) / 64); - } else if (sample < 4064) { - sample = 0x90 | (15 - (sample - 2016) / 128); - } else if (sample < 8160) { - sample = 0x80 | (15 - (sample - 4064) / 256); - } else { - sample = 0x80; - } - return (mask & sample); + int mask; + + if (sample < 0) { + sample = -sample; + mask = 0x7f; + } else { + mask = 0xff; + } + + if (sample < 32) { + sample = 0xF0 | (15 - sample / 2); + } else if (sample < 96) { + sample = 0xE0 | (15 - (sample - 32) / 4); + } else if (sample < 224) { + sample = 0xD0 | (15 - (sample - 96) / 8); + } else if (sample < 480) { + sample = 0xC0 | (15 - (sample - 224) / 16); + } else if (sample < 992) { + sample = 0xB0 | (15 - (sample - 480) / 32); + } else if (sample < 2016) { + sample = 0xA0 | (15 - (sample - 992) / 64); + } else if (sample < 4064) { + sample = 0x90 | (15 - (sample - 2016) / 128); + } else if (sample < 8160) { + sample = 0x80 | (15 - (sample - 4064) / 256); + } else { + sample = 0x80; + } + return (mask & sample); } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/audio/sun/SDL_sunaudio.h b/src/audio/sun/SDL_sunaudio.h index 51b0d5e85..7f33a2f32 100644 --- a/src/audio/sun/SDL_sunaudio.h +++ b/src/audio/sun/SDL_sunaudio.h @@ -29,17 +29,18 @@ /* Hidden "this" pointer for the video functions */ #define _THIS SDL_AudioDevice *this -struct SDL_PrivateAudioData { - /* The file descriptor for the audio device */ - int audio_fd; - - Uint16 audio_fmt; /* The app audio format */ - Uint8 *mixbuf; /* The app mixing buffer */ - int ulaw_only; /* Flag -- does hardware only output U-law? */ - Uint8 *ulaw_buf; /* The U-law mixing buffer */ - Sint32 written; /* The number of samples written */ - int fragsize; /* The audio fragment size in samples */ - int frequency; /* The audio frequency in KHz */ +struct SDL_PrivateAudioData +{ + /* The file descriptor for the audio device */ + int audio_fd; + + Uint16 audio_fmt; /* The app audio format */ + Uint8 *mixbuf; /* The app mixing buffer */ + int ulaw_only; /* Flag -- does hardware only output U-law? */ + Uint8 *ulaw_buf; /* The U-law mixing buffer */ + Sint32 written; /* The number of samples written */ + int fragsize; /* The audio fragment size in samples */ + int frequency; /* The audio frequency in KHz */ }; /* Old variable names */ @@ -53,3 +54,4 @@ struct SDL_PrivateAudioData { #define frequency (this->hidden->frequency) #endif /* _SDL_lowaudio_h */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/audio/ums/SDL_umsaudio.c b/src/audio/ums/SDL_umsaudio.c index 90bcd9b5b..c2524cf3a 100644 --- a/src/audio/ums/SDL_umsaudio.c +++ b/src/audio/ums/SDL_umsaudio.c @@ -45,50 +45,64 @@ #define DEBUG_AUDIO 1 /* Audio driver functions */ -static int UMS_OpenAudio(_THIS, SDL_AudioSpec *spec); +static int UMS_OpenAudio(_THIS, SDL_AudioSpec * spec); static void UMS_PlayAudio(_THIS); static Uint8 *UMS_GetAudioBuf(_THIS); static void UMS_CloseAudio(_THIS); -static UMSAudioDevice_ReturnCode UADOpen(_THIS, string device, string mode, long flags); +static UMSAudioDevice_ReturnCode UADOpen(_THIS, string device, string mode, + long flags); static UMSAudioDevice_ReturnCode UADClose(_THIS); -static UMSAudioDevice_ReturnCode UADGetBitsPerSample(_THIS, long* bits); +static UMSAudioDevice_ReturnCode UADGetBitsPerSample(_THIS, long *bits); static UMSAudioDevice_ReturnCode UADSetBitsPerSample(_THIS, long bits); -static UMSAudioDevice_ReturnCode UADSetSampleRate(_THIS, long rate, long* set_rate); +static UMSAudioDevice_ReturnCode UADSetSampleRate(_THIS, long rate, + long *set_rate); static UMSAudioDevice_ReturnCode UADSetByteOrder(_THIS, string byte_order); static UMSAudioDevice_ReturnCode UADSetAudioFormatType(_THIS, string fmt); static UMSAudioDevice_ReturnCode UADSetNumberFormat(_THIS, string fmt); static UMSAudioDevice_ReturnCode UADInitialize(_THIS); static UMSAudioDevice_ReturnCode UADStart(_THIS); static UMSAudioDevice_ReturnCode UADStop(_THIS); -static UMSAudioDevice_ReturnCode UADSetTimeFormat(_THIS, UMSAudioTypes_TimeFormat fmt ); -static UMSAudioDevice_ReturnCode UADWriteBuffSize(_THIS, long* buff_size ); -static UMSAudioDevice_ReturnCode UADWriteBuffRemain(_THIS, long* buff_size ); -static UMSAudioDevice_ReturnCode UADWriteBuffUsed(_THIS, long* buff_size ); -static UMSAudioDevice_ReturnCode UADSetDMABufferSize(_THIS, long bytes, long* bytes_ret ); -static UMSAudioDevice_ReturnCode UADSetVolume(_THIS, long volume ); -static UMSAudioDevice_ReturnCode UADSetBalance(_THIS, long balance ); -static UMSAudioDevice_ReturnCode UADSetChannels(_THIS, long channels ); -static UMSAudioDevice_ReturnCode UADPlayRemainingData(_THIS, boolean block ); -static UMSAudioDevice_ReturnCode UADEnableOutput(_THIS, string output, long* left_gain, long* right_gain); -static UMSAudioDevice_ReturnCode UADWrite(_THIS, UMSAudioTypes_Buffer* buff, long samples, long* samples_written); +static UMSAudioDevice_ReturnCode UADSetTimeFormat(_THIS, + UMSAudioTypes_TimeFormat + fmt); +static UMSAudioDevice_ReturnCode UADWriteBuffSize(_THIS, long *buff_size); +static UMSAudioDevice_ReturnCode UADWriteBuffRemain(_THIS, long *buff_size); +static UMSAudioDevice_ReturnCode UADWriteBuffUsed(_THIS, long *buff_size); +static UMSAudioDevice_ReturnCode UADSetDMABufferSize(_THIS, long bytes, + long *bytes_ret); +static UMSAudioDevice_ReturnCode UADSetVolume(_THIS, long volume); +static UMSAudioDevice_ReturnCode UADSetBalance(_THIS, long balance); +static UMSAudioDevice_ReturnCode UADSetChannels(_THIS, long channels); +static UMSAudioDevice_ReturnCode UADPlayRemainingData(_THIS, boolean block); +static UMSAudioDevice_ReturnCode UADEnableOutput(_THIS, string output, + long *left_gain, + long *right_gain); +static UMSAudioDevice_ReturnCode UADWrite(_THIS, UMSAudioTypes_Buffer * buff, + long samples, + long *samples_written); /* Audio driver bootstrap functions */ -static int Audio_Available(void) +static int +Audio_Available(void) { return 1; } -static void Audio_DeleteDevice(_THIS) +static void +Audio_DeleteDevice(_THIS) { - if(this->hidden->playbuf._buffer) SDL_free(this->hidden->playbuf._buffer); - if(this->hidden->fillbuf._buffer) SDL_free(this->hidden->fillbuf._buffer); - _somFree( this->hidden->umsdev ); + if (this->hidden->playbuf._buffer) + SDL_free(this->hidden->playbuf._buffer); + if (this->hidden->fillbuf._buffer) + SDL_free(this->hidden->fillbuf._buffer); + _somFree(this->hidden->umsdev); SDL_free(this->hidden); SDL_free(this); } -static SDL_AudioDevice *Audio_CreateDevice(int devindex) +static SDL_AudioDevice * +Audio_CreateDevice(int devindex) { SDL_AudioDevice *this; @@ -96,17 +110,18 @@ static SDL_AudioDevice *Audio_CreateDevice(int devindex) * Allocate and initialize management storage and private management * storage for this SDL-using library. */ - this = (SDL_AudioDevice *)SDL_malloc(sizeof(SDL_AudioDevice)); - if ( this ) { + this = (SDL_AudioDevice *) SDL_malloc(sizeof(SDL_AudioDevice)); + if (this) { SDL_memset(this, 0, (sizeof *this)); - this->hidden = (struct SDL_PrivateAudioData *)SDL_malloc((sizeof *this->hidden)); + this->hidden = (struct SDL_PrivateAudioData *) + SDL_malloc((sizeof *this->hidden)); } - if ( (this == NULL) || (this->hidden == NULL) ) { + if ((this == NULL) || (this->hidden == NULL)) { SDL_OutOfMemory(); - if ( this ) { + if (this) { SDL_free(this); } - return(0); + return (0); } SDL_memset(this->hidden, 0, (sizeof *this->hidden)); #ifdef DEBUG_AUDIO @@ -116,18 +131,18 @@ static SDL_AudioDevice *Audio_CreateDevice(int devindex) /* * Calls for UMS env initialization and audio object construction. */ - this->hidden->ev = somGetGlobalEnvironment(); + this->hidden->ev = somGetGlobalEnvironment(); this->hidden->umsdev = UMSAudioDeviceNew(); /* * Set the function pointers. */ - this->OpenAudio = UMS_OpenAudio; - this->WaitAudio = NULL; /* we do blocking output */ - this->PlayAudio = UMS_PlayAudio; + this->OpenAudio = UMS_OpenAudio; + this->WaitAudio = NULL; /* we do blocking output */ + this->PlayAudio = UMS_PlayAudio; this->GetAudioBuf = UMS_GetAudioBuf; - this->CloseAudio = UMS_CloseAudio; - this->free = Audio_DeleteDevice; + this->CloseAudio = UMS_CloseAudio; + this->free = Audio_DeleteDevice; #ifdef DEBUG_AUDIO fprintf(stderr, "done\n"); @@ -136,11 +151,12 @@ static SDL_AudioDevice *Audio_CreateDevice(int devindex) } AudioBootStrap UMS_bootstrap = { - UMS_DRIVER_NAME, "AUX UMS audio", - Audio_Available, Audio_CreateDevice + UMS_DRIVER_NAME, "AUX UMS audio", + Audio_Available, Audio_CreateDevice }; -static Uint8 *UMS_GetAudioBuf(_THIS) +static Uint8 * +UMS_GetAudioBuf(_THIS) { #ifdef DEBUG_AUDIO fprintf(stderr, "enter UMS_GetAudioBuf\n"); @@ -155,7 +171,8 @@ static Uint8 *UMS_GetAudioBuf(_THIS) */ } -static void UMS_CloseAudio(_THIS) +static void +UMS_CloseAudio(_THIS) { UMSAudioDevice_ReturnCode rc; @@ -167,43 +184,44 @@ static void UMS_CloseAudio(_THIS) rc = UADClose(this); } -static void UMS_PlayAudio(_THIS) +static void +UMS_PlayAudio(_THIS) { UMSAudioDevice_ReturnCode rc; - long samplesToWrite; - long samplesWritten; - UMSAudioTypes_Buffer swpbuf; + long samplesToWrite; + long samplesWritten; + UMSAudioTypes_Buffer swpbuf; #ifdef DEBUG_AUDIO fprintf(stderr, "enter UMS_PlayAudio\n"); #endif - samplesToWrite = this->hidden->playbuf._length/this->hidden->bytesPerSample; - do - { - rc = UADWrite(this, &this->hidden->playbuf, - samplesToWrite, - &samplesWritten ); - samplesToWrite -= samplesWritten; - - /* rc values: UMSAudioDevice_Success - * UMSAudioDevice_Failure - * UMSAudioDevice_Preempted - * UMSAudioDevice_Interrupted - * UMSAudioDevice_DeviceError - */ - if ( rc == UMSAudioDevice_DeviceError ) { + samplesToWrite = + this->hidden->playbuf._length / this->hidden->bytesPerSample; + do { + rc = UADWrite(this, &this->hidden->playbuf, + samplesToWrite, &samplesWritten); + samplesToWrite -= samplesWritten; + + /* rc values: UMSAudioDevice_Success + * UMSAudioDevice_Failure + * UMSAudioDevice_Preempted + * UMSAudioDevice_Interrupted + * UMSAudioDevice_DeviceError + */ + if (rc == UMSAudioDevice_DeviceError) { #ifdef DEBUG_AUDIO - fprintf(stderr, "Returning from PlayAudio with devices error\n"); + fprintf(stderr, "Returning from PlayAudio with devices error\n"); #endif - return; - } + return; + } } - while(samplesToWrite>0); + while (samplesToWrite > 0); SDL_LockAudio(); - SDL_memcpy( &swpbuf, &this->hidden->playbuf, sizeof(UMSAudioTypes_Buffer) ); - SDL_memcpy( &this->hidden->playbuf, &this->hidden->fillbuf, sizeof(UMSAudioTypes_Buffer) ); - SDL_memcpy( &this->hidden->fillbuf, &swpbuf, sizeof(UMSAudioTypes_Buffer) ); + SDL_memcpy(&swpbuf, &this->hidden->playbuf, sizeof(UMSAudioTypes_Buffer)); + SDL_memcpy(&this->hidden->playbuf, &this->hidden->fillbuf, + sizeof(UMSAudioTypes_Buffer)); + SDL_memcpy(&this->hidden->fillbuf, &swpbuf, sizeof(UMSAudioTypes_Buffer)); SDL_UnlockAudio(); #ifdef DEBUG_AUDIO @@ -212,133 +230,133 @@ static void UMS_PlayAudio(_THIS) } #if 0 -// /* Set the DSP frequency */ -// value = spec->freq; -// if ( ioctl(this->hidden->audio_fd, SOUND_PCM_WRITE_RATE, &value) < 0 ) { -// SDL_SetError("Couldn't set audio frequency"); -// return(-1); -// } -// spec->freq = value; +// /* Set the DSP frequency */ +// value = spec->freq; +// if ( ioctl(this->hidden->audio_fd, SOUND_PCM_WRITE_RATE, &value) < 0 ) { +// SDL_SetError("Couldn't set audio frequency"); +// return(-1); +// } +// spec->freq = value; #endif -static int UMS_OpenAudio(_THIS, SDL_AudioSpec *spec) +static int +UMS_OpenAudio(_THIS, SDL_AudioSpec * spec) { - char* audiodev = "/dev/paud0"; - long lgain; - long rgain; - long outRate; - long outBufSize; - long bitsPerSample; - long samplesPerSec; - long success; + char *audiodev = "/dev/paud0"; + long lgain; + long rgain; + long outRate; + long outBufSize; + long bitsPerSample; + long samplesPerSec; + long success; Uint16 test_format; - int frag_spec; + int frag_spec; UMSAudioDevice_ReturnCode rc; #ifdef DEBUG_AUDIO fprintf(stderr, "enter UMS_OpenAudio\n"); #endif - rc = UADOpen(this, audiodev,"PLAY", UMSAudioDevice_BlockingIO); - if ( rc != UMSAudioDevice_Success ) { - SDL_SetError("Couldn't open %s: %s", audiodev, strerror(errno)); - return -1; + rc = UADOpen(this, audiodev, "PLAY", UMSAudioDevice_BlockingIO); + if (rc != UMSAudioDevice_Success) { + SDL_SetError("Couldn't open %s: %s", audiodev, strerror(errno)); + return -1; } - - rc = UADSetAudioFormatType(this, "PCM"); + + rc = UADSetAudioFormatType(this, "PCM"); success = 0; test_format = SDL_FirstAudioFormat(spec->format); - do - { + do { #ifdef DEBUG_AUDIO fprintf(stderr, "Trying format 0x%4.4x\n", test_format); #endif - switch ( test_format ) - { + switch (test_format) { case AUDIO_U8: /* from the mac code: better ? */ /* sample_bits = spec->size / spec->samples / spec->channels * 8; */ - success = 1; + success = 1; bitsPerSample = 8; - rc = UADSetSampleRate(this, spec->freq << 16, &outRate ); - rc = UADSetByteOrder(this, "MSB"); /* irrelevant */ + rc = UADSetSampleRate(this, spec->freq << 16, &outRate); + rc = UADSetByteOrder(this, "MSB"); /* irrelevant */ rc = UADSetNumberFormat(this, "UNSIGNED"); break; case AUDIO_S8: - success = 1; + success = 1; bitsPerSample = 8; - rc = UADSetSampleRate(this, spec->freq << 16, &outRate ); - rc = UADSetByteOrder(this, "MSB"); /* irrelevant */ + rc = UADSetSampleRate(this, spec->freq << 16, &outRate); + rc = UADSetByteOrder(this, "MSB"); /* irrelevant */ rc = UADSetNumberFormat(this, "SIGNED"); break; case AUDIO_S16LSB: - success = 1; + success = 1; bitsPerSample = 16; - rc = UADSetSampleRate(this, spec->freq << 16, &outRate ); + rc = UADSetSampleRate(this, spec->freq << 16, &outRate); rc = UADSetByteOrder(this, "LSB"); rc = UADSetNumberFormat(this, "SIGNED"); break; case AUDIO_S16MSB: - success = 1; + success = 1; bitsPerSample = 16; - rc = UADSetSampleRate(this, spec->freq << 16, &outRate ); + rc = UADSetSampleRate(this, spec->freq << 16, &outRate); rc = UADSetByteOrder(this, "MSB"); rc = UADSetNumberFormat(this, "SIGNED"); break; case AUDIO_U16LSB: - success = 1; + success = 1; bitsPerSample = 16; - rc = UADSetSampleRate(this, spec->freq << 16, &outRate ); + rc = UADSetSampleRate(this, spec->freq << 16, &outRate); rc = UADSetByteOrder(this, "LSB"); rc = UADSetNumberFormat(this, "UNSIGNED"); break; case AUDIO_U16MSB: - success = 1; + success = 1; bitsPerSample = 16; - rc = UADSetSampleRate(this, spec->freq << 16, &outRate ); + rc = UADSetSampleRate(this, spec->freq << 16, &outRate); rc = UADSetByteOrder(this, "MSB"); rc = UADSetNumberFormat(this, "UNSIGNED"); break; default: break; } - if ( ! success ) { + if (!success) { test_format = SDL_NextAudioFormat(); } } - while ( ! success && test_format ); + while (!success && test_format); - if ( success == 0 ) { + if (success == 0) { SDL_SetError("Couldn't find any hardware audio formats"); return -1; } spec->format = test_format; - for ( frag_spec = 0; (0x01<size; ++frag_spec ); - if ( (0x01<size ) { + for (frag_spec = 0; (0x01 << frag_spec) < spec->size; ++frag_spec); + if ((0x01 << frag_spec) != spec->size) { SDL_SetError("Fragment size must be a power of two"); return -1; } - if ( frag_spec > 2048 ) frag_spec = 2048; + if (frag_spec > 2048) + frag_spec = 2048; - this->hidden->bytesPerSample = (bitsPerSample / 8) * spec->channels; - samplesPerSec = this->hidden->bytesPerSample * outRate; + this->hidden->bytesPerSample = (bitsPerSample / 8) * spec->channels; + samplesPerSec = this->hidden->bytesPerSample * outRate; - this->hidden->playbuf._length = 0; + this->hidden->playbuf._length = 0; this->hidden->playbuf._maximum = spec->size; - this->hidden->playbuf._buffer = (unsigned char*)SDL_malloc(spec->size); - this->hidden->fillbuf._length = 0; + this->hidden->playbuf._buffer = (unsigned char *) SDL_malloc(spec->size); + this->hidden->fillbuf._length = 0; this->hidden->fillbuf._maximum = spec->size; - this->hidden->fillbuf._buffer = (unsigned char*)SDL_malloc(spec->size); + this->hidden->fillbuf._buffer = (unsigned char *) SDL_malloc(spec->size); - rc = UADSetBitsPerSample(this, bitsPerSample ); - rc = UADSetDMABufferSize(this, frag_spec, &outBufSize ); - rc = UADSetChannels(this, spec->channels); /* functions reduces to mono or stereo */ + rc = UADSetBitsPerSample(this, bitsPerSample); + rc = UADSetDMABufferSize(this, frag_spec, &outBufSize); + rc = UADSetChannels(this, spec->channels); /* functions reduces to mono or stereo */ - lgain = 100; /*maximum left input gain*/ - rgain = 100; /*maimum right input gain*/ - rc = UADEnableOutput(this, "LINE_OUT",&lgain,&rgain); + lgain = 100; /*maximum left input gain */ + rgain = 100; /*maimum right input gain */ + rc = UADEnableOutput(this, "LINE_OUT", &lgain, &rgain); rc = UADInitialize(this); rc = UADStart(this); rc = UADSetVolume(this, 100); @@ -347,201 +365,197 @@ static int UMS_OpenAudio(_THIS, SDL_AudioSpec *spec) /* We're ready to rock and roll. :-) */ return 0; } - -static UMSAudioDevice_ReturnCode UADGetBitsPerSample(_THIS, long* bits) + +static UMSAudioDevice_ReturnCode +UADGetBitsPerSample(_THIS, long *bits) { - return UMSAudioDevice_get_bits_per_sample( this->hidden->umsdev, - this->hidden->ev, - bits ); + return UMSAudioDevice_get_bits_per_sample(this->hidden->umsdev, + this->hidden->ev, bits); } -static UMSAudioDevice_ReturnCode UADSetBitsPerSample(_THIS, long bits) +static UMSAudioDevice_ReturnCode +UADSetBitsPerSample(_THIS, long bits) { - return UMSAudioDevice_set_bits_per_sample( this->hidden->umsdev, - this->hidden->ev, - bits ); + return UMSAudioDevice_set_bits_per_sample(this->hidden->umsdev, + this->hidden->ev, bits); } -static UMSAudioDevice_ReturnCode UADSetSampleRate(_THIS, long rate, long* set_rate) +static UMSAudioDevice_ReturnCode +UADSetSampleRate(_THIS, long rate, long *set_rate) { /* from the mac code: sample rate = spec->freq << 16; */ - return UMSAudioDevice_set_sample_rate( this->hidden->umsdev, - this->hidden->ev, - rate, - set_rate ); + return UMSAudioDevice_set_sample_rate(this->hidden->umsdev, + this->hidden->ev, rate, set_rate); } -static UMSAudioDevice_ReturnCode UADSetByteOrder(_THIS, string byte_order) +static UMSAudioDevice_ReturnCode +UADSetByteOrder(_THIS, string byte_order) { - return UMSAudioDevice_set_byte_order( this->hidden->umsdev, - this->hidden->ev, - byte_order ); + return UMSAudioDevice_set_byte_order(this->hidden->umsdev, + this->hidden->ev, byte_order); } -static UMSAudioDevice_ReturnCode UADSetAudioFormatType(_THIS, string fmt) +static UMSAudioDevice_ReturnCode +UADSetAudioFormatType(_THIS, string fmt) { /* possible PCM, A_LAW or MU_LAW */ - return UMSAudioDevice_set_audio_format_type( this->hidden->umsdev, - this->hidden->ev, - fmt ); + return UMSAudioDevice_set_audio_format_type(this->hidden->umsdev, + this->hidden->ev, fmt); } -static UMSAudioDevice_ReturnCode UADSetNumberFormat(_THIS, string fmt) +static UMSAudioDevice_ReturnCode +UADSetNumberFormat(_THIS, string fmt) { /* possible SIGNED, UNSIGNED, or TWOS_COMPLEMENT */ - return UMSAudioDevice_set_number_format( this->hidden->umsdev, - this->hidden->ev, - fmt ); + return UMSAudioDevice_set_number_format(this->hidden->umsdev, + this->hidden->ev, fmt); } -static UMSAudioDevice_ReturnCode UADInitialize(_THIS) +static UMSAudioDevice_ReturnCode +UADInitialize(_THIS) { - return UMSAudioDevice_initialize( this->hidden->umsdev, - this->hidden->ev ); + return UMSAudioDevice_initialize(this->hidden->umsdev, this->hidden->ev); } -static UMSAudioDevice_ReturnCode UADStart(_THIS) +static UMSAudioDevice_ReturnCode +UADStart(_THIS) { - return UMSAudioDevice_start( this->hidden->umsdev, - this->hidden->ev ); + return UMSAudioDevice_start(this->hidden->umsdev, this->hidden->ev); } -static UMSAudioDevice_ReturnCode UADSetTimeFormat(_THIS, UMSAudioTypes_TimeFormat fmt ) +static UMSAudioDevice_ReturnCode +UADSetTimeFormat(_THIS, UMSAudioTypes_TimeFormat fmt) { /* * Switches the time format to the new format, immediately. * possible UMSAudioTypes_Msecs, UMSAudioTypes_Bytes or UMSAudioTypes_Samples */ - return UMSAudioDevice_set_time_format( this->hidden->umsdev, - this->hidden->ev, - fmt ); + return UMSAudioDevice_set_time_format(this->hidden->umsdev, + this->hidden->ev, fmt); } -static UMSAudioDevice_ReturnCode UADWriteBuffSize(_THIS, long* buff_size ) +static UMSAudioDevice_ReturnCode +UADWriteBuffSize(_THIS, long *buff_size) { /* * returns write buffer size in the current time format */ - return UMSAudioDevice_write_buff_size( this->hidden->umsdev, - this->hidden->ev, - buff_size ); + return UMSAudioDevice_write_buff_size(this->hidden->umsdev, + this->hidden->ev, buff_size); } -static UMSAudioDevice_ReturnCode UADWriteBuffRemain(_THIS, long* buff_size ) +static UMSAudioDevice_ReturnCode +UADWriteBuffRemain(_THIS, long *buff_size) { /* * returns amount of available space in the write buffer * in the current time format */ - return UMSAudioDevice_write_buff_remain( this->hidden->umsdev, - this->hidden->ev, - buff_size ); + return UMSAudioDevice_write_buff_remain(this->hidden->umsdev, + this->hidden->ev, buff_size); } -static UMSAudioDevice_ReturnCode UADWriteBuffUsed(_THIS, long* buff_size ) +static UMSAudioDevice_ReturnCode +UADWriteBuffUsed(_THIS, long *buff_size) { /* * returns amount of filled space in the write buffer * in the current time format */ - return UMSAudioDevice_write_buff_used( this->hidden->umsdev, - this->hidden->ev, - buff_size ); + return UMSAudioDevice_write_buff_used(this->hidden->umsdev, + this->hidden->ev, buff_size); } -static UMSAudioDevice_ReturnCode UADSetDMABufferSize(_THIS, long bytes, long* bytes_ret ) +static UMSAudioDevice_ReturnCode +UADSetDMABufferSize(_THIS, long bytes, long *bytes_ret) { /* * Request a new DMA buffer size, maximum requested size 2048. * Takes effect with next initialize() call. * Devices may or may not support DMA. */ - return UMSAudioDevice_set_DMA_buffer_size( this->hidden->umsdev, - this->hidden->ev, - bytes, - bytes_ret ); + return UMSAudioDevice_set_DMA_buffer_size(this->hidden->umsdev, + this->hidden->ev, + bytes, bytes_ret); } -static UMSAudioDevice_ReturnCode UADSetVolume(_THIS, long volume ) +static UMSAudioDevice_ReturnCode +UADSetVolume(_THIS, long volume) { /* * Set the volume. * Takes effect immediately. */ - return UMSAudioDevice_set_volume( this->hidden->umsdev, - this->hidden->ev, - volume ); + return UMSAudioDevice_set_volume(this->hidden->umsdev, + this->hidden->ev, volume); } -static UMSAudioDevice_ReturnCode UADSetBalance(_THIS, long balance ) +static UMSAudioDevice_ReturnCode +UADSetBalance(_THIS, long balance) { /* * Set the balance. * Takes effect immediately. */ - return UMSAudioDevice_set_balance( this->hidden->umsdev, - this->hidden->ev, - balance ); + return UMSAudioDevice_set_balance(this->hidden->umsdev, + this->hidden->ev, balance); } -static UMSAudioDevice_ReturnCode UADSetChannels(_THIS, long channels ) +static UMSAudioDevice_ReturnCode +UADSetChannels(_THIS, long channels) { /* * Set mono or stereo. * Takes effect with next initialize() call. */ - if ( channels != 1 ) channels = 2; - return UMSAudioDevice_set_number_of_channels( this->hidden->umsdev, - this->hidden->ev, - channels ); + if (channels != 1) + channels = 2; + return UMSAudioDevice_set_number_of_channels(this->hidden->umsdev, + this->hidden->ev, channels); } -static UMSAudioDevice_ReturnCode UADOpen(_THIS, string device, string mode, long flags) +static UMSAudioDevice_ReturnCode +UADOpen(_THIS, string device, string mode, long flags) { - return UMSAudioDevice_open( this->hidden->umsdev, - this->hidden->ev, - device, - mode, - flags ); + return UMSAudioDevice_open(this->hidden->umsdev, + this->hidden->ev, device, mode, flags); } -static UMSAudioDevice_ReturnCode UADWrite(_THIS, UMSAudioTypes_Buffer* buff, - long samples, - long* samples_written) +static UMSAudioDevice_ReturnCode +UADWrite(_THIS, UMSAudioTypes_Buffer * buff, + long samples, long *samples_written) { - return UMSAudioDevice_write( this->hidden->umsdev, - this->hidden->ev, - buff, - samples, - samples_written ); + return UMSAudioDevice_write(this->hidden->umsdev, + this->hidden->ev, + buff, samples, samples_written); } -static UMSAudioDevice_ReturnCode UADPlayRemainingData(_THIS, boolean block ) +static UMSAudioDevice_ReturnCode +UADPlayRemainingData(_THIS, boolean block) { - return UMSAudioDevice_play_remaining_data( this->hidden->umsdev, - this->hidden->ev, - block); + return UMSAudioDevice_play_remaining_data(this->hidden->umsdev, + this->hidden->ev, block); } -static UMSAudioDevice_ReturnCode UADStop(_THIS) +static UMSAudioDevice_ReturnCode +UADStop(_THIS) { - return UMSAudioDevice_stop( this->hidden->umsdev, - this->hidden->ev ); + return UMSAudioDevice_stop(this->hidden->umsdev, this->hidden->ev); } -static UMSAudioDevice_ReturnCode UADClose(_THIS) +static UMSAudioDevice_ReturnCode +UADClose(_THIS) { - return UMSAudioDevice_close( this->hidden->umsdev, - this->hidden->ev ); + return UMSAudioDevice_close(this->hidden->umsdev, this->hidden->ev); } -static UMSAudioDevice_ReturnCode UADEnableOutput(_THIS, string output, long* left_gain, long* right_gain) +static UMSAudioDevice_ReturnCode +UADEnableOutput(_THIS, string output, long *left_gain, long *right_gain) { - return UMSAudioDevice_enable_output( this->hidden->umsdev, - this->hidden->ev, - output, - left_gain, - right_gain ); + return UMSAudioDevice_enable_output(this->hidden->umsdev, + this->hidden->ev, + output, left_gain, right_gain); } +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/audio/ums/SDL_umsaudio.h b/src/audio/ums/SDL_umsaudio.h index 97410cc2f..e7c95d444 100644 --- a/src/audio/ums/SDL_umsaudio.h +++ b/src/audio/ums/SDL_umsaudio.h @@ -36,7 +36,7 @@ struct SDL_PrivateAudioData { /* Pointer to the (open) UMS audio device */ - Environment* ev; + Environment *ev; UMSAudioDevice umsdev; /* Raw mixing buffer */ @@ -47,4 +47,4 @@ struct SDL_PrivateAudioData }; #endif /* _SDL_UMSaudio_h */ - +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/audio/windib/SDL_dibaudio.c b/src/audio/windib/SDL_dibaudio.c index 9c10db52d..757e4e7c7 100644 --- a/src/audio/windib/SDL_dibaudio.c +++ b/src/audio/windib/SDL_dibaudio.c @@ -37,7 +37,7 @@ /* Audio driver functions */ -static int DIB_OpenAudio(_THIS, SDL_AudioSpec *spec); +static int DIB_OpenAudio(_THIS, SDL_AudioSpec * spec); static void DIB_ThreadInit(_THIS); static void DIB_WaitAudio(_THIS); static Uint8 *DIB_GetAudioBuf(_THIS); @@ -47,276 +47,290 @@ static void DIB_CloseAudio(_THIS); /* Audio driver bootstrap functions */ -static int Audio_Available(void) +static int +Audio_Available(void) { - return(1); + return (1); } -static void Audio_DeleteDevice(SDL_AudioDevice *device) +static void +Audio_DeleteDevice(SDL_AudioDevice * device) { - SDL_free(device->hidden); - SDL_free(device); + SDL_free(device->hidden); + SDL_free(device); } -static SDL_AudioDevice *Audio_CreateDevice(int devindex) +static SDL_AudioDevice * +Audio_CreateDevice(int devindex) { - SDL_AudioDevice *this; - - /* Initialize all variables that we clean on shutdown */ - this = (SDL_AudioDevice *)SDL_malloc(sizeof(SDL_AudioDevice)); - if ( this ) { - SDL_memset(this, 0, (sizeof *this)); - this->hidden = (struct SDL_PrivateAudioData *) - SDL_malloc((sizeof *this->hidden)); - } - if ( (this == NULL) || (this->hidden == NULL) ) { - SDL_OutOfMemory(); - if ( this ) { - SDL_free(this); - } - return(0); - } - SDL_memset(this->hidden, 0, (sizeof *this->hidden)); - - /* Set the function pointers */ - this->OpenAudio = DIB_OpenAudio; - this->ThreadInit = DIB_ThreadInit; - this->WaitAudio = DIB_WaitAudio; - this->PlayAudio = DIB_PlayAudio; - this->GetAudioBuf = DIB_GetAudioBuf; - this->WaitDone = DIB_WaitDone; - this->CloseAudio = DIB_CloseAudio; - - this->free = Audio_DeleteDevice; - - return this; + SDL_AudioDevice *this; + + /* Initialize all variables that we clean on shutdown */ + this = (SDL_AudioDevice *) SDL_malloc(sizeof(SDL_AudioDevice)); + if (this) { + SDL_memset(this, 0, (sizeof *this)); + this->hidden = (struct SDL_PrivateAudioData *) + SDL_malloc((sizeof *this->hidden)); + } + if ((this == NULL) || (this->hidden == NULL)) { + SDL_OutOfMemory(); + if (this) { + SDL_free(this); + } + return (0); + } + SDL_memset(this->hidden, 0, (sizeof *this->hidden)); + + /* Set the function pointers */ + this->OpenAudio = DIB_OpenAudio; + this->ThreadInit = DIB_ThreadInit; + this->WaitAudio = DIB_WaitAudio; + this->PlayAudio = DIB_PlayAudio; + this->GetAudioBuf = DIB_GetAudioBuf; + this->WaitDone = DIB_WaitDone; + this->CloseAudio = DIB_CloseAudio; + + this->free = Audio_DeleteDevice; + + return this; } AudioBootStrap WAVEOUT_bootstrap = { - "waveout", "Win95/98/NT/2000 WaveOut", - Audio_Available, Audio_CreateDevice + "waveout", "Win95/98/NT/2000 WaveOut", + Audio_Available, Audio_CreateDevice }; /* The Win32 callback for filling the WAVE device */ -static void CALLBACK FillSound(HWAVEOUT hwo, UINT uMsg, DWORD_PTR dwInstance, - DWORD dwParam1, DWORD dwParam2) +static void CALLBACK +FillSound(HWAVEOUT hwo, UINT uMsg, DWORD_PTR dwInstance, + DWORD dwParam1, DWORD dwParam2) { - SDL_AudioDevice *this = (SDL_AudioDevice *)dwInstance; + SDL_AudioDevice *this = (SDL_AudioDevice *) dwInstance; - /* Only service "buffer done playing" messages */ - if ( uMsg != WOM_DONE ) - return; + /* Only service "buffer done playing" messages */ + if (uMsg != WOM_DONE) + return; - /* Signal that we are done playing a buffer */ + /* Signal that we are done playing a buffer */ #if defined(_WIN32_WCE) && (_WIN32_WCE < 300) - ReleaseSemaphoreCE(audio_sem, 1, NULL); + ReleaseSemaphoreCE(audio_sem, 1, NULL); #else - ReleaseSemaphore(audio_sem, 1, NULL); + ReleaseSemaphore(audio_sem, 1, NULL); #endif } -static void SetMMerror(char *function, MMRESULT code) +static void +SetMMerror(char *function, MMRESULT code) { - size_t len; - char errbuf[MAXERRORLENGTH]; + size_t len; + char errbuf[MAXERRORLENGTH]; #ifdef _WIN32_WCE - wchar_t werrbuf[MAXERRORLENGTH]; + wchar_t werrbuf[MAXERRORLENGTH]; #endif - SDL_snprintf(errbuf, SDL_arraysize(errbuf), "%s: ", function); - len = SDL_strlen(errbuf); + SDL_snprintf(errbuf, SDL_arraysize(errbuf), "%s: ", function); + len = SDL_strlen(errbuf); #ifdef _WIN32_WCE - /* UNICODE version */ - waveOutGetErrorText(code, werrbuf, MAXERRORLENGTH-len); - WideCharToMultiByte(CP_ACP,0,werrbuf,-1,errbuf+len,MAXERRORLENGTH-len,NULL,NULL); + /* UNICODE version */ + waveOutGetErrorText(code, werrbuf, MAXERRORLENGTH - len); + WideCharToMultiByte(CP_ACP, 0, werrbuf, -1, errbuf + len, + MAXERRORLENGTH - len, NULL, NULL); #else - waveOutGetErrorText(code, errbuf+len, (UINT)(MAXERRORLENGTH-len)); + waveOutGetErrorText(code, errbuf + len, (UINT) (MAXERRORLENGTH - len)); #endif - SDL_SetError("%s",errbuf); + SDL_SetError("%s", errbuf); } /* Set high priority for the audio thread */ -static void DIB_ThreadInit(_THIS) +static void +DIB_ThreadInit(_THIS) { - SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST); + SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST); } -void DIB_WaitAudio(_THIS) +void +DIB_WaitAudio(_THIS) { - /* Wait for an audio chunk to finish */ + /* Wait for an audio chunk to finish */ #if defined(_WIN32_WCE) && (_WIN32_WCE < 300) - WaitForSemaphoreCE(audio_sem, INFINITE); + WaitForSemaphoreCE(audio_sem, INFINITE); #else - WaitForSingleObject(audio_sem, INFINITE); + WaitForSingleObject(audio_sem, INFINITE); #endif } -Uint8 *DIB_GetAudioBuf(_THIS) +Uint8 * +DIB_GetAudioBuf(_THIS) { - Uint8 *retval; + Uint8 *retval; - retval = (Uint8 *)(wavebuf[next_buffer].lpData); - return retval; + retval = (Uint8 *) (wavebuf[next_buffer].lpData); + return retval; } -void DIB_PlayAudio(_THIS) +void +DIB_PlayAudio(_THIS) { - /* Queue it up */ - waveOutWrite(sound, &wavebuf[next_buffer], sizeof(wavebuf[0])); - next_buffer = (next_buffer+1)%NUM_BUFFERS; + /* Queue it up */ + waveOutWrite(sound, &wavebuf[next_buffer], sizeof(wavebuf[0])); + next_buffer = (next_buffer + 1) % NUM_BUFFERS; } -void DIB_WaitDone(_THIS) +void +DIB_WaitDone(_THIS) { - int i, left; - - do { - left = NUM_BUFFERS; - for ( i=0; i 0 ) { - SDL_Delay(100); - } - } while ( left > 0 ); + int i, left; + + do { + left = NUM_BUFFERS; + for (i = 0; i < NUM_BUFFERS; ++i) { + if (wavebuf[i].dwFlags & WHDR_DONE) { + --left; + } + } + if (left > 0) { + SDL_Delay(100); + } + } + while (left > 0); } -void DIB_CloseAudio(_THIS) +void +DIB_CloseAudio(_THIS) { - int i; + int i; - /* Close up audio */ - if ( audio_sem ) { + /* Close up audio */ + if (audio_sem) { #if defined(_WIN32_WCE) && (_WIN32_WCE < 300) - CloseSynchHandle(audio_sem); + CloseSynchHandle(audio_sem); #else - CloseHandle(audio_sem); + CloseHandle(audio_sem); #endif - } - if ( sound ) { - waveOutClose(sound); - } - - /* Clean up mixing buffers */ - for ( i=0; iformat & 0xFF ) { - case 8: - /* Unsigned 8 bit audio data */ - spec->format = AUDIO_U8; - waveformat.wBitsPerSample = 8; - break; - case 16: - /* Signed 16 bit audio data */ - spec->format = AUDIO_S16; - waveformat.wBitsPerSample = 16; - break; - default: - SDL_SetError("Unsupported audio format"); - return(-1); - } - waveformat.nChannels = spec->channels; - waveformat.nSamplesPerSec = spec->freq; - waveformat.nBlockAlign = - waveformat.nChannels * (waveformat.wBitsPerSample/8); - waveformat.nAvgBytesPerSec = - waveformat.nSamplesPerSec * waveformat.nBlockAlign; - - /* Check the buffer size -- minimum of 1/4 second (word aligned) */ - if ( spec->samples < (spec->freq/4) ) - spec->samples = ((spec->freq/4)+3)&~3; - - /* Update the fragment size as size in bytes */ - SDL_CalculateAudioSpec(spec); - - /* Open the audio device */ - result = waveOutOpen(&sound, WAVE_MAPPER, &waveformat, - (DWORD_PTR)FillSound, (DWORD_PTR)this, CALLBACK_FUNCTION); - if ( result != MMSYSERR_NOERROR ) { - SetMMerror("waveOutOpen()", result); - return(-1); - } - + MMRESULT result; + int i; + WAVEFORMATEX waveformat; + + /* Initialize the wavebuf structures for closing */ + sound = NULL; + audio_sem = NULL; + for (i = 0; i < NUM_BUFFERS; ++i) + wavebuf[i].dwUser = 0xFFFF; + mixbuf = NULL; + + /* Set basic WAVE format parameters */ + SDL_memset(&waveformat, 0, sizeof(waveformat)); + waveformat.wFormatTag = WAVE_FORMAT_PCM; + + /* Determine the audio parameters from the AudioSpec */ + switch (spec->format & 0xFF) { + case 8: + /* Unsigned 8 bit audio data */ + spec->format = AUDIO_U8; + waveformat.wBitsPerSample = 8; + break; + case 16: + /* Signed 16 bit audio data */ + spec->format = AUDIO_S16; + waveformat.wBitsPerSample = 16; + break; + default: + SDL_SetError("Unsupported audio format"); + return (-1); + } + waveformat.nChannels = spec->channels; + waveformat.nSamplesPerSec = spec->freq; + waveformat.nBlockAlign = + waveformat.nChannels * (waveformat.wBitsPerSample / 8); + waveformat.nAvgBytesPerSec = + waveformat.nSamplesPerSec * waveformat.nBlockAlign; + + /* Check the buffer size -- minimum of 1/4 second (word aligned) */ + if (spec->samples < (spec->freq / 4)) + spec->samples = ((spec->freq / 4) + 3) & ~3; + + /* Update the fragment size as size in bytes */ + SDL_CalculateAudioSpec(spec); + + /* Open the audio device */ + result = waveOutOpen(&sound, WAVE_MAPPER, &waveformat, + (DWORD_PTR) FillSound, (DWORD_PTR) this, + CALLBACK_FUNCTION); + if (result != MMSYSERR_NOERROR) { + SetMMerror("waveOutOpen()", result); + return (-1); + } #ifdef SOUND_DEBUG - /* Check the sound device we retrieved */ - { - WAVEOUTCAPS caps; - - result = waveOutGetDevCaps((UINT)sound, &caps, sizeof(caps)); - if ( result != MMSYSERR_NOERROR ) { - SetMMerror("waveOutGetDevCaps()", result); - return(-1); - } - printf("Audio device: %s\n", caps.szPname); - } + /* Check the sound device we retrieved */ + { + WAVEOUTCAPS caps; + + result = waveOutGetDevCaps((UINT) sound, &caps, sizeof(caps)); + if (result != MMSYSERR_NOERROR) { + SetMMerror("waveOutGetDevCaps()", result); + return (-1); + } + printf("Audio device: %s\n", caps.szPname); + } #endif - /* Create the audio buffer semaphore */ + /* Create the audio buffer semaphore */ #if defined(_WIN32_WCE) && (_WIN32_WCE < 300) - audio_sem = CreateSemaphoreCE(NULL, NUM_BUFFERS-1, NUM_BUFFERS, NULL); + audio_sem = CreateSemaphoreCE(NULL, NUM_BUFFERS - 1, NUM_BUFFERS, NULL); #else - audio_sem = CreateSemaphore(NULL, NUM_BUFFERS-1, NUM_BUFFERS, NULL); + audio_sem = CreateSemaphore(NULL, NUM_BUFFERS - 1, NUM_BUFFERS, NULL); #endif - if ( audio_sem == NULL ) { - SDL_SetError("Couldn't create semaphore"); - return(-1); - } - - /* Create the sound buffers */ - mixbuf = (Uint8 *)SDL_malloc(NUM_BUFFERS*spec->size); - if ( mixbuf == NULL ) { - SDL_SetError("Out of memory"); - return(-1); - } - for ( i = 0; i < NUM_BUFFERS; ++i ) { - SDL_memset(&wavebuf[i], 0, sizeof(wavebuf[i])); - wavebuf[i].lpData = (LPSTR) &mixbuf[i*spec->size]; - wavebuf[i].dwBufferLength = spec->size; - wavebuf[i].dwFlags = WHDR_DONE; - result = waveOutPrepareHeader(sound, &wavebuf[i], - sizeof(wavebuf[i])); - if ( result != MMSYSERR_NOERROR ) { - SetMMerror("waveOutPrepareHeader()", result); - return(-1); - } - } - - /* Ready to go! */ - next_buffer = 0; - return(0); + if (audio_sem == NULL) { + SDL_SetError("Couldn't create semaphore"); + return (-1); + } + + /* Create the sound buffers */ + mixbuf = (Uint8 *) SDL_malloc(NUM_BUFFERS * spec->size); + if (mixbuf == NULL) { + SDL_SetError("Out of memory"); + return (-1); + } + for (i = 0; i < NUM_BUFFERS; ++i) { + SDL_memset(&wavebuf[i], 0, sizeof(wavebuf[i])); + wavebuf[i].lpData = (LPSTR) & mixbuf[i * spec->size]; + wavebuf[i].dwBufferLength = spec->size; + wavebuf[i].dwFlags = WHDR_DONE; + result = waveOutPrepareHeader(sound, &wavebuf[i], sizeof(wavebuf[i])); + if (result != MMSYSERR_NOERROR) { + SetMMerror("waveOutPrepareHeader()", result); + return (-1); + } + } + + /* Ready to go! */ + next_buffer = 0; + return (0); } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/audio/windib/SDL_dibaudio.h b/src/audio/windib/SDL_dibaudio.h index f6a6e0857..c5e7d1468 100644 --- a/src/audio/windib/SDL_dibaudio.h +++ b/src/audio/windib/SDL_dibaudio.h @@ -29,14 +29,15 @@ /* Hidden "this" pointer for the video functions */ #define _THIS SDL_AudioDevice *this -#define NUM_BUFFERS 2 /* -- Don't lower this! */ - -struct SDL_PrivateAudioData { - HWAVEOUT sound; - HANDLE audio_sem; - Uint8 *mixbuf; /* The raw allocated mixing buffer */ - WAVEHDR wavebuf[NUM_BUFFERS]; /* Wave audio fragments */ - int next_buffer; +#define NUM_BUFFERS 2 /* -- Don't lower this! */ + +struct SDL_PrivateAudioData +{ + HWAVEOUT sound; + HANDLE audio_sem; + Uint8 *mixbuf; /* The raw allocated mixing buffer */ + WAVEHDR wavebuf[NUM_BUFFERS]; /* Wave audio fragments */ + int next_buffer; }; /* Old variable names */ @@ -47,3 +48,4 @@ struct SDL_PrivateAudioData { #define next_buffer (this->hidden->next_buffer) #endif /* _SDL_lowaudio_h */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/audio/windx5/SDL_dx5audio.c b/src/audio/windx5/SDL_dx5audio.c index 26bd2e8f6..db4d62cc4 100644 --- a/src/audio/windx5/SDL_dx5audio.c +++ b/src/audio/windx5/SDL_dx5audio.c @@ -32,10 +32,10 @@ //#define USE_POSITION_NOTIFY /* DirectX function pointers for audio */ -HRESULT (WINAPI *DSoundCreate)(LPGUID, LPDIRECTSOUND *, LPUNKNOWN); +HRESULT(WINAPI * DSoundCreate) (LPGUID, LPDIRECTSOUND *, LPUNKNOWN); /* Audio driver functions */ -static int DX5_OpenAudio(_THIS, SDL_AudioSpec *spec); +static int DX5_OpenAudio(_THIS, SDL_AudioSpec * spec); static void DX5_ThreadInit(_THIS); static void DX5_WaitAudio_BusyWait(_THIS); #ifdef USE_POSITION_NOTIFY @@ -48,658 +48,686 @@ static void DX5_CloseAudio(_THIS); /* Audio driver bootstrap functions */ -static int Audio_Available(void) +static int +Audio_Available(void) { - HINSTANCE DSoundDLL; - int dsound_ok; - - /* Version check DSOUND.DLL (Is DirectX okay?) */ - dsound_ok = 0; - DSoundDLL = LoadLibrary(TEXT("DSOUND.DLL")); - if ( DSoundDLL != NULL ) { - /* We just use basic DirectSound, we're okay */ - /* Yay! */ - /* Unfortunately, the sound drivers on NT have - higher latencies than the audio buffers used - by many SDL applications, so there are gaps - in the audio - it sounds terrible. Punt for now. - */ - OSVERSIONINFO ver; - ver.dwOSVersionInfoSize = sizeof (OSVERSIONINFO); - GetVersionEx(&ver); - switch (ver.dwPlatformId) { - case VER_PLATFORM_WIN32_NT: - if ( ver.dwMajorVersion > 4 ) { - /* Win2K */ - dsound_ok = 1; - } else { - /* WinNT */ - dsound_ok = 0; - } - break; - default: - /* Win95 or Win98 */ - dsound_ok = 1; - break; - } - /* Now check for DirectX 5 or better - otherwise - * we will fail later in DX5_OpenAudio without a chance - * to fall back to the DIB driver. */ - if (dsound_ok) { - /* DirectSoundCaptureCreate was added in DX5 */ - if (!GetProcAddress(DSoundDLL, TEXT("DirectSoundCaptureCreate"))) - dsound_ok = 0; - - } - /* Clean up.. */ - FreeLibrary(DSoundDLL); - } - return(dsound_ok); + HINSTANCE DSoundDLL; + int dsound_ok; + + /* Version check DSOUND.DLL (Is DirectX okay?) */ + dsound_ok = 0; + DSoundDLL = LoadLibrary(TEXT("DSOUND.DLL")); + if (DSoundDLL != NULL) { + /* We just use basic DirectSound, we're okay */ + /* Yay! */ + /* Unfortunately, the sound drivers on NT have + higher latencies than the audio buffers used + by many SDL applications, so there are gaps + in the audio - it sounds terrible. Punt for now. + */ + OSVERSIONINFO ver; + ver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); + GetVersionEx(&ver); + switch (ver.dwPlatformId) { + case VER_PLATFORM_WIN32_NT: + if (ver.dwMajorVersion > 4) { + /* Win2K */ + dsound_ok = 1; + } else { + /* WinNT */ + dsound_ok = 0; + } + break; + default: + /* Win95 or Win98 */ + dsound_ok = 1; + break; + } + /* Now check for DirectX 5 or better - otherwise + * we will fail later in DX5_OpenAudio without a chance + * to fall back to the DIB driver. */ + if (dsound_ok) { + /* DirectSoundCaptureCreate was added in DX5 */ + if (!GetProcAddress(DSoundDLL, TEXT("DirectSoundCaptureCreate"))) + dsound_ok = 0; + + } + /* Clean up.. */ + FreeLibrary(DSoundDLL); + } + return (dsound_ok); } /* Functions for loading the DirectX functions dynamically */ static HINSTANCE DSoundDLL = NULL; -static void DX5_Unload(void) +static void +DX5_Unload(void) { - if ( DSoundDLL != NULL ) { - FreeLibrary(DSoundDLL); - DSoundCreate = NULL; - DSoundDLL = NULL; - } + if (DSoundDLL != NULL) { + FreeLibrary(DSoundDLL); + DSoundCreate = NULL; + DSoundDLL = NULL; + } } -static int DX5_Load(void) +static int +DX5_Load(void) { - int status; - - DX5_Unload(); - DSoundDLL = LoadLibrary(TEXT("DSOUND.DLL")); - if ( DSoundDLL != NULL ) { - DSoundCreate = (void *)GetProcAddress(DSoundDLL, - TEXT("DirectSoundCreate")); - } - if ( DSoundDLL && DSoundCreate ) { - status = 0; - } else { - DX5_Unload(); - status = -1; - } - return status; + int status; + + DX5_Unload(); + DSoundDLL = LoadLibrary(TEXT("DSOUND.DLL")); + if (DSoundDLL != NULL) { + DSoundCreate = (void *) GetProcAddress(DSoundDLL, + TEXT("DirectSoundCreate")); + } + if (DSoundDLL && DSoundCreate) { + status = 0; + } else { + DX5_Unload(); + status = -1; + } + return status; } -static void Audio_DeleteDevice(SDL_AudioDevice *device) +static void +Audio_DeleteDevice(SDL_AudioDevice * device) { - DX5_Unload(); - SDL_free(device->hidden); - SDL_free(device); + DX5_Unload(); + SDL_free(device->hidden); + SDL_free(device); } -static SDL_AudioDevice *Audio_CreateDevice(int devindex) +static SDL_AudioDevice * +Audio_CreateDevice(int devindex) { - SDL_AudioDevice *this; - - /* Load DirectX */ - if ( DX5_Load() < 0 ) { - return(NULL); - } - - /* Initialize all variables that we clean on shutdown */ - this = (SDL_AudioDevice *)SDL_malloc(sizeof(SDL_AudioDevice)); - if ( this ) { - SDL_memset(this, 0, (sizeof *this)); - this->hidden = (struct SDL_PrivateAudioData *) - SDL_malloc((sizeof *this->hidden)); - } - if ( (this == NULL) || (this->hidden == NULL) ) { - SDL_OutOfMemory(); - if ( this ) { - SDL_free(this); - } - return(0); - } - SDL_memset(this->hidden, 0, (sizeof *this->hidden)); - - /* Set the function pointers */ - this->OpenAudio = DX5_OpenAudio; - this->ThreadInit = DX5_ThreadInit; - this->WaitAudio = DX5_WaitAudio_BusyWait; - this->PlayAudio = DX5_PlayAudio; - this->GetAudioBuf = DX5_GetAudioBuf; - this->WaitDone = DX5_WaitDone; - this->CloseAudio = DX5_CloseAudio; - - this->free = Audio_DeleteDevice; - - return this; + SDL_AudioDevice *this; + + /* Load DirectX */ + if (DX5_Load() < 0) { + return (NULL); + } + + /* Initialize all variables that we clean on shutdown */ + this = (SDL_AudioDevice *) SDL_malloc(sizeof(SDL_AudioDevice)); + if (this) { + SDL_memset(this, 0, (sizeof *this)); + this->hidden = (struct SDL_PrivateAudioData *) + SDL_malloc((sizeof *this->hidden)); + } + if ((this == NULL) || (this->hidden == NULL)) { + SDL_OutOfMemory(); + if (this) { + SDL_free(this); + } + return (0); + } + SDL_memset(this->hidden, 0, (sizeof *this->hidden)); + + /* Set the function pointers */ + this->OpenAudio = DX5_OpenAudio; + this->ThreadInit = DX5_ThreadInit; + this->WaitAudio = DX5_WaitAudio_BusyWait; + this->PlayAudio = DX5_PlayAudio; + this->GetAudioBuf = DX5_GetAudioBuf; + this->WaitDone = DX5_WaitDone; + this->CloseAudio = DX5_CloseAudio; + + this->free = Audio_DeleteDevice; + + return this; } AudioBootStrap DSOUND_bootstrap = { - "dsound", "Win95/98/2000 DirectSound", - Audio_Available, Audio_CreateDevice + "dsound", "Win95/98/2000 DirectSound", + Audio_Available, Audio_CreateDevice }; -static void SetDSerror(const char *function, int code) +static void +SetDSerror(const char *function, int code) { - static const char *error; - static char errbuf[1024]; - - errbuf[0] = 0; - switch (code) { - case E_NOINTERFACE: - error = - "Unsupported interface\n-- Is DirectX 5.0 or later installed?"; - break; - case DSERR_ALLOCATED: - error = "Audio device in use"; - break; - case DSERR_BADFORMAT: - error = "Unsupported audio format"; - break; - case DSERR_BUFFERLOST: - error = "Mixing buffer was lost"; - break; - case DSERR_CONTROLUNAVAIL: - error = "Control requested is not available"; - break; - case DSERR_INVALIDCALL: - error = "Invalid call for the current state"; - break; - case DSERR_INVALIDPARAM: - error = "Invalid parameter"; - break; - case DSERR_NODRIVER: - error = "No audio device found"; - break; - case DSERR_OUTOFMEMORY: - error = "Out of memory"; - break; - case DSERR_PRIOLEVELNEEDED: - error = "Caller doesn't have priority"; - break; - case DSERR_UNSUPPORTED: - error = "Function not supported"; - break; - default: - SDL_snprintf(errbuf, SDL_arraysize(errbuf), - "%s: Unknown DirectSound error: 0x%x", - function, code); - break; - } - if ( ! errbuf[0] ) { - SDL_snprintf(errbuf, SDL_arraysize(errbuf), "%s: %s", function, error); - } - SDL_SetError("%s", errbuf); - return; + static const char *error; + static char errbuf[1024]; + + errbuf[0] = 0; + switch (code) { + case E_NOINTERFACE: + error = + "Unsupported interface\n-- Is DirectX 5.0 or later installed?"; + break; + case DSERR_ALLOCATED: + error = "Audio device in use"; + break; + case DSERR_BADFORMAT: + error = "Unsupported audio format"; + break; + case DSERR_BUFFERLOST: + error = "Mixing buffer was lost"; + break; + case DSERR_CONTROLUNAVAIL: + error = "Control requested is not available"; + break; + case DSERR_INVALIDCALL: + error = "Invalid call for the current state"; + break; + case DSERR_INVALIDPARAM: + error = "Invalid parameter"; + break; + case DSERR_NODRIVER: + error = "No audio device found"; + break; + case DSERR_OUTOFMEMORY: + error = "Out of memory"; + break; + case DSERR_PRIOLEVELNEEDED: + error = "Caller doesn't have priority"; + break; + case DSERR_UNSUPPORTED: + error = "Function not supported"; + break; + default: + SDL_snprintf(errbuf, SDL_arraysize(errbuf), + "%s: Unknown DirectSound error: 0x%x", function, code); + break; + } + if (!errbuf[0]) { + SDL_snprintf(errbuf, SDL_arraysize(errbuf), "%s: %s", function, + error); + } + SDL_SetError("%s", errbuf); + return; } /* DirectSound needs to be associated with a window */ static HWND mainwin = NULL; /* */ -void DX5_SoundFocus(HWND hwnd) +void +DX5_SoundFocus(HWND hwnd) { - mainwin = hwnd; + mainwin = hwnd; } -static void DX5_ThreadInit(_THIS) +static void +DX5_ThreadInit(_THIS) { - SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST); + SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST); } -static void DX5_WaitAudio_BusyWait(_THIS) +static void +DX5_WaitAudio_BusyWait(_THIS) { - DWORD status; - DWORD cursor, junk; - HRESULT result; - - /* Semi-busy wait, since we have no way of getting play notification - on a primary mixing buffer located in hardware (DirectX 5.0) - */ - result = IDirectSoundBuffer_GetCurrentPosition(mixbuf, &junk, &cursor); - if ( result != DS_OK ) { - if ( result == DSERR_BUFFERLOST ) { - IDirectSoundBuffer_Restore(mixbuf); - } + DWORD status; + DWORD cursor, junk; + HRESULT result; + + /* Semi-busy wait, since we have no way of getting play notification + on a primary mixing buffer located in hardware (DirectX 5.0) + */ + result = IDirectSoundBuffer_GetCurrentPosition(mixbuf, &junk, &cursor); + if (result != DS_OK) { + if (result == DSERR_BUFFERLOST) { + IDirectSoundBuffer_Restore(mixbuf); + } #ifdef DEBUG_SOUND - SetDSerror("DirectSound GetCurrentPosition", result); + SetDSerror("DirectSound GetCurrentPosition", result); #endif - return; - } - - while ( (cursor/mixlen) == lastchunk ) { - /* FIXME: find out how much time is left and sleep that long */ - SDL_Delay(1); - - /* Try to restore a lost sound buffer */ - IDirectSoundBuffer_GetStatus(mixbuf, &status); - if ( (status&DSBSTATUS_BUFFERLOST) ) { - IDirectSoundBuffer_Restore(mixbuf); - IDirectSoundBuffer_GetStatus(mixbuf, &status); - if ( (status&DSBSTATUS_BUFFERLOST) ) { - break; - } - } - if ( ! (status&DSBSTATUS_PLAYING) ) { - result = IDirectSoundBuffer_Play(mixbuf, 0, 0, DSBPLAY_LOOPING); - if ( result == DS_OK ) { - continue; - } + return; + } + + while ((cursor / mixlen) == lastchunk) { + /* FIXME: find out how much time is left and sleep that long */ + SDL_Delay(1); + + /* Try to restore a lost sound buffer */ + IDirectSoundBuffer_GetStatus(mixbuf, &status); + if ((status & DSBSTATUS_BUFFERLOST)) { + IDirectSoundBuffer_Restore(mixbuf); + IDirectSoundBuffer_GetStatus(mixbuf, &status); + if ((status & DSBSTATUS_BUFFERLOST)) { + break; + } + } + if (!(status & DSBSTATUS_PLAYING)) { + result = IDirectSoundBuffer_Play(mixbuf, 0, 0, DSBPLAY_LOOPING); + if (result == DS_OK) { + continue; + } #ifdef DEBUG_SOUND - SetDSerror("DirectSound Play", result); + SetDSerror("DirectSound Play", result); #endif - return; - } - - /* Find out where we are playing */ - result = IDirectSoundBuffer_GetCurrentPosition(mixbuf, - &junk, &cursor); - if ( result != DS_OK ) { - SetDSerror("DirectSound GetCurrentPosition", result); - return; - } - } + return; + } + + /* Find out where we are playing */ + result = IDirectSoundBuffer_GetCurrentPosition(mixbuf, + &junk, &cursor); + if (result != DS_OK) { + SetDSerror("DirectSound GetCurrentPosition", result); + return; + } + } } #ifdef USE_POSITION_NOTIFY -static void DX6_WaitAudio_EventWait(_THIS) +static void +DX6_WaitAudio_EventWait(_THIS) { - DWORD status; - HRESULT result; - - /* Try to restore a lost sound buffer */ - IDirectSoundBuffer_GetStatus(mixbuf, &status); - if ( (status&DSBSTATUS_BUFFERLOST) ) { - IDirectSoundBuffer_Restore(mixbuf); - IDirectSoundBuffer_GetStatus(mixbuf, &status); - if ( (status&DSBSTATUS_BUFFERLOST) ) { - return; - } - } - if ( ! (status&DSBSTATUS_PLAYING) ) { - result = IDirectSoundBuffer_Play(mixbuf, 0, 0, DSBPLAY_LOOPING); - if ( result != DS_OK ) { + DWORD status; + HRESULT result; + + /* Try to restore a lost sound buffer */ + IDirectSoundBuffer_GetStatus(mixbuf, &status); + if ((status & DSBSTATUS_BUFFERLOST)) { + IDirectSoundBuffer_Restore(mixbuf); + IDirectSoundBuffer_GetStatus(mixbuf, &status); + if ((status & DSBSTATUS_BUFFERLOST)) { + return; + } + } + if (!(status & DSBSTATUS_PLAYING)) { + result = IDirectSoundBuffer_Play(mixbuf, 0, 0, DSBPLAY_LOOPING); + if (result != DS_OK) { #ifdef DEBUG_SOUND - SetDSerror("DirectSound Play", result); + SetDSerror("DirectSound Play", result); #endif - return; - } - } - WaitForSingleObject(audio_event, INFINITE); + return; + } + } + WaitForSingleObject(audio_event, INFINITE); } #endif /* USE_POSITION_NOTIFY */ -static void DX5_PlayAudio(_THIS) +static void +DX5_PlayAudio(_THIS) { - /* Unlock the buffer, allowing it to play */ - if ( locked_buf ) { - IDirectSoundBuffer_Unlock(mixbuf, locked_buf, mixlen, NULL, 0); - } + /* Unlock the buffer, allowing it to play */ + if (locked_buf) { + IDirectSoundBuffer_Unlock(mixbuf, locked_buf, mixlen, NULL, 0); + } } -static Uint8 *DX5_GetAudioBuf(_THIS) +static Uint8 * +DX5_GetAudioBuf(_THIS) { - DWORD cursor, junk; - HRESULT result; - DWORD rawlen; - - /* Figure out which blocks to fill next */ - locked_buf = NULL; - result = IDirectSoundBuffer_GetCurrentPosition(mixbuf, &junk, &cursor); - if ( result == DSERR_BUFFERLOST ) { - IDirectSoundBuffer_Restore(mixbuf); - result = IDirectSoundBuffer_GetCurrentPosition(mixbuf, - &junk, &cursor); - } - if ( result != DS_OK ) { - SetDSerror("DirectSound GetCurrentPosition", result); - return(NULL); - } - cursor /= mixlen; + DWORD cursor, junk; + HRESULT result; + DWORD rawlen; + + /* Figure out which blocks to fill next */ + locked_buf = NULL; + result = IDirectSoundBuffer_GetCurrentPosition(mixbuf, &junk, &cursor); + if (result == DSERR_BUFFERLOST) { + IDirectSoundBuffer_Restore(mixbuf); + result = IDirectSoundBuffer_GetCurrentPosition(mixbuf, + &junk, &cursor); + } + if (result != DS_OK) { + SetDSerror("DirectSound GetCurrentPosition", result); + return (NULL); + } + cursor /= mixlen; #ifdef DEBUG_SOUND - /* Detect audio dropouts */ - { DWORD spot = cursor; - if ( spot < lastchunk ) { - spot += NUM_BUFFERS; - } - if ( spot > lastchunk+1 ) { - fprintf(stderr, "Audio dropout, missed %d fragments\n", - (spot - (lastchunk+1))); - } - } + /* Detect audio dropouts */ + { + DWORD spot = cursor; + if (spot < lastchunk) { + spot += NUM_BUFFERS; + } + if (spot > lastchunk + 1) { + fprintf(stderr, "Audio dropout, missed %d fragments\n", + (spot - (lastchunk + 1))); + } + } #endif - lastchunk = cursor; - cursor = (cursor+1)%NUM_BUFFERS; - cursor *= mixlen; - - /* Lock the audio buffer */ - result = IDirectSoundBuffer_Lock(mixbuf, cursor, mixlen, - (LPVOID *)&locked_buf, &rawlen, NULL, &junk, 0); - if ( result == DSERR_BUFFERLOST ) { - IDirectSoundBuffer_Restore(mixbuf); - result = IDirectSoundBuffer_Lock(mixbuf, cursor, mixlen, - (LPVOID *)&locked_buf, &rawlen, NULL, &junk, 0); - } - if ( result != DS_OK ) { - SetDSerror("DirectSound Lock", result); - return(NULL); - } - return(locked_buf); + lastchunk = cursor; + cursor = (cursor + 1) % NUM_BUFFERS; + cursor *= mixlen; + + /* Lock the audio buffer */ + result = IDirectSoundBuffer_Lock(mixbuf, cursor, mixlen, + (LPVOID *) & locked_buf, &rawlen, NULL, + &junk, 0); + if (result == DSERR_BUFFERLOST) { + IDirectSoundBuffer_Restore(mixbuf); + result = IDirectSoundBuffer_Lock(mixbuf, cursor, mixlen, + (LPVOID *) & locked_buf, &rawlen, + NULL, &junk, 0); + } + if (result != DS_OK) { + SetDSerror("DirectSound Lock", result); + return (NULL); + } + return (locked_buf); } -static void DX5_WaitDone(_THIS) +static void +DX5_WaitDone(_THIS) { - Uint8 *stream; - - /* Wait for the playing chunk to finish */ - stream = this->GetAudioBuf(this); - if ( stream != NULL ) { - SDL_memset(stream, silence, mixlen); - this->PlayAudio(this); - } - this->WaitAudio(this); - - /* Stop the looping sound buffer */ - IDirectSoundBuffer_Stop(mixbuf); + Uint8 *stream; + + /* Wait for the playing chunk to finish */ + stream = this->GetAudioBuf(this); + if (stream != NULL) { + SDL_memset(stream, silence, mixlen); + this->PlayAudio(this); + } + this->WaitAudio(this); + + /* Stop the looping sound buffer */ + IDirectSoundBuffer_Stop(mixbuf); } -static void DX5_CloseAudio(_THIS) +static void +DX5_CloseAudio(_THIS) { - if ( sound != NULL ) { - if ( mixbuf != NULL ) { - /* Clean up the audio buffer */ - IDirectSoundBuffer_Release(mixbuf); - mixbuf = NULL; - } - if ( audio_event != NULL ) { - CloseHandle(audio_event); - audio_event = NULL; - } - IDirectSound_Release(sound); - sound = NULL; - } + if (sound != NULL) { + if (mixbuf != NULL) { + /* Clean up the audio buffer */ + IDirectSoundBuffer_Release(mixbuf); + mixbuf = NULL; + } + if (audio_event != NULL) { + CloseHandle(audio_event); + audio_event = NULL; + } + IDirectSound_Release(sound); + sound = NULL; + } } #ifdef USE_PRIMARY_BUFFER /* This function tries to create a primary audio buffer, and returns the number of audio chunks available in the created buffer. */ -static int CreatePrimary(LPDIRECTSOUND sndObj, HWND focus, - LPDIRECTSOUNDBUFFER *sndbuf, WAVEFORMATEX *wavefmt, Uint32 chunksize) +static int +CreatePrimary(LPDIRECTSOUND sndObj, HWND focus, + LPDIRECTSOUNDBUFFER * sndbuf, WAVEFORMATEX * wavefmt, + Uint32 chunksize) { - HRESULT result; - DSBUFFERDESC format; - DSBCAPS caps; - int numchunks; - - /* Try to set primary mixing privileges */ - result = IDirectSound_SetCooperativeLevel(sndObj, focus, - DSSCL_WRITEPRIMARY); - if ( result != DS_OK ) { + HRESULT result; + DSBUFFERDESC format; + DSBCAPS caps; + int numchunks; + + /* Try to set primary mixing privileges */ + result = IDirectSound_SetCooperativeLevel(sndObj, focus, + DSSCL_WRITEPRIMARY); + if (result != DS_OK) { #ifdef DEBUG_SOUND - SetDSerror("DirectSound SetCooperativeLevel", result); + SetDSerror("DirectSound SetCooperativeLevel", result); #endif - return(-1); - } - - /* Try to create the primary buffer */ - SDL_memset(&format, 0, sizeof(format)); - format.dwSize = sizeof(format); - format.dwFlags=(DSBCAPS_PRIMARYBUFFER|DSBCAPS_GETCURRENTPOSITION2); - format.dwFlags |= DSBCAPS_STICKYFOCUS; + return (-1); + } + + /* Try to create the primary buffer */ + SDL_memset(&format, 0, sizeof(format)); + format.dwSize = sizeof(format); + format.dwFlags = (DSBCAPS_PRIMARYBUFFER | DSBCAPS_GETCURRENTPOSITION2); + format.dwFlags |= DSBCAPS_STICKYFOCUS; #ifdef USE_POSITION_NOTIFY - format.dwFlags |= DSBCAPS_CTRLPOSITIONNOTIFY; + format.dwFlags |= DSBCAPS_CTRLPOSITIONNOTIFY; #endif - result = IDirectSound_CreateSoundBuffer(sndObj, &format, sndbuf, NULL); - if ( result != DS_OK ) { + result = IDirectSound_CreateSoundBuffer(sndObj, &format, sndbuf, NULL); + if (result != DS_OK) { #ifdef DEBUG_SOUND - SetDSerror("DirectSound CreateSoundBuffer", result); + SetDSerror("DirectSound CreateSoundBuffer", result); #endif - return(-1); - } - - /* Check the size of the fragment buffer */ - SDL_memset(&caps, 0, sizeof(caps)); - caps.dwSize = sizeof(caps); - result = IDirectSoundBuffer_GetCaps(*sndbuf, &caps); - if ( result != DS_OK ) { + return (-1); + } + + /* Check the size of the fragment buffer */ + SDL_memset(&caps, 0, sizeof(caps)); + caps.dwSize = sizeof(caps); + result = IDirectSoundBuffer_GetCaps(*sndbuf, &caps); + if (result != DS_OK) { #ifdef DEBUG_SOUND - SetDSerror("DirectSound GetCaps", result); + SetDSerror("DirectSound GetCaps", result); #endif - IDirectSoundBuffer_Release(*sndbuf); - return(-1); - } - if ( (chunksize > caps.dwBufferBytes) || - ((caps.dwBufferBytes%chunksize) != 0) ) { - /* The primary buffer size is not a multiple of 'chunksize' - -- this hopefully doesn't happen when 'chunksize' is a - power of 2. - */ - IDirectSoundBuffer_Release(*sndbuf); - SDL_SetError( -"Primary buffer size is: %d, cannot break it into chunks of %d bytes\n", - caps.dwBufferBytes, chunksize); - return(-1); - } - numchunks = (caps.dwBufferBytes/chunksize); - - /* Set the primary audio format */ - result = IDirectSoundBuffer_SetFormat(*sndbuf, wavefmt); - if ( result != DS_OK ) { + IDirectSoundBuffer_Release(*sndbuf); + return (-1); + } + if ((chunksize > caps.dwBufferBytes) || + ((caps.dwBufferBytes % chunksize) != 0)) { + /* The primary buffer size is not a multiple of 'chunksize' + -- this hopefully doesn't happen when 'chunksize' is a + power of 2. + */ + IDirectSoundBuffer_Release(*sndbuf); + SDL_SetError + ("Primary buffer size is: %d, cannot break it into chunks of %d bytes\n", + caps.dwBufferBytes, chunksize); + return (-1); + } + numchunks = (caps.dwBufferBytes / chunksize); + + /* Set the primary audio format */ + result = IDirectSoundBuffer_SetFormat(*sndbuf, wavefmt); + if (result != DS_OK) { #ifdef DEBUG_SOUND - SetDSerror("DirectSound SetFormat", result); + SetDSerror("DirectSound SetFormat", result); #endif - IDirectSoundBuffer_Release(*sndbuf); - return(-1); - } - return(numchunks); + IDirectSoundBuffer_Release(*sndbuf); + return (-1); + } + return (numchunks); } #endif /* USE_PRIMARY_BUFFER */ /* This function tries to create a secondary audio buffer, and returns the number of audio chunks available in the created buffer. */ -static int CreateSecondary(LPDIRECTSOUND sndObj, HWND focus, - LPDIRECTSOUNDBUFFER *sndbuf, WAVEFORMATEX *wavefmt, Uint32 chunksize) +static int +CreateSecondary(LPDIRECTSOUND sndObj, HWND focus, + LPDIRECTSOUNDBUFFER * sndbuf, WAVEFORMATEX * wavefmt, + Uint32 chunksize) { - const int numchunks = 8; - HRESULT result; - DSBUFFERDESC format; - LPVOID pvAudioPtr1, pvAudioPtr2; - DWORD dwAudioBytes1, dwAudioBytes2; - - /* Try to set primary mixing privileges */ - if ( focus ) { - result = IDirectSound_SetCooperativeLevel(sndObj, - focus, DSSCL_PRIORITY); - } else { - result = IDirectSound_SetCooperativeLevel(sndObj, - GetDesktopWindow(), DSSCL_NORMAL); - } - if ( result != DS_OK ) { + const int numchunks = 8; + HRESULT result; + DSBUFFERDESC format; + LPVOID pvAudioPtr1, pvAudioPtr2; + DWORD dwAudioBytes1, dwAudioBytes2; + + /* Try to set primary mixing privileges */ + if (focus) { + result = IDirectSound_SetCooperativeLevel(sndObj, + focus, DSSCL_PRIORITY); + } else { + result = IDirectSound_SetCooperativeLevel(sndObj, + GetDesktopWindow(), + DSSCL_NORMAL); + } + if (result != DS_OK) { #ifdef DEBUG_SOUND - SetDSerror("DirectSound SetCooperativeLevel", result); + SetDSerror("DirectSound SetCooperativeLevel", result); #endif - return(-1); - } + return (-1); + } - /* Try to create the secondary buffer */ - SDL_memset(&format, 0, sizeof(format)); - format.dwSize = sizeof(format); - format.dwFlags = DSBCAPS_GETCURRENTPOSITION2; + /* Try to create the secondary buffer */ + SDL_memset(&format, 0, sizeof(format)); + format.dwSize = sizeof(format); + format.dwFlags = DSBCAPS_GETCURRENTPOSITION2; #ifdef USE_POSITION_NOTIFY - format.dwFlags |= DSBCAPS_CTRLPOSITIONNOTIFY; + format.dwFlags |= DSBCAPS_CTRLPOSITIONNOTIFY; #endif - if ( ! focus ) { - format.dwFlags |= DSBCAPS_GLOBALFOCUS; - } else { - format.dwFlags |= DSBCAPS_STICKYFOCUS; - } - format.dwBufferBytes = numchunks*chunksize; - if ( (format.dwBufferBytes < DSBSIZE_MIN) || - (format.dwBufferBytes > DSBSIZE_MAX) ) { - SDL_SetError("Sound buffer size must be between %d and %d", - DSBSIZE_MIN/numchunks, DSBSIZE_MAX/numchunks); - return(-1); - } - format.dwReserved = 0; - format.lpwfxFormat = wavefmt; - result = IDirectSound_CreateSoundBuffer(sndObj, &format, sndbuf, NULL); - if ( result != DS_OK ) { - SetDSerror("DirectSound CreateSoundBuffer", result); - return(-1); - } - IDirectSoundBuffer_SetFormat(*sndbuf, wavefmt); - - /* Silence the initial audio buffer */ - result = IDirectSoundBuffer_Lock(*sndbuf, 0, format.dwBufferBytes, - (LPVOID *)&pvAudioPtr1, &dwAudioBytes1, - (LPVOID *)&pvAudioPtr2, &dwAudioBytes2, - DSBLOCK_ENTIREBUFFER); - if ( result == DS_OK ) { - if ( wavefmt->wBitsPerSample == 8 ) { - SDL_memset(pvAudioPtr1, 0x80, dwAudioBytes1); - } else { - SDL_memset(pvAudioPtr1, 0x00, dwAudioBytes1); - } - IDirectSoundBuffer_Unlock(*sndbuf, - (LPVOID)pvAudioPtr1, dwAudioBytes1, - (LPVOID)pvAudioPtr2, dwAudioBytes2); - } - - /* We're ready to go */ - return(numchunks); + if (!focus) { + format.dwFlags |= DSBCAPS_GLOBALFOCUS; + } else { + format.dwFlags |= DSBCAPS_STICKYFOCUS; + } + format.dwBufferBytes = numchunks * chunksize; + if ((format.dwBufferBytes < DSBSIZE_MIN) || + (format.dwBufferBytes > DSBSIZE_MAX)) { + SDL_SetError("Sound buffer size must be between %d and %d", + DSBSIZE_MIN / numchunks, DSBSIZE_MAX / numchunks); + return (-1); + } + format.dwReserved = 0; + format.lpwfxFormat = wavefmt; + result = IDirectSound_CreateSoundBuffer(sndObj, &format, sndbuf, NULL); + if (result != DS_OK) { + SetDSerror("DirectSound CreateSoundBuffer", result); + return (-1); + } + IDirectSoundBuffer_SetFormat(*sndbuf, wavefmt); + + /* Silence the initial audio buffer */ + result = IDirectSoundBuffer_Lock(*sndbuf, 0, format.dwBufferBytes, + (LPVOID *) & pvAudioPtr1, &dwAudioBytes1, + (LPVOID *) & pvAudioPtr2, &dwAudioBytes2, + DSBLOCK_ENTIREBUFFER); + if (result == DS_OK) { + if (wavefmt->wBitsPerSample == 8) { + SDL_memset(pvAudioPtr1, 0x80, dwAudioBytes1); + } else { + SDL_memset(pvAudioPtr1, 0x00, dwAudioBytes1); + } + IDirectSoundBuffer_Unlock(*sndbuf, + (LPVOID) pvAudioPtr1, dwAudioBytes1, + (LPVOID) pvAudioPtr2, dwAudioBytes2); + } + + /* We're ready to go */ + return (numchunks); } /* This function tries to set position notify events on the mixing buffer */ #ifdef USE_POSITION_NOTIFY -static int CreateAudioEvent(_THIS) +static int +CreateAudioEvent(_THIS) { - LPDIRECTSOUNDNOTIFY notify; - DSBPOSITIONNOTIFY *notify_positions; - int i, retval; - HRESULT result; - - /* Default to fail on exit */ - retval = -1; - notify = NULL; - - /* Query for the interface */ - result = IDirectSoundBuffer_QueryInterface(mixbuf, - &IID_IDirectSoundNotify, (void *)¬ify); - if ( result != DS_OK ) { - goto done; - } - - /* Allocate the notify structures */ - notify_positions = (DSBPOSITIONNOTIFY *)SDL_malloc(NUM_BUFFERS* - sizeof(*notify_positions)); - if ( notify_positions == NULL ) { - goto done; - } - - /* Create the notify event */ - audio_event = CreateEvent(NULL, FALSE, FALSE, NULL); - if ( audio_event == NULL ) { - goto done; - } - - /* Set up the notify structures */ - for ( i=0; iformat & 0xFF ) { - case 8: - /* Unsigned 8 bit audio data */ - spec->format = AUDIO_U8; - silence = 0x80; - waveformat.wBitsPerSample = 8; - break; - case 16: - /* Signed 16 bit audio data */ - spec->format = AUDIO_S16; - silence = 0x00; - waveformat.wBitsPerSample = 16; - break; - default: - SDL_SetError("Unsupported audio format"); - return(-1); - } - waveformat.nChannels = spec->channels; - waveformat.nSamplesPerSec = spec->freq; - waveformat.nBlockAlign = - waveformat.nChannels * (waveformat.wBitsPerSample/8); - waveformat.nAvgBytesPerSec = - waveformat.nSamplesPerSec * waveformat.nBlockAlign; - - /* Update the fragment size as size in bytes */ - SDL_CalculateAudioSpec(spec); - - /* Open the audio device */ - result = DSoundCreate(NULL, &sound, NULL); - if ( result != DS_OK ) { - SetDSerror("DirectSoundCreate", result); - return(-1); - } - - /* Create the audio buffer to which we write */ - NUM_BUFFERS = -1; + HRESULT result; + WAVEFORMATEX waveformat; + + /* Set basic WAVE format parameters */ + SDL_memset(&waveformat, 0, sizeof(waveformat)); + waveformat.wFormatTag = WAVE_FORMAT_PCM; + + /* Determine the audio parameters from the AudioSpec */ + switch (spec->format & 0xFF) { + case 8: + /* Unsigned 8 bit audio data */ + spec->format = AUDIO_U8; + silence = 0x80; + waveformat.wBitsPerSample = 8; + break; + case 16: + /* Signed 16 bit audio data */ + spec->format = AUDIO_S16; + silence = 0x00; + waveformat.wBitsPerSample = 16; + break; + default: + SDL_SetError("Unsupported audio format"); + return (-1); + } + waveformat.nChannels = spec->channels; + waveformat.nSamplesPerSec = spec->freq; + waveformat.nBlockAlign = + waveformat.nChannels * (waveformat.wBitsPerSample / 8); + waveformat.nAvgBytesPerSec = + waveformat.nSamplesPerSec * waveformat.nBlockAlign; + + /* Update the fragment size as size in bytes */ + SDL_CalculateAudioSpec(spec); + + /* Open the audio device */ + result = DSoundCreate(NULL, &sound, NULL); + if (result != DS_OK) { + SetDSerror("DirectSoundCreate", result); + return (-1); + } + + /* Create the audio buffer to which we write */ + NUM_BUFFERS = -1; #ifdef USE_PRIMARY_BUFFER - if ( mainwin ) { - NUM_BUFFERS = CreatePrimary(sound, mainwin, &mixbuf, - &waveformat, spec->size); - } + if (mainwin) { + NUM_BUFFERS = CreatePrimary(sound, mainwin, &mixbuf, + &waveformat, spec->size); + } #endif /* USE_PRIMARY_BUFFER */ - if ( NUM_BUFFERS < 0 ) { - NUM_BUFFERS = CreateSecondary(sound, mainwin, &mixbuf, - &waveformat, spec->size); - if ( NUM_BUFFERS < 0 ) { - return(-1); - } + if (NUM_BUFFERS < 0) { + NUM_BUFFERS = CreateSecondary(sound, mainwin, &mixbuf, + &waveformat, spec->size); + if (NUM_BUFFERS < 0) { + return (-1); + } #ifdef DEBUG_SOUND - fprintf(stderr, "Using secondary audio buffer\n"); + fprintf(stderr, "Using secondary audio buffer\n"); #endif - } + } #ifdef DEBUG_SOUND - else - fprintf(stderr, "Using primary audio buffer\n"); + else + fprintf(stderr, "Using primary audio buffer\n"); #endif - /* The buffer will auto-start playing in DX5_WaitAudio() */ - lastchunk = 0; - mixlen = spec->size; + /* The buffer will auto-start playing in DX5_WaitAudio() */ + lastchunk = 0; + mixlen = spec->size; #ifdef USE_POSITION_NOTIFY - /* See if we can use DirectX 6 event notification */ - if ( CreateAudioEvent(this) == 0 ) { - this->WaitAudio = DX6_WaitAudio_EventWait; - } else { - this->WaitAudio = DX5_WaitAudio_BusyWait; - } + /* See if we can use DirectX 6 event notification */ + if (CreateAudioEvent(this) == 0) { + this->WaitAudio = DX6_WaitAudio_EventWait; + } else { + this->WaitAudio = DX5_WaitAudio_BusyWait; + } #endif - return(0); + return (0); } +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/audio/windx5/SDL_dx5audio.h b/src/audio/windx5/SDL_dx5audio.h index eebdf6d66..93ecb60e3 100644 --- a/src/audio/windx5/SDL_dx5audio.h +++ b/src/audio/windx5/SDL_dx5audio.h @@ -32,14 +32,15 @@ #define _THIS SDL_AudioDevice *this /* The DirectSound objects */ -struct SDL_PrivateAudioData { - LPDIRECTSOUND sound; - LPDIRECTSOUNDBUFFER mixbuf; - int NUM_BUFFERS; - int mixlen, silence; - DWORD lastchunk; - Uint8 *locked_buf; - HANDLE audio_event; +struct SDL_PrivateAudioData +{ + LPDIRECTSOUND sound; + LPDIRECTSOUNDBUFFER mixbuf; + int NUM_BUFFERS; + int mixlen, silence; + DWORD lastchunk; + Uint8 *locked_buf; + HANDLE audio_event; }; /* Old variable names */ @@ -53,3 +54,5 @@ struct SDL_PrivateAudioData { #define audio_event (this->hidden->audio_event) #endif /* _SDL_lowaudio_h */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/audio/windx5/directx.h b/src/audio/windx5/directx.h index d14d6c637..bb9f2d2e1 100644 --- a/src/audio/windx5/directx.h +++ b/src/audio/windx5/directx.h @@ -82,3 +82,4 @@ #include #endif /* _directx_h */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/cdrom/SDL_cdrom.c b/src/cdrom/SDL_cdrom.c index e842b5a68..0ed81ef9a 100644 --- a/src/cdrom/SDL_cdrom.c +++ b/src/cdrom/SDL_cdrom.c @@ -27,7 +27,7 @@ #include "SDL_syscdrom.h" #if !defined(__MACOS__) -#define CLIP_FRAMES 10 /* Some CD-ROMs won't go all the way */ +#define CLIP_FRAMES 10 /* Some CD-ROMs won't go all the way */ #endif static int SDL_cdinitted = 0; @@ -35,307 +35,324 @@ static SDL_CD *default_cdrom; /* The system level CD-ROM control functions */ struct CDcaps SDL_CDcaps = { - NULL, /* Name */ - NULL, /* Open */ - NULL, /* GetTOC */ - NULL, /* Status */ - NULL, /* Play */ - NULL, /* Pause */ - NULL, /* Resume */ - NULL, /* Stop */ - NULL, /* Eject */ - NULL, /* Close */ + NULL, /* Name */ + NULL, /* Open */ + NULL, /* GetTOC */ + NULL, /* Status */ + NULL, /* Play */ + NULL, /* Pause */ + NULL, /* Resume */ + NULL, /* Stop */ + NULL, /* Eject */ + NULL, /* Close */ }; int SDL_numcds; -int SDL_CDROMInit(void) +int +SDL_CDROMInit(void) { - int retval; - - SDL_numcds = 0; - retval = SDL_SYS_CDInit(); - if ( retval == 0 ) { - SDL_cdinitted = 1; - } - default_cdrom = NULL; - return(retval); + int retval; + + SDL_numcds = 0; + retval = SDL_SYS_CDInit(); + if (retval == 0) { + SDL_cdinitted = 1; + } + default_cdrom = NULL; + return (retval); } /* Check to see if the CD-ROM subsystem has been initialized */ -static int CheckInit(int check_cdrom, SDL_CD **cdrom) +static int +CheckInit(int check_cdrom, SDL_CD ** cdrom) { - int okay; - - okay = SDL_cdinitted; - if ( check_cdrom && (*cdrom == NULL) ) { - *cdrom = default_cdrom; - if ( *cdrom == NULL ) { - SDL_SetError("CD-ROM not opened"); - okay = 0; - } - } - if ( ! SDL_cdinitted ) { - SDL_SetError("CD-ROM subsystem not initialized"); - } - return(okay); + int okay; + + okay = SDL_cdinitted; + if (check_cdrom && (*cdrom == NULL)) { + *cdrom = default_cdrom; + if (*cdrom == NULL) { + SDL_SetError("CD-ROM not opened"); + okay = 0; + } + } + if (!SDL_cdinitted) { + SDL_SetError("CD-ROM subsystem not initialized"); + } + return (okay); } -int SDL_CDNumDrives(void) +int +SDL_CDNumDrives(void) { - if ( ! CheckInit(0, NULL) ) { - return(-1); - } - return(SDL_numcds); + if (!CheckInit(0, NULL)) { + return (-1); + } + return (SDL_numcds); } -const char *SDL_CDName(int drive) +const char * +SDL_CDName(int drive) { - if ( ! CheckInit(0, NULL) ) { - return(NULL); - } - if ( drive >= SDL_numcds ) { - SDL_SetError("Invalid CD-ROM drive index"); - return(NULL); - } - if ( SDL_CDcaps.Name ) { - return(SDL_CDcaps.Name(drive)); - } else { - return(""); - } + if (!CheckInit(0, NULL)) { + return (NULL); + } + if (drive >= SDL_numcds) { + SDL_SetError("Invalid CD-ROM drive index"); + return (NULL); + } + if (SDL_CDcaps.Name) { + return (SDL_CDcaps.Name(drive)); + } else { + return (""); + } } -SDL_CD *SDL_CDOpen(int drive) +SDL_CD * +SDL_CDOpen(int drive) { - struct SDL_CD *cdrom; - - if ( ! CheckInit(0, NULL) ) { - return(NULL); - } - if ( drive >= SDL_numcds ) { - SDL_SetError("Invalid CD-ROM drive index"); - return(NULL); - } - cdrom = (SDL_CD *)SDL_malloc(sizeof(*cdrom)); - if ( cdrom == NULL ) { - SDL_OutOfMemory(); - return(NULL); - } - SDL_memset(cdrom, 0, sizeof(*cdrom)); - cdrom->id = SDL_CDcaps.Open(drive); - if ( cdrom->id < 0 ) { - SDL_free(cdrom); - return(NULL); - } - default_cdrom = cdrom; - return(cdrom); + struct SDL_CD *cdrom; + + if (!CheckInit(0, NULL)) { + return (NULL); + } + if (drive >= SDL_numcds) { + SDL_SetError("Invalid CD-ROM drive index"); + return (NULL); + } + cdrom = (SDL_CD *) SDL_malloc(sizeof(*cdrom)); + if (cdrom == NULL) { + SDL_OutOfMemory(); + return (NULL); + } + SDL_memset(cdrom, 0, sizeof(*cdrom)); + cdrom->id = SDL_CDcaps.Open(drive); + if (cdrom->id < 0) { + SDL_free(cdrom); + return (NULL); + } + default_cdrom = cdrom; + return (cdrom); } -CDstatus SDL_CDStatus(SDL_CD *cdrom) +CDstatus +SDL_CDStatus(SDL_CD * cdrom) { - CDstatus status; - int i; - Uint32 position; - - /* Check if the CD-ROM subsystem has been initialized */ - if ( ! CheckInit(1, &cdrom) ) { - return(CD_ERROR); - } - - /* Get the current status of the drive */ - cdrom->numtracks = 0; - cdrom->cur_track = 0; - cdrom->cur_frame = 0; - status = SDL_CDcaps.Status(cdrom, &i); - position = (Uint32)i; - cdrom->status = status; - - /* Get the table of contents, if there's a CD available */ - if ( CD_INDRIVE(status) ) { - if ( SDL_CDcaps.GetTOC(cdrom) < 0 ) { - status = CD_ERROR; - } - /* If the drive is playing, get current play position */ - if ( (status == CD_PLAYING) || (status == CD_PAUSED) ) { - for ( i=1; cdrom->track[i].offset <= position; ++i ) { - /* Keep looking */; - } + CDstatus status; + int i; + Uint32 position; + + /* Check if the CD-ROM subsystem has been initialized */ + if (!CheckInit(1, &cdrom)) { + return (CD_ERROR); + } + + /* Get the current status of the drive */ + cdrom->numtracks = 0; + cdrom->cur_track = 0; + cdrom->cur_frame = 0; + status = SDL_CDcaps.Status(cdrom, &i); + position = (Uint32) i; + cdrom->status = status; + + /* Get the table of contents, if there's a CD available */ + if (CD_INDRIVE(status)) { + if (SDL_CDcaps.GetTOC(cdrom) < 0) { + status = CD_ERROR; + } + /* If the drive is playing, get current play position */ + if ((status == CD_PLAYING) || (status == CD_PAUSED)) { + for (i = 1; cdrom->track[i].offset <= position; ++i) { + /* Keep looking */ ; + } #ifdef DEBUG_CDROM - fprintf(stderr, "Current position: %d, track = %d (offset is %d)\n", - position, i-1, cdrom->track[i-1].offset); + fprintf(stderr, + "Current position: %d, track = %d (offset is %d)\n", + position, i - 1, cdrom->track[i - 1].offset); #endif - cdrom->cur_track = i-1; - position -= cdrom->track[cdrom->cur_track].offset; - cdrom->cur_frame = position; - } - } - return(status); + cdrom->cur_track = i - 1; + position -= cdrom->track[cdrom->cur_track].offset; + cdrom->cur_frame = position; + } + } + return (status); } -int SDL_CDPlayTracks(SDL_CD *cdrom, - int strack, int sframe, int ntracks, int nframes) +int +SDL_CDPlayTracks(SDL_CD * cdrom, + int strack, int sframe, int ntracks, int nframes) { - int etrack, eframe; - int start, length; - - /* Check if the CD-ROM subsystem has been initialized */ - if ( ! CheckInit(1, &cdrom) ) { - return(CD_ERROR); - } - - /* Determine the starting and ending tracks */ - if ( (strack < 0) || (strack >= cdrom->numtracks) ) { - SDL_SetError("Invalid starting track"); - return(CD_ERROR); - } - if ( ! ntracks && ! nframes ) { - etrack = cdrom->numtracks; - eframe = 0; - } else { - etrack = strack+ntracks; - if ( etrack == strack ) { - eframe = sframe + nframes; - } else { - eframe = nframes; - } - } - if ( etrack > cdrom->numtracks ) { - SDL_SetError("Invalid play length"); - return(CD_ERROR); - } - - /* Skip data tracks and verify frame offsets */ - while ( (strack <= etrack) && - (cdrom->track[strack].type == SDL_DATA_TRACK) ) { - ++strack; - } - if ( sframe >= (int)cdrom->track[strack].length ) { - SDL_SetError("Invalid starting frame for track %d", strack); - return(CD_ERROR); - } - while ( (etrack > strack) && - (cdrom->track[etrack-1].type == SDL_DATA_TRACK) ) { - --etrack; - } - if ( eframe > (int)cdrom->track[etrack].length ) { - SDL_SetError("Invalid ending frame for track %d", etrack); - return(CD_ERROR); - } - - /* Determine start frame and play length */ - start = (cdrom->track[strack].offset+sframe); - length = (cdrom->track[etrack].offset+eframe)-start; + int etrack, eframe; + int start, length; + + /* Check if the CD-ROM subsystem has been initialized */ + if (!CheckInit(1, &cdrom)) { + return (CD_ERROR); + } + + /* Determine the starting and ending tracks */ + if ((strack < 0) || (strack >= cdrom->numtracks)) { + SDL_SetError("Invalid starting track"); + return (CD_ERROR); + } + if (!ntracks && !nframes) { + etrack = cdrom->numtracks; + eframe = 0; + } else { + etrack = strack + ntracks; + if (etrack == strack) { + eframe = sframe + nframes; + } else { + eframe = nframes; + } + } + if (etrack > cdrom->numtracks) { + SDL_SetError("Invalid play length"); + return (CD_ERROR); + } + + /* Skip data tracks and verify frame offsets */ + while ((strack <= etrack) && + (cdrom->track[strack].type == SDL_DATA_TRACK)) { + ++strack; + } + if (sframe >= (int) cdrom->track[strack].length) { + SDL_SetError("Invalid starting frame for track %d", strack); + return (CD_ERROR); + } + while ((etrack > strack) && + (cdrom->track[etrack - 1].type == SDL_DATA_TRACK)) { + --etrack; + } + if (eframe > (int) cdrom->track[etrack].length) { + SDL_SetError("Invalid ending frame for track %d", etrack); + return (CD_ERROR); + } + + /* Determine start frame and play length */ + start = (cdrom->track[strack].offset + sframe); + length = (cdrom->track[etrack].offset + eframe) - start; #ifdef CLIP_FRAMES - /* I've never seen this necessary, but xmcd does it.. */ - length -= CLIP_FRAMES; /* CLIP_FRAMES == 10 */ + /* I've never seen this necessary, but xmcd does it.. */ + length -= CLIP_FRAMES; /* CLIP_FRAMES == 10 */ #endif - if ( length < 0 ) { - return(0); - } + if (length < 0) { + return (0); + } - /* Play! */ + /* Play! */ #ifdef DEBUG_CDROM - fprintf(stderr, "Playing %d frames at offset %d\n", length, start); + fprintf(stderr, "Playing %d frames at offset %d\n", length, start); #endif - return(SDL_CDcaps.Play(cdrom, start, length)); + return (SDL_CDcaps.Play(cdrom, start, length)); } -int SDL_CDPlay(SDL_CD *cdrom, int sframe, int length) +int +SDL_CDPlay(SDL_CD * cdrom, int sframe, int length) { - /* Check if the CD-ROM subsystem has been initialized */ - if ( ! CheckInit(1, &cdrom) ) { - return(CD_ERROR); - } + /* Check if the CD-ROM subsystem has been initialized */ + if (!CheckInit(1, &cdrom)) { + return (CD_ERROR); + } - return(SDL_CDcaps.Play(cdrom, sframe, length)); + return (SDL_CDcaps.Play(cdrom, sframe, length)); } -int SDL_CDPause(SDL_CD *cdrom) +int +SDL_CDPause(SDL_CD * cdrom) { - CDstatus status; - int retval; - - /* Check if the CD-ROM subsystem has been initialized */ - if ( ! CheckInit(1, &cdrom) ) { - return(CD_ERROR); - } - - status = SDL_CDcaps.Status(cdrom, NULL); - switch (status) { - case CD_PLAYING: - retval = SDL_CDcaps.Pause(cdrom); - break; - default: - retval = 0; - break; - } - return(retval); + CDstatus status; + int retval; + + /* Check if the CD-ROM subsystem has been initialized */ + if (!CheckInit(1, &cdrom)) { + return (CD_ERROR); + } + + status = SDL_CDcaps.Status(cdrom, NULL); + switch (status) { + case CD_PLAYING: + retval = SDL_CDcaps.Pause(cdrom); + break; + default: + retval = 0; + break; + } + return (retval); } -int SDL_CDResume(SDL_CD *cdrom) +int +SDL_CDResume(SDL_CD * cdrom) { - CDstatus status; - int retval; - - /* Check if the CD-ROM subsystem has been initialized */ - if ( ! CheckInit(1, &cdrom) ) { - return(CD_ERROR); - } - - status = SDL_CDcaps.Status(cdrom, NULL); - switch (status) { - case CD_PAUSED: - retval = SDL_CDcaps.Resume(cdrom); - default: - retval = 0; - break; - } - return(retval); + CDstatus status; + int retval; + + /* Check if the CD-ROM subsystem has been initialized */ + if (!CheckInit(1, &cdrom)) { + return (CD_ERROR); + } + + status = SDL_CDcaps.Status(cdrom, NULL); + switch (status) { + case CD_PAUSED: + retval = SDL_CDcaps.Resume(cdrom); + default: + retval = 0; + break; + } + return (retval); } -int SDL_CDStop(SDL_CD *cdrom) +int +SDL_CDStop(SDL_CD * cdrom) { - CDstatus status; - int retval; - - /* Check if the CD-ROM subsystem has been initialized */ - if ( ! CheckInit(1, &cdrom) ) { - return(CD_ERROR); - } - - status = SDL_CDcaps.Status(cdrom, NULL); - switch (status) { - case CD_PLAYING: - case CD_PAUSED: - retval = SDL_CDcaps.Stop(cdrom); - default: - retval = 0; - break; - } - return(retval); + CDstatus status; + int retval; + + /* Check if the CD-ROM subsystem has been initialized */ + if (!CheckInit(1, &cdrom)) { + return (CD_ERROR); + } + + status = SDL_CDcaps.Status(cdrom, NULL); + switch (status) { + case CD_PLAYING: + case CD_PAUSED: + retval = SDL_CDcaps.Stop(cdrom); + default: + retval = 0; + break; + } + return (retval); } -int SDL_CDEject(SDL_CD *cdrom) +int +SDL_CDEject(SDL_CD * cdrom) { - /* Check if the CD-ROM subsystem has been initialized */ - if ( ! CheckInit(1, &cdrom) ) { - return(CD_ERROR); - } - return(SDL_CDcaps.Eject(cdrom)); + /* Check if the CD-ROM subsystem has been initialized */ + if (!CheckInit(1, &cdrom)) { + return (CD_ERROR); + } + return (SDL_CDcaps.Eject(cdrom)); } -void SDL_CDClose(SDL_CD *cdrom) +void +SDL_CDClose(SDL_CD * cdrom) { - /* Check if the CD-ROM subsystem has been initialized */ - if ( ! CheckInit(1, &cdrom) ) { - return; - } - SDL_CDcaps.Close(cdrom); - SDL_free(cdrom); - default_cdrom = NULL; + /* Check if the CD-ROM subsystem has been initialized */ + if (!CheckInit(1, &cdrom)) { + return; + } + SDL_CDcaps.Close(cdrom); + SDL_free(cdrom); + default_cdrom = NULL; } -void SDL_CDROMQuit(void) +void +SDL_CDROMQuit(void) { - SDL_SYS_CDQuit(); - SDL_cdinitted = 0; + SDL_SYS_CDQuit(); + SDL_cdinitted = 0; } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/cdrom/SDL_syscdrom.h b/src/cdrom/SDL_syscdrom.h index b51e07b5e..ced2f63ab 100644 --- a/src/cdrom/SDL_syscdrom.h +++ b/src/cdrom/SDL_syscdrom.h @@ -24,41 +24,42 @@ /* This is the system specific header for the SDL CD-ROM API */ /* Structure of CD audio control functions */ -extern struct CDcaps { - /* Get the name of the specified drive */ - const char *(*Name)(int drive); +extern struct CDcaps +{ + /* Get the name of the specified drive */ + const char *(*Name) (int drive); - /* Open the specified drive, returning a drive id, or -1 on error */ - int (*Open)(int drive); + /* Open the specified drive, returning a drive id, or -1 on error */ + int (*Open) (int drive); - /* Get table-of-contents (number of tracks + track info) for disk. - The TOC information should be stored in the cdrom structure. - This function should return 0 on success, or -1 on error. - */ - int (*GetTOC)(SDL_CD *cdrom); + /* Get table-of-contents (number of tracks + track info) for disk. + The TOC information should be stored in the cdrom structure. + This function should return 0 on success, or -1 on error. + */ + int (*GetTOC) (SDL_CD * cdrom); - /* Return the current status and play position, in frames, of the - drive. 'position' may be NULL, and if so, should be ignored. - */ - CDstatus (*Status)(SDL_CD *cdrom, int *position); + /* Return the current status and play position, in frames, of the + drive. 'position' may be NULL, and if so, should be ignored. + */ + CDstatus(*Status) (SDL_CD * cdrom, int *position); - /* Play from frame 'start' to 'start+len' */ - int (*Play)(SDL_CD *cdrom, int start, int len); + /* Play from frame 'start' to 'start+len' */ + int (*Play) (SDL_CD * cdrom, int start, int len); - /* Pause play */ - int (*Pause)(SDL_CD *cdrom); + /* Pause play */ + int (*Pause) (SDL_CD * cdrom); - /* Resume play */ - int (*Resume)(SDL_CD *cdrom); + /* Resume play */ + int (*Resume) (SDL_CD * cdrom); - /* Stop play */ - int (*Stop)(SDL_CD *cdrom); + /* Stop play */ + int (*Stop) (SDL_CD * cdrom); - /* Eject the current disk */ - int (*Eject)(SDL_CD *cdrom); + /* Eject the current disk */ + int (*Eject) (SDL_CD * cdrom); - /* Close the specified drive */ - void (*Close)(SDL_CD *cdrom); + /* Close the specified drive */ + void (*Close) (SDL_CD * cdrom); } SDL_CDcaps; /* The number of available CD-ROM drives on the system */ @@ -69,8 +70,8 @@ extern int SDL_numcds; * drives. Drive 0 should be the system default CD-ROM. * It should return 0, or -1 on an unrecoverable fatal error. */ -extern int SDL_SYS_CDInit(void); +extern int SDL_SYS_CDInit(void); /* Function to perform any system-specific CD-ROM related cleanup */ extern void SDL_SYS_CDQuit(void); - +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/cdrom/aix/SDL_syscdrom.c b/src/cdrom/aix/SDL_syscdrom.c index 41f23a9c1..95994adfd 100644 --- a/src/cdrom/aix/SDL_syscdrom.c +++ b/src/cdrom/aix/SDL_syscdrom.c @@ -47,7 +47,7 @@ #include "../SDL_syscdrom.h" /* The maximum number of CD-ROM drives we'll detect */ -#define MAX_DRIVES 16 +#define MAX_DRIVES 16 /* A list of available CD-ROM drives */ static char *SDL_cdlist[MAX_DRIVES]; @@ -55,19 +55,20 @@ static dev_t SDL_cdmode[MAX_DRIVES]; /* The system-dependent CD control functions */ static const char *SDL_SYS_CDName(int drive); -static int SDL_SYS_CDOpen(int drive); -static int SDL_SYS_CDGetTOC(SDL_CD *cdrom); -static CDstatus SDL_SYS_CDStatus(SDL_CD *cdrom, int *position); -static int SDL_SYS_CDPlay(SDL_CD *cdrom, int start, int length); -static int SDL_SYS_CDPause(SDL_CD *cdrom); -static int SDL_SYS_CDResume(SDL_CD *cdrom); -static int SDL_SYS_CDStop(SDL_CD *cdrom); -static int SDL_SYS_CDEject(SDL_CD *cdrom); -static void SDL_SYS_CDClose(SDL_CD *cdrom); -static int SDL_SYS_CDioctl(int id, int command, void *arg); +static int SDL_SYS_CDOpen(int drive); +static int SDL_SYS_CDGetTOC(SDL_CD * cdrom); +static CDstatus SDL_SYS_CDStatus(SDL_CD * cdrom, int *position); +static int SDL_SYS_CDPlay(SDL_CD * cdrom, int start, int length); +static int SDL_SYS_CDPause(SDL_CD * cdrom); +static int SDL_SYS_CDResume(SDL_CD * cdrom); +static int SDL_SYS_CDStop(SDL_CD * cdrom); +static int SDL_SYS_CDEject(SDL_CD * cdrom); +static void SDL_SYS_CDClose(SDL_CD * cdrom); +static int SDL_SYS_CDioctl(int id, int command, void *arg); /* Check a drive to see if it is a CD-ROM */ -static int CheckDrive(char *drive, struct stat *stbuf) +static int +CheckDrive(char *drive, struct stat *stbuf) { int is_cd; int cdfd; @@ -75,316 +76,320 @@ static int CheckDrive(char *drive, struct stat *stbuf) struct devinfo info; /* If it doesn't exist, return -1 */ - if ( stat(drive, stbuf) < 0 ) { + if (stat(drive, stbuf) < 0) { return -1; } /* If it does exist, verify that it's an available CD-ROM */ is_cd = 0; - if ( S_ISCHR(stbuf->st_mode) || S_ISBLK(stbuf->st_mode) ) { - cdfd = open(drive, (O_RDONLY|O_EXCL|O_NONBLOCK), 0); - if ( cdfd >= 0 ) { - ret = SDL_SYS_CDioctl( cdfd, IOCINFO, &info ); - if ( ret < 0 ) { - /* Some kind of error */ - is_cd = 0; - } else { - if ( info.devtype == DD_CDROM ) { - is_cd = 1; - } else { - is_cd = 0; - } - } + if (S_ISCHR(stbuf->st_mode) || S_ISBLK(stbuf->st_mode)) { + cdfd = open(drive, (O_RDONLY | O_EXCL | O_NONBLOCK), 0); + if (cdfd >= 0) { + ret = SDL_SYS_CDioctl(cdfd, IOCINFO, &info); + if (ret < 0) { + /* Some kind of error */ + is_cd = 0; + } else { + if (info.devtype == DD_CDROM) { + is_cd = 1; + } else { + is_cd = 0; + } + } close(cdfd); - } + } #ifdef DEBUG_CDROM - else - { - fprintf(stderr, "Could not open drive %s (%s)\n", drive, strerror(errno)); - } + else { + fprintf(stderr, "Could not open drive %s (%s)\n", drive, + strerror(errno)); + } #endif } return is_cd; } /* Add a CD-ROM drive to our list of valid drives */ -static void AddDrive(char *drive, struct stat *stbuf) +static void +AddDrive(char *drive, struct stat *stbuf) { - int i; - - if ( SDL_numcds < MAX_DRIVES ) { - /* Check to make sure it's not already in our list. - This can happen when we see a drive via symbolic link. - */ - for ( i=0; ist_rdev == SDL_cdmode[i] ) { + int i; + + if (SDL_numcds < MAX_DRIVES) { + /* Check to make sure it's not already in our list. + This can happen when we see a drive via symbolic link. + */ + for (i = 0; i < SDL_numcds; ++i) { + if (stbuf->st_rdev == SDL_cdmode[i]) { #ifdef DEBUG_CDROM - fprintf(stderr, "Duplicate drive detected: %s == %s\n", drive, SDL_cdlist[i]); + fprintf(stderr, "Duplicate drive detected: %s == %s\n", + drive, SDL_cdlist[i]); #endif - return; - } - } - - /* Add this drive to our list */ - i = SDL_numcds; - SDL_cdlist[i] = SDL_strdup(drive); - if ( SDL_cdlist[i] == NULL ) { - SDL_OutOfMemory(); - return; - } - SDL_cdmode[i] = stbuf->st_rdev; - ++SDL_numcds; + return; + } + } + + /* Add this drive to our list */ + i = SDL_numcds; + SDL_cdlist[i] = SDL_strdup(drive); + if (SDL_cdlist[i] == NULL) { + SDL_OutOfMemory(); + return; + } + SDL_cdmode[i] = stbuf->st_rdev; + ++SDL_numcds; #ifdef DEBUG_CDROM - fprintf(stderr, "Added CD-ROM drive: %s\n", drive); + fprintf(stderr, "Added CD-ROM drive: %s\n", drive); #endif - } + } } -static void CheckMounts() +static void +CheckMounts() { - char* buffer; - int bufsz; - struct vmount* ptr; - int ret; - - buffer = (char*)SDL_malloc(10); - bufsz = 10; - if ( buffer==NULL ) - { - fprintf(stderr, "Could not allocate 10 bytes in aix/SDL_syscdrom.c:CheckMounts\n" ); - exit ( -10 ); + char *buffer; + int bufsz; + struct vmount *ptr; + int ret; + + buffer = (char *) SDL_malloc(10); + bufsz = 10; + if (buffer == NULL) { + fprintf(stderr, + "Could not allocate 10 bytes in aix/SDL_syscdrom.c:CheckMounts\n"); + exit(-10); } - do - { - /* mntctrl() returns an array of all mounted filesystems */ - ret = mntctl ( MCTL_QUERY, bufsz, buffer ); - if ( ret == 0 ) - { - /* Buffer was too small, realloc. */ - bufsz = *(int*)buffer; /* Required size is in first word. */ - /* (whatever a word is in AIX 4.3.3) */ - /* int seems to be OK in 32bit mode. */ + do { + /* mntctrl() returns an array of all mounted filesystems */ + ret = mntctl(MCTL_QUERY, bufsz, buffer); + if (ret == 0) { + /* Buffer was too small, realloc. */ + bufsz = *(int *) buffer; /* Required size is in first word. */ + /* (whatever a word is in AIX 4.3.3) */ + /* int seems to be OK in 32bit mode. */ SDL_free(buffer); - buffer = (char*)SDL_malloc(bufsz); - if ( buffer==NULL ) - { + buffer = (char *) SDL_malloc(bufsz); + if (buffer == NULL) { fprintf(stderr, - "Could not allocate %d bytes in aix/SDL_syscdrom.c:CheckMounts\n", - bufsz ); - exit ( -10 ); + "Could not allocate %d bytes in aix/SDL_syscdrom.c:CheckMounts\n", + bufsz); + exit(-10); } - } - else if ( ret < 0 ) - { + } else if (ret < 0) { #ifdef DEBUG_CDROM fprintf(stderr, "Error reading vmount structures\n"); #endif - return; - } + return; + } } - while ( ret == 0 ); + while (ret == 0); #ifdef DEBUG_CDROM - fprintf ( stderr, "Read %d vmount structures\n",ret ); + fprintf(stderr, "Read %d vmount structures\n", ret); #endif - ptr = (struct vmount*)buffer; - do - { - switch(ptr->vmt_gfstype) + ptr = (struct vmount *) buffer; + do { + switch (ptr->vmt_gfstype) { + case MNT_CDROM: { - case MNT_CDROM : - { - struct stat stbuf; - char* text; + struct stat stbuf; + char *text; - text = (char*)ptr + ptr->vmt_data[VMT_OBJECT].vmt_off; + text = (char *) ptr + ptr->vmt_data[VMT_OBJECT].vmt_off; #ifdef DEBUG_CDROM - fprintf(stderr, "Checking mount path: %s mounted on %s\n", - text, (char*)ptr + ptr->vmt_data[VMT_STUB].vmt_off ); + fprintf(stderr, + "Checking mount path: %s mounted on %s\n", text, + (char *) ptr + ptr->vmt_data[VMT_STUB].vmt_off); #endif - if ( CheckDrive( text, &stbuf) > 0) - { - AddDrive( text, &stbuf); - } + if (CheckDrive(text, &stbuf) > 0) { + AddDrive(text, &stbuf); } - break; - default : - break; } - ptr = (struct vmount*)((char*)ptr + ptr->vmt_length); - ret--; + break; + default: + break; + } + ptr = (struct vmount *) ((char *) ptr + ptr->vmt_length); + ret--; } - while ( ret > 0 ); + while (ret > 0); - free ( buffer ); + free(buffer); } -static int CheckNonmounts() +static int +CheckNonmounts() { #ifdef _THREAD_SAFE - AFILE_t fsFile = NULL; - int passNo = 0; - int ret; + AFILE_t fsFile = NULL; + int passNo = 0; + int ret; struct fstab entry; - struct stat stbuf; - - ret = setfsent_r( &fsFile, &passNo ); - if ( ret != 0 ) return -1; - do - { - ret = getfsent_r ( &entry, &fsFile, &passNo ); - if ( ret == 0 ) { - char* l = SDL_strrchr(entry.fs_spec,'/'); - if ( l != NULL ) { - if ( !SDL_strncmp("cd",++l,2) ) { + struct stat stbuf; + + ret = setfsent_r(&fsFile, &passNo); + if (ret != 0) + return -1; + do { + ret = getfsent_r(&entry, &fsFile, &passNo); + if (ret == 0) { + char *l = SDL_strrchr(entry.fs_spec, '/'); + if (l != NULL) { + if (!SDL_strncmp("cd", ++l, 2)) { #ifdef DEBUG_CDROM fprintf(stderr, - "Found unmounted CD ROM drive with device name %s\n", - entry.fs_spec); + "Found unmounted CD ROM drive with device name %s\n", + entry.fs_spec); #endif - if ( CheckDrive( entry.fs_spec, &stbuf) > 0) - { - AddDrive( entry.fs_spec, &stbuf); - } + if (CheckDrive(entry.fs_spec, &stbuf) > 0) { + AddDrive(entry.fs_spec, &stbuf); + } } } } } - while ( ret == 0 ); - ret = endfsent_r ( &fsFile ); - if ( ret != 0 ) return -1; + while (ret == 0); + ret = endfsent_r(&fsFile); + if (ret != 0) + return -1; return 0; #else - struct fstab* entry; - struct stat stbuf; + struct fstab *entry; + struct stat stbuf; setfsent(); - do - { + do { entry = getfsent(); - if ( entry != NULL ) { - char* l = SDL_strrchr(entry->fs_spec,'/'); - if ( l != NULL ) { - if ( !SDL_strncmp("cd",++l,2) ) { + if (entry != NULL) { + char *l = SDL_strrchr(entry->fs_spec, '/'); + if (l != NULL) { + if (!SDL_strncmp("cd", ++l, 2)) { #ifdef DEBUG_CDROM - fprintf(stderr,"Found unmounted CD ROM drive with device name %s", entry->fs_spec); + fprintf(stderr, + "Found unmounted CD ROM drive with device name %s", + entry->fs_spec); #endif - if ( CheckDrive( entry->fs_spec, &stbuf) > 0) - { - AddDrive( entry->fs_spec, &stbuf); - } + if (CheckDrive(entry->fs_spec, &stbuf) > 0) { + AddDrive(entry->fs_spec, &stbuf); + } } } } } - while ( entry != NULL ); + while (entry != NULL); endfsent(); #endif } -int SDL_SYS_CDInit(void) +int +SDL_SYS_CDInit(void) { - char *SDLcdrom; - struct stat stbuf; - - /* Fill in our driver capabilities */ - SDL_CDcaps.Name = SDL_SYS_CDName; - SDL_CDcaps.Open = SDL_SYS_CDOpen; - SDL_CDcaps.GetTOC = SDL_SYS_CDGetTOC; - SDL_CDcaps.Status = SDL_SYS_CDStatus; - SDL_CDcaps.Play = SDL_SYS_CDPlay; - SDL_CDcaps.Pause = SDL_SYS_CDPause; - SDL_CDcaps.Resume = SDL_SYS_CDResume; - SDL_CDcaps.Stop = SDL_SYS_CDStop; - SDL_CDcaps.Eject = SDL_SYS_CDEject; - SDL_CDcaps.Close = SDL_SYS_CDClose; - - /* Look in the environment for our CD-ROM drive list */ - SDLcdrom = SDL_getenv("SDL_CDROM"); /* ':' separated list of devices */ - if ( SDLcdrom != NULL ) { - char *cdpath, *delim; - size_t len = SDL_strlen(SDLcdrom)+1; - cdpath = SDL_stack_alloc(char, len); - if ( cdpath != NULL ) { - SDL_strlcpy(cdpath, SDLcdrom, len); - SDLcdrom = cdpath; - do { - delim = SDL_strchr(SDLcdrom, ':'); - if ( delim ) { - *delim++ = '\0'; - } + char *SDLcdrom; + struct stat stbuf; + + /* Fill in our driver capabilities */ + SDL_CDcaps.Name = SDL_SYS_CDName; + SDL_CDcaps.Open = SDL_SYS_CDOpen; + SDL_CDcaps.GetTOC = SDL_SYS_CDGetTOC; + SDL_CDcaps.Status = SDL_SYS_CDStatus; + SDL_CDcaps.Play = SDL_SYS_CDPlay; + SDL_CDcaps.Pause = SDL_SYS_CDPause; + SDL_CDcaps.Resume = SDL_SYS_CDResume; + SDL_CDcaps.Stop = SDL_SYS_CDStop; + SDL_CDcaps.Eject = SDL_SYS_CDEject; + SDL_CDcaps.Close = SDL_SYS_CDClose; + + /* Look in the environment for our CD-ROM drive list */ + SDLcdrom = SDL_getenv("SDL_CDROM"); /* ':' separated list of devices */ + if (SDLcdrom != NULL) { + char *cdpath, *delim; + size_t len = SDL_strlen(SDLcdrom) + 1; + cdpath = SDL_stack_alloc(char, len); + if (cdpath != NULL) { + SDL_strlcpy(cdpath, SDLcdrom, len); + SDLcdrom = cdpath; + do { + delim = SDL_strchr(SDLcdrom, ':'); + if (delim) { + *delim++ = '\0'; + } #ifdef DEBUG_CDROM - fprintf(stderr, "Checking CD-ROM drive from SDL_CDROM: %s\n", SDLcdrom); + fprintf(stderr, + "Checking CD-ROM drive from SDL_CDROM: %s\n", + SDLcdrom); #endif - if ( CheckDrive(SDLcdrom, &stbuf) > 0 ) { - AddDrive(SDLcdrom, &stbuf); - } - if ( delim ) { - SDLcdrom = delim; - } else { - SDLcdrom = NULL; - } - } while ( SDLcdrom ); - SDL_stack_free(cdpath); - } - - /* If we found our drives, there's nothing left to do */ - if ( SDL_numcds > 0 ) { - return(0); - } - } - - CheckMounts(); - CheckNonmounts(); - - return 0; + if (CheckDrive(SDLcdrom, &stbuf) > 0) { + AddDrive(SDLcdrom, &stbuf); + } + if (delim) { + SDLcdrom = delim; + } else { + SDLcdrom = NULL; + } + } + while (SDLcdrom); + SDL_stack_free(cdpath); + } + + /* If we found our drives, there's nothing left to do */ + if (SDL_numcds > 0) { + return (0); + } + } + + CheckMounts(); + CheckNonmounts(); + + return 0; } /* General ioctl() CD-ROM command function */ -static int SDL_SYS_CDioctl(int id, int command, void *arg) +static int +SDL_SYS_CDioctl(int id, int command, void *arg) { int retval; retval = ioctl(id, command, arg); - if ( retval < 0 ) { + if (retval < 0) { SDL_SetError("ioctl() error: %s", strerror(errno)); } return retval; } -static const char *SDL_SYS_CDName(int drive) +static const char * +SDL_SYS_CDName(int drive) { - return(SDL_cdlist[drive]); + return (SDL_cdlist[drive]); } -static int SDL_SYS_CDOpen(int drive) +static int +SDL_SYS_CDOpen(int drive) { - int fd; - char* lastsl; - char* cdromname; + int fd; + char *lastsl; + char *cdromname; size_t len; /* * We found /dev/cd? drives and that is in our list. But we can * open only the /dev/rcd? versions of those devices for Audio CD. */ - len = SDL_strlen(SDL_cdlist[drive])+2; - cdromname = (char*)SDL_malloc(len); - SDL_strlcpy(cdromname,SDL_cdlist[drive],len); - lastsl = SDL_strrchr(cdromname,'/'); + len = SDL_strlen(SDL_cdlist[drive]) + 2; + cdromname = (char *) SDL_malloc(len); + SDL_strlcpy(cdromname, SDL_cdlist[drive], len); + lastsl = SDL_strrchr(cdromname, '/'); if (lastsl) { - *lastsl = 0; - SDL_strlcat(cdromname,"/r",len); - lastsl = SDL_strrchr(SDL_cdlist[drive],'/'); - if (lastsl) { - lastsl++; - SDL_strlcat(cdromname,lastsl,len); - } + *lastsl = 0; + SDL_strlcat(cdromname, "/r", len); + lastsl = SDL_strrchr(SDL_cdlist[drive], '/'); + if (lastsl) { + lastsl++; + SDL_strlcat(cdromname, lastsl, len); + } } - #ifdef DEBUG_CDROM - fprintf(stderr, "Should open drive %s, opening %s\n", SDL_cdlist[drive], cdromname); + fprintf(stderr, "Should open drive %s, opening %s\n", SDL_cdlist[drive], + cdromname); #endif /* @@ -393,176 +398,175 @@ static int SDL_SYS_CDOpen(int drive) * exclusive access with less trouble. */ fd = openx(cdromname, O_RDONLY, NULL, SC_SINGLE); - if ( fd < 0 ) - { + if (fd < 0) { #ifdef DEBUG_CDROM - fprintf(stderr, "Could not open drive %s (%s)\n", cdromname, strerror(errno)); + fprintf(stderr, "Could not open drive %s (%s)\n", cdromname, + strerror(errno)); #endif - } - else - { - struct mode_form_op cdMode; - int ret; + } else { + struct mode_form_op cdMode; + int ret; #ifdef DEBUG_CDROM - cdMode.action = CD_GET_MODE; - ret = SDL_SYS_CDioctl(fd, DK_CD_MODE, &cdMode); - if ( ret < 0 ) { + cdMode.action = CD_GET_MODE; + ret = SDL_SYS_CDioctl(fd, DK_CD_MODE, &cdMode); + if (ret < 0) { fprintf(stderr, - "Could not get drive mode for %s (%s)\n", - cdromname, strerror(errno)); - } else { - switch(cdMode.cd_mode_form) { - case CD_MODE1 : - fprintf(stderr, - "Drive mode for %s is %s\n", - cdromname, "CD-ROM Data Mode 1"); - break; - case CD_MODE2_FORM1 : - fprintf(stderr, - "Drive mode for %s is %s\n", - cdromname, "CD-ROM XA Data Mode 2 Form 1"); - break; - case CD_MODE2_FORM2 : - fprintf(stderr, - "Drive mode for %s is %s\n", - cdromname, "CD-ROM XA Data Mode 2 Form 2"); - break; - case CD_DA : - fprintf(stderr, - "Drive mode for %s is %s\n", - cdromname, "CD-DA"); - break; - default : - fprintf(stderr, - "Drive mode for %s is %s\n", - cdromname, "unknown"); - break; - } - } + "Could not get drive mode for %s (%s)\n", + cdromname, strerror(errno)); + } else { + switch (cdMode.cd_mode_form) { + case CD_MODE1: + fprintf(stderr, + "Drive mode for %s is %s\n", + cdromname, "CD-ROM Data Mode 1"); + break; + case CD_MODE2_FORM1: + fprintf(stderr, + "Drive mode for %s is %s\n", + cdromname, "CD-ROM XA Data Mode 2 Form 1"); + break; + case CD_MODE2_FORM2: + fprintf(stderr, + "Drive mode for %s is %s\n", + cdromname, "CD-ROM XA Data Mode 2 Form 2"); + break; + case CD_DA: + fprintf(stderr, + "Drive mode for %s is %s\n", cdromname, "CD-DA"); + break; + default: + fprintf(stderr, + "Drive mode for %s is %s\n", cdromname, "unknown"); + break; + } + } #endif - cdMode.action = CD_CHG_MODE; - cdMode.cd_mode_form = CD_DA; - ret = SDL_SYS_CDioctl(fd, DK_CD_MODE, &cdMode); - if ( ret < 0 ) { + cdMode.action = CD_CHG_MODE; + cdMode.cd_mode_form = CD_DA; + ret = SDL_SYS_CDioctl(fd, DK_CD_MODE, &cdMode); + if (ret < 0) { #ifdef DEBUG_CDROM fprintf(stderr, - "Could not set drive mode for %s (%s)\n", - cdromname, strerror(errno)); + "Could not set drive mode for %s (%s)\n", + cdromname, strerror(errno)); #endif - SDL_SetError("ioctl() error: Could not set CD drive mode, %s", - strerror(errno)); - } else { + SDL_SetError + ("ioctl() error: Could not set CD drive mode, %s", + strerror(errno)); + } else { #ifdef DEBUG_CDROM - fprintf(stderr, - "Drive mode for %s set to CD_DA\n", - cdromname); + fprintf(stderr, "Drive mode for %s set to CD_DA\n", cdromname); #endif - } + } } SDL_free(cdromname); return fd; } -static int SDL_SYS_CDGetTOC(SDL_CD *cdrom) +static int +SDL_SYS_CDGetTOC(SDL_CD * cdrom) { struct cd_audio_cmd cmd; struct cd_audio_cmd entry; - int i; - int okay; + int i; + int okay; cmd.audio_cmds = CD_TRK_INFO_AUDIO; - cmd.msf_flag = FALSE; - if ( SDL_SYS_CDioctl(cdrom->id, DKAUDIO, &cmd) < 0 ) { - return -1; + cmd.msf_flag = FALSE; + if (SDL_SYS_CDioctl(cdrom->id, DKAUDIO, &cmd) < 0) { + return -1; } okay = 0; cdrom->numtracks = cmd.indexing.track_index.last_track - - cmd.indexing.track_index.first_track+1; - if ( cdrom->numtracks > SDL_MAX_TRACKS ) { + - cmd.indexing.track_index.first_track + 1; + if (cdrom->numtracks > SDL_MAX_TRACKS) { cdrom->numtracks = SDL_MAX_TRACKS; } /* Read all the track TOC entries */ - for ( i=0; i<=cdrom->numtracks; ++i ) { - if ( i == cdrom->numtracks ) { + for (i = 0; i <= cdrom->numtracks; ++i) { + if (i == cdrom->numtracks) { cdrom->track[i].id = 0xAA;; } else { - cdrom->track[i].id = cmd.indexing.track_index.first_track+i; + cdrom->track[i].id = cmd.indexing.track_index.first_track + i; } - entry.audio_cmds = CD_GET_TRK_MSF; - entry.indexing.track_msf.track = cdrom->track[i].id; - if ( SDL_SYS_CDioctl(cdrom->id, DKAUDIO, &entry) < 0 ) { + entry.audio_cmds = CD_GET_TRK_MSF; + entry.indexing.track_msf.track = cdrom->track[i].id; + if (SDL_SYS_CDioctl(cdrom->id, DKAUDIO, &entry) < 0) { break; } else { - cdrom->track[i].type = 0; /* don't know how to detect 0x04 data track */ - cdrom->track[i].offset = MSF_TO_FRAMES( - entry.indexing.track_msf.mins, - entry.indexing.track_msf.secs, - entry.indexing.track_msf.frames); + cdrom->track[i].type = 0; /* don't know how to detect 0x04 data track */ + cdrom->track[i].offset = + MSF_TO_FRAMES(entry.indexing.track_msf.mins, + entry.indexing.track_msf.secs, + entry.indexing.track_msf.frames); cdrom->track[i].length = 0; - if ( i > 0 ) { - cdrom->track[i-1].length = cdrom->track[i].offset - - cdrom->track[i-1].offset; + if (i > 0) { + cdrom->track[i - 1].length = cdrom->track[i].offset + - cdrom->track[i - 1].offset; } } } - if ( i == (cdrom->numtracks+1) ) { + if (i == (cdrom->numtracks + 1)) { okay = 1; } - return(okay ? 0 : -1); + return (okay ? 0 : -1); } /* Get CD-ROM status */ -static CDstatus SDL_SYS_CDStatus(SDL_CD *cdrom, int *position) +static CDstatus +SDL_SYS_CDStatus(SDL_CD * cdrom, int *position) { - CDstatus status; + CDstatus status; struct cd_audio_cmd cmd; cmd.audio_cmds = CD_INFO_AUDIO; - if ( SDL_SYS_CDioctl(cdrom->id, DKAUDIO, &cmd) < 0 ) { + if (SDL_SYS_CDioctl(cdrom->id, DKAUDIO, &cmd) < 0) { #ifdef DEBUG_CDROM - fprintf(stderr, "ioctl failed in SDL_SYS_CDStatus (%s)\n", SDL_GetError()); + fprintf(stderr, "ioctl failed in SDL_SYS_CDStatus (%s)\n", + SDL_GetError()); #endif status = CD_ERROR; } else { switch (cmd.status) { - case CD_NO_AUDIO: - case CD_COMPLETED: - status = CD_STOPPED; - break; - case CD_PLAY_AUDIO: - status = CD_PLAYING; - break; - case CD_PAUSE_AUDIO: - status = CD_PAUSED; - break; - case CD_NOT_VALID: + case CD_NO_AUDIO: + case CD_COMPLETED: + status = CD_STOPPED; + break; + case CD_PLAY_AUDIO: + status = CD_PLAYING; + break; + case CD_PAUSE_AUDIO: + status = CD_PAUSED; + break; + case CD_NOT_VALID: #ifdef DEBUG_CDROM - fprintf(stderr, "cdStatus failed with CD_NOT_VALID\n"); + fprintf(stderr, "cdStatus failed with CD_NOT_VALID\n"); #endif - status = CD_ERROR; - break; - case CD_STATUS_ERROR: + status = CD_ERROR; + break; + case CD_STATUS_ERROR: #ifdef DEBUG_CDROM - fprintf(stderr, "cdStatus failed with CD_STATUS_ERROR\n"); + fprintf(stderr, "cdStatus failed with CD_STATUS_ERROR\n"); #endif - status = CD_ERROR; - break; - default: + status = CD_ERROR; + break; + default: #ifdef DEBUG_CDROM - fprintf(stderr, "cdStatus failed with unknown error\n"); + fprintf(stderr, "cdStatus failed with unknown error\n"); #endif - status = CD_ERROR; - break; + status = CD_ERROR; + break; } } - if ( position ) { - if ( status == CD_PLAYING || (status == CD_PAUSED) ) { - *position = MSF_TO_FRAMES( cmd.indexing.info_audio.current_mins, - cmd.indexing.info_audio.current_secs, - cmd.indexing.info_audio.current_frames); + if (position) { + if (status == CD_PLAYING || (status == CD_PAUSED)) { + *position = + MSF_TO_FRAMES(cmd.indexing.info_audio.current_mins, + cmd.indexing.info_audio.current_secs, + cmd.indexing.info_audio.current_frames); } else { *position = 0; } @@ -571,7 +575,8 @@ static CDstatus SDL_SYS_CDStatus(SDL_CD *cdrom, int *position) } /* Start play */ -static int SDL_SYS_CDPlay(SDL_CD *cdrom, int start, int length) +static int +SDL_SYS_CDPlay(SDL_CD * cdrom, int start, int length) { struct cd_audio_cmd cmd; @@ -581,80 +586,85 @@ static int SDL_SYS_CDPlay(SDL_CD *cdrom, int start, int length) * its better to do this elsewhere? */ cmd.audio_cmds = CD_PLAY_AUDIO | CD_SET_VOLUME; - cmd.msf_flag = TRUE; + cmd.msf_flag = TRUE; FRAMES_TO_MSF(start, &cmd.indexing.msf.first_mins, &cmd.indexing.msf.first_secs, &cmd.indexing.msf.first_frames); - FRAMES_TO_MSF(start+length, + FRAMES_TO_MSF(start + length, &cmd.indexing.msf.last_mins, - &cmd.indexing.msf.last_secs, - &cmd.indexing.msf.last_frames); - cmd.volume_type = CD_VOLUME_ALL; - cmd.all_channel_vol = 255; /* This is a uchar. What is a good value? No docu! */ - cmd.out_port_0_sel = CD_AUDIO_CHNL_0; - cmd.out_port_1_sel = CD_AUDIO_CHNL_1; - cmd.out_port_2_sel = CD_AUDIO_CHNL_2; - cmd.out_port_3_sel = CD_AUDIO_CHNL_3; + &cmd.indexing.msf.last_secs, &cmd.indexing.msf.last_frames); + cmd.volume_type = CD_VOLUME_ALL; + cmd.all_channel_vol = 255; /* This is a uchar. What is a good value? No docu! */ + cmd.out_port_0_sel = CD_AUDIO_CHNL_0; + cmd.out_port_1_sel = CD_AUDIO_CHNL_1; + cmd.out_port_2_sel = CD_AUDIO_CHNL_2; + cmd.out_port_3_sel = CD_AUDIO_CHNL_3; #ifdef DEBUG_CDROM - fprintf(stderr, "Trying to play from %d:%d:%d to %d:%d:%d\n", - cmd.indexing.msf.first_mins, - cmd.indexing.msf.first_secs, - cmd.indexing.msf.first_frames, - cmd.indexing.msf.last_mins, - cmd.indexing.msf.last_secs, - cmd.indexing.msf.last_frames); + fprintf(stderr, "Trying to play from %d:%d:%d to %d:%d:%d\n", + cmd.indexing.msf.first_mins, + cmd.indexing.msf.first_secs, + cmd.indexing.msf.first_frames, + cmd.indexing.msf.last_mins, + cmd.indexing.msf.last_secs, cmd.indexing.msf.last_frames); #endif - return(SDL_SYS_CDioctl(cdrom->id, DKAUDIO, &cmd)); + return (SDL_SYS_CDioctl(cdrom->id, DKAUDIO, &cmd)); } /* Pause play */ -static int SDL_SYS_CDPause(SDL_CD *cdrom) +static int +SDL_SYS_CDPause(SDL_CD * cdrom) { struct cd_audio_cmd cmd; cmd.audio_cmds = CD_PAUSE_AUDIO; - return(SDL_SYS_CDioctl(cdrom->id, DKAUDIO, &cmd)); + return (SDL_SYS_CDioctl(cdrom->id, DKAUDIO, &cmd)); } /* Resume play */ -static int SDL_SYS_CDResume(SDL_CD *cdrom) +static int +SDL_SYS_CDResume(SDL_CD * cdrom) { struct cd_audio_cmd cmd; cmd.audio_cmds = CD_RESUME_AUDIO; - return(SDL_SYS_CDioctl(cdrom->id, DKAUDIO, &cmd)); + return (SDL_SYS_CDioctl(cdrom->id, DKAUDIO, &cmd)); } /* Stop play */ -static int SDL_SYS_CDStop(SDL_CD *cdrom) +static int +SDL_SYS_CDStop(SDL_CD * cdrom) { struct cd_audio_cmd cmd; cmd.audio_cmds = CD_STOP_AUDIO; - return(SDL_SYS_CDioctl(cdrom->id, DKAUDIO, &cmd)); + return (SDL_SYS_CDioctl(cdrom->id, DKAUDIO, &cmd)); } /* Eject the CD-ROM */ -static int SDL_SYS_CDEject(SDL_CD *cdrom) +static int +SDL_SYS_CDEject(SDL_CD * cdrom) { - return(SDL_SYS_CDioctl(cdrom->id, DKEJECT, 0)); + return (SDL_SYS_CDioctl(cdrom->id, DKEJECT, 0)); } /* Close the CD-ROM handle */ -static void SDL_SYS_CDClose(SDL_CD *cdrom) +static void +SDL_SYS_CDClose(SDL_CD * cdrom) { close(cdrom->id); } -void SDL_SYS_CDQuit(void) +void +SDL_SYS_CDQuit(void) { - int i; - - if ( SDL_numcds > 0 ) { - for ( i=0; i 0) { + for (i = 0; i < SDL_numcds; ++i) { + SDL_free(SDL_cdlist[i]); + } + SDL_numcds = 0; + } } #endif /* SDL_CDROM_AIX */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/cdrom/beos/SDL_syscdrom.cc b/src/cdrom/beos/SDL_syscdrom.cc index af9094ab7..3bca020b6 100644 --- a/src/cdrom/beos/SDL_syscdrom.cc +++ b/src/cdrom/beos/SDL_syscdrom.cc @@ -37,7 +37,8 @@ #include #include "SDL_cdrom.h" -extern "C" { +extern "C" +{ #include "../SDL_syscdrom.h" } @@ -59,7 +60,7 @@ extern "C" { #define POS_REL_F(pos) pos.position[15] /* The maximum number of CD-ROM drives we'll detect */ -#define MAX_DRIVES 16 +#define MAX_DRIVES 16 /* A list of available CD-ROM drives */ static char *SDL_cdlist[MAX_DRIVES]; @@ -67,346 +68,361 @@ static char *SDL_cdlist[MAX_DRIVES]; /* The system-dependent CD control functions */ static const char *SDL_SYS_CDName(int drive); static int SDL_SYS_CDOpen(int drive); -static int SDL_SYS_CDGetTOC(SDL_CD *cdrom); -static CDstatus SDL_SYS_CDStatus(SDL_CD *cdrom, int *position); -static int SDL_SYS_CDPlay(SDL_CD *cdrom, int start, int length); -static int SDL_SYS_CDPause(SDL_CD *cdrom); -static int SDL_SYS_CDResume(SDL_CD *cdrom); -static int SDL_SYS_CDStop(SDL_CD *cdrom); -static int SDL_SYS_CDEject(SDL_CD *cdrom); -static void SDL_SYS_CDClose(SDL_CD *cdrom); +static int SDL_SYS_CDGetTOC(SDL_CD * cdrom); +static CDstatus SDL_SYS_CDStatus(SDL_CD * cdrom, int *position); +static int SDL_SYS_CDPlay(SDL_CD * cdrom, int start, int length); +static int SDL_SYS_CDPause(SDL_CD * cdrom); +static int SDL_SYS_CDResume(SDL_CD * cdrom); +static int SDL_SYS_CDStop(SDL_CD * cdrom); +static int SDL_SYS_CDEject(SDL_CD * cdrom); +static void SDL_SYS_CDClose(SDL_CD * cdrom); int try_dir(const char *directory); /* Check a drive to see if it is a CD-ROM */ -static int CheckDrive(char *drive) +static int +CheckDrive(char *drive) { - struct stat stbuf; - int is_cd, cdfd; - device_geometry info; - - /* If it doesn't exist, return -1 */ - if ( stat(drive, &stbuf) < 0 ) { - return(-1); - } - - /* If it does exist, verify that it's an available CD-ROM */ - is_cd = 0; - cdfd = open(drive, 0); - if ( cdfd >= 0 ) { - if ( ioctl(cdfd, B_GET_GEOMETRY, &info) == B_NO_ERROR ) { - if ( info.device_type == B_CD ) { - is_cd = 1; - } - } - close(cdfd); - } else { - /* This can happen when the drive is open .. (?) */; - is_cd = 1; - } - return(is_cd); + struct stat stbuf; + int is_cd, cdfd; + device_geometry info; + + /* If it doesn't exist, return -1 */ + if (stat(drive, &stbuf) < 0) { + return (-1); + } + + /* If it does exist, verify that it's an available CD-ROM */ + is_cd = 0; + cdfd = open(drive, 0); + if (cdfd >= 0) { + if (ioctl(cdfd, B_GET_GEOMETRY, &info) == B_NO_ERROR) { + if (info.device_type == B_CD) { + is_cd = 1; + } + } + close(cdfd); + } else { + /* This can happen when the drive is open .. (?) */ ; + is_cd = 1; + } + return (is_cd); } /* Add a CD-ROM drive to our list of valid drives */ -static void AddDrive(char *drive) +static void +AddDrive(char *drive) { - int i; - size_t len; - - if ( SDL_numcds < MAX_DRIVES ) { - /* Add this drive to our list */ - i = SDL_numcds; - len = SDL_strlen(drive)+1; - SDL_cdlist[i] = (char *)SDL_malloc(len); - if ( SDL_cdlist[i] == NULL ) { - SDL_OutOfMemory(); - return; - } - SDL_strlcpy(SDL_cdlist[i], drive, len); - ++SDL_numcds; + int i; + size_t len; + + if (SDL_numcds < MAX_DRIVES) { + /* Add this drive to our list */ + i = SDL_numcds; + len = SDL_strlen(drive) + 1; + SDL_cdlist[i] = (char *) SDL_malloc(len); + if (SDL_cdlist[i] == NULL) { + SDL_OutOfMemory(); + return; + } + SDL_strlcpy(SDL_cdlist[i], drive, len); + ++SDL_numcds; #ifdef CDROM_DEBUG - fprintf(stderr, "Added CD-ROM drive: %s\n", drive); + fprintf(stderr, "Added CD-ROM drive: %s\n", drive); #endif - } + } } /* IDE bus scanning magic */ -enum { - IDE_GET_DEVICES_INFO = B_DEVICE_OP_CODES_END + 50, +enum +{ + IDE_GET_DEVICES_INFO = B_DEVICE_OP_CODES_END + 50, }; -struct ide_ctrl_info { - bool ide_0_present; - bool ide_0_master_present; - bool ide_0_slave_present; - int ide_0_master_type; - int ide_0_slave_type; - bool ide_1_present; - bool ide_1_master_present; - bool ide_1_slave_present; - int ide_1_master_type; - int ide_1_slave_type; +struct ide_ctrl_info +{ + bool ide_0_present; + bool ide_0_master_present; + bool ide_0_slave_present; + int ide_0_master_type; + int ide_0_slave_type; + bool ide_1_present; + bool ide_1_master_present; + bool ide_1_slave_present; + int ide_1_master_type; + int ide_1_slave_type; }; -int SDL_SYS_CDInit(void) +int +SDL_SYS_CDInit(void) { - char *SDLcdrom; - int raw_fd; - struct ide_ctrl_info info; - - /* Fill in our driver capabilities */ - SDL_CDcaps.Name = SDL_SYS_CDName; - SDL_CDcaps.Open = SDL_SYS_CDOpen; - SDL_CDcaps.GetTOC = SDL_SYS_CDGetTOC; - SDL_CDcaps.Status = SDL_SYS_CDStatus; - SDL_CDcaps.Play = SDL_SYS_CDPlay; - SDL_CDcaps.Pause = SDL_SYS_CDPause; - SDL_CDcaps.Resume = SDL_SYS_CDResume; - SDL_CDcaps.Stop = SDL_SYS_CDStop; - SDL_CDcaps.Eject = SDL_SYS_CDEject; - SDL_CDcaps.Close = SDL_SYS_CDClose; - - /* Look in the environment for our CD-ROM drive list */ - SDLcdrom = SDL_getenv("SDL_CDROM"); /* ':' separated list of devices */ - if ( SDLcdrom != NULL ) { - char *cdpath, *delim; - size_t len = SDL_strlen(SDLcdrom)+1; - cdpath = SDL_stack_alloc(char, len); - if ( cdpath != NULL ) { - SDL_strlcpy(cdpath, SDLcdrom, len); - SDLcdrom = cdpath; - do { - delim = SDL_strchr(SDLcdrom, ':'); - if ( delim ) { - *delim++ = '\0'; - } - if ( CheckDrive(SDLcdrom) > 0 ) { - AddDrive(SDLcdrom); - } - if ( delim ) { - SDLcdrom = delim; - } else { - SDLcdrom = NULL; - } - } while ( SDLcdrom ); - SDL_stack_free(cdpath); - } - - /* If we found our drives, there's nothing left to do */ - if ( SDL_numcds > 0 ) { - return(0); - } - } - - /* Scan the system for CD-ROM drives */ - try_dir("/dev/disk"); - return 0; + char *SDLcdrom; + int raw_fd; + struct ide_ctrl_info info; + + /* Fill in our driver capabilities */ + SDL_CDcaps.Name = SDL_SYS_CDName; + SDL_CDcaps.Open = SDL_SYS_CDOpen; + SDL_CDcaps.GetTOC = SDL_SYS_CDGetTOC; + SDL_CDcaps.Status = SDL_SYS_CDStatus; + SDL_CDcaps.Play = SDL_SYS_CDPlay; + SDL_CDcaps.Pause = SDL_SYS_CDPause; + SDL_CDcaps.Resume = SDL_SYS_CDResume; + SDL_CDcaps.Stop = SDL_SYS_CDStop; + SDL_CDcaps.Eject = SDL_SYS_CDEject; + SDL_CDcaps.Close = SDL_SYS_CDClose; + + /* Look in the environment for our CD-ROM drive list */ + SDLcdrom = SDL_getenv("SDL_CDROM"); /* ':' separated list of devices */ + if (SDLcdrom != NULL) { + char *cdpath, *delim; + size_t len = SDL_strlen(SDLcdrom) + 1; + cdpath = SDL_stack_alloc(char, len); + if (cdpath != NULL) { + SDL_strlcpy(cdpath, SDLcdrom, len); + SDLcdrom = cdpath; + do { + delim = SDL_strchr(SDLcdrom, ':'); + if (delim) { + *delim++ = '\0'; + } + if (CheckDrive(SDLcdrom) > 0) { + AddDrive(SDLcdrom); + } + if (delim) { + SDLcdrom = delim; + } else { + SDLcdrom = NULL; + } + } + while (SDLcdrom); + SDL_stack_free(cdpath); + } + + /* If we found our drives, there's nothing left to do */ + if (SDL_numcds > 0) { + return (0); + } + } + + /* Scan the system for CD-ROM drives */ + try_dir("/dev/disk"); + return 0; } -int try_dir(const char *directory) -{ - BDirectory dir; - dir.SetTo(directory); - if(dir.InitCheck() != B_NO_ERROR) { - return false; - } - dir.Rewind(); - BEntry entry; - while(dir.GetNextEntry(&entry) >= 0) { - BPath path; - const char *name; - entry_ref e; - - if(entry.GetPath(&path) != B_NO_ERROR) - continue; - name = path.Path(); - - if(entry.GetRef(&e) != B_NO_ERROR) - continue; - - if(entry.IsDirectory()) { - if(SDL_strcmp(e.name, "floppy") == 0) - continue; /* ignore floppy (it is not silent) */ - int devfd = try_dir(name); - if(devfd >= 0) - return devfd; - } - else { - int devfd; - device_geometry g; - - if(SDL_strcmp(e.name, "raw") != 0) - continue; /* ignore partitions */ - - devfd = open(name, O_RDONLY); - if(devfd < 0) - continue; - - if(ioctl(devfd, B_GET_GEOMETRY, &g, sizeof(g)) >= 0) { - if(g.device_type == B_CD) - { - AddDrive(strdup(name)); - } - } - close(devfd); - } - } - return B_ERROR; +int +try_dir(const char *directory) +{ + BDirectory dir; + dir.SetTo(directory); + if (dir.InitCheck() != B_NO_ERROR) { + return false; + } + dir.Rewind(); + BEntry entry; + while (dir.GetNextEntry(&entry) >= 0) { + BPath path; + const char *name; + entry_ref e; + + if (entry.GetPath(&path) != B_NO_ERROR) + continue; + name = path.Path(); + + if (entry.GetRef(&e) != B_NO_ERROR) + continue; + + if (entry.IsDirectory()) { + if (SDL_strcmp(e.name, "floppy") == 0) + continue; /* ignore floppy (it is not silent) */ + int devfd = try_dir(name); + if (devfd >= 0) + return devfd; + } else { + int devfd; + device_geometry g; + + if (SDL_strcmp(e.name, "raw") != 0) + continue; /* ignore partitions */ + + devfd = open(name, O_RDONLY); + if (devfd < 0) + continue; + + if (ioctl(devfd, B_GET_GEOMETRY, &g, sizeof(g)) >= 0) { + if (g.device_type == B_CD) { + AddDrive(strdup(name)); + } + } + close(devfd); + } + } + return B_ERROR; } /* General ioctl() CD-ROM command function */ -static int SDL_SYS_CDioctl(int index, int command, void *arg) +static int +SDL_SYS_CDioctl(int index, int command, void *arg) { - int okay; - int fd; - - okay = 0; - fd = open(SDL_cdlist[index], 0); - if ( fd >= 0 ) { - if ( ioctl(fd, command, arg) == B_NO_ERROR ) { - okay = 1; - } - close(fd); - } - return(okay ? 0 : -1); + int okay; + int fd; + + okay = 0; + fd = open(SDL_cdlist[index], 0); + if (fd >= 0) { + if (ioctl(fd, command, arg) == B_NO_ERROR) { + okay = 1; + } + close(fd); + } + return (okay ? 0 : -1); } -static const char *SDL_SYS_CDName(int drive) +static const char * +SDL_SYS_CDName(int drive) { - return(SDL_cdlist[drive]); -} + return (SDL_cdlist[drive]); +} -static int SDL_SYS_CDOpen(int drive) +static int +SDL_SYS_CDOpen(int drive) { - return(drive); + return (drive); } -static int SDL_SYS_CDGetTOC(SDL_CD *cdrom) +static int +SDL_SYS_CDGetTOC(SDL_CD * cdrom) { - int i; - scsi_toc toc; - - if ( SDL_SYS_CDioctl(cdrom->id, B_SCSI_GET_TOC, &toc) == 0 ) { - cdrom->numtracks = CD_NUMTRACKS(toc); - if ( cdrom->numtracks > SDL_MAX_TRACKS ) { - cdrom->numtracks = SDL_MAX_TRACKS; - } - for ( i=0; i<=cdrom->numtracks; ++i ) { - cdrom->track[i].id = CD_TRACK_N(toc, i); - /* FIXME: How do we tell on BeOS? */ - cdrom->track[i].type = SDL_AUDIO_TRACK; - cdrom->track[i].offset = MSF_TO_FRAMES( - CD_TRACK_M(toc, i), - CD_TRACK_S(toc, i), - CD_TRACK_F(toc, i)); - cdrom->track[i].length = 0; - if ( i > 0 ) { - cdrom->track[i-1].length = - cdrom->track[i].offset- - cdrom->track[i-1].offset; - } - } - return(0); - } else { - return(-1); - } + int i; + scsi_toc toc; + + if (SDL_SYS_CDioctl(cdrom->id, B_SCSI_GET_TOC, &toc) == 0) { + cdrom->numtracks = CD_NUMTRACKS(toc); + if (cdrom->numtracks > SDL_MAX_TRACKS) { + cdrom->numtracks = SDL_MAX_TRACKS; + } + for (i = 0; i <= cdrom->numtracks; ++i) { + cdrom->track[i].id = CD_TRACK_N(toc, i); + /* FIXME: How do we tell on BeOS? */ + cdrom->track[i].type = SDL_AUDIO_TRACK; + cdrom->track[i].offset = MSF_TO_FRAMES(CD_TRACK_M(toc, i), + CD_TRACK_S(toc, i), + CD_TRACK_F(toc, i)); + cdrom->track[i].length = 0; + if (i > 0) { + cdrom->track[i - 1].length = + cdrom->track[i].offset - cdrom->track[i - 1].offset; + } + } + return (0); + } else { + return (-1); + } } /* Get CD-ROM status */ -static CDstatus SDL_SYS_CDStatus(SDL_CD *cdrom, int *position) +static CDstatus +SDL_SYS_CDStatus(SDL_CD * cdrom, int *position) { - CDstatus status; - int fd; - int cur_frame; - scsi_position pos; - - fd = open(SDL_cdlist[cdrom->id], 0); - cur_frame = 0; - if ( fd >= 0 ) { - if ( ioctl(fd, B_SCSI_GET_POSITION, &pos) == B_NO_ERROR ) { - cur_frame = MSF_TO_FRAMES( - POS_ABS_M(pos), POS_ABS_S(pos), POS_ABS_F(pos)); - } - if ( ! pos.position[1] || (pos.position[1] >= 0x13) || - ((pos.position[1] == 0x12) && (!pos.position[6])) ) { - status = CD_STOPPED; - } else - if ( pos.position[1] == 0x11 ) { - status = CD_PLAYING; - } else { - status = CD_PAUSED; - } - close(fd); - } else { - status = CD_TRAYEMPTY; - } - if ( position ) { - *position = cur_frame; - } - return(status); + CDstatus status; + int fd; + int cur_frame; + scsi_position pos; + + fd = open(SDL_cdlist[cdrom->id], 0); + cur_frame = 0; + if (fd >= 0) { + if (ioctl(fd, B_SCSI_GET_POSITION, &pos) == B_NO_ERROR) { + cur_frame = + MSF_TO_FRAMES(POS_ABS_M(pos), POS_ABS_S(pos), POS_ABS_F(pos)); + } + if (!pos.position[1] || (pos.position[1] >= 0x13) || + ((pos.position[1] == 0x12) && (!pos.position[6]))) { + status = CD_STOPPED; + } else if (pos.position[1] == 0x11) { + status = CD_PLAYING; + } else { + status = CD_PAUSED; + } + close(fd); + } else { + status = CD_TRAYEMPTY; + } + if (position) { + *position = cur_frame; + } + return (status); } /* Start play */ -static int SDL_SYS_CDPlay(SDL_CD *cdrom, int start, int length) +static int +SDL_SYS_CDPlay(SDL_CD * cdrom, int start, int length) { - int okay; - int fd; - scsi_play_position pos; - - okay = 0; - fd = open(SDL_cdlist[cdrom->id], 0); - if ( fd >= 0 ) { - FRAMES_TO_MSF(start, &pos.start_m, &pos.start_s, &pos.start_f); - FRAMES_TO_MSF(start+length, &pos.end_m, &pos.end_s, &pos.end_f); - if ( ioctl(fd, B_SCSI_PLAY_POSITION, &pos) == B_NO_ERROR ) { - okay = 1; - } - close(fd); - } - return(okay ? 0 : -1); + int okay; + int fd; + scsi_play_position pos; + + okay = 0; + fd = open(SDL_cdlist[cdrom->id], 0); + if (fd >= 0) { + FRAMES_TO_MSF(start, &pos.start_m, &pos.start_s, &pos.start_f); + FRAMES_TO_MSF(start + length, &pos.end_m, &pos.end_s, &pos.end_f); + if (ioctl(fd, B_SCSI_PLAY_POSITION, &pos) == B_NO_ERROR) { + okay = 1; + } + close(fd); + } + return (okay ? 0 : -1); } /* Pause play */ -static int SDL_SYS_CDPause(SDL_CD *cdrom) +static int +SDL_SYS_CDPause(SDL_CD * cdrom) { - return(SDL_SYS_CDioctl(cdrom->id, B_SCSI_PAUSE_AUDIO, 0)); + return (SDL_SYS_CDioctl(cdrom->id, B_SCSI_PAUSE_AUDIO, 0)); } /* Resume play */ -static int SDL_SYS_CDResume(SDL_CD *cdrom) +static int +SDL_SYS_CDResume(SDL_CD * cdrom) { - return(SDL_SYS_CDioctl(cdrom->id, B_SCSI_RESUME_AUDIO, 0)); + return (SDL_SYS_CDioctl(cdrom->id, B_SCSI_RESUME_AUDIO, 0)); } /* Stop play */ -static int SDL_SYS_CDStop(SDL_CD *cdrom) +static int +SDL_SYS_CDStop(SDL_CD * cdrom) { - return(SDL_SYS_CDioctl(cdrom->id, B_SCSI_STOP_AUDIO, 0)); + return (SDL_SYS_CDioctl(cdrom->id, B_SCSI_STOP_AUDIO, 0)); } /* Eject the CD-ROM */ -static int SDL_SYS_CDEject(SDL_CD *cdrom) +static int +SDL_SYS_CDEject(SDL_CD * cdrom) { - return(SDL_SYS_CDioctl(cdrom->id, B_SCSI_EJECT, 0)); + return (SDL_SYS_CDioctl(cdrom->id, B_SCSI_EJECT, 0)); } /* Close the CD-ROM handle */ -static void SDL_SYS_CDClose(SDL_CD *cdrom) +static void +SDL_SYS_CDClose(SDL_CD * cdrom) { - close(cdrom->id); + close(cdrom->id); } -void SDL_SYS_CDQuit(void) +void +SDL_SYS_CDQuit(void) { - int i; - - if ( SDL_numcds > 0 ) { - for ( i=0; i 0) { + for (i = 0; i < SDL_numcds; ++i) { + SDL_free(SDL_cdlist[i]); + } + SDL_numcds = 0; + } } #endif /* SDL_CDROM_BEOS */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/cdrom/bsdi/SDL_syscdrom.c b/src/cdrom/bsdi/SDL_syscdrom.c index 7687f21c4..719c12d5e 100644 --- a/src/cdrom/bsdi/SDL_syscdrom.c +++ b/src/cdrom/bsdi/SDL_syscdrom.c @@ -53,20 +53,20 @@ int msf_to_frame(int minute, int second, int frame) - { - return(minute * FRAMES_PER_MINUTE + second * FRAMES_PER_SECOND + frame); - } +{ + return (minute * FRAMES_PER_MINUTE + second * FRAMES_PER_SECOND + frame); +} void frame_to_msf(int frame, int *minp, int *secp, int *framep) - { - *minp = frame / FRAMES_PER_MINUTE; - *secp = (frame % FRAMES_PER_MINUTE) / FRAMES_PER_SECOND; - *framep = frame % FRAMES_PER_SECOND; - } +{ + *minp = frame / FRAMES_PER_MINUTE; + *secp = (frame % FRAMES_PER_MINUTE) / FRAMES_PER_SECOND; + *framep = frame % FRAMES_PER_SECOND; +} /* The maximum number of CD-ROM drives we'll detect */ -#define MAX_DRIVES 16 +#define MAX_DRIVES 16 /* A list of available CD-ROM drives */ static char *SDL_cdlist[MAX_DRIVES]; @@ -75,468 +75,477 @@ static dev_t SDL_cdmode[MAX_DRIVES]; /* The system-dependent CD control functions */ static const char *SDL_SYS_CDName(int drive); static int SDL_SYS_CDOpen(int drive); -static int SDL_SYS_CDGetTOC(SDL_CD *cdrom); -static CDstatus SDL_SYS_CDStatus(SDL_CD *cdrom, int *position); -static int SDL_SYS_CDPlay(SDL_CD *cdrom, int start, int length); -static int SDL_SYS_CDPause(SDL_CD *cdrom); -static int SDL_SYS_CDResume(SDL_CD *cdrom); -static int SDL_SYS_CDStop(SDL_CD *cdrom); -static int SDL_SYS_CDEject(SDL_CD *cdrom); -static void SDL_SYS_CDClose(SDL_CD *cdrom); - -typedef struct scsi_cdb cdb_t; - -static int scsi_cmd(int fd, - struct scsi_cdb *cdb, - int cdblen, - int rw, - caddr_t data, - int datalen, - struct scsi_user_cdb *sus) - { - int scsistatus; - unsigned char *cp; - struct scsi_user_cdb suc; +static int SDL_SYS_CDGetTOC(SDL_CD * cdrom); +static CDstatus SDL_SYS_CDStatus(SDL_CD * cdrom, int *position); +static int SDL_SYS_CDPlay(SDL_CD * cdrom, int start, int length); +static int SDL_SYS_CDPause(SDL_CD * cdrom); +static int SDL_SYS_CDResume(SDL_CD * cdrom); +static int SDL_SYS_CDStop(SDL_CD * cdrom); +static int SDL_SYS_CDEject(SDL_CD * cdrom); +static void SDL_SYS_CDClose(SDL_CD * cdrom); + +typedef struct scsi_cdb cdb_t; + +static int +scsi_cmd(int fd, + struct scsi_cdb *cdb, + int cdblen, + int rw, caddr_t data, int datalen, struct scsi_user_cdb *sus) +{ + int scsistatus; + unsigned char *cp; + struct scsi_user_cdb suc; /* safety checks */ - if (!cdb) return(-1); - if (rw != SUC_READ && rw != SUC_WRITE) return(-1); - - suc.suc_flags = rw; - suc.suc_cdblen = cdblen; - bcopy(cdb, suc.suc_cdb, cdblen); - suc.suc_datalen = datalen; - suc.suc_data = data; - suc.suc_timeout = 10; /* 10 secs max for TUR or SENSE */ - if (ioctl(fd, SCSIRAWCDB, &suc) == -1) - return(-11); - scsistatus = suc.suc_sus.sus_status; - cp = suc.suc_sus.sus_sense; + if (!cdb) + return (-1); + if (rw != SUC_READ && rw != SUC_WRITE) + return (-1); + + suc.suc_flags = rw; + suc.suc_cdblen = cdblen; + bcopy(cdb, suc.suc_cdb, cdblen); + suc.suc_datalen = datalen; + suc.suc_data = data; + suc.suc_timeout = 10; /* 10 secs max for TUR or SENSE */ + if (ioctl(fd, SCSIRAWCDB, &suc) == -1) + return (-11); + scsistatus = suc.suc_sus.sus_status; + cp = suc.suc_sus.sus_sense; /* * If a place to copy the sense data back to has been provided then the * caller is responsible for checking the errors and printing any information * out if the status was not successful. */ - if (scsistatus != 0 && !sus) - { - fprintf(stderr,"scsistatus = %x cmd = %x\n", - scsistatus, cdb[0]); - fprintf(stderr, "sense %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x\n", - cp[0], cp[1], cp[2], cp[3], cp[4], cp[5], - cp[6], cp[7], cp[8], cp[9], cp[10], cp[11], - cp[12], cp[13], cp[14], cp[15]); - return(1); - } - if (sus) - bcopy(&suc, sus, sizeof (struct scsi_user_cdb)); - if (scsistatus) - return(1); /* Return non-zero for unsuccessful status */ - return(0); - } + if (scsistatus != 0 && !sus) { + fprintf(stderr, "scsistatus = %x cmd = %x\n", scsistatus, cdb[0]); + fprintf(stderr, + "sense %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x\n", + cp[0], cp[1], cp[2], cp[3], cp[4], cp[5], cp[6], cp[7], + cp[8], cp[9], cp[10], cp[11], cp[12], cp[13], cp[14], cp[15]); + return (1); + } + if (sus) + bcopy(&suc, sus, sizeof(struct scsi_user_cdb)); + if (scsistatus) + return (1); /* Return non-zero for unsuccessful status */ + return (0); +} /* request vendor brand and model */ -unsigned char *Inquiry(int fd) - { - static struct scsi_cdb6 cdb = - { - 0x12, - 0, 0, 0, - 56, - 0 - }; - static unsigned char Inqbuffer[56]; - - if (scsi_cmd(fd, (cdb_t *)&cdb, 6, SUC_READ, Inqbuffer, - sizeof(Inqbuffer), 0)) - return("\377"); - return(Inqbuffer); - } +unsigned char * +Inquiry(int fd) +{ + static struct scsi_cdb6 cdb = { + 0x12, + 0, 0, 0, + 56, + 0 + }; + static unsigned char Inqbuffer[56]; + + if (scsi_cmd(fd, (cdb_t *) & cdb, 6, SUC_READ, Inqbuffer, + sizeof(Inqbuffer), 0)) + return ("\377"); + return (Inqbuffer); +} #define ADD_SENSECODE 12 #define ADD_SC_QUALIFIER 13 -int TestForMedium(int fd) - { - int sts, asc, ascq; - struct scsi_user_cdb sus; - static struct scsi_cdb6 cdb = - { - CMD_TEST_UNIT_READY, /* command */ - 0, /* reserved */ - 0, /* reserved */ - 0, /* reserved */ - 0, /* reserved */ - 0 /* reserved */ - }; - -again: sts = scsi_cmd(fd, (cdb_t *)&cdb, 6, SUC_READ, 0, 0, &sus); - asc = sus.suc_sus.sus_sense[ADD_SENSECODE]; - ascq = sus.suc_sus.sus_sense[ADD_SC_QUALIFIER]; - if (asc == 0x3a && ascq == 0x0) /* no medium */ - return(0); - if (asc == 0x28 && ascq == 0x0) /* medium changed */ - goto again; - if (asc == 0x4 && ascq == 0x1 ) /* coming ready */ - { - sleep(2); - goto again; - } - return(1); - } +int +TestForMedium(int fd) +{ + int sts, asc, ascq; + struct scsi_user_cdb sus; + static struct scsi_cdb6 cdb = { + CMD_TEST_UNIT_READY, /* command */ + 0, /* reserved */ + 0, /* reserved */ + 0, /* reserved */ + 0, /* reserved */ + 0 /* reserved */ + }; + + again:sts = scsi_cmd(fd, (cdb_t *) & cdb, 6, SUC_READ, 0, 0, &sus); + asc = sus.suc_sus.sus_sense[ADD_SENSECODE]; + ascq = sus.suc_sus.sus_sense[ADD_SC_QUALIFIER]; + if (asc == 0x3a && ascq == 0x0) /* no medium */ + return (0); + if (asc == 0x28 && ascq == 0x0) /* medium changed */ + goto again; + if (asc == 0x4 && ascq == 0x1) { /* coming ready */ + sleep(2); + goto again; + } + return (1); +} /* Check a drive to see if it is a CD-ROM */ -static int CheckDrive(char *drive, struct stat *stbuf) +static int +CheckDrive(char *drive, struct stat *stbuf) { - int is_cd = 0, cdfd; - char *p; - - /* If it doesn't exist, return -1 */ - if ( stat(drive, stbuf) < 0 ) { - return(-1); - } - - /* If it does exist, verify that it's an available CD-ROM */ - cdfd = open(drive, (O_RDONLY|O_EXCL|O_NONBLOCK), 0); - if ( cdfd >= 0 ) { - p = Inquiry(cdfd); - if (*p == TYPE_ROM) - is_cd = 1; - close(cdfd); - } - return(is_cd); + int is_cd = 0, cdfd; + char *p; + + /* If it doesn't exist, return -1 */ + if (stat(drive, stbuf) < 0) { + return (-1); + } + + /* If it does exist, verify that it's an available CD-ROM */ + cdfd = open(drive, (O_RDONLY | O_EXCL | O_NONBLOCK), 0); + if (cdfd >= 0) { + p = Inquiry(cdfd); + if (*p == TYPE_ROM) + is_cd = 1; + close(cdfd); + } + return (is_cd); } /* Add a CD-ROM drive to our list of valid drives */ -static void AddDrive(char *drive, struct stat *stbuf) +static void +AddDrive(char *drive, struct stat *stbuf) { - int i; - - if ( SDL_numcds < MAX_DRIVES ) { - /* Check to make sure it's not already in our list. - This can happen when we see a drive via symbolic link. - */ - for ( i=0; ist_rdev == SDL_cdmode[i] ) { + int i; + + if (SDL_numcds < MAX_DRIVES) { + /* Check to make sure it's not already in our list. + This can happen when we see a drive via symbolic link. + */ + for (i = 0; i < SDL_numcds; ++i) { + if (stbuf->st_rdev == SDL_cdmode[i]) { #ifdef DEBUG_CDROM - fprintf(stderr, "Duplicate drive detected: %s == %s\n", drive, SDL_cdlist[i]); + fprintf(stderr, "Duplicate drive detected: %s == %s\n", + drive, SDL_cdlist[i]); #endif - return; - } - } - - /* Add this drive to our list */ - i = SDL_numcds; - SDL_cdlist[i] = SDL_strdup(drive); - if ( SDL_cdlist[i] == NULL ) { - SDL_OutOfMemory(); - return; - } - SDL_cdmode[i] = stbuf->st_rdev; - ++SDL_numcds; + return; + } + } + + /* Add this drive to our list */ + i = SDL_numcds; + SDL_cdlist[i] = SDL_strdup(drive); + if (SDL_cdlist[i] == NULL) { + SDL_OutOfMemory(); + return; + } + SDL_cdmode[i] = stbuf->st_rdev; + ++SDL_numcds; #ifdef DEBUG_CDROM - fprintf(stderr, "Added CD-ROM drive: %s\n", drive); + fprintf(stderr, "Added CD-ROM drive: %s\n", drive); #endif - } + } } -int SDL_SYS_CDInit(void) +int +SDL_SYS_CDInit(void) { - /* checklist: /dev/rsr?c */ - static char *checklist[] = { - "?0 rsr?", NULL - }; - char *SDLcdrom; - int i, j, exists; - char drive[32]; - struct stat stbuf; - - /* Fill in our driver capabilities */ - SDL_CDcaps.Name = SDL_SYS_CDName; - SDL_CDcaps.Open = SDL_SYS_CDOpen; - SDL_CDcaps.GetTOC = SDL_SYS_CDGetTOC; - SDL_CDcaps.Status = SDL_SYS_CDStatus; - SDL_CDcaps.Play = SDL_SYS_CDPlay; - SDL_CDcaps.Pause = SDL_SYS_CDPause; - SDL_CDcaps.Resume = SDL_SYS_CDResume; - SDL_CDcaps.Stop = SDL_SYS_CDStop; - SDL_CDcaps.Eject = SDL_SYS_CDEject; - SDL_CDcaps.Close = SDL_SYS_CDClose; - - /* Look in the environment for our CD-ROM drive list */ - SDLcdrom = SDL_getenv("SDL_CDROM"); /* ':' separated list of devices */ - if ( SDLcdrom != NULL ) { - char *cdpath, *delim; - size_t len = SDL_strlen(SDLcdrom)+1; - cdpath = SDL_stack_alloc(char, len); - if ( cdpath != NULL ) { - SDL_strlcpy(cdpath, SDLcdrom, len); - SDLcdrom = cdpath; - do { - delim = SDL_strchr(SDLcdrom, ':'); - if ( delim ) { - *delim++ = '\0'; - } - if ( CheckDrive(SDLcdrom, &stbuf) > 0 ) { - AddDrive(SDLcdrom, &stbuf); - } - if ( delim ) { - SDLcdrom = delim; - } else { - SDLcdrom = NULL; - } - } while ( SDLcdrom ); - SDL_stack_free(cdpath); - } - - /* If we found our drives, there's nothing left to do */ - if ( SDL_numcds > 0 ) { - return(0); - } - } - - /* Scan the system for CD-ROM drives */ - for ( i=0; checklist[i]; ++i ) { - if ( checklist[i][0] == '?' ) { - char *insert; - exists = 1; - for ( j=checklist[i][1]; exists; ++j ) { - SDL_snprintf(drive, SDL_arraysize(drive), "/dev/%sc", &checklist[i][3]); - insert = SDL_strchr(drive, '?'); - if ( insert != NULL ) { - *insert = j; - } - switch (CheckDrive(drive, &stbuf)) { - /* Drive exists and is a CD-ROM */ - case 1: - AddDrive(drive, &stbuf); - break; - /* Drive exists, but isn't a CD-ROM */ - case 0: - break; - /* Drive doesn't exist */ - case -1: - exists = 0; - break; - } - } - } else { - SDL_snprintf(drive, SDL_arraysize(drive), "/dev/%s", checklist[i]); - if ( CheckDrive(drive, &stbuf) > 0 ) { - AddDrive(drive, &stbuf); - } - } - } - return(0); + /* checklist: /dev/rsr?c */ + static char *checklist[] = { + "?0 rsr?", NULL + }; + char *SDLcdrom; + int i, j, exists; + char drive[32]; + struct stat stbuf; + + /* Fill in our driver capabilities */ + SDL_CDcaps.Name = SDL_SYS_CDName; + SDL_CDcaps.Open = SDL_SYS_CDOpen; + SDL_CDcaps.GetTOC = SDL_SYS_CDGetTOC; + SDL_CDcaps.Status = SDL_SYS_CDStatus; + SDL_CDcaps.Play = SDL_SYS_CDPlay; + SDL_CDcaps.Pause = SDL_SYS_CDPause; + SDL_CDcaps.Resume = SDL_SYS_CDResume; + SDL_CDcaps.Stop = SDL_SYS_CDStop; + SDL_CDcaps.Eject = SDL_SYS_CDEject; + SDL_CDcaps.Close = SDL_SYS_CDClose; + + /* Look in the environment for our CD-ROM drive list */ + SDLcdrom = SDL_getenv("SDL_CDROM"); /* ':' separated list of devices */ + if (SDLcdrom != NULL) { + char *cdpath, *delim; + size_t len = SDL_strlen(SDLcdrom) + 1; + cdpath = SDL_stack_alloc(char, len); + if (cdpath != NULL) { + SDL_strlcpy(cdpath, SDLcdrom, len); + SDLcdrom = cdpath; + do { + delim = SDL_strchr(SDLcdrom, ':'); + if (delim) { + *delim++ = '\0'; + } + if (CheckDrive(SDLcdrom, &stbuf) > 0) { + AddDrive(SDLcdrom, &stbuf); + } + if (delim) { + SDLcdrom = delim; + } else { + SDLcdrom = NULL; + } + } + while (SDLcdrom); + SDL_stack_free(cdpath); + } + + /* If we found our drives, there's nothing left to do */ + if (SDL_numcds > 0) { + return (0); + } + } + + /* Scan the system for CD-ROM drives */ + for (i = 0; checklist[i]; ++i) { + if (checklist[i][0] == '?') { + char *insert; + exists = 1; + for (j = checklist[i][1]; exists; ++j) { + SDL_snprintf(drive, SDL_arraysize(drive), "/dev/%sc", + &checklist[i][3]); + insert = SDL_strchr(drive, '?'); + if (insert != NULL) { + *insert = j; + } + switch (CheckDrive(drive, &stbuf)) { + /* Drive exists and is a CD-ROM */ + case 1: + AddDrive(drive, &stbuf); + break; + /* Drive exists, but isn't a CD-ROM */ + case 0: + break; + /* Drive doesn't exist */ + case -1: + exists = 0; + break; + } + } + } else { + SDL_snprintf(drive, SDL_arraysize(drive), "/dev/%s", + checklist[i]); + if (CheckDrive(drive, &stbuf) > 0) { + AddDrive(drive, &stbuf); + } + } + } + return (0); } -static const char *SDL_SYS_CDName(int drive) +static const char * +SDL_SYS_CDName(int drive) { - return(SDL_cdlist[drive]); + return (SDL_cdlist[drive]); } -static int SDL_SYS_CDOpen(int drive) +static int +SDL_SYS_CDOpen(int drive) { - return(open(SDL_cdlist[drive], O_RDONLY | O_NONBLOCK | O_EXCL, 0)); + return (open(SDL_cdlist[drive], O_RDONLY | O_NONBLOCK | O_EXCL, 0)); } -static int SDL_SYS_CDGetTOC(SDL_CD *cdrom) - { - u_char cdb[10], buf[4], *p, *toc; - struct scsi_user_cdb sus; - int i, sts, first_track, last_track, ntracks, toc_size; - - bzero(cdb, sizeof (cdb)); - cdb[0] = 0x43; /* Read TOC */ - cdb[1] = 0x2; /* MSF */ - cdb[8] = 4; /* size TOC header */ - sts = scsi_cmd(cdrom->id, (cdb_t *)cdb, 10, SUC_READ, buf, 4, &sus); - if (sts < 0) - return(-1); - first_track = buf[2]; - last_track = buf[3]; - ntracks = last_track - first_track + 1; - cdrom->numtracks = ntracks; - toc_size = 4 + (ntracks + 1) * 8; - toc = (u_char *)SDL_malloc(toc_size); - if (toc == NULL) - return(-1); - bzero(cdb, sizeof (cdb)); - cdb[0] = 0x43; - cdb[1] = 0x2; - cdb[6] = first_track; - cdb[7] = toc_size >> 8; - cdb[8] = toc_size & 0xff; - sts = scsi_cmd(cdrom->id, (cdb_t *)cdb, 10, SUC_READ, toc, toc_size, - &sus); - if (sts < 0) - { - SDL_free(toc); - return(-1); - } - - for (i = 0, p = toc+4; i <= ntracks; i++, p+= 8) - { - if (i == ntracks) - cdrom->track[i].id = 0xAA; /* Leadout */ - else - cdrom->track[i].id = first_track + i; - if (p[1] & 0x20) - cdrom->track[i].type = SDL_DATA_TRACK; - else - cdrom->track[i].type = SDL_AUDIO_TRACK; - cdrom->track[i].offset = msf_to_frame(p[5], p[6], p[7]); - cdrom->track[i].length = 0; - if (i > 0) - cdrom->track[i-1].length = cdrom->track[i].offset - - cdrom->track[i-1].offset; - } - SDL_free(toc); - return(0); - } +static int +SDL_SYS_CDGetTOC(SDL_CD * cdrom) +{ + u_char cdb[10], buf[4], *p, *toc; + struct scsi_user_cdb sus; + int i, sts, first_track, last_track, ntracks, toc_size; + + bzero(cdb, sizeof(cdb)); + cdb[0] = 0x43; /* Read TOC */ + cdb[1] = 0x2; /* MSF */ + cdb[8] = 4; /* size TOC header */ + sts = scsi_cmd(cdrom->id, (cdb_t *) cdb, 10, SUC_READ, buf, 4, &sus); + if (sts < 0) + return (-1); + first_track = buf[2]; + last_track = buf[3]; + ntracks = last_track - first_track + 1; + cdrom->numtracks = ntracks; + toc_size = 4 + (ntracks + 1) * 8; + toc = (u_char *) SDL_malloc(toc_size); + if (toc == NULL) + return (-1); + bzero(cdb, sizeof(cdb)); + cdb[0] = 0x43; + cdb[1] = 0x2; + cdb[6] = first_track; + cdb[7] = toc_size >> 8; + cdb[8] = toc_size & 0xff; + sts = scsi_cmd(cdrom->id, (cdb_t *) cdb, 10, SUC_READ, toc, toc_size, + &sus); + if (sts < 0) { + SDL_free(toc); + return (-1); + } + + for (i = 0, p = toc + 4; i <= ntracks; i++, p += 8) { + if (i == ntracks) + cdrom->track[i].id = 0xAA; /* Leadout */ + else + cdrom->track[i].id = first_track + i; + if (p[1] & 0x20) + cdrom->track[i].type = SDL_DATA_TRACK; + else + cdrom->track[i].type = SDL_AUDIO_TRACK; + cdrom->track[i].offset = msf_to_frame(p[5], p[6], p[7]); + cdrom->track[i].length = 0; + if (i > 0) + cdrom->track[i - 1].length = cdrom->track[i].offset - + cdrom->track[i - 1].offset; + } + SDL_free(toc); + return (0); +} /* Get CD-ROM status */ -static CDstatus SDL_SYS_CDStatus(SDL_CD *cdrom, int *position) - { - CDstatus status; - u_char cdb[10], buf[16]; - int sts; - struct scsi_user_cdb sus; - - bzero(cdb, sizeof (cdb)); - cdb[0] = 0x42; /* read subq */ - cdb[1] = 0x2; /* MSF */ - cdb[2] = 0x40; /* q channel */ - cdb[3] = 1; /* current pos */ - cdb[7] = sizeof (buf) >> 8; - cdb[8] = sizeof (buf) & 0xff; - sts = scsi_cmd(cdrom->id, (cdb_t *)cdb, 10, SUC_READ, buf, sizeof (buf), - &sus); - if (sts < 0) - return(-1); - if (sts) - { - if (TestForMedium(cdrom->id) == 0) - status = CD_TRAYEMPTY; - else - status = CD_ERROR; - } - else - { - switch (buf[1]) - { - case 0x11: - status = CD_PLAYING; - break; - case 0x12: - status = CD_PAUSED; - break; - case 0x13: - case 0x14: - case 0x15: - status = CD_STOPPED; - break; - default: - status = CD_ERROR; - break; - } - } - if (position) - { - if ( status == CD_PLAYING || (status == CD_PAUSED) ) - *position = msf_to_frame(buf[9], buf[10], buf[11]); - else - *position = 0; - } - return(status); - } +static CDstatus +SDL_SYS_CDStatus(SDL_CD * cdrom, int *position) +{ + CDstatus status; + u_char cdb[10], buf[16]; + int sts; + struct scsi_user_cdb sus; + + bzero(cdb, sizeof(cdb)); + cdb[0] = 0x42; /* read subq */ + cdb[1] = 0x2; /* MSF */ + cdb[2] = 0x40; /* q channel */ + cdb[3] = 1; /* current pos */ + cdb[7] = sizeof(buf) >> 8; + cdb[8] = sizeof(buf) & 0xff; + sts = scsi_cmd(cdrom->id, (cdb_t *) cdb, 10, SUC_READ, buf, sizeof(buf), + &sus); + if (sts < 0) + return (-1); + if (sts) { + if (TestForMedium(cdrom->id) == 0) + status = CD_TRAYEMPTY; + else + status = CD_ERROR; + } else { + switch (buf[1]) { + case 0x11: + status = CD_PLAYING; + break; + case 0x12: + status = CD_PAUSED; + break; + case 0x13: + case 0x14: + case 0x15: + status = CD_STOPPED; + break; + default: + status = CD_ERROR; + break; + } + } + if (position) { + if (status == CD_PLAYING || (status == CD_PAUSED)) + *position = msf_to_frame(buf[9], buf[10], buf[11]); + else + *position = 0; + } + return (status); +} /* Start play */ -static int SDL_SYS_CDPlay(SDL_CD *cdrom, int start, int length) - { - u_char cdb[10]; - int sts, minute, second, frame, eminute, esecond, eframe; - struct scsi_user_cdb sus; - - bzero(cdb, sizeof(cdb)); - cdb[0] = 0x47; /* Play */ - frame_to_msf(start, &minute, &second, &frame); - frame_to_msf(start + length, &eminute, &esecond, &eframe); - cdb[3] = minute; - cdb[4] = second; - cdb[5] = frame; - cdb[6] = eminute; - cdb[7] = esecond; - cdb[8] = eframe; - sts = scsi_cmd(cdrom->id, (cdb_t *)cdb, 10, SUC_READ, 0, 0, &sus); - return(sts); - } - -static int -pauseresume(SDL_CD *cdrom, int flag) - { - u_char cdb[10]; - struct scsi_user_cdb sus; - - bzero(cdb, sizeof (cdb)); - cdb[0] = 0x4b; - cdb[8] = flag & 0x1; - return(scsi_cmd(cdrom->id, (cdb_t *)cdb, 10, SUC_READ, 0, 0, &sus)); - } +static int +SDL_SYS_CDPlay(SDL_CD * cdrom, int start, int length) +{ + u_char cdb[10]; + int sts, minute, second, frame, eminute, esecond, eframe; + struct scsi_user_cdb sus; + + bzero(cdb, sizeof(cdb)); + cdb[0] = 0x47; /* Play */ + frame_to_msf(start, &minute, &second, &frame); + frame_to_msf(start + length, &eminute, &esecond, &eframe); + cdb[3] = minute; + cdb[4] = second; + cdb[5] = frame; + cdb[6] = eminute; + cdb[7] = esecond; + cdb[8] = eframe; + sts = scsi_cmd(cdrom->id, (cdb_t *) cdb, 10, SUC_READ, 0, 0, &sus); + return (sts); +} + +static int +pauseresume(SDL_CD * cdrom, int flag) +{ + u_char cdb[10]; + struct scsi_user_cdb sus; + + bzero(cdb, sizeof(cdb)); + cdb[0] = 0x4b; + cdb[8] = flag & 0x1; + return (scsi_cmd(cdrom->id, (cdb_t *) cdb, 10, SUC_READ, 0, 0, &sus)); +} /* Pause play */ -static int SDL_SYS_CDPause(SDL_CD *cdrom) +static int +SDL_SYS_CDPause(SDL_CD * cdrom) { - return(pauseresume(cdrom, 0)); + return (pauseresume(cdrom, 0)); } /* Resume play */ -static int SDL_SYS_CDResume(SDL_CD *cdrom) +static int +SDL_SYS_CDResume(SDL_CD * cdrom) { - return(pauseresume(cdrom, 1)); + return (pauseresume(cdrom, 1)); } /* Stop play */ -static int SDL_SYS_CDStop(SDL_CD *cdrom) +static int +SDL_SYS_CDStop(SDL_CD * cdrom) { - u_char cdb[6]; - struct scsi_user_cdb sus; + u_char cdb[6]; + struct scsi_user_cdb sus; - bzero(cdb, sizeof (cdb)); - cdb[0] = 0x1b; /* stop */ - cdb[1] = 1; /* immediate */ - return(scsi_cmd(cdrom->id, (cdb_t *)cdb, 6, SUC_READ, 0, 0, &sus)); + bzero(cdb, sizeof(cdb)); + cdb[0] = 0x1b; /* stop */ + cdb[1] = 1; /* immediate */ + return (scsi_cmd(cdrom->id, (cdb_t *) cdb, 6, SUC_READ, 0, 0, &sus)); } /* Eject the CD-ROM */ -static int SDL_SYS_CDEject(SDL_CD *cdrom) +static int +SDL_SYS_CDEject(SDL_CD * cdrom) { - u_char cdb[6]; - struct scsi_user_cdb sus; - - bzero(cdb, sizeof (cdb)); - cdb[0] = 0x1b; /* stop */ - cdb[1] = 1; /* immediate */ - cdb[4] = 2; /* eject */ - return(scsi_cmd(cdrom->id, (cdb_t *)cdb, 6, SUC_READ, 0, 0, &sus)); + u_char cdb[6]; + struct scsi_user_cdb sus; + + bzero(cdb, sizeof(cdb)); + cdb[0] = 0x1b; /* stop */ + cdb[1] = 1; /* immediate */ + cdb[4] = 2; /* eject */ + return (scsi_cmd(cdrom->id, (cdb_t *) cdb, 6, SUC_READ, 0, 0, &sus)); } /* Close the CD-ROM handle */ -static void SDL_SYS_CDClose(SDL_CD *cdrom) - { - close(cdrom->id); - } +static void +SDL_SYS_CDClose(SDL_CD * cdrom) +{ + close(cdrom->id); +} -void SDL_SYS_CDQuit(void) +void +SDL_SYS_CDQuit(void) { - int i; - - if ( SDL_numcds > 0 ) { - for ( i=0; i 0) { + for (i = 0; i < SDL_numcds; ++i) { + SDL_free(SDL_cdlist[i]); + } + } + SDL_numcds = 0; } #endif /* SDL_CDROM_BSDI */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/cdrom/dc/SDL_syscdrom.c b/src/cdrom/dc/SDL_syscdrom.c index d89e08968..16a225eb8 100644 --- a/src/cdrom/dc/SDL_syscdrom.c +++ b/src/cdrom/dc/SDL_syscdrom.c @@ -34,134 +34,154 @@ /* The system-dependent CD control functions */ static const char *SDL_SYS_CDName(int drive); static int SDL_SYS_CDOpen(int drive); -static int SDL_SYS_CDGetTOC(SDL_CD *cdrom); -static CDstatus SDL_SYS_CDStatus(SDL_CD *cdrom, int *position); -static int SDL_SYS_CDPlay(SDL_CD *cdrom, int start, int length); -static int SDL_SYS_CDPause(SDL_CD *cdrom); -static int SDL_SYS_CDResume(SDL_CD *cdrom); -static int SDL_SYS_CDStop(SDL_CD *cdrom); -static int SDL_SYS_CDEject(SDL_CD *cdrom); -static void SDL_SYS_CDClose(SDL_CD *cdrom); - - -int SDL_SYS_CDInit(void) +static int SDL_SYS_CDGetTOC(SDL_CD * cdrom); +static CDstatus SDL_SYS_CDStatus(SDL_CD * cdrom, int *position); +static int SDL_SYS_CDPlay(SDL_CD * cdrom, int start, int length); +static int SDL_SYS_CDPause(SDL_CD * cdrom); +static int SDL_SYS_CDResume(SDL_CD * cdrom); +static int SDL_SYS_CDStop(SDL_CD * cdrom); +static int SDL_SYS_CDEject(SDL_CD * cdrom); +static void SDL_SYS_CDClose(SDL_CD * cdrom); + + +int +SDL_SYS_CDInit(void) { - /* Fill in our driver capabilities */ - SDL_CDcaps.Name = SDL_SYS_CDName; - SDL_CDcaps.Open = SDL_SYS_CDOpen; - SDL_CDcaps.GetTOC = SDL_SYS_CDGetTOC; - SDL_CDcaps.Status = SDL_SYS_CDStatus; - SDL_CDcaps.Play = SDL_SYS_CDPlay; - SDL_CDcaps.Pause = SDL_SYS_CDPause; - SDL_CDcaps.Resume = SDL_SYS_CDResume; - SDL_CDcaps.Stop = SDL_SYS_CDStop; - SDL_CDcaps.Eject = SDL_SYS_CDEject; - SDL_CDcaps.Close = SDL_SYS_CDClose; - - return(0); + /* Fill in our driver capabilities */ + SDL_CDcaps.Name = SDL_SYS_CDName; + SDL_CDcaps.Open = SDL_SYS_CDOpen; + SDL_CDcaps.GetTOC = SDL_SYS_CDGetTOC; + SDL_CDcaps.Status = SDL_SYS_CDStatus; + SDL_CDcaps.Play = SDL_SYS_CDPlay; + SDL_CDcaps.Pause = SDL_SYS_CDPause; + SDL_CDcaps.Resume = SDL_SYS_CDResume; + SDL_CDcaps.Stop = SDL_SYS_CDStop; + SDL_CDcaps.Eject = SDL_SYS_CDEject; + SDL_CDcaps.Close = SDL_SYS_CDClose; + + return (0); } -static const char *SDL_SYS_CDName(int drive) +static const char * +SDL_SYS_CDName(int drive) { - return "/cd"; + return "/cd"; } -static int SDL_SYS_CDOpen(int drive) +static int +SDL_SYS_CDOpen(int drive) { - return(drive); + return (drive); } #define TRACK_CDDA 0 -static int SDL_SYS_CDGetTOC(SDL_CD *cdrom) +static int +SDL_SYS_CDGetTOC(SDL_CD * cdrom) { - CDROM_TOC toc; - int ret,i; - - ret = cdrom_read_toc(&toc,0); - if (ret!=ERR_OK) { - return -1; - } - - cdrom->numtracks = TOC_TRACK(toc.last)-TOC_TRACK(toc.first)+1; - for(i=0;inumtracks;i++) { - unsigned long entry = toc.entry[i]; - cdrom->track[i].id = i+1; - cdrom->track[i].type = (TOC_CTRL(toc.entry[i])==TRACK_CDDA)?SDL_AUDIO_TRACK:SDL_DATA_TRACK; - cdrom->track[i].offset = TOC_LBA(entry)-150; - cdrom->track[i].length = TOC_LBA((i+1numtracks = TOC_TRACK(toc.last) - TOC_TRACK(toc.first) + 1; + for (i = 0; i < cdrom->numtracks; i++) { + unsigned long entry = toc.entry[i]; + cdrom->track[i].id = i + 1; + cdrom->track[i].type = + (TOC_CTRL(toc.entry[i]) == + TRACK_CDDA) ? SDL_AUDIO_TRACK : SDL_DATA_TRACK; + cdrom->track[i].offset = TOC_LBA(entry) - 150; + cdrom->track[i].length = + TOC_LBA((i + 1 < + toc.last) ? toc.entry[i + 1] : toc.leadout_sector) - + TOC_LBA(entry); + } + + return 0; } /* Get CD-ROM status */ -static CDstatus SDL_SYS_CDStatus(SDL_CD *cdrom, int *position) +static CDstatus +SDL_SYS_CDStatus(SDL_CD * cdrom, int *position) { - int ret,dc_status,disc_type; - - ret = cdrom_get_status(&dc_status,&disc_type); - if (ret!=ERR_OK) return CD_ERROR; - - switch(dc_status) { -// case CD_STATUS_BUSY: - case CD_STATUS_PAUSED: - return CD_PAUSED; - case CD_STATUS_STANDBY: - return CD_STOPPED; - case CD_STATUS_PLAYING: - return CD_PLAYING; -// case CD_STATUS_SEEKING: -// case CD_STATUS_SCANING: - case CD_STATUS_OPEN: - case CD_STATUS_NO_DISC: - return CD_TRAYEMPTY; - default: - return CD_ERROR; - } + int ret, dc_status, disc_type; + + ret = cdrom_get_status(&dc_status, &disc_type); + if (ret != ERR_OK) + return CD_ERROR; + + switch (dc_status) { +// case CD_STATUS_BUSY: + case CD_STATUS_PAUSED: + return CD_PAUSED; + case CD_STATUS_STANDBY: + return CD_STOPPED; + case CD_STATUS_PLAYING: + return CD_PLAYING; +// case CD_STATUS_SEEKING: +// case CD_STATUS_SCANING: + case CD_STATUS_OPEN: + case CD_STATUS_NO_DISC: + return CD_TRAYEMPTY; + default: + return CD_ERROR; + } } /* Start play */ -static int SDL_SYS_CDPlay(SDL_CD *cdrom, int start, int length) +static int +SDL_SYS_CDPlay(SDL_CD * cdrom, int start, int length) { - int ret = cdrom_cdda_play(start-150,start-150+length,1,CDDA_SECTORS); - return ret==ERR_OK?0:-1; + int ret = + cdrom_cdda_play(start - 150, start - 150 + length, 1, CDDA_SECTORS); + return ret == ERR_OK ? 0 : -1; } /* Pause play */ -static int SDL_SYS_CDPause(SDL_CD *cdrom) +static int +SDL_SYS_CDPause(SDL_CD * cdrom) { - int ret=cdrom_cdda_pause(); - return ret==ERR_OK?0:-1; + int ret = cdrom_cdda_pause(); + return ret == ERR_OK ? 0 : -1; } /* Resume play */ -static int SDL_SYS_CDResume(SDL_CD *cdrom) +static int +SDL_SYS_CDResume(SDL_CD * cdrom) { - int ret=cdrom_cdda_resume(); - return ret==ERR_OK?0:-1; + int ret = cdrom_cdda_resume(); + return ret == ERR_OK ? 0 : -1; } /* Stop play */ -static int SDL_SYS_CDStop(SDL_CD *cdrom) +static int +SDL_SYS_CDStop(SDL_CD * cdrom) { - int ret=cdrom_spin_down(); - return ret==ERR_OK?0:-1; + int ret = cdrom_spin_down(); + return ret == ERR_OK ? 0 : -1; } /* Eject the CD-ROM */ -static int SDL_SYS_CDEject(SDL_CD *cdrom) +static int +SDL_SYS_CDEject(SDL_CD * cdrom) { - return -1; + return -1; } /* Close the CD-ROM handle */ -static void SDL_SYS_CDClose(SDL_CD *cdrom) +static void +SDL_SYS_CDClose(SDL_CD * cdrom) { } -void SDL_SYS_CDQuit(void) +void +SDL_SYS_CDQuit(void) { } #endif /* SDL_CDROM_DC */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/cdrom/dummy/SDL_syscdrom.c b/src/cdrom/dummy/SDL_syscdrom.c index 4a99303cc..f8e4bc0a6 100644 --- a/src/cdrom/dummy/SDL_syscdrom.c +++ b/src/cdrom/dummy/SDL_syscdrom.c @@ -28,14 +28,17 @@ #include "SDL_cdrom.h" #include "../SDL_syscdrom.h" -int SDL_SYS_CDInit(void) +int +SDL_SYS_CDInit(void) { - return(0); + return (0); } -void SDL_SYS_CDQuit(void) +void +SDL_SYS_CDQuit(void) { - return; + return; } #endif /* SDL_CDROM_DUMMY || SDL_CDROM_DISABLED */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/cdrom/freebsd/SDL_syscdrom.c b/src/cdrom/freebsd/SDL_syscdrom.c index 30b5c907e..21e239209 100644 --- a/src/cdrom/freebsd/SDL_syscdrom.c +++ b/src/cdrom/freebsd/SDL_syscdrom.c @@ -37,7 +37,7 @@ /* The maximum number of CD-ROM drives we'll detect */ -#define MAX_DRIVES 16 +#define MAX_DRIVES 16 /* A list of available CD-ROM drives */ static char *SDL_cdlist[MAX_DRIVES]; @@ -46,361 +46,378 @@ static dev_t SDL_cdmode[MAX_DRIVES]; /* The system-dependent CD control functions */ static const char *SDL_SYS_CDName(int drive); static int SDL_SYS_CDOpen(int drive); -static int SDL_SYS_CDGetTOC(SDL_CD *cdrom); -static CDstatus SDL_SYS_CDStatus(SDL_CD *cdrom, int *position); -static int SDL_SYS_CDPlay(SDL_CD *cdrom, int start, int length); -static int SDL_SYS_CDPause(SDL_CD *cdrom); -static int SDL_SYS_CDResume(SDL_CD *cdrom); -static int SDL_SYS_CDStop(SDL_CD *cdrom); -static int SDL_SYS_CDEject(SDL_CD *cdrom); -static void SDL_SYS_CDClose(SDL_CD *cdrom); +static int SDL_SYS_CDGetTOC(SDL_CD * cdrom); +static CDstatus SDL_SYS_CDStatus(SDL_CD * cdrom, int *position); +static int SDL_SYS_CDPlay(SDL_CD * cdrom, int start, int length); +static int SDL_SYS_CDPause(SDL_CD * cdrom); +static int SDL_SYS_CDResume(SDL_CD * cdrom); +static int SDL_SYS_CDStop(SDL_CD * cdrom); +static int SDL_SYS_CDEject(SDL_CD * cdrom); +static void SDL_SYS_CDClose(SDL_CD * cdrom); /* Some ioctl() errno values which occur when the tray is empty */ #define ERRNO_TRAYEMPTY(errno) \ ((errno == EIO) || (errno == ENOENT) || (errno == EINVAL)) /* Check a drive to see if it is a CD-ROM */ -static int CheckDrive(char *drive, struct stat *stbuf) +static int +CheckDrive(char *drive, struct stat *stbuf) { - int is_cd, cdfd; - struct ioc_read_subchannel info; - - /* If it doesn't exist, return -1 */ - if ( stat(drive, stbuf) < 0 ) { - return(-1); - } - - /* If it does exist, verify that it's an available CD-ROM */ - is_cd = 0; - if ( S_ISCHR(stbuf->st_mode) || S_ISBLK(stbuf->st_mode) ) { - cdfd = open(drive, (O_RDONLY|O_EXCL|O_NONBLOCK), 0); - if ( cdfd >= 0 ) { - info.address_format = CD_MSF_FORMAT; - info.data_format = CD_CURRENT_POSITION; - info.data_len = 0; - info.data = NULL; - /* Under Linux, EIO occurs when a disk is not present. - This isn't 100% reliable, so we use the USE_MNTENT - code above instead. - */ - if ( (ioctl(cdfd, CDIOCREADSUBCHANNEL, &info) == 0) || - ERRNO_TRAYEMPTY(errno) ) { - is_cd = 1; - } - close(cdfd); - } - } - return(is_cd); + int is_cd, cdfd; + struct ioc_read_subchannel info; + + /* If it doesn't exist, return -1 */ + if (stat(drive, stbuf) < 0) { + return (-1); + } + + /* If it does exist, verify that it's an available CD-ROM */ + is_cd = 0; + if (S_ISCHR(stbuf->st_mode) || S_ISBLK(stbuf->st_mode)) { + cdfd = open(drive, (O_RDONLY | O_EXCL | O_NONBLOCK), 0); + if (cdfd >= 0) { + info.address_format = CD_MSF_FORMAT; + info.data_format = CD_CURRENT_POSITION; + info.data_len = 0; + info.data = NULL; + /* Under Linux, EIO occurs when a disk is not present. + This isn't 100% reliable, so we use the USE_MNTENT + code above instead. + */ + if ((ioctl(cdfd, CDIOCREADSUBCHANNEL, &info) == 0) || + ERRNO_TRAYEMPTY(errno)) { + is_cd = 1; + } + close(cdfd); + } + } + return (is_cd); } /* Add a CD-ROM drive to our list of valid drives */ -static void AddDrive(char *drive, struct stat *stbuf) +static void +AddDrive(char *drive, struct stat *stbuf) { - int i; - - if ( SDL_numcds < MAX_DRIVES ) { - /* Check to make sure it's not already in our list. - This can happen when we see a drive via symbolic link. - */ - for ( i=0; ist_rdev == SDL_cdmode[i] ) { + int i; + + if (SDL_numcds < MAX_DRIVES) { + /* Check to make sure it's not already in our list. + This can happen when we see a drive via symbolic link. + */ + for (i = 0; i < SDL_numcds; ++i) { + if (stbuf->st_rdev == SDL_cdmode[i]) { #ifdef DEBUG_CDROM - fprintf(stderr, "Duplicate drive detected: %s == %s\n", drive, SDL_cdlist[i]); + fprintf(stderr, "Duplicate drive detected: %s == %s\n", + drive, SDL_cdlist[i]); #endif - return; - } - } - - /* Add this drive to our list */ - i = SDL_numcds; - SDL_cdlist[i] = SDL_strdup(drive); - if ( SDL_cdlist[i] == NULL ) { - SDL_OutOfMemory(); - return; - } - SDL_cdmode[i] = stbuf->st_rdev; - ++SDL_numcds; + return; + } + } + + /* Add this drive to our list */ + i = SDL_numcds; + SDL_cdlist[i] = SDL_strdup(drive); + if (SDL_cdlist[i] == NULL) { + SDL_OutOfMemory(); + return; + } + SDL_cdmode[i] = stbuf->st_rdev; + ++SDL_numcds; #ifdef DEBUG_CDROM - fprintf(stderr, "Added CD-ROM drive: %s\n", drive); + fprintf(stderr, "Added CD-ROM drive: %s\n", drive); #endif - } + } } -int SDL_SYS_CDInit(void) +int +SDL_SYS_CDInit(void) { - /* checklist: /dev/cdrom,/dev/cd?c /dev/acd?c - /dev/matcd?c /dev/mcd?c /dev/scd?c */ - static char *checklist[] = { - "cdrom", "?0 cd?", "?0 acd?", "?0 matcd?", "?0 mcd?", "?0 scd?",NULL - }; - char *SDLcdrom; - int i, j, exists; - char drive[32]; - struct stat stbuf; - - /* Fill in our driver capabilities */ - SDL_CDcaps.Name = SDL_SYS_CDName; - SDL_CDcaps.Open = SDL_SYS_CDOpen; - SDL_CDcaps.GetTOC = SDL_SYS_CDGetTOC; - SDL_CDcaps.Status = SDL_SYS_CDStatus; - SDL_CDcaps.Play = SDL_SYS_CDPlay; - SDL_CDcaps.Pause = SDL_SYS_CDPause; - SDL_CDcaps.Resume = SDL_SYS_CDResume; - SDL_CDcaps.Stop = SDL_SYS_CDStop; - SDL_CDcaps.Eject = SDL_SYS_CDEject; - SDL_CDcaps.Close = SDL_SYS_CDClose; - - /* Look in the environment for our CD-ROM drive list */ - SDLcdrom = SDL_getenv("SDL_CDROM"); /* ':' separated list of devices */ - if ( SDLcdrom != NULL ) { - char *cdpath, *delim; - size_t len = SDL_strlen(SDLcdrom)+1; - cdpath = SDL_stack_alloc(char, len); - if ( cdpath != NULL ) { - SDL_strlcpy(cdpath, SDLcdrom, len); - SDLcdrom = cdpath; - do { - delim = SDL_strchr(SDLcdrom, ':'); - if ( delim ) { - *delim++ = '\0'; - } - if ( CheckDrive(SDLcdrom, &stbuf) > 0 ) { - AddDrive(SDLcdrom, &stbuf); - } - if ( delim ) { - SDLcdrom = delim; - } else { - SDLcdrom = NULL; - } - } while ( SDLcdrom ); - SDL_stack_free(cdpath); - } - - /* If we found our drives, there's nothing left to do */ - if ( SDL_numcds > 0 ) { - return(0); - } - } - - /* Scan the system for CD-ROM drives */ - for ( i=0; checklist[i]; ++i ) { - if ( checklist[i][0] == '?' ) { - char *insert; - exists = 1; - for ( j=checklist[i][1]; exists; ++j ) { - SDL_snprintf(drive, SDL_arraysize(drive), "/dev/%sc", &checklist[i][3]); - insert = SDL_strchr(drive, '?'); - if ( insert != NULL ) { - *insert = j; - } - switch (CheckDrive(drive, &stbuf)) { - /* Drive exists and is a CD-ROM */ - case 1: - AddDrive(drive, &stbuf); - break; - /* Drive exists, but isn't a CD-ROM */ - case 0: - break; - /* Drive doesn't exist */ - case -1: - exists = 0; - break; - } - } - } else { - SDL_snprintf(drive, SDL_arraysize(drive), "/dev/%s", checklist[i]); - if ( CheckDrive(drive, &stbuf) > 0 ) { - AddDrive(drive, &stbuf); - } - } - } - return(0); + /* checklist: /dev/cdrom,/dev/cd?c /dev/acd?c + /dev/matcd?c /dev/mcd?c /dev/scd?c */ + static char *checklist[] = { + "cdrom", "?0 cd?", "?0 acd?", "?0 matcd?", "?0 mcd?", "?0 scd?", NULL + }; + char *SDLcdrom; + int i, j, exists; + char drive[32]; + struct stat stbuf; + + /* Fill in our driver capabilities */ + SDL_CDcaps.Name = SDL_SYS_CDName; + SDL_CDcaps.Open = SDL_SYS_CDOpen; + SDL_CDcaps.GetTOC = SDL_SYS_CDGetTOC; + SDL_CDcaps.Status = SDL_SYS_CDStatus; + SDL_CDcaps.Play = SDL_SYS_CDPlay; + SDL_CDcaps.Pause = SDL_SYS_CDPause; + SDL_CDcaps.Resume = SDL_SYS_CDResume; + SDL_CDcaps.Stop = SDL_SYS_CDStop; + SDL_CDcaps.Eject = SDL_SYS_CDEject; + SDL_CDcaps.Close = SDL_SYS_CDClose; + + /* Look in the environment for our CD-ROM drive list */ + SDLcdrom = SDL_getenv("SDL_CDROM"); /* ':' separated list of devices */ + if (SDLcdrom != NULL) { + char *cdpath, *delim; + size_t len = SDL_strlen(SDLcdrom) + 1; + cdpath = SDL_stack_alloc(char, len); + if (cdpath != NULL) { + SDL_strlcpy(cdpath, SDLcdrom, len); + SDLcdrom = cdpath; + do { + delim = SDL_strchr(SDLcdrom, ':'); + if (delim) { + *delim++ = '\0'; + } + if (CheckDrive(SDLcdrom, &stbuf) > 0) { + AddDrive(SDLcdrom, &stbuf); + } + if (delim) { + SDLcdrom = delim; + } else { + SDLcdrom = NULL; + } + } + while (SDLcdrom); + SDL_stack_free(cdpath); + } + + /* If we found our drives, there's nothing left to do */ + if (SDL_numcds > 0) { + return (0); + } + } + + /* Scan the system for CD-ROM drives */ + for (i = 0; checklist[i]; ++i) { + if (checklist[i][0] == '?') { + char *insert; + exists = 1; + for (j = checklist[i][1]; exists; ++j) { + SDL_snprintf(drive, SDL_arraysize(drive), "/dev/%sc", + &checklist[i][3]); + insert = SDL_strchr(drive, '?'); + if (insert != NULL) { + *insert = j; + } + switch (CheckDrive(drive, &stbuf)) { + /* Drive exists and is a CD-ROM */ + case 1: + AddDrive(drive, &stbuf); + break; + /* Drive exists, but isn't a CD-ROM */ + case 0: + break; + /* Drive doesn't exist */ + case -1: + exists = 0; + break; + } + } + } else { + SDL_snprintf(drive, SDL_arraysize(drive), "/dev/%s", + checklist[i]); + if (CheckDrive(drive, &stbuf) > 0) { + AddDrive(drive, &stbuf); + } + } + } + return (0); } /* General ioctl() CD-ROM command function */ -static int SDL_SYS_CDioctl(int id, int command, void *arg) +static int +SDL_SYS_CDioctl(int id, int command, void *arg) { - int retval; + int retval; - retval = ioctl(id, command, arg); - if ( retval < 0 ) { - SDL_SetError("ioctl() error: %s", strerror(errno)); - } - return(retval); + retval = ioctl(id, command, arg); + if (retval < 0) { + SDL_SetError("ioctl() error: %s", strerror(errno)); + } + return (retval); } -static const char *SDL_SYS_CDName(int drive) +static const char * +SDL_SYS_CDName(int drive) { - return(SDL_cdlist[drive]); + return (SDL_cdlist[drive]); } -static int SDL_SYS_CDOpen(int drive) +static int +SDL_SYS_CDOpen(int drive) { - return(open(SDL_cdlist[drive], (O_RDONLY|O_EXCL|O_NONBLOCK), 0)); + return (open(SDL_cdlist[drive], (O_RDONLY | O_EXCL | O_NONBLOCK), 0)); } -static int SDL_SYS_CDGetTOC(SDL_CD *cdrom) +static int +SDL_SYS_CDGetTOC(SDL_CD * cdrom) { - struct ioc_toc_header toc; - int i, okay; - struct ioc_read_toc_entry entry; - struct cd_toc_entry data; - - okay = 0; - if ( SDL_SYS_CDioctl(cdrom->id, CDIOREADTOCHEADER, &toc) == 0 ) { - cdrom->numtracks = toc.ending_track-toc.starting_track+1; - if ( cdrom->numtracks > SDL_MAX_TRACKS ) { - cdrom->numtracks = SDL_MAX_TRACKS; - } - /* Read all the track TOC entries */ - for ( i=0; i<=cdrom->numtracks; ++i ) { - if ( i == cdrom->numtracks ) { - cdrom->track[i].id = 0xAA; /* CDROM_LEADOUT */ - } else { - cdrom->track[i].id = toc.starting_track+i; - } - entry.starting_track = cdrom->track[i].id; - entry.address_format = CD_MSF_FORMAT; - entry.data_len = sizeof(data); - entry.data = &data; - if ( SDL_SYS_CDioctl(cdrom->id, CDIOREADTOCENTRYS, - &entry) < 0 ) { - break; - } else { - cdrom->track[i].type = data.control; - cdrom->track[i].offset = MSF_TO_FRAMES( - data.addr.msf.minute, - data.addr.msf.second, - data.addr.msf.frame); - cdrom->track[i].length = 0; - if ( i > 0 ) { - cdrom->track[i-1].length = - cdrom->track[i].offset- - cdrom->track[i-1].offset; - } - } - } - if ( i == (cdrom->numtracks+1) ) { - okay = 1; - } - } - return(okay ? 0 : -1); + struct ioc_toc_header toc; + int i, okay; + struct ioc_read_toc_entry entry; + struct cd_toc_entry data; + + okay = 0; + if (SDL_SYS_CDioctl(cdrom->id, CDIOREADTOCHEADER, &toc) == 0) { + cdrom->numtracks = toc.ending_track - toc.starting_track + 1; + if (cdrom->numtracks > SDL_MAX_TRACKS) { + cdrom->numtracks = SDL_MAX_TRACKS; + } + /* Read all the track TOC entries */ + for (i = 0; i <= cdrom->numtracks; ++i) { + if (i == cdrom->numtracks) { + cdrom->track[i].id = 0xAA; /* CDROM_LEADOUT */ + } else { + cdrom->track[i].id = toc.starting_track + i; + } + entry.starting_track = cdrom->track[i].id; + entry.address_format = CD_MSF_FORMAT; + entry.data_len = sizeof(data); + entry.data = &data; + if (SDL_SYS_CDioctl(cdrom->id, CDIOREADTOCENTRYS, &entry) < 0) { + break; + } else { + cdrom->track[i].type = data.control; + cdrom->track[i].offset = + MSF_TO_FRAMES(data.addr.msf.minute, + data.addr.msf.second, data.addr.msf.frame); + cdrom->track[i].length = 0; + if (i > 0) { + cdrom->track[i - 1].length = + cdrom->track[i].offset - cdrom->track[i - 1].offset; + } + } + } + if (i == (cdrom->numtracks + 1)) { + okay = 1; + } + } + return (okay ? 0 : -1); } /* Get CD-ROM status */ -static CDstatus SDL_SYS_CDStatus(SDL_CD *cdrom, int *position) +static CDstatus +SDL_SYS_CDStatus(SDL_CD * cdrom, int *position) { - CDstatus status; - struct ioc_toc_header toc; - struct ioc_read_subchannel info; - struct cd_sub_channel_info data; - - info.address_format = CD_MSF_FORMAT; - info.data_format = CD_CURRENT_POSITION; - info.track = 0; - info.data_len = sizeof(data); - info.data = &data; - if ( ioctl(cdrom->id, CDIOCREADSUBCHANNEL, &info) < 0 ) { - if ( ERRNO_TRAYEMPTY(errno) ) { - status = CD_TRAYEMPTY; - } else { - status = CD_ERROR; - } - } else { - switch (data.header.audio_status) { - case CD_AS_AUDIO_INVALID: - case CD_AS_NO_STATUS: - /* Try to determine if there's a CD available */ - if (ioctl(cdrom->id,CDIOREADTOCHEADER,&toc)==0) - status = CD_STOPPED; - else - status = CD_TRAYEMPTY; - break; - case CD_AS_PLAY_COMPLETED: - status = CD_STOPPED; - break; - case CD_AS_PLAY_IN_PROGRESS: - status = CD_PLAYING; - break; - case CD_AS_PLAY_PAUSED: - status = CD_PAUSED; - break; - default: - status = CD_ERROR; - break; - } - } - if ( position ) { - if ( status == CD_PLAYING || (status == CD_PAUSED) ) { - *position = MSF_TO_FRAMES( - data.what.position.absaddr.msf.minute, - data.what.position.absaddr.msf.second, - data.what.position.absaddr.msf.frame); - } else { - *position = 0; - } - } - return(status); + CDstatus status; + struct ioc_toc_header toc; + struct ioc_read_subchannel info; + struct cd_sub_channel_info data; + + info.address_format = CD_MSF_FORMAT; + info.data_format = CD_CURRENT_POSITION; + info.track = 0; + info.data_len = sizeof(data); + info.data = &data; + if (ioctl(cdrom->id, CDIOCREADSUBCHANNEL, &info) < 0) { + if (ERRNO_TRAYEMPTY(errno)) { + status = CD_TRAYEMPTY; + } else { + status = CD_ERROR; + } + } else { + switch (data.header.audio_status) { + case CD_AS_AUDIO_INVALID: + case CD_AS_NO_STATUS: + /* Try to determine if there's a CD available */ + if (ioctl(cdrom->id, CDIOREADTOCHEADER, &toc) == 0) + status = CD_STOPPED; + else + status = CD_TRAYEMPTY; + break; + case CD_AS_PLAY_COMPLETED: + status = CD_STOPPED; + break; + case CD_AS_PLAY_IN_PROGRESS: + status = CD_PLAYING; + break; + case CD_AS_PLAY_PAUSED: + status = CD_PAUSED; + break; + default: + status = CD_ERROR; + break; + } + } + if (position) { + if (status == CD_PLAYING || (status == CD_PAUSED)) { + *position = + MSF_TO_FRAMES(data.what.position.absaddr.msf.minute, + data.what.position.absaddr.msf.second, + data.what.position.absaddr.msf.frame); + } else { + *position = 0; + } + } + return (status); } /* Start play */ -static int SDL_SYS_CDPlay(SDL_CD *cdrom, int start, int length) +static int +SDL_SYS_CDPlay(SDL_CD * cdrom, int start, int length) { - struct ioc_play_msf playtime; + struct ioc_play_msf playtime; - FRAMES_TO_MSF(start, - &playtime.start_m, &playtime.start_s, &playtime.start_f); - FRAMES_TO_MSF(start+length, - &playtime.end_m, &playtime.end_s, &playtime.end_f); + FRAMES_TO_MSF(start, + &playtime.start_m, &playtime.start_s, &playtime.start_f); + FRAMES_TO_MSF(start + length, + &playtime.end_m, &playtime.end_s, &playtime.end_f); #ifdef DEBUG_CDROM - fprintf(stderr, "Trying to play from %d:%d:%d to %d:%d:%d\n", - playtime.cdmsf_min0, playtime.cdmsf_sec0, playtime.cdmsf_frame0, - playtime.cdmsf_min1, playtime.cdmsf_sec1, playtime.cdmsf_frame1); + fprintf(stderr, "Trying to play from %d:%d:%d to %d:%d:%d\n", + playtime.cdmsf_min0, playtime.cdmsf_sec0, playtime.cdmsf_frame0, + playtime.cdmsf_min1, playtime.cdmsf_sec1, playtime.cdmsf_frame1); #endif - ioctl(cdrom->id, CDIOCSTART, 0); - return(SDL_SYS_CDioctl(cdrom->id, CDIOCPLAYMSF, &playtime)); + ioctl(cdrom->id, CDIOCSTART, 0); + return (SDL_SYS_CDioctl(cdrom->id, CDIOCPLAYMSF, &playtime)); } /* Pause play */ -static int SDL_SYS_CDPause(SDL_CD *cdrom) +static int +SDL_SYS_CDPause(SDL_CD * cdrom) { - return(SDL_SYS_CDioctl(cdrom->id, CDIOCPAUSE, 0)); + return (SDL_SYS_CDioctl(cdrom->id, CDIOCPAUSE, 0)); } /* Resume play */ -static int SDL_SYS_CDResume(SDL_CD *cdrom) +static int +SDL_SYS_CDResume(SDL_CD * cdrom) { - return(SDL_SYS_CDioctl(cdrom->id, CDIOCRESUME, 0)); + return (SDL_SYS_CDioctl(cdrom->id, CDIOCRESUME, 0)); } /* Stop play */ -static int SDL_SYS_CDStop(SDL_CD *cdrom) +static int +SDL_SYS_CDStop(SDL_CD * cdrom) { - return(SDL_SYS_CDioctl(cdrom->id, CDIOCSTOP, 0)); + return (SDL_SYS_CDioctl(cdrom->id, CDIOCSTOP, 0)); } /* Eject the CD-ROM */ -static int SDL_SYS_CDEject(SDL_CD *cdrom) +static int +SDL_SYS_CDEject(SDL_CD * cdrom) { - return(SDL_SYS_CDioctl(cdrom->id, CDIOCEJECT, 0)); + return (SDL_SYS_CDioctl(cdrom->id, CDIOCEJECT, 0)); } /* Close the CD-ROM handle */ -static void SDL_SYS_CDClose(SDL_CD *cdrom) +static void +SDL_SYS_CDClose(SDL_CD * cdrom) { - close(cdrom->id); + close(cdrom->id); } -void SDL_SYS_CDQuit(void) +void +SDL_SYS_CDQuit(void) { - int i; - - if ( SDL_numcds > 0 ) { - for ( i=0; i 0) { + for (i = 0; i < SDL_numcds; ++i) { + SDL_free(SDL_cdlist[i]); + } + SDL_numcds = 0; + } } #endif /* SDL_CDROM_FREEBSD */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/cdrom/linux/SDL_syscdrom.c b/src/cdrom/linux/SDL_syscdrom.c index 4d3e70cd0..171abcb3b 100644 --- a/src/cdrom/linux/SDL_syscdrom.c +++ b/src/cdrom/linux/SDL_syscdrom.c @@ -25,7 +25,7 @@ /* Functions for system-level CD-ROM audio control */ -#include /* For strerror() */ +#include /* For strerror() */ #include #include #include @@ -89,7 +89,7 @@ /* The maximum number of CD-ROM drives we'll detect */ -#define MAX_DRIVES 16 +#define MAX_DRIVES 16 /* A list of available CD-ROM drives */ static char *SDL_cdlist[MAX_DRIVES]; @@ -98,14 +98,14 @@ static dev_t SDL_cdmode[MAX_DRIVES]; /* The system-dependent CD control functions */ static const char *SDL_SYS_CDName(int drive); static int SDL_SYS_CDOpen(int drive); -static int SDL_SYS_CDGetTOC(SDL_CD *cdrom); -static CDstatus SDL_SYS_CDStatus(SDL_CD *cdrom, int *position); -static int SDL_SYS_CDPlay(SDL_CD *cdrom, int start, int length); -static int SDL_SYS_CDPause(SDL_CD *cdrom); -static int SDL_SYS_CDResume(SDL_CD *cdrom); -static int SDL_SYS_CDStop(SDL_CD *cdrom); -static int SDL_SYS_CDEject(SDL_CD *cdrom); -static void SDL_SYS_CDClose(SDL_CD *cdrom); +static int SDL_SYS_CDGetTOC(SDL_CD * cdrom); +static CDstatus SDL_SYS_CDStatus(SDL_CD * cdrom, int *position); +static int SDL_SYS_CDPlay(SDL_CD * cdrom, int start, int length); +static int SDL_SYS_CDPause(SDL_CD * cdrom); +static int SDL_SYS_CDResume(SDL_CD * cdrom); +static int SDL_SYS_CDStop(SDL_CD * cdrom); +static int SDL_SYS_CDEject(SDL_CD * cdrom); +static void SDL_SYS_CDClose(SDL_CD * cdrom); /* Some ioctl() errno values which occur when the tray is empty */ #ifndef ENOMEDIUM @@ -116,449 +116,471 @@ static void SDL_SYS_CDClose(SDL_CD *cdrom); (errno == EINVAL) || (errno == ENOMEDIUM)) /* Check a drive to see if it is a CD-ROM */ -static int CheckDrive(char *drive, char *mnttype, struct stat *stbuf) +static int +CheckDrive(char *drive, char *mnttype, struct stat *stbuf) { - int is_cd, cdfd; - struct cdrom_subchnl info; - - /* If it doesn't exist, return -1 */ - if ( stat(drive, stbuf) < 0 ) { - return(-1); - } - - /* If it does exist, verify that it's an available CD-ROM */ - is_cd = 0; - if ( S_ISCHR(stbuf->st_mode) || S_ISBLK(stbuf->st_mode) ) { - cdfd = open(drive, (O_RDONLY|O_NONBLOCK), 0); - if ( cdfd >= 0 ) { - info.cdsc_format = CDROM_MSF; - /* Under Linux, EIO occurs when a disk is not present. - */ - if ( (ioctl(cdfd, CDROMSUBCHNL, &info) == 0) || - ERRNO_TRAYEMPTY(errno) ) { - is_cd = 1; - } - close(cdfd); - } + int is_cd, cdfd; + struct cdrom_subchnl info; + + /* If it doesn't exist, return -1 */ + if (stat(drive, stbuf) < 0) { + return (-1); + } + + /* If it does exist, verify that it's an available CD-ROM */ + is_cd = 0; + if (S_ISCHR(stbuf->st_mode) || S_ISBLK(stbuf->st_mode)) { + cdfd = open(drive, (O_RDONLY | O_NONBLOCK), 0); + if (cdfd >= 0) { + info.cdsc_format = CDROM_MSF; + /* Under Linux, EIO occurs when a disk is not present. + */ + if ((ioctl(cdfd, CDROMSUBCHNL, &info) == 0) || + ERRNO_TRAYEMPTY(errno)) { + is_cd = 1; + } + close(cdfd); + } #ifdef USE_MNTENT - /* Even if we can't read it, it might be mounted */ - else if ( mnttype && (SDL_strcmp(mnttype, MNTTYPE_CDROM) == 0) ) { - is_cd = 1; - } + /* Even if we can't read it, it might be mounted */ + else if (mnttype && (SDL_strcmp(mnttype, MNTTYPE_CDROM) == 0)) { + is_cd = 1; + } #endif - } - return(is_cd); + } + return (is_cd); } /* Add a CD-ROM drive to our list of valid drives */ -static void AddDrive(char *drive, struct stat *stbuf) +static void +AddDrive(char *drive, struct stat *stbuf) { - int i; - - if ( SDL_numcds < MAX_DRIVES ) { - /* Check to make sure it's not already in our list. - This can happen when we see a drive via symbolic link. - */ - for ( i=0; ist_rdev == SDL_cdmode[i] ) { + int i; + + if (SDL_numcds < MAX_DRIVES) { + /* Check to make sure it's not already in our list. + This can happen when we see a drive via symbolic link. + */ + for (i = 0; i < SDL_numcds; ++i) { + if (stbuf->st_rdev == SDL_cdmode[i]) { #ifdef DEBUG_CDROM - fprintf(stderr, "Duplicate drive detected: %s == %s\n", drive, SDL_cdlist[i]); + fprintf(stderr, "Duplicate drive detected: %s == %s\n", + drive, SDL_cdlist[i]); #endif - return; - } - } - - /* Add this drive to our list */ - i = SDL_numcds; - SDL_cdlist[i] = SDL_strdup(drive); - if ( SDL_cdlist[i] == NULL ) { - SDL_OutOfMemory(); - return; - } - SDL_cdmode[i] = stbuf->st_rdev; - ++SDL_numcds; + return; + } + } + + /* Add this drive to our list */ + i = SDL_numcds; + SDL_cdlist[i] = SDL_strdup(drive); + if (SDL_cdlist[i] == NULL) { + SDL_OutOfMemory(); + return; + } + SDL_cdmode[i] = stbuf->st_rdev; + ++SDL_numcds; #ifdef DEBUG_CDROM - fprintf(stderr, "Added CD-ROM drive: %s\n", drive); + fprintf(stderr, "Added CD-ROM drive: %s\n", drive); #endif - } + } } #ifdef USE_MNTENT -static void CheckMounts(const char *mtab) +static void +CheckMounts(const char *mtab) { - FILE *mntfp; - struct mntent *mntent; - struct stat stbuf; - - mntfp = setmntent(mtab, "r"); - if ( mntfp != NULL ) { - char *tmp; - char *mnt_type; - size_t mnt_type_len; - char *mnt_dev; - size_t mnt_dev_len; - - while ( (mntent=getmntent(mntfp)) != NULL ) { - mnt_type_len = SDL_strlen(mntent->mnt_type) + 1; - mnt_type = SDL_stack_alloc(char, mnt_type_len); - if (mnt_type == NULL) - continue; /* maybe you'll get lucky next time. */ - - mnt_dev_len = SDL_strlen(mntent->mnt_fsname) + 1; - mnt_dev = SDL_stack_alloc(char, mnt_dev_len); - if (mnt_dev == NULL) { - SDL_stack_free(mnt_type); - continue; - } - - SDL_strlcpy(mnt_type, mntent->mnt_type, mnt_type_len); - SDL_strlcpy(mnt_dev, mntent->mnt_fsname, mnt_dev_len); - - /* Handle "supermount" filesystem mounts */ - if ( SDL_strcmp(mnt_type, MNTTYPE_SUPER) == 0 ) { - tmp = SDL_strstr(mntent->mnt_opts, "fs="); - if ( tmp ) { - SDL_free(mnt_type); - mnt_type = SDL_strdup(tmp + SDL_strlen("fs=")); - if ( mnt_type ) { - tmp = SDL_strchr(mnt_type, ','); - if ( tmp ) { - *tmp = '\0'; - } - } - } - tmp = SDL_strstr(mntent->mnt_opts, "dev="); - if ( tmp ) { - SDL_free(mnt_dev); - mnt_dev = SDL_strdup(tmp + SDL_strlen("dev=")); - if ( mnt_dev ) { - tmp = SDL_strchr(mnt_dev, ','); - if ( tmp ) { - *tmp = '\0'; - } - } - } - } - if ( SDL_strcmp(mnt_type, MNTTYPE_CDROM) == 0 ) { + FILE *mntfp; + struct mntent *mntent; + struct stat stbuf; + + mntfp = setmntent(mtab, "r"); + if (mntfp != NULL) { + char *tmp; + char *mnt_type; + size_t mnt_type_len; + char *mnt_dev; + size_t mnt_dev_len; + + while ((mntent = getmntent(mntfp)) != NULL) { + mnt_type_len = SDL_strlen(mntent->mnt_type) + 1; + mnt_type = SDL_stack_alloc(char, mnt_type_len); + if (mnt_type == NULL) + continue; /* maybe you'll get lucky next time. */ + + mnt_dev_len = SDL_strlen(mntent->mnt_fsname) + 1; + mnt_dev = SDL_stack_alloc(char, mnt_dev_len); + if (mnt_dev == NULL) { + SDL_stack_free(mnt_type); + continue; + } + + SDL_strlcpy(mnt_type, mntent->mnt_type, mnt_type_len); + SDL_strlcpy(mnt_dev, mntent->mnt_fsname, mnt_dev_len); + + /* Handle "supermount" filesystem mounts */ + if (SDL_strcmp(mnt_type, MNTTYPE_SUPER) == 0) { + tmp = SDL_strstr(mntent->mnt_opts, "fs="); + if (tmp) { + SDL_free(mnt_type); + mnt_type = SDL_strdup(tmp + SDL_strlen("fs=")); + if (mnt_type) { + tmp = SDL_strchr(mnt_type, ','); + if (tmp) { + *tmp = '\0'; + } + } + } + tmp = SDL_strstr(mntent->mnt_opts, "dev="); + if (tmp) { + SDL_free(mnt_dev); + mnt_dev = SDL_strdup(tmp + SDL_strlen("dev=")); + if (mnt_dev) { + tmp = SDL_strchr(mnt_dev, ','); + if (tmp) { + *tmp = '\0'; + } + } + } + } + if (SDL_strcmp(mnt_type, MNTTYPE_CDROM) == 0) { #ifdef DEBUG_CDROM - fprintf(stderr, "Checking mount path from %s: %s mounted on %s of %s\n", - mtab, mnt_dev, mntent->mnt_dir, mnt_type); + fprintf(stderr, + "Checking mount path from %s: %s mounted on %s of %s\n", + mtab, mnt_dev, mntent->mnt_dir, mnt_type); #endif - if (CheckDrive(mnt_dev, mnt_type, &stbuf) > 0) { - AddDrive(mnt_dev, &stbuf); - } - } - SDL_stack_free(mnt_dev); - SDL_stack_free(mnt_type); - } - endmntent(mntfp); - } + if (CheckDrive(mnt_dev, mnt_type, &stbuf) > 0) { + AddDrive(mnt_dev, &stbuf); + } + } + SDL_stack_free(mnt_dev); + SDL_stack_free(mnt_type); + } + endmntent(mntfp); + } } #endif /* USE_MNTENT */ -int SDL_SYS_CDInit(void) +int +SDL_SYS_CDInit(void) { - /* checklist: /dev/cdrom, /dev/hd?, /dev/scd? /dev/sr? */ - static char *checklist[] = { - "cdrom", "?a hd?", "?0 scd?", "?0 sr?", NULL - }; - char *SDLcdrom; - int i, j, exists; - char drive[32]; - struct stat stbuf; - - /* Fill in our driver capabilities */ - SDL_CDcaps.Name = SDL_SYS_CDName; - SDL_CDcaps.Open = SDL_SYS_CDOpen; - SDL_CDcaps.GetTOC = SDL_SYS_CDGetTOC; - SDL_CDcaps.Status = SDL_SYS_CDStatus; - SDL_CDcaps.Play = SDL_SYS_CDPlay; - SDL_CDcaps.Pause = SDL_SYS_CDPause; - SDL_CDcaps.Resume = SDL_SYS_CDResume; - SDL_CDcaps.Stop = SDL_SYS_CDStop; - SDL_CDcaps.Eject = SDL_SYS_CDEject; - SDL_CDcaps.Close = SDL_SYS_CDClose; - - /* Look in the environment for our CD-ROM drive list */ - SDLcdrom = SDL_getenv("SDL_CDROM"); /* ':' separated list of devices */ - if ( SDLcdrom != NULL ) { - char *cdpath, *delim; - size_t len = SDL_strlen(SDLcdrom)+1; - cdpath = SDL_stack_alloc(char, len); - if ( cdpath != NULL ) { - SDL_strlcpy(cdpath, SDLcdrom, len); - SDLcdrom = cdpath; - do { - delim = SDL_strchr(SDLcdrom, ':'); - if ( delim ) { - *delim++ = '\0'; - } + /* checklist: /dev/cdrom, /dev/hd?, /dev/scd? /dev/sr? */ + static char *checklist[] = { + "cdrom", "?a hd?", "?0 scd?", "?0 sr?", NULL + }; + char *SDLcdrom; + int i, j, exists; + char drive[32]; + struct stat stbuf; + + /* Fill in our driver capabilities */ + SDL_CDcaps.Name = SDL_SYS_CDName; + SDL_CDcaps.Open = SDL_SYS_CDOpen; + SDL_CDcaps.GetTOC = SDL_SYS_CDGetTOC; + SDL_CDcaps.Status = SDL_SYS_CDStatus; + SDL_CDcaps.Play = SDL_SYS_CDPlay; + SDL_CDcaps.Pause = SDL_SYS_CDPause; + SDL_CDcaps.Resume = SDL_SYS_CDResume; + SDL_CDcaps.Stop = SDL_SYS_CDStop; + SDL_CDcaps.Eject = SDL_SYS_CDEject; + SDL_CDcaps.Close = SDL_SYS_CDClose; + + /* Look in the environment for our CD-ROM drive list */ + SDLcdrom = SDL_getenv("SDL_CDROM"); /* ':' separated list of devices */ + if (SDLcdrom != NULL) { + char *cdpath, *delim; + size_t len = SDL_strlen(SDLcdrom) + 1; + cdpath = SDL_stack_alloc(char, len); + if (cdpath != NULL) { + SDL_strlcpy(cdpath, SDLcdrom, len); + SDLcdrom = cdpath; + do { + delim = SDL_strchr(SDLcdrom, ':'); + if (delim) { + *delim++ = '\0'; + } #ifdef DEBUG_CDROM - fprintf(stderr, "Checking CD-ROM drive from SDL_CDROM: %s\n", SDLcdrom); + fprintf(stderr, + "Checking CD-ROM drive from SDL_CDROM: %s\n", + SDLcdrom); #endif - if ( CheckDrive(SDLcdrom, NULL, &stbuf) > 0 ) { - AddDrive(SDLcdrom, &stbuf); - } - if ( delim ) { - SDLcdrom = delim; - } else { - SDLcdrom = NULL; - } - } while ( SDLcdrom ); - SDL_stack_free(cdpath); - } - - /* If we found our drives, there's nothing left to do */ - if ( SDL_numcds > 0 ) { - return(0); - } - } - + if (CheckDrive(SDLcdrom, NULL, &stbuf) > 0) { + AddDrive(SDLcdrom, &stbuf); + } + if (delim) { + SDLcdrom = delim; + } else { + SDLcdrom = NULL; + } + } + while (SDLcdrom); + SDL_stack_free(cdpath); + } + + /* If we found our drives, there's nothing left to do */ + if (SDL_numcds > 0) { + return (0); + } + } #ifdef USE_MNTENT - /* Check /dev/cdrom first :-) */ - if (CheckDrive("/dev/cdrom", NULL, &stbuf) > 0) { - AddDrive("/dev/cdrom", &stbuf); - } + /* Check /dev/cdrom first :-) */ + if (CheckDrive("/dev/cdrom", NULL, &stbuf) > 0) { + AddDrive("/dev/cdrom", &stbuf); + } - /* Now check the currently mounted CD drives */ - CheckMounts(_PATH_MOUNTED); + /* Now check the currently mounted CD drives */ + CheckMounts(_PATH_MOUNTED); - /* Finally check possible mountable drives in /etc/fstab */ - CheckMounts(_PATH_MNTTAB); + /* Finally check possible mountable drives in /etc/fstab */ + CheckMounts(_PATH_MNTTAB); - /* If we found our drives, there's nothing left to do */ - if ( SDL_numcds > 0 ) { - return(0); - } + /* If we found our drives, there's nothing left to do */ + if (SDL_numcds > 0) { + return (0); + } #endif /* USE_MNTENT */ - /* Scan the system for CD-ROM drives. - Not always 100% reliable, so use the USE_MNTENT code above first. - */ - for ( i=0; checklist[i]; ++i ) { - if ( checklist[i][0] == '?' ) { - char *insert; - exists = 1; - for ( j=checklist[i][1]; exists; ++j ) { - SDL_snprintf(drive, SDL_arraysize(drive), "/dev/%s", &checklist[i][3]); - insert = SDL_strchr(drive, '?'); - if ( insert != NULL ) { - *insert = j; - } + /* Scan the system for CD-ROM drives. + Not always 100% reliable, so use the USE_MNTENT code above first. + */ + for (i = 0; checklist[i]; ++i) { + if (checklist[i][0] == '?') { + char *insert; + exists = 1; + for (j = checklist[i][1]; exists; ++j) { + SDL_snprintf(drive, SDL_arraysize(drive), "/dev/%s", + &checklist[i][3]); + insert = SDL_strchr(drive, '?'); + if (insert != NULL) { + *insert = j; + } #ifdef DEBUG_CDROM - fprintf(stderr, "Checking possible CD-ROM drive: %s\n", drive); + fprintf(stderr, "Checking possible CD-ROM drive: %s\n", + drive); #endif - switch (CheckDrive(drive, NULL, &stbuf)) { - /* Drive exists and is a CD-ROM */ - case 1: - AddDrive(drive, &stbuf); - break; - /* Drive exists, but isn't a CD-ROM */ - case 0: - break; - /* Drive doesn't exist */ - case -1: - exists = 0; - break; - } - } - } else { - SDL_snprintf(drive, SDL_arraysize(drive), "/dev/%s", checklist[i]); + switch (CheckDrive(drive, NULL, &stbuf)) { + /* Drive exists and is a CD-ROM */ + case 1: + AddDrive(drive, &stbuf); + break; + /* Drive exists, but isn't a CD-ROM */ + case 0: + break; + /* Drive doesn't exist */ + case -1: + exists = 0; + break; + } + } + } else { + SDL_snprintf(drive, SDL_arraysize(drive), "/dev/%s", + checklist[i]); #ifdef DEBUG_CDROM - fprintf(stderr, "Checking possible CD-ROM drive: %s\n", drive); + fprintf(stderr, "Checking possible CD-ROM drive: %s\n", drive); #endif - if ( CheckDrive(drive, NULL, &stbuf) > 0 ) { - AddDrive(drive, &stbuf); - } - } - } - return(0); + if (CheckDrive(drive, NULL, &stbuf) > 0) { + AddDrive(drive, &stbuf); + } + } + } + return (0); } /* General ioctl() CD-ROM command function */ -static int SDL_SYS_CDioctl(int id, int command, void *arg) +static int +SDL_SYS_CDioctl(int id, int command, void *arg) { - int retval; + int retval; - retval = ioctl(id, command, arg); - if ( retval < 0 ) { - SDL_SetError("ioctl() error: %s", strerror(errno)); - } - return(retval); + retval = ioctl(id, command, arg); + if (retval < 0) { + SDL_SetError("ioctl() error: %s", strerror(errno)); + } + return (retval); } -static const char *SDL_SYS_CDName(int drive) +static const char * +SDL_SYS_CDName(int drive) { - return(SDL_cdlist[drive]); + return (SDL_cdlist[drive]); } -static int SDL_SYS_CDOpen(int drive) +static int +SDL_SYS_CDOpen(int drive) { - return(open(SDL_cdlist[drive], (O_RDONLY|O_NONBLOCK), 0)); + return (open(SDL_cdlist[drive], (O_RDONLY | O_NONBLOCK), 0)); } -static int SDL_SYS_CDGetTOC(SDL_CD *cdrom) +static int +SDL_SYS_CDGetTOC(SDL_CD * cdrom) { - struct cdrom_tochdr toc; - int i, okay; - struct cdrom_tocentry entry; - - okay = 0; - if ( SDL_SYS_CDioctl(cdrom->id, CDROMREADTOCHDR, &toc) == 0 ) { - cdrom->numtracks = toc.cdth_trk1-toc.cdth_trk0+1; - if ( cdrom->numtracks > SDL_MAX_TRACKS ) { - cdrom->numtracks = SDL_MAX_TRACKS; - } - /* Read all the track TOC entries */ - for ( i=0; i<=cdrom->numtracks; ++i ) { - if ( i == cdrom->numtracks ) { - cdrom->track[i].id = CDROM_LEADOUT; - } else { - cdrom->track[i].id = toc.cdth_trk0+i; - } - entry.cdte_track = cdrom->track[i].id; - entry.cdte_format = CDROM_MSF; - if ( SDL_SYS_CDioctl(cdrom->id, CDROMREADTOCENTRY, - &entry) < 0 ) { - break; - } else { - if ( entry.cdte_ctrl & CDROM_DATA_TRACK ) { - cdrom->track[i].type = SDL_DATA_TRACK; - } else { - cdrom->track[i].type = SDL_AUDIO_TRACK; - } - cdrom->track[i].offset = MSF_TO_FRAMES( - entry.cdte_addr.msf.minute, - entry.cdte_addr.msf.second, - entry.cdte_addr.msf.frame); - cdrom->track[i].length = 0; - if ( i > 0 ) { - cdrom->track[i-1].length = - cdrom->track[i].offset- - cdrom->track[i-1].offset; - } - } - } - if ( i == (cdrom->numtracks+1) ) { - okay = 1; - } - } - return(okay ? 0 : -1); + struct cdrom_tochdr toc; + int i, okay; + struct cdrom_tocentry entry; + + okay = 0; + if (SDL_SYS_CDioctl(cdrom->id, CDROMREADTOCHDR, &toc) == 0) { + cdrom->numtracks = toc.cdth_trk1 - toc.cdth_trk0 + 1; + if (cdrom->numtracks > SDL_MAX_TRACKS) { + cdrom->numtracks = SDL_MAX_TRACKS; + } + /* Read all the track TOC entries */ + for (i = 0; i <= cdrom->numtracks; ++i) { + if (i == cdrom->numtracks) { + cdrom->track[i].id = CDROM_LEADOUT; + } else { + cdrom->track[i].id = toc.cdth_trk0 + i; + } + entry.cdte_track = cdrom->track[i].id; + entry.cdte_format = CDROM_MSF; + if (SDL_SYS_CDioctl(cdrom->id, CDROMREADTOCENTRY, &entry) < 0) { + break; + } else { + if (entry.cdte_ctrl & CDROM_DATA_TRACK) { + cdrom->track[i].type = SDL_DATA_TRACK; + } else { + cdrom->track[i].type = SDL_AUDIO_TRACK; + } + cdrom->track[i].offset = + MSF_TO_FRAMES(entry.cdte_addr.msf.minute, + entry.cdte_addr.msf.second, + entry.cdte_addr.msf.frame); + cdrom->track[i].length = 0; + if (i > 0) { + cdrom->track[i - 1].length = + cdrom->track[i].offset - cdrom->track[i - 1].offset; + } + } + } + if (i == (cdrom->numtracks + 1)) { + okay = 1; + } + } + return (okay ? 0 : -1); } /* Get CD-ROM status */ -static CDstatus SDL_SYS_CDStatus(SDL_CD *cdrom, int *position) +static CDstatus +SDL_SYS_CDStatus(SDL_CD * cdrom, int *position) { - CDstatus status; - struct cdrom_tochdr toc; - struct cdrom_subchnl info; - - info.cdsc_format = CDROM_MSF; - if ( ioctl(cdrom->id, CDROMSUBCHNL, &info) < 0 ) { - if ( ERRNO_TRAYEMPTY(errno) ) { - status = CD_TRAYEMPTY; - } else { - status = CD_ERROR; - } - } else { - switch (info.cdsc_audiostatus) { - case CDROM_AUDIO_INVALID: - case CDROM_AUDIO_NO_STATUS: - /* Try to determine if there's a CD available */ - if (ioctl(cdrom->id, CDROMREADTOCHDR, &toc)==0) - status = CD_STOPPED; - else - status = CD_TRAYEMPTY; - break; - case CDROM_AUDIO_COMPLETED: - status = CD_STOPPED; - break; - case CDROM_AUDIO_PLAY: - status = CD_PLAYING; - break; - case CDROM_AUDIO_PAUSED: - /* Workaround buggy CD-ROM drive */ - if ( info.cdsc_trk == CDROM_LEADOUT ) { - status = CD_STOPPED; - } else { - status = CD_PAUSED; - } - break; - default: - status = CD_ERROR; - break; - } - } - if ( position ) { - if ( status == CD_PLAYING || (status == CD_PAUSED) ) { - *position = MSF_TO_FRAMES( - info.cdsc_absaddr.msf.minute, - info.cdsc_absaddr.msf.second, - info.cdsc_absaddr.msf.frame); - } else { - *position = 0; - } - } - return(status); + CDstatus status; + struct cdrom_tochdr toc; + struct cdrom_subchnl info; + + info.cdsc_format = CDROM_MSF; + if (ioctl(cdrom->id, CDROMSUBCHNL, &info) < 0) { + if (ERRNO_TRAYEMPTY(errno)) { + status = CD_TRAYEMPTY; + } else { + status = CD_ERROR; + } + } else { + switch (info.cdsc_audiostatus) { + case CDROM_AUDIO_INVALID: + case CDROM_AUDIO_NO_STATUS: + /* Try to determine if there's a CD available */ + if (ioctl(cdrom->id, CDROMREADTOCHDR, &toc) == 0) + status = CD_STOPPED; + else + status = CD_TRAYEMPTY; + break; + case CDROM_AUDIO_COMPLETED: + status = CD_STOPPED; + break; + case CDROM_AUDIO_PLAY: + status = CD_PLAYING; + break; + case CDROM_AUDIO_PAUSED: + /* Workaround buggy CD-ROM drive */ + if (info.cdsc_trk == CDROM_LEADOUT) { + status = CD_STOPPED; + } else { + status = CD_PAUSED; + } + break; + default: + status = CD_ERROR; + break; + } + } + if (position) { + if (status == CD_PLAYING || (status == CD_PAUSED)) { + *position = MSF_TO_FRAMES(info.cdsc_absaddr.msf.minute, + info.cdsc_absaddr.msf.second, + info.cdsc_absaddr.msf.frame); + } else { + *position = 0; + } + } + return (status); } /* Start play */ -static int SDL_SYS_CDPlay(SDL_CD *cdrom, int start, int length) +static int +SDL_SYS_CDPlay(SDL_CD * cdrom, int start, int length) { - struct cdrom_msf playtime; + struct cdrom_msf playtime; - FRAMES_TO_MSF(start, - &playtime.cdmsf_min0, &playtime.cdmsf_sec0, &playtime.cdmsf_frame0); - FRAMES_TO_MSF(start+length, - &playtime.cdmsf_min1, &playtime.cdmsf_sec1, &playtime.cdmsf_frame1); + FRAMES_TO_MSF(start, + &playtime.cdmsf_min0, &playtime.cdmsf_sec0, + &playtime.cdmsf_frame0); + FRAMES_TO_MSF(start + length, &playtime.cdmsf_min1, &playtime.cdmsf_sec1, + &playtime.cdmsf_frame1); #ifdef DEBUG_CDROM - fprintf(stderr, "Trying to play from %d:%d:%d to %d:%d:%d\n", - playtime.cdmsf_min0, playtime.cdmsf_sec0, playtime.cdmsf_frame0, - playtime.cdmsf_min1, playtime.cdmsf_sec1, playtime.cdmsf_frame1); + fprintf(stderr, "Trying to play from %d:%d:%d to %d:%d:%d\n", + playtime.cdmsf_min0, playtime.cdmsf_sec0, playtime.cdmsf_frame0, + playtime.cdmsf_min1, playtime.cdmsf_sec1, playtime.cdmsf_frame1); #endif - return(SDL_SYS_CDioctl(cdrom->id, CDROMPLAYMSF, &playtime)); + return (SDL_SYS_CDioctl(cdrom->id, CDROMPLAYMSF, &playtime)); } /* Pause play */ -static int SDL_SYS_CDPause(SDL_CD *cdrom) +static int +SDL_SYS_CDPause(SDL_CD * cdrom) { - return(SDL_SYS_CDioctl(cdrom->id, CDROMPAUSE, 0)); + return (SDL_SYS_CDioctl(cdrom->id, CDROMPAUSE, 0)); } /* Resume play */ -static int SDL_SYS_CDResume(SDL_CD *cdrom) +static int +SDL_SYS_CDResume(SDL_CD * cdrom) { - return(SDL_SYS_CDioctl(cdrom->id, CDROMRESUME, 0)); + return (SDL_SYS_CDioctl(cdrom->id, CDROMRESUME, 0)); } /* Stop play */ -static int SDL_SYS_CDStop(SDL_CD *cdrom) +static int +SDL_SYS_CDStop(SDL_CD * cdrom) { - return(SDL_SYS_CDioctl(cdrom->id, CDROMSTOP, 0)); + return (SDL_SYS_CDioctl(cdrom->id, CDROMSTOP, 0)); } /* Eject the CD-ROM */ -static int SDL_SYS_CDEject(SDL_CD *cdrom) +static int +SDL_SYS_CDEject(SDL_CD * cdrom) { - return(SDL_SYS_CDioctl(cdrom->id, CDROMEJECT, 0)); + return (SDL_SYS_CDioctl(cdrom->id, CDROMEJECT, 0)); } /* Close the CD-ROM handle */ -static void SDL_SYS_CDClose(SDL_CD *cdrom) +static void +SDL_SYS_CDClose(SDL_CD * cdrom) { - close(cdrom->id); + close(cdrom->id); } -void SDL_SYS_CDQuit(void) +void +SDL_SYS_CDQuit(void) { - int i; - - if ( SDL_numcds > 0 ) { - for ( i=0; i 0) { + for (i = 0; i < SDL_numcds; ++i) { + SDL_free(SDL_cdlist[i]); + } + SDL_numcds = 0; + } } #endif /* SDL_CDROM_LINUX */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/cdrom/macos/SDL_syscdrom.c b/src/cdrom/macos/SDL_syscdrom.c index bbe69e957..69a30510d 100644 --- a/src/cdrom/macos/SDL_syscdrom.c +++ b/src/cdrom/macos/SDL_syscdrom.c @@ -27,7 +27,7 @@ #include #include -#include /* Use entry table macros, not functions in InterfaceLib */ +#include /* Use entry table macros, not functions in InterfaceLib */ #include "SDL_cdrom.h" #include "../SDL_syscdrom.h" @@ -35,491 +35,509 @@ /* Added by Matt Slot */ #if !defined(LMGetUnitTableEntryCount) - #define LMGetUnitTableEntryCount() *(short *)0x01D2 +#define LMGetUnitTableEntryCount() *(short *)0x01D2 #endif /* The maximum number of CD-ROM drives we'll detect */ -#define MAX_DRIVES 26 +#define MAX_DRIVES 26 /* A list of available CD-ROM drives */ static long SDL_cdversion = 0; -static struct { - short dRefNum; - short driveNum; - long frames; - char name[256]; - Boolean hasAudio; - } SDL_cdlist[MAX_DRIVES]; +static struct +{ + short dRefNum; + short driveNum; + long frames; + char name[256]; + Boolean hasAudio; +} SDL_cdlist[MAX_DRIVES]; static StringPtr gDriverName = "\p.AppleCD"; /* The system-dependent CD control functions */ static const char *SDL_SYS_CDName(int drive); static int SDL_SYS_CDOpen(int drive); -static int SDL_SYS_CDGetTOC(SDL_CD *cdrom); -static CDstatus SDL_SYS_CDStatus(SDL_CD *cdrom, int *position); -static int SDL_SYS_CDPlay(SDL_CD *cdrom, int start, int length); -static int SDL_SYS_CDPause(SDL_CD *cdrom); -static int SDL_SYS_CDResume(SDL_CD *cdrom); -static int SDL_SYS_CDStop(SDL_CD *cdrom); -static int SDL_SYS_CDEject(SDL_CD *cdrom); -static void SDL_SYS_CDClose(SDL_CD *cdrom); - -static short SDL_SYS_ShortToBCD(short value) +static int SDL_SYS_CDGetTOC(SDL_CD * cdrom); +static CDstatus SDL_SYS_CDStatus(SDL_CD * cdrom, int *position); +static int SDL_SYS_CDPlay(SDL_CD * cdrom, int start, int length); +static int SDL_SYS_CDPause(SDL_CD * cdrom); +static int SDL_SYS_CDResume(SDL_CD * cdrom); +static int SDL_SYS_CDStop(SDL_CD * cdrom); +static int SDL_SYS_CDEject(SDL_CD * cdrom); +static void SDL_SYS_CDClose(SDL_CD * cdrom); + +static short +SDL_SYS_ShortToBCD(short value) { - return((value % 10) + (value / 10) * 0x10); /* Convert value to BCD */ + return ((value % 10) + (value / 10) * 0x10); /* Convert value to BCD */ } -static short SDL_SYS_BCDToShort(short value) +static short +SDL_SYS_BCDToShort(short value) { - return((value % 0x10) + (value / 0x10) * 10); /* Convert value from BCD */ + return ((value % 0x10) + (value / 0x10) * 10); /* Convert value from BCD */ } -int SDL_SYS_CDInit(void) +int +SDL_SYS_CDInit(void) { - SInt16 dRefNum = 0; - SInt16 first, last; - - SDL_numcds = 0; - - /* Check that the software is available */ - if (Gestalt(kGestaltAudioCDSelector, &SDL_cdversion) || - !SDL_cdversion) return(0); - - /* Fill in our driver capabilities */ - SDL_CDcaps.Name = SDL_SYS_CDName; - SDL_CDcaps.Open = SDL_SYS_CDOpen; - SDL_CDcaps.GetTOC = SDL_SYS_CDGetTOC; - SDL_CDcaps.Status = SDL_SYS_CDStatus; - SDL_CDcaps.Play = SDL_SYS_CDPlay; - SDL_CDcaps.Pause = SDL_SYS_CDPause; - SDL_CDcaps.Resume = SDL_SYS_CDResume; - SDL_CDcaps.Stop = SDL_SYS_CDStop; - SDL_CDcaps.Eject = SDL_SYS_CDEject; - SDL_CDcaps.Close = SDL_SYS_CDClose; - - /* Walk the list, count each AudioCD driver, and save the refnums */ - first = -1; - last = 0 - LMGetUnitTableEntryCount(); - for(dRefNum = first; dRefNum >= last; dRefNum--) { - Str255 driverName; - StringPtr namePtr; - DCtlHandle deviceEntry; - - deviceEntry = GetDCtlEntry(dRefNum); - if (! deviceEntry) continue; - - /* Is this an .AppleCD ? */ - namePtr = (*deviceEntry)->dCtlFlags & (1L << dRAMBased) ? - ((StringPtr) ((DCtlPtr) deviceEntry)->dCtlDriver + 18) : - ((StringPtr) (*deviceEntry)->dCtlDriver + 18); - BlockMoveData(namePtr, driverName, namePtr[0]+1); - if (driverName[0] > gDriverName[0]) driverName[0] = gDriverName[0]; - if (! EqualString(driverName, gDriverName, false, false)) continue; - - /* Record the basic info for each drive */ - SDL_cdlist[SDL_numcds].dRefNum = dRefNum; - BlockMoveData(namePtr + 1, SDL_cdlist[SDL_numcds].name, namePtr[0]); - SDL_cdlist[SDL_numcds].name[namePtr[0]] = 0; - SDL_cdlist[SDL_numcds].hasAudio = false; - SDL_numcds++; - } - return(0); + SInt16 dRefNum = 0; + SInt16 first, last; + + SDL_numcds = 0; + + /* Check that the software is available */ + if (Gestalt(kGestaltAudioCDSelector, &SDL_cdversion) || !SDL_cdversion) + return (0); + + /* Fill in our driver capabilities */ + SDL_CDcaps.Name = SDL_SYS_CDName; + SDL_CDcaps.Open = SDL_SYS_CDOpen; + SDL_CDcaps.GetTOC = SDL_SYS_CDGetTOC; + SDL_CDcaps.Status = SDL_SYS_CDStatus; + SDL_CDcaps.Play = SDL_SYS_CDPlay; + SDL_CDcaps.Pause = SDL_SYS_CDPause; + SDL_CDcaps.Resume = SDL_SYS_CDResume; + SDL_CDcaps.Stop = SDL_SYS_CDStop; + SDL_CDcaps.Eject = SDL_SYS_CDEject; + SDL_CDcaps.Close = SDL_SYS_CDClose; + + /* Walk the list, count each AudioCD driver, and save the refnums */ + first = -1; + last = 0 - LMGetUnitTableEntryCount(); + for (dRefNum = first; dRefNum >= last; dRefNum--) { + Str255 driverName; + StringPtr namePtr; + DCtlHandle deviceEntry; + + deviceEntry = GetDCtlEntry(dRefNum); + if (!deviceEntry) + continue; + + /* Is this an .AppleCD ? */ + namePtr = (*deviceEntry)->dCtlFlags & (1L << dRAMBased) ? + ((StringPtr) ((DCtlPtr) deviceEntry)->dCtlDriver + 18) : + ((StringPtr) (*deviceEntry)->dCtlDriver + 18); + BlockMoveData(namePtr, driverName, namePtr[0] + 1); + if (driverName[0] > gDriverName[0]) + driverName[0] = gDriverName[0]; + if (!EqualString(driverName, gDriverName, false, false)) + continue; + + /* Record the basic info for each drive */ + SDL_cdlist[SDL_numcds].dRefNum = dRefNum; + BlockMoveData(namePtr + 1, SDL_cdlist[SDL_numcds].name, namePtr[0]); + SDL_cdlist[SDL_numcds].name[namePtr[0]] = 0; + SDL_cdlist[SDL_numcds].hasAudio = false; + SDL_numcds++; + } + return (0); } -static const char *SDL_SYS_CDName(int drive) +static const char * +SDL_SYS_CDName(int drive) { - return(SDL_cdlist[drive].name); + return (SDL_cdlist[drive].name); } -static int get_drivenum(int drive) +static int +get_drivenum(int drive) { - QHdr *driveQ = GetDrvQHdr(); - DrvQEl *driveElem; - - /* Update the drive number */ - SDL_cdlist[drive].driveNum = 0; - if ( driveQ->qTail ) { - driveQ->qTail->qLink = 0; - } - for ( driveElem=(DrvQEl *)driveQ->qHead; driveElem; - driveElem = (DrvQEl *)driveElem->qLink ) { - if ( driveElem->dQRefNum == SDL_cdlist[drive].dRefNum ) { - SDL_cdlist[drive].driveNum = driveElem->dQDrive; - break; - } - } - return(SDL_cdlist[drive].driveNum); + QHdr *driveQ = GetDrvQHdr(); + DrvQEl *driveElem; + + /* Update the drive number */ + SDL_cdlist[drive].driveNum = 0; + if (driveQ->qTail) { + driveQ->qTail->qLink = 0; + } + for (driveElem = (DrvQEl *) driveQ->qHead; driveElem; + driveElem = (DrvQEl *) driveElem->qLink) { + if (driveElem->dQRefNum == SDL_cdlist[drive].dRefNum) { + SDL_cdlist[drive].driveNum = driveElem->dQDrive; + break; + } + } + return (SDL_cdlist[drive].driveNum); } -static int SDL_SYS_CDOpen(int drive) +static int +SDL_SYS_CDOpen(int drive) { - return(drive); + return (drive); } -static int SDL_SYS_CDGetTOC(SDL_CD *cdrom) +static int +SDL_SYS_CDGetTOC(SDL_CD * cdrom) { - CDCntrlParam cdpb; - CDTrackData tracks[SDL_MAX_TRACKS]; - long i, leadout; - - /* Get the number of tracks on the CD by examining the TOC */ - SDL_memset(&cdpb, 0, sizeof(cdpb)); - cdpb.ioVRefNum = SDL_cdlist[cdrom->id].driveNum; - cdpb.ioCRefNum = SDL_cdlist[cdrom->id].dRefNum; - cdpb.csCode = kReadTOC; - cdpb.csParam.words[0] = kGetTrackRange; - if ( PBControlSync((ParmBlkPtr)&cdpb) != noErr ) { - SDL_SetError("PBControlSync() failed"); - return(-1); - } - - cdrom->numtracks = - SDL_SYS_BCDToShort(cdpb.csParam.bytes[1]) - - SDL_SYS_BCDToShort(cdpb.csParam.bytes[0]) + 1; - if ( cdrom->numtracks > SDL_MAX_TRACKS ) - cdrom->numtracks = SDL_MAX_TRACKS; - cdrom->status = CD_STOPPED; - cdrom->cur_track = 0; /* Apparently these are set elsewhere */ - cdrom->cur_frame = 0; /* Apparently these are set elsewhere */ - - - /* Get the lead out area of the CD by examining the TOC */ - SDL_memset(&cdpb, 0, sizeof(cdpb)); - cdpb.ioVRefNum = SDL_cdlist[cdrom->id].driveNum; - cdpb.ioCRefNum = SDL_cdlist[cdrom->id].dRefNum; - cdpb.csCode = kReadTOC; - cdpb.csParam.words[0] = kGetLeadOutArea; - if ( PBControlSync((ParmBlkPtr)&cdpb) != noErr ) { - SDL_SetError("PBControlSync() failed"); - return(-1); - } - - leadout = MSF_TO_FRAMES( - SDL_SYS_BCDToShort(cdpb.csParam.bytes[0]), - SDL_SYS_BCDToShort(cdpb.csParam.bytes[1]), - SDL_SYS_BCDToShort(cdpb.csParam.bytes[2])); - - /* Get an array of track locations by examining the TOC */ - SDL_memset(tracks, 0, sizeof(tracks)); - SDL_memset(&cdpb, 0, sizeof(cdpb)); - cdpb.ioVRefNum = SDL_cdlist[cdrom->id].driveNum; - cdpb.ioCRefNum = SDL_cdlist[cdrom->id].dRefNum; - cdpb.csCode = kReadTOC; - cdpb.csParam.words[0] = kGetTrackEntries; /* Type of Query */ - * ((long *) (cdpb.csParam.words+1)) = (long) tracks; - cdpb.csParam.words[3] = cdrom->numtracks * sizeof(tracks[0]); - * ((char *) (cdpb.csParam.words+4)) = 1; /* First track */ - if ( PBControlSync((ParmBlkPtr)&cdpb) != noErr ) { - SDL_SetError("PBControlSync() failed"); - return(-1); - } - - /* Read all the track TOC entries */ - SDL_cdlist[cdrom->id].hasAudio = false; - for ( i=0; inumtracks; ++i ) - { - cdrom->track[i].id = i+1; - if (tracks[i].entry.control & kDataTrackMask) - cdrom->track[i].type = SDL_DATA_TRACK; - else - { - cdrom->track[i].type = SDL_AUDIO_TRACK; - SDL_cdlist[SDL_numcds].hasAudio = true; - } - - cdrom->track[i].offset = MSF_TO_FRAMES( - SDL_SYS_BCDToShort(tracks[i].entry.min), - SDL_SYS_BCDToShort(tracks[i].entry.min), - SDL_SYS_BCDToShort(tracks[i].entry.frame)); - cdrom->track[i].length = MSF_TO_FRAMES( - SDL_SYS_BCDToShort(tracks[i+1].entry.min), - SDL_SYS_BCDToShort(tracks[i+1].entry.min), - SDL_SYS_BCDToShort(tracks[i+1].entry.frame)) - - cdrom->track[i].offset; - } - - /* Apparently SDL wants a fake last entry */ - cdrom->track[i].offset = leadout; - cdrom->track[i].length = 0; - - return(0); + CDCntrlParam cdpb; + CDTrackData tracks[SDL_MAX_TRACKS]; + long i, leadout; + + /* Get the number of tracks on the CD by examining the TOC */ + SDL_memset(&cdpb, 0, sizeof(cdpb)); + cdpb.ioVRefNum = SDL_cdlist[cdrom->id].driveNum; + cdpb.ioCRefNum = SDL_cdlist[cdrom->id].dRefNum; + cdpb.csCode = kReadTOC; + cdpb.csParam.words[0] = kGetTrackRange; + if (PBControlSync((ParmBlkPtr) & cdpb) != noErr) { + SDL_SetError("PBControlSync() failed"); + return (-1); + } + + cdrom->numtracks = + SDL_SYS_BCDToShort(cdpb.csParam.bytes[1]) - + SDL_SYS_BCDToShort(cdpb.csParam.bytes[0]) + 1; + if (cdrom->numtracks > SDL_MAX_TRACKS) + cdrom->numtracks = SDL_MAX_TRACKS; + cdrom->status = CD_STOPPED; + cdrom->cur_track = 0; /* Apparently these are set elsewhere */ + cdrom->cur_frame = 0; /* Apparently these are set elsewhere */ + + + /* Get the lead out area of the CD by examining the TOC */ + SDL_memset(&cdpb, 0, sizeof(cdpb)); + cdpb.ioVRefNum = SDL_cdlist[cdrom->id].driveNum; + cdpb.ioCRefNum = SDL_cdlist[cdrom->id].dRefNum; + cdpb.csCode = kReadTOC; + cdpb.csParam.words[0] = kGetLeadOutArea; + if (PBControlSync((ParmBlkPtr) & cdpb) != noErr) { + SDL_SetError("PBControlSync() failed"); + return (-1); + } + + leadout = MSF_TO_FRAMES(SDL_SYS_BCDToShort(cdpb.csParam.bytes[0]), + SDL_SYS_BCDToShort(cdpb.csParam.bytes[1]), + SDL_SYS_BCDToShort(cdpb.csParam.bytes[2])); + + /* Get an array of track locations by examining the TOC */ + SDL_memset(tracks, 0, sizeof(tracks)); + SDL_memset(&cdpb, 0, sizeof(cdpb)); + cdpb.ioVRefNum = SDL_cdlist[cdrom->id].driveNum; + cdpb.ioCRefNum = SDL_cdlist[cdrom->id].dRefNum; + cdpb.csCode = kReadTOC; + cdpb.csParam.words[0] = kGetTrackEntries; /* Type of Query */ + *((long *) (cdpb.csParam.words + 1)) = (long) tracks; + cdpb.csParam.words[3] = cdrom->numtracks * sizeof(tracks[0]); + *((char *) (cdpb.csParam.words + 4)) = 1; /* First track */ + if (PBControlSync((ParmBlkPtr) & cdpb) != noErr) { + SDL_SetError("PBControlSync() failed"); + return (-1); + } + + /* Read all the track TOC entries */ + SDL_cdlist[cdrom->id].hasAudio = false; + for (i = 0; i < cdrom->numtracks; ++i) { + cdrom->track[i].id = i + 1; + if (tracks[i].entry.control & kDataTrackMask) + cdrom->track[i].type = SDL_DATA_TRACK; + else { + cdrom->track[i].type = SDL_AUDIO_TRACK; + SDL_cdlist[SDL_numcds].hasAudio = true; + } + + cdrom->track[i].offset = + MSF_TO_FRAMES(SDL_SYS_BCDToShort(tracks[i].entry.min), + SDL_SYS_BCDToShort(tracks[i].entry.min), + SDL_SYS_BCDToShort(tracks[i].entry.frame)); + cdrom->track[i].length = + MSF_TO_FRAMES(SDL_SYS_BCDToShort(tracks[i + 1].entry.min), + SDL_SYS_BCDToShort(tracks[i + 1].entry.min), + SDL_SYS_BCDToShort(tracks[i + 1].entry.frame)) - + cdrom->track[i].offset; + } + + /* Apparently SDL wants a fake last entry */ + cdrom->track[i].offset = leadout; + cdrom->track[i].length = 0; + + return (0); } /* Get CD-ROM status */ -static CDstatus SDL_SYS_CDStatus(SDL_CD *cdrom, int *position) +static CDstatus +SDL_SYS_CDStatus(SDL_CD * cdrom, int *position) { - CDCntrlParam cdpb; - CDstatus status = CD_ERROR; - Boolean spinning = false; - - if (position) *position = 0; - - /* Get the number of tracks on the CD by examining the TOC */ - if ( ! get_drivenum(cdrom->id) ) { - return(CD_TRAYEMPTY); - } - SDL_memset(&cdpb, 0, sizeof(cdpb)); - cdpb.ioVRefNum = SDL_cdlist[cdrom->id].driveNum; - cdpb.ioCRefNum = SDL_cdlist[cdrom->id].dRefNum; - cdpb.csCode = kReadTOC; - cdpb.csParam.words[0] = kGetTrackRange; - if ( PBControlSync((ParmBlkPtr)&cdpb) != noErr ) { - SDL_SetError("PBControlSync() failed"); - return(CD_ERROR); - } - - cdrom->numtracks = - SDL_SYS_BCDToShort(cdpb.csParam.bytes[1]) - - SDL_SYS_BCDToShort(cdpb.csParam.bytes[0]) + 1; - if ( cdrom->numtracks > SDL_MAX_TRACKS ) - cdrom->numtracks = SDL_MAX_TRACKS; - cdrom->cur_track = 0; /* Apparently these are set elsewhere */ - cdrom->cur_frame = 0; /* Apparently these are set elsewhere */ - - - if (1 || SDL_cdlist[cdrom->id].hasAudio) { - /* Get the current playback status */ - SDL_memset(&cdpb, 0, sizeof(cdpb)); - cdpb.ioVRefNum = SDL_cdlist[cdrom->id].driveNum; - cdpb.ioCRefNum = SDL_cdlist[cdrom->id].dRefNum; - cdpb.csCode = kAudioStatus; - if ( PBControlSync((ParmBlkPtr)&cdpb) != noErr ) { - SDL_SetError("PBControlSync() failed"); - return(-1); - } - - switch(cdpb.csParam.cd.status) { - case kStatusPlaying: - status = CD_PLAYING; - spinning = true; - break; - case kStatusPaused: - status = CD_PAUSED; - spinning = true; - break; - case kStatusMuted: - status = CD_PLAYING; /* What should I do here? */ - spinning = true; - break; - case kStatusDone: - status = CD_STOPPED; - spinning = true; - break; - case kStatusStopped: - status = CD_STOPPED; - spinning = false; - break; - case kStatusError: - default: - status = CD_ERROR; - spinning = false; - break; - } - - if (spinning && position) *position = MSF_TO_FRAMES( - SDL_SYS_BCDToShort(cdpb.csParam.cd.minute), - SDL_SYS_BCDToShort(cdpb.csParam.cd.second), - SDL_SYS_BCDToShort(cdpb.csParam.cd.frame)); - } - else - status = CD_ERROR; /* What should I do here? */ - - return(status); + CDCntrlParam cdpb; + CDstatus status = CD_ERROR; + Boolean spinning = false; + + if (position) + *position = 0; + + /* Get the number of tracks on the CD by examining the TOC */ + if (!get_drivenum(cdrom->id)) { + return (CD_TRAYEMPTY); + } + SDL_memset(&cdpb, 0, sizeof(cdpb)); + cdpb.ioVRefNum = SDL_cdlist[cdrom->id].driveNum; + cdpb.ioCRefNum = SDL_cdlist[cdrom->id].dRefNum; + cdpb.csCode = kReadTOC; + cdpb.csParam.words[0] = kGetTrackRange; + if (PBControlSync((ParmBlkPtr) & cdpb) != noErr) { + SDL_SetError("PBControlSync() failed"); + return (CD_ERROR); + } + + cdrom->numtracks = + SDL_SYS_BCDToShort(cdpb.csParam.bytes[1]) - + SDL_SYS_BCDToShort(cdpb.csParam.bytes[0]) + 1; + if (cdrom->numtracks > SDL_MAX_TRACKS) + cdrom->numtracks = SDL_MAX_TRACKS; + cdrom->cur_track = 0; /* Apparently these are set elsewhere */ + cdrom->cur_frame = 0; /* Apparently these are set elsewhere */ + + + if (1 || SDL_cdlist[cdrom->id].hasAudio) { + /* Get the current playback status */ + SDL_memset(&cdpb, 0, sizeof(cdpb)); + cdpb.ioVRefNum = SDL_cdlist[cdrom->id].driveNum; + cdpb.ioCRefNum = SDL_cdlist[cdrom->id].dRefNum; + cdpb.csCode = kAudioStatus; + if (PBControlSync((ParmBlkPtr) & cdpb) != noErr) { + SDL_SetError("PBControlSync() failed"); + return (-1); + } + + switch (cdpb.csParam.cd.status) { + case kStatusPlaying: + status = CD_PLAYING; + spinning = true; + break; + case kStatusPaused: + status = CD_PAUSED; + spinning = true; + break; + case kStatusMuted: + status = CD_PLAYING; /* What should I do here? */ + spinning = true; + break; + case kStatusDone: + status = CD_STOPPED; + spinning = true; + break; + case kStatusStopped: + status = CD_STOPPED; + spinning = false; + break; + case kStatusError: + default: + status = CD_ERROR; + spinning = false; + break; + } + + if (spinning && position) + *position = + MSF_TO_FRAMES(SDL_SYS_BCDToShort(cdpb.csParam.cd.minute), + SDL_SYS_BCDToShort(cdpb.csParam.cd.second), + SDL_SYS_BCDToShort(cdpb.csParam.cd.frame)); + } else + status = CD_ERROR; /* What should I do here? */ + + return (status); } /* Start play */ -static int SDL_SYS_CDPlay(SDL_CD *cdrom, int start, int length) +static int +SDL_SYS_CDPlay(SDL_CD * cdrom, int start, int length) { - CDCntrlParam cdpb; - - /* Pause the current audio playback to avoid audible artifacts */ - if ( SDL_SYS_CDPause(cdrom) < 0 ) { - return(-1); - } - - /* Specify the AudioCD playback mode */ - SDL_memset(&cdpb, 0, sizeof(cdpb)); - cdpb.ioVRefNum = SDL_cdlist[cdrom->id].driveNum; - cdpb.ioCRefNum = SDL_cdlist[cdrom->id].dRefNum; - cdpb.csCode = kSetPlayMode; - cdpb.csParam.bytes[0] = false; /* Repeat? */ - cdpb.csParam.bytes[1] = kPlayModeSequential; /* Play mode */ - /* ¥¥¥ÊTreat as soft error, NEC Drive doesnt support this call ¥¥¥ */ - PBControlSync((ParmBlkPtr) &cdpb); + CDCntrlParam cdpb; + + /* Pause the current audio playback to avoid audible artifacts */ + if (SDL_SYS_CDPause(cdrom) < 0) { + return (-1); + } + + /* Specify the AudioCD playback mode */ + SDL_memset(&cdpb, 0, sizeof(cdpb)); + cdpb.ioVRefNum = SDL_cdlist[cdrom->id].driveNum; + cdpb.ioCRefNum = SDL_cdlist[cdrom->id].dRefNum; + cdpb.csCode = kSetPlayMode; + cdpb.csParam.bytes[0] = false; /* Repeat? */ + cdpb.csParam.bytes[1] = kPlayModeSequential; /* Play mode */ + /* ¥¥¥ÊTreat as soft error, NEC Drive doesnt support this call ¥¥¥ */ + PBControlSync((ParmBlkPtr) & cdpb); #if 1 - /* Specify the end of audio playback */ - SDL_memset(&cdpb, 0, sizeof(cdpb)); - cdpb.ioVRefNum = SDL_cdlist[cdrom->id].driveNum; - cdpb.ioCRefNum = SDL_cdlist[cdrom->id].dRefNum; - cdpb.csCode = kAudioStop; - cdpb.csParam.words[0] = kBlockPosition; /* Position Mode */ - *(long *) (cdpb.csParam.words + 1) = start+length-1; /* Search Address */ - if ( PBControlSync((ParmBlkPtr)&cdpb) != noErr ) { - SDL_SetError("PBControlSync() failed"); - return(-1); - } - - /* Specify the start of audio playback, and start it */ - SDL_memset(&cdpb, 0, sizeof(cdpb)); - cdpb.ioVRefNum = SDL_cdlist[cdrom->id].driveNum; - cdpb.ioCRefNum = SDL_cdlist[cdrom->id].dRefNum; - cdpb.csCode = kAudioPlay; - cdpb.csParam.words[0] = kBlockPosition; /* Position Mode */ - *(long *) (cdpb.csParam.words + 1) = start+1; /* Search Address */ - cdpb.csParam.words[3] = false; /* Stop address? */ - cdpb.csParam.words[4] = kStereoPlayMode; /* Audio Play Mode */ - if ( PBControlSync((ParmBlkPtr)&cdpb) != noErr ) { - SDL_SetError("PBControlSync() failed"); - return(-1); - } + /* Specify the end of audio playback */ + SDL_memset(&cdpb, 0, sizeof(cdpb)); + cdpb.ioVRefNum = SDL_cdlist[cdrom->id].driveNum; + cdpb.ioCRefNum = SDL_cdlist[cdrom->id].dRefNum; + cdpb.csCode = kAudioStop; + cdpb.csParam.words[0] = kBlockPosition; /* Position Mode */ + *(long *) (cdpb.csParam.words + 1) = start + length - 1; /* Search Address */ + if (PBControlSync((ParmBlkPtr) & cdpb) != noErr) { + SDL_SetError("PBControlSync() failed"); + return (-1); + } + + /* Specify the start of audio playback, and start it */ + SDL_memset(&cdpb, 0, sizeof(cdpb)); + cdpb.ioVRefNum = SDL_cdlist[cdrom->id].driveNum; + cdpb.ioCRefNum = SDL_cdlist[cdrom->id].dRefNum; + cdpb.csCode = kAudioPlay; + cdpb.csParam.words[0] = kBlockPosition; /* Position Mode */ + *(long *) (cdpb.csParam.words + 1) = start + 1; /* Search Address */ + cdpb.csParam.words[3] = false; /* Stop address? */ + cdpb.csParam.words[4] = kStereoPlayMode; /* Audio Play Mode */ + if (PBControlSync((ParmBlkPtr) & cdpb) != noErr) { + SDL_SetError("PBControlSync() failed"); + return (-1); + } #else - /* Specify the end of audio playback */ - FRAMES_TO_MSF(start+length, &m, &s, &f); - SDL_memset(&cdpb, 0, sizeof(cdpb)); - cdpb.ioVRefNum = SDL_cdlist[cdrom->id].driveNum; - cdpb.ioCRefNum = SDL_cdlist[cdrom->id].dRefNum; - cdpb.csCode = kAudioStop; - cdpb.csParam.words[0] = kTrackPosition; /* Position Mode */ - cdpb.csParam.words[1] = 0; /* Search Address (hiword)*/ - cdpb.csParam.words[2] = /* Search Address (loword)*/ - SDL_SYS_ShortToBCD(cdrom->numtracks); - if ( PBControlSync((ParmBlkPtr)&cdpb) != noErr ) { - SDL_SetError("PBControlSync() failed"); - return(-1); - } - - /* Specify the start of audio playback, and start it */ - FRAMES_TO_MSF(start, &m, &s, &f); - SDL_memset(&cdpb, 0, sizeof(cdpb)); - cdpb.ioVRefNum = SDL_cdlist[cdrom->id].driveNum; - cdpb.ioCRefNum = SDL_cdlist[cdrom->id].dRefNum; - cdpb.csCode = kAudioPlay; - cdpb.csParam.words[0] = kTrackPosition; /* Position Mode */ - cdpb.csParam.words[1] = 0; /* Search Address (hiword)*/ - cdpb.csParam.words[2] = SDL_SYS_ShortToBCD(1); /* Search Address (loword)*/ - cdpb.csParam.words[3] = false; /* Stop address? */ - cdpb.csParam.words[4] = kStereoPlayMode; /* Audio Play Mode */ - if ( PBControlSync((ParmBlkPtr)&cdpb) != noErr ) { - SDL_SetError("PBControlSync() failed"); - return(-1); - } + /* Specify the end of audio playback */ + FRAMES_TO_MSF(start + length, &m, &s, &f); + SDL_memset(&cdpb, 0, sizeof(cdpb)); + cdpb.ioVRefNum = SDL_cdlist[cdrom->id].driveNum; + cdpb.ioCRefNum = SDL_cdlist[cdrom->id].dRefNum; + cdpb.csCode = kAudioStop; + cdpb.csParam.words[0] = kTrackPosition; /* Position Mode */ + cdpb.csParam.words[1] = 0; /* Search Address (hiword) */ + cdpb.csParam.words[2] = /* Search Address (loword) */ + SDL_SYS_ShortToBCD(cdrom->numtracks); + if (PBControlSync((ParmBlkPtr) & cdpb) != noErr) { + SDL_SetError("PBControlSync() failed"); + return (-1); + } + + /* Specify the start of audio playback, and start it */ + FRAMES_TO_MSF(start, &m, &s, &f); + SDL_memset(&cdpb, 0, sizeof(cdpb)); + cdpb.ioVRefNum = SDL_cdlist[cdrom->id].driveNum; + cdpb.ioCRefNum = SDL_cdlist[cdrom->id].dRefNum; + cdpb.csCode = kAudioPlay; + cdpb.csParam.words[0] = kTrackPosition; /* Position Mode */ + cdpb.csParam.words[1] = 0; /* Search Address (hiword) */ + cdpb.csParam.words[2] = SDL_SYS_ShortToBCD(1); /* Search Address (loword) */ + cdpb.csParam.words[3] = false; /* Stop address? */ + cdpb.csParam.words[4] = kStereoPlayMode; /* Audio Play Mode */ + if (PBControlSync((ParmBlkPtr) & cdpb) != noErr) { + SDL_SetError("PBControlSync() failed"); + return (-1); + } #endif - return(0); + return (0); } /* Pause play */ -static int SDL_SYS_CDPause(SDL_CD *cdrom) +static int +SDL_SYS_CDPause(SDL_CD * cdrom) { - CDCntrlParam cdpb; - - SDL_memset(&cdpb, 0, sizeof(cdpb)); - cdpb.ioVRefNum = SDL_cdlist[cdrom->id].driveNum; - cdpb.ioCRefNum = SDL_cdlist[cdrom->id].dRefNum; - cdpb.csCode = kAudioPause; - cdpb.csParam.words[0] = 0; /* Pause/Continue Flag (hiword) */ - cdpb.csParam.words[1] = 1; /* Pause/Continue Flag (loword) */ - if ( PBControlSync((ParmBlkPtr)&cdpb) != noErr ) { - SDL_SetError("PBControlSync() failed"); - return(-1); - } - return(0); + CDCntrlParam cdpb; + + SDL_memset(&cdpb, 0, sizeof(cdpb)); + cdpb.ioVRefNum = SDL_cdlist[cdrom->id].driveNum; + cdpb.ioCRefNum = SDL_cdlist[cdrom->id].dRefNum; + cdpb.csCode = kAudioPause; + cdpb.csParam.words[0] = 0; /* Pause/Continue Flag (hiword) */ + cdpb.csParam.words[1] = 1; /* Pause/Continue Flag (loword) */ + if (PBControlSync((ParmBlkPtr) & cdpb) != noErr) { + SDL_SetError("PBControlSync() failed"); + return (-1); + } + return (0); } /* Resume play */ -static int SDL_SYS_CDResume(SDL_CD *cdrom) +static int +SDL_SYS_CDResume(SDL_CD * cdrom) { - CDCntrlParam cdpb; - - SDL_memset(&cdpb, 0, sizeof(cdpb)); - cdpb.ioVRefNum = SDL_cdlist[cdrom->id].driveNum; - cdpb.ioCRefNum = SDL_cdlist[cdrom->id].dRefNum; - cdpb.csCode = kAudioPause; - cdpb.csParam.words[0] = 0; /* Pause/Continue Flag (hiword) */ - cdpb.csParam.words[1] = 0; /* Pause/Continue Flag (loword) */ - if ( PBControlSync((ParmBlkPtr)&cdpb) != noErr ) { - SDL_SetError("PBControlSync() failed"); - return(-1); - } - return(0); + CDCntrlParam cdpb; + + SDL_memset(&cdpb, 0, sizeof(cdpb)); + cdpb.ioVRefNum = SDL_cdlist[cdrom->id].driveNum; + cdpb.ioCRefNum = SDL_cdlist[cdrom->id].dRefNum; + cdpb.csCode = kAudioPause; + cdpb.csParam.words[0] = 0; /* Pause/Continue Flag (hiword) */ + cdpb.csParam.words[1] = 0; /* Pause/Continue Flag (loword) */ + if (PBControlSync((ParmBlkPtr) & cdpb) != noErr) { + SDL_SetError("PBControlSync() failed"); + return (-1); + } + return (0); } /* Stop play */ -static int SDL_SYS_CDStop(SDL_CD *cdrom) +static int +SDL_SYS_CDStop(SDL_CD * cdrom) { - CDCntrlParam cdpb; - - SDL_memset(&cdpb, 0, sizeof(cdpb)); - cdpb.ioVRefNum = SDL_cdlist[cdrom->id].driveNum; - cdpb.ioCRefNum = SDL_cdlist[cdrom->id].dRefNum; - cdpb.csCode = kAudioStop; - cdpb.csParam.words[0] = 0; /* Position Mode */ - cdpb.csParam.words[1] = 0; /* Search Address (hiword) */ - cdpb.csParam.words[2] = 0; /* Search Address (loword) */ - if ( PBControlSync((ParmBlkPtr)&cdpb) != noErr ) { - SDL_SetError("PBControlSync() failed"); - return(-1); - } - return(0); + CDCntrlParam cdpb; + + SDL_memset(&cdpb, 0, sizeof(cdpb)); + cdpb.ioVRefNum = SDL_cdlist[cdrom->id].driveNum; + cdpb.ioCRefNum = SDL_cdlist[cdrom->id].dRefNum; + cdpb.csCode = kAudioStop; + cdpb.csParam.words[0] = 0; /* Position Mode */ + cdpb.csParam.words[1] = 0; /* Search Address (hiword) */ + cdpb.csParam.words[2] = 0; /* Search Address (loword) */ + if (PBControlSync((ParmBlkPtr) & cdpb) != noErr) { + SDL_SetError("PBControlSync() failed"); + return (-1); + } + return (0); } /* Eject the CD-ROM */ -static int SDL_SYS_CDEject(SDL_CD *cdrom) +static int +SDL_SYS_CDEject(SDL_CD * cdrom) { - Boolean disk = false; - QHdr *driveQ = GetDrvQHdr(); - DrvQEl *driveElem; - HParamBlockRec hpb; - ParamBlockRec cpb; - - for ( driveElem = (DrvQEl *) driveQ->qHead; driveElem; driveElem = - (driveElem) ? ((DrvQEl *) driveElem->qLink) : - ((DrvQEl *) driveQ->qHead) ) { - if ( driveQ->qTail ) { - driveQ->qTail->qLink = 0; - } - if ( driveElem->dQRefNum != SDL_cdlist[cdrom->id].dRefNum ) { - continue; - } - - /* Does drive contain mounted volume? If not, skip */ - SDL_memset(&hpb, 0, sizeof(hpb)); - hpb.volumeParam.ioVRefNum = driveElem->dQDrive; - if ( PBHGetVInfoSync(&hpb) != noErr ) { - continue; - } - if ( (UnmountVol(0, driveElem->dQDrive) == noErr) && - (Eject(0, driveElem->dQDrive) == noErr) ) { - driveElem = 0; /* Clear pointer to reset our loop */ - disk = true; - } - } - - /* If no disk is present, just eject the tray */ - if (! disk) { - SDL_memset(&cpb, 0, sizeof(cpb)); - cpb.cntrlParam.ioVRefNum = 0; /* No Drive */ - cpb.cntrlParam.ioCRefNum = SDL_cdlist[cdrom->id].dRefNum; - cpb.cntrlParam.csCode = kEjectTheDisc; - if ( PBControlSync((ParmBlkPtr)&cpb) != noErr ) { - SDL_SetError("PBControlSync() failed"); - return(-1); - } - } - return(0); + Boolean disk = false; + QHdr *driveQ = GetDrvQHdr(); + DrvQEl *driveElem; + HParamBlockRec hpb; + ParamBlockRec cpb; + + for (driveElem = (DrvQEl *) driveQ->qHead; driveElem; driveElem = + (driveElem) ? ((DrvQEl *) driveElem->qLink) : + ((DrvQEl *) driveQ->qHead)) { + if (driveQ->qTail) { + driveQ->qTail->qLink = 0; + } + if (driveElem->dQRefNum != SDL_cdlist[cdrom->id].dRefNum) { + continue; + } + + /* Does drive contain mounted volume? If not, skip */ + SDL_memset(&hpb, 0, sizeof(hpb)); + hpb.volumeParam.ioVRefNum = driveElem->dQDrive; + if (PBHGetVInfoSync(&hpb) != noErr) { + continue; + } + if ((UnmountVol(0, driveElem->dQDrive) == noErr) && + (Eject(0, driveElem->dQDrive) == noErr)) { + driveElem = 0; /* Clear pointer to reset our loop */ + disk = true; + } + } + + /* If no disk is present, just eject the tray */ + if (!disk) { + SDL_memset(&cpb, 0, sizeof(cpb)); + cpb.cntrlParam.ioVRefNum = 0; /* No Drive */ + cpb.cntrlParam.ioCRefNum = SDL_cdlist[cdrom->id].dRefNum; + cpb.cntrlParam.csCode = kEjectTheDisc; + if (PBControlSync((ParmBlkPtr) & cpb) != noErr) { + SDL_SetError("PBControlSync() failed"); + return (-1); + } + } + return (0); } /* Close the CD-ROM handle */ -static void SDL_SYS_CDClose(SDL_CD *cdrom) +static void +SDL_SYS_CDClose(SDL_CD * cdrom) { - return; + return; } -void SDL_SYS_CDQuit(void) +void +SDL_SYS_CDQuit(void) { - while(SDL_numcds--) - SDL_memset(SDL_cdlist + SDL_numcds, 0, sizeof(SDL_cdlist[0])); + while (SDL_numcds--) + SDL_memset(SDL_cdlist + SDL_numcds, 0, sizeof(SDL_cdlist[0])); } #endif /* SDL_CDROM_MACOS */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/cdrom/macos/SDL_syscdrom_c.h b/src/cdrom/macos/SDL_syscdrom_c.h index 835826e27..07ea54d80 100644 --- a/src/cdrom/macos/SDL_syscdrom_c.h +++ b/src/cdrom/macos/SDL_syscdrom_c.h @@ -26,55 +26,55 @@ */ /* AppleCD Control calls */ -#define kVerifyTheDisc 5 /* Returns noErr if there is disc inserted */ -#define kEjectTheDisc 7 /* Eject disc from drive */ -#define kUserEject 80 /* Enable/disable the CD-ROM eject button */ -#define kReadTOC 100 /* Extract various TOC information from the disc */ -#define kReadQ 101 /* Extract Q subcode info for the current track */ -#define kAudioTrackSearch 103 /* Start playback from the indicated position */ -#define kAudioPlay 104 /* Start playback from the indicated position */ -#define kAudioPause 105 /* Pause/continue the playback */ -#define kAudioStop 106 /* Stop playback at the indicated position */ -#define kAudioStatus 107 /* Return audio play status */ -#define kAudioControl 109 /* Set the output volume for the audio channels */ -#define kReadAudioVolume 112 /* Get the output volume for the audio channels */ -#define kSetTrackList 122 /* Set the track program for the audio CD to play */ -#define kGetTrackList 123 /* Get the track program the audio CD is playing */ -#define kGetTrackIndex 124 /* Get the track index the audio CD is playing */ -#define kSetPlayMode 125 /* Set the audio tracks play mode */ -#define kGetPlayMode 126 /* Get the audio tracks play mode */ +#define kVerifyTheDisc 5 /* Returns noErr if there is disc inserted */ +#define kEjectTheDisc 7 /* Eject disc from drive */ +#define kUserEject 80 /* Enable/disable the CD-ROM eject button */ +#define kReadTOC 100 /* Extract various TOC information from the disc */ +#define kReadQ 101 /* Extract Q subcode info for the current track */ +#define kAudioTrackSearch 103 /* Start playback from the indicated position */ +#define kAudioPlay 104 /* Start playback from the indicated position */ +#define kAudioPause 105 /* Pause/continue the playback */ +#define kAudioStop 106 /* Stop playback at the indicated position */ +#define kAudioStatus 107 /* Return audio play status */ +#define kAudioControl 109 /* Set the output volume for the audio channels */ +#define kReadAudioVolume 112 /* Get the output volume for the audio channels */ +#define kSetTrackList 122 /* Set the track program for the audio CD to play */ +#define kGetTrackList 123 /* Get the track program the audio CD is playing */ +#define kGetTrackIndex 124 /* Get the track index the audio CD is playing */ +#define kSetPlayMode 125 /* Set the audio tracks play mode */ +#define kGetPlayMode 126 /* Get the audio tracks play mode */ /* AppleCD Status calls */ -#define kGetDriveType 96 /* Get the type of the physical CD-ROM drive */ -#define kWhoIsThere 97 /* Get a bitmap of SCSI IDs the driver controls */ -#define kGetBlockSize 98 /* Get current block size of the CD-ROM drive */ - +#define kGetDriveType 96 /* Get the type of the physical CD-ROM drive */ +#define kWhoIsThere 97 /* Get a bitmap of SCSI IDs the driver controls */ +#define kGetBlockSize 98 /* Get current block size of the CD-ROM drive */ + /* AppleCD other constants */ -#define kBlockPosition 0 /* Position at the specified logical block number */ -#define kAbsMSFPosition 1 /* Position at the specified Min/Sec/Frame (in BCD) */ -#define kTrackPosition 2 /* Position at the specified track number (in BCD) */ -#define kIndexPosition 3 /* Position at the nth track in program (in BCD) */ +#define kBlockPosition 0 /* Position at the specified logical block number */ +#define kAbsMSFPosition 1 /* Position at the specified Min/Sec/Frame (in BCD) */ +#define kTrackPosition 2 /* Position at the specified track number (in BCD) */ +#define kIndexPosition 3 /* Position at the nth track in program (in BCD) */ -#define kMutedPlayMode 0 /* Play the audio track with no output */ -#define kStereoPlayMode 9 /* Play the audio track in normal stereo */ +#define kMutedPlayMode 0 /* Play the audio track with no output */ +#define kStereoPlayMode 9 /* Play the audio track in normal stereo */ -#define kControlFieldMask 0x0D /* Bits 3,2,0 in the nibble */ -#define kDataTrackMask 0x04 /* Indicates Data Track */ +#define kControlFieldMask 0x0D /* Bits 3,2,0 in the nibble */ +#define kDataTrackMask 0x04 /* Indicates Data Track */ -#define kGetTrackRange 1 /* Query TOC for track numbers */ -#define kGetLeadOutArea 2 /* Query TOC for "Lead Out" end of audio data */ -#define kGetTrackEntries 3 /* Query TOC for track starts and data types */ +#define kGetTrackRange 1 /* Query TOC for track numbers */ +#define kGetLeadOutArea 2 /* Query TOC for "Lead Out" end of audio data */ +#define kGetTrackEntries 3 /* Query TOC for track starts and data types */ -#define kStatusPlaying 0 /* Audio Play operation in progress */ -#define kStatusPaused 1 /* CD-ROM device in Hold Track ("Pause") state */ -#define kStatusMuted 2 /* MUTING-ON operation in progress */ -#define kStatusDone 3 /* Audio Play completed */ -#define kStatusError 4 /* Error occurred during audio play operation */ -#define kStatusStopped 5 /* Audio play operation not requested */ +#define kStatusPlaying 0 /* Audio Play operation in progress */ +#define kStatusPaused 1 /* CD-ROM device in Hold Track ("Pause") state */ +#define kStatusMuted 2 /* MUTING-ON operation in progress */ +#define kStatusDone 3 /* Audio Play completed */ +#define kStatusError 4 /* Error occurred during audio play operation */ +#define kStatusStopped 5 /* Audio play operation not requested */ -#define kPlayModeSequential 0 /* Play tracks in order */ -#define kPlayModeShuffled 1 /* Play tracks randomly */ -#define kPlayModeProgrammed 2 /* Use custom playlist */ +#define kPlayModeSequential 0 /* Play tracks in order */ +#define kPlayModeShuffled 1 /* Play tracks randomly */ +#define kPlayModeProgrammed 2 /* Use custom playlist */ /* AppleCD Gestalt selectors */ #define kGestaltAudioCDSelector 'aucd' @@ -92,49 +92,55 @@ #define kLastSCSIDevice -40 #if PRAGMA_STRUCT_ALIGN - #pragma options align=mac68k +#pragma options align=mac68k #endif /* AppleCD driver parameter block */ -typedef struct CDCntrlParam { - QElemPtr qLink; - short qType; - short ioTrap; - Ptr ioCmdAddr; - IOCompletionUPP ioCompletion; - OSErr ioResult; - StringPtr ioNamePtr; - short ioVRefNum; - short ioCRefNum; - short csCode; - - union { - long longs[6]; - short words[11]; - unsigned char bytes[22]; - struct { - unsigned char status; - unsigned char play; - unsigned char control; - unsigned char minute; - unsigned char second; - unsigned char frame; - } cd; - } csParam; - - } CDCntrlParam, *CDCntrlParamPtr; - -typedef union CDTrackData { - long value; /* Treat as a longword value */ - struct { - unsigned char reserved : 4; /* Unused by AppleCD driver */ - unsigned char control : 4; /* Track flags (data track?) */ - unsigned char min; /* Start of track (BCD) */ - unsigned char sec; /* Start of track (BCD) */ - unsigned char frame; /* Start of track (BCD) */ - } entry; /* Broken into fields */ - } CDTrackData, *CDTrackPtr; - +typedef struct CDCntrlParam +{ + QElemPtr qLink; + short qType; + short ioTrap; + Ptr ioCmdAddr; + IOCompletionUPP ioCompletion; + OSErr ioResult; + StringPtr ioNamePtr; + short ioVRefNum; + short ioCRefNum; + short csCode; + + union + { + long longs[6]; + short words[11]; + unsigned char bytes[22]; + struct + { + unsigned char status; + unsigned char play; + unsigned char control; + unsigned char minute; + unsigned char second; + unsigned char frame; + } cd; + } csParam; + +} CDCntrlParam, *CDCntrlParamPtr; + +typedef union CDTrackData +{ + long value; /* Treat as a longword value */ + struct + { + unsigned char reserved:4; /* Unused by AppleCD driver */ + unsigned char control:4; /* Track flags (data track?) */ + unsigned char min; /* Start of track (BCD) */ + unsigned char sec; /* Start of track (BCD) */ + unsigned char frame; /* Start of track (BCD) */ + } entry; /* Broken into fields */ +} CDTrackData, *CDTrackPtr; + #if PRAGMA_STRUCT_ALIGN - #pragma options align=reset +#pragma options align=reset #endif +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/cdrom/macosx/AudioFilePlayer.c b/src/cdrom/macosx/AudioFilePlayer.c index 333eb0c1c..569baf4ea 100644 --- a/src/cdrom/macosx/AudioFilePlayer.c +++ b/src/cdrom/macosx/AudioFilePlayer.c @@ -38,135 +38,151 @@ void ThrowResult (OSStatus result, const char* str) */ #if DEBUG -static void PrintStreamDesc (AudioStreamBasicDescription *inDesc) +static void +PrintStreamDesc(AudioStreamBasicDescription * inDesc) { if (!inDesc) { - printf ("Can't print a NULL desc!\n"); + printf("Can't print a NULL desc!\n"); return; } - - printf ("- - - - - - - - - - - - - - - - - - - -\n"); - printf (" Sample Rate:%f\n", inDesc->mSampleRate); - printf (" Format ID:%s\n", (char*)&inDesc->mFormatID); - printf (" Format Flags:%lX\n", inDesc->mFormatFlags); - printf (" Bytes per Packet:%ld\n", inDesc->mBytesPerPacket); - printf (" Frames per Packet:%ld\n", inDesc->mFramesPerPacket); - printf (" Bytes per Frame:%ld\n", inDesc->mBytesPerFrame); - printf (" Channels per Frame:%ld\n", inDesc->mChannelsPerFrame); - printf (" Bits per Channel:%ld\n", inDesc->mBitsPerChannel); - printf ("- - - - - - - - - - - - - - - - - - - -\n"); + + printf("- - - - - - - - - - - - - - - - - - - -\n"); + printf(" Sample Rate:%f\n", inDesc->mSampleRate); + printf(" Format ID:%s\n", (char *) &inDesc->mFormatID); + printf(" Format Flags:%lX\n", inDesc->mFormatFlags); + printf(" Bytes per Packet:%ld\n", inDesc->mBytesPerPacket); + printf(" Frames per Packet:%ld\n", inDesc->mFramesPerPacket); + printf(" Bytes per Frame:%ld\n", inDesc->mBytesPerFrame); + printf(" Channels per Frame:%ld\n", inDesc->mChannelsPerFrame); + printf(" Bits per Channel:%ld\n", inDesc->mBitsPerChannel); + printf("- - - - - - - - - - - - - - - - - - - -\n"); } #endif -static int AudioFilePlayer_SetDestination (AudioFilePlayer *afp, AudioUnit *inDestUnit) +static int +AudioFilePlayer_SetDestination(AudioFilePlayer * afp, AudioUnit * inDestUnit) { - /*if (afp->mConnected) throw static_cast(-1);*/ /* can't set dest if already engaged */ + /*if (afp->mConnected) throw static_cast(-1); *//* can't set dest if already engaged */ if (afp->mConnected) - return 0 ; + return 0; - SDL_memcpy(&afp->mPlayUnit, inDestUnit, sizeof (afp->mPlayUnit)); + SDL_memcpy(&afp->mPlayUnit, inDestUnit, sizeof(afp->mPlayUnit)); OSStatus result = noErr; - - /* we can "down" cast a component instance to a component */ + + /* we can "down" cast a component instance to a component */ ComponentDescription desc; - result = GetComponentInfo ((Component)*inDestUnit, &desc, 0, 0, 0); - if (result) return 0; /*THROW_RESULT("GetComponentInfo")*/ - - /* we're going to use this to know which convert routine to call - a v1 audio unit will have a type of 'aunt' - a v2 audio unit will have one of several different types. */ + result = GetComponentInfo((Component) * inDestUnit, &desc, 0, 0, 0); + if (result) + return 0; /*THROW_RESULT("GetComponentInfo") */ + + /* we're going to use this to know which convert routine to call + a v1 audio unit will have a type of 'aunt' + a v2 audio unit will have one of several different types. */ if (desc.componentType != kAudioUnitComponentType) { result = badComponentInstance; - /*THROW_RESULT("BAD COMPONENT")*/ - if (result) return 0; + /*THROW_RESULT("BAD COMPONENT") */ + if (result) + return 0; } /* Set the input format of the audio unit. */ - result = AudioUnitSetProperty (*inDestUnit, - kAudioUnitProperty_StreamFormat, - kAudioUnitScope_Input, - 0, - &afp->mFileDescription, - sizeof (afp->mFileDescription)); - /*THROW_RESULT("AudioUnitSetProperty")*/ - if (result) return 0; + result = AudioUnitSetProperty(*inDestUnit, + kAudioUnitProperty_StreamFormat, + kAudioUnitScope_Input, + 0, + &afp->mFileDescription, + sizeof(afp->mFileDescription)); + /*THROW_RESULT("AudioUnitSetProperty") */ + if (result) + return 0; return 1; } -static void AudioFilePlayer_SetNotifier(AudioFilePlayer *afp, AudioFilePlayNotifier inNotifier, void *inRefCon) +static void +AudioFilePlayer_SetNotifier(AudioFilePlayer * afp, + AudioFilePlayNotifier inNotifier, void *inRefCon) { afp->mNotifier = inNotifier; afp->mRefCon = inRefCon; } -static int AudioFilePlayer_IsConnected(AudioFilePlayer *afp) +static int +AudioFilePlayer_IsConnected(AudioFilePlayer * afp) { return afp->mConnected; } -static AudioUnit AudioFilePlayer_GetDestUnit(AudioFilePlayer *afp) +static AudioUnit +AudioFilePlayer_GetDestUnit(AudioFilePlayer * afp) { - return afp->mPlayUnit; + return afp->mPlayUnit; } -static void AudioFilePlayer_Print(AudioFilePlayer *afp) +static void +AudioFilePlayer_Print(AudioFilePlayer * afp) { -#if DEBUG - printf ("Is Connected:%s\n", (IsConnected() ? "true" : "false")); - printf ("- - - - - - - - - - - - - - \n"); +#if DEBUG + printf("Is Connected:%s\n", (IsConnected()? "true" : "false")); + printf("- - - - - - - - - - - - - - \n"); #endif } -static void AudioFilePlayer_SetStartFrame (AudioFilePlayer *afp, int frame) +static void +AudioFilePlayer_SetStartFrame(AudioFilePlayer * afp, int frame) { SInt64 position = frame * 2352; afp->mStartFrame = frame; - afp->mAudioFileManager->SetPosition (afp->mAudioFileManager, position); + afp->mAudioFileManager->SetPosition(afp->mAudioFileManager, position); } - -static int AudioFilePlayer_GetCurrentFrame (AudioFilePlayer *afp) + +static int +AudioFilePlayer_GetCurrentFrame(AudioFilePlayer * afp) { - return afp->mStartFrame + (afp->mAudioFileManager->GetByteCounter(afp->mAudioFileManager) / 2352); + return afp->mStartFrame + + (afp->mAudioFileManager->GetByteCounter(afp->mAudioFileManager) / + 2352); } - -static void AudioFilePlayer_SetStopFrame (AudioFilePlayer *afp, int frame) + +static void +AudioFilePlayer_SetStopFrame(AudioFilePlayer * afp, int frame) { - SInt64 position = frame * 2352; - - afp->mAudioFileManager->SetEndOfFile (afp->mAudioFileManager, position); + SInt64 position = frame * 2352; + + afp->mAudioFileManager->SetEndOfFile(afp->mAudioFileManager, position); } - -void delete_AudioFilePlayer(AudioFilePlayer *afp) + +void +delete_AudioFilePlayer(AudioFilePlayer * afp) { - if (afp != NULL) - { + if (afp != NULL) { afp->Disconnect(afp); - + if (afp->mAudioFileManager) { delete_AudioFileManager(afp->mAudioFileManager); afp->mAudioFileManager = 0; } - + if (afp->mForkRefNum) { - FSCloseFork (afp->mForkRefNum); + FSCloseFork(afp->mForkRefNum); afp->mForkRefNum = 0; } SDL_free(afp); } } -static int AudioFilePlayer_Connect(AudioFilePlayer *afp) +static int +AudioFilePlayer_Connect(AudioFilePlayer * afp) { #if DEBUG - printf ("Connect:%x, engaged=%d\n", (int)afp->mPlayUnit, (afp->mConnected ? 1 : 0)); + printf("Connect:%x, engaged=%d\n", (int) afp->mPlayUnit, + (afp->mConnected ? 1 : 0)); #endif - if (!afp->mConnected) - { + if (!afp->mConnected) { if (!afp->mAudioFileManager->DoConnect(afp->mAudioFileManager)) return 0; @@ -174,13 +190,14 @@ static int AudioFilePlayer_Connect(AudioFilePlayer *afp) afp->mInputCallback.inputProc = afp->mAudioFileManager->FileInputProc; afp->mInputCallback.inputProcRefCon = afp->mAudioFileManager; - OSStatus result = AudioUnitSetProperty (afp->mPlayUnit, - kAudioUnitProperty_SetInputCallback, - kAudioUnitScope_Input, - 0, - &afp->mInputCallback, - sizeof(afp->mInputCallback)); - if (result) return 0; /*THROW_RESULT("AudioUnitSetProperty")*/ + OSStatus result = AudioUnitSetProperty(afp->mPlayUnit, + kAudioUnitProperty_SetInputCallback, + kAudioUnitScope_Input, + 0, + &afp->mInputCallback, + sizeof(afp->mInputCallback)); + if (result) + return 0; /*THROW_RESULT("AudioUnitSetProperty") */ afp->mConnected = 1; } @@ -189,13 +206,14 @@ static int AudioFilePlayer_Connect(AudioFilePlayer *afp) /* warning noted, now please go away ;-) */ /* #warning This should redirect the calling of notification code to some other thread */ -static void AudioFilePlayer_DoNotification (AudioFilePlayer *afp, OSStatus inStatus) +static void +AudioFilePlayer_DoNotification(AudioFilePlayer * afp, OSStatus inStatus) { if (afp->mNotifier) { (*afp->mNotifier) (afp->mRefCon, inStatus); } else { - SDL_SetError ("Notification posted with no notifier in place"); - + SDL_SetError("Notification posted with no notifier in place"); + if (inStatus == kAudioFilePlay_FileIsFinished) afp->Disconnect(afp); else if (inStatus != kAudioFilePlayErr_FilePlayUnderrun) @@ -203,36 +221,41 @@ static void AudioFilePlayer_DoNotification (AudioFilePlayer *afp, OSStatus in } } -static void AudioFilePlayer_Disconnect (AudioFilePlayer *afp) +static void +AudioFilePlayer_Disconnect(AudioFilePlayer * afp) { #if DEBUG - printf ("Disconnect:%x,%ld, engaged=%d\n", (int)afp->mPlayUnit, 0, (afp->mConnected ? 1 : 0)); + printf("Disconnect:%x,%ld, engaged=%d\n", (int) afp->mPlayUnit, 0, + (afp->mConnected ? 1 : 0)); #endif - if (afp->mConnected) - { + if (afp->mConnected) { afp->mConnected = 0; - + afp->mInputCallback.inputProc = 0; afp->mInputCallback.inputProcRefCon = 0; - OSStatus result = AudioUnitSetProperty (afp->mPlayUnit, - kAudioUnitProperty_SetInputCallback, - kAudioUnitScope_Input, - 0, - &afp->mInputCallback, - sizeof(afp->mInputCallback)); - if (result) - SDL_SetError ("AudioUnitSetProperty:RemoveInputCallback:%ld", result); + OSStatus result = AudioUnitSetProperty(afp->mPlayUnit, + kAudioUnitProperty_SetInputCallback, + kAudioUnitScope_Input, + 0, + &afp->mInputCallback, + sizeof(afp->mInputCallback)); + if (result) + SDL_SetError("AudioUnitSetProperty:RemoveInputCallback:%ld", + result); afp->mAudioFileManager->Disconnect(afp->mAudioFileManager); } } -typedef struct { +typedef struct +{ UInt32 offset; UInt32 blockSize; } SSNDData; -static int AudioFilePlayer_OpenFile (AudioFilePlayer *afp, const FSRef *inRef, SInt64 *outFileDataSize) +static int +AudioFilePlayer_OpenFile(AudioFilePlayer * afp, const FSRef * inRef, + SInt64 * outFileDataSize) { ContainerChunk chunkHeader; ChunkHeader chunk; @@ -245,46 +268,63 @@ static int AudioFilePlayer_OpenFile (AudioFilePlayer *afp, const FSRef *inRef /* Open the data fork of the input file */ result = FSGetDataForkName(&dfName); - if (result) return 0; /*THROW_RESULT("AudioFilePlayer::OpenFile(): FSGetDataForkName")*/ + if (result) + return 0; /*THROW_RESULT("AudioFilePlayer::OpenFile(): FSGetDataForkName") */ + + result = + FSOpenFork(inRef, dfName.length, dfName.unicode, fsRdPerm, + &afp->mForkRefNum); + if (result) + return 0; /*THROW_RESULT("AudioFilePlayer::OpenFile(): FSOpenFork") */ - result = FSOpenFork(inRef, dfName.length, dfName.unicode, fsRdPerm, &afp->mForkRefNum); - if (result) return 0; /*THROW_RESULT("AudioFilePlayer::OpenFile(): FSOpenFork")*/ - /* Read the file header, and check if it's indeed an AIFC file */ - result = FSReadFork(afp->mForkRefNum, fsAtMark, 0, sizeof(chunkHeader), &chunkHeader, &actual); - if (result) return 0; /*THROW_RESULT("AudioFilePlayer::OpenFile(): FSReadFork")*/ + result = + FSReadFork(afp->mForkRefNum, fsAtMark, 0, sizeof(chunkHeader), + &chunkHeader, &actual); + if (result) + return 0; /*THROW_RESULT("AudioFilePlayer::OpenFile(): FSReadFork") */ if (chunkHeader.ckID != 'FORM') { result = -1; - if (result) return 0; /*THROW_RESULT("AudioFilePlayer::OpenFile(): chunk id is not 'FORM'");*/ + if (result) + return 0; /*THROW_RESULT("AudioFilePlayer::OpenFile(): chunk id is not 'FORM'"); */ } if (chunkHeader.formType != 'AIFC') { result = -1; - if (result) return 0; /*THROW_RESULT("AudioFilePlayer::OpenFile(): file format is not 'AIFC'");*/ + if (result) + return 0; /*THROW_RESULT("AudioFilePlayer::OpenFile(): file format is not 'AIFC'"); */ } /* Search for the SSND chunk. We ignore all compression etc. information in other chunks. Of course that is kind of evil, but for now we are lazy and rely on the cdfs to always give us the same fixed format. TODO: Parse the COMM chunk we currently skip to fill in mFileDescription. - */ + */ offset = 0; do { - result = FSReadFork(afp->mForkRefNum, fsFromMark, offset, sizeof(chunk), &chunk, &actual); - if (result) return 0; /*THROW_RESULT("AudioFilePlayer::OpenFile(): FSReadFork")*/ - + result = + FSReadFork(afp->mForkRefNum, fsFromMark, offset, + sizeof(chunk), &chunk, &actual); + if (result) + return 0; /*THROW_RESULT("AudioFilePlayer::OpenFile(): FSReadFork") */ + /* Skip the chunk data */ offset = chunk.ckSize; - } while (chunk.ckID != 'SSND'); + } + while (chunk.ckID != 'SSND'); /* Read the header of the SSND chunk. After this, we are positioned right at the start of the audio data. */ - result = FSReadFork(afp->mForkRefNum, fsAtMark, 0, sizeof(ssndData), &ssndData, &actual); - if (result) return 0; /*THROW_RESULT("AudioFilePlayer::OpenFile(): FSReadFork")*/ + result = + FSReadFork(afp->mForkRefNum, fsAtMark, 0, sizeof(ssndData), + &ssndData, &actual); + if (result) + return 0; /*THROW_RESULT("AudioFilePlayer::OpenFile(): FSReadFork") */ result = FSSetForkPosition(afp->mForkRefNum, fsFromMark, ssndData.offset); - if (result) return 0; /*THROW_RESULT("AudioFilePlayer::OpenFile(): FSSetForkPosition")*/ + if (result) + return 0; /*THROW_RESULT("AudioFilePlayer::OpenFile(): FSSetForkPosition") */ /* Data size */ *outFileDataSize = chunk.ckSize - ssndData.offset - 8; @@ -292,7 +332,8 @@ static int AudioFilePlayer_OpenFile (AudioFilePlayer *afp, const FSRef *inRef /* File format */ afp->mFileDescription.mSampleRate = 44100; afp->mFileDescription.mFormatID = kAudioFormatLinearPCM; - afp->mFileDescription.mFormatFlags = kLinearPCMFormatFlagIsPacked | kLinearPCMFormatFlagIsSignedInteger; + afp->mFileDescription.mFormatFlags = + kLinearPCMFormatFlagIsPacked | kLinearPCMFormatFlagIsSignedInteger; afp->mFileDescription.mBytesPerPacket = 4; afp->mFileDescription.mFramesPerPacket = 1; afp->mFileDescription.mBytesPerFrame = 4; @@ -302,16 +343,18 @@ static int AudioFilePlayer_OpenFile (AudioFilePlayer *afp, const FSRef *inRef return 1; } -AudioFilePlayer *new_AudioFilePlayer (const FSRef *inFileRef) +AudioFilePlayer * +new_AudioFilePlayer(const FSRef * inFileRef) { - SInt64 fileDataSize = 0; + SInt64 fileDataSize = 0; - AudioFilePlayer *afp = (AudioFilePlayer *) SDL_malloc(sizeof (AudioFilePlayer)); + AudioFilePlayer *afp = + (AudioFilePlayer *) SDL_malloc(sizeof(AudioFilePlayer)); if (afp == NULL) return NULL; - SDL_memset(afp, '\0', sizeof (*afp)); + SDL_memset(afp, '\0', sizeof(*afp)); - #define SET_AUDIOFILEPLAYER_METHOD(m) afp->m = AudioFilePlayer_##m +#define SET_AUDIOFILEPLAYER_METHOD(m) afp->m = AudioFilePlayer_##m SET_AUDIOFILEPLAYER_METHOD(SetDestination); SET_AUDIOFILEPLAYER_METHOD(SetNotifier); SET_AUDIOFILEPLAYER_METHOD(SetStartFrame); @@ -324,27 +367,27 @@ AudioFilePlayer *new_AudioFilePlayer (const FSRef *inFileRef) SET_AUDIOFILEPLAYER_METHOD(GetDestUnit); SET_AUDIOFILEPLAYER_METHOD(Print); SET_AUDIOFILEPLAYER_METHOD(OpenFile); - #undef SET_AUDIOFILEPLAYER_METHOD +#undef SET_AUDIOFILEPLAYER_METHOD - if (!afp->OpenFile (afp, inFileRef, &fileDataSize)) - { + if (!afp->OpenFile(afp, inFileRef, &fileDataSize)) { SDL_free(afp); return NULL; } - + /* we want about 4 seconds worth of data for the buffer */ - int bytesPerSecond = (UInt32) (4 * afp->mFileDescription.mSampleRate * afp->mFileDescription.mBytesPerFrame); - + int bytesPerSecond = + (UInt32) (4 * afp->mFileDescription.mSampleRate * + afp->mFileDescription.mBytesPerFrame); + #if DEBUG printf("File format:\n"); - PrintStreamDesc (&afp->mFileDescription); + PrintStreamDesc(&afp->mFileDescription); #endif - + afp->mAudioFileManager = new_AudioFileManager(afp, afp->mForkRefNum, fileDataSize, bytesPerSecond); - if (afp->mAudioFileManager == NULL) - { + if (afp->mAudioFileManager == NULL) { delete_AudioFilePlayer(afp); return NULL; } @@ -352,3 +395,4 @@ AudioFilePlayer *new_AudioFilePlayer (const FSRef *inFileRef) return afp; } +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/cdrom/macosx/AudioFilePlayer.h b/src/cdrom/macosx/AudioFilePlayer.h index 1d7eb19d4..5916bdb08 100644 --- a/src/cdrom/macosx/AudioFilePlayer.h +++ b/src/cdrom/macosx/AudioFilePlayer.h @@ -36,7 +36,7 @@ #include "SDL_error.h" -const char* AudioFilePlayerErrorStr (OSStatus error); +const char *AudioFilePlayerErrorStr(OSStatus error); /* void ThrowResult (OSStatus result, const char *str); @@ -47,10 +47,10 @@ void ThrowResult (OSStatus result, const char *str); } */ -typedef void (*AudioFilePlayNotifier)(void *inRefCon, - OSStatus inStatus); +typedef void (*AudioFilePlayNotifier) (void *inRefCon, OSStatus inStatus); -enum { +enum +{ kAudioFilePlayErr_FilePlayUnderrun = -10000, kAudioFilePlay_FileIsFinished = -10001, kAudioFilePlay_PlayerIsUninitialized = -10002 @@ -63,43 +63,46 @@ struct S_AudioFileManager; typedef struct S_AudioFilePlayer { /*public:*/ - int (*SetDestination)(struct S_AudioFilePlayer *afp, AudioUnit *inDestUnit); - void (*SetNotifier)(struct S_AudioFilePlayer *afp, AudioFilePlayNotifier inNotifier, void *inRefCon); - void (*SetStartFrame)(struct S_AudioFilePlayer *afp, int frame); /* seek in the file */ - int (*GetCurrentFrame)(struct S_AudioFilePlayer *afp); /* get the current frame position */ - void (*SetStopFrame)(struct S_AudioFilePlayer *afp, int frame); /* set limit in the file */ - int (*Connect)(struct S_AudioFilePlayer *afp); - void (*Disconnect)(struct S_AudioFilePlayer *afp); - void (*DoNotification)(struct S_AudioFilePlayer *afp, OSStatus inError); - int (*IsConnected)(struct S_AudioFilePlayer *afp); - AudioUnit (*GetDestUnit)(struct S_AudioFilePlayer *afp); - void (*Print)(struct S_AudioFilePlayer *afp); + int (*SetDestination) (struct S_AudioFilePlayer * afp, + AudioUnit * inDestUnit); + void (*SetNotifier) (struct S_AudioFilePlayer * afp, + AudioFilePlayNotifier inNotifier, void *inRefCon); + void (*SetStartFrame) (struct S_AudioFilePlayer * afp, int frame); /* seek in the file */ + int (*GetCurrentFrame) (struct S_AudioFilePlayer * afp); /* get the current frame position */ + void (*SetStopFrame) (struct S_AudioFilePlayer * afp, int frame); /* set limit in the file */ + int (*Connect) (struct S_AudioFilePlayer * afp); + void (*Disconnect) (struct S_AudioFilePlayer * afp); + void (*DoNotification) (struct S_AudioFilePlayer * afp, OSStatus inError); + int (*IsConnected) (struct S_AudioFilePlayer * afp); + AudioUnit(*GetDestUnit) (struct S_AudioFilePlayer * afp); + void (*Print) (struct S_AudioFilePlayer * afp); /*private:*/ - AudioUnit mPlayUnit; - SInt16 mForkRefNum; - - AudioUnitInputCallback mInputCallback; - - AudioStreamBasicDescription mFileDescription; - - int mConnected; - - struct S_AudioFileManager* mAudioFileManager; - - AudioFilePlayNotifier mNotifier; - void* mRefCon; - - int mStartFrame; - + AudioUnit mPlayUnit; + SInt16 mForkRefNum; + + AudioUnitInputCallback mInputCallback; + + AudioStreamBasicDescription mFileDescription; + + int mConnected; + + struct S_AudioFileManager *mAudioFileManager; + + AudioFilePlayNotifier mNotifier; + void *mRefCon; + + int mStartFrame; + #pragma mark __________ Private_Methods - - int (*OpenFile)(struct S_AudioFilePlayer *afp, const FSRef *inRef, SInt64 *outFileSize); + + int (*OpenFile) (struct S_AudioFilePlayer * afp, const FSRef * inRef, + SInt64 * outFileSize); } AudioFilePlayer; -AudioFilePlayer *new_AudioFilePlayer(const FSRef *inFileRef); -void delete_AudioFilePlayer(AudioFilePlayer *afp); +AudioFilePlayer *new_AudioFilePlayer(const FSRef * inFileRef); +void delete_AudioFilePlayer(AudioFilePlayer * afp); @@ -107,64 +110,66 @@ void delete_AudioFilePlayer(AudioFilePlayer *afp); typedef struct S_AudioFileManager { /*public:*/ - /* this method should NOT be called by an object of this class - as it is called by the parent's Disconnect() method */ - void (*Disconnect)(struct S_AudioFileManager *afm); - int (*DoConnect)(struct S_AudioFileManager *afm); - OSStatus (*Read)(struct S_AudioFileManager *afm, char *buffer, UInt32 *len); - const char* (*GetFileBuffer)(struct S_AudioFileManager *afm); - const AudioFilePlayer *(*GetParent)(struct S_AudioFileManager *afm); - void (*SetPosition)(struct S_AudioFileManager *afm, SInt64 pos); /* seek/rewind in the file */ - int (*GetByteCounter)(struct S_AudioFileManager *afm); /* return actual bytes streamed to audio hardware */ - void (*SetEndOfFile)(struct S_AudioFileManager *afm, SInt64 pos); /* set the "EOF" (will behave just like it reached eof) */ - + /* this method should NOT be called by an object of this class + as it is called by the parent's Disconnect() method */ + void (*Disconnect) (struct S_AudioFileManager * afm); + int (*DoConnect) (struct S_AudioFileManager * afm); + OSStatus(*Read) (struct S_AudioFileManager * afm, char *buffer, + UInt32 * len); + const char *(*GetFileBuffer) (struct S_AudioFileManager * afm); + const AudioFilePlayer *(*GetParent) (struct S_AudioFileManager * afm); + void (*SetPosition) (struct S_AudioFileManager * afm, SInt64 pos); /* seek/rewind in the file */ + int (*GetByteCounter) (struct S_AudioFileManager * afm); /* return actual bytes streamed to audio hardware */ + void (*SetEndOfFile) (struct S_AudioFileManager * afm, SInt64 pos); /* set the "EOF" (will behave just like it reached eof) */ + /*protected:*/ - AudioFilePlayer* mParent; - SInt16 mForkRefNum; - SInt64 mAudioDataOffset; - - char* mFileBuffer; + AudioFilePlayer *mParent; + SInt16 mForkRefNum; + SInt64 mAudioDataOffset; + + char *mFileBuffer; - int mByteCounter; + int mByteCounter; - int mReadFromFirstBuffer; - int mLockUnsuccessful; - int mIsEngaged; - - int mNumTimesAskedSinceFinished; + int mReadFromFirstBuffer; + int mLockUnsuccessful; + int mIsEngaged; + int mNumTimesAskedSinceFinished; - void* mTmpBuffer; - UInt32 mBufferSize; - UInt32 mBufferOffset; + + void *mTmpBuffer; + UInt32 mBufferSize; + UInt32 mBufferOffset; /*public:*/ - UInt32 mChunkSize; - SInt64 mFileLength; - SInt64 mReadFilePosition; - int mWriteToFirstBuffer; - int mFinishedReadingData; + UInt32 mChunkSize; + SInt64 mFileLength; + SInt64 mReadFilePosition; + int mWriteToFirstBuffer; + int mFinishedReadingData; /*protected:*/ - OSStatus (*Render)(struct S_AudioFileManager *afm, AudioBuffer *ioData); - OSStatus (*GetFileData)(struct S_AudioFileManager *afm, void** inOutData, UInt32 *inOutDataSize); - void (*AfterRender)(struct S_AudioFileManager *afm); + OSStatus(*Render) (struct S_AudioFileManager * afm, + AudioBuffer * ioData); + OSStatus(*GetFileData) (struct S_AudioFileManager * afm, + void **inOutData, UInt32 * inOutDataSize); + void (*AfterRender) (struct S_AudioFileManager * afm); /*public:*/ - /*static*/ - OSStatus (*FileInputProc)(void *inRefCon, - AudioUnitRenderActionFlags inActionFlags, - const AudioTimeStamp *inTimeStamp, - UInt32 inBusNumber, - AudioBuffer *ioData); + /*static */ + OSStatus(*FileInputProc) (void *inRefCon, + AudioUnitRenderActionFlags inActionFlags, + const AudioTimeStamp * inTimeStamp, + UInt32 inBusNumber, AudioBuffer * ioData); } AudioFileManager; -AudioFileManager *new_AudioFileManager (AudioFilePlayer *inParent, - SInt16 inForkRefNum, - SInt64 inFileLength, - UInt32 inChunkSize); - -void delete_AudioFileManager(AudioFileManager *afm); +AudioFileManager *new_AudioFileManager(AudioFilePlayer * inParent, + SInt16 inForkRefNum, + SInt64 inFileLength, + UInt32 inChunkSize); -#endif +void delete_AudioFileManager(AudioFileManager * afm); +#endif +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/cdrom/macosx/AudioFileReaderThread.c b/src/cdrom/macosx/AudioFileReaderThread.c index db7fe9b22..fb9f45b58 100644 --- a/src/cdrom/macosx/AudioFileReaderThread.c +++ b/src/cdrom/macosx/AudioFileReaderThread.c @@ -28,7 +28,7 @@ AudioFileManager.cpp */ #include "AudioFilePlayer.h" -#include /* used for setting policy of thread */ +#include /* used for setting policy of thread */ #include "SDLOSXCAGuard.h" #include @@ -42,56 +42,64 @@ typedef struct S_FileData } FileData; -typedef struct S_FileReaderThread { +typedef struct S_FileReaderThread +{ /*public:*/ - SDLOSXCAGuard* (*GetGuard)(struct S_FileReaderThread *frt); - void (*AddReader)(struct S_FileReaderThread *frt); - void (*RemoveReader)(struct S_FileReaderThread *frt, AudioFileManager* inItem); - int (*TryNextRead)(struct S_FileReaderThread *frt, AudioFileManager* inItem); + SDLOSXCAGuard *(*GetGuard) (struct S_FileReaderThread * frt); + void (*AddReader) (struct S_FileReaderThread * frt); + void (*RemoveReader) (struct S_FileReaderThread * frt, + AudioFileManager * inItem); + int (*TryNextRead) (struct S_FileReaderThread * frt, + AudioFileManager * inItem); + + int mThreadShouldDie; - int mThreadShouldDie; - /*private:*/ - /*typedef std::list FileData;*/ + /*typedef std::list FileData; */ - SDLOSXCAGuard *mGuard; - UInt32 mThreadPriority; - - int mNumReaders; - FileData *mFileData; + SDLOSXCAGuard *mGuard; + UInt32 mThreadPriority; + int mNumReaders; + FileData *mFileData; - void (*ReadNextChunk)(struct S_FileReaderThread *frt); - int (*StartFixedPriorityThread)(struct S_FileReaderThread *frt); - /*static*/ - UInt32 (*GetThreadBasePriority)(pthread_t inThread); - /*static*/ - void* (*DiskReaderEntry)(void *inRefCon); + + void (*ReadNextChunk) (struct S_FileReaderThread * frt); + int (*StartFixedPriorityThread) (struct S_FileReaderThread * frt); + /*static */ + UInt32(*GetThreadBasePriority) (pthread_t inThread); + /*static */ + void *(*DiskReaderEntry) (void *inRefCon); } FileReaderThread; -static SDLOSXCAGuard* FileReaderThread_GetGuard(FileReaderThread *frt) +static SDLOSXCAGuard * +FileReaderThread_GetGuard(FileReaderThread * frt) { return frt->mGuard; } /* returns 1 if succeeded */ -static int FileReaderThread_TryNextRead (FileReaderThread *frt, AudioFileManager* inItem) +static int +FileReaderThread_TryNextRead(FileReaderThread * frt, + AudioFileManager * inItem) { int didLock = 0; int succeeded = 0; - if (frt->mGuard->Try(frt->mGuard, &didLock)) - { - /*frt->mFileData.push_back (inItem);*/ + if (frt->mGuard->Try(frt->mGuard, &didLock)) { + /*frt->mFileData.push_back (inItem); */ /* !!! FIXME: this could be faster with a "tail" member. --ryan. */ FileData *i = frt->mFileData; FileData *prev = NULL; - FileData *newfd = (FileData *) SDL_malloc(sizeof (FileData)); + FileData *newfd = (FileData *) SDL_malloc(sizeof(FileData)); newfd->obj = inItem; newfd->next = NULL; - while (i != NULL) { prev = i; i = i->next; } + while (i != NULL) { + prev = i; + i = i->next; + } if (prev == NULL) frt->mFileData = newfd; else @@ -103,36 +111,35 @@ static int FileReaderThread_TryNextRead (FileReaderThread *frt, AudioFileManager if (didLock) frt->mGuard->Unlock(frt->mGuard); } - + return succeeded; } -static void FileReaderThread_AddReader(FileReaderThread *frt) +static void +FileReaderThread_AddReader(FileReaderThread * frt) { - if (frt->mNumReaders == 0) - { + if (frt->mNumReaders == 0) { frt->mThreadShouldDie = 0; - frt->StartFixedPriorityThread (frt); + frt->StartFixedPriorityThread(frt); } frt->mNumReaders++; } -static void FileReaderThread_RemoveReader (FileReaderThread *frt, AudioFileManager* inItem) +static void +FileReaderThread_RemoveReader(FileReaderThread * frt, + AudioFileManager * inItem) { - if (frt->mNumReaders > 0) - { + if (frt->mNumReaders > 0) { int bNeedsRelease = frt->mGuard->Lock(frt->mGuard); - - /*frt->mFileData.remove (inItem);*/ + + /*frt->mFileData.remove (inItem); */ FileData *i = frt->mFileData; FileData *prev = NULL; - while (i != NULL) - { + while (i != NULL) { FileData *next = i->next; if (i->obj != inItem) prev = i; - else - { + else { if (prev == NULL) frt->mFileData = next; else @@ -144,181 +151,212 @@ static void FileReaderThread_RemoveReader (FileReaderThread *frt, AudioFileMa if (--frt->mNumReaders == 0) { frt->mThreadShouldDie = 1; - frt->mGuard->Notify(frt->mGuard); /* wake up thread so it will quit */ - frt->mGuard->Wait(frt->mGuard); /* wait for thread to die */ + frt->mGuard->Notify(frt->mGuard); /* wake up thread so it will quit */ + frt->mGuard->Wait(frt->mGuard); /* wait for thread to die */ } - if (bNeedsRelease) frt->mGuard->Unlock(frt->mGuard); - } + if (bNeedsRelease) + frt->mGuard->Unlock(frt->mGuard); + } } -static int FileReaderThread_StartFixedPriorityThread (FileReaderThread *frt) +static int +FileReaderThread_StartFixedPriorityThread(FileReaderThread * frt) { - pthread_attr_t theThreadAttrs; - pthread_t pThread; + pthread_attr_t theThreadAttrs; + pthread_t pThread; OSStatus result = pthread_attr_init(&theThreadAttrs); - if (result) return 0; /*THROW_RESULT("pthread_attr_init - Thread attributes could not be created.")*/ - - result = pthread_attr_setdetachstate(&theThreadAttrs, PTHREAD_CREATE_DETACHED); - if (result) return 0; /*THROW_RESULT("pthread_attr_setdetachstate - Thread attributes could not be detached.")*/ - - result = pthread_create (&pThread, &theThreadAttrs, frt->DiskReaderEntry, frt); - if (result) return 0; /*THROW_RESULT("pthread_create - Create and start the thread.")*/ - + if (result) + return 0; /*THROW_RESULT("pthread_attr_init - Thread attributes could not be created.") */ + + result = + pthread_attr_setdetachstate(&theThreadAttrs, PTHREAD_CREATE_DETACHED); + if (result) + return 0; /*THROW_RESULT("pthread_attr_setdetachstate - Thread attributes could not be detached.") */ + + result = + pthread_create(&pThread, &theThreadAttrs, frt->DiskReaderEntry, frt); + if (result) + return 0; /*THROW_RESULT("pthread_create - Create and start the thread.") */ + pthread_attr_destroy(&theThreadAttrs); - + /* we've now created the thread and started it we'll now set the priority of the thread to the nominated priority and we'll also make the thread fixed */ - thread_extended_policy_data_t theFixedPolicy; - thread_precedence_policy_data_t thePrecedencePolicy; - SInt32 relativePriority; - + thread_extended_policy_data_t theFixedPolicy; + thread_precedence_policy_data_t thePrecedencePolicy; + SInt32 relativePriority; + /* make thread fixed */ - theFixedPolicy.timeshare = 0; /* set to 1 for a non-fixed thread */ - result = thread_policy_set (pthread_mach_thread_np(pThread), THREAD_EXTENDED_POLICY, (thread_policy_t)&theFixedPolicy, THREAD_EXTENDED_POLICY_COUNT); - if (result) return 0; /*THROW_RESULT("thread_policy - Couldn't set thread as fixed priority.")*/ + theFixedPolicy.timeshare = 0; /* set to 1 for a non-fixed thread */ + result = + thread_policy_set(pthread_mach_thread_np(pThread), + THREAD_EXTENDED_POLICY, + (thread_policy_t) & theFixedPolicy, + THREAD_EXTENDED_POLICY_COUNT); + if (result) + return 0; /*THROW_RESULT("thread_policy - Couldn't set thread as fixed priority.") */ /* set priority */ /* precedency policy's "importance" value is relative to spawning thread's priority */ - relativePriority = frt->mThreadPriority - frt->GetThreadBasePriority(pthread_self()); - + relativePriority = + frt->mThreadPriority - frt->GetThreadBasePriority(pthread_self()); + thePrecedencePolicy.importance = relativePriority; - result = thread_policy_set (pthread_mach_thread_np(pThread), THREAD_PRECEDENCE_POLICY, (thread_policy_t)&thePrecedencePolicy, THREAD_PRECEDENCE_POLICY_COUNT); - if (result) return 0; /*THROW_RESULT("thread_policy - Couldn't set thread priority.")*/ + result = + thread_policy_set(pthread_mach_thread_np(pThread), + THREAD_PRECEDENCE_POLICY, + (thread_policy_t) & thePrecedencePolicy, + THREAD_PRECEDENCE_POLICY_COUNT); + if (result) + return 0; /*THROW_RESULT("thread_policy - Couldn't set thread priority.") */ return 1; } -static UInt32 FileReaderThread_GetThreadBasePriority (pthread_t inThread) +static UInt32 +FileReaderThread_GetThreadBasePriority(pthread_t inThread) { - thread_basic_info_data_t threadInfo; - policy_info_data_t thePolicyInfo; - unsigned int count; - + thread_basic_info_data_t threadInfo; + policy_info_data_t thePolicyInfo; + unsigned int count; + /* get basic info */ count = THREAD_BASIC_INFO_COUNT; - thread_info (pthread_mach_thread_np (inThread), THREAD_BASIC_INFO, (integer_t*)&threadInfo, &count); - + thread_info(pthread_mach_thread_np(inThread), THREAD_BASIC_INFO, + (integer_t *) & threadInfo, &count); + switch (threadInfo.policy) { - case POLICY_TIMESHARE: - count = POLICY_TIMESHARE_INFO_COUNT; - thread_info(pthread_mach_thread_np (inThread), THREAD_SCHED_TIMESHARE_INFO, (integer_t*)&(thePolicyInfo.ts), &count); - return thePolicyInfo.ts.base_priority; - break; - - case POLICY_FIFO: - count = POLICY_FIFO_INFO_COUNT; - thread_info(pthread_mach_thread_np (inThread), THREAD_SCHED_FIFO_INFO, (integer_t*)&(thePolicyInfo.fifo), &count); - if (thePolicyInfo.fifo.depressed) { - return thePolicyInfo.fifo.depress_priority; - } else { - return thePolicyInfo.fifo.base_priority; - } - break; - - case POLICY_RR: - count = POLICY_RR_INFO_COUNT; - thread_info(pthread_mach_thread_np (inThread), THREAD_SCHED_RR_INFO, (integer_t*)&(thePolicyInfo.rr), &count); - if (thePolicyInfo.rr.depressed) { - return thePolicyInfo.rr.depress_priority; - } else { - return thePolicyInfo.rr.base_priority; - } - break; + case POLICY_TIMESHARE: + count = POLICY_TIMESHARE_INFO_COUNT; + thread_info(pthread_mach_thread_np(inThread), + THREAD_SCHED_TIMESHARE_INFO, + (integer_t *) & (thePolicyInfo.ts), &count); + return thePolicyInfo.ts.base_priority; + break; + + case POLICY_FIFO: + count = POLICY_FIFO_INFO_COUNT; + thread_info(pthread_mach_thread_np(inThread), + THREAD_SCHED_FIFO_INFO, + (integer_t *) & (thePolicyInfo.fifo), &count); + if (thePolicyInfo.fifo.depressed) { + return thePolicyInfo.fifo.depress_priority; + } else { + return thePolicyInfo.fifo.base_priority; + } + break; + + case POLICY_RR: + count = POLICY_RR_INFO_COUNT; + thread_info(pthread_mach_thread_np(inThread), + THREAD_SCHED_RR_INFO, + (integer_t *) & (thePolicyInfo.rr), &count); + if (thePolicyInfo.rr.depressed) { + return thePolicyInfo.rr.depress_priority; + } else { + return thePolicyInfo.rr.base_priority; + } + break; } - + return 0; } -static void *FileReaderThread_DiskReaderEntry (void *inRefCon) +static void * +FileReaderThread_DiskReaderEntry(void *inRefCon) { - FileReaderThread *frt = (FileReaderThread *)inRefCon; + FileReaderThread *frt = (FileReaderThread *) inRefCon; frt->ReadNextChunk(frt); - #if DEBUG - printf ("finished with reading file\n"); - #endif - +#if DEBUG + printf("finished with reading file\n"); +#endif + return 0; } -static void FileReaderThread_ReadNextChunk (FileReaderThread *frt) +static void +FileReaderThread_ReadNextChunk(FileReaderThread * frt) { OSStatus result; - UInt32 dataChunkSize; - AudioFileManager* theItem = 0; + UInt32 dataChunkSize; + AudioFileManager *theItem = 0; - for (;;) - { - { /* this is a scoped based lock */ + for (;;) { + { /* this is a scoped based lock */ int bNeedsRelease = frt->mGuard->Lock(frt->mGuard); - + if (frt->mThreadShouldDie) { frt->mGuard->Notify(frt->mGuard); - if (bNeedsRelease) frt->mGuard->Unlock(frt->mGuard); + if (bNeedsRelease) + frt->mGuard->Unlock(frt->mGuard); return; } - - /*if (frt->mFileData.empty())*/ - if (frt->mFileData == NULL) - { + + /*if (frt->mFileData.empty()) */ + if (frt->mFileData == NULL) { frt->mGuard->Wait(frt->mGuard); } - + /* kill thread */ if (frt->mThreadShouldDie) { - + frt->mGuard->Notify(frt->mGuard); - if (bNeedsRelease) frt->mGuard->Unlock(frt->mGuard); + if (bNeedsRelease) + frt->mGuard->Unlock(frt->mGuard); return; } - /*theItem = frt->mFileData.front();*/ - /*frt->mFileData.pop_front();*/ + /*theItem = frt->mFileData.front(); */ + /*frt->mFileData.pop_front(); */ theItem = NULL; - if (frt->mFileData != NULL) - { + if (frt->mFileData != NULL) { FileData *next = frt->mFileData->next; theItem = frt->mFileData->obj; SDL_free(frt->mFileData); frt->mFileData = next; } - if (bNeedsRelease) frt->mGuard->Unlock(frt->mGuard); + if (bNeedsRelease) + frt->mGuard->Unlock(frt->mGuard); } - - if ((theItem->mFileLength - theItem->mReadFilePosition) < theItem->mChunkSize) + + if ((theItem->mFileLength - theItem->mReadFilePosition) < + theItem->mChunkSize) dataChunkSize = theItem->mFileLength - theItem->mReadFilePosition; else dataChunkSize = theItem->mChunkSize; - - /* this is the exit condition for the thread */ + + /* this is the exit condition for the thread */ if (dataChunkSize <= 0) { theItem->mFinishedReadingData = 1; continue; } - /* construct pointer */ - char* writePtr = (char *) (theItem->GetFileBuffer(theItem) + - (theItem->mWriteToFirstBuffer ? 0 : theItem->mChunkSize)); - - /* read data */ + /* construct pointer */ + char *writePtr = (char *) (theItem->GetFileBuffer(theItem) + + (theItem-> + mWriteToFirstBuffer ? 0 : theItem-> + mChunkSize)); + + /* read data */ result = theItem->Read(theItem, writePtr, &dataChunkSize); if (result != noErr && result != eofErr) { - AudioFilePlayer *afp = (AudioFilePlayer *) theItem->GetParent(theItem); + AudioFilePlayer *afp = + (AudioFilePlayer *) theItem->GetParent(theItem); afp->DoNotification(afp, result); continue; } - - if (dataChunkSize != theItem->mChunkSize) - { + + if (dataChunkSize != theItem->mChunkSize) { writePtr += dataChunkSize; /* can't exit yet.. we still have to pass the partial buffer back */ SDL_memset(writePtr, 0, (theItem->mChunkSize - dataChunkSize)); } - + theItem->mWriteToFirstBuffer = !theItem->mWriteToFirstBuffer; /* switch buffers */ - + if (result == eofErr) theItem->mReadFilePosition = theItem->mFileLength; else @@ -326,30 +364,30 @@ static void FileReaderThread_ReadNextChunk (FileReaderThread *frt) } } -void delete_FileReaderThread(FileReaderThread *frt) +void +delete_FileReaderThread(FileReaderThread * frt) { - if (frt != NULL) - { + if (frt != NULL) { delete_SDLOSXCAGuard(frt->mGuard); SDL_free(frt); } } -FileReaderThread *new_FileReaderThread () +FileReaderThread * +new_FileReaderThread() { - FileReaderThread *frt = (FileReaderThread *) SDL_malloc(sizeof (FileReaderThread)); + FileReaderThread *frt = + (FileReaderThread *) SDL_malloc(sizeof(FileReaderThread)); if (frt == NULL) return NULL; - SDL_memset(frt, '\0', sizeof (*frt)); + SDL_memset(frt, '\0', sizeof(*frt)); frt->mGuard = new_SDLOSXCAGuard(); - if (frt->mGuard == NULL) - { + if (frt->mGuard == NULL) { SDL_free(frt); return NULL; } - - #define SET_FILEREADERTHREAD_METHOD(m) frt->m = FileReaderThread_##m +#define SET_FILEREADERTHREAD_METHOD(m) frt->m = FileReaderThread_##m SET_FILEREADERTHREAD_METHOD(GetGuard); SET_FILEREADERTHREAD_METHOD(AddReader); SET_FILEREADERTHREAD_METHOD(RemoveReader); @@ -358,7 +396,7 @@ FileReaderThread *new_FileReaderThread () SET_FILEREADERTHREAD_METHOD(StartFixedPriorityThread); SET_FILEREADERTHREAD_METHOD(GetThreadBasePriority); SET_FILEREADERTHREAD_METHOD(DiskReaderEntry); - #undef SET_FILEREADERTHREAD_METHOD +#undef SET_FILEREADERTHREAD_METHOD frt->mThreadPriority = 62; return frt; @@ -368,184 +406,200 @@ FileReaderThread *new_FileReaderThread () static FileReaderThread *sReaderThread; -static int AudioFileManager_DoConnect (AudioFileManager *afm) +static int +AudioFileManager_DoConnect(AudioFileManager * afm) { - if (!afm->mIsEngaged) - { + if (!afm->mIsEngaged) { OSStatus result; - /*afm->mReadFilePosition = 0;*/ + /*afm->mReadFilePosition = 0; */ afm->mFinishedReadingData = 0; afm->mNumTimesAskedSinceFinished = 0; afm->mLockUnsuccessful = 0; - + UInt32 dataChunkSize; - + if ((afm->mFileLength - afm->mReadFilePosition) < afm->mChunkSize) dataChunkSize = afm->mFileLength - afm->mReadFilePosition; else dataChunkSize = afm->mChunkSize; - + result = afm->Read(afm, afm->mFileBuffer, &dataChunkSize); - if (result) return 0; /*THROW_RESULT("AudioFileManager::DoConnect(): Read")*/ + if (result) + return 0; /*THROW_RESULT("AudioFileManager::DoConnect(): Read") */ afm->mReadFilePosition += dataChunkSize; - + afm->mWriteToFirstBuffer = 0; afm->mReadFromFirstBuffer = 1; sReaderThread->AddReader(sReaderThread); - + afm->mIsEngaged = 1; } /* - else - throw static_cast(-1); */ /* thread has already been started */ + else + throw static_cast(-1); *//* thread has already been started */ return 1; } -static void AudioFileManager_Disconnect (AudioFileManager *afm) +static void +AudioFileManager_Disconnect(AudioFileManager * afm) { - if (afm->mIsEngaged) - { - sReaderThread->RemoveReader (sReaderThread, afm); + if (afm->mIsEngaged) { + sReaderThread->RemoveReader(sReaderThread, afm); afm->mIsEngaged = 0; } } -static OSStatus AudioFileManager_Read(AudioFileManager *afm, char *buffer, UInt32 *len) +static OSStatus +AudioFileManager_Read(AudioFileManager * afm, char *buffer, UInt32 * len) { - return FSReadFork (afm->mForkRefNum, - fsFromStart, - afm->mReadFilePosition + afm->mAudioDataOffset, - *len, - buffer, - len); + return FSReadFork(afm->mForkRefNum, + fsFromStart, + afm->mReadFilePosition + afm->mAudioDataOffset, + *len, buffer, len); } -static OSStatus AudioFileManager_GetFileData (AudioFileManager *afm, void** inOutData, UInt32 *inOutDataSize) +static OSStatus +AudioFileManager_GetFileData(AudioFileManager * afm, void **inOutData, + UInt32 * inOutDataSize) { - if (afm->mFinishedReadingData) - { + if (afm->mFinishedReadingData) { ++afm->mNumTimesAskedSinceFinished; *inOutDataSize = 0; *inOutData = 0; return noErr; } - + if (afm->mReadFromFirstBuffer == afm->mWriteToFirstBuffer) { - #if DEBUG - printf ("* * * * * * * Can't keep up with reading file\n"); - #endif - - afm->mParent->DoNotification (afm->mParent, kAudioFilePlayErr_FilePlayUnderrun); +#if DEBUG + printf("* * * * * * * Can't keep up with reading file\n"); +#endif + + afm->mParent->DoNotification(afm->mParent, + kAudioFilePlayErr_FilePlayUnderrun); *inOutDataSize = 0; *inOutData = 0; } else { *inOutDataSize = afm->mChunkSize; - *inOutData = afm->mReadFromFirstBuffer ? afm->mFileBuffer : (afm->mFileBuffer + afm->mChunkSize); + *inOutData = + afm->mReadFromFirstBuffer ? afm->mFileBuffer : (afm-> + mFileBuffer + + afm->mChunkSize); } - afm->mLockUnsuccessful = !sReaderThread->TryNextRead (sReaderThread, afm); - + afm->mLockUnsuccessful = !sReaderThread->TryNextRead(sReaderThread, afm); + afm->mReadFromFirstBuffer = !afm->mReadFromFirstBuffer; return noErr; } -static void AudioFileManager_AfterRender (AudioFileManager *afm) +static void +AudioFileManager_AfterRender(AudioFileManager * afm) { - if (afm->mNumTimesAskedSinceFinished > 0) - { + if (afm->mNumTimesAskedSinceFinished > 0) { int didLock = 0; SDLOSXCAGuard *guard = sReaderThread->GetGuard(sReaderThread); if (guard->Try(guard, &didLock)) { - afm->mParent->DoNotification (afm->mParent, kAudioFilePlay_FileIsFinished); + afm->mParent->DoNotification(afm->mParent, + kAudioFilePlay_FileIsFinished); if (didLock) guard->Unlock(guard); } } if (afm->mLockUnsuccessful) - afm->mLockUnsuccessful = !sReaderThread->TryNextRead (sReaderThread, afm); + afm->mLockUnsuccessful = + !sReaderThread->TryNextRead(sReaderThread, afm); } -static void AudioFileManager_SetPosition (AudioFileManager *afm, SInt64 pos) +static void +AudioFileManager_SetPosition(AudioFileManager * afm, SInt64 pos) { if (pos < 0 || pos >= afm->mFileLength) { - SDL_SetError ("AudioFileManager::SetPosition - position invalid: %d filelen=%d\n", - (unsigned int)pos, (unsigned int)afm->mFileLength); + SDL_SetError + ("AudioFileManager::SetPosition - position invalid: %d filelen=%d\n", + (unsigned int) pos, (unsigned int) afm->mFileLength); pos = 0; } - + afm->mReadFilePosition = pos; } - -static void AudioFileManager_SetEndOfFile (AudioFileManager *afm, SInt64 pos) + +static void +AudioFileManager_SetEndOfFile(AudioFileManager * afm, SInt64 pos) { if (pos <= 0 || pos > afm->mFileLength) { - SDL_SetError ("AudioFileManager::SetEndOfFile - position beyond actual eof\n"); + SDL_SetError + ("AudioFileManager::SetEndOfFile - position beyond actual eof\n"); pos = afm->mFileLength; } - + afm->mFileLength = pos; } -static const char *AudioFileManager_GetFileBuffer(AudioFileManager *afm) +static const char * +AudioFileManager_GetFileBuffer(AudioFileManager * afm) { return afm->mFileBuffer; } -const AudioFilePlayer *AudioFileManager_GetParent(AudioFileManager *afm) +const AudioFilePlayer * +AudioFileManager_GetParent(AudioFileManager * afm) { return afm->mParent; } -static int AudioFileManager_GetByteCounter(AudioFileManager *afm) +static int +AudioFileManager_GetByteCounter(AudioFileManager * afm) { return afm->mByteCounter; } -static OSStatus AudioFileManager_FileInputProc (void *inRefCon, - AudioUnitRenderActionFlags inActionFlags, - const AudioTimeStamp *inTimeStamp, - UInt32 inBusNumber, - AudioBuffer *ioData) +static OSStatus +AudioFileManager_FileInputProc(void *inRefCon, + AudioUnitRenderActionFlags inActionFlags, + const AudioTimeStamp * inTimeStamp, + UInt32 inBusNumber, AudioBuffer * ioData) { - AudioFileManager* afm = (AudioFileManager*)inRefCon; + AudioFileManager *afm = (AudioFileManager *) inRefCon; return afm->Render(afm, ioData); } -static OSStatus AudioFileManager_Render (AudioFileManager *afm, AudioBuffer *ioData) +static OSStatus +AudioFileManager_Render(AudioFileManager * afm, AudioBuffer * ioData) { OSStatus result = noErr; - - if (afm->mBufferOffset >= afm->mBufferSize) { - result = afm->GetFileData(afm, &afm->mTmpBuffer, &afm->mBufferSize); - if (result) { - SDL_SetError ("AudioConverterFillBuffer:%ld\n", result); - afm->mParent->DoNotification(afm->mParent, result); - return result; - } - - afm->mBufferOffset = 0; - } - + + if (afm->mBufferOffset >= afm->mBufferSize) { + result = afm->GetFileData(afm, &afm->mTmpBuffer, &afm->mBufferSize); + if (result) { + SDL_SetError("AudioConverterFillBuffer:%ld\n", result); + afm->mParent->DoNotification(afm->mParent, result); + return result; + } + + afm->mBufferOffset = 0; + } + if (ioData->mDataByteSize > afm->mBufferSize - afm->mBufferOffset) - ioData->mDataByteSize = afm->mBufferSize - afm->mBufferOffset; - ioData->mData = (char *)afm->mTmpBuffer + afm->mBufferOffset; + ioData->mDataByteSize = afm->mBufferSize - afm->mBufferOffset; + ioData->mData = (char *) afm->mTmpBuffer + afm->mBufferOffset; afm->mBufferOffset += ioData->mDataByteSize; - - afm->mByteCounter += ioData->mDataByteSize; - afm->AfterRender(afm); + + afm->mByteCounter += ioData->mDataByteSize; + afm->AfterRender(afm); return result; } -void delete_AudioFileManager (AudioFileManager *afm) +void +delete_AudioFileManager(AudioFileManager * afm) { if (afm != NULL) { if (afm->mFileBuffer) { @@ -557,26 +611,25 @@ void delete_AudioFileManager (AudioFileManager *afm) } -AudioFileManager *new_AudioFileManager(AudioFilePlayer *inParent, - SInt16 inForkRefNum, - SInt64 inFileLength, - UInt32 inChunkSize) +AudioFileManager * +new_AudioFileManager(AudioFilePlayer * inParent, + SInt16 inForkRefNum, + SInt64 inFileLength, UInt32 inChunkSize) { AudioFileManager *afm; - if (sReaderThread == NULL) - { + if (sReaderThread == NULL) { sReaderThread = new_FileReaderThread(); if (sReaderThread == NULL) return NULL; } - afm = (AudioFileManager *) SDL_malloc(sizeof (AudioFileManager)); + afm = (AudioFileManager *) SDL_malloc(sizeof(AudioFileManager)); if (afm == NULL) return NULL; - SDL_memset(afm, '\0', sizeof (*afm)); + SDL_memset(afm, '\0', sizeof(*afm)); - #define SET_AUDIOFILEMANAGER_METHOD(m) afm->m = AudioFileManager_##m +#define SET_AUDIOFILEMANAGER_METHOD(m) afm->m = AudioFileManager_##m SET_AUDIOFILEMANAGER_METHOD(Disconnect); SET_AUDIOFILEMANAGER_METHOD(DoConnect); SET_AUDIOFILEMANAGER_METHOD(Read); @@ -589,7 +642,7 @@ AudioFileManager *new_AudioFileManager(AudioFilePlayer *inParent, SET_AUDIOFILEMANAGER_METHOD(GetFileData); SET_AUDIOFILEMANAGER_METHOD(AfterRender); SET_AUDIOFILEMANAGER_METHOD(FileInputProc); - #undef SET_AUDIOFILEMANAGER_METHOD +#undef SET_AUDIOFILEMANAGER_METHOD afm->mParent = inParent; afm->mForkRefNum = inForkRefNum; @@ -597,9 +650,10 @@ AudioFileManager *new_AudioFileManager(AudioFilePlayer *inParent, afm->mBufferOffset = inChunkSize; afm->mChunkSize = inChunkSize; afm->mFileLength = inFileLength; - afm->mFileBuffer = (char*) SDL_malloc(afm->mChunkSize * 2); + afm->mFileBuffer = (char *) SDL_malloc(afm->mChunkSize * 2); FSGetForkPosition(afm->mForkRefNum, &afm->mAudioDataOffset); - assert (afm->mFileBuffer != NULL); + assert(afm->mFileBuffer != NULL); return afm; } +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/cdrom/macosx/CDPlayer.c b/src/cdrom/macosx/CDPlayer.c index 16dc21397..25d086238 100644 --- a/src/cdrom/macosx/CDPlayer.c +++ b/src/cdrom/macosx/CDPlayer.c @@ -32,7 +32,7 @@ Constants //////////////////////////////////////////////////////////////////////////*/ -#define kAudioCDFilesystemID (UInt16)(('J' << 8) | 'H') /* 'JH'; this avoids compiler warning */ +#define kAudioCDFilesystemID (UInt16)(('J' << 8) | 'H') /* 'JH'; this avoids compiler warning */ /* XML PList keys */ #define kRawTOCDataString "Format 0x02 TOC Data" @@ -45,21 +45,21 @@ #define kDataKeyString "Data" #define kPointKeyString "Point" #define kSessionNumberKeyString "Session Number" -#define kStartBlockKeyString "Start Block" - +#define kStartBlockKeyString "Start Block" + /*/////////////////////////////////////////////////////////////////////////// Globals //////////////////////////////////////////////////////////////////////////*/ #pragma mark -- Globals -- -static int playBackWasInit = 0; -static AudioUnit theUnit; -static AudioFilePlayer* thePlayer = NULL; -static CDPlayerCompletionProc completionProc = NULL; -static SDL_mutex *apiMutex = NULL; -static SDL_sem *callbackSem; -static SDL_CD* theCDROM; +static int playBackWasInit = 0; +static AudioUnit theUnit; +static AudioFilePlayer *thePlayer = NULL; +static CDPlayerCompletionProc completionProc = NULL; +static SDL_mutex *apiMutex = NULL; +static SDL_sem *callbackSem; +static SDL_CD *theCDROM; /*/////////////////////////////////////////////////////////////////////////// Prototypes @@ -67,16 +67,17 @@ static SDL_CD* theCDROM; #pragma mark -- Prototypes -- -static OSStatus CheckInit (); +static OSStatus CheckInit(); -static void FilePlayNotificationHandler (void* inRefCon, OSStatus inStatus); +static void FilePlayNotificationHandler(void *inRefCon, OSStatus inStatus); -static int RunCallBackThread (void* inRefCon); +static int RunCallBackThread(void *inRefCon); #pragma mark -- Public Functions -- -void Lock () +void +Lock() { if (!apiMutex) { apiMutex = SDL_CreateMutex(); @@ -84,221 +85,244 @@ void Lock () SDL_mutexP(apiMutex); } -void Unlock () +void +Unlock() { SDL_mutexV(apiMutex); } -int DetectAudioCDVolumes(FSVolumeRefNum *volumes, int numVolumes) +int +DetectAudioCDVolumes(FSVolumeRefNum * volumes, int numVolumes) { int volumeIndex; int cdVolumeCount = 0; OSStatus result = noErr; - - for (volumeIndex = 1; result == noErr || result != nsvErr; volumeIndex++) - { - FSVolumeRefNum actualVolume; - FSVolumeInfo volumeInfo; - - memset (&volumeInfo, 0, sizeof(volumeInfo)); - - result = FSGetVolumeInfo (kFSInvalidVolumeRefNum, - volumeIndex, - &actualVolume, - kFSVolInfoFSInfo, - &volumeInfo, - NULL, - NULL); - - if (result == noErr) - { - if (volumeInfo.filesystemID == kAudioCDFilesystemID) /* It's an audio CD */ - { + + for (volumeIndex = 1; result == noErr || result != nsvErr; volumeIndex++) { + FSVolumeRefNum actualVolume; + FSVolumeInfo volumeInfo; + + memset(&volumeInfo, 0, sizeof(volumeInfo)); + + result = FSGetVolumeInfo(kFSInvalidVolumeRefNum, + volumeIndex, + &actualVolume, + kFSVolInfoFSInfo, &volumeInfo, NULL, NULL); + + if (result == noErr) { + if (volumeInfo.filesystemID == kAudioCDFilesystemID) { /* It's an audio CD */ if (volumes != NULL && cdVolumeCount < numVolumes) volumes[cdVolumeCount] = actualVolume; - + cdVolumeCount++; } - } - else - { + } else { /* I'm commenting this out because it seems to be harmless */ - /*SDL_SetError ("DetectAudioCDVolumes: FSGetVolumeInfo returned %d", result);*/ + /*SDL_SetError ("DetectAudioCDVolumes: FSGetVolumeInfo returned %d", result); */ } } - + return cdVolumeCount; } -int ReadTOCData (FSVolumeRefNum theVolume, SDL_CD *theCD) +int +ReadTOCData(FSVolumeRefNum theVolume, SDL_CD * theCD) { - HFSUniStr255 dataForkName; - OSStatus theErr; - SInt16 forkRefNum; - SInt64 forkSize; - Ptr forkData = 0; - ByteCount actualRead; - CFDataRef dataRef = 0; + HFSUniStr255 dataForkName; + OSStatus theErr; + SInt16 forkRefNum; + SInt64 forkSize; + Ptr forkData = 0; + ByteCount actualRead; + CFDataRef dataRef = 0; CFPropertyListRef propertyListRef = 0; - FSRefParam fsRefPB; - FSRef tocPlistFSRef; - - const char* error = "Unspecified Error"; - + FSRefParam fsRefPB; + FSRef tocPlistFSRef; + + const char *error = "Unspecified Error"; + /* get stuff from .TOC.plist */ fsRefPB.ioCompletion = NULL; fsRefPB.ioNamePtr = "\p.TOC.plist"; fsRefPB.ioVRefNum = theVolume; fsRefPB.ioDirID = 0; fsRefPB.newRef = &tocPlistFSRef; - - theErr = PBMakeFSRefSync (&fsRefPB); - if(theErr != noErr) { + + theErr = PBMakeFSRefSync(&fsRefPB); + if (theErr != noErr) { error = "PBMakeFSRefSync"; goto bail; } - + /* Load and parse the TOC XML data */ - theErr = FSGetDataForkName (&dataForkName); + theErr = FSGetDataForkName(&dataForkName); if (theErr != noErr) { error = "FSGetDataForkName"; goto bail; } - - theErr = FSOpenFork (&tocPlistFSRef, dataForkName.length, dataForkName.unicode, fsRdPerm, &forkRefNum); + + theErr = + FSOpenFork(&tocPlistFSRef, dataForkName.length, dataForkName.unicode, + fsRdPerm, &forkRefNum); if (theErr != noErr) { error = "FSOpenFork"; goto bail; } - - theErr = FSGetForkSize (forkRefNum, &forkSize); + + theErr = FSGetForkSize(forkRefNum, &forkSize); if (theErr != noErr) { error = "FSGetForkSize"; goto bail; } - + /* Allocate some memory for the XML data */ - forkData = NewPtr (forkSize); - if(forkData == NULL) { + forkData = NewPtr(forkSize); + if (forkData == NULL) { error = "NewPtr"; goto bail; } - - theErr = FSReadFork (forkRefNum, fsFromStart, 0 /* offset location */, forkSize, forkData, &actualRead); - if(theErr != noErr) { + + theErr = FSReadFork(forkRefNum, fsFromStart, 0 /* offset location */ , + forkSize, forkData, &actualRead); + if (theErr != noErr) { error = "FSReadFork"; goto bail; } - - dataRef = CFDataCreate (kCFAllocatorDefault, (UInt8 *)forkData, forkSize); - if(dataRef == 0) { + + dataRef = CFDataCreate(kCFAllocatorDefault, (UInt8 *) forkData, forkSize); + if (dataRef == 0) { error = "CFDataCreate"; goto bail; } - propertyListRef = CFPropertyListCreateFromXMLData (kCFAllocatorDefault, - dataRef, - kCFPropertyListImmutable, - NULL); + propertyListRef = CFPropertyListCreateFromXMLData(kCFAllocatorDefault, + dataRef, + kCFPropertyListImmutable, + NULL); if (propertyListRef == NULL) { error = "CFPropertyListCreateFromXMLData"; goto bail; } /* Now we got the Property List in memory. Parse it. */ - + /* First, make sure the root item is a CFDictionary. If not, release and bail. */ - if(CFGetTypeID(propertyListRef)== CFDictionaryGetTypeID()) - { - CFDictionaryRef dictRef = (CFDictionaryRef)propertyListRef; - - CFDataRef theRawTOCDataRef; - CFArrayRef theSessionArrayRef; - CFIndex numSessions; - CFIndex index; - + if (CFGetTypeID(propertyListRef) == CFDictionaryGetTypeID()) { + CFDictionaryRef dictRef = (CFDictionaryRef) propertyListRef; + + CFDataRef theRawTOCDataRef; + CFArrayRef theSessionArrayRef; + CFIndex numSessions; + CFIndex index; + /* This is how we get the Raw TOC Data */ - theRawTOCDataRef = (CFDataRef)CFDictionaryGetValue (dictRef, CFSTR(kRawTOCDataString)); - + theRawTOCDataRef = + (CFDataRef) CFDictionaryGetValue(dictRef, + CFSTR(kRawTOCDataString)); + /* Get the session array info. */ - theSessionArrayRef = (CFArrayRef)CFDictionaryGetValue (dictRef, CFSTR(kSessionsString)); - + theSessionArrayRef = + (CFArrayRef) CFDictionaryGetValue(dictRef, + CFSTR(kSessionsString)); + /* Find out how many sessions there are. */ - numSessions = CFArrayGetCount (theSessionArrayRef); - + numSessions = CFArrayGetCount(theSessionArrayRef); + /* Initialize the total number of tracks to 0 */ theCD->numtracks = 0; - + /* Iterate over all sessions, collecting the track data */ - for(index = 0; index < numSessions; index++) - { + for (index = 0; index < numSessions; index++) { CFDictionaryRef theSessionDict; - CFNumberRef leadoutBlock; - CFArrayRef trackArray; - CFIndex numTracks; - CFIndex trackIndex; - UInt32 value = 0; - - theSessionDict = (CFDictionaryRef) CFArrayGetValueAtIndex (theSessionArrayRef, index); - leadoutBlock = (CFNumberRef) CFDictionaryGetValue (theSessionDict, CFSTR(kLeadoutBlockString)); - - trackArray = (CFArrayRef)CFDictionaryGetValue (theSessionDict, CFSTR(kTrackArrayString)); - - numTracks = CFArrayGetCount (trackArray); - - for(trackIndex = 0; trackIndex < numTracks; trackIndex++) { - + CFNumberRef leadoutBlock; + CFArrayRef trackArray; + CFIndex numTracks; + CFIndex trackIndex; + UInt32 value = 0; + + theSessionDict = (CFDictionaryRef) + CFArrayGetValueAtIndex(theSessionArrayRef, index); + leadoutBlock = + (CFNumberRef) CFDictionaryGetValue(theSessionDict, + CFSTR + (kLeadoutBlockString)); + + trackArray = + (CFArrayRef) CFDictionaryGetValue(theSessionDict, + CFSTR(kTrackArrayString)); + + numTracks = CFArrayGetCount(trackArray); + + for (trackIndex = 0; trackIndex < numTracks; trackIndex++) { + CFDictionaryRef theTrackDict; - CFNumberRef trackNumber; - CFNumberRef sessionNumber; - CFNumberRef startBlock; - CFBooleanRef isDataTrack; - UInt32 value; - - theTrackDict = (CFDictionaryRef) CFArrayGetValueAtIndex (trackArray, trackIndex); - - trackNumber = (CFNumberRef) CFDictionaryGetValue (theTrackDict, CFSTR(kPointKeyString)); - sessionNumber = (CFNumberRef) CFDictionaryGetValue (theTrackDict, CFSTR(kSessionNumberKeyString)); - startBlock = (CFNumberRef) CFDictionaryGetValue (theTrackDict, CFSTR(kStartBlockKeyString)); - isDataTrack = (CFBooleanRef) CFDictionaryGetValue (theTrackDict, CFSTR(kDataKeyString)); - + CFNumberRef trackNumber; + CFNumberRef sessionNumber; + CFNumberRef startBlock; + CFBooleanRef isDataTrack; + UInt32 value; + + theTrackDict = (CFDictionaryRef) + CFArrayGetValueAtIndex(trackArray, trackIndex); + + trackNumber = + (CFNumberRef) CFDictionaryGetValue(theTrackDict, + CFSTR + (kPointKeyString)); + sessionNumber = + (CFNumberRef) CFDictionaryGetValue(theTrackDict, + CFSTR + (kSessionNumberKeyString)); + startBlock = + (CFNumberRef) CFDictionaryGetValue(theTrackDict, + CFSTR + (kStartBlockKeyString)); + isDataTrack = + (CFBooleanRef) CFDictionaryGetValue(theTrackDict, + CFSTR + (kDataKeyString)); + /* Fill in the SDL_CD struct */ int idx = theCD->numtracks++; - CFNumberGetValue (trackNumber, kCFNumberSInt32Type, &value); + CFNumberGetValue(trackNumber, kCFNumberSInt32Type, &value); theCD->track[idx].id = value; - - CFNumberGetValue (startBlock, kCFNumberSInt32Type, &value); + + CFNumberGetValue(startBlock, kCFNumberSInt32Type, &value); theCD->track[idx].offset = value; - theCD->track[idx].type = (isDataTrack == kCFBooleanTrue) ? SDL_DATA_TRACK : SDL_AUDIO_TRACK; + theCD->track[idx].type = + (isDataTrack == + kCFBooleanTrue) ? SDL_DATA_TRACK : SDL_AUDIO_TRACK; /* Since the track lengths are not stored in .TOC.plist we compute them. */ if (trackIndex > 0) { - theCD->track[idx-1].length = theCD->track[idx].offset - theCD->track[idx-1].offset; + theCD->track[idx - 1].length = + theCD->track[idx].offset - theCD->track[idx - + 1].offset; } } - + /* Compute the length of the last track */ - CFNumberGetValue (leadoutBlock, kCFNumberSInt32Type, &value); - - theCD->track[theCD->numtracks-1].length = - value - theCD->track[theCD->numtracks-1].offset; + CFNumberGetValue(leadoutBlock, kCFNumberSInt32Type, &value); + + theCD->track[theCD->numtracks - 1].length = + value - theCD->track[theCD->numtracks - 1].offset; /* Set offset to leadout track */ theCD->track[theCD->numtracks].offset = value; } - + } theErr = 0; goto cleanup; -bail: - SDL_SetError ("ReadTOCData: %s returned %d", error, theErr); + bail: + SDL_SetError("ReadTOCData: %s returned %d", error, theErr); theErr = -1; -cleanup: + cleanup: if (propertyListRef != NULL) CFRelease(propertyListRef); @@ -306,323 +330,341 @@ int ReadTOCData (FSVolumeRefNum theVolume, SDL_CD *theCD) CFRelease(dataRef); if (forkData != NULL) DisposePtr(forkData); - - FSCloseFork (forkRefNum); + + FSCloseFork(forkRefNum); return theErr; } -int ListTrackFiles (FSVolumeRefNum theVolume, FSRef *trackFiles, int numTracks) +int +ListTrackFiles(FSVolumeRefNum theVolume, FSRef * trackFiles, int numTracks) { - OSStatus result = -1; - FSIterator iterator; - ItemCount actualObjects; - FSRef rootDirectory; - FSRef ref; - HFSUniStr255 nameStr; - - result = FSGetVolumeInfo (theVolume, - 0, - NULL, - kFSVolInfoFSInfo, - NULL, - NULL, - &rootDirectory); - + OSStatus result = -1; + FSIterator iterator; + ItemCount actualObjects; + FSRef rootDirectory; + FSRef ref; + HFSUniStr255 nameStr; + + result = FSGetVolumeInfo(theVolume, + 0, + NULL, + kFSVolInfoFSInfo, NULL, NULL, &rootDirectory); + if (result != noErr) { - SDL_SetError ("ListTrackFiles: FSGetVolumeInfo returned %d", result); + SDL_SetError("ListTrackFiles: FSGetVolumeInfo returned %d", result); return result; } - result = FSOpenIterator (&rootDirectory, kFSIterateFlat, &iterator); + result = FSOpenIterator(&rootDirectory, kFSIterateFlat, &iterator); if (result == noErr) { - do - { - result = FSGetCatalogInfoBulk (iterator, 1, &actualObjects, - NULL, kFSCatInfoNone, NULL, &ref, NULL, &nameStr); + do { + result = FSGetCatalogInfoBulk(iterator, 1, &actualObjects, + NULL, kFSCatInfoNone, NULL, + &ref, NULL, &nameStr); if (result == noErr) { - - CFStringRef name; - name = CFStringCreateWithCharacters (NULL, nameStr.unicode, nameStr.length); - + + CFStringRef name; + name = + CFStringCreateWithCharacters(NULL, nameStr.unicode, + nameStr.length); + /* Look for .aiff extension */ - if (CFStringHasSuffix (name, CFSTR(".aiff")) || - CFStringHasSuffix (name, CFSTR(".cdda"))) { - + if (CFStringHasSuffix(name, CFSTR(".aiff")) || + CFStringHasSuffix(name, CFSTR(".cdda"))) { + /* Extract the track id from the filename */ int trackID = 0, i = 0; while (i < nameStr.length && !isdigit(nameStr.unicode[i])) { ++i; } while (i < nameStr.length && isdigit(nameStr.unicode[i])) { - trackID = 10 * trackID +(nameStr.unicode[i] - '0'); + trackID = 10 * trackID + (nameStr.unicode[i] - '0'); ++i; } - #if DEBUG_CDROM - printf("Found AIFF for track %d: '%s'\n", trackID, - CFStringGetCStringPtr (name, CFStringGetSystemEncoding())); - #endif - +#if DEBUG_CDROM + printf("Found AIFF for track %d: '%s'\n", + trackID, CFStringGetCStringPtr(name, + CFStringGetSystemEncoding + ())); +#endif + /* Track ID's start at 1, but we want to start at 0 */ trackID--; - + assert(0 <= trackID && trackID <= SDL_MAX_TRACKS); - + if (trackID < numTracks) - memcpy (&trackFiles[trackID], &ref, sizeof(FSRef)); + memcpy(&trackFiles[trackID], &ref, sizeof(FSRef)); } - CFRelease (name); + CFRelease(name); } - } while(noErr == result); - FSCloseIterator (iterator); + } + while (noErr == result); + FSCloseIterator(iterator); } - + return 0; } -int LoadFile (const FSRef *ref, int startFrame, int stopFrame) +int +LoadFile(const FSRef * ref, int startFrame, int stopFrame) { int error = -1; - - if (CheckInit () < 0) + + if (CheckInit() < 0) goto bail; - + /* release any currently playing file */ - if (ReleaseFile () < 0) + if (ReleaseFile() < 0) goto bail; - - #if DEBUG_CDROM - printf ("LoadFile: %d %d\n", startFrame, stopFrame); - #endif - - /*try {*/ - - /* create a new player, and attach to the audio unit */ - - thePlayer = new_AudioFilePlayer(ref); - if (thePlayer == NULL) { - SDL_SetError ("LoadFile: Could not create player"); - return -3; /*throw (-3);*/ - } - - if (!thePlayer->SetDestination(thePlayer, &theUnit)) - goto bail; - - if (startFrame >= 0) - thePlayer->SetStartFrame (thePlayer, startFrame); - - if (stopFrame >= 0 && stopFrame > startFrame) - thePlayer->SetStopFrame (thePlayer, stopFrame); - - /* we set the notifier later */ - /*thePlayer->SetNotifier(thePlayer, FilePlayNotificationHandler, NULL);*/ - - if (!thePlayer->Connect(thePlayer)) - goto bail; - - #if DEBUG_CDROM - thePlayer->Print(thePlayer); - fflush (stdout); - #endif + +#if DEBUG_CDROM + printf("LoadFile: %d %d\n", startFrame, stopFrame); +#endif + + /*try { */ + + /* create a new player, and attach to the audio unit */ + + thePlayer = new_AudioFilePlayer(ref); + if (thePlayer == NULL) { + SDL_SetError("LoadFile: Could not create player"); + return -3; /*throw (-3); */ + } + + if (!thePlayer->SetDestination(thePlayer, &theUnit)) + goto bail; + + if (startFrame >= 0) + thePlayer->SetStartFrame(thePlayer, startFrame); + + if (stopFrame >= 0 && stopFrame > startFrame) + thePlayer->SetStopFrame(thePlayer, stopFrame); + + /* we set the notifier later */ + /*thePlayer->SetNotifier(thePlayer, FilePlayNotificationHandler, NULL); */ + + if (!thePlayer->Connect(thePlayer)) + goto bail; + +#if DEBUG_CDROM + thePlayer->Print(thePlayer); + fflush(stdout); +#endif /*} - catch (...) - { - goto bail; - }*/ - + catch (...) + { + goto bail; + } */ + error = 0; - bail: + bail: return error; } -int ReleaseFile () +int +ReleaseFile() { int error = -1; - + /* (Don't see any way that the original C++ code could throw here.) --ryan. */ - /*try {*/ - if (thePlayer != NULL) { - - thePlayer->Disconnect(thePlayer); - - delete_AudioFilePlayer(thePlayer); - - thePlayer = NULL; - } + /*try { */ + if (thePlayer != NULL) { + + thePlayer->Disconnect(thePlayer); + + delete_AudioFilePlayer(thePlayer); + + thePlayer = NULL; + } /*} - catch (...) - { - goto bail; - }*/ - + catch (...) + { + goto bail; + } */ + error = 0; - + /* bail: */ return error; } -int PlayFile () +int +PlayFile() { OSStatus result = -1; - - if (CheckInit () < 0) + + if (CheckInit() < 0) goto bail; - - /*try {*/ - - // start processing of the audio unit - result = AudioOutputUnitStart (theUnit); - if (result) goto bail; //THROW_RESULT("PlayFile: AudioOutputUnitStart") - + + /*try { */ + + // start processing of the audio unit + result = AudioOutputUnitStart(theUnit); + if (result) + goto bail; //THROW_RESULT("PlayFile: AudioOutputUnitStart") + /*} - catch (...) - { - goto bail; - }*/ - + catch (...) + { + goto bail; + } */ + result = 0; - -bail: + + bail: return result; } -int PauseFile () +int +PauseFile() { OSStatus result = -1; - - if (CheckInit () < 0) + + if (CheckInit() < 0) goto bail; - - /*try {*/ - - /* stop processing the audio unit */ - result = AudioOutputUnitStop (theUnit); - if (result) goto bail; /*THROW_RESULT("PauseFile: AudioOutputUnitStop")*/ + + /*try { */ + + /* stop processing the audio unit */ + result = AudioOutputUnitStop(theUnit); + if (result) + goto bail; /*THROW_RESULT("PauseFile: AudioOutputUnitStop") */ /*} - catch (...) - { - goto bail; - }*/ - + catch (...) + { + goto bail; + } */ + result = 0; -bail: + bail: return result; } -void SetCompletionProc (CDPlayerCompletionProc proc, SDL_CD *cdrom) +void +SetCompletionProc(CDPlayerCompletionProc proc, SDL_CD * cdrom) { assert(thePlayer != NULL); theCDROM = cdrom; completionProc = proc; - thePlayer->SetNotifier (thePlayer, FilePlayNotificationHandler, cdrom); + thePlayer->SetNotifier(thePlayer, FilePlayNotificationHandler, cdrom); } -int GetCurrentFrame () -{ +int +GetCurrentFrame() +{ int frame; - + if (thePlayer == NULL) frame = 0; else - frame = thePlayer->GetCurrentFrame (thePlayer); - - return frame; + frame = thePlayer->GetCurrentFrame(thePlayer); + + return frame; } #pragma mark -- Private Functions -- -static OSStatus CheckInit () -{ +static OSStatus +CheckInit() +{ if (playBackWasInit) return 0; - + OSStatus result = noErr; - + /* Create the callback semaphore */ callbackSem = SDL_CreateSemaphore(0); /* Start callback thread */ SDL_CreateThread(RunCallBackThread, NULL); - { /*try {*/ + { /*try { */ ComponentDescription desc; - + desc.componentType = kAudioUnitComponentType; desc.componentSubType = kAudioUnitSubType_Output; desc.componentManufacturer = kAudioUnitID_DefaultOutput; desc.componentFlags = 0; desc.componentFlagsMask = 0; - - Component comp = FindNextComponent (NULL, &desc); + + Component comp = FindNextComponent(NULL, &desc); if (comp == NULL) { - SDL_SetError ("CheckInit: FindNextComponent returned NULL"); - if (result) return -1; //throw(internalComponentErr); + SDL_SetError("CheckInit: FindNextComponent returned NULL"); + if (result) + return -1; //throw(internalComponentErr); } - - result = OpenAComponent (comp, &theUnit); - if (result) return -1; //THROW_RESULT("CheckInit: OpenAComponent") - + + result = OpenAComponent(comp, &theUnit); + if (result) + return -1; //THROW_RESULT("CheckInit: OpenAComponent") + // you need to initialize the output unit before you set it as a destination - result = AudioUnitInitialize (theUnit); - if (result) return -1; //THROW_RESULT("CheckInit: AudioUnitInitialize") - - + result = AudioUnitInitialize(theUnit); + if (result) + return -1; //THROW_RESULT("CheckInit: AudioUnitInitialize") + + playBackWasInit = true; } /*catch (...) - { - return -1; - }*/ - + { + return -1; + } */ + return 0; } -static void FilePlayNotificationHandler(void * inRefCon, OSStatus inStatus) +static void +FilePlayNotificationHandler(void *inRefCon, OSStatus inStatus) { if (inStatus == kAudioFilePlay_FileIsFinished) { - + /* notify non-CA thread to perform the callback */ SDL_SemPost(callbackSem); - + } else if (inStatus == kAudioFilePlayErr_FilePlayUnderrun) { - - SDL_SetError ("CDPlayer Notification: buffer underrun"); + + SDL_SetError("CDPlayer Notification: buffer underrun"); } else if (inStatus == kAudioFilePlay_PlayerIsUninitialized) { - - SDL_SetError ("CDPlayer Notification: player is uninitialized"); + + SDL_SetError("CDPlayer Notification: player is uninitialized"); } else { - - SDL_SetError ("CDPlayer Notification: unknown error %ld", inStatus); + + SDL_SetError("CDPlayer Notification: unknown error %ld", inStatus); } } -static int RunCallBackThread (void *param) +static int +RunCallBackThread(void *param) { for (;;) { - - SDL_SemWait(callbackSem); + + SDL_SemWait(callbackSem); if (completionProc && theCDROM) { - #if DEBUG_CDROM - printf ("callback!\n"); - #endif - (*completionProc)(theCDROM); +#if DEBUG_CDROM + printf("callback!\n"); +#endif + (*completionProc) (theCDROM); } else { - #if DEBUG_CDROM - printf ("callback?\n"); - #endif +#if DEBUG_CDROM + printf("callback?\n"); +#endif } } - - #if DEBUG_CDROM - printf ("thread dying now...\n"); - #endif - + +#if DEBUG_CDROM + printf("thread dying now...\n"); +#endif + return 0; } /*}; // extern "C" */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/cdrom/macosx/CDPlayer.h b/src/cdrom/macosx/CDPlayer.h index 5b41128dd..e44ee65d4 100644 --- a/src/cdrom/macosx/CDPlayer.h +++ b/src/cdrom/macosx/CDPlayer.h @@ -35,35 +35,38 @@ #include "SDL_mutex.h" #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif -typedef void (*CDPlayerCompletionProc)(SDL_CD *cdrom) ; + typedef void (*CDPlayerCompletionProc) (SDL_CD * cdrom); -void Lock (); + void Lock(); -void Unlock(); + void Unlock(); -int LoadFile (const FSRef *ref, int startFrame, int endFrame); /* pass -1 to do nothing */ + int LoadFile(const FSRef * ref, int startFrame, int endFrame); /* pass -1 to do nothing */ -int ReleaseFile (); + int ReleaseFile(); -int PlayFile (); + int PlayFile(); -int PauseFile (); + int PauseFile(); -void SetCompletionProc (CDPlayerCompletionProc proc, SDL_CD *cdrom); + void SetCompletionProc(CDPlayerCompletionProc proc, SDL_CD * cdrom); -int ReadTOCData (FSVolumeRefNum theVolume, SDL_CD *theCD); + int ReadTOCData(FSVolumeRefNum theVolume, SDL_CD * theCD); -int ListTrackFiles (FSVolumeRefNum theVolume, FSRef *trackFiles, int numTracks); + int ListTrackFiles(FSVolumeRefNum theVolume, FSRef * trackFiles, + int numTracks); -int DetectAudioCDVolumes (FSVolumeRefNum *volumes, int numVolumes); + int DetectAudioCDVolumes(FSVolumeRefNum * volumes, int numVolumes); -int GetCurrentFrame (); + int GetCurrentFrame(); #ifdef __cplusplus }; #endif #endif /* __CD_Player__H__ */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/cdrom/macosx/SDLOSXCAGuard.c b/src/cdrom/macosx/SDLOSXCAGuard.c index 7689c4ed9..651edc7c1 100644 --- a/src/cdrom/macosx/SDLOSXCAGuard.c +++ b/src/cdrom/macosx/SDLOSXCAGuard.c @@ -91,14 +91,14 @@ SDLOSXCAGuard =============================================================================*/ -static int SDLOSXCAGuard_Lock(SDLOSXCAGuard *cag) +static int +SDLOSXCAGuard_Lock(SDLOSXCAGuard * cag) { int theAnswer = 0; - - if(pthread_self() != cag->mOwner) - { + + if (pthread_self() != cag->mOwner) { OSStatus theError = pthread_mutex_lock(&cag->mMutex); - (void)theError; + (void) theError; assert(theError == 0); cag->mOwner = pthread_self(); theAnswer = 1; @@ -107,22 +107,24 @@ static int SDLOSXCAGuard_Lock(SDLOSXCAGuard *cag) return theAnswer; } -static void SDLOSXCAGuard_Unlock(SDLOSXCAGuard *cag) +static void +SDLOSXCAGuard_Unlock(SDLOSXCAGuard * cag) { OSStatus theError; assert(pthread_self() == cag->mOwner); cag->mOwner = 0; theError = pthread_mutex_unlock(&cag->mMutex); - (void)theError; + (void) theError; assert(theError == 0); } -static int SDLOSXCAGuard_Try (SDLOSXCAGuard *cag, int *outWasLocked) +static int +SDLOSXCAGuard_Try(SDLOSXCAGuard * cag, int *outWasLocked) { int theAnswer = 0; *outWasLocked = 0; - + if (pthread_self() == cag->mOwner) { theAnswer = 1; *outWasLocked = 0; @@ -134,11 +136,12 @@ static int SDLOSXCAGuard_Try (SDLOSXCAGuard *cag, int *outWasLocked) *outWasLocked = 1; } } - + return theAnswer; } -static void SDLOSXCAGuard_Wait(SDLOSXCAGuard *cag) +static void +SDLOSXCAGuard_Wait(SDLOSXCAGuard * cag) { OSStatus theError; assert(pthread_self() == cag->mOwner); @@ -146,54 +149,57 @@ static void SDLOSXCAGuard_Wait(SDLOSXCAGuard *cag) cag->mOwner = 0; theError = pthread_cond_wait(&cag->mCondVar, &cag->mMutex); - (void)theError; + (void) theError; assert(theError == 0); cag->mOwner = pthread_self(); } -static void SDLOSXCAGuard_Notify(SDLOSXCAGuard *cag) +static void +SDLOSXCAGuard_Notify(SDLOSXCAGuard * cag) { OSStatus theError = pthread_cond_signal(&cag->mCondVar); - (void)theError; + (void) theError; assert(theError == 0); } -SDLOSXCAGuard *new_SDLOSXCAGuard(void) +SDLOSXCAGuard * +new_SDLOSXCAGuard(void) { OSStatus theError; - SDLOSXCAGuard *cag = (SDLOSXCAGuard *) SDL_malloc(sizeof (SDLOSXCAGuard)); + SDLOSXCAGuard *cag = (SDLOSXCAGuard *) SDL_malloc(sizeof(SDLOSXCAGuard)); if (cag == NULL) return NULL; - SDL_memset(cag, '\0', sizeof (*cag)); + SDL_memset(cag, '\0', sizeof(*cag)); - #define SET_SDLOSXCAGUARD_METHOD(m) cag->m = SDLOSXCAGuard_##m +#define SET_SDLOSXCAGUARD_METHOD(m) cag->m = SDLOSXCAGuard_##m SET_SDLOSXCAGUARD_METHOD(Lock); SET_SDLOSXCAGUARD_METHOD(Unlock); SET_SDLOSXCAGUARD_METHOD(Try); SET_SDLOSXCAGUARD_METHOD(Wait); SET_SDLOSXCAGUARD_METHOD(Notify); - #undef SET_SDLOSXCAGUARD_METHOD +#undef SET_SDLOSXCAGUARD_METHOD theError = pthread_mutex_init(&cag->mMutex, NULL); - (void)theError; + (void) theError; assert(theError == 0); - + theError = pthread_cond_init(&cag->mCondVar, NULL); - (void)theError; + (void) theError; assert(theError == 0); - + cag->mOwner = 0; return cag; } -void delete_SDLOSXCAGuard(SDLOSXCAGuard *cag) +void +delete_SDLOSXCAGuard(SDLOSXCAGuard * cag) { - if (cag != NULL) - { + if (cag != NULL) { pthread_mutex_destroy(&cag->mMutex); pthread_cond_destroy(&cag->mCondVar); SDL_free(cag); } } +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/cdrom/macosx/SDLOSXCAGuard.h b/src/cdrom/macosx/SDLOSXCAGuard.h index 520387a5f..a4376c034 100644 --- a/src/cdrom/macosx/SDLOSXCAGuard.h +++ b/src/cdrom/macosx/SDLOSXCAGuard.h @@ -96,21 +96,21 @@ typedef struct S_SDLOSXCAGuard /*public:*/ /* Actions */ /*public:*/ - int (*Lock)(struct S_SDLOSXCAGuard *cag); - void (*Unlock)(struct S_SDLOSXCAGuard *cag); - int (*Try)(struct S_SDLOSXCAGuard *cag, int *outWasLocked); /* returns true if lock is free, false if not */ - void (*Wait)(struct S_SDLOSXCAGuard *cag); - void (*Notify)(struct S_SDLOSXCAGuard *cag); + int (*Lock) (struct S_SDLOSXCAGuard * cag); + void (*Unlock) (struct S_SDLOSXCAGuard * cag); + int (*Try) (struct S_SDLOSXCAGuard * cag, int *outWasLocked); /* returns true if lock is free, false if not */ + void (*Wait) (struct S_SDLOSXCAGuard * cag); + void (*Notify) (struct S_SDLOSXCAGuard * cag); /* Implementation */ /*protected:*/ pthread_mutex_t mMutex; - pthread_cond_t mCondVar; - pthread_t mOwner; + pthread_cond_t mCondVar; + pthread_t mOwner; } SDLOSXCAGuard; SDLOSXCAGuard *new_SDLOSXCAGuard(void); -void delete_SDLOSXCAGuard(SDLOSXCAGuard *cag); +void delete_SDLOSXCAGuard(SDLOSXCAGuard * cag); #endif - +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/cdrom/macosx/SDL_syscdrom.c b/src/cdrom/macosx/SDL_syscdrom.c index ea43d8bde..1a9d3c384 100644 --- a/src/cdrom/macosx/SDL_syscdrom.c +++ b/src/cdrom/macosx/SDL_syscdrom.c @@ -27,257 +27,265 @@ #pragma mark -- Globals -- -static FSRef** tracks; -static FSVolumeRefNum* volumes; -static CDstatus status; -static int nextTrackFrame; -static int nextTrackFramesRemaining; -static int fakeCD; -static int currentTrack; -static int didReadTOC; -static int cacheTOCNumTracks; -static int currentDrive; /* Only allow 1 drive in use at a time */ +static FSRef **tracks; +static FSVolumeRefNum *volumes; +static CDstatus status; +static int nextTrackFrame; +static int nextTrackFramesRemaining; +static int fakeCD; +static int currentTrack; +static int didReadTOC; +static int cacheTOCNumTracks; +static int currentDrive; /* Only allow 1 drive in use at a time */ #pragma mark -- Prototypes -- -static const char *SDL_SYS_CDName (int drive); -static int SDL_SYS_CDOpen (int drive); -static int SDL_SYS_CDGetTOC (SDL_CD *cdrom); -static CDstatus SDL_SYS_CDStatus (SDL_CD *cdrom, int *position); -static int SDL_SYS_CDPlay (SDL_CD *cdrom, int start, int length); -static int SDL_SYS_CDPause (SDL_CD *cdrom); -static int SDL_SYS_CDResume (SDL_CD *cdrom); -static int SDL_SYS_CDStop (SDL_CD *cdrom); -static int SDL_SYS_CDEject (SDL_CD *cdrom); -static void SDL_SYS_CDClose (SDL_CD *cdrom); +static const char *SDL_SYS_CDName(int drive); +static int SDL_SYS_CDOpen(int drive); +static int SDL_SYS_CDGetTOC(SDL_CD * cdrom); +static CDstatus SDL_SYS_CDStatus(SDL_CD * cdrom, int *position); +static int SDL_SYS_CDPlay(SDL_CD * cdrom, int start, int length); +static int SDL_SYS_CDPause(SDL_CD * cdrom); +static int SDL_SYS_CDResume(SDL_CD * cdrom); +static int SDL_SYS_CDStop(SDL_CD * cdrom); +static int SDL_SYS_CDEject(SDL_CD * cdrom); +static void SDL_SYS_CDClose(SDL_CD * cdrom); #pragma mark -- Helper Functions -- /* Read a list of tracks from the volume */ -static int LoadTracks (SDL_CD *cdrom) +static int +LoadTracks(SDL_CD * cdrom) { /* Check if tracks are already loaded */ - if ( tracks[cdrom->id] != NULL ) + if (tracks[cdrom->id] != NULL) return 0; - + /* Allocate memory for tracks */ - tracks[cdrom->id] = (FSRef*) SDL_calloc (1, sizeof(**tracks) * cdrom->numtracks); + tracks[cdrom->id] = + (FSRef *) SDL_calloc(1, sizeof(**tracks) * cdrom->numtracks); if (tracks[cdrom->id] == NULL) { - SDL_OutOfMemory (); + SDL_OutOfMemory(); return -1; } - + /* Load tracks */ - if (ListTrackFiles (volumes[cdrom->id], tracks[cdrom->id], cdrom->numtracks) < 0) + if (ListTrackFiles + (volumes[cdrom->id], tracks[cdrom->id], cdrom->numtracks) < 0) return -1; return 0; } /* Find a file for a given start frame and length */ -static FSRef* GetFileForOffset (SDL_CD *cdrom, int start, int length, int *outStartFrame, int *outStopFrame) +static FSRef * +GetFileForOffset(SDL_CD * cdrom, int start, int length, int *outStartFrame, + int *outStopFrame) { int i; - + for (i = 0; i < cdrom->numtracks; i++) { - + if (cdrom->track[i].offset <= start && start < (cdrom->track[i].offset + cdrom->track[i].length)) break; } - + if (i == cdrom->numtracks) return NULL; - + currentTrack = i; *outStartFrame = start - cdrom->track[i].offset; - + if ((*outStartFrame + length) < cdrom->track[i].length) { *outStopFrame = *outStartFrame + length; length = 0; nextTrackFrame = -1; nextTrackFramesRemaining = -1; - } - else { + } else { *outStopFrame = -1; length -= cdrom->track[i].length - *outStartFrame; - nextTrackFrame = cdrom->track[i+1].offset; + nextTrackFrame = cdrom->track[i + 1].offset; nextTrackFramesRemaining = length; } - + return &tracks[cdrom->id][i]; } /* Setup another file for playback, or stop playback (called from another thread) */ -static void CompletionProc (SDL_CD *cdrom) +static void +CompletionProc(SDL_CD * cdrom) { - - Lock (); - + + Lock(); + if (nextTrackFrame > 0 && nextTrackFramesRemaining > 0) { - + /* Load the next file to play */ int startFrame, stopFrame; FSRef *file; - - PauseFile (); - ReleaseFile (); - - file = GetFileForOffset (cdrom, nextTrackFrame, - nextTrackFramesRemaining, &startFrame, &stopFrame); - + + PauseFile(); + ReleaseFile(); + + file = GetFileForOffset(cdrom, nextTrackFrame, + nextTrackFramesRemaining, &startFrame, + &stopFrame); + if (file == NULL) { status = CD_STOPPED; - Unlock (); + Unlock(); return; } - - LoadFile (file, startFrame, stopFrame); - - SetCompletionProc (CompletionProc, cdrom); - - PlayFile (); - } - else { - + + LoadFile(file, startFrame, stopFrame); + + SetCompletionProc(CompletionProc, cdrom); + + PlayFile(); + } else { + /* Release the current file */ - PauseFile (); - ReleaseFile (); + PauseFile(); + ReleaseFile(); status = CD_STOPPED; } - - Unlock (); + + Unlock(); } #pragma mark -- Driver Functions -- /* Initialize */ -int SDL_SYS_CDInit (void) +int +SDL_SYS_CDInit(void) { /* Initialize globals */ volumes = NULL; - tracks = NULL; - status = CD_STOPPED; + tracks = NULL; + status = CD_STOPPED; nextTrackFrame = -1; nextTrackFramesRemaining = -1; - fakeCD = SDL_FALSE; + fakeCD = SDL_FALSE; currentTrack = -1; didReadTOC = SDL_FALSE; cacheTOCNumTracks = -1; currentDrive = -1; - + /* Fill in function pointers */ - SDL_CDcaps.Name = SDL_SYS_CDName; - SDL_CDcaps.Open = SDL_SYS_CDOpen; + SDL_CDcaps.Name = SDL_SYS_CDName; + SDL_CDcaps.Open = SDL_SYS_CDOpen; SDL_CDcaps.GetTOC = SDL_SYS_CDGetTOC; SDL_CDcaps.Status = SDL_SYS_CDStatus; - SDL_CDcaps.Play = SDL_SYS_CDPlay; - SDL_CDcaps.Pause = SDL_SYS_CDPause; + SDL_CDcaps.Play = SDL_SYS_CDPlay; + SDL_CDcaps.Pause = SDL_SYS_CDPause; SDL_CDcaps.Resume = SDL_SYS_CDResume; - SDL_CDcaps.Stop = SDL_SYS_CDStop; - SDL_CDcaps.Eject = SDL_SYS_CDEject; - SDL_CDcaps.Close = SDL_SYS_CDClose; + SDL_CDcaps.Stop = SDL_SYS_CDStop; + SDL_CDcaps.Eject = SDL_SYS_CDEject; + SDL_CDcaps.Close = SDL_SYS_CDClose; /* - Read the list of "drives" - - This is currently a hack that infers drives from - mounted audio CD volumes, rather than - actual CD-ROM devices - which means it may not - act as expected sometimes. - */ - + Read the list of "drives" + + This is currently a hack that infers drives from + mounted audio CD volumes, rather than + actual CD-ROM devices - which means it may not + act as expected sometimes. + */ + /* Find out how many cd volumes are mounted */ - SDL_numcds = DetectAudioCDVolumes (NULL, 0); + SDL_numcds = DetectAudioCDVolumes(NULL, 0); /* - If there are no volumes, fake a cd device - so tray empty can be reported. - */ + If there are no volumes, fake a cd device + so tray empty can be reported. + */ if (SDL_numcds == 0) { - + fakeCD = SDL_TRUE; SDL_numcds = 1; status = CD_TRAYEMPTY; - + return 0; } - + /* Allocate space for volumes */ - volumes = (FSVolumeRefNum*) SDL_calloc (1, sizeof(*volumes) * SDL_numcds); + volumes = (FSVolumeRefNum *) SDL_calloc(1, sizeof(*volumes) * SDL_numcds); if (volumes == NULL) { - SDL_OutOfMemory (); + SDL_OutOfMemory(); return -1; } - + /* Allocate space for tracks */ - tracks = (FSRef**) SDL_calloc (1, sizeof(*tracks) * (SDL_numcds + 1)); + tracks = (FSRef **) SDL_calloc(1, sizeof(*tracks) * (SDL_numcds + 1)); if (tracks == NULL) { - SDL_OutOfMemory (); + SDL_OutOfMemory(); return -1; } - + /* Mark the end of the tracks array */ - tracks[ SDL_numcds ] = (FSRef*)-1; - + tracks[SDL_numcds] = (FSRef *) - 1; + /* - Redetect, now save all volumes for later - Update SDL_numcds just in case it changed - */ + Redetect, now save all volumes for later + Update SDL_numcds just in case it changed + */ { int numVolumes = SDL_numcds; - - SDL_numcds = DetectAudioCDVolumes (volumes, numVolumes); - + + SDL_numcds = DetectAudioCDVolumes(volumes, numVolumes); + /* If more cds suddenly show up, ignore them */ if (SDL_numcds > numVolumes) { - SDL_SetError ("Some CD's were added but they will be ignored"); + SDL_SetError("Some CD's were added but they will be ignored"); SDL_numcds = numVolumes; } } - + return 0; } /* Shutdown and cleanup */ -void SDL_SYS_CDQuit(void) +void +SDL_SYS_CDQuit(void) { ReleaseFile(); - + if (volumes != NULL) - free (volumes); - + free(volumes); + if (tracks != NULL) { - + FSRef **ptr; - for (ptr = tracks; *ptr != (FSRef*)-1; ptr++) + for (ptr = tracks; *ptr != (FSRef *) - 1; ptr++) if (*ptr != NULL) - free (*ptr); - - free (tracks); + free(*ptr); + + free(tracks); } } /* Get the Unix disk name of the volume */ -static const char *SDL_SYS_CDName (int drive) +static const char * +SDL_SYS_CDName(int drive) { - OSStatus err = noErr; - HParamBlockRec pb; - GetVolParmsInfoBuffer volParmsInfo; - + OSStatus err = noErr; + HParamBlockRec pb; + GetVolParmsInfoBuffer volParmsInfo; + if (fakeCD) return "Fake CD-ROM Device"; pb.ioParam.ioNamePtr = NULL; pb.ioParam.ioVRefNum = volumes[drive]; - pb.ioParam.ioBuffer = (Ptr)&volParmsInfo; - pb.ioParam.ioReqCount = (SInt32)sizeof(volParmsInfo); + pb.ioParam.ioBuffer = (Ptr) & volParmsInfo; + pb.ioParam.ioReqCount = (SInt32) sizeof(volParmsInfo); err = PBHGetVolParmsSync(&pb); if (err != noErr) { - SDL_SetError ("PBHGetVolParmsSync returned %d", err); + SDL_SetError("PBHGetVolParmsSync returned %d", err); return NULL; } @@ -285,221 +293,231 @@ static const char *SDL_SYS_CDName (int drive) } /* Open the "device" */ -static int SDL_SYS_CDOpen (int drive) +static int +SDL_SYS_CDOpen(int drive) { /* Only allow 1 device to be open */ if (currentDrive >= 0) { - SDL_SetError ("Only one cdrom is supported"); + SDL_SetError("Only one cdrom is supported"); return -1; - } - else + } else currentDrive = drive; return drive; } /* Get the table of contents */ -static int SDL_SYS_CDGetTOC (SDL_CD *cdrom) +static int +SDL_SYS_CDGetTOC(SDL_CD * cdrom) { if (fakeCD) { - SDL_SetError (kErrorFakeDevice); + SDL_SetError(kErrorFakeDevice); return -1; } - + if (didReadTOC) { cdrom->numtracks = cacheTOCNumTracks; return 0; } - - - ReadTOCData (volumes[cdrom->id], cdrom); + + + ReadTOCData(volumes[cdrom->id], cdrom); didReadTOC = SDL_TRUE; cacheTOCNumTracks = cdrom->numtracks; - + return 0; } /* Get CD-ROM status */ -static CDstatus SDL_SYS_CDStatus (SDL_CD *cdrom, int *position) +static CDstatus +SDL_SYS_CDStatus(SDL_CD * cdrom, int *position) { if (position) { int trackFrame; - - Lock (); - trackFrame = GetCurrentFrame (); - Unlock (); - + + Lock(); + trackFrame = GetCurrentFrame(); + Unlock(); + *position = cdrom->track[currentTrack].offset + trackFrame; } - + return status; } /* Start playback */ -static int SDL_SYS_CDPlay(SDL_CD *cdrom, int start, int length) +static int +SDL_SYS_CDPlay(SDL_CD * cdrom, int start, int length) { int startFrame, stopFrame; FSRef *ref; - + if (fakeCD) { - SDL_SetError (kErrorFakeDevice); + SDL_SetError(kErrorFakeDevice); return -1; } - + Lock(); - - if (LoadTracks (cdrom) < 0) + + if (LoadTracks(cdrom) < 0) return -2; - - if (PauseFile () < 0) + + if (PauseFile() < 0) return -3; - - if (ReleaseFile () < 0) + + if (ReleaseFile() < 0) return -4; - - ref = GetFileForOffset (cdrom, start, length, &startFrame, &stopFrame); + + ref = GetFileForOffset(cdrom, start, length, &startFrame, &stopFrame); if (ref == NULL) { - SDL_SetError ("SDL_SYS_CDPlay: No file for start=%d, length=%d", start, length); + SDL_SetError("SDL_SYS_CDPlay: No file for start=%d, length=%d", + start, length); return -5; } - - if (LoadFile (ref, startFrame, stopFrame) < 0) + + if (LoadFile(ref, startFrame, stopFrame) < 0) return -6; - - SetCompletionProc (CompletionProc, cdrom); - - if (PlayFile () < 0) + + SetCompletionProc(CompletionProc, cdrom); + + if (PlayFile() < 0) return -7; - + status = CD_PLAYING; - + Unlock(); - + return 0; } /* Pause playback */ -static int SDL_SYS_CDPause(SDL_CD *cdrom) +static int +SDL_SYS_CDPause(SDL_CD * cdrom) { if (fakeCD) { - SDL_SetError (kErrorFakeDevice); + SDL_SetError(kErrorFakeDevice); return -1; } - - Lock (); - - if (PauseFile () < 0) { - Unlock (); + + Lock(); + + if (PauseFile() < 0) { + Unlock(); return -2; } - + status = CD_PAUSED; - - Unlock (); - + + Unlock(); + return 0; } /* Resume playback */ -static int SDL_SYS_CDResume(SDL_CD *cdrom) +static int +SDL_SYS_CDResume(SDL_CD * cdrom) { if (fakeCD) { - SDL_SetError (kErrorFakeDevice); + SDL_SetError(kErrorFakeDevice); return -1; } - - Lock (); - - if (PlayFile () < 0) { - Unlock (); + + Lock(); + + if (PlayFile() < 0) { + Unlock(); return -2; } - + status = CD_PLAYING; - - Unlock (); - + + Unlock(); + return 0; } /* Stop playback */ -static int SDL_SYS_CDStop(SDL_CD *cdrom) +static int +SDL_SYS_CDStop(SDL_CD * cdrom) { if (fakeCD) { - SDL_SetError (kErrorFakeDevice); + SDL_SetError(kErrorFakeDevice); return -1; } - - Lock (); - - if (PauseFile () < 0) { - Unlock (); + + Lock(); + + if (PauseFile() < 0) { + Unlock(); return -2; } - - if (ReleaseFile () < 0) { - Unlock (); + + if (ReleaseFile() < 0) { + Unlock(); return -3; } - + status = CD_STOPPED; - - Unlock (); - + + Unlock(); + return 0; } /* Eject the CD-ROM (Unmount the volume) */ -static int SDL_SYS_CDEject(SDL_CD *cdrom) +static int +SDL_SYS_CDEject(SDL_CD * cdrom) { OSStatus err; pid_t dissenter; if (fakeCD) { - SDL_SetError (kErrorFakeDevice); + SDL_SetError(kErrorFakeDevice); return -1; } - - Lock (); - - if (PauseFile () < 0) { - Unlock (); + + Lock(); + + if (PauseFile() < 0) { + Unlock(); return -2; } - - if (ReleaseFile () < 0) { - Unlock (); + + if (ReleaseFile() < 0) { + Unlock(); return -3; } - + status = CD_STOPPED; - - /* Eject the volume */ - err = FSEjectVolumeSync(volumes[cdrom->id], kNilOptions, &dissenter); - - if (err != noErr) { - Unlock (); - SDL_SetError ("PBUnmountVol returned %d", err); - return -4; - } - + + /* Eject the volume */ + err = FSEjectVolumeSync(volumes[cdrom->id], kNilOptions, &dissenter); + + if (err != noErr) { + Unlock(); + SDL_SetError("PBUnmountVol returned %d", err); + return -4; + } + status = CD_TRAYEMPTY; /* Invalidate volume and track info */ volumes[cdrom->id] = 0; - free (tracks[cdrom->id]); + free(tracks[cdrom->id]); tracks[cdrom->id] = NULL; - - Unlock (); - + + Unlock(); + return 0; } /* Close the CD-ROM */ -static void SDL_SYS_CDClose(SDL_CD *cdrom) +static void +SDL_SYS_CDClose(SDL_CD * cdrom) { currentDrive = -1; return; } #endif /* SDL_CDROM_MACOSX */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/cdrom/macosx/SDL_syscdrom_c.h b/src/cdrom/macosx/SDL_syscdrom_c.h index cc13198ef..4c263a47a 100644 --- a/src/cdrom/macosx/SDL_syscdrom_c.h +++ b/src/cdrom/macosx/SDL_syscdrom_c.h @@ -133,4 +133,4 @@ #include "CDPlayer.h" #define kErrorFakeDevice "Error: Cannot proceed since we're faking a CD-ROM device. Reinit the CD-ROM subsystem to scan for new volumes." - +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/cdrom/mint/SDL_syscdrom.c b/src/cdrom/mint/SDL_syscdrom.c index c817899b0..a1283146b 100644 --- a/src/cdrom/mint/SDL_syscdrom.c +++ b/src/cdrom/mint/SDL_syscdrom.c @@ -46,11 +46,12 @@ (errno == EINVAL) || (errno == ENOMEDIUM)) /* The maximum number of CD-ROM drives we'll detect */ -#define MAX_DRIVES 32 +#define MAX_DRIVES 32 -typedef struct { - unsigned char device[3]; /* Physical device letter + ':' + '\0' */ - metaopen_t metaopen; /* Infos on opened drive */ +typedef struct +{ + unsigned char device[3]; /* Physical device letter + ':' + '\0' */ + metaopen_t metaopen; /* Infos on opened drive */ } metados_drive_t; static metados_drive_t metados_drives[MAX_DRIVES]; @@ -58,260 +59,281 @@ static metados_drive_t metados_drives[MAX_DRIVES]; /* The system-dependent CD control functions */ static const char *SDL_SYS_CDName(int drive); static int SDL_SYS_CDOpen(int drive); -static void SDL_SYS_CDClose(SDL_CD *cdrom); +static void SDL_SYS_CDClose(SDL_CD * cdrom); static int SDL_SYS_CDioctl(int id, int command, void *arg); -static int SDL_SYS_CDGetTOC(SDL_CD *cdrom); -static CDstatus SDL_SYS_CDStatus(SDL_CD *cdrom, int *position); -static int SDL_SYS_CDPlay(SDL_CD *cdrom, int start, int length); -static int SDL_SYS_CDPause(SDL_CD *cdrom); -static int SDL_SYS_CDResume(SDL_CD *cdrom); -static int SDL_SYS_CDStop(SDL_CD *cdrom); -static int SDL_SYS_CDEject(SDL_CD *cdrom); - -int SDL_SYS_CDInit(void) +static int SDL_SYS_CDGetTOC(SDL_CD * cdrom); +static CDstatus SDL_SYS_CDStatus(SDL_CD * cdrom, int *position); +static int SDL_SYS_CDPlay(SDL_CD * cdrom, int start, int length); +static int SDL_SYS_CDPause(SDL_CD * cdrom); +static int SDL_SYS_CDResume(SDL_CD * cdrom); +static int SDL_SYS_CDStop(SDL_CD * cdrom); +static int SDL_SYS_CDEject(SDL_CD * cdrom); + +int +SDL_SYS_CDInit(void) { - metainit_t metainit={0,0,0,0}; - metaopen_t metaopen; - int i, handle; - struct cdrom_subchnl info; + metainit_t metainit = { 0, 0, 0, 0 }; + metaopen_t metaopen; + int i, handle; + struct cdrom_subchnl info; - Metainit(&metainit); - if (metainit.version == NULL) { + Metainit(&metainit); + if (metainit.version == NULL) { #ifdef DEBUG_CDROM - fprintf(stderr, "MetaDOS not installed\n"); + fprintf(stderr, "MetaDOS not installed\n"); #endif - return -1; - } + return -1; + } - if (metainit.drives_map == 0) { + if (metainit.drives_map == 0) { #ifdef DEBUG_CDROM - fprintf(stderr, "No MetaDOS devices present\n"); + fprintf(stderr, "No MetaDOS devices present\n"); #endif - return -1; - } - - SDL_numcds = 0; - - for (i='A'; i<='Z'; i++) { - metados_drives[SDL_numcds].device[0] = 0; - metados_drives[SDL_numcds].device[1] = ':'; - metados_drives[SDL_numcds].device[2] = 0; - - if (metainit.drives_map & (1<<(i-'A'))) { - handle = Metaopen(i, &metaopen); - if (handle == 0) { - - info.cdsc_format = CDROM_MSF; - if ( (Metaioctl(i, METADOS_IOCTL_MAGIC, CDROMSUBCHNL, &info) == 0) || ERRNO_TRAYEMPTY(errno) ) { - metados_drives[SDL_numcds].device[0] = i; - ++SDL_numcds; - } - - Metaclose(i); - } - } - } - - /* Fill in our driver capabilities */ - SDL_CDcaps.Name = SDL_SYS_CDName; - SDL_CDcaps.Open = SDL_SYS_CDOpen; - SDL_CDcaps.Close = SDL_SYS_CDClose; - - SDL_CDcaps.GetTOC = SDL_SYS_CDGetTOC; - SDL_CDcaps.Status = SDL_SYS_CDStatus; - SDL_CDcaps.Play = SDL_SYS_CDPlay; - SDL_CDcaps.Pause = SDL_SYS_CDPause; - SDL_CDcaps.Resume = SDL_SYS_CDResume; - SDL_CDcaps.Stop = SDL_SYS_CDStop; - SDL_CDcaps.Eject = SDL_SYS_CDEject; - - return 0; + return -1; + } + + SDL_numcds = 0; + + for (i = 'A'; i <= 'Z'; i++) { + metados_drives[SDL_numcds].device[0] = 0; + metados_drives[SDL_numcds].device[1] = ':'; + metados_drives[SDL_numcds].device[2] = 0; + + if (metainit.drives_map & (1 << (i - 'A'))) { + handle = Metaopen(i, &metaopen); + if (handle == 0) { + + info.cdsc_format = CDROM_MSF; + if ((Metaioctl + (i, METADOS_IOCTL_MAGIC, CDROMSUBCHNL, &info) == 0) + || ERRNO_TRAYEMPTY(errno)) { + metados_drives[SDL_numcds].device[0] = i; + ++SDL_numcds; + } + + Metaclose(i); + } + } + } + + /* Fill in our driver capabilities */ + SDL_CDcaps.Name = SDL_SYS_CDName; + SDL_CDcaps.Open = SDL_SYS_CDOpen; + SDL_CDcaps.Close = SDL_SYS_CDClose; + + SDL_CDcaps.GetTOC = SDL_SYS_CDGetTOC; + SDL_CDcaps.Status = SDL_SYS_CDStatus; + SDL_CDcaps.Play = SDL_SYS_CDPlay; + SDL_CDcaps.Pause = SDL_SYS_CDPause; + SDL_CDcaps.Resume = SDL_SYS_CDResume; + SDL_CDcaps.Stop = SDL_SYS_CDStop; + SDL_CDcaps.Eject = SDL_SYS_CDEject; + + return 0; } -void SDL_SYS_CDQuit(void) +void +SDL_SYS_CDQuit(void) { - SDL_numcds = 0; + SDL_numcds = 0; } -static const char *SDL_SYS_CDName(int drive) +static const char * +SDL_SYS_CDName(int drive) { - return(metados_drives[drive].device); + return (metados_drives[drive].device); } -static int SDL_SYS_CDOpen(int drive) +static int +SDL_SYS_CDOpen(int drive) { - int handle; + int handle; - handle = Metaopen(metados_drives[drive].device[0], &(metados_drives[drive].metaopen)); - if (handle == 0) { - return drive; - } + handle = + Metaopen(metados_drives[drive].device[0], + &(metados_drives[drive].metaopen)); + if (handle == 0) { + return drive; + } - return -1; + return -1; } -static void SDL_SYS_CDClose(SDL_CD *cdrom) +static void +SDL_SYS_CDClose(SDL_CD * cdrom) { - Metaclose(metados_drives[cdrom->id].device[0]); + Metaclose(metados_drives[cdrom->id].device[0]); } -static int SDL_SYS_CDioctl(int id, int command, void *arg) +static int +SDL_SYS_CDioctl(int id, int command, void *arg) { - int retval; - - retval = Metaioctl(metados_drives[id].device[0], METADOS_IOCTL_MAGIC, command, arg); - if ( retval < 0 ) { - SDL_SetError("ioctl() error: %s", strerror(errno)); - } - return(retval); + int retval; + + retval = + Metaioctl(metados_drives[id].device[0], METADOS_IOCTL_MAGIC, command, + arg); + if (retval < 0) { + SDL_SetError("ioctl() error: %s", strerror(errno)); + } + return (retval); } -static int SDL_SYS_CDGetTOC(SDL_CD *cdrom) +static int +SDL_SYS_CDGetTOC(SDL_CD * cdrom) { - int i,okay; - struct cdrom_tochdr toc; - struct cdrom_tocentry entry; - - /* Use standard ioctl() */ - if (SDL_SYS_CDioctl(cdrom->id, CDROMREADTOCHDR, &toc)<0) { - return -1; - } - - cdrom->numtracks = toc.cdth_trk1-toc.cdth_trk0+1; - if ( cdrom->numtracks > SDL_MAX_TRACKS ) { - cdrom->numtracks = SDL_MAX_TRACKS; - } - - /* Read all the track TOC entries */ - okay=1; - for ( i=0; i<=cdrom->numtracks; ++i ) { - if ( i == cdrom->numtracks ) { - cdrom->track[i].id = CDROM_LEADOUT; - } else { - cdrom->track[i].id = toc.cdth_trk0+i; - } - entry.cdte_track = cdrom->track[i].id; - entry.cdte_format = CDROM_MSF; - if ( SDL_SYS_CDioctl(cdrom->id, CDROMREADTOCENTRY, &entry) < 0 ) { - okay=0; - break; - } else { - if ( entry.cdte_ctrl & CDROM_DATA_TRACK ) { - cdrom->track[i].type = SDL_DATA_TRACK; - } else { - cdrom->track[i].type = SDL_AUDIO_TRACK; - } - cdrom->track[i].offset = MSF_TO_FRAMES( - entry.cdte_addr.msf.minute, - entry.cdte_addr.msf.second, - entry.cdte_addr.msf.frame); - cdrom->track[i].length = 0; - if ( i > 0 ) { - cdrom->track[i-1].length = cdrom->track[i].offset-cdrom->track[i-1].offset; - } - } - } - - return(okay ? 0 : -1); + int i, okay; + struct cdrom_tochdr toc; + struct cdrom_tocentry entry; + + /* Use standard ioctl() */ + if (SDL_SYS_CDioctl(cdrom->id, CDROMREADTOCHDR, &toc) < 0) { + return -1; + } + + cdrom->numtracks = toc.cdth_trk1 - toc.cdth_trk0 + 1; + if (cdrom->numtracks > SDL_MAX_TRACKS) { + cdrom->numtracks = SDL_MAX_TRACKS; + } + + /* Read all the track TOC entries */ + okay = 1; + for (i = 0; i <= cdrom->numtracks; ++i) { + if (i == cdrom->numtracks) { + cdrom->track[i].id = CDROM_LEADOUT; + } else { + cdrom->track[i].id = toc.cdth_trk0 + i; + } + entry.cdte_track = cdrom->track[i].id; + entry.cdte_format = CDROM_MSF; + if (SDL_SYS_CDioctl(cdrom->id, CDROMREADTOCENTRY, &entry) < 0) { + okay = 0; + break; + } else { + if (entry.cdte_ctrl & CDROM_DATA_TRACK) { + cdrom->track[i].type = SDL_DATA_TRACK; + } else { + cdrom->track[i].type = SDL_AUDIO_TRACK; + } + cdrom->track[i].offset = + MSF_TO_FRAMES(entry.cdte_addr.msf.minute, + entry.cdte_addr.msf.second, + entry.cdte_addr.msf.frame); + cdrom->track[i].length = 0; + if (i > 0) { + cdrom->track[i - 1].length = + cdrom->track[i].offset - cdrom->track[i - 1].offset; + } + } + } + + return (okay ? 0 : -1); } /* Get CD-ROM status */ -static CDstatus SDL_SYS_CDStatus(SDL_CD *cdrom, int *position) +static CDstatus +SDL_SYS_CDStatus(SDL_CD * cdrom, int *position) { - CDstatus status; - struct cdrom_tochdr toc; - struct cdrom_subchnl info; - - info.cdsc_format = CDROM_MSF; - if ( SDL_SYS_CDioctl(cdrom->id, CDROMSUBCHNL, &info) < 0 ) { - if ( ERRNO_TRAYEMPTY(errno) ) { - status = CD_TRAYEMPTY; - } else { - status = CD_ERROR; - } - } else { - switch (info.cdsc_audiostatus) { - case CDROM_AUDIO_INVALID: - case CDROM_AUDIO_NO_STATUS: - /* Try to determine if there's a CD available */ - if (SDL_SYS_CDioctl(cdrom->id, CDROMREADTOCHDR, &toc)==0) { - status = CD_STOPPED; - } else { - status = CD_TRAYEMPTY; - } - break; - case CDROM_AUDIO_COMPLETED: - status = CD_STOPPED; - break; - case CDROM_AUDIO_PLAY: - status = CD_PLAYING; - break; - case CDROM_AUDIO_PAUSED: - /* Workaround buggy CD-ROM drive */ - if ( info.cdsc_trk == CDROM_LEADOUT ) { - status = CD_STOPPED; - } else { - status = CD_PAUSED; - } - break; - default: - status = CD_ERROR; - break; - } - } - if ( position ) { - if ( status == CD_PLAYING || (status == CD_PAUSED) ) { - *position = MSF_TO_FRAMES( - info.cdsc_absaddr.msf.minute, - info.cdsc_absaddr.msf.second, - info.cdsc_absaddr.msf.frame); - } else { - *position = 0; - } - } - return(status); + CDstatus status; + struct cdrom_tochdr toc; + struct cdrom_subchnl info; + + info.cdsc_format = CDROM_MSF; + if (SDL_SYS_CDioctl(cdrom->id, CDROMSUBCHNL, &info) < 0) { + if (ERRNO_TRAYEMPTY(errno)) { + status = CD_TRAYEMPTY; + } else { + status = CD_ERROR; + } + } else { + switch (info.cdsc_audiostatus) { + case CDROM_AUDIO_INVALID: + case CDROM_AUDIO_NO_STATUS: + /* Try to determine if there's a CD available */ + if (SDL_SYS_CDioctl(cdrom->id, CDROMREADTOCHDR, &toc) == 0) { + status = CD_STOPPED; + } else { + status = CD_TRAYEMPTY; + } + break; + case CDROM_AUDIO_COMPLETED: + status = CD_STOPPED; + break; + case CDROM_AUDIO_PLAY: + status = CD_PLAYING; + break; + case CDROM_AUDIO_PAUSED: + /* Workaround buggy CD-ROM drive */ + if (info.cdsc_trk == CDROM_LEADOUT) { + status = CD_STOPPED; + } else { + status = CD_PAUSED; + } + break; + default: + status = CD_ERROR; + break; + } + } + if (position) { + if (status == CD_PLAYING || (status == CD_PAUSED)) { + *position = MSF_TO_FRAMES(info.cdsc_absaddr.msf.minute, + info.cdsc_absaddr.msf.second, + info.cdsc_absaddr.msf.frame); + } else { + *position = 0; + } + } + return (status); } /* Start play */ -static int SDL_SYS_CDPlay(SDL_CD *cdrom, int start, int length) +static int +SDL_SYS_CDPlay(SDL_CD * cdrom, int start, int length) { - struct cdrom_msf playtime; + struct cdrom_msf playtime; - FRAMES_TO_MSF(start, - &playtime.cdmsf_min0, &playtime.cdmsf_sec0, &playtime.cdmsf_frame0); - FRAMES_TO_MSF(start+length, - &playtime.cdmsf_min1, &playtime.cdmsf_sec1, &playtime.cdmsf_frame1); + FRAMES_TO_MSF(start, + &playtime.cdmsf_min0, &playtime.cdmsf_sec0, + &playtime.cdmsf_frame0); + FRAMES_TO_MSF(start + length, &playtime.cdmsf_min1, &playtime.cdmsf_sec1, + &playtime.cdmsf_frame1); #ifdef DEBUG_CDROM - fprintf(stderr, "Trying to play from %d:%d:%d to %d:%d:%d\n", - playtime.cdmsf_min0, playtime.cdmsf_sec0, playtime.cdmsf_frame0, - playtime.cdmsf_min1, playtime.cdmsf_sec1, playtime.cdmsf_frame1); + fprintf(stderr, "Trying to play from %d:%d:%d to %d:%d:%d\n", + playtime.cdmsf_min0, playtime.cdmsf_sec0, playtime.cdmsf_frame0, + playtime.cdmsf_min1, playtime.cdmsf_sec1, playtime.cdmsf_frame1); #endif - return SDL_SYS_CDioctl(cdrom->id, CDROMPLAYMSF, &playtime); + return SDL_SYS_CDioctl(cdrom->id, CDROMPLAYMSF, &playtime); } /* Pause play */ -static int SDL_SYS_CDPause(SDL_CD *cdrom) +static int +SDL_SYS_CDPause(SDL_CD * cdrom) { - return SDL_SYS_CDioctl(cdrom->id, CDROMPAUSE, 0); + return SDL_SYS_CDioctl(cdrom->id, CDROMPAUSE, 0); } /* Resume play */ -static int SDL_SYS_CDResume(SDL_CD *cdrom) +static int +SDL_SYS_CDResume(SDL_CD * cdrom) { - return SDL_SYS_CDioctl(cdrom->id, CDROMRESUME, 0); + return SDL_SYS_CDioctl(cdrom->id, CDROMRESUME, 0); } /* Stop play */ -static int SDL_SYS_CDStop(SDL_CD *cdrom) +static int +SDL_SYS_CDStop(SDL_CD * cdrom) { - return SDL_SYS_CDioctl(cdrom->id, CDROMSTOP, 0); + return SDL_SYS_CDioctl(cdrom->id, CDROMSTOP, 0); } /* Eject the CD-ROM */ -static int SDL_SYS_CDEject(SDL_CD *cdrom) +static int +SDL_SYS_CDEject(SDL_CD * cdrom) { - return SDL_SYS_CDioctl(cdrom->id, CDROMEJECT, 0); + return SDL_SYS_CDioctl(cdrom->id, CDROMEJECT, 0); } #endif /* SDL_CDROM_MINT */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/cdrom/openbsd/SDL_syscdrom.c b/src/cdrom/openbsd/SDL_syscdrom.c index 1d77c82c4..ce0deb0be 100644 --- a/src/cdrom/openbsd/SDL_syscdrom.c +++ b/src/cdrom/openbsd/SDL_syscdrom.c @@ -39,7 +39,7 @@ /* The maximum number of CD-ROM drives we'll detect */ -#define MAX_DRIVES 16 +#define MAX_DRIVES 16 /* A list of available CD-ROM drives */ static char *SDL_cdlist[MAX_DRIVES]; @@ -48,14 +48,14 @@ static dev_t SDL_cdmode[MAX_DRIVES]; /* The system-dependent CD control functions */ static const char *SDL_SYS_CDName(int drive); static int SDL_SYS_CDOpen(int drive); -static int SDL_SYS_CDGetTOC(SDL_CD *cdrom); -static CDstatus SDL_SYS_CDStatus(SDL_CD *cdrom, int *position); -static int SDL_SYS_CDPlay(SDL_CD *cdrom, int start, int length); -static int SDL_SYS_CDPause(SDL_CD *cdrom); -static int SDL_SYS_CDResume(SDL_CD *cdrom); -static int SDL_SYS_CDStop(SDL_CD *cdrom); -static int SDL_SYS_CDEject(SDL_CD *cdrom); -static void SDL_SYS_CDClose(SDL_CD *cdrom); +static int SDL_SYS_CDGetTOC(SDL_CD * cdrom); +static CDstatus SDL_SYS_CDStatus(SDL_CD * cdrom, int *position); +static int SDL_SYS_CDPlay(SDL_CD * cdrom, int start, int length); +static int SDL_SYS_CDPause(SDL_CD * cdrom); +static int SDL_SYS_CDResume(SDL_CD * cdrom); +static int SDL_SYS_CDStop(SDL_CD * cdrom); +static int SDL_SYS_CDEject(SDL_CD * cdrom); +static void SDL_SYS_CDClose(SDL_CD * cdrom); /* Some ioctl() errno values which occur when the tray is empty */ #define ERRNO_TRAYEMPTY(errno) \ @@ -63,353 +63,369 @@ static void SDL_SYS_CDClose(SDL_CD *cdrom); (errno == ENODEV)) /* Check a drive to see if it is a CD-ROM */ -static int CheckDrive(char *drive, struct stat *stbuf) +static int +CheckDrive(char *drive, struct stat *stbuf) { - int is_cd, cdfd; - struct ioc_read_subchannel info; - - /* If it doesn't exist, return -1 */ - if ( stat(drive, stbuf) < 0 ) { - return(-1); - } - - /* If it does exist, verify that it's an available CD-ROM */ - is_cd = 0; - if ( S_ISCHR(stbuf->st_mode) || S_ISBLK(stbuf->st_mode) ) { - cdfd = open(drive, (O_RDONLY|O_EXCL|O_NONBLOCK), 0); - if ( cdfd >= 0 ) { - info.address_format = CD_MSF_FORMAT; - info.data_format = CD_CURRENT_POSITION; - info.data_len = 0; - info.data = NULL; - /* Under Linux, EIO occurs when a disk is not present. - This isn't 100% reliable, so we use the USE_MNTENT - code above instead. - */ - if ( (ioctl(cdfd, CDIOCREADSUBCHANNEL, &info) == 0) || - ERRNO_TRAYEMPTY(errno) ) { - is_cd = 1; - } - close(cdfd); - } - else if (ERRNO_TRAYEMPTY(errno)) - is_cd = 1; - } - return(is_cd); + int is_cd, cdfd; + struct ioc_read_subchannel info; + + /* If it doesn't exist, return -1 */ + if (stat(drive, stbuf) < 0) { + return (-1); + } + + /* If it does exist, verify that it's an available CD-ROM */ + is_cd = 0; + if (S_ISCHR(stbuf->st_mode) || S_ISBLK(stbuf->st_mode)) { + cdfd = open(drive, (O_RDONLY | O_EXCL | O_NONBLOCK), 0); + if (cdfd >= 0) { + info.address_format = CD_MSF_FORMAT; + info.data_format = CD_CURRENT_POSITION; + info.data_len = 0; + info.data = NULL; + /* Under Linux, EIO occurs when a disk is not present. + This isn't 100% reliable, so we use the USE_MNTENT + code above instead. + */ + if ((ioctl(cdfd, CDIOCREADSUBCHANNEL, &info) == 0) || + ERRNO_TRAYEMPTY(errno)) { + is_cd = 1; + } + close(cdfd); + } else if (ERRNO_TRAYEMPTY(errno)) + is_cd = 1; + } + return (is_cd); } /* Add a CD-ROM drive to our list of valid drives */ -static void AddDrive(char *drive, struct stat *stbuf) +static void +AddDrive(char *drive, struct stat *stbuf) { - int i; - - if ( SDL_numcds < MAX_DRIVES ) { - /* Check to make sure it's not already in our list. - This can happen when we see a drive via symbolic link. - */ - for ( i=0; ist_rdev == SDL_cdmode[i] ) { + int i; + + if (SDL_numcds < MAX_DRIVES) { + /* Check to make sure it's not already in our list. + This can happen when we see a drive via symbolic link. + */ + for (i = 0; i < SDL_numcds; ++i) { + if (stbuf->st_rdev == SDL_cdmode[i]) { #ifdef DEBUG_CDROM - fprintf(stderr, "Duplicate drive detected: %s == %s\n", drive, SDL_cdlist[i]); + fprintf(stderr, "Duplicate drive detected: %s == %s\n", + drive, SDL_cdlist[i]); #endif - return; - } - } - - /* Add this drive to our list */ - i = SDL_numcds; - SDL_cdlist[i] = SDL_strdup(drive); - if ( SDL_cdlist[i] == NULL ) { - SDL_OutOfMemory(); - return; - } - SDL_cdmode[i] = stbuf->st_rdev; - ++SDL_numcds; + return; + } + } + + /* Add this drive to our list */ + i = SDL_numcds; + SDL_cdlist[i] = SDL_strdup(drive); + if (SDL_cdlist[i] == NULL) { + SDL_OutOfMemory(); + return; + } + SDL_cdmode[i] = stbuf->st_rdev; + ++SDL_numcds; #ifdef DEBUG_CDROM - fprintf(stderr, "Added CD-ROM drive: %s\n", drive); + fprintf(stderr, "Added CD-ROM drive: %s\n", drive); #endif - } + } } -int SDL_SYS_CDInit(void) +int +SDL_SYS_CDInit(void) { - static char *checklist[] = { + static char *checklist[] = { #if defined(__OPENBSD__) - "?0 cd?c", "cdrom", NULL + "?0 cd?c", "cdrom", NULL #elif defined(__NETBSD__) - "?0 cd?d", "?0 cd?c", "cdrom", NULL + "?0 cd?d", "?0 cd?c", "cdrom", NULL #else - "?0 cd?c", "?0 acd?c", "cdrom", NULL + "?0 cd?c", "?0 acd?c", "cdrom", NULL #endif - }; - char *SDLcdrom; - int i, j, exists; - char drive[32]; - struct stat stbuf; - - /* Fill in our driver capabilities */ - SDL_CDcaps.Name = SDL_SYS_CDName; - SDL_CDcaps.Open = SDL_SYS_CDOpen; - SDL_CDcaps.GetTOC = SDL_SYS_CDGetTOC; - SDL_CDcaps.Status = SDL_SYS_CDStatus; - SDL_CDcaps.Play = SDL_SYS_CDPlay; - SDL_CDcaps.Pause = SDL_SYS_CDPause; - SDL_CDcaps.Resume = SDL_SYS_CDResume; - SDL_CDcaps.Stop = SDL_SYS_CDStop; - SDL_CDcaps.Eject = SDL_SYS_CDEject; - SDL_CDcaps.Close = SDL_SYS_CDClose; - - /* Look in the environment for our CD-ROM drive list */ - SDLcdrom = SDL_getenv("SDL_CDROM"); /* ':' separated list of devices */ - if ( SDLcdrom != NULL ) { - char *cdpath, *delim; - size_t len = SDL_strlen(SDLcdrom)+1; - cdpath = SDL_stack_alloc(char, len); - if ( cdpath != NULL ) { - SDL_strlcpy(cdpath, SDLcdrom, len); - SDLcdrom = cdpath; - do { - delim = SDL_strchr(SDLcdrom, ':'); - if ( delim ) { - *delim++ = '\0'; - } - if ( CheckDrive(SDLcdrom, &stbuf) > 0 ) { - AddDrive(SDLcdrom, &stbuf); - } - if ( delim ) { - SDLcdrom = delim; - } else { - SDLcdrom = NULL; - } - } while ( SDLcdrom ); - SDL_stack_free(cdpath); - } - - /* If we found our drives, there's nothing left to do */ - if ( SDL_numcds > 0 ) { - return(0); - } - } - - /* Scan the system for CD-ROM drives */ - for ( i=0; checklist[i]; ++i ) { - if ( checklist[i][0] == '?' ) { - char *insert; - exists = 1; - for ( j=checklist[i][1]; exists; ++j ) { - SDL_snprintf(drive, SDL_arraysize(drive), "/dev/%s", &checklist[i][3]); - insert = SDL_strchr(drive, '?'); - if ( insert != NULL ) { - *insert = j; - } - switch (CheckDrive(drive, &stbuf)) { - /* Drive exists and is a CD-ROM */ - case 1: - AddDrive(drive, &stbuf); - break; - /* Drive exists, but isn't a CD-ROM */ - case 0: - break; - /* Drive doesn't exist */ - case -1: - exists = 0; - break; - } - } - } else { - SDL_snprintf(drive, SDL_arraysize(drive), "/dev/%s", checklist[i]); - if ( CheckDrive(drive, &stbuf) > 0 ) { - AddDrive(drive, &stbuf); - } - } - } - return(0); + }; + char *SDLcdrom; + int i, j, exists; + char drive[32]; + struct stat stbuf; + + /* Fill in our driver capabilities */ + SDL_CDcaps.Name = SDL_SYS_CDName; + SDL_CDcaps.Open = SDL_SYS_CDOpen; + SDL_CDcaps.GetTOC = SDL_SYS_CDGetTOC; + SDL_CDcaps.Status = SDL_SYS_CDStatus; + SDL_CDcaps.Play = SDL_SYS_CDPlay; + SDL_CDcaps.Pause = SDL_SYS_CDPause; + SDL_CDcaps.Resume = SDL_SYS_CDResume; + SDL_CDcaps.Stop = SDL_SYS_CDStop; + SDL_CDcaps.Eject = SDL_SYS_CDEject; + SDL_CDcaps.Close = SDL_SYS_CDClose; + + /* Look in the environment for our CD-ROM drive list */ + SDLcdrom = SDL_getenv("SDL_CDROM"); /* ':' separated list of devices */ + if (SDLcdrom != NULL) { + char *cdpath, *delim; + size_t len = SDL_strlen(SDLcdrom) + 1; + cdpath = SDL_stack_alloc(char, len); + if (cdpath != NULL) { + SDL_strlcpy(cdpath, SDLcdrom, len); + SDLcdrom = cdpath; + do { + delim = SDL_strchr(SDLcdrom, ':'); + if (delim) { + *delim++ = '\0'; + } + if (CheckDrive(SDLcdrom, &stbuf) > 0) { + AddDrive(SDLcdrom, &stbuf); + } + if (delim) { + SDLcdrom = delim; + } else { + SDLcdrom = NULL; + } + } + while (SDLcdrom); + SDL_stack_free(cdpath); + } + + /* If we found our drives, there's nothing left to do */ + if (SDL_numcds > 0) { + return (0); + } + } + + /* Scan the system for CD-ROM drives */ + for (i = 0; checklist[i]; ++i) { + if (checklist[i][0] == '?') { + char *insert; + exists = 1; + for (j = checklist[i][1]; exists; ++j) { + SDL_snprintf(drive, SDL_arraysize(drive), "/dev/%s", + &checklist[i][3]); + insert = SDL_strchr(drive, '?'); + if (insert != NULL) { + *insert = j; + } + switch (CheckDrive(drive, &stbuf)) { + /* Drive exists and is a CD-ROM */ + case 1: + AddDrive(drive, &stbuf); + break; + /* Drive exists, but isn't a CD-ROM */ + case 0: + break; + /* Drive doesn't exist */ + case -1: + exists = 0; + break; + } + } + } else { + SDL_snprintf(drive, SDL_arraysize(drive), "/dev/%s", + checklist[i]); + if (CheckDrive(drive, &stbuf) > 0) { + AddDrive(drive, &stbuf); + } + } + } + return (0); } /* General ioctl() CD-ROM command function */ -static int SDL_SYS_CDioctl(int id, int command, void *arg) +static int +SDL_SYS_CDioctl(int id, int command, void *arg) { - int retval; + int retval; - retval = ioctl(id, command, arg); - if ( retval < 0 ) { - SDL_SetError("ioctl() error: %s", strerror(errno)); - } - return(retval); + retval = ioctl(id, command, arg); + if (retval < 0) { + SDL_SetError("ioctl() error: %s", strerror(errno)); + } + return (retval); } -static const char *SDL_SYS_CDName(int drive) +static const char * +SDL_SYS_CDName(int drive) { - return(SDL_cdlist[drive]); + return (SDL_cdlist[drive]); } -static int SDL_SYS_CDOpen(int drive) +static int +SDL_SYS_CDOpen(int drive) { - return(open(SDL_cdlist[drive], (O_RDONLY|O_EXCL|O_NONBLOCK), 0)); + return (open(SDL_cdlist[drive], (O_RDONLY | O_EXCL | O_NONBLOCK), 0)); } -static int SDL_SYS_CDGetTOC(SDL_CD *cdrom) +static int +SDL_SYS_CDGetTOC(SDL_CD * cdrom) { - struct ioc_toc_header toc; - int i, okay; - struct ioc_read_toc_entry entry; - struct cd_toc_entry data; - - okay = 0; - if ( SDL_SYS_CDioctl(cdrom->id, CDIOREADTOCHEADER, &toc) == 0 ) { - cdrom->numtracks = toc.ending_track-toc.starting_track+1; - if ( cdrom->numtracks > SDL_MAX_TRACKS ) { - cdrom->numtracks = SDL_MAX_TRACKS; - } - /* Read all the track TOC entries */ - for ( i=0; i<=cdrom->numtracks; ++i ) { - if ( i == cdrom->numtracks ) { - cdrom->track[i].id = 0xAA; /* CDROM_LEADOUT */ - } else { - cdrom->track[i].id = toc.starting_track+i; - } - entry.starting_track = cdrom->track[i].id; - entry.address_format = CD_MSF_FORMAT; - entry.data_len = sizeof(data); - entry.data = &data; - if ( SDL_SYS_CDioctl(cdrom->id, CDIOREADTOCENTRYS, - &entry) < 0 ) { - break; - } else { - cdrom->track[i].type = data.control; - cdrom->track[i].offset = MSF_TO_FRAMES( - data.addr.msf.minute, - data.addr.msf.second, - data.addr.msf.frame); - cdrom->track[i].length = 0; - if ( i > 0 ) { - cdrom->track[i-1].length = - cdrom->track[i].offset- - cdrom->track[i-1].offset; - } - } - } - if ( i == (cdrom->numtracks+1) ) { - okay = 1; - } - } - return(okay ? 0 : -1); + struct ioc_toc_header toc; + int i, okay; + struct ioc_read_toc_entry entry; + struct cd_toc_entry data; + + okay = 0; + if (SDL_SYS_CDioctl(cdrom->id, CDIOREADTOCHEADER, &toc) == 0) { + cdrom->numtracks = toc.ending_track - toc.starting_track + 1; + if (cdrom->numtracks > SDL_MAX_TRACKS) { + cdrom->numtracks = SDL_MAX_TRACKS; + } + /* Read all the track TOC entries */ + for (i = 0; i <= cdrom->numtracks; ++i) { + if (i == cdrom->numtracks) { + cdrom->track[i].id = 0xAA; /* CDROM_LEADOUT */ + } else { + cdrom->track[i].id = toc.starting_track + i; + } + entry.starting_track = cdrom->track[i].id; + entry.address_format = CD_MSF_FORMAT; + entry.data_len = sizeof(data); + entry.data = &data; + if (SDL_SYS_CDioctl(cdrom->id, CDIOREADTOCENTRYS, &entry) < 0) { + break; + } else { + cdrom->track[i].type = data.control; + cdrom->track[i].offset = + MSF_TO_FRAMES(data.addr.msf.minute, + data.addr.msf.second, data.addr.msf.frame); + cdrom->track[i].length = 0; + if (i > 0) { + cdrom->track[i - 1].length = + cdrom->track[i].offset - cdrom->track[i - 1].offset; + } + } + } + if (i == (cdrom->numtracks + 1)) { + okay = 1; + } + } + return (okay ? 0 : -1); } /* Get CD-ROM status */ -static CDstatus SDL_SYS_CDStatus(SDL_CD *cdrom, int *position) +static CDstatus +SDL_SYS_CDStatus(SDL_CD * cdrom, int *position) { - CDstatus status; - struct ioc_toc_header toc; - struct ioc_read_subchannel info; - struct cd_sub_channel_info data; - - info.address_format = CD_MSF_FORMAT; - info.data_format = CD_CURRENT_POSITION; - info.track = 0; - info.data_len = sizeof(data); - info.data = &data; - if ( ioctl(cdrom->id, CDIOCREADSUBCHANNEL, &info) < 0 ) { - if ( ERRNO_TRAYEMPTY(errno) ) { - status = CD_TRAYEMPTY; - } else { - status = CD_ERROR; - } - } else { - switch (data.header.audio_status) { - case CD_AS_AUDIO_INVALID: - case CD_AS_NO_STATUS: - /* Try to determine if there's a CD available */ - if (ioctl(cdrom->id,CDIOREADTOCHEADER,&toc)==0) - status = CD_STOPPED; - else - status = CD_TRAYEMPTY; - break; - case CD_AS_PLAY_COMPLETED: - status = CD_STOPPED; - break; - case CD_AS_PLAY_IN_PROGRESS: - status = CD_PLAYING; - break; - case CD_AS_PLAY_PAUSED: - status = CD_PAUSED; - break; - default: - status = CD_ERROR; - break; - } - } - if ( position ) { - if ( status == CD_PLAYING || (status == CD_PAUSED) ) { - *position = MSF_TO_FRAMES( - data.what.position.absaddr.msf.minute, - data.what.position.absaddr.msf.second, - data.what.position.absaddr.msf.frame); - } else { - *position = 0; - } - } - return(status); + CDstatus status; + struct ioc_toc_header toc; + struct ioc_read_subchannel info; + struct cd_sub_channel_info data; + + info.address_format = CD_MSF_FORMAT; + info.data_format = CD_CURRENT_POSITION; + info.track = 0; + info.data_len = sizeof(data); + info.data = &data; + if (ioctl(cdrom->id, CDIOCREADSUBCHANNEL, &info) < 0) { + if (ERRNO_TRAYEMPTY(errno)) { + status = CD_TRAYEMPTY; + } else { + status = CD_ERROR; + } + } else { + switch (data.header.audio_status) { + case CD_AS_AUDIO_INVALID: + case CD_AS_NO_STATUS: + /* Try to determine if there's a CD available */ + if (ioctl(cdrom->id, CDIOREADTOCHEADER, &toc) == 0) + status = CD_STOPPED; + else + status = CD_TRAYEMPTY; + break; + case CD_AS_PLAY_COMPLETED: + status = CD_STOPPED; + break; + case CD_AS_PLAY_IN_PROGRESS: + status = CD_PLAYING; + break; + case CD_AS_PLAY_PAUSED: + status = CD_PAUSED; + break; + default: + status = CD_ERROR; + break; + } + } + if (position) { + if (status == CD_PLAYING || (status == CD_PAUSED)) { + *position = + MSF_TO_FRAMES(data.what.position.absaddr.msf.minute, + data.what.position.absaddr.msf.second, + data.what.position.absaddr.msf.frame); + } else { + *position = 0; + } + } + return (status); } /* Start play */ -static int SDL_SYS_CDPlay(SDL_CD *cdrom, int start, int length) +static int +SDL_SYS_CDPlay(SDL_CD * cdrom, int start, int length) { - struct ioc_play_msf playtime; + struct ioc_play_msf playtime; - FRAMES_TO_MSF(start, - &playtime.start_m, &playtime.start_s, &playtime.start_f); - FRAMES_TO_MSF(start+length, - &playtime.end_m, &playtime.end_s, &playtime.end_f); + FRAMES_TO_MSF(start, + &playtime.start_m, &playtime.start_s, &playtime.start_f); + FRAMES_TO_MSF(start + length, + &playtime.end_m, &playtime.end_s, &playtime.end_f); #ifdef DEBUG_CDROM - fprintf(stderr, "Trying to play from %d:%d:%d to %d:%d:%d\n", - playtime.start_m, playtime.start_s, playtime.start_f, - playtime.end_m, playtime.end_s, playtime.end_f); + fprintf(stderr, "Trying to play from %d:%d:%d to %d:%d:%d\n", + playtime.start_m, playtime.start_s, playtime.start_f, + playtime.end_m, playtime.end_s, playtime.end_f); #endif - ioctl(cdrom->id, CDIOCSTART, 0); - return(SDL_SYS_CDioctl(cdrom->id, CDIOCPLAYMSF, &playtime)); + ioctl(cdrom->id, CDIOCSTART, 0); + return (SDL_SYS_CDioctl(cdrom->id, CDIOCPLAYMSF, &playtime)); } /* Pause play */ -static int SDL_SYS_CDPause(SDL_CD *cdrom) +static int +SDL_SYS_CDPause(SDL_CD * cdrom) { - return(SDL_SYS_CDioctl(cdrom->id, CDIOCPAUSE, 0)); + return (SDL_SYS_CDioctl(cdrom->id, CDIOCPAUSE, 0)); } /* Resume play */ -static int SDL_SYS_CDResume(SDL_CD *cdrom) +static int +SDL_SYS_CDResume(SDL_CD * cdrom) { - return(SDL_SYS_CDioctl(cdrom->id, CDIOCRESUME, 0)); + return (SDL_SYS_CDioctl(cdrom->id, CDIOCRESUME, 0)); } /* Stop play */ -static int SDL_SYS_CDStop(SDL_CD *cdrom) +static int +SDL_SYS_CDStop(SDL_CD * cdrom) { - return(SDL_SYS_CDioctl(cdrom->id, CDIOCSTOP, 0)); + return (SDL_SYS_CDioctl(cdrom->id, CDIOCSTOP, 0)); } /* Eject the CD-ROM */ -static int SDL_SYS_CDEject(SDL_CD *cdrom) +static int +SDL_SYS_CDEject(SDL_CD * cdrom) { - return(SDL_SYS_CDioctl(cdrom->id, CDIOCEJECT, 0)); + return (SDL_SYS_CDioctl(cdrom->id, CDIOCEJECT, 0)); } /* Close the CD-ROM handle */ -static void SDL_SYS_CDClose(SDL_CD *cdrom) +static void +SDL_SYS_CDClose(SDL_CD * cdrom) { - close(cdrom->id); + close(cdrom->id); } -void SDL_SYS_CDQuit(void) +void +SDL_SYS_CDQuit(void) { - int i; - - if ( SDL_numcds > 0 ) { - for ( i=0; i 0) { + for (i = 0; i < SDL_numcds; ++i) { + SDL_free(SDL_cdlist[i]); + } + SDL_numcds = 0; + } } #endif /* SDL_CDROM_OPENBSD */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/cdrom/os2/SDL_syscdrom.c b/src/cdrom/os2/SDL_syscdrom.c index 56205fd7f..245e8d3de 100644 --- a/src/cdrom/os2/SDL_syscdrom.c +++ b/src/cdrom/os2/SDL_syscdrom.c @@ -36,7 +36,7 @@ #define MCI_CMDRETBUFSIZE 128 /* The maximum number of CD-ROM drives we'll detect */ -#define MAX_DRIVES 16 +#define MAX_DRIVES 16 /* A list of available CD-ROM drives */ static char *SDL_cdlist[MAX_DRIVES]; @@ -45,14 +45,14 @@ static char *SDL_cdlist[MAX_DRIVES]; /* The system-dependent CD control functions */ static const char *SDL_SYS_CDName(int drive); static int SDL_SYS_CDOpen(int drive); -static int SDL_SYS_CDGetTOC(SDL_CD *cdrom); -static CDstatus SDL_SYS_CDStatus(SDL_CD *cdrom, int *position); -static int SDL_SYS_CDPlay(SDL_CD *cdrom, int start, int length); -static int SDL_SYS_CDPause(SDL_CD *cdrom); -static int SDL_SYS_CDResume(SDL_CD *cdrom); -static int SDL_SYS_CDStop(SDL_CD *cdrom); -static int SDL_SYS_CDEject(SDL_CD *cdrom); -static void SDL_SYS_CDClose(SDL_CD *cdrom); +static int SDL_SYS_CDGetTOC(SDL_CD * cdrom); +static CDstatus SDL_SYS_CDStatus(SDL_CD * cdrom, int *position); +static int SDL_SYS_CDPlay(SDL_CD * cdrom, int start, int length); +static int SDL_SYS_CDPause(SDL_CD * cdrom); +static int SDL_SYS_CDResume(SDL_CD * cdrom); +static int SDL_SYS_CDStop(SDL_CD * cdrom); +static int SDL_SYS_CDEject(SDL_CD * cdrom); +static void SDL_SYS_CDClose(SDL_CD * cdrom); /* MCI Timing Functions */ #define MCI_MMTIMEPERSECOND 3000 @@ -60,334 +60,383 @@ static void SDL_SYS_CDClose(SDL_CD *cdrom); /* Ready for MCI CDAudio Devices */ -int SDL_SYS_CDInit(void) +int +SDL_SYS_CDInit(void) { -int i; /* generig counter */ -MCI_SYSINFO_PARMS msp; /* Structure to MCI SysInfo parameters */ -CHAR SysInfoRet[MCI_CMDRETBUFSIZE]; /* Buffer for MCI Command result */ + int i; /* generig counter */ + MCI_SYSINFO_PARMS msp; /* Structure to MCI SysInfo parameters */ + CHAR SysInfoRet[MCI_CMDRETBUFSIZE]; /* Buffer for MCI Command result */ /* Fill in our driver capabilities */ -SDL_CDcaps.Name = SDL_SYS_CDName; -SDL_CDcaps.Open = SDL_SYS_CDOpen; -SDL_CDcaps.GetTOC = SDL_SYS_CDGetTOC; -SDL_CDcaps.Status = SDL_SYS_CDStatus; -SDL_CDcaps.Play = SDL_SYS_CDPlay; -SDL_CDcaps.Pause = SDL_SYS_CDPause; -SDL_CDcaps.Resume = SDL_SYS_CDResume; -SDL_CDcaps.Stop = SDL_SYS_CDStop; -SDL_CDcaps.Eject = SDL_SYS_CDEject; -SDL_CDcaps.Close = SDL_SYS_CDClose; + SDL_CDcaps.Name = SDL_SYS_CDName; + SDL_CDcaps.Open = SDL_SYS_CDOpen; + SDL_CDcaps.GetTOC = SDL_SYS_CDGetTOC; + SDL_CDcaps.Status = SDL_SYS_CDStatus; + SDL_CDcaps.Play = SDL_SYS_CDPlay; + SDL_CDcaps.Pause = SDL_SYS_CDPause; + SDL_CDcaps.Resume = SDL_SYS_CDResume; + SDL_CDcaps.Stop = SDL_SYS_CDStop; + SDL_CDcaps.Eject = SDL_SYS_CDEject; + SDL_CDcaps.Close = SDL_SYS_CDClose; /* Get the number of CD ROMs in the System */ /* Clean SysInfo structure */ -SDL_memset(&msp, 0x00, sizeof(MCI_SYSINFO_PARMS)); + SDL_memset(&msp, 0x00, sizeof(MCI_SYSINFO_PARMS)); /* Prepare structure to Ask Numer of Audio CDs */ -msp.usDeviceType = MCI_DEVTYPE_CD_AUDIO; /* CD Audio Type */ -msp.pszReturn = (PSZ)&SysInfoRet; /* Return Structure */ -msp.ulRetSize = MCI_CMDRETBUFSIZE; /* Size of ret struct */ -if (LOUSHORT(mciSendCommand(0,MCI_SYSINFO, MCI_SYSINFO_QUANTITY | MCI_WAIT, (PVOID)&msp, 0)) != MCIERR_SUCCESS) return(CD_ERROR); -SDL_numcds = atoi(SysInfoRet); -if (SDL_numcds > MAX_DRIVES) SDL_numcds = MAX_DRIVES; /* Limit maximum CD number */ + msp.usDeviceType = MCI_DEVTYPE_CD_AUDIO; /* CD Audio Type */ + msp.pszReturn = (PSZ) & SysInfoRet; /* Return Structure */ + msp.ulRetSize = MCI_CMDRETBUFSIZE; /* Size of ret struct */ + if (LOUSHORT + (mciSendCommand + (0, MCI_SYSINFO, MCI_SYSINFO_QUANTITY | MCI_WAIT, (PVOID) & msp, + 0)) != MCIERR_SUCCESS) + return (CD_ERROR); + SDL_numcds = atoi(SysInfoRet); + if (SDL_numcds > MAX_DRIVES) + SDL_numcds = MAX_DRIVES; /* Limit maximum CD number */ /* Get and Add their system name to the SDL_cdlist */ -msp.pszReturn = (PSZ)&SysInfoRet; /* Return Structure */ -msp.ulRetSize = MCI_CMDRETBUFSIZE; /* Size of ret struct */ -msp.usDeviceType = MCI_DEVTYPE_CD_AUDIO; /* CD Audio Type */ -for (i=0; istatus == CD_PLAYING || cdrom->status == CD_PAUSED) return 0; + if (cdrom->status == CD_PLAYING || cdrom->status == CD_PAUSED) + return 0; /* Get Number of Tracks */ -msp.hwndCallback = (HWND)NULL; /* None */ -msp.ulReturn = (ULONG)NULL; /* We want this information */ -msp.ulItem = MCI_STATUS_NUMBER_OF_TRACKS; -msp.ulValue = (ULONG)NULL; /* No additional information */ -if (LOUSHORT(mciSendCommand(cdrom->id,MCI_STATUS,MCI_WAIT | MCI_STATUS_ITEM,&msp, 0)) != MCIERR_SUCCESS) return(CD_ERROR); -cdrom->numtracks = msp.ulReturn; -if ( cdrom->numtracks > SDL_MAX_TRACKS ) - { - cdrom->numtracks = SDL_MAX_TRACKS; - } + msp.hwndCallback = (HWND) NULL; /* None */ + msp.ulReturn = (ULONG) NULL; /* We want this information */ + msp.ulItem = MCI_STATUS_NUMBER_OF_TRACKS; + msp.ulValue = (ULONG) NULL; /* No additional information */ + if (LOUSHORT + (mciSendCommand + (cdrom->id, MCI_STATUS, MCI_WAIT | MCI_STATUS_ITEM, &msp, + 0)) != MCIERR_SUCCESS) + return (CD_ERROR); + cdrom->numtracks = msp.ulReturn; + if (cdrom->numtracks > SDL_MAX_TRACKS) { + cdrom->numtracks = SDL_MAX_TRACKS; + } /* Alocate space for TOC data */ -mtr = (MCI_TOC_REC *)SDL_malloc(cdrom->numtracks*sizeof(MCI_TOC_REC)); -if ( mtr == NULL ) - { - SDL_OutOfMemory(); - return(-1); - } + mtr = (MCI_TOC_REC *) SDL_malloc(cdrom->numtracks * sizeof(MCI_TOC_REC)); + if (mtr == NULL) { + SDL_OutOfMemory(); + return (-1); + } /* Get TOC from CD */ -mtp.pBuf = mtr; -mtp.ulBufSize = cdrom->numtracks*sizeof(MCI_TOC_REC); -if (LOUSHORT(mciSendCommand(cdrom->id,MCI_GETTOC,MCI_WAIT,&mtp, 0)) != MCIERR_SUCCESS) - { - SDL_OutOfMemory(); - SDL_free(mtr); - return(CD_ERROR); - } + mtp.pBuf = mtr; + mtp.ulBufSize = cdrom->numtracks * sizeof(MCI_TOC_REC); + if (LOUSHORT(mciSendCommand(cdrom->id, MCI_GETTOC, MCI_WAIT, &mtp, 0)) + != MCIERR_SUCCESS) { + SDL_OutOfMemory(); + SDL_free(mtr); + return (CD_ERROR); + } /* Fill SDL Tracks Structure */ -for (i=0; inumtracks; i++) - { - /* Set Track ID */ - cdrom->track[i].id = (mtr+i)->TrackNum; - /* Set Track Type */ - msp.hwndCallback = (HWND)NULL; /* None */ - msp.ulReturn = (ULONG)NULL; /* We want this information */ - msp.ulItem = MCI_CD_STATUS_TRACK_TYPE; - msp.ulValue = (ULONG)((mtr+i)->TrackNum); /* Track Number? */ - if (LOUSHORT(mciSendCommand(cdrom->id,MCI_STATUS,MCI_WAIT | MCI_TRACK | MCI_STATUS_ITEM,&msp, 0)) != MCIERR_SUCCESS) - { - SDL_free(mtr); - return (CD_ERROR); - } - if (msp.ulReturn==MCI_CD_TRACK_AUDIO) cdrom->track[i].type = SDL_AUDIO_TRACK; - else cdrom->track[i].type = SDL_DATA_TRACK; - /* Set Track Length - values from MCI are in MMTIMEs - 3000 MMTIME = 1 second */ - cdrom->track[i].length = FRAMESFROMMM((mtr+i)->ulEndAddr - (mtr+i)->ulStartAddr); - /* Set Track Offset */ - cdrom->track[i].offset = FRAMESFROMMM((mtr+i)->ulStartAddr); - } -SDL_free(mtr); -return(0); + for (i = 0; i < cdrom->numtracks; i++) { + /* Set Track ID */ + cdrom->track[i].id = (mtr + i)->TrackNum; + /* Set Track Type */ + msp.hwndCallback = (HWND) NULL; /* None */ + msp.ulReturn = (ULONG) NULL; /* We want this information */ + msp.ulItem = MCI_CD_STATUS_TRACK_TYPE; + msp.ulValue = (ULONG) ((mtr + i)->TrackNum); /* Track Number? */ + if (LOUSHORT + (mciSendCommand + (cdrom->id, MCI_STATUS, MCI_WAIT | MCI_TRACK | MCI_STATUS_ITEM, + &msp, 0)) != MCIERR_SUCCESS) { + SDL_free(mtr); + return (CD_ERROR); + } + if (msp.ulReturn == MCI_CD_TRACK_AUDIO) + cdrom->track[i].type = SDL_AUDIO_TRACK; + else + cdrom->track[i].type = SDL_DATA_TRACK; + /* Set Track Length - values from MCI are in MMTIMEs - 3000 MMTIME = 1 second */ + cdrom->track[i].length = + FRAMESFROMMM((mtr + i)->ulEndAddr - (mtr + i)->ulStartAddr); + /* Set Track Offset */ + cdrom->track[i].offset = FRAMESFROMMM((mtr + i)->ulStartAddr); + } + SDL_free(mtr); + return (0); } /* Get CD-ROM status - Ready for MCI */ -static CDstatus SDL_SYS_CDStatus(SDL_CD *cdrom, int *position) +static CDstatus +SDL_SYS_CDStatus(SDL_CD * cdrom, int *position) { -CDstatus status; -MCI_STATUS_PARMS msp; + CDstatus status; + MCI_STATUS_PARMS msp; /* Get Status from MCI */ -msp.hwndCallback = (HWND)NULL; /* None */ -msp.ulReturn = (ULONG)NULL; /* We want this information */ -msp.ulItem = MCI_STATUS_MODE; -msp.ulValue = (ULONG)NULL; /* No additional information */ -if (LOUSHORT(mciSendCommand(cdrom->id,MCI_STATUS,MCI_WAIT | MCI_STATUS_ITEM,&msp, 0)) != MCIERR_SUCCESS) status = CD_ERROR; -else - { - switch(msp.ulReturn) - { - case MCI_MODE_NOT_READY: - status = CD_TRAYEMPTY; - break; - case MCI_MODE_PAUSE: - status = CD_PAUSED; - break; - case MCI_MODE_PLAY: - status = CD_PLAYING; - break; - case MCI_MODE_STOP: - status = CD_STOPPED; - break; - /* These cases should not occour */ - case MCI_MODE_RECORD: - case MCI_MODE_SEEK: - default: - status = CD_ERROR; - break; - } - } + msp.hwndCallback = (HWND) NULL; /* None */ + msp.ulReturn = (ULONG) NULL; /* We want this information */ + msp.ulItem = MCI_STATUS_MODE; + msp.ulValue = (ULONG) NULL; /* No additional information */ + if (LOUSHORT + (mciSendCommand + (cdrom->id, MCI_STATUS, MCI_WAIT | MCI_STATUS_ITEM, &msp, + 0)) != MCIERR_SUCCESS) + status = CD_ERROR; + else { + switch (msp.ulReturn) { + case MCI_MODE_NOT_READY: + status = CD_TRAYEMPTY; + break; + case MCI_MODE_PAUSE: + status = CD_PAUSED; + break; + case MCI_MODE_PLAY: + status = CD_PLAYING; + break; + case MCI_MODE_STOP: + status = CD_STOPPED; + break; + /* These cases should not occour */ + case MCI_MODE_RECORD: + case MCI_MODE_SEEK: + default: + status = CD_ERROR; + break; + } + } /* Determine position */ -if (position != NULL) /* The SDL $&$&%# CDROM call sends NULL pointer here! */ - { - if ((status == CD_PLAYING) || (status == CD_PAUSED)) - { - /* Get Position */ - msp.hwndCallback = (HWND)NULL; /* None */ - msp.ulReturn = (ULONG)NULL; /* We want this information */ - msp.ulItem = MCI_STATUS_POSITION; - msp.ulValue = (ULONG)NULL; /* No additiona info */ - if (LOUSHORT(mciSendCommand(cdrom->id,MCI_STATUS,MCI_WAIT | MCI_STATUS_ITEM,&msp, 0)) != MCIERR_SUCCESS) return (CD_ERROR); - /* Convert from MSF (format selected in the Open process) to Frames (format that will be returned) */ - *position = MSF_TO_FRAMES(MSF_MINUTE(msp.ulReturn),MSF_SECOND(msp.ulReturn),MSF_FRAME(msp.ulReturn)); - } - else *position = 0; - } -return(status); + if (position != NULL) { /* The SDL $&$&%# CDROM call sends NULL pointer here! */ + if ((status == CD_PLAYING) || (status == CD_PAUSED)) { + /* Get Position */ + msp.hwndCallback = (HWND) NULL; /* None */ + msp.ulReturn = (ULONG) NULL; /* We want this information */ + msp.ulItem = MCI_STATUS_POSITION; + msp.ulValue = (ULONG) NULL; /* No additiona info */ + if (LOUSHORT + (mciSendCommand + (cdrom->id, MCI_STATUS, MCI_WAIT | MCI_STATUS_ITEM, &msp, + 0)) != MCIERR_SUCCESS) + return (CD_ERROR); + /* Convert from MSF (format selected in the Open process) to Frames (format that will be returned) */ + *position = + MSF_TO_FRAMES(MSF_MINUTE(msp.ulReturn), + MSF_SECOND(msp.ulReturn), + MSF_FRAME(msp.ulReturn)); + } else + *position = 0; + } + return (status); } /* Start play - Ready for MCI */ -static int SDL_SYS_CDPlay(SDL_CD *cdrom, int start, int length) +static int +SDL_SYS_CDPlay(SDL_CD * cdrom, int start, int length) { -MCI_GENERIC_PARMS mgp; -MCI_STATUS_PARMS msp; -MCI_PLAY_PARMS mpp; -ULONG min,sec,frm; + MCI_GENERIC_PARMS mgp; + MCI_STATUS_PARMS msp; + MCI_PLAY_PARMS mpp; + ULONG min, sec, frm; /* Start MSF */ -FRAMES_TO_MSF(start, &min, &sec, &frm); -MSF_MINUTE(mpp.ulFrom) = min; -MSF_SECOND(mpp.ulFrom) = sec; -MSF_FRAME(mpp.ulFrom) = frm; + FRAMES_TO_MSF(start, &min, &sec, &frm); + MSF_MINUTE(mpp.ulFrom) = min; + MSF_SECOND(mpp.ulFrom) = sec; + MSF_FRAME(mpp.ulFrom) = frm; /* End MSF */ -FRAMES_TO_MSF(start+length, &min, &sec, &frm); -MSF_MINUTE(mpp.ulTo) = min; -MSF_SECOND(mpp.ulTo) = sec; -MSF_FRAME(mpp.ulTo) = frm; + FRAMES_TO_MSF(start + length, &min, &sec, &frm); + MSF_MINUTE(mpp.ulTo) = min; + MSF_SECOND(mpp.ulTo) = sec; + MSF_FRAME(mpp.ulTo) = frm; #ifdef DEBUG_CDROM - fprintf(stderr, "Trying to play from %d:%d:%d to %d:%d:%d\n", - playtime.cdmsf_min0, playtime.cdmsf_sec0, playtime.cdmsf_frame0, - playtime.cdmsf_min1, playtime.cdmsf_sec1, playtime.cdmsf_frame1); + fprintf(stderr, "Trying to play from %d:%d:%d to %d:%d:%d\n", + playtime.cdmsf_min0, playtime.cdmsf_sec0, playtime.cdmsf_frame0, + playtime.cdmsf_min1, playtime.cdmsf_sec1, playtime.cdmsf_frame1); #endif /* Verifies if it is paused first... and if it is, unpause before stopping it. */ -msp.hwndCallback = (HWND)NULL; /* None */ -msp.ulReturn = (ULONG)NULL; /* We want this information */ -msp.ulItem = MCI_STATUS_MODE; -msp.ulValue = (ULONG)NULL; /* No additional information */ -if (LOUSHORT(mciSendCommand(cdrom->id,MCI_STATUS,MCI_WAIT | MCI_STATUS_ITEM,&msp, 0)) == MCIERR_SUCCESS) - { - if (msp.ulReturn == MCI_MODE_PAUSE) - { - mgp.hwndCallback = (HWND)NULL; // None - mciSendCommand(cdrom->id,MCI_RESUME,0,&mgp, 0); - } - } + msp.hwndCallback = (HWND) NULL; /* None */ + msp.ulReturn = (ULONG) NULL; /* We want this information */ + msp.ulItem = MCI_STATUS_MODE; + msp.ulValue = (ULONG) NULL; /* No additional information */ + if (LOUSHORT + (mciSendCommand + (cdrom->id, MCI_STATUS, MCI_WAIT | MCI_STATUS_ITEM, &msp, + 0)) == MCIERR_SUCCESS) { + if (msp.ulReturn == MCI_MODE_PAUSE) { + mgp.hwndCallback = (HWND) NULL; // None + mciSendCommand(cdrom->id, MCI_RESUME, 0, &mgp, 0); + } + } /* Now play it. */ -mpp.hwndCallback = (HWND)NULL; // We do not want the info. temp -if (LOUSHORT(mciSendCommand(cdrom->id,MCI_PLAY,MCI_FROM | MCI_TO,&mpp, 0)) == MCIERR_SUCCESS) return 0; -return (CD_ERROR); + mpp.hwndCallback = (HWND) NULL; // We do not want the info. temp + if (LOUSHORT + (mciSendCommand(cdrom->id, MCI_PLAY, MCI_FROM | MCI_TO, &mpp, 0)) == + MCIERR_SUCCESS) + return 0; + return (CD_ERROR); } /* Pause play - Ready for MCI */ -static int SDL_SYS_CDPause(SDL_CD *cdrom) +static int +SDL_SYS_CDPause(SDL_CD * cdrom) { -MCI_GENERIC_PARMS mgp; + MCI_GENERIC_PARMS mgp; -mgp.hwndCallback = (HWND)NULL; // None -if (LOUSHORT(mciSendCommand(cdrom->id,MCI_PAUSE,MCI_WAIT,&mgp, 0)) == MCIERR_SUCCESS) return 0; -return(CD_ERROR); + mgp.hwndCallback = (HWND) NULL; // None + if (LOUSHORT(mciSendCommand(cdrom->id, MCI_PAUSE, MCI_WAIT, &mgp, 0)) == + MCIERR_SUCCESS) + return 0; + return (CD_ERROR); } /* Resume play - Ready for MCI */ -static int SDL_SYS_CDResume(SDL_CD *cdrom) +static int +SDL_SYS_CDResume(SDL_CD * cdrom) { -MCI_GENERIC_PARMS mgp; + MCI_GENERIC_PARMS mgp; -mgp.hwndCallback = (HWND)NULL; // None -if (LOUSHORT(mciSendCommand(cdrom->id,MCI_RESUME,MCI_WAIT,&mgp, 0)) == MCIERR_SUCCESS) return 0; -return(CD_ERROR); + mgp.hwndCallback = (HWND) NULL; // None + if (LOUSHORT(mciSendCommand(cdrom->id, MCI_RESUME, MCI_WAIT, &mgp, 0)) + == MCIERR_SUCCESS) + return 0; + return (CD_ERROR); } /* Stop play - Ready for MCI */ -static int SDL_SYS_CDStop(SDL_CD *cdrom) +static int +SDL_SYS_CDStop(SDL_CD * cdrom) { -MCI_GENERIC_PARMS mgp; -MCI_STATUS_PARMS msp; + MCI_GENERIC_PARMS mgp; + MCI_STATUS_PARMS msp; /* Verifies if it is paused first... and if it is, unpause before stopping it. */ -msp.hwndCallback = (HWND)NULL; /* None */ -msp.ulReturn = (ULONG)NULL; /* We want this information */ -msp.ulItem = MCI_STATUS_MODE; -msp.ulValue = (ULONG)NULL; /* No additional information */ -if (LOUSHORT(mciSendCommand(cdrom->id,MCI_STATUS,MCI_WAIT | MCI_STATUS_ITEM,&msp, 0)) == MCIERR_SUCCESS) - { - if (msp.ulReturn == MCI_MODE_PAUSE) - { - mgp.hwndCallback = (HWND)NULL; // None - mciSendCommand(cdrom->id,MCI_RESUME,0,&mgp, 0); - } - } + msp.hwndCallback = (HWND) NULL; /* None */ + msp.ulReturn = (ULONG) NULL; /* We want this information */ + msp.ulItem = MCI_STATUS_MODE; + msp.ulValue = (ULONG) NULL; /* No additional information */ + if (LOUSHORT + (mciSendCommand + (cdrom->id, MCI_STATUS, MCI_WAIT | MCI_STATUS_ITEM, &msp, + 0)) == MCIERR_SUCCESS) { + if (msp.ulReturn == MCI_MODE_PAUSE) { + mgp.hwndCallback = (HWND) NULL; // None + mciSendCommand(cdrom->id, MCI_RESUME, 0, &mgp, 0); + } + } /* Now stops the media */ -mgp.hwndCallback = (HWND)NULL; // None -if (LOUSHORT(mciSendCommand(cdrom->id,MCI_STOP,MCI_WAIT,&mgp, 0)) == MCIERR_SUCCESS) return 0; -return(CD_ERROR); + mgp.hwndCallback = (HWND) NULL; // None + if (LOUSHORT(mciSendCommand(cdrom->id, MCI_STOP, MCI_WAIT, &mgp, 0)) == + MCIERR_SUCCESS) + return 0; + return (CD_ERROR); } /* Eject the CD-ROM - Ready for MCI */ -static int SDL_SYS_CDEject(SDL_CD *cdrom) +static int +SDL_SYS_CDEject(SDL_CD * cdrom) { -MCI_SET_PARMS msp; - -msp.hwndCallback = (HWND)NULL; // None -msp.ulTimeFormat = (ULONG)NULL; // No change -msp.ulSpeedFormat = (ULONG)NULL; // No change -msp.ulAudio = (ULONG)NULL; // No Channel -msp.ulLevel = (ULONG)NULL; // No Volume -msp.ulOver = (ULONG)NULL; // No Delay -msp.ulItem = (ULONG)NULL; // No item -msp.ulValue = (ULONG)NULL; // No value for item flag -if (LOUSHORT(mciSendCommand(cdrom->id,MCI_SET,MCI_WAIT | MCI_SET_DOOR_OPEN,&msp, 0)) == MCIERR_SUCCESS) return 0; -return(CD_ERROR); + MCI_SET_PARMS msp; + + msp.hwndCallback = (HWND) NULL; // None + msp.ulTimeFormat = (ULONG) NULL; // No change + msp.ulSpeedFormat = (ULONG) NULL; // No change + msp.ulAudio = (ULONG) NULL; // No Channel + msp.ulLevel = (ULONG) NULL; // No Volume + msp.ulOver = (ULONG) NULL; // No Delay + msp.ulItem = (ULONG) NULL; // No item + msp.ulValue = (ULONG) NULL; // No value for item flag + if (LOUSHORT + (mciSendCommand + (cdrom->id, MCI_SET, MCI_WAIT | MCI_SET_DOOR_OPEN, &msp, + 0)) == MCIERR_SUCCESS) + return 0; + return (CD_ERROR); } /* Close the CD-ROM handle - Ready for MCI */ -static void SDL_SYS_CDClose(SDL_CD *cdrom) +static void +SDL_SYS_CDClose(SDL_CD * cdrom) { -MCI_GENERIC_PARMS mgp; + MCI_GENERIC_PARMS mgp; -mgp.hwndCallback = (HWND)NULL; // None -mciSendCommand(cdrom->id,MCI_CLOSE,MCI_WAIT,&mgp, 0); + mgp.hwndCallback = (HWND) NULL; // None + mciSendCommand(cdrom->id, MCI_CLOSE, MCI_WAIT, &mgp, 0); } /* Finalize CDROM Subsystem - Ready for MCI */ -void SDL_SYS_CDQuit(void) +void +SDL_SYS_CDQuit(void) { -int i; - -if ( SDL_numcds > 0 ) - { - for ( i=0; i 0) { + for (i = 0; i < SDL_numcds; ++i) { + SDL_free(SDL_cdlist[i]); + } + SDL_numcds = 0; + } } #endif /* SDL_CDROM_OS2 */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/cdrom/osf/SDL_syscdrom.c b/src/cdrom/osf/SDL_syscdrom.c index 8478a7b4c..5ee6e202e 100644 --- a/src/cdrom/osf/SDL_syscdrom.c +++ b/src/cdrom/osf/SDL_syscdrom.c @@ -46,95 +46,100 @@ static dev_t SDL_cdmode[MAX_DRIVES]; /* The system-dependent CD control functions */ static const char *SDL_SYS_CDName(int drive); -static int SDL_SYS_CDOpen(int drive); -static int SDL_SYS_CDGetTOC(SDL_CD *cdrom); -static CDstatus SDL_SYS_CDStatus(SDL_CD *cdrom, int *position); -static int SDL_SYS_CDPlay(SDL_CD *cdrom, int start, int length); -static int SDL_SYS_CDPause(SDL_CD *cdrom); -static int SDL_SYS_CDResume(SDL_CD *cdrom); -static int SDL_SYS_CDStop(SDL_CD *cdrom); -static int SDL_SYS_CDEject(SDL_CD *cdrom); -static void SDL_SYS_CDClose(SDL_CD *cdrom); +static int SDL_SYS_CDOpen(int drive); +static int SDL_SYS_CDGetTOC(SDL_CD * cdrom); +static CDstatus SDL_SYS_CDStatus(SDL_CD * cdrom, int *position); +static int SDL_SYS_CDPlay(SDL_CD * cdrom, int start, int length); +static int SDL_SYS_CDPause(SDL_CD * cdrom); +static int SDL_SYS_CDResume(SDL_CD * cdrom); +static int SDL_SYS_CDStop(SDL_CD * cdrom); +static int SDL_SYS_CDEject(SDL_CD * cdrom); +static void SDL_SYS_CDClose(SDL_CD * cdrom); /* Check a drive to see if it is a CD-ROM */ -/* Caution!! Not tested. */ -static int CheckDrive(char *drive, struct stat *stbuf) +/* Caution!! Not tested. */ +static int +CheckDrive(char *drive, struct stat *stbuf) { int cdfd, is_cd = 0; struct mode_sel_sns_params msp; struct inquiry_info inq; #ifdef DEBUG_CDROM - char *devtype[] = {"Disk", "Tape", "Printer", "Processor", "WORM", - "CD-ROM", "Scanner", "Optical", "Changer", "Comm", "Unknown"}; + char *devtype[] = { "Disk", "Tape", "Printer", "Processor", "WORM", + "CD-ROM", "Scanner", "Optical", "Changer", "Comm", "Unknown" + }; #endif bzero(&msp, sizeof(msp)); bzero(&inq, sizeof(inq)); /* If it doesn't exist, return -1 */ - if ( stat(drive, stbuf) < 0 ) { - return(-1); + if (stat(drive, stbuf) < 0) { + return (-1); } - if ( (cdfd = open(drive, (O_RDWR|O_NDELAY), 0)) >= 0 ) { - msp.msp_addr = (caddr_t) &inq; - msp.msp_pgcode = 0; - msp.msp_pgctrl = 0; - msp.msp_length = sizeof(inq); - msp.msp_setps = 0; + if ((cdfd = open(drive, (O_RDWR | O_NDELAY), 0)) >= 0) { + msp.msp_addr = (caddr_t) & inq; + msp.msp_pgcode = 0; + msp.msp_pgctrl = 0; + msp.msp_length = sizeof(inq); + msp.msp_setps = 0; - if ( ioctl(cdfd, SCSI_GET_INQUIRY_DATA, &msp) ) - return (0); + if (ioctl(cdfd, SCSI_GET_INQUIRY_DATA, &msp)) + return (0); #ifdef DEBUG_CDROM - fprintf(stderr, "Device Type: %s\n", devtype[inq.perfdt]); - fprintf(stderr, "Vendor: %.8s\n", inq.vndrid); - fprintf(stderr, "Product: %.8s\n", inq.prodid); - fprintf(stderr, "Revision: %.8s\n", inq.revlvl); + fprintf(stderr, "Device Type: %s\n", devtype[inq.perfdt]); + fprintf(stderr, "Vendor: %.8s\n", inq.vndrid); + fprintf(stderr, "Product: %.8s\n", inq.prodid); + fprintf(stderr, "Revision: %.8s\n", inq.revlvl); #endif - if ( inq.perfdt == DTYPE_RODIRECT ) - is_cd = 1; + if (inq.perfdt == DTYPE_RODIRECT) + is_cd = 1; } - return(is_cd); + return (is_cd); } /* Add a CD-ROM drive to our list of valid drives */ -static void AddDrive(char *drive, struct stat *stbuf) +static void +AddDrive(char *drive, struct stat *stbuf) { int i; - if ( SDL_numcds < MAX_DRIVES ) { - /* Check to make sure it's not already in our list. - * This can happen when we see a drive via symbolic link. - * - */ - for ( i=0; ist_rdev == SDL_cdmode[i] ) { + if (SDL_numcds < MAX_DRIVES) { + /* Check to make sure it's not already in our list. + * This can happen when we see a drive via symbolic link. + * + */ + for (i = 0; i < SDL_numcds; ++i) { + if (stbuf->st_rdev == SDL_cdmode[i]) { #ifdef DEBUG_CDROM - fprintf(stderr, "Duplicate drive detected: %s == %s\n", drive, SDL_cdlist[i]); + fprintf(stderr, "Duplicate drive detected: %s == %s\n", + drive, SDL_cdlist[i]); #endif - return; - } - } - - /* Add this drive to our list */ - i = SDL_numcds; - SDL_cdlist[i] = SDL_strdup(drive); - if ( SDL_cdlist[i] == NULL ) { - SDL_OutOfMemory(); - return; - } - SDL_cdmode[i] = stbuf->st_rdev; - ++SDL_numcds; + return; + } + } + + /* Add this drive to our list */ + i = SDL_numcds; + SDL_cdlist[i] = SDL_strdup(drive); + if (SDL_cdlist[i] == NULL) { + SDL_OutOfMemory(); + return; + } + SDL_cdmode[i] = stbuf->st_rdev; + ++SDL_numcds; #ifdef DEBUG_CDROM - fprintf(stderr, "Added CD-ROM drive: %s\n", drive); + fprintf(stderr, "Added CD-ROM drive: %s\n", drive); #endif } } -int SDL_SYS_CDInit(void) +int +SDL_SYS_CDInit(void) { /* checklist: * @@ -145,239 +150,250 @@ int SDL_SYS_CDInit(void) * dir: /dev, name: rrz * */ - struct { - char *dir; - char *name; + struct + { + char *dir; + char *name; } checklist[] = { - {"/dev/rdisk", "cdrom"}, - {"/dev", "rrz"}, - {NULL, NULL}}; + { + "/dev/rdisk", "cdrom"}, { + "/dev", "rrz"}, { + NULL, NULL}}; char drive[32]; char *SDLcdrom; int i, j, exists; struct stat stbuf; /* Fill in our driver capabilities */ - SDL_CDcaps.Name = SDL_SYS_CDName; - SDL_CDcaps.Open = SDL_SYS_CDOpen; + SDL_CDcaps.Name = SDL_SYS_CDName; + SDL_CDcaps.Open = SDL_SYS_CDOpen; SDL_CDcaps.GetTOC = SDL_SYS_CDGetTOC; SDL_CDcaps.Status = SDL_SYS_CDStatus; - SDL_CDcaps.Play = SDL_SYS_CDPlay; - SDL_CDcaps.Pause = SDL_SYS_CDPause; + SDL_CDcaps.Play = SDL_SYS_CDPlay; + SDL_CDcaps.Pause = SDL_SYS_CDPause; SDL_CDcaps.Resume = SDL_SYS_CDResume; - SDL_CDcaps.Stop = SDL_SYS_CDStop; - SDL_CDcaps.Eject = SDL_SYS_CDEject; - SDL_CDcaps.Close = SDL_SYS_CDClose; + SDL_CDcaps.Stop = SDL_SYS_CDStop; + SDL_CDcaps.Eject = SDL_SYS_CDEject; + SDL_CDcaps.Close = SDL_SYS_CDClose; /* Look in the environment for our CD-ROM drive list */ - SDLcdrom = SDL_getenv("SDL_CDROM"); /* ':' separated list of devices */ - if ( SDLcdrom != NULL ) { - char *cdpath, *delim; - size_t len = SDL_strlen(SDLcdrom)+1; - cdpath = SDL_stack_alloc(char, len); - if ( cdpath != NULL ) { - SDL_strlcpy(cdpath, SDLcdrom, len); - SDLcdrom = cdpath; - do { - delim = SDL_strchr(SDLcdrom, ':'); - if ( delim ) { - *delim++ = '\0'; - } - if ( CheckDrive(SDLcdrom, &stbuf) > 0 ) { - AddDrive(SDLcdrom, &stbuf); - } - if ( delim ) { - SDLcdrom = delim; - } else { - SDLcdrom = NULL; - } - } while ( SDLcdrom ); - SDL_stack_free(cdpath); - } - - /* If we found our drives, there's nothing left to do */ - if ( SDL_numcds > 0 ) { - return(0); - } + SDLcdrom = SDL_getenv("SDL_CDROM"); /* ':' separated list of devices */ + if (SDLcdrom != NULL) { + char *cdpath, *delim; + size_t len = SDL_strlen(SDLcdrom) + 1; + cdpath = SDL_stack_alloc(char, len); + if (cdpath != NULL) { + SDL_strlcpy(cdpath, SDLcdrom, len); + SDLcdrom = cdpath; + do { + delim = SDL_strchr(SDLcdrom, ':'); + if (delim) { + *delim++ = '\0'; + } + if (CheckDrive(SDLcdrom, &stbuf) > 0) { + AddDrive(SDLcdrom, &stbuf); + } + if (delim) { + SDLcdrom = delim; + } else { + SDLcdrom = NULL; + } + } + while (SDLcdrom); + SDL_stack_free(cdpath); + } + + /* If we found our drives, there's nothing left to do */ + if (SDL_numcds > 0) { + return (0); + } } /* Scan the system for CD-ROM drives */ - for ( i = 0; checklist[i].dir; ++i) { - DIR *devdir; - struct dirent *devent; - int name_len; - - devdir = opendir(checklist[i].dir); - if (devdir) { - name_len = SDL_strlen(checklist[i].name); - while (devent = readdir(devdir)) - if (SDL_memcmp(checklist[i].name, devent->d_name, name_len) == 0) - if (devent->d_name[devent->d_namlen-1] == 'c') { - SDL_snprintf(drive, SDL_arraysize(drive), "%s/%s", checklist[i].dir, devent->d_name); + for (i = 0; checklist[i].dir; ++i) { + DIR *devdir; + struct dirent *devent; + int name_len; + + devdir = opendir(checklist[i].dir); + if (devdir) { + name_len = SDL_strlen(checklist[i].name); + while (devent = readdir(devdir)) + if (SDL_memcmp + (checklist[i].name, devent->d_name, name_len) == 0) + if (devent->d_name[devent->d_namlen - 1] == 'c') { + SDL_snprintf(drive, SDL_arraysize(drive), + "%s/%s", checklist[i].dir, + devent->d_name); #ifdef DEBUG_CDROM - fprintf(stderr, "Try to add drive: %s\n", drive); + fprintf(stderr, "Try to add drive: %s\n", drive); #endif - if ( CheckDrive(drive, &stbuf) > 0 ) - AddDrive(drive, &stbuf); - } - closedir(devdir); - } else { + if (CheckDrive(drive, &stbuf) > 0) + AddDrive(drive, &stbuf); + } + closedir(devdir); + } else { #ifdef DEBUG_CDROM - fprintf(stderr, "cannot open dir: %s\n", checklist[i].dir); + fprintf(stderr, "cannot open dir: %s\n", checklist[i].dir); #endif - } + } } return (0); } -static const char *SDL_SYS_CDName(int drive) +static const char * +SDL_SYS_CDName(int drive) { - return(SDL_cdlist[drive]); + return (SDL_cdlist[drive]); } -static int SDL_SYS_CDOpen(int drive) +static int +SDL_SYS_CDOpen(int drive) { /* O_RDWR: To use ioctl(fd, SCSI_STOP_UNIT) */ - return(open(SDL_cdlist[drive], (O_RDWR|O_NDELAY), 0)); + return (open(SDL_cdlist[drive], (O_RDWR | O_NDELAY), 0)); } -static int SDL_SYS_CDGetTOC(SDL_CD *cdrom) +static int +SDL_SYS_CDGetTOC(SDL_CD * cdrom) { - struct cd_toc toc; - struct cd_toc_header hdr; - struct cd_toc_entry *cdte; + struct cd_toc toc; + struct cd_toc_header hdr; + struct cd_toc_entry *cdte; int i; int okay = 0; - if ( ioctl(cdrom->id, CDROM_TOC_HEADER, &hdr) ) { - fprintf(stderr,"ioctl error CDROM_TOC_HEADER\n"); - return -1; + if (ioctl(cdrom->id, CDROM_TOC_HEADER, &hdr)) { + fprintf(stderr, "ioctl error CDROM_TOC_HEADER\n"); + return -1; } cdrom->numtracks = hdr.th_ending_track - hdr.th_starting_track + 1; - if ( cdrom->numtracks > SDL_MAX_TRACKS ) { - cdrom->numtracks = SDL_MAX_TRACKS; + if (cdrom->numtracks > SDL_MAX_TRACKS) { + cdrom->numtracks = SDL_MAX_TRACKS; } #ifdef DEBUG_CDROM - fprintf(stderr,"hdr.th_data_len1 = %d\n", hdr.th_data_len1); - fprintf(stderr,"hdr.th_data_len0 = %d\n", hdr.th_data_len0); - fprintf(stderr,"hdr.th_starting_track = %d\n", hdr.th_starting_track); - fprintf(stderr,"hdr.th_ending_track = %d\n", hdr.th_ending_track); - fprintf(stderr,"cdrom->numtracks = %d\n", cdrom->numtracks); + fprintf(stderr, "hdr.th_data_len1 = %d\n", hdr.th_data_len1); + fprintf(stderr, "hdr.th_data_len0 = %d\n", hdr.th_data_len0); + fprintf(stderr, "hdr.th_starting_track = %d\n", hdr.th_starting_track); + fprintf(stderr, "hdr.th_ending_track = %d\n", hdr.th_ending_track); + fprintf(stderr, "cdrom->numtracks = %d\n", cdrom->numtracks); #endif toc.toc_address_format = CDROM_LBA_FORMAT; toc.toc_starting_track = 0; toc.toc_alloc_length = (hdr.th_data_len1 << 8) + - hdr.th_data_len0 + sizeof(hdr); - if ( (toc.toc_buffer = alloca(toc.toc_alloc_length)) == NULL) { - fprintf(stderr,"cannot allocate toc.toc_buffer\n"); - return -1; + hdr.th_data_len0 + sizeof(hdr); + if ((toc.toc_buffer = alloca(toc.toc_alloc_length)) == NULL) { + fprintf(stderr, "cannot allocate toc.toc_buffer\n"); + return -1; } - bzero (toc.toc_buffer, toc.toc_alloc_length); + bzero(toc.toc_buffer, toc.toc_alloc_length); if (ioctl(cdrom->id, CDROM_TOC_ENTRYS, &toc)) { - fprintf(stderr,"ioctl error CDROM_TOC_ENTRYS\n"); - return -1; + fprintf(stderr, "ioctl error CDROM_TOC_ENTRYS\n"); + return -1; } - cdte =(struct cd_toc_entry *) ((char *) toc.toc_buffer + sizeof(hdr)); - for (i=0; i <= cdrom->numtracks; ++i) { - if (i == cdrom->numtracks ) { - cdrom->track[i].id = 0xAA;; - } else { - cdrom->track[i].id = hdr.th_starting_track + i; - } - - cdrom->track[i].type = - cdte[i].te_control & CDROM_DATA_TRACK; - cdrom->track[i].offset = - cdte[i].te_absaddr.lba.addr3 << 24 | - cdte[i].te_absaddr.lba.addr2 << 16 | - cdte[i].te_absaddr.lba.addr1 << 8 | - cdte[i].te_absaddr.lba.addr0; - cdrom->track[i].length = 0; - if ( i > 0 ) { - cdrom->track[i - 1].length = - cdrom->track[i].offset - - cdrom->track[i - 1].offset; - } + cdte = (struct cd_toc_entry *) ((char *) toc.toc_buffer + sizeof(hdr)); + for (i = 0; i <= cdrom->numtracks; ++i) { + if (i == cdrom->numtracks) { + cdrom->track[i].id = 0xAA;; + } else { + cdrom->track[i].id = hdr.th_starting_track + i; + } + + cdrom->track[i].type = cdte[i].te_control & CDROM_DATA_TRACK; + cdrom->track[i].offset = + cdte[i].te_absaddr.lba.addr3 << 24 | + cdte[i].te_absaddr.lba.addr2 << 16 | + cdte[i].te_absaddr.lba.addr1 << 8 | cdte[i].te_absaddr.lba.addr0; + cdrom->track[i].length = 0; + if (i > 0) { + cdrom->track[i - 1].length = + cdrom->track[i].offset - cdrom->track[i - 1].offset; + } } #ifdef DEBUG_CDROM - for (i = 0; i <= cdrom->numtracks; i++) { - fprintf(stderr,"toc_entry[%d].te_track_number = %d\n", - i,cdte[i].te_track_number); - fprintf(stderr,"cdrom->track[%d].id = %d\n", i,cdrom->track[i].id); - fprintf(stderr,"cdrom->track[%d].type = %x\n", i,cdrom->track[i].type); - fprintf(stderr,"cdrom->track[%d].offset = %d\n", i,cdrom->track[i].offset); - fprintf(stderr,"cdrom->track[%d].length = %d\n", i,cdrom->track[i].length); - } + for (i = 0; i <= cdrom->numtracks; i++) { + fprintf(stderr, "toc_entry[%d].te_track_number = %d\n", + i, cdte[i].te_track_number); + fprintf(stderr, "cdrom->track[%d].id = %d\n", i, cdrom->track[i].id); + fprintf(stderr, "cdrom->track[%d].type = %x\n", i, + cdrom->track[i].type); + fprintf(stderr, "cdrom->track[%d].offset = %d\n", i, + cdrom->track[i].offset); + fprintf(stderr, "cdrom->track[%d].length = %d\n", i, + cdrom->track[i].length); + } #endif - if ( i == (cdrom->numtracks+1) ) { - okay = 1; + if (i == (cdrom->numtracks + 1)) { + okay = 1; } - return(okay ? 0 : -1); + return (okay ? 0 : -1); } /* Get CD-ROM status */ -static CDstatus SDL_SYS_CDStatus(SDL_CD *cdrom, int *position) +static CDstatus +SDL_SYS_CDStatus(SDL_CD * cdrom, int *position) { - CDstatus status; - struct cd_sub_channel sc; - struct cd_subc_channel_data scd; + CDstatus status; + struct cd_sub_channel sc; + struct cd_subc_channel_data scd; sc.sch_address_format = CDROM_LBA_FORMAT; - sc.sch_data_format = CDROM_CURRENT_POSITION; - sc.sch_track_number = 0; - sc.sch_alloc_length = sizeof(scd); - sc.sch_buffer = (caddr_t)&scd; - if ( ioctl(cdrom->id, CDROM_READ_SUBCHANNEL, &sc) ) { - status = CD_ERROR; - fprintf(stderr,"ioctl error CDROM_READ_SUBCHANNEL \n"); + sc.sch_data_format = CDROM_CURRENT_POSITION; + sc.sch_track_number = 0; + sc.sch_alloc_length = sizeof(scd); + sc.sch_buffer = (caddr_t) & scd; + if (ioctl(cdrom->id, CDROM_READ_SUBCHANNEL, &sc)) { + status = CD_ERROR; + fprintf(stderr, "ioctl error CDROM_READ_SUBCHANNEL \n"); } else { - switch (scd.scd_header.sh_audio_status) { - case AS_AUDIO_INVALID: - status = CD_STOPPED; - break; - case AS_PLAY_IN_PROGRESS: - status = CD_PLAYING; - break; - case AS_PLAY_PAUSED: - status = CD_PAUSED; - break; - case AS_PLAY_COMPLETED: - status = CD_STOPPED; - break; - case AS_PLAY_ERROR: - status = CD_ERROR; - break; - case AS_NO_STATUS: - status = CD_STOPPED; - break; - default: - status = CD_ERROR; - break; - } + switch (scd.scd_header.sh_audio_status) { + case AS_AUDIO_INVALID: + status = CD_STOPPED; + break; + case AS_PLAY_IN_PROGRESS: + status = CD_PLAYING; + break; + case AS_PLAY_PAUSED: + status = CD_PAUSED; + break; + case AS_PLAY_COMPLETED: + status = CD_STOPPED; + break; + case AS_PLAY_ERROR: + status = CD_ERROR; + break; + case AS_NO_STATUS: + status = CD_STOPPED; + break; + default: + status = CD_ERROR; + break; + } #ifdef DEBUG_CDROM - fprintf(stderr,"scd.scd_header.sh_audio_status = %x\n", - scd.scd_header.sh_audio_status); + fprintf(stderr, "scd.scd_header.sh_audio_status = %x\n", + scd.scd_header.sh_audio_status); #endif } if (position) { - if (status == CD_PLAYING || (status == CD_PAUSED) ) { - *position = - scd.scd_position_data.scp_absaddr.lba.addr3 << 24 | - scd.scd_position_data.scp_absaddr.lba.addr2 << 16 | - scd.scd_position_data.scp_absaddr.lba.addr1 << 8 | - scd.scd_position_data.scp_absaddr.lba.addr0; - } else { - *position = 0; - } + if (status == CD_PLAYING || (status == CD_PAUSED)) { + *position = + scd.scd_position_data.scp_absaddr.lba.addr3 << 24 | + scd.scd_position_data.scp_absaddr.lba.addr2 << 16 | + scd.scd_position_data.scp_absaddr.lba.addr1 << 8 | + scd.scd_position_data.scp_absaddr.lba.addr0; + } else { + *position = 0; + } } return status; } /* Start play */ -static int SDL_SYS_CDPlay(SDL_CD *cdrom, int start, int length) +static int +SDL_SYS_CDPlay(SDL_CD * cdrom, int start, int length) { /* * Play MSF @@ -386,59 +402,64 @@ static int SDL_SYS_CDPlay(SDL_CD *cdrom, int start, int length) int end; bzero(&msf, sizeof(msf)); - end = start +length; - FRAMES_TO_MSF(start + 150, /* LBA = 4500*M + 75*S + F - 150 */ - &msf.msf_starting_M_unit, - &msf.msf_starting_S_unit, - &msf.msf_starting_F_unit); - FRAMES_TO_MSF(end + 150, /* LBA = 4500*M + 75*S + F - 150 */ - &msf.msf_ending_M_unit, - &msf.msf_ending_S_unit, - &msf.msf_ending_F_unit); - - return(ioctl(cdrom->id, CDROM_PLAY_AUDIO_MSF, &msf)); + end = start + length; + FRAMES_TO_MSF(start + 150, /* LBA = 4500*M + 75*S + F - 150 */ + &msf.msf_starting_M_unit, + &msf.msf_starting_S_unit, &msf.msf_starting_F_unit); + FRAMES_TO_MSF(end + 150, /* LBA = 4500*M + 75*S + F - 150 */ + &msf.msf_ending_M_unit, + &msf.msf_ending_S_unit, &msf.msf_ending_F_unit); + + return (ioctl(cdrom->id, CDROM_PLAY_AUDIO_MSF, &msf)); } /* Pause play */ -static int SDL_SYS_CDPause(SDL_CD *cdrom) +static int +SDL_SYS_CDPause(SDL_CD * cdrom) { - return(ioctl(cdrom->id, CDROM_PAUSE_PLAY)); + return (ioctl(cdrom->id, CDROM_PAUSE_PLAY)); } /* Resume play */ -static int SDL_SYS_CDResume(SDL_CD *cdrom) +static int +SDL_SYS_CDResume(SDL_CD * cdrom) { - return(ioctl(cdrom->id, CDROM_RESUME_PLAY)); + return (ioctl(cdrom->id, CDROM_RESUME_PLAY)); } /* Stop play */ -static int SDL_SYS_CDStop(SDL_CD *cdrom) +static int +SDL_SYS_CDStop(SDL_CD * cdrom) { - return(ioctl(cdrom->id, SCSI_STOP_UNIT)); + return (ioctl(cdrom->id, SCSI_STOP_UNIT)); } /* Eject the CD-ROM */ -static int SDL_SYS_CDEject(SDL_CD *cdrom) +static int +SDL_SYS_CDEject(SDL_CD * cdrom) { - return(ioctl(cdrom->id, CDROM_EJECT_CADDY)); + return (ioctl(cdrom->id, CDROM_EJECT_CADDY)); } /* Close the CD-ROM handle */ -static void SDL_SYS_CDClose(SDL_CD *cdrom) +static void +SDL_SYS_CDClose(SDL_CD * cdrom) { close(cdrom->id); } -void SDL_SYS_CDQuit(void) +void +SDL_SYS_CDQuit(void) { int i; - if ( SDL_numcds > 0 ) { - for ( i=0; i 0) { + for (i = 0; i < SDL_numcds; ++i) { + SDL_free(SDL_cdlist[i]); + } + SDL_numcds = 0; } } #endif /* SDL_CDROM_OSF */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/cdrom/qnx/SDL_syscdrom.c b/src/cdrom/qnx/SDL_syscdrom.c index d41d64084..e9e7f3adc 100644 --- a/src/cdrom/qnx/SDL_syscdrom.c +++ b/src/cdrom/qnx/SDL_syscdrom.c @@ -46,80 +46,76 @@ /* A list of available CD-ROM drives */ static char *SDL_cdlist[MAX_DRIVES]; static dev_t SDL_cdmode[MAX_DRIVES]; -static int SDL_cdopen[MAX_DRIVES]; +static int SDL_cdopen[MAX_DRIVES]; /* The system-dependent CD control functions */ static const char *SDL_SYS_CDName(int drive); static int SDL_SYS_CDOpen(int drive); -static int SDL_SYS_CDGetTOC(SDL_CD *cdrom); -static CDstatus SDL_SYS_CDStatus(SDL_CD *cdrom, int *position); -static int SDL_SYS_CDPlay(SDL_CD *cdrom, int start, int length); -static int SDL_SYS_CDPause(SDL_CD *cdrom); -static int SDL_SYS_CDResume(SDL_CD *cdrom); -static int SDL_SYS_CDStop(SDL_CD *cdrom); -static int SDL_SYS_CDEject(SDL_CD *cdrom); -static void SDL_SYS_CDClose(SDL_CD *cdrom); +static int SDL_SYS_CDGetTOC(SDL_CD * cdrom); +static CDstatus SDL_SYS_CDStatus(SDL_CD * cdrom, int *position); +static int SDL_SYS_CDPlay(SDL_CD * cdrom, int start, int length); +static int SDL_SYS_CDPause(SDL_CD * cdrom); +static int SDL_SYS_CDResume(SDL_CD * cdrom); +static int SDL_SYS_CDStop(SDL_CD * cdrom); +static int SDL_SYS_CDEject(SDL_CD * cdrom); +static void SDL_SYS_CDClose(SDL_CD * cdrom); /* Check a drive to see if it is a CD-ROM */ -static int CheckDrive(char *drive, struct stat *stbuf) +static int +CheckDrive(char *drive, struct stat *stbuf) { int is_cd, cdfd; cam_devinfo_t dinfo; - int devctlret=0; + int devctlret = 0; int atapi; int removable; int cdb10; /* If it doesn't exist, return -1 */ - if (stat(drive, stbuf) < 0) - { - return(-1); + if (stat(drive, stbuf) < 0) { + return (-1); } /* If it does exist, verify that it's an available CD-ROM */ is_cd = 0; - if (S_ISCHR(stbuf->st_mode) || S_ISBLK(stbuf->st_mode)) - { + if (S_ISCHR(stbuf->st_mode) || S_ISBLK(stbuf->st_mode)) { cdfd = open(drive, QNX_CD_OPENMODE); - if ( cdfd >= 0 ) - { - devctlret=devctl(cdfd, DCMD_CAM_DEVINFO, &dinfo, sizeof(cam_devinfo_t), NULL); - - if (devctlret==EOK) - { - atapi=dinfo.flags & DEV_ATAPI; - removable=dinfo.flags & DEV_REMOVABLE; - cdb10=dinfo.flags & DEV_CDB_10; /* I'm not sure about that flag */ - - /* in the near future need to add more checks for splitting cdroms from other devices */ - if ((atapi)&&(removable)) - { - is_cd = 1; - } + if (cdfd >= 0) { + devctlret = + devctl(cdfd, DCMD_CAM_DEVINFO, &dinfo, + sizeof(cam_devinfo_t), NULL); + + if (devctlret == EOK) { + atapi = dinfo.flags & DEV_ATAPI; + removable = dinfo.flags & DEV_REMOVABLE; + cdb10 = dinfo.flags & DEV_CDB_10; /* I'm not sure about that flag */ + + /* in the near future need to add more checks for splitting cdroms from other devices */ + if ((atapi) && (removable)) { + is_cd = 1; + } } close(cdfd); } } - return(is_cd); + return (is_cd); } /* Add a CD-ROM drive to our list of valid drives */ -static void AddDrive(char *drive, struct stat *stbuf) +static void +AddDrive(char *drive, struct stat *stbuf) { int i; - if (SDL_numcds < MAX_DRIVES) - { + if (SDL_numcds < MAX_DRIVES) { /* Check to make sure it's not already in our list. - This can happen when we see a drive via symbolic link. */ + This can happen when we see a drive via symbolic link. */ - for (i=0; ist_rdev == SDL_cdmode[i]) - { + for (i = 0; i < SDL_numcds; ++i) { + if (stbuf->st_rdev == SDL_cdmode[i]) { return; } } @@ -128,8 +124,7 @@ static void AddDrive(char *drive, struct stat *stbuf) i = SDL_numcds; SDL_cdlist[i] = SDL_strdup(drive); - if (SDL_cdlist[i] == NULL) - { + if (SDL_cdlist[i] == NULL) { SDL_OutOfMemory(); return; } @@ -138,10 +133,12 @@ static void AddDrive(char *drive, struct stat *stbuf) } } -int SDL_SYS_CDInit(void) +int +SDL_SYS_CDInit(void) { /* checklist: /dev/cdrom, /dev/cd?, /dev/scd? */ - static char *checklist[]={"cdrom", "?0 cd?", "?1 cd?", "?0 scd?", NULL}; + static char *checklist[] = + { "cdrom", "?0 cd?", "?1 cd?", "?0 scd?", NULL }; char *SDLcdrom; int i, j, exists; @@ -161,150 +158,132 @@ int SDL_SYS_CDInit(void) SDL_CDcaps.Close = SDL_SYS_CDClose; /* clearing device open status */ - for (i=0; i 0) - { + if (CheckDrive(SDLcdrom, &stbuf) > 0) { AddDrive(SDLcdrom, &stbuf); } - if (delim) - { + if (delim) { SDLcdrom = delim; - } - else - { + } else { SDLcdrom = NULL; } - } while (SDLcdrom); + } + while (SDLcdrom); SDL_stack_free(cdpath); } /* If we found our drives, there's nothing left to do */ - if (SDL_numcds > 0) - { - return(0); + if (SDL_numcds > 0) { + return (0); } } /* Scan the system for CD-ROM drives */ - for ( i=0; checklist[i]; ++i ) - { - if (checklist[i][0] == '?') - { - char* insert; + for (i = 0; checklist[i]; ++i) { + if (checklist[i][0] == '?') { + char *insert; exists = 1; - for ( j=checklist[i][1]; exists; ++j ) - { - SDL_snprintf(drive, SDL_arraysize(drive), "/dev/%s", &checklist[i][3]); + for (j = checklist[i][1]; exists; ++j) { + SDL_snprintf(drive, SDL_arraysize(drive), "/dev/%s", + &checklist[i][3]); insert = SDL_strchr(drive, '?'); - if (insert != NULL) - { + if (insert != NULL) { *insert = j; } - switch (CheckDrive(drive, &stbuf)) - { + switch (CheckDrive(drive, &stbuf)) { /* Drive exists and is a CD-ROM */ - case 1: - AddDrive(drive, &stbuf); - break; + case 1: + AddDrive(drive, &stbuf); + break; /* Drive exists, but isn't a CD-ROM */ - case 0: - break; + case 0: + break; /* Drive doesn't exist */ - case -1: - exists = 0; - break; + case -1: + exists = 0; + break; } } - } - else - { - SDL_snprintf(drive, SDL_arraysize(drive), "/dev/%s", checklist[i]); - if (CheckDrive(drive, &stbuf) > 0) - { + } else { + SDL_snprintf(drive, SDL_arraysize(drive), "/dev/%s", + checklist[i]); + if (CheckDrive(drive, &stbuf) > 0) { AddDrive(drive, &stbuf); } } } - return(0); + return (0); } -static const char *SDL_SYS_CDName(int drive) +static const char * +SDL_SYS_CDName(int drive) { - return(SDL_cdlist[drive]); + return (SDL_cdlist[drive]); } -static int SDL_SYS_CDOpen(int drive) +static int +SDL_SYS_CDOpen(int drive) { int handle; - handle=open(SDL_cdlist[drive], QNX_CD_OPENMODE); + handle = open(SDL_cdlist[drive], QNX_CD_OPENMODE); - if (handle>0) - { - SDL_cdopen[drive]=handle; + if (handle > 0) { + SDL_cdopen[drive] = handle; } return (handle); } -static int SDL_SYS_CDGetTOC(SDL_CD *cdrom) +static int +SDL_SYS_CDGetTOC(SDL_CD * cdrom) { cdrom_read_toc_t toc; int i, okay; okay = 0; - if (devctl(cdrom->id, DCMD_CAM_CDROMREADTOC, &toc, sizeof(toc), NULL) == 0) - { + if (devctl(cdrom->id, DCMD_CAM_CDROMREADTOC, &toc, sizeof(toc), NULL) == + 0) { cdrom->numtracks = toc.last_track - toc.first_track + 1; - if (cdrom->numtracks > SDL_MAX_TRACKS) - { + if (cdrom->numtracks > SDL_MAX_TRACKS) { cdrom->numtracks = SDL_MAX_TRACKS; } /* Read all the track TOC entries */ - for (i=0; i<=cdrom->numtracks; ++i) - { - if (i == cdrom->numtracks) - { + for (i = 0; i <= cdrom->numtracks; ++i) { + if (i == cdrom->numtracks) { cdrom->track[i].id = CDROM_LEADOUT; - } - else - { - cdrom->track[i].id = toc.first_track+i; + } else { + cdrom->track[i].id = toc.first_track + i; } cdrom->track[i].type = toc.toc_entry[i].control_adr & 0x0F; cdrom->track[i].offset = toc.toc_entry[i].addr.lba; cdrom->track[i].length = 0; - if (i > 0) - { - cdrom->track[i-1].length = cdrom->track[i].offset-cdrom->track[i-1].offset; + if (i > 0) { + cdrom->track[i - 1].length = + cdrom->track[i].offset - cdrom->track[i - 1].offset; } } - if (i == (cdrom->numtracks+1)) - { + if (i == (cdrom->numtracks + 1)) { okay = 1; } } @@ -312,7 +291,8 @@ static int SDL_SYS_CDGetTOC(SDL_CD *cdrom) } /* Get CD-ROM status */ -static CDstatus SDL_SYS_CDStatus(SDL_CD *cdrom, int *position) +static CDstatus +SDL_SYS_CDStatus(SDL_CD * cdrom, int *position) { CDstatus status; @@ -320,22 +300,21 @@ static CDstatus SDL_SYS_CDStatus(SDL_CD *cdrom, int *position) cdrom_subch_data_t info; cam_devinfo_t dinfo; - int devctlret=0; - int drive=-1; + int devctlret = 0; + int drive = -1; int i; - int eagaincnt=0; + int eagaincnt = 0; /* check media presence before read subchannel call, some cdroms can lockups */ /* if no media, while calling read subchannel functions. */ - devctlret=devctl(cdrom->id, DCMD_CAM_DEVINFO, &dinfo, sizeof(cam_devinfo_t), NULL); + devctlret = + devctl(cdrom->id, DCMD_CAM_DEVINFO, &dinfo, sizeof(cam_devinfo_t), + NULL); - if (devctlret==EOK) - { - if ((dinfo.flags & DEV_NO_MEDIA)!=0) - { + if (devctlret == EOK) { + if ((dinfo.flags & DEV_NO_MEDIA) != 0) { status = CD_TRAYEMPTY; - if (position) - { + if (position) { *position = 0; } return (status); @@ -348,200 +327,178 @@ static CDstatus SDL_SYS_CDStatus(SDL_CD *cdrom, int *position) info.subch_command.data_format = CDROM_SUBCH_CURRENT_POSITION; do { - devctlret=devctl(cdrom->id, DCMD_CAM_CDROMSUBCHNL, &info, sizeof(info), NULL); - if (devctlret==EIO) - { + devctlret = + devctl(cdrom->id, DCMD_CAM_CDROMSUBCHNL, &info, sizeof(info), + NULL); + if (devctlret == EIO) { /* big workaround for media change, handle is unusable after that, that bug was found in QNX 6.2, 6.2.1 is not released yet. */ - for (i=0; iid) - { - drive=i; + for (i = 0; i < MAX_DRIVES; i++) { + if (SDL_cdopen[i] == cdrom->id) { + drive = i; break; } } - if (drive==-1) - { - /* that cannot happen, but ... */ - break; + if (drive == -1) { + /* that cannot happen, but ... */ + break; } close(cdrom->id); - cdrom->id=open(SDL_cdlist[drive], QNX_CD_OPENMODE); - devctlret=EAGAIN; + cdrom->id = open(SDL_cdlist[drive], QNX_CD_OPENMODE); + devctlret = EAGAIN; } - if (devctlret==EAGAIN) - { + if (devctlret == EAGAIN) { eagaincnt++; } - if (eagaincnt==2) - { + if (eagaincnt == 2) { /* workaround for broken cdroms, which can return always EAGAIN when its not ready, */ /* that mean errornous media or just no media avail */ - devctlret=ENXIO; + devctlret = ENXIO; break; } - } while ((devctlret==EAGAIN)||(devctlret==ESTALE)); + } + while ((devctlret == EAGAIN) || (devctlret == ESTALE)); - if (devctlret != 0) - { - if (devctlret==ENXIO) - { + if (devctlret != 0) { + if (devctlret == ENXIO) { status = CD_TRAYEMPTY; - } - else - { + } else { status = CD_ERROR; } - } - else - { - switch (info.current_position.header.audio_status) - { - case CDROM_AUDIO_INVALID: - case CDROM_AUDIO_NO_STATUS: - /* Try to determine if there's a CD available */ - if (devctl(cdrom->id, DCMD_CAM_CDROMREADTOC, &toc, sizeof(toc), NULL)==0) - status = CD_STOPPED; - else - status = CD_TRAYEMPTY; - break; - case CDROM_AUDIO_COMPLETED: - status = CD_STOPPED; - break; - case CDROM_AUDIO_PLAY: - status = CD_PLAYING; - break; - case CDROM_AUDIO_PAUSED: - /* Workaround buggy CD-ROM drive */ - if (info.current_position.data_format == CDROM_LEADOUT) - { - status = CD_STOPPED; - } - else - { - status = CD_PAUSED; - } - break; - default: - status = CD_ERROR; - break; + } else { + switch (info.current_position.header.audio_status) { + case CDROM_AUDIO_INVALID: + case CDROM_AUDIO_NO_STATUS: + /* Try to determine if there's a CD available */ + if (devctl + (cdrom->id, DCMD_CAM_CDROMREADTOC, &toc, sizeof(toc), + NULL) == 0) + status = CD_STOPPED; + else + status = CD_TRAYEMPTY; + break; + case CDROM_AUDIO_COMPLETED: + status = CD_STOPPED; + break; + case CDROM_AUDIO_PLAY: + status = CD_PLAYING; + break; + case CDROM_AUDIO_PAUSED: + /* Workaround buggy CD-ROM drive */ + if (info.current_position.data_format == CDROM_LEADOUT) { + status = CD_STOPPED; + } else { + status = CD_PAUSED; + } + break; + default: + status = CD_ERROR; + break; } } - if (position) - { - if (status==CD_PLAYING || (status==CD_PAUSED)) - { - *position = MSF_TO_FRAMES(info.current_position.addr.msf.minute, - info.current_position.addr.msf.second, - info.current_position.addr.msf.frame); - } - else - { - *position = 0; - } + if (position) { + if (status == CD_PLAYING || (status == CD_PAUSED)) { + *position = + MSF_TO_FRAMES(info.current_position.addr.msf.minute, + info.current_position.addr.msf.second, + info.current_position.addr.msf.frame); + } else { + *position = 0; + } } return (status); } /* Start play */ -static int SDL_SYS_CDPlay(SDL_CD *cdrom, int start, int length) +static int +SDL_SYS_CDPlay(SDL_CD * cdrom, int start, int length) { cdrom_playmsf_t playtime; - FRAMES_TO_MSF(start, &playtime.start_minute, &playtime.start_second, &playtime.start_frame); - FRAMES_TO_MSF(start+length, &playtime.end_minute, &playtime.end_second, &playtime.end_frame); - - if (devctl(cdrom->id, DCMD_CAM_CDROMPLAYMSF, &playtime, sizeof(playtime), NULL) != 0) - { - return -1; - } - else - { - return 0; + FRAMES_TO_MSF(start, &playtime.start_minute, &playtime.start_second, + &playtime.start_frame); + FRAMES_TO_MSF(start + length, &playtime.end_minute, &playtime.end_second, + &playtime.end_frame); + + if (devctl + (cdrom->id, DCMD_CAM_CDROMPLAYMSF, &playtime, sizeof(playtime), + NULL) != 0) { + return -1; + } else { + return 0; } } /* Pause play */ -static int SDL_SYS_CDPause(SDL_CD *cdrom) +static int +SDL_SYS_CDPause(SDL_CD * cdrom) { - if (devctl(cdrom->id, DCMD_CAM_CDROMPAUSE, NULL, 0, NULL)!=0) - { - return -1; - } - else - { - return 0; + if (devctl(cdrom->id, DCMD_CAM_CDROMPAUSE, NULL, 0, NULL) != 0) { + return -1; + } else { + return 0; } } /* Resume play */ -static int SDL_SYS_CDResume(SDL_CD *cdrom) +static int +SDL_SYS_CDResume(SDL_CD * cdrom) { - if (devctl(cdrom->id, DCMD_CAM_CDROMRESUME, NULL, 0, NULL)!=0) - { - return -1; - } - else - { - return 0; + if (devctl(cdrom->id, DCMD_CAM_CDROMRESUME, NULL, 0, NULL) != 0) { + return -1; + } else { + return 0; } } /* Stop play */ -static int SDL_SYS_CDStop(SDL_CD *cdrom) +static int +SDL_SYS_CDStop(SDL_CD * cdrom) { - if (devctl(cdrom->id, DCMD_CAM_CDROMSTOP, NULL, 0, NULL)!=0) - { - return -1; - } - else - { - return 0; + if (devctl(cdrom->id, DCMD_CAM_CDROMSTOP, NULL, 0, NULL) != 0) { + return -1; + } else { + return 0; } } /* Eject the CD-ROM */ -static int SDL_SYS_CDEject(SDL_CD *cdrom) +static int +SDL_SYS_CDEject(SDL_CD * cdrom) { - if (devctl(cdrom->id, DCMD_CAM_EJECT_MEDIA, NULL, 0, NULL)!=0) - { - return -1; - } - else - { - return 0; + if (devctl(cdrom->id, DCMD_CAM_EJECT_MEDIA, NULL, 0, NULL) != 0) { + return -1; + } else { + return 0; } } /* Close the CD-ROM handle */ -static void SDL_SYS_CDClose(SDL_CD *cdrom) +static void +SDL_SYS_CDClose(SDL_CD * cdrom) { int i; - for (i=0; iid) - { - SDL_cdopen[i]=0; - break; - } + for (i = 0; i < MAX_DRIVES; i++) { + if (SDL_cdopen[i] == cdrom->id) { + SDL_cdopen[i] = 0; + break; + } } close(cdrom->id); } -void SDL_SYS_CDQuit(void) +void +SDL_SYS_CDQuit(void) { int i; - if (SDL_numcds > 0) - { - for (i=0; i 0) { + for (i = 0; i < SDL_numcds; ++i) { SDL_free(SDL_cdlist[i]); } SDL_numcds = 0; @@ -549,3 +506,4 @@ void SDL_SYS_CDQuit(void) } #endif /* SDL_CDROM_QNX */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/cdrom/win32/SDL_syscdrom.c b/src/cdrom/win32/SDL_syscdrom.c index 3d0587dad..8e4dd8881 100644 --- a/src/cdrom/win32/SDL_syscdrom.c +++ b/src/cdrom/win32/SDL_syscdrom.c @@ -33,10 +33,10 @@ #include "../SDL_syscdrom.h" /* This really broken?? */ -#define BROKEN_MCI_PAUSE /* Pausing actually stops play -- Doh! */ +#define BROKEN_MCI_PAUSE /* Pausing actually stops play -- Doh! */ /* The maximum number of CD-ROM drives we'll detect (Don't change!) */ -#define MAX_DRIVES 26 +#define MAX_DRIVES 26 /* A list of available CD-ROM drives */ static char *SDL_cdlist[MAX_DRIVES]; @@ -49,337 +49,352 @@ static int SDL_CD_end_position; /* The system-dependent CD control functions */ static const char *SDL_SYS_CDName(int drive); static int SDL_SYS_CDOpen(int drive); -static int SDL_SYS_CDGetTOC(SDL_CD *cdrom); -static CDstatus SDL_SYS_CDStatus(SDL_CD *cdrom, int *position); -static int SDL_SYS_CDPlay(SDL_CD *cdrom, int start, int length); -static int SDL_SYS_CDPause(SDL_CD *cdrom); -static int SDL_SYS_CDResume(SDL_CD *cdrom); -static int SDL_SYS_CDStop(SDL_CD *cdrom); -static int SDL_SYS_CDEject(SDL_CD *cdrom); -static void SDL_SYS_CDClose(SDL_CD *cdrom); +static int SDL_SYS_CDGetTOC(SDL_CD * cdrom); +static CDstatus SDL_SYS_CDStatus(SDL_CD * cdrom, int *position); +static int SDL_SYS_CDPlay(SDL_CD * cdrom, int start, int length); +static int SDL_SYS_CDPause(SDL_CD * cdrom); +static int SDL_SYS_CDResume(SDL_CD * cdrom); +static int SDL_SYS_CDStop(SDL_CD * cdrom); +static int SDL_SYS_CDEject(SDL_CD * cdrom); +static void SDL_SYS_CDClose(SDL_CD * cdrom); /* Add a CD-ROM drive to our list of valid drives */ -static void AddDrive(char *drive) +static void +AddDrive(char *drive) { - int i; - - if ( SDL_numcds < MAX_DRIVES ) { - /* Add this drive to our list */ - i = SDL_numcds; - SDL_cdlist[i] = SDL_strdup(drive); - if ( SDL_cdlist[i] == NULL ) { - SDL_OutOfMemory(); - return; - } - ++SDL_numcds; + int i; + + if (SDL_numcds < MAX_DRIVES) { + /* Add this drive to our list */ + i = SDL_numcds; + SDL_cdlist[i] = SDL_strdup(drive); + if (SDL_cdlist[i] == NULL) { + SDL_OutOfMemory(); + return; + } + ++SDL_numcds; #ifdef CDROM_DEBUG - fprintf(stderr, "Added CD-ROM drive: %s\n", drive); + fprintf(stderr, "Added CD-ROM drive: %s\n", drive); #endif - } + } } -int SDL_SYS_CDInit(void) +int +SDL_SYS_CDInit(void) { - /* checklist: Drive 'A' - 'Z' */ - int i; - char drive[4]; - - /* Fill in our driver capabilities */ - SDL_CDcaps.Name = SDL_SYS_CDName; - SDL_CDcaps.Open = SDL_SYS_CDOpen; - SDL_CDcaps.GetTOC = SDL_SYS_CDGetTOC; - SDL_CDcaps.Status = SDL_SYS_CDStatus; - SDL_CDcaps.Play = SDL_SYS_CDPlay; - SDL_CDcaps.Pause = SDL_SYS_CDPause; - SDL_CDcaps.Resume = SDL_SYS_CDResume; - SDL_CDcaps.Stop = SDL_SYS_CDStop; - SDL_CDcaps.Eject = SDL_SYS_CDEject; - SDL_CDcaps.Close = SDL_SYS_CDClose; - - /* Scan the system for CD-ROM drives */ - for ( i='A'; i<='Z'; ++i ) { - SDL_snprintf(drive, SDL_arraysize(drive), "%c:\\", i); - if ( GetDriveType(drive) == DRIVE_CDROM ) { - AddDrive(drive); - } - } - SDL_memset(SDL_mciID, 0, sizeof(SDL_mciID)); - return(0); + /* checklist: Drive 'A' - 'Z' */ + int i; + char drive[4]; + + /* Fill in our driver capabilities */ + SDL_CDcaps.Name = SDL_SYS_CDName; + SDL_CDcaps.Open = SDL_SYS_CDOpen; + SDL_CDcaps.GetTOC = SDL_SYS_CDGetTOC; + SDL_CDcaps.Status = SDL_SYS_CDStatus; + SDL_CDcaps.Play = SDL_SYS_CDPlay; + SDL_CDcaps.Pause = SDL_SYS_CDPause; + SDL_CDcaps.Resume = SDL_SYS_CDResume; + SDL_CDcaps.Stop = SDL_SYS_CDStop; + SDL_CDcaps.Eject = SDL_SYS_CDEject; + SDL_CDcaps.Close = SDL_SYS_CDClose; + + /* Scan the system for CD-ROM drives */ + for (i = 'A'; i <= 'Z'; ++i) { + SDL_snprintf(drive, SDL_arraysize(drive), "%c:\\", i); + if (GetDriveType(drive) == DRIVE_CDROM) { + AddDrive(drive); + } + } + SDL_memset(SDL_mciID, 0, sizeof(SDL_mciID)); + return (0); } /* General ioctl() CD-ROM command function */ -static int SDL_SYS_CDioctl(int id, UINT msg, DWORD flags, void *arg) +static int +SDL_SYS_CDioctl(int id, UINT msg, DWORD flags, void *arg) { - MCIERROR mci_error; + MCIERROR mci_error; - mci_error = mciSendCommand(SDL_mciID[id], msg, flags, (DWORD_PTR)arg); - if ( mci_error ) { - char error[256]; + mci_error = mciSendCommand(SDL_mciID[id], msg, flags, (DWORD_PTR) arg); + if (mci_error) { + char error[256]; - mciGetErrorString(mci_error, error, 256); - SDL_SetError("mciSendCommand() error: %s", error); - } - return(!mci_error ? 0 : -1); + mciGetErrorString(mci_error, error, 256); + SDL_SetError("mciSendCommand() error: %s", error); + } + return (!mci_error ? 0 : -1); } -static const char *SDL_SYS_CDName(int drive) +static const char * +SDL_SYS_CDName(int drive) { - return(SDL_cdlist[drive]); + return (SDL_cdlist[drive]); } -static int SDL_SYS_CDOpen(int drive) +static int +SDL_SYS_CDOpen(int drive) { - MCI_OPEN_PARMS mci_open; - MCI_SET_PARMS mci_set; - char device[3]; - DWORD flags; - - /* Open the requested device */ - mci_open.lpstrDeviceType = (LPCSTR) MCI_DEVTYPE_CD_AUDIO; - device[0] = *SDL_cdlist[drive]; - device[1] = ':'; - device[2] = '\0'; - mci_open.lpstrElementName = device; - flags = - (MCI_OPEN_TYPE|MCI_OPEN_SHAREABLE|MCI_OPEN_TYPE_ID|MCI_OPEN_ELEMENT); - if ( SDL_SYS_CDioctl(0, MCI_OPEN, flags, &mci_open) < 0 ) { - flags &= ~MCI_OPEN_SHAREABLE; - if ( SDL_SYS_CDioctl(0, MCI_OPEN, flags, &mci_open) < 0 ) { - return(-1); - } - } - SDL_mciID[drive] = mci_open.wDeviceID; - - /* Set the minute-second-frame time format */ - mci_set.dwTimeFormat = MCI_FORMAT_MSF; - SDL_SYS_CDioctl(drive, MCI_SET, MCI_SET_TIME_FORMAT, &mci_set); + MCI_OPEN_PARMS mci_open; + MCI_SET_PARMS mci_set; + char device[3]; + DWORD flags; + + /* Open the requested device */ + mci_open.lpstrDeviceType = (LPCSTR) MCI_DEVTYPE_CD_AUDIO; + device[0] = *SDL_cdlist[drive]; + device[1] = ':'; + device[2] = '\0'; + mci_open.lpstrElementName = device; + flags = + (MCI_OPEN_TYPE | MCI_OPEN_SHAREABLE | MCI_OPEN_TYPE_ID | + MCI_OPEN_ELEMENT); + if (SDL_SYS_CDioctl(0, MCI_OPEN, flags, &mci_open) < 0) { + flags &= ~MCI_OPEN_SHAREABLE; + if (SDL_SYS_CDioctl(0, MCI_OPEN, flags, &mci_open) < 0) { + return (-1); + } + } + SDL_mciID[drive] = mci_open.wDeviceID; + + /* Set the minute-second-frame time format */ + mci_set.dwTimeFormat = MCI_FORMAT_MSF; + SDL_SYS_CDioctl(drive, MCI_SET, MCI_SET_TIME_FORMAT, &mci_set); #ifdef BROKEN_MCI_PAUSE - SDL_paused[drive] = 0; + SDL_paused[drive] = 0; #endif - return(drive); + return (drive); } -static int SDL_SYS_CDGetTOC(SDL_CD *cdrom) +static int +SDL_SYS_CDGetTOC(SDL_CD * cdrom) { - MCI_STATUS_PARMS mci_status; - int i, okay; - DWORD flags; - - okay = 0; - mci_status.dwItem = MCI_STATUS_NUMBER_OF_TRACKS; - flags = MCI_STATUS_ITEM | MCI_WAIT; - if ( SDL_SYS_CDioctl(cdrom->id, MCI_STATUS, flags, &mci_status) == 0 ) { - cdrom->numtracks = mci_status.dwReturn; - if ( cdrom->numtracks > SDL_MAX_TRACKS ) { - cdrom->numtracks = SDL_MAX_TRACKS; - } - /* Read all the track TOC entries */ - flags = MCI_STATUS_ITEM | MCI_TRACK | MCI_WAIT; - for ( i=0; inumtracks; ++i ) { - cdrom->track[i].id = i+1; - mci_status.dwTrack = cdrom->track[i].id; + MCI_STATUS_PARMS mci_status; + int i, okay; + DWORD flags; + + okay = 0; + mci_status.dwItem = MCI_STATUS_NUMBER_OF_TRACKS; + flags = MCI_STATUS_ITEM | MCI_WAIT; + if (SDL_SYS_CDioctl(cdrom->id, MCI_STATUS, flags, &mci_status) == 0) { + cdrom->numtracks = mci_status.dwReturn; + if (cdrom->numtracks > SDL_MAX_TRACKS) { + cdrom->numtracks = SDL_MAX_TRACKS; + } + /* Read all the track TOC entries */ + flags = MCI_STATUS_ITEM | MCI_TRACK | MCI_WAIT; + for (i = 0; i < cdrom->numtracks; ++i) { + cdrom->track[i].id = i + 1; + mci_status.dwTrack = cdrom->track[i].id; #ifdef MCI_CDA_STATUS_TYPE_TRACK - mci_status.dwItem = MCI_CDA_STATUS_TYPE_TRACK; - if ( SDL_SYS_CDioctl(cdrom->id, MCI_STATUS, flags, - &mci_status) < 0 ) { - break; - } - if ( mci_status.dwReturn == MCI_CDA_TRACK_AUDIO ) { - cdrom->track[i].type = SDL_AUDIO_TRACK; - } else { - cdrom->track[i].type = SDL_DATA_TRACK; - } + mci_status.dwItem = MCI_CDA_STATUS_TYPE_TRACK; + if (SDL_SYS_CDioctl(cdrom->id, MCI_STATUS, flags, + &mci_status) < 0) { + break; + } + if (mci_status.dwReturn == MCI_CDA_TRACK_AUDIO) { + cdrom->track[i].type = SDL_AUDIO_TRACK; + } else { + cdrom->track[i].type = SDL_DATA_TRACK; + } #else - cdrom->track[i].type = SDL_AUDIO_TRACK; + cdrom->track[i].type = SDL_AUDIO_TRACK; #endif - mci_status.dwItem = MCI_STATUS_POSITION; - if ( SDL_SYS_CDioctl(cdrom->id, MCI_STATUS, flags, - &mci_status) < 0 ) { - break; - } - cdrom->track[i].offset = MSF_TO_FRAMES( - MCI_MSF_MINUTE(mci_status.dwReturn), - MCI_MSF_SECOND(mci_status.dwReturn), - MCI_MSF_FRAME(mci_status.dwReturn)); - cdrom->track[i].length = 0; - if ( i > 0 ) { - cdrom->track[i-1].length = - cdrom->track[i].offset- - cdrom->track[i-1].offset; - } - } - if ( i == cdrom->numtracks ) { - mci_status.dwTrack = cdrom->track[i - 1].id; - mci_status.dwItem = MCI_STATUS_LENGTH; - if ( SDL_SYS_CDioctl(cdrom->id, MCI_STATUS, flags, - &mci_status) == 0 ) { - cdrom->track[i - 1].length = MSF_TO_FRAMES( - MCI_MSF_MINUTE(mci_status.dwReturn), - MCI_MSF_SECOND(mci_status.dwReturn), - MCI_MSF_FRAME(mci_status.dwReturn)); - /* compute lead-out offset */ - cdrom->track[i].offset = cdrom->track[i - 1].offset + - cdrom->track[i - 1].length; - cdrom->track[i].length = 0; - okay = 1; - } - } - } - return(okay ? 0 : -1); + mci_status.dwItem = MCI_STATUS_POSITION; + if (SDL_SYS_CDioctl(cdrom->id, MCI_STATUS, flags, + &mci_status) < 0) { + break; + } + cdrom->track[i].offset = + MSF_TO_FRAMES(MCI_MSF_MINUTE(mci_status.dwReturn), + MCI_MSF_SECOND(mci_status.dwReturn), + MCI_MSF_FRAME(mci_status.dwReturn)); + cdrom->track[i].length = 0; + if (i > 0) { + cdrom->track[i - 1].length = + cdrom->track[i].offset - cdrom->track[i - 1].offset; + } + } + if (i == cdrom->numtracks) { + mci_status.dwTrack = cdrom->track[i - 1].id; + mci_status.dwItem = MCI_STATUS_LENGTH; + if (SDL_SYS_CDioctl(cdrom->id, MCI_STATUS, flags, + &mci_status) == 0) { + cdrom->track[i - 1].length = + MSF_TO_FRAMES(MCI_MSF_MINUTE(mci_status.dwReturn), + MCI_MSF_SECOND(mci_status.dwReturn), + MCI_MSF_FRAME(mci_status.dwReturn)); + /* compute lead-out offset */ + cdrom->track[i].offset = cdrom->track[i - 1].offset + + cdrom->track[i - 1].length; + cdrom->track[i].length = 0; + okay = 1; + } + } + } + return (okay ? 0 : -1); } /* Get CD-ROM status */ -static CDstatus SDL_SYS_CDStatus(SDL_CD *cdrom, int *position) +static CDstatus +SDL_SYS_CDStatus(SDL_CD * cdrom, int *position) { - CDstatus status; - MCI_STATUS_PARMS mci_status; - DWORD flags; - - flags = MCI_STATUS_ITEM | MCI_WAIT; - mci_status.dwItem = MCI_STATUS_MODE; - if ( SDL_SYS_CDioctl(cdrom->id, MCI_STATUS, flags, &mci_status) < 0 ) { - status = CD_ERROR; - } else { - switch (mci_status.dwReturn) { - case MCI_MODE_NOT_READY: - case MCI_MODE_OPEN: - status = CD_TRAYEMPTY; - break; - case MCI_MODE_STOP: + CDstatus status; + MCI_STATUS_PARMS mci_status; + DWORD flags; + + flags = MCI_STATUS_ITEM | MCI_WAIT; + mci_status.dwItem = MCI_STATUS_MODE; + if (SDL_SYS_CDioctl(cdrom->id, MCI_STATUS, flags, &mci_status) < 0) { + status = CD_ERROR; + } else { + switch (mci_status.dwReturn) { + case MCI_MODE_NOT_READY: + case MCI_MODE_OPEN: + status = CD_TRAYEMPTY; + break; + case MCI_MODE_STOP: #ifdef BROKEN_MCI_PAUSE - if ( SDL_paused[cdrom->id] ) { - status = CD_PAUSED; - } else { - status = CD_STOPPED; - } + if (SDL_paused[cdrom->id]) { + status = CD_PAUSED; + } else { + status = CD_STOPPED; + } #else - status = CD_STOPPED; + status = CD_STOPPED; #endif /* BROKEN_MCI_PAUSE */ - break; - case MCI_MODE_PLAY: + break; + case MCI_MODE_PLAY: #ifdef BROKEN_MCI_PAUSE - if ( SDL_paused[cdrom->id] ) { - status = CD_PAUSED; - } else { - status = CD_PLAYING; - } + if (SDL_paused[cdrom->id]) { + status = CD_PAUSED; + } else { + status = CD_PLAYING; + } #else - status = CD_PLAYING; + status = CD_PLAYING; #endif /* BROKEN_MCI_PAUSE */ - break; - case MCI_MODE_PAUSE: - status = CD_PAUSED; - break; - default: - status = CD_ERROR; - break; - } - } - if ( position ) { - if ( status == CD_PLAYING || (status == CD_PAUSED) ) { - mci_status.dwItem = MCI_STATUS_POSITION; - if ( SDL_SYS_CDioctl(cdrom->id, MCI_STATUS, flags, - &mci_status) == 0 ) { - *position = MSF_TO_FRAMES( - MCI_MSF_MINUTE(mci_status.dwReturn), - MCI_MSF_SECOND(mci_status.dwReturn), - MCI_MSF_FRAME(mci_status.dwReturn)); - } else { - *position = 0; - } - } else { - *position = 0; - } - } - return(status); + break; + case MCI_MODE_PAUSE: + status = CD_PAUSED; + break; + default: + status = CD_ERROR; + break; + } + } + if (position) { + if (status == CD_PLAYING || (status == CD_PAUSED)) { + mci_status.dwItem = MCI_STATUS_POSITION; + if (SDL_SYS_CDioctl(cdrom->id, MCI_STATUS, flags, + &mci_status) == 0) { + *position = + MSF_TO_FRAMES(MCI_MSF_MINUTE(mci_status.dwReturn), + MCI_MSF_SECOND(mci_status.dwReturn), + MCI_MSF_FRAME(mci_status.dwReturn)); + } else { + *position = 0; + } + } else { + *position = 0; + } + } + return (status); } /* Start play */ -static int SDL_SYS_CDPlay(SDL_CD *cdrom, int start, int length) +static int +SDL_SYS_CDPlay(SDL_CD * cdrom, int start, int length) { - MCI_PLAY_PARMS mci_play; - int m, s, f; - DWORD flags; - - flags = MCI_FROM | MCI_TO | MCI_NOTIFY; - mci_play.dwCallback = 0; - FRAMES_TO_MSF(start, &m, &s, &f); - mci_play.dwFrom = MCI_MAKE_MSF(m, s, f); - FRAMES_TO_MSF(start+length, &m, &s, &f); - mci_play.dwTo = MCI_MAKE_MSF(m, s, f); - SDL_CD_end_position = mci_play.dwTo; - return(SDL_SYS_CDioctl(cdrom->id, MCI_PLAY, flags, &mci_play)); + MCI_PLAY_PARMS mci_play; + int m, s, f; + DWORD flags; + + flags = MCI_FROM | MCI_TO | MCI_NOTIFY; + mci_play.dwCallback = 0; + FRAMES_TO_MSF(start, &m, &s, &f); + mci_play.dwFrom = MCI_MAKE_MSF(m, s, f); + FRAMES_TO_MSF(start + length, &m, &s, &f); + mci_play.dwTo = MCI_MAKE_MSF(m, s, f); + SDL_CD_end_position = mci_play.dwTo; + return (SDL_SYS_CDioctl(cdrom->id, MCI_PLAY, flags, &mci_play)); } /* Pause play */ -static int SDL_SYS_CDPause(SDL_CD *cdrom) +static int +SDL_SYS_CDPause(SDL_CD * cdrom) { #ifdef BROKEN_MCI_PAUSE - SDL_paused[cdrom->id] = 1; + SDL_paused[cdrom->id] = 1; #endif - return(SDL_SYS_CDioctl(cdrom->id, MCI_PAUSE, MCI_WAIT, NULL)); + return (SDL_SYS_CDioctl(cdrom->id, MCI_PAUSE, MCI_WAIT, NULL)); } /* Resume play */ -static int SDL_SYS_CDResume(SDL_CD *cdrom) +static int +SDL_SYS_CDResume(SDL_CD * cdrom) { #ifdef BROKEN_MCI_PAUSE - MCI_STATUS_PARMS mci_status; - int okay; - int flags; - - okay = 0; - /* Play from the current play position to the end position set earlier */ - flags = MCI_STATUS_ITEM | MCI_WAIT; - mci_status.dwItem = MCI_STATUS_POSITION; - if ( SDL_SYS_CDioctl(cdrom->id, MCI_STATUS, flags, &mci_status) == 0 ) { - MCI_PLAY_PARMS mci_play; - - flags = MCI_FROM | MCI_TO | MCI_NOTIFY; - mci_play.dwCallback = 0; - mci_play.dwFrom = mci_status.dwReturn; - mci_play.dwTo = SDL_CD_end_position; - if (SDL_SYS_CDioctl(cdrom->id,MCI_PLAY,flags,&mci_play) == 0) { - okay = 1; - SDL_paused[cdrom->id] = 0; - } - } - return(okay ? 0 : -1); + MCI_STATUS_PARMS mci_status; + int okay; + int flags; + + okay = 0; + /* Play from the current play position to the end position set earlier */ + flags = MCI_STATUS_ITEM | MCI_WAIT; + mci_status.dwItem = MCI_STATUS_POSITION; + if (SDL_SYS_CDioctl(cdrom->id, MCI_STATUS, flags, &mci_status) == 0) { + MCI_PLAY_PARMS mci_play; + + flags = MCI_FROM | MCI_TO | MCI_NOTIFY; + mci_play.dwCallback = 0; + mci_play.dwFrom = mci_status.dwReturn; + mci_play.dwTo = SDL_CD_end_position; + if (SDL_SYS_CDioctl(cdrom->id, MCI_PLAY, flags, &mci_play) == 0) { + okay = 1; + SDL_paused[cdrom->id] = 0; + } + } + return (okay ? 0 : -1); #else - return(SDL_SYS_CDioctl(cdrom->id, MCI_RESUME, MCI_WAIT, NULL)); + return (SDL_SYS_CDioctl(cdrom->id, MCI_RESUME, MCI_WAIT, NULL)); #endif /* BROKEN_MCI_PAUSE */ } /* Stop play */ -static int SDL_SYS_CDStop(SDL_CD *cdrom) +static int +SDL_SYS_CDStop(SDL_CD * cdrom) { - return(SDL_SYS_CDioctl(cdrom->id, MCI_STOP, MCI_WAIT, NULL)); + return (SDL_SYS_CDioctl(cdrom->id, MCI_STOP, MCI_WAIT, NULL)); } /* Eject the CD-ROM */ -static int SDL_SYS_CDEject(SDL_CD *cdrom) +static int +SDL_SYS_CDEject(SDL_CD * cdrom) { - return(SDL_SYS_CDioctl(cdrom->id, MCI_SET, MCI_SET_DOOR_OPEN, NULL)); + return (SDL_SYS_CDioctl(cdrom->id, MCI_SET, MCI_SET_DOOR_OPEN, NULL)); } /* Close the CD-ROM handle */ -static void SDL_SYS_CDClose(SDL_CD *cdrom) +static void +SDL_SYS_CDClose(SDL_CD * cdrom) { - SDL_SYS_CDioctl(cdrom->id, MCI_CLOSE, MCI_WAIT, NULL); + SDL_SYS_CDioctl(cdrom->id, MCI_CLOSE, MCI_WAIT, NULL); } -void SDL_SYS_CDQuit(void) +void +SDL_SYS_CDQuit(void) { - int i; - - if ( SDL_numcds > 0 ) { - for ( i=0; i 0) { + for (i = 0; i < SDL_numcds; ++i) { + SDL_free(SDL_cdlist[i]); + } + SDL_numcds = 0; + } } #endif /* SDL_CDROM_WIN32 */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/cpuinfo/SDL_cpuinfo.c b/src/cpuinfo/SDL_cpuinfo.c index be3987eae..147e1b8e3 100644 --- a/src/cpuinfo/SDL_cpuinfo.c +++ b/src/cpuinfo/SDL_cpuinfo.c @@ -27,7 +27,7 @@ #include "SDL_cpuinfo.h" #if defined(__MACOSX__) && defined(__ppc__) -#include /* For AltiVec check */ +#include /* For AltiVec check */ #elif SDL_ALTIVEC_BLITTERS && HAVE_SETJMP #include #include @@ -47,15 +47,18 @@ the idea is borrowed from the libmpeg2 library - thanks! */ static jmp_buf jmpbuf; -static void illegal_instruction(int sig) +static void +illegal_instruction(int sig) { - longjmp(jmpbuf, 1); + longjmp(jmpbuf, 1); } #endif /* HAVE_SETJMP */ -static __inline__ int CPU_haveCPUID(void) +static __inline__ int +CPU_haveCPUID(void) { - int has_CPUID = 0; + int has_CPUID = 0; +/* *INDENT-OFF* */ #if defined(__GNUC__) && defined(i386) __asm__ ( " pushfl # Get original EFLAGS \n" @@ -140,12 +143,15 @@ CPUid by definition. But it's nice to be able to prove it. :) */ "1: \n" ); #endif - return has_CPUID; +/* *INDENT-ON* */ + return has_CPUID; } -static __inline__ int CPU_getCPUIDFeatures(void) +static __inline__ int +CPU_getCPUIDFeatures(void) { - int features = 0; + int features = 0; +/* *INDENT-OFF* */ #if defined(__GNUC__) && ( defined(i386) || defined(__x86_64__) ) __asm__ ( " movl %%ebx,%%edi\n" @@ -193,12 +199,15 @@ static __inline__ int CPU_getCPUIDFeatures(void) "1: \n" " movl %edi,%ebx\n" ); #endif - return features; +/* *INDENT-ON* */ + return features; } -static __inline__ int CPU_getCPUIDFeaturesExt(void) +static __inline__ int +CPU_getCPUIDFeaturesExt(void) { - int features = 0; + int features = 0; +/* *INDENT-OFF* */ #if defined(__GNUC__) && (defined(i386) || defined (__x86_64__) ) __asm__ ( " movl %%ebx,%%edi\n" @@ -244,203 +253,221 @@ static __inline__ int CPU_getCPUIDFeaturesExt(void) " movl %edi,%ebx\n" ); #endif - return features; +/* *INDENT-ON* */ + return features; } -static __inline__ int CPU_haveRDTSC(void) +static __inline__ int +CPU_haveRDTSC(void) { - if ( CPU_haveCPUID() ) { - return (CPU_getCPUIDFeatures() & 0x00000010); - } - return 0; + if (CPU_haveCPUID()) { + return (CPU_getCPUIDFeatures() & 0x00000010); + } + return 0; } -static __inline__ int CPU_haveMMX(void) +static __inline__ int +CPU_haveMMX(void) { - if ( CPU_haveCPUID() ) { - return (CPU_getCPUIDFeatures() & 0x00800000); - } - return 0; + if (CPU_haveCPUID()) { + return (CPU_getCPUIDFeatures() & 0x00800000); + } + return 0; } -static __inline__ int CPU_haveMMXExt(void) +static __inline__ int +CPU_haveMMXExt(void) { - if ( CPU_haveCPUID() ) { - return (CPU_getCPUIDFeaturesExt() & 0x00400000); - } - return 0; + if (CPU_haveCPUID()) { + return (CPU_getCPUIDFeaturesExt() & 0x00400000); + } + return 0; } -static __inline__ int CPU_have3DNow(void) +static __inline__ int +CPU_have3DNow(void) { - if ( CPU_haveCPUID() ) { - return (CPU_getCPUIDFeaturesExt() & 0x80000000); - } - return 0; + if (CPU_haveCPUID()) { + return (CPU_getCPUIDFeaturesExt() & 0x80000000); + } + return 0; } -static __inline__ int CPU_have3DNowExt(void) +static __inline__ int +CPU_have3DNowExt(void) { - if ( CPU_haveCPUID() ) { - return (CPU_getCPUIDFeaturesExt() & 0x40000000); - } - return 0; + if (CPU_haveCPUID()) { + return (CPU_getCPUIDFeaturesExt() & 0x40000000); + } + return 0; } -static __inline__ int CPU_haveSSE(void) +static __inline__ int +CPU_haveSSE(void) { - if ( CPU_haveCPUID() ) { - return (CPU_getCPUIDFeatures() & 0x02000000); - } - return 0; + if (CPU_haveCPUID()) { + return (CPU_getCPUIDFeatures() & 0x02000000); + } + return 0; } -static __inline__ int CPU_haveSSE2(void) +static __inline__ int +CPU_haveSSE2(void) { - if ( CPU_haveCPUID() ) { - return (CPU_getCPUIDFeatures() & 0x04000000); - } - return 0; + if (CPU_haveCPUID()) { + return (CPU_getCPUIDFeatures() & 0x04000000); + } + return 0; } -static __inline__ int CPU_haveAltiVec(void) +static __inline__ int +CPU_haveAltiVec(void) { - volatile int altivec = 0; + volatile int altivec = 0; #if defined(__MACOSX__) && defined(__ppc__) - int selectors[2] = { CTL_HW, HW_VECTORUNIT }; - int hasVectorUnit = 0; - size_t length = sizeof(hasVectorUnit); - int error = sysctl(selectors, 2, &hasVectorUnit, &length, NULL, 0); - if( 0 == error ) - altivec = (hasVectorUnit != 0); + int selectors[2] = { CTL_HW, HW_VECTORUNIT }; + int hasVectorUnit = 0; + size_t length = sizeof(hasVectorUnit); + int error = sysctl(selectors, 2, &hasVectorUnit, &length, NULL, 0); + if (0 == error) + altivec = (hasVectorUnit != 0); #elif SDL_ALTIVEC_BLITTERS && HAVE_SETJMP - void (*handler)(int sig); - handler = signal(SIGILL, illegal_instruction); - if ( setjmp(jmpbuf) == 0 ) { - asm volatile ("mtspr 256, %0\n\t" - "vand %%v0, %%v0, %%v0" - : - : "r" (-1)); - altivec = 1; - } - signal(SIGILL, handler); + void (*handler) (int sig); + handler = signal(SIGILL, illegal_instruction); + if (setjmp(jmpbuf) == 0) { + asm volatile ("mtspr 256, %0\n\t" "vand %%v0, %%v0, %%v0"::"r" (-1)); + altivec = 1; + } + signal(SIGILL, handler); #endif - return altivec; + return altivec; } static Uint32 SDL_CPUFeatures = 0xFFFFFFFF; -static Uint32 SDL_GetCPUFeatures(void) +static Uint32 +SDL_GetCPUFeatures(void) { - if ( SDL_CPUFeatures == 0xFFFFFFFF ) { - SDL_CPUFeatures = 0; - if ( CPU_haveRDTSC() ) { - SDL_CPUFeatures |= CPU_HAS_RDTSC; - } - if ( CPU_haveMMX() ) { - SDL_CPUFeatures |= CPU_HAS_MMX; - } - if ( CPU_haveMMXExt() ) { - SDL_CPUFeatures |= CPU_HAS_MMXEXT; - } - if ( CPU_have3DNow() ) { - SDL_CPUFeatures |= CPU_HAS_3DNOW; - } - if ( CPU_have3DNowExt() ) { - SDL_CPUFeatures |= CPU_HAS_3DNOWEXT; - } - if ( CPU_haveSSE() ) { - SDL_CPUFeatures |= CPU_HAS_SSE; - } - if ( CPU_haveSSE2() ) { - SDL_CPUFeatures |= CPU_HAS_SSE2; - } - if ( CPU_haveAltiVec() ) { - SDL_CPUFeatures |= CPU_HAS_ALTIVEC; - } - } - return SDL_CPUFeatures; + if (SDL_CPUFeatures == 0xFFFFFFFF) { + SDL_CPUFeatures = 0; + if (CPU_haveRDTSC()) { + SDL_CPUFeatures |= CPU_HAS_RDTSC; + } + if (CPU_haveMMX()) { + SDL_CPUFeatures |= CPU_HAS_MMX; + } + if (CPU_haveMMXExt()) { + SDL_CPUFeatures |= CPU_HAS_MMXEXT; + } + if (CPU_have3DNow()) { + SDL_CPUFeatures |= CPU_HAS_3DNOW; + } + if (CPU_have3DNowExt()) { + SDL_CPUFeatures |= CPU_HAS_3DNOWEXT; + } + if (CPU_haveSSE()) { + SDL_CPUFeatures |= CPU_HAS_SSE; + } + if (CPU_haveSSE2()) { + SDL_CPUFeatures |= CPU_HAS_SSE2; + } + if (CPU_haveAltiVec()) { + SDL_CPUFeatures |= CPU_HAS_ALTIVEC; + } + } + return SDL_CPUFeatures; } -SDL_bool SDL_HasRDTSC(void) +SDL_bool +SDL_HasRDTSC(void) { - if ( SDL_GetCPUFeatures() & CPU_HAS_RDTSC ) { - return SDL_TRUE; - } - return SDL_FALSE; + if (SDL_GetCPUFeatures() & CPU_HAS_RDTSC) { + return SDL_TRUE; + } + return SDL_FALSE; } -SDL_bool SDL_HasMMX(void) +SDL_bool +SDL_HasMMX(void) { - if ( SDL_GetCPUFeatures() & CPU_HAS_MMX ) { - return SDL_TRUE; - } - return SDL_FALSE; + if (SDL_GetCPUFeatures() & CPU_HAS_MMX) { + return SDL_TRUE; + } + return SDL_FALSE; } -SDL_bool SDL_HasMMXExt(void) +SDL_bool +SDL_HasMMXExt(void) { - if ( SDL_GetCPUFeatures() & CPU_HAS_MMXEXT ) { - return SDL_TRUE; - } - return SDL_FALSE; + if (SDL_GetCPUFeatures() & CPU_HAS_MMXEXT) { + return SDL_TRUE; + } + return SDL_FALSE; } -SDL_bool SDL_Has3DNow(void) +SDL_bool +SDL_Has3DNow(void) { - if ( SDL_GetCPUFeatures() & CPU_HAS_3DNOW ) { - return SDL_TRUE; - } - return SDL_FALSE; + if (SDL_GetCPUFeatures() & CPU_HAS_3DNOW) { + return SDL_TRUE; + } + return SDL_FALSE; } -SDL_bool SDL_Has3DNowExt(void) +SDL_bool +SDL_Has3DNowExt(void) { - if ( SDL_GetCPUFeatures() & CPU_HAS_3DNOWEXT ) { - return SDL_TRUE; - } - return SDL_FALSE; + if (SDL_GetCPUFeatures() & CPU_HAS_3DNOWEXT) { + return SDL_TRUE; + } + return SDL_FALSE; } -SDL_bool SDL_HasSSE(void) +SDL_bool +SDL_HasSSE(void) { - if ( SDL_GetCPUFeatures() & CPU_HAS_SSE ) { - return SDL_TRUE; - } - return SDL_FALSE; + if (SDL_GetCPUFeatures() & CPU_HAS_SSE) { + return SDL_TRUE; + } + return SDL_FALSE; } -SDL_bool SDL_HasSSE2(void) +SDL_bool +SDL_HasSSE2(void) { - if ( SDL_GetCPUFeatures() & CPU_HAS_SSE2 ) { - return SDL_TRUE; - } - return SDL_FALSE; + if (SDL_GetCPUFeatures() & CPU_HAS_SSE2) { + return SDL_TRUE; + } + return SDL_FALSE; } -SDL_bool SDL_HasAltiVec(void) +SDL_bool +SDL_HasAltiVec(void) { - if ( SDL_GetCPUFeatures() & CPU_HAS_ALTIVEC ) { - return SDL_TRUE; - } - return SDL_FALSE; + if (SDL_GetCPUFeatures() & CPU_HAS_ALTIVEC) { + return SDL_TRUE; + } + return SDL_FALSE; } #ifdef TEST_MAIN #include -int main() +int +main() { - printf("RDTSC: %d\n", SDL_HasRDTSC()); - printf("MMX: %d\n", SDL_HasMMX()); - printf("MMXExt: %d\n", SDL_HasMMXExt()); - printf("3DNow: %d\n", SDL_Has3DNow()); - printf("3DNowExt: %d\n", SDL_Has3DNowExt()); - printf("SSE: %d\n", SDL_HasSSE()); - printf("SSE2: %d\n", SDL_HasSSE2()); - printf("AltiVec: %d\n", SDL_HasAltiVec()); - return 0; + printf("RDTSC: %d\n", SDL_HasRDTSC()); + printf("MMX: %d\n", SDL_HasMMX()); + printf("MMXExt: %d\n", SDL_HasMMXExt()); + printf("3DNow: %d\n", SDL_Has3DNow()); + printf("3DNowExt: %d\n", SDL_Has3DNowExt()); + printf("SSE: %d\n", SDL_HasSSE()); + printf("SSE2: %d\n", SDL_HasSSE2()); + printf("AltiVec: %d\n", SDL_HasAltiVec()); + return 0; } #endif /* TEST_MAIN */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/events/SDL_active.c b/src/events/SDL_active.c deleted file mode 100644 index 17b5908a8..000000000 --- a/src/events/SDL_active.c +++ /dev/null @@ -1,91 +0,0 @@ -/* - SDL - Simple DirectMedia Layer - Copyright (C) 1997-2006 Sam Lantinga - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - - Sam Lantinga - slouken@libsdl.org -*/ -#include "SDL_config.h" - -/* Application focus/iconification handling code for SDL */ - -#include "SDL_events.h" -#include "SDL_events_c.h" - - -/* These are static for our active event handling code */ -static Uint8 SDL_appstate = 0; - -/* Public functions */ -int SDL_AppActiveInit(void) -{ - /* Start completely active */ - SDL_appstate = (SDL_APPACTIVE|SDL_APPINPUTFOCUS|SDL_APPMOUSEFOCUS); - - /* That's it! */ - return(0); -} -void SDL_AppActiveQuit(void) -{ -} - -Uint8 SDL_GetAppState(void) -{ - return(SDL_appstate); -} - -/* This is global for SDL_eventloop.c */ -int SDL_PrivateAppActive(Uint8 gain, Uint8 state) -{ - int posted; - Uint8 new_state; - - /* Modify the current state with the given mask */ - if ( gain ) { - new_state = (SDL_appstate | state); - } else { - new_state = (SDL_appstate & ~state); - } - - /* Drop events that don't change state */ - if ( new_state == SDL_appstate ) { - return(0); - } - - /* Update internal active state */ - SDL_appstate = new_state; - - /* Post the event, if desired */ - posted = 0; - if ( SDL_ProcessEvents[SDL_ACTIVEEVENT] == SDL_ENABLE ) { - SDL_Event event; - SDL_memset(&event, 0, sizeof(event)); - event.type = SDL_ACTIVEEVENT; - event.active.gain = gain; - event.active.state = state; - if ( (SDL_EventOK == NULL) || (*SDL_EventOK)(&event) ) { - posted = 1; - SDL_PushEvent(&event); - } - } - - /* If we lost keyboard focus, post key-up events */ - if ( (state & SDL_APPINPUTFOCUS) && !gain ) { - SDL_ResetKeyboard(); - } - return(posted); -} diff --git a/src/events/SDL_events.c b/src/events/SDL_events.c index 1a51dbd7e..5b706fa41 100644 --- a/src/events/SDL_events.c +++ b/src/events/SDL_events.c @@ -34,46 +34,51 @@ /* Public data -- the event filter */ SDL_EventFilter SDL_EventOK = NULL; +void *SDL_EventOKParam; Uint8 SDL_ProcessEvents[SDL_NUMEVENTS]; static Uint32 SDL_eventstate = 0; /* Private data -- event queue */ #define MAXEVENTS 128 -static struct { - SDL_mutex *lock; - int active; - int head; - int tail; - SDL_Event event[MAXEVENTS]; - int wmmsg_next; - struct SDL_SysWMmsg wmmsg[MAXEVENTS]; +static struct +{ + SDL_mutex *lock; + int active; + int head; + int tail; + SDL_Event event[MAXEVENTS]; + int wmmsg_next; + struct SDL_SysWMmsg wmmsg[MAXEVENTS]; } SDL_EventQ; /* Private data -- event locking structure */ -static struct { - SDL_mutex *lock; - int safe; +static struct +{ + SDL_mutex *lock; + int safe; } SDL_EventLock; /* Thread functions */ -static SDL_Thread *SDL_EventThread = NULL; /* Thread handle */ -static Uint32 event_thread; /* The event thread id */ +static SDL_Thread *SDL_EventThread = NULL; /* Thread handle */ +static Uint32 event_thread; /* The event thread id */ -void SDL_Lock_EventThread(void) +void +SDL_Lock_EventThread(void) { - if ( SDL_EventThread && (SDL_ThreadID() != event_thread) ) { - /* Grab lock and spin until we're sure event thread stopped */ - SDL_mutexP(SDL_EventLock.lock); - while ( ! SDL_EventLock.safe ) { - SDL_Delay(1); - } - } + if (SDL_EventThread && (SDL_ThreadID() != event_thread)) { + /* Grab lock and spin until we're sure event thread stopped */ + SDL_mutexP(SDL_EventLock.lock); + while (!SDL_EventLock.safe) { + SDL_Delay(1); + } + } } -void SDL_Unlock_EventThread(void) +void +SDL_Unlock_EventThread(void) { - if ( SDL_EventThread && (SDL_ThreadID() != event_thread) ) { - SDL_mutexV(SDL_EventLock.lock); - } + if (SDL_EventThread && (SDL_ThreadID() != event_thread)) { + SDL_mutexV(SDL_EventLock.lock); + } } #ifdef __OS2__ @@ -87,414 +92,461 @@ void SDL_Unlock_EventThread(void) #include #endif -static int SDLCALL SDL_GobbleEvents(void *unused) +static int SDLCALL +SDL_GobbleEvents(void *unused) { - event_thread = SDL_ThreadID(); + event_thread = SDL_ThreadID(); #ifdef __OS2__ #ifdef USE_DOSSETPRIORITY - /* Increase thread priority, so it will process events in time for sure! */ - DosSetPriority(PRTYS_THREAD, PRTYC_REGULAR, +16, 0); + /* Increase thread priority, so it will process events in time for sure! */ + DosSetPriority(PRTYS_THREAD, PRTYC_REGULAR, +16, 0); #endif #endif - while ( SDL_EventQ.active ) { - SDL_VideoDevice *video = current_video; - SDL_VideoDevice *this = current_video; + while (SDL_EventQ.active) { + SDL_VideoDevice *_this = SDL_GetVideoDevice(); - /* Get events from the video subsystem */ - if ( video ) { - video->PumpEvents(this); - } + /* Get events from the video subsystem */ + if (_this) { + _this->PumpEvents(_this); + } - /* Queue pending key-repeat events */ - SDL_CheckKeyRepeat(); + /* Queue pending key-repeat events */ + SDL_CheckKeyRepeat(); #if !SDL_JOYSTICK_DISABLED - /* Check for joystick state change */ - if ( SDL_numjoysticks && (SDL_eventstate & SDL_JOYEVENTMASK) ) { - SDL_JoystickUpdate(); - } + /* Check for joystick state change */ + if (SDL_numjoysticks && (SDL_eventstate & SDL_JOYEVENTMASK)) { + SDL_JoystickUpdate(); + } #endif - /* Give up the CPU for the rest of our timeslice */ - SDL_EventLock.safe = 1; - if ( SDL_timer_running ) { - SDL_ThreadedTimerCheck(); - } - SDL_Delay(1); - - /* Check for event locking. - On the P of the lock mutex, if the lock is held, this thread - will wait until the lock is released before continuing. The - safe flag will be set, meaning that the other thread can go - about it's business. The safe flag is reset before the V, - so as soon as the mutex is free, other threads can see that - it's not safe to interfere with the event thread. - */ - SDL_mutexP(SDL_EventLock.lock); - SDL_EventLock.safe = 0; - SDL_mutexV(SDL_EventLock.lock); - } - SDL_SetTimerThreaded(0); - event_thread = 0; - return(0); + /* Give up the CPU for the rest of our timeslice */ + SDL_EventLock.safe = 1; + if (SDL_timer_running) { + SDL_ThreadedTimerCheck(); + } + SDL_Delay(1); + + /* Check for event locking. + On the P of the lock mutex, if the lock is held, this thread + will wait until the lock is released before continuing. The + safe flag will be set, meaning that the other thread can go + about it's business. The safe flag is reset before the V, + so as soon as the mutex is free, other threads can see that + it's not safe to interfere with the event thread. + */ + SDL_mutexP(SDL_EventLock.lock); + SDL_EventLock.safe = 0; + SDL_mutexV(SDL_EventLock.lock); + } + SDL_SetTimerThreaded(0); + event_thread = 0; + return (0); } -static int SDL_StartEventThread(Uint32 flags) +static int +SDL_StartEventThread(Uint32 flags) { - /* Reset everything to zero */ - SDL_EventThread = NULL; - SDL_memset(&SDL_EventLock, 0, sizeof(SDL_EventLock)); + /* Reset everything to zero */ + SDL_EventThread = NULL; + SDL_memset(&SDL_EventLock, 0, sizeof(SDL_EventLock)); - /* Create the lock and set ourselves active */ + /* Create the lock and set ourselves active */ #if !SDL_THREADS_DISABLED - SDL_EventQ.lock = SDL_CreateMutex(); - if ( SDL_EventQ.lock == NULL ) { -#ifdef __MACOS__ /* MacOS classic you can't multithread, so no lock needed */ - ; + SDL_EventQ.lock = SDL_CreateMutex(); + if (SDL_EventQ.lock == NULL) { +#ifdef __MACOS__ /* MacOS classic you can't multithread, so no lock needed */ + ; #else - return(-1); + return (-1); #endif - } + } #endif /* !SDL_THREADS_DISABLED */ - SDL_EventQ.active = 1; + SDL_EventQ.active = 1; - if ( (flags&SDL_INIT_EVENTTHREAD) == SDL_INIT_EVENTTHREAD ) { - SDL_EventLock.lock = SDL_CreateMutex(); - if ( SDL_EventLock.lock == NULL ) { - return(-1); - } - SDL_EventLock.safe = 0; + if ((flags & SDL_INIT_EVENTTHREAD) == SDL_INIT_EVENTTHREAD) { + SDL_EventLock.lock = SDL_CreateMutex(); + if (SDL_EventLock.lock == NULL) { + return (-1); + } + SDL_EventLock.safe = 0; - /* The event thread will handle timers too */ - SDL_SetTimerThreaded(2); + /* The event thread will handle timers too */ + SDL_SetTimerThreaded(2); #if (defined(__WIN32__) && !defined(_WIN32_WCE)) && !defined(HAVE_LIBC) #undef SDL_CreateThread - SDL_EventThread = SDL_CreateThread(SDL_GobbleEvents, NULL, NULL, NULL); + SDL_EventThread = + SDL_CreateThread(SDL_GobbleEvents, NULL, NULL, NULL); #else - SDL_EventThread = SDL_CreateThread(SDL_GobbleEvents, NULL); + SDL_EventThread = SDL_CreateThread(SDL_GobbleEvents, NULL); #endif - if ( SDL_EventThread == NULL ) { - return(-1); - } - } else { - event_thread = 0; - } - return(0); + if (SDL_EventThread == NULL) { + return (-1); + } + } else { + event_thread = 0; + } + return (0); } -static void SDL_StopEventThread(void) +static void +SDL_StopEventThread(void) { - SDL_EventQ.active = 0; - if ( SDL_EventThread ) { - SDL_WaitThread(SDL_EventThread, NULL); - SDL_EventThread = NULL; - SDL_DestroyMutex(SDL_EventLock.lock); - } + SDL_EventQ.active = 0; + if (SDL_EventThread) { + SDL_WaitThread(SDL_EventThread, NULL); + SDL_EventThread = NULL; + SDL_DestroyMutex(SDL_EventLock.lock); + } #ifndef IPOD - SDL_DestroyMutex(SDL_EventQ.lock); + SDL_DestroyMutex(SDL_EventQ.lock); #endif } -Uint32 SDL_EventThreadID(void) +Uint32 +SDL_EventThreadID(void) { - return(event_thread); + return (event_thread); } /* Public functions */ -void SDL_StopEventLoop(void) +void +SDL_StopEventLoop(void) { - /* Halt the event thread, if running */ - SDL_StopEventThread(); - - /* Shutdown event handlers */ - SDL_AppActiveQuit(); - SDL_KeyboardQuit(); - SDL_MouseQuit(); - SDL_QuitQuit(); - - /* Clean out EventQ */ - SDL_EventQ.head = 0; - SDL_EventQ.tail = 0; - SDL_EventQ.wmmsg_next = 0; + /* Halt the event thread, if running */ + SDL_StopEventThread(); + + /* Shutdown event handlers */ + SDL_KeyboardQuit(); + SDL_MouseQuit(); + SDL_QuitQuit(); + + /* Clean out EventQ */ + SDL_EventQ.head = 0; + SDL_EventQ.tail = 0; + SDL_EventQ.wmmsg_next = 0; } /* This function (and associated calls) may be called more than once */ -int SDL_StartEventLoop(Uint32 flags) +int +SDL_StartEventLoop(Uint32 flags) { - int retcode; - - /* Clean out the event queue */ - SDL_EventThread = NULL; - SDL_EventQ.lock = NULL; - SDL_StopEventLoop(); - - /* No filter to start with, process most event types */ - SDL_EventOK = NULL; - SDL_memset(SDL_ProcessEvents,SDL_ENABLE,sizeof(SDL_ProcessEvents)); - SDL_eventstate = ~0; - /* It's not save to call SDL_EventState() yet */ - SDL_eventstate &= ~(0x00000001 << SDL_SYSWMEVENT); - SDL_ProcessEvents[SDL_SYSWMEVENT] = SDL_IGNORE; - - /* Initialize event handlers */ - retcode = 0; - retcode += SDL_AppActiveInit(); - retcode += SDL_KeyboardInit(); - retcode += SDL_MouseInit(); - retcode += SDL_QuitInit(); - if ( retcode < 0 ) { - /* We don't expect them to fail, but... */ - return(-1); - } - - /* Create the lock and event thread */ - if ( SDL_StartEventThread(flags) < 0 ) { - SDL_StopEventLoop(); - return(-1); - } - return(0); + int retcode; + + /* Clean out the event queue */ + SDL_EventThread = NULL; + SDL_EventQ.lock = NULL; + SDL_StopEventLoop(); + + /* No filter to start with, process most event types */ + SDL_EventOK = NULL; + SDL_memset(SDL_ProcessEvents, SDL_ENABLE, sizeof(SDL_ProcessEvents)); + SDL_eventstate = ~0; + /* It's not save to call SDL_EventState() yet */ + SDL_eventstate &= ~(0x00000001 << SDL_SYSWMEVENT); + SDL_ProcessEvents[SDL_SYSWMEVENT] = SDL_IGNORE; + + /* Initialize event handlers */ + retcode = 0; + retcode += SDL_KeyboardInit(); + retcode += SDL_MouseInit(); + retcode += SDL_QuitInit(); + if (retcode < 0) { + /* We don't expect them to fail, but... */ + return (-1); + } + + /* Create the lock and event thread */ + if (SDL_StartEventThread(flags) < 0) { + SDL_StopEventLoop(); + return (-1); + } + return (0); } /* Add an event to the event queue -- called with the queue locked */ -static int SDL_AddEvent(SDL_Event *event) +static int +SDL_AddEvent(SDL_Event * event) { - int tail, added; - - tail = (SDL_EventQ.tail+1)%MAXEVENTS; - if ( tail == SDL_EventQ.head ) { - /* Overflow, drop event */ - added = 0; - } else { - SDL_EventQ.event[SDL_EventQ.tail] = *event; - if (event->type == SDL_SYSWMEVENT) { - /* Note that it's possible to lose an event */ - int next = SDL_EventQ.wmmsg_next; - SDL_EventQ.wmmsg[next] = *event->syswm.msg; - SDL_EventQ.event[SDL_EventQ.tail].syswm.msg = - &SDL_EventQ.wmmsg[next]; - SDL_EventQ.wmmsg_next = (next+1)%MAXEVENTS; - } - SDL_EventQ.tail = tail; - added = 1; - } - return(added); + int tail, added; + + tail = (SDL_EventQ.tail + 1) % MAXEVENTS; + if (tail == SDL_EventQ.head) { + /* Overflow, drop event */ + added = 0; + } else { + SDL_EventQ.event[SDL_EventQ.tail] = *event; + if (event->type == SDL_SYSWMEVENT) { + /* Note that it's possible to lose an event */ + int next = SDL_EventQ.wmmsg_next; + SDL_EventQ.wmmsg[next] = *event->syswm.msg; + SDL_EventQ.event[SDL_EventQ.tail].syswm.msg = + &SDL_EventQ.wmmsg[next]; + SDL_EventQ.wmmsg_next = (next + 1) % MAXEVENTS; + } + SDL_EventQ.tail = tail; + added = 1; + } + return (added); } /* Cut an event, and return the next valid spot, or the tail */ /* -- called with the queue locked */ -static int SDL_CutEvent(int spot) +static int +SDL_CutEvent(int spot) { - if ( spot == SDL_EventQ.head ) { - SDL_EventQ.head = (SDL_EventQ.head+1)%MAXEVENTS; - return(SDL_EventQ.head); - } else - if ( (spot+1)%MAXEVENTS == SDL_EventQ.tail ) { - SDL_EventQ.tail = spot; - return(SDL_EventQ.tail); - } else - /* We cut the middle -- shift everything over */ - { - int here, next; - - /* This can probably be optimized with SDL_memcpy() -- careful! */ - if ( --SDL_EventQ.tail < 0 ) { - SDL_EventQ.tail = MAXEVENTS-1; - } - for ( here=spot; here != SDL_EventQ.tail; here = next ) { - next = (here+1)%MAXEVENTS; - SDL_EventQ.event[here] = SDL_EventQ.event[next]; - } - return(spot); - } - /* NOTREACHED */ + if (spot == SDL_EventQ.head) { + SDL_EventQ.head = (SDL_EventQ.head + 1) % MAXEVENTS; + return (SDL_EventQ.head); + } else if ((spot + 1) % MAXEVENTS == SDL_EventQ.tail) { + SDL_EventQ.tail = spot; + return (SDL_EventQ.tail); + } else + /* We cut the middle -- shift everything over */ + { + int here, next; + + /* This can probably be optimized with SDL_memcpy() -- careful! */ + if (--SDL_EventQ.tail < 0) { + SDL_EventQ.tail = MAXEVENTS - 1; + } + for (here = spot; here != SDL_EventQ.tail; here = next) { + next = (here + 1) % MAXEVENTS; + SDL_EventQ.event[here] = SDL_EventQ.event[next]; + } + return (spot); + } + /* NOTREACHED */ } /* Lock the event queue, take a peep at it, and unlock it */ -int SDL_PeepEvents(SDL_Event *events, int numevents, SDL_eventaction action, - Uint32 mask) +int +SDL_PeepEvents(SDL_Event * events, int numevents, SDL_eventaction action, + Uint32 mask) +{ + int i, used; + + /* Don't look after we've quit */ + if (!SDL_EventQ.active) { + return (-1); + } + /* Lock the event queue */ + used = 0; + if (SDL_mutexP(SDL_EventQ.lock) == 0) { + if (action == SDL_ADDEVENT) { + for (i = 0; i < numevents; ++i) { + used += SDL_AddEvent(&events[i]); + } + } else { + SDL_Event tmpevent; + int spot; + + /* If 'events' is NULL, just see if they exist */ + if (events == NULL) { + action = SDL_PEEKEVENT; + numevents = 1; + events = &tmpevent; + } + spot = SDL_EventQ.head; + while ((used < numevents) && (spot != SDL_EventQ.tail)) { + if (mask & SDL_EVENTMASK(SDL_EventQ.event[spot].type)) { + events[used++] = SDL_EventQ.event[spot]; + if (action == SDL_GETEVENT) { + spot = SDL_CutEvent(spot); + } else { + spot = (spot + 1) % MAXEVENTS; + } + } else { + spot = (spot + 1) % MAXEVENTS; + } + } + } + SDL_mutexV(SDL_EventQ.lock); + } else { + SDL_SetError("Couldn't lock event queue"); + used = -1; + } + return (used); +} + +SDL_bool +SDL_HasEvent(Uint32 mask) { - int i, used; - - /* Don't look after we've quit */ - if ( ! SDL_EventQ.active ) { - return(-1); - } - /* Lock the event queue */ - used = 0; - if ( SDL_mutexP(SDL_EventQ.lock) == 0 ) { - if ( action == SDL_ADDEVENT ) { - for ( i=0; i 0); } /* Run the system dependent event loops */ -void SDL_PumpEvents(void) +void +SDL_PumpEvents(void) { - if ( !SDL_EventThread ) { - SDL_VideoDevice *video = current_video; - SDL_VideoDevice *this = current_video; + if (!SDL_EventThread) { + SDL_VideoDevice *_this = SDL_GetVideoDevice(); - /* Get events from the video subsystem */ - if ( video ) { - video->PumpEvents(this); - } + /* Get events from the video subsystem */ + if (_this) { + _this->PumpEvents(_this); + } - /* Queue pending key-repeat events */ - SDL_CheckKeyRepeat(); + /* Queue pending key-repeat events */ + SDL_CheckKeyRepeat(); #if !SDL_JOYSTICK_DISABLED - /* Check for joystick state change */ - if ( SDL_numjoysticks && (SDL_eventstate & SDL_JOYEVENTMASK) ) { - SDL_JoystickUpdate(); - } + /* Check for joystick state change */ + if (SDL_numjoysticks && (SDL_eventstate & SDL_JOYEVENTMASK)) { + SDL_JoystickUpdate(); + } #endif - } + } } /* Public functions */ -int SDL_PollEvent (SDL_Event *event) +int +SDL_PollEvent(SDL_Event * event) { - SDL_PumpEvents(); + SDL_PumpEvents(); - /* We can't return -1, just return 0 (no event) on error */ - if ( SDL_PeepEvents(event, 1, SDL_GETEVENT, SDL_ALLEVENTS) <= 0 ) - return 0; - return 1; + /* We can't return -1, just return 0 (no event) on error */ + if (SDL_PeepEvents(event, 1, SDL_GETEVENT, SDL_ALLEVENTS) <= 0) + return 0; + return 1; } -int SDL_WaitEvent (SDL_Event *event) +int +SDL_WaitEvent(SDL_Event * event) { - while ( 1 ) { - SDL_PumpEvents(); - switch(SDL_PeepEvents(event, 1, SDL_GETEVENT, SDL_ALLEVENTS)) { - case -1: return 0; - case 1: return 1; - case 0: SDL_Delay(10); - } - } + while (1) { + SDL_PumpEvents(); + switch (SDL_PeepEvents(event, 1, SDL_GETEVENT, SDL_ALLEVENTS)) { + case -1: + return 0; + case 1: + return 1; + case 0: + SDL_Delay(10); + } + } } -int SDL_PushEvent(SDL_Event *event) +int +SDL_PushEvent(SDL_Event * event) { - if ( SDL_PeepEvents(event, 1, SDL_ADDEVENT, 0) <= 0 ) - return -1; - return 0; + if (SDL_EventOK && !SDL_EventOK(SDL_EventOKParam, event)) { + return 0; + } + if (SDL_PeepEvents(event, 1, SDL_ADDEVENT, 0) <= 0) { + return -1; + } + return 1; } -void SDL_SetEventFilter (SDL_EventFilter filter) +void +SDL_SetEventFilter(SDL_EventFilter filter, void *userdata) { - SDL_Event bitbucket; + SDL_Event bitbucket; - /* Set filter and discard pending events */ - SDL_EventOK = filter; - while ( SDL_PollEvent(&bitbucket) > 0 ) - ; + /* Set filter and discard pending events */ + SDL_EventOK = filter; + SDL_EventOKParam = userdata; + while (SDL_PollEvent(&bitbucket) > 0); } -SDL_EventFilter SDL_GetEventFilter(void) +SDL_bool +SDL_GetEventFilter(SDL_EventFilter * filter, void **userdata) { - return(SDL_EventOK); + if (filter) { + *filter = SDL_EventOK; + } + if (userdata) { + *userdata = SDL_EventOKParam; + } + return SDL_EventOK ? SDL_TRUE : SDL_FALSE; } -Uint8 SDL_EventState (Uint8 type, int state) +void +SDL_FilterEvents(SDL_EventFilter filter, void *userdata) { - SDL_Event bitbucket; - Uint8 current_state; - - /* If SDL_ALLEVENTS was specified... */ - if ( type == 0xFF ) { - current_state = SDL_IGNORE; - for ( type=0; type 0 ) - ; - return(current_state); - } - - /* Just set the state for one event type */ - current_state = SDL_ProcessEvents[type]; - switch (state) { - case SDL_IGNORE: - case SDL_ENABLE: - /* Set state and discard pending events */ - SDL_ProcessEvents[type] = state; - if ( state == SDL_ENABLE ) { - SDL_eventstate |= (0x00000001 << (type)); - } else { - SDL_eventstate &= ~(0x00000001 << (type)); - } - while ( SDL_PollEvent(&bitbucket) > 0 ) - ; - break; - default: - /* Querying state? */ - break; - } - return(current_state); + if (SDL_mutexP(SDL_EventQ.lock) == 0) { + int spot; + + spot = SDL_EventQ.head; + while (spot != SDL_EventQ.tail) { + if (filter(userdata, &SDL_EventQ.event[spot])) { + spot = (spot + 1) % MAXEVENTS; + } else { + spot = SDL_CutEvent(spot); + } + } + } + SDL_mutexV(SDL_EventQ.lock); +} + +Uint8 +SDL_EventState(Uint8 type, int state) +{ + SDL_Event bitbucket; + Uint8 current_state; + + /* If SDL_ALLEVENTS was specified... */ + if (type == 0xFF) { + current_state = SDL_IGNORE; + for (type = 0; type < SDL_NUMEVENTS; ++type) { + if (SDL_ProcessEvents[type] != SDL_IGNORE) { + current_state = SDL_ENABLE; + } + SDL_ProcessEvents[type] = state; + if (state == SDL_ENABLE) { + SDL_eventstate |= (0x00000001 << (type)); + } else { + SDL_eventstate &= ~(0x00000001 << (type)); + } + } + while (SDL_PollEvent(&bitbucket) > 0); + return (current_state); + } + + /* Just set the state for one event type */ + current_state = SDL_ProcessEvents[type]; + switch (state) { + case SDL_IGNORE: + case SDL_ENABLE: + /* Set state and discard pending events */ + SDL_ProcessEvents[type] = state; + if (state == SDL_ENABLE) { + SDL_eventstate |= (0x00000001 << (type)); + } else { + SDL_eventstate &= ~(0x00000001 << (type)); + } + while (SDL_PollEvent(&bitbucket) > 0); + break; + default: + /* Querying state? */ + break; + } + return (current_state); } /* This is a generic event handler. */ -int SDL_PrivateSysWMEvent(SDL_SysWMmsg *message) +int +SDL_SendSysWMEvent(SDL_SysWMmsg * message) { - int posted; - - posted = 0; - if ( SDL_ProcessEvents[SDL_SYSWMEVENT] == SDL_ENABLE ) { - SDL_Event event; - SDL_memset(&event, 0, sizeof(event)); - event.type = SDL_SYSWMEVENT; - event.syswm.msg = message; - if ( (SDL_EventOK == NULL) || (*SDL_EventOK)(&event) ) { - posted = 1; - SDL_PushEvent(&event); - } - } - /* Update internal event state */ - return(posted); + int posted; + + posted = 0; + if (SDL_ProcessEvents[SDL_SYSWMEVENT] == SDL_ENABLE) { + SDL_Event event; + SDL_memset(&event, 0, sizeof(event)); + event.type = SDL_SYSWMEVENT; + event.syswm.msg = message; + posted = (SDL_PushEvent(&event) > 0); + } + /* Update internal event state */ + return (posted); } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/events/SDL_events_c.h b/src/events/SDL_events_c.h index 6b5a38c01..9dc6c0976 100644 --- a/src/events/SDL_events_c.h +++ b/src/events/SDL_events_c.h @@ -23,6 +23,9 @@ /* Useful functions and variables from SDL_events.c */ #include "SDL_events.h" +#include "SDL_mouse_c.h" +#include "SDL_keyboard_c.h" +#include "SDL_windowevents_c.h" /* Start and stop the event processing loop */ extern int SDL_StartEventLoop(Uint32 flags); @@ -33,48 +36,17 @@ extern void SDL_Lock_EventThread(void); extern void SDL_Unlock_EventThread(void); extern Uint32 SDL_EventThreadID(void); -/* Event handler init routines */ -extern int SDL_AppActiveInit(void); -extern int SDL_KeyboardInit(void); -extern int SDL_MouseInit(void); -extern int SDL_QuitInit(void); +extern int SDL_SendSysWMEvent(SDL_SysWMmsg * message); -/* Event handler quit routines */ -extern void SDL_AppActiveQuit(void); -extern void SDL_KeyboardQuit(void); -extern void SDL_MouseQuit(void); +extern int SDL_QuitInit(void); +extern int SDL_SendQuit(void); extern void SDL_QuitQuit(void); /* The event filter function */ extern SDL_EventFilter SDL_EventOK; +extern void *SDL_EventOKParam; /* The array of event processing states */ extern Uint8 SDL_ProcessEvents[SDL_NUMEVENTS]; -/* Internal event queueing functions - (from SDL_active.c, SDL_mouse.c, SDL_keyboard.c, SDL_quit.c, SDL_events.c) - */ -extern int SDL_PrivateAppActive(Uint8 gain, Uint8 state); -extern int SDL_PrivateMouseMotion(Uint8 buttonstate, int relative, - Sint16 x, Sint16 y); -extern int SDL_PrivateMouseButton(Uint8 state, Uint8 button,Sint16 x,Sint16 y); -extern int SDL_PrivateKeyboard(Uint8 state, SDL_keysym *key); -extern int SDL_PrivateResize(int w, int h); -extern int SDL_PrivateExpose(void); -extern int SDL_PrivateQuit(void); -extern int SDL_PrivateSysWMEvent(SDL_SysWMmsg *message); - -/* Used by the activity event handler to remove mouse focus */ -extern void SDL_ResetMouse(void); - -/* Used by the activity event handler to remove keyboard focus */ -extern void SDL_ResetKeyboard(void); - -/* Used by the event loop to queue pending keyboard repeat events */ -extern void SDL_CheckKeyRepeat(void); - -/* Used by the OS keyboard code to detect whether or not to do UNICODE */ -#ifndef DEFAULT_UNICODE_TRANSLATION -#define DEFAULT_UNICODE_TRANSLATION 0 /* Default off because of overhead */ -#endif -extern int SDL_TranslateUNICODE; +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/events/SDL_expose.c b/src/events/SDL_expose.c deleted file mode 100644 index d325ea112..000000000 --- a/src/events/SDL_expose.c +++ /dev/null @@ -1,51 +0,0 @@ -/* - SDL - Simple DirectMedia Layer - Copyright (C) 1997-2006 Sam Lantinga - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - - Sam Lantinga - slouken@libsdl.org -*/ -#include "SDL_config.h" - -/* Refresh event handling code for SDL */ - -#include "SDL_events.h" -#include "SDL_events_c.h" - - -/* This is global for SDL_eventloop.c */ -int SDL_PrivateExpose(void) -{ - int posted; - SDL_Event events[32]; - - /* Pull out all old refresh events */ - SDL_PeepEvents(events, sizeof(events)/sizeof(events[0]), - SDL_GETEVENT, SDL_VIDEOEXPOSEMASK); - - /* Post the event, if desired */ - posted = 0; - if ( SDL_ProcessEvents[SDL_VIDEOEXPOSE] == SDL_ENABLE ) { - SDL_Event event; - event.type = SDL_VIDEOEXPOSE; - if ( (SDL_EventOK == NULL) || (*SDL_EventOK)(&event) ) { - posted = 1; - SDL_PushEvent(&event); - } - } - return(posted); -} diff --git a/src/events/SDL_keyboard.c b/src/events/SDL_keyboard.c index 5f7af429c..aff822d78 100644 --- a/src/events/SDL_keyboard.c +++ b/src/events/SDL_keyboard.c @@ -29,550 +29,749 @@ #include "SDL_sysevents.h" -/* Global keystate information */ -static Uint8 SDL_KeyState[SDLK_LAST]; -static SDLMod SDL_ModState; +/* Global keyboard information */ int SDL_TranslateUNICODE = 0; +static int SDL_num_keyboards; +static int SDL_current_keyboard; +static SDL_Keyboard **SDL_keyboards; -static const char *keynames[SDLK_LAST]; /* Array of keycode names */ +static const char *SDL_keynames[SDLK_LAST]; /* Array of keycode names */ -/* - * jk 991215 - added - */ -struct { - int firsttime; /* if we check against the delay or repeat value */ - int delay; /* the delay before we start repeating */ - int interval; /* the delay between key repeat events */ - Uint32 timestamp; /* the time the first keydown event occurred */ +/* Public functions */ +int +SDL_KeyboardInit(void) +{ + int i; + + /* Set default mode of UNICODE translation */ + SDL_EnableUNICODE(DEFAULT_UNICODE_TRANSLATION); + + /* Initialize the tables */ + for (i = 0; i < SDL_arraysize(SDL_keynames); ++i) { + switch (i) { + case SDLK_BACKSPACE: + SDL_keynames[i] = "backspace"; + break; + case SDLK_TAB: + SDL_keynames[i] = "tab"; + break; + case SDLK_CLEAR: + SDL_keynames[i] = "clear"; + break; + case SDLK_RETURN: + SDL_keynames[i] = "return"; + break; + case SDLK_PAUSE: + SDL_keynames[i] = "pause"; + break; + case SDLK_ESCAPE: + SDL_keynames[i] = "escape"; + break; + case SDLK_SPACE: + SDL_keynames[i] = "space"; + break; + + case SDLK_KP0: + SDL_keynames[i] = "[0]"; + break; + case SDLK_KP1: + SDL_keynames[i] = "[1]"; + break; + case SDLK_KP2: + SDL_keynames[i] = "[2]"; + break; + case SDLK_KP3: + SDL_keynames[i] = "[3]"; + break; + case SDLK_KP4: + SDL_keynames[i] = "[4]"; + break; + case SDLK_KP5: + SDL_keynames[i] = "[5]"; + break; + case SDLK_KP6: + SDL_keynames[i] = "[6]"; + break; + case SDLK_KP7: + SDL_keynames[i] = "[7]"; + break; + case SDLK_KP8: + SDL_keynames[i] = "[8]"; + break; + case SDLK_KP9: + SDL_keynames[i] = "[9]"; + break; + case SDLK_KP_PERIOD: + SDL_keynames[i] = "[.]"; + break; + case SDLK_KP_DIVIDE: + SDL_keynames[i] = "[/]"; + break; + case SDLK_KP_MULTIPLY: + SDL_keynames[i] = "[*]"; + break; + case SDLK_KP_MINUS: + SDL_keynames[i] = "[-]"; + break; + case SDLK_KP_PLUS: + SDL_keynames[i] = "[+]"; + break; + case SDLK_KP_ENTER: + SDL_keynames[i] = "enter"; + break; + case SDLK_KP_EQUALS: + SDL_keynames[i] = "equals"; + break; + + case SDLK_UP: + SDL_keynames[i] = "up"; + break; + case SDLK_DOWN: + SDL_keynames[i] = "down"; + break; + case SDLK_RIGHT: + SDL_keynames[i] = "right"; + break; + case SDLK_LEFT: + SDL_keynames[i] = "left"; + break; + case SDLK_INSERT: + SDL_keynames[i] = "insert"; + break; + case SDLK_HOME: + SDL_keynames[i] = "home"; + break; + case SDLK_END: + SDL_keynames[i] = "end"; + break; + case SDLK_PAGEUP: + SDL_keynames[i] = "page up"; + break; + case SDLK_PAGEDOWN: + SDL_keynames[i] = "page down"; + break; + + case SDLK_F1: + SDL_keynames[i] = "f1"; + break; + case SDLK_F2: + SDL_keynames[i] = "f2"; + break; + case SDLK_F3: + SDL_keynames[i] = "f3"; + break; + case SDLK_F4: + SDL_keynames[i] = "f4"; + break; + case SDLK_F5: + SDL_keynames[i] = "f5"; + break; + case SDLK_F6: + SDL_keynames[i] = "f6"; + break; + case SDLK_F7: + SDL_keynames[i] = "f7"; + break; + case SDLK_F8: + SDL_keynames[i] = "f8"; + break; + case SDLK_F9: + SDL_keynames[i] = "f9"; + break; + case SDLK_F10: + SDL_keynames[i] = "f10"; + break; + case SDLK_F11: + SDL_keynames[i] = "f11"; + break; + case SDLK_F12: + SDL_keynames[i] = "f12"; + break; + case SDLK_F13: + SDL_keynames[i] = "f13"; + break; + case SDLK_F14: + SDL_keynames[i] = "f14"; + break; + case SDLK_F15: + SDL_keynames[i] = "f15"; + break; + + case SDLK_NUMLOCK: + SDL_keynames[i] = "numlock"; + break; + case SDLK_CAPSLOCK: + SDL_keynames[i] = "caps lock"; + break; + case SDLK_SCROLLOCK: + SDL_keynames[i] = "scroll lock"; + break; + case SDLK_RSHIFT: + SDL_keynames[i] = "right shift"; + break; + case SDLK_LSHIFT: + SDL_keynames[i] = "left shift"; + break; + case SDLK_RCTRL: + SDL_keynames[i] = "right ctrl"; + break; + case SDLK_LCTRL: + SDL_keynames[i] = "left ctrl"; + break; + case SDLK_RALT: + SDL_keynames[i] = "right alt"; + break; + case SDLK_LALT: + SDL_keynames[i] = "left alt"; + break; + case SDLK_RMETA: + SDL_keynames[i] = "right meta"; + break; + case SDLK_LMETA: + SDL_keynames[i] = "left meta"; + break; + case SDLK_LSUPER: + SDL_keynames[i] = "left super"; /* "Windows" keys */ + break; + case SDLK_RSUPER: + SDL_keynames[i] = "right super"; + break; + case SDLK_MODE: + SDL_keynames[i] = "alt gr"; + break; + case SDLK_COMPOSE: + SDL_keynames[i] = "compose"; + break; + + case SDLK_HELP: + SDL_keynames[i] = "help"; + break; + case SDLK_PRINT: + SDL_keynames[i] = "print screen"; + break; + case SDLK_SYSREQ: + SDL_keynames[i] = "sys req"; + break; + case SDLK_BREAK: + SDL_keynames[i] = "break"; + break; + case SDLK_MENU: + SDL_keynames[i] = "menu"; + break; + case SDLK_POWER: + SDL_keynames[i] = "power"; + break; + case SDLK_EURO: + SDL_keynames[i] = "euro"; + break; + case SDLK_UNDO: + SDL_keynames[i] = "undo"; + break; + + default: + SDL_keynames[i] = NULL; + break; + } + } + + /* Done. Whew. */ + return (0); +} - SDL_Event evt; /* the event we are supposed to repeat */ -} SDL_KeyRepeat; +SDL_Keyboard * +SDL_GetKeyboard(int index) +{ + if (index < 0 || index >= SDL_num_keyboards) { + return NULL; + } + return SDL_keyboards[index]; +} -/* Public functions */ -int SDL_KeyboardInit(void) +int +SDL_AddKeyboard(const SDL_Keyboard * keyboard, int index) { - SDL_VideoDevice *video = current_video; - SDL_VideoDevice *this = current_video; - - /* Set default mode of UNICODE translation */ - SDL_EnableUNICODE(DEFAULT_UNICODE_TRANSLATION); - - /* Initialize the tables */ - SDL_ModState = KMOD_NONE; - SDL_memset((void*)keynames, 0, sizeof(keynames)); - SDL_memset(SDL_KeyState, 0, sizeof(SDL_KeyState)); - video->InitOSKeymap(this); - - SDL_EnableKeyRepeat(0, 0); - - /* Fill in the blanks in keynames */ - keynames[SDLK_BACKSPACE] = "backspace"; - keynames[SDLK_TAB] = "tab"; - keynames[SDLK_CLEAR] = "clear"; - keynames[SDLK_RETURN] = "return"; - keynames[SDLK_PAUSE] = "pause"; - keynames[SDLK_ESCAPE] = "escape"; - keynames[SDLK_SPACE] = "space"; - keynames[SDLK_EXCLAIM] = "!"; - keynames[SDLK_QUOTEDBL] = "\""; - keynames[SDLK_HASH] = "#"; - keynames[SDLK_DOLLAR] = "$"; - keynames[SDLK_AMPERSAND] = "&"; - keynames[SDLK_QUOTE] = "'"; - keynames[SDLK_LEFTPAREN] = "("; - keynames[SDLK_RIGHTPAREN] = ")"; - keynames[SDLK_ASTERISK] = "*"; - keynames[SDLK_PLUS] = "+"; - keynames[SDLK_COMMA] = ","; - keynames[SDLK_MINUS] = "-"; - keynames[SDLK_PERIOD] = "."; - keynames[SDLK_SLASH] = "/"; - keynames[SDLK_0] = "0"; - keynames[SDLK_1] = "1"; - keynames[SDLK_2] = "2"; - keynames[SDLK_3] = "3"; - keynames[SDLK_4] = "4"; - keynames[SDLK_5] = "5"; - keynames[SDLK_6] = "6"; - keynames[SDLK_7] = "7"; - keynames[SDLK_8] = "8"; - keynames[SDLK_9] = "9"; - keynames[SDLK_COLON] = ":"; - keynames[SDLK_SEMICOLON] = ";"; - keynames[SDLK_LESS] = "<"; - keynames[SDLK_EQUALS] = "="; - keynames[SDLK_GREATER] = ">"; - keynames[SDLK_QUESTION] = "?"; - keynames[SDLK_AT] = "@"; - keynames[SDLK_LEFTBRACKET] = "["; - keynames[SDLK_BACKSLASH] = "\\"; - keynames[SDLK_RIGHTBRACKET] = "]"; - keynames[SDLK_CARET] = "^"; - keynames[SDLK_UNDERSCORE] = "_"; - keynames[SDLK_BACKQUOTE] = "`"; - keynames[SDLK_a] = "a"; - keynames[SDLK_b] = "b"; - keynames[SDLK_c] = "c"; - keynames[SDLK_d] = "d"; - keynames[SDLK_e] = "e"; - keynames[SDLK_f] = "f"; - keynames[SDLK_g] = "g"; - keynames[SDLK_h] = "h"; - keynames[SDLK_i] = "i"; - keynames[SDLK_j] = "j"; - keynames[SDLK_k] = "k"; - keynames[SDLK_l] = "l"; - keynames[SDLK_m] = "m"; - keynames[SDLK_n] = "n"; - keynames[SDLK_o] = "o"; - keynames[SDLK_p] = "p"; - keynames[SDLK_q] = "q"; - keynames[SDLK_r] = "r"; - keynames[SDLK_s] = "s"; - keynames[SDLK_t] = "t"; - keynames[SDLK_u] = "u"; - keynames[SDLK_v] = "v"; - keynames[SDLK_w] = "w"; - keynames[SDLK_x] = "x"; - keynames[SDLK_y] = "y"; - keynames[SDLK_z] = "z"; - keynames[SDLK_DELETE] = "delete"; - - keynames[SDLK_WORLD_0] = "world 0"; - keynames[SDLK_WORLD_1] = "world 1"; - keynames[SDLK_WORLD_2] = "world 2"; - keynames[SDLK_WORLD_3] = "world 3"; - keynames[SDLK_WORLD_4] = "world 4"; - keynames[SDLK_WORLD_5] = "world 5"; - keynames[SDLK_WORLD_6] = "world 6"; - keynames[SDLK_WORLD_7] = "world 7"; - keynames[SDLK_WORLD_8] = "world 8"; - keynames[SDLK_WORLD_9] = "world 9"; - keynames[SDLK_WORLD_10] = "world 10"; - keynames[SDLK_WORLD_11] = "world 11"; - keynames[SDLK_WORLD_12] = "world 12"; - keynames[SDLK_WORLD_13] = "world 13"; - keynames[SDLK_WORLD_14] = "world 14"; - keynames[SDLK_WORLD_15] = "world 15"; - keynames[SDLK_WORLD_16] = "world 16"; - keynames[SDLK_WORLD_17] = "world 17"; - keynames[SDLK_WORLD_18] = "world 18"; - keynames[SDLK_WORLD_19] = "world 19"; - keynames[SDLK_WORLD_20] = "world 20"; - keynames[SDLK_WORLD_21] = "world 21"; - keynames[SDLK_WORLD_22] = "world 22"; - keynames[SDLK_WORLD_23] = "world 23"; - keynames[SDLK_WORLD_24] = "world 24"; - keynames[SDLK_WORLD_25] = "world 25"; - keynames[SDLK_WORLD_26] = "world 26"; - keynames[SDLK_WORLD_27] = "world 27"; - keynames[SDLK_WORLD_28] = "world 28"; - keynames[SDLK_WORLD_29] = "world 29"; - keynames[SDLK_WORLD_30] = "world 30"; - keynames[SDLK_WORLD_31] = "world 31"; - keynames[SDLK_WORLD_32] = "world 32"; - keynames[SDLK_WORLD_33] = "world 33"; - keynames[SDLK_WORLD_34] = "world 34"; - keynames[SDLK_WORLD_35] = "world 35"; - keynames[SDLK_WORLD_36] = "world 36"; - keynames[SDLK_WORLD_37] = "world 37"; - keynames[SDLK_WORLD_38] = "world 38"; - keynames[SDLK_WORLD_39] = "world 39"; - keynames[SDLK_WORLD_40] = "world 40"; - keynames[SDLK_WORLD_41] = "world 41"; - keynames[SDLK_WORLD_42] = "world 42"; - keynames[SDLK_WORLD_43] = "world 43"; - keynames[SDLK_WORLD_44] = "world 44"; - keynames[SDLK_WORLD_45] = "world 45"; - keynames[SDLK_WORLD_46] = "world 46"; - keynames[SDLK_WORLD_47] = "world 47"; - keynames[SDLK_WORLD_48] = "world 48"; - keynames[SDLK_WORLD_49] = "world 49"; - keynames[SDLK_WORLD_50] = "world 50"; - keynames[SDLK_WORLD_51] = "world 51"; - keynames[SDLK_WORLD_52] = "world 52"; - keynames[SDLK_WORLD_53] = "world 53"; - keynames[SDLK_WORLD_54] = "world 54"; - keynames[SDLK_WORLD_55] = "world 55"; - keynames[SDLK_WORLD_56] = "world 56"; - keynames[SDLK_WORLD_57] = "world 57"; - keynames[SDLK_WORLD_58] = "world 58"; - keynames[SDLK_WORLD_59] = "world 59"; - keynames[SDLK_WORLD_60] = "world 60"; - keynames[SDLK_WORLD_61] = "world 61"; - keynames[SDLK_WORLD_62] = "world 62"; - keynames[SDLK_WORLD_63] = "world 63"; - keynames[SDLK_WORLD_64] = "world 64"; - keynames[SDLK_WORLD_65] = "world 65"; - keynames[SDLK_WORLD_66] = "world 66"; - keynames[SDLK_WORLD_67] = "world 67"; - keynames[SDLK_WORLD_68] = "world 68"; - keynames[SDLK_WORLD_69] = "world 69"; - keynames[SDLK_WORLD_70] = "world 70"; - keynames[SDLK_WORLD_71] = "world 71"; - keynames[SDLK_WORLD_72] = "world 72"; - keynames[SDLK_WORLD_73] = "world 73"; - keynames[SDLK_WORLD_74] = "world 74"; - keynames[SDLK_WORLD_75] = "world 75"; - keynames[SDLK_WORLD_76] = "world 76"; - keynames[SDLK_WORLD_77] = "world 77"; - keynames[SDLK_WORLD_78] = "world 78"; - keynames[SDLK_WORLD_79] = "world 79"; - keynames[SDLK_WORLD_80] = "world 80"; - keynames[SDLK_WORLD_81] = "world 81"; - keynames[SDLK_WORLD_82] = "world 82"; - keynames[SDLK_WORLD_83] = "world 83"; - keynames[SDLK_WORLD_84] = "world 84"; - keynames[SDLK_WORLD_85] = "world 85"; - keynames[SDLK_WORLD_86] = "world 86"; - keynames[SDLK_WORLD_87] = "world 87"; - keynames[SDLK_WORLD_88] = "world 88"; - keynames[SDLK_WORLD_89] = "world 89"; - keynames[SDLK_WORLD_90] = "world 90"; - keynames[SDLK_WORLD_91] = "world 91"; - keynames[SDLK_WORLD_92] = "world 92"; - keynames[SDLK_WORLD_93] = "world 93"; - keynames[SDLK_WORLD_94] = "world 94"; - keynames[SDLK_WORLD_95] = "world 95"; - - keynames[SDLK_KP0] = "[0]"; - keynames[SDLK_KP1] = "[1]"; - keynames[SDLK_KP2] = "[2]"; - keynames[SDLK_KP3] = "[3]"; - keynames[SDLK_KP4] = "[4]"; - keynames[SDLK_KP5] = "[5]"; - keynames[SDLK_KP6] = "[6]"; - keynames[SDLK_KP7] = "[7]"; - keynames[SDLK_KP8] = "[8]"; - keynames[SDLK_KP9] = "[9]"; - keynames[SDLK_KP_PERIOD] = "[.]"; - keynames[SDLK_KP_DIVIDE] = "[/]"; - keynames[SDLK_KP_MULTIPLY] = "[*]"; - keynames[SDLK_KP_MINUS] = "[-]"; - keynames[SDLK_KP_PLUS] = "[+]"; - keynames[SDLK_KP_ENTER] = "enter"; - keynames[SDLK_KP_EQUALS] = "equals"; - - keynames[SDLK_UP] = "up"; - keynames[SDLK_DOWN] = "down"; - keynames[SDLK_RIGHT] = "right"; - keynames[SDLK_LEFT] = "left"; - keynames[SDLK_DOWN] = "down"; - keynames[SDLK_INSERT] = "insert"; - keynames[SDLK_HOME] = "home"; - keynames[SDLK_END] = "end"; - keynames[SDLK_PAGEUP] = "page up"; - keynames[SDLK_PAGEDOWN] = "page down"; - - keynames[SDLK_F1] = "f1"; - keynames[SDLK_F2] = "f2"; - keynames[SDLK_F3] = "f3"; - keynames[SDLK_F4] = "f4"; - keynames[SDLK_F5] = "f5"; - keynames[SDLK_F6] = "f6"; - keynames[SDLK_F7] = "f7"; - keynames[SDLK_F8] = "f8"; - keynames[SDLK_F9] = "f9"; - keynames[SDLK_F10] = "f10"; - keynames[SDLK_F11] = "f11"; - keynames[SDLK_F12] = "f12"; - keynames[SDLK_F13] = "f13"; - keynames[SDLK_F14] = "f14"; - keynames[SDLK_F15] = "f15"; - - keynames[SDLK_NUMLOCK] = "numlock"; - keynames[SDLK_CAPSLOCK] = "caps lock"; - keynames[SDLK_SCROLLOCK] = "scroll lock"; - keynames[SDLK_RSHIFT] = "right shift"; - keynames[SDLK_LSHIFT] = "left shift"; - keynames[SDLK_RCTRL] = "right ctrl"; - keynames[SDLK_LCTRL] = "left ctrl"; - keynames[SDLK_RALT] = "right alt"; - keynames[SDLK_LALT] = "left alt"; - keynames[SDLK_RMETA] = "right meta"; - keynames[SDLK_LMETA] = "left meta"; - keynames[SDLK_LSUPER] = "left super"; /* "Windows" keys */ - keynames[SDLK_RSUPER] = "right super"; - keynames[SDLK_MODE] = "alt gr"; - keynames[SDLK_COMPOSE] = "compose"; - - keynames[SDLK_HELP] = "help"; - keynames[SDLK_PRINT] = "print screen"; - keynames[SDLK_SYSREQ] = "sys req"; - keynames[SDLK_BREAK] = "break"; - keynames[SDLK_MENU] = "menu"; - keynames[SDLK_POWER] = "power"; - keynames[SDLK_EURO] = "euro"; - keynames[SDLK_UNDO] = "undo"; - - /* Done. Whew. */ - return(0); + SDL_Keyboard **keyboards; + + /* Add the keyboard to the list of keyboards */ + if (index < 0 || index >= SDL_num_keyboards || SDL_keyboards[index]) { + keyboards = + (SDL_Keyboard **) SDL_realloc(SDL_keyboards, + (SDL_num_keyboards + + 1) * sizeof(*keyboards)); + if (!keyboards) { + SDL_OutOfMemory(); + return -1; + } + + SDL_keyboards = keyboards; + index = SDL_num_keyboards++; + } + SDL_keyboards[index] = + (SDL_Keyboard *) SDL_malloc(sizeof(*SDL_keyboards[index])); + if (!SDL_keyboards[index]) { + SDL_OutOfMemory(); + return -1; + } + *SDL_keyboards[index] = *keyboard; + + return index; } -void SDL_KeyboardQuit(void) + +void +SDL_DelKeyboard(int index) { + SDL_Keyboard *keyboard = SDL_GetKeyboard(index); + + if (!keyboard) { + return; + } + + if (keyboard->FreeKeyboard) { + keyboard->FreeKeyboard(keyboard); + } + SDL_free(keyboard); + + SDL_keyboards[index] = NULL; } -/* We lost the keyboard, so post key up messages for all pressed keys */ -void SDL_ResetKeyboard(void) +void +SDL_ResetKeyboard(int index) { - SDL_keysym keysym; - SDLKey key; - - SDL_memset(&keysym, 0, (sizeof keysym)); - for ( key=SDLK_FIRST; keykeystate[key] == SDL_PRESSED) { + SDL_SendKeyboardKey(index, SDL_RELEASED, 0, key); + } + } + keyboard->repeat.timestamp = 0; } -int SDL_EnableUNICODE(int enable) +void +SDL_KeyboardQuit(void) { - int old_mode; + int i; + + for (i = 0; i < SDL_num_keyboards; ++i) { + SDL_DelKeyboard(i); + } + SDL_num_keyboards = 0; + SDL_current_keyboard = 0; + + if (SDL_keyboards) { + SDL_free(SDL_keyboards); + SDL_keyboards = NULL; + } +} - old_mode = SDL_TranslateUNICODE; - if ( enable >= 0 ) { - SDL_TranslateUNICODE = enable; - } - return(old_mode); +int +SDL_GetNumKeyboards(void) +{ + return SDL_num_keyboards; } -Uint8 * SDL_GetKeyState (int *numkeys) +int +SDL_SelectKeyboard(int index) { - if ( numkeys != (int *)0 ) - *numkeys = SDLK_LAST; - return(SDL_KeyState); + if (index >= 0 && index < SDL_num_keyboards) { + SDL_current_keyboard = index; + } + return SDL_current_keyboard; } -SDLMod SDL_GetModState (void) + +int +SDL_EnableUNICODE(int enable) { - return(SDL_ModState); + int old_mode; + + old_mode = SDL_TranslateUNICODE; + if (enable >= 0) { + SDL_TranslateUNICODE = enable; + } + return (old_mode); } -void SDL_SetModState (SDLMod modstate) + +Uint8 * +SDL_GetKeyState(int *numkeys) { - SDL_ModState = modstate; + SDL_Keyboard *keyboard = SDL_GetKeyboard(SDL_current_keyboard); + + if (numkeys != (int *) 0) { + *numkeys = SDLK_LAST; + } + + if (!keyboard) { + return NULL; + } + return keyboard->keystate; } -char *SDL_GetKeyName(SDLKey key) +SDLMod +SDL_GetModState(void) { - const char *keyname; - - keyname = NULL; - if ( key < SDLK_LAST ) { - keyname = keynames[key]; - } - if ( keyname == NULL ) { - keyname = "unknown key"; - } - /* FIXME: make this function const in 1.3 */ - return (char *)(keyname); + SDL_Keyboard *keyboard = SDL_GetKeyboard(SDL_current_keyboard); + + if (!keyboard) { + return KMOD_NONE; + } + return keyboard->modstate; } -/* These are global for SDL_eventloop.c */ -int SDL_PrivateKeyboard(Uint8 state, SDL_keysym *keysym) +void +SDL_SetModState(SDLMod modstate) { - SDL_Event event; - int posted, repeatable; - Uint16 modstate; + SDL_Keyboard *keyboard = SDL_GetKeyboard(SDL_current_keyboard); - SDL_memset(&event, 0, sizeof(event)); + if (!keyboard) { + return; + } + keyboard->modstate = modstate; +} + +const char * +SDL_GetKeyName(SDLKey key) +{ + const char *keyname; + + if (key < SDL_arraysize(SDL_keynames)) { + keyname = SDL_keynames[key]; + } else { + keyname = NULL; + } + if (keyname == NULL) { + if (key < 256) { + static char temp[4]; + char *cvt; + temp[0] = (char) key; + temp[1] = '\0'; + cvt = SDL_iconv_string("UTF-8", "LATIN1", temp, 1); + SDL_strlcpy(temp, cvt, SDL_arraysize(temp)); + SDL_free(cvt); + keyname = temp; + } else { + keyname = "unknown key"; + } + } + return keyname; +} + +void +SDL_SetKeyboardFocus(int index, SDL_WindowID windowID) +{ + SDL_Keyboard *keyboard = SDL_GetKeyboard(index); + int i; + SDL_bool focus; + + if (!keyboard || (keyboard->focus == windowID)) { + return; + } + + /* See if the current window has lost focus */ + if (keyboard->focus) { + focus = SDL_FALSE; + for (i = 0; i < SDL_num_keyboards; ++i) { + SDL_Keyboard *check; + if (i != index) { + check = SDL_GetKeyboard(i); + if (check && check->focus == keyboard->focus) { + focus = SDL_TRUE; + break; + } + } + } + if (!focus) { + SDL_SendWindowEvent(keyboard->focus, SDL_WINDOWEVENT_FOCUS_LOST, + 0, 0); + } + } + + keyboard->focus = windowID; + + if (keyboard->focus) { + focus = SDL_FALSE; + for (i = 0; i < SDL_num_keyboards; ++i) { + SDL_Keyboard *check; + if (i != index) { + check = SDL_GetKeyboard(i); + if (check && check->focus == keyboard->focus) { + focus = SDL_TRUE; + break; + } + } + } + if (!focus) { + SDL_SendWindowEvent(keyboard->focus, SDL_WINDOWEVENT_FOCUS_GAINED, + 0, 0); + } + } +} +int +SDL_SendKeyboardKey(int index, Uint8 state, Uint8 scancode, SDLKey key) +{ + SDL_Keyboard *keyboard = SDL_GetKeyboard(index); + int posted, repeatable; + Uint16 modstate; + Uint8 type; + + if (!keyboard) { + return 0; + } #if 0 -printf("The '%s' key has been %s\n", SDL_GetKeyName(keysym->sym), - state == SDL_PRESSED ? "pressed" : "released"); + printf("The '%s' key has been %s\n", SDL_GetKeyName(key), + state == SDL_PRESSED ? "pressed" : "released"); #endif - /* Set up the keysym */ - modstate = (Uint16)SDL_ModState; - - repeatable = 0; - - if ( state == SDL_PRESSED ) { - keysym->mod = (SDLMod)modstate; - switch (keysym->sym) { - case SDLK_UNKNOWN: - break; - case SDLK_NUMLOCK: - modstate ^= KMOD_NUM; - if ( ! (modstate&KMOD_NUM) ) - state = SDL_RELEASED; - keysym->mod = (SDLMod)modstate; - break; - case SDLK_CAPSLOCK: - modstate ^= KMOD_CAPS; - if ( ! (modstate&KMOD_CAPS) ) - state = SDL_RELEASED; - keysym->mod = (SDLMod)modstate; - break; - case SDLK_LCTRL: - modstate |= KMOD_LCTRL; - break; - case SDLK_RCTRL: - modstate |= KMOD_RCTRL; - break; - case SDLK_LSHIFT: - modstate |= KMOD_LSHIFT; - break; - case SDLK_RSHIFT: - modstate |= KMOD_RSHIFT; - break; - case SDLK_LALT: - modstate |= KMOD_LALT; - break; - case SDLK_RALT: - modstate |= KMOD_RALT; - break; - case SDLK_LMETA: - modstate |= KMOD_LMETA; - break; - case SDLK_RMETA: - modstate |= KMOD_RMETA; - break; - case SDLK_MODE: - modstate |= KMOD_MODE; - break; - default: - repeatable = 1; - break; - } - } else { - switch (keysym->sym) { - case SDLK_UNKNOWN: - break; - case SDLK_NUMLOCK: - case SDLK_CAPSLOCK: - /* Only send keydown events */ - return(0); - case SDLK_LCTRL: - modstate &= ~KMOD_LCTRL; - break; - case SDLK_RCTRL: - modstate &= ~KMOD_RCTRL; - break; - case SDLK_LSHIFT: - modstate &= ~KMOD_LSHIFT; - break; - case SDLK_RSHIFT: - modstate &= ~KMOD_RSHIFT; - break; - case SDLK_LALT: - modstate &= ~KMOD_LALT; - break; - case SDLK_RALT: - modstate &= ~KMOD_RALT; - break; - case SDLK_LMETA: - modstate &= ~KMOD_LMETA; - break; - case SDLK_RMETA: - modstate &= ~KMOD_RMETA; - break; - case SDLK_MODE: - modstate &= ~KMOD_MODE; - break; - default: - break; - } - keysym->mod = (SDLMod)modstate; - } - - /* Figure out what type of event this is */ - switch (state) { - case SDL_PRESSED: - event.type = SDL_KEYDOWN; - break; - case SDL_RELEASED: - event.type = SDL_KEYUP; - /* - * jk 991215 - Added - */ - if ( SDL_KeyRepeat.timestamp && - SDL_KeyRepeat.evt.key.keysym.sym == keysym->sym ) { - SDL_KeyRepeat.timestamp = 0; - } - break; - default: - /* Invalid state -- bail */ - return(0); - } - - if ( keysym->sym != SDLK_UNKNOWN ) { - /* Drop events that don't change state */ - if ( SDL_KeyState[keysym->sym] == state ) { + repeatable = 0; + if (state == SDL_PRESSED) { + modstate = keyboard->modstate; + switch (key) { + case SDLK_UNKNOWN: + break; + case SDLK_NUMLOCK: + keyboard->modstate ^= KMOD_NUM; + break; + case SDLK_CAPSLOCK: + keyboard->modstate ^= KMOD_CAPS; + break; + case SDLK_LCTRL: + keyboard->modstate |= KMOD_LCTRL; + break; + case SDLK_RCTRL: + keyboard->modstate |= KMOD_RCTRL; + break; + case SDLK_LSHIFT: + keyboard->modstate |= KMOD_LSHIFT; + break; + case SDLK_RSHIFT: + keyboard->modstate |= KMOD_RSHIFT; + break; + case SDLK_LALT: + keyboard->modstate |= KMOD_LALT; + break; + case SDLK_RALT: + keyboard->modstate |= KMOD_RALT; + break; + case SDLK_LMETA: + keyboard->modstate |= KMOD_LMETA; + break; + case SDLK_RMETA: + keyboard->modstate |= KMOD_RMETA; + break; + case SDLK_MODE: + keyboard->modstate |= KMOD_MODE; + break; + default: + repeatable = 1; + break; + } + } else { + switch (key) { + case SDLK_UNKNOWN: + break; + case SDLK_NUMLOCK: + case SDLK_CAPSLOCK: + break; + case SDLK_LCTRL: + keyboard->modstate &= ~KMOD_LCTRL; + break; + case SDLK_RCTRL: + keyboard->modstate &= ~KMOD_RCTRL; + break; + case SDLK_LSHIFT: + keyboard->modstate &= ~KMOD_LSHIFT; + break; + case SDLK_RSHIFT: + keyboard->modstate &= ~KMOD_RSHIFT; + break; + case SDLK_LALT: + keyboard->modstate &= ~KMOD_LALT; + break; + case SDLK_RALT: + keyboard->modstate &= ~KMOD_RALT; + break; + case SDLK_LMETA: + keyboard->modstate &= ~KMOD_LMETA; + break; + case SDLK_RMETA: + keyboard->modstate &= ~KMOD_RMETA; + break; + case SDLK_MODE: + keyboard->modstate &= ~KMOD_MODE; + break; + default: + break; + } + modstate = keyboard->modstate; + } + + /* Figure out what type of event this is */ + switch (state) { + case SDL_PRESSED: + type = SDL_KEYDOWN; + break; + case SDL_RELEASED: + type = SDL_KEYUP; + /* + * jk 991215 - Added + */ + if (keyboard->repeat.timestamp && + keyboard->repeat.evt.key.keysym.sym == key) { + keyboard->repeat.timestamp = 0; + } + break; + default: + /* Invalid state -- bail */ + return 0; + } + + if (key != SDLK_UNKNOWN) { + /* Drop events that don't change state */ + if (keyboard->keystate[key] == state) { #if 0 -printf("Keyboard event didn't change state - dropped!\n"); + printf("Keyboard event didn't change state - dropped!\n"); #endif - return(0); - } - - /* Update internal keyboard state */ - SDL_ModState = (SDLMod)modstate; - SDL_KeyState[keysym->sym] = state; - } - - /* Post the event, if desired */ - posted = 0; - if ( SDL_ProcessEvents[event.type] == SDL_ENABLE ) { - event.key.state = state; - event.key.keysym = *keysym; - /* - * jk 991215 - Added - */ - if (repeatable && (SDL_KeyRepeat.delay != 0)) { - SDL_KeyRepeat.evt = event; - SDL_KeyRepeat.firsttime = 1; - SDL_KeyRepeat.timestamp=SDL_GetTicks(); - } - if ( (SDL_EventOK == NULL) || SDL_EventOK(&event) ) { - posted = 1; - SDL_PushEvent(&event); - } - } - return(posted); + return 0; + } + + /* Update internal keyboard state */ + keyboard->keystate[key] = state; + } + + /* Post the event, if desired */ + posted = 0; + if (SDL_ProcessEvents[type] == SDL_ENABLE) { + SDL_Event event; + event.key.type = type; + event.key.which = (Uint8) index; + event.key.state = state; + event.key.keysym.scancode = scancode; + event.key.keysym.sym = (Uint16) key; + event.key.keysym.mod = modstate; + event.key.keysym.unicode = 0; + event.key.windowID = keyboard->focus; + /* + * jk 991215 - Added + */ + if (repeatable && (keyboard->repeat.delay != 0)) { + Uint32 timestamp = SDL_GetTicks(); + if (!timestamp) { + timestamp = 1; + } + keyboard->repeat.evt = event; + keyboard->repeat.firsttime = 1; + keyboard->repeat.timestamp = 1; + } + posted = (SDL_PushEvent(&event) > 0); + } + return (posted); +} + +int +SDL_SendKeyboardText(int index, const char *text) +{ + SDL_Keyboard *keyboard = SDL_GetKeyboard(index); + int posted; + + if (!keyboard) { + return 0; + } + + /* Post the event, if desired */ + posted = 0; + if (SDL_ProcessEvents[SDL_TEXTINPUT] == SDL_ENABLE) { + SDL_Event event; + event.text.type = SDL_TEXTINPUT; + event.text.which = (Uint8) index; + SDL_strlcpy(event.text.text, text, SDL_arraysize(event.text.text)); + event.key.windowID = keyboard->focus; + posted = (SDL_PushEvent(&event) > 0); + } + return (posted); } /* * jk 991215 - Added */ -void SDL_CheckKeyRepeat(void) +void +SDL_CheckKeyRepeat(void) { - if ( SDL_KeyRepeat.timestamp ) { - Uint32 now, interval; - - now = SDL_GetTicks(); - interval = (now - SDL_KeyRepeat.timestamp); - if ( SDL_KeyRepeat.firsttime ) { - if ( interval > (Uint32)SDL_KeyRepeat.delay ) { - SDL_KeyRepeat.timestamp = now; - SDL_KeyRepeat.firsttime = 0; - } - } else { - if ( interval > (Uint32)SDL_KeyRepeat.interval ) { - SDL_KeyRepeat.timestamp = now; - if ( (SDL_EventOK == NULL) || SDL_EventOK(&SDL_KeyRepeat.evt) ) { - SDL_PushEvent(&SDL_KeyRepeat.evt); - } - } - } - } + int i; + + for (i = 0; i < SDL_num_keyboards; ++i) { + SDL_Keyboard *keyboard = SDL_keyboards[i]; + + if (!keyboard) { + continue; + } + + if (keyboard->repeat.timestamp) { + Uint32 now, interval; + + now = SDL_GetTicks(); + interval = (now - keyboard->repeat.timestamp); + if (keyboard->repeat.firsttime) { + if (interval > (Uint32) keyboard->repeat.delay) { + keyboard->repeat.timestamp = now; + keyboard->repeat.firsttime = 0; + } + } else { + if (interval > (Uint32) keyboard->repeat.interval) { + keyboard->repeat.timestamp = now; + SDL_PushEvent(&keyboard->repeat.evt); + } + } + } + } } -int SDL_EnableKeyRepeat(int delay, int interval) +int +SDL_EnableKeyRepeat(int delay, int interval) { - if ( (delay < 0) || (interval < 0) ) { - SDL_SetError("keyboard repeat value less than zero"); - return(-1); - } - SDL_KeyRepeat.firsttime = 0; - SDL_KeyRepeat.delay = delay; - SDL_KeyRepeat.interval = interval; - SDL_KeyRepeat.timestamp = 0; - return(0); + SDL_Keyboard *keyboard = SDL_GetKeyboard(SDL_current_keyboard); + + if (!keyboard) { + SDL_SetError("No keyboard is currently selected"); + return -1; + } + + if ((delay < 0) || (interval < 0)) { + SDL_SetError("keyboard repeat value less than zero"); + return -1; + } + + keyboard->repeat.firsttime = 0; + keyboard->repeat.delay = delay; + keyboard->repeat.interval = interval; + keyboard->repeat.timestamp = 0; + + return 0; } -void SDL_GetKeyRepeat(int *delay, int *interval) +void +SDL_GetKeyRepeat(int *delay, int *interval) { - *delay = SDL_KeyRepeat.delay; - *interval = SDL_KeyRepeat.interval; + SDL_Keyboard *keyboard = SDL_GetKeyboard(SDL_current_keyboard); + + if (!keyboard) { + if (delay) { + *delay = 0; + } + if (interval) { + *interval = 0; + } + return; + } + if (delay) { + *delay = keyboard->repeat.delay; + } + if (interval) { + *interval = keyboard->repeat.interval; + } } +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/events/SDL_keyboard_c.h b/src/events/SDL_keyboard_c.h new file mode 100644 index 000000000..0d0b58627 --- /dev/null +++ b/src/events/SDL_keyboard_c.h @@ -0,0 +1,96 @@ +/* + SDL - Simple DirectMedia Layer + Copyright (C) 1997-2006 Sam Lantinga + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + Sam Lantinga + slouken@libsdl.org +*/ +#include "SDL_config.h" + +#ifndef _SDL_keyboard_c_h +#define _SDL_keyboard_c_h + +#include "SDL_keysym.h" +#include "SDL_events.h" + +typedef struct SDL_Keyboard SDL_Keyboard; + +struct SDL_Keyboard +{ + /* Free the keyboard when it's time */ + void (*FreeKeyboard) (SDL_Keyboard * keyboard); + + /* Data common to all keyboards */ + SDL_WindowID focus; + Uint16 modstate; + Uint8 keystate[SDLK_LAST]; + + struct + { + int firsttime; /* if we check against the delay or repeat value */ + int delay; /* the delay before we start repeating */ + int interval; /* the delay between key repeat events */ + Uint32 timestamp; /* the time the first keydown event occurred */ + + SDL_Event evt; /* the event we are supposed to repeat */ + } repeat; + + void *driverdata; +}; + +/* Used by the OS keyboard code to detect whether or not to do UNICODE */ +#ifndef DEFAULT_UNICODE_TRANSLATION +#define DEFAULT_UNICODE_TRANSLATION 0 /* Default off because of overhead */ +#endif +extern int SDL_TranslateUNICODE; + +/* Initialize the keyboard subsystem */ +extern int SDL_KeyboardInit(void); + +/* Get the keyboard at an index */ +extern SDL_Keyboard *SDL_GetKeyboard(int index); + +/* Add a keyboard, possibly reattaching at a particular index (or -1), + returning the index of the keyboard, or -1 if there was an error. + */ +extern int SDL_AddKeyboard(const SDL_Keyboard * keyboard, int index); + +/* Remove a keyboard at an index, clearing the slot for later */ +extern void SDL_DelKeyboard(int index); + +/* Clear the state of a keyboard at an index */ +extern void SDL_ResetKeyboard(int index); + +/* Set the keyboard focus window */ +extern void SDL_SetKeyboardFocus(int index, SDL_WindowID windowID); + +/* Send a keyboard event for a keyboard at an index */ +extern int SDL_SendKeyboardKey(int index, Uint8 state, Uint8 scancode, + SDLKey key); + +/* Send keyboard text input for a keyboard at an index */ +extern int SDL_SendKeyboardText(int index, const char *text); + +/* Used by the event loop to queue pending keyboard repeat events */ +extern void SDL_CheckKeyRepeat(void); + +/* Shutdown the keyboard subsystem */ +extern void SDL_KeyboardQuit(void); + +#endif /* _SDL_keyboard_c_h */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/events/SDL_mouse.c b/src/events/SDL_mouse.c index f72ef3c80..0236d204b 100644 --- a/src/events/SDL_mouse.c +++ b/src/events/SDL_mouse.c @@ -25,239 +25,627 @@ #include "SDL_events.h" #include "SDL_events_c.h" -#include "../video/SDL_cursor_c.h" -#include "../video/SDL_sysvideo.h" +#include "default_cursor.h" -/* These are static for our mouse handling code */ -static Sint16 SDL_MouseX = 0; -static Sint16 SDL_MouseY = 0; -static Sint16 SDL_DeltaX = 0; -static Sint16 SDL_DeltaY = 0; -static Uint8 SDL_ButtonState = 0; +static int SDL_num_mice; +static int SDL_current_mouse; +static SDL_Mouse **SDL_mice; /* Public functions */ -int SDL_MouseInit(void) +int +SDL_MouseInit(void) { - /* The mouse is at (0,0) */ - SDL_MouseX = 0; - SDL_MouseY = 0; - SDL_DeltaX = 0; - SDL_DeltaY = 0; - SDL_ButtonState = 0; - - /* That's it! */ - return(0); + return (0); } -void SDL_MouseQuit(void) + +SDL_Mouse * +SDL_GetMouse(int index) +{ + if (index < 0 || index >= SDL_num_mice) { + return NULL; + } + return SDL_mice[index]; +} + +int +SDL_AddMouse(const SDL_Mouse * mouse, int index) +{ + SDL_Mouse **mice; + int selected_mouse; + + /* Add the mouse to the list of mice */ + if (index < 0 || index >= SDL_num_mice || SDL_mice[index]) { + mice = + (SDL_Mouse **) SDL_realloc(SDL_mice, + (SDL_num_mice + 1) * sizeof(*mice)); + if (!mice) { + SDL_OutOfMemory(); + return -1; + } + + SDL_mice = mice; + index = SDL_num_mice++; + } + SDL_mice[index] = (SDL_Mouse *) SDL_malloc(sizeof(*SDL_mice[index])); + if (!SDL_mice[index]) { + SDL_OutOfMemory(); + return -1; + } + *SDL_mice[index] = *mouse; + + /* Create the default cursor for the mouse */ + SDL_mice[index]->cursor_shown = SDL_TRUE; + selected_mouse = SDL_SelectMouse(index); + SDL_mice[index]->cur_cursor = NULL; + SDL_mice[index]->def_cursor = + SDL_CreateCursor(default_cdata, default_cmask, DEFAULT_CWIDTH, + DEFAULT_CHEIGHT, DEFAULT_CHOTX, DEFAULT_CHOTY); + SDL_SetCursor(SDL_mice[index]->def_cursor); + SDL_SelectMouse(selected_mouse); + + return index; +} + +void +SDL_DelMouse(int index) +{ + SDL_Mouse *mouse = SDL_GetMouse(index); + + if (!mouse) { + return; + } + + mouse->def_cursor = NULL; + while (mouse->cursors) { + SDL_FreeCursor(mouse->cursors); + } + + if (mouse->FreeMouse) { + mouse->FreeMouse(mouse); + } + SDL_free(mouse); + + SDL_mice[index] = NULL; +} + +void +SDL_ResetMouse(int index) +{ + SDL_Mouse *mouse = SDL_GetMouse(index); + + if (!mouse) { + return; + } + + /* FIXME */ +} + +void +SDL_MouseQuit(void) +{ + int i; + + for (i = 0; i < SDL_num_mice; ++i) { + SDL_DelMouse(i); + } + SDL_num_mice = 0; + SDL_current_mouse = 0; + + if (SDL_mice) { + SDL_free(SDL_mice); + SDL_mice = NULL; + } +} + +int +SDL_GetNumMice(void) +{ + return SDL_num_mice; +} + +int +SDL_SelectMouse(int index) { + if (index >= 0 && index < SDL_num_mice) { + SDL_current_mouse = index; + } + return SDL_current_mouse; } -/* We lost the mouse, so post button up messages for all pressed buttons */ -void SDL_ResetMouse(void) +SDL_WindowID +SDL_GetMouseFocusWindow() { - Uint8 i; - for ( i = 0; i < sizeof(SDL_ButtonState)*8; ++i ) { - if ( SDL_ButtonState & SDL_BUTTON(i) ) { - SDL_PrivateMouseButton(SDL_RELEASED, i, 0, 0); - } - } + SDL_Mouse *mouse = SDL_GetMouse(SDL_current_mouse); + + if (!mouse) { + return 0; + } + return mouse->focus; } -Uint8 SDL_GetMouseState (int *x, int *y) +static int +FlushMouseMotion(void *param, SDL_Event * event) { - if ( x ) { - *x = SDL_MouseX; - } - if ( y ) { - *y = SDL_MouseY; - } - return(SDL_ButtonState); + if (event->type == SDL_MOUSEMOTION + && event->motion.which == (Uint8) SDL_current_mouse) { + return 0; + } else { + return 1; + } } -Uint8 SDL_GetRelativeMouseState (int *x, int *y) +int +SDL_SetRelativeMouseMode(SDL_bool enabled) { - if ( x ) - *x = SDL_DeltaX; - if ( y ) - *y = SDL_DeltaY; - SDL_DeltaX = 0; - SDL_DeltaY = 0; - return(SDL_ButtonState); + SDL_Mouse *mouse = SDL_GetMouse(SDL_current_mouse); + + if (!mouse) { + return -1; + } + + /* Flush pending mouse motion */ + mouse->flush_motion = SDL_TRUE; + SDL_PumpEvents(); + mouse->flush_motion = SDL_FALSE; + SDL_FilterEvents(FlushMouseMotion, mouse); + + /* Set the relative mode */ + mouse->relative_mode = enabled; + + /* Update cursor visibility */ + SDL_SetCursor(NULL); + + if (!enabled) { + /* Restore the expected mouse position */ + SDL_WarpMouseInWindow(mouse->focus, mouse->x, mouse->y); + } + return 0; } -static void ClipOffset(Sint16 *x, Sint16 *y) +SDL_bool +SDL_GetRelativeMouseMode() { - /* This clips absolute mouse coordinates when the apparent - display surface is smaller than the real display surface. - */ - if ( SDL_VideoSurface->offset ) { - *y -= SDL_VideoSurface->offset/SDL_VideoSurface->pitch; - *x -= (SDL_VideoSurface->offset%SDL_VideoSurface->pitch)/ - SDL_VideoSurface->format->BytesPerPixel; - } + SDL_Mouse *mouse = SDL_GetMouse(SDL_current_mouse); + + if (!mouse) { + return SDL_FALSE; + } + return mouse->relative_mode; } -/* These are global for SDL_eventloop.c */ -int SDL_PrivateMouseMotion(Uint8 buttonstate, int relative, Sint16 x, Sint16 y) +Uint8 +SDL_GetMouseState(int *x, int *y) { - int posted; - Uint16 X, Y; - Sint16 Xrel; - Sint16 Yrel; - - /* Don't handle mouse motion if there's no cursor surface */ - if ( SDL_VideoSurface == NULL ) { - return(0); - } - - /* Default buttonstate is the current one */ - if ( ! buttonstate ) { - buttonstate = SDL_ButtonState; - } - - Xrel = x; - Yrel = y; - if ( relative ) { - /* Push the cursor around */ - x = (SDL_MouseX+x); - y = (SDL_MouseY+y); - } else { - /* Do we need to clip {x,y} ? */ - ClipOffset(&x, &y); - } - - /* Mouse coordinates range from 0 - width-1 and 0 - height-1 */ - if ( x < 0 ) - X = 0; - else - if ( x >= SDL_VideoSurface->w ) - X = SDL_VideoSurface->w-1; - else - X = (Uint16)x; - - if ( y < 0 ) - Y = 0; - else - if ( y >= SDL_VideoSurface->h ) - Y = SDL_VideoSurface->h-1; - else - Y = (Uint16)y; - - /* If not relative mode, generate relative motion from clamped X/Y. - This prevents lots of extraneous large delta relative motion when - the screen is windowed mode and the mouse is outside the window. - */ - if ( ! relative ) { - Xrel = X-SDL_MouseX; - Yrel = Y-SDL_MouseY; - } - - /* Drop events that don't change state */ - if ( ! Xrel && ! Yrel ) { + SDL_Mouse *mouse = SDL_GetMouse(SDL_current_mouse); + + if (!mouse) { + if (x) { + *x = 0; + } + if (y) { + *y = 0; + } + return 0; + } + + if (x) { + *x = mouse->x; + } + if (y) { + *y = mouse->y; + } + return mouse->buttonstate; +} + +Uint8 +SDL_GetRelativeMouseState(int *x, int *y) +{ + SDL_Mouse *mouse = SDL_GetMouse(SDL_current_mouse); + + if (!mouse) { + if (x) { + *x = 0; + } + if (y) { + *y = 0; + } + return 0; + } + + if (x) { + *x = mouse->xdelta; + } + if (y) { + *y = mouse->ydelta; + } + mouse->xdelta = 0; + mouse->ydelta = 0; + return mouse->buttonstate; +} + +void +SDL_SetMouseFocus(int index, SDL_WindowID windowID) +{ + SDL_Mouse *mouse = SDL_GetMouse(index); + int i; + SDL_bool focus; + + if (!mouse || (mouse->focus == windowID)) { + return; + } + + /* See if the current window has lost focus */ + if (mouse->focus) { + focus = SDL_FALSE; + for (i = 0; i < SDL_num_mice; ++i) { + SDL_Mouse *check; + if (i != index) { + check = SDL_GetMouse(i); + if (check && check->focus == mouse->focus) { + focus = SDL_TRUE; + break; + } + } + } + if (!focus) { + SDL_SendWindowEvent(mouse->focus, SDL_WINDOWEVENT_LEAVE, 0, 0); + } + } + + mouse->focus = windowID; + + if (mouse->focus) { + focus = SDL_FALSE; + for (i = 0; i < SDL_num_mice; ++i) { + SDL_Mouse *check; + if (i != index) { + check = SDL_GetMouse(i); + if (check && check->focus == mouse->focus) { + focus = SDL_TRUE; + break; + } + } + } + if (!focus) { + SDL_SendWindowEvent(mouse->focus, SDL_WINDOWEVENT_ENTER, 0, 0); + } + } +} + +int +SDL_SendMouseMotion(int index, int relative, int x, int y) +{ + SDL_Mouse *mouse = SDL_GetMouse(index); + int posted; + int xrel; + int yrel; + + if (!mouse || mouse->flush_motion) { + return 0; + } + + if (relative) { + /* Push the cursor around */ + xrel = x; + yrel = y; + x = (mouse->x + xrel); + y = (mouse->y + yrel); + } else { + xrel = x - mouse->x; + yrel = y - mouse->y; + } + + /* Drop events that don't change state */ + if (!xrel && !yrel) { #if 0 -printf("Mouse event didn't change state - dropped!\n"); + printf("Mouse event didn't change state - dropped!\n"); #endif - return(0); - } - - /* Update internal mouse state */ - SDL_ButtonState = buttonstate; - SDL_MouseX = X; - SDL_MouseY = Y; - SDL_DeltaX += Xrel; - SDL_DeltaY += Yrel; - SDL_MoveCursor(SDL_MouseX, SDL_MouseY); - - /* Post the event, if desired */ - posted = 0; - if ( SDL_ProcessEvents[SDL_MOUSEMOTION] == SDL_ENABLE ) { - SDL_Event event; - SDL_memset(&event, 0, sizeof(event)); - event.type = SDL_MOUSEMOTION; - event.motion.state = buttonstate; - event.motion.x = X; - event.motion.y = Y; - event.motion.xrel = Xrel; - event.motion.yrel = Yrel; - if ( (SDL_EventOK == NULL) || (*SDL_EventOK)(&event) ) { - posted = 1; - SDL_PushEvent(&event); - } - } - return(posted); + return 0; + } + + /* Update internal mouse state */ + if (!mouse->relative_mode) { + mouse->x = x; + mouse->y = y; + } + mouse->xdelta += xrel; + mouse->ydelta += yrel; + + /* Move the mouse cursor, if needed */ + if (mouse->cursor_shown && !mouse->relative_mode && + mouse->MoveCursor && mouse->cur_cursor) { + mouse->MoveCursor(mouse->cur_cursor); + } + + /* Post the event, if desired */ + posted = 0; + if (SDL_ProcessEvents[SDL_MOUSEMOTION] == SDL_ENABLE) { + SDL_Event event; + event.motion.type = SDL_MOUSEMOTION; + event.motion.which = (Uint8) index; + event.motion.state = mouse->buttonstate; + event.motion.x = mouse->x; + event.motion.y = mouse->y; + event.motion.xrel = xrel; + event.motion.yrel = yrel; + event.motion.windowID = mouse->focus; + posted = (SDL_PushEvent(&event) > 0); + } + return posted; +} + +int +SDL_SendMouseButton(int index, Uint8 state, Uint8 button) +{ + SDL_Mouse *mouse = SDL_GetMouse(index); + int posted; + Uint8 type; + + if (!mouse) { + return 0; + } + + /* Figure out which event to perform */ + switch (state) { + case SDL_PRESSED: + if (mouse->buttonstate & SDL_BUTTON(button)) { + /* Ignore this event, no state change */ + return 0; + } + type = SDL_MOUSEBUTTONDOWN; + mouse->buttonstate |= SDL_BUTTON(button); + break; + case SDL_RELEASED: + if (!(mouse->buttonstate & SDL_BUTTON(button))) { + /* Ignore this event, no state change */ + return 0; + } + type = SDL_MOUSEBUTTONUP; + mouse->buttonstate &= ~SDL_BUTTON(button); + break; + default: + /* Invalid state -- bail */ + return 0; + } + + /* Post the event, if desired */ + posted = 0; + if (SDL_ProcessEvents[type] == SDL_ENABLE) { + SDL_Event event; + event.type = type; + event.button.which = (Uint8) index; + event.button.state = state; + event.button.button = button; + event.button.x = mouse->x; + event.button.y = mouse->y; + event.button.windowID = mouse->focus; + posted = (SDL_PushEvent(&event) > 0); + } + return posted; +} + +int +SDL_SendMouseWheel(int index, int motion) +{ + SDL_Mouse *mouse = SDL_GetMouse(index); + int posted; + + if (!mouse || !motion) { + return 0; + } + + /* Post the event, if desired */ + posted = 0; + if (SDL_ProcessEvents[SDL_MOUSEWHEEL] == SDL_ENABLE) { + SDL_Event event; + event.type = SDL_MOUSEWHEEL; + event.wheel.which = (Uint8) index; + event.wheel.motion = motion; + event.wheel.windowID = mouse->focus; + posted = (SDL_PushEvent(&event) > 0); + } + return posted; +} + +void +SDL_WarpMouseInWindow(SDL_WindowID windowID, int x, int y) +{ + SDL_Mouse *mouse = SDL_GetMouse(SDL_current_mouse); + + if (!mouse) { + return; + } + + if (mouse->WarpMouse) { + mouse->WarpMouse(mouse, windowID, x, y); + } else { + SDL_SetMouseFocus(SDL_current_mouse, windowID); + SDL_SendMouseMotion(SDL_current_mouse, 0, x, y); + } +} + +SDL_Cursor * +SDL_CreateCursor(const Uint8 * data, const Uint8 * mask, + int w, int h, int hot_x, int hot_y) +{ + SDL_Mouse *mouse = SDL_GetMouse(SDL_current_mouse); + SDL_Surface *surface; + SDL_Cursor *cursor; + int x, y; + Uint32 *pixel; + Uint8 datab, maskb; + const Uint32 black = 0xFF000000; + const Uint32 white = 0xFFFFFFFF; + const Uint32 transparent = 0x00000000; + + if (!mouse) { + SDL_SetError("No mice are initialized"); + return NULL; + } + + if (!mouse->CreateCursor) { + SDL_SetError("Current mouse doesn't have cursor support"); + return NULL; + } + + /* Sanity check the hot spot */ + if ((hot_x < 0) || (hot_y < 0) || (hot_x >= w) || (hot_y >= h)) { + SDL_SetError("Cursor hot spot doesn't lie within cursor"); + return NULL; + } + + /* Make sure the width is a multiple of 8 */ + w = ((w + 7) & ~7); + + /* Create the surface from a bitmap */ + surface = + SDL_CreateRGBSurface(0, w, h, 32, 0x00FF0000, 0x0000FF00, 0x000000FF, + 0xFF000000); + if (!surface) { + return NULL; + } + for (y = 0; y < h; ++y) { + pixel = (Uint32 *) ((Uint8 *) surface->pixels + y * surface->pitch); + for (x = 0; x < w; ++x) { + if ((x % 8) == 0) { + datab = *data++; + maskb = *mask++; + } + if (maskb & 0x80) { + *pixel++ = (datab & 0x80) ? black : white; + } else { + *pixel++ = (datab & 0x80) ? black : transparent; + } + datab <<= 1; + maskb <<= 1; + } + } + + cursor = mouse->CreateCursor(surface, hot_x, hot_y); + if (cursor) { + cursor->mouse = mouse; + cursor->next = mouse->cursors; + mouse->cursors = cursor; + } + + SDL_FreeSurface(surface); + + return cursor; +} + +/* SDL_SetCursor(NULL) can be used to force the cursor redraw, + if this is desired for any reason. This is used when setting + the video mode and when the SDL window gains the mouse focus. + */ +void +SDL_SetCursor(SDL_Cursor * cursor) +{ + SDL_Mouse *mouse = SDL_GetMouse(SDL_current_mouse); + + if (!mouse) { + SDL_SetError("No mice are initialized"); + return; + } + + /* Set the new cursor */ + if (cursor) { + /* Make sure the cursor is still valid for this mouse */ + SDL_Cursor *found; + for (found = mouse->cursors; found; found = found->next) { + if (found == cursor) { + break; + } + } + if (!found) { + SDL_SetError("Cursor not associated with the current mouse"); + return; + } + mouse->cur_cursor = cursor; + } else { + cursor = mouse->cur_cursor; + } + + if (cursor && mouse->cursor_shown && !mouse->relative_mode) { + if (mouse->ShowCursor) { + mouse->ShowCursor(cursor); + } + } else { + if (mouse->ShowCursor) { + mouse->ShowCursor(NULL); + } + } +} + +SDL_Cursor * +SDL_GetCursor(void) +{ + SDL_Mouse *mouse = SDL_GetMouse(SDL_current_mouse); + + if (!mouse) { + return NULL; + } + return mouse->cur_cursor; +} + +void +SDL_FreeCursor(SDL_Cursor * cursor) +{ + SDL_Mouse *mouse; + SDL_Cursor *curr, *prev; + + if (!cursor) { + return; + } + mouse = cursor->mouse; + + if (cursor == mouse->def_cursor) { + return; + } + if (cursor == mouse->cur_cursor) { + SDL_SetCursor(mouse->def_cursor); + } + + for (prev = NULL, curr = mouse->cursors; curr; + prev = curr, curr = curr->next) { + if (curr == cursor) { + if (prev) { + prev->next = curr->next; + } else { + mouse->cursors = curr->next; + } + + if (mouse->FreeCursor) { + mouse->FreeCursor(curr); + } + return; + } + } } -int SDL_PrivateMouseButton(Uint8 state, Uint8 button, Sint16 x, Sint16 y) +int +SDL_ShowCursor(int toggle) { - SDL_Event event; - int posted; - int move_mouse; - Uint8 buttonstate; - - SDL_memset(&event, 0, sizeof(event)); - - /* Check parameters */ - if ( x || y ) { - ClipOffset(&x, &y); - move_mouse = 1; - /* Mouse coordinates range from 0 - width-1 and 0 - height-1 */ - if ( x < 0 ) - x = 0; - else - if ( x >= SDL_VideoSurface->w ) - x = SDL_VideoSurface->w-1; - - if ( y < 0 ) - y = 0; - else - if ( y >= SDL_VideoSurface->h ) - y = SDL_VideoSurface->h-1; - } else { - move_mouse = 0; - } - if ( ! x ) - x = SDL_MouseX; - if ( ! y ) - y = SDL_MouseY; - - /* Figure out which event to perform */ - buttonstate = SDL_ButtonState; - switch ( state ) { - case SDL_PRESSED: - event.type = SDL_MOUSEBUTTONDOWN; - buttonstate |= SDL_BUTTON(button); - break; - case SDL_RELEASED: - event.type = SDL_MOUSEBUTTONUP; - buttonstate &= ~SDL_BUTTON(button); - break; - default: - /* Invalid state -- bail */ - return(0); - } - - /* Update internal mouse state */ - SDL_ButtonState = buttonstate; - if ( move_mouse ) { - SDL_MouseX = x; - SDL_MouseY = y; - SDL_MoveCursor(SDL_MouseX, SDL_MouseY); - } - - /* Post the event, if desired */ - posted = 0; - if ( SDL_ProcessEvents[event.type] == SDL_ENABLE ) { - event.button.state = state; - event.button.button = button; - event.button.x = x; - event.button.y = y; - if ( (SDL_EventOK == NULL) || (*SDL_EventOK)(&event) ) { - posted = 1; - SDL_PushEvent(&event); - } - } - return(posted); + SDL_Mouse *mouse = SDL_GetMouse(SDL_current_mouse); + SDL_bool shown; + + if (!mouse) { + return 0; + } + + shown = mouse->cursor_shown; + if (toggle >= 0) { + if (toggle) { + mouse->cursor_shown = SDL_TRUE; + } else { + mouse->cursor_shown = SDL_FALSE; + } + if (mouse->cursor_shown != shown) { + SDL_SetCursor(NULL); + } + } + return shown; } +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/events/SDL_mouse_c.h b/src/events/SDL_mouse_c.h new file mode 100644 index 000000000..4bc60835f --- /dev/null +++ b/src/events/SDL_mouse_c.h @@ -0,0 +1,112 @@ +/* + SDL - Simple DirectMedia Layer + Copyright (C) 1997-2006 Sam Lantinga + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + Sam Lantinga + slouken@libsdl.org +*/ +#include "SDL_config.h" + +#ifndef _SDL_mouse_c_h +#define _SDL_mouse_c_h + +typedef struct SDL_Mouse SDL_Mouse; + +struct SDL_Cursor +{ + SDL_Mouse *mouse; + + SDL_Cursor *next; + + void *driverdata; +}; + +struct SDL_Mouse +{ + /* Create a cursor from a surface */ + SDL_Cursor *(*CreateCursor) (SDL_Surface * surface, int hot_x, int hot_y); + + /* Show the specified cursor, or hide if cursor is NULL */ + int (*ShowCursor) (SDL_Cursor * cursor); + + /* This is called when a mouse motion event occurs */ + void (*MoveCursor) (SDL_Cursor * cursor); + + /* Free a window manager cursor */ + void (*FreeCursor) (SDL_Cursor * cursor); + + /* Warp the mouse to (x,y) */ + void (*WarpMouse) (SDL_Mouse * mouse, SDL_WindowID windowID, int x, + int y); + + /* Free the mouse when it's time */ + void (*FreeMouse) (SDL_Mouse * mouse); + + /* Data common to all mice */ + SDL_WindowID focus; + int x; + int y; + int xdelta; + int ydelta; + Uint8 buttonstate; + SDL_bool relative_mode; + SDL_bool flush_motion; + + SDL_Cursor *cursors; + SDL_Cursor *def_cursor; + SDL_Cursor *cur_cursor; + SDL_bool cursor_shown; + + void *driverdata; +}; + + +/* Initialize the mouse subsystem */ +extern int SDL_MouseInit(void); + +/* Get the mouse at an index */ +extern SDL_Mouse *SDL_GetMouse(int index); + +/* Add a mouse, possibly reattaching at a particular index (or -1), + returning the index of the mouse, or -1 if there was an error. + */ +extern int SDL_AddMouse(const SDL_Mouse * mouse, int index); + +/* Remove a mouse at an index, clearing the slot for later */ +extern void SDL_DelMouse(int index); + +/* Clear the button state of a mouse at an index */ +extern void SDL_ResetMouse(int index); + +/* Set the mouse focus window */ +extern void SDL_SetMouseFocus(int index, SDL_WindowID windowID); + +/* Send a mouse motion event for a mouse at an index */ +extern int SDL_SendMouseMotion(int index, int relative, int x, int y); + +/* Send a mouse button event for a mouse at an index */ +extern int SDL_SendMouseButton(int index, Uint8 state, Uint8 button); + +/* Send a mouse wheel event for a mouse at an index */ +extern int SDL_SendMouseWheel(int index, int motion); + +/* Shutdown the mouse subsystem */ +extern void SDL_MouseQuit(void); + +#endif /* _SDL_mouse_c_h */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/events/SDL_quit.c b/src/events/SDL_quit.c index 591f3274a..4d7567dfa 100644 --- a/src/events/SDL_quit.c +++ b/src/events/SDL_quit.c @@ -32,61 +32,65 @@ #ifdef HAVE_SIGNAL_H -static void SDL_HandleSIG(int sig) +static void +SDL_HandleSIG(int sig) { - /* Reset the signal handler */ - signal(sig, SDL_HandleSIG); + /* Reset the signal handler */ + signal(sig, SDL_HandleSIG); - /* Signal a quit interrupt */ - SDL_PrivateQuit(); + /* Signal a quit interrupt */ + SDL_SendQuit(); } #endif /* HAVE_SIGNAL_H */ /* Public functions */ -int SDL_QuitInit(void) +int +SDL_QuitInit(void) { #ifdef HAVE_SIGNAL_H - void (*ohandler)(int); - - /* Both SIGINT and SIGTERM are translated into quit interrupts */ - ohandler = signal(SIGINT, SDL_HandleSIG); - if ( ohandler != SIG_DFL ) - signal(SIGINT, ohandler); - ohandler = signal(SIGTERM, SDL_HandleSIG); - if ( ohandler != SIG_DFL ) - signal(SIGTERM, ohandler); + void (*ohandler) (int); + + /* Both SIGINT and SIGTERM are translated into quit interrupts */ + ohandler = signal(SIGINT, SDL_HandleSIG); + if (ohandler != SIG_DFL) + signal(SIGINT, ohandler); + ohandler = signal(SIGTERM, SDL_HandleSIG); + if (ohandler != SIG_DFL) + signal(SIGTERM, ohandler); #endif /* HAVE_SIGNAL_H */ - /* That's it! */ - return(0); + /* That's it! */ + return (0); } -void SDL_QuitQuit(void) + +void +SDL_QuitQuit(void) { #ifdef HAVE_SIGNAL_H - void (*ohandler)(int); - - ohandler = signal(SIGINT, SIG_DFL); - if ( ohandler != SDL_HandleSIG ) - signal(SIGINT, ohandler); - ohandler = signal(SIGTERM, SIG_DFL); - if ( ohandler != SDL_HandleSIG ) - signal(SIGTERM, ohandler); + void (*ohandler) (int); + + ohandler = signal(SIGINT, SIG_DFL); + if (ohandler != SDL_HandleSIG) + signal(SIGINT, ohandler); + ohandler = signal(SIGTERM, SIG_DFL); + if (ohandler != SDL_HandleSIG) + signal(SIGTERM, ohandler); #endif /* HAVE_SIGNAL_H */ } /* This function returns 1 if it's okay to close the application window */ -int SDL_PrivateQuit(void) +int +SDL_SendQuit(void) { - int posted; - - posted = 0; - if ( SDL_ProcessEvents[SDL_QUIT] == SDL_ENABLE ) { - SDL_Event event; - event.type = SDL_QUIT; - if ( (SDL_EventOK == NULL) || (*SDL_EventOK)(&event) ) { - posted = 1; - SDL_PushEvent(&event); - } - } - return(posted); + int posted; + + posted = 0; + if (SDL_ProcessEvents[SDL_QUIT] == SDL_ENABLE) { + SDL_Event event; + event.type = SDL_QUIT; + posted = (SDL_PushEvent(&event) > 0); + } + return (posted); } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/events/SDL_resize.c b/src/events/SDL_resize.c deleted file mode 100644 index f625f706c..000000000 --- a/src/events/SDL_resize.c +++ /dev/null @@ -1,75 +0,0 @@ -/* - SDL - Simple DirectMedia Layer - Copyright (C) 1997-2006 Sam Lantinga - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - - Sam Lantinga - slouken@libsdl.org -*/ -#include "SDL_config.h" - -/* Resize event handling code for SDL */ - -#include "SDL_events.h" -#include "SDL_events_c.h" -#include "../video/SDL_sysvideo.h" - - -/* Keep the last resize event so we don't post duplicates */ -static struct { - int w; - int h; -} last_resize; - -/* This is global for SDL_eventloop.c */ -int SDL_PrivateResize(int w, int h) -{ - int posted; - SDL_Event events[32]; - - /* See if this event would change the video surface */ - if ( !w || !h -#ifndef __OS2__ - || ((last_resize.w == w) && (last_resize.h == h)) -#endif - ) { - return(0); - } - last_resize.w = w; - last_resize.h = h; - if ( ! SDL_VideoSurface || - ((w == SDL_VideoSurface->w) && (h == SDL_VideoSurface->h)) ) { - return(0); - } - - /* Pull out all old resize events */ - SDL_PeepEvents(events, sizeof(events)/sizeof(events[0]), - SDL_GETEVENT, SDL_VIDEORESIZEMASK); - - /* Post the event, if desired */ - posted = 0; - if ( SDL_ProcessEvents[SDL_VIDEORESIZE] == SDL_ENABLE ) { - SDL_Event event; - event.type = SDL_VIDEORESIZE; - event.resize.w = w; - event.resize.h = h; - if ( (SDL_EventOK == NULL) || (*SDL_EventOK)(&event) ) { - posted = 1; - SDL_PushEvent(&event); - } - } - return(posted); -} diff --git a/src/events/SDL_sysevents.h b/src/events/SDL_sysevents.h index 07d55b421..8c515d9b5 100644 --- a/src/events/SDL_sysevents.h +++ b/src/events/SDL_sysevents.h @@ -25,22 +25,23 @@ /* Useful functions and variables from SDL_sysevents.c */ -#ifdef __BEOS__ /* The Be event loop runs in a separate thread */ +#ifdef __BEOS__ /* The Be event loop runs in a separate thread */ #define MUST_THREAD_EVENTS #endif -#ifdef __WIN32__ /* Win32 doesn't allow a separate event thread */ +#ifdef __WIN32__ /* Win32 doesn't allow a separate event thread */ #define CANT_THREAD_EVENTS #endif -#ifdef IPOD /* iPod doesn't support threading at all */ +#ifdef IPOD /* iPod doesn't support threading at all */ #define CANT_THREAD_EVENTS #endif -#ifdef __MACOS__ /* MacOS 7/8 don't support preemptive multi-tasking */ +#ifdef __MACOS__ /* MacOS 7/8 don't support preemptive multi-tasking */ #define CANT_THREAD_EVENTS #endif -#ifdef __OS2__ /* The OS/2 event loop runs in a separate thread */ +#ifdef __OS2__ /* The OS/2 event loop runs in a separate thread */ #define MUST_THREAD_EVENTS #endif +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/events/SDL_windowevents.c b/src/events/SDL_windowevents.c new file mode 100644 index 000000000..9f3eeac27 --- /dev/null +++ b/src/events/SDL_windowevents.c @@ -0,0 +1,132 @@ +/* + SDL - Simple DirectMedia Layer + Copyright (C) 1997-2006 Sam Lantinga + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + Sam Lantinga + slouken@libsdl.org +*/ +#include "SDL_config.h" + +/* Window event handling code for SDL */ + +#include "SDL_events.h" +#include "SDL_events_c.h" +#include "../video/SDL_sysvideo.h" + +int +SDL_SendWindowEvent(SDL_WindowID windowID, Uint8 windowevent, int data1, + int data2) +{ + int posted; + SDL_Window *window; + + window = SDL_GetWindowFromID(windowID); + if (!window) { + return 0; + } + switch (windowevent) { + case SDL_WINDOWEVENT_SHOWN: + if (window->flags & SDL_WINDOW_SHOWN) { + return 0; + } + window->flags |= SDL_WINDOW_SHOWN; + SDL_OnWindowShown(window); + break; + case SDL_WINDOWEVENT_HIDDEN: + if (!(window->flags & SDL_WINDOW_SHOWN)) { + return 0; + } + window->flags &= ~SDL_WINDOW_SHOWN; + SDL_OnWindowHidden(window); + break; + case SDL_WINDOWEVENT_MOVED: + if (window->flags & SDL_WINDOW_FULLSCREEN) { + return 0; + } + if (data1 == window->x && data2 == window->y) { + return 0; + } + break; + case SDL_WINDOWEVENT_RESIZED: + if (window->flags & SDL_WINDOW_FULLSCREEN) { + return 0; + } + if (data1 == window->w && data2 == window->h) { + return 0; + } + break; + case SDL_WINDOWEVENT_MINIMIZED: + if (window->flags & SDL_WINDOW_MINIMIZED) { + return 0; + } + window->flags |= SDL_WINDOW_MINIMIZED; + break; + case SDL_WINDOWEVENT_MAXIMIZED: + if (window->flags & SDL_WINDOW_MAXIMIZED) { + return 0; + } + window->flags |= SDL_WINDOW_MAXIMIZED; + break; + case SDL_WINDOWEVENT_RESTORED: + if (!(window->flags & (SDL_WINDOW_MINIMIZED | SDL_WINDOW_MAXIMIZED))) { + return 0; + } + window->flags &= ~(SDL_WINDOW_MINIMIZED | SDL_WINDOW_MAXIMIZED); + break; + case SDL_WINDOWEVENT_ENTER: + if (window->flags & SDL_WINDOW_MOUSE_FOCUS) { + return 0; + } + window->flags |= SDL_WINDOW_MOUSE_FOCUS; + break; + case SDL_WINDOWEVENT_LEAVE: + if (!(window->flags & SDL_WINDOW_MOUSE_FOCUS)) { + return 0; + } + window->flags &= ~SDL_WINDOW_MOUSE_FOCUS; + break; + case SDL_WINDOWEVENT_FOCUS_GAINED: + if (window->flags & SDL_WINDOW_INPUT_FOCUS) { + return 0; + } + window->flags |= SDL_WINDOW_INPUT_FOCUS; + SDL_OnWindowFocusGained(window); + break; + case SDL_WINDOWEVENT_FOCUS_LOST: + if (!(window->flags & SDL_WINDOW_INPUT_FOCUS)) { + return 0; + } + window->flags &= ~SDL_WINDOW_INPUT_FOCUS; + SDL_OnWindowFocusLost(window); + break; + } + + /* Post the event, if desired */ + posted = 0; + if (SDL_ProcessEvents[SDL_WINDOWEVENT] == SDL_ENABLE) { + SDL_Event event; + event.type = SDL_WINDOWEVENT; + event.window.event = windowevent; + event.window.data1 = data1; + event.window.data2 = data2; + event.window.windowID = windowID; + posted = (SDL_PushEvent(&event) > 0); + } + return (posted); +} + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/events/SDL_windowevents_c.h b/src/events/SDL_windowevents_c.h new file mode 100644 index 000000000..39aef943f --- /dev/null +++ b/src/events/SDL_windowevents_c.h @@ -0,0 +1,32 @@ +/* + SDL - Simple DirectMedia Layer + Copyright (C) 1997-2006 Sam Lantinga + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + Sam Lantinga + slouken@libsdl.org +*/ +#include "SDL_config.h" + +#ifndef _SDL_windowevents_c_h +#define _SDL_windowevents_c_h + +extern int SDL_SendWindowEvent(SDL_WindowID windowID, Uint8 windowevent, + int data1, int data2); + +#endif /* _SDL_windowevents_c_h */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/blank_cursor.h b/src/events/blank_cursor.h similarity index 97% rename from src/video/blank_cursor.h rename to src/events/blank_cursor.h index f63fae32e..c62406cf7 100644 --- a/src/video/blank_cursor.h +++ b/src/events/blank_cursor.h @@ -31,3 +31,4 @@ static unsigned char blank_cdata[8] = { 0, 0, 0, 0, 0, 0, 0, 0 }; static unsigned char blank_cmask[8] = { 0, 0, 0, 0, 0, 0, 0, 0 }; +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/default_cursor.h b/src/events/default_cursor.h similarity index 51% rename from src/video/default_cursor.h rename to src/events/default_cursor.h index 9953e01b9..1fcc19e09 100644 --- a/src/video/default_cursor.h +++ b/src/events/default_cursor.h @@ -33,84 +33,81 @@ #ifdef USE_MACOS_CURSOR -static unsigned char default_cdata[] = -{ - 0x00,0x00, - 0x40,0x00, - 0x60,0x00, - 0x70,0x00, - 0x78,0x00, - 0x7C,0x00, - 0x7E,0x00, - 0x7F,0x00, - 0x7F,0x80, - 0x7C,0x00, - 0x6C,0x00, - 0x46,0x00, - 0x06,0x00, - 0x03,0x00, - 0x03,0x00, - 0x00,0x00 +static unsigned char default_cdata[] = { + 0x00, 0x00, + 0x40, 0x00, + 0x60, 0x00, + 0x70, 0x00, + 0x78, 0x00, + 0x7C, 0x00, + 0x7E, 0x00, + 0x7F, 0x00, + 0x7F, 0x80, + 0x7C, 0x00, + 0x6C, 0x00, + 0x46, 0x00, + 0x06, 0x00, + 0x03, 0x00, + 0x03, 0x00, + 0x00, 0x00 }; -static unsigned char default_cmask[] = -{ - 0xC0,0x00, - 0xE0,0x00, - 0xF0,0x00, - 0xF8,0x00, - 0xFC,0x00, - 0xFE,0x00, - 0xFF,0x00, - 0xFF,0x80, - 0xFF,0xC0, - 0xFF,0xE0, - 0xFE,0x00, - 0xEF,0x00, - 0xCF,0x00, - 0x87,0x80, - 0x07,0x80, - 0x03,0x00 +static unsigned char default_cmask[] = { + 0xC0, 0x00, + 0xE0, 0x00, + 0xF0, 0x00, + 0xF8, 0x00, + 0xFC, 0x00, + 0xFE, 0x00, + 0xFF, 0x00, + 0xFF, 0x80, + 0xFF, 0xC0, + 0xFF, 0xE0, + 0xFE, 0x00, + 0xEF, 0x00, + 0xCF, 0x00, + 0x87, 0x80, + 0x07, 0x80, + 0x03, 0x00 }; #else -static unsigned char default_cdata[] = -{ - 0x00,0x00, - 0x40,0x00, - 0x60,0x00, - 0x70,0x00, - 0x78,0x00, - 0x7C,0x00, - 0x7E,0x00, - 0x7F,0x00, - 0x7F,0x80, - 0x7C,0x00, - 0x6C,0x00, - 0x46,0x00, - 0x06,0x00, - 0x03,0x00, - 0x03,0x00, - 0x00,0x00 +static unsigned char default_cdata[] = { + 0x00, 0x00, + 0x40, 0x00, + 0x60, 0x00, + 0x70, 0x00, + 0x78, 0x00, + 0x7C, 0x00, + 0x7E, 0x00, + 0x7F, 0x00, + 0x7F, 0x80, + 0x7C, 0x00, + 0x6C, 0x00, + 0x46, 0x00, + 0x06, 0x00, + 0x03, 0x00, + 0x03, 0x00, + 0x00, 0x00 }; -static unsigned char default_cmask[] = -{ - 0x40,0x00, - 0xE0,0x00, - 0xF0,0x00, - 0xF8,0x00, - 0xFC,0x00, - 0xFE,0x00, - 0xFF,0x00, - 0xFF,0x80, - 0xFF,0xC0, - 0xFF,0x80, - 0xFE,0x00, - 0xEF,0x00, - 0x4F,0x00, - 0x07,0x80, - 0x07,0x80, - 0x03,0x00 +static unsigned char default_cmask[] = { + 0x40, 0x00, + 0xE0, 0x00, + 0xF0, 0x00, + 0xF8, 0x00, + 0xFC, 0x00, + 0xFE, 0x00, + 0xFF, 0x00, + 0xFF, 0x80, + 0xFF, 0xC0, + 0xFF, 0x80, + 0xFE, 0x00, + 0xEF, 0x00, + 0x4F, 0x00, + 0x07, 0x80, + 0x07, 0x80, + 0x03, 0x00 }; #endif /* TRUE_MACINTOSH_CURSOR */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/file/SDL_rwops.c b/src/file/SDL_rwops.c index add218fd2..22c71007e 100644 --- a/src/file/SDL_rwops.c +++ b/src/file/SDL_rwops.c @@ -43,275 +43,307 @@ #define INVALID_SET_FILE_POINTER 0xFFFFFFFF #endif -static int SDLCALL win32_file_open(SDL_RWops *context, const char *filename, const char *mode) +static int SDLCALL +win32_file_open(SDL_RWops * context, const char *filename, const char *mode) { #ifndef _WIN32_WCE - UINT old_error_mode; + UINT old_error_mode; #endif - HANDLE h; - DWORD r_right, w_right; - DWORD must_exist, truncate; - int a_mode; - - if (!context) - return -1; - - context->hidden.win32io.h = INVALID_HANDLE_VALUE; /* mark this as unusable */ - - /* "r" = reading, file must exist */ - /* "w" = writing, truncate existing, file may not exist */ - /* "r+"= reading or writing, file must exist */ - /* "a" = writing, append file may not exist */ - /* "a+"= append + read, file may not exist */ - /* "w+" = read, write, truncate. file may not exist */ - - must_exist = ( SDL_strchr(mode,'r') != NULL ) ? OPEN_EXISTING : 0; - truncate = ( SDL_strchr(mode,'w') != NULL ) ? CREATE_ALWAYS : 0; - r_right = ( SDL_strchr(mode,'+') != NULL || must_exist ) ? GENERIC_READ : 0; - a_mode = ( SDL_strchr(mode,'a') != NULL ) ? OPEN_ALWAYS : 0; - w_right = ( a_mode || SDL_strchr(mode,'+') || truncate ) ? GENERIC_WRITE : 0; - - if (!r_right && !w_right) /* inconsistent mode */ - return -1; /* failed (invalid call)*/ + HANDLE h; + DWORD r_right, w_right; + DWORD must_exist, truncate; + int a_mode; + + if (!context) + return -1; + + context->hidden.win32io.h = INVALID_HANDLE_VALUE; /* mark this as unusable */ + + /* "r" = reading, file must exist */ + /* "w" = writing, truncate existing, file may not exist */ + /* "r+"= reading or writing, file must exist */ + /* "a" = writing, append file may not exist */ + /* "a+"= append + read, file may not exist */ + /* "w+" = read, write, truncate. file may not exist */ + + must_exist = (SDL_strchr(mode, 'r') != NULL) ? OPEN_EXISTING : 0; + truncate = (SDL_strchr(mode, 'w') != NULL) ? CREATE_ALWAYS : 0; + r_right = (SDL_strchr(mode, '+') != NULL + || must_exist) ? GENERIC_READ : 0; + a_mode = (SDL_strchr(mode, 'a') != NULL) ? OPEN_ALWAYS : 0; + w_right = (a_mode || SDL_strchr(mode, '+') + || truncate) ? GENERIC_WRITE : 0; + + if (!r_right && !w_right) /* inconsistent mode */ + return -1; /* failed (invalid call) */ #ifdef _WIN32_WCE - { - size_t size = SDL_strlen(filename)+1; - wchar_t *filenameW = SDL_stack_alloc(wchar_t, size); - - if ( MultiByteToWideChar(CP_UTF8, 0, filename, -1, filenameW, size) == 0 ) { - SDL_SetError("Unable to convert filename to Unicode"); - SDL_stack_free(filenameW); - return -1; - } - h = CreateFile(filenameW, (w_right|r_right), (w_right)? 0 : FILE_SHARE_READ, - NULL, (must_exist|truncate|a_mode), FILE_ATTRIBUTE_NORMAL,NULL); - SDL_stack_free(filenameW); - } + { + size_t size = SDL_strlen(filename) + 1; + wchar_t *filenameW = SDL_stack_alloc(wchar_t, size); + + if (MultiByteToWideChar(CP_UTF8, 0, filename, -1, filenameW, size) == + 0) { + SDL_SetError("Unable to convert filename to Unicode"); + SDL_stack_free(filenameW); + return -1; + } + h = CreateFile(filenameW, (w_right | r_right), + (w_right) ? 0 : FILE_SHARE_READ, NULL, + (must_exist | truncate | a_mode), + FILE_ATTRIBUTE_NORMAL, NULL); + SDL_stack_free(filenameW); + } #else - /* Do not open a dialog box if failure */ - old_error_mode = SetErrorMode(SEM_NOOPENFILEERRORBOX|SEM_FAILCRITICALERRORS); + /* Do not open a dialog box if failure */ + old_error_mode = + SetErrorMode(SEM_NOOPENFILEERRORBOX | SEM_FAILCRITICALERRORS); - h = CreateFile(filename, (w_right|r_right), (w_right)? 0 : FILE_SHARE_READ, - NULL, (must_exist|truncate|a_mode), FILE_ATTRIBUTE_NORMAL,NULL); + h = CreateFile(filename, (w_right | r_right), + (w_right) ? 0 : FILE_SHARE_READ, NULL, + (must_exist | truncate | a_mode), FILE_ATTRIBUTE_NORMAL, + NULL); - /* restore old behaviour */ - SetErrorMode(old_error_mode); + /* restore old behaviour */ + SetErrorMode(old_error_mode); #endif /* _WIN32_WCE */ - if (h==INVALID_HANDLE_VALUE) { - SDL_SetError("Couldn't open %s",filename); - return -2; /* failed (CreateFile) */ - } - context->hidden.win32io.h = h; - context->hidden.win32io.append = a_mode; - - return 0; /* ok */ -} -static int SDLCALL win32_file_seek(SDL_RWops *context, int offset, int whence) -{ - DWORD win32whence; - int file_pos; - - if (!context || context->hidden.win32io.h == INVALID_HANDLE_VALUE) { - SDL_SetError("win32_file_seek: invalid context/file not opened"); - return -1; - } - - switch (whence) { - case RW_SEEK_SET: - win32whence = FILE_BEGIN; break; - case RW_SEEK_CUR: - win32whence = FILE_CURRENT; break; - case RW_SEEK_END: - win32whence = FILE_END; break; - default: - SDL_SetError("win32_file_seek: Unknown value for 'whence'"); - return -1; - } - - file_pos = SetFilePointer(context->hidden.win32io.h,offset,NULL,win32whence); - - if ( file_pos != INVALID_SET_FILE_POINTER ) - return file_pos; /* success */ - - SDL_Error(SDL_EFSEEK); - return -1; /* error */ -} -static int SDLCALL win32_file_read(SDL_RWops *context, void *ptr, int size, int maxnum) -{ - - int total_bytes; - DWORD byte_read,nread; - - total_bytes = size*maxnum; - - if (!context || context->hidden.win32io.h == INVALID_HANDLE_VALUE || total_bytes<=0 || !size) - return 0; - - if (!ReadFile(context->hidden.win32io.h,ptr,total_bytes,&byte_read,NULL)) { - SDL_Error(SDL_EFREAD); - return 0; - } - nread = byte_read/size; - return nread; -} -static int SDLCALL win32_file_write(SDL_RWops *context, const void *ptr, int size, int num) -{ - - int total_bytes; - DWORD byte_written,nwritten; - - total_bytes = size*num; - - if (!context || context->hidden.win32io.h==INVALID_HANDLE_VALUE || total_bytes<=0 || !size) - return 0; - - /* if in append mode, we must go to the EOF before write */ - if (context->hidden.win32io.append) { - if ( SetFilePointer(context->hidden.win32io.h,0L,NULL,FILE_END) == INVALID_SET_FILE_POINTER ) { - SDL_Error(SDL_EFWRITE); - return 0; - } - } - - if (!WriteFile(context->hidden.win32io.h,ptr,total_bytes,&byte_written,NULL)) { - SDL_Error(SDL_EFWRITE); - return 0; - } - - nwritten = byte_written/size; - return nwritten; -} -static int SDLCALL win32_file_close(SDL_RWops *context) -{ - - if ( context ) { - if (context->hidden.win32io.h != INVALID_HANDLE_VALUE) { - CloseHandle(context->hidden.win32io.h); - context->hidden.win32io.h = INVALID_HANDLE_VALUE; /* to be sure */ - } - SDL_FreeRW(context); - } - return(0); + if (h == INVALID_HANDLE_VALUE) { + SDL_SetError("Couldn't open %s", filename); + return -2; /* failed (CreateFile) */ + } + context->hidden.win32io.h = h; + context->hidden.win32io.append = a_mode; + + return 0; /* ok */ } -#endif /* __WIN32__ */ +static int SDLCALL +win32_file_seek(SDL_RWops * context, int offset, int whence) +{ + DWORD win32whence; + int file_pos; -#ifdef HAVE_STDIO_H + if (!context || context->hidden.win32io.h == INVALID_HANDLE_VALUE) { + SDL_SetError("win32_file_seek: invalid context/file not opened"); + return -1; + } -/* Functions to read/write stdio file pointers */ + switch (whence) { + case RW_SEEK_SET: + win32whence = FILE_BEGIN; + break; + case RW_SEEK_CUR: + win32whence = FILE_CURRENT; + break; + case RW_SEEK_END: + win32whence = FILE_END; + break; + default: + SDL_SetError("win32_file_seek: Unknown value for 'whence'"); + return -1; + } -static int SDLCALL stdio_seek(SDL_RWops *context, int offset, int whence) -{ - if ( fseek(context->hidden.stdio.fp, offset, whence) == 0 ) { - return(ftell(context->hidden.stdio.fp)); - } else { - SDL_Error(SDL_EFSEEK); - return(-1); - } -} -static int SDLCALL stdio_read(SDL_RWops *context, void *ptr, int size, int maxnum) -{ - size_t nread; + file_pos = + SetFilePointer(context->hidden.win32io.h, offset, NULL, win32whence); + + if (file_pos != INVALID_SET_FILE_POINTER) + return file_pos; /* success */ - nread = fread(ptr, size, maxnum, context->hidden.stdio.fp); - if ( nread == 0 && ferror(context->hidden.stdio.fp) ) { - SDL_Error(SDL_EFREAD); - } - return(nread); + SDL_Error(SDL_EFSEEK); + return -1; /* error */ } -static int SDLCALL stdio_write(SDL_RWops *context, const void *ptr, int size, int num) +static int SDLCALL +win32_file_read(SDL_RWops * context, void *ptr, int size, int maxnum) { - size_t nwrote; - nwrote = fwrite(ptr, size, num, context->hidden.stdio.fp); - if ( nwrote == 0 && ferror(context->hidden.stdio.fp) ) { - SDL_Error(SDL_EFWRITE); - } - return(nwrote); + int total_bytes; + DWORD byte_read, nread; + + total_bytes = size * maxnum; + + if (!context || context->hidden.win32io.h == INVALID_HANDLE_VALUE + || total_bytes <= 0 || !size) + return 0; + + if (!ReadFile + (context->hidden.win32io.h, ptr, total_bytes, &byte_read, NULL)) { + SDL_Error(SDL_EFREAD); + return 0; + } + nread = byte_read / size; + return nread; } -static int SDLCALL stdio_close(SDL_RWops *context) +static int SDLCALL +win32_file_write(SDL_RWops * context, const void *ptr, int size, int num) { - if ( context ) { - if ( context->hidden.stdio.autoclose ) { - /* WARNING: Check the return value here! */ - fclose(context->hidden.stdio.fp); - } - SDL_FreeRW(context); - } - return(0); -} -#endif /* !HAVE_STDIO_H */ -/* Functions to read/write memory pointers */ + int total_bytes; + DWORD byte_written, nwritten; -static int SDLCALL mem_seek(SDL_RWops *context, int offset, int whence) -{ - Uint8 *newpos; + total_bytes = size * num; + + if (!context || context->hidden.win32io.h == INVALID_HANDLE_VALUE + || total_bytes <= 0 || !size) + return 0; + + /* if in append mode, we must go to the EOF before write */ + if (context->hidden.win32io.append) { + if (SetFilePointer(context->hidden.win32io.h, 0L, NULL, FILE_END) + == INVALID_SET_FILE_POINTER) { + SDL_Error(SDL_EFWRITE); + return 0; + } + } - switch (whence) { - case RW_SEEK_SET: - newpos = context->hidden.mem.base+offset; - break; - case RW_SEEK_CUR: - newpos = context->hidden.mem.here+offset; - break; - case RW_SEEK_END: - newpos = context->hidden.mem.stop+offset; - break; - default: - SDL_SetError("Unknown value for 'whence'"); - return(-1); - } - if ( newpos < context->hidden.mem.base ) { - newpos = context->hidden.mem.base; - } - if ( newpos > context->hidden.mem.stop ) { - newpos = context->hidden.mem.stop; - } - context->hidden.mem.here = newpos; - return(context->hidden.mem.here-context->hidden.mem.base); + if (!WriteFile + (context->hidden.win32io.h, ptr, total_bytes, &byte_written, NULL)) { + SDL_Error(SDL_EFWRITE); + return 0; + } + + nwritten = byte_written / size; + return nwritten; } -static int SDLCALL mem_read(SDL_RWops *context, void *ptr, int size, int maxnum) +static int SDLCALL +win32_file_close(SDL_RWops * context) { - size_t total_bytes; - size_t mem_available; - total_bytes = (maxnum * size); - if ( (maxnum <= 0) || (size <= 0) || ((total_bytes / maxnum) != (size_t) size) ) { - return 0; - } + if (context) { + if (context->hidden.win32io.h != INVALID_HANDLE_VALUE) { + CloseHandle(context->hidden.win32io.h); + context->hidden.win32io.h = INVALID_HANDLE_VALUE; /* to be sure */ + } + SDL_FreeRW(context); + } + return (0); +} +#endif /* __WIN32__ */ - mem_available = (context->hidden.mem.stop - context->hidden.mem.here); - if (total_bytes > mem_available) { - total_bytes = mem_available; - } +#ifdef HAVE_STDIO_H - SDL_memcpy(ptr, context->hidden.mem.here, total_bytes); - context->hidden.mem.here += total_bytes; +/* Functions to read/write stdio file pointers */ - return (total_bytes / size); +static int SDLCALL +stdio_seek(SDL_RWops * context, int offset, int whence) +{ + if (fseek(context->hidden.stdio.fp, offset, whence) == 0) { + return (ftell(context->hidden.stdio.fp)); + } else { + SDL_Error(SDL_EFSEEK); + return (-1); + } } -static int SDLCALL mem_write(SDL_RWops *context, const void *ptr, int size, int num) +static int SDLCALL +stdio_read(SDL_RWops * context, void *ptr, int size, int maxnum) { - if ( (context->hidden.mem.here + (num*size)) > context->hidden.mem.stop ) { - num = (context->hidden.mem.stop-context->hidden.mem.here)/size; - } - SDL_memcpy(context->hidden.mem.here, ptr, num*size); - context->hidden.mem.here += num*size; - return(num); + size_t nread; + + nread = fread(ptr, size, maxnum, context->hidden.stdio.fp); + if (nread == 0 && ferror(context->hidden.stdio.fp)) { + SDL_Error(SDL_EFREAD); + } + return (nread); } -static int SDLCALL mem_writeconst(SDL_RWops *context, const void *ptr, int size, int num) +static int SDLCALL +stdio_write(SDL_RWops * context, const void *ptr, int size, int num) { - SDL_SetError("Can't write to read-only memory"); - return(-1); + size_t nwrote; + + nwrote = fwrite(ptr, size, num, context->hidden.stdio.fp); + if (nwrote == 0 && ferror(context->hidden.stdio.fp)) { + SDL_Error(SDL_EFWRITE); + } + return (nwrote); } -static int SDLCALL mem_close(SDL_RWops *context) +static int SDLCALL +stdio_close(SDL_RWops * context) { - if ( context ) { - SDL_FreeRW(context); - } - return(0); + if (context) { + if (context->hidden.stdio.autoclose) { + /* WARNING: Check the return value here! */ + fclose(context->hidden.stdio.fp); + } + SDL_FreeRW(context); + } + return (0); +} +#endif /* !HAVE_STDIO_H */ + +/* Functions to read/write memory pointers */ + +static int SDLCALL +mem_seek(SDL_RWops * context, int offset, int whence) +{ + Uint8 *newpos; + + switch (whence) { + case RW_SEEK_SET: + newpos = context->hidden.mem.base + offset; + break; + case RW_SEEK_CUR: + newpos = context->hidden.mem.here + offset; + break; + case RW_SEEK_END: + newpos = context->hidden.mem.stop + offset; + break; + default: + SDL_SetError("Unknown value for 'whence'"); + return (-1); + } + if (newpos < context->hidden.mem.base) { + newpos = context->hidden.mem.base; + } + if (newpos > context->hidden.mem.stop) { + newpos = context->hidden.mem.stop; + } + context->hidden.mem.here = newpos; + return (context->hidden.mem.here - context->hidden.mem.base); +} +static int SDLCALL +mem_read(SDL_RWops * context, void *ptr, int size, int maxnum) +{ + size_t total_bytes; + size_t mem_available; + + total_bytes = (maxnum * size); + if ((maxnum <= 0) || (size <= 0) + || ((total_bytes / maxnum) != (size_t) size)) { + return 0; + } + + mem_available = (context->hidden.mem.stop - context->hidden.mem.here); + if (total_bytes > mem_available) { + total_bytes = mem_available; + } + + SDL_memcpy(ptr, context->hidden.mem.here, total_bytes); + context->hidden.mem.here += total_bytes; + + return (total_bytes / size); +} +static int SDLCALL +mem_write(SDL_RWops * context, const void *ptr, int size, int num) +{ + if ((context->hidden.mem.here + (num * size)) > context->hidden.mem.stop) { + num = (context->hidden.mem.stop - context->hidden.mem.here) / size; + } + SDL_memcpy(context->hidden.mem.here, ptr, num * size); + context->hidden.mem.here += num * size; + return (num); +} +static int SDLCALL +mem_writeconst(SDL_RWops * context, const void *ptr, int size, int num) +{ + SDL_SetError("Can't write to read-only memory"); + return (-1); +} +static int SDLCALL +mem_close(SDL_RWops * context) +{ + if (context) { + SDL_FreeRW(context); + } + return (0); } @@ -322,233 +354,263 @@ static int SDLCALL mem_close(SDL_RWops *context) * translate unix-style slash-separated filename to mac-style colon-separated * name; return malloced string */ -static char *unix_to_mac(const char *file) -{ - int flen = SDL_strlen(file); - char *path = SDL_malloc(flen + 2); - const char *src = file; - char *dst = path; - if(*src == '/') { - /* really depends on filesystem layout, hope for the best */ - src++; - } else { - /* Check if this is a MacOS path to begin with */ - if(*src != ':') - *dst++ = ':'; /* relative paths begin with ':' */ - } - while(src < file + flen) { - const char *end = SDL_strchr(src, '/'); - int len; - if(!end) - end = file + flen; /* last component */ - len = end - src; - if(len == 0 || (len == 1 && src[0] == '.')) { - /* remove repeated slashes and . */ - } else { - if(len == 2 && src[0] == '.' && src[1] == '.') { - /* replace .. with the empty string */ - } else { - SDL_memcpy(dst, src, len); - dst += len; - } - if(end < file + flen) - *dst++ = ':'; - } - src = end + 1; - } - *dst++ = '\0'; - return path; +static char * +unix_to_mac(const char *file) +{ + int flen = SDL_strlen(file); + char *path = SDL_malloc(flen + 2); + const char *src = file; + char *dst = path; + if (*src == '/') { + /* really depends on filesystem layout, hope for the best */ + src++; + } else { + /* Check if this is a MacOS path to begin with */ + if (*src != ':') + *dst++ = ':'; /* relative paths begin with ':' */ + } + while (src < file + flen) { + const char *end = SDL_strchr(src, '/'); + int len; + if (!end) + end = file + flen; /* last component */ + len = end - src; + if (len == 0 || (len == 1 && src[0] == '.')) { + /* remove repeated slashes and . */ + } else { + if (len == 2 && src[0] == '.' && src[1] == '.') { + /* replace .. with the empty string */ + } else { + SDL_memcpy(dst, src, len); + dst += len; + } + if (end < file + flen) + *dst++ = ':'; + } + src = end + 1; + } + *dst++ = '\0'; + return path; } #endif /* __MACOS__ */ -SDL_RWops *SDL_RWFromFile(const char *file, const char *mode) +SDL_RWops * +SDL_RWFromFile(const char *file, const char *mode) { - SDL_RWops *rwops = NULL; + SDL_RWops *rwops = NULL; #ifdef HAVE_STDIO_H - FILE *fp = NULL; + FILE *fp = NULL; #endif - if ( !file || !*file || !mode || !*mode ) { - SDL_SetError("SDL_RWFromFile(): No file or no mode specified"); - return NULL; - } - + if (!file || !*file || !mode || !*mode) { + SDL_SetError("SDL_RWFromFile(): No file or no mode specified"); + return NULL; + } #if defined(__WIN32__) - rwops = SDL_AllocRW(); - if (!rwops) - return NULL; /* SDL_SetError already setup by SDL_AllocRW() */ - rwops->hidden.win32io.h = INVALID_HANDLE_VALUE; - if (win32_file_open(rwops,file,mode)) { - SDL_FreeRW(rwops); - return NULL; - } - rwops->seek = win32_file_seek; - rwops->read = win32_file_read; - rwops->write = win32_file_write; - rwops->close = win32_file_close; + rwops = SDL_AllocRW(); + if (!rwops) + return NULL; /* SDL_SetError already setup by SDL_AllocRW() */ + rwops->hidden.win32io.h = INVALID_HANDLE_VALUE; + if (win32_file_open(rwops, file, mode)) { + SDL_FreeRW(rwops); + return NULL; + } + rwops->seek = win32_file_seek; + rwops->read = win32_file_read; + rwops->write = win32_file_write; + rwops->close = win32_file_close; #elif HAVE_STDIO_H #ifdef __MACOS__ - { - char *mpath = unix_to_mac(file); - fp = fopen(mpath, mode); - SDL_free(mpath); - } + { + char *mpath = unix_to_mac(file); + fp = fopen(mpath, mode); + SDL_free(mpath); + } #else - fp = fopen(file, mode); + fp = fopen(file, mode); #endif - if ( fp == NULL ) { - SDL_SetError("Couldn't open %s", file); - } else { - rwops = SDL_RWFromFP(fp, 1); - } + if (fp == NULL) { + SDL_SetError("Couldn't open %s", file); + } else { + rwops = SDL_RWFromFP(fp, 1); + } #else - SDL_SetError("SDL not compiled with stdio support"); + SDL_SetError("SDL not compiled with stdio support"); #endif /* !HAVE_STDIO_H */ - return(rwops); + return (rwops); } #ifdef HAVE_STDIO_H -SDL_RWops *SDL_RWFromFP(FILE *fp, int autoclose) -{ - SDL_RWops *rwops = NULL; - - rwops = SDL_AllocRW(); - if ( rwops != NULL ) { - rwops->seek = stdio_seek; - rwops->read = stdio_read; - rwops->write = stdio_write; - rwops->close = stdio_close; - rwops->hidden.stdio.fp = fp; - rwops->hidden.stdio.autoclose = autoclose; - } - return(rwops); +SDL_RWops * +SDL_RWFromFP(FILE * fp, int autoclose) +{ + SDL_RWops *rwops = NULL; + + rwops = SDL_AllocRW(); + if (rwops != NULL) { + rwops->seek = stdio_seek; + rwops->read = stdio_read; + rwops->write = stdio_write; + rwops->close = stdio_close; + rwops->hidden.stdio.fp = fp; + rwops->hidden.stdio.autoclose = autoclose; + } + return (rwops); } #endif /* HAVE_STDIO_H */ -SDL_RWops *SDL_RWFromMem(void *mem, int size) +SDL_RWops * +SDL_RWFromMem(void *mem, int size) { - SDL_RWops *rwops; + SDL_RWops *rwops; - rwops = SDL_AllocRW(); - if ( rwops != NULL ) { - rwops->seek = mem_seek; - rwops->read = mem_read; - rwops->write = mem_write; - rwops->close = mem_close; - rwops->hidden.mem.base = (Uint8 *)mem; - rwops->hidden.mem.here = rwops->hidden.mem.base; - rwops->hidden.mem.stop = rwops->hidden.mem.base+size; - } - return(rwops); + rwops = SDL_AllocRW(); + if (rwops != NULL) { + rwops->seek = mem_seek; + rwops->read = mem_read; + rwops->write = mem_write; + rwops->close = mem_close; + rwops->hidden.mem.base = (Uint8 *) mem; + rwops->hidden.mem.here = rwops->hidden.mem.base; + rwops->hidden.mem.stop = rwops->hidden.mem.base + size; + } + return (rwops); } -SDL_RWops *SDL_RWFromConstMem(const void *mem, int size) +SDL_RWops * +SDL_RWFromConstMem(const void *mem, int size) { - SDL_RWops *rwops; + SDL_RWops *rwops; - rwops = SDL_AllocRW(); - if ( rwops != NULL ) { - rwops->seek = mem_seek; - rwops->read = mem_read; - rwops->write = mem_writeconst; - rwops->close = mem_close; - rwops->hidden.mem.base = (Uint8 *)mem; - rwops->hidden.mem.here = rwops->hidden.mem.base; - rwops->hidden.mem.stop = rwops->hidden.mem.base+size; - } - return(rwops); + rwops = SDL_AllocRW(); + if (rwops != NULL) { + rwops->seek = mem_seek; + rwops->read = mem_read; + rwops->write = mem_writeconst; + rwops->close = mem_close; + rwops->hidden.mem.base = (Uint8 *) mem; + rwops->hidden.mem.here = rwops->hidden.mem.base; + rwops->hidden.mem.stop = rwops->hidden.mem.base + size; + } + return (rwops); } -SDL_RWops *SDL_AllocRW(void) +SDL_RWops * +SDL_AllocRW(void) { - SDL_RWops *area; + SDL_RWops *area; - area = (SDL_RWops *)SDL_malloc(sizeof *area); - if ( area == NULL ) { - SDL_OutOfMemory(); - } - return(area); + area = (SDL_RWops *) SDL_malloc(sizeof *area); + if (area == NULL) { + SDL_OutOfMemory(); + } + return (area); } -void SDL_FreeRW(SDL_RWops *area) +void +SDL_FreeRW(SDL_RWops * area) { - SDL_free(area); + SDL_free(area); } /* Functions for dynamically reading and writing endian-specific values */ -Uint16 SDL_ReadLE16 (SDL_RWops *src) +Uint16 +SDL_ReadLE16(SDL_RWops * src) { - Uint16 value; + Uint16 value; - SDL_RWread(src, &value, (sizeof value), 1); - return(SDL_SwapLE16(value)); + SDL_RWread(src, &value, (sizeof value), 1); + return (SDL_SwapLE16(value)); } -Uint16 SDL_ReadBE16 (SDL_RWops *src) + +Uint16 +SDL_ReadBE16(SDL_RWops * src) { - Uint16 value; + Uint16 value; - SDL_RWread(src, &value, (sizeof value), 1); - return(SDL_SwapBE16(value)); + SDL_RWread(src, &value, (sizeof value), 1); + return (SDL_SwapBE16(value)); } -Uint32 SDL_ReadLE32 (SDL_RWops *src) + +Uint32 +SDL_ReadLE32(SDL_RWops * src) { - Uint32 value; + Uint32 value; - SDL_RWread(src, &value, (sizeof value), 1); - return(SDL_SwapLE32(value)); + SDL_RWread(src, &value, (sizeof value), 1); + return (SDL_SwapLE32(value)); } -Uint32 SDL_ReadBE32 (SDL_RWops *src) + +Uint32 +SDL_ReadBE32(SDL_RWops * src) { - Uint32 value; + Uint32 value; - SDL_RWread(src, &value, (sizeof value), 1); - return(SDL_SwapBE32(value)); + SDL_RWread(src, &value, (sizeof value), 1); + return (SDL_SwapBE32(value)); } -Uint64 SDL_ReadLE64 (SDL_RWops *src) + +Uint64 +SDL_ReadLE64(SDL_RWops * src) { - Uint64 value; + Uint64 value; - SDL_RWread(src, &value, (sizeof value), 1); - return(SDL_SwapLE64(value)); + SDL_RWread(src, &value, (sizeof value), 1); + return (SDL_SwapLE64(value)); } -Uint64 SDL_ReadBE64 (SDL_RWops *src) + +Uint64 +SDL_ReadBE64(SDL_RWops * src) { - Uint64 value; + Uint64 value; - SDL_RWread(src, &value, (sizeof value), 1); - return(SDL_SwapBE64(value)); + SDL_RWread(src, &value, (sizeof value), 1); + return (SDL_SwapBE64(value)); } -int SDL_WriteLE16 (SDL_RWops *dst, Uint16 value) +int +SDL_WriteLE16(SDL_RWops * dst, Uint16 value) { - value = SDL_SwapLE16(value); - return(SDL_RWwrite(dst, &value, (sizeof value), 1)); + value = SDL_SwapLE16(value); + return (SDL_RWwrite(dst, &value, (sizeof value), 1)); } -int SDL_WriteBE16 (SDL_RWops *dst, Uint16 value) + +int +SDL_WriteBE16(SDL_RWops * dst, Uint16 value) { - value = SDL_SwapBE16(value); - return(SDL_RWwrite(dst, &value, (sizeof value), 1)); + value = SDL_SwapBE16(value); + return (SDL_RWwrite(dst, &value, (sizeof value), 1)); } -int SDL_WriteLE32 (SDL_RWops *dst, Uint32 value) + +int +SDL_WriteLE32(SDL_RWops * dst, Uint32 value) { - value = SDL_SwapLE32(value); - return(SDL_RWwrite(dst, &value, (sizeof value), 1)); + value = SDL_SwapLE32(value); + return (SDL_RWwrite(dst, &value, (sizeof value), 1)); } -int SDL_WriteBE32 (SDL_RWops *dst, Uint32 value) + +int +SDL_WriteBE32(SDL_RWops * dst, Uint32 value) { - value = SDL_SwapBE32(value); - return(SDL_RWwrite(dst, &value, (sizeof value), 1)); + value = SDL_SwapBE32(value); + return (SDL_RWwrite(dst, &value, (sizeof value), 1)); } -int SDL_WriteLE64 (SDL_RWops *dst, Uint64 value) + +int +SDL_WriteLE64(SDL_RWops * dst, Uint64 value) { - value = SDL_SwapLE64(value); - return(SDL_RWwrite(dst, &value, (sizeof value), 1)); + value = SDL_SwapLE64(value); + return (SDL_RWwrite(dst, &value, (sizeof value), 1)); } -int SDL_WriteBE64 (SDL_RWops *dst, Uint64 value) + +int +SDL_WriteBE64(SDL_RWops * dst, Uint64 value) { - value = SDL_SwapBE64(value); - return(SDL_RWwrite(dst, &value, (sizeof value), 1)); + value = SDL_SwapBE64(value); + return (SDL_RWwrite(dst, &value, (sizeof value), 1)); } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/hermes/HeadMMX.h b/src/hermes/HeadMMX.h index 11cf6da5b..9dc0e2cff 100644 --- a/src/hermes/HeadMMX.h +++ b/src/hermes/HeadMMX.h @@ -19,24 +19,25 @@ #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif -void STACKCALL ConvertMMX(HermesConverterInterface *); + void STACKCALL ConvertMMX(HermesConverterInterface *); -void STACKCALL ClearMMX_32(HermesClearInterface *); -void STACKCALL ClearMMX_24(HermesClearInterface *); -void STACKCALL ClearMMX_16(HermesClearInterface *); -void STACKCALL ClearMMX_8(HermesClearInterface *); + void STACKCALL ClearMMX_32(HermesClearInterface *); + void STACKCALL ClearMMX_24(HermesClearInterface *); + void STACKCALL ClearMMX_16(HermesClearInterface *); + void STACKCALL ClearMMX_8(HermesClearInterface *); -void ConvertMMXpII32_24RGB888(); -void ConvertMMXpII32_16RGB565(); -void ConvertMMXpII32_16BGR565(); -void ConvertMMXpII32_16RGB555(); -void ConvertMMXpII32_16BGR565(); -void ConvertMMXpII32_16BGR555(); + void ConvertMMXpII32_24RGB888(); + void ConvertMMXpII32_16RGB565(); + void ConvertMMXpII32_16BGR565(); + void ConvertMMXpII32_16RGB555(); + void ConvertMMXpII32_16BGR565(); + void ConvertMMXpII32_16BGR555(); -void ConvertMMXp32_16RGB555(); + void ConvertMMXp32_16RGB555(); #ifdef __cplusplus } @@ -47,29 +48,30 @@ void ConvertMMXp32_16RGB555(); /* Fix the underscore business with ELF compilers */ #if defined(__ELF__) && defined(__GNUC__) - #ifdef __cplusplus - extern "C" { - #endif +#ifdef __cplusplus +extern "C" +{ +#endif - extern void _ConvertMMX(HermesConverterInterface *); - extern void _ConvertMMXpII32_24RGB888(); - extern void _ConvertMMXpII32_16RGB565(); - extern void _ConvertMMXpII32_16BGR565(); - extern void _ConvertMMXpII32_16RGB555(); - extern void _ConvertMMXpII32_16BGR555(); + extern void _ConvertMMX(HermesConverterInterface *); + extern void _ConvertMMXpII32_24RGB888(); + extern void _ConvertMMXpII32_16RGB565(); + extern void _ConvertMMXpII32_16BGR565(); + extern void _ConvertMMXpII32_16RGB555(); + extern void _ConvertMMXpII32_16BGR555(); - #define ConvertMMX _ConvertMMX - #define ConvertMMXpII32_24RGB888 _ConvertMMXpII32_24RGB888 - #define ConvertMMXpII32_16RGB565 _ConvertMMXpII32_16RGB565 - #define ConvertMMXpII32_16BGR565 _ConvertMMXpII32_16BGR565 - #define ConvertMMXpII32_16RGB555 _ConvertMMXpII32_16RGB555 - #define ConvertMMXpII32_16BGR555 _ConvertMMXpII32_16BGR555 +#define ConvertMMX _ConvertMMX +#define ConvertMMXpII32_24RGB888 _ConvertMMXpII32_24RGB888 +#define ConvertMMXpII32_16RGB565 _ConvertMMXpII32_16RGB565 +#define ConvertMMXpII32_16BGR565 _ConvertMMXpII32_16BGR565 +#define ConvertMMXpII32_16RGB555 _ConvertMMXpII32_16RGB555 +#define ConvertMMXpII32_16BGR555 _ConvertMMXpII32_16BGR555 - #ifdef __cplusplus - } - #endif +#ifdef __cplusplus +} +#endif -#endif /* ELF and GNUC */ +#endif /* ELF and GNUC */ @@ -92,9 +94,10 @@ void ConvertMMXp32_16RGB555(); #pragma aux ConvertMMXpII32_16BGR555 "_*" #pragma aux ConvertMMXp32_16RGB555 "_*" -#endif /* WATCOM */ +#endif /* WATCOM */ -#endif /* X86_ASSEMBLER */ +#endif /* X86_ASSEMBLER */ #endif +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/hermes/HeadX86.h b/src/hermes/HeadX86.h index 54e0cc9d7..244fb5fd5 100644 --- a/src/hermes/HeadX86.h +++ b/src/hermes/HeadX86.h @@ -17,54 +17,55 @@ /* Ok, we start with normal function definitions */ #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif -void STACKCALL ConvertX86(HermesConverterInterface *); -void STACKCALL ClearX86_32(HermesClearInterface *); -void STACKCALL ClearX86_24(HermesClearInterface *); -void STACKCALL ClearX86_16(HermesClearInterface *); -void STACKCALL ClearX86_8(HermesClearInterface *); - -int STACKCALL Hermes_X86_CPU(); - -void ConvertX86p32_32BGR888(); -void ConvertX86p32_32RGBA888(); -void ConvertX86p32_32BGRA888(); -void ConvertX86p32_24RGB888(); -void ConvertX86p32_24BGR888(); -void ConvertX86p32_16RGB565(); -void ConvertX86p32_16BGR565(); -void ConvertX86p32_16RGB555(); -void ConvertX86p32_16BGR555(); -void ConvertX86p32_8RGB332(); - -void ConvertX86p16_32RGB888(); -void ConvertX86p16_32BGR888(); -void ConvertX86p16_32RGBA888(); -void ConvertX86p16_32BGRA888(); -void ConvertX86p16_24RGB888(); -void ConvertX86p16_24BGR888(); -void ConvertX86p16_16BGR565(); -void ConvertX86p16_16RGB555(); -void ConvertX86p16_16BGR555(); -void ConvertX86p16_8RGB332(); - -void CopyX86p_4byte(); -void CopyX86p_3byte(); -void CopyX86p_2byte(); -void CopyX86p_1byte(); - -void ConvertX86pI8_32(); -void ConvertX86pI8_24(); -void ConvertX86pI8_16(); - -extern int ConvertX86p16_32RGB888_LUT_X86[512]; -extern int ConvertX86p16_32BGR888_LUT_X86[512]; -extern int ConvertX86p16_32RGBA888_LUT_X86[512]; -extern int ConvertX86p16_32BGRA888_LUT_X86[512]; - + void STACKCALL ConvertX86(HermesConverterInterface *); + void STACKCALL ClearX86_32(HermesClearInterface *); + void STACKCALL ClearX86_24(HermesClearInterface *); + void STACKCALL ClearX86_16(HermesClearInterface *); + void STACKCALL ClearX86_8(HermesClearInterface *); + + int STACKCALL Hermes_X86_CPU(); + + void ConvertX86p32_32BGR888(); + void ConvertX86p32_32RGBA888(); + void ConvertX86p32_32BGRA888(); + void ConvertX86p32_24RGB888(); + void ConvertX86p32_24BGR888(); + void ConvertX86p32_16RGB565(); + void ConvertX86p32_16BGR565(); + void ConvertX86p32_16RGB555(); + void ConvertX86p32_16BGR555(); + void ConvertX86p32_8RGB332(); + + void ConvertX86p16_32RGB888(); + void ConvertX86p16_32BGR888(); + void ConvertX86p16_32RGBA888(); + void ConvertX86p16_32BGRA888(); + void ConvertX86p16_24RGB888(); + void ConvertX86p16_24BGR888(); + void ConvertX86p16_16BGR565(); + void ConvertX86p16_16RGB555(); + void ConvertX86p16_16BGR555(); + void ConvertX86p16_8RGB332(); + + void CopyX86p_4byte(); + void CopyX86p_3byte(); + void CopyX86p_2byte(); + void CopyX86p_1byte(); + + void ConvertX86pI8_32(); + void ConvertX86pI8_24(); + void ConvertX86pI8_16(); + + extern int ConvertX86p16_32RGB888_LUT_X86[512]; + extern int ConvertX86p16_32BGR888_LUT_X86[512]; + extern int ConvertX86p16_32RGBA888_LUT_X86[512]; + extern int ConvertX86p16_32BGRA888_LUT_X86[512]; + #ifdef __cplusplus } #endif @@ -75,57 +76,58 @@ extern int ConvertX86p16_32BGRA888_LUT_X86[512]; /* Now fix up the ELF underscore problem */ #if defined(__ELF__) && defined(__GNUC__) - #ifdef __cplusplus - extern "C" { - #endif +#ifdef __cplusplus +extern "C" +{ +#endif - extern int _Hermes_X86_CPU(); + extern int _Hermes_X86_CPU(); - extern void _ConvertX86(HermesConverterInterface *); + extern void _ConvertX86(HermesConverterInterface *); - extern void _ConvertX86p32_32BGR888(); - extern void _ConvertX86p32_32RGBA888(); - extern void _ConvertX86p32_32BGRA888(); - extern void _ConvertX86p32_24RGB888(); - extern void _ConvertX86p32_24BGR888(); - extern void _ConvertX86p32_16RGB565(); - extern void _ConvertX86p32_16BGR565(); - extern void _ConvertX86p32_16RGB555(); - extern void _ConvertX86p32_16BGR555(); - extern void _ConvertX86p32_8RGB332(); + extern void _ConvertX86p32_32BGR888(); + extern void _ConvertX86p32_32RGBA888(); + extern void _ConvertX86p32_32BGRA888(); + extern void _ConvertX86p32_24RGB888(); + extern void _ConvertX86p32_24BGR888(); + extern void _ConvertX86p32_16RGB565(); + extern void _ConvertX86p32_16BGR565(); + extern void _ConvertX86p32_16RGB555(); + extern void _ConvertX86p32_16BGR555(); + extern void _ConvertX86p32_8RGB332(); - extern void _ConvertX86p16_16BGR565(); - extern void _ConvertX86p16_16RGB555(); - extern void _ConvertX86p16_16BGR555(); - extern void _ConvertX86p16_8RGB332(); + extern void _ConvertX86p16_16BGR565(); + extern void _ConvertX86p16_16RGB555(); + extern void _ConvertX86p16_16BGR555(); + extern void _ConvertX86p16_8RGB332(); - #define Hermes_X86_CPU _Hermes_X86_CPU +#define Hermes_X86_CPU _Hermes_X86_CPU - #define ConvertX86 _ConvertX86 +#define ConvertX86 _ConvertX86 - #define ConvertX86p32_32BGR888 _ConvertX86p32_32BGR888 - #define ConvertX86p32_32RGBA888 _ConvertX86p32_32RGBA888 - #define ConvertX86p32_32BGRA888 _ConvertX86p32_32BGRA888 - #define ConvertX86p32_24RGB888 _ConvertX86p32_24RGB888 - #define ConvertX86p32_24BGR888 _ConvertX86p32_24BGR888 - #define ConvertX86p32_16RGB565 _ConvertX86p32_16RGB565 - #define ConvertX86p32_16BGR565 _ConvertX86p32_16BGR565 - #define ConvertX86p32_16RGB555 _ConvertX86p32_16RGB555 - #define ConvertX86p32_16BGR555 _ConvertX86p32_16BGR555 - #define ConvertX86p32_8RGB332 _ConvertX86p32_8RGB332 +#define ConvertX86p32_32BGR888 _ConvertX86p32_32BGR888 +#define ConvertX86p32_32RGBA888 _ConvertX86p32_32RGBA888 +#define ConvertX86p32_32BGRA888 _ConvertX86p32_32BGRA888 +#define ConvertX86p32_24RGB888 _ConvertX86p32_24RGB888 +#define ConvertX86p32_24BGR888 _ConvertX86p32_24BGR888 +#define ConvertX86p32_16RGB565 _ConvertX86p32_16RGB565 +#define ConvertX86p32_16BGR565 _ConvertX86p32_16BGR565 +#define ConvertX86p32_16RGB555 _ConvertX86p32_16RGB555 +#define ConvertX86p32_16BGR555 _ConvertX86p32_16BGR555 +#define ConvertX86p32_8RGB332 _ConvertX86p32_8RGB332 - #define ConvertX86p16_16BGR565 _ConvertX86p16_16BGR565 - #define ConvertX86p16_16RGB555 _ConvertX86p16_16RGB555 - #define ConvertX86p16_16BGR555 _ConvertX86p16_16BGR555 - #define ConvertX86p16_8RGB332 _ConvertX86p16_8RGB332 +#define ConvertX86p16_16BGR565 _ConvertX86p16_16BGR565 +#define ConvertX86p16_16RGB555 _ConvertX86p16_16RGB555 +#define ConvertX86p16_16BGR555 _ConvertX86p16_16BGR555 +#define ConvertX86p16_8RGB332 _ConvertX86p16_8RGB332 - #ifdef __cplusplus - } - #endif +#ifdef __cplusplus +} +#endif -#endif /* ELF & GNU */ +#endif /* ELF & GNU */ @@ -177,10 +179,11 @@ extern int ConvertX86p16_32BGRA888_LUT_X86[512]; #pragma aux ConvertX86p16_32RGBA888_LUT_X86 "_*" #pragma aux ConvertX86p16_32BGRA888_LUT_X86 "_*" -#endif /* __WATCOMC__ */ +#endif /* __WATCOMC__ */ -#endif /* X86_ASSEMBLER */ +#endif /* X86_ASSEMBLER */ -#endif +#endif +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/joystick/SDL_joystick.c b/src/joystick/SDL_joystick.c index 5984a3200..c230da858 100644 --- a/src/joystick/SDL_joystick.c +++ b/src/joystick/SDL_joystick.c @@ -40,47 +40,49 @@ Uint8 SDL_numjoysticks = 0; SDL_Joystick **SDL_joysticks = NULL; static SDL_Joystick *default_joystick = NULL; -int SDL_JoystickInit(void) +int +SDL_JoystickInit(void) { - int arraylen; - int status; - - SDL_numjoysticks = 0; - status = SDL_SYS_JoystickInit(); - if ( status >= 0 ) { - arraylen = (status+1)*sizeof(*SDL_joysticks); - SDL_joysticks = (SDL_Joystick **)SDL_malloc(arraylen); - if ( SDL_joysticks == NULL ) { - SDL_numjoysticks = 0; - } else { - SDL_memset(SDL_joysticks, 0, arraylen); - SDL_numjoysticks = status; - } - status = 0; - } - default_joystick = NULL; - return(status); + int arraylen; + int status; + + SDL_numjoysticks = 0; + status = SDL_SYS_JoystickInit(); + if (status >= 0) { + arraylen = (status + 1) * sizeof(*SDL_joysticks); + SDL_joysticks = (SDL_Joystick **) SDL_malloc(arraylen); + if (SDL_joysticks == NULL) { + SDL_numjoysticks = 0; + } else { + SDL_memset(SDL_joysticks, 0, arraylen); + SDL_numjoysticks = status; + } + status = 0; + } + default_joystick = NULL; + return (status); } /* * Count the number of joysticks attached to the system */ -int SDL_NumJoysticks(void) +int +SDL_NumJoysticks(void) { - return SDL_numjoysticks; + return SDL_numjoysticks; } /* * Get the implementation dependent name of a joystick */ -const char *SDL_JoystickName(int device_index) +const char * +SDL_JoystickName(int device_index) { - if ( (device_index < 0) || (device_index >= SDL_numjoysticks) ) { - SDL_SetError("There are %d joysticks available", - SDL_numjoysticks); - return(NULL); - } - return(SDL_SYS_JoystickName(device_index)); + if ((device_index < 0) || (device_index >= SDL_numjoysticks)) { + SDL_SetError("There are %d joysticks available", SDL_numjoysticks); + return (NULL); + } + return (SDL_SYS_JoystickName(device_index)); } /* @@ -90,484 +92,509 @@ const char *SDL_JoystickName(int device_index) * * This function returns a joystick identifier, or NULL if an error occurred. */ -SDL_Joystick *SDL_JoystickOpen(int device_index) +SDL_Joystick * +SDL_JoystickOpen(int device_index) { - int i; - SDL_Joystick *joystick; - - if ( (device_index < 0) || (device_index >= SDL_numjoysticks) ) { - SDL_SetError("There are %d joysticks available", - SDL_numjoysticks); - return(NULL); - } - - /* If the joystick is already open, return it */ - for ( i=0; SDL_joysticks[i]; ++i ) { - if ( device_index == SDL_joysticks[i]->index ) { - joystick = SDL_joysticks[i]; - ++joystick->ref_count; - return(joystick); - } - } - - /* Create and initialize the joystick */ - joystick = (SDL_Joystick *)SDL_malloc((sizeof *joystick)); - if ( joystick != NULL ) { - SDL_memset(joystick, 0, (sizeof *joystick)); - joystick->index = device_index; - if ( SDL_SYS_JoystickOpen(joystick) < 0 ) { - SDL_free(joystick); - joystick = NULL; - } else { - if ( joystick->naxes > 0 ) { - joystick->axes = (Sint16 *)SDL_malloc - (joystick->naxes*sizeof(Sint16)); - } - if ( joystick->nhats > 0 ) { - joystick->hats = (Uint8 *)SDL_malloc - (joystick->nhats*sizeof(Uint8)); - } - if ( joystick->nballs > 0 ) { - joystick->balls = (struct balldelta *)SDL_malloc - (joystick->nballs*sizeof(*joystick->balls)); - } - if ( joystick->nbuttons > 0 ) { - joystick->buttons = (Uint8 *)SDL_malloc - (joystick->nbuttons*sizeof(Uint8)); - } - if ( ((joystick->naxes > 0) && !joystick->axes) - || ((joystick->nhats > 0) && !joystick->hats) - || ((joystick->nballs > 0) && !joystick->balls) - || ((joystick->nbuttons > 0) && !joystick->buttons)) { - SDL_OutOfMemory(); - SDL_JoystickClose(joystick); - joystick = NULL; - } - if ( joystick->axes ) { - SDL_memset(joystick->axes, 0, - joystick->naxes*sizeof(Sint16)); - } - if ( joystick->hats ) { - SDL_memset(joystick->hats, 0, - joystick->nhats*sizeof(Uint8)); - } - if ( joystick->balls ) { - SDL_memset(joystick->balls, 0, - joystick->nballs*sizeof(*joystick->balls)); - } - if ( joystick->buttons ) { - SDL_memset(joystick->buttons, 0, - joystick->nbuttons*sizeof(Uint8)); - } - } - } - if ( joystick ) { - /* Add joystick to list */ - ++joystick->ref_count; - SDL_Lock_EventThread(); - for ( i=0; SDL_joysticks[i]; ++i ) - /* Skip to next joystick */; - SDL_joysticks[i] = joystick; - SDL_Unlock_EventThread(); - } - return(joystick); + int i; + SDL_Joystick *joystick; + + if ((device_index < 0) || (device_index >= SDL_numjoysticks)) { + SDL_SetError("There are %d joysticks available", SDL_numjoysticks); + return (NULL); + } + + /* If the joystick is already open, return it */ + for (i = 0; SDL_joysticks[i]; ++i) { + if (device_index == SDL_joysticks[i]->index) { + joystick = SDL_joysticks[i]; + ++joystick->ref_count; + return (joystick); + } + } + + /* Create and initialize the joystick */ + joystick = (SDL_Joystick *) SDL_malloc((sizeof *joystick)); + if (joystick != NULL) { + SDL_memset(joystick, 0, (sizeof *joystick)); + joystick->index = device_index; + if (SDL_SYS_JoystickOpen(joystick) < 0) { + SDL_free(joystick); + joystick = NULL; + } else { + if (joystick->naxes > 0) { + joystick->axes = (Sint16 *) SDL_malloc + (joystick->naxes * sizeof(Sint16)); + } + if (joystick->nhats > 0) { + joystick->hats = (Uint8 *) SDL_malloc + (joystick->nhats * sizeof(Uint8)); + } + if (joystick->nballs > 0) { + joystick->balls = (struct balldelta *) SDL_malloc + (joystick->nballs * sizeof(*joystick->balls)); + } + if (joystick->nbuttons > 0) { + joystick->buttons = (Uint8 *) SDL_malloc + (joystick->nbuttons * sizeof(Uint8)); + } + if (((joystick->naxes > 0) && !joystick->axes) + || ((joystick->nhats > 0) && !joystick->hats) + || ((joystick->nballs > 0) && !joystick->balls) + || ((joystick->nbuttons > 0) && !joystick->buttons)) { + SDL_OutOfMemory(); + SDL_JoystickClose(joystick); + joystick = NULL; + } + if (joystick->axes) { + SDL_memset(joystick->axes, 0, + joystick->naxes * sizeof(Sint16)); + } + if (joystick->hats) { + SDL_memset(joystick->hats, 0, + joystick->nhats * sizeof(Uint8)); + } + if (joystick->balls) { + SDL_memset(joystick->balls, 0, + joystick->nballs * sizeof(*joystick->balls)); + } + if (joystick->buttons) { + SDL_memset(joystick->buttons, 0, + joystick->nbuttons * sizeof(Uint8)); + } + } + } + if (joystick) { + /* Add joystick to list */ + ++joystick->ref_count; + SDL_Lock_EventThread(); + for (i = 0; SDL_joysticks[i]; ++i) + /* Skip to next joystick */ ; + SDL_joysticks[i] = joystick; + SDL_Unlock_EventThread(); + } + return (joystick); } /* * Returns 1 if the joystick has been opened, or 0 if it has not. */ -int SDL_JoystickOpened(int device_index) +int +SDL_JoystickOpened(int device_index) { - int i, opened; - - opened = 0; - for ( i=0; SDL_joysticks[i]; ++i ) { - if ( SDL_joysticks[i]->index == (Uint8)device_index ) { - opened = 1; - break; - } - } - return(opened); + int i, opened; + + opened = 0; + for (i = 0; SDL_joysticks[i]; ++i) { + if (SDL_joysticks[i]->index == (Uint8) device_index) { + opened = 1; + break; + } + } + return (opened); } -static int ValidJoystick(SDL_Joystick **joystick) +static int +ValidJoystick(SDL_Joystick ** joystick) { - int valid; - - if ( *joystick == NULL ) { - *joystick = default_joystick; - } - if ( *joystick == NULL ) { - SDL_SetError("Joystick hasn't been opened yet"); - valid = 0; - } else { - valid = 1; - } - return valid; + int valid; + + if (*joystick == NULL) { + *joystick = default_joystick; + } + if (*joystick == NULL) { + SDL_SetError("Joystick hasn't been opened yet"); + valid = 0; + } else { + valid = 1; + } + return valid; } /* * Get the device index of an opened joystick. */ -int SDL_JoystickIndex(SDL_Joystick *joystick) +int +SDL_JoystickIndex(SDL_Joystick * joystick) { - if ( ! ValidJoystick(&joystick) ) { - return(-1); - } - return(joystick->index); + if (!ValidJoystick(&joystick)) { + return (-1); + } + return (joystick->index); } /* * Get the number of multi-dimensional axis controls on a joystick */ -int SDL_JoystickNumAxes(SDL_Joystick *joystick) +int +SDL_JoystickNumAxes(SDL_Joystick * joystick) { - if ( ! ValidJoystick(&joystick) ) { - return(-1); - } - return(joystick->naxes); + if (!ValidJoystick(&joystick)) { + return (-1); + } + return (joystick->naxes); } /* * Get the number of hats on a joystick */ -int SDL_JoystickNumHats(SDL_Joystick *joystick) +int +SDL_JoystickNumHats(SDL_Joystick * joystick) { - if ( ! ValidJoystick(&joystick) ) { - return(-1); - } - return(joystick->nhats); + if (!ValidJoystick(&joystick)) { + return (-1); + } + return (joystick->nhats); } /* * Get the number of trackballs on a joystick */ -int SDL_JoystickNumBalls(SDL_Joystick *joystick) +int +SDL_JoystickNumBalls(SDL_Joystick * joystick) { - if ( ! ValidJoystick(&joystick) ) { - return(-1); - } - return(joystick->nballs); + if (!ValidJoystick(&joystick)) { + return (-1); + } + return (joystick->nballs); } /* * Get the number of buttons on a joystick */ -int SDL_JoystickNumButtons(SDL_Joystick *joystick) +int +SDL_JoystickNumButtons(SDL_Joystick * joystick) { - if ( ! ValidJoystick(&joystick) ) { - return(-1); - } - return(joystick->nbuttons); + if (!ValidJoystick(&joystick)) { + return (-1); + } + return (joystick->nbuttons); } /* * Get the current state of an axis control on a joystick */ -Sint16 SDL_JoystickGetAxis(SDL_Joystick *joystick, int axis) +Sint16 +SDL_JoystickGetAxis(SDL_Joystick * joystick, int axis) { - Sint16 state; - - if ( ! ValidJoystick(&joystick) ) { - return(0); - } - if ( axis < joystick->naxes ) { - state = joystick->axes[axis]; - } else { - SDL_SetError("Joystick only has %d axes", joystick->naxes); - state = 0; - } - return(state); + Sint16 state; + + if (!ValidJoystick(&joystick)) { + return (0); + } + if (axis < joystick->naxes) { + state = joystick->axes[axis]; + } else { + SDL_SetError("Joystick only has %d axes", joystick->naxes); + state = 0; + } + return (state); } /* * Get the current state of a hat on a joystick */ -Uint8 SDL_JoystickGetHat(SDL_Joystick *joystick, int hat) +Uint8 +SDL_JoystickGetHat(SDL_Joystick * joystick, int hat) { - Uint8 state; - - if ( ! ValidJoystick(&joystick) ) { - return(0); - } - if ( hat < joystick->nhats ) { - state = joystick->hats[hat]; - } else { - SDL_SetError("Joystick only has %d hats", joystick->nhats); - state = 0; - } - return(state); + Uint8 state; + + if (!ValidJoystick(&joystick)) { + return (0); + } + if (hat < joystick->nhats) { + state = joystick->hats[hat]; + } else { + SDL_SetError("Joystick only has %d hats", joystick->nhats); + state = 0; + } + return (state); } /* * Get the ball axis change since the last poll */ -int SDL_JoystickGetBall(SDL_Joystick *joystick, int ball, int *dx, int *dy) +int +SDL_JoystickGetBall(SDL_Joystick * joystick, int ball, int *dx, int *dy) { - int retval; - - if ( ! ValidJoystick(&joystick) ) { - return(-1); - } - - retval = 0; - if ( ball < joystick->nballs ) { - if ( dx ) { - *dx = joystick->balls[ball].dx; - } - if ( dy ) { - *dy = joystick->balls[ball].dy; - } - joystick->balls[ball].dx = 0; - joystick->balls[ball].dy = 0; - } else { - SDL_SetError("Joystick only has %d balls", joystick->nballs); - retval = -1; - } - return(retval); + int retval; + + if (!ValidJoystick(&joystick)) { + return (-1); + } + + retval = 0; + if (ball < joystick->nballs) { + if (dx) { + *dx = joystick->balls[ball].dx; + } + if (dy) { + *dy = joystick->balls[ball].dy; + } + joystick->balls[ball].dx = 0; + joystick->balls[ball].dy = 0; + } else { + SDL_SetError("Joystick only has %d balls", joystick->nballs); + retval = -1; + } + return (retval); } /* * Get the current state of a button on a joystick */ -Uint8 SDL_JoystickGetButton(SDL_Joystick *joystick, int button) +Uint8 +SDL_JoystickGetButton(SDL_Joystick * joystick, int button) { - Uint8 state; - - if ( ! ValidJoystick(&joystick) ) { - return(0); - } - if ( button < joystick->nbuttons ) { - state = joystick->buttons[button]; - } else { - SDL_SetError("Joystick only has %d buttons",joystick->nbuttons); - state = 0; - } - return(state); + Uint8 state; + + if (!ValidJoystick(&joystick)) { + return (0); + } + if (button < joystick->nbuttons) { + state = joystick->buttons[button]; + } else { + SDL_SetError("Joystick only has %d buttons", joystick->nbuttons); + state = 0; + } + return (state); } /* * Close a joystick previously opened with SDL_JoystickOpen() */ -void SDL_JoystickClose(SDL_Joystick *joystick) +void +SDL_JoystickClose(SDL_Joystick * joystick) { - int i; - - if ( ! ValidJoystick(&joystick) ) { - return; - } - - /* First decrement ref count */ - if ( --joystick->ref_count > 0 ) { - return; - } - - /* Lock the event queue - prevent joystick polling */ - SDL_Lock_EventThread(); - - if ( joystick == default_joystick ) { - default_joystick = NULL; - } - SDL_SYS_JoystickClose(joystick); - - /* Remove joystick from list */ - for ( i=0; SDL_joysticks[i]; ++i ) { - if ( joystick == SDL_joysticks[i] ) { - SDL_memcpy(&SDL_joysticks[i], &SDL_joysticks[i+1], - (SDL_numjoysticks-i)*sizeof(joystick)); - break; - } - } - - /* Let the event thread keep running */ - SDL_Unlock_EventThread(); - - /* Free the data associated with this joystick */ - if ( joystick->axes ) { - SDL_free(joystick->axes); - } - if ( joystick->hats ) { - SDL_free(joystick->hats); - } - if ( joystick->balls ) { - SDL_free(joystick->balls); - } - if ( joystick->buttons ) { - SDL_free(joystick->buttons); - } - SDL_free(joystick); + int i; + + if (!ValidJoystick(&joystick)) { + return; + } + + /* First decrement ref count */ + if (--joystick->ref_count > 0) { + return; + } + + /* Lock the event queue - prevent joystick polling */ + SDL_Lock_EventThread(); + + if (joystick == default_joystick) { + default_joystick = NULL; + } + SDL_SYS_JoystickClose(joystick); + + /* Remove joystick from list */ + for (i = 0; SDL_joysticks[i]; ++i) { + if (joystick == SDL_joysticks[i]) { + SDL_memcpy(&SDL_joysticks[i], &SDL_joysticks[i + 1], + (SDL_numjoysticks - i) * sizeof(joystick)); + break; + } + } + + /* Let the event thread keep running */ + SDL_Unlock_EventThread(); + + /* Free the data associated with this joystick */ + if (joystick->axes) { + SDL_free(joystick->axes); + } + if (joystick->hats) { + SDL_free(joystick->hats); + } + if (joystick->balls) { + SDL_free(joystick->balls); + } + if (joystick->buttons) { + SDL_free(joystick->buttons); + } + SDL_free(joystick); } -void SDL_JoystickQuit(void) +void +SDL_JoystickQuit(void) { - /* Stop the event polling */ - SDL_Lock_EventThread(); - SDL_numjoysticks = 0; - SDL_Unlock_EventThread(); - - /* Quit the joystick setup */ - SDL_SYS_JoystickQuit(); - if ( SDL_joysticks ) { - SDL_free(SDL_joysticks); - SDL_joysticks = NULL; - } + /* Stop the event polling */ + SDL_Lock_EventThread(); + SDL_numjoysticks = 0; + SDL_Unlock_EventThread(); + + /* Quit the joystick setup */ + SDL_SYS_JoystickQuit(); + if (SDL_joysticks) { + SDL_free(SDL_joysticks); + SDL_joysticks = NULL; + } } /* These are global for SDL_sysjoystick.c and SDL_events.c */ -int SDL_PrivateJoystickAxis(SDL_Joystick *joystick, Uint8 axis, Sint16 value) +int +SDL_PrivateJoystickAxis(SDL_Joystick * joystick, Uint8 axis, Sint16 value) { - int posted; + int posted; - /* Update internal joystick state */ - joystick->axes[axis] = value; + /* Update internal joystick state */ + joystick->axes[axis] = value; - /* Post the event, if desired */ - posted = 0; + /* Post the event, if desired */ + posted = 0; #if !SDL_EVENTS_DISABLED - if ( SDL_ProcessEvents[SDL_JOYAXISMOTION] == SDL_ENABLE ) { - SDL_Event event; - event.type = SDL_JOYAXISMOTION; - event.jaxis.which = joystick->index; - event.jaxis.axis = axis; - event.jaxis.value = value; - if ( (SDL_EventOK == NULL) || (*SDL_EventOK)(&event) ) { - posted = 1; - SDL_PushEvent(&event); - } - } + if (SDL_ProcessEvents[SDL_JOYAXISMOTION] == SDL_ENABLE) { + SDL_Event event; + event.type = SDL_JOYAXISMOTION; + event.jaxis.which = joystick->index; + event.jaxis.axis = axis; + event.jaxis.value = value; + if ((SDL_EventOK == NULL) + || (*SDL_EventOK) (SDL_EventOKParam, &event)) { + posted = 1; + SDL_PushEvent(&event); + } + } #endif /* !SDL_EVENTS_DISABLED */ - return(posted); + return (posted); } -int SDL_PrivateJoystickHat(SDL_Joystick *joystick, Uint8 hat, Uint8 value) +int +SDL_PrivateJoystickHat(SDL_Joystick * joystick, Uint8 hat, Uint8 value) { - int posted; + int posted; - /* Update internal joystick state */ - joystick->hats[hat] = value; + /* Update internal joystick state */ + joystick->hats[hat] = value; - /* Post the event, if desired */ - posted = 0; + /* Post the event, if desired */ + posted = 0; #if !SDL_EVENTS_DISABLED - if ( SDL_ProcessEvents[SDL_JOYHATMOTION] == SDL_ENABLE ) { - SDL_Event event; - event.jhat.type = SDL_JOYHATMOTION; - event.jhat.which = joystick->index; - event.jhat.hat = hat; - event.jhat.value = value; - if ( (SDL_EventOK == NULL) || (*SDL_EventOK)(&event) ) { - posted = 1; - SDL_PushEvent(&event); - } - } + if (SDL_ProcessEvents[SDL_JOYHATMOTION] == SDL_ENABLE) { + SDL_Event event; + event.jhat.type = SDL_JOYHATMOTION; + event.jhat.which = joystick->index; + event.jhat.hat = hat; + event.jhat.value = value; + if ((SDL_EventOK == NULL) + || (*SDL_EventOK) (SDL_EventOKParam, &event)) { + posted = 1; + SDL_PushEvent(&event); + } + } #endif /* !SDL_EVENTS_DISABLED */ - return(posted); + return (posted); } -int SDL_PrivateJoystickBall(SDL_Joystick *joystick, Uint8 ball, - Sint16 xrel, Sint16 yrel) +int +SDL_PrivateJoystickBall(SDL_Joystick * joystick, Uint8 ball, + Sint16 xrel, Sint16 yrel) { - int posted; + int posted; - /* Update internal mouse state */ - joystick->balls[ball].dx += xrel; - joystick->balls[ball].dy += yrel; + /* Update internal mouse state */ + joystick->balls[ball].dx += xrel; + joystick->balls[ball].dy += yrel; - /* Post the event, if desired */ - posted = 0; + /* Post the event, if desired */ + posted = 0; #if !SDL_EVENTS_DISABLED - if ( SDL_ProcessEvents[SDL_JOYBALLMOTION] == SDL_ENABLE ) { - SDL_Event event; - event.jball.type = SDL_JOYBALLMOTION; - event.jball.which = joystick->index; - event.jball.ball = ball; - event.jball.xrel = xrel; - event.jball.yrel = yrel; - if ( (SDL_EventOK == NULL) || (*SDL_EventOK)(&event) ) { - posted = 1; - SDL_PushEvent(&event); - } - } + if (SDL_ProcessEvents[SDL_JOYBALLMOTION] == SDL_ENABLE) { + SDL_Event event; + event.jball.type = SDL_JOYBALLMOTION; + event.jball.which = joystick->index; + event.jball.ball = ball; + event.jball.xrel = xrel; + event.jball.yrel = yrel; + if ((SDL_EventOK == NULL) + || (*SDL_EventOK) (SDL_EventOKParam, &event)) { + posted = 1; + SDL_PushEvent(&event); + } + } #endif /* !SDL_EVENTS_DISABLED */ - return(posted); + return (posted); } -int SDL_PrivateJoystickButton(SDL_Joystick *joystick, Uint8 button, Uint8 state) +int +SDL_PrivateJoystickButton(SDL_Joystick * joystick, Uint8 button, Uint8 state) { - int posted; + int posted; #if !SDL_EVENTS_DISABLED - SDL_Event event; - - switch ( state ) { - case SDL_PRESSED: - event.type = SDL_JOYBUTTONDOWN; - break; - case SDL_RELEASED: - event.type = SDL_JOYBUTTONUP; - break; - default: - /* Invalid state -- bail */ - return(0); - } + SDL_Event event; + + switch (state) { + case SDL_PRESSED: + event.type = SDL_JOYBUTTONDOWN; + break; + case SDL_RELEASED: + event.type = SDL_JOYBUTTONUP; + break; + default: + /* Invalid state -- bail */ + return (0); + } #endif /* !SDL_EVENTS_DISABLED */ - /* Update internal joystick state */ - joystick->buttons[button] = state; + /* Update internal joystick state */ + joystick->buttons[button] = state; - /* Post the event, if desired */ - posted = 0; + /* Post the event, if desired */ + posted = 0; #if !SDL_EVENTS_DISABLED - if ( SDL_ProcessEvents[event.type] == SDL_ENABLE ) { - event.jbutton.which = joystick->index; - event.jbutton.button = button; - event.jbutton.state = state; - if ( (SDL_EventOK == NULL) || (*SDL_EventOK)(&event) ) { - posted = 1; - SDL_PushEvent(&event); - } - } + if (SDL_ProcessEvents[event.type] == SDL_ENABLE) { + event.jbutton.which = joystick->index; + event.jbutton.button = button; + event.jbutton.state = state; + if ((SDL_EventOK == NULL) + || (*SDL_EventOK) (SDL_EventOKParam, &event)) { + posted = 1; + SDL_PushEvent(&event); + } + } #endif /* !SDL_EVENTS_DISABLED */ - return(posted); + return (posted); } -void SDL_JoystickUpdate(void) +void +SDL_JoystickUpdate(void) { - int i; + int i; - for ( i=0; SDL_joysticks[i]; ++i ) { - SDL_SYS_JoystickUpdate(SDL_joysticks[i]); - } + for (i = 0; SDL_joysticks[i]; ++i) { + SDL_SYS_JoystickUpdate(SDL_joysticks[i]); + } } -int SDL_JoystickEventState(int state) +int +SDL_JoystickEventState(int state) { #if SDL_EVENTS_DISABLED - return SDL_IGNORE; + return SDL_IGNORE; #else - const Uint8 event_list[] = { - SDL_JOYAXISMOTION, SDL_JOYBALLMOTION, SDL_JOYHATMOTION, - SDL_JOYBUTTONDOWN, SDL_JOYBUTTONUP, - }; - unsigned int i; - - switch (state) { - case SDL_QUERY: - state = SDL_IGNORE; - for ( i=0; iindex)); + ULONG temp, i; + D(bug("Opening joystick %ld\n", joystick->index)); - if(!(joystick->hwdata=SDL_malloc(sizeof(struct joystick_hwdata)))) - return -1; + if (!(joystick->hwdata = SDL_malloc(sizeof(struct joystick_hwdata)))) + return -1; /* This loop is to check if the controller is a joypad */ - for(i=0;i<20;i++) - { - temp=ReadJoyPort(joystick->index^1); // fix to invert amiga joyports - WaitTOF(); - } + for (i = 0; i < 20; i++) { + temp = ReadJoyPort(joystick->index ^ 1); // fix to invert amiga joyports + WaitTOF(); + } - if((temp&JP_TYPE_MASK)==JP_TYPE_GAMECTLR) - joystick->nbuttons=7; - else - joystick->nbuttons=3; + if ((temp & JP_TYPE_MASK) == JP_TYPE_GAMECTLR) + joystick->nbuttons = 7; + else + joystick->nbuttons = 3; - joystick->nhats=0; - joystick->nballs=0; - joystick->naxes=2; - joystick->hwdata->joystate=0L; + joystick->nhats = 0; + joystick->nballs = 0; + joystick->naxes = 2; + joystick->hwdata->joystate = 0L; - return 0; + return 0; } /* Function to update the state of a joystick - called as a device poll. @@ -143,91 +140,80 @@ int SDL_SYS_JoystickOpen(SDL_Joystick *joystick) * but instead should call SDL_PrivateJoystick*() to deliver events * and update joystick device state. */ -void SDL_SYS_JoystickUpdate(SDL_Joystick *joystick) +void +SDL_SYS_JoystickUpdate(SDL_Joystick * joystick) { - ULONG data; - int i; - - if(joystick->index<2) - { - data=ReadJoyPort(joystick->index); - - if(data&JP_DIRECTION_MASK) - { - if(data&JPF_JOY_DOWN) - { - if(!(joystick->hwdata->joystate&JPF_JOY_DOWN)) - SDL_PrivateJoystickAxis(joystick,0,127); - } - else if(data&JPF_JOY_UP) - { - if(!(joystick->hwdata->joystate&JPF_JOY_UP)) - SDL_PrivateJoystickAxis(joystick,0,-127); - } - else if(joystick->hwdata->joystate&(JPF_JOY_UP|JPF_JOY_DOWN)) - SDL_PrivateJoystickAxis(joystick,0,0); - - if(data&JPF_JOY_LEFT) - { - if(!(joystick->hwdata->joystate&JPF_JOY_LEFT)) - SDL_PrivateJoystickAxis(joystick,1,-127); - } - else if(data&JPF_JOY_RIGHT) - { - if(!(joystick->hwdata->joystate&JPF_JOY_RIGHT)) - SDL_PrivateJoystickAxis(joystick,1,127); - } - else if(joystick->hwdata->joystate&(JPF_JOY_LEFT|JPF_JOY_RIGHT)) - SDL_PrivateJoystickAxis(joystick,1,0); - } - else if(joystick->hwdata->joystate&(JPF_JOY_LEFT|JPF_JOY_RIGHT)) - { - SDL_PrivateJoystickAxis(joystick,1,0); - } - else if(joystick->hwdata->joystate&(JPF_JOY_UP|JPF_JOY_DOWN)) - { - SDL_PrivateJoystickAxis(joystick,0,0); - } - - for(i=0;inbuttons;i++) - { - if( (data&joybut[i]) ) - { - if(i==1) - data&=(~(joybut[2])); - - if(!(joystick->hwdata->joystate&joybut[i])) - SDL_PrivateJoystickButton(joystick,i,SDL_PRESSED); - } - else if(joystick->hwdata->joystate&joybut[i]) - SDL_PrivateJoystickButton(joystick,i,SDL_RELEASED); - } - - joystick->hwdata->joystate=data; - } - - return; + ULONG data; + int i; + + if (joystick->index < 2) { + data = ReadJoyPort(joystick->index); + + if (data & JP_DIRECTION_MASK) { + if (data & JPF_JOY_DOWN) { + if (!(joystick->hwdata->joystate & JPF_JOY_DOWN)) + SDL_PrivateJoystickAxis(joystick, 0, 127); + } else if (data & JPF_JOY_UP) { + if (!(joystick->hwdata->joystate & JPF_JOY_UP)) + SDL_PrivateJoystickAxis(joystick, 0, -127); + } else if (joystick->hwdata-> + joystate & (JPF_JOY_UP | JPF_JOY_DOWN)) + SDL_PrivateJoystickAxis(joystick, 0, 0); + + if (data & JPF_JOY_LEFT) { + if (!(joystick->hwdata->joystate & JPF_JOY_LEFT)) + SDL_PrivateJoystickAxis(joystick, 1, -127); + } else if (data & JPF_JOY_RIGHT) { + if (!(joystick->hwdata->joystate & JPF_JOY_RIGHT)) + SDL_PrivateJoystickAxis(joystick, 1, 127); + } else if (joystick->hwdata-> + joystate & (JPF_JOY_LEFT | JPF_JOY_RIGHT)) + SDL_PrivateJoystickAxis(joystick, 1, 0); + } else if (joystick->hwdata-> + joystate & (JPF_JOY_LEFT | JPF_JOY_RIGHT)) { + SDL_PrivateJoystickAxis(joystick, 1, 0); + } else if (joystick->hwdata->joystate & (JPF_JOY_UP | JPF_JOY_DOWN)) { + SDL_PrivateJoystickAxis(joystick, 0, 0); + } + + for (i = 0; i < joystick->nbuttons; i++) { + if ((data & joybut[i])) { + if (i == 1) + data &= (~(joybut[2])); + + if (!(joystick->hwdata->joystate & joybut[i])) + SDL_PrivateJoystickButton(joystick, i, SDL_PRESSED); + } else if (joystick->hwdata->joystate & joybut[i]) + SDL_PrivateJoystickButton(joystick, i, SDL_RELEASED); + } + + joystick->hwdata->joystate = data; + } + + return; } /* Function to close a joystick after use */ -void SDL_SYS_JoystickClose(SDL_Joystick *joystick) +void +SDL_SYS_JoystickClose(SDL_Joystick * joystick) { - if(joystick->hwdata) - SDL_free(joystick->hwdata); - return; + if (joystick->hwdata) + SDL_free(joystick->hwdata); + return; } /* Function to perform any system-specific joystick related cleanup */ -void SDL_SYS_JoystickQuit(void) +void +SDL_SYS_JoystickQuit(void) { - if(LowLevelBase) - { - CloseLibrary(LowLevelBase); - LowLevelBase=NULL; - SDL_numjoysticks=0; - } - return; + if (LowLevelBase) { + CloseLibrary(LowLevelBase); + LowLevelBase = NULL; + SDL_numjoysticks = 0; + } + return; } #endif /* SDL_JOYSTICK_AMIGA */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/joystick/beos/SDL_bejoystick.cc b/src/joystick/beos/SDL_bejoystick.cc index 7c52b8664..863a9b2d0 100644 --- a/src/joystick/beos/SDL_bejoystick.cc +++ b/src/joystick/beos/SDL_bejoystick.cc @@ -28,7 +28,8 @@ #include #include -extern "C" { +extern "C" +{ #include "SDL_joystick.h" #include "../SDL_sysjoystick.h" @@ -36,202 +37,204 @@ extern "C" { /* The maximum number of joysticks we'll detect */ -#define MAX_JOYSTICKS 16 +#define MAX_JOYSTICKS 16 /* A list of available joysticks */ -static char *SDL_joyport[MAX_JOYSTICKS]; -static char *SDL_joyname[MAX_JOYSTICKS]; + static char *SDL_joyport[MAX_JOYSTICKS]; + static char *SDL_joyname[MAX_JOYSTICKS]; /* The private structure used to keep track of a joystick */ -struct joystick_hwdata { - BJoystick *stick; - uint8 *new_hats; - int16 *new_axes; -}; + struct joystick_hwdata + { + BJoystick *stick; + uint8 *new_hats; + int16 *new_axes; + }; /* Function to scan the system for joysticks. * This function should set SDL_numjoysticks to the number of available * joysticks. Joystick 0 should be the system default joystick. * It should return 0, or -1 on an unrecoverable fatal error. */ -int SDL_SYS_JoystickInit(void) -{ - BJoystick joystick; - int numjoysticks; - int i; - int32 nports; - char name[B_OS_NAME_LENGTH]; - - /* Search for attached joysticks */ - nports = joystick.CountDevices(); - numjoysticks = 0; - SDL_memset(SDL_joyport, 0, (sizeof SDL_joyport)); - SDL_memset(SDL_joyname, 0, (sizeof SDL_joyname)); - for ( i=0; (SDL_numjoysticks < MAX_JOYSTICKS) && (i < nports); ++i ) { - if ( joystick.GetDeviceName(i, name) == B_OK ) { - if ( joystick.Open(name) != B_ERROR ) { - BString stick_name; - joystick.GetControllerName(&stick_name); - SDL_joyport[numjoysticks] = strdup(name); - SDL_joyname[numjoysticks] = - strdup(stick_name.String()); - numjoysticks++; - joystick.Close(); - } - } - } - return(numjoysticks); -} + int SDL_SYS_JoystickInit(void) + { + BJoystick joystick; + int numjoysticks; + int i; + int32 nports; + char name[B_OS_NAME_LENGTH]; + + /* Search for attached joysticks */ + nports = joystick.CountDevices(); + numjoysticks = 0; + SDL_memset(SDL_joyport, 0, (sizeof SDL_joyport)); + SDL_memset(SDL_joyname, 0, (sizeof SDL_joyname)); + for (i = 0; (SDL_numjoysticks < MAX_JOYSTICKS) && (i < nports); ++i) + { + if (joystick.GetDeviceName(i, name) == B_OK) { + if (joystick.Open(name) != B_ERROR) { + BString stick_name; + joystick.GetControllerName(&stick_name); + SDL_joyport[numjoysticks] = strdup(name); + SDL_joyname[numjoysticks] = strdup(stick_name.String()); + numjoysticks++; + joystick.Close(); + } + } + } + return (numjoysticks); + } /* Function to get the device-dependent name of a joystick */ -const char *SDL_SYS_JoystickName(int index) -{ - return SDL_joyname[index]; -} + const char *SDL_SYS_JoystickName(int index) + { + return SDL_joyname[index]; + } /* Function to open a joystick for use. The joystick to open is specified by the index field of the joystick. This should fill the nbuttons and naxes fields of the joystick structure. It returns 0, or -1 if there is an error. */ -int SDL_SYS_JoystickOpen(SDL_Joystick *joystick) -{ - BJoystick *stick; - - /* Create the joystick data structure */ - joystick->hwdata = (struct joystick_hwdata *) - SDL_malloc(sizeof(*joystick->hwdata)); - if ( joystick->hwdata == NULL ) { - SDL_OutOfMemory(); - return(-1); - } - SDL_memset(joystick->hwdata, 0, sizeof(*joystick->hwdata)); - stick = new BJoystick; - joystick->hwdata->stick = stick; - - /* Open the requested joystick for use */ - if ( stick->Open(SDL_joyport[joystick->index]) == B_ERROR ) { - SDL_SetError("Unable to open joystick"); - SDL_SYS_JoystickClose(joystick); - return(-1); - } - - /* Set the joystick to calibrated mode */ - stick->EnableCalibration(); - - /* Get the number of buttons, hats, and axes on the joystick */ - joystick->nbuttons = stick->CountButtons(); - joystick->naxes = stick->CountAxes(); - joystick->nhats = stick->CountHats(); - - joystick->hwdata->new_axes = (int16 *) - SDL_malloc(joystick->naxes*sizeof(int16)); - joystick->hwdata->new_hats = (uint8 *) - SDL_malloc(joystick->nhats*sizeof(uint8)); - if ( ! joystick->hwdata->new_hats || ! joystick->hwdata->new_axes ) { - SDL_OutOfMemory(); - SDL_SYS_JoystickClose(joystick); - return(-1); - } - - /* We're done! */ - return(0); -} + int SDL_SYS_JoystickOpen(SDL_Joystick * joystick) + { + BJoystick *stick; + + /* Create the joystick data structure */ + joystick->hwdata = (struct joystick_hwdata *) + SDL_malloc(sizeof(*joystick->hwdata)); + if (joystick->hwdata == NULL) { + SDL_OutOfMemory(); + return (-1); + } + SDL_memset(joystick->hwdata, 0, sizeof(*joystick->hwdata)); + stick = new BJoystick; + joystick->hwdata->stick = stick; + + /* Open the requested joystick for use */ + if (stick->Open(SDL_joyport[joystick->index]) == B_ERROR) { + SDL_SetError("Unable to open joystick"); + SDL_SYS_JoystickClose(joystick); + return (-1); + } + + /* Set the joystick to calibrated mode */ + stick->EnableCalibration(); + + /* Get the number of buttons, hats, and axes on the joystick */ + joystick->nbuttons = stick->CountButtons(); + joystick->naxes = stick->CountAxes(); + joystick->nhats = stick->CountHats(); + + joystick->hwdata->new_axes = (int16 *) + SDL_malloc(joystick->naxes * sizeof(int16)); + joystick->hwdata->new_hats = (uint8 *) + SDL_malloc(joystick->nhats * sizeof(uint8)); + if (!joystick->hwdata->new_hats || !joystick->hwdata->new_axes) { + SDL_OutOfMemory(); + SDL_SYS_JoystickClose(joystick); + return (-1); + } + + /* We're done! */ + return (0); + } /* Function to update the state of a joystick - called as a device poll. * This function shouldn't update the joystick structure directly, * but instead should call SDL_PrivateJoystick*() to deliver events * and update joystick device state. */ -void SDL_SYS_JoystickUpdate(SDL_Joystick *joystick) -{ - static const Uint8 hat_map[9] = { - SDL_HAT_CENTERED, - SDL_HAT_UP, - SDL_HAT_RIGHTUP, - SDL_HAT_RIGHT, - SDL_HAT_RIGHTDOWN, - SDL_HAT_DOWN, - SDL_HAT_LEFTDOWN, - SDL_HAT_LEFT, - SDL_HAT_LEFTUP - }; - const int JITTER = (32768/10); /* 10% jitter threshold (ok?) */ - - BJoystick *stick; - int i, change; - int16 *axes; - uint8 *hats; - uint32 buttons; - - /* Set up data pointers */ - stick = joystick->hwdata->stick; - axes = joystick->hwdata->new_axes; - hats = joystick->hwdata->new_hats; - - /* Get the new joystick state */ - stick->Update(); - stick->GetAxisValues(axes); - stick->GetHatValues(hats); - buttons = stick->ButtonValues(); - - /* Generate axis motion events */ - for ( i=0; inaxes; ++i ) { - change = ((int32)axes[i] - joystick->axes[i]); - if ( (change > JITTER) || (change < -JITTER) ) { - SDL_PrivateJoystickAxis(joystick, i, axes[i]); - } - } - - /* Generate hat change events */ - for ( i=0; inhats; ++i ) { - if ( hats[i] != joystick->hats[i] ) { - SDL_PrivateJoystickHat(joystick, i, hat_map[hats[i]]); - } - } - - /* Generate button events */ - for ( i=0; inbuttons; ++i ) { - if ( (buttons&0x01) != joystick->buttons[i] ) { - SDL_PrivateJoystickButton(joystick, i, (buttons&0x01)); - } - buttons >>= 1; - } -} + void SDL_SYS_JoystickUpdate(SDL_Joystick * joystick) + { + static const Uint8 hat_map[9] = { + SDL_HAT_CENTERED, + SDL_HAT_UP, + SDL_HAT_RIGHTUP, + SDL_HAT_RIGHT, + SDL_HAT_RIGHTDOWN, + SDL_HAT_DOWN, + SDL_HAT_LEFTDOWN, + SDL_HAT_LEFT, + SDL_HAT_LEFTUP + }; + const int JITTER = (32768 / 10); /* 10% jitter threshold (ok?) */ + + BJoystick *stick; + int i, change; + int16 *axes; + uint8 *hats; + uint32 buttons; + + /* Set up data pointers */ + stick = joystick->hwdata->stick; + axes = joystick->hwdata->new_axes; + hats = joystick->hwdata->new_hats; + + /* Get the new joystick state */ + stick->Update(); + stick->GetAxisValues(axes); + stick->GetHatValues(hats); + buttons = stick->ButtonValues(); + + /* Generate axis motion events */ + for (i = 0; i < joystick->naxes; ++i) { + change = ((int32) axes[i] - joystick->axes[i]); + if ((change > JITTER) || (change < -JITTER)) { + SDL_PrivateJoystickAxis(joystick, i, axes[i]); + } + } + + /* Generate hat change events */ + for (i = 0; i < joystick->nhats; ++i) { + if (hats[i] != joystick->hats[i]) { + SDL_PrivateJoystickHat(joystick, i, hat_map[hats[i]]); + } + } + + /* Generate button events */ + for (i = 0; i < joystick->nbuttons; ++i) { + if ((buttons & 0x01) != joystick->buttons[i]) { + SDL_PrivateJoystickButton(joystick, i, (buttons & 0x01)); + } + buttons >>= 1; + } + } /* Function to close a joystick after use */ -void SDL_SYS_JoystickClose(SDL_Joystick *joystick) -{ - if ( joystick->hwdata ) { - joystick->hwdata->stick->Close(); - delete joystick->hwdata->stick; - if ( joystick->hwdata->new_hats ) { - SDL_free(joystick->hwdata->new_hats); - } - if ( joystick->hwdata->new_axes ) { - SDL_free(joystick->hwdata->new_axes); - } - SDL_free(joystick->hwdata); - joystick->hwdata = NULL; - } -} + void SDL_SYS_JoystickClose(SDL_Joystick * joystick) + { + if (joystick->hwdata) { + joystick->hwdata->stick->Close(); + delete joystick->hwdata->stick; + if (joystick->hwdata->new_hats) { + SDL_free(joystick->hwdata->new_hats); + } + if (joystick->hwdata->new_axes) { + SDL_free(joystick->hwdata->new_axes); + } + SDL_free(joystick->hwdata); + joystick->hwdata = NULL; + } + } /* Function to perform any system-specific joystick related cleanup */ -void SDL_SYS_JoystickQuit(void) -{ - int i; + void SDL_SYS_JoystickQuit(void) + { + int i; - for ( i=0; SDL_joyport[i]; ++i ) { - SDL_free(SDL_joyport[i]); - } - SDL_joyport[0] = NULL; + for (i = 0; SDL_joyport[i]; ++i) { + SDL_free(SDL_joyport[i]); + } + SDL_joyport[0] = NULL; - for ( i=0; SDL_joyname[i]; ++i ) { - SDL_free(SDL_joyname[i]); - } - SDL_joyname[0] = NULL; -} + for (i = 0; SDL_joyname[i]; ++i) { + SDL_free(SDL_joyname[i]); + } + SDL_joyname[0] = NULL; + } -}; // extern "C" +}; // extern "C" #endif /* SDL_JOYSTICK_BEOS */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/joystick/bsd/SDL_sysjoystick.c b/src/joystick/bsd/SDL_sysjoystick.c index 0c7043aca..e6866b182 100644 --- a/src/joystick/bsd/SDL_sysjoystick.c +++ b/src/joystick/bsd/SDL_sysjoystick.c @@ -74,62 +74,69 @@ #define MAX_JOY_JOYS 2 #define MAX_JOYS (MAX_UHID_JOYS + MAX_JOY_JOYS) -struct report { - struct usb_ctl_report *buf; /* Buffer */ - size_t size; /* Buffer size */ - int rid; /* Report ID */ - enum { - SREPORT_UNINIT, - SREPORT_CLEAN, - SREPORT_DIRTY - } status; +struct report +{ + struct usb_ctl_report *buf; /* Buffer */ + size_t size; /* Buffer size */ + int rid; /* Report ID */ + enum + { + SREPORT_UNINIT, + SREPORT_CLEAN, + SREPORT_DIRTY + } status; }; -static struct { - int uhid_report; - hid_kind_t kind; - const char *name; +static struct +{ + int uhid_report; + hid_kind_t kind; + const char *name; } const repinfo[] = { - { UHID_INPUT_REPORT, hid_input, "input" }, - { UHID_OUTPUT_REPORT, hid_output, "output" }, - { UHID_FEATURE_REPORT, hid_feature, "feature" } + {UHID_INPUT_REPORT, hid_input, "input"}, + {UHID_OUTPUT_REPORT, hid_output, "output"}, + {UHID_FEATURE_REPORT, hid_feature, "feature"} }; -enum { - REPORT_INPUT = 0, - REPORT_OUTPUT = 1, - REPORT_FEATURE = 2 +enum +{ + REPORT_INPUT = 0, + REPORT_OUTPUT = 1, + REPORT_FEATURE = 2 }; -enum { - JOYAXE_X, - JOYAXE_Y, - JOYAXE_Z, - JOYAXE_SLIDER, - JOYAXE_WHEEL, - JOYAXE_RX, - JOYAXE_RY, - JOYAXE_RZ, - JOYAXE_count +enum +{ + JOYAXE_X, + JOYAXE_Y, + JOYAXE_Z, + JOYAXE_SLIDER, + JOYAXE_WHEEL, + JOYAXE_RX, + JOYAXE_RY, + JOYAXE_RZ, + JOYAXE_count }; -struct joystick_hwdata { - int fd; - char *path; - enum { - BSDJOY_UHID, /* uhid(4) */ - BSDJOY_JOY /* joy(4) */ - } type; - struct report_desc *repdesc; - struct report inreport; - int axis_map[JOYAXE_count]; /* map present JOYAXE_* to 0,1,..*/ +struct joystick_hwdata +{ + int fd; + char *path; + enum + { + BSDJOY_UHID, /* uhid(4) */ + BSDJOY_JOY /* joy(4) */ + } type; + struct report_desc *repdesc; + struct report inreport; + int axis_map[JOYAXE_count]; /* map present JOYAXE_* to 0,1,.. */ }; static char *joynames[MAX_JOYS]; static char *joydevnames[MAX_JOYS]; -static int report_alloc(struct report *, struct report_desc *, int); -static void report_free(struct report *); +static int report_alloc(struct report *, struct report_desc *, int); +static void report_free(struct report *); #ifdef USBHID_UCR_DATA #define REP_BUF_DATA(rep) ((rep)->buf->ucr_data) @@ -140,52 +147,52 @@ static void report_free(struct report *); int SDL_SYS_JoystickInit(void) { - char s[16]; - int i, fd; - - SDL_numjoysticks = 0; - - SDL_memset(joynames, 0, sizeof(joynames)); - SDL_memset(joydevnames, 0, sizeof(joydevnames)); - - for (i = 0; i < MAX_UHID_JOYS; i++) { - SDL_Joystick nj; - - SDL_snprintf(s, SDL_arraysize(s), "/dev/uhid%d", i); - - nj.index = SDL_numjoysticks; - joynames[nj.index] = strdup(s); - - if (SDL_SYS_JoystickOpen(&nj) == 0) { - SDL_SYS_JoystickClose(&nj); - SDL_numjoysticks++; - } else { - SDL_free(joynames[nj.index]); - joynames[nj.index] = NULL; - } - } - for (i = 0; i < MAX_JOY_JOYS; i++) { - SDL_snprintf(s, SDL_arraysize(s), "/dev/joy%d", i); - fd = open(s, O_RDONLY); - if (fd != -1) { - joynames[SDL_numjoysticks++] = strdup(s); - close(fd); - } - } - - /* Read the default USB HID usage table. */ - hid_init(NULL); - - return (SDL_numjoysticks); + char s[16]; + int i, fd; + + SDL_numjoysticks = 0; + + SDL_memset(joynames, 0, sizeof(joynames)); + SDL_memset(joydevnames, 0, sizeof(joydevnames)); + + for (i = 0; i < MAX_UHID_JOYS; i++) { + SDL_Joystick nj; + + SDL_snprintf(s, SDL_arraysize(s), "/dev/uhid%d", i); + + nj.index = SDL_numjoysticks; + joynames[nj.index] = strdup(s); + + if (SDL_SYS_JoystickOpen(&nj) == 0) { + SDL_SYS_JoystickClose(&nj); + SDL_numjoysticks++; + } else { + SDL_free(joynames[nj.index]); + joynames[nj.index] = NULL; + } + } + for (i = 0; i < MAX_JOY_JOYS; i++) { + SDL_snprintf(s, SDL_arraysize(s), "/dev/joy%d", i); + fd = open(s, O_RDONLY); + if (fd != -1) { + joynames[SDL_numjoysticks++] = strdup(s); + close(fd); + } + } + + /* Read the default USB HID usage table. */ + hid_init(NULL); + + return (SDL_numjoysticks); } const char * SDL_SYS_JoystickName(int index) { - if (joydevnames[index] != NULL) { - return (joydevnames[index]); - } - return (joynames[index]); + if (joydevnames[index] != NULL) { + return (joydevnames[index]); + } + return (joynames[index]); } static int @@ -194,387 +201,398 @@ usage_to_joyaxe(unsigned usage) int joyaxe; switch (usage) { case HUG_X: - joyaxe = JOYAXE_X; break; + joyaxe = JOYAXE_X; + break; case HUG_Y: - joyaxe = JOYAXE_Y; break; + joyaxe = JOYAXE_Y; + break; case HUG_Z: - joyaxe = JOYAXE_Z; break; + joyaxe = JOYAXE_Z; + break; case HUG_SLIDER: - joyaxe = JOYAXE_SLIDER; break; + joyaxe = JOYAXE_SLIDER; + break; case HUG_WHEEL: - joyaxe = JOYAXE_WHEEL; break; + joyaxe = JOYAXE_WHEEL; + break; case HUG_RX: - joyaxe = JOYAXE_RX; break; + joyaxe = JOYAXE_RX; + break; case HUG_RY: - joyaxe = JOYAXE_RY; break; + joyaxe = JOYAXE_RY; + break; case HUG_RZ: - joyaxe = JOYAXE_RZ; break; + joyaxe = JOYAXE_RZ; + break; default: - joyaxe = -1; + joyaxe = -1; } - return joyaxe; + return joyaxe; } static unsigned hatval_to_sdl(Sint32 hatval) { static const unsigned hat_dir_map[8] = { - SDL_HAT_UP, SDL_HAT_RIGHTUP, SDL_HAT_RIGHT, SDL_HAT_RIGHTDOWN, - SDL_HAT_DOWN, SDL_HAT_LEFTDOWN, SDL_HAT_LEFT, SDL_HAT_LEFTUP + SDL_HAT_UP, SDL_HAT_RIGHTUP, SDL_HAT_RIGHT, SDL_HAT_RIGHTDOWN, + SDL_HAT_DOWN, SDL_HAT_LEFTDOWN, SDL_HAT_LEFT, SDL_HAT_LEFTUP }; unsigned result; - if ((hatval & 7) == hatval) - result = hat_dir_map[hatval]; - else - result = SDL_HAT_CENTERED; + if ((hatval & 7) == hatval) + result = hat_dir_map[hatval]; + else + result = SDL_HAT_CENTERED; return result; } int -SDL_SYS_JoystickOpen(SDL_Joystick *joy) +SDL_SYS_JoystickOpen(SDL_Joystick * joy) { - char *path = joynames[joy->index]; - struct joystick_hwdata *hw; - struct hid_item hitem; - struct hid_data *hdata; - struct report *rep; - int fd; - int i; - - fd = open(path, O_RDONLY); - if (fd == -1) { - SDL_SetError("%s: %s", path, strerror(errno)); - return (-1); - } - - hw = (struct joystick_hwdata *)SDL_malloc(sizeof(struct joystick_hwdata)); - if (hw == NULL) { - SDL_OutOfMemory(); - close(fd); - return (-1); - } - joy->hwdata = hw; - hw->fd = fd; - hw->path = strdup(path); - if (! SDL_strncmp(path, "/dev/joy", 8)) { - hw->type = BSDJOY_JOY; - joy->naxes = 2; - joy->nbuttons = 2; - joy->nhats = 0; - joy->nballs = 0; - joydevnames[joy->index] = strdup("Gameport joystick"); - goto usbend; - } else { - hw->type = BSDJOY_UHID; - } - - { - int ax; - for (ax = 0; ax < JOYAXE_count; ax++) - hw->axis_map[ax] = -1; - } - hw->repdesc = hid_get_report_desc(fd); - if (hw->repdesc == NULL) { - SDL_SetError("%s: USB_GET_REPORT_DESC: %s", hw->path, - strerror(errno)); - goto usberr; - } - - rep = &hw->inreport; - if (ioctl(fd, USB_GET_REPORT_ID, &rep->rid) < 0) { - rep->rid = -1; /* XXX */ - } - if (report_alloc(rep, hw->repdesc, REPORT_INPUT) < 0) { - goto usberr; - } - if (rep->size <= 0) { - SDL_SetError("%s: Input report descriptor has invalid length", - hw->path); - goto usberr; - } + char *path = joynames[joy->index]; + struct joystick_hwdata *hw; + struct hid_item hitem; + struct hid_data *hdata; + struct report *rep; + int fd; + int i; + + fd = open(path, O_RDONLY); + if (fd == -1) { + SDL_SetError("%s: %s", path, strerror(errno)); + return (-1); + } + + hw = (struct joystick_hwdata *) + SDL_malloc(sizeof(struct joystick_hwdata)); + if (hw == NULL) { + SDL_OutOfMemory(); + close(fd); + return (-1); + } + joy->hwdata = hw; + hw->fd = fd; + hw->path = strdup(path); + if (!SDL_strncmp(path, "/dev/joy", 8)) { + hw->type = BSDJOY_JOY; + joy->naxes = 2; + joy->nbuttons = 2; + joy->nhats = 0; + joy->nballs = 0; + joydevnames[joy->index] = strdup("Gameport joystick"); + goto usbend; + } else { + hw->type = BSDJOY_UHID; + } + + { + int ax; + for (ax = 0; ax < JOYAXE_count; ax++) + hw->axis_map[ax] = -1; + } + hw->repdesc = hid_get_report_desc(fd); + if (hw->repdesc == NULL) { + SDL_SetError("%s: USB_GET_REPORT_DESC: %s", hw->path, + strerror(errno)); + goto usberr; + } + rep = &hw->inreport; + if (ioctl(fd, USB_GET_REPORT_ID, &rep->rid) < 0) { + rep->rid = -1; /* XXX */ + } + if (report_alloc(rep, hw->repdesc, REPORT_INPUT) < 0) { + goto usberr; + } + if (rep->size <= 0) { + SDL_SetError("%s: Input report descriptor has invalid length", + hw->path); + goto usberr; + } #if defined(USBHID_NEW) || (defined(__FREEBSD__) && __FreeBSD_version >= 500111) - hdata = hid_start_parse(hw->repdesc, 1 << hid_input, rep->rid); + hdata = hid_start_parse(hw->repdesc, 1 << hid_input, rep->rid); #else - hdata = hid_start_parse(hw->repdesc, 1 << hid_input); + hdata = hid_start_parse(hw->repdesc, 1 << hid_input); #endif - if (hdata == NULL) { - SDL_SetError("%s: Cannot start HID parser", hw->path); - goto usberr; - } - joy->naxes = 0; - joy->nbuttons = 0; - joy->nhats = 0; - joy->nballs = 0; - for (i=0; iaxis_map[i] = -1; - - while (hid_get_item(hdata, &hitem) > 0) { - char *sp; - const char *s; - - switch (hitem.kind) { - case hid_collection: - switch (HID_PAGE(hitem.usage)) { - case HUP_GENERIC_DESKTOP: - switch (HID_USAGE(hitem.usage)) { - case HUG_JOYSTICK: - case HUG_GAME_PAD: - s = hid_usage_in_page(hitem.usage); - sp = SDL_malloc(SDL_strlen(s) + 5); - SDL_snprintf(sp, SDL_strlen(s) + 5, "%s (%d)", s, - joy->index); - joydevnames[joy->index] = sp; - } - } - break; - case hid_input: - switch (HID_PAGE(hitem.usage)) { - case HUP_GENERIC_DESKTOP: { - unsigned usage = HID_USAGE(hitem.usage); - int joyaxe = usage_to_joyaxe(usage); - if (joyaxe >= 0) { - hw->axis_map[joyaxe] = 1; - } else if (usage == HUG_HAT_SWITCH) { - joy->nhats++; - } - break; - } - case HUP_BUTTON: - joy->nbuttons++; - break; - default: - break; - } - break; - default: - break; - } - } - hid_end_parse(hdata); - for (i=0; iaxis_map[i] > 0) - hw->axis_map[i] = joy->naxes++; - -usbend: - /* The poll blocks the event thread. */ - fcntl(fd, F_SETFL, O_NONBLOCK); - - return (0); -usberr: - close(hw->fd); - SDL_free(hw->path); - SDL_free(hw); - return (-1); + if (hdata == NULL) { + SDL_SetError("%s: Cannot start HID parser", hw->path); + goto usberr; + } + joy->naxes = 0; + joy->nbuttons = 0; + joy->nhats = 0; + joy->nballs = 0; + for (i = 0; i < JOYAXE_count; i++) + hw->axis_map[i] = -1; + + while (hid_get_item(hdata, &hitem) > 0) { + char *sp; + const char *s; + + switch (hitem.kind) { + case hid_collection: + switch (HID_PAGE(hitem.usage)) { + case HUP_GENERIC_DESKTOP: + switch (HID_USAGE(hitem.usage)) { + case HUG_JOYSTICK: + case HUG_GAME_PAD: + s = hid_usage_in_page(hitem.usage); + sp = SDL_malloc(SDL_strlen(s) + 5); + SDL_snprintf(sp, SDL_strlen(s) + 5, "%s (%d)", + s, joy->index); + joydevnames[joy->index] = sp; + } + } + break; + case hid_input: + switch (HID_PAGE(hitem.usage)) { + case HUP_GENERIC_DESKTOP: + { + unsigned usage = HID_USAGE(hitem.usage); + int joyaxe = usage_to_joyaxe(usage); + if (joyaxe >= 0) { + hw->axis_map[joyaxe] = 1; + } else if (usage == HUG_HAT_SWITCH) { + joy->nhats++; + } + break; + } + case HUP_BUTTON: + joy->nbuttons++; + break; + default: + break; + } + break; + default: + break; + } + } + hid_end_parse(hdata); + for (i = 0; i < JOYAXE_count; i++) + if (hw->axis_map[i] > 0) + hw->axis_map[i] = joy->naxes++; + + usbend: + /* The poll blocks the event thread. */ + fcntl(fd, F_SETFL, O_NONBLOCK); + + return (0); + usberr: + close(hw->fd); + SDL_free(hw->path); + SDL_free(hw); + return (-1); } void -SDL_SYS_JoystickUpdate(SDL_Joystick *joy) +SDL_SYS_JoystickUpdate(SDL_Joystick * joy) { - struct hid_item hitem; - struct hid_data *hdata; - struct report *rep; - int nbutton, naxe = -1; - Sint32 v; + struct hid_item hitem; + struct hid_data *hdata; + struct report *rep; + int nbutton, naxe = -1; + Sint32 v; #if defined(__FREEBSD__) || SDL_JOYSTICK_USBHID_MACHINE_JOYSTICK_H - struct joystick gameport; - static int x, y, xmin = 0xffff, ymin = 0xffff, xmax = 0, ymax = 0; - - if (joy->hwdata->type == BSDJOY_JOY) { - if (read(joy->hwdata->fd, &gameport, sizeof gameport) != sizeof gameport) - return; - if (abs(x - gameport.x) > 8) { - x = gameport.x; - if (x < xmin) { - xmin = x; - } - if (x > xmax) { - xmax = x; - } - if (xmin == xmax) { - xmin--; - xmax++; - } - v = (Sint32)x; - v -= (xmax + xmin + 1)/2; - v *= 32768/((xmax - xmin + 1)/2); - SDL_PrivateJoystickAxis(joy, 0, v); - } - if (abs(y - gameport.y) > 8) { - y = gameport.y; - if (y < ymin) { - ymin = y; - } - if (y > ymax) { - ymax = y; - } - if (ymin == ymax) { - ymin--; - ymax++; - } - v = (Sint32)y; - v -= (ymax + ymin + 1)/2; - v *= 32768/((ymax - ymin + 1)/2); - SDL_PrivateJoystickAxis(joy, 1, v); - } - if (gameport.b1 != joy->buttons[0]) { - SDL_PrivateJoystickButton(joy, 0, gameport.b1); - } - if (gameport.b2 != joy->buttons[1]) { - SDL_PrivateJoystickButton(joy, 1, gameport.b2); - } - return; - } + struct joystick gameport; + static int x, y, xmin = 0xffff, ymin = 0xffff, xmax = 0, ymax = 0; + + if (joy->hwdata->type == BSDJOY_JOY) { + if (read(joy->hwdata->fd, &gameport, sizeof gameport) != + sizeof gameport) + return; + if (abs(x - gameport.x) > 8) { + x = gameport.x; + if (x < xmin) { + xmin = x; + } + if (x > xmax) { + xmax = x; + } + if (xmin == xmax) { + xmin--; + xmax++; + } + v = (Sint32) x; + v -= (xmax + xmin + 1) / 2; + v *= 32768 / ((xmax - xmin + 1) / 2); + SDL_PrivateJoystickAxis(joy, 0, v); + } + if (abs(y - gameport.y) > 8) { + y = gameport.y; + if (y < ymin) { + ymin = y; + } + if (y > ymax) { + ymax = y; + } + if (ymin == ymax) { + ymin--; + ymax++; + } + v = (Sint32) y; + v -= (ymax + ymin + 1) / 2; + v *= 32768 / ((ymax - ymin + 1) / 2); + SDL_PrivateJoystickAxis(joy, 1, v); + } + if (gameport.b1 != joy->buttons[0]) { + SDL_PrivateJoystickButton(joy, 0, gameport.b1); + } + if (gameport.b2 != joy->buttons[1]) { + SDL_PrivateJoystickButton(joy, 1, gameport.b2); + } + return; + } #endif /* defined(__FREEBSD__) || SDL_JOYSTICK_USBHID_MACHINE_JOYSTICK_H */ - - rep = &joy->hwdata->inreport; - if (read(joy->hwdata->fd, REP_BUF_DATA(rep), rep->size) != rep->size) { - return; - } + rep = &joy->hwdata->inreport; + + if (read(joy->hwdata->fd, REP_BUF_DATA(rep), rep->size) != rep->size) { + return; + } #if defined(USBHID_NEW) || (defined(__FREEBSD__) && __FreeBSD_version >= 500111) - hdata = hid_start_parse(joy->hwdata->repdesc, 1 << hid_input, rep->rid); + hdata = hid_start_parse(joy->hwdata->repdesc, 1 << hid_input, rep->rid); #else - hdata = hid_start_parse(joy->hwdata->repdesc, 1 << hid_input); + hdata = hid_start_parse(joy->hwdata->repdesc, 1 << hid_input); #endif - if (hdata == NULL) { - fprintf(stderr, "%s: Cannot start HID parser\n", - joy->hwdata->path); - return; - } - - for (nbutton = 0; hid_get_item(hdata, &hitem) > 0;) { - switch (hitem.kind) { - case hid_input: - switch (HID_PAGE(hitem.usage)) { - case HUP_GENERIC_DESKTOP: { - unsigned usage = HID_USAGE(hitem.usage); - int joyaxe = usage_to_joyaxe(usage); - if (joyaxe >= 0) { - naxe = joy->hwdata->axis_map[joyaxe]; - /* scaleaxe */ - v = (Sint32)hid_get_data(REP_BUF_DATA(rep), - &hitem); - v -= (hitem.logical_maximum + hitem.logical_minimum + 1)/2; - v *= 32768/((hitem.logical_maximum - hitem.logical_minimum + 1)/2); - if (v != joy->axes[naxe]) { - SDL_PrivateJoystickAxis(joy, naxe, v); - } - } else if (usage == HUG_HAT_SWITCH) { - v = (Sint32)hid_get_data(REP_BUF_DATA(rep), - &hitem); - SDL_PrivateJoystickHat(joy, 0, - hatval_to_sdl(v)-hitem.logical_minimum); - } - break; - } - case HUP_BUTTON: - v = (Sint32)hid_get_data(REP_BUF_DATA(rep), - &hitem); - if (joy->buttons[nbutton] != v) { - SDL_PrivateJoystickButton(joy, - nbutton, v); - } - nbutton++; - break; - default: - continue; - } - break; - default: - break; - } - } - hid_end_parse(hdata); - - return; + if (hdata == NULL) { + fprintf(stderr, "%s: Cannot start HID parser\n", joy->hwdata->path); + return; + } + + for (nbutton = 0; hid_get_item(hdata, &hitem) > 0;) { + switch (hitem.kind) { + case hid_input: + switch (HID_PAGE(hitem.usage)) { + case HUP_GENERIC_DESKTOP: + { + unsigned usage = HID_USAGE(hitem.usage); + int joyaxe = usage_to_joyaxe(usage); + if (joyaxe >= 0) { + naxe = joy->hwdata->axis_map[joyaxe]; + /* scaleaxe */ + v = (Sint32) hid_get_data(REP_BUF_DATA(rep), &hitem); + v -= (hitem.logical_maximum + + hitem.logical_minimum + 1) / 2; + v *= 32768 / + ((hitem.logical_maximum - + hitem.logical_minimum + 1) / 2); + if (v != joy->axes[naxe]) { + SDL_PrivateJoystickAxis(joy, naxe, v); + } + } else if (usage == HUG_HAT_SWITCH) { + v = (Sint32) hid_get_data(REP_BUF_DATA(rep), &hitem); + SDL_PrivateJoystickHat(joy, 0, + hatval_to_sdl(v) - + hitem.logical_minimum); + } + break; + } + case HUP_BUTTON: + v = (Sint32) hid_get_data(REP_BUF_DATA(rep), &hitem); + if (joy->buttons[nbutton] != v) { + SDL_PrivateJoystickButton(joy, nbutton, v); + } + nbutton++; + break; + default: + continue; + } + break; + default: + break; + } + } + hid_end_parse(hdata); + + return; } /* Function to close a joystick after use */ void -SDL_SYS_JoystickClose(SDL_Joystick *joy) +SDL_SYS_JoystickClose(SDL_Joystick * joy) { - if (SDL_strncmp(joy->hwdata->path, "/dev/joy", 8)) { - report_free(&joy->hwdata->inreport); - hid_dispose_report_desc(joy->hwdata->repdesc); - } - close(joy->hwdata->fd); - SDL_free(joy->hwdata->path); - SDL_free(joy->hwdata); - - return; + if (SDL_strncmp(joy->hwdata->path, "/dev/joy", 8)) { + report_free(&joy->hwdata->inreport); + hid_dispose_report_desc(joy->hwdata->repdesc); + } + close(joy->hwdata->fd); + SDL_free(joy->hwdata->path); + SDL_free(joy->hwdata); + + return; } void SDL_SYS_JoystickQuit(void) { - int i; + int i; - for (i = 0; i < MAX_JOYS; i++) { - if (joynames[i] != NULL) - SDL_free(joynames[i]); - if (joydevnames[i] != NULL) - SDL_free(joydevnames[i]); - } + for (i = 0; i < MAX_JOYS; i++) { + if (joynames[i] != NULL) + SDL_free(joynames[i]); + if (joydevnames[i] != NULL) + SDL_free(joydevnames[i]); + } - return; + return; } static int report_alloc(struct report *r, struct report_desc *rd, int repind) { - int len; + int len; #ifdef __DragonFly__ - len = hid_report_size(rd, r->rid, repinfo[repind].kind); + len = hid_report_size(rd, r->rid, repinfo[repind].kind); #elif __FREEBSD__ # if (__FreeBSD_version >= 460000) # if (__FreeBSD_version <= 500111) - len = hid_report_size(rd, r->rid, repinfo[repind].kind); + len = hid_report_size(rd, r->rid, repinfo[repind].kind); # else - len = hid_report_size(rd, repinfo[repind].kind, r->rid); + len = hid_report_size(rd, repinfo[repind].kind, r->rid); # endif # else - len = hid_report_size(rd, repinfo[repind].kind, &r->rid); + len = hid_report_size(rd, repinfo[repind].kind, &r->rid); # endif #else # ifdef USBHID_NEW - len = hid_report_size(rd, repinfo[repind].kind, r->rid); + len = hid_report_size(rd, repinfo[repind].kind, r->rid); # else - len = hid_report_size(rd, repinfo[repind].kind, &r->rid); + len = hid_report_size(rd, repinfo[repind].kind, &r->rid); # endif #endif - if (len < 0) { - SDL_SetError("Negative HID report size"); - return (-1); - } - r->size = len; - - if (r->size > 0) { - r->buf = SDL_malloc(sizeof(*r->buf) - sizeof(REP_BUF_DATA(r)) + - r->size); - if (r->buf == NULL) { - SDL_OutOfMemory(); - return (-1); - } - } else { - r->buf = NULL; - } - - r->status = SREPORT_CLEAN; - return (0); + if (len < 0) { + SDL_SetError("Negative HID report size"); + return (-1); + } + r->size = len; + + if (r->size > 0) { + r->buf = SDL_malloc(sizeof(*r->buf) - sizeof(REP_BUF_DATA(r)) + + r->size); + if (r->buf == NULL) { + SDL_OutOfMemory(); + return (-1); + } + } else { + r->buf = NULL; + } + + r->status = SREPORT_CLEAN; + return (0); } static void report_free(struct report *r) { - if (r->buf != NULL) { - SDL_free(r->buf); - } - r->status = SREPORT_UNINIT; + if (r->buf != NULL) { + SDL_free(r->buf); + } + r->status = SREPORT_UNINIT; } #endif /* SDL_JOYSTICK_USBHID */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/joystick/darwin/SDL_sysjoystick.c b/src/joystick/darwin/SDL_sysjoystick.c index 022c992d4..42f90d521 100644 --- a/src/joystick/darwin/SDL_sysjoystick.c +++ b/src/joystick/darwin/SDL_sysjoystick.c @@ -42,7 +42,7 @@ #include #include #include -#include /* for NewPtrClear, DisposePtr */ +#include /* for NewPtrClear, DisposePtr */ #include "SDL_joystick.h" #include "../SDL_sysjoystick.h" @@ -50,51 +50,51 @@ struct recElement { - IOHIDElementCookie cookie; /* unique value which identifies element, will NOT change */ - long min; /* reported min value possible */ - long max; /* reported max value possible */ + IOHIDElementCookie cookie; /* unique value which identifies element, will NOT change */ + long min; /* reported min value possible */ + long max; /* reported max value possible */ #if 0 - /* TODO: maybe should handle the following stuff somehow? */ - - long scaledMin; /* reported scaled min value possible */ - long scaledMax; /* reported scaled max value possible */ - long size; /* size in bits of data return from element */ - Boolean relative; /* are reports relative to last report (deltas) */ - Boolean wrapping; /* does element wrap around (one value higher than max is min) */ - Boolean nonLinear; /* are the values reported non-linear relative to element movement */ - Boolean preferredState; /* does element have a preferred state (such as a button) */ - Boolean nullState; /* does element have null state */ -#endif /* 0 */ - - /* runtime variables used for auto-calibration */ - long minReport; /* min returned value */ - long maxReport; /* max returned value */ - - struct recElement * pNext; /* next element in list */ + /* TODO: maybe should handle the following stuff somehow? */ + + long scaledMin; /* reported scaled min value possible */ + long scaledMax; /* reported scaled max value possible */ + long size; /* size in bits of data return from element */ + Boolean relative; /* are reports relative to last report (deltas) */ + Boolean wrapping; /* does element wrap around (one value higher than max is min) */ + Boolean nonLinear; /* are the values reported non-linear relative to element movement */ + Boolean preferredState; /* does element have a preferred state (such as a button) */ + Boolean nullState; /* does element have null state */ +#endif /* 0 */ + + /* runtime variables used for auto-calibration */ + long minReport; /* min returned value */ + long maxReport; /* max returned value */ + + struct recElement *pNext; /* next element in list */ }; typedef struct recElement recElement; struct joystick_hwdata { - IOHIDDeviceInterface ** interface; /* interface to device, NULL = no interface */ + IOHIDDeviceInterface **interface; /* interface to device, NULL = no interface */ - char product[256]; /* name of product */ - long usage; /* usage page from IOUSBHID Parser.h which defines general usage */ - long usagePage; /* usage within above page from IOUSBHID Parser.h which defines specific usage */ + char product[256]; /* name of product */ + long usage; /* usage page from IOUSBHID Parser.h which defines general usage */ + long usagePage; /* usage within above page from IOUSBHID Parser.h which defines specific usage */ - long axes; /* number of axis (calculated, not reported by device) */ - long buttons; /* number of buttons (calculated, not reported by device) */ - long hats; /* number of hat switches (calculated, not reported by device) */ - long elements; /* number of total elements (shouldbe total of above) (calculated, not reported by device) */ + long axes; /* number of axis (calculated, not reported by device) */ + long buttons; /* number of buttons (calculated, not reported by device) */ + long hats; /* number of hat switches (calculated, not reported by device) */ + long elements; /* number of total elements (shouldbe total of above) (calculated, not reported by device) */ - recElement* firstAxis; - recElement* firstButton; - recElement* firstHat; + recElement *firstAxis; + recElement *firstButton; + recElement *firstHat; - int removed; - int uncentered; + int removed; + int uncentered; - struct joystick_hwdata* pNext; /* next device */ + struct joystick_hwdata *pNext; /* next device */ }; typedef struct joystick_hwdata recDevice; @@ -103,60 +103,65 @@ typedef struct joystick_hwdata recDevice; static recDevice *gpDeviceList = NULL; -static void HIDReportErrorNum (char * strError, long numError) +static void +HIDReportErrorNum(char *strError, long numError) { - SDL_SetError(strError); + SDL_SetError(strError); } -static void HIDGetCollectionElements (CFMutableDictionaryRef deviceProperties, recDevice *pDevice); +static void HIDGetCollectionElements(CFMutableDictionaryRef deviceProperties, + recDevice * pDevice); /* returns current value for element, polling element * will return 0 on error conditions which should be accounted for by application */ -static SInt32 HIDGetElementValue (recDevice *pDevice, recElement *pElement) +static SInt32 +HIDGetElementValue(recDevice * pDevice, recElement * pElement) { - IOReturn result = kIOReturnSuccess; - IOHIDEventStruct hidEvent; - hidEvent.value = 0; - - if (NULL != pDevice && NULL != pElement && NULL != pDevice->interface) - { - result = (*(pDevice->interface))->getElementValue(pDevice->interface, pElement->cookie, &hidEvent); - if (kIOReturnSuccess == result) - { - /* record min and max for auto calibration */ - if (hidEvent.value < pElement->minReport) - pElement->minReport = hidEvent.value; - if (hidEvent.value > pElement->maxReport) - pElement->maxReport = hidEvent.value; - } - } - - /* auto user scale */ - return hidEvent.value; + IOReturn result = kIOReturnSuccess; + IOHIDEventStruct hidEvent; + hidEvent.value = 0; + + if (NULL != pDevice && NULL != pElement && NULL != pDevice->interface) { + result = + (*(pDevice->interface))->getElementValue(pDevice->interface, + pElement->cookie, + &hidEvent); + if (kIOReturnSuccess == result) { + /* record min and max for auto calibration */ + if (hidEvent.value < pElement->minReport) + pElement->minReport = hidEvent.value; + if (hidEvent.value > pElement->maxReport) + pElement->maxReport = hidEvent.value; + } + } + + /* auto user scale */ + return hidEvent.value; } -static SInt32 HIDScaledCalibratedValue (recDevice *pDevice, recElement *pElement, long min, long max) +static SInt32 +HIDScaledCalibratedValue(recDevice * pDevice, recElement * pElement, + long min, long max) { - float deviceScale = max - min; - float readScale = pElement->maxReport - pElement->minReport; - SInt32 value = HIDGetElementValue(pDevice, pElement); - if (readScale == 0) - return value; /* no scaling at all */ - else - return ((value - pElement->minReport) * deviceScale / readScale) + min; + float deviceScale = max - min; + float readScale = pElement->maxReport - pElement->minReport; + SInt32 value = HIDGetElementValue(pDevice, pElement); + if (readScale == 0) + return value; /* no scaling at all */ + else + return ((value - pElement->minReport) * deviceScale / readScale) + + min; } -static void HIDRemovalCallback(void * target, - IOReturn result, - void * refcon, - void * sender) +static void +HIDRemovalCallback(void *target, IOReturn result, void *refcon, void *sender) { - recDevice *device = (recDevice *) refcon; - device->removed = 1; - device->uncentered = 1; + recDevice *device = (recDevice *) refcon; + device->removed = 1; + device->uncentered = 1; } @@ -165,39 +170,50 @@ static void HIDRemovalCallback(void * target, * Note: appliction now owns the device and must close and release it prior to exiting */ -static IOReturn HIDCreateOpenDeviceInterface (io_object_t hidDevice, recDevice *pDevice) +static IOReturn +HIDCreateOpenDeviceInterface(io_object_t hidDevice, recDevice * pDevice) { - IOReturn result = kIOReturnSuccess; - HRESULT plugInResult = S_OK; - SInt32 score = 0; - IOCFPlugInInterface ** ppPlugInInterface = NULL; - - if (NULL == pDevice->interface) - { - result = IOCreatePlugInInterfaceForService (hidDevice, kIOHIDDeviceUserClientTypeID, - kIOCFPlugInInterfaceID, &ppPlugInInterface, &score); - if (kIOReturnSuccess == result) - { - /* Call a method of the intermediate plug-in to create the device interface */ - plugInResult = (*ppPlugInInterface)->QueryInterface (ppPlugInInterface, - CFUUIDGetUUIDBytes (kIOHIDDeviceInterfaceID), (void *) &(pDevice->interface)); - if (S_OK != plugInResult) - HIDReportErrorNum ("CouldnÕt query HID class device interface from plugInInterface", plugInResult); - (*ppPlugInInterface)->Release (ppPlugInInterface); - } - else - HIDReportErrorNum ("Failed to create **plugInInterface via IOCreatePlugInInterfaceForService.", result); - } - if (NULL != pDevice->interface) - { - result = (*(pDevice->interface))->open (pDevice->interface, 0); - if (kIOReturnSuccess != result) - HIDReportErrorNum ("Failed to open pDevice->interface via open.", result); - else - (*(pDevice->interface))->setRemovalCallback (pDevice->interface, HIDRemovalCallback, pDevice, pDevice); - - } - return result; + IOReturn result = kIOReturnSuccess; + HRESULT plugInResult = S_OK; + SInt32 score = 0; + IOCFPlugInInterface **ppPlugInInterface = NULL; + + if (NULL == pDevice->interface) { + result = + IOCreatePlugInInterfaceForService(hidDevice, + kIOHIDDeviceUserClientTypeID, + kIOCFPlugInInterfaceID, + &ppPlugInInterface, &score); + if (kIOReturnSuccess == result) { + /* Call a method of the intermediate plug-in to create the device interface */ + plugInResult = + (*ppPlugInInterface)->QueryInterface(ppPlugInInterface, + CFUUIDGetUUIDBytes + (kIOHIDDeviceInterfaceID), + (void *) &(pDevice-> + interface)); + if (S_OK != plugInResult) + HIDReportErrorNum + ("CouldnÕt query HID class device interface from plugInInterface", + plugInResult); + (*ppPlugInInterface)->Release(ppPlugInInterface); + } else + HIDReportErrorNum + ("Failed to create **plugInInterface via IOCreatePlugInInterfaceForService.", + result); + } + if (NULL != pDevice->interface) { + result = (*(pDevice->interface))->open(pDevice->interface, 0); + if (kIOReturnSuccess != result) + HIDReportErrorNum + ("Failed to open pDevice->interface via open.", result); + else + (*(pDevice->interface))->setRemovalCallback(pDevice->interface, + HIDRemovalCallback, + pDevice, pDevice); + + } + return result; } /* Closes and releases interface to device, should be done prior to exting application @@ -206,47 +222,48 @@ static IOReturn HIDCreateOpenDeviceInterface (io_object_t hidDevice, recDevice * * (device may have to be plug and re-plugged in different location to get it working again without a restart) */ -static IOReturn HIDCloseReleaseInterface (recDevice *pDevice) +static IOReturn +HIDCloseReleaseInterface(recDevice * pDevice) { - IOReturn result = kIOReturnSuccess; - - if ((NULL != pDevice) && (NULL != pDevice->interface)) - { - /* close the interface */ - result = (*(pDevice->interface))->close (pDevice->interface); - if (kIOReturnNotOpen == result) - { - /* do nothing as device was not opened, thus can't be closed */ - } - else if (kIOReturnSuccess != result) - HIDReportErrorNum ("Failed to close IOHIDDeviceInterface.", result); - /* release the interface */ - result = (*(pDevice->interface))->Release (pDevice->interface); - if (kIOReturnSuccess != result) - HIDReportErrorNum ("Failed to release IOHIDDeviceInterface.", result); - pDevice->interface = NULL; - } - return result; + IOReturn result = kIOReturnSuccess; + + if ((NULL != pDevice) && (NULL != pDevice->interface)) { + /* close the interface */ + result = (*(pDevice->interface))->close(pDevice->interface); + if (kIOReturnNotOpen == result) { + /* do nothing as device was not opened, thus can't be closed */ + } else if (kIOReturnSuccess != result) + HIDReportErrorNum("Failed to close IOHIDDeviceInterface.", + result); + /* release the interface */ + result = (*(pDevice->interface))->Release(pDevice->interface); + if (kIOReturnSuccess != result) + HIDReportErrorNum("Failed to release IOHIDDeviceInterface.", + result); + pDevice->interface = NULL; + } + return result; } /* extracts actual specific element information from each element CF dictionary entry */ -static void HIDGetElementInfo (CFTypeRef refElement, recElement *pElement) +static void +HIDGetElementInfo(CFTypeRef refElement, recElement * pElement) { - long number; - CFTypeRef refType; - - refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementCookieKey)); - if (refType && CFNumberGetValue (refType, kCFNumberLongType, &number)) - pElement->cookie = (IOHIDElementCookie) number; - refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementMinKey)); - if (refType && CFNumberGetValue (refType, kCFNumberLongType, &number)) - pElement->min = number; - pElement->maxReport = pElement->min; - refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementMaxKey)); - if (refType && CFNumberGetValue (refType, kCFNumberLongType, &number)) - pElement->max = number; - pElement->minReport = pElement->max; + long number; + CFTypeRef refType; + + refType = CFDictionaryGetValue(refElement, CFSTR(kIOHIDElementCookieKey)); + if (refType && CFNumberGetValue(refType, kCFNumberLongType, &number)) + pElement->cookie = (IOHIDElementCookie) number; + refType = CFDictionaryGetValue(refElement, CFSTR(kIOHIDElementMinKey)); + if (refType && CFNumberGetValue(refType, kCFNumberLongType, &number)) + pElement->min = number; + pElement->maxReport = pElement->min; + refType = CFDictionaryGetValue(refElement, CFSTR(kIOHIDElementMaxKey)); + if (refType && CFNumberGetValue(refType, kCFNumberLongType, &number)) + pElement->max = number; + pElement->minReport = pElement->max; /* TODO: maybe should handle the following stuff somehow? @@ -275,292 +292,319 @@ static void HIDGetElementInfo (CFTypeRef refElement, recElement *pElement) if (refType) pElement->nullState = CFBooleanGetValue (refType); */ -} +} /* examines CF dictionary vlaue in device element hierarchy to determine if it is element of interest or a collection of more elements * if element of interest allocate storage, add to list and retrieve element specific info * if collection then pass on to deconstruction collection into additional individual elements */ -static void HIDAddElement (CFTypeRef refElement, recDevice* pDevice) +static void +HIDAddElement(CFTypeRef refElement, recDevice * pDevice) { - recElement* element = NULL; - recElement** headElement = NULL; - long elementType, usagePage, usage; - CFTypeRef refElementType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementTypeKey)); - CFTypeRef refUsagePage = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementUsagePageKey)); - CFTypeRef refUsage = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementUsageKey)); - - - if ((refElementType) && (CFNumberGetValue (refElementType, kCFNumberLongType, &elementType))) - { - /* look at types of interest */ - if ((elementType == kIOHIDElementTypeInput_Misc) || (elementType == kIOHIDElementTypeInput_Button) || - (elementType == kIOHIDElementTypeInput_Axis)) - { - if (refUsagePage && CFNumberGetValue (refUsagePage, kCFNumberLongType, &usagePage) && - refUsage && CFNumberGetValue (refUsage, kCFNumberLongType, &usage)) - { - switch (usagePage) /* only interested in kHIDPage_GenericDesktop and kHIDPage_Button */ - { - case kHIDPage_GenericDesktop: - { - switch (usage) /* look at usage to determine function */ - { - case kHIDUsage_GD_X: - case kHIDUsage_GD_Y: - case kHIDUsage_GD_Z: - case kHIDUsage_GD_Rx: - case kHIDUsage_GD_Ry: - case kHIDUsage_GD_Rz: - case kHIDUsage_GD_Slider: - case kHIDUsage_GD_Dial: - case kHIDUsage_GD_Wheel: - element = (recElement *) NewPtrClear (sizeof (recElement)); - if (element) - { - pDevice->axes++; - headElement = &(pDevice->firstAxis); - } - break; - case kHIDUsage_GD_Hatswitch: - element = (recElement *) NewPtrClear (sizeof (recElement)); - if (element) - { - pDevice->hats++; - headElement = &(pDevice->firstHat); - } - break; - } - } - break; - case kHIDPage_Button: - element = (recElement *) NewPtrClear (sizeof (recElement)); - if (element) - { - pDevice->buttons++; - headElement = &(pDevice->firstButton); - } - break; - default: - break; - } - } - } - else if (kIOHIDElementTypeCollection == elementType) - HIDGetCollectionElements ((CFMutableDictionaryRef) refElement, pDevice); - } - - if (element && headElement) /* add to list */ - { - pDevice->elements++; - if (NULL == *headElement) - *headElement = element; - else - { - recElement *elementPrevious, *elementCurrent; - elementCurrent = *headElement; - while (elementCurrent) - { - elementPrevious = elementCurrent; - elementCurrent = elementPrevious->pNext; - } - elementPrevious->pNext = element; - } - element->pNext = NULL; - HIDGetElementInfo (refElement, element); - } + recElement *element = NULL; + recElement **headElement = NULL; + long elementType, usagePage, usage; + CFTypeRef refElementType = + CFDictionaryGetValue(refElement, CFSTR(kIOHIDElementTypeKey)); + CFTypeRef refUsagePage = + CFDictionaryGetValue(refElement, CFSTR(kIOHIDElementUsagePageKey)); + CFTypeRef refUsage = + CFDictionaryGetValue(refElement, CFSTR(kIOHIDElementUsageKey)); + + + if ((refElementType) + && + (CFNumberGetValue(refElementType, kCFNumberLongType, &elementType))) { + /* look at types of interest */ + if ((elementType == kIOHIDElementTypeInput_Misc) + || (elementType == kIOHIDElementTypeInput_Button) + || (elementType == kIOHIDElementTypeInput_Axis)) { + if (refUsagePage + && CFNumberGetValue(refUsagePage, kCFNumberLongType, + &usagePage) && refUsage + && CFNumberGetValue(refUsage, kCFNumberLongType, &usage)) { + switch (usagePage) { /* only interested in kHIDPage_GenericDesktop and kHIDPage_Button */ + case kHIDPage_GenericDesktop: + { + switch (usage) { /* look at usage to determine function */ + case kHIDUsage_GD_X: + case kHIDUsage_GD_Y: + case kHIDUsage_GD_Z: + case kHIDUsage_GD_Rx: + case kHIDUsage_GD_Ry: + case kHIDUsage_GD_Rz: + case kHIDUsage_GD_Slider: + case kHIDUsage_GD_Dial: + case kHIDUsage_GD_Wheel: + element = (recElement *) + NewPtrClear(sizeof(recElement)); + if (element) { + pDevice->axes++; + headElement = &(pDevice->firstAxis); + } + break; + case kHIDUsage_GD_Hatswitch: + element = (recElement *) + NewPtrClear(sizeof(recElement)); + if (element) { + pDevice->hats++; + headElement = &(pDevice->firstHat); + } + break; + } + } + break; + case kHIDPage_Button: + element = (recElement *) + NewPtrClear(sizeof(recElement)); + if (element) { + pDevice->buttons++; + headElement = &(pDevice->firstButton); + } + break; + default: + break; + } + } + } else if (kIOHIDElementTypeCollection == elementType) + HIDGetCollectionElements((CFMutableDictionaryRef) refElement, + pDevice); + } + + if (element && headElement) { /* add to list */ + pDevice->elements++; + if (NULL == *headElement) + *headElement = element; + else { + recElement *elementPrevious, *elementCurrent; + elementCurrent = *headElement; + while (elementCurrent) { + elementPrevious = elementCurrent; + elementCurrent = elementPrevious->pNext; + } + elementPrevious->pNext = element; + } + element->pNext = NULL; + HIDGetElementInfo(refElement, element); + } } /* collects information from each array member in device element list (each array memeber = element) */ -static void HIDGetElementsCFArrayHandler (const void * value, void * parameter) +static void +HIDGetElementsCFArrayHandler(const void *value, void *parameter) { - if (CFGetTypeID (value) == CFDictionaryGetTypeID ()) - HIDAddElement ((CFTypeRef) value, (recDevice *) parameter); + if (CFGetTypeID(value) == CFDictionaryGetTypeID()) + HIDAddElement((CFTypeRef) value, (recDevice *) parameter); } /* handles retrieval of element information from arrays of elements in device IO registry information */ -static void HIDGetElements (CFTypeRef refElementCurrent, recDevice *pDevice) +static void +HIDGetElements(CFTypeRef refElementCurrent, recDevice * pDevice) { - CFTypeID type = CFGetTypeID (refElementCurrent); - if (type == CFArrayGetTypeID()) /* if element is an array */ - { - CFRange range = {0, CFArrayGetCount (refElementCurrent)}; - /* CountElementsCFArrayHandler called for each array member */ - CFArrayApplyFunction (refElementCurrent, range, HIDGetElementsCFArrayHandler, pDevice); - } -} + CFTypeID type = CFGetTypeID(refElementCurrent); + if (type == CFArrayGetTypeID()) { /* if element is an array */ + CFRange range = { 0, CFArrayGetCount(refElementCurrent) }; + /* CountElementsCFArrayHandler called for each array member */ + CFArrayApplyFunction(refElementCurrent, range, + HIDGetElementsCFArrayHandler, pDevice); + } +} /* handles extracting element information from element collection CF types * used from top level element decoding and hierarchy deconstruction to flatten device element list */ -static void HIDGetCollectionElements (CFMutableDictionaryRef deviceProperties, recDevice *pDevice) +static void +HIDGetCollectionElements(CFMutableDictionaryRef deviceProperties, + recDevice * pDevice) { - CFTypeRef refElementTop = CFDictionaryGetValue (deviceProperties, CFSTR(kIOHIDElementKey)); - if (refElementTop) - HIDGetElements (refElementTop, pDevice); + CFTypeRef refElementTop = + CFDictionaryGetValue(deviceProperties, CFSTR(kIOHIDElementKey)); + if (refElementTop) + HIDGetElements(refElementTop, pDevice); } /* use top level element usage page and usage to discern device usage page and usage setting appropriate vlaues in device record */ -static void HIDTopLevelElementHandler (const void * value, void * parameter) +static void +HIDTopLevelElementHandler(const void *value, void *parameter) { - CFTypeRef refCF = 0; - if (CFGetTypeID (value) != CFDictionaryGetTypeID ()) - return; - refCF = CFDictionaryGetValue (value, CFSTR(kIOHIDElementUsagePageKey)); - if (!CFNumberGetValue (refCF, kCFNumberLongType, &((recDevice *) parameter)->usagePage)) - SDL_SetError ("CFNumberGetValue error retrieving pDevice->usagePage."); - refCF = CFDictionaryGetValue (value, CFSTR(kIOHIDElementUsageKey)); - if (!CFNumberGetValue (refCF, kCFNumberLongType, &((recDevice *) parameter)->usage)) - SDL_SetError ("CFNumberGetValue error retrieving pDevice->usage."); + CFTypeRef refCF = 0; + if (CFGetTypeID(value) != CFDictionaryGetTypeID()) + return; + refCF = CFDictionaryGetValue(value, CFSTR(kIOHIDElementUsagePageKey)); + if (!CFNumberGetValue + (refCF, kCFNumberLongType, &((recDevice *) parameter)->usagePage)) + SDL_SetError("CFNumberGetValue error retrieving pDevice->usagePage."); + refCF = CFDictionaryGetValue(value, CFSTR(kIOHIDElementUsageKey)); + if (!CFNumberGetValue + (refCF, kCFNumberLongType, &((recDevice *) parameter)->usage)) + SDL_SetError("CFNumberGetValue error retrieving pDevice->usage."); } /* extracts device info from CF dictionary records in IO registry */ -static void HIDGetDeviceInfo (io_object_t hidDevice, CFMutableDictionaryRef hidProperties, recDevice *pDevice) +static void +HIDGetDeviceInfo(io_object_t hidDevice, CFMutableDictionaryRef hidProperties, + recDevice * pDevice) { - CFMutableDictionaryRef usbProperties = 0; - io_registry_entry_t parent1, parent2; - - /* Mac OS X currently is not mirroring all USB properties to HID page so need to look at USB device page also - * get dictionary for usb properties: step up two levels and get CF dictionary for USB properties - */ - if ((KERN_SUCCESS == IORegistryEntryGetParentEntry (hidDevice, kIOServicePlane, &parent1)) && - (KERN_SUCCESS == IORegistryEntryGetParentEntry (parent1, kIOServicePlane, &parent2)) && - (KERN_SUCCESS == IORegistryEntryCreateCFProperties (parent2, &usbProperties, kCFAllocatorDefault, kNilOptions))) - { - if (usbProperties) - { - CFTypeRef refCF = 0; - /* get device info - * try hid dictionary first, if fail then go to usb dictionary - */ - - - /* get product name */ - refCF = CFDictionaryGetValue (hidProperties, CFSTR(kIOHIDProductKey)); - if (!refCF) - refCF = CFDictionaryGetValue (usbProperties, CFSTR("USB Product Name")); - if (refCF) - { - if (!CFStringGetCString (refCF, pDevice->product, 256, CFStringGetSystemEncoding ())) - SDL_SetError ("CFStringGetCString error retrieving pDevice->product."); - } - - /* get usage page and usage */ - refCF = CFDictionaryGetValue (hidProperties, CFSTR(kIOHIDPrimaryUsagePageKey)); - if (refCF) - { - if (!CFNumberGetValue (refCF, kCFNumberLongType, &pDevice->usagePage)) - SDL_SetError ("CFNumberGetValue error retrieving pDevice->usagePage."); - refCF = CFDictionaryGetValue (hidProperties, CFSTR(kIOHIDPrimaryUsageKey)); - if (refCF) - if (!CFNumberGetValue (refCF, kCFNumberLongType, &pDevice->usage)) - SDL_SetError ("CFNumberGetValue error retrieving pDevice->usage."); - } - - if (NULL == refCF) /* get top level element HID usage page or usage */ - { - /* use top level element instead */ - CFTypeRef refCFTopElement = 0; - refCFTopElement = CFDictionaryGetValue (hidProperties, CFSTR(kIOHIDElementKey)); - { - /* refCFTopElement points to an array of element dictionaries */ - CFRange range = {0, CFArrayGetCount (refCFTopElement)}; - CFArrayApplyFunction (refCFTopElement, range, HIDTopLevelElementHandler, pDevice); - } - } - - CFRelease (usbProperties); - } - else - SDL_SetError ("IORegistryEntryCreateCFProperties failed to create usbProperties."); - - if (kIOReturnSuccess != IOObjectRelease (parent2)) - SDL_SetError ("IOObjectRelease error with parent2."); - if (kIOReturnSuccess != IOObjectRelease (parent1)) - SDL_SetError ("IOObjectRelease error with parent1."); - } + CFMutableDictionaryRef usbProperties = 0; + io_registry_entry_t parent1, parent2; + + /* Mac OS X currently is not mirroring all USB properties to HID page so need to look at USB device page also + * get dictionary for usb properties: step up two levels and get CF dictionary for USB properties + */ + if ((KERN_SUCCESS == + IORegistryEntryGetParentEntry(hidDevice, kIOServicePlane, &parent1)) + && (KERN_SUCCESS == + IORegistryEntryGetParentEntry(parent1, kIOServicePlane, &parent2)) + && (KERN_SUCCESS == + IORegistryEntryCreateCFProperties(parent2, &usbProperties, + kCFAllocatorDefault, + kNilOptions))) { + if (usbProperties) { + CFTypeRef refCF = 0; + /* get device info + * try hid dictionary first, if fail then go to usb dictionary + */ + + + /* get product name */ + refCF = + CFDictionaryGetValue(hidProperties, CFSTR(kIOHIDProductKey)); + if (!refCF) + refCF = + CFDictionaryGetValue(usbProperties, + CFSTR("USB Product Name")); + if (refCF) { + if (!CFStringGetCString + (refCF, pDevice->product, 256, + CFStringGetSystemEncoding())) + SDL_SetError + ("CFStringGetCString error retrieving pDevice->product."); + } + + /* get usage page and usage */ + refCF = + CFDictionaryGetValue(hidProperties, + CFSTR(kIOHIDPrimaryUsagePageKey)); + if (refCF) { + if (!CFNumberGetValue + (refCF, kCFNumberLongType, &pDevice->usagePage)) + SDL_SetError + ("CFNumberGetValue error retrieving pDevice->usagePage."); + refCF = + CFDictionaryGetValue(hidProperties, + CFSTR(kIOHIDPrimaryUsageKey)); + if (refCF) + if (!CFNumberGetValue + (refCF, kCFNumberLongType, &pDevice->usage)) + SDL_SetError + ("CFNumberGetValue error retrieving pDevice->usage."); + } + + if (NULL == refCF) { /* get top level element HID usage page or usage */ + /* use top level element instead */ + CFTypeRef refCFTopElement = 0; + refCFTopElement = + CFDictionaryGetValue(hidProperties, + CFSTR(kIOHIDElementKey)); + { + /* refCFTopElement points to an array of element dictionaries */ + CFRange range = { 0, CFArrayGetCount(refCFTopElement) }; + CFArrayApplyFunction(refCFTopElement, range, + HIDTopLevelElementHandler, pDevice); + } + } + + CFRelease(usbProperties); + } else + SDL_SetError + ("IORegistryEntryCreateCFProperties failed to create usbProperties."); + + if (kIOReturnSuccess != IOObjectRelease(parent2)) + SDL_SetError("IOObjectRelease error with parent2."); + if (kIOReturnSuccess != IOObjectRelease(parent1)) + SDL_SetError("IOObjectRelease error with parent1."); + } } -static recDevice *HIDBuildDevice (io_object_t hidDevice) +static recDevice * +HIDBuildDevice(io_object_t hidDevice) { - recDevice *pDevice = (recDevice *) NewPtrClear (sizeof (recDevice)); - if (pDevice) - { - /* get dictionary for HID properties */ - CFMutableDictionaryRef hidProperties = 0; - kern_return_t result = IORegistryEntryCreateCFProperties (hidDevice, &hidProperties, kCFAllocatorDefault, kNilOptions); - if ((result == KERN_SUCCESS) && hidProperties) - { - /* create device interface */ - result = HIDCreateOpenDeviceInterface (hidDevice, pDevice); - if (kIOReturnSuccess == result) - { - HIDGetDeviceInfo (hidDevice, hidProperties, pDevice); /* hidDevice used to find parents in registry tree */ - HIDGetCollectionElements (hidProperties, pDevice); - } - else - { - DisposePtr((Ptr)pDevice); - pDevice = NULL; - } - CFRelease (hidProperties); - } - else - { - DisposePtr((Ptr)pDevice); - pDevice = NULL; - } - } - return pDevice; + recDevice *pDevice = (recDevice *) NewPtrClear(sizeof(recDevice)); + if (pDevice) { + /* get dictionary for HID properties */ + CFMutableDictionaryRef hidProperties = 0; + kern_return_t result = + IORegistryEntryCreateCFProperties(hidDevice, &hidProperties, + kCFAllocatorDefault, + kNilOptions); + if ((result == KERN_SUCCESS) && hidProperties) { + /* create device interface */ + result = HIDCreateOpenDeviceInterface(hidDevice, pDevice); + if (kIOReturnSuccess == result) { + HIDGetDeviceInfo(hidDevice, hidProperties, pDevice); /* hidDevice used to find parents in registry tree */ + HIDGetCollectionElements(hidProperties, pDevice); + } else { + DisposePtr((Ptr) pDevice); + pDevice = NULL; + } + CFRelease(hidProperties); + } else { + DisposePtr((Ptr) pDevice); + pDevice = NULL; + } + } + return pDevice; } /* disposes of the element list associated with a device and the memory associated with the list */ -static void HIDDisposeElementList (recElement **elementList) +static void +HIDDisposeElementList(recElement ** elementList) { - recElement *pElement = *elementList; - while (pElement) - { - recElement *pElementNext = pElement->pNext; - DisposePtr ((Ptr) pElement); - pElement = pElementNext; - } - *elementList = NULL; + recElement *pElement = *elementList; + while (pElement) { + recElement *pElementNext = pElement->pNext; + DisposePtr((Ptr) pElement); + pElement = pElementNext; + } + *elementList = NULL; } /* disposes of a single device, closing and releaseing interface, freeing memory fro device and elements, setting device pointer to NULL * all your device no longer belong to us... (i.e., you do not 'own' the device anymore) */ -static recDevice *HIDDisposeDevice (recDevice **ppDevice) +static recDevice * +HIDDisposeDevice(recDevice ** ppDevice) { - kern_return_t result = KERN_SUCCESS; - recDevice *pDeviceNext = NULL; - if (*ppDevice) - { - /* save next device prior to disposing of this device */ - pDeviceNext = (*ppDevice)->pNext; - - /* free element lists */ - HIDDisposeElementList (&(*ppDevice)->firstAxis); - HIDDisposeElementList (&(*ppDevice)->firstButton); - HIDDisposeElementList (&(*ppDevice)->firstHat); - - result = HIDCloseReleaseInterface (*ppDevice); /* function sanity checks interface value (now application does not own device) */ - if (kIOReturnSuccess != result) - HIDReportErrorNum ("HIDCloseReleaseInterface failed when trying to dipose device.", result); - DisposePtr ((Ptr)*ppDevice); - *ppDevice = NULL; - } - return pDeviceNext; + kern_return_t result = KERN_SUCCESS; + recDevice *pDeviceNext = NULL; + if (*ppDevice) { + /* save next device prior to disposing of this device */ + pDeviceNext = (*ppDevice)->pNext; + + /* free element lists */ + HIDDisposeElementList(&(*ppDevice)->firstAxis); + HIDDisposeElementList(&(*ppDevice)->firstButton); + HIDDisposeElementList(&(*ppDevice)->firstHat); + + result = HIDCloseReleaseInterface(*ppDevice); /* function sanity checks interface value (now application does not own device) */ + if (kIOReturnSuccess != result) + HIDReportErrorNum + ("HIDCloseReleaseInterface failed when trying to dipose device.", + result); + DisposePtr((Ptr) * ppDevice); + *ppDevice = NULL; + } + return pDeviceNext; } @@ -569,126 +613,122 @@ static recDevice *HIDDisposeDevice (recDevice **ppDevice) * This function should return the number of available joysticks, or -1 * on an unrecoverable fatal error. */ -int SDL_SYS_JoystickInit(void) +int +SDL_SYS_JoystickInit(void) { - IOReturn result = kIOReturnSuccess; - mach_port_t masterPort = 0; - io_iterator_t hidObjectIterator = 0; - CFMutableDictionaryRef hidMatchDictionary = NULL; - recDevice *device, *lastDevice; - io_object_t ioHIDDeviceObject = 0; - - SDL_numjoysticks = 0; - - if (gpDeviceList) - { - SDL_SetError("Joystick: Device list already inited."); - return -1; - } - - result = IOMasterPort (bootstrap_port, &masterPort); - if (kIOReturnSuccess != result) - { - SDL_SetError("Joystick: IOMasterPort error with bootstrap_port."); - return -1; - } - - /* Set up a matching dictionary to search I/O Registry by class name for all HID class devices. */ - hidMatchDictionary = IOServiceMatching (kIOHIDDeviceKey); - if (hidMatchDictionary) - { - /* Add key for device type (joystick, in this case) to refine the matching dictionary. */ - - /* NOTE: we now perform this filtering later - UInt32 usagePage = kHIDPage_GenericDesktop; - UInt32 usage = kHIDUsage_GD_Joystick; - CFNumberRef refUsage = NULL, refUsagePage = NULL; - - refUsage = CFNumberCreate (kCFAllocatorDefault, kCFNumberIntType, &usage); - CFDictionarySetValue (hidMatchDictionary, CFSTR (kIOHIDPrimaryUsageKey), refUsage); - refUsagePage = CFNumberCreate (kCFAllocatorDefault, kCFNumberIntType, &usagePage); - CFDictionarySetValue (hidMatchDictionary, CFSTR (kIOHIDPrimaryUsagePageKey), refUsagePage); - */ - } - else - { - SDL_SetError("Joystick: Failed to get HID CFMutableDictionaryRef via IOServiceMatching."); - return -1; - } - - /*/ Now search I/O Registry for matching devices. */ - result = IOServiceGetMatchingServices (masterPort, hidMatchDictionary, &hidObjectIterator); - /* Check for errors */ - if (kIOReturnSuccess != result) - { - SDL_SetError("Joystick: Couldn't create a HID object iterator."); - return -1; - } - if (!hidObjectIterator) /* there are no joysticks */ - { - gpDeviceList = NULL; - SDL_numjoysticks = 0; - return 0; - } - /* IOServiceGetMatchingServices consumes a reference to the dictionary, so we don't need to release the dictionary ref. */ - - /* build flat linked list of devices from device iterator */ - - gpDeviceList = lastDevice = NULL; - - while ((ioHIDDeviceObject = IOIteratorNext (hidObjectIterator))) - { - /* build a device record */ - device = HIDBuildDevice (ioHIDDeviceObject); - if (!device) - continue; - - /* dump device object, it is no longer needed */ - result = IOObjectRelease (ioHIDDeviceObject); + IOReturn result = kIOReturnSuccess; + mach_port_t masterPort = 0; + io_iterator_t hidObjectIterator = 0; + CFMutableDictionaryRef hidMatchDictionary = NULL; + recDevice *device, *lastDevice; + io_object_t ioHIDDeviceObject = 0; + + SDL_numjoysticks = 0; + + if (gpDeviceList) { + SDL_SetError("Joystick: Device list already inited."); + return -1; + } + + result = IOMasterPort(bootstrap_port, &masterPort); + if (kIOReturnSuccess != result) { + SDL_SetError("Joystick: IOMasterPort error with bootstrap_port."); + return -1; + } + + /* Set up a matching dictionary to search I/O Registry by class name for all HID class devices. */ + hidMatchDictionary = IOServiceMatching(kIOHIDDeviceKey); + if (hidMatchDictionary) { + /* Add key for device type (joystick, in this case) to refine the matching dictionary. */ + + /* NOTE: we now perform this filtering later + UInt32 usagePage = kHIDPage_GenericDesktop; + UInt32 usage = kHIDUsage_GD_Joystick; + CFNumberRef refUsage = NULL, refUsagePage = NULL; + + refUsage = CFNumberCreate (kCFAllocatorDefault, kCFNumberIntType, &usage); + CFDictionarySetValue (hidMatchDictionary, CFSTR (kIOHIDPrimaryUsageKey), refUsage); + refUsagePage = CFNumberCreate (kCFAllocatorDefault, kCFNumberIntType, &usagePage); + CFDictionarySetValue (hidMatchDictionary, CFSTR (kIOHIDPrimaryUsagePageKey), refUsagePage); + */ + } else { + SDL_SetError + ("Joystick: Failed to get HID CFMutableDictionaryRef via IOServiceMatching."); + return -1; + } + + /*/ Now search I/O Registry for matching devices. */ + result = + IOServiceGetMatchingServices(masterPort, hidMatchDictionary, + &hidObjectIterator); + /* Check for errors */ + if (kIOReturnSuccess != result) { + SDL_SetError("Joystick: Couldn't create a HID object iterator."); + return -1; + } + if (!hidObjectIterator) { /* there are no joysticks */ + gpDeviceList = NULL; + SDL_numjoysticks = 0; + return 0; + } + /* IOServiceGetMatchingServices consumes a reference to the dictionary, so we don't need to release the dictionary ref. */ + + /* build flat linked list of devices from device iterator */ + + gpDeviceList = lastDevice = NULL; + + while ((ioHIDDeviceObject = IOIteratorNext(hidObjectIterator))) { + /* build a device record */ + device = HIDBuildDevice(ioHIDDeviceObject); + if (!device) + continue; + + /* dump device object, it is no longer needed */ + result = IOObjectRelease(ioHIDDeviceObject); /* if (KERN_SUCCESS != result) HIDReportErrorNum ("IOObjectRelease error with ioHIDDeviceObject.", result); */ - /* Filter device list to non-keyboard/mouse stuff */ - if ( (device->usagePage != kHIDPage_GenericDesktop) || - ((device->usage != kHIDUsage_GD_Joystick && - device->usage != kHIDUsage_GD_GamePad)) ) { - - /* release memory for the device */ - HIDDisposeDevice (&device); - DisposePtr((Ptr)device); - continue; - } - - /* Add device to the end of the list */ - if (lastDevice) - lastDevice->pNext = device; - else - gpDeviceList = device; - lastDevice = device; - } - result = IOObjectRelease (hidObjectIterator); /* release the iterator */ - - /* Count the total number of devices we found */ - device = gpDeviceList; - while (device) - { - SDL_numjoysticks++; - device = device->pNext; - } - - return SDL_numjoysticks; + /* Filter device list to non-keyboard/mouse stuff */ + if ((device->usagePage != kHIDPage_GenericDesktop) || + ((device->usage != kHIDUsage_GD_Joystick && + device->usage != kHIDUsage_GD_GamePad))) { + + /* release memory for the device */ + HIDDisposeDevice(&device); + DisposePtr((Ptr) device); + continue; + } + + /* Add device to the end of the list */ + if (lastDevice) + lastDevice->pNext = device; + else + gpDeviceList = device; + lastDevice = device; + } + result = IOObjectRelease(hidObjectIterator); /* release the iterator */ + + /* Count the total number of devices we found */ + device = gpDeviceList; + while (device) { + SDL_numjoysticks++; + device = device->pNext; + } + + return SDL_numjoysticks; } /* Function to get the device-dependent name of a joystick */ -const char *SDL_SYS_JoystickName(int index) +const char * +SDL_SYS_JoystickName(int index) { - recDevice *device = gpDeviceList; - - for (; index > 0; index--) - device = device->pNext; + recDevice *device = gpDeviceList; - return device->product; + for (; index > 0; index--) + device = device->pNext; + + return device->product; } /* Function to open a joystick for use. @@ -696,23 +736,24 @@ const char *SDL_SYS_JoystickName(int index) * This should fill the nbuttons and naxes fields of the joystick structure. * It returns 0, or -1 if there is an error. */ -int SDL_SYS_JoystickOpen(SDL_Joystick *joystick) +int +SDL_SYS_JoystickOpen(SDL_Joystick * joystick) { - recDevice *device = gpDeviceList; - int index; - - for (index = joystick->index; index > 0; index--) - device = device->pNext; + recDevice *device = gpDeviceList; + int index; + + for (index = joystick->index; index > 0; index--) + device = device->pNext; - joystick->hwdata = device; - joystick->name = device->product; + joystick->hwdata = device; + joystick->name = device->product; - joystick->naxes = device->axes; - joystick->nhats = device->hats; - joystick->nballs = 0; - joystick->nbuttons = device->buttons; + joystick->naxes = device->axes; + joystick->nhats = device->hats; + joystick->nballs = 0; + joystick->nbuttons = device->buttons; - return 0; + return 0; } /* Function to update the state of a joystick - called as a device poll. @@ -720,123 +761,121 @@ int SDL_SYS_JoystickOpen(SDL_Joystick *joystick) * but instead should call SDL_PrivateJoystick*() to deliver events * and update joystick device state. */ -void SDL_SYS_JoystickUpdate(SDL_Joystick *joystick) +void +SDL_SYS_JoystickUpdate(SDL_Joystick * joystick) { - recDevice *device = joystick->hwdata; - recElement *element; - SInt32 value; - int i; - - if (device->removed) /* device was unplugged; ignore it. */ - { - if (device->uncentered) - { - device->uncentered = 0; - - /* Tell the app that everything is centered/unpressed... */ - for (i = 0; i < device->axes; i++) - SDL_PrivateJoystickAxis(joystick, i, 0); - - for (i = 0; i < device->buttons; i++) - SDL_PrivateJoystickButton(joystick, i, 0); - - for (i = 0; i < device->hats; i++) - SDL_PrivateJoystickHat(joystick, i, SDL_HAT_CENTERED); - } - - return; - } - - element = device->firstAxis; - i = 0; - while (element) - { - value = HIDScaledCalibratedValue(device, element, -32768, 32767); - if ( value != joystick->axes[i] ) - SDL_PrivateJoystickAxis(joystick, i, value); - element = element->pNext; - ++i; - } - - element = device->firstButton; - i = 0; - while (element) - { - value = HIDGetElementValue(device, element); - if (value > 1) /* handle pressure-sensitive buttons */ + recDevice *device = joystick->hwdata; + recElement *element; + SInt32 value; + int i; + + if (device->removed) { /* device was unplugged; ignore it. */ + if (device->uncentered) { + device->uncentered = 0; + + /* Tell the app that everything is centered/unpressed... */ + for (i = 0; i < device->axes; i++) + SDL_PrivateJoystickAxis(joystick, i, 0); + + for (i = 0; i < device->buttons; i++) + SDL_PrivateJoystickButton(joystick, i, 0); + + for (i = 0; i < device->hats; i++) + SDL_PrivateJoystickHat(joystick, i, SDL_HAT_CENTERED); + } + + return; + } + + element = device->firstAxis; + i = 0; + while (element) { + value = HIDScaledCalibratedValue(device, element, -32768, 32767); + if (value != joystick->axes[i]) + SDL_PrivateJoystickAxis(joystick, i, value); + element = element->pNext; + ++i; + } + + element = device->firstButton; + i = 0; + while (element) { + value = HIDGetElementValue(device, element); + if (value > 1) /* handle pressure-sensitive buttons */ value = 1; - if ( value != joystick->buttons[i] ) - SDL_PrivateJoystickButton(joystick, i, value); - element = element->pNext; - ++i; - } - - element = device->firstHat; - i = 0; - while (element) - { - Uint8 pos = 0; - - value = HIDGetElementValue(device, element); - if (element->max == 3) /* 4 position hatswitch - scale up value */ - value *= 2; - else if (element->max != 7) /* Neither a 4 nor 8 positions - fall back to default position (centered) */ - value = -1; - switch(value) - { - case 0: - pos = SDL_HAT_UP; - break; - case 1: - pos = SDL_HAT_RIGHTUP; - break; - case 2: - pos = SDL_HAT_RIGHT; - break; - case 3: - pos = SDL_HAT_RIGHTDOWN; - break; - case 4: - pos = SDL_HAT_DOWN; - break; - case 5: - pos = SDL_HAT_LEFTDOWN; - break; - case 6: - pos = SDL_HAT_LEFT; - break; - case 7: - pos = SDL_HAT_LEFTUP; - break; - default: - /* Every other value is mapped to center. We do that because some - * joysticks use 8 and some 15 for this value, and apparently - * there are even more variants out there - so we try to be generous. - */ - pos = SDL_HAT_CENTERED; - break; - } - if ( pos != joystick->hats[i] ) - SDL_PrivateJoystickHat(joystick, i, pos); - element = element->pNext; - ++i; - } - - return; + if (value != joystick->buttons[i]) + SDL_PrivateJoystickButton(joystick, i, value); + element = element->pNext; + ++i; + } + + element = device->firstHat; + i = 0; + while (element) { + Uint8 pos = 0; + + value = HIDGetElementValue(device, element); + if (element->max == 3) /* 4 position hatswitch - scale up value */ + value *= 2; + else if (element->max != 7) /* Neither a 4 nor 8 positions - fall back to default position (centered) */ + value = -1; + switch (value) { + case 0: + pos = SDL_HAT_UP; + break; + case 1: + pos = SDL_HAT_RIGHTUP; + break; + case 2: + pos = SDL_HAT_RIGHT; + break; + case 3: + pos = SDL_HAT_RIGHTDOWN; + break; + case 4: + pos = SDL_HAT_DOWN; + break; + case 5: + pos = SDL_HAT_LEFTDOWN; + break; + case 6: + pos = SDL_HAT_LEFT; + break; + case 7: + pos = SDL_HAT_LEFTUP; + break; + default: + /* Every other value is mapped to center. We do that because some + * joysticks use 8 and some 15 for this value, and apparently + * there are even more variants out there - so we try to be generous. + */ + pos = SDL_HAT_CENTERED; + break; + } + if (pos != joystick->hats[i]) + SDL_PrivateJoystickHat(joystick, i, pos); + element = element->pNext; + ++i; + } + + return; } /* Function to close a joystick after use */ -void SDL_SYS_JoystickClose(SDL_Joystick *joystick) +void +SDL_SYS_JoystickClose(SDL_Joystick * joystick) { - /* Should we do anything here? */ - return; + /* Should we do anything here? */ + return; } /* Function to perform any system-specific joystick related cleanup */ -void SDL_SYS_JoystickQuit(void) +void +SDL_SYS_JoystickQuit(void) { - while (NULL != gpDeviceList) - gpDeviceList = HIDDisposeDevice (&gpDeviceList); + while (NULL != gpDeviceList) + gpDeviceList = HIDDisposeDevice(&gpDeviceList); } #endif /* SDL_JOYSTICK_IOKIT */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/joystick/dc/SDL_sysjoystick.c b/src/joystick/dc/SDL_sysjoystick.c index ac7247334..ee2b7f850 100644 --- a/src/joystick/dc/SDL_sysjoystick.c +++ b/src/joystick/dc/SDL_sysjoystick.c @@ -31,21 +31,21 @@ #include #include -#define MAX_JOYSTICKS 8 /* only 2 are supported in the multimedia API */ -#define MAX_AXES 6 /* each joystick can have up to 6 axes */ -#define MAX_BUTTONS 8 /* and 8 buttons */ +#define MAX_JOYSTICKS 8 /* only 2 are supported in the multimedia API */ +#define MAX_AXES 6 /* each joystick can have up to 6 axes */ +#define MAX_BUTTONS 8 /* and 8 buttons */ #define MAX_HATS 2 #define JOYNAMELEN 8 /* array to hold joystick ID values */ -static uint8 SYS_Joystick_addr[MAX_JOYSTICKS]; +static uint8 SYS_Joystick_addr[MAX_JOYSTICKS]; /* The private structure used to keep track of a joystick */ struct joystick_hwdata { - cont_cond_t prev_cond; - int prev_buttons; + cont_cond_t prev_cond; + int prev_buttons; }; /* Function to scan the system for joysticks. @@ -53,31 +53,35 @@ struct joystick_hwdata * joysticks. Joystick 0 should be the system default joystick. * It should return 0, or -1 on an unrecoverable fatal error. */ -int SDL_SYS_JoystickInit(void) +int +SDL_SYS_JoystickInit(void) { - int numdevs; + int numdevs; - int p,u; + int p, u; - numdevs = 0; - for(p=0;pinfo.product_name; + maple_device_t *dev; + if (maple_compat_resolve + (SYS_Joystick_addr[index], &dev, MAPLE_FUNC_CONTROLLER) != 0) + return NULL; + return dev->info.product_name; } /* Function to open a joystick for use. @@ -85,22 +89,23 @@ const char *SDL_SYS_JoystickName(int index) This should fill the nbuttons and naxes fields of the joystick structure. It returns 0, or -1 if there is an error. */ -int SDL_SYS_JoystickOpen(SDL_Joystick *joystick) +int +SDL_SYS_JoystickOpen(SDL_Joystick * joystick) { - /* allocate memory for system specific hardware data */ - joystick->hwdata = (struct joystick_hwdata *) SDL_malloc(sizeof(*joystick->hwdata)); - if (joystick->hwdata == NULL) - { - SDL_OutOfMemory(); - return(-1); - } - SDL_memset(joystick->hwdata, 0, sizeof(*joystick->hwdata)); - - /* fill nbuttons, naxes, and nhats fields */ - joystick->nbuttons = MAX_BUTTONS; - joystick->naxes = MAX_AXES; - joystick->nhats = MAX_HATS; - return(0); + /* allocate memory for system specific hardware data */ + joystick->hwdata = + (struct joystick_hwdata *) SDL_malloc(sizeof(*joystick->hwdata)); + if (joystick->hwdata == NULL) { + SDL_OutOfMemory(); + return (-1); + } + SDL_memset(joystick->hwdata, 0, sizeof(*joystick->hwdata)); + + /* fill nbuttons, naxes, and nhats fields */ + joystick->nbuttons = MAX_BUTTONS; + joystick->naxes = MAX_AXES; + joystick->nhats = MAX_HATS; + return (0); } @@ -110,84 +115,102 @@ int SDL_SYS_JoystickOpen(SDL_Joystick *joystick) * and update joystick device state. */ -void SDL_SYS_JoystickUpdate(SDL_Joystick *joystick) +void +SDL_SYS_JoystickUpdate(SDL_Joystick * joystick) { -const int sdl_buttons[] = { - CONT_C, - CONT_B, - CONT_A, - CONT_START, - CONT_Z, - CONT_Y, - CONT_X, - CONT_D -}; - - uint8 addr; - cont_cond_t cond,*prev_cond; - int buttons,prev_buttons,i,changed; - - addr = SYS_Joystick_addr[joystick->index]; - if (cont_get_cond(addr,&cond)<0) return; - - buttons = cond.buttons; - prev_buttons = joystick->hwdata->prev_buttons; - changed = buttons^prev_buttons; - - if ((changed)&(CONT_DPAD_UP|CONT_DPAD_DOWN|CONT_DPAD_LEFT|CONT_DPAD_RIGHT)) { - int hat = SDL_HAT_CENTERED; - if (buttons&CONT_DPAD_UP) hat|=SDL_HAT_UP; - if (buttons&CONT_DPAD_DOWN) hat|=SDL_HAT_DOWN; - if (buttons&CONT_DPAD_LEFT) hat|=SDL_HAT_LEFT; - if (buttons&CONT_DPAD_RIGHT) hat|=SDL_HAT_RIGHT; - SDL_PrivateJoystickHat(joystick, 0, hat); - } - if ((changed)&(CONT_DPAD2_UP|CONT_DPAD2_DOWN|CONT_DPAD2_LEFT|CONT_DPAD2_RIGHT)) { - int hat = SDL_HAT_CENTERED; - if (buttons&CONT_DPAD2_UP) hat|=SDL_HAT_UP; - if (buttons&CONT_DPAD2_DOWN) hat|=SDL_HAT_DOWN; - if (buttons&CONT_DPAD2_LEFT) hat|=SDL_HAT_LEFT; - if (buttons&CONT_DPAD2_RIGHT) hat|=SDL_HAT_RIGHT; - SDL_PrivateJoystickHat(joystick, 1, hat); - } - - for(i=0;ihwdata->prev_cond; - if (cond.joyx!=prev_cond->joyx) - SDL_PrivateJoystickAxis(joystick, 0, cond.joyx-128); - if (cond.joyy!=prev_cond->joyy) - SDL_PrivateJoystickAxis(joystick, 1, cond.joyy-128); - if (cond.rtrig!=prev_cond->rtrig) - SDL_PrivateJoystickAxis(joystick, 2, cond.rtrig); - if (cond.ltrig!=prev_cond->ltrig) - SDL_PrivateJoystickAxis(joystick, 3, cond.ltrig); - if (cond.joy2x!=prev_cond->joy2x) - SDL_PrivateJoystickAxis(joystick, 4, cond.joy2x-128); - if (cond.joy2y!=prev_cond->joy2y) - SDL_PrivateJoystickAxis(joystick, 5, cond.joy2y-128); - - joystick->hwdata->prev_buttons = buttons; - joystick->hwdata->prev_cond = cond; + const int sdl_buttons[] = { + CONT_C, + CONT_B, + CONT_A, + CONT_START, + CONT_Z, + CONT_Y, + CONT_X, + CONT_D + }; + + uint8 addr; + cont_cond_t cond, *prev_cond; + int buttons, prev_buttons, i, changed; + + addr = SYS_Joystick_addr[joystick->index]; + if (cont_get_cond(addr, &cond) < 0) + return; + + buttons = cond.buttons; + prev_buttons = joystick->hwdata->prev_buttons; + changed = buttons ^ prev_buttons; + + if ((changed) & + (CONT_DPAD_UP | CONT_DPAD_DOWN | CONT_DPAD_LEFT | CONT_DPAD_RIGHT)) { + int hat = SDL_HAT_CENTERED; + if (buttons & CONT_DPAD_UP) + hat |= SDL_HAT_UP; + if (buttons & CONT_DPAD_DOWN) + hat |= SDL_HAT_DOWN; + if (buttons & CONT_DPAD_LEFT) + hat |= SDL_HAT_LEFT; + if (buttons & CONT_DPAD_RIGHT) + hat |= SDL_HAT_RIGHT; + SDL_PrivateJoystickHat(joystick, 0, hat); + } + if ((changed) & + (CONT_DPAD2_UP | CONT_DPAD2_DOWN | CONT_DPAD2_LEFT | + CONT_DPAD2_RIGHT)) { + int hat = SDL_HAT_CENTERED; + if (buttons & CONT_DPAD2_UP) + hat |= SDL_HAT_UP; + if (buttons & CONT_DPAD2_DOWN) + hat |= SDL_HAT_DOWN; + if (buttons & CONT_DPAD2_LEFT) + hat |= SDL_HAT_LEFT; + if (buttons & CONT_DPAD2_RIGHT) + hat |= SDL_HAT_RIGHT; + SDL_PrivateJoystickHat(joystick, 1, hat); + } + + for (i = 0; i < sizeof(sdl_buttons) / sizeof(sdl_buttons[0]); i++) { + if (changed & sdl_buttons[i]) { + SDL_PrivateJoystickButton(joystick, i, + (buttons & sdl_buttons[i]) ? + SDL_PRESSED : SDL_RELEASED); + } + } + + prev_cond = &joystick->hwdata->prev_cond; + if (cond.joyx != prev_cond->joyx) + SDL_PrivateJoystickAxis(joystick, 0, cond.joyx - 128); + if (cond.joyy != prev_cond->joyy) + SDL_PrivateJoystickAxis(joystick, 1, cond.joyy - 128); + if (cond.rtrig != prev_cond->rtrig) + SDL_PrivateJoystickAxis(joystick, 2, cond.rtrig); + if (cond.ltrig != prev_cond->ltrig) + SDL_PrivateJoystickAxis(joystick, 3, cond.ltrig); + if (cond.joy2x != prev_cond->joy2x) + SDL_PrivateJoystickAxis(joystick, 4, cond.joy2x - 128); + if (cond.joy2y != prev_cond->joy2y) + SDL_PrivateJoystickAxis(joystick, 5, cond.joy2y - 128); + + joystick->hwdata->prev_buttons = buttons; + joystick->hwdata->prev_cond = cond; } /* Function to close a joystick after use */ -void SDL_SYS_JoystickClose(SDL_Joystick *joystick) +void +SDL_SYS_JoystickClose(SDL_Joystick * joystick) { - if (joystick->hwdata != NULL) { - /* free system specific hardware data */ - SDL_free(joystick->hwdata); - } + if (joystick->hwdata != NULL) { + /* free system specific hardware data */ + SDL_free(joystick->hwdata); + } } /* Function to perform any system-specific joystick related cleanup */ -void SDL_SYS_JoystickQuit(void) +void +SDL_SYS_JoystickQuit(void) { - return; + return; } #endif /* SDL_JOYSTICK_DC */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/joystick/dummy/SDL_sysjoystick.c b/src/joystick/dummy/SDL_sysjoystick.c index f3209a2c3..e829dee33 100644 --- a/src/joystick/dummy/SDL_sysjoystick.c +++ b/src/joystick/dummy/SDL_sysjoystick.c @@ -34,17 +34,19 @@ * joysticks. Joystick 0 should be the system default joystick. * It should return 0, or -1 on an unrecoverable fatal error. */ -int SDL_SYS_JoystickInit(void) +int +SDL_SYS_JoystickInit(void) { - SDL_numjoysticks = 0; - return(0); + SDL_numjoysticks = 0; + return (0); } /* Function to get the device-dependent name of a joystick */ -const char *SDL_SYS_JoystickName(int index) +const char * +SDL_SYS_JoystickName(int index) { - SDL_SetError("Logic error: No joysticks available"); - return(NULL); + SDL_SetError("Logic error: No joysticks available"); + return (NULL); } /* Function to open a joystick for use. @@ -52,10 +54,11 @@ const char *SDL_SYS_JoystickName(int index) This should fill the nbuttons and naxes fields of the joystick structure. It returns 0, or -1 if there is an error. */ -int SDL_SYS_JoystickOpen(SDL_Joystick *joystick) +int +SDL_SYS_JoystickOpen(SDL_Joystick * joystick) { - SDL_SetError("Logic error: No joysticks available"); - return(-1); + SDL_SetError("Logic error: No joysticks available"); + return (-1); } /* Function to update the state of a joystick - called as a device poll. @@ -63,21 +66,25 @@ int SDL_SYS_JoystickOpen(SDL_Joystick *joystick) * but instead should call SDL_PrivateJoystick*() to deliver events * and update joystick device state. */ -void SDL_SYS_JoystickUpdate(SDL_Joystick *joystick) +void +SDL_SYS_JoystickUpdate(SDL_Joystick * joystick) { - return; + return; } /* Function to close a joystick after use */ -void SDL_SYS_JoystickClose(SDL_Joystick *joystick) +void +SDL_SYS_JoystickClose(SDL_Joystick * joystick) { - return; + return; } /* Function to perform any system-specific joystick related cleanup */ -void SDL_SYS_JoystickQuit(void) +void +SDL_SYS_JoystickQuit(void) { - return; + return; } #endif /* SDL_JOYSTICK_DUMMY || SDL_JOYSTICK_DISABLED */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/joystick/linux/SDL_sysjoystick.c b/src/joystick/linux/SDL_sysjoystick.c index 37cf4efe0..be49a3a45 100644 --- a/src/joystick/linux/SDL_sysjoystick.c +++ b/src/joystick/linux/SDL_sysjoystick.c @@ -29,7 +29,7 @@ #include #include #include -#include /* For the definition of PATH_MAX */ +#include /* For the definition of PATH_MAX */ #include #if SDL_INPUT_LINUXEV #include @@ -40,22 +40,25 @@ #include "../SDL_joystick_c.h" /* Special joystick configurations */ -static struct { - const char *name; - int naxes; - int nhats; - int nballs; +static struct +{ + const char *name; + int naxes; + int nhats; + int nballs; } special_joysticks[] = { - { "MadCatz Panther XL", 3, 2, 1 }, /* We don't handle rudder (axis 8) */ - { "SideWinder Precision Pro", 4, 1, 0 }, - { "SideWinder 3D Pro", 4, 1, 0 }, - { "Microsoft SideWinder 3D Pro", 4, 1, 0 }, - { "Microsoft SideWinder Dual Strike USB version 1.0", 2, 1, 0 }, - { "WingMan Interceptor", 3, 3, 0 }, - { "WingMan Extreme Digital 3D", 4, 1, 0 }, - { "Microsoft SideWinder Precision 2 Joystick", 4, 1, 0 }, - { "Logitech Inc. WingMan Extreme Digital 3D", 4, 1, 0 }, - { "Saitek Saitek X45", 6, 1, 0 } + { + "MadCatz Panther XL", 3, 2, 1}, /* We don't handle rudder (axis 8) */ + { + "SideWinder Precision Pro", 4, 1, 0}, { + "SideWinder 3D Pro", 4, 1, 0}, { + "Microsoft SideWinder 3D Pro", 4, 1, 0}, { + "Microsoft SideWinder Dual Strike USB version 1.0", 2, 1, 0}, { + "WingMan Interceptor", 3, 3, 0}, { + "WingMan Extreme Digital 3D", 4, 1, 0}, { + "Microsoft SideWinder Precision 2 Joystick", 4, 1, 0}, { + "Logitech Inc. WingMan Extreme Digital 3D", 4, 1, 0}, { + "Saitek Saitek X45", 6, 1, 0} }; #ifndef NO_LOGICAL_JOYSTICKS @@ -71,9 +74,10 @@ static struct { -id */ -struct joystick_logical_mapping { - int njoy; - int nthing; +struct joystick_logical_mapping +{ + int njoy; + int nthing; }; /* @@ -84,69 +88,80 @@ struct joystick_logical_mapping { */ static struct joystick_logical_mapping mp88xx_1_logical_axismap[] = { - {0,0},{0,1},{0,2},{0,3},{0,4},{0,5} + {0, 0}, {0, 1}, {0, 2}, {0, 3}, {0, 4}, {0, 5} }; static struct joystick_logical_mapping mp88xx_1_logical_buttonmap[] = { - {0,0},{0,1},{0,2},{0,3},{0,4},{0,5},{0,6},{0,7},{0,8},{0,9},{0,10},{0,11} + {0, 0}, {0, 1}, {0, 2}, {0, 3}, {0, 4}, {0, 5}, {0, 6}, {0, 7}, {0, 8}, + {0, 9}, {0, 10}, {0, 11} }; static struct joystick_logical_mapping mp88xx_2_logical_axismap[] = { - {0,0},{0,1},{0,2},{1,0},{1,1},{0,3}, - {1,2},{1,3},{0,4},{0,5},{1,4},{1,5} + {0, 0}, {0, 1}, {0, 2}, {1, 0}, {1, 1}, {0, 3}, + {1, 2}, {1, 3}, {0, 4}, {0, 5}, {1, 4}, {1, 5} }; static struct joystick_logical_mapping mp88xx_2_logical_buttonmap[] = { - {0,0},{0,1},{0,2},{0,3},{0,4},{0,5},{0,6},{0,7},{0,8},{0,9},{0,10},{0,11}, - {1,0},{1,1},{1,2},{1,3},{1,4},{1,5},{1,6},{1,7},{1,8},{1,9},{1,10},{1,11} + {0, 0}, {0, 1}, {0, 2}, {0, 3}, {0, 4}, {0, 5}, {0, 6}, {0, 7}, {0, 8}, + {0, 9}, {0, 10}, {0, 11}, + {1, 0}, {1, 1}, {1, 2}, {1, 3}, {1, 4}, {1, 5}, {1, 6}, {1, 7}, {1, 8}, + {1, 9}, {1, 10}, {1, 11} }; static struct joystick_logical_mapping mp88xx_3_logical_axismap[] = { - {0,0},{0,1},{0,2},{1,0},{1,1},{0,3}, - {1,2},{1,3},{2,0},{2,1},{2,2},{2,3}, - {0,4},{0,5},{1,4},{1,5},{2,4},{2,5} + {0, 0}, {0, 1}, {0, 2}, {1, 0}, {1, 1}, {0, 3}, + {1, 2}, {1, 3}, {2, 0}, {2, 1}, {2, 2}, {2, 3}, + {0, 4}, {0, 5}, {1, 4}, {1, 5}, {2, 4}, {2, 5} }; static struct joystick_logical_mapping mp88xx_3_logical_buttonmap[] = { - {0,0},{0,1},{0,2},{0,3},{0,4},{0,5},{0,6},{0,7},{0,8},{0,9},{0,10},{0,11}, - {1,0},{1,1},{1,2},{1,3},{1,4},{1,5},{1,6},{1,7},{1,8},{1,9},{1,10},{1,11}, - {2,0},{2,1},{2,2},{2,3},{2,4},{2,5},{2,6},{2,7},{2,8},{2,9},{2,10},{2,11} + {0, 0}, {0, 1}, {0, 2}, {0, 3}, {0, 4}, {0, 5}, {0, 6}, {0, 7}, {0, 8}, + {0, 9}, {0, 10}, {0, 11}, + {1, 0}, {1, 1}, {1, 2}, {1, 3}, {1, 4}, {1, 5}, {1, 6}, {1, 7}, {1, 8}, + {1, 9}, {1, 10}, {1, 11}, + {2, 0}, {2, 1}, {2, 2}, {2, 3}, {2, 4}, {2, 5}, {2, 6}, {2, 7}, {2, 8}, + {2, 9}, {2, 10}, {2, 11} }; static struct joystick_logical_mapping mp88xx_4_logical_axismap[] = { - {0,0},{0,1},{0,2},{1,0},{1,1},{0,3}, - {1,2},{1,3},{2,0},{2,1},{2,2},{2,3}, - {3,0},{3,1},{3,2},{3,3},{0,4},{0,5}, - {1,4},{1,5},{2,4},{2,5},{3,4},{3,5} + {0, 0}, {0, 1}, {0, 2}, {1, 0}, {1, 1}, {0, 3}, + {1, 2}, {1, 3}, {2, 0}, {2, 1}, {2, 2}, {2, 3}, + {3, 0}, {3, 1}, {3, 2}, {3, 3}, {0, 4}, {0, 5}, + {1, 4}, {1, 5}, {2, 4}, {2, 5}, {3, 4}, {3, 5} }; static struct joystick_logical_mapping mp88xx_4_logical_buttonmap[] = { - {0,0},{0,1},{0,2},{0,3},{0,4},{0,5},{0,6},{0,7},{0,8},{0,9},{0,10},{0,11}, - {1,0},{1,1},{1,2},{1,3},{1,4},{1,5},{1,6},{1,7},{1,8},{1,9},{1,10},{1,11}, - {2,0},{2,1},{2,2},{2,3},{2,4},{2,5},{2,6},{2,7},{2,8},{2,9},{2,10},{2,11}, - {3,0},{3,1},{3,2},{3,3},{3,4},{3,5},{3,6},{3,7},{3,8},{3,9},{3,10},{3,11} + {0, 0}, {0, 1}, {0, 2}, {0, 3}, {0, 4}, {0, 5}, {0, 6}, {0, 7}, {0, 8}, + {0, 9}, {0, 10}, {0, 11}, + {1, 0}, {1, 1}, {1, 2}, {1, 3}, {1, 4}, {1, 5}, {1, 6}, {1, 7}, {1, 8}, + {1, 9}, {1, 10}, {1, 11}, + {2, 0}, {2, 1}, {2, 2}, {2, 3}, {2, 4}, {2, 5}, {2, 6}, {2, 7}, {2, 8}, + {2, 9}, {2, 10}, {2, 11}, + {3, 0}, {3, 1}, {3, 2}, {3, 3}, {3, 4}, {3, 5}, {3, 6}, {3, 7}, {3, 8}, + {3, 9}, {3, 10}, {3, 11} }; -struct joystick_logical_layout { - int naxes; - int nhats; - int nballs; - int nbuttons; +struct joystick_logical_layout +{ + int naxes; + int nhats; + int nballs; + int nbuttons; }; static struct joystick_logical_layout mp88xx_1_logical_layout[] = { - {6, 0, 0, 12} + {6, 0, 0, 12} }; static struct joystick_logical_layout mp88xx_2_logical_layout[] = { - {6, 0, 0, 12}, - {6, 0, 0, 12} + {6, 0, 0, 12}, + {6, 0, 0, 12} }; static struct joystick_logical_layout mp88xx_3_logical_layout[] = { - {6, 0, 0, 12}, - {6, 0, 0, 12}, - {6, 0, 0, 12} + {6, 0, 0, 12}, + {6, 0, 0, 12}, + {6, 0, 0, 12} }; static struct joystick_logical_layout mp88xx_4_logical_layout[] = { - {6, 0, 0, 12}, - {6, 0, 0, 12}, - {6, 0, 0, 12}, - {6, 0, 0, 12} + {6, 0, 0, 12}, + {6, 0, 0, 12}, + {6, 0, 0, 12}, + {6, 0, 0, 12} }; /* @@ -162,78 +177,73 @@ static struct joystick_logical_layout mp88xx_4_logical_layout[] = { axes, hats, balls, buttons arrays that map a physical thingy to a logical thingy */ -struct joystick_logicalmap { - const char *name; - int nbuttons; - int njoys; - struct joystick_logical_layout *layout; - struct joystick_logical_mapping *axismap; - struct joystick_logical_mapping *hatmap; - struct joystick_logical_mapping *ballmap; - struct joystick_logical_mapping *buttonmap; +struct joystick_logicalmap +{ + const char *name; + int nbuttons; + int njoys; + struct joystick_logical_layout *layout; + struct joystick_logical_mapping *axismap; + struct joystick_logical_mapping *hatmap; + struct joystick_logical_mapping *ballmap; + struct joystick_logical_mapping *buttonmap; }; static struct joystick_logicalmap joystick_logicalmap[] = { - { - "WiseGroup.,Ltd MP-8866 Dual USB Joypad", - 12, - 1, - mp88xx_1_logical_layout, - mp88xx_1_logical_axismap, - NULL, - NULL, - mp88xx_1_logical_buttonmap - }, - { - "WiseGroup.,Ltd MP-8866 Dual USB Joypad", - 24, - 2, - mp88xx_2_logical_layout, - mp88xx_2_logical_axismap, - NULL, - NULL, - mp88xx_2_logical_buttonmap - }, - { - "WiseGroup.,Ltd MP-8800 Quad USB Joypad", - 12, - 1, - mp88xx_1_logical_layout, - mp88xx_1_logical_axismap, - NULL, - NULL, - mp88xx_1_logical_buttonmap - }, - { - "WiseGroup.,Ltd MP-8800 Quad USB Joypad", - 24, - 2, - mp88xx_2_logical_layout, - mp88xx_2_logical_axismap, - NULL, - NULL, - mp88xx_2_logical_buttonmap - }, - { - "WiseGroup.,Ltd MP-8800 Quad USB Joypad", - 36, - 3, - mp88xx_3_logical_layout, - mp88xx_3_logical_axismap, - NULL, - NULL, - mp88xx_3_logical_buttonmap - }, - { - "WiseGroup.,Ltd MP-8800 Quad USB Joypad", - 48, - 4, - mp88xx_4_logical_layout, - mp88xx_4_logical_axismap, - NULL, - NULL, - mp88xx_4_logical_buttonmap - } + { + "WiseGroup.,Ltd MP-8866 Dual USB Joypad", + 12, + 1, + mp88xx_1_logical_layout, + mp88xx_1_logical_axismap, + NULL, + NULL, + mp88xx_1_logical_buttonmap}, + { + "WiseGroup.,Ltd MP-8866 Dual USB Joypad", + 24, + 2, + mp88xx_2_logical_layout, + mp88xx_2_logical_axismap, + NULL, + NULL, + mp88xx_2_logical_buttonmap}, + { + "WiseGroup.,Ltd MP-8800 Quad USB Joypad", + 12, + 1, + mp88xx_1_logical_layout, + mp88xx_1_logical_axismap, + NULL, + NULL, + mp88xx_1_logical_buttonmap}, + { + "WiseGroup.,Ltd MP-8800 Quad USB Joypad", + 24, + 2, + mp88xx_2_logical_layout, + mp88xx_2_logical_axismap, + NULL, + NULL, + mp88xx_2_logical_buttonmap}, + { + "WiseGroup.,Ltd MP-8800 Quad USB Joypad", + 36, + 3, + mp88xx_3_logical_layout, + mp88xx_3_logical_axismap, + NULL, + NULL, + mp88xx_3_logical_buttonmap}, + { + "WiseGroup.,Ltd MP-8800 Quad USB Joypad", + 48, + 4, + mp88xx_4_logical_layout, + mp88xx_4_logical_axismap, + NULL, + NULL, + mp88xx_4_logical_buttonmap} }; /* find the head of a linked list, given a point in it @@ -256,114 +266,120 @@ static struct joystick_logicalmap joystick_logicalmap[] = { /* A list of available joysticks */ static struct { - char* fname; + char *fname; #ifndef NO_LOGICAL_JOYSTICKS - SDL_Joystick* joy; - struct joystick_logicalmap* map; - int prev; - int next; - int logicalno; -#endif /* USE_LOGICAL_JOYSTICKS */ + SDL_Joystick *joy; + struct joystick_logicalmap *map; + int prev; + int next; + int logicalno; +#endif /* USE_LOGICAL_JOYSTICKS */ } SDL_joylist[MAX_JOYSTICKS]; /* The private structure used to keep track of a joystick */ -struct joystick_hwdata { - int fd; - /* The current linux joystick driver maps hats to two axes */ - struct hwdata_hat { - int axis[2]; - } *hats; - /* The current linux joystick driver maps balls to two axes */ - struct hwdata_ball { - int axis[2]; - } *balls; - - /* Support for the Linux 2.4 unified input interface */ +struct joystick_hwdata +{ + int fd; + /* The current linux joystick driver maps hats to two axes */ + struct hwdata_hat + { + int axis[2]; + } *hats; + /* The current linux joystick driver maps balls to two axes */ + struct hwdata_ball + { + int axis[2]; + } *balls; + + /* Support for the Linux 2.4 unified input interface */ #if SDL_INPUT_LINUXEV - SDL_bool is_hid; - Uint8 key_map[KEY_MAX-BTN_MISC]; - Uint8 abs_map[ABS_MAX]; - struct axis_correct { - int used; - int coef[3]; - } abs_correct[ABS_MAX]; + SDL_bool is_hid; + Uint8 key_map[KEY_MAX - BTN_MISC]; + Uint8 abs_map[ABS_MAX]; + struct axis_correct + { + int used; + int coef[3]; + } abs_correct[ABS_MAX]; #endif }; #ifndef NO_LOGICAL_JOYSTICKS -static int CountLogicalJoysticks(int max) +static int +CountLogicalJoysticks(int max) { - register int i, j, k, ret, prev; - const char* name; - int nbuttons, fd; - unsigned char n; - - ret = 0; - - for(i = 0; i < max; i++) { - name = SDL_SYS_JoystickName(i); - - fd = open(SDL_joylist[i].fname, O_RDONLY, 0); - if ( fd >= 0 ) { - if ( ioctl(fd, JSIOCGBUTTONS, &n) < 0 ) { - nbuttons = -1; - } else { - nbuttons = n; - } - close(fd); - } - else { - nbuttons=-1; - } - - if (name) { - for(j = 0; j < SDL_arraysize(joystick_logicalmap); j++) { - if (!SDL_strcmp(name, joystick_logicalmap[j].name) && (nbuttons==-1 || nbuttons==joystick_logicalmap[j].nbuttons)) { - prev = i; - SDL_joylist[prev].map = &(joystick_logicalmap[j]); - - for(k = 1; k < joystick_logicalmap[j].njoys; k++) { - SDL_joylist[prev].next = max + ret; - SDL_joylist[max+ret].prev = prev; - - prev = max + ret; - SDL_joylist[prev].logicalno = k; - SDL_joylist[prev].map = &(joystick_logicalmap[j]); - ret++; - } - - break; + register int i, j, k, ret, prev; + const char *name; + int nbuttons, fd; + unsigned char n; + + ret = 0; + + for (i = 0; i < max; i++) { + name = SDL_SYS_JoystickName(i); + + fd = open(SDL_joylist[i].fname, O_RDONLY, 0); + if (fd >= 0) { + if (ioctl(fd, JSIOCGBUTTONS, &n) < 0) { + nbuttons = -1; + } else { + nbuttons = n; + } + close(fd); + } else { + nbuttons = -1; + } + + if (name) { + for (j = 0; j < SDL_arraysize(joystick_logicalmap); j++) { + if (!SDL_strcmp(name, joystick_logicalmap[j].name) + && (nbuttons == -1 + || nbuttons == joystick_logicalmap[j].nbuttons)) { + prev = i; + SDL_joylist[prev].map = &(joystick_logicalmap[j]); + + for (k = 1; k < joystick_logicalmap[j].njoys; k++) { + SDL_joylist[prev].next = max + ret; + SDL_joylist[max + ret].prev = prev; + + prev = max + ret; + SDL_joylist[prev].logicalno = k; + SDL_joylist[prev].map = &(joystick_logicalmap[j]); + ret++; + } + + break; + } } - } - } - } + } + } - return ret; + return ret; } -static void LogicalSuffix(int logicalno, char* namebuf, int len) +static void +LogicalSuffix(int logicalno, char *namebuf, int len) { - register int slen; - const static char suffixs[] = - "01020304050607080910111213141516171819" - "20212223242526272829303132"; - const char* suffix; - slen = SDL_strlen(namebuf); - suffix = NULL; - - if (logicalno*2> 5])) != 0) -static int EV_IsJoystick(int fd) +static int +EV_IsJoystick(int fd) { - unsigned long evbit[40]; - unsigned long keybit[40]; - unsigned long absbit[40]; - - if ( (ioctl(fd, EVIOCGBIT(0, sizeof(evbit)), evbit) < 0) || - (ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(keybit)), keybit) < 0) || - (ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(absbit)), absbit) < 0) ) { - return(0); - } - if (!(test_bit(EV_KEY, evbit) && test_bit(EV_ABS, evbit) && - test_bit(ABS_X, absbit) && test_bit(ABS_Y, absbit) && - (test_bit(BTN_TRIGGER, keybit) || test_bit(BTN_A, keybit) || test_bit(BTN_1, keybit)))) return 0; - return(1); + unsigned long evbit[40]; + unsigned long keybit[40]; + unsigned long absbit[40]; + + if ((ioctl(fd, EVIOCGBIT(0, sizeof(evbit)), evbit) < 0) || + (ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(keybit)), keybit) < 0) || + (ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(absbit)), absbit) < 0)) { + return (0); + } + if (!(test_bit(EV_KEY, evbit) && test_bit(EV_ABS, evbit) && + test_bit(ABS_X, absbit) && test_bit(ABS_Y, absbit) && + (test_bit(BTN_TRIGGER, keybit) || test_bit(BTN_A, keybit) + || test_bit(BTN_1, keybit)))) + return 0; + return (1); } #endif /* SDL_INPUT_LINUXEV */ /* Function to scan the system for joysticks */ -int SDL_SYS_JoystickInit(void) +int +SDL_SYS_JoystickInit(void) { - /* The base path of the joystick devices */ - const char *joydev_pattern[] = { + /* The base path of the joystick devices */ + const char *joydev_pattern[] = { #if SDL_INPUT_LINUXEV - "/dev/input/event%d", + "/dev/input/event%d", #endif - "/dev/input/js%d", - "/dev/js%d" - }; - int numjoysticks; - int i, j; - int fd; - char path[PATH_MAX]; - dev_t dev_nums[MAX_JOYSTICKS]; /* major/minor device numbers */ - struct stat sb; - int n, duplicate; - - numjoysticks = 0; - - /* First see if the user specified a joystick to use */ - if ( SDL_getenv("SDL_JOYSTICK_DEVICE") != NULL ) { - SDL_strlcpy(path, SDL_getenv("SDL_JOYSTICK_DEVICE"), sizeof(path)); - if ( stat(path, &sb) == 0 ) { - fd = open(path, O_RDONLY, 0); - if ( fd >= 0 ) { - /* Assume the user knows what they're doing. */ - SDL_joylist[numjoysticks].fname = SDL_strdup(path); - if ( SDL_joylist[numjoysticks].fname ) { - dev_nums[numjoysticks] = sb.st_rdev; - ++numjoysticks; - } - close(fd); - } - } - } - - for ( i=0; i= 0) { + /* Assume the user knows what they're doing. */ + SDL_joylist[numjoysticks].fname = SDL_strdup(path); + if (SDL_joylist[numjoysticks].fname) { + dev_nums[numjoysticks] = sb.st_rdev; + ++numjoysticks; + } + close(fd); + } + } + } + + for (i = 0; i < SDL_arraysize(joydev_pattern); ++i) { + for (j = 0; j < MAX_JOYSTICKS; ++j) { + SDL_snprintf(path, SDL_arraysize(path), joydev_pattern[i], j); + + /* rcg06302000 replaced access(F_OK) call with stat(). + * stat() will fail if the file doesn't exist, so it's + * equivalent behaviour. + */ + if (stat(path, &sb) == 0) { + /* Check to make sure it's not already in list. + * This happens when we see a stick via symlink. + */ + duplicate = 0; + for (n = 0; (n < numjoysticks) && !duplicate; ++n) { + if (sb.st_rdev == dev_nums[n]) { + duplicate = 1; + } + } + if (duplicate) { + continue; + } + + fd = open(path, O_RDONLY, 0); + if (fd < 0) { + continue; + } #if SDL_INPUT_LINUXEV #ifdef DEBUG_INPUT_EVENTS - printf("Checking %s\n", path); + printf("Checking %s\n", path); #endif - if ( (i == 0) && ! EV_IsJoystick(fd) ) { - close(fd); - continue; - } + if ((i == 0) && !EV_IsJoystick(fd)) { + close(fd); + continue; + } #endif - close(fd); - - /* We're fine, add this joystick */ - SDL_joylist[numjoysticks].fname = SDL_strdup(path); - if ( SDL_joylist[numjoysticks].fname ) { - dev_nums[numjoysticks] = sb.st_rdev; - ++numjoysticks; - } - } else - break; - } + close(fd); + + /* We're fine, add this joystick */ + SDL_joylist[numjoysticks].fname = SDL_strdup(path); + if (SDL_joylist[numjoysticks].fname) { + dev_nums[numjoysticks] = sb.st_rdev; + ++numjoysticks; + } + } else + break; + } #if SDL_INPUT_LINUXEV - /* This is a special case... - If the event devices are valid then the joystick devices - will be duplicates but without extra information about their - hats or balls. Unfortunately, the event devices can't - currently be calibrated, so it's a win-lose situation. - So : /dev/input/eventX = /dev/input/jsY = /dev/jsY - */ - if ( (i == 0) && (numjoysticks > 0) ) - break; + /* This is a special case... + If the event devices are valid then the joystick devices + will be duplicates but without extra information about their + hats or balls. Unfortunately, the event devices can't + currently be calibrated, so it's a win-lose situation. + So : /dev/input/eventX = /dev/input/jsY = /dev/jsY + */ + if ((i == 0) && (numjoysticks > 0)) + break; #endif - } + } #ifndef NO_LOGICAL_JOYSTICKS - numjoysticks += CountLogicalJoysticks(numjoysticks); + numjoysticks += CountLogicalJoysticks(numjoysticks); #endif - return(numjoysticks); + return (numjoysticks); } /* Function to get the device-dependent name of a joystick */ -const char *SDL_SYS_JoystickName(int index) +const char * +SDL_SYS_JoystickName(int index) { - int fd; - static char namebuf[128]; - char *name; - SDL_logical_joydecl(int oindex = index); + int fd; + static char namebuf[128]; + char *name; + SDL_logical_joydecl(int oindex = index); #ifndef NO_LOGICAL_JOYSTICKS - SDL_joylist_head(index, index); + SDL_joylist_head(index, index); #endif - name = NULL; - fd = open(SDL_joylist[index].fname, O_RDONLY, 0); - if ( fd >= 0 ) { - if ( + name = NULL; + fd = open(SDL_joylist[index].fname, O_RDONLY, 0); + if (fd >= 0) { + if ( #if SDL_INPUT_LINUXEV - (ioctl(fd, EVIOCGNAME(sizeof(namebuf)), namebuf) <= 0) && + (ioctl(fd, EVIOCGNAME(sizeof(namebuf)), namebuf) <= 0) && #endif - (ioctl(fd, JSIOCGNAME(sizeof(namebuf)), namebuf) <= 0) ) { - name = SDL_joylist[index].fname; - } else { - name = namebuf; - } - close(fd); + (ioctl(fd, JSIOCGNAME(sizeof(namebuf)), namebuf) <= 0)) { + name = SDL_joylist[index].fname; + } else { + name = namebuf; + } + close(fd); #ifndef NO_LOGICAL_JOYSTICKS - if (SDL_joylist[oindex].prev || SDL_joylist[oindex].next || index!=oindex) - { - LogicalSuffix(SDL_joylist[oindex].logicalno, namebuf, 128); - } + if (SDL_joylist[oindex].prev || SDL_joylist[oindex].next + || index != oindex) { + LogicalSuffix(SDL_joylist[oindex].logicalno, namebuf, 128); + } #endif - } - return name; + } + return name; } -static int allocate_hatdata(SDL_Joystick *joystick) +static int +allocate_hatdata(SDL_Joystick * joystick) { - int i; - - joystick->hwdata->hats = (struct hwdata_hat *)SDL_malloc( - joystick->nhats * sizeof(struct hwdata_hat)); - if ( joystick->hwdata->hats == NULL ) { - return(-1); - } - for ( i=0; inhats; ++i ) { - joystick->hwdata->hats[i].axis[0] = 1; - joystick->hwdata->hats[i].axis[1] = 1; - } - return(0); + int i; + + joystick->hwdata->hats = + (struct hwdata_hat *) SDL_malloc(joystick->nhats * + sizeof(struct hwdata_hat)); + if (joystick->hwdata->hats == NULL) { + return (-1); + } + for (i = 0; i < joystick->nhats; ++i) { + joystick->hwdata->hats[i].axis[0] = 1; + joystick->hwdata->hats[i].axis[1] = 1; + } + return (0); } -static int allocate_balldata(SDL_Joystick *joystick) +static int +allocate_balldata(SDL_Joystick * joystick) { - int i; - - joystick->hwdata->balls = (struct hwdata_ball *)SDL_malloc( - joystick->nballs * sizeof(struct hwdata_ball)); - if ( joystick->hwdata->balls == NULL ) { - return(-1); - } - for ( i=0; inballs; ++i ) { - joystick->hwdata->balls[i].axis[0] = 0; - joystick->hwdata->balls[i].axis[1] = 0; - } - return(0); + int i; + + joystick->hwdata->balls = + (struct hwdata_ball *) SDL_malloc(joystick->nballs * + sizeof(struct hwdata_ball)); + if (joystick->hwdata->balls == NULL) { + return (-1); + } + for (i = 0; i < joystick->nballs; ++i) { + joystick->hwdata->balls[i].axis[0] = 0; + joystick->hwdata->balls[i].axis[1] = 0; + } + return (0); } -static SDL_bool JS_ConfigJoystick(SDL_Joystick *joystick, int fd) +static SDL_bool +JS_ConfigJoystick(SDL_Joystick * joystick, int fd) { - SDL_bool handled; - unsigned char n; - int old_axes, tmp_naxes, tmp_nhats, tmp_nballs; - const char *name; - char *env, env_name[128]; - int i; - - handled = SDL_FALSE; - - /* Default joystick device settings */ - if ( ioctl(fd, JSIOCGAXES, &n) < 0 ) { - joystick->naxes = 2; - } else { - joystick->naxes = n; - } - if ( ioctl(fd, JSIOCGBUTTONS, &n) < 0 ) { - joystick->nbuttons = 2; - } else { - joystick->nbuttons = n; - } - - name = SDL_SYS_JoystickName(joystick->index); - old_axes = joystick->naxes; - - /* Generic analog joystick support */ - if ( SDL_strstr(name, "Analog") == name && SDL_strstr(name, "-hat") ) { - if ( SDL_sscanf(name,"Analog %d-axis %*d-button %d-hat", - &tmp_naxes, &tmp_nhats) == 2 ) { - - joystick->naxes = tmp_naxes; - joystick->nhats = tmp_nhats; - - handled = SDL_TRUE; - } - } - - /* Special joystick support */ - for ( i=0; i < SDL_arraysize(special_joysticks); ++i ) { - if ( SDL_strcmp(name, special_joysticks[i].name) == 0 ) { - - joystick->naxes = special_joysticks[i].naxes; - joystick->nhats = special_joysticks[i].nhats; - joystick->nballs = special_joysticks[i].nballs; - - handled = SDL_TRUE; - break; - } - } - - /* User environment joystick support */ - if ( (env = SDL_getenv("SDL_LINUX_JOYSTICK")) ) { - *env_name = '\0'; - if ( *env == '\'' && SDL_sscanf(env, "'%[^']s'", env_name) == 1 ) - env += SDL_strlen(env_name)+2; - else if ( SDL_sscanf(env, "%s", env_name) == 1 ) - env += SDL_strlen(env_name); - - if ( SDL_strcmp(name, env_name) == 0 ) { - - if ( SDL_sscanf(env, "%d %d %d", &tmp_naxes, &tmp_nhats, - &tmp_nballs) == 3 ) { - - joystick->naxes = tmp_naxes; - joystick->nhats = tmp_nhats; - joystick->nballs = tmp_nballs; - - handled = SDL_TRUE; - } - } - } - - /* Remap hats and balls */ - if (handled) { - if ( joystick->nhats > 0 ) { - if ( allocate_hatdata(joystick) < 0 ) { - joystick->nhats = 0; - } - } - if ( joystick->nballs > 0 ) { - if ( allocate_balldata(joystick) < 0 ) { - joystick->nballs = 0; - } - } - } - - return(handled); + SDL_bool handled; + unsigned char n; + int old_axes, tmp_naxes, tmp_nhats, tmp_nballs; + const char *name; + char *env, env_name[128]; + int i; + + handled = SDL_FALSE; + + /* Default joystick device settings */ + if (ioctl(fd, JSIOCGAXES, &n) < 0) { + joystick->naxes = 2; + } else { + joystick->naxes = n; + } + if (ioctl(fd, JSIOCGBUTTONS, &n) < 0) { + joystick->nbuttons = 2; + } else { + joystick->nbuttons = n; + } + + name = SDL_SYS_JoystickName(joystick->index); + old_axes = joystick->naxes; + + /* Generic analog joystick support */ + if (SDL_strstr(name, "Analog") == name && SDL_strstr(name, "-hat")) { + if (SDL_sscanf(name, "Analog %d-axis %*d-button %d-hat", + &tmp_naxes, &tmp_nhats) == 2) { + + joystick->naxes = tmp_naxes; + joystick->nhats = tmp_nhats; + + handled = SDL_TRUE; + } + } + + /* Special joystick support */ + for (i = 0; i < SDL_arraysize(special_joysticks); ++i) { + if (SDL_strcmp(name, special_joysticks[i].name) == 0) { + + joystick->naxes = special_joysticks[i].naxes; + joystick->nhats = special_joysticks[i].nhats; + joystick->nballs = special_joysticks[i].nballs; + + handled = SDL_TRUE; + break; + } + } + + /* User environment joystick support */ + if ((env = SDL_getenv("SDL_LINUX_JOYSTICK"))) { + *env_name = '\0'; + if (*env == '\'' && SDL_sscanf(env, "'%[^']s'", env_name) == 1) + env += SDL_strlen(env_name) + 2; + else if (SDL_sscanf(env, "%s", env_name) == 1) + env += SDL_strlen(env_name); + + if (SDL_strcmp(name, env_name) == 0) { + + if (SDL_sscanf(env, "%d %d %d", &tmp_naxes, &tmp_nhats, + &tmp_nballs) == 3) { + + joystick->naxes = tmp_naxes; + joystick->nhats = tmp_nhats; + joystick->nballs = tmp_nballs; + + handled = SDL_TRUE; + } + } + } + + /* Remap hats and balls */ + if (handled) { + if (joystick->nhats > 0) { + if (allocate_hatdata(joystick) < 0) { + joystick->nhats = 0; + } + } + if (joystick->nballs > 0) { + if (allocate_balldata(joystick) < 0) { + joystick->nballs = 0; + } + } + } + + return (handled); } #if SDL_INPUT_LINUXEV -static SDL_bool EV_ConfigJoystick(SDL_Joystick *joystick, int fd) +static SDL_bool +EV_ConfigJoystick(SDL_Joystick * joystick, int fd) { - int i, t; - unsigned long keybit[40]; - unsigned long absbit[40]; - unsigned long relbit[40]; - - /* See if this device uses the new unified event API */ - if ( (ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(keybit)), keybit) >= 0) && - (ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(absbit)), absbit) >= 0) && - (ioctl(fd, EVIOCGBIT(EV_REL, sizeof(relbit)), relbit) >= 0) ) { - joystick->hwdata->is_hid = SDL_TRUE; - - /* Get the number of buttons, axes, and other thingamajigs */ - for ( i=BTN_JOYSTICK; i < KEY_MAX; ++i ) { - if ( test_bit(i, keybit) ) { + int i, t; + unsigned long keybit[40]; + unsigned long absbit[40]; + unsigned long relbit[40]; + + /* See if this device uses the new unified event API */ + if ((ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(keybit)), keybit) >= 0) && + (ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(absbit)), absbit) >= 0) && + (ioctl(fd, EVIOCGBIT(EV_REL, sizeof(relbit)), relbit) >= 0)) { + joystick->hwdata->is_hid = SDL_TRUE; + + /* Get the number of buttons, axes, and other thingamajigs */ + for (i = BTN_JOYSTICK; i < KEY_MAX; ++i) { + if (test_bit(i, keybit)) { #ifdef DEBUG_INPUT_EVENTS - printf("Joystick has button: 0x%x\n", i); + printf("Joystick has button: 0x%x\n", i); #endif - joystick->hwdata->key_map[i-BTN_MISC] = - joystick->nbuttons; - ++joystick->nbuttons; - } - } - for ( i=BTN_MISC; i < BTN_JOYSTICK; ++i ) { - if ( test_bit(i, keybit) ) { + joystick->hwdata->key_map[i - BTN_MISC] = joystick->nbuttons; + ++joystick->nbuttons; + } + } + for (i = BTN_MISC; i < BTN_JOYSTICK; ++i) { + if (test_bit(i, keybit)) { #ifdef DEBUG_INPUT_EVENTS - printf("Joystick has button: 0x%x\n", i); + printf("Joystick has button: 0x%x\n", i); #endif - joystick->hwdata->key_map[i-BTN_MISC] = - joystick->nbuttons; - ++joystick->nbuttons; - } - } - for ( i=0; ihwdata->key_map[i - BTN_MISC] = joystick->nbuttons; + ++joystick->nbuttons; + } + } + for (i = 0; i < ABS_MAX; ++i) { + /* Skip hats */ + if (i == ABS_HAT0X) { + i = ABS_HAT3Y; + continue; + } + if (test_bit(i, absbit)) { + int values[5]; + + if (ioctl(fd, EVIOCGABS(i), values) < 0) + continue; #ifdef DEBUG_INPUT_EVENTS - printf("Joystick has absolute axis: %x\n", i); - printf("Values = { %d, %d, %d, %d, %d }\n", - values[0], values[1], - values[2], values[3], values[4]); + printf("Joystick has absolute axis: %x\n", i); + printf("Values = { %d, %d, %d, %d, %d }\n", + values[0], values[1], values[2], values[3], values[4]); #endif /* DEBUG_INPUT_EVENTS */ - joystick->hwdata->abs_map[i] = joystick->naxes; - if ( values[1] == values[2] ) { - joystick->hwdata->abs_correct[i].used = 0; - } else { - joystick->hwdata->abs_correct[i].used = 1; - joystick->hwdata->abs_correct[i].coef[0] = - (values[2] + values[1]) / 2 - values[4]; - joystick->hwdata->abs_correct[i].coef[1] = - (values[2] + values[1]) / 2 + values[4]; - t = ((values[2] - values[1]) / 2 - 2 * values[4]); - if ( t != 0 ) { - joystick->hwdata->abs_correct[i].coef[2] = (1 << 29) / t; - } else { - joystick->hwdata->abs_correct[i].coef[2] = 0; - } - } - ++joystick->naxes; - } - } - for ( i=ABS_HAT0X; i <= ABS_HAT3Y; i += 2 ) { - if ( test_bit(i, absbit) || test_bit(i+1, absbit) ) { + joystick->hwdata->abs_map[i] = joystick->naxes; + if (values[1] == values[2]) { + joystick->hwdata->abs_correct[i].used = 0; + } else { + joystick->hwdata->abs_correct[i].used = 1; + joystick->hwdata->abs_correct[i].coef[0] = + (values[2] + values[1]) / 2 - values[4]; + joystick->hwdata->abs_correct[i].coef[1] = + (values[2] + values[1]) / 2 + values[4]; + t = ((values[2] - values[1]) / 2 - 2 * values[4]); + if (t != 0) { + joystick->hwdata->abs_correct[i].coef[2] = + (1 << 29) / t; + } else { + joystick->hwdata->abs_correct[i].coef[2] = 0; + } + } + ++joystick->naxes; + } + } + for (i = ABS_HAT0X; i <= ABS_HAT3Y; i += 2) { + if (test_bit(i, absbit) || test_bit(i + 1, absbit)) { #ifdef DEBUG_INPUT_EVENTS - printf("Joystick has hat %d\n",(i-ABS_HAT0X)/2); + printf("Joystick has hat %d\n", (i - ABS_HAT0X) / 2); #endif - ++joystick->nhats; - } - } - if ( test_bit(REL_X, relbit) || test_bit(REL_Y, relbit) ) { - ++joystick->nballs; - } - - /* Allocate data to keep track of these thingamajigs */ - if ( joystick->nhats > 0 ) { - if ( allocate_hatdata(joystick) < 0 ) { - joystick->nhats = 0; - } - } - if ( joystick->nballs > 0 ) { - if ( allocate_balldata(joystick) < 0 ) { - joystick->nballs = 0; - } - } - } - return(joystick->hwdata->is_hid); + ++joystick->nhats; + } + } + if (test_bit(REL_X, relbit) || test_bit(REL_Y, relbit)) { + ++joystick->nballs; + } + + /* Allocate data to keep track of these thingamajigs */ + if (joystick->nhats > 0) { + if (allocate_hatdata(joystick) < 0) { + joystick->nhats = 0; + } + } + if (joystick->nballs > 0) { + if (allocate_balldata(joystick) < 0) { + joystick->nballs = 0; + } + } + } + return (joystick->hwdata->is_hid); } #endif /* SDL_INPUT_LINUXEV */ #ifndef NO_LOGICAL_JOYSTICKS -static void ConfigLogicalJoystick(SDL_Joystick *joystick) +static void +ConfigLogicalJoystick(SDL_Joystick * joystick) { - struct joystick_logical_layout* layout; - - layout = SDL_joylist[joystick->index].map->layout + - SDL_joylist[joystick->index].logicalno; - - joystick->nbuttons = layout->nbuttons; - joystick->nhats = layout->nhats; - joystick->naxes = layout->naxes; - joystick->nballs = layout->nballs; + struct joystick_logical_layout *layout; + + layout = SDL_joylist[joystick->index].map->layout + + SDL_joylist[joystick->index].logicalno; + + joystick->nbuttons = layout->nbuttons; + joystick->nhats = layout->nhats; + joystick->naxes = layout->naxes; + joystick->nballs = layout->nballs; } #endif @@ -775,192 +801,193 @@ static void ConfigLogicalJoystick(SDL_Joystick *joystick) This should fill the nbuttons and naxes fields of the joystick structure. It returns 0, or -1 if there is an error. */ -int SDL_SYS_JoystickOpen(SDL_Joystick *joystick) +int +SDL_SYS_JoystickOpen(SDL_Joystick * joystick) { - int fd; - SDL_logical_joydecl(int realindex); - SDL_logical_joydecl(SDL_Joystick *realjoy = NULL); + int fd; + SDL_logical_joydecl(int realindex); + SDL_logical_joydecl(SDL_Joystick * realjoy = NULL); - /* Open the joystick and set the joystick file descriptor */ + /* Open the joystick and set the joystick file descriptor */ #ifndef NO_LOGICAL_JOYSTICKS - if (SDL_joylist[joystick->index].fname == NULL) { - SDL_joylist_head(realindex, joystick->index); - realjoy = SDL_JoystickOpen(realindex); + if (SDL_joylist[joystick->index].fname == NULL) { + SDL_joylist_head(realindex, joystick->index); + realjoy = SDL_JoystickOpen(realindex); - if (realjoy == NULL) - return(-1); - - fd = realjoy->hwdata->fd; + if (realjoy == NULL) + return (-1); + + fd = realjoy->hwdata->fd; - } else { - fd = open(SDL_joylist[joystick->index].fname, O_RDONLY, 0); - } - SDL_joylist[joystick->index].joy = joystick; + } else { + fd = open(SDL_joylist[joystick->index].fname, O_RDONLY, 0); + } + SDL_joylist[joystick->index].joy = joystick; #else - fd = open(SDL_joylist[joystick->index].fname, O_RDONLY, 0); + fd = open(SDL_joylist[joystick->index].fname, O_RDONLY, 0); #endif - if ( fd < 0 ) { - SDL_SetError("Unable to open %s\n", - SDL_joylist[joystick->index]); - return(-1); - } - joystick->hwdata = (struct joystick_hwdata *) - SDL_malloc(sizeof(*joystick->hwdata)); - if ( joystick->hwdata == NULL ) { - SDL_OutOfMemory(); - close(fd); - return(-1); - } - SDL_memset(joystick->hwdata, 0, sizeof(*joystick->hwdata)); - joystick->hwdata->fd = fd; - - /* Set the joystick to non-blocking read mode */ - fcntl(fd, F_SETFL, O_NONBLOCK); - - /* Get the number of buttons and axes on the joystick */ + if (fd < 0) { + SDL_SetError("Unable to open %s\n", SDL_joylist[joystick->index]); + return (-1); + } + joystick->hwdata = (struct joystick_hwdata *) + SDL_malloc(sizeof(*joystick->hwdata)); + if (joystick->hwdata == NULL) { + SDL_OutOfMemory(); + close(fd); + return (-1); + } + SDL_memset(joystick->hwdata, 0, sizeof(*joystick->hwdata)); + joystick->hwdata->fd = fd; + + /* Set the joystick to non-blocking read mode */ + fcntl(fd, F_SETFL, O_NONBLOCK); + + /* Get the number of buttons and axes on the joystick */ #ifndef NO_LOGICAL_JOYSTICKS - if (realjoy) - ConfigLogicalJoystick(joystick); - else + if (realjoy) + ConfigLogicalJoystick(joystick); + else #endif #if SDL_INPUT_LINUXEV - if ( ! EV_ConfigJoystick(joystick, fd) ) + if (!EV_ConfigJoystick(joystick, fd)) #endif - JS_ConfigJoystick(joystick, fd); + JS_ConfigJoystick(joystick, fd); - return(0); + return (0); } #ifndef NO_LOGICAL_JOYSTICKS -static SDL_Joystick* FindLogicalJoystick( - SDL_Joystick *joystick, struct joystick_logical_mapping* v) +static SDL_Joystick * +FindLogicalJoystick(SDL_Joystick * joystick, + struct joystick_logical_mapping *v) { - SDL_Joystick *logicaljoy; - register int i; + SDL_Joystick *logicaljoy; + register int i; - i = joystick->index; - logicaljoy = NULL; + i = joystick->index; + logicaljoy = NULL; - /* get the fake joystick that will receive the event - */ - for(;;) { + /* get the fake joystick that will receive the event + */ + for (;;) { - if (SDL_joylist[i].logicalno == v->njoy) { - logicaljoy = SDL_joylist[i].joy; - break; - } + if (SDL_joylist[i].logicalno == v->njoy) { + logicaljoy = SDL_joylist[i].joy; + break; + } - if (SDL_joylist[i].next == 0) - break; + if (SDL_joylist[i].next == 0) + break; - i = SDL_joylist[i].next; + i = SDL_joylist[i].next; - } + } - return logicaljoy; + return logicaljoy; } -static int LogicalJoystickButton( - SDL_Joystick *joystick, Uint8 button, Uint8 state){ - struct joystick_logical_mapping* buttons; - SDL_Joystick *logicaljoy = NULL; +static int +LogicalJoystickButton(SDL_Joystick * joystick, Uint8 button, Uint8 state) +{ + struct joystick_logical_mapping *buttons; + SDL_Joystick *logicaljoy = NULL; - /* if there's no map then this is just a regular joystick - */ - if (SDL_joylist[joystick->index].map == NULL) - return 0; + /* if there's no map then this is just a regular joystick + */ + if (SDL_joylist[joystick->index].map == NULL) + return 0; - /* get the logical joystick that will receive the event - */ - buttons = SDL_joylist[joystick->index].map->buttonmap+button; - logicaljoy = FindLogicalJoystick(joystick, buttons); + /* get the logical joystick that will receive the event + */ + buttons = SDL_joylist[joystick->index].map->buttonmap + button; + logicaljoy = FindLogicalJoystick(joystick, buttons); - if (logicaljoy == NULL) - return 1; + if (logicaljoy == NULL) + return 1; - SDL_PrivateJoystickButton(logicaljoy, buttons->nthing, state); + SDL_PrivateJoystickButton(logicaljoy, buttons->nthing, state); - return 1; + return 1; } -static int LogicalJoystickAxis( - SDL_Joystick *joystick, Uint8 axis, Sint16 value) +static int +LogicalJoystickAxis(SDL_Joystick * joystick, Uint8 axis, Sint16 value) { - struct joystick_logical_mapping* axes; - SDL_Joystick *logicaljoy = NULL; + struct joystick_logical_mapping *axes; + SDL_Joystick *logicaljoy = NULL; - /* if there's no map then this is just a regular joystick - */ - if (SDL_joylist[joystick->index].map == NULL) - return 0; + /* if there's no map then this is just a regular joystick + */ + if (SDL_joylist[joystick->index].map == NULL) + return 0; - /* get the logical joystick that will receive the event - */ - axes = SDL_joylist[joystick->index].map->axismap+axis; - logicaljoy = FindLogicalJoystick(joystick, axes); + /* get the logical joystick that will receive the event + */ + axes = SDL_joylist[joystick->index].map->axismap + axis; + logicaljoy = FindLogicalJoystick(joystick, axes); - if (logicaljoy == NULL) - return 1; + if (logicaljoy == NULL) + return 1; - SDL_PrivateJoystickAxis(logicaljoy, axes->nthing, value); + SDL_PrivateJoystickAxis(logicaljoy, axes->nthing, value); - return 1; + return 1; } #endif /* USE_LOGICAL_JOYSTICKS */ -static __inline__ -void HandleHat(SDL_Joystick *stick, Uint8 hat, int axis, int value) +static __inline__ void +HandleHat(SDL_Joystick * stick, Uint8 hat, int axis, int value) { - struct hwdata_hat *the_hat; - const Uint8 position_map[3][3] = { - { SDL_HAT_LEFTUP, SDL_HAT_UP, SDL_HAT_RIGHTUP }, - { SDL_HAT_LEFT, SDL_HAT_CENTERED, SDL_HAT_RIGHT }, - { SDL_HAT_LEFTDOWN, SDL_HAT_DOWN, SDL_HAT_RIGHTDOWN } - }; - SDL_logical_joydecl(SDL_Joystick *logicaljoy = NULL); - SDL_logical_joydecl(struct joystick_logical_mapping* hats = NULL); - - the_hat = &stick->hwdata->hats[hat]; - if ( value < 0 ) { - value = 0; - } else - if ( value == 0 ) { - value = 1; - } else - if ( value > 0 ) { - value = 2; - } - if ( value != the_hat->axis[axis] ) { - the_hat->axis[axis] = value; + struct hwdata_hat *the_hat; + const Uint8 position_map[3][3] = { + {SDL_HAT_LEFTUP, SDL_HAT_UP, SDL_HAT_RIGHTUP}, + {SDL_HAT_LEFT, SDL_HAT_CENTERED, SDL_HAT_RIGHT}, + {SDL_HAT_LEFTDOWN, SDL_HAT_DOWN, SDL_HAT_RIGHTDOWN} + }; + SDL_logical_joydecl(SDL_Joystick * logicaljoy = NULL); + SDL_logical_joydecl(struct joystick_logical_mapping *hats = NULL); + + the_hat = &stick->hwdata->hats[hat]; + if (value < 0) { + value = 0; + } else if (value == 0) { + value = 1; + } else if (value > 0) { + value = 2; + } + if (value != the_hat->axis[axis]) { + the_hat->axis[axis] = value; #ifndef NO_LOGICAL_JOYSTICKS - /* if there's no map then this is just a regular joystick - */ - if (SDL_joylist[stick->index].map != NULL) { - - /* get the fake joystick that will receive the event - */ - hats = SDL_joylist[stick->index].map->hatmap+hat; - logicaljoy = FindLogicalJoystick(stick, hats); - } - - if (logicaljoy) { - stick = logicaljoy; - hat = hats->nthing; - } + /* if there's no map then this is just a regular joystick + */ + if (SDL_joylist[stick->index].map != NULL) { + + /* get the fake joystick that will receive the event + */ + hats = SDL_joylist[stick->index].map->hatmap + hat; + logicaljoy = FindLogicalJoystick(stick, hats); + } + + if (logicaljoy) { + stick = logicaljoy; + hat = hats->nthing; + } #endif /* USE_LOGICAL_JOYSTICKS */ - SDL_PrivateJoystickHat(stick, hat, - position_map[the_hat->axis[1]][the_hat->axis[0]]); - } + SDL_PrivateJoystickHat(stick, hat, + position_map[the_hat->axis[1]][the_hat-> + axis[0]]); + } } -static __inline__ -void HandleBall(SDL_Joystick *stick, Uint8 ball, int axis, int value) +static __inline__ void +HandleBall(SDL_Joystick * stick, Uint8 ball, int axis, int value) { - stick->hwdata->balls[ball].axis[axis] += value; + stick->hwdata->balls[ball].axis[axis] += value; } /* Function to update the state of a joystick - called as a device poll. @@ -968,231 +995,244 @@ void HandleBall(SDL_Joystick *stick, Uint8 ball, int axis, int value) * but instead should call SDL_PrivateJoystick*() to deliver events * and update joystick device state. */ -static __inline__ void JS_HandleEvents(SDL_Joystick *joystick) +static __inline__ void +JS_HandleEvents(SDL_Joystick * joystick) { - struct js_event events[32]; - int i, len; - Uint8 other_axis; + struct js_event events[32]; + int i, len; + Uint8 other_axis; #ifndef NO_LOGICAL_JOYSTICKS - if (SDL_joylist[joystick->index].fname == NULL) { - SDL_joylist_head(i, joystick->index); - JS_HandleEvents(SDL_joylist[i].joy); - return; - } + if (SDL_joylist[joystick->index].fname == NULL) { + SDL_joylist_head(i, joystick->index); + JS_HandleEvents(SDL_joylist[i].joy); + return; + } #endif - while ((len=read(joystick->hwdata->fd, events, (sizeof events))) > 0) { - len /= sizeof(events[0]); - for ( i=0; inaxes ) { + while ((len = read(joystick->hwdata->fd, events, (sizeof events))) > 0) { + len /= sizeof(events[0]); + for (i = 0; i < len; ++i) { + switch (events[i].type & ~JS_EVENT_INIT) { + case JS_EVENT_AXIS: + if (events[i].number < joystick->naxes) { #ifndef NO_LOGICAL_JOYSTICKS - if (!LogicalJoystickAxis(joystick, - events[i].number, events[i].value)) + if (!LogicalJoystickAxis(joystick, + events[i].number, + events[i].value)) #endif - SDL_PrivateJoystickAxis(joystick, - events[i].number, events[i].value); - break; - } - events[i].number -= joystick->naxes; - other_axis = (events[i].number / 2); - if ( other_axis < joystick->nhats ) { - HandleHat(joystick, other_axis, - events[i].number%2, - events[i].value); - break; - } - events[i].number -= joystick->nhats*2; - other_axis = (events[i].number / 2); - if ( other_axis < joystick->nballs ) { - HandleBall(joystick, other_axis, - events[i].number%2, - events[i].value); - break; - } - break; - case JS_EVENT_BUTTON: + SDL_PrivateJoystickAxis(joystick, + events[i].number, + events[i].value); + break; + } + events[i].number -= joystick->naxes; + other_axis = (events[i].number / 2); + if (other_axis < joystick->nhats) { + HandleHat(joystick, other_axis, + events[i].number % 2, events[i].value); + break; + } + events[i].number -= joystick->nhats * 2; + other_axis = (events[i].number / 2); + if (other_axis < joystick->nballs) { + HandleBall(joystick, other_axis, + events[i].number % 2, events[i].value); + break; + } + break; + case JS_EVENT_BUTTON: #ifndef NO_LOGICAL_JOYSTICKS - if (!LogicalJoystickButton(joystick, - events[i].number, events[i].value)) + if (!LogicalJoystickButton(joystick, + events[i].number, events[i].value)) #endif - SDL_PrivateJoystickButton(joystick, - events[i].number, events[i].value); - break; - default: - /* ?? */ - break; - } - } - } + SDL_PrivateJoystickButton(joystick, + events[i].number, + events[i].value); + break; + default: + /* ?? */ + break; + } + } + } } + #if SDL_INPUT_LINUXEV -static __inline__ int EV_AxisCorrect(SDL_Joystick *joystick, int which, int value) +static __inline__ int +EV_AxisCorrect(SDL_Joystick * joystick, int which, int value) { - struct axis_correct *correct; - - correct = &joystick->hwdata->abs_correct[which]; - if ( correct->used ) { - if ( value > correct->coef[0] ) { - if ( value < correct->coef[1] ) { - return 0; - } - value -= correct->coef[1]; - } else { - value -= correct->coef[0]; - } - value *= correct->coef[2]; - value >>= 14; - } - - /* Clamp and return */ - if ( value < -32768 ) return -32768; - if ( value > 32767 ) return 32767; - - return value; + struct axis_correct *correct; + + correct = &joystick->hwdata->abs_correct[which]; + if (correct->used) { + if (value > correct->coef[0]) { + if (value < correct->coef[1]) { + return 0; + } + value -= correct->coef[1]; + } else { + value -= correct->coef[0]; + } + value *= correct->coef[2]; + value >>= 14; + } + + /* Clamp and return */ + if (value < -32768) + return -32768; + if (value > 32767) + return 32767; + + return value; } -static __inline__ void EV_HandleEvents(SDL_Joystick *joystick) +static __inline__ void +EV_HandleEvents(SDL_Joystick * joystick) { - struct input_event events[32]; - int i, len; - int code; + struct input_event events[32]; + int i, len; + int code; #ifndef NO_LOGICAL_JOYSTICKS - if (SDL_joylist[joystick->index].fname == NULL) { - SDL_joylist_head(i, joystick->index); - return EV_HandleEvents(SDL_joylist[i].joy); - } + if (SDL_joylist[joystick->index].fname == NULL) { + SDL_joylist_head(i, joystick->index); + return EV_HandleEvents(SDL_joylist[i].joy); + } #endif - while ((len=read(joystick->hwdata->fd, events, (sizeof events))) > 0) { - len /= sizeof(events[0]); - for ( i=0; i= BTN_MISC ) { - code -= BTN_MISC; + while ((len = read(joystick->hwdata->fd, events, (sizeof events))) > 0) { + len /= sizeof(events[0]); + for (i = 0; i < len; ++i) { + code = events[i].code; + switch (events[i].type) { + case EV_KEY: + if (code >= BTN_MISC) { + code -= BTN_MISC; #ifndef NO_LOGICAL_JOYSTICKS - if (!LogicalJoystickButton(joystick, - joystick->hwdata->key_map[code], - events[i].value)) + if (!LogicalJoystickButton(joystick, + joystick->hwdata-> + key_map[code], + events[i].value)) #endif - SDL_PrivateJoystickButton(joystick, - joystick->hwdata->key_map[code], - events[i].value); - } - break; - case EV_ABS: - switch (code) { - case ABS_HAT0X: - case ABS_HAT0Y: - case ABS_HAT1X: - case ABS_HAT1Y: - case ABS_HAT2X: - case ABS_HAT2Y: - case ABS_HAT3X: - case ABS_HAT3Y: - code -= ABS_HAT0X; - HandleHat(joystick, code/2, code%2, - events[i].value); - break; - default: - events[i].value = EV_AxisCorrect(joystick, code, events[i].value); + SDL_PrivateJoystickButton(joystick, + joystick->hwdata-> + key_map[code], + events[i].value); + } + break; + case EV_ABS: + switch (code) { + case ABS_HAT0X: + case ABS_HAT0Y: + case ABS_HAT1X: + case ABS_HAT1Y: + case ABS_HAT2X: + case ABS_HAT2Y: + case ABS_HAT3X: + case ABS_HAT3Y: + code -= ABS_HAT0X; + HandleHat(joystick, code / 2, code % 2, events[i].value); + break; + default: + events[i].value = + EV_AxisCorrect(joystick, code, events[i].value); #ifndef NO_LOGICAL_JOYSTICKS - if (!LogicalJoystickAxis(joystick, - joystick->hwdata->abs_map[code], - events[i].value)) + if (!LogicalJoystickAxis(joystick, + joystick->hwdata-> + abs_map[code], events[i].value)) #endif - SDL_PrivateJoystickAxis(joystick, - joystick->hwdata->abs_map[code], - events[i].value); - break; - } - break; - case EV_REL: - switch (code) { - case REL_X: - case REL_Y: - code -= REL_X; - HandleBall(joystick, code/2, code%2, - events[i].value); - break; - default: - break; - } - break; - default: - break; - } - } - } + SDL_PrivateJoystickAxis(joystick, + joystick->hwdata-> + abs_map[code], + events[i].value); + break; + } + break; + case EV_REL: + switch (code) { + case REL_X: + case REL_Y: + code -= REL_X; + HandleBall(joystick, code / 2, code % 2, events[i].value); + break; + default: + break; + } + break; + default: + break; + } + } + } } #endif /* SDL_INPUT_LINUXEV */ -void SDL_SYS_JoystickUpdate(SDL_Joystick *joystick) +void +SDL_SYS_JoystickUpdate(SDL_Joystick * joystick) { - int i; - + int i; + #if SDL_INPUT_LINUXEV - if ( joystick->hwdata->is_hid ) - EV_HandleEvents(joystick); - else + if (joystick->hwdata->is_hid) + EV_HandleEvents(joystick); + else #endif - JS_HandleEvents(joystick); - - /* Deliver ball motion updates */ - for ( i=0; inballs; ++i ) { - int xrel, yrel; - - xrel = joystick->hwdata->balls[i].axis[0]; - yrel = joystick->hwdata->balls[i].axis[1]; - if ( xrel || yrel ) { - joystick->hwdata->balls[i].axis[0] = 0; - joystick->hwdata->balls[i].axis[1] = 0; - SDL_PrivateJoystickBall(joystick, (Uint8)i, xrel, yrel); - } - } + JS_HandleEvents(joystick); + + /* Deliver ball motion updates */ + for (i = 0; i < joystick->nballs; ++i) { + int xrel, yrel; + + xrel = joystick->hwdata->balls[i].axis[0]; + yrel = joystick->hwdata->balls[i].axis[1]; + if (xrel || yrel) { + joystick->hwdata->balls[i].axis[0] = 0; + joystick->hwdata->balls[i].axis[1] = 0; + SDL_PrivateJoystickBall(joystick, (Uint8) i, xrel, yrel); + } + } } /* Function to close a joystick after use */ -void SDL_SYS_JoystickClose(SDL_Joystick *joystick) +void +SDL_SYS_JoystickClose(SDL_Joystick * joystick) { #ifndef NO_LOGICAL_JOYSTICKS - register int i; - if (SDL_joylist[joystick->index].fname == NULL) { - SDL_joylist_head(i, joystick->index); - SDL_JoystickClose(SDL_joylist[i].joy); - } + register int i; + if (SDL_joylist[joystick->index].fname == NULL) { + SDL_joylist_head(i, joystick->index); + SDL_JoystickClose(SDL_joylist[i].joy); + } #endif - if ( joystick->hwdata ) { + if (joystick->hwdata) { #ifndef NO_LOGICAL_JOYSTICKS - if (SDL_joylist[joystick->index].fname != NULL) + if (SDL_joylist[joystick->index].fname != NULL) #endif - close(joystick->hwdata->fd); - if ( joystick->hwdata->hats ) { - SDL_free(joystick->hwdata->hats); - } - if ( joystick->hwdata->balls ) { - SDL_free(joystick->hwdata->balls); - } - SDL_free(joystick->hwdata); - joystick->hwdata = NULL; - } + close(joystick->hwdata->fd); + if (joystick->hwdata->hats) { + SDL_free(joystick->hwdata->hats); + } + if (joystick->hwdata->balls) { + SDL_free(joystick->hwdata->balls); + } + SDL_free(joystick->hwdata); + joystick->hwdata = NULL; + } } /* Function to perform any system-specific joystick related cleanup */ -void SDL_SYS_JoystickQuit(void) +void +SDL_SYS_JoystickQuit(void) { - int i; + int i; - for ( i=0; SDL_joylist[i].fname; ++i ) { - SDL_free(SDL_joylist[i].fname); - } - SDL_joylist[0].fname = NULL; + for (i = 0; SDL_joylist[i].fname; ++i) { + SDL_free(SDL_joylist[i].fname); + } + SDL_joylist[0].fname = NULL; } #endif /* SDL_JOYSTICK_LINUX */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/joystick/macos/SDL_sysjoystick.c b/src/joystick/macos/SDL_sysjoystick.c index 25609b30a..e4c476bdb 100644 --- a/src/joystick/macos/SDL_sysjoystick.c +++ b/src/joystick/macos/SDL_sysjoystick.c @@ -37,25 +37,25 @@ /* The max number of joysticks we will detect */ -#define MAX_JOYSTICKS 16 +#define MAX_JOYSTICKS 16 /* Limit ourselves to 32 elements per device */ -#define kMaxReferences 32 +#define kMaxReferences 32 #define ISpSymmetricAxisToFloat(axis) ((((float) axis) - kISpAxisMiddle) / (kISpAxisMaximum-kISpAxisMiddle)) #define ISpAsymmetricAxisToFloat(axis) (((float) axis) / (kISpAxisMaximum)) -static ISpDeviceReference SYS_Joysticks[MAX_JOYSTICKS]; -static ISpElementListReference SYS_Elements[MAX_JOYSTICKS]; -static ISpDeviceDefinition SYS_DevDef[MAX_JOYSTICKS]; +static ISpDeviceReference SYS_Joysticks[MAX_JOYSTICKS]; +static ISpElementListReference SYS_Elements[MAX_JOYSTICKS]; +static ISpDeviceDefinition SYS_DevDef[MAX_JOYSTICKS]; -struct joystick_hwdata +struct joystick_hwdata { char name[64]; /* Uint8 id;*/ ISpElementReference refs[kMaxReferences]; /* gonna need some sort of mapping info */ -}; +}; /* Function to scan the system for joysticks. @@ -63,62 +63,55 @@ struct joystick_hwdata * This function should return the number of available joysticks, or -1 * on an unrecoverable fatal error. */ -int SDL_SYS_JoystickInit(void) +int +SDL_SYS_JoystickInit(void) { static ISpDeviceClass classes[4] = { kISpDeviceClass_Joystick, - #if kISpDeviceClass_Gamepad +#if kISpDeviceClass_Gamepad kISpDeviceClass_Gamepad, - #endif +#endif kISpDeviceClass_Wheel, 0 }; - OSErr err; - int i; - UInt32 count, numJoysticks; + OSErr err; + int i; + UInt32 count, numJoysticks; - if ( (Ptr)0 == (Ptr)ISpStartup ) { + if ((Ptr) 0 == (Ptr) ISpStartup) { SDL_SetError("InputSprocket not installed"); - return -1; // InputSprocket not installed + return -1; // InputSprocket not installed } - if( (Ptr)0 == (Ptr)ISpGetVersion ) { + if ((Ptr) 0 == (Ptr) ISpGetVersion) { SDL_SetError("InputSprocket not version 1.1 or newer"); - return -1; // old version of ISp (not at least 1.1) + return -1; // old version of ISp (not at least 1.1) } ISpStartup(); /* Get all the joysticks */ numJoysticks = 0; - for ( i=0; classes[i]; ++i ) { + for (i = 0; classes[i]; ++i) { count = 0; - err = ISpDevices_ExtractByClass( - classes[i], - MAX_JOYSTICKS-numJoysticks, - &count, - &SYS_Joysticks[numJoysticks]); + err = ISpDevices_ExtractByClass(classes[i], + MAX_JOYSTICKS - numJoysticks, + &count, &SYS_Joysticks[numJoysticks]); numJoysticks += count; } - for(i = 0; i < numJoysticks; i++) - { - ISpDevice_GetDefinition( - SYS_Joysticks[i], sizeof(ISpDeviceDefinition), - &SYS_DevDef[i]); - - err = ISpElementList_New( - 0, NULL, - &SYS_Elements[i], 0); - + for (i = 0; i < numJoysticks; i++) { + ISpDevice_GetDefinition(SYS_Joysticks[i], + sizeof(ISpDeviceDefinition), &SYS_DevDef[i]); + + err = ISpElementList_New(0, NULL, &SYS_Elements[i], 0); + if (err) { SDL_OutOfMemory(); return -1; } - ISpDevice_GetElementList( - SYS_Joysticks[i], - &SYS_Elements[i]); + ISpDevice_GetElementList(SYS_Joysticks[i], &SYS_Elements[i]); } ISpDevices_Deactivate(numJoysticks, SYS_Joysticks); @@ -127,14 +120,15 @@ int SDL_SYS_JoystickInit(void) } /* Function to get the device-dependent name of a joystick */ -const char *SDL_SYS_JoystickName(int index) +const char * +SDL_SYS_JoystickName(int index) { static char name[64]; int len; /* convert pascal string to c-string */ len = SYS_DevDef[index].deviceName[0]; - if ( len >= sizeof(name) ) { + if (len >= sizeof(name)) { len = (sizeof(name) - 1); } SDL_memcpy(name, &SYS_DevDef[index].deviceName[1], len); @@ -148,11 +142,12 @@ const char *SDL_SYS_JoystickName(int index) This should fill the nbuttons and naxes fields of the joystick structure. It returns 0, or -1 if there is an error. */ -int SDL_SYS_JoystickOpen(SDL_Joystick *joystick) +int +SDL_SYS_JoystickOpen(SDL_Joystick * joystick) { - int index; - UInt32 count, gotCount, count2; - long numAxis, numButtons, numHats, numBalls; + int index; + UInt32 count, gotCount, count2; + long numAxis, numButtons, numHats, numBalls; count = kMaxReferences; count2 = 0; @@ -161,44 +156,40 @@ int SDL_SYS_JoystickOpen(SDL_Joystick *joystick) index = joystick->index; /* allocate memory for system specific hardware data */ - joystick->hwdata = (struct joystick_hwdata *) SDL_malloc(sizeof(*joystick->hwdata)); - if (joystick->hwdata == NULL) - { - SDL_OutOfMemory(); - return(-1); + joystick->hwdata = + (struct joystick_hwdata *) SDL_malloc(sizeof(*joystick->hwdata)); + if (joystick->hwdata == NULL) { + SDL_OutOfMemory(); + return (-1); } SDL_memset(joystick->hwdata, 0, sizeof(*joystick->hwdata)); - SDL_strlcpy(joystick->hwdata->name, SDL_SYS_JoystickName(index), SDL_arraysize(joystick->hwdata->name)); + SDL_strlcpy(joystick->hwdata->name, SDL_SYS_JoystickName(index), + SDL_arraysize(joystick->hwdata->name)); joystick->name = joystick->hwdata->name; - ISpElementList_ExtractByKind( - SYS_Elements[index], - kISpElementKind_Axis, - count, - &gotCount, - joystick->hwdata->refs); + ISpElementList_ExtractByKind(SYS_Elements[index], + kISpElementKind_Axis, + count, &gotCount, joystick->hwdata->refs); numAxis = gotCount; count -= gotCount; count2 += gotCount; - ISpElementList_ExtractByKind( - SYS_Elements[index], - kISpElementKind_DPad, - count, - &gotCount, - &(joystick->hwdata->refs[count2])); + ISpElementList_ExtractByKind(SYS_Elements[index], + kISpElementKind_DPad, + count, + &gotCount, + &(joystick->hwdata->refs[count2])); numHats = gotCount; count -= gotCount; count2 += gotCount; - ISpElementList_ExtractByKind( - SYS_Elements[index], - kISpElementKind_Button, - count, - &gotCount, - &(joystick->hwdata->refs[count2])); + ISpElementList_ExtractByKind(SYS_Elements[index], + kISpElementKind_Button, + count, + &gotCount, + &(joystick->hwdata->refs[count2])); numButtons = gotCount; count -= gotCount; @@ -209,9 +200,7 @@ int SDL_SYS_JoystickOpen(SDL_Joystick *joystick) joystick->nballs = numBalls; joystick->nbuttons = numButtons; - ISpDevices_Activate( - 1, - &SYS_Joysticks[index]); + ISpDevices_Activate(1, &SYS_Joysticks[index]); return 0; } @@ -221,100 +210,92 @@ int SDL_SYS_JoystickOpen(SDL_Joystick *joystick) * but instead should call SDL_PrivateJoystick*() to deliver events * and update joystick device state. */ -void SDL_SYS_JoystickUpdate(SDL_Joystick *joystick) +void +SDL_SYS_JoystickUpdate(SDL_Joystick * joystick) { - int i, j; - ISpAxisData a; - ISpDPadData b; + int i, j; + ISpAxisData a; + ISpDPadData b; //ISpDeltaData c; - ISpButtonData d; + ISpButtonData d; - for(i = 0, j = 0; i < joystick->naxes; i++, j++) - { + for (i = 0, j = 0; i < joystick->naxes; i++, j++) { Sint16 value; - ISpElement_GetSimpleState( - joystick->hwdata->refs[j], - &a); - value = (ISpSymmetricAxisToFloat(a)* 32767.0); - if ( value != joystick->axes[i] ) { + ISpElement_GetSimpleState(joystick->hwdata->refs[j], &a); + value = (ISpSymmetricAxisToFloat(a) * 32767.0); + if (value != joystick->axes[i]) { SDL_PrivateJoystickAxis(joystick, i, value); } } - for(i = 0; i < joystick->nhats; i++, j++) - { + for (i = 0; i < joystick->nhats; i++, j++) { Uint8 pos; - ISpElement_GetSimpleState( - joystick->hwdata->refs[j], - &b); - switch(b) { - case kISpPadIdle: - pos = SDL_HAT_CENTERED; - break; - case kISpPadLeft: - pos = SDL_HAT_LEFT; - break; - case kISpPadUpLeft: - pos = SDL_HAT_LEFTUP; - break; - case kISpPadUp: - pos = SDL_HAT_UP; - break; - case kISpPadUpRight: - pos = SDL_HAT_RIGHTUP; - break; - case kISpPadRight: - pos = SDL_HAT_RIGHT; - break; - case kISpPadDownRight: - pos = SDL_HAT_RIGHTDOWN; - break; - case kISpPadDown: - pos = SDL_HAT_DOWN; - break; - case kISpPadDownLeft: - pos = SDL_HAT_LEFTDOWN; - break; + ISpElement_GetSimpleState(joystick->hwdata->refs[j], &b); + switch (b) { + case kISpPadIdle: + pos = SDL_HAT_CENTERED; + break; + case kISpPadLeft: + pos = SDL_HAT_LEFT; + break; + case kISpPadUpLeft: + pos = SDL_HAT_LEFTUP; + break; + case kISpPadUp: + pos = SDL_HAT_UP; + break; + case kISpPadUpRight: + pos = SDL_HAT_RIGHTUP; + break; + case kISpPadRight: + pos = SDL_HAT_RIGHT; + break; + case kISpPadDownRight: + pos = SDL_HAT_RIGHTDOWN; + break; + case kISpPadDown: + pos = SDL_HAT_DOWN; + break; + case kISpPadDownLeft: + pos = SDL_HAT_LEFTDOWN; + break; } - if ( pos != joystick->hats[i] ) { + if (pos != joystick->hats[i]) { SDL_PrivateJoystickHat(joystick, i, pos); } } - for(i = 0; i < joystick->nballs; i++, j++) - { + for (i = 0; i < joystick->nballs; i++, j++) { /* ignore balls right now */ } - for(i = 0; i < joystick->nbuttons; i++, j++) - { - ISpElement_GetSimpleState( - joystick->hwdata->refs[j], - &d); - if ( d != joystick->buttons[i] ) { + for (i = 0; i < joystick->nbuttons; i++, j++) { + ISpElement_GetSimpleState(joystick->hwdata->refs[j], &d); + if (d != joystick->buttons[i]) { SDL_PrivateJoystickButton(joystick, i, d); } } } /* Function to close a joystick after use */ -void SDL_SYS_JoystickClose(SDL_Joystick *joystick) +void +SDL_SYS_JoystickClose(SDL_Joystick * joystick) { int index; index = joystick->index; - ISpDevices_Deactivate( - 1, - &SYS_Joysticks[index]); + ISpDevices_Deactivate(1, &SYS_Joysticks[index]); } /* Function to perform any system-specific joystick related cleanup */ -void SDL_SYS_JoystickQuit(void) +void +SDL_SYS_JoystickQuit(void) { ISpShutdown(); } #endif /* SDL_JOYSTICK_MACOS */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/joystick/mint/SDL_sysjoystick.c b/src/joystick/mint/SDL_sysjoystick.c index 0a129fe81..eada425d4 100644 --- a/src/joystick/mint/SDL_sysjoystick.c +++ b/src/joystick/mint/SDL_sysjoystick.c @@ -52,32 +52,34 @@ 2 joysticks on parallel port */ -enum { - IKBD_JOY1=0, - XBIOS_JOY1, - PORTA_PAD, - PORTB_PAD, - PORTA_JOY0, - PORTA_JOY1, - PORTB_JOY0, - PORTB_JOY1, - PORTA_LP, - PORTA_ANPAD, - PORTB_ANPAD, +enum +{ + IKBD_JOY1 = 0, + XBIOS_JOY1, + PORTA_PAD, + PORTB_PAD, + PORTA_JOY0, + PORTA_JOY1, + PORTB_JOY0, + PORTB_JOY1, + PORTA_LP, + PORTA_ANPAD, + PORTB_ANPAD, #if 0 - PARA_JOY0, - PARA_JOY1, + PARA_JOY0, + PARA_JOY1, #endif - MAX_JOYSTICKS + MAX_JOYSTICKS }; -enum { - MCH_ST=0, - MCH_STE, - MCH_TT, - MCH_F30, - MCH_CLONE, - MCH_ARANYM +enum +{ + MCH_ST = 0, + MCH_STE, + MCH_TT, + MCH_F30, + MCH_CLONE, + MCH_ARANYM }; /* Joypad buttons @@ -86,13 +88,14 @@ enum { * X,Y,Z are connected to 7,8,9 */ -enum { - JP_UP=0, JP_DOWN, JP_LEFT, JP_RIGHT, - JP_KPMULT, JP_KP7, JP_KP4, JP_KP1, - JP_KP0, JP_KP8, JP_KP5, JP_KP2, - JP_KPNUM, JP_KP9, JP_KP6, JP_KP3, - JP_PAUSE, JP_FIRE0, JP_UNDEF0, JP_FIRE1, - JP_UNDEF1, JP_FIRE2, JP_UNDEF2, JP_OPTION +enum +{ + JP_UP = 0, JP_DOWN, JP_LEFT, JP_RIGHT, + JP_KPMULT, JP_KP7, JP_KP4, JP_KP1, + JP_KP0, JP_KP8, JP_KP5, JP_KP2, + JP_KPNUM, JP_KP9, JP_KP6, JP_KP3, + JP_PAUSE, JP_FIRE0, JP_UNDEF0, JP_FIRE1, + JP_UNDEF1, JP_FIRE2, JP_UNDEF2, JP_OPTION }; #define JP_NUM_BUTTONS 17 @@ -105,41 +108,42 @@ enum { /*--- Types ---*/ -typedef struct { - SDL_bool enabled; - unsigned char *name; - Uint32 prevstate; +typedef struct +{ + SDL_bool enabled; + unsigned char *name; + Uint32 prevstate; } atarijoy_t; /*--- Variables ---*/ -static atarijoy_t atarijoysticks[MAX_JOYSTICKS]={ - {SDL_FALSE,"IKBD joystick port 1",0}, - {SDL_FALSE,"Xbios joystick port 1",0}, - {SDL_FALSE,"Joypad port A",0}, - {SDL_FALSE,"Joypad port B",0}, - {SDL_FALSE,"Joystick 0 port A",0}, - {SDL_FALSE,"Joystick 1 port A",0}, - {SDL_FALSE,"Joystick 0 port B",0}, - {SDL_FALSE,"Joystick 1 port B",0}, - {SDL_FALSE,"Lightpen port A",0}, - {SDL_FALSE,"Analog paddle port A",0}, - {SDL_FALSE,"Analog paddle port B",0} +static atarijoy_t atarijoysticks[MAX_JOYSTICKS] = { + {SDL_FALSE, "IKBD joystick port 1", 0}, + {SDL_FALSE, "Xbios joystick port 1", 0}, + {SDL_FALSE, "Joypad port A", 0}, + {SDL_FALSE, "Joypad port B", 0}, + {SDL_FALSE, "Joystick 0 port A", 0}, + {SDL_FALSE, "Joystick 1 port A", 0}, + {SDL_FALSE, "Joystick 0 port B", 0}, + {SDL_FALSE, "Joystick 1 port B", 0}, + {SDL_FALSE, "Lightpen port A", 0}, + {SDL_FALSE, "Analog paddle port A", 0}, + {SDL_FALSE, "Analog paddle port B", 0} #if 0 - ,{SDL_FALSE,"Joystick 0 parallel port",0}, - {SDL_FALSE,"Joystick 1 parallel port",0} + , {SDL_FALSE, "Joystick 0 parallel port", 0}, + {SDL_FALSE, "Joystick 1 parallel port", 0} #endif }; -static const int jp_buttons[JP_NUM_BUTTONS]={ - JP_FIRE0, JP_FIRE1, JP_FIRE2, JP_PAUSE, - JP_OPTION, JP_KPMULT, JP_KPNUM, JP_KP0, - JP_KP1, JP_KP2, JP_KP3, JP_KP4, - JP_KP5, JP_KP6, JP_KP7, JP_KP8, - JP_KP9 +static const int jp_buttons[JP_NUM_BUTTONS] = { + JP_FIRE0, JP_FIRE1, JP_FIRE2, JP_PAUSE, + JP_OPTION, JP_KPMULT, JP_KPNUM, JP_KP0, + JP_KP1, JP_KP2, JP_KP3, JP_KP4, + JP_KP5, JP_KP6, JP_KP7, JP_KP8, + JP_KP9 }; -static SDL_bool joypad_ports_enabled=SDL_FALSE; +static SDL_bool joypad_ports_enabled = SDL_FALSE; /* Updated joypad ports */ static Uint16 jp_paddles[4]; @@ -155,12 +159,13 @@ static void UpdateJoypads(void); /*--- Functions ---*/ -int SDL_SYS_JoystickInit(void) +int +SDL_SYS_JoystickInit(void) { - int i; - unsigned long cookie_mch; - const char *envr=SDL_getenv("SDL_JOYSTICK_ATARI"); - + int i; + unsigned long cookie_mch; + const char *envr = SDL_getenv("SDL_JOYSTICK_ATARI"); + #define TEST_JOY_ENABLED(env,idstring,num) \ if (SDL_strstr(env,idstring"-off")) { \ atarijoysticks[num].enabled=SDL_FALSE; \ @@ -169,465 +174,499 @@ int SDL_SYS_JoystickInit(void) atarijoysticks[num].enabled=SDL_TRUE; \ } - /* Cookie _MCH present ? if not, assume ST machine */ - if (Getcookie(C__MCH, &cookie_mch) != C_FOUND) { - cookie_mch = MCH_ST << 16; - } - - /* Enable some default joysticks */ - if ((cookie_mch == MCH_ST<<16) || ((cookie_mch>>16) == MCH_STE) || - (cookie_mch == MCH_TT<<16) || (cookie_mch == MCH_F30<<16) || - (cookie_mch == MCH_ARANYM<<16)) { - atarijoysticks[IKBD_JOY1].enabled=(SDL_AtariIkbd_enabled!=0); - } - if ((cookie_mch == MCH_STE<<16) || (cookie_mch == MCH_F30<<16)) { - atarijoysticks[PORTA_PAD].enabled=SDL_TRUE; - atarijoysticks[PORTB_PAD].enabled=SDL_TRUE; - } - if (!atarijoysticks[IKBD_JOY1].enabled) { - atarijoysticks[XBIOS_JOY1].enabled=(SDL_AtariXbios_enabled!=0); - } - - /* Read environment for joysticks to enable */ - if (envr) { - /* IKBD on any Atari, maybe clones */ - if ((cookie_mch == MCH_ST<<16) || ((cookie_mch>>16) == MCH_STE) || - (cookie_mch == MCH_TT<<16) || (cookie_mch == MCH_F30<<16) || - (cookie_mch == MCH_ARANYM<<16)) { - if (SDL_AtariIkbd_enabled!=0) { - TEST_JOY_ENABLED(envr, "ikbd-joy1", IKBD_JOY1); - } - } - /* Joypads ports only on STE and Falcon */ - if ((cookie_mch == MCH_STE<<16) || (cookie_mch == MCH_F30<<16)) { - TEST_JOY_ENABLED(envr, "porta-pad", PORTA_PAD); - if (!atarijoysticks[PORTA_PAD].enabled) { - TEST_JOY_ENABLED(envr, "porta-joy0", PORTA_JOY0); - TEST_JOY_ENABLED(envr, "porta-joy1", PORTA_JOY1); - if (!(atarijoysticks[PORTA_JOY0].enabled) && !(atarijoysticks[PORTA_JOY1].enabled)) { - TEST_JOY_ENABLED(envr, "porta-lp", PORTA_LP); - if (!atarijoysticks[PORTA_LP].enabled) { - TEST_JOY_ENABLED(envr, "porta-anpad", PORTA_ANPAD); - } - } - } - - TEST_JOY_ENABLED(envr, "portb-pad", PORTB_PAD); - if (!atarijoysticks[PORTB_PAD].enabled) { - TEST_JOY_ENABLED(envr, "portb-joy0", PORTB_JOY0); - TEST_JOY_ENABLED(envr, "portb-joy1", PORTB_JOY1); - if (!(atarijoysticks[PORTB_JOY0].enabled) && !(atarijoysticks[PORTB_JOY1].enabled)) { - TEST_JOY_ENABLED(envr, "portb-anpad", PORTB_ANPAD); - } - } - } - - if (!atarijoysticks[IKBD_JOY1].enabled) { - if (SDL_AtariXbios_enabled!=0) { - TEST_JOY_ENABLED(envr, "xbios-joy1", XBIOS_JOY1); - } - } + /* Cookie _MCH present ? if not, assume ST machine */ + if (Getcookie(C__MCH, &cookie_mch) != C_FOUND) { + cookie_mch = MCH_ST << 16; + } + + /* Enable some default joysticks */ + if ((cookie_mch == MCH_ST << 16) || ((cookie_mch >> 16) == MCH_STE) || + (cookie_mch == MCH_TT << 16) || (cookie_mch == MCH_F30 << 16) || + (cookie_mch == MCH_ARANYM << 16)) { + atarijoysticks[IKBD_JOY1].enabled = (SDL_AtariIkbd_enabled != 0); + } + if ((cookie_mch == MCH_STE << 16) || (cookie_mch == MCH_F30 << 16)) { + atarijoysticks[PORTA_PAD].enabled = SDL_TRUE; + atarijoysticks[PORTB_PAD].enabled = SDL_TRUE; + } + if (!atarijoysticks[IKBD_JOY1].enabled) { + atarijoysticks[XBIOS_JOY1].enabled = (SDL_AtariXbios_enabled != 0); + } + + /* Read environment for joysticks to enable */ + if (envr) { + /* IKBD on any Atari, maybe clones */ + if ((cookie_mch == MCH_ST << 16) || ((cookie_mch >> 16) == MCH_STE) + || (cookie_mch == MCH_TT << 16) || (cookie_mch == MCH_F30 << 16) + || (cookie_mch == MCH_ARANYM << 16)) { + if (SDL_AtariIkbd_enabled != 0) { + TEST_JOY_ENABLED(envr, "ikbd-joy1", IKBD_JOY1); + } + } + /* Joypads ports only on STE and Falcon */ + if ((cookie_mch == MCH_STE << 16) || (cookie_mch == MCH_F30 << 16)) { + TEST_JOY_ENABLED(envr, "porta-pad", PORTA_PAD); + if (!atarijoysticks[PORTA_PAD].enabled) { + TEST_JOY_ENABLED(envr, "porta-joy0", PORTA_JOY0); + TEST_JOY_ENABLED(envr, "porta-joy1", PORTA_JOY1); + if (!(atarijoysticks[PORTA_JOY0].enabled) + && !(atarijoysticks[PORTA_JOY1].enabled)) { + TEST_JOY_ENABLED(envr, "porta-lp", PORTA_LP); + if (!atarijoysticks[PORTA_LP].enabled) { + TEST_JOY_ENABLED(envr, "porta-anpad", PORTA_ANPAD); + } + } + } + + TEST_JOY_ENABLED(envr, "portb-pad", PORTB_PAD); + if (!atarijoysticks[PORTB_PAD].enabled) { + TEST_JOY_ENABLED(envr, "portb-joy0", PORTB_JOY0); + TEST_JOY_ENABLED(envr, "portb-joy1", PORTB_JOY1); + if (!(atarijoysticks[PORTB_JOY0].enabled) + && !(atarijoysticks[PORTB_JOY1].enabled)) { + TEST_JOY_ENABLED(envr, "portb-anpad", PORTB_ANPAD); + } + } + } + + if (!atarijoysticks[IKBD_JOY1].enabled) { + if (SDL_AtariXbios_enabled != 0) { + TEST_JOY_ENABLED(envr, "xbios-joy1", XBIOS_JOY1); + } + } #if 0 - /* Parallel port on any Atari, maybe clones */ - if ((cookie_mch == MCH_ST<<16) || ((cookie_mch>>16) == MCH_STE) || - (cookie_mch == MCH_TT<<16) || (cookie_mch == MCH_F30<<16)) { - TEST_JOY_ENABLED(envr, "para-joy0", PARA_JOY0); - TEST_JOY_ENABLED(envr, "para-joy1", PARA_JOY1); - } + /* Parallel port on any Atari, maybe clones */ + if ((cookie_mch == MCH_ST << 16) || ((cookie_mch >> 16) == MCH_STE) + || (cookie_mch == MCH_TT << 16) + || (cookie_mch == MCH_F30 << 16)) { + TEST_JOY_ENABLED(envr, "para-joy0", PARA_JOY0); + TEST_JOY_ENABLED(envr, "para-joy1", PARA_JOY1); + } #endif - } - - /* Need to update joypad ports ? */ - joypad_ports_enabled=SDL_FALSE; - for (i=PORTA_PAD;i<=PORTB_ANPAD;i++) { - if (atarijoysticks[i].enabled) { - joypad_ports_enabled=SDL_TRUE; - break; - } - } - - SDL_numjoysticks = 0; - for (i=0;iindex); - if (numjoystick==-1) - return -1; - - joystick->naxes=0; - joystick->nhats=0; - joystick->nballs=0; - - switch(numjoystick) { - case PORTA_PAD: - case PORTB_PAD: - joystick->nhats=1; - joystick->nbuttons=JP_NUM_BUTTONS; - break; - case PORTA_LP: - case PORTA_ANPAD: - case PORTB_ANPAD: - joystick->naxes=2; - joystick->nbuttons=2; - break; - default: - joystick->nhats=1; - joystick->nbuttons=1; - break; - } - - return(0); + int numjoystick; + + numjoystick = GetEnabledAtariJoystick(joystick->index); + if (numjoystick == -1) + return -1; + + joystick->naxes = 0; + joystick->nhats = 0; + joystick->nballs = 0; + + switch (numjoystick) { + case PORTA_PAD: + case PORTB_PAD: + joystick->nhats = 1; + joystick->nbuttons = JP_NUM_BUTTONS; + break; + case PORTA_LP: + case PORTA_ANPAD: + case PORTB_ANPAD: + joystick->naxes = 2; + joystick->nbuttons = 2; + break; + default: + joystick->nhats = 1; + joystick->nbuttons = 1; + break; + } + + return (0); } -void SDL_SYS_JoystickUpdate(SDL_Joystick *joystick) +void +SDL_SYS_JoystickUpdate(SDL_Joystick * joystick) { - int numjoystick; - Uint8 hatstate; - Uint32 curstate,prevstate; - - numjoystick=GetEnabledAtariJoystick(joystick->index); - if (numjoystick==-1) - return; - - prevstate = atarijoysticks[numjoystick].prevstate; - - if (joypad_ports_enabled) { - Supexec(UpdateJoypads); - } - - switch (numjoystick) { - case IKBD_JOY1: - case XBIOS_JOY1: - { - curstate = 0; - - if (numjoystick==IKBD_JOY1) { - curstate = SDL_AtariIkbd_joystick & 0xff; - } - if (numjoystick==XBIOS_JOY1) { - curstate = SDL_AtariXbios_joystick & 0xff; - } - - if (curstate != prevstate) { - hatstate = SDL_HAT_CENTERED; - if (curstate & IKBD_JOY_LEFT) { - hatstate |= SDL_HAT_LEFT; - } - if (curstate & IKBD_JOY_RIGHT) { - hatstate |= SDL_HAT_RIGHT; - } - if (curstate & IKBD_JOY_UP) { - hatstate |= SDL_HAT_UP; - } - if (curstate & IKBD_JOY_DOWN) { - hatstate |= SDL_HAT_DOWN; - } - SDL_PrivateJoystickHat(joystick, 0, hatstate); - - /* Button */ - if ((curstate & IKBD_JOY_FIRE) && !(prevstate & IKBD_JOY_FIRE)) { - SDL_PrivateJoystickButton(joystick,0,SDL_PRESSED); - } - if (!(curstate & IKBD_JOY_FIRE) && (prevstate & IKBD_JOY_FIRE)) { - SDL_PrivateJoystickButton(joystick,0,SDL_RELEASED); - } - } - atarijoysticks[numjoystick].prevstate = curstate; - } - break; - case PORTA_PAD: - case PORTB_PAD: - { - int numjoypad,i; - - numjoypad=0; - if (numjoystick==PORTB_PAD) numjoypad=1; - - curstate=jp_joypads[numjoypad]; - if (curstate!=prevstate) { - hatstate = SDL_HAT_CENTERED; - if (curstate & (1<>dir_shift) & 15; - curstate |= ((jp_fires>>fire_shift) & 1)<<4; - - if (curstate != prevstate) { - hatstate = SDL_HAT_CENTERED; - if (curstate & PORT_JS_LEFT) { - hatstate |= SDL_HAT_LEFT; - } - if (curstate & PORT_JS_RIGHT) { - hatstate |= SDL_HAT_RIGHT; - } - if (curstate & PORT_JS_UP) { - hatstate |= SDL_HAT_UP; - } - if (curstate & PORT_JS_DOWN) { - hatstate |= SDL_HAT_DOWN; - } - SDL_PrivateJoystickHat(joystick, 0, hatstate); - - /* Button */ - if ((curstate & PORT_JS_FIRE) && !(prevstate & PORT_JS_FIRE)) { - SDL_PrivateJoystickButton(joystick,0,SDL_PRESSED); - } - if (!(curstate & PORT_JS_FIRE) && (prevstate & PORT_JS_FIRE)) { - SDL_PrivateJoystickButton(joystick,0,SDL_RELEASED); - } - } - atarijoysticks[numjoystick].prevstate = curstate; - } - break; - case PORTA_LP: - { - int i; - - curstate = jp_lightpens[0]>>1; - curstate |= (jp_lightpens[1]>>1)<<15; - curstate |= (jp_fires & 3)<<30; - - if (curstate != prevstate) { - /* X axis */ - SDL_PrivateJoystickAxis(joystick,0,jp_lightpens[0] ^ 0x8000); - /* Y axis */ - SDL_PrivateJoystickAxis(joystick,1,jp_lightpens[1] ^ 0x8000); - /* Buttons */ - for (i=0;i<2;i++) { - int button; - - button=1<<(30+i); - - if ((curstate & button) && !(prevstate & button)) { - SDL_PrivateJoystickButton(joystick,i,SDL_PRESSED); - } - if (!(curstate & button) && (prevstate & button)) { - SDL_PrivateJoystickButton(joystick,i,SDL_RELEASED); - } - } - } - atarijoysticks[numjoystick].prevstate = curstate; - } - break; - case PORTA_ANPAD: - case PORTB_ANPAD: - { - int numpaddle, i; - - numpaddle=0<<1; - if (numjoystick==PORTB_ANPAD) numpaddle=1<<1; - - curstate = jp_paddles[numpaddle]>>1; - curstate |= (jp_paddles[numpaddle+1]>>1)<<15; - curstate |= ((jp_fires>>numpaddle) & 3)<<30; - - if (curstate != prevstate) { - /* X axis */ - SDL_PrivateJoystickAxis(joystick,0,jp_paddles[numpaddle] ^ 0x8000); - /* Y axis */ - SDL_PrivateJoystickAxis(joystick,1,jp_paddles[numpaddle+1] ^ 0x8000); - /* Buttons */ - for (i=0;i<2;i++) { - int button; - - button=1<<(30+i); - - if ((curstate & button) && !(prevstate & button)) { - SDL_PrivateJoystickButton(joystick,i,SDL_PRESSED); - } - if (!(curstate & button) && (prevstate & button)) { - SDL_PrivateJoystickButton(joystick,i,SDL_RELEASED); - } - } - } - atarijoysticks[numjoystick].prevstate = curstate; - } - break; + int numjoystick; + Uint8 hatstate; + Uint32 curstate, prevstate; + + numjoystick = GetEnabledAtariJoystick(joystick->index); + if (numjoystick == -1) + return; + + prevstate = atarijoysticks[numjoystick].prevstate; + + if (joypad_ports_enabled) { + Supexec(UpdateJoypads); + } + + switch (numjoystick) { + case IKBD_JOY1: + case XBIOS_JOY1: + { + curstate = 0; + + if (numjoystick == IKBD_JOY1) { + curstate = SDL_AtariIkbd_joystick & 0xff; + } + if (numjoystick == XBIOS_JOY1) { + curstate = SDL_AtariXbios_joystick & 0xff; + } + + if (curstate != prevstate) { + hatstate = SDL_HAT_CENTERED; + if (curstate & IKBD_JOY_LEFT) { + hatstate |= SDL_HAT_LEFT; + } + if (curstate & IKBD_JOY_RIGHT) { + hatstate |= SDL_HAT_RIGHT; + } + if (curstate & IKBD_JOY_UP) { + hatstate |= SDL_HAT_UP; + } + if (curstate & IKBD_JOY_DOWN) { + hatstate |= SDL_HAT_DOWN; + } + SDL_PrivateJoystickHat(joystick, 0, hatstate); + + /* Button */ + if ((curstate & IKBD_JOY_FIRE) + && !(prevstate & IKBD_JOY_FIRE)) { + SDL_PrivateJoystickButton(joystick, 0, SDL_PRESSED); + } + if (!(curstate & IKBD_JOY_FIRE) + && (prevstate & IKBD_JOY_FIRE)) { + SDL_PrivateJoystickButton(joystick, 0, SDL_RELEASED); + } + } + atarijoysticks[numjoystick].prevstate = curstate; + } + break; + case PORTA_PAD: + case PORTB_PAD: + { + int numjoypad, i; + + numjoypad = 0; + if (numjoystick == PORTB_PAD) + numjoypad = 1; + + curstate = jp_joypads[numjoypad]; + if (curstate != prevstate) { + hatstate = SDL_HAT_CENTERED; + if (curstate & (1 << JP_LEFT)) { + hatstate |= SDL_HAT_LEFT; + } + if (curstate & (1 << JP_RIGHT)) { + hatstate |= SDL_HAT_RIGHT; + } + if (curstate & (1 << JP_UP)) { + hatstate |= SDL_HAT_UP; + } + if (curstate & (1 << JP_DOWN)) { + hatstate |= SDL_HAT_DOWN; + } + SDL_PrivateJoystickHat(joystick, 0, hatstate); + + /* Buttons */ + for (i = 0; i < JP_NUM_BUTTONS; i++) { + int button; + + button = 1 << jp_buttons[i]; + + if ((curstate & button) && !(prevstate & button)) { + SDL_PrivateJoystickButton(joystick, i, SDL_PRESSED); + } + if (!(curstate & button) && (prevstate & button)) { + SDL_PrivateJoystickButton(joystick, i, SDL_RELEASED); + } + } + } + atarijoysticks[numjoystick].prevstate = curstate; + } + break; + case PORTA_JOY0: + case PORTA_JOY1: + case PORTB_JOY0: + case PORTB_JOY1: + { + int fire_shift = 0, dir_shift = 0; + + if (numjoystick == PORTA_JOY0) { + fire_shift = 0; + dir_shift = 0; + } + if (numjoystick == PORTA_JOY1) { + fire_shift = 1; + dir_shift = 4; + } + if (numjoystick == PORTB_JOY0) { + fire_shift = 2; + dir_shift = 8; + } + if (numjoystick == PORTB_JOY1) { + fire_shift = 3; + dir_shift = 12; + } + + curstate = (jp_directions >> dir_shift) & 15; + curstate |= ((jp_fires >> fire_shift) & 1) << 4; + + if (curstate != prevstate) { + hatstate = SDL_HAT_CENTERED; + if (curstate & PORT_JS_LEFT) { + hatstate |= SDL_HAT_LEFT; + } + if (curstate & PORT_JS_RIGHT) { + hatstate |= SDL_HAT_RIGHT; + } + if (curstate & PORT_JS_UP) { + hatstate |= SDL_HAT_UP; + } + if (curstate & PORT_JS_DOWN) { + hatstate |= SDL_HAT_DOWN; + } + SDL_PrivateJoystickHat(joystick, 0, hatstate); + + /* Button */ + if ((curstate & PORT_JS_FIRE) + && !(prevstate & PORT_JS_FIRE)) { + SDL_PrivateJoystickButton(joystick, 0, SDL_PRESSED); + } + if (!(curstate & PORT_JS_FIRE) + && (prevstate & PORT_JS_FIRE)) { + SDL_PrivateJoystickButton(joystick, 0, SDL_RELEASED); + } + } + atarijoysticks[numjoystick].prevstate = curstate; + } + break; + case PORTA_LP: + { + int i; + + curstate = jp_lightpens[0] >> 1; + curstate |= (jp_lightpens[1] >> 1) << 15; + curstate |= (jp_fires & 3) << 30; + + if (curstate != prevstate) { + /* X axis */ + SDL_PrivateJoystickAxis(joystick, 0, + jp_lightpens[0] ^ 0x8000); + /* Y axis */ + SDL_PrivateJoystickAxis(joystick, 1, + jp_lightpens[1] ^ 0x8000); + /* Buttons */ + for (i = 0; i < 2; i++) { + int button; + + button = 1 << (30 + i); + + if ((curstate & button) && !(prevstate & button)) { + SDL_PrivateJoystickButton(joystick, i, SDL_PRESSED); + } + if (!(curstate & button) && (prevstate & button)) { + SDL_PrivateJoystickButton(joystick, i, SDL_RELEASED); + } + } + } + atarijoysticks[numjoystick].prevstate = curstate; + } + break; + case PORTA_ANPAD: + case PORTB_ANPAD: + { + int numpaddle, i; + + numpaddle = 0 << 1; + if (numjoystick == PORTB_ANPAD) + numpaddle = 1 << 1; + + curstate = jp_paddles[numpaddle] >> 1; + curstate |= (jp_paddles[numpaddle + 1] >> 1) << 15; + curstate |= ((jp_fires >> numpaddle) & 3) << 30; + + if (curstate != prevstate) { + /* X axis */ + SDL_PrivateJoystickAxis(joystick, 0, + jp_paddles[numpaddle] ^ 0x8000); + /* Y axis */ + SDL_PrivateJoystickAxis(joystick, 1, + jp_paddles[numpaddle + 1] ^ 0x8000); + /* Buttons */ + for (i = 0; i < 2; i++) { + int button; + + button = 1 << (30 + i); + + if ((curstate & button) && !(prevstate & button)) { + SDL_PrivateJoystickButton(joystick, i, SDL_PRESSED); + } + if (!(curstate & button) && (prevstate & button)) { + SDL_PrivateJoystickButton(joystick, i, SDL_RELEASED); + } + } + } + atarijoysticks[numjoystick].prevstate = curstate; + } + break; #if 0 - case PARA_JOY0: - case PARA_JOY1: - break; + case PARA_JOY0: + case PARA_JOY1: + break; #endif - }; + }; - return; + return; } -void SDL_SYS_JoystickClose(SDL_Joystick *joystick) +void +SDL_SYS_JoystickClose(SDL_Joystick * joystick) { - return; + return; } -void SDL_SYS_JoystickQuit(void) +void +SDL_SYS_JoystickQuit(void) { - SDL_numjoysticks=0; - return; + SDL_numjoysticks = 0; + return; } /*--- Joypad I/O read/write interface ---*/ #define JOYPAD_IO_BASE (0xffff9200) -struct JOYPAD_IO_S { - Uint16 fires; - Uint16 directions; - Uint16 dummy1[6]; - Uint16 paddles[4]; - Uint16 dummy2[4]; - Uint16 lightpens[2]; +struct JOYPAD_IO_S +{ + Uint16 fires; + Uint16 directions; + Uint16 dummy1[6]; + Uint16 paddles[4]; + Uint16 dummy2[4]; + Uint16 lightpens[2]; }; #define JOYPAD_IO ((*(volatile struct JOYPAD_IO_S *)JOYPAD_IO_BASE)) -static void UpdateJoypads(void) +static void +UpdateJoypads(void) { - Uint16 tmp; - - /*--- This function is called in supervisor mode ---*/ - - /* Update joysticks */ - jp_fires = (~(JOYPAD_IO.fires)) & 15; - jp_directions = (~(JOYPAD_IO.directions)); - - /* Update lightpen */ - tmp = JOYPAD_IO.lightpens[0] & 1023; - jp_lightpens[0] = (tmp<<6) | (tmp>>4); - tmp = JOYPAD_IO.lightpens[1] & 1023; - jp_lightpens[1] = (tmp<<6) | (tmp>>4); - - /* Update paddles */ - tmp = (JOYPAD_IO.paddles[0] & 255); - jp_paddles[0] = (tmp<<8) | tmp; - tmp = (JOYPAD_IO.paddles[1] & 255); - jp_paddles[1] = (tmp<<8) | tmp; - tmp = (JOYPAD_IO.paddles[2] & 255); - jp_paddles[2] = (tmp<<8) | tmp; - tmp = (JOYPAD_IO.paddles[3] & 255); - jp_paddles[3] = (tmp<<8) | tmp; - - /* Update joypad 0 */ - JOYPAD_IO.directions=0xfffe; - jp_joypads[0]=((~(JOYPAD_IO.fires)) & 3)<<(16); - JOYPAD_IO.directions=0xfffe; - jp_joypads[0] |= ((~(JOYPAD_IO.directions))>>8) & 15; - - JOYPAD_IO.directions=0xfffd; - jp_joypads[0] |= ((~(JOYPAD_IO.fires)) & 3)<<(16+2); - JOYPAD_IO.directions=0xfffd; - jp_joypads[0] |= (((~(JOYPAD_IO.directions))>>8) & 15)<<4; - - JOYPAD_IO.directions=0xfffb; - jp_joypads[0] |= ((~(JOYPAD_IO.fires)) & 3)<<(16+4); - JOYPAD_IO.directions=0xfffb; - jp_joypads[0] |= (((~(JOYPAD_IO.directions))>>8) & 15)<<8; - - JOYPAD_IO.directions=0xfff7; - jp_joypads[0] |= ((~(JOYPAD_IO.fires)) & 3)<<(16+6); - JOYPAD_IO.directions=0xfff7; - jp_joypads[0] |= (((~(JOYPAD_IO.directions))>>8) & 15)<<12; - - /* Update joypad 1 */ - JOYPAD_IO.directions=0xffef; - jp_joypads[1]=((~(JOYPAD_IO.fires)) & (3<<2))<<(16-2); - JOYPAD_IO.directions=0xffef; - jp_joypads[1] |= ((~(JOYPAD_IO.directions))>>12) & 15; - - JOYPAD_IO.directions=0xffdf; - jp_joypads[1] |= ((~(JOYPAD_IO.fires)) & (3<<2))<<(16); - JOYPAD_IO.directions=0xffdf; - jp_joypads[1] |= (((~(JOYPAD_IO.directions))>>12) & 15)<<4; - - JOYPAD_IO.directions=0xffbf; - jp_joypads[1] |= ((~(JOYPAD_IO.fires)) & (3<<2))<<(16+2); - JOYPAD_IO.directions=0xffbf; - jp_joypads[1] |= (((~(JOYPAD_IO.directions))>>12) & 15)<<8; - - JOYPAD_IO.directions=0xff7f; - jp_joypads[1] |= ((~(JOYPAD_IO.fires)) & (3<<2))<<(16+4); - JOYPAD_IO.directions=0xff7f; - jp_joypads[1] |= (((~(JOYPAD_IO.directions))>>12) & 15)<<12; + Uint16 tmp; + + /*--- This function is called in supervisor mode ---*/ + + /* Update joysticks */ + jp_fires = (~(JOYPAD_IO.fires)) & 15; + jp_directions = (~(JOYPAD_IO.directions)); + + /* Update lightpen */ + tmp = JOYPAD_IO.lightpens[0] & 1023; + jp_lightpens[0] = (tmp << 6) | (tmp >> 4); + tmp = JOYPAD_IO.lightpens[1] & 1023; + jp_lightpens[1] = (tmp << 6) | (tmp >> 4); + + /* Update paddles */ + tmp = (JOYPAD_IO.paddles[0] & 255); + jp_paddles[0] = (tmp << 8) | tmp; + tmp = (JOYPAD_IO.paddles[1] & 255); + jp_paddles[1] = (tmp << 8) | tmp; + tmp = (JOYPAD_IO.paddles[2] & 255); + jp_paddles[2] = (tmp << 8) | tmp; + tmp = (JOYPAD_IO.paddles[3] & 255); + jp_paddles[3] = (tmp << 8) | tmp; + + /* Update joypad 0 */ + JOYPAD_IO.directions = 0xfffe; + jp_joypads[0] = ((~(JOYPAD_IO.fires)) & 3) << (16); + JOYPAD_IO.directions = 0xfffe; + jp_joypads[0] |= ((~(JOYPAD_IO.directions)) >> 8) & 15; + + JOYPAD_IO.directions = 0xfffd; + jp_joypads[0] |= ((~(JOYPAD_IO.fires)) & 3) << (16 + 2); + JOYPAD_IO.directions = 0xfffd; + jp_joypads[0] |= (((~(JOYPAD_IO.directions)) >> 8) & 15) << 4; + + JOYPAD_IO.directions = 0xfffb; + jp_joypads[0] |= ((~(JOYPAD_IO.fires)) & 3) << (16 + 4); + JOYPAD_IO.directions = 0xfffb; + jp_joypads[0] |= (((~(JOYPAD_IO.directions)) >> 8) & 15) << 8; + + JOYPAD_IO.directions = 0xfff7; + jp_joypads[0] |= ((~(JOYPAD_IO.fires)) & 3) << (16 + 6); + JOYPAD_IO.directions = 0xfff7; + jp_joypads[0] |= (((~(JOYPAD_IO.directions)) >> 8) & 15) << 12; + + /* Update joypad 1 */ + JOYPAD_IO.directions = 0xffef; + jp_joypads[1] = ((~(JOYPAD_IO.fires)) & (3 << 2)) << (16 - 2); + JOYPAD_IO.directions = 0xffef; + jp_joypads[1] |= ((~(JOYPAD_IO.directions)) >> 12) & 15; + + JOYPAD_IO.directions = 0xffdf; + jp_joypads[1] |= ((~(JOYPAD_IO.fires)) & (3 << 2)) << (16); + JOYPAD_IO.directions = 0xffdf; + jp_joypads[1] |= (((~(JOYPAD_IO.directions)) >> 12) & 15) << 4; + + JOYPAD_IO.directions = 0xffbf; + jp_joypads[1] |= ((~(JOYPAD_IO.fires)) & (3 << 2)) << (16 + 2); + JOYPAD_IO.directions = 0xffbf; + jp_joypads[1] |= (((~(JOYPAD_IO.directions)) >> 12) & 15) << 8; + + JOYPAD_IO.directions = 0xff7f; + jp_joypads[1] |= ((~(JOYPAD_IO.fires)) & (3 << 2)) << (16 + 4); + JOYPAD_IO.directions = 0xff7f; + jp_joypads[1] |= (((~(JOYPAD_IO.directions)) >> 12) & 15) << 12; } #endif /* SDL_JOYSTICK_MINT */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/joystick/os2/SDL_sysjoystick.c b/src/joystick/os2/SDL_sysjoystick.c index 15dca4eb7..1a01dfd3c 100644 --- a/src/joystick/os2/SDL_sysjoystick.c +++ b/src/joystick/os2/SDL_sysjoystick.c @@ -38,15 +38,15 @@ #include "../SDL_sysjoystick.h" #include "../SDL_joystick_c.h" -HFILE hJoyPort = NULL; /* Joystick GAME$ Port Address */ -#define MAX_JOYSTICKS 2 /* Maximum of two joysticks */ -#define MAX_AXES 4 /* each joystick can have up to 4 axes */ -#define MAX_BUTTONS 8 /* 8 buttons */ -#define MAX_HATS 0 /* 0 hats - OS/2 doesn't support it */ -#define MAX_BALLS 0 /* and 0 balls - OS/2 doesn't support it */ -#define AXIS_MIN -32768 /* minimum value for axes coordinate */ -#define AXIS_MAX 32767 /* maximum value for axes coordinate */ -#define MAX_JOYNAME 128 /* Joystick name may have 128 characters */ +HFILE hJoyPort = NULL; /* Joystick GAME$ Port Address */ +#define MAX_JOYSTICKS 2 /* Maximum of two joysticks */ +#define MAX_AXES 4 /* each joystick can have up to 4 axes */ +#define MAX_BUTTONS 8 /* 8 buttons */ +#define MAX_HATS 0 /* 0 hats - OS/2 doesn't support it */ +#define MAX_BALLS 0 /* and 0 balls - OS/2 doesn't support it */ +#define AXIS_MIN -32768 /* minimum value for axes coordinate */ +#define AXIS_MAX 32767 /* maximum value for axes coordinate */ +#define MAX_JOYNAME 128 /* Joystick name may have 128 characters */ /* limit axes to 256 possible positions to filter out noise */ #define JOY_AXIS_THRESHOLD (((AXIS_MAX)-(AXIS_MIN))/256) /* Calc Button Flag for buttons A to D */ @@ -55,16 +55,16 @@ HFILE hJoyPort = NULL; /* Joystick GAME$ Port Address */ /* Joystick data... hold information about detected devices */ typedef struct SYS_JoyData_s { -Sint8 id; // Device ID -char szDeviceName[MAX_JOYNAME]; // Device Name -char axes; // Number of axes -char buttons; // Number of buttons -char hats; // Number of buttons -char balls; // Number of buttons -int axes_min[MAX_AXES]; // minimum callibration value for axes -int axes_med[MAX_AXES]; // medium callibration value for axes -int axes_max[MAX_AXES]; // maximum callibration value for axes -int buttoncalc[4]; // Used for buttons 5, 6, 7 and 8. + Sint8 id; // Device ID + char szDeviceName[MAX_JOYNAME]; // Device Name + char axes; // Number of axes + char buttons; // Number of buttons + char hats; // Number of buttons + char balls; // Number of buttons + int axes_min[MAX_AXES]; // minimum callibration value for axes + int axes_med[MAX_AXES]; // medium callibration value for axes + int axes_max[MAX_AXES]; // maximum callibration value for axes + int buttoncalc[4]; // Used for buttons 5, 6, 7 and 8. } SYS_JoyData_t, *SYS_JoyData_p; SYS_JoyData_t SYS_JoyData[MAX_JOYSTICKS]; @@ -73,30 +73,30 @@ SYS_JoyData_t SYS_JoyData[MAX_JOYSTICKS]; /* Structure used to convert data from OS/2 driver format to SDL format */ struct joystick_hwdata { -Sint8 id; -struct _transaxes - { - int offset; /* Center Offset */ - float scale1; /* Center to left/up Scale */ - float scale2; /* Center to right/down Scale */ - } transaxes[MAX_AXES]; + Sint8 id; + struct _transaxes + { + int offset; /* Center Offset */ + float scale1; /* Center to left/up Scale */ + float scale2; /* Center to right/down Scale */ + } transaxes[MAX_AXES]; }; /* Structure used to get values from Joystick Environment Variable */ struct _joycfg { -char name[MAX_JOYNAME]; -unsigned int axes; -unsigned int buttons; -unsigned int hats; -unsigned int balls; + char name[MAX_JOYNAME]; + unsigned int axes; + unsigned int buttons; + unsigned int hats; + unsigned int balls; }; /* OS/2 Implementation Function Prototypes */ APIRET joyPortOpen(HFILE * hGame); void joyPortClose(HFILE * hGame); int joyGetData(char *joyenv, char *name, char stopchar, size_t maxchars); -int joyGetEnv(struct _joycfg * joydata); +int joyGetEnv(struct _joycfg *joydata); @@ -106,214 +106,228 @@ int joyGetEnv(struct _joycfg * joydata); /* joysticks. Joystick 0 should be the system default joystick. */ /* It should return 0, or -1 on an unrecoverable fatal error. */ /************************************************************************/ -int SDL_SYS_JoystickInit(void) +int +SDL_SYS_JoystickInit(void) { -APIRET rc; /* Generic OS/2 return code */ -GAME_PORT_STRUCT stJoyStatus; /* Joystick Status Structure */ -GAME_PARM_STRUCT stGameParms; /* Joystick Parameter Structure */ -GAME_CALIB_STRUCT stGameCalib; /* Calibration Struct */ -ULONG ulDataLen; /* Size of data */ -ULONG ulLastTick; /* Tick Counter for timing operations */ -Uint8 maxdevs; /* Maximum number of devices */ -Uint8 numdevs; /* Number of present devices */ -Uint8 maxbut; /* Maximum number of buttons... */ -Uint8 i; /* Temporary Count Vars */ -Uint8 ucNewJoystickMask; /* Mask for Joystick Detection */ -struct _joycfg joycfg; /* Joy Configuration from envvar */ + APIRET rc; /* Generic OS/2 return code */ + GAME_PORT_STRUCT stJoyStatus; /* Joystick Status Structure */ + GAME_PARM_STRUCT stGameParms; /* Joystick Parameter Structure */ + GAME_CALIB_STRUCT stGameCalib; /* Calibration Struct */ + ULONG ulDataLen; /* Size of data */ + ULONG ulLastTick; /* Tick Counter for timing operations */ + Uint8 maxdevs; /* Maximum number of devices */ + Uint8 numdevs; /* Number of present devices */ + Uint8 maxbut; /* Maximum number of buttons... */ + Uint8 i; /* Temporary Count Vars */ + Uint8 ucNewJoystickMask; /* Mask for Joystick Detection */ + struct _joycfg joycfg; /* Joy Configuration from envvar */ /* Get Max Number of Devices */ -rc = joyPortOpen(&hJoyPort); /* Open GAME$ port */ -if (rc != 0) return 0; /* Cannot open... report no joystick */ -ulDataLen = sizeof(stGameParms); -rc = DosDevIOCtl(hJoyPort, IOCTL_CAT_USER, GAME_GET_PARMS, - NULL, 0, NULL, &stGameParms, ulDataLen, &ulDataLen); /* Ask device info */ -if (rc != 0) - { - joyPortClose(&hJoyPort); - SDL_SetError("Could not read joystick port."); - return -1; - } -if (stGameParms.useA != 0) maxdevs++; -if (stGameParms.useB != 0) maxdevs++; -if ( maxdevs > MAX_JOYSTICKS ) maxdevs = MAX_JOYSTICKS; + rc = joyPortOpen(&hJoyPort); /* Open GAME$ port */ + if (rc != 0) + return 0; /* Cannot open... report no joystick */ + ulDataLen = sizeof(stGameParms); + rc = DosDevIOCtl(hJoyPort, IOCTL_CAT_USER, GAME_GET_PARMS, NULL, 0, NULL, &stGameParms, ulDataLen, &ulDataLen); /* Ask device info */ + if (rc != 0) { + joyPortClose(&hJoyPort); + SDL_SetError("Could not read joystick port."); + return -1; + } + if (stGameParms.useA != 0) + maxdevs++; + if (stGameParms.useB != 0) + maxdevs++; + if (maxdevs > MAX_JOYSTICKS) + maxdevs = MAX_JOYSTICKS; /* Defines min/max axes values (callibration) */ -ulDataLen = sizeof(stGameCalib); -rc = DosDevIOCtl(hJoyPort, IOCTL_CAT_USER, GAME_GET_CALIB, - NULL, 0, NULL, &stGameCalib, ulDataLen, &ulDataLen); -if (rc != 0) - { - joyPortClose(&hJoyPort); - SDL_SetError("Could not read callibration data."); - return -1; - } + ulDataLen = sizeof(stGameCalib); + rc = DosDevIOCtl(hJoyPort, IOCTL_CAT_USER, GAME_GET_CALIB, + NULL, 0, NULL, &stGameCalib, ulDataLen, &ulDataLen); + if (rc != 0) { + joyPortClose(&hJoyPort); + SDL_SetError("Could not read callibration data."); + return -1; + } /* Determine how many joysticks are active */ -numdevs = 0; /* Points no device */ -ucNewJoystickMask = 0x0F; /* read all 4 joystick axis */ -ulDataLen = sizeof(ucNewJoystickMask); -rc = DosDevIOCtl(hJoyPort, IOCTL_CAT_USER, GAME_PORT_RESET, - &ucNewJoystickMask, ulDataLen, &ulDataLen, NULL, 0, NULL); -if (rc == 0) - { - ulDataLen = sizeof(stJoyStatus); - rc = DosDevIOCtl(hJoyPort, IOCTL_CAT_USER, GAME_PORT_GET, - NULL, 0, NULL, &stJoyStatus, ulDataLen, &ulDataLen); - if (rc != 0) - { - joyPortClose(&hJoyPort); - SDL_SetError("Could not call joystick port."); - return -1; - } - ulLastTick = stJoyStatus.ulJs_Ticks; - while (stJoyStatus.ulJs_Ticks == ulLastTick) - { - rc = DosDevIOCtl(hJoyPort, IOCTL_CAT_USER, GAME_PORT_GET, - NULL, 0, NULL, &stJoyStatus, ulDataLen, &ulDataLen); - } - if ((stJoyStatus.ucJs_JoyStickMask & 0x03) > 0) numdevs++; - if (((stJoyStatus.ucJs_JoyStickMask >> 2) & 0x03) > 0) numdevs++; - } - -if (numdevs>maxdevs) numdevs=maxdevs; + numdevs = 0; /* Points no device */ + ucNewJoystickMask = 0x0F; /* read all 4 joystick axis */ + ulDataLen = sizeof(ucNewJoystickMask); + rc = DosDevIOCtl(hJoyPort, IOCTL_CAT_USER, GAME_PORT_RESET, + &ucNewJoystickMask, ulDataLen, &ulDataLen, NULL, 0, + NULL); + if (rc == 0) { + ulDataLen = sizeof(stJoyStatus); + rc = DosDevIOCtl(hJoyPort, IOCTL_CAT_USER, GAME_PORT_GET, + NULL, 0, NULL, &stJoyStatus, ulDataLen, &ulDataLen); + if (rc != 0) { + joyPortClose(&hJoyPort); + SDL_SetError("Could not call joystick port."); + return -1; + } + ulLastTick = stJoyStatus.ulJs_Ticks; + while (stJoyStatus.ulJs_Ticks == ulLastTick) { + rc = DosDevIOCtl(hJoyPort, IOCTL_CAT_USER, GAME_PORT_GET, + NULL, 0, NULL, &stJoyStatus, ulDataLen, + &ulDataLen); + } + if ((stJoyStatus.ucJs_JoyStickMask & 0x03) > 0) + numdevs++; + if (((stJoyStatus.ucJs_JoyStickMask >> 2) & 0x03) > 0) + numdevs++; + } + + if (numdevs > maxdevs) + numdevs = maxdevs; /* If *any* joystick was detected... Let's configure SDL for them */ -if (numdevs > 0) - { - /* Verify if it is a "user defined" joystick */ - if (joyGetEnv(&joycfg)) - { - GAME_3POS_STRUCT * axis[4]; - axis[0] = &stGameCalib.Ax; - axis[1] = &stGameCalib.Ay; - axis[2] = &stGameCalib.Bx; - axis[3] = &stGameCalib.By; - /* Say it has one device only (user defined is always one device only) */ - numdevs = 1; - /* Define Device 0 as... */ - SYS_JoyData[0].id=0; - /* Define Number of Axes... up to 4 */ - if (joycfg.axes>MAX_AXES) joycfg.axes = MAX_AXES; - SYS_JoyData[0].axes = joycfg.axes; - /* Define number of buttons... 8 if 2 axes, 6 if 3 axes and 4 if 4 axes */ - maxbut = MAX_BUTTONS; - if (joycfg.axes>2) maxbut-=((joycfg.axes-2)<<1); /* MAX_BUTTONS - 2*(axes-2) */ - if (joycfg.buttons > maxbut) joycfg.buttons = maxbut; - SYS_JoyData[0].buttons = joycfg.buttons; - /* Define number of hats */ - if (joycfg.hats > MAX_HATS) joycfg.hats = MAX_HATS; - SYS_JoyData[0].hats = joycfg.hats; - /* Define number of balls */ - if (joycfg.balls > MAX_BALLS) joycfg.balls = MAX_BALLS; - SYS_JoyData[0].balls = joycfg.balls; - /* Initialize Axes Callibration Values */ - for (i=0; ilower; - SYS_JoyData[0].axes_med[i] = axis[i]->centre; - SYS_JoyData[0].axes_max[i] = axis[i]->upper; - } - /* Initialize Buttons 5 to 8 structures */ - if (joycfg.buttons>=5) SYS_JoyData[0].buttoncalc[0]=((axis[2]->lower+axis[3]->centre)>>1); - if (joycfg.buttons>=6) SYS_JoyData[0].buttoncalc[1]=((axis[3]->lower+axis[3]->centre)>>1); - if (joycfg.buttons>=7) SYS_JoyData[0].buttoncalc[2]=((axis[2]->upper+axis[3]->centre)>>1); - if (joycfg.buttons>=8) SYS_JoyData[0].buttoncalc[3]=((axis[3]->upper+axis[3]->centre)>>1); - /* Intialize Joystick Name */ - SDL_strlcpy (SYS_JoyData[0].szDeviceName,joycfg.name, SDL_arraysize(SYS_JoyData[0].szDeviceName)); - } - /* Default Init ... autoconfig */ - else - { - /* if two devices were detected... configure as Joy1 4 axis and Joy2 2 axis */ - if (numdevs==2) - { - /* Define Device 0 as 4 axes, 4 buttons */ - SYS_JoyData[0].id=0; - SYS_JoyData[0].axes = 4; - SYS_JoyData[0].buttons = 4; - SYS_JoyData[0].hats = 0; - SYS_JoyData[0].balls = 0; - SYS_JoyData[0].axes_min[0] = stGameCalib.Ax.lower; - SYS_JoyData[0].axes_med[0] = stGameCalib.Ax.centre; - SYS_JoyData[0].axes_max[0] = stGameCalib.Ax.upper; - SYS_JoyData[0].axes_min[1] = stGameCalib.Ay.lower; - SYS_JoyData[0].axes_med[1] = stGameCalib.Ay.centre; - SYS_JoyData[0].axes_max[1] = stGameCalib.Ay.upper; - SYS_JoyData[0].axes_min[2] = stGameCalib.Bx.lower; - SYS_JoyData[0].axes_med[2] = stGameCalib.Bx.centre; - SYS_JoyData[0].axes_max[2] = stGameCalib.Bx.upper; - SYS_JoyData[0].axes_min[3] = stGameCalib.By.lower; - SYS_JoyData[0].axes_med[3] = stGameCalib.By.centre; - SYS_JoyData[0].axes_max[3] = stGameCalib.By.upper; - /* Define Device 1 as 2 axes, 2 buttons */ - SYS_JoyData[1].id=1; - SYS_JoyData[1].axes = 2; - SYS_JoyData[1].buttons = 2; - SYS_JoyData[1].hats = 0; - SYS_JoyData[1].balls = 0; - SYS_JoyData[1].axes_min[0] = stGameCalib.Bx.lower; - SYS_JoyData[1].axes_med[0] = stGameCalib.Bx.centre; - SYS_JoyData[1].axes_max[0] = stGameCalib.Bx.upper; - SYS_JoyData[1].axes_min[1] = stGameCalib.By.lower; - SYS_JoyData[1].axes_med[1] = stGameCalib.By.centre; - SYS_JoyData[1].axes_max[1] = stGameCalib.By.upper; - } - /* One joystick only? */ - else - { - /* If it is joystick A... */ - if ((stJoyStatus.ucJs_JoyStickMask & 0x03) > 0) - { - /* Define Device 0 as 2 axes, 4 buttons */ - SYS_JoyData[0].id=0; - SYS_JoyData[0].axes = 2; - SYS_JoyData[0].buttons = 4; - SYS_JoyData[0].hats = 0; - SYS_JoyData[0].balls = 0; - SYS_JoyData[0].axes_min[0] = stGameCalib.Ax.lower; - SYS_JoyData[0].axes_med[0] = stGameCalib.Ax.centre; - SYS_JoyData[0].axes_max[0] = stGameCalib.Ax.upper; - SYS_JoyData[0].axes_min[1] = stGameCalib.Ay.lower; - SYS_JoyData[0].axes_med[1] = stGameCalib.Ay.centre; - SYS_JoyData[0].axes_max[1] = stGameCalib.Ay.upper; - } - /* If not, it is joystick B */ - else - { - /* Define Device 1 as 2 axes, 2 buttons */ - SYS_JoyData[0].id=1; - SYS_JoyData[0].axes = 2; - SYS_JoyData[0].buttons = 2; - SYS_JoyData[0].hats = 0; - SYS_JoyData[0].balls = 0; - SYS_JoyData[0].axes_min[0] = stGameCalib.Bx.lower; - SYS_JoyData[0].axes_med[0] = stGameCalib.Bx.centre; - SYS_JoyData[0].axes_max[0] = stGameCalib.Bx.upper; - SYS_JoyData[0].axes_min[1] = stGameCalib.By.lower; - SYS_JoyData[0].axes_med[1] = stGameCalib.By.centre; - SYS_JoyData[0].axes_max[1] = stGameCalib.By.upper; - } - } - /* Hack to define Joystick Port Names */ - if ( numdevs > maxdevs ) numdevs = maxdevs; - for (i=0; i 0) { + /* Verify if it is a "user defined" joystick */ + if (joyGetEnv(&joycfg)) { + GAME_3POS_STRUCT *axis[4]; + axis[0] = &stGameCalib.Ax; + axis[1] = &stGameCalib.Ay; + axis[2] = &stGameCalib.Bx; + axis[3] = &stGameCalib.By; + /* Say it has one device only (user defined is always one device only) */ + numdevs = 1; + /* Define Device 0 as... */ + SYS_JoyData[0].id = 0; + /* Define Number of Axes... up to 4 */ + if (joycfg.axes > MAX_AXES) + joycfg.axes = MAX_AXES; + SYS_JoyData[0].axes = joycfg.axes; + /* Define number of buttons... 8 if 2 axes, 6 if 3 axes and 4 if 4 axes */ + maxbut = MAX_BUTTONS; + if (joycfg.axes > 2) + maxbut -= ((joycfg.axes - 2) << 1); /* MAX_BUTTONS - 2*(axes-2) */ + if (joycfg.buttons > maxbut) + joycfg.buttons = maxbut; + SYS_JoyData[0].buttons = joycfg.buttons; + /* Define number of hats */ + if (joycfg.hats > MAX_HATS) + joycfg.hats = MAX_HATS; + SYS_JoyData[0].hats = joycfg.hats; + /* Define number of balls */ + if (joycfg.balls > MAX_BALLS) + joycfg.balls = MAX_BALLS; + SYS_JoyData[0].balls = joycfg.balls; + /* Initialize Axes Callibration Values */ + for (i = 0; i < joycfg.axes; i++) { + SYS_JoyData[0].axes_min[i] = axis[i]->lower; + SYS_JoyData[0].axes_med[i] = axis[i]->centre; + SYS_JoyData[0].axes_max[i] = axis[i]->upper; + } + /* Initialize Buttons 5 to 8 structures */ + if (joycfg.buttons >= 5) + SYS_JoyData[0].buttoncalc[0] = + ((axis[2]->lower + axis[3]->centre) >> 1); + if (joycfg.buttons >= 6) + SYS_JoyData[0].buttoncalc[1] = + ((axis[3]->lower + axis[3]->centre) >> 1); + if (joycfg.buttons >= 7) + SYS_JoyData[0].buttoncalc[2] = + ((axis[2]->upper + axis[3]->centre) >> 1); + if (joycfg.buttons >= 8) + SYS_JoyData[0].buttoncalc[3] = + ((axis[3]->upper + axis[3]->centre) >> 1); + /* Intialize Joystick Name */ + SDL_strlcpy(SYS_JoyData[0].szDeviceName, joycfg.name, + SDL_arraysize(SYS_JoyData[0].szDeviceName)); + } + /* Default Init ... autoconfig */ + else { + /* if two devices were detected... configure as Joy1 4 axis and Joy2 2 axis */ + if (numdevs == 2) { + /* Define Device 0 as 4 axes, 4 buttons */ + SYS_JoyData[0].id = 0; + SYS_JoyData[0].axes = 4; + SYS_JoyData[0].buttons = 4; + SYS_JoyData[0].hats = 0; + SYS_JoyData[0].balls = 0; + SYS_JoyData[0].axes_min[0] = stGameCalib.Ax.lower; + SYS_JoyData[0].axes_med[0] = stGameCalib.Ax.centre; + SYS_JoyData[0].axes_max[0] = stGameCalib.Ax.upper; + SYS_JoyData[0].axes_min[1] = stGameCalib.Ay.lower; + SYS_JoyData[0].axes_med[1] = stGameCalib.Ay.centre; + SYS_JoyData[0].axes_max[1] = stGameCalib.Ay.upper; + SYS_JoyData[0].axes_min[2] = stGameCalib.Bx.lower; + SYS_JoyData[0].axes_med[2] = stGameCalib.Bx.centre; + SYS_JoyData[0].axes_max[2] = stGameCalib.Bx.upper; + SYS_JoyData[0].axes_min[3] = stGameCalib.By.lower; + SYS_JoyData[0].axes_med[3] = stGameCalib.By.centre; + SYS_JoyData[0].axes_max[3] = stGameCalib.By.upper; + /* Define Device 1 as 2 axes, 2 buttons */ + SYS_JoyData[1].id = 1; + SYS_JoyData[1].axes = 2; + SYS_JoyData[1].buttons = 2; + SYS_JoyData[1].hats = 0; + SYS_JoyData[1].balls = 0; + SYS_JoyData[1].axes_min[0] = stGameCalib.Bx.lower; + SYS_JoyData[1].axes_med[0] = stGameCalib.Bx.centre; + SYS_JoyData[1].axes_max[0] = stGameCalib.Bx.upper; + SYS_JoyData[1].axes_min[1] = stGameCalib.By.lower; + SYS_JoyData[1].axes_med[1] = stGameCalib.By.centre; + SYS_JoyData[1].axes_max[1] = stGameCalib.By.upper; + } + /* One joystick only? */ + else { + /* If it is joystick A... */ + if ((stJoyStatus.ucJs_JoyStickMask & 0x03) > 0) { + /* Define Device 0 as 2 axes, 4 buttons */ + SYS_JoyData[0].id = 0; + SYS_JoyData[0].axes = 2; + SYS_JoyData[0].buttons = 4; + SYS_JoyData[0].hats = 0; + SYS_JoyData[0].balls = 0; + SYS_JoyData[0].axes_min[0] = stGameCalib.Ax.lower; + SYS_JoyData[0].axes_med[0] = stGameCalib.Ax.centre; + SYS_JoyData[0].axes_max[0] = stGameCalib.Ax.upper; + SYS_JoyData[0].axes_min[1] = stGameCalib.Ay.lower; + SYS_JoyData[0].axes_med[1] = stGameCalib.Ay.centre; + SYS_JoyData[0].axes_max[1] = stGameCalib.Ay.upper; + } + /* If not, it is joystick B */ + else { + /* Define Device 1 as 2 axes, 2 buttons */ + SYS_JoyData[0].id = 1; + SYS_JoyData[0].axes = 2; + SYS_JoyData[0].buttons = 2; + SYS_JoyData[0].hats = 0; + SYS_JoyData[0].balls = 0; + SYS_JoyData[0].axes_min[0] = stGameCalib.Bx.lower; + SYS_JoyData[0].axes_med[0] = stGameCalib.Bx.centre; + SYS_JoyData[0].axes_max[0] = stGameCalib.Bx.upper; + SYS_JoyData[0].axes_min[1] = stGameCalib.By.lower; + SYS_JoyData[0].axes_med[1] = stGameCalib.By.centre; + SYS_JoyData[0].axes_max[1] = stGameCalib.By.upper; } - } + } + /* Hack to define Joystick Port Names */ + if (numdevs > maxdevs) + numdevs = maxdevs; + for (i = 0; i < numdevs; i++) + SDL_snprintf(SYS_JoyData[i].szDeviceName, + SDL_arraysize(SYS_JoyData[i].szDeviceName), + "Default Joystick %c", 'A' + SYS_JoyData[i].id); + + } + } /* Return the number of devices found */ -return(numdevs); + return (numdevs); } /***********************************************************/ /* Function to get the device-dependent name of a joystick */ /***********************************************************/ -const char *SDL_SYS_JoystickName(int index) +const char * +SDL_SYS_JoystickName(int index) { /* No need to verify if device exists, already done in upper layer */ -return(SYS_JoyData[index].szDeviceName); + return (SYS_JoyData[index].szDeviceName); } @@ -324,51 +338,51 @@ return(SYS_JoyData[index].szDeviceName); /* This should fill the nbuttons and naxes fields of the joystick structure. */ /* It returns 0, or -1 if there is an error. */ /******************************************************************************/ -int SDL_SYS_JoystickOpen(SDL_Joystick *joystick) +int +SDL_SYS_JoystickOpen(SDL_Joystick * joystick) { -int index; /* Index shortcut for index in joystick structure */ -int i; /* Generic Counter */ + int index; /* Index shortcut for index in joystick structure */ + int i; /* Generic Counter */ /* allocate memory for system specific hardware data */ -joystick->hwdata = (struct joystick_hwdata *) SDL_malloc(sizeof(*joystick->hwdata)); -if (joystick->hwdata == NULL) - { - SDL_OutOfMemory(); - return(-1); - } + joystick->hwdata = + (struct joystick_hwdata *) SDL_malloc(sizeof(*joystick->hwdata)); + if (joystick->hwdata == NULL) { + SDL_OutOfMemory(); + return (-1); + } /* Reset Hardware Data */ -SDL_memset(joystick->hwdata, 0, sizeof(*joystick->hwdata)); + SDL_memset(joystick->hwdata, 0, sizeof(*joystick->hwdata)); /* ShortCut Pointer */ -index = joystick->index; + index = joystick->index; /* Define offsets and scales for all axes */ -joystick->hwdata->id = SYS_JoyData[index].id; -for ( i = 0; i < MAX_AXES; ++i ) - { - if ( (i<2) || i < SYS_JoyData[index].axes ) - { - joystick->hwdata->transaxes[i].offset = ((AXIS_MAX + AXIS_MIN)>>1) - SYS_JoyData[index].axes_med[i]; - //joystick->hwdata->transaxes[i].scale = (float)((AXIS_MAX - AXIS_MIN)/(SYS_JoyData[index].axes_max[i]-SYS_JoyData[index].axes_min[i])); - joystick->hwdata->transaxes[i].scale1 = (float)abs((AXIS_MIN/SYS_JoyData[index].axes_min[i])); - joystick->hwdata->transaxes[i].scale2 = (float)abs((AXIS_MAX/SYS_JoyData[index].axes_max[i])); - } - else - { - joystick->hwdata->transaxes[i].offset = 0; - //joystick->hwdata->transaxes[i].scale = 1.0; /* Just in case */ - joystick->hwdata->transaxes[i].scale1 = 1.0; /* Just in case */ - joystick->hwdata->transaxes[i].scale2 = 1.0; /* Just in case */ - } - } + joystick->hwdata->id = SYS_JoyData[index].id; + for (i = 0; i < MAX_AXES; ++i) { + if ((i < 2) || i < SYS_JoyData[index].axes) { + joystick->hwdata->transaxes[i].offset = + ((AXIS_MAX + AXIS_MIN) >> 1) - SYS_JoyData[index].axes_med[i]; + //joystick->hwdata->transaxes[i].scale = (float)((AXIS_MAX - AXIS_MIN)/(SYS_JoyData[index].axes_max[i]-SYS_JoyData[index].axes_min[i])); + joystick->hwdata->transaxes[i].scale1 = + (float) abs((AXIS_MIN / SYS_JoyData[index].axes_min[i])); + joystick->hwdata->transaxes[i].scale2 = + (float) abs((AXIS_MAX / SYS_JoyData[index].axes_max[i])); + } else { + joystick->hwdata->transaxes[i].offset = 0; + //joystick->hwdata->transaxes[i].scale = 1.0; /* Just in case */ + joystick->hwdata->transaxes[i].scale1 = 1.0; /* Just in case */ + joystick->hwdata->transaxes[i].scale2 = 1.0; /* Just in case */ + } + } /* fill nbuttons, naxes, and nhats fields */ -joystick->nbuttons = SYS_JoyData[index].buttons; -joystick->naxes = SYS_JoyData[index].axes; + joystick->nbuttons = SYS_JoyData[index].buttons; + joystick->naxes = SYS_JoyData[index].axes; /* joystick->nhats = SYS_JoyData[index].hats; */ -joystick->nhats = 0; /* No support for hats at this time */ + joystick->nhats = 0; /* No support for hats at this time */ /* joystick->nballs = SYS_JoyData[index].balls; */ -joystick->nballs = 0; /* No support for balls at this time */ -return 0; + joystick->nballs = 0; /* No support for balls at this time */ + return 0; } @@ -379,131 +393,132 @@ return 0; /* but instead should call SDL_PrivateJoystick*() to deliver events */ /* and update joystick device state. */ /***************************************************************************/ -void SDL_SYS_JoystickUpdate(SDL_Joystick *joystick) +void +SDL_SYS_JoystickUpdate(SDL_Joystick * joystick) { -APIRET rc; /* Generic OS/2 return code */ -int index; /* index shortcurt to joystick index */ -int i; /* Generic counter */ -int normbut; /* Number of buttons reported by joystick */ -int corr; /* Correction for button names */ -Sint16 value, change; /* Values used to update axis values */ -struct _transaxes *transaxes; /* Shortcut for Correction structure */ -Uint32 pos[MAX_AXES]; /* Vector to inform the Axis status */ -ULONG ulDataLen; /* Size of data */ -GAME_STATUS_STRUCT stGameStatus; /* Joystick Status Structure */ - -ulDataLen = sizeof(stGameStatus); -rc = DosDevIOCtl(hJoyPort, IOCTL_CAT_USER, GAME_GET_STATUS, - NULL, 0, NULL, &stGameStatus, ulDataLen, &ulDataLen); -if (rc != 0) - { - SDL_SetError("Could not read joystick status."); - return; /* Could not read data */ - } + APIRET rc; /* Generic OS/2 return code */ + int index; /* index shortcurt to joystick index */ + int i; /* Generic counter */ + int normbut; /* Number of buttons reported by joystick */ + int corr; /* Correction for button names */ + Sint16 value, change; /* Values used to update axis values */ + struct _transaxes *transaxes; /* Shortcut for Correction structure */ + Uint32 pos[MAX_AXES]; /* Vector to inform the Axis status */ + ULONG ulDataLen; /* Size of data */ + GAME_STATUS_STRUCT stGameStatus; /* Joystick Status Structure */ + + ulDataLen = sizeof(stGameStatus); + rc = DosDevIOCtl(hJoyPort, IOCTL_CAT_USER, GAME_GET_STATUS, + NULL, 0, NULL, &stGameStatus, ulDataLen, &ulDataLen); + if (rc != 0) { + SDL_SetError("Could not read joystick status."); + return; /* Could not read data */ + } /* Shortcut pointer */ -index = joystick->index; + index = joystick->index; /* joystick motion events */ -if (SYS_JoyData[index].id == 0) - { - pos[0] = stGameStatus.curdata.A.x; - pos[1] = stGameStatus.curdata.A.y; - if (SYS_JoyData[index].axes >= 3) pos[2] = stGameStatus.curdata.B.x; - else pos[2]=0; - if (SYS_JoyData[index].axes >= 4) pos[3] = stGameStatus.curdata.B.y; - else pos[3]=0; - pos[4]=0; /* OS/2 basic drivers do not support more than 4 axes joysticks */ - pos[5]=0; - } -else if (SYS_JoyData[index].id == 1) - { - pos[0] = stGameStatus.curdata.B.x; - pos[1] = stGameStatus.curdata.B.y; - pos[2]=0; - pos[3]=0; - pos[4]=0; - pos[5]=0; - } + if (SYS_JoyData[index].id == 0) { + pos[0] = stGameStatus.curdata.A.x; + pos[1] = stGameStatus.curdata.A.y; + if (SYS_JoyData[index].axes >= 3) + pos[2] = stGameStatus.curdata.B.x; + else + pos[2] = 0; + if (SYS_JoyData[index].axes >= 4) + pos[3] = stGameStatus.curdata.B.y; + else + pos[3] = 0; + pos[4] = 0; /* OS/2 basic drivers do not support more than 4 axes joysticks */ + pos[5] = 0; + } else if (SYS_JoyData[index].id == 1) { + pos[0] = stGameStatus.curdata.B.x; + pos[1] = stGameStatus.curdata.B.y; + pos[2] = 0; + pos[3] = 0; + pos[4] = 0; + pos[5] = 0; + } /* Corrects the movements using the callibration */ -transaxes = joystick->hwdata->transaxes; -for (i = 0; i < joystick->naxes; i++) - { - value = pos[i] + transaxes[i].offset; - if (value<0) - { - value*=transaxes[i].scale1; - if (value>0) value = AXIS_MIN; - } - else - { - value*=transaxes[i].scale2; - if (value<0) value = AXIS_MAX; - } - change = (value - joystick->axes[i]); - if ( (change < -JOY_AXIS_THRESHOLD) || (change > JOY_AXIS_THRESHOLD) ) - { - SDL_PrivateJoystickAxis(joystick, (Uint8)i, (Sint16)value); - } - } + transaxes = joystick->hwdata->transaxes; + for (i = 0; i < joystick->naxes; i++) { + value = pos[i] + transaxes[i].offset; + if (value < 0) { + value *= transaxes[i].scale1; + if (value > 0) + value = AXIS_MIN; + } else { + value *= transaxes[i].scale2; + if (value < 0) + value = AXIS_MAX; + } + change = (value - joystick->axes[i]); + if ((change < -JOY_AXIS_THRESHOLD) || (change > JOY_AXIS_THRESHOLD)) { + SDL_PrivateJoystickAxis(joystick, (Uint8) i, (Sint16) value); + } + } /* joystick button A to D events */ -if (SYS_JoyData[index].id == 1) corr = 2; -else corr = 0; -normbut=4; /* Number of normal buttons */ -if (joystick->nbuttonsnbuttons; -for ( i = corr; (i-corr) < normbut; ++i ) - { - /* - Button A: 1110 0000 - Button B: 1101 0000 - Button C: 1011 0000 - Button D: 0111 0000 - */ - if ( (~stGameStatus.curdata.butMask)>>4 & JOY_BUTTON_FLAG(i) ) - { - if ( ! joystick->buttons[i-corr] ) - { - SDL_PrivateJoystickButton(joystick, (Uint8)(i-corr), SDL_PRESSED); - } - } - else - { - if ( joystick->buttons[i-corr] ) - { - SDL_PrivateJoystickButton(joystick, (Uint8)(i-corr), SDL_RELEASED); - } - } - } + if (SYS_JoyData[index].id == 1) + corr = 2; + else + corr = 0; + normbut = 4; /* Number of normal buttons */ + if (joystick->nbuttons < normbut) + normbut = joystick->nbuttons; + for (i = corr; (i - corr) < normbut; ++i) { + /* + Button A: 1110 0000 + Button B: 1101 0000 + Button C: 1011 0000 + Button D: 0111 0000 + */ + if ((~stGameStatus.curdata.butMask) >> 4 & JOY_BUTTON_FLAG(i)) { + if (!joystick->buttons[i - corr]) { + SDL_PrivateJoystickButton(joystick, (Uint8) (i - corr), + SDL_PRESSED); + } + } else { + if (joystick->buttons[i - corr]) { + SDL_PrivateJoystickButton(joystick, (Uint8) (i - corr), + SDL_RELEASED); + } + } + } /* Joystick button E to H buttons */ - /* - Button E: Axis 2 X Left - Button F: Axis 2 Y Up - Button G: Axis 2 X Right - Button H: Axis 2 Y Down - */ -if (joystick->nbuttons>=5) - { - if (stGameStatus.curdata.B.x < SYS_JoyData[index].buttoncalc[0]) SDL_PrivateJoystickButton(joystick, (Uint8)4, SDL_PRESSED); - else SDL_PrivateJoystickButton(joystick, (Uint8)4, SDL_RELEASED); - } -if (joystick->nbuttons>=6) - { - if (stGameStatus.curdata.B.y < SYS_JoyData[index].buttoncalc[1]) SDL_PrivateJoystickButton(joystick, (Uint8)5, SDL_PRESSED); - else SDL_PrivateJoystickButton(joystick, (Uint8)5, SDL_RELEASED); - } -if (joystick->nbuttons>=7) - { - if (stGameStatus.curdata.B.x > SYS_JoyData[index].buttoncalc[2]) SDL_PrivateJoystickButton(joystick, (Uint8)6, SDL_PRESSED); - else SDL_PrivateJoystickButton(joystick, (Uint8)6, SDL_RELEASED); - } -if (joystick->nbuttons>=8) - { - if (stGameStatus.curdata.B.y > SYS_JoyData[index].buttoncalc[3]) SDL_PrivateJoystickButton(joystick, (Uint8)7, SDL_PRESSED); - else SDL_PrivateJoystickButton(joystick, (Uint8)7, SDL_RELEASED); - } + /* + Button E: Axis 2 X Left + Button F: Axis 2 Y Up + Button G: Axis 2 X Right + Button H: Axis 2 Y Down + */ + if (joystick->nbuttons >= 5) { + if (stGameStatus.curdata.B.x < SYS_JoyData[index].buttoncalc[0]) + SDL_PrivateJoystickButton(joystick, (Uint8) 4, SDL_PRESSED); + else + SDL_PrivateJoystickButton(joystick, (Uint8) 4, SDL_RELEASED); + } + if (joystick->nbuttons >= 6) { + if (stGameStatus.curdata.B.y < SYS_JoyData[index].buttoncalc[1]) + SDL_PrivateJoystickButton(joystick, (Uint8) 5, SDL_PRESSED); + else + SDL_PrivateJoystickButton(joystick, (Uint8) 5, SDL_RELEASED); + } + if (joystick->nbuttons >= 7) { + if (stGameStatus.curdata.B.x > SYS_JoyData[index].buttoncalc[2]) + SDL_PrivateJoystickButton(joystick, (Uint8) 6, SDL_PRESSED); + else + SDL_PrivateJoystickButton(joystick, (Uint8) 6, SDL_RELEASED); + } + if (joystick->nbuttons >= 8) { + if (stGameStatus.curdata.B.y > SYS_JoyData[index].buttoncalc[3]) + SDL_PrivateJoystickButton(joystick, (Uint8) 7, SDL_PRESSED); + else + SDL_PrivateJoystickButton(joystick, (Uint8) 7, SDL_RELEASED); + } /* joystick hat events */ /* Not Supported under OS/2 */ @@ -516,13 +531,13 @@ if (joystick->nbuttons>=8) /******************************************/ /* Function to close a joystick after use */ /******************************************/ -void SDL_SYS_JoystickClose(SDL_Joystick *joystick) +void +SDL_SYS_JoystickClose(SDL_Joystick * joystick) { -if (joystick->hwdata != NULL) - { - /* free system specific hardware data */ - SDL_free(joystick->hwdata); - } + if (joystick->hwdata != NULL) { + /* free system specific hardware data */ + SDL_free(joystick->hwdata); + } } @@ -530,9 +545,10 @@ if (joystick->hwdata != NULL) /********************************************************************/ /* Function to perform any system-specific joystick related cleanup */ /********************************************************************/ -void SDL_SYS_JoystickQuit(void) +void +SDL_SYS_JoystickQuit(void) { -joyPortClose(&hJoyPort); + joyPortClose(&hJoyPort); } @@ -547,42 +563,42 @@ joyPortClose(&hJoyPort); /*****************************************/ /* Open Joystick Port, if not opened yet */ /*****************************************/ -APIRET joyPortOpen(HFILE * hGame) +APIRET +joyPortOpen(HFILE * hGame) { -APIRET rc; /* Generic Return Code */ -ULONG ulAction; /* ? */ -ULONG ulVersion; /* Version of joystick driver */ -ULONG ulDataLen; /* Size of version data */ + APIRET rc; /* Generic Return Code */ + ULONG ulAction; /* ? */ + ULONG ulVersion; /* Version of joystick driver */ + ULONG ulDataLen; /* Size of version data */ /* Verifies if joyport is not already open... */ -if (*hGame != NULL) return 0; + if (*hGame != NULL) + return 0; /* Open GAME$ for read */ -rc = DosOpen((PSZ)GAMEPDDNAME, hGame, &ulAction, 0, FILE_READONLY, - FILE_OPEN, OPEN_ACCESS_READONLY | OPEN_SHARE_DENYNONE, NULL); -if (rc != 0) - { - SDL_SetError("Could not open Joystick Port."); - return -1; - } - + rc = DosOpen((PSZ) GAMEPDDNAME, hGame, &ulAction, 0, FILE_READONLY, + FILE_OPEN, OPEN_ACCESS_READONLY | OPEN_SHARE_DENYNONE, NULL); + if (rc != 0) { + SDL_SetError("Could not open Joystick Port."); + return -1; + } + /* Get Joystick Driver Version... must be 2.0 or higher */ -ulVersion = 0; -ulDataLen = sizeof(ulVersion); -rc = DosDevIOCtl( *hGame, IOCTL_CAT_USER, GAME_GET_VERSION, - NULL, 0, NULL, &ulVersion, ulDataLen, &ulDataLen); -if (rc != 0) - { - joyPortClose(hGame); - SDL_SetError("Could not get Joystick Driver version."); - return -1; - } -if (ulVersion < GAME_VERSION) - { - joyPortClose(hGame); - SDL_SetError("Driver too old. At least IBM driver version 2.0 required."); - return -1; - } -return 0; + ulVersion = 0; + ulDataLen = sizeof(ulVersion); + rc = DosDevIOCtl(*hGame, IOCTL_CAT_USER, GAME_GET_VERSION, + NULL, 0, NULL, &ulVersion, ulDataLen, &ulDataLen); + if (rc != 0) { + joyPortClose(hGame); + SDL_SetError("Could not get Joystick Driver version."); + return -1; + } + if (ulVersion < GAME_VERSION) { + joyPortClose(hGame); + SDL_SetError + ("Driver too old. At least IBM driver version 2.0 required."); + return -1; + } + return 0; } @@ -590,10 +606,12 @@ return 0; /****************************/ /* Close JoyPort, if opened */ /****************************/ -void joyPortClose(HFILE * hGame) +void +joyPortClose(HFILE * hGame) { -if (*hGame != NULL) DosClose(*hGame); -*hGame = NULL; + if (*hGame != NULL) + DosClose(*hGame); + *hGame = NULL; } @@ -601,37 +619,50 @@ if (*hGame != NULL) DosClose(*hGame); /***************************/ /* Get SDL Joystick EnvVar */ /***************************/ -int joyGetEnv(struct _joycfg * joydata) +int +joyGetEnv(struct _joycfg *joydata) { -char *joyenv; /* Pointer to tested character */ -char tempnumber[5]; /* Temporary place to put numeric texts */ + char *joyenv; /* Pointer to tested character */ + char tempnumber[5]; /* Temporary place to put numeric texts */ -joyenv = SDL_getenv("SDL_OS2_JOYSTICK"); -if (joyenv == NULL) return 0; + joyenv = SDL_getenv("SDL_OS2_JOYSTICK"); + if (joyenv == NULL) + return 0; /* Joystick Environment is defined! */ -while (*joyenv==' ' && *joyenv!=0) joyenv++; /* jump spaces... */ + while (*joyenv == ' ' && *joyenv != 0) + joyenv++; /* jump spaces... */ /* If the string name starts with '... get if fully */ -if (*joyenv=='\'') joyenv+=joyGetData(++joyenv,joydata->name,'\'',sizeof(joydata->name)); + if (*joyenv == '\'') + joyenv += + joyGetData(++joyenv, joydata->name, '\'', sizeof(joydata->name)); /* If not, get it until the next space */ -else if (*joyenv=='\"') joyenv+=joyGetData(++joyenv,joydata->name,'\"',sizeof(joydata->name)); -else joyenv+=joyGetData(joyenv,joydata->name,' ',sizeof(joydata->name)); + else if (*joyenv == '\"') + joyenv += + joyGetData(++joyenv, joydata->name, '\"', sizeof(joydata->name)); + else + joyenv += + joyGetData(joyenv, joydata->name, ' ', sizeof(joydata->name)); /* Now get the number of axes */ -while (*joyenv==' ' && *joyenv!=0) joyenv++; /* jump spaces... */ -joyenv+=joyGetData(joyenv,tempnumber,' ',sizeof(tempnumber)); -joydata->axes = atoi(tempnumber); + while (*joyenv == ' ' && *joyenv != 0) + joyenv++; /* jump spaces... */ + joyenv += joyGetData(joyenv, tempnumber, ' ', sizeof(tempnumber)); + joydata->axes = atoi(tempnumber); /* Now get the number of buttons */ -while (*joyenv==' ' && *joyenv!=0) joyenv++; /* jump spaces... */ -joyenv+=joyGetData(joyenv,tempnumber,' ',sizeof(tempnumber)); -joydata->buttons = atoi(tempnumber); + while (*joyenv == ' ' && *joyenv != 0) + joyenv++; /* jump spaces... */ + joyenv += joyGetData(joyenv, tempnumber, ' ', sizeof(tempnumber)); + joydata->buttons = atoi(tempnumber); /* Now get the number of hats */ -while (*joyenv==' ' && *joyenv!=0) joyenv++; /* jump spaces... */ -joyenv+=joyGetData(joyenv,tempnumber,' ',sizeof(tempnumber)); -joydata->hats = atoi(tempnumber); + while (*joyenv == ' ' && *joyenv != 0) + joyenv++; /* jump spaces... */ + joyenv += joyGetData(joyenv, tempnumber, ' ', sizeof(tempnumber)); + joydata->hats = atoi(tempnumber); /* Now get the number of balls */ -while (*joyenv==' ' && *joyenv!=0) joyenv++; /* jump spaces... */ -joyenv+=joyGetData(joyenv,tempnumber,' ',sizeof(tempnumber)); -joydata->balls = atoi(tempnumber); -return 1; + while (*joyenv == ' ' && *joyenv != 0) + joyenv++; /* jump spaces... */ + joyenv += joyGetData(joyenv, tempnumber, ' ', sizeof(tempnumber)); + joydata->balls = atoi(tempnumber); + return 1; } @@ -640,29 +671,28 @@ return 1; /* Get a text from in the string starting in joyenv until it finds */ /* the stopchar or maxchars is reached. The result is placed in name. */ /************************************************************************/ -int joyGetData(char *joyenv, char *name, char stopchar, size_t maxchars) +int +joyGetData(char *joyenv, char *name, char stopchar, size_t maxchars) { -char *nameptr; /* Pointer to the selected character */ -int chcnt=0; /* Count how many characters where copied */ - -nameptr=name; -while (*joyenv!=stopchar && *joyenv!=0) - { - if (nameptr<(name+(maxchars-1))) - { - *nameptr = *joyenv; /* Only copy if smaller than maximum */ - nameptr++; - } - chcnt++; - joyenv++; - } -if (*joyenv==stopchar) - { - joyenv++; /* Jump stopchar */ - chcnt++; - } -*nameptr = 0; /* Mark last byte */ -return chcnt; + char *nameptr; /* Pointer to the selected character */ + int chcnt = 0; /* Count how many characters where copied */ + + nameptr = name; + while (*joyenv != stopchar && *joyenv != 0) { + if (nameptr < (name + (maxchars - 1))) { + *nameptr = *joyenv; /* Only copy if smaller than maximum */ + nameptr++; + } + chcnt++; + joyenv++; + } + if (*joyenv == stopchar) { + joyenv++; /* Jump stopchar */ + chcnt++; + } + *nameptr = 0; /* Mark last byte */ + return chcnt; } #endif /* SDL_JOYSTICK_OS2 */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/joystick/os2/joyos2.h b/src/joystick/os2/joyos2.h index 29800106e..0ceace1bc 100644 --- a/src/joystick/os2/joyos2.h +++ b/src/joystick/os2/joyos2.h @@ -13,27 +13,28 @@ #define JOYOS2_H /****** GAMEPORT.SYS joystick definitions, start *****************************/ -#define GAME_VERSION 0x20 /* 2.0 First IBM version */ +#define GAME_VERSION 0x20 /* 2.0 First IBM version */ #define GAMEPDDNAME "GAME$ " #define IOCTL_CAT_USER 0x80 -#define GAME_PORT_GET 0x20 /* read GAMEPORT.SYS values */ -#define GAME_PORT_RESET 0x60 /* reset joystick mask with given value */ - -#pragma pack(1) /* pack structure size is 1 byte */ -typedef struct { /* GAMEPORT.SYS structure */ - USHORT usJs_AxCnt; /* Joystick_A X position */ - USHORT usJs_AyCnt; /* Joystick_A Y position */ - USHORT usJs_BxCnt; /* Joystick_B X position */ - USHORT usJs_ByCnt; /* Joystick_B Y position */ - USHORT usJs_ButtonA1Cnt; /* button A1 press count */ - USHORT usJs_ButtonA2Cnt; /* button A2 press count */ - USHORT usJs_ButtonB1Cnt; /* button B1 press count */ - USHORT usJs_ButtonB2Cnt; /* button B2 press count */ - UCHAR ucJs_JoyStickMask; /* mask of connected joystick pots */ - UCHAR ucJs_ButtonStatus; /* bits of switches down */ - ULONG ulJs_Ticks; /* joystick clock ticks */ +#define GAME_PORT_GET 0x20 /* read GAMEPORT.SYS values */ +#define GAME_PORT_RESET 0x60 /* reset joystick mask with given value */ + +#pragma pack(1) /* pack structure size is 1 byte */ +typedef struct +{ /* GAMEPORT.SYS structure */ + USHORT usJs_AxCnt; /* Joystick_A X position */ + USHORT usJs_AyCnt; /* Joystick_A Y position */ + USHORT usJs_BxCnt; /* Joystick_B X position */ + USHORT usJs_ByCnt; /* Joystick_B Y position */ + USHORT usJs_ButtonA1Cnt; /* button A1 press count */ + USHORT usJs_ButtonA2Cnt; /* button A2 press count */ + USHORT usJs_ButtonB1Cnt; /* button B1 press count */ + USHORT usJs_ButtonB2Cnt; /* button B2 press count */ + UCHAR ucJs_JoyStickMask; /* mask of connected joystick pots */ + UCHAR ucJs_ButtonStatus; /* bits of switches down */ + ULONG ulJs_Ticks; /* joystick clock ticks */ } GAME_PORT_STRUCT; -#pragma pack() /*reset to normal pack size */ +#pragma pack() /*reset to normal pack size */ /****** GAMEPORT.SYS joystick definitions, end *******************************/ @@ -70,31 +71,31 @@ typedef struct { /* GAMEPORT.SYS structure */ /****************************************************************************/ // 1-D position struct used for each axis -typedef SHORT GAME_POS; /* some data formats require signed values */ +typedef SHORT GAME_POS; /* some data formats require signed values */ // simple 2-D position for each joystick typedef struct { - GAME_POS x; - GAME_POS y; + GAME_POS x; + GAME_POS y; } GAME_2DPOS_STRUCT; // struct defining the instantaneous state of both sticks and all buttons typedef struct { - GAME_2DPOS_STRUCT A; - GAME_2DPOS_STRUCT B; - USHORT butMask; + GAME_2DPOS_STRUCT A; + GAME_2DPOS_STRUCT B; + USHORT butMask; } GAME_DATA_STRUCT; // struct to be used for calibration and digital response on each axis typedef struct { - GAME_POS lower; - GAME_POS centre; - GAME_POS upper; + GAME_POS lower; + GAME_POS centre; + GAME_POS upper; } GAME_3POS_STRUCT; /****************************************************************************/ @@ -104,11 +105,11 @@ GAME_3POS_STRUCT; // current data for all sticks as well as button counts since last read typedef struct { - GAME_DATA_STRUCT curdata; - USHORT b1cnt; - USHORT b2cnt; - USHORT b3cnt; - USHORT b4cnt; + GAME_DATA_STRUCT curdata; + USHORT b1cnt; + USHORT b2cnt; + USHORT b3cnt; + USHORT b4cnt; } GAME_STATUS_STRUCT; /****************************************************************************/ @@ -135,14 +136,14 @@ GAME_STATUS_STRUCT; // parameters defining the operation of the driver typedef struct { - USHORT useA; /* new bitmasks: see above */ - USHORT useB; - USHORT mode; /* see consts above */ - USHORT format; /* see consts above */ - USHORT sampDiv; /* samp freq = 32 / n */ - USHORT scale; /* scaling factor */ - USHORT res1; /* must be 0 */ - USHORT res2; /* must be 0 */ + USHORT useA; /* new bitmasks: see above */ + USHORT useB; + USHORT mode; /* see consts above */ + USHORT format; /* see consts above */ + USHORT sampDiv; /* samp freq = 32 / n */ + USHORT scale; /* scaling factor */ + USHORT res1; /* must be 0 */ + USHORT res2; /* must be 0 */ } GAME_PARM_STRUCT; /****************************************************************************/ @@ -154,10 +155,10 @@ GAME_PARM_STRUCT; // - lower limit on value to be considered in upper range typedef struct { - GAME_3POS_STRUCT Ax; - GAME_3POS_STRUCT Ay; - GAME_3POS_STRUCT Bx; - GAME_3POS_STRUCT By; + GAME_3POS_STRUCT Ax; + GAME_3POS_STRUCT Ay; + GAME_3POS_STRUCT Bx; + GAME_3POS_STRUCT By; } GAME_CALIB_STRUCT; /****************************************************************************/ @@ -166,12 +167,13 @@ GAME_CALIB_STRUCT; // struct defining the digital response values for all axes typedef struct { - GAME_3POS_STRUCT Ax; - GAME_3POS_STRUCT Ay; - GAME_3POS_STRUCT Bx; - GAME_3POS_STRUCT By; + GAME_3POS_STRUCT Ax; + GAME_3POS_STRUCT Ay; + GAME_3POS_STRUCT Bx; + GAME_3POS_STRUCT By; } GAME_DIGSET_STRUCT; /****************************************************************************/ #endif +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/joystick/riscos/SDL_sysjoystick.c b/src/joystick/riscos/SDL_sysjoystick.c index ed8ac91cb..d2a8a4b04 100644 --- a/src/joystick/riscos/SDL_sysjoystick.c +++ b/src/joystick/riscos/SDL_sysjoystick.c @@ -41,9 +41,9 @@ #define JOYSTICK_READ 0x43F40 -struct joystick_hwdata +struct joystick_hwdata { - int joystate; + int joystate; }; @@ -52,32 +52,32 @@ struct joystick_hwdata * joysticks. Joystick 0 should be the system default joystick. * It should return number of joysticks, or -1 on an unrecoverable fatal error. */ -int SDL_SYS_JoystickInit(void) +int +SDL_SYS_JoystickInit(void) { - _kernel_swi_regs regs; - - /* Try to read joystick 0 */ - regs.r[0] = 0; - if (_kernel_swi(JOYSTICK_READ, ®s, ®s) == NULL) - { - /* Switch works so assume we've got a joystick */ - return 1; - } - /* Switch fails so it looks like there's no joystick here */ - - return(0); + _kernel_swi_regs regs; + + /* Try to read joystick 0 */ + regs.r[0] = 0; + if (_kernel_swi(JOYSTICK_READ, ®s, ®s) == NULL) { + /* Switch works so assume we've got a joystick */ + return 1; + } + /* Switch fails so it looks like there's no joystick here */ + + return (0); } /* Function to get the device-dependent name of a joystick */ -const char *SDL_SYS_JoystickName(int index) +const char * +SDL_SYS_JoystickName(int index) { - if (index == 0) - { - return "RISC OS Joystick 0"; - } + if (index == 0) { + return "RISC OS Joystick 0"; + } - SDL_SetError("No joystick available with that index"); - return(NULL); + SDL_SetError("No joystick available with that index"); + return (NULL); } /* Function to open a joystick for use. @@ -85,24 +85,25 @@ const char *SDL_SYS_JoystickName(int index) This should fill the nbuttons and naxes fields of the joystick structure. It returns 0, or -1 if there is an error. */ -int SDL_SYS_JoystickOpen(SDL_Joystick *joystick) +int +SDL_SYS_JoystickOpen(SDL_Joystick * joystick) { - _kernel_swi_regs regs; + _kernel_swi_regs regs; - if(!(joystick->hwdata=SDL_malloc(sizeof(struct joystick_hwdata)))) - return -1; + if (!(joystick->hwdata = SDL_malloc(sizeof(struct joystick_hwdata)))) + return -1; - regs.r[0] = joystick->index; + regs.r[0] = joystick->index; - /* Don't know how to get exact count of buttons so assume max of 4 for now */ - joystick->nbuttons=4; + /* Don't know how to get exact count of buttons so assume max of 4 for now */ + joystick->nbuttons = 4; - joystick->nhats=0; - joystick->nballs=0; - joystick->naxes=2; - joystick->hwdata->joystate=0; + joystick->nhats = 0; + joystick->nballs = 0; + joystick->naxes = 2; + joystick->hwdata->joystate = 0; - return 0; + return 0; } @@ -111,66 +112,69 @@ int SDL_SYS_JoystickOpen(SDL_Joystick *joystick) * but instead should call SDL_PrivateJoystick*() to deliver events * and update joystick device state. */ -void SDL_SYS_JoystickUpdate(SDL_Joystick *joystick) +void +SDL_SYS_JoystickUpdate(SDL_Joystick * joystick) { - _kernel_swi_regs regs; - regs.r[0] = joystick->index; - - if (_kernel_swi(JOYSTICK_READ, ®s, ®s) == NULL) - { - int newstate = regs.r[0]; - int oldstate = joystick->hwdata->joystate; - if (newstate != oldstate) - { - if ((newstate & 0xFF) != (oldstate & 0xFF)) - { - int y = regs.r[0] & 0xFF; - /* Convert to signed values */ - if (y >= 128) y -= 256; - SDL_PrivateJoystickAxis(joystick,1,-y * 256); /* Up and down opposite to result in SDL */ - } - if ((newstate & 0xFF00) != (oldstate & 0xFF00)) - { - int x = (regs.r[0] & 0xFF00) >> 8; - if (x >= 128) x -= 256; - SDL_PrivateJoystickAxis(joystick,0,x * 256); - } - - if ((newstate & 0xFF0000) != (oldstate & 0xFF0000)) - { - int buttons = (regs.r[0] & 0xFF0000) >> 16; - int oldbuttons = (oldstate & 0xFF0000) >> 16; - int i; - for (i = 0; i < joystick->nbuttons; i++) - { - if ((buttons & (1<hwdata->joystate = newstate; - } - } - - return; + _kernel_swi_regs regs; + regs.r[0] = joystick->index; + + if (_kernel_swi(JOYSTICK_READ, ®s, ®s) == NULL) { + int newstate = regs.r[0]; + int oldstate = joystick->hwdata->joystate; + if (newstate != oldstate) { + if ((newstate & 0xFF) != (oldstate & 0xFF)) { + int y = regs.r[0] & 0xFF; + /* Convert to signed values */ + if (y >= 128) + y -= 256; + SDL_PrivateJoystickAxis(joystick, 1, -y * 256); /* Up and down opposite to result in SDL */ + } + if ((newstate & 0xFF00) != (oldstate & 0xFF00)) { + int x = (regs.r[0] & 0xFF00) >> 8; + if (x >= 128) + x -= 256; + SDL_PrivateJoystickAxis(joystick, 0, x * 256); + } + + if ((newstate & 0xFF0000) != (oldstate & 0xFF0000)) { + int buttons = (regs.r[0] & 0xFF0000) >> 16; + int oldbuttons = (oldstate & 0xFF0000) >> 16; + int i; + for (i = 0; i < joystick->nbuttons; i++) { + if ((buttons & (1 << i)) != (oldbuttons & (1 << i))) { + if (buttons & (1 << i)) + SDL_PrivateJoystickButton(joystick, i, + SDL_PRESSED); + else + SDL_PrivateJoystickButton(joystick, i, + SDL_RELEASED); + } + } + } + joystick->hwdata->joystate = newstate; + } + } + + return; } /* Function to close a joystick after use */ -void SDL_SYS_JoystickClose(SDL_Joystick *joystick) +void +SDL_SYS_JoystickClose(SDL_Joystick * joystick) { - if(joystick->hwdata) - SDL_free(joystick->hwdata); - return; + if (joystick->hwdata) + SDL_free(joystick->hwdata); + return; } /* Function to perform any system-specific joystick related cleanup */ -void SDL_SYS_JoystickQuit(void) +void +SDL_SYS_JoystickQuit(void) { - SDL_numjoysticks=0; + SDL_numjoysticks = 0; - return; + return; } #endif /* SDL_JOYSTICK_RISCOS */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/joystick/win32/SDL_dxjoystick.c b/src/joystick/win32/SDL_dxjoystick.c new file mode 100644 index 000000000..7b47c1909 --- /dev/null +++ b/src/joystick/win32/SDL_dxjoystick.c @@ -0,0 +1,579 @@ +/* + SDL - Simple DirectMedia Layer + Copyright (C) 1997-2006 Sam Lantinga + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + Sam Lantinga + slouken@libsdl.org +*/ +#include "SDL_config.h" + +#ifdef SDL_JOYSTICK_DINPUT + +/* DirectInput joystick driver; written by Glenn Maynard, based on Andrei de + * A. Formiga's WINMM driver. + * + * Hats and sliders are completely untested; the app I'm writing this for mostly + * doesn't use them and I don't own any joysticks with them. + * + * We don't bother to use event notification here. It doesn't seem to work + * with polled devices, and it's fine to call IDirectInputDevice2_GetDeviceData and + * let it return 0 events. */ + +#include "SDL_error.h" +#include "SDL_events.h" +#include "SDL_joystick.h" +#include "../SDL_sysjoystick.h" +#include "../SDL_joystick_c.h" + +#define WIN32_LEAN_AND_MEAN +#include + +#define DIRECTINPUT_VERSION 0x0500 +#include + +#define INPUT_QSIZE 32 /* Buffer up to 32 input messages */ + +extern HINSTANCE SDL_Instance; +extern int DX5_Load(); +extern void DX5_Unload(); +extern HRESULT(WINAPI * DInputCreate) (HINSTANCE hinst, DWORD dwVersion, + LPDIRECTINPUT * ppDI, + LPUNKNOWN punkOuter); + +static LPDIRECTINPUT dinput = NULL; + +#define MAX_JOYSTICKS 8 +#define MAX_INPUTS 256 /* each joystick can have up to 256 inputs */ +#define AXIS_MIN -32768 /* minimum value for axis coordinate */ +#define AXIS_MAX 32767 /* maximum value for axis coordinate */ +#define JOY_AXIS_THRESHOLD (((AXIS_MAX)-(AXIS_MIN))/100) /* 1% motion */ + +typedef enum Type +{ BUTTON, AXIS, HAT } Type; + +/* array to hold joystick ID values */ +static DIDEVICEINSTANCE SYS_Joystick[MAX_JOYSTICKS]; +static int SYS_NumJoysticks; + +extern HWND SDL_Window; + +typedef struct input_t +{ + /* DirectInput offset for this input type: */ + DWORD ofs; + + /* Button, axis or hat: */ + Type type; + + /* SDL input offset: */ + Uint8 num; +} input_t; + +/* The private structure used to keep track of a joystick */ +struct joystick_hwdata +{ + LPDIRECTINPUTDEVICE2 InputDevice; + int buffered; + + input_t Inputs[MAX_INPUTS]; + int NumInputs; +}; + +/* Convert a DirectInput return code to a text message */ +static void +SetDIerror(char *function, int code) +{ + static char *error; + static char errbuf[1024]; + + errbuf[0] = 0; + switch (code) { + case DIERR_GENERIC: + error = "Undefined error!"; + break; + case DIERR_OLDDIRECTINPUTVERSION: + error = "Your version of DirectInput needs upgrading"; + break; + case DIERR_INVALIDPARAM: + error = "Invalid parameters"; + break; + case DIERR_OUTOFMEMORY: + error = "Out of memory"; + break; + case DIERR_DEVICENOTREG: + error = "Device not registered"; + break; + case DIERR_NOINTERFACE: + error = "Interface not supported"; + break; + case DIERR_NOTINITIALIZED: + error = "Device not initialized"; + break; + default: + sprintf(errbuf, "%s: Unknown DirectInput error: 0x%x", + function, code); + break; + } + if (!errbuf[0]) { + sprintf(errbuf, "%s: %s", function, error); + } + SDL_SetError("%s", errbuf); + return; +} + + +BOOL CALLBACK +EnumJoysticksCallback(const DIDEVICEINSTANCE * pdidInstance, VOID * pContext) +{ + memcpy(&SYS_Joystick[SYS_NumJoysticks], pdidInstance, + sizeof(DIDEVICEINSTANCE)); + SYS_NumJoysticks++; + + if (SYS_NumJoysticks >= MAX_JOYSTICKS) + return DIENUM_STOP; + + return DIENUM_CONTINUE; +} + +static BOOL CALLBACK +DIJoystick_EnumDevObjectsProc(LPCDIDEVICEOBJECTINSTANCE dev, LPVOID pvRef) +{ + SDL_Joystick *joystick = (SDL_Joystick *) pvRef; + HRESULT result; + input_t *in = &joystick->hwdata->Inputs[joystick->hwdata->NumInputs]; + const int SupportedMask = DIDFT_BUTTON | DIDFT_POV | DIDFT_AXIS; + if (!(dev->dwType & SupportedMask)) + return DIENUM_CONTINUE; /* unsupported */ + + in->ofs = dev->dwOfs; + + if (dev->dwType & DIDFT_BUTTON) { + in->type = BUTTON; + in->num = joystick->nbuttons; + joystick->nbuttons++; + } else if (dev->dwType & DIDFT_POV) { + in->type = HAT; + in->num = joystick->nhats; + joystick->nhats++; + } else { /* dev->dwType & DIDFT_AXIS */ + DIPROPRANGE diprg; + DIPROPDWORD dilong; + + in->type = AXIS; + in->num = joystick->naxes; + + diprg.diph.dwSize = sizeof(diprg); + diprg.diph.dwHeaderSize = sizeof(diprg.diph); + diprg.diph.dwObj = dev->dwOfs; + diprg.diph.dwHow = DIPH_BYOFFSET; + diprg.lMin = AXIS_MIN; + diprg.lMax = AXIS_MAX; + + result = + IDirectInputDevice2_SetProperty(joystick->hwdata->InputDevice, + DIPROP_RANGE, &diprg.diph); + if (result != DI_OK) + return DIENUM_CONTINUE; /* don't use this axis */ + + /* Set dead zone to 0. */ + dilong.diph.dwSize = sizeof(dilong); + dilong.diph.dwHeaderSize = sizeof(dilong.diph); + dilong.diph.dwObj = dev->dwOfs; + dilong.diph.dwHow = DIPH_BYOFFSET; + dilong.dwData = 0; + result = + IDirectInputDevice2_SetProperty(joystick->hwdata->InputDevice, + DIPROP_DEADZONE, &dilong.diph); + if (result != DI_OK) + return DIENUM_CONTINUE; /* don't use this axis */ + + joystick->naxes++; + } + + joystick->hwdata->NumInputs++; + + if (joystick->hwdata->NumInputs == MAX_INPUTS) + return DIENUM_STOP; /* too many */ + + return DIENUM_CONTINUE; +} + +/* Function to scan the system for joysticks. + * This function should set SDL_numjoysticks to the number of available + * joysticks. Joystick 0 should be the system default joystick. + * It should return 0, or -1 on an unrecoverable fatal error. + */ +int +SDL_SYS_JoystickInit(void) +{ + HRESULT result; + + SYS_NumJoysticks = 0; + + /* Create the DirectInput object */ + if (DX5_Load() < 0) { + SDL_SetError("Couldn't load DirectInput"); + return (-1); + } + result = DInputCreate(SDL_Instance, DIRECTINPUT_VERSION, &dinput, NULL); + if (result != DI_OK) { + DX5_Unload(); + SetDIerror("DirectInputCreate", result); + return (-1); + } + + result = IDirectInput_EnumDevices(dinput, + DIDEVTYPE_JOYSTICK, + EnumJoysticksCallback, + NULL, DIEDFL_ATTACHEDONLY); + + return SYS_NumJoysticks; +} + +/* Function to get the device-dependent name of a joystick */ +const char * +SDL_SYS_JoystickName(int index) +{ + /***-> test for invalid index ? */ + return (SYS_Joystick[index].tszProductName); +} + +/* Function to open a joystick for use. + The joystick to open is specified by the index field of the joystick. + This should fill the nbuttons and naxes fields of the joystick structure. + It returns 0, or -1 if there is an error. + */ +int +SDL_SYS_JoystickOpen(SDL_Joystick * joystick) +{ + HRESULT result; + LPDIRECTINPUTDEVICE device; + + /* allocate memory for system specific hardware data */ + joystick->hwdata = + (struct joystick_hwdata *) malloc(sizeof(*joystick->hwdata)); + if (joystick->hwdata == NULL) { + SDL_OutOfMemory(); + return (-1); + } + memset(joystick->hwdata, 0, sizeof(*joystick->hwdata)); + joystick->hwdata->buffered = 1; + + result = + IDirectInput_CreateDevice(dinput, + &SYS_Joystick[joystick->index]. + guidInstance, &device, NULL); + if (result != DI_OK) { + SetDIerror("DirectInput::CreateDevice", result); + return (-1); + } + + result = IDirectInputDevice_QueryInterface(device, + &IID_IDirectInputDevice2, + (LPVOID *) & joystick-> + hwdata->InputDevice); + IDirectInputDevice_Release(device); + if (result != DI_OK) { + SetDIerror("DirectInputDevice::QueryInterface", result); + return (-1); + } + + result = + IDirectInputDevice2_SetCooperativeLevel(joystick->hwdata-> + InputDevice, SDL_Window, + DISCL_NONEXCLUSIVE | + DISCL_BACKGROUND); + if (result != DI_OK) { + SetDIerror("DirectInputDevice::SetCooperativeLevel", result); + return (-1); + } + + result = + IDirectInputDevice2_SetDataFormat(joystick->hwdata->InputDevice, + &c_dfDIJoystick); + if (result != DI_OK) { + SetDIerror("DirectInputDevice::SetDataFormat", result); + return (-1); + } + + IDirectInputDevice2_EnumObjects(joystick->hwdata->InputDevice, + DIJoystick_EnumDevObjectsProc, + joystick, + DIDFT_BUTTON | DIDFT_AXIS | DIDFT_POV); + + { + DIPROPDWORD dipdw; + memset(&dipdw, 0, sizeof(dipdw)); + dipdw.diph.dwSize = sizeof(dipdw); + dipdw.diph.dwHeaderSize = sizeof(dipdw.diph); + dipdw.diph.dwObj = 0; + dipdw.diph.dwHow = DIPH_DEVICE; + dipdw.dwData = INPUT_QSIZE; + result = + IDirectInputDevice2_SetProperty(joystick->hwdata->InputDevice, + DIPROP_BUFFERSIZE, &dipdw.diph); + + if (result == DI_POLLEDDEVICE) { + /* This device doesn't support buffering, so we're forced + * to use less reliable polling. */ + joystick->hwdata->buffered = 0; + } else if (result != DI_OK) { + SetDIerror("DirectInputDevice::SetProperty", result); + return (-1); + } + } + + return (0); +} + +static Uint8 +TranslatePOV(DWORD value) +{ + const int HAT_VALS[] = { + SDL_HAT_UP, + SDL_HAT_UP | SDL_HAT_RIGHT, + SDL_HAT_RIGHT, + SDL_HAT_DOWN | SDL_HAT_RIGHT, + SDL_HAT_DOWN, + SDL_HAT_DOWN | SDL_HAT_LEFT, + SDL_HAT_LEFT, + SDL_HAT_UP | SDL_HAT_LEFT + }; + + if (LOWORD(value) == 0xFFFF) + return SDL_HAT_CENTERED; + + /* Round the value up: */ + value += 4500 / 2; + value %= 36000; + value /= 4500; + + if (value >= 8) + return SDL_HAT_CENTERED; /* shouldn't happen */ + + return HAT_VALS[value]; +} + +/* SDL_PrivateJoystick* doesn't discard duplicate events, so we need to + * do it. */ +static int +SDL_PrivateJoystickAxis_Int(SDL_Joystick * joystick, Uint8 axis, Sint16 value) +{ + if (joystick->axes[axis] != value) + return SDL_PrivateJoystickAxis(joystick, axis, value); + return 0; +} + +static int +SDL_PrivateJoystickHat_Int(SDL_Joystick * joystick, Uint8 hat, Uint8 value) +{ + if (joystick->hats[hat] != value) + return SDL_PrivateJoystickHat(joystick, hat, value); + return 0; +} + +static int +SDL_PrivateJoystickButton_Int(SDL_Joystick * joystick, Uint8 button, + Uint8 state) +{ + if (joystick->buttons[button] != state) + return SDL_PrivateJoystickButton(joystick, button, state); + return 0; +} + +/* Function to update the state of a joystick - called as a device poll. + * This function shouldn't update the joystick structure directly, + * but instead should call SDL_PrivateJoystick*() to deliver events + * and update joystick device state. + */ +void +SDL_SYS_JoystickUpdate_Polled(SDL_Joystick * joystick) +{ + DIJOYSTATE state; + HRESULT result; + int i; + + result = + IDirectInputDevice2_GetDeviceState(joystick->hwdata->InputDevice, + sizeof(state), &state); + if (result == DIERR_INPUTLOST || result == DIERR_NOTACQUIRED) { + IDirectInputDevice2_Acquire(joystick->hwdata->InputDevice); + result = + IDirectInputDevice2_GetDeviceState(joystick->hwdata-> + InputDevice, sizeof(state), + &state); + } + + /* Set each known axis, button and POV. */ + for (i = 0; i < joystick->hwdata->NumInputs; ++i) { + const input_t *in = &joystick->hwdata->Inputs[i]; + + switch (in->type) { + case AXIS: + switch (in->ofs) { + case DIJOFS_X: + SDL_PrivateJoystickAxis_Int(joystick, in->num, + (Sint16) state.lX); + break; + case DIJOFS_Y: + SDL_PrivateJoystickAxis_Int(joystick, in->num, + (Sint16) state.lY); + break; + case DIJOFS_Z: + SDL_PrivateJoystickAxis_Int(joystick, in->num, + (Sint16) state.lZ); + break; + case DIJOFS_RX: + SDL_PrivateJoystickAxis_Int(joystick, in->num, + (Sint16) state.lRx); + break; + case DIJOFS_RY: + SDL_PrivateJoystickAxis_Int(joystick, in->num, + (Sint16) state.lRy); + break; + case DIJOFS_RZ: + SDL_PrivateJoystickAxis_Int(joystick, in->num, + (Sint16) state.lRz); + break; + case DIJOFS_SLIDER(0): + SDL_PrivateJoystickAxis_Int(joystick, in->num, + (Sint16) state.rglSlider[0]); + break; + case DIJOFS_SLIDER(1): + SDL_PrivateJoystickAxis_Int(joystick, in->num, + (Sint16) state.rglSlider[0]); + break; + } + + break; + + case BUTTON: + SDL_PrivateJoystickButton_Int(joystick, in->num, + (Uint8) (state. + rgbButtons[in->ofs - + DIJOFS_BUTTON0] + ? SDL_PRESSED : + SDL_RELEASED)); + break; + case HAT: + { + Uint8 pos = + TranslatePOV(state.rgdwPOV[in->ofs - DIJOFS_POV(0)]); + SDL_PrivateJoystickHat_Int(joystick, in->num, pos); + break; + } + } + } +} + +void +SDL_SYS_JoystickUpdate_Buffered(SDL_Joystick * joystick) +{ + int i; + HRESULT result; + DWORD numevents; + DIDEVICEOBJECTDATA evtbuf[INPUT_QSIZE]; + + numevents = INPUT_QSIZE; + result = + IDirectInputDevice2_GetDeviceData(joystick->hwdata->InputDevice, + sizeof(DIDEVICEOBJECTDATA), + evtbuf, &numevents, 0); + if (result == DIERR_INPUTLOST || result == DIERR_NOTACQUIRED) { + IDirectInputDevice2_Acquire(joystick->hwdata->InputDevice); + result = + IDirectInputDevice2_GetDeviceData(joystick->hwdata-> + InputDevice, + sizeof(DIDEVICEOBJECTDATA), + evtbuf, &numevents, 0); + } + + /* Handle the events */ + if (result != DI_OK) + return; + + for (i = 0; i < (int) numevents; ++i) { + int j; + + for (j = 0; j < joystick->hwdata->NumInputs; ++j) { + const input_t *in = &joystick->hwdata->Inputs[j]; + + if (evtbuf[i].dwOfs != in->ofs) + continue; + + switch (in->type) { + case AXIS: + SDL_PrivateJoystickAxis(joystick, in->num, + (Sint16) evtbuf[i].dwData); + break; + case BUTTON: + SDL_PrivateJoystickButton(joystick, in->num, + (Uint8) (evtbuf[i]. + dwData ? SDL_PRESSED + : SDL_RELEASED)); + break; + case HAT: + { + Uint8 pos = TranslatePOV(evtbuf[i].dwData); + SDL_PrivateJoystickHat(joystick, in->num, pos); + } + } + } + } +} + +void +SDL_SYS_JoystickUpdate(SDL_Joystick * joystick) +{ + HRESULT result; + + result = IDirectInputDevice2_Poll(joystick->hwdata->InputDevice); + if (result == DIERR_INPUTLOST || result == DIERR_NOTACQUIRED) { + IDirectInputDevice2_Acquire(joystick->hwdata->InputDevice); + IDirectInputDevice2_Poll(joystick->hwdata->InputDevice); + } + + if (joystick->hwdata->buffered) + SDL_SYS_JoystickUpdate_Buffered(joystick); + else + SDL_SYS_JoystickUpdate_Polled(joystick); +} + +/* Function to close a joystick after use */ +void +SDL_SYS_JoystickClose(SDL_Joystick * joystick) +{ + IDirectInputDevice2_Unacquire(joystick->hwdata->InputDevice); + IDirectInputDevice2_Release(joystick->hwdata->InputDevice); + + if (joystick->hwdata != NULL) { + /* free system specific hardware data */ + free(joystick->hwdata); + } +} + +/* Function to perform any system-specific joystick related cleanup */ +void +SDL_SYS_JoystickQuit(void) +{ + IDirectInput_Release(dinput); + dinput = NULL; + DX5_Unload(); +} + +#endif /* SDL_JOYSTICK_DINPUT */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/joystick/win32/SDL_mmjoystick.c b/src/joystick/win32/SDL_mmjoystick.c index 2523bbec4..f70214500 100644 --- a/src/joystick/win32/SDL_mmjoystick.c +++ b/src/joystick/win32/SDL_mmjoystick.c @@ -36,8 +36,8 @@ #include "../SDL_joystick_c.h" #define MAX_JOYSTICKS 16 -#define MAX_AXES 6 /* each joystick can have up to 6 axes */ -#define MAX_BUTTONS 32 /* and 32 buttons */ +#define MAX_AXES 6 /* each joystick can have up to 6 axes */ +#define MAX_BUTTONS 32 /* and 32 buttons */ #define AXIS_MIN -32768 /* minimum value for axis coordinate */ #define AXIS_MAX 32767 /* maximum value for axis coordinate */ /* limit axis to 256 possible positions to filter out noise */ @@ -46,98 +46,92 @@ /* array to hold joystick ID values */ -static UINT SYS_JoystickID[MAX_JOYSTICKS]; -static JOYCAPS SYS_Joystick[MAX_JOYSTICKS]; -static char *SYS_JoystickName[MAX_JOYSTICKS]; +static UINT SYS_JoystickID[MAX_JOYSTICKS]; +static JOYCAPS SYS_Joystick[MAX_JOYSTICKS]; +static char *SYS_JoystickName[MAX_JOYSTICKS]; /* The private structure used to keep track of a joystick */ struct joystick_hwdata { - /* joystick ID */ - UINT id; - - /* values used to translate device-specific coordinates into - SDL-standard ranges */ - struct _transaxis { - int offset; - float scale; - } transaxis[6]; + /* joystick ID */ + UINT id; + + /* values used to translate device-specific coordinates into + SDL-standard ranges */ + struct _transaxis + { + int offset; + float scale; + } transaxis[6]; }; /* Convert a win32 Multimedia API return code to a text message */ static void SetMMerror(char *function, int code); -static char *GetJoystickName(int index, const char *szRegKey) +static char * +GetJoystickName(int index, const char *szRegKey) { - /* added 7/24/2004 by Eckhard Stolberg */ - /* - see if there is a joystick for the current - index (1-16) listed in the registry - */ - char *name = NULL; - HKEY hKey; - DWORD regsize; - LONG regresult; - unsigned char regkey[256]; - unsigned char regvalue[256]; - unsigned char regname[256]; - - SDL_snprintf((char *) regkey, SDL_arraysize(regkey), "%s\\%s\\%s", - REGSTR_PATH_JOYCONFIG, - szRegKey, - REGSTR_KEY_JOYCURR); - regresult = RegOpenKeyExA(HKEY_LOCAL_MACHINE, - (LPTSTR) ®key, 0, KEY_READ, &hKey); - if (regresult == ERROR_SUCCESS) - { - /* - find the registry key name for the - joystick's properties - */ - regsize = sizeof(regname); - SDL_snprintf((char *) regvalue, SDL_arraysize(regvalue), - "Joystick%d%s", index+1, - REGSTR_VAL_JOYOEMNAME); - regresult = RegQueryValueExA(hKey, - (char *) regvalue, 0, 0, (LPBYTE) ®name, - (LPDWORD) ®size); - RegCloseKey(hKey); - if (regresult == ERROR_SUCCESS) - { - /* open that registry key */ - SDL_snprintf((char *) regkey, SDL_arraysize(regkey), "%s\\%s", - REGSTR_PATH_JOYOEM, regname); - regresult = RegOpenKeyExA(HKEY_LOCAL_MACHINE, - (char *) regkey, 0, KEY_READ, &hKey); - if (regresult == ERROR_SUCCESS) - { - /* find the size for the OEM name text */ - regsize = sizeof(regvalue); - regresult = - RegQueryValueExA(hKey, - REGSTR_VAL_JOYOEMNAME, - 0, 0, NULL, - (LPDWORD) ®size); - if (regresult == ERROR_SUCCESS) - { - /* - allocate enough memory - for the OEM name text ... - */ - name = (char *) SDL_malloc(regsize); - /* ... and read it from the registry */ - regresult = - RegQueryValueExA(hKey, - REGSTR_VAL_JOYOEMNAME, 0, 0, - (LPBYTE) name, - (LPDWORD) ®size); - RegCloseKey(hKey); - } - } - } - } - return(name); + /* added 7/24/2004 by Eckhard Stolberg */ + /* + see if there is a joystick for the current + index (1-16) listed in the registry + */ + char *name = NULL; + HKEY hKey; + DWORD regsize; + LONG regresult; + unsigned char regkey[256]; + unsigned char regvalue[256]; + unsigned char regname[256]; + + SDL_snprintf((char *) regkey, SDL_arraysize(regkey), "%s\\%s\\%s", + REGSTR_PATH_JOYCONFIG, szRegKey, REGSTR_KEY_JOYCURR); + regresult = RegOpenKeyExA(HKEY_LOCAL_MACHINE, + (LPTSTR) & regkey, 0, KEY_READ, &hKey); + if (regresult == ERROR_SUCCESS) { + /* + find the registry key name for the + joystick's properties + */ + regsize = sizeof(regname); + SDL_snprintf((char *) regvalue, SDL_arraysize(regvalue), + "Joystick%d%s", index + 1, REGSTR_VAL_JOYOEMNAME); + regresult = RegQueryValueExA(hKey, + (char *) regvalue, 0, 0, + (LPBYTE) & regname, (LPDWORD) & regsize); + RegCloseKey(hKey); + if (regresult == ERROR_SUCCESS) { + /* open that registry key */ + SDL_snprintf((char *) regkey, SDL_arraysize(regkey), + "%s\\%s", REGSTR_PATH_JOYOEM, regname); + regresult = + RegOpenKeyExA(HKEY_LOCAL_MACHINE, (char *) regkey, 0, + KEY_READ, &hKey); + if (regresult == ERROR_SUCCESS) { + /* find the size for the OEM name text */ + regsize = sizeof(regvalue); + regresult = + RegQueryValueExA(hKey, + REGSTR_VAL_JOYOEMNAME, + 0, 0, NULL, (LPDWORD) & regsize); + if (regresult == ERROR_SUCCESS) { + /* + allocate enough memory + for the OEM name text ... + */ + name = (char *) SDL_malloc(regsize); + /* ... and read it from the registry */ + regresult = + RegQueryValueExA(hKey, + REGSTR_VAL_JOYOEMNAME, 0, 0, + (LPBYTE) name, (LPDWORD) & regsize); + RegCloseKey(hKey); + } + } + } + } + return (name); } /* Function to scan the system for joysticks. @@ -145,50 +139,53 @@ static char *GetJoystickName(int index, const char *szRegKey) * joysticks. Joystick 0 should be the system default joystick. * It should return 0, or -1 on an unrecoverable fatal error. */ -int SDL_SYS_JoystickInit(void) +int +SDL_SYS_JoystickInit(void) { - int i; - int maxdevs; - int numdevs; - JOYINFOEX joyinfo; - JOYCAPS joycaps; - MMRESULT result; - - /* Reset the joystick ID & name mapping tables */ - for ( i = 0; i < MAX_JOYSTICKS; ++i ) { - SYS_JoystickID[i] = 0; - SYS_JoystickName[i] = NULL; - } - - /* Loop over all potential joystick devices */ - numdevs = 0; - maxdevs = joyGetNumDevs(); - for ( i = JOYSTICKID1; i < maxdevs && numdevs < MAX_JOYSTICKS; ++i ) { - - joyinfo.dwSize = sizeof(joyinfo); - joyinfo.dwFlags = JOY_RETURNALL; - result = joyGetPosEx(SYS_JoystickID[i], &joyinfo); - if ( result == JOYERR_NOERROR ) { - result = joyGetDevCaps(i, &joycaps, sizeof(joycaps)); - if ( result == JOYERR_NOERROR ) { - SYS_JoystickID[numdevs] = i; - SYS_Joystick[numdevs] = joycaps; - SYS_JoystickName[numdevs] = GetJoystickName(i, joycaps.szRegKey); - numdevs++; - } - } - } - return(numdevs); + int i; + int maxdevs; + int numdevs; + JOYINFOEX joyinfo; + JOYCAPS joycaps; + MMRESULT result; + + /* Reset the joystick ID & name mapping tables */ + for (i = 0; i < MAX_JOYSTICKS; ++i) { + SYS_JoystickID[i] = 0; + SYS_JoystickName[i] = NULL; + } + + /* Loop over all potential joystick devices */ + numdevs = 0; + maxdevs = joyGetNumDevs(); + for (i = JOYSTICKID1; i < maxdevs && numdevs < MAX_JOYSTICKS; ++i) { + + joyinfo.dwSize = sizeof(joyinfo); + joyinfo.dwFlags = JOY_RETURNALL; + result = joyGetPosEx(SYS_JoystickID[i], &joyinfo); + if (result == JOYERR_NOERROR) { + result = joyGetDevCaps(i, &joycaps, sizeof(joycaps)); + if (result == JOYERR_NOERROR) { + SYS_JoystickID[numdevs] = i; + SYS_Joystick[numdevs] = joycaps; + SYS_JoystickName[numdevs] = + GetJoystickName(i, joycaps.szRegKey); + numdevs++; + } + } + } + return (numdevs); } /* Function to get the device-dependent name of a joystick */ -const char *SDL_SYS_JoystickName(int index) +const char * +SDL_SYS_JoystickName(int index) { - if ( SYS_JoystickName[index] != NULL ) { - return(SYS_JoystickName[index]); - } else { - return(SYS_Joystick[index].szPname); - } + if (SYS_JoystickName[index] != NULL) { + return (SYS_JoystickName[index]); + } else { + return (SYS_Joystick[index].szPname); + } } /* Function to open a joystick for use. @@ -196,83 +193,84 @@ const char *SDL_SYS_JoystickName(int index) This should fill the nbuttons and naxes fields of the joystick structure. It returns 0, or -1 if there is an error. */ -int SDL_SYS_JoystickOpen(SDL_Joystick *joystick) +int +SDL_SYS_JoystickOpen(SDL_Joystick * joystick) { - int index, i; - int caps_flags[MAX_AXES-2] = - { JOYCAPS_HASZ, JOYCAPS_HASR, JOYCAPS_HASU, JOYCAPS_HASV }; - int axis_min[MAX_AXES], axis_max[MAX_AXES]; - - - /* shortcut */ - index = joystick->index; - axis_min[0] = SYS_Joystick[index].wXmin; - axis_max[0] = SYS_Joystick[index].wXmax; - axis_min[1] = SYS_Joystick[index].wYmin; - axis_max[1] = SYS_Joystick[index].wYmax; - axis_min[2] = SYS_Joystick[index].wZmin; - axis_max[2] = SYS_Joystick[index].wZmax; - axis_min[3] = SYS_Joystick[index].wRmin; - axis_max[3] = SYS_Joystick[index].wRmax; - axis_min[4] = SYS_Joystick[index].wUmin; - axis_max[4] = SYS_Joystick[index].wUmax; - axis_min[5] = SYS_Joystick[index].wVmin; - axis_max[5] = SYS_Joystick[index].wVmax; - - /* allocate memory for system specific hardware data */ - joystick->hwdata = (struct joystick_hwdata *) SDL_malloc(sizeof(*joystick->hwdata)); - if (joystick->hwdata == NULL) - { - SDL_OutOfMemory(); - return(-1); - } - SDL_memset(joystick->hwdata, 0, sizeof(*joystick->hwdata)); - - /* set hardware data */ - joystick->hwdata->id = SYS_JoystickID[index]; - for ( i = 0; i < MAX_AXES; ++i ) { - if ( (i<2) || (SYS_Joystick[index].wCaps & caps_flags[i-2]) ) { - joystick->hwdata->transaxis[i].offset = - AXIS_MIN - axis_min[i]; - joystick->hwdata->transaxis[i].scale = - (float)(AXIS_MAX - AXIS_MIN) / (axis_max[i] - axis_min[i]); - } else { - joystick->hwdata->transaxis[i].offset = 0; - joystick->hwdata->transaxis[i].scale = 1.0; /* Just in case */ - } - } - - /* fill nbuttons, naxes, and nhats fields */ - joystick->nbuttons = SYS_Joystick[index].wNumButtons; - joystick->naxes = SYS_Joystick[index].wNumAxes; - if ( SYS_Joystick[index].wCaps & JOYCAPS_HASPOV ) { - joystick->nhats = 1; - } else { - joystick->nhats = 0; - } - return(0); + int index, i; + int caps_flags[MAX_AXES - 2] = + { JOYCAPS_HASZ, JOYCAPS_HASR, JOYCAPS_HASU, JOYCAPS_HASV }; + int axis_min[MAX_AXES], axis_max[MAX_AXES]; + + + /* shortcut */ + index = joystick->index; + axis_min[0] = SYS_Joystick[index].wXmin; + axis_max[0] = SYS_Joystick[index].wXmax; + axis_min[1] = SYS_Joystick[index].wYmin; + axis_max[1] = SYS_Joystick[index].wYmax; + axis_min[2] = SYS_Joystick[index].wZmin; + axis_max[2] = SYS_Joystick[index].wZmax; + axis_min[3] = SYS_Joystick[index].wRmin; + axis_max[3] = SYS_Joystick[index].wRmax; + axis_min[4] = SYS_Joystick[index].wUmin; + axis_max[4] = SYS_Joystick[index].wUmax; + axis_min[5] = SYS_Joystick[index].wVmin; + axis_max[5] = SYS_Joystick[index].wVmax; + + /* allocate memory for system specific hardware data */ + joystick->hwdata = + (struct joystick_hwdata *) SDL_malloc(sizeof(*joystick->hwdata)); + if (joystick->hwdata == NULL) { + SDL_OutOfMemory(); + return (-1); + } + SDL_memset(joystick->hwdata, 0, sizeof(*joystick->hwdata)); + + /* set hardware data */ + joystick->hwdata->id = SYS_JoystickID[index]; + for (i = 0; i < MAX_AXES; ++i) { + if ((i < 2) || (SYS_Joystick[index].wCaps & caps_flags[i - 2])) { + joystick->hwdata->transaxis[i].offset = AXIS_MIN - axis_min[i]; + joystick->hwdata->transaxis[i].scale = + (float) (AXIS_MAX - AXIS_MIN) / (axis_max[i] - axis_min[i]); + } else { + joystick->hwdata->transaxis[i].offset = 0; + joystick->hwdata->transaxis[i].scale = 1.0; /* Just in case */ + } + } + + /* fill nbuttons, naxes, and nhats fields */ + joystick->nbuttons = SYS_Joystick[index].wNumButtons; + joystick->naxes = SYS_Joystick[index].wNumAxes; + if (SYS_Joystick[index].wCaps & JOYCAPS_HASPOV) { + joystick->nhats = 1; + } else { + joystick->nhats = 0; + } + return (0); } -static Uint8 TranslatePOV(DWORD value) +static Uint8 +TranslatePOV(DWORD value) { - Uint8 pos; - - pos = SDL_HAT_CENTERED; - if ( value != JOY_POVCENTERED ) { - if ( (value > JOY_POVLEFT) || (value < JOY_POVRIGHT) ) { - pos |= SDL_HAT_UP; - } - if ( (value > JOY_POVFORWARD) && (value < JOY_POVBACKWARD) ) { - pos |= SDL_HAT_RIGHT; - } - if ( (value > JOY_POVRIGHT) && (value < JOY_POVLEFT) ) { - pos |= SDL_HAT_DOWN; - } - if ( value > JOY_POVBACKWARD ) { - pos |= SDL_HAT_LEFT; - } - } - return(pos); + Uint8 pos; + + pos = SDL_HAT_CENTERED; + if (value != JOY_POVCENTERED) { + if ((value > JOY_POVLEFT) || (value < JOY_POVRIGHT)) { + pos |= SDL_HAT_UP; + } + if ((value > JOY_POVFORWARD) && (value < JOY_POVBACKWARD)) { + pos |= SDL_HAT_RIGHT; + } + if ((value > JOY_POVRIGHT) && (value < JOY_POVLEFT)) { + pos |= SDL_HAT_DOWN; + } + if (value > JOY_POVBACKWARD) { + pos |= SDL_HAT_LEFT; + } + } + return (pos); } /* Function to update the state of a joystick - called as a device poll. @@ -280,135 +278,146 @@ static Uint8 TranslatePOV(DWORD value) * but instead should call SDL_PrivateJoystick*() to deliver events * and update joystick device state. */ -void SDL_SYS_JoystickUpdate(SDL_Joystick *joystick) +void +SDL_SYS_JoystickUpdate(SDL_Joystick * joystick) { - MMRESULT result; - int i; - DWORD flags[MAX_AXES] = { JOY_RETURNX, JOY_RETURNY, JOY_RETURNZ, - JOY_RETURNR, JOY_RETURNU, JOY_RETURNV }; - DWORD pos[MAX_AXES]; - struct _transaxis *transaxis; - int value, change; - JOYINFOEX joyinfo; - - joyinfo.dwSize = sizeof(joyinfo); - joyinfo.dwFlags = JOY_RETURNALL|JOY_RETURNPOVCTS; - if ( ! joystick->hats ) { - joyinfo.dwFlags &= ~(JOY_RETURNPOV|JOY_RETURNPOVCTS); - } - result = joyGetPosEx(joystick->hwdata->id, &joyinfo); - if ( result != JOYERR_NOERROR ) { - SetMMerror("joyGetPosEx", result); - return; - } - - /* joystick motion events */ - pos[0] = joyinfo.dwXpos; - pos[1] = joyinfo.dwYpos; - pos[2] = joyinfo.dwZpos; - pos[3] = joyinfo.dwRpos; - pos[4] = joyinfo.dwUpos; - pos[5] = joyinfo.dwVpos; - - transaxis = joystick->hwdata->transaxis; - for (i = 0; i < joystick->naxes; i++) { - if (joyinfo.dwFlags & flags[i]) { - value = (int)(((float)pos[i] + transaxis[i].offset) * transaxis[i].scale); - change = (value - joystick->axes[i]); - if ( (change < -JOY_AXIS_THRESHOLD) || (change > JOY_AXIS_THRESHOLD) ) { - SDL_PrivateJoystickAxis(joystick, (Uint8)i, (Sint16)value); - } - } - } - - /* joystick button events */ - if ( joyinfo.dwFlags & JOY_RETURNBUTTONS ) { - for ( i = 0; i < joystick->nbuttons; ++i ) { - if ( joyinfo.dwButtons & JOY_BUTTON_FLAG(i) ) { - if ( ! joystick->buttons[i] ) { - SDL_PrivateJoystickButton(joystick, (Uint8)i, SDL_PRESSED); - } - } else { - if ( joystick->buttons[i] ) { - SDL_PrivateJoystickButton(joystick, (Uint8)i, SDL_RELEASED); - } - } - } - } - - /* joystick hat events */ - if ( joyinfo.dwFlags & JOY_RETURNPOV ) { - Uint8 pos; - - pos = TranslatePOV(joyinfo.dwPOV); - if ( pos != joystick->hats[0] ) { - SDL_PrivateJoystickHat(joystick, 0, pos); - } - } + MMRESULT result; + int i; + DWORD flags[MAX_AXES] = { JOY_RETURNX, JOY_RETURNY, JOY_RETURNZ, + JOY_RETURNR, JOY_RETURNU, JOY_RETURNV + }; + DWORD pos[MAX_AXES]; + struct _transaxis *transaxis; + int value, change; + JOYINFOEX joyinfo; + + joyinfo.dwSize = sizeof(joyinfo); + joyinfo.dwFlags = JOY_RETURNALL | JOY_RETURNPOVCTS; + if (!joystick->hats) { + joyinfo.dwFlags &= ~(JOY_RETURNPOV | JOY_RETURNPOVCTS); + } + result = joyGetPosEx(joystick->hwdata->id, &joyinfo); + if (result != JOYERR_NOERROR) { + SetMMerror("joyGetPosEx", result); + return; + } + + /* joystick motion events */ + pos[0] = joyinfo.dwXpos; + pos[1] = joyinfo.dwYpos; + pos[2] = joyinfo.dwZpos; + pos[3] = joyinfo.dwRpos; + pos[4] = joyinfo.dwUpos; + pos[5] = joyinfo.dwVpos; + + transaxis = joystick->hwdata->transaxis; + for (i = 0; i < joystick->naxes; i++) { + if (joyinfo.dwFlags & flags[i]) { + value = + (int) (((float) pos[i] + + transaxis[i].offset) * transaxis[i].scale); + change = (value - joystick->axes[i]); + if ((change < -JOY_AXIS_THRESHOLD) + || (change > JOY_AXIS_THRESHOLD)) { + SDL_PrivateJoystickAxis(joystick, (Uint8) i, (Sint16) value); + } + } + } + + /* joystick button events */ + if (joyinfo.dwFlags & JOY_RETURNBUTTONS) { + for (i = 0; i < joystick->nbuttons; ++i) { + if (joyinfo.dwButtons & JOY_BUTTON_FLAG(i)) { + if (!joystick->buttons[i]) { + SDL_PrivateJoystickButton(joystick, (Uint8) i, + SDL_PRESSED); + } + } else { + if (joystick->buttons[i]) { + SDL_PrivateJoystickButton(joystick, (Uint8) i, + SDL_RELEASED); + } + } + } + } + + /* joystick hat events */ + if (joyinfo.dwFlags & JOY_RETURNPOV) { + Uint8 pos; + + pos = TranslatePOV(joyinfo.dwPOV); + if (pos != joystick->hats[0]) { + SDL_PrivateJoystickHat(joystick, 0, pos); + } + } } /* Function to close a joystick after use */ -void SDL_SYS_JoystickClose(SDL_Joystick *joystick) +void +SDL_SYS_JoystickClose(SDL_Joystick * joystick) { - if (joystick->hwdata != NULL) { - /* free system specific hardware data */ - SDL_free(joystick->hwdata); - } + if (joystick->hwdata != NULL) { + /* free system specific hardware data */ + SDL_free(joystick->hwdata); + } } /* Function to perform any system-specific joystick related cleanup */ -void SDL_SYS_JoystickQuit(void) +void +SDL_SYS_JoystickQuit(void) { - int i; - for (i = 0; i < MAX_JOYSTICKS; i++) { - if ( SYS_JoystickName[i] != NULL ) { - SDL_free(SYS_JoystickName[i]); - } - } + int i; + for (i = 0; i < MAX_JOYSTICKS; i++) { + if (SYS_JoystickName[i] != NULL) { + SDL_free(SYS_JoystickName[i]); + } + } } /* implementation functions */ -void SetMMerror(char *function, int code) +void +SetMMerror(char *function, int code) { - static char *error; - static char errbuf[1024]; - - errbuf[0] = 0; - switch (code) - { - case MMSYSERR_NODRIVER: - error = "Joystick driver not present"; - break; - - case MMSYSERR_INVALPARAM: - case JOYERR_PARMS: - error = "Invalid parameter(s)"; - break; - - case MMSYSERR_BADDEVICEID: - error = "Bad device ID"; - break; - - case JOYERR_UNPLUGGED: - error = "Joystick not attached"; - break; - - case JOYERR_NOCANDO: - error = "Can't capture joystick input"; - break; - - default: - SDL_snprintf(errbuf, SDL_arraysize(errbuf), - "%s: Unknown Multimedia system error: 0x%x", - function, code); - break; - } - - if ( ! errbuf[0] ) { - SDL_snprintf(errbuf, SDL_arraysize(errbuf), "%s: %s", function, error); - } - SDL_SetError("%s", errbuf); + static char *error; + static char errbuf[1024]; + + errbuf[0] = 0; + switch (code) { + case MMSYSERR_NODRIVER: + error = "Joystick driver not present"; + break; + + case MMSYSERR_INVALPARAM: + case JOYERR_PARMS: + error = "Invalid parameter(s)"; + break; + + case MMSYSERR_BADDEVICEID: + error = "Bad device ID"; + break; + + case JOYERR_UNPLUGGED: + error = "Joystick not attached"; + break; + + case JOYERR_NOCANDO: + error = "Can't capture joystick input"; + break; + + default: + SDL_snprintf(errbuf, SDL_arraysize(errbuf), + "%s: Unknown Multimedia system error: 0x%x", + function, code); + break; + } + + if (!errbuf[0]) { + SDL_snprintf(errbuf, SDL_arraysize(errbuf), "%s: %s", function, + error); + } + SDL_SetError("%s", errbuf); } #endif /* SDL_JOYSTICK_WINMM */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/loadso/beos/SDL_sysloadso.c b/src/loadso/beos/SDL_sysloadso.c index cf14c0b32..7e4be9376 100644 --- a/src/loadso/beos/SDL_sysloadso.c +++ b/src/loadso/beos/SDL_sysloadso.c @@ -31,46 +31,50 @@ #include "SDL_loadso.h" -void *SDL_LoadObject(const char *sofile) +void * +SDL_LoadObject(const char *sofile) { - void *handle = NULL; - const char *loaderror = "Unknown error"; - image_id library_id = load_add_on(sofile); - if ( library_id == B_ERROR ) { - loaderror = "BeOS error"; - } else { - handle = (void *)(library_id); - } + void *handle = NULL; + const char *loaderror = "Unknown error"; + image_id library_id = load_add_on(sofile); + if (library_id == B_ERROR) { + loaderror = "BeOS error"; + } else { + handle = (void *) (library_id); + } - if ( handle == NULL ) { - SDL_SetError("Failed loading %s: %s", sofile, loaderror); - } - return(handle); + if (handle == NULL) { + SDL_SetError("Failed loading %s: %s", sofile, loaderror); + } + return (handle); } -void *SDL_LoadFunction(void *handle, const char *name) +void * +SDL_LoadFunction(void *handle, const char *name) { - void *symbol = NULL; - const char *loaderror = "Unknown error"; - image_id library_id = (image_id)handle; - if ( get_image_symbol(library_id, - name, B_SYMBOL_TYPE_TEXT, &symbol) != B_NO_ERROR ) { - loaderror = "Symbol not found"; - } + void *symbol = NULL; + const char *loaderror = "Unknown error"; + image_id library_id = (image_id) handle; + if (get_image_symbol(library_id, + name, B_SYMBOL_TYPE_TEXT, &symbol) != B_NO_ERROR) { + loaderror = "Symbol not found"; + } - if ( symbol == NULL ) { - SDL_SetError("Failed loading %s: %s", name, loaderror); - } - return(symbol); + if (symbol == NULL) { + SDL_SetError("Failed loading %s: %s", name, loaderror); + } + return (symbol); } -void SDL_UnloadObject(void *handle) +void +SDL_UnloadObject(void *handle) { - image_id library_id; - if ( handle != NULL ) { - library_id = (image_id)handle; - unload_add_on(library_id); - } + image_id library_id; + if (handle != NULL) { + library_id = (image_id) handle; + unload_add_on(library_id); + } } #endif /* SDL_LOADSO_BEOS */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/loadso/dlopen/SDL_sysloadso.c b/src/loadso/dlopen/SDL_sysloadso.c index ebd595500..bfcf5fe33 100644 --- a/src/loadso/dlopen/SDL_sysloadso.c +++ b/src/loadso/dlopen/SDL_sysloadso.c @@ -31,38 +31,43 @@ #include "SDL_loadso.h" -void *SDL_LoadObject(const char *sofile) +void * +SDL_LoadObject(const char *sofile) { - void *handle = dlopen(sofile, RTLD_NOW); - const char *loaderror = (char *)dlerror(); - if ( handle == NULL ) { - SDL_SetError("Failed loading %s: %s", sofile, loaderror); - } - return(handle); + void *handle = dlopen(sofile, RTLD_NOW); + const char *loaderror = (char *) dlerror(); + if (handle == NULL) { + SDL_SetError("Failed loading %s: %s", sofile, loaderror); + } + return (handle); } -void *SDL_LoadFunction(void *handle, const char *name) +void * +SDL_LoadFunction(void *handle, const char *name) { - void *symbol = dlsym(handle, name); - if ( symbol == NULL ) { - size_t len = 1+SDL_strlen(name)+1; - char *_name = SDL_stack_alloc(char, len); - _name[0] = '_'; - SDL_strlcpy(&_name[1], name, len); - symbol = dlsym(handle, name); - SDL_stack_free(_name); - if ( symbol == NULL ) { - SDL_SetError("Failed loading %s: %s", name, (const char *)dlerror()); - } - } - return(symbol); + void *symbol = dlsym(handle, name); + if (symbol == NULL) { + size_t len = 1 + SDL_strlen(name) + 1; + char *_name = SDL_stack_alloc(char, len); + _name[0] = '_'; + SDL_strlcpy(&_name[1], name, len); + symbol = dlsym(handle, name); + SDL_stack_free(_name); + if (symbol == NULL) { + SDL_SetError("Failed loading %s: %s", name, + (const char *) dlerror()); + } + } + return (symbol); } -void SDL_UnloadObject(void *handle) +void +SDL_UnloadObject(void *handle) { - if ( handle != NULL ) { - dlclose(handle); - } + if (handle != NULL) { + dlclose(handle); + } } #endif /* SDL_LOADSO_DLOPEN */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/loadso/dummy/SDL_sysloadso.c b/src/loadso/dummy/SDL_sysloadso.c index 6cd16b9a4..512da3406 100644 --- a/src/loadso/dummy/SDL_sysloadso.c +++ b/src/loadso/dummy/SDL_sysloadso.c @@ -28,23 +28,27 @@ #include "SDL_loadso.h" -void *SDL_LoadObject(const char *sofile) +void * +SDL_LoadObject(const char *sofile) { - const char *loaderror = "SDL_LoadObject() not implemented"; - SDL_SetError("Failed loading %s: %s", sofile, loaderror); - return(NULL); + const char *loaderror = "SDL_LoadObject() not implemented"; + SDL_SetError("Failed loading %s: %s", sofile, loaderror); + return (NULL); } -void *SDL_LoadFunction(void *handle, const char *name) +void * +SDL_LoadFunction(void *handle, const char *name) { - const char *loaderror = "SDL_LoadFunction() not implemented"; - SDL_SetError("Failed loading %s: %s", name, loaderror); - return(NULL); + const char *loaderror = "SDL_LoadFunction() not implemented"; + SDL_SetError("Failed loading %s: %s", name, loaderror); + return (NULL); } -void SDL_UnloadObject(void *handle) +void +SDL_UnloadObject(void *handle) { /* no-op. */ } #endif /* SDL_LOADSO_DUMMY || SDL_LOADSO_DISABLED */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/loadso/macos/SDL_sysloadso.c b/src/loadso/macos/SDL_sysloadso.c index 9a6df1d32..344fd0d01 100644 --- a/src/loadso/macos/SDL_sysloadso.c +++ b/src/loadso/macos/SDL_sysloadso.c @@ -35,72 +35,76 @@ #include "SDL_loadso.h" -void *SDL_LoadObject(const char *sofile) +void * +SDL_LoadObject(const char *sofile) { - void *handle = NULL; - const char *loaderror = NULL; - CFragConnectionID library_id; - Ptr mainAddr; - Str255 errName; - OSErr error; - char psofile[512]; + void *handle = NULL; + const char *loaderror = NULL; + CFragConnectionID library_id; + Ptr mainAddr; + Str255 errName; + OSErr error; + char psofile[512]; - SDL_strlcpy(psofile, sofile, SDL_arraysize(psofile)); - error = GetSharedLibrary(C2PStr(psofile), kCompiledCFragArch, - kLoadCFrag, &library_id, &mainAddr, errName); - switch (error) { - case noErr: - loaderror = NULL; - break; - case cfragNoLibraryErr: - loaderror = "Library not found"; - break; - case cfragUnresolvedErr: - loaderror = "Unabled to resolve symbols"; - break; - case cfragNoPrivateMemErr: - case cfragNoClientMemErr: - loaderror = "Out of memory"; - break; - default: - loaderror = "Unknown Code Fragment Manager error"; - break; - } - if ( loaderror == NULL ) { - handle = (void *)(library_id); - } else { - SDL_SetError("Failed loading %s: %s", sofile, loaderror); - } - return(handle); + SDL_strlcpy(psofile, sofile, SDL_arraysize(psofile)); + error = GetSharedLibrary(C2PStr(psofile), kCompiledCFragArch, + kLoadCFrag, &library_id, &mainAddr, errName); + switch (error) { + case noErr: + loaderror = NULL; + break; + case cfragNoLibraryErr: + loaderror = "Library not found"; + break; + case cfragUnresolvedErr: + loaderror = "Unabled to resolve symbols"; + break; + case cfragNoPrivateMemErr: + case cfragNoClientMemErr: + loaderror = "Out of memory"; + break; + default: + loaderror = "Unknown Code Fragment Manager error"; + break; + } + if (loaderror == NULL) { + handle = (void *) (library_id); + } else { + SDL_SetError("Failed loading %s: %s", sofile, loaderror); + } + return (handle); } -void *SDL_LoadFunction(void *handle, const char *name) +void * +SDL_LoadFunction(void *handle, const char *name) { - void *symbol = NULL; - const char *loaderror = NULL; - CFragSymbolClass class; - CFragConnectionID library_id = (CFragConnectionID)handle; - char pname[512]; + void *symbol = NULL; + const char *loaderror = NULL; + CFragSymbolClass class; + CFragConnectionID library_id = (CFragConnectionID) handle; + char pname[512]; - SDL_strlcpy(pname, name, SDL_arraysize(pname)); - if ( FindSymbol(library_id, C2PStr(pname), - (char **)&symbol, &class) != noErr ) { - loaderror = "Symbol not found"; - } + SDL_strlcpy(pname, name, SDL_arraysize(pname)); + if (FindSymbol(library_id, C2PStr(pname), + (char **) &symbol, &class) != noErr) { + loaderror = "Symbol not found"; + } - if ( symbol == NULL ) { - SDL_SetError("Failed loading %s: %s", name, loaderror); - } - return(symbol); + if (symbol == NULL) { + SDL_SetError("Failed loading %s: %s", name, loaderror); + } + return (symbol); } -void SDL_UnloadObject(void *handle) +void +SDL_UnloadObject(void *handle) { - CFragConnectionID library_id; - if ( handle != NULL ) { - library_id = (CFragConnectionID)handle; - CloseConnection(&library_id); - } + CFragConnectionID library_id; + if (handle != NULL) { + library_id = (CFragConnectionID) handle; + CloseConnection(&library_id); + } } #endif /* SDL_LOADSO_MACOS */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/loadso/macosx/SDL_dlcompat.c b/src/loadso/macosx/SDL_dlcompat.c index 8628dd105..980c08af3 100644 --- a/src/loadso/macosx/SDL_dlcompat.c +++ b/src/loadso/macosx/SDL_dlcompat.c @@ -85,7 +85,8 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. /*include "dlfcn.h"*/ #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif #if defined (__GNUC__) && __GNUC__ > 3 @@ -99,21 +100,24 @@ extern "C" { /* * Structure filled in by dladdr(). */ -typedef struct SDL_OSX_dl_info { - const char *dli_fname; /* Pathname of shared object */ - void *dli_fbase; /* Base address of shared object */ - const char *dli_sname; /* Name of nearest symbol */ - void *dli_saddr; /* Address of nearest symbol */ -} SDL_OSX_Dl_info; - -static int SDL_OSX_dladdr(const void * dl_restrict, SDL_OSX_Dl_info * dl_restrict); -#endif /* ! _POSIX_SOURCE */ -#endif /* 0 */ - -static int SDL_OSX_dlclose(void * handle); -static const char * SDL_OSX_dlerror(void); -static void * SDL_OSX_dlopen(const char *path, int mode); -static void * SDL_OSX_dlsym(void * dl_restrict handle, const char * dl_restrict symbol); + typedef struct SDL_OSX_dl_info + { + const char *dli_fname; /* Pathname of shared object */ + void *dli_fbase; /* Base address of shared object */ + const char *dli_sname; /* Name of nearest symbol */ + void *dli_saddr; /* Address of nearest symbol */ + } SDL_OSX_Dl_info; + + static int SDL_OSX_dladdr(const void *dl_restrict, + SDL_OSX_Dl_info * dl_restrict); +#endif /* ! _POSIX_SOURCE */ +#endif /* 0 */ + + static int SDL_OSX_dlclose(void *handle); + static const char *SDL_OSX_dlerror(void); + static void *SDL_OSX_dlopen(const char *path, int mode); + static void *SDL_OSX_dlsym(void *dl_restrict handle, + const char *dl_restrict symbol); #define RTLD_LAZY 0x1 #define RTLD_NOW 0x2 @@ -127,9 +131,9 @@ static void * SDL_OSX_dlsym(void * dl_restrict handle, const char * dl_restrict /* * Special handle arguments for SDL_OSX_dlsym(). */ -#define RTLD_NEXT ((void *) -1) /* Search subsequent objects. */ -#define RTLD_DEFAULT ((void *) -2) /* Use default search algorithm. */ -#endif /* ! _POSIX_SOURCE */ +#define RTLD_NEXT ((void *) -1) /* Search subsequent objects. */ +#define RTLD_DEFAULT ((void *) -2) /* Use default search algorithm. */ +#endif /* ! _POSIX_SOURCE */ #ifdef __cplusplus } @@ -162,10 +166,13 @@ static void * SDL_OSX_dlsym(void * dl_restrict handle, const char * dl_restrict #define NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR 0x4 #endif /* These symbols will be looked for in dyld */ -static const struct mach_header *(*dyld_NSAddImage) (const char *, unsigned long) = 0; -static int (*dyld_NSIsSymbolNameDefinedInImage) (const struct mach_header *, const char *) = 0; -static NSSymbol(*dyld_NSLookupSymbolInImage) - (const struct mach_header *, const char *, unsigned long) = 0; +static const struct mach_header *(*dyld_NSAddImage) (const char *, + unsigned long) = 0; +static int (*dyld_NSIsSymbolNameDefinedInImage) (const struct mach_header *, + const char *) = 0; +static NSSymbol(*dyld_NSLookupSymbolInImage) (const struct mach_header *, + const char *, unsigned long) = + 0; /* Define this to make dlcompat reuse data block. This way in theory we save * a little bit of overhead. However we then couldn't correctly catch excess @@ -194,9 +201,9 @@ static pthread_key_t dlerror_key; struct dlthread { - int lockcnt; - unsigned char errset; - char errstr[ERR_STR_LEN]; + int lockcnt; + unsigned char errset; + char errstr[ERR_STR_LEN]; }; /* This is our central data structure. Whenever a module is loaded via @@ -204,18 +211,19 @@ struct dlthread */ struct dlstatus { - struct dlstatus *next; /* pointer to next element in the linked list */ - NSModule module; - const struct mach_header *lib; - int refs; /* reference count */ - int mode; /* mode in which this module was loaded */ - dev_t device; - ino_t inode; - int flags; /* Any internal flags we may need */ + struct dlstatus *next; /* pointer to next element in the linked list */ + NSModule module; + const struct mach_header *lib; + int refs; /* reference count */ + int mode; /* mode in which this module was loaded */ + dev_t device; + ino_t inode; + int flags; /* Any internal flags we may need */ }; /* Head node of the dlstatus list */ -static struct dlstatus mainStatus = { 0, MAGIC_DYLIB_MOD, NULL, -1, RTLD_GLOBAL, 0, 0, 0 }; +static struct dlstatus mainStatus = + { 0, MAGIC_DYLIB_MOD, NULL, -1, RTLD_GLOBAL, 0, 0, 0 }; static struct dlstatus *stqueue = &mainStatus; @@ -237,10 +245,13 @@ static struct dlstatus *lookupStatus(const struct stat *sbuf); static void insertStatus(struct dlstatus *dls, const struct stat *sbuf); static int promoteLocalToGlobal(struct dlstatus *dls); static void *reference(struct dlstatus *dls, int mode); -static void *dlsymIntern(struct dlstatus *dls, const char *symbol, int canSetError); +static void *dlsymIntern(struct dlstatus *dls, const char *symbol, + int canSetError); static struct dlstatus *allocStatus(void); -static struct dlstatus *loadModule(const char *path, const struct stat *sbuf, int mode); -static NSSymbol search_linked_libs(const struct mach_header *mh, const char *symbol); +static struct dlstatus *loadModule(const char *path, const struct stat *sbuf, + int mode); +static NSSymbol search_linked_libs(const struct mach_header *mh, + const char *symbol); static const char *get_lib_name(const struct mach_header *mh); static const struct mach_header *get_mach_header_from_NSModule(NSModule mod); static void dlcompat_init_func(void); @@ -259,96 +270,98 @@ static void *dlsym_prepend_underscore(void *handle, const char *symbol); static void *dlsym_auto_underscore(void *handle, const char *symbol); /* And their _intern counterparts */ -static void *dlsym_prepend_underscore_intern(void *handle, const char *symbol); +static void *dlsym_prepend_underscore_intern(void *handle, + const char *symbol); static void *dlsym_auto_underscore_intern(void *handle, const char *symbol); #endif /* Functions */ -static void debug(const char *fmt, ...) +static void +debug(const char *fmt, ...) { #if DEBUG > 1 - va_list arg; - va_start(arg, fmt); - fprintf(stderr, "DLDEBUG: "); - vfprintf(stderr, fmt, arg); - fprintf(stderr, "\n"); - fflush(stderr); - va_end(arg); + va_list arg; + va_start(arg, fmt); + fprintf(stderr, "DLDEBUG: "); + vfprintf(stderr, fmt, arg); + fprintf(stderr, "\n"); + fflush(stderr); + va_end(arg); #endif } -static void error(const char *str, ...) +static void +error(const char *str, ...) { - va_list arg; - struct dlthread *tss; - char * err_str; - va_start(arg, str); - tss = pthread_getspecific(dlerror_key); - err_str = tss->errstr; - SDL_strlcpy(err_str, "dlcompat: ", ERR_STR_LEN); - vsnprintf(err_str + 10, ERR_STR_LEN - 10, str, arg); - va_end(arg); - debug("ERROR: %s\n", err_str); - tss->errset = 1; + va_list arg; + struct dlthread *tss; + char *err_str; + va_start(arg, str); + tss = pthread_getspecific(dlerror_key); + err_str = tss->errstr; + SDL_strlcpy(err_str, "dlcompat: ", ERR_STR_LEN); + vsnprintf(err_str + 10, ERR_STR_LEN - 10, str, arg); + va_end(arg); + debug("ERROR: %s\n", err_str); + tss->errset = 1; } -static void warning(const char *str) +static void +warning(const char *str) { #if DEBUG > 0 - fprintf(stderr, "WARNING: dlcompat: %s\n", str); + fprintf(stderr, "WARNING: dlcompat: %s\n", str); #endif } -static const char *safegetenv(const char *s) +static const char * +safegetenv(const char *s) { - const char *ss = SDL_getenv(s); - return ss ? ss : ""; + const char *ss = SDL_getenv(s); + return ss ? ss : ""; } /* because this is only used for debugging and error reporting functions, we * don't really care about how elegant it is... it could use the load * commands to find the install name of the library, but... */ -static const char *get_lib_name(const struct mach_header *mh) +static const char * +get_lib_name(const struct mach_header *mh) { - unsigned long count = _dyld_image_count(); - unsigned long i; - const char *val = NULL; - if (mh) - { - for (i = 0; i < count; i++) - { - if (mh == _dyld_get_image_header(i)) - { - val = _dyld_get_image_name(i); - break; - } - } - } - return val; + unsigned long count = _dyld_image_count(); + unsigned long i; + const char *val = NULL; + if (mh) { + for (i = 0; i < count; i++) { + if (mh == _dyld_get_image_header(i)) { + val = _dyld_get_image_name(i); + break; + } + } + } + return val; } /* Returns the mach_header for the module bu going through all the loaded images * and finding the one with the same name as the module. There really ought to be * an api for doing this, would be faster, but there isn't one right now */ -static const struct mach_header *get_mach_header_from_NSModule(NSModule mod) +static const struct mach_header * +get_mach_header_from_NSModule(NSModule mod) { - const char *mod_name = NSNameOfModule(mod); - const struct mach_header *mh = NULL; - unsigned long count = _dyld_image_count(); - unsigned long i; - debug("Module name: %s", mod_name); - for (i = 0; i < count; i++) - { - if (!SDL_strcmp(mod_name, _dyld_get_image_name(i))) - { - mh = _dyld_get_image_header(i); - break; - } - } - return mh; + const char *mod_name = NSNameOfModule(mod); + const struct mach_header *mh = NULL; + unsigned long count = _dyld_image_count(); + unsigned long i; + debug("Module name: %s", mod_name); + for (i = 0; i < count; i++) { + if (!SDL_strcmp(mod_name, _dyld_get_image_name(i))) { + mh = _dyld_get_image_header(i); + break; + } + } + return mh; } @@ -360,225 +373,224 @@ static const struct mach_header *get_mach_header_from_NSModule(NSModule mod) * into one big string, which we then can easily parse. * Splitting this string into the actual path list is done by getSearchPath() */ -static const char *searchList() +static const char * +searchList() { - size_t buf_size; - static char *buf=NULL; - const char *ldlp = safegetenv("LD_LIBRARY_PATH"); - const char *dyldlp = safegetenv("DYLD_LIBRARY_PATH"); - const char *stdpath = SDL_getenv("DYLD_FALLBACK_LIBRARY_PATH"); - if (!stdpath) - stdpath = "/usr/local/lib:/lib:/usr/lib"; - if (!buf) - { - buf_size = SDL_strlen(ldlp) + SDL_strlen(dyldlp) + SDL_strlen(stdpath) + 4; - buf = SDL_malloc(buf_size); - SDL_snprintf(buf, buf_size, "%s%s%s%s%s%c", dyldlp, (dyldlp[0] ? ":" : ""), ldlp, (ldlp[0] ? ":" : ""), - stdpath, '\0'); - } - return buf; + size_t buf_size; + static char *buf = NULL; + const char *ldlp = safegetenv("LD_LIBRARY_PATH"); + const char *dyldlp = safegetenv("DYLD_LIBRARY_PATH"); + const char *stdpath = SDL_getenv("DYLD_FALLBACK_LIBRARY_PATH"); + if (!stdpath) + stdpath = "/usr/local/lib:/lib:/usr/lib"; + if (!buf) { + buf_size = + SDL_strlen(ldlp) + SDL_strlen(dyldlp) + SDL_strlen(stdpath) + 4; + buf = SDL_malloc(buf_size); + SDL_snprintf(buf, buf_size, "%s%s%s%s%s%c", dyldlp, + (dyldlp[0] ? ":" : ""), ldlp, (ldlp[0] ? ":" : ""), + stdpath, '\0'); + } + return buf; } /* Returns the ith search path from the list as computed by searchList() */ -static const char *getSearchPath(int i) +static const char * +getSearchPath(int i) { - static const char *list = 0; - static char **path = (char **)0; - static int end = 0; - static int numsize = MAX_SEARCH_PATHS; - static char **tmp; - /* So we can call SDL_free() in the "destructor" we use i=-1 to return the alloc'd array */ - if (i == -1) - { - return (const char*)path; - } - if (!path) - { - path = (char **)SDL_calloc(MAX_SEARCH_PATHS, sizeof(char **)); - } - if (!list && !end) - list = searchList(); - if (i >= (numsize)) - { - debug("Increasing size for long PATH"); - tmp = (char **)SDL_calloc((MAX_SEARCH_PATHS + numsize), sizeof(char **)); - if (tmp) - { - SDL_memcpy(tmp, path, sizeof(char **) * numsize); - SDL_free(path); - path = tmp; - numsize += MAX_SEARCH_PATHS; - } - else - { - return 0; - } - } - - while (!path[i] && !end) - { - path[i] = strsep((char **)&list, ":"); - - if (path[i][0] == 0) - path[i] = 0; - end = (list == 0); - } - return path[i]; + static const char *list = 0; + static char **path = (char **) 0; + static int end = 0; + static int numsize = MAX_SEARCH_PATHS; + static char **tmp; + /* So we can call SDL_free() in the "destructor" we use i=-1 to return the alloc'd array */ + if (i == -1) { + return (const char *) path; + } + if (!path) { + path = (char **) SDL_calloc(MAX_SEARCH_PATHS, sizeof(char **)); + } + if (!list && !end) + list = searchList(); + if (i >= (numsize)) { + debug("Increasing size for long PATH"); + tmp = + (char **) SDL_calloc((MAX_SEARCH_PATHS + numsize), + sizeof(char **)); + if (tmp) { + SDL_memcpy(tmp, path, sizeof(char **) * numsize); + SDL_free(path); + path = tmp; + numsize += MAX_SEARCH_PATHS; + } else { + return 0; + } + } + + while (!path[i] && !end) { + path[i] = strsep((char **) &list, ":"); + + if (path[i][0] == 0) + path[i] = 0; + end = (list == 0); + } + return path[i]; } -static const char *getFullPath(int i, const char *file) +static const char * +getFullPath(int i, const char *file) { - static char buf[PATH_MAX]; - const char *path = getSearchPath(i); - if (path) - { - SDL_snprintf(buf, PATH_MAX, "%s/%s", path, file); - } - return path ? buf : 0; + static char buf[PATH_MAX]; + const char *path = getSearchPath(i); + if (path) { + SDL_snprintf(buf, PATH_MAX, "%s/%s", path, file); + } + return path ? buf : 0; } /* Given a file name, try to determine the full path for that file. Starts * its search in the current directory, and then tries all paths in the * search list in the order they are specified there. */ -static const struct stat *findFile(const char *file, const char **fullPath) +static const struct stat * +findFile(const char *file, const char **fullPath) { - int i = 0; - static struct stat sbuf; - char *fileName; - debug("finding file %s", file); - *fullPath = file; - if (0 == stat(file, &sbuf)) - return &sbuf; - if (SDL_strchr(file, '/')) - return 0; /* If the path had a / we don't look in env var places */ - fileName = NULL; - if (!fileName) - fileName = (char *)file; - while ((*fullPath = getFullPath(i++, fileName))) - { - if (0 == stat(*fullPath, &sbuf)) - return &sbuf; - } - ; - return 0; + int i = 0; + static struct stat sbuf; + char *fileName; + debug("finding file %s", file); + *fullPath = file; + if (0 == stat(file, &sbuf)) + return &sbuf; + if (SDL_strchr(file, '/')) + return 0; /* If the path had a / we don't look in env var places */ + fileName = NULL; + if (!fileName) + fileName = (char *) file; + while ((*fullPath = getFullPath(i++, fileName))) { + if (0 == stat(*fullPath, &sbuf)) + return &sbuf; + } + ; + return 0; } /* Determine whether a given dlstatus is valid or not */ -static int isValidStatus(struct dlstatus *status) +static int +isValidStatus(struct dlstatus *status) { - /* Walk the list to verify status is contained in it */ - struct dlstatus *dls = stqueue; - while (dls && status != dls) - dls = dls->next; - if (dls == 0) - error("invalid handle"); - else if ((dls->module == 0) || (dls->refs == 0)) - error("handle to closed library"); - else - return TRUE; - return FALSE; + /* Walk the list to verify status is contained in it */ + struct dlstatus *dls = stqueue; + while (dls && status != dls) + dls = dls->next; + if (dls == 0) + error("invalid handle"); + else if ((dls->module == 0) || (dls->refs == 0)) + error("handle to closed library"); + else + return TRUE; + return FALSE; } -static inline int isFlagSet(int mode, int flag) +static inline int +isFlagSet(int mode, int flag) { - return (mode & flag) == flag; + return (mode & flag) == flag; } -static struct dlstatus *lookupStatus(const struct stat *sbuf) +static struct dlstatus * +lookupStatus(const struct stat *sbuf) { - struct dlstatus *dls = stqueue; - debug("looking for status"); - while (dls && ( /* isFlagSet(dls->mode, RTLD_UNSHARED) */ 0 - || sbuf->st_dev != dls->device || sbuf->st_ino != dls->inode)) - dls = dls->next; - return dls; + struct dlstatus *dls = stqueue; + debug("looking for status"); + while (dls && ( /* isFlagSet(dls->mode, RTLD_UNSHARED) */ 0 + || sbuf->st_dev != dls->device + || sbuf->st_ino != dls->inode)) + dls = dls->next; + return dls; } -static void insertStatus(struct dlstatus *dls, const struct stat *sbuf) +static void +insertStatus(struct dlstatus *dls, const struct stat *sbuf) { - debug("inserting status"); - dls->inode = sbuf->st_ino; - dls->device = sbuf->st_dev; - dls->refs = 0; - dls->mode = 0; - if ((dls->flags & DL_IN_LIST) == 0) - { - dls->next = stqueue; - stqueue = dls; - dls->flags |= DL_IN_LIST; - } + debug("inserting status"); + dls->inode = sbuf->st_ino; + dls->device = sbuf->st_dev; + dls->refs = 0; + dls->mode = 0; + if ((dls->flags & DL_IN_LIST) == 0) { + dls->next = stqueue; + stqueue = dls; + dls->flags |= DL_IN_LIST; + } } -static struct dlstatus *allocStatus() +static struct dlstatus * +allocStatus() { - struct dlstatus *dls; + struct dlstatus *dls; #ifdef REUSE_STATUS - dls = stqueue; - while (dls && dls->module) - dls = dls->next; - if (!dls) + dls = stqueue; + while (dls && dls->module) + dls = dls->next; + if (!dls) #endif - dls = SDL_calloc(sizeof(*dls),1); - return dls; + dls = SDL_calloc(sizeof(*dls), 1); + return dls; } -static int promoteLocalToGlobal(struct dlstatus *dls) +static int +promoteLocalToGlobal(struct dlstatus *dls) { - static int (*p) (NSModule module) = 0; - debug("promoting"); - if (!p) - _dyld_func_lookup("__dyld_NSMakePrivateModulePublic", (void **)&p); - return (dls->module == MAGIC_DYLIB_MOD) || (p && p(dls->module)); + static int (*p) (NSModule module) = 0; + debug("promoting"); + if (!p) + _dyld_func_lookup("__dyld_NSMakePrivateModulePublic", (void **) &p); + return (dls->module == MAGIC_DYLIB_MOD) || (p && p(dls->module)); } -static void *reference(struct dlstatus *dls, int mode) +static void * +reference(struct dlstatus *dls, int mode) { - if (dls) - { - if (dls->module == MAGIC_DYLIB_MOD && isFlagSet(mode, RTLD_LOCAL)) - { - warning("trying to open a .dylib with RTLD_LOCAL"); - error("unable to open a .dylib with RTLD_LOCAL"); - return NULL; - } - if (isFlagSet(mode, RTLD_GLOBAL) && - !isFlagSet(dls->mode, RTLD_GLOBAL) && !promoteLocalToGlobal(dls)) - { - error("unable to promote local module to global"); - return NULL; - } - dls->mode |= mode; - dls->refs++; - } - else - debug("reference called with NULL argument"); - - return dls; + if (dls) { + if (dls->module == MAGIC_DYLIB_MOD && isFlagSet(mode, RTLD_LOCAL)) { + warning("trying to open a .dylib with RTLD_LOCAL"); + error("unable to open a .dylib with RTLD_LOCAL"); + return NULL; + } + if (isFlagSet(mode, RTLD_GLOBAL) && !isFlagSet(dls->mode, RTLD_GLOBAL) + && !promoteLocalToGlobal(dls)) { + error("unable to promote local module to global"); + return NULL; + } + dls->mode |= mode; + dls->refs++; + } else + debug("reference called with NULL argument"); + + return dls; } -static const struct mach_header *my_find_image(const char *name) +static const struct mach_header * +my_find_image(const char *name) { - const struct mach_header *mh = 0; - const char *id = NULL; - int i = _dyld_image_count(); - int j; - mh = (struct mach_header *) - dyld_NSAddImage(name, NSADDIMAGE_OPTION_RETURN_ONLY_IF_LOADED | - NSADDIMAGE_OPTION_RETURN_ON_ERROR); - if (!mh) - { - for (j = 0; j < i; j++) - { - id = _dyld_get_image_name(j); - if (!SDL_strcmp(id, name)) - { - mh = _dyld_get_image_header(j); - break; - } - } - } - return mh; + const struct mach_header *mh = 0; + const char *id = NULL; + int i = _dyld_image_count(); + int j; + mh = (struct mach_header *) + dyld_NSAddImage(name, NSADDIMAGE_OPTION_RETURN_ONLY_IF_LOADED | + NSADDIMAGE_OPTION_RETURN_ON_ERROR); + if (!mh) { + for (j = 0; j < i; j++) { + id = _dyld_get_image_name(j); + if (!SDL_strcmp(id, name)) { + mh = _dyld_get_image_header(j); + break; + } + } + } + return mh; } /* @@ -587,468 +599,440 @@ static const struct mach_header *my_find_image(const char *name) * bother adding the extra dependencies, if the symbols are neither in the loaded image nor * any of it's direct dependencies, then it probably isn't there. */ -static NSSymbol search_linked_libs(const struct mach_header * mh, const char *symbol) +static NSSymbol +search_linked_libs(const struct mach_header *mh, const char *symbol) { - unsigned int n; - struct load_command *lc = 0; - struct mach_header *wh; - NSSymbol nssym = 0; - if (dyld_NSAddImage && dyld_NSIsSymbolNameDefinedInImage && dyld_NSLookupSymbolInImage) - { - lc = (struct load_command *)((char *)mh + sizeof(struct mach_header)); - for (n = 0; n < mh->ncmds; n++, lc = (struct load_command *)((char *)lc + lc->cmdsize)) - { - if ((LC_LOAD_DYLIB == lc->cmd) || (LC_LOAD_WEAK_DYLIB == lc->cmd)) - { - if ((wh = (struct mach_header *) - my_find_image((char *)(((struct dylib_command *)lc)->dylib.name.offset + - (char *)lc)))) - { - if (dyld_NSIsSymbolNameDefinedInImage(wh, symbol)) - { - nssym = dyld_NSLookupSymbolInImage(wh, - symbol, - NSLOOKUPSYMBOLINIMAGE_OPTION_BIND | - NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR); - break; - } - } - } - } - if ((!nssym) && NSIsSymbolNameDefined(symbol)) - { - /* I've never seen this debug message...*/ - debug("Symbol \"%s\" is defined but was not found", symbol); - } - } - return nssym; + unsigned int n; + struct load_command *lc = 0; + struct mach_header *wh; + NSSymbol nssym = 0; + if (dyld_NSAddImage && dyld_NSIsSymbolNameDefinedInImage + && dyld_NSLookupSymbolInImage) { + lc = (struct load_command *) ((char *) mh + + sizeof(struct mach_header)); + for (n = 0; n < mh->ncmds; + n++, lc = (struct load_command *) ((char *) lc + lc->cmdsize)) { + if ((LC_LOAD_DYLIB == lc->cmd) + || (LC_LOAD_WEAK_DYLIB == lc->cmd)) { + if ((wh = (struct mach_header *) + my_find_image((char + *) (((struct dylib_command *) lc)-> + dylib.name.offset + (char *) lc)))) { + if (dyld_NSIsSymbolNameDefinedInImage(wh, symbol)) { + nssym = dyld_NSLookupSymbolInImage(wh, + symbol, + NSLOOKUPSYMBOLINIMAGE_OPTION_BIND + | + NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR); + break; + } + } + } + } + if ((!nssym) && NSIsSymbolNameDefined(symbol)) { + /* I've never seen this debug message... */ + debug("Symbol \"%s\" is defined but was not found", symbol); + } + } + return nssym; } /* Up to the caller to SDL_free() returned string */ -static inline char *dyld_error_str() +static inline char * +dyld_error_str() { - NSLinkEditErrors dylder; - int dylderno; - const char *dylderrstr; - const char *dyldfile; - char* retStr = NULL; - NSLinkEditError(&dylder, &dylderno, &dyldfile, &dylderrstr); - if (dylderrstr && *dylderrstr) - { - retStr = SDL_strdup(dylderrstr); - } - return retStr; + NSLinkEditErrors dylder; + int dylderno; + const char *dylderrstr; + const char *dyldfile; + char *retStr = NULL; + NSLinkEditError(&dylder, &dylderno, &dyldfile, &dylderrstr); + if (dylderrstr && *dylderrstr) { + retStr = SDL_strdup(dylderrstr); + } + return retStr; } -static void *dlsymIntern(struct dlstatus *dls, const char *symbol, int canSetError) +static void * +dlsymIntern(struct dlstatus *dls, const char *symbol, int canSetError) { - NSSymbol nssym = 0; -#ifdef __GCC__ - void *caller = __builtin_return_address(1); /* Be *very* careful about inlining */ + NSSymbol nssym = 0; +#ifdef __GCC__ + void *caller = __builtin_return_address(1); /* Be *very* careful about inlining */ #else - void *caller = NULL; + void *caller = NULL; #endif - const struct mach_header *caller_mh = 0; - char *savedErrorStr = NULL; - resetdlerror(); + const struct mach_header *caller_mh = 0; + char *savedErrorStr = NULL; + resetdlerror(); #ifndef RTLD_SELF #define RTLD_SELF ((void *) -3) #endif - if (NULL == dls) - dls = RTLD_SELF; - if ((RTLD_NEXT == dls) || (RTLD_SELF == dls)) - { - if (dyld_NSIsSymbolNameDefinedInImage && dyld_NSLookupSymbolInImage && caller) - { - caller_mh = image_for_address(caller); - if (RTLD_SELF == dls) - { - /* FIXME: We should be using the NSModule api, if SELF is an MH_BUNDLE - * But it appears to work anyway, and looking at the code in dyld_libfuncs.c - * this is acceptable. - */ - if (dyld_NSIsSymbolNameDefinedInImage(caller_mh, symbol)) - { - nssym = dyld_NSLookupSymbolInImage(caller_mh, - symbol, - NSLOOKUPSYMBOLINIMAGE_OPTION_BIND | - NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR); - } - } - if (!nssym) - { - if (RTLD_SELF == dls) - savedErrorStr = dyld_error_str(); - nssym = search_linked_libs(caller_mh, symbol); - } - } - else - { - if (canSetError) - error("RTLD_SELF and RTLD_NEXT are not supported"); - return NULL; - } - } - if (!nssym) - { - - if (RTLD_DEFAULT == dls) - { - dls = &mainStatus; - } - if (!isValidStatus(dls)) - return NULL; - - if (dls->module != MAGIC_DYLIB_MOD) - { - nssym = NSLookupSymbolInModule(dls->module, symbol); - if (!nssym && NSIsSymbolNameDefined(symbol)) - { - debug("Searching dependencies"); - savedErrorStr = dyld_error_str(); - nssym = search_linked_libs(get_mach_header_from_NSModule(dls->module), symbol); - } - } - else if (dls->lib && dyld_NSIsSymbolNameDefinedInImage && dyld_NSLookupSymbolInImage) - { - if (dyld_NSIsSymbolNameDefinedInImage(dls->lib, symbol)) - { - nssym = dyld_NSLookupSymbolInImage(dls->lib, - symbol, - NSLOOKUPSYMBOLINIMAGE_OPTION_BIND | - NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR); - } - else if (NSIsSymbolNameDefined(symbol)) - { - debug("Searching dependencies"); - savedErrorStr = dyld_error_str(); - nssym = search_linked_libs(dls->lib, symbol); - } - } - else if (dls->module == MAGIC_DYLIB_MOD) - { - /* Global context, use NSLookupAndBindSymbol */ - if (NSIsSymbolNameDefined(symbol)) - { - /* There doesn't seem to be a return on error option for this call??? - this is potentially broken, if binding fails, it will improperly - exit the application. */ - nssym = NSLookupAndBindSymbol(symbol); - } - else - { - if (savedErrorStr) - SDL_free(savedErrorStr); - savedErrorStr = SDL_malloc(256); - SDL_snprintf(savedErrorStr, 256, "Symbol \"%s\" not in global context",symbol); - } - } - } - /* Error reporting */ - if (!nssym) - { - if (!savedErrorStr || !SDL_strlen(savedErrorStr)) - { - if (savedErrorStr) - SDL_free(savedErrorStr); - savedErrorStr = SDL_malloc(256); - SDL_snprintf(savedErrorStr, 256,"Symbol \"%s\" not found",symbol); - } - if (canSetError) - { - error(savedErrorStr); - } - else - { - debug(savedErrorStr); - } - if (savedErrorStr) - SDL_free(savedErrorStr); - return NULL; - } - return NSAddressOfSymbol(nssym); + if (NULL == dls) + dls = RTLD_SELF; + if ((RTLD_NEXT == dls) || (RTLD_SELF == dls)) { + if (dyld_NSIsSymbolNameDefinedInImage && dyld_NSLookupSymbolInImage + && caller) { + caller_mh = image_for_address(caller); + if (RTLD_SELF == dls) { + /* FIXME: We should be using the NSModule api, if SELF is an MH_BUNDLE + * But it appears to work anyway, and looking at the code in dyld_libfuncs.c + * this is acceptable. + */ + if (dyld_NSIsSymbolNameDefinedInImage(caller_mh, symbol)) { + nssym = dyld_NSLookupSymbolInImage(caller_mh, + symbol, + NSLOOKUPSYMBOLINIMAGE_OPTION_BIND + | + NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR); + } + } + if (!nssym) { + if (RTLD_SELF == dls) + savedErrorStr = dyld_error_str(); + nssym = search_linked_libs(caller_mh, symbol); + } + } else { + if (canSetError) + error("RTLD_SELF and RTLD_NEXT are not supported"); + return NULL; + } + } + if (!nssym) { + + if (RTLD_DEFAULT == dls) { + dls = &mainStatus; + } + if (!isValidStatus(dls)) + return NULL; + + if (dls->module != MAGIC_DYLIB_MOD) { + nssym = NSLookupSymbolInModule(dls->module, symbol); + if (!nssym && NSIsSymbolNameDefined(symbol)) { + debug("Searching dependencies"); + savedErrorStr = dyld_error_str(); + nssym = + search_linked_libs(get_mach_header_from_NSModule + (dls->module), symbol); + } + } else if (dls->lib && dyld_NSIsSymbolNameDefinedInImage + && dyld_NSLookupSymbolInImage) { + if (dyld_NSIsSymbolNameDefinedInImage(dls->lib, symbol)) { + nssym = dyld_NSLookupSymbolInImage(dls->lib, + symbol, + NSLOOKUPSYMBOLINIMAGE_OPTION_BIND + | + NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR); + } else if (NSIsSymbolNameDefined(symbol)) { + debug("Searching dependencies"); + savedErrorStr = dyld_error_str(); + nssym = search_linked_libs(dls->lib, symbol); + } + } else if (dls->module == MAGIC_DYLIB_MOD) { + /* Global context, use NSLookupAndBindSymbol */ + if (NSIsSymbolNameDefined(symbol)) { + /* There doesn't seem to be a return on error option for this call??? + this is potentially broken, if binding fails, it will improperly + exit the application. */ + nssym = NSLookupAndBindSymbol(symbol); + } else { + if (savedErrorStr) + SDL_free(savedErrorStr); + savedErrorStr = SDL_malloc(256); + SDL_snprintf(savedErrorStr, 256, + "Symbol \"%s\" not in global context", symbol); + } + } + } + /* Error reporting */ + if (!nssym) { + if (!savedErrorStr || !SDL_strlen(savedErrorStr)) { + if (savedErrorStr) + SDL_free(savedErrorStr); + savedErrorStr = SDL_malloc(256); + SDL_snprintf(savedErrorStr, 256, "Symbol \"%s\" not found", + symbol); + } + if (canSetError) { + error(savedErrorStr); + } else { + debug(savedErrorStr); + } + if (savedErrorStr) + SDL_free(savedErrorStr); + return NULL; + } + return NSAddressOfSymbol(nssym); } -static struct dlstatus *loadModule(const char *path, const struct stat *sbuf, int mode) +static struct dlstatus * +loadModule(const char *path, const struct stat *sbuf, int mode) { - NSObjectFileImage ofi = 0; - NSObjectFileImageReturnCode ofirc; - struct dlstatus *dls; - NSLinkEditErrors ler; - int lerno; - const char *errstr; - const char *file; - void (*init) (void); - - ofirc = NSCreateObjectFileImageFromFile(path, &ofi); - switch (ofirc) - { - case NSObjectFileImageSuccess: - break; - case NSObjectFileImageInappropriateFile: - if (dyld_NSAddImage && dyld_NSIsSymbolNameDefinedInImage && dyld_NSLookupSymbolInImage) - { - if (isFlagSet(mode, RTLD_LOCAL)) - { - warning("trying to open a .dylib with RTLD_LOCAL"); - error("unable to open this file with RTLD_LOCAL"); - return NULL; - } - } - else - { - error("opening this file is unsupported on this system"); - return NULL; - } - break; - case NSObjectFileImageFailure: - error("object file setup failure"); - return NULL; - case NSObjectFileImageArch: - error("no object for this architecture"); - return NULL; - case NSObjectFileImageFormat: - error("bad object file format"); - return NULL; - case NSObjectFileImageAccess: - error("can't read object file"); - return NULL; - default: - error("unknown error from NSCreateObjectFileImageFromFile()"); - return NULL; - } - dls = lookupStatus(sbuf); - if (!dls) - { - dls = allocStatus(); - } - if (!dls) - { - error("unable to allocate memory"); - return NULL; - } - // dls->lib = 0; - if (ofirc == NSObjectFileImageInappropriateFile) - { - if ((dls->lib = dyld_NSAddImage(path, NSADDIMAGE_OPTION_RETURN_ON_ERROR))) - { - debug("Dynamic lib loaded at %ld", dls->lib); - ofi = MAGIC_DYLIB_OFI; - dls->module = MAGIC_DYLIB_MOD; - ofirc = NSObjectFileImageSuccess; - /* Although it is possible with a bit of work to modify this so it works and - functions with RTLD_NOW, I don't deem it necessary at the moment */ - } - if (!(dls->module)) - { - NSLinkEditError(&ler, &lerno, &file, &errstr); - if (!errstr || (!SDL_strlen(errstr))) - error("Can't open this file type"); - else - error(errstr); - if ((dls->flags & DL_IN_LIST) == 0) - { - SDL_free(dls); - } - return NULL; - } - } - else - { - dls->module = NSLinkModule(ofi, path, - NSLINKMODULE_OPTION_RETURN_ON_ERROR | - NSLINKMODULE_OPTION_PRIVATE | - (isFlagSet(mode, RTLD_NOW) ? NSLINKMODULE_OPTION_BINDNOW : 0)); - NSDestroyObjectFileImage(ofi); - if (dls->module) - { - dls->lib = get_mach_header_from_NSModule(dls->module); - } - } - if (!dls->module) - { - NSLinkEditError(&ler, &lerno, &file, &errstr); - if ((dls->flags & DL_IN_LIST) == 0) - { - SDL_free(dls); - } - error(errstr); - return NULL; - } - - insertStatus(dls, sbuf); - dls = reference(dls, mode); - if ((init = dlsymIntern(dls, "__init", 0))) - { - debug("calling _init()"); - init(); - } - return dls; + NSObjectFileImage ofi = 0; + NSObjectFileImageReturnCode ofirc; + struct dlstatus *dls; + NSLinkEditErrors ler; + int lerno; + const char *errstr; + const char *file; + void (*init) (void); + + ofirc = NSCreateObjectFileImageFromFile(path, &ofi); + switch (ofirc) { + case NSObjectFileImageSuccess: + break; + case NSObjectFileImageInappropriateFile: + if (dyld_NSAddImage && dyld_NSIsSymbolNameDefinedInImage + && dyld_NSLookupSymbolInImage) { + if (isFlagSet(mode, RTLD_LOCAL)) { + warning("trying to open a .dylib with RTLD_LOCAL"); + error("unable to open this file with RTLD_LOCAL"); + return NULL; + } + } else { + error("opening this file is unsupported on this system"); + return NULL; + } + break; + case NSObjectFileImageFailure: + error("object file setup failure"); + return NULL; + case NSObjectFileImageArch: + error("no object for this architecture"); + return NULL; + case NSObjectFileImageFormat: + error("bad object file format"); + return NULL; + case NSObjectFileImageAccess: + error("can't read object file"); + return NULL; + default: + error("unknown error from NSCreateObjectFileImageFromFile()"); + return NULL; + } + dls = lookupStatus(sbuf); + if (!dls) { + dls = allocStatus(); + } + if (!dls) { + error("unable to allocate memory"); + return NULL; + } + // dls->lib = 0; + if (ofirc == NSObjectFileImageInappropriateFile) { + if ((dls->lib = + dyld_NSAddImage(path, NSADDIMAGE_OPTION_RETURN_ON_ERROR))) { + debug("Dynamic lib loaded at %ld", dls->lib); + ofi = MAGIC_DYLIB_OFI; + dls->module = MAGIC_DYLIB_MOD; + ofirc = NSObjectFileImageSuccess; + /* Although it is possible with a bit of work to modify this so it works and + functions with RTLD_NOW, I don't deem it necessary at the moment */ + } + if (!(dls->module)) { + NSLinkEditError(&ler, &lerno, &file, &errstr); + if (!errstr || (!SDL_strlen(errstr))) + error("Can't open this file type"); + else + error(errstr); + if ((dls->flags & DL_IN_LIST) == 0) { + SDL_free(dls); + } + return NULL; + } + } else { + dls->module = NSLinkModule(ofi, path, + NSLINKMODULE_OPTION_RETURN_ON_ERROR | + NSLINKMODULE_OPTION_PRIVATE | + (isFlagSet(mode, RTLD_NOW) ? + NSLINKMODULE_OPTION_BINDNOW : 0)); + NSDestroyObjectFileImage(ofi); + if (dls->module) { + dls->lib = get_mach_header_from_NSModule(dls->module); + } + } + if (!dls->module) { + NSLinkEditError(&ler, &lerno, &file, &errstr); + if ((dls->flags & DL_IN_LIST) == 0) { + SDL_free(dls); + } + error(errstr); + return NULL; + } + + insertStatus(dls, sbuf); + dls = reference(dls, mode); + if ((init = dlsymIntern(dls, "__init", 0))) { + debug("calling _init()"); + init(); + } + return dls; } -inline static void dlcompat_init_check(void) +inline static void +dlcompat_init_check(void) { - static pthread_mutex_t l = PTHREAD_MUTEX_INITIALIZER; - static int init_done = 0; - - pthread_mutex_lock(&l); - if (!init_done) { - dlcompat_init_func(); - init_done = 1; - } - pthread_mutex_unlock(&l); + static pthread_mutex_t l = PTHREAD_MUTEX_INITIALIZER; + static int init_done = 0; + + pthread_mutex_lock(&l); + if (!init_done) { + dlcompat_init_func(); + init_done = 1; + } + pthread_mutex_unlock(&l); } -static void dlcompat_init_func(void) +static void +dlcompat_init_func(void) { - _dyld_func_lookup("__dyld_NSAddImage", (void **)&dyld_NSAddImage); - _dyld_func_lookup("__dyld_NSIsSymbolNameDefinedInImage", - (void **)&dyld_NSIsSymbolNameDefinedInImage); - _dyld_func_lookup("__dyld_NSLookupSymbolInImage", (void **)&dyld_NSLookupSymbolInImage); - if (pthread_mutex_init(&dlcompat_mutex, NULL)) - exit(1); - if (pthread_key_create(&dlerror_key, &dlerrorfree)) - exit(1); + _dyld_func_lookup("__dyld_NSAddImage", (void **) &dyld_NSAddImage); + _dyld_func_lookup("__dyld_NSIsSymbolNameDefinedInImage", + (void **) &dyld_NSIsSymbolNameDefinedInImage); + _dyld_func_lookup("__dyld_NSLookupSymbolInImage", + (void **) &dyld_NSLookupSymbolInImage); + if (pthread_mutex_init(&dlcompat_mutex, NULL)) + exit(1); + if (pthread_key_create(&dlerror_key, &dlerrorfree)) + exit(1); } -static void resetdlerror() +static void +resetdlerror() { - struct dlthread *tss; - tss = pthread_getspecific(dlerror_key); - tss->errset = 0; + struct dlthread *tss; + tss = pthread_getspecific(dlerror_key); + tss->errset = 0; } -static void dlerrorfree(void *data) +static void +dlerrorfree(void *data) { - SDL_free(data); + SDL_free(data); } /* We kind of want a recursive lock here, but meet a little trouble * because they are not available pre OS X 10.2, so we fake it * using thread specific storage to keep a lock count - */ -static inline void dolock(void) + */ +static inline void +dolock(void) { - int err = 0; - struct dlthread *tss; - dlcompat_init_check(); - tss = pthread_getspecific(dlerror_key); - if (!tss) - { - tss = SDL_malloc(sizeof(struct dlthread)); - tss->lockcnt = 0; - tss->errset = 0; - if (pthread_setspecific(dlerror_key, tss)) - { - fprintf(stderr,"dlcompat: pthread_setspecific failed\n"); - exit(1); - } - } - if (!tss->lockcnt) - err = pthread_mutex_lock(&dlcompat_mutex); - tss->lockcnt = tss->lockcnt +1; - if (err) - exit(err); + int err = 0; + struct dlthread *tss; + dlcompat_init_check(); + tss = pthread_getspecific(dlerror_key); + if (!tss) { + tss = SDL_malloc(sizeof(struct dlthread)); + tss->lockcnt = 0; + tss->errset = 0; + if (pthread_setspecific(dlerror_key, tss)) { + fprintf(stderr, "dlcompat: pthread_setspecific failed\n"); + exit(1); + } + } + if (!tss->lockcnt) + err = pthread_mutex_lock(&dlcompat_mutex); + tss->lockcnt = tss->lockcnt + 1; + if (err) + exit(err); } -static inline void dounlock(void) +static inline void +dounlock(void) { - int err = 0; - struct dlthread *tss; - tss = pthread_getspecific(dlerror_key); - tss->lockcnt = tss->lockcnt -1; - if (!tss->lockcnt) - err = pthread_mutex_unlock(&dlcompat_mutex); - if (err) - exit(err); + int err = 0; + struct dlthread *tss; + tss = pthread_getspecific(dlerror_key); + tss->lockcnt = tss->lockcnt - 1; + if (!tss->lockcnt) + err = pthread_mutex_unlock(&dlcompat_mutex); + if (err) + exit(err); } -static void *SDL_OSX_dlopen(const char *path, int mode) +static void * +SDL_OSX_dlopen(const char *path, int mode) { - const struct stat *sbuf; - struct dlstatus *dls; - const char *fullPath; - - dolock(); - resetdlerror(); - if (!path) - { - dls = &mainStatus; - goto dlopenok; - } - if (!(sbuf = findFile(path, &fullPath))) - { - error("file \"%s\" not found", path); - goto dlopenerror; - } - /* Now checks that it hasn't been closed already */ - if ((dls = lookupStatus(sbuf)) && (dls->refs > 0)) - { - /* debug("status found"); */ - dls = reference(dls, mode); - goto dlopenok; - } + const struct stat *sbuf; + struct dlstatus *dls; + const char *fullPath; + + dolock(); + resetdlerror(); + if (!path) { + dls = &mainStatus; + goto dlopenok; + } + if (!(sbuf = findFile(path, &fullPath))) { + error("file \"%s\" not found", path); + goto dlopenerror; + } + /* Now checks that it hasn't been closed already */ + if ((dls = lookupStatus(sbuf)) && (dls->refs > 0)) { + /* debug("status found"); */ + dls = reference(dls, mode); + goto dlopenok; + } #ifdef RTLD_NOLOAD - if (isFlagSet(mode, RTLD_NOLOAD)) - { - error("no existing handle and RTLD_NOLOAD specified"); - goto dlopenerror; - } + if (isFlagSet(mode, RTLD_NOLOAD)) { + error("no existing handle and RTLD_NOLOAD specified"); + goto dlopenerror; + } #endif - if (isFlagSet(mode, RTLD_LAZY) && isFlagSet(mode, RTLD_NOW)) - { - error("how can I load something both RTLD_LAZY and RTLD_NOW?"); - goto dlopenerror; - } - dls = loadModule(fullPath, sbuf, mode); - + if (isFlagSet(mode, RTLD_LAZY) && isFlagSet(mode, RTLD_NOW)) { + error("how can I load something both RTLD_LAZY and RTLD_NOW?"); + goto dlopenerror; + } + dls = loadModule(fullPath, sbuf, mode); + dlopenok: - dounlock(); - return (void *)dls; + dounlock(); + return (void *) dls; dlopenerror: - dounlock(); - return NULL; + dounlock(); + return NULL; } #if !FINK_BUILD -static void *SDL_OSX_dlsym(void * dl_restrict handle, const char * dl_restrict symbol) +static void * +SDL_OSX_dlsym(void *dl_restrict handle, const char *dl_restrict symbol) { - int sym_len = SDL_strlen(symbol); - void *value = NULL; - char *malloc_sym = NULL; - dolock(); - malloc_sym = SDL_malloc(sym_len + 2); - if (malloc_sym) - { - SDL_snprintf(malloc_sym, sym_len+2, "_%s", symbol); - value = dlsymIntern(handle, malloc_sym, 1); - SDL_free(malloc_sym); - } - else - { - error("Unable to allocate memory"); - goto dlsymerror; - } - dounlock(); - return value; + int sym_len = SDL_strlen(symbol); + void *value = NULL; + char *malloc_sym = NULL; + dolock(); + malloc_sym = SDL_malloc(sym_len + 2); + if (malloc_sym) { + SDL_snprintf(malloc_sym, sym_len + 2, "_%s", symbol); + value = dlsymIntern(handle, malloc_sym, 1); + SDL_free(malloc_sym); + } else { + error("Unable to allocate memory"); + goto dlsymerror; + } + dounlock(); + return value; dlsymerror: - dounlock(); - return NULL; + dounlock(); + return NULL; } #endif #if FINK_BUILD -static void *dlsym_prepend_underscore(void *handle, const char *symbol) +static void * +dlsym_prepend_underscore(void *handle, const char *symbol) { - void *answer; - dolock(); - answer = dlsym_prepend_underscore_intern(handle, symbol); - dounlock(); - return answer; + void *answer; + dolock(); + answer = dlsym_prepend_underscore_intern(handle, symbol); + dounlock(); + return answer; } -static void *dlsym_prepend_underscore_intern(void *handle, const char *symbol) +static void * +dlsym_prepend_underscore_intern(void *handle, const char *symbol) { /* * A quick and easy way for porting packages which call dlsym(handle,"sym") @@ -1059,272 +1043,268 @@ static void *dlsym_prepend_underscore_intern(void *handle, const char *symbol) * the underscore always, or not at all. These global functions need to go away * for opendarwin. */ - int sym_len = SDL_strlen(symbol); - void *value = NULL; - char *malloc_sym = NULL; - malloc_sym = SDL_malloc(sym_len + 2); - if (malloc_sym) - { - SDL_snprintf(malloc_sym, sym_len+2, "_%s", symbol); - value = dlsymIntern(handle, malloc_sym, 1); - SDL_free(malloc_sym); - } - else - { - error("Unable to allocate memory"); - } - return value; + int sym_len = SDL_strlen(symbol); + void *value = NULL; + char *malloc_sym = NULL; + malloc_sym = SDL_malloc(sym_len + 2); + if (malloc_sym) { + SDL_snprintf(malloc_sym, sym_len + 2, "_%s", symbol); + value = dlsymIntern(handle, malloc_sym, 1); + SDL_free(malloc_sym); + } else { + error("Unable to allocate memory"); + } + return value; } -static void *dlsym_auto_underscore(void *handle, const char *symbol) +static void * +dlsym_auto_underscore(void *handle, const char *symbol) { - void *answer; - dolock(); - answer = dlsym_auto_underscore_intern(handle, symbol); - dounlock(); - return answer; + void *answer; + dolock(); + answer = dlsym_auto_underscore_intern(handle, symbol); + dounlock(); + return answer; } -static void *dlsym_auto_underscore_intern(void *handle, const char *symbol) +static void * +dlsym_auto_underscore_intern(void *handle, const char *symbol) { - struct dlstatus *dls = handle; - void *addr = 0; - addr = dlsymIntern(dls, symbol, 0); - if (!addr) - addr = dlsym_prepend_underscore_intern(handle, symbol); - return addr; + struct dlstatus *dls = handle; + void *addr = 0; + addr = dlsymIntern(dls, symbol, 0); + if (!addr) + addr = dlsym_prepend_underscore_intern(handle, symbol); + return addr; } -static void *SDL_OSX_dlsym(void * dl_restrict handle, const char * dl_restrict symbol) +static void * +SDL_OSX_dlsym(void *dl_restrict handle, const char *dl_restrict symbol) { - struct dlstatus *dls = handle; - void *addr = 0; - dolock(); - addr = dlsymIntern(dls, symbol, 1); - dounlock(); - return addr; + struct dlstatus *dls = handle; + void *addr = 0; + dolock(); + addr = dlsymIntern(dls, symbol, 1); + dounlock(); + return addr; } #endif -static int SDL_OSX_dlclose(void *handle) +static int +SDL_OSX_dlclose(void *handle) { - struct dlstatus *dls = handle; - dolock(); - resetdlerror(); - if (!isValidStatus(dls)) - { - goto dlcloseerror; - } - if (dls->module == MAGIC_DYLIB_MOD) - { - const char *name; - if (!dls->lib) - { - name = "global context"; - } - else - { - name = get_lib_name(dls->lib); - } - warning("trying to close a .dylib!"); - error("Not closing \"%s\" - dynamic libraries cannot be closed", name); - goto dlcloseerror; - } - if (!dls->module) - { - error("module already closed"); - goto dlcloseerror; - } - - if (dls->refs == 1) - { - unsigned long options = 0; - void (*fini) (void); - if ((fini = dlsymIntern(dls, "__fini", 0))) - { - debug("calling _fini()"); - fini(); - } - options |= NSUNLINKMODULE_OPTION_RESET_LAZY_REFERENCES; + struct dlstatus *dls = handle; + dolock(); + resetdlerror(); + if (!isValidStatus(dls)) { + goto dlcloseerror; + } + if (dls->module == MAGIC_DYLIB_MOD) { + const char *name; + if (!dls->lib) { + name = "global context"; + } else { + name = get_lib_name(dls->lib); + } + warning("trying to close a .dylib!"); + error("Not closing \"%s\" - dynamic libraries cannot be closed", + name); + goto dlcloseerror; + } + if (!dls->module) { + error("module already closed"); + goto dlcloseerror; + } + + if (dls->refs == 1) { + unsigned long options = 0; + void (*fini) (void); + if ((fini = dlsymIntern(dls, "__fini", 0))) { + debug("calling _fini()"); + fini(); + } + options |= NSUNLINKMODULE_OPTION_RESET_LAZY_REFERENCES; #ifdef RTLD_NODELETE - if (isFlagSet(dls->mode, RTLD_NODELETE)) - options |= NSUNLINKMODULE_OPTION_KEEP_MEMORY_MAPPED; + if (isFlagSet(dls->mode, RTLD_NODELETE)) + options |= NSUNLINKMODULE_OPTION_KEEP_MEMORY_MAPPED; #endif - if (!NSUnLinkModule(dls->module, options)) - { - error("unable to unlink module"); - goto dlcloseerror; - } - dls->refs--; - dls->module = 0; - /* Note: the dlstatus struct dls is neither removed from the list - * nor is the memory it occupies freed. This shouldn't pose a - * problem in mostly all cases, though. - */ - } - dounlock(); - return 0; + if (!NSUnLinkModule(dls->module, options)) { + error("unable to unlink module"); + goto dlcloseerror; + } + dls->refs--; + dls->module = 0; + /* Note: the dlstatus struct dls is neither removed from the list + * nor is the memory it occupies freed. This shouldn't pose a + * problem in mostly all cases, though. + */ + } + dounlock(); + return 0; dlcloseerror: - dounlock(); - return 1; + dounlock(); + return 1; } -static const char *SDL_OSX_dlerror(void) +static const char * +SDL_OSX_dlerror(void) { - struct dlthread *tss; - const char * err_str = NULL; - dlcompat_init_check(); - tss = pthread_getspecific(dlerror_key); - if (tss != NULL && tss->errset != 0) { - tss->errset = 0; - err_str = tss->errstr; - } - return (err_str); + struct dlthread *tss; + const char *err_str = NULL; + dlcompat_init_check(); + tss = pthread_getspecific(dlerror_key); + if (tss != NULL && tss->errset != 0) { + tss->errset = 0; + err_str = tss->errstr; + } + return (err_str); } /* Given an address, return the mach_header for the image containing it * or zero if the given address is not contained in any loaded images. */ -static const struct mach_header *image_for_address(const void *address) +static const struct mach_header * +image_for_address(const void *address) { - unsigned long i; - unsigned long j; - unsigned long count = _dyld_image_count(); - const struct mach_header *mh = 0; - struct load_command *lc = 0; - unsigned long addr = 0; - for (i = 0; i < count; i++) - { - addr = (unsigned long)address - _dyld_get_image_vmaddr_slide(i); - mh = _dyld_get_image_header(i); - if (mh) - { - lc = (struct load_command *)((char *)mh + sizeof(struct mach_header)); - for (j = 0; j < mh->ncmds; j++, lc = (struct load_command *)((char *)lc + lc->cmdsize)) - { - if (LC_SEGMENT == lc->cmd && - addr >= ((struct segment_command *)lc)->vmaddr && - addr < - ((struct segment_command *)lc)->vmaddr + ((struct segment_command *)lc)->vmsize) - { - goto image_found; - } - } - } - mh = 0; - } + unsigned long i; + unsigned long j; + unsigned long count = _dyld_image_count(); + const struct mach_header *mh = 0; + struct load_command *lc = 0; + unsigned long addr = 0; + for (i = 0; i < count; i++) { + addr = (unsigned long) address - _dyld_get_image_vmaddr_slide(i); + mh = _dyld_get_image_header(i); + if (mh) { + lc = (struct load_command *) ((char *) mh + + sizeof(struct mach_header)); + for (j = 0; j < mh->ncmds; + j++, lc = + (struct load_command *) ((char *) lc + lc->cmdsize)) { + if (LC_SEGMENT == lc->cmd && + addr >= ((struct segment_command *) lc)->vmaddr && + addr < + ((struct segment_command *) lc)->vmaddr + + ((struct segment_command *) lc)->vmsize) { + goto image_found; + } + } + } + mh = 0; + } image_found: - return mh; + return mh; } -#if 0 /* unused */ -static int SDL_OSX_dladdr(const void * dl_restrict p, SDL_OSX_Dl_info * dl_restrict info) +#if 0 /* unused */ +static int +SDL_OSX_dladdr(const void *dl_restrict p, SDL_OSX_Dl_info * dl_restrict info) { /* FIXME: USe the routine image_for_address. */ - unsigned long i; - unsigned long j; - unsigned long count = _dyld_image_count(); - struct mach_header *mh = 0; - struct load_command *lc = 0; - unsigned long addr = NULL; - unsigned long table_off = (unsigned long)0; - int found = 0; - if (!info) - return 0; - dolock(); - resetdlerror(); - info->dli_fname = 0; - info->dli_fbase = 0; - info->dli_sname = 0; - info->dli_saddr = 0; + unsigned long i; + unsigned long j; + unsigned long count = _dyld_image_count(); + struct mach_header *mh = 0; + struct load_command *lc = 0; + unsigned long addr = NULL; + unsigned long table_off = (unsigned long) 0; + int found = 0; + if (!info) + return 0; + dolock(); + resetdlerror(); + info->dli_fname = 0; + info->dli_fbase = 0; + info->dli_sname = 0; + info->dli_saddr = 0; /* Some of this was swiped from code posted by Douglas Davidson * to darwin-development AT lists DOT apple DOT com and slightly modified */ - for (i = 0; i < count; i++) - { - addr = (unsigned long)p - _dyld_get_image_vmaddr_slide(i); - mh = _dyld_get_image_header(i); - if (mh) - { - lc = (struct load_command *)((char *)mh + sizeof(struct mach_header)); - for (j = 0; j < mh->ncmds; j++, lc = (struct load_command *)((char *)lc + lc->cmdsize)) - { - if (LC_SEGMENT == lc->cmd && - addr >= ((struct segment_command *)lc)->vmaddr && - addr < - ((struct segment_command *)lc)->vmaddr + ((struct segment_command *)lc)->vmsize) - { - info->dli_fname = _dyld_get_image_name(i); - info->dli_fbase = (void *)mh; - found = 1; - break; - } - } - if (found) - break; - } - } - if (!found) - { - dounlock(); - return 0; - } - lc = (struct load_command *)((char *)mh + sizeof(struct mach_header)); - for (j = 0; j < mh->ncmds; j++, lc = (struct load_command *)((char *)lc + lc->cmdsize)) - { - if (LC_SEGMENT == lc->cmd) - { - if (!SDL_strcmp(((struct segment_command *)lc)->segname, "__LINKEDIT")) - break; - } - } - table_off = - ((unsigned long)((struct segment_command *)lc)->vmaddr) - - ((unsigned long)((struct segment_command *)lc)->fileoff) + _dyld_get_image_vmaddr_slide(i); - debug("table off %x", table_off); - - lc = (struct load_command *)((char *)mh + sizeof(struct mach_header)); - for (j = 0; j < mh->ncmds; j++, lc = (struct load_command *)((char *)lc + lc->cmdsize)) - { - if (LC_SYMTAB == lc->cmd) - { - - struct nlist *symtable = (struct nlist *)(((struct symtab_command *)lc)->symoff + table_off); - unsigned long numsyms = ((struct symtab_command *)lc)->nsyms; - struct nlist *nearest = NULL; - unsigned long diff = 0xffffffff; - unsigned long strtable = (unsigned long)(((struct symtab_command *)lc)->stroff + table_off); - debug("symtable %x", symtable); - for (i = 0; i < numsyms; i++) - { - /* Ignore the following kinds of Symbols */ - if ((!symtable->n_value) /* Undefined */ - || (symtable->n_type >= N_PEXT) /* Debug symbol */ - || (!(symtable->n_type & N_EXT)) /* Local Symbol */ - ) - { - symtable++; - continue; - } - if ((addr >= symtable->n_value) && (diff >= (symtable->n_value - addr))) - { - diff = (unsigned long)symtable->n_value - addr; - nearest = symtable; - } - symtable++; - } - if (nearest) - { - info->dli_saddr = nearest->n_value + ((void *)p - addr); - info->dli_sname = (char *)(strtable + nearest->n_un.n_strx); - } - } - } - dounlock(); - return 1; + for (i = 0; i < count; i++) { + addr = (unsigned long) p - _dyld_get_image_vmaddr_slide(i); + mh = _dyld_get_image_header(i); + if (mh) { + lc = (struct load_command *) ((char *) mh + + sizeof(struct mach_header)); + for (j = 0; j < mh->ncmds; + j++, lc = + (struct load_command *) ((char *) lc + lc->cmdsize)) { + if (LC_SEGMENT == lc->cmd && + addr >= ((struct segment_command *) lc)->vmaddr && + addr < + ((struct segment_command *) lc)->vmaddr + + ((struct segment_command *) lc)->vmsize) { + info->dli_fname = _dyld_get_image_name(i); + info->dli_fbase = (void *) mh; + found = 1; + break; + } + } + if (found) + break; + } + } + if (!found) { + dounlock(); + return 0; + } + lc = (struct load_command *) ((char *) mh + sizeof(struct mach_header)); + for (j = 0; j < mh->ncmds; + j++, lc = (struct load_command *) ((char *) lc + lc->cmdsize)) { + if (LC_SEGMENT == lc->cmd) { + if (!SDL_strcmp + (((struct segment_command *) lc)->segname, "__LINKEDIT")) + break; + } + } + table_off = + ((unsigned long) ((struct segment_command *) lc)->vmaddr) - + ((unsigned long) ((struct segment_command *) lc)->fileoff) + + _dyld_get_image_vmaddr_slide(i); + debug("table off %x", table_off); + + lc = (struct load_command *) ((char *) mh + sizeof(struct mach_header)); + for (j = 0; j < mh->ncmds; + j++, lc = (struct load_command *) ((char *) lc + lc->cmdsize)) { + if (LC_SYMTAB == lc->cmd) { + + struct nlist *symtable = + (struct nlist *) (((struct symtab_command *) lc)->symoff + + table_off); + unsigned long numsyms = ((struct symtab_command *) lc)->nsyms; + struct nlist *nearest = NULL; + unsigned long diff = 0xffffffff; + unsigned long strtable = + (unsigned long) (((struct symtab_command *) lc)->stroff + + table_off); + debug("symtable %x", symtable); + for (i = 0; i < numsyms; i++) { + /* Ignore the following kinds of Symbols */ + if ((!symtable->n_value) /* Undefined */ + ||(symtable->n_type >= N_PEXT) /* Debug symbol */ + ||(!(symtable->n_type & N_EXT)) /* Local Symbol */ + ) { + symtable++; + continue; + } + if ((addr >= symtable->n_value) + && (diff >= (symtable->n_value - addr))) { + diff = (unsigned long) symtable->n_value - addr; + nearest = symtable; + } + symtable++; + } + if (nearest) { + info->dli_saddr = nearest->n_value + ((void *) p - addr); + info->dli_sname = (char *) (strtable + nearest->n_un.n_strx); + } + } + } + dounlock(); + return 1; } #endif @@ -1337,34 +1317,32 @@ static int SDL_OSX_dladdr(const void * dl_restrict p, SDL_OSX_Dl_info * dl_restr * have the same representation, which is true on all platforms FreeBSD * runs on, but is not guaranteed by the C standard. */ -#if 0 -static dlfunc_t SDL_OSX_dlfunc(void * dl_restrict handle, const char * dl_restrict symbol) +#if 0 +static dlfunc_t +SDL_OSX_dlfunc(void *dl_restrict handle, const char *dl_restrict symbol) { - union - { - void *d; - dlfunc_t f; - } rv; - int sym_len = SDL_strlen(symbol); - char *malloc_sym = NULL; - dolock(); - malloc_sym = SDL_malloc(sym_len + 2); - if (malloc_sym) - { - SDL_snprintf(malloc_sym, sym_len+2, "_%s", symbol); - rv.d = dlsymIntern(handle, malloc_sym, 1); - SDL_free(malloc_sym); - } - else - { - error("Unable to allocate memory"); - goto dlfuncerror; - } - dounlock(); - return rv.f; + union + { + void *d; + dlfunc_t f; + } rv; + int sym_len = SDL_strlen(symbol); + char *malloc_sym = NULL; + dolock(); + malloc_sym = SDL_malloc(sym_len + 2); + if (malloc_sym) { + SDL_snprintf(malloc_sym, sym_len + 2, "_%s", symbol); + rv.d = dlsymIntern(handle, malloc_sym, 1); + SDL_free(malloc_sym); + } else { + error("Unable to allocate memory"); + goto dlfuncerror; + } + dounlock(); + return rv.f; dlfuncerror: - dounlock(); - return NULL; + dounlock(); + return NULL; } #endif @@ -1378,30 +1356,34 @@ static dlfunc_t SDL_OSX_dlfunc(void * dl_restrict handle, const char * dl_restri #include "SDL_loadso.h" -void *SDL_LoadObject(const char *sofile) +void * +SDL_LoadObject(const char *sofile) { - void *handle = SDL_OSX_dlopen(sofile, RTLD_NOW); - const char *loaderror = SDL_OSX_dlerror(); - if ( handle == NULL ) { - SDL_SetError("Failed loading %s: %s", sofile, loaderror); - } - return(handle); + void *handle = SDL_OSX_dlopen(sofile, RTLD_NOW); + const char *loaderror = SDL_OSX_dlerror(); + if (handle == NULL) { + SDL_SetError("Failed loading %s: %s", sofile, loaderror); + } + return (handle); } -void *SDL_LoadFunction(void *handle, const char *name) +void * +SDL_LoadFunction(void *handle, const char *name) { - void *symbol = SDL_OSX_dlsym(handle, name); - if ( symbol == NULL ) { - SDL_SetError("Failed loading %s: %s", name, SDL_OSX_dlerror()); - } - return(symbol); + void *symbol = SDL_OSX_dlsym(handle, name); + if (symbol == NULL) { + SDL_SetError("Failed loading %s: %s", name, SDL_OSX_dlerror()); + } + return (symbol); } -void SDL_UnloadObject(void *handle) +void +SDL_UnloadObject(void *handle) { - if ( handle != NULL ) { - SDL_OSX_dlclose(handle); - } + if (handle != NULL) { + SDL_OSX_dlclose(handle); + } } #endif /* SDL_LOADSO_DLCOMPAT */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/loadso/mint/SDL_sysloadso.c b/src/loadso/mint/SDL_sysloadso.c index d089e1b93..69f0a0331 100644 --- a/src/loadso/mint/SDL_sysloadso.c +++ b/src/loadso/mint/SDL_sysloadso.c @@ -32,31 +32,35 @@ #include "SDL_loadso.h" -void *SDL_LoadObject(const char *sofile) +void * +SDL_LoadObject(const char *sofile) { - const char *loaderror = "Unknown error"; - void *handle = (void *)ldg_open((char *)sofile, ldg_global); - if ( handle == NULL ) { - SDL_SetError("Failed loading %s: %s", sofile, loaderror); - } - return(handle); + const char *loaderror = "Unknown error"; + void *handle = (void *) ldg_open((char *) sofile, ldg_global); + if (handle == NULL) { + SDL_SetError("Failed loading %s: %s", sofile, loaderror); + } + return (handle); } -void *SDL_LoadFunction(void *handle, const char *name) +void * +SDL_LoadFunction(void *handle, const char *name) { - const char *loaderror = "Unknown error"; - void *symbol = (void *)ldg_find((char *)name, (LDG *)handle); - if ( symbol == NULL ) { - SDL_SetError("Failed loading %s: %s", name, loaderror); - } - return(symbol); + const char *loaderror = "Unknown error"; + void *symbol = (void *) ldg_find((char *) name, (LDG *) handle); + if (symbol == NULL) { + SDL_SetError("Failed loading %s: %s", name, loaderror); + } + return (symbol); } -void SDL_UnloadObject(void *handle) +void +SDL_UnloadObject(void *handle) { - if ( handle != NULL ) { - ldg_close((LDG *)handle, ldg_global); - } + if (handle != NULL) { + ldg_close((LDG *) handle, ldg_global); + } } #endif /* SDL_LOADSO_LDG */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/loadso/os2/SDL_sysloadso.c b/src/loadso/os2/SDL_sysloadso.c index 006759103..4e3aeebdb 100644 --- a/src/loadso/os2/SDL_sysloadso.c +++ b/src/loadso/os2/SDL_sysloadso.c @@ -33,24 +33,27 @@ #include "SDL_loadso.h" -void *SDL_LoadObject(const char *sofile) +void * +SDL_LoadObject(const char *sofile) { HMODULE handle = NULL; char buf[512]; - APIRET ulrc = DosLoadModule(buf, sizeof (buf), (char *) sofile, &handle); + APIRET ulrc = DosLoadModule(buf, sizeof(buf), (char *) sofile, &handle); /* Generate an error message if all loads failed */ if ((ulrc != NO_ERROR) || (handle == NULL)) SDL_SetError("Failed loading %s: %s", sofile, buf); - return((void *) handle); + return ((void *) handle); } -void *SDL_LoadFunction(void *handle, const char *name) +void * +SDL_LoadFunction(void *handle, const char *name) { const char *loaderror = "Unknown error"; void *symbol = NULL; - APIRET ulrc = DosQueryProcAddr((HMODULE)handle, 0, (char *)name, &symbol); + APIRET ulrc = + DosQueryProcAddr((HMODULE) handle, 0, (char *) name, &symbol); if (ulrc == ERROR_INVALID_HANDLE) loaderror = "Invalid module handle"; else if (ulrc == ERROR_INVALID_NAME) @@ -59,13 +62,15 @@ void *SDL_LoadFunction(void *handle, const char *name) if (symbol == NULL) SDL_SetError("Failed loading %s: %s", name, loaderror); - return(symbol); + return (symbol); } -void SDL_UnloadObject(void *handle) +void +SDL_UnloadObject(void *handle) { - if ( handle != NULL ) + if (handle != NULL) DosFreeModule((HMODULE) handle); } #endif /* SDL_LOADSO_OS2 */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/loadso/win32/SDL_sysloadso.c b/src/loadso/win32/SDL_sysloadso.c index 8ed7c68c4..93cb5f0c8 100644 --- a/src/loadso/win32/SDL_sysloadso.c +++ b/src/loadso/win32/SDL_sysloadso.c @@ -31,109 +31,114 @@ #include "SDL_loadso.h" -void *SDL_LoadObject(const char *sofile) +void * +SDL_LoadObject(const char *sofile) { - void *handle = NULL; - const char *loaderror = "Unknown error"; + void *handle = NULL; + const char *loaderror = "Unknown error"; #if defined(_WIN32_WCE) - char errbuf[512]; - - wchar_t *errbuf_t = SDL_malloc(512 * sizeof(wchar_t)); - wchar_t *sofile_t = SDL_malloc((MAX_PATH+1) * sizeof(wchar_t)); - - MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, sofile, -1, sofile_t, MAX_PATH); - handle = (void *)LoadLibrary(sofile_t); - - /* Generate an error message if all loads failed */ - if ( handle == NULL ) { - FormatMessage((FORMAT_MESSAGE_IGNORE_INSERTS | - FORMAT_MESSAGE_FROM_SYSTEM), - NULL, GetLastError(), - MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), - errbuf_t, SDL_arraysize(errbuf), NULL); - WideCharToMultiByte(CP_ACP, 0, errbuf_t, -1, errbuf, 511, NULL, NULL); - loaderror = errbuf; - } - - SDL_free(sofile_t); - SDL_free(errbuf_t); - -#else /*if defined(__WIN32__)*/ - char errbuf[512]; - - handle = (void *)LoadLibrary(sofile); - - /* Generate an error message if all loads failed */ - if ( handle == NULL ) { - FormatMessage((FORMAT_MESSAGE_IGNORE_INSERTS | - FORMAT_MESSAGE_FROM_SYSTEM), - NULL, GetLastError(), - MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), - errbuf, SDL_arraysize(errbuf), NULL); - loaderror = errbuf; - } + char errbuf[512]; + + wchar_t *errbuf_t = SDL_malloc(512 * sizeof(wchar_t)); + wchar_t *sofile_t = SDL_malloc((MAX_PATH + 1) * sizeof(wchar_t)); + + MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, sofile, -1, sofile_t, + MAX_PATH); + handle = (void *) LoadLibrary(sofile_t); + + /* Generate an error message if all loads failed */ + if (handle == NULL) { + FormatMessage((FORMAT_MESSAGE_IGNORE_INSERTS | + FORMAT_MESSAGE_FROM_SYSTEM), + NULL, GetLastError(), + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), + errbuf_t, SDL_arraysize(errbuf), NULL); + WideCharToMultiByte(CP_ACP, 0, errbuf_t, -1, errbuf, 511, NULL, NULL); + loaderror = errbuf; + } + + SDL_free(sofile_t); + SDL_free(errbuf_t); + +#else /*if defined(__WIN32__) */ + char errbuf[512]; + + handle = (void *) LoadLibrary(sofile); + + /* Generate an error message if all loads failed */ + if (handle == NULL) { + FormatMessage((FORMAT_MESSAGE_IGNORE_INSERTS | + FORMAT_MESSAGE_FROM_SYSTEM), + NULL, GetLastError(), + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), + errbuf, SDL_arraysize(errbuf), NULL); + loaderror = errbuf; + } #endif - if ( handle == NULL ) { - SDL_SetError("Failed loading %s: %s", sofile, loaderror); - } - return(handle); + if (handle == NULL) { + SDL_SetError("Failed loading %s: %s", sofile, loaderror); + } + return (handle); } -void *SDL_LoadFunction(void *handle, const char *name) +void * +SDL_LoadFunction(void *handle, const char *name) { - void *symbol = NULL; - const char *loaderror = "Unknown error"; + void *symbol = NULL; + const char *loaderror = "Unknown error"; #if defined(_WIN32_WCE) - char errbuf[512]; - int length = SDL_strlen(name); - - wchar_t *name_t = SDL_malloc((length + 1) * sizeof(wchar_t)); - wchar_t *errbuf_t = SDL_malloc(512 * sizeof(wchar_t)); - - MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, name, -1, name_t, length); - - symbol = (void *)GetProcAddress((HMODULE)handle, name_t); - if ( symbol == NULL ) { - FormatMessage((FORMAT_MESSAGE_IGNORE_INSERTS | - FORMAT_MESSAGE_FROM_SYSTEM), - NULL, GetLastError(), - MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), - errbuf_t, SDL_arraysize(errbuf), NULL); - WideCharToMultiByte(CP_ACP, 0, errbuf_t, -1, errbuf, 511, NULL, NULL); - loaderror = errbuf; - } - - SDL_free(name_t); - SDL_free(errbuf_t); - -#else /*if defined(WIN32)*/ - char errbuf[512]; - - symbol = (void *)GetProcAddress((HMODULE)handle, name); - if ( symbol == NULL ) { - FormatMessage((FORMAT_MESSAGE_IGNORE_INSERTS | - FORMAT_MESSAGE_FROM_SYSTEM), - NULL, GetLastError(), - MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), - errbuf, SDL_arraysize(errbuf), NULL); - loaderror = errbuf; - } + char errbuf[512]; + int length = SDL_strlen(name); + + wchar_t *name_t = SDL_malloc((length + 1) * sizeof(wchar_t)); + wchar_t *errbuf_t = SDL_malloc(512 * sizeof(wchar_t)); + + MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, name, -1, name_t, length); + + symbol = (void *) GetProcAddress((HMODULE) handle, name_t); + if (symbol == NULL) { + FormatMessage((FORMAT_MESSAGE_IGNORE_INSERTS | + FORMAT_MESSAGE_FROM_SYSTEM), + NULL, GetLastError(), + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), + errbuf_t, SDL_arraysize(errbuf), NULL); + WideCharToMultiByte(CP_ACP, 0, errbuf_t, -1, errbuf, 511, NULL, NULL); + loaderror = errbuf; + } + + SDL_free(name_t); + SDL_free(errbuf_t); + +#else /*if defined(WIN32) */ + char errbuf[512]; + + symbol = (void *) GetProcAddress((HMODULE) handle, name); + if (symbol == NULL) { + FormatMessage((FORMAT_MESSAGE_IGNORE_INSERTS | + FORMAT_MESSAGE_FROM_SYSTEM), + NULL, GetLastError(), + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), + errbuf, SDL_arraysize(errbuf), NULL); + loaderror = errbuf; + } #endif - if ( symbol == NULL ) { - SDL_SetError("Failed loading %s: %s", name, loaderror); - } - return(symbol); + if (symbol == NULL) { + SDL_SetError("Failed loading %s: %s", name, loaderror); + } + return (symbol); } -void SDL_UnloadObject(void *handle) +void +SDL_UnloadObject(void *handle) { - if ( handle != NULL ) { - FreeLibrary((HMODULE)handle); - } + if (handle != NULL) { + FreeLibrary((HMODULE) handle); + } } #endif /* SDL_LOADSO_WIN32 */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/main/beos/SDL_BeApp.cc b/src/main/beos/SDL_BeApp.cc index 96268cc16..02df93e7b 100644 --- a/src/main/beos/SDL_BeApp.cc +++ b/src/main/beos/SDL_BeApp.cc @@ -37,73 +37,79 @@ int SDL_BeAppActive = 0; static SDL_Thread *SDL_AppThread = NULL; -static int StartBeApp(void *unused) +static int +StartBeApp(void *unused) { - BApplication *App; + BApplication *App; - App = new BApplication("application/x-SDL-executable"); + App = new BApplication("application/x-SDL-executable"); - App->Run(); - delete App; - return(0); + App->Run(); + delete App; + return (0); } /* Initialize the Be Application, if it's not already started */ -int SDL_InitBeApp(void) +int +SDL_InitBeApp(void) { - /* Create the BApplication that handles appserver interaction */ - if ( SDL_BeAppActive <= 0 ) { - SDL_AppThread = SDL_CreateThread(StartBeApp, NULL); - if ( SDL_AppThread == NULL ) { - SDL_SetError("Couldn't create BApplication thread"); - return(-1); - } - - /* Change working to directory to that of executable */ - app_info info; - if (B_OK == be_app->GetAppInfo(&info)) { - entry_ref ref = info.ref; - BEntry entry; - if (B_OK == entry.SetTo(&ref)) { - BPath path; - if (B_OK == path.SetTo(&entry)) { - if (B_OK == path.GetParent(&path)) { - chdir(path.Path()); - } - } - } - } - - do { - SDL_Delay(10); - } while ( (be_app == NULL) || be_app->IsLaunching() ); - - /* Mark the application active */ - SDL_BeAppActive = 0; - } - - /* Increment the application reference count */ - ++SDL_BeAppActive; - - /* The app is running, and we're ready to go */ - return(0); + /* Create the BApplication that handles appserver interaction */ + if (SDL_BeAppActive <= 0) { + SDL_AppThread = SDL_CreateThread(StartBeApp, NULL); + if (SDL_AppThread == NULL) { + SDL_SetError("Couldn't create BApplication thread"); + return (-1); + } + + /* Change working to directory to that of executable */ + app_info info; + if (B_OK == be_app->GetAppInfo(&info)) { + entry_ref ref = info.ref; + BEntry entry; + if (B_OK == entry.SetTo(&ref)) { + BPath path; + if (B_OK == path.SetTo(&entry)) { + if (B_OK == path.GetParent(&path)) { + chdir(path.Path()); + } + } + } + } + + do { + SDL_Delay(10); + } + while ((be_app == NULL) || be_app->IsLaunching()); + + /* Mark the application active */ + SDL_BeAppActive = 0; + } + + /* Increment the application reference count */ + ++SDL_BeAppActive; + + /* The app is running, and we're ready to go */ + return (0); } /* Quit the Be Application, if there's nothing left to do */ -void SDL_QuitBeApp(void) +void +SDL_QuitBeApp(void) { - /* Decrement the application reference count */ - --SDL_BeAppActive; - - /* If the reference count reached zero, clean up the app */ - if ( SDL_BeAppActive == 0 ) { - if ( SDL_AppThread != NULL ) { - if ( be_app != NULL ) { /* Not tested */ - be_app->PostMessage(B_QUIT_REQUESTED); - } - SDL_WaitThread(SDL_AppThread, NULL); - SDL_AppThread = NULL; - } - /* be_app should now be NULL since be_app has quit */ - } + /* Decrement the application reference count */ + --SDL_BeAppActive; + + /* If the reference count reached zero, clean up the app */ + if (SDL_BeAppActive == 0) { + if (SDL_AppThread != NULL) { + if (be_app != NULL) { /* Not tested */ + be_app->PostMessage(B_QUIT_REQUESTED); + } + SDL_WaitThread(SDL_AppThread, NULL); + SDL_AppThread = NULL; + } + /* be_app should now be NULL since be_app has quit */ + } } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/main/beos/SDL_BeApp.h b/src/main/beos/SDL_BeApp.h index f55dc1d80..8d047876e 100644 --- a/src/main/beos/SDL_BeApp.h +++ b/src/main/beos/SDL_BeApp.h @@ -31,3 +31,4 @@ extern void SDL_QuitBeApp(void); /* Flag to tell whether the app is active or not */ extern int SDL_BeAppActive; +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/main/dummy/SDL_dummy_main.c b/src/main/dummy/SDL_dummy_main.c index da47d06a8..53a93d174 100644 --- a/src/main/dummy/SDL_dummy_main.c +++ b/src/main/dummy/SDL_dummy_main.c @@ -4,10 +4,12 @@ #ifdef main #undef main -int main(int argc, char *argv[]) +int +main(int argc, char *argv[]) { - return(SDL_main(argc, argv)); + return (SDL_main(argc, argv)); } #else /* Nothing to do on this platform */ #endif +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/main/macos/SDL_main.c b/src/main/macos/SDL_main.c index 348638b0d..8f121bb0c 100644 --- a/src/main/macos/SDL_main.c +++ b/src/main/macos/SDL_main.c @@ -50,561 +50,598 @@ #endif #if !defined(__MWERKS__) && !TARGET_API_MAC_CARBON - /* In MPW, the qd global has been removed from the libraries */ - QDGlobals qd; + /* In MPW, the qd global has been removed from the libraries */ +QDGlobals qd; #endif /* Structure for keeping prefs in 1 variable */ -typedef struct { - Str255 command_line; - Str255 video_driver_name; +typedef struct +{ + Str255 command_line; + Str255 video_driver_name; Boolean output_to_file; -} PrefsRecord; +} PrefsRecord; /* See if the command key is held down at startup */ -static Boolean CommandKeyIsDown(void) +static Boolean +CommandKeyIsDown(void) { - KeyMap theKeyMap; + KeyMap theKeyMap; - GetKeys(theKeyMap); + GetKeys(theKeyMap); - if (((unsigned char *) theKeyMap)[6] & 0x80) { - return(true); - } - return(false); + if (((unsigned char *) theKeyMap)[6] & 0x80) { + return (true); + } + return (false); } #if !(defined(__APPLE__) && defined(__MACH__)) /* Parse a command line buffer into arguments */ -static int ParseCommandLine(char *cmdline, char **argv) +static int +ParseCommandLine(char *cmdline, char **argv) { - char *bufp; - int argc; - - argc = 0; - for ( bufp = cmdline; *bufp; ) { - /* Skip leading whitespace */ - while ( SDL_isspace(*bufp) ) { - ++bufp; - } - /* Skip over argument */ - if ( *bufp == '"' ) { - ++bufp; - if ( *bufp ) { - if ( argv ) { - argv[argc] = bufp; - } - ++argc; - } - /* Skip over word */ - while ( *bufp && (*bufp != '"') ) { - ++bufp; - } - } else { - if ( *bufp ) { - if ( argv ) { - argv[argc] = bufp; - } - ++argc; - } - /* Skip over word */ - while ( *bufp && ! SDL_isspace(*bufp) ) { - ++bufp; - } - } - if ( *bufp ) { - if ( argv ) { - *bufp = '\0'; - } - ++bufp; - } - } - if ( argv ) { - argv[argc] = NULL; - } - return(argc); + char *bufp; + int argc; + + argc = 0; + for (bufp = cmdline; *bufp;) { + /* Skip leading whitespace */ + while (SDL_isspace(*bufp)) { + ++bufp; + } + /* Skip over argument */ + if (*bufp == '"') { + ++bufp; + if (*bufp) { + if (argv) { + argv[argc] = bufp; + } + ++argc; + } + /* Skip over word */ + while (*bufp && (*bufp != '"')) { + ++bufp; + } + } else { + if (*bufp) { + if (argv) { + argv[argc] = bufp; + } + ++argc; + } + /* Skip over word */ + while (*bufp && !SDL_isspace(*bufp)) { + ++bufp; + } + } + if (*bufp) { + if (argv) { + *bufp = '\0'; + } + ++bufp; + } + } + if (argv) { + argv[argc] = NULL; + } + return (argc); } /* Remove the output files if there was no output written */ -static void cleanup_output(void) +static void +cleanup_output(void) { - FILE *file; - int empty; - - /* Flush the output in case anything is queued */ - fclose(stdout); - fclose(stderr); - - /* See if the files have any output in them */ - file = fopen(STDOUT_FILE, "rb"); - if ( file ) { - empty = (fgetc(file) == EOF) ? 1 : 0; - fclose(file); - if ( empty ) { - remove(STDOUT_FILE); - } - } - file = fopen(STDERR_FILE, "rb"); - if ( file ) { - empty = (fgetc(file) == EOF) ? 1 : 0; - fclose(file); - if ( empty ) { - remove(STDERR_FILE); - } - } + FILE *file; + int empty; + + /* Flush the output in case anything is queued */ + fclose(stdout); + fclose(stderr); + + /* See if the files have any output in them */ + file = fopen(STDOUT_FILE, "rb"); + if (file) { + empty = (fgetc(file) == EOF) ? 1 : 0; + fclose(file); + if (empty) { + remove(STDOUT_FILE); + } + } + file = fopen(STDERR_FILE, "rb"); + if (file) { + empty = (fgetc(file) == EOF) ? 1 : 0; + fclose(file); + if (empty) { + remove(STDERR_FILE); + } + } } #endif //!(defined(__APPLE__) && defined(__MACH__)) -static int getCurrentAppName (StrFileName name) { - +static int +getCurrentAppName(StrFileName name) +{ + ProcessSerialNumber process; - ProcessInfoRec process_info; - FSSpec process_fsp; - + ProcessInfoRec process_info; + FSSpec process_fsp; + process.highLongOfPSN = 0; - process.lowLongOfPSN = kCurrentProcess; - process_info.processInfoLength = sizeof (process_info); - process_info.processName = NULL; + process.lowLongOfPSN = kCurrentProcess; + process_info.processInfoLength = sizeof(process_info); + process_info.processName = NULL; process_info.processAppSpec = &process_fsp; - - if ( noErr != GetProcessInformation (&process, &process_info) ) - return 0; - + + if (noErr != GetProcessInformation(&process, &process_info)) + return 0; + SDL_memcpy(name, process_fsp.name, process_fsp.name[0] + 1); return 1; } -static int getPrefsFile (FSSpec *prefs_fsp, int create) { +static int +getPrefsFile(FSSpec * prefs_fsp, int create) +{ /* The prefs file name is the application name, possibly truncated, */ /* plus " Preferences */ - - #define SUFFIX " Preferences" - #define MAX_NAME 19 /* 31 - strlen (SUFFIX) */ - - short volume_ref_number; - long directory_id; - StrFileName prefs_name; - StrFileName app_name; - + +#define SUFFIX " Preferences" +#define MAX_NAME 19 /* 31 - strlen (SUFFIX) */ + + short volume_ref_number; + long directory_id; + StrFileName prefs_name; + StrFileName app_name; + /* Get Preferences folder - works with Multiple Users */ - if ( noErr != FindFolder ( kOnSystemDisk, kPreferencesFolderType, kDontCreateFolder, - &volume_ref_number, &directory_id) ) - exit (-1); - - if ( ! getCurrentAppName (app_name) ) - exit (-1); - + if (noErr != + FindFolder(kOnSystemDisk, kPreferencesFolderType, kDontCreateFolder, + &volume_ref_number, &directory_id)) + exit(-1); + + if (!getCurrentAppName(app_name)) + exit(-1); + /* Truncate if name is too long */ - if (app_name[0] > MAX_NAME ) + if (app_name[0] > MAX_NAME) app_name[0] = MAX_NAME; - - SDL_memcpy(prefs_name + 1, app_name + 1, app_name[0]); - SDL_memcpy(prefs_name + app_name[0] + 1, SUFFIX, strlen (SUFFIX)); - prefs_name[0] = app_name[0] + strlen (SUFFIX); - + + SDL_memcpy(prefs_name + 1, app_name + 1, app_name[0]); + SDL_memcpy(prefs_name + app_name[0] + 1, SUFFIX, strlen(SUFFIX)); + prefs_name[0] = app_name[0] + strlen(SUFFIX); + /* Make the file spec for prefs file */ - if ( noErr != FSMakeFSSpec (volume_ref_number, directory_id, prefs_name, prefs_fsp) ) { - if ( !create ) + if (noErr != + FSMakeFSSpec(volume_ref_number, directory_id, prefs_name, prefs_fsp)) + { + if (!create) return 0; else { /* Create the prefs file */ SDL_memcpy(prefs_fsp->name, prefs_name, prefs_name[0] + 1); - prefs_fsp->parID = directory_id; + prefs_fsp->parID = directory_id; prefs_fsp->vRefNum = volume_ref_number; - - FSpCreateResFile (prefs_fsp, 0x3f3f3f3f, 'pref', 0); // '????' parsed as trigraph - - if ( noErr != ResError () ) + + FSpCreateResFile(prefs_fsp, 0x3f3f3f3f, 'pref', 0); // '????' parsed as trigraph + + if (noErr != ResError()) return 0; } - } + } return 1; } -static int readPrefsResource (PrefsRecord *prefs) { - +static int +readPrefsResource(PrefsRecord * prefs) +{ + Handle prefs_handle; - - prefs_handle = Get1Resource( 'CLne', 128 ); - - if (prefs_handle != NULL) { - int offset = 0; -// int j = 0; - - HLock(prefs_handle); - - /* Get command line string */ - SDL_memcpy(prefs->command_line, *prefs_handle, (*prefs_handle)[0]+1); - - /* Get video driver name */ - offset += (*prefs_handle)[0] + 1; - SDL_memcpy(prefs->video_driver_name, *prefs_handle + offset, (*prefs_handle)[offset] + 1); - - /* Get save-to-file option (1 or 0) */ - offset += (*prefs_handle)[offset] + 1; - prefs->output_to_file = (*prefs_handle)[offset]; - - ReleaseResource( prefs_handle ); - + + prefs_handle = Get1Resource('CLne', 128); + + if (prefs_handle != NULL) { + int offset = 0; +// int j = 0; + + HLock(prefs_handle); + + /* Get command line string */ + SDL_memcpy(prefs->command_line, *prefs_handle, + (*prefs_handle)[0] + 1); + + /* Get video driver name */ + offset += (*prefs_handle)[0] + 1; + SDL_memcpy(prefs->video_driver_name, *prefs_handle + offset, + (*prefs_handle)[offset] + 1); + + /* Get save-to-file option (1 or 0) */ + offset += (*prefs_handle)[offset] + 1; + prefs->output_to_file = (*prefs_handle)[offset]; + + ReleaseResource(prefs_handle); + return ResError() == noErr; } return 0; } -static int writePrefsResource (PrefsRecord *prefs, short resource_file) { +static int +writePrefsResource(PrefsRecord * prefs, short resource_file) +{ Handle prefs_handle; - - UseResFile (resource_file); - - prefs_handle = Get1Resource ( 'CLne', 128 ); + + UseResFile(resource_file); + + prefs_handle = Get1Resource('CLne', 128); if (prefs_handle != NULL) - RemoveResource (prefs_handle); - - prefs_handle = NewHandle ( prefs->command_line[0] + prefs->video_driver_name[0] + 4 ); + RemoveResource(prefs_handle); + + prefs_handle = + NewHandle(prefs->command_line[0] + prefs->video_driver_name[0] + 4); if (prefs_handle != NULL) { - + int offset; - - HLock (prefs_handle); - + + HLock(prefs_handle); + /* Command line text */ offset = 0; - SDL_memcpy(*prefs_handle, prefs->command_line, prefs->command_line[0] + 1); - + SDL_memcpy(*prefs_handle, prefs->command_line, + prefs->command_line[0] + 1); + /* Video driver name */ offset += prefs->command_line[0] + 1; - SDL_memcpy(*prefs_handle + offset, prefs->video_driver_name, prefs->video_driver_name[0] + 1); - + SDL_memcpy(*prefs_handle + offset, prefs->video_driver_name, + prefs->video_driver_name[0] + 1); + /* Output-to-file option */ offset += prefs->video_driver_name[0] + 1; - *( *((char**)prefs_handle) + offset) = (char)prefs->output_to_file; - *( *((char**)prefs_handle) + offset + 1) = 0; - - AddResource (prefs_handle, 'CLne', 128, "\pCommand Line"); - WriteResource (prefs_handle); - UpdateResFile (resource_file); - DisposeHandle (prefs_handle); - + *(*((char **) prefs_handle) + offset) = (char) prefs->output_to_file; + *(*((char **) prefs_handle) + offset + 1) = 0; + + AddResource(prefs_handle, 'CLne', 128, "\pCommand Line"); + WriteResource(prefs_handle); + UpdateResFile(resource_file); + DisposeHandle(prefs_handle); + return ResError() == noErr; } - + return 0; } -static int readPreferences (PrefsRecord *prefs) { +static int +readPreferences(PrefsRecord * prefs) +{ - int no_error = 1; + int no_error = 1; FSSpec prefs_fsp; /* Check for prefs file first */ - if ( getPrefsFile (&prefs_fsp, 0) ) { - - short prefs_resource; - - prefs_resource = FSpOpenResFile (&prefs_fsp, fsRdPerm); - if ( prefs_resource == -1 ) /* this shouldn't happen, but... */ + if (getPrefsFile(&prefs_fsp, 0)) { + + short prefs_resource; + + prefs_resource = FSpOpenResFile(&prefs_fsp, fsRdPerm); + if (prefs_resource == -1) /* this shouldn't happen, but... */ return 0; - - UseResFile (prefs_resource); - no_error = readPrefsResource (prefs); - CloseResFile (prefs_resource); + + UseResFile(prefs_resource); + no_error = readPrefsResource(prefs); + CloseResFile(prefs_resource); } - + /* Fall back to application's resource fork (reading only, so this is safe) */ else { - - no_error = readPrefsResource (prefs); - } + + no_error = readPrefsResource(prefs); + } return no_error; } -static int writePreferences (PrefsRecord *prefs) { - - int no_error = 1; +static int +writePreferences(PrefsRecord * prefs) +{ + + int no_error = 1; FSSpec prefs_fsp; - + /* Get prefs file, create if it doesn't exist */ - if ( getPrefsFile (&prefs_fsp, 1) ) { - - short prefs_resource; - - prefs_resource = FSpOpenResFile (&prefs_fsp, fsRdWrPerm); + if (getPrefsFile(&prefs_fsp, 1)) { + + short prefs_resource; + + prefs_resource = FSpOpenResFile(&prefs_fsp, fsRdWrPerm); if (prefs_resource == -1) return 0; - no_error = writePrefsResource (prefs, prefs_resource); - CloseResFile (prefs_resource); + no_error = writePrefsResource(prefs, prefs_resource); + CloseResFile(prefs_resource); } - + return no_error; } /* This is where execution begins */ -int main(int argc, char *argv[]) +int +main(int argc, char *argv[]) { #if !(defined(__APPLE__) && defined(__MACH__)) #pragma unused(argc, argv) #endif - -#define DEFAULT_ARGS "\p" /* pascal string for default args */ -#define DEFAULT_VIDEO_DRIVER "\ptoolbox" /* pascal string for default video driver name */ -#define DEFAULT_OUTPUT_TO_FILE 1 /* 1 == output to file, 0 == no output */ -#define VIDEO_ID_DRAWSPROCKET 1 /* these correspond to popup menu choices */ +#define DEFAULT_ARGS "\p" /* pascal string for default args */ +#define DEFAULT_VIDEO_DRIVER "\ptoolbox" /* pascal string for default video driver name */ +#define DEFAULT_OUTPUT_TO_FILE 1 /* 1 == output to file, 0 == no output */ + +#define VIDEO_ID_DRAWSPROCKET 1 /* these correspond to popup menu choices */ #define VIDEO_ID_TOOLBOX 2 - PrefsRecord prefs = { DEFAULT_ARGS, DEFAULT_VIDEO_DRIVER, DEFAULT_OUTPUT_TO_FILE }; - + PrefsRecord prefs = + { DEFAULT_ARGS, DEFAULT_VIDEO_DRIVER, DEFAULT_OUTPUT_TO_FILE }; + #if !(defined(__APPLE__) && defined(__MACH__)) - int nargs; - char **args; - char *commandLine; - - StrFileName appNameText; + int nargs; + char **args; + char *commandLine; + + StrFileName appNameText; #endif - int videodriver = VIDEO_ID_TOOLBOX; - int settingsChanged = 0; - - long i; + int videodriver = VIDEO_ID_TOOLBOX; + int settingsChanged = 0; - /* Kyle's SDL command-line dialog code ... */ + long i; + + /* Kyle's SDL command-line dialog code ... */ #if !TARGET_API_MAC_CARBON - InitGraf (&qd.thePort); - InitFonts (); - InitWindows (); - InitMenus (); - InitDialogs (nil); + InitGraf(&qd.thePort); + InitFonts(); + InitWindows(); + InitMenus(); + InitDialogs(nil); #endif - InitCursor (); - FlushEvents(everyEvent,0); + InitCursor(); + FlushEvents(everyEvent, 0); #if !TARGET_API_MAC_CARBON - MaxApplZone (); + MaxApplZone(); #endif - MoreMasters (); - MoreMasters (); + MoreMasters(); + MoreMasters(); #if 0 - /* Intialize SDL, and put up a dialog if we fail */ - if ( SDL_Init (0) < 0 ) { + /* Intialize SDL, and put up a dialog if we fail */ + if (SDL_Init(0) < 0) { #define kErr_OK 1 #define kErr_Text 2 DialogPtr errorDialog; - short dummyType; - Rect dummyRect; - Handle dummyHandle; - short itemHit; - - errorDialog = GetNewDialog (1001, nil, (WindowPtr)-1); - if (errorDialog == NULL) - return -1; - DrawDialog (errorDialog); - - GetDialogItem (errorDialog, kErr_Text, &dummyType, &dummyHandle, &dummyRect); - SetDialogItemText (dummyHandle, "\pError Initializing SDL"); - + short dummyType; + Rect dummyRect; + Handle dummyHandle; + short itemHit; + + errorDialog = GetNewDialog(1001, nil, (WindowPtr) - 1); + if (errorDialog == NULL) + return -1; + DrawDialog(errorDialog); + + GetDialogItem(errorDialog, kErr_Text, &dummyType, &dummyHandle, + &dummyRect); + SetDialogItemText(dummyHandle, "\pError Initializing SDL"); + #if TARGET_API_MAC_CARBON - SetPort (GetDialogPort(errorDialog)); + SetPort(GetDialogPort(errorDialog)); #else - SetPort (errorDialog); + SetPort(errorDialog); #endif - do { - ModalDialog (nil, &itemHit); - } while (itemHit != kErr_OK); - - DisposeDialog (errorDialog); - exit (-1); - } - atexit(cleanup_output); - atexit(SDL_Quit); + do { + ModalDialog(nil, &itemHit); + } + while (itemHit != kErr_OK); + + DisposeDialog(errorDialog); + exit(-1); + } + atexit(cleanup_output); + atexit(SDL_Quit); #endif /* Set up SDL's QuickDraw environment */ #if !TARGET_API_MAC_CARBON - SDL_InitQuickDraw(&qd); + SDL_InitQuickDraw(&qd); #endif - if ( readPreferences (&prefs) ) { - - if (SDL_memcmp(prefs.video_driver_name+1, "DSp", 3) == 0) + if (readPreferences(&prefs)) { + + if (SDL_memcmp(prefs.video_driver_name + 1, "DSp", 3) == 0) videodriver = 1; - else if (SDL_memcmp(prefs.video_driver_name+1, "toolbox", 7) == 0) + else if (SDL_memcmp(prefs.video_driver_name + 1, "toolbox", 7) == 0) videodriver = 2; - } - - if ( CommandKeyIsDown() ) { + } + + if (CommandKeyIsDown()) { #define kCL_OK 1 #define kCL_Cancel 2 #define kCL_Text 3 #define kCL_File 4 #define kCL_Video 6 - + DialogPtr commandDialog; - short dummyType; - Rect dummyRect; - Handle dummyHandle; - short itemHit; - #if TARGET_API_MAC_CARBON + short dummyType; + Rect dummyRect; + Handle dummyHandle; + short itemHit; +#if TARGET_API_MAC_CARBON ControlRef control; - #endif - +#endif + /* Assume that they will change settings, rather than do exhaustive check */ settingsChanged = 1; - + /* Create dialog and display it */ - commandDialog = GetNewDialog (1000, nil, (WindowPtr)-1); - #if TARGET_API_MAC_CARBON - SetPort ( GetDialogPort(commandDialog) ); - #else - SetPort (commandDialog); - #endif - + commandDialog = GetNewDialog(1000, nil, (WindowPtr) - 1); +#if TARGET_API_MAC_CARBON + SetPort(GetDialogPort(commandDialog)); +#else + SetPort(commandDialog); +#endif + /* Setup controls */ - #if TARGET_API_MAC_CARBON +#if TARGET_API_MAC_CARBON GetDialogItemAsControl(commandDialog, kCL_File, &control); - SetControlValue (control, prefs.output_to_file); - #else - GetDialogItem (commandDialog, kCL_File, &dummyType, &dummyHandle, &dummyRect); /* MJS */ - SetControlValue ((ControlHandle)dummyHandle, prefs.output_to_file ); - #endif + SetControlValue(control, prefs.output_to_file); +#else + GetDialogItem(commandDialog, kCL_File, &dummyType, &dummyHandle, &dummyRect); /* MJS */ + SetControlValue((ControlHandle) dummyHandle, prefs.output_to_file); +#endif - GetDialogItem (commandDialog, kCL_Text, &dummyType, &dummyHandle, &dummyRect); - SetDialogItemText (dummyHandle, prefs.command_line); + GetDialogItem(commandDialog, kCL_Text, &dummyType, &dummyHandle, + &dummyRect); + SetDialogItemText(dummyHandle, prefs.command_line); - #if TARGET_API_MAC_CARBON +#if TARGET_API_MAC_CARBON GetDialogItemAsControl(commandDialog, kCL_Video, &control); - SetControlValue (control, videodriver); - #else - GetDialogItem (commandDialog, kCL_Video, &dummyType, &dummyHandle, &dummyRect); - SetControlValue ((ControlRef)dummyHandle, videodriver); - #endif + SetControlValue(control, videodriver); +#else + GetDialogItem(commandDialog, kCL_Video, &dummyType, &dummyHandle, + &dummyRect); + SetControlValue((ControlRef) dummyHandle, videodriver); +#endif - SetDialogDefaultItem (commandDialog, kCL_OK); - SetDialogCancelItem (commandDialog, kCL_Cancel); + SetDialogDefaultItem(commandDialog, kCL_OK); + SetDialogCancelItem(commandDialog, kCL_Cancel); do { - - ModalDialog(nil, &itemHit); /* wait for user response */ - - /* Toggle command-line output checkbox */ - if ( itemHit == kCL_File ) { - #if TARGET_API_MAC_CARBON - GetDialogItemAsControl(commandDialog, kCL_File, &control); - SetControlValue (control, !GetControlValue(control)); - #else - GetDialogItem(commandDialog, kCL_File, &dummyType, &dummyHandle, &dummyRect); /* MJS */ - SetControlValue((ControlHandle)dummyHandle, !GetControlValue((ControlHandle)dummyHandle) ); - #endif - } - - } while (itemHit != kCL_OK && itemHit != kCL_Cancel); + + ModalDialog(nil, &itemHit); /* wait for user response */ + + /* Toggle command-line output checkbox */ + if (itemHit == kCL_File) { +#if TARGET_API_MAC_CARBON + GetDialogItemAsControl(commandDialog, kCL_File, &control); + SetControlValue(control, !GetControlValue(control)); +#else + GetDialogItem(commandDialog, kCL_File, &dummyType, &dummyHandle, &dummyRect); /* MJS */ + SetControlValue((ControlHandle) dummyHandle, + !GetControlValue((ControlHandle) + dummyHandle)); +#endif + } + + } + while (itemHit != kCL_OK && itemHit != kCL_Cancel); /* Get control values, even if they did not change */ - GetDialogItem (commandDialog, kCL_Text, &dummyType, &dummyHandle, &dummyRect); /* MJS */ - GetDialogItemText (dummyHandle, prefs.command_line); + GetDialogItem(commandDialog, kCL_Text, &dummyType, &dummyHandle, &dummyRect); /* MJS */ + GetDialogItemText(dummyHandle, prefs.command_line); - #if TARGET_API_MAC_CARBON +#if TARGET_API_MAC_CARBON GetDialogItemAsControl(commandDialog, kCL_File, &control); prefs.output_to_file = GetControlValue(control); - #else - GetDialogItem (commandDialog, kCL_File, &dummyType, &dummyHandle, &dummyRect); /* MJS */ - prefs.output_to_file = GetControlValue ((ControlHandle)dummyHandle); - #endif +#else + GetDialogItem(commandDialog, kCL_File, &dummyType, &dummyHandle, &dummyRect); /* MJS */ + prefs.output_to_file = GetControlValue((ControlHandle) dummyHandle); +#endif - #if TARGET_API_MAC_CARBON +#if TARGET_API_MAC_CARBON GetDialogItemAsControl(commandDialog, kCL_Video, &control); videodriver = GetControlValue(control); - #else - GetDialogItem (commandDialog, kCL_Video, &dummyType, &dummyHandle, &dummyRect); - videodriver = GetControlValue ((ControlRef)dummyHandle); - #endif +#else + GetDialogItem(commandDialog, kCL_Video, &dummyType, &dummyHandle, + &dummyRect); + videodriver = GetControlValue((ControlRef) dummyHandle); +#endif - DisposeDialog (commandDialog); + DisposeDialog(commandDialog); - if (itemHit == kCL_Cancel ) { - exit (0); + if (itemHit == kCL_Cancel) { + exit(0); } - } - + } + /* Set pseudo-environment variables for video driver, update prefs */ - switch ( videodriver ) { - case VIDEO_ID_DRAWSPROCKET: - SDL_putenv("SDL_VIDEODRIVER=DSp"); - SDL_memcpy(prefs.video_driver_name, "\pDSp", 4); - break; - case VIDEO_ID_TOOLBOX: - SDL_putenv("SDL_VIDEODRIVER=toolbox"); - SDL_memcpy(prefs.video_driver_name, "\ptoolbox", 8); - break; - } + switch (videodriver) { + case VIDEO_ID_DRAWSPROCKET: + SDL_putenv("SDL_VIDEODRIVER=DSp"); + SDL_memcpy(prefs.video_driver_name, "\pDSp", 4); + break; + case VIDEO_ID_TOOLBOX: + SDL_putenv("SDL_VIDEODRIVER=toolbox"); + SDL_memcpy(prefs.video_driver_name, "\ptoolbox", 8); + break; + } #if !(defined(__APPLE__) && defined(__MACH__)) /* Redirect standard I/O to files */ - if ( prefs.output_to_file ) { - freopen (STDOUT_FILE, "w", stdout); - freopen (STDERR_FILE, "w", stderr); - } else { - fclose (stdout); - fclose (stderr); - } + if (prefs.output_to_file) { + freopen(STDOUT_FILE, "w", stdout); + freopen(STDERR_FILE, "w", stderr); + } else { + fclose(stdout); + fclose(stderr); + } #endif - + if (settingsChanged) { /* Save the prefs, even if they might not have changed (but probably did) */ - if ( ! writePreferences (&prefs) ) - fprintf (stderr, "WARNING: Could not save preferences!\n"); + if (!writePreferences(&prefs)) + fprintf(stderr, "WARNING: Could not save preferences!\n"); } - #if !(defined(__APPLE__) && defined(__MACH__)) appNameText[0] = 0; - getCurrentAppName (appNameText); /* check for error here ? */ + getCurrentAppName(appNameText); /* check for error here ? */ - commandLine = (char*) malloc (appNameText[0] + prefs.command_line[0] + 2); - if ( commandLine == NULL ) { - exit(-1); + commandLine = (char *) malloc(appNameText[0] + prefs.command_line[0] + 2); + if (commandLine == NULL) { + exit(-1); } /* Rather than rewrite ParseCommandLine method, let's replace */ /* any spaces in application name with underscores, */ - /* so that the app name is only 1 argument */ - for (i = 1; i < 1+appNameText[0]; i++) - if ( appNameText[i] == ' ' ) appNameText[i] = '_'; + /* so that the app name is only 1 argument */ + for (i = 1; i < 1 + appNameText[0]; i++) + if (appNameText[i] == ' ') + appNameText[i] = '_'; - /* Copy app name & full command text to command-line C-string */ + /* Copy app name & full command text to command-line C-string */ SDL_memcpy(commandLine, appNameText + 1, appNameText[0]); commandLine[appNameText[0]] = ' '; - SDL_memcpy(commandLine + appNameText[0] + 1, prefs.command_line + 1, prefs.command_line[0]); - commandLine[ appNameText[0] + 1 + prefs.command_line[0] ] = '\0'; + SDL_memcpy(commandLine + appNameText[0] + 1, prefs.command_line + 1, + prefs.command_line[0]); + commandLine[appNameText[0] + 1 + prefs.command_line[0]] = '\0'; /* Parse C-string into argv and argc */ - nargs = ParseCommandLine (commandLine, NULL); - args = (char **)malloc((nargs+1)*(sizeof *args)); - if ( args == NULL ) { - exit(-1); - } - ParseCommandLine (commandLine, args); - - /* Run the main application code */ - SDL_main(nargs, args); - free (args); - free (commandLine); - - /* Remove useless stdout.txt and stderr.txt */ - cleanup_output (); + nargs = ParseCommandLine(commandLine, NULL); + args = (char **) malloc((nargs + 1) * (sizeof *args)); + if (args == NULL) { + exit(-1); + } + ParseCommandLine(commandLine, args); + + /* Run the main application code */ + SDL_main(nargs, args); + free(args); + free(commandLine); + + /* Remove useless stdout.txt and stderr.txt */ + cleanup_output(); #else // defined(__APPLE__) && defined(__MACH__) - SDL_main(argc, argv); + SDL_main(argc, argv); #endif - - /* Exit cleanly, calling atexit() functions */ - exit (0); - /* Never reached, but keeps the compiler quiet */ - return (0); + /* Exit cleanly, calling atexit() functions */ + exit(0); + + /* Never reached, but keeps the compiler quiet */ + return (0); } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/main/macos/exports/SDL.x b/src/main/macos/exports/SDL.x index 44db7a48e..388bf1dc8 100644 --- a/src/main/macos/exports/SDL.x +++ b/src/main/macos/exports/SDL.x @@ -178,9 +178,6 @@ SDL_GL_SetAttribute SDL_GL_GetAttribute SDL_GL_SwapBuffers - SDL_GL_UpdateRects - SDL_GL_Lock - SDL_GL_Unlock SDL_WM_SetCaption SDL_WM_GetCaption SDL_WM_SetIcon diff --git a/src/main/macosx/SDLMain.h b/src/main/macosx/SDLMain.h index 4683df57a..e0a9a826b 100644 --- a/src/main/macosx/SDLMain.h +++ b/src/main/macosx/SDLMain.h @@ -7,5 +7,5 @@ #import -@interface SDLMain : NSObject -@end +@ interface SDLMain:NSObject @ end +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/main/qtopia/SDL_qtopia_main.cc b/src/main/qtopia/SDL_qtopia_main.cc index 46fd518ff..a61a91aa6 100644 --- a/src/main/qtopia/SDL_qtopia_main.cc +++ b/src/main/qtopia/SDL_qtopia_main.cc @@ -16,14 +16,20 @@ // some issues in Qtopia where there are left-over qcop files in /tmp/. // I'm guessing this will also clean up the taskbar in the Sharp version // of Qtopia. -static inline void cleanupQCop() { - QString appname(qApp->argv()[0]); - int slash = appname.findRev("/"); - if(slash != -1) { appname = appname.mid(slash+1); } - QString cmd = QPEApplication::qpeDir() + "bin/qcop QPE/System 'closing(QString)' '"+appname+"'"; - system(cmd.latin1()); - cmd = "/tmp/qcop-msg-"+appname; - unlink(cmd.latin1()); +static inline void +cleanupQCop() +{ + QString appname(qApp->argv()[0]); + int slash = appname.findRev("/"); + if (slash != -1) { + appname = appname.mid(slash + 1); + } + QString cmd = + QPEApplication::qpeDir() + + "bin/qcop QPE/System 'closing(QString)' '" + appname + "'"; + system(cmd.latin1()); + cmd = "/tmp/qcop-msg-" + appname; + unlink(cmd.latin1()); } static QPEApplication *app; @@ -31,17 +37,20 @@ static QPEApplication *app; extern int SDL_main(int argc, char *argv[]); -int main(int argc, char *argv[]) +int +main(int argc, char *argv[]) { #ifdef QWS - // This initializes the Qtopia application. It needs to be done here - // because it parses command line options. - app = new QPEApplication(argc, argv); - QWidget dummy; - app->showMainWidget(&dummy); - atexit(cleanupQCop); + // This initializes the Qtopia application. It needs to be done here + // because it parses command line options. + app = new QPEApplication(argc, argv); + QWidget dummy; + app->showMainWidget(&dummy); + atexit(cleanupQCop); #endif - // Exit here because if return is used, the application - // doesn't seem to quit correctly. - exit(SDL_main(argc, argv)); + // Exit here because if return is used, the application + // doesn't seem to quit correctly. + exit(SDL_main(argc, argv)); } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/main/win32/SDL_win32_main.c b/src/main/win32/SDL_win32_main.c index d78708f33..16858a633 100644 --- a/src/main/win32/SDL_win32_main.c +++ b/src/main/win32/SDL_win32_main.c @@ -10,20 +10,6 @@ #define WIN32_LEAN_AND_MEAN #include -#ifdef _WIN32_WCE -# define DIR_SEPERATOR TEXT("\\") -# undef _getcwd -# define _getcwd(str,len) wcscpy(str,TEXT("")) -# define setbuf(f,b) -# define setvbuf(w,x,y,z) -# define fopen _wfopen -# define freopen _wfreopen -# define remove(x) DeleteFile(x) -#else -# define DIR_SEPERATOR TEXT("/") -# include -#endif - /* Include the SDL main definition header */ #include "SDL.h" #include "SDL_main.h" @@ -34,135 +20,80 @@ # endif /* _WIN32_WCE_EMULATION */ #endif /* main */ -/* The standard output files */ -#define STDOUT_FILE TEXT("stdout.txt") -#define STDERR_FILE TEXT("stderr.txt") - -#ifndef NO_STDIO_REDIRECT -# ifdef _WIN32_WCE - static wchar_t stdoutPath[MAX_PATH]; - static wchar_t stderrPath[MAX_PATH]; -# else - static char stdoutPath[MAX_PATH]; - static char stderrPath[MAX_PATH]; -# endif -#endif - #if defined(_WIN32_WCE) && _WIN32_WCE < 300 /* seems to be undefined in Win CE although in online help */ #define isspace(a) (((CHAR)a == ' ') || ((CHAR)a == '\t')) #endif /* _WIN32_WCE < 300 */ /* Parse a command line buffer into arguments */ -static int ParseCommandLine(char *cmdline, char **argv) +static int +ParseCommandLine(char *cmdline, char **argv) { - char *bufp; - int argc; - - argc = 0; - for ( bufp = cmdline; *bufp; ) { - /* Skip leading whitespace */ - while ( isspace(*bufp) ) { - ++bufp; - } - /* Skip over argument */ - if ( *bufp == '"' ) { - ++bufp; - if ( *bufp ) { - if ( argv ) { - argv[argc] = bufp; - } - ++argc; - } - /* Skip over word */ - while ( *bufp && (*bufp != '"') ) { - ++bufp; - } - } else { - if ( *bufp ) { - if ( argv ) { - argv[argc] = bufp; - } - ++argc; - } - /* Skip over word */ - while ( *bufp && ! isspace(*bufp) ) { - ++bufp; - } - } - if ( *bufp ) { - if ( argv ) { - *bufp = '\0'; - } - ++bufp; - } - } - if ( argv ) { - argv[argc] = NULL; - } - return(argc); + char *bufp; + int argc; + + argc = 0; + for (bufp = cmdline; *bufp;) { + /* Skip leading whitespace */ + while (isspace(*bufp)) { + ++bufp; + } + /* Skip over argument */ + if (*bufp == '"') { + ++bufp; + if (*bufp) { + if (argv) { + argv[argc] = bufp; + } + ++argc; + } + /* Skip over word */ + while (*bufp && (*bufp != '"')) { + ++bufp; + } + } else { + if (*bufp) { + if (argv) { + argv[argc] = bufp; + } + ++argc; + } + /* Skip over word */ + while (*bufp && !isspace(*bufp)) { + ++bufp; + } + } + if (*bufp) { + if (argv) { + *bufp = '\0'; + } + ++bufp; + } + } + if (argv) { + argv[argc] = NULL; + } + return (argc); } /* Show an error message */ -static void ShowError(const char *title, const char *message) +static void +ShowError(const char *title, const char *message) { /* If USE_MESSAGEBOX is defined, you need to link with user32.lib */ #ifdef USE_MESSAGEBOX - MessageBox(NULL, message, title, MB_ICONEXCLAMATION|MB_OK); + MessageBox(NULL, message, title, MB_ICONEXCLAMATION | MB_OK); #else - fprintf(stderr, "%s: %s\n", title, message); + fprintf(stderr, "%s: %s\n", title, message); #endif } /* Pop up an out of memory message, returns to Windows */ -static BOOL OutOfMemory(void) -{ - ShowError("Fatal Error", "Out of memory - aborting"); - return FALSE; -} - -/* SDL_Quit() shouldn't be used with atexit() directly because - calling conventions may differ... */ -static void cleanup(void) -{ - SDL_Quit(); -} - -/* Remove the output files if there was no output written */ -static void cleanup_output(void) +static BOOL +OutOfMemory(void) { -#ifndef NO_STDIO_REDIRECT - FILE *file; - int empty; -#endif - - /* Flush the output in case anything is queued */ - fclose(stdout); - fclose(stderr); - -#ifndef NO_STDIO_REDIRECT - /* See if the files have any output in them */ - if ( stdoutPath[0] ) { - file = fopen(stdoutPath, TEXT("rb")); - if ( file ) { - empty = (fgetc(file) == EOF) ? 1 : 0; - fclose(file); - if ( empty ) { - remove(stdoutPath); - } - } - } - if ( stderrPath[0] ) { - file = fopen(stderrPath, TEXT("rb")); - if ( file ) { - empty = (fgetc(file) == EOF) ? 1 : 0; - fclose(file); - if ( empty ) { - remove(stderrPath); - } - } - } -#endif + ShowError("Fatal Error", "Out of memory - aborting"); + return FALSE; } #if defined(_MSC_VER) && !defined(_WIN32_WCE) @@ -171,187 +102,73 @@ static void cleanup_output(void) #endif /* This is where execution begins [console apps] */ -int console_main(int argc, char *argv[]) +int +console_main(int argc, char *argv[]) { - size_t n; - char *bufp, *appname; - int status; + int status; - /* Get the class name from argv[0] */ - appname = argv[0]; - if ( (bufp=SDL_strrchr(argv[0], '\\')) != NULL ) { - appname = bufp+1; - } else - if ( (bufp=SDL_strrchr(argv[0], '/')) != NULL ) { - appname = bufp+1; - } + /* Run the application main() code */ + status = SDL_main(argc, argv); - if ( (bufp=SDL_strrchr(appname, '.')) == NULL ) - n = SDL_strlen(appname); - else - n = (bufp-appname); + /* Exit cleanly, calling atexit() functions */ + exit(status); - bufp = SDL_stack_alloc(char, n+1); - if ( bufp == NULL ) { - return OutOfMemory(); - } - SDL_strlcpy(bufp, appname, n+1); - appname = bufp; - - /* Load SDL dynamic link library */ - if ( SDL_Init(SDL_INIT_NOPARACHUTE) < 0 ) { - ShowError("WinMain() error", SDL_GetError()); - return(FALSE); - } - atexit(cleanup_output); - atexit(cleanup); - - /* Sam: - We still need to pass in the application handle so that - DirectInput will initialize properly when SDL_RegisterApp() - is called later in the video initialization. - */ - SDL_SetModuleHandle(GetModuleHandle(NULL)); - - /* Run the application main() code */ - status = SDL_main(argc, argv); - - /* Exit cleanly, calling atexit() functions */ - exit(status); - - /* Hush little compiler, don't you cry... */ - return 0; + /* Hush little compiler, don't you cry... */ + return 0; } /* This is where execution begins [windowed apps] */ -#ifdef _WIN32_WCE -int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPWSTR szCmdLine, int sw) -#else -int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR szCmdLine, int sw) -#endif +int WINAPI +WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPTSTR szCmdLine, int sw) { - HINSTANCE handle; - char **argv; - int argc; - char *cmdline; - DWORD pathlen; -#ifdef _WIN32_WCE - wchar_t path[MAX_PATH]; -#else - char path[MAX_PATH]; -#endif -#ifdef _WIN32_WCE - wchar_t *bufp; - int nLen; -#else - char *bufp; - size_t nLen; -#endif -#ifndef NO_STDIO_REDIRECT - FILE *newfp; -#endif - - /* Start up DDHELP.EXE before opening any files, so DDHELP doesn't - keep them open. This is a hack.. hopefully it will be fixed - someday. DDHELP.EXE starts up the first time DDRAW.DLL is loaded. - */ - handle = LoadLibrary(TEXT("DDRAW.DLL")); - if ( handle != NULL ) { - FreeLibrary(handle); - } - -#ifndef NO_STDIO_REDIRECT - pathlen = GetModuleFileName(NULL, path, SDL_arraysize(path)); - while ( pathlen > 0 && path[pathlen] != '\\' ) { - --pathlen; - } - path[pathlen] = '\0'; - + char **argv; + int argc; + char *cmdline; #ifdef _WIN32_WCE - wcsncpy( stdoutPath, path, SDL_arraysize(stdoutPath) ); - wcsncat( stdoutPath, DIR_SEPERATOR STDOUT_FILE, SDL_arraysize(stdoutPath) ); + wchar_t *bufp; + int nLen; #else - SDL_strlcpy( stdoutPath, path, SDL_arraysize(stdoutPath) ); - SDL_strlcat( stdoutPath, DIR_SEPERATOR STDOUT_FILE, SDL_arraysize(stdoutPath) ); + char *bufp; + size_t nLen; #endif - - /* Redirect standard input and standard output */ - newfp = freopen(stdoutPath, TEXT("w"), stdout); - -#ifndef _WIN32_WCE - if ( newfp == NULL ) { /* This happens on NT */ -#if !defined(stdout) - stdout = fopen(stdoutPath, TEXT("w")); -#else - newfp = fopen(stdoutPath, TEXT("w")); - if ( newfp ) { - *stdout = *newfp; - } -#endif - } -#endif /* _WIN32_WCE */ - -#ifdef _WIN32_WCE - wcsncpy( stderrPath, path, SDL_arraysize(stdoutPath) ); - wcsncat( stderrPath, DIR_SEPERATOR STDOUT_FILE, SDL_arraysize(stdoutPath) ); -#else - SDL_strlcpy( stderrPath, path, SDL_arraysize(stderrPath) ); - SDL_strlcat( stderrPath, DIR_SEPERATOR STDERR_FILE, SDL_arraysize(stderrPath) ); -#endif - - newfp = freopen(stderrPath, TEXT("w"), stderr); -#ifndef _WIN32_WCE - if ( newfp == NULL ) { /* This happens on NT */ -#if !defined(stderr) - stderr = fopen(stderrPath, TEXT("w")); -#else - newfp = fopen(stderrPath, TEXT("w")); - if ( newfp ) { - *stderr = *newfp; - } -#endif - } -#endif /* _WIN32_WCE */ - - setvbuf(stdout, NULL, _IOLBF, BUFSIZ); /* Line buffered */ - setbuf(stderr, NULL); /* No buffering */ -#endif /* !NO_STDIO_REDIRECT */ #ifdef _WIN32_WCE - nLen = wcslen(szCmdLine)+128+1; - bufp = SDL_stack_alloc(wchar_t, nLen*2); - wcscpy (bufp, TEXT("\"")); - GetModuleFileName(NULL, bufp+1, 128-3); - wcscpy (bufp+wcslen(bufp), TEXT("\" ")); - wcsncpy(bufp+wcslen(bufp), szCmdLine,nLen-wcslen(bufp)); - nLen = wcslen(bufp)+1; - cmdline = SDL_stack_alloc(char, nLen); - if ( cmdline == NULL ) { - return OutOfMemory(); - } - WideCharToMultiByte(CP_ACP, 0, bufp, -1, cmdline, nLen, NULL, NULL); + nLen = wcslen(szCmdLine) + 128 + 1; + bufp = SDL_stack_alloc(wchar_t, nLen * 2); + wcscpy(bufp, TEXT("\"")); + GetModuleFileName(NULL, bufp + 1, 128 - 3); + wcscpy(bufp + wcslen(bufp), TEXT("\" ")); + wcsncpy(bufp + wcslen(bufp), szCmdLine, nLen - wcslen(bufp)); + nLen = wcslen(bufp) + 1; + cmdline = SDL_stack_alloc(char, nLen); + if (cmdline == NULL) { + return OutOfMemory(); + } + WideCharToMultiByte(CP_ACP, 0, bufp, -1, cmdline, nLen, NULL, NULL); #else - /* Grab the command line */ - bufp = GetCommandLine(); - nLen = SDL_strlen(bufp)+1; - cmdline = SDL_stack_alloc(char, nLen); - if ( cmdline == NULL ) { - return OutOfMemory(); - } - SDL_strlcpy(cmdline, bufp, nLen); + /* Grab the command line */ + bufp = GetCommandLine(); + nLen = SDL_strlen(bufp) + 1; + cmdline = SDL_stack_alloc(char, nLen); + if (cmdline == NULL) { + return OutOfMemory(); + } + SDL_strlcpy(cmdline, bufp, nLen); #endif - /* Parse it into argv and argc */ - argc = ParseCommandLine(cmdline, NULL); - argv = SDL_stack_alloc(char*, argc+1); - if ( argv == NULL ) { - return OutOfMemory(); - } - ParseCommandLine(cmdline, argv); + /* Parse it into argv and argc */ + argc = ParseCommandLine(cmdline, NULL); + argv = SDL_stack_alloc(char *, argc + 1); + if (argv == NULL) { + return OutOfMemory(); + } + ParseCommandLine(cmdline, argv); - /* Run the main program (after a little SDL initialization) */ - console_main(argc, argv); + /* Run the main program */ + console_main(argc, argv); - /* Hush little compiler, don't you cry... */ - return 0; + /* Hush little compiler, don't you cry... */ + return 0; } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/stdlib/SDL_getenv.c b/src/stdlib/SDL_getenv.c index 74116cc97..c06af7fcd 100644 --- a/src/stdlib/SDL_getenv.c +++ b/src/stdlib/SDL_getenv.c @@ -32,143 +32,148 @@ /* Note this isn't thread-safe! */ -static char *SDL_envmem = NULL; /* Ugh, memory leak */ +static char *SDL_envmem = NULL; /* Ugh, memory leak */ static size_t SDL_envmemlen = 0; /* Put a variable of the form "name=value" into the environment */ -int SDL_putenv(const char *variable) +int +SDL_putenv(const char *variable) { - size_t bufferlen; - char *value; - const char *sep; - - sep = SDL_strchr(variable, '='); - if ( sep == NULL ) { - return -1; - } - bufferlen = SDL_strlen(variable)+1; - if ( bufferlen > SDL_envmemlen ) { - char *newmem = (char *)SDL_realloc(SDL_envmem, bufferlen); - if ( newmem == NULL ) { - return -1; - } - SDL_envmem = newmem; - SDL_envmemlen = bufferlen; - } - SDL_strlcpy(SDL_envmem, variable, bufferlen); - value = SDL_envmem + (sep - variable); - *value++ = '\0'; - if ( !SetEnvironmentVariable(SDL_envmem, *value ? value : NULL) ) { - return -1; - } - return 0; + size_t bufferlen; + char *value; + const char *sep; + + sep = SDL_strchr(variable, '='); + if (sep == NULL) { + return -1; + } + bufferlen = SDL_strlen(variable) + 1; + if (bufferlen > SDL_envmemlen) { + char *newmem = (char *) SDL_realloc(SDL_envmem, bufferlen); + if (newmem == NULL) { + return -1; + } + SDL_envmem = newmem; + SDL_envmemlen = bufferlen; + } + SDL_strlcpy(SDL_envmem, variable, bufferlen); + value = SDL_envmem + (sep - variable); + *value++ = '\0'; + if (!SetEnvironmentVariable(SDL_envmem, *value ? value : NULL)) { + return -1; + } + return 0; } /* Retrieve a variable named "name" from the environment */ -char *SDL_getenv(const char *name) +char * +SDL_getenv(const char *name) { - size_t bufferlen; - - bufferlen = GetEnvironmentVariable(name, SDL_envmem, (DWORD)SDL_envmemlen); - if ( bufferlen == 0 ) { - return NULL; - } - if ( bufferlen > SDL_envmemlen ) { - char *newmem = (char *)SDL_realloc(SDL_envmem, bufferlen); - if ( newmem == NULL ) { - return NULL; - } - SDL_envmem = newmem; - SDL_envmemlen = bufferlen; - GetEnvironmentVariable(name, SDL_envmem, (DWORD)SDL_envmemlen); - } - return SDL_envmem; + size_t bufferlen; + + bufferlen = + GetEnvironmentVariable(name, SDL_envmem, (DWORD) SDL_envmemlen); + if (bufferlen == 0) { + return NULL; + } + if (bufferlen > SDL_envmemlen) { + char *newmem = (char *) SDL_realloc(SDL_envmem, bufferlen); + if (newmem == NULL) { + return NULL; + } + SDL_envmem = newmem; + SDL_envmemlen = bufferlen; + GetEnvironmentVariable(name, SDL_envmem, (DWORD) SDL_envmemlen); + } + return SDL_envmem; } #else /* roll our own */ -static char **SDL_env = (char **)0; +static char **SDL_env = (char **) 0; /* Put a variable of the form "name=value" into the environment */ -int SDL_putenv(const char *variable) +int +SDL_putenv(const char *variable) { - const char *name, *value; - int added; - int len, i; - char **new_env; - char *new_variable; - - /* A little error checking */ - if ( ! variable ) { - return(-1); - } - name = variable; - for ( value=variable; *value && (*value != '='); ++value ) { - /* Keep looking for '=' */ ; - } - if ( *value ) { - ++value; - } else { - return(-1); - } - - /* Allocate memory for the variable */ - new_variable = SDL_strdup(variable); - if ( ! new_variable ) { - return(-1); - } - - /* Actually put it into the environment */ - added = 0; - i = 0; - if ( SDL_env ) { - /* Check to see if it's already there... */ - len = (value - name); - for ( ; SDL_env[i]; ++i ) { - if ( SDL_strncmp(SDL_env[i], name, len) == 0 ) { - break; - } - } - /* If we found it, just replace the entry */ - if ( SDL_env[i] ) { - SDL_free(SDL_env[i]); - SDL_env[i] = new_variable; - added = 1; - } - } - - /* Didn't find it in the environment, expand and add */ - if ( ! added ) { - new_env = SDL_realloc(SDL_env, (i+2)*sizeof(char *)); - if ( new_env ) { - SDL_env = new_env; - SDL_env[i++] = new_variable; - SDL_env[i++] = (char *)0; - added = 1; - } else { - SDL_free(new_variable); - } - } - return (added ? 0 : -1); + const char *name, *value; + int added; + int len, i; + char **new_env; + char *new_variable; + + /* A little error checking */ + if (!variable) { + return (-1); + } + name = variable; + for (value = variable; *value && (*value != '='); ++value) { + /* Keep looking for '=' */ ; + } + if (*value) { + ++value; + } else { + return (-1); + } + + /* Allocate memory for the variable */ + new_variable = SDL_strdup(variable); + if (!new_variable) { + return (-1); + } + + /* Actually put it into the environment */ + added = 0; + i = 0; + if (SDL_env) { + /* Check to see if it's already there... */ + len = (value - name); + for (; SDL_env[i]; ++i) { + if (SDL_strncmp(SDL_env[i], name, len) == 0) { + break; + } + } + /* If we found it, just replace the entry */ + if (SDL_env[i]) { + SDL_free(SDL_env[i]); + SDL_env[i] = new_variable; + added = 1; + } + } + + /* Didn't find it in the environment, expand and add */ + if (!added) { + new_env = SDL_realloc(SDL_env, (i + 2) * sizeof(char *)); + if (new_env) { + SDL_env = new_env; + SDL_env[i++] = new_variable; + SDL_env[i++] = (char *) 0; + added = 1; + } else { + SDL_free(new_variable); + } + } + return (added ? 0 : -1); } /* Retrieve a variable named "name" from the environment */ -char *SDL_getenv(const char *name) +char * +SDL_getenv(const char *name) { - int len, i; - char *value; - - value = (char *)0; - if ( SDL_env ) { - len = SDL_strlen(name); - for ( i=0; SDL_env[i] && !value; ++i ) { - if ( (SDL_strncmp(SDL_env[i], name, len) == 0) && - (SDL_env[i][len] == '=') ) { - value = &SDL_env[i][len+1]; - } - } - } - return value; + int len, i; + char *value; + + value = (char *) 0; + if (SDL_env) { + len = SDL_strlen(name); + for (i = 0; SDL_env[i] && !value; ++i) { + if ((SDL_strncmp(SDL_env[i], name, len) == 0) && + (SDL_env[i][len] == '=')) { + value = &SDL_env[i][len + 1]; + } + } + } + return value; } #endif /* __WIN32__ */ @@ -178,70 +183,71 @@ char *SDL_getenv(const char *name) #ifdef TEST_MAIN #include -int main(int argc, char *argv[]) +int +main(int argc, char *argv[]) { - char *value; - - printf("Checking for non-existent variable... "); - fflush(stdout); - if ( ! SDL_getenv("EXISTS") ) { - printf("okay\n"); - } else { - printf("failed\n"); - } - printf("Setting FIRST=VALUE1 in the environment... "); - fflush(stdout); - if ( SDL_putenv("FIRST=VALUE1") == 0 ) { - printf("okay\n"); - } else { - printf("failed\n"); - } - printf("Getting FIRST from the environment... "); - fflush(stdout); - value = SDL_getenv("FIRST"); - if ( value && (SDL_strcmp(value, "VALUE1") == 0) ) { - printf("okay\n"); - } else { - printf("failed\n"); - } - printf("Setting SECOND=VALUE2 in the environment... "); - fflush(stdout); - if ( SDL_putenv("SECOND=VALUE2") == 0 ) { - printf("okay\n"); - } else { - printf("failed\n"); - } - printf("Getting SECOND from the environment... "); - fflush(stdout); - value = SDL_getenv("SECOND"); - if ( value && (SDL_strcmp(value, "VALUE2") == 0) ) { - printf("okay\n"); - } else { - printf("failed\n"); - } - printf("Setting FIRST=NOVALUE in the environment... "); - fflush(stdout); - if ( SDL_putenv("FIRST=NOVALUE") == 0 ) { - printf("okay\n"); - } else { - printf("failed\n"); - } - printf("Getting FIRST from the environment... "); - fflush(stdout); - value = SDL_getenv("FIRST"); - if ( value && (SDL_strcmp(value, "NOVALUE") == 0) ) { - printf("okay\n"); - } else { - printf("failed\n"); - } - printf("Checking for non-existent variable... "); - fflush(stdout); - if ( ! SDL_getenv("EXISTS") ) { - printf("okay\n"); - } else { - printf("failed\n"); - } - return(0); + char *value; + + printf("Checking for non-existent variable... "); + fflush(stdout); + if (!SDL_getenv("EXISTS")) { + printf("okay\n"); + } else { + printf("failed\n"); + } + printf("Setting FIRST=VALUE1 in the environment... "); + fflush(stdout); + if (SDL_putenv("FIRST=VALUE1") == 0) { + printf("okay\n"); + } else { + printf("failed\n"); + } + printf("Getting FIRST from the environment... "); + fflush(stdout); + value = SDL_getenv("FIRST"); + if (value && (SDL_strcmp(value, "VALUE1") == 0)) { + printf("okay\n"); + } else { + printf("failed\n"); + } + printf("Setting SECOND=VALUE2 in the environment... "); + fflush(stdout); + if (SDL_putenv("SECOND=VALUE2") == 0) { + printf("okay\n"); + } else { + printf("failed\n"); + } + printf("Getting SECOND from the environment... "); + fflush(stdout); + value = SDL_getenv("SECOND"); + if (value && (SDL_strcmp(value, "VALUE2") == 0)) { + printf("okay\n"); + } else { + printf("failed\n"); + } + printf("Setting FIRST=NOVALUE in the environment... "); + fflush(stdout); + if (SDL_putenv("FIRST=NOVALUE") == 0) { + printf("okay\n"); + } else { + printf("failed\n"); + } + printf("Getting FIRST from the environment... "); + fflush(stdout); + value = SDL_getenv("FIRST"); + if (value && (SDL_strcmp(value, "NOVALUE") == 0)) { + printf("okay\n"); + } else { + printf("failed\n"); + } + printf("Checking for non-existent variable... "); + fflush(stdout); + if (!SDL_getenv("EXISTS")) { + printf("okay\n"); + } else { + printf("failed\n"); + } + return (0); } #endif /* TEST_MAIN */ - +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/stdlib/SDL_iconv.c b/src/stdlib/SDL_iconv.c index 1a94e0f3b..d5b8fa808 100644 --- a/src/stdlib/SDL_iconv.c +++ b/src/stdlib/SDL_iconv.c @@ -30,24 +30,25 @@ #include -size_t SDL_iconv(SDL_iconv_t cd, - char **inbuf, size_t *inbytesleft, - char **outbuf, size_t *outbytesleft) +size_t +SDL_iconv(SDL_iconv_t cd, + char **inbuf, size_t * inbytesleft, + char **outbuf, size_t * outbytesleft) { - size_t retCode = iconv(cd, inbuf, inbytesleft, outbuf, outbytesleft); - if ( retCode == (size_t)-1 ) { - switch(errno) { - case E2BIG: - return SDL_ICONV_E2BIG; - case EILSEQ: - return SDL_ICONV_EILSEQ; - case EINVAL: - return SDL_ICONV_EINVAL; - default: - return SDL_ICONV_ERROR; - } - } - return retCode; + size_t retCode = iconv(cd, inbuf, inbytesleft, outbuf, outbytesleft); + if (retCode == (size_t) - 1) { + switch (errno) { + case E2BIG: + return SDL_ICONV_E2BIG; + case EILSEQ: + return SDL_ICONV_EILSEQ; + case EINVAL: + return SDL_ICONV_EINVAL; + default: + return SDL_ICONV_ERROR; + } + } + return retCode; } #else @@ -61,19 +62,20 @@ size_t SDL_iconv(SDL_iconv_t cd, #define UNKNOWN_ASCII '?' #define UNKNOWN_UNICODE 0xFFFD -enum { - ENCODING_UNKNOWN, - ENCODING_ASCII, - ENCODING_LATIN1, - ENCODING_UTF8, - ENCODING_UTF16, /* Needs byte order marker */ - ENCODING_UTF16BE, - ENCODING_UTF16LE, - ENCODING_UTF32, /* Needs byte order marker */ - ENCODING_UTF32BE, - ENCODING_UTF32LE, - ENCODING_UCS2, /* Native byte order assumed */ - ENCODING_UCS4, /* Native byte order assumed */ +enum +{ + ENCODING_UNKNOWN, + ENCODING_ASCII, + ENCODING_LATIN1, + ENCODING_UTF8, + ENCODING_UTF16, /* Needs byte order marker */ + ENCODING_UTF16BE, + ENCODING_UTF16LE, + ENCODING_UTF32, /* Needs byte order marker */ + ENCODING_UTF32BE, + ENCODING_UTF32LE, + ENCODING_UCS2, /* Native byte order assumed */ + ENCODING_UCS4, /* Native byte order assumed */ }; #if SDL_BYTEORDER == SDL_BIG_ENDIAN #define ENCODING_UTF16NATIVE ENCODING_UTF16BE @@ -85,730 +87,731 @@ enum { struct _SDL_iconv_t { - int src_fmt; - int dst_fmt; + int src_fmt; + int dst_fmt; }; -static struct { - const char *name; - int format; +static struct +{ + const char *name; + int format; } encodings[] = { - { "ASCII", ENCODING_ASCII }, - { "US-ASCII", ENCODING_ASCII }, - { "LATIN1", ENCODING_LATIN1 }, - { "ISO-8859-1", ENCODING_LATIN1 }, - { "UTF8", ENCODING_UTF8 }, - { "UTF-8", ENCODING_UTF8 }, - { "UTF16", ENCODING_UTF16 }, - { "UTF-16", ENCODING_UTF16 }, - { "UTF16BE", ENCODING_UTF16BE }, - { "UTF-16BE", ENCODING_UTF16BE }, - { "UTF16LE", ENCODING_UTF16LE }, - { "UTF-16LE", ENCODING_UTF16LE }, - { "UTF32", ENCODING_UTF32 }, - { "UTF-32", ENCODING_UTF32 }, - { "UTF32BE", ENCODING_UTF32BE }, - { "UTF-32BE", ENCODING_UTF32BE }, - { "UTF32LE", ENCODING_UTF32LE }, - { "UTF-32LE", ENCODING_UTF32LE }, - { "UCS2", ENCODING_UCS2 }, - { "UCS-2", ENCODING_UCS2 }, - { "UCS4", ENCODING_UCS4 }, - { "UCS-4", ENCODING_UCS4 }, -}; - -SDL_iconv_t SDL_iconv_open(const char *tocode, const char *fromcode) + { + "ASCII", ENCODING_ASCII}, { + "US-ASCII", ENCODING_ASCII}, { + "LATIN1", ENCODING_LATIN1}, { + "ISO-8859-1", ENCODING_LATIN1}, { + "UTF8", ENCODING_UTF8}, { + "UTF-8", ENCODING_UTF8}, { + "UTF16", ENCODING_UTF16}, { + "UTF-16", ENCODING_UTF16}, { + "UTF16BE", ENCODING_UTF16BE}, { + "UTF-16BE", ENCODING_UTF16BE}, { + "UTF16LE", ENCODING_UTF16LE}, { + "UTF-16LE", ENCODING_UTF16LE}, { + "UTF32", ENCODING_UTF32}, { + "UTF-32", ENCODING_UTF32}, { + "UTF32BE", ENCODING_UTF32BE}, { + "UTF-32BE", ENCODING_UTF32BE}, { + "UTF32LE", ENCODING_UTF32LE}, { + "UTF-32LE", ENCODING_UTF32LE}, { + "UCS2", ENCODING_UCS2}, { + "UCS-2", ENCODING_UCS2}, { + "UCS4", ENCODING_UCS4}, { +"UCS-4", ENCODING_UCS4},}; + +SDL_iconv_t +SDL_iconv_open(const char *tocode, const char *fromcode) { - int src_fmt = ENCODING_UNKNOWN; - int dst_fmt = ENCODING_UNKNOWN; - int i; - - for ( i = 0; i < SDL_arraysize(encodings); ++i ) { - if ( SDL_strcasecmp(fromcode, encodings[i].name) == 0 ) { - src_fmt = encodings[i].format; - if ( dst_fmt != ENCODING_UNKNOWN ) { - break; - } - } - if ( SDL_strcasecmp(tocode, encodings[i].name) == 0 ) { - dst_fmt = encodings[i].format; - if ( src_fmt != ENCODING_UNKNOWN ) { - break; - } - } - } - if ( src_fmt != ENCODING_UNKNOWN && dst_fmt != ENCODING_UNKNOWN ) { - SDL_iconv_t cd = (SDL_iconv_t)SDL_malloc(sizeof(*cd)); - if ( cd ) { - cd->src_fmt = src_fmt; - cd->dst_fmt = dst_fmt; - return cd; - } - } - return (SDL_iconv_t)-1; + int src_fmt = ENCODING_UNKNOWN; + int dst_fmt = ENCODING_UNKNOWN; + int i; + + for (i = 0; i < SDL_arraysize(encodings); ++i) { + if (SDL_strcasecmp(fromcode, encodings[i].name) == 0) { + src_fmt = encodings[i].format; + if (dst_fmt != ENCODING_UNKNOWN) { + break; + } + } + if (SDL_strcasecmp(tocode, encodings[i].name) == 0) { + dst_fmt = encodings[i].format; + if (src_fmt != ENCODING_UNKNOWN) { + break; + } + } + } + if (src_fmt != ENCODING_UNKNOWN && dst_fmt != ENCODING_UNKNOWN) { + SDL_iconv_t cd = (SDL_iconv_t) SDL_malloc(sizeof(*cd)); + if (cd) { + cd->src_fmt = src_fmt; + cd->dst_fmt = dst_fmt; + return cd; + } + } + return (SDL_iconv_t) - 1; } -size_t SDL_iconv(SDL_iconv_t cd, - char **inbuf, size_t *inbytesleft, - char **outbuf, size_t *outbytesleft) +size_t +SDL_iconv(SDL_iconv_t cd, + char **inbuf, size_t * inbytesleft, + char **outbuf, size_t * outbytesleft) { - /* For simplicity, we'll convert everything to and from UCS-4 */ - char *src, *dst; - size_t srclen, dstlen; - Uint32 ch = 0; - size_t total; - - if ( !inbuf || !*inbuf ) { - /* Reset the context */ - return 0; - } - if ( !outbuf || !*outbuf || !outbytesleft || !*outbytesleft ) { - return SDL_ICONV_E2BIG; - } - src = *inbuf; - srclen = (inbytesleft ? *inbytesleft : 0); - dst = *outbuf; - dstlen = *outbytesleft; - - switch ( cd->src_fmt ) { - case ENCODING_UTF16: - /* Scan for a byte order marker */ - { - Uint8 *p = (Uint8 *)src; - size_t n = srclen / 2; - while ( n ) { - if ( p[0] == 0xFF && p[1] == 0xFE ) { - cd->src_fmt = ENCODING_UTF16BE; - break; - } else if ( p[0] == 0xFE && p[1] == 0xFF ) { - cd->src_fmt = ENCODING_UTF16LE; - break; - } - p += 2; - --n; - } - if ( n == 0 ) { - /* We can't tell, default to host order */ - cd->src_fmt = ENCODING_UTF16NATIVE; - } - } - break; - case ENCODING_UTF32: - /* Scan for a byte order marker */ - { - Uint8 *p = (Uint8 *)src; - size_t n = srclen / 4; - while ( n ) { - if ( p[0] == 0xFF && p[1] == 0xFE && - p[2] == 0x00 && p[3] == 0x00 ) { - cd->src_fmt = ENCODING_UTF32BE; - break; - } else if ( p[0] == 0x00 && p[1] == 0x00 && - p[2] == 0xFE && p[3] == 0xFF ) { - cd->src_fmt = ENCODING_UTF32LE; - break; - } - p += 4; - --n; - } - if ( n == 0 ) { - /* We can't tell, default to host order */ - cd->src_fmt = ENCODING_UTF32NATIVE; - } - } - break; - } - - switch ( cd->dst_fmt ) { - case ENCODING_UTF16: - /* Default to host order, need to add byte order marker */ - if ( dstlen < 2 ) { - return SDL_ICONV_E2BIG; - } - *(Uint16 *)dst = UNICODE_BOM; - dst += 2; - dstlen -= 2; - cd->dst_fmt = ENCODING_UTF16NATIVE; - break; - case ENCODING_UTF32: - /* Default to host order, need to add byte order marker */ - if ( dstlen < 4 ) { - return SDL_ICONV_E2BIG; - } - *(Uint32 *)dst = UNICODE_BOM; - dst += 4; - dstlen -= 4; - cd->dst_fmt = ENCODING_UTF32NATIVE; - break; - } - - total = 0; - while ( srclen > 0 ) { - /* Decode a character */ - switch ( cd->src_fmt ) { - case ENCODING_ASCII: - { - Uint8 *p = (Uint8 *)src; - ch = (Uint32)(p[0] & 0x7F); - ++src; - --srclen; - } - break; - case ENCODING_LATIN1: - { - Uint8 *p = (Uint8 *)src; - ch = (Uint32)p[0]; - ++src; - --srclen; - } - break; - case ENCODING_UTF8: /* RFC 3629 */ - { - Uint8 *p = (Uint8 *)src; - size_t left = 0; - SDL_bool overlong = SDL_FALSE; - if ( p[0] >= 0xFC ) { - if ( (p[0] & 0xFE) != 0xFC ) { - /* Skip illegal sequences - return SDL_ICONV_EILSEQ; - */ - ch = UNKNOWN_UNICODE; - } else { - if ( p[0] == 0xFC ) { - overlong = SDL_TRUE; - } - ch = (Uint32)(p[0] & 0x01); - left = 5; - } - } else if ( p[0] >= 0xF8 ) { - if ( (p[0] & 0xFC) != 0xF8 ) { - /* Skip illegal sequences - return SDL_ICONV_EILSEQ; - */ - ch = UNKNOWN_UNICODE; - } else { - if ( p[0] == 0xF8 ) { - overlong = SDL_TRUE; - } - ch = (Uint32)(p[0] & 0x03); - left = 4; - } - } else if ( p[0] >= 0xF0 ) { - if ( (p[0] & 0xF8) != 0xF0 ) { - /* Skip illegal sequences - return SDL_ICONV_EILSEQ; - */ - ch = UNKNOWN_UNICODE; - } else { - if ( p[0] == 0xF0 ) { - overlong = SDL_TRUE; - } - ch = (Uint32)(p[0] & 0x07); - left = 3; - } - } else if ( p[0] >= 0xE0 ) { - if ( (p[0] & 0xF0) != 0xE0 ) { - /* Skip illegal sequences - return SDL_ICONV_EILSEQ; - */ - ch = UNKNOWN_UNICODE; - } else { - if ( p[0] == 0xE0 ) { - overlong = SDL_TRUE; - } - ch = (Uint32)(p[0] & 0x0F); - left = 2; - } - } else if ( p[0] >= 0xC0 ) { - if ( (p[0] & 0xE0) != 0xC0 ) { - /* Skip illegal sequences - return SDL_ICONV_EILSEQ; - */ - ch = UNKNOWN_UNICODE; - } else { - if ( (p[0] & 0xCE) == 0xC0 ) { - overlong = SDL_TRUE; - } - ch = (Uint32)(p[0] & 0x1F); - left = 1; - } - } else { - if ( (p[0] & 0x80) != 0x00 ) { - /* Skip illegal sequences - return SDL_ICONV_EILSEQ; - */ - ch = UNKNOWN_UNICODE; - } else { - ch = (Uint32)p[0]; - } - } - ++src; - --srclen; - if ( srclen < left ) { - return SDL_ICONV_EINVAL; - } - while ( left-- ) { - ++p; - if ( (p[0] & 0xC0) != 0x80 ) { - /* Skip illegal sequences - return SDL_ICONV_EILSEQ; - */ - ch = UNKNOWN_UNICODE; - break; - } - ch <<= 6; - ch |= (p[0] & 0x3F); - ++src; - --srclen; - } - if ( overlong ) { - /* Potential security risk - return SDL_ICONV_EILSEQ; - */ - ch = UNKNOWN_UNICODE; - } - if ( (ch >= 0xD800 && ch <= 0xDFFF) || - (ch == 0xFFFE || ch == 0xFFFF) || - ch > 0x10FFFF ) { - /* Skip illegal sequences - return SDL_ICONV_EILSEQ; - */ - ch = UNKNOWN_UNICODE; - } - } - break; - case ENCODING_UTF16BE: /* RFC 2781 */ - { - Uint8 *p = (Uint8 *)src; - Uint16 W1, W2; - if ( srclen < 2 ) { - return SDL_ICONV_EINVAL; - } - W1 = ((Uint16)p[0] << 8) | - (Uint16)p[1]; - src += 2; - srclen -= 2; - if ( W1 < 0xD800 || W1 > 0xDFFF ) { - ch = (Uint32)W1; - break; - } - if ( W1 > 0xDBFF ) { - /* Skip illegal sequences - return SDL_ICONV_EILSEQ; - */ - ch = UNKNOWN_UNICODE; - break; - } - if ( srclen < 2 ) { - return SDL_ICONV_EINVAL; - } - p = (Uint8 *)src; - W2 = ((Uint16)p[0] << 8) | - (Uint16)p[1]; - src += 2; - srclen -= 2; - if ( W2 < 0xDC00 || W2 > 0xDFFF ) { - /* Skip illegal sequences - return SDL_ICONV_EILSEQ; - */ - ch = UNKNOWN_UNICODE; - break; - } - ch = (((Uint32)(W1 & 0x3FF) << 10) | - (Uint32)(W2 & 0x3FF)) + 0x10000; - } - break; - case ENCODING_UTF16LE: /* RFC 2781 */ - { - Uint8 *p = (Uint8 *)src; - Uint16 W1, W2; - if ( srclen < 2 ) { - return SDL_ICONV_EINVAL; - } - W1 = ((Uint16)p[1] << 8) | - (Uint16)p[0]; - src += 2; - srclen -= 2; - if ( W1 < 0xD800 || W1 > 0xDFFF ) { - ch = (Uint32)W1; - break; - } - if ( W1 > 0xDBFF ) { - /* Skip illegal sequences - return SDL_ICONV_EILSEQ; - */ - ch = UNKNOWN_UNICODE; - break; - } - if ( srclen < 2 ) { - return SDL_ICONV_EINVAL; - } - p = (Uint8 *)src; - W2 = ((Uint16)p[1] << 8) | - (Uint16)p[0]; - src += 2; - srclen -= 2; - if ( W2 < 0xDC00 || W2 > 0xDFFF ) { - /* Skip illegal sequences - return SDL_ICONV_EILSEQ; - */ - ch = UNKNOWN_UNICODE; - break; - } - ch = (((Uint32)(W1 & 0x3FF) << 10) | - (Uint32)(W2 & 0x3FF)) + 0x10000; - } - break; - case ENCODING_UTF32BE: - { - Uint8 *p = (Uint8 *)src; - if ( srclen < 4 ) { - return SDL_ICONV_EINVAL; - } - ch = ((Uint32)p[0] << 24) | - ((Uint32)p[1] << 16) | - ((Uint32)p[2] << 8) | - (Uint32)p[3]; - src += 4; - srclen -= 4; - } - break; - case ENCODING_UTF32LE: - { - Uint8 *p = (Uint8 *)src; - if ( srclen < 4 ) { - return SDL_ICONV_EINVAL; - } - ch = ((Uint32)p[3] << 24) | - ((Uint32)p[2] << 16) | - ((Uint32)p[1] << 8) | - (Uint32)p[0]; - src += 4; - srclen -= 4; - } - break; - case ENCODING_UCS2: - { - Uint16 *p = (Uint16 *)src; - if ( srclen < 2 ) { - return SDL_ICONV_EINVAL; - } - ch = *p; - src += 2; - srclen -= 2; - } - break; - case ENCODING_UCS4: - { - Uint32 *p = (Uint32 *)src; - if ( srclen < 4 ) { - return SDL_ICONV_EINVAL; - } - ch = *p; - src += 4; - srclen -= 4; - } - break; - } - - /* Encode a character */ - switch ( cd->dst_fmt ) { - case ENCODING_ASCII: - { - Uint8 *p = (Uint8 *)dst; - if ( dstlen < 1 ) { - return SDL_ICONV_E2BIG; - } - if ( ch > 0x7F ) { - *p = UNKNOWN_ASCII; - } else { - *p = (Uint8)ch; - } - ++dst; - --dstlen; - } - break; - case ENCODING_LATIN1: - { - Uint8 *p = (Uint8 *)dst; - if ( dstlen < 1 ) { - return SDL_ICONV_E2BIG; - } - if ( ch > 0xFF ) { - *p = UNKNOWN_ASCII; - } else { - *p = (Uint8)ch; - } - ++dst; - --dstlen; - } - break; - case ENCODING_UTF8: /* RFC 3629 */ - { - Uint8 *p = (Uint8 *)dst; - if ( ch > 0x10FFFF ) { - ch = UNKNOWN_UNICODE; - } - if ( ch <= 0x7F ) { - if ( dstlen < 1 ) { - return SDL_ICONV_E2BIG; - } - *p = (Uint8)ch; - ++dst; - --dstlen; - } else if ( ch <= 0x7FF ) { - if ( dstlen < 2 ) { - return SDL_ICONV_E2BIG; - } - p[0] = 0xC0 | (Uint8)((ch >> 6) & 0x1F); - p[1] = 0x80 | (Uint8)(ch & 0x3F); - dst += 2; - dstlen -= 2; - } else if ( ch <= 0xFFFF ) { - if ( dstlen < 3 ) { - return SDL_ICONV_E2BIG; - } - p[0] = 0xE0 | (Uint8)((ch >> 12) & 0x0F); - p[1] = 0x80 | (Uint8)((ch >> 6) & 0x3F); - p[2] = 0x80 | (Uint8)(ch & 0x3F); - dst += 3; - dstlen -= 3; - } else if ( ch <= 0x1FFFFF ) { - if ( dstlen < 4 ) { - return SDL_ICONV_E2BIG; - } - p[0] = 0xF0 | (Uint8)((ch >> 18) & 0x07); - p[1] = 0x80 | (Uint8)((ch >> 12) & 0x3F); - p[2] = 0x80 | (Uint8)((ch >> 6) & 0x3F); - p[3] = 0x80 | (Uint8)(ch & 0x3F); - dst += 4; - dstlen -= 4; - } else if ( ch <= 0x3FFFFFF ) { - if ( dstlen < 5 ) { - return SDL_ICONV_E2BIG; - } - p[0] = 0xF8 | (Uint8)((ch >> 24) & 0x03); - p[1] = 0x80 | (Uint8)((ch >> 18) & 0x3F); - p[2] = 0x80 | (Uint8)((ch >> 12) & 0x3F); - p[3] = 0x80 | (Uint8)((ch >> 6) & 0x3F); - p[4] = 0x80 | (Uint8)(ch & 0x3F); - dst += 5; - dstlen -= 5; - } else { - if ( dstlen < 6 ) { - return SDL_ICONV_E2BIG; - } - p[0] = 0xFC | (Uint8)((ch >> 30) & 0x01); - p[1] = 0x80 | (Uint8)((ch >> 24) & 0x3F); - p[2] = 0x80 | (Uint8)((ch >> 18) & 0x3F); - p[3] = 0x80 | (Uint8)((ch >> 12) & 0x3F); - p[4] = 0x80 | (Uint8)((ch >> 6) & 0x3F); - p[5] = 0x80 | (Uint8)(ch & 0x3F); - dst += 6; - dstlen -= 6; - } - } - break; - case ENCODING_UTF16BE: /* RFC 2781 */ - { - Uint8 *p = (Uint8 *)dst; - if ( ch > 0x10FFFF ) { - ch = UNKNOWN_UNICODE; - } - if ( ch < 0x10000 ) { - if ( dstlen < 2 ) { - return SDL_ICONV_E2BIG; - } - p[0] = (Uint8)(ch >> 8); - p[1] = (Uint8)ch; - dst += 2; - dstlen -= 2; - } else { - Uint16 W1, W2; - if ( dstlen < 4 ) { - return SDL_ICONV_E2BIG; - } - ch = ch - 0x10000; - W1 = 0xD800 | (Uint16)((ch >> 10) & 0x3FF); - W2 = 0xDC00 | (Uint16)(ch & 0x3FF); - p[0] = (Uint8)(W1 >> 8); - p[1] = (Uint8)W1; - p[2] = (Uint8)(W2 >> 8); - p[3] = (Uint8)W2; - dst += 4; - dstlen -= 4; - } - } - break; - case ENCODING_UTF16LE: /* RFC 2781 */ - { - Uint8 *p = (Uint8 *)dst; - if ( ch > 0x10FFFF ) { - ch = UNKNOWN_UNICODE; - } - if ( ch < 0x10000 ) { - if ( dstlen < 2 ) { - return SDL_ICONV_E2BIG; - } - p[1] = (Uint8)(ch >> 8); - p[0] = (Uint8)ch; - dst += 2; - dstlen -= 2; - } else { - Uint16 W1, W2; - if ( dstlen < 4 ) { - return SDL_ICONV_E2BIG; - } - ch = ch - 0x10000; - W1 = 0xD800 | (Uint16)((ch >> 10) & 0x3FF); - W2 = 0xDC00 | (Uint16)(ch & 0x3FF); - p[1] = (Uint8)(W1 >> 8); - p[0] = (Uint8)W1; - p[3] = (Uint8)(W2 >> 8); - p[2] = (Uint8)W2; - dst += 4; - dstlen -= 4; - } - } - break; - case ENCODING_UTF32BE: - { - Uint8 *p = (Uint8 *)dst; - if ( ch > 0x10FFFF ) { - ch = UNKNOWN_UNICODE; - } - if ( dstlen < 4 ) { - return SDL_ICONV_E2BIG; - } - p[0] = (Uint8)(ch >> 24); - p[1] = (Uint8)(ch >> 16); - p[2] = (Uint8)(ch >> 8); - p[3] = (Uint8)ch; - dst += 4; - dstlen -= 4; - } - break; - case ENCODING_UTF32LE: - { - Uint8 *p = (Uint8 *)dst; - if ( ch > 0x10FFFF ) { - ch = UNKNOWN_UNICODE; - } - if ( dstlen < 4 ) { - return SDL_ICONV_E2BIG; - } - p[3] = (Uint8)(ch >> 24); - p[2] = (Uint8)(ch >> 16); - p[1] = (Uint8)(ch >> 8); - p[0] = (Uint8)ch; - dst += 4; - dstlen -= 4; - } - break; - case ENCODING_UCS2: - { - Uint16 *p = (Uint16 *)dst; - if ( ch > 0xFFFF ) { - ch = UNKNOWN_UNICODE; - } - if ( dstlen < 2 ) { - return SDL_ICONV_E2BIG; - } - *p = (Uint16)ch; - dst += 2; - dstlen -= 2; - } - break; - case ENCODING_UCS4: - { - Uint32 *p = (Uint32 *)dst; - if ( ch > 0x7FFFFFFF ) { - ch = UNKNOWN_UNICODE; - } - if ( dstlen < 4 ) { - return SDL_ICONV_E2BIG; - } - *p = ch; - dst += 4; - dstlen -= 4; - } - break; - } - - /* Update state */ - *inbuf = src; - *inbytesleft = srclen; - *outbuf = dst; - *outbytesleft = dstlen; - ++total; - } - return total; + /* For simplicity, we'll convert everything to and from UCS-4 */ + char *src, *dst; + size_t srclen, dstlen; + Uint32 ch; + size_t total; + + if (!inbuf || !*inbuf) { + /* Reset the context */ + return 0; + } + if (!outbuf || !*outbuf || !outbytesleft || !*outbytesleft) { + return SDL_ICONV_E2BIG; + } + src = *inbuf; + srclen = (inbytesleft ? *inbytesleft : 0); + dst = *outbuf; + dstlen = *outbytesleft; + + switch (cd->src_fmt) { + case ENCODING_UTF16: + /* Scan for a byte order marker */ + { + Uint8 *p = (Uint8 *) src; + size_t n = srclen / 2; + while (n) { + if (p[0] == 0xFF && p[1] == 0xFE) { + cd->src_fmt = ENCODING_UTF16BE; + break; + } else if (p[0] == 0xFE && p[1] == 0xFF) { + cd->src_fmt = ENCODING_UTF16LE; + break; + } + p += 2; + --n; + } + if (n == 0) { + /* We can't tell, default to host order */ + cd->src_fmt = ENCODING_UTF16NATIVE; + } + } + break; + case ENCODING_UTF32: + /* Scan for a byte order marker */ + { + Uint8 *p = (Uint8 *) src; + size_t n = srclen / 4; + while (n) { + if (p[0] == 0xFF && p[1] == 0xFE && + p[2] == 0x00 && p[3] == 0x00) { + cd->src_fmt = ENCODING_UTF32BE; + break; + } else if (p[0] == 0x00 && p[1] == 0x00 && + p[2] == 0xFE && p[3] == 0xFF) { + cd->src_fmt = ENCODING_UTF32LE; + break; + } + p += 4; + --n; + } + if (n == 0) { + /* We can't tell, default to host order */ + cd->src_fmt = ENCODING_UTF32NATIVE; + } + } + break; + } + + switch (cd->dst_fmt) { + case ENCODING_UTF16: + /* Default to host order, need to add byte order marker */ + if (dstlen < 2) { + return SDL_ICONV_E2BIG; + } + *(Uint16 *) dst = UNICODE_BOM; + dst += 2; + dstlen -= 2; + cd->dst_fmt = ENCODING_UTF16NATIVE; + break; + case ENCODING_UTF32: + /* Default to host order, need to add byte order marker */ + if (dstlen < 4) { + return SDL_ICONV_E2BIG; + } + *(Uint32 *) dst = UNICODE_BOM; + dst += 4; + dstlen -= 4; + cd->dst_fmt = ENCODING_UTF32NATIVE; + break; + } + + total = 0; + while (srclen > 0) { + /* Decode a character */ + switch (cd->src_fmt) { + case ENCODING_ASCII: + { + Uint8 *p = (Uint8 *) src; + ch = (Uint32) (p[0] & 0x7F); + ++src; + --srclen; + } + break; + case ENCODING_LATIN1: + { + Uint8 *p = (Uint8 *) src; + ch = (Uint32) p[0]; + ++src; + --srclen; + } + break; + case ENCODING_UTF8: /* RFC 3629 */ + { + Uint8 *p = (Uint8 *) src; + size_t left = 0; + SDL_bool overlong = SDL_FALSE; + if (p[0] >= 0xFC) { + if ((p[0] & 0xFE) != 0xFC) { + /* Skip illegal sequences + return SDL_ICONV_EILSEQ; + */ + ch = UNKNOWN_UNICODE; + } else { + if (p[0] == 0xFC) { + overlong = SDL_TRUE; + } + ch = (Uint32) (p[0] & 0x01); + left = 5; + } + } else if (p[0] >= 0xF8) { + if ((p[0] & 0xFC) != 0xF8) { + /* Skip illegal sequences + return SDL_ICONV_EILSEQ; + */ + ch = UNKNOWN_UNICODE; + } else { + if (p[0] == 0xF8) { + overlong = SDL_TRUE; + } + ch = (Uint32) (p[0] & 0x03); + left = 4; + } + } else if (p[0] >= 0xF0) { + if ((p[0] & 0xF8) != 0xF0) { + /* Skip illegal sequences + return SDL_ICONV_EILSEQ; + */ + ch = UNKNOWN_UNICODE; + } else { + if (p[0] == 0xF0) { + overlong = SDL_TRUE; + } + ch = (Uint32) (p[0] & 0x07); + left = 3; + } + } else if (p[0] >= 0xE0) { + if ((p[0] & 0xF0) != 0xE0) { + /* Skip illegal sequences + return SDL_ICONV_EILSEQ; + */ + ch = UNKNOWN_UNICODE; + } else { + if (p[0] == 0xE0) { + overlong = SDL_TRUE; + } + ch = (Uint32) (p[0] & 0x0F); + left = 2; + } + } else if (p[0] >= 0xC0) { + if ((p[0] & 0xE0) != 0xC0) { + /* Skip illegal sequences + return SDL_ICONV_EILSEQ; + */ + ch = UNKNOWN_UNICODE; + } else { + if ((p[0] & 0xCE) == 0xC0) { + overlong = SDL_TRUE; + } + ch = (Uint32) (p[0] & 0x1F); + left = 1; + } + } else { + if ((p[0] & 0x80) != 0x00) { + /* Skip illegal sequences + return SDL_ICONV_EILSEQ; + */ + ch = UNKNOWN_UNICODE; + } else { + ch = (Uint32) p[0]; + } + } + ++src; + --srclen; + if (srclen < left) { + return SDL_ICONV_EINVAL; + } + while (left--) { + ++p; + if ((p[0] & 0xC0) != 0x80) { + /* Skip illegal sequences + return SDL_ICONV_EILSEQ; + */ + ch = UNKNOWN_UNICODE; + break; + } + ch <<= 6; + ch |= (p[0] & 0x3F); + ++src; + --srclen; + } + if (overlong) { + /* Potential security risk + return SDL_ICONV_EILSEQ; + */ + ch = UNKNOWN_UNICODE; + } + if ((ch >= 0xD800 && ch <= 0xDFFF) || + (ch == 0xFFFE || ch == 0xFFFF) || ch > 0x10FFFF) { + /* Skip illegal sequences + return SDL_ICONV_EILSEQ; + */ + ch = UNKNOWN_UNICODE; + } + } + break; + case ENCODING_UTF16BE: /* RFC 2781 */ + { + Uint8 *p = (Uint8 *) src; + Uint16 W1, W2; + if (srclen < 2) { + return SDL_ICONV_EINVAL; + } + W1 = ((Uint16) p[0] << 8) | (Uint16) p[1]; + src += 2; + srclen -= 2; + if (W1 < 0xD800 || W1 > 0xDFFF) { + ch = (Uint32) W1; + break; + } + if (W1 > 0xDBFF) { + /* Skip illegal sequences + return SDL_ICONV_EILSEQ; + */ + ch = UNKNOWN_UNICODE; + break; + } + if (srclen < 2) { + return SDL_ICONV_EINVAL; + } + p = (Uint8 *) src; + W2 = ((Uint16) p[0] << 8) | (Uint16) p[1]; + src += 2; + srclen -= 2; + if (W2 < 0xDC00 || W2 > 0xDFFF) { + /* Skip illegal sequences + return SDL_ICONV_EILSEQ; + */ + ch = UNKNOWN_UNICODE; + break; + } + ch = (((Uint32) (W1 & 0x3FF) << 10) | + (Uint32) (W2 & 0x3FF)) + 0x10000; + } + break; + case ENCODING_UTF16LE: /* RFC 2781 */ + { + Uint8 *p = (Uint8 *) src; + Uint16 W1, W2; + if (srclen < 2) { + return SDL_ICONV_EINVAL; + } + W1 = ((Uint16) p[1] << 8) | (Uint16) p[0]; + src += 2; + srclen -= 2; + if (W1 < 0xD800 || W1 > 0xDFFF) { + ch = (Uint32) W1; + break; + } + if (W1 > 0xDBFF) { + /* Skip illegal sequences + return SDL_ICONV_EILSEQ; + */ + ch = UNKNOWN_UNICODE; + break; + } + if (srclen < 2) { + return SDL_ICONV_EINVAL; + } + p = (Uint8 *) src; + W2 = ((Uint16) p[1] << 8) | (Uint16) p[0]; + src += 2; + srclen -= 2; + if (W2 < 0xDC00 || W2 > 0xDFFF) { + /* Skip illegal sequences + return SDL_ICONV_EILSEQ; + */ + ch = UNKNOWN_UNICODE; + break; + } + ch = (((Uint32) (W1 & 0x3FF) << 10) | + (Uint32) (W2 & 0x3FF)) + 0x10000; + } + break; + case ENCODING_UTF32BE: + { + Uint8 *p = (Uint8 *) src; + if (srclen < 4) { + return SDL_ICONV_EINVAL; + } + ch = ((Uint32) p[0] << 24) | + ((Uint32) p[1] << 16) | + ((Uint32) p[2] << 8) | (Uint32) p[3]; + src += 4; + srclen -= 4; + } + break; + case ENCODING_UTF32LE: + { + Uint8 *p = (Uint8 *) src; + if (srclen < 4) { + return SDL_ICONV_EINVAL; + } + ch = ((Uint32) p[3] << 24) | + ((Uint32) p[2] << 16) | + ((Uint32) p[1] << 8) | (Uint32) p[0]; + src += 4; + srclen -= 4; + } + break; + case ENCODING_UCS2: + { + Uint16 *p = (Uint16 *) src; + if (srclen < 2) { + return SDL_ICONV_EINVAL; + } + ch = *p; + src += 2; + srclen -= 2; + } + break; + case ENCODING_UCS4: + { + Uint32 *p = (Uint32 *) src; + if (srclen < 4) { + return SDL_ICONV_EINVAL; + } + ch = *p; + src += 4; + srclen -= 4; + } + break; + } + + /* Encode a character */ + switch (cd->dst_fmt) { + case ENCODING_ASCII: + { + Uint8 *p = (Uint8 *) dst; + if (dstlen < 1) { + return SDL_ICONV_E2BIG; + } + if (ch > 0x7F) { + *p = UNKNOWN_ASCII; + } else { + *p = (Uint8) ch; + } + ++dst; + --dstlen; + } + break; + case ENCODING_LATIN1: + { + Uint8 *p = (Uint8 *) dst; + if (dstlen < 1) { + return SDL_ICONV_E2BIG; + } + if (ch > 0xFF) { + *p = UNKNOWN_ASCII; + } else { + *p = (Uint8) ch; + } + ++dst; + --dstlen; + } + break; + case ENCODING_UTF8: /* RFC 3629 */ + { + Uint8 *p = (Uint8 *) dst; + if (ch > 0x10FFFF) { + ch = UNKNOWN_UNICODE; + } + if (ch <= 0x7F) { + if (dstlen < 1) { + return SDL_ICONV_E2BIG; + } + *p = (Uint8) ch; + ++dst; + --dstlen; + } else if (ch <= 0x7FF) { + if (dstlen < 2) { + return SDL_ICONV_E2BIG; + } + p[0] = 0xC0 | (Uint8) ((ch >> 6) & 0x1F); + p[1] = 0x80 | (Uint8) (ch & 0x3F); + dst += 2; + dstlen -= 2; + } else if (ch <= 0xFFFF) { + if (dstlen < 3) { + return SDL_ICONV_E2BIG; + } + p[0] = 0xE0 | (Uint8) ((ch >> 12) & 0x0F); + p[1] = 0x80 | (Uint8) ((ch >> 6) & 0x3F); + p[2] = 0x80 | (Uint8) (ch & 0x3F); + dst += 3; + dstlen -= 3; + } else if (ch <= 0x1FFFFF) { + if (dstlen < 4) { + return SDL_ICONV_E2BIG; + } + p[0] = 0xF0 | (Uint8) ((ch >> 18) & 0x07); + p[1] = 0x80 | (Uint8) ((ch >> 12) & 0x3F); + p[2] = 0x80 | (Uint8) ((ch >> 6) & 0x3F); + p[3] = 0x80 | (Uint8) (ch & 0x3F); + dst += 4; + dstlen -= 4; + } else if (ch <= 0x3FFFFFF) { + if (dstlen < 5) { + return SDL_ICONV_E2BIG; + } + p[0] = 0xF8 | (Uint8) ((ch >> 24) & 0x03); + p[1] = 0x80 | (Uint8) ((ch >> 18) & 0x3F); + p[2] = 0x80 | (Uint8) ((ch >> 12) & 0x3F); + p[3] = 0x80 | (Uint8) ((ch >> 6) & 0x3F); + p[4] = 0x80 | (Uint8) (ch & 0x3F); + dst += 5; + dstlen -= 5; + } else { + if (dstlen < 6) { + return SDL_ICONV_E2BIG; + } + p[0] = 0xFC | (Uint8) ((ch >> 30) & 0x01); + p[1] = 0x80 | (Uint8) ((ch >> 24) & 0x3F); + p[2] = 0x80 | (Uint8) ((ch >> 18) & 0x3F); + p[3] = 0x80 | (Uint8) ((ch >> 12) & 0x3F); + p[4] = 0x80 | (Uint8) ((ch >> 6) & 0x3F); + p[5] = 0x80 | (Uint8) (ch & 0x3F); + dst += 6; + dstlen -= 6; + } + } + break; + case ENCODING_UTF16BE: /* RFC 2781 */ + { + Uint8 *p = (Uint8 *) dst; + if (ch > 0x10FFFF) { + ch = UNKNOWN_UNICODE; + } + if (ch < 0x10000) { + if (dstlen < 2) { + return SDL_ICONV_E2BIG; + } + p[0] = (Uint8) (ch >> 8); + p[1] = (Uint8) ch; + dst += 2; + dstlen -= 2; + } else { + Uint16 W1, W2; + if (dstlen < 4) { + return SDL_ICONV_E2BIG; + } + ch = ch - 0x10000; + W1 = 0xD800 | (Uint16) ((ch >> 10) & 0x3FF); + W2 = 0xDC00 | (Uint16) (ch & 0x3FF); + p[0] = (Uint8) (W1 >> 8); + p[1] = (Uint8) W1; + p[2] = (Uint8) (W2 >> 8); + p[3] = (Uint8) W2; + dst += 4; + dstlen -= 4; + } + } + break; + case ENCODING_UTF16LE: /* RFC 2781 */ + { + Uint8 *p = (Uint8 *) dst; + if (ch > 0x10FFFF) { + ch = UNKNOWN_UNICODE; + } + if (ch < 0x10000) { + if (dstlen < 2) { + return SDL_ICONV_E2BIG; + } + p[1] = (Uint8) (ch >> 8); + p[0] = (Uint8) ch; + dst += 2; + dstlen -= 2; + } else { + Uint16 W1, W2; + if (dstlen < 4) { + return SDL_ICONV_E2BIG; + } + ch = ch - 0x10000; + W1 = 0xD800 | (Uint16) ((ch >> 10) & 0x3FF); + W2 = 0xDC00 | (Uint16) (ch & 0x3FF); + p[1] = (Uint8) (W1 >> 8); + p[0] = (Uint8) W1; + p[3] = (Uint8) (W2 >> 8); + p[2] = (Uint8) W2; + dst += 4; + dstlen -= 4; + } + } + break; + case ENCODING_UTF32BE: + { + Uint8 *p = (Uint8 *) dst; + if (ch > 0x10FFFF) { + ch = UNKNOWN_UNICODE; + } + if (dstlen < 4) { + return SDL_ICONV_E2BIG; + } + p[0] = (Uint8) (ch >> 24); + p[1] = (Uint8) (ch >> 16); + p[2] = (Uint8) (ch >> 8); + p[3] = (Uint8) ch; + dst += 4; + dstlen -= 4; + } + break; + case ENCODING_UTF32LE: + { + Uint8 *p = (Uint8 *) dst; + if (ch > 0x10FFFF) { + ch = UNKNOWN_UNICODE; + } + if (dstlen < 4) { + return SDL_ICONV_E2BIG; + } + p[3] = (Uint8) (ch >> 24); + p[2] = (Uint8) (ch >> 16); + p[1] = (Uint8) (ch >> 8); + p[0] = (Uint8) ch; + dst += 4; + dstlen -= 4; + } + break; + case ENCODING_UCS2: + { + Uint16 *p = (Uint16 *) dst; + if (ch > 0xFFFF) { + ch = UNKNOWN_UNICODE; + } + if (dstlen < 2) { + return SDL_ICONV_E2BIG; + } + *p = (Uint16) ch; + dst += 2; + dstlen -= 2; + } + break; + case ENCODING_UCS4: + { + Uint32 *p = (Uint32 *) dst; + if (ch > 0x7FFFFFFF) { + ch = UNKNOWN_UNICODE; + } + if (dstlen < 4) { + return SDL_ICONV_E2BIG; + } + *p = ch; + dst += 4; + dstlen -= 4; + } + break; + } + + /* Update state */ + *inbuf = src; + *inbytesleft = srclen; + *outbuf = dst; + *outbytesleft = dstlen; + ++total; + } + return total; } -int SDL_iconv_close(SDL_iconv_t cd) +int +SDL_iconv_close(SDL_iconv_t cd) { - if ( cd && cd != (SDL_iconv_t)-1 ) { - SDL_free(cd); - } - return 0; + if (cd && cd != (SDL_iconv_t) - 1) { + SDL_free(cd); + } + return 0; } #endif /* !HAVE_ICONV */ -char *SDL_iconv_string(const char *tocode, const char *fromcode, char *inbuf, size_t inbytesleft) +char * +SDL_iconv_string(const char *tocode, const char *fromcode, char *inbuf, + size_t inbytesleft) { - SDL_iconv_t cd; - char *string; - size_t stringsize; - char *outbuf; - size_t outbytesleft; - size_t retCode = 0; - - cd = SDL_iconv_open(tocode, fromcode); - if ( cd == (SDL_iconv_t)-1 ) { - return NULL; - } - - stringsize = inbytesleft > 4 ? inbytesleft : 4; - string = SDL_malloc(stringsize); - if ( !string ) { - SDL_iconv_close(cd); - return NULL; - } - outbuf = string; - outbytesleft = stringsize; - SDL_memset(outbuf, 0, 4); - - while ( inbytesleft > 0 ) { - retCode = SDL_iconv(cd, &inbuf, &inbytesleft, &outbuf, &outbytesleft); - switch (retCode) { - case SDL_ICONV_E2BIG: - { - char *oldstring = string; - stringsize *= 2; - string = SDL_realloc(string, stringsize); - if ( !string ) { - SDL_iconv_close(cd); - return NULL; - } - outbuf = string + (outbuf - oldstring); - outbytesleft = stringsize - (outbuf - string); - SDL_memset(outbuf, 0, 4); - } - break; - case SDL_ICONV_EILSEQ: - /* Try skipping some input data - not perfect, but... */ - ++inbuf; - --inbytesleft; - break; - case SDL_ICONV_EINVAL: - case SDL_ICONV_ERROR: - /* We can't continue... */ - inbytesleft = 0; - break; - } - } - SDL_iconv_close(cd); - - return string; + SDL_iconv_t cd; + char *string; + size_t stringsize; + char *outbuf; + size_t outbytesleft; + size_t retCode = 0; + + cd = SDL_iconv_open(tocode, fromcode); + if (cd == (SDL_iconv_t) - 1) { + return NULL; + } + + stringsize = inbytesleft > 4 ? inbytesleft : 4; + string = SDL_malloc(stringsize); + if (!string) { + SDL_iconv_close(cd); + return NULL; + } + outbuf = string; + outbytesleft = stringsize; + SDL_memset(outbuf, 0, 4); + + while (inbytesleft > 0) { + retCode = SDL_iconv(cd, &inbuf, &inbytesleft, &outbuf, &outbytesleft); + switch (retCode) { + case SDL_ICONV_E2BIG: + { + char *oldstring = string; + stringsize *= 2; + string = SDL_realloc(string, stringsize); + if (!string) { + SDL_iconv_close(cd); + return NULL; + } + outbuf = string + (outbuf - oldstring); + outbytesleft = stringsize - (outbuf - string); + SDL_memset(outbuf, 0, 4); + } + break; + case SDL_ICONV_EILSEQ: + /* Try skipping some input data - not perfect, but... */ + ++inbuf; + --inbytesleft; + break; + case SDL_ICONV_EINVAL: + case SDL_ICONV_ERROR: + /* We can't continue... */ + inbytesleft = 0; + break; + } + } + SDL_iconv_close(cd); + + return string; } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/stdlib/SDL_malloc.c b/src/stdlib/SDL_malloc.c index 3d973f625..63f851406 100644 --- a/src/stdlib/SDL_malloc.c +++ b/src/stdlib/SDL_malloc.c @@ -477,8 +477,8 @@ DEFAULT_MMAP_THRESHOLD default: 256K #ifndef WIN32 #ifdef _WIN32 #define WIN32 1 -#endif /* _WIN32 */ -#endif /* WIN32 */ +#endif /* _WIN32 */ +#endif /* WIN32 */ #ifdef WIN32 #define WIN32_LEAN_AND_MEAN #include @@ -491,123 +491,123 @@ DEFAULT_MMAP_THRESHOLD default: 256K #define LACKS_STRINGS_H #define LACKS_SYS_TYPES_H #define LACKS_ERRNO_H -#define LACKS_FCNTL_H +#define LACKS_FCNTL_H #define MALLOC_FAILURE_ACTION -#define MMAP_CLEARS 0 /* WINCE and some others apparently don't clear */ -#endif /* WIN32 */ +#define MMAP_CLEARS 0 /* WINCE and some others apparently don't clear */ +#endif /* WIN32 */ #if defined(DARWIN) || defined(_DARWIN) /* Mac OSX docs advise not to use sbrk; it seems better to use mmap */ #ifndef HAVE_MORECORE #define HAVE_MORECORE 0 #define HAVE_MMAP 1 -#endif /* HAVE_MORECORE */ -#endif /* DARWIN */ +#endif /* HAVE_MORECORE */ +#endif /* DARWIN */ #ifndef LACKS_SYS_TYPES_H -#include /* For size_t */ -#endif /* LACKS_SYS_TYPES_H */ +#include /* For size_t */ +#endif /* LACKS_SYS_TYPES_H */ /* The maximum possible size_t value has all bits set */ #define MAX_SIZE_T (~(size_t)0) #ifndef ONLY_MSPACES #define ONLY_MSPACES 0 -#endif /* ONLY_MSPACES */ +#endif /* ONLY_MSPACES */ #ifndef MSPACES #if ONLY_MSPACES #define MSPACES 1 -#else /* ONLY_MSPACES */ +#else /* ONLY_MSPACES */ #define MSPACES 0 -#endif /* ONLY_MSPACES */ -#endif /* MSPACES */ +#endif /* ONLY_MSPACES */ +#endif /* MSPACES */ #ifndef MALLOC_ALIGNMENT #define MALLOC_ALIGNMENT ((size_t)8U) -#endif /* MALLOC_ALIGNMENT */ +#endif /* MALLOC_ALIGNMENT */ #ifndef FOOTERS #define FOOTERS 0 -#endif /* FOOTERS */ +#endif /* FOOTERS */ #ifndef ABORT #define ABORT abort() -#endif /* ABORT */ +#endif /* ABORT */ #ifndef ABORT_ON_ASSERT_FAILURE #define ABORT_ON_ASSERT_FAILURE 1 -#endif /* ABORT_ON_ASSERT_FAILURE */ +#endif /* ABORT_ON_ASSERT_FAILURE */ #ifndef PROCEED_ON_ERROR #define PROCEED_ON_ERROR 0 -#endif /* PROCEED_ON_ERROR */ +#endif /* PROCEED_ON_ERROR */ #ifndef USE_LOCKS #define USE_LOCKS 0 -#endif /* USE_LOCKS */ +#endif /* USE_LOCKS */ #ifndef INSECURE #define INSECURE 0 -#endif /* INSECURE */ +#endif /* INSECURE */ #ifndef HAVE_MMAP #define HAVE_MMAP 1 -#endif /* HAVE_MMAP */ +#endif /* HAVE_MMAP */ #ifndef MMAP_CLEARS #define MMAP_CLEARS 1 -#endif /* MMAP_CLEARS */ +#endif /* MMAP_CLEARS */ #ifndef HAVE_MREMAP #ifdef linux #define HAVE_MREMAP 1 -#else /* linux */ +#else /* linux */ #define HAVE_MREMAP 0 -#endif /* linux */ -#endif /* HAVE_MREMAP */ +#endif /* linux */ +#endif /* HAVE_MREMAP */ #ifndef MALLOC_FAILURE_ACTION #define MALLOC_FAILURE_ACTION errno = ENOMEM; -#endif /* MALLOC_FAILURE_ACTION */ +#endif /* MALLOC_FAILURE_ACTION */ #ifndef HAVE_MORECORE #if ONLY_MSPACES #define HAVE_MORECORE 0 -#else /* ONLY_MSPACES */ +#else /* ONLY_MSPACES */ #define HAVE_MORECORE 1 -#endif /* ONLY_MSPACES */ -#endif /* HAVE_MORECORE */ +#endif /* ONLY_MSPACES */ +#endif /* HAVE_MORECORE */ #if !HAVE_MORECORE #define MORECORE_CONTIGUOUS 0 -#else /* !HAVE_MORECORE */ +#else /* !HAVE_MORECORE */ #ifndef MORECORE #define MORECORE sbrk -#endif /* MORECORE */ +#endif /* MORECORE */ #ifndef MORECORE_CONTIGUOUS #define MORECORE_CONTIGUOUS 1 -#endif /* MORECORE_CONTIGUOUS */ -#endif /* HAVE_MORECORE */ +#endif /* MORECORE_CONTIGUOUS */ +#endif /* HAVE_MORECORE */ #ifndef DEFAULT_GRANULARITY #if MORECORE_CONTIGUOUS -#define DEFAULT_GRANULARITY (0) /* 0 means to compute in init_mparams */ -#else /* MORECORE_CONTIGUOUS */ +#define DEFAULT_GRANULARITY (0) /* 0 means to compute in init_mparams */ +#else /* MORECORE_CONTIGUOUS */ #define DEFAULT_GRANULARITY ((size_t)64U * (size_t)1024U) -#endif /* MORECORE_CONTIGUOUS */ -#endif /* DEFAULT_GRANULARITY */ +#endif /* MORECORE_CONTIGUOUS */ +#endif /* DEFAULT_GRANULARITY */ #ifndef DEFAULT_TRIM_THRESHOLD #ifndef MORECORE_CANNOT_TRIM #define DEFAULT_TRIM_THRESHOLD ((size_t)2U * (size_t)1024U * (size_t)1024U) -#else /* MORECORE_CANNOT_TRIM */ +#else /* MORECORE_CANNOT_TRIM */ #define DEFAULT_TRIM_THRESHOLD MAX_SIZE_T -#endif /* MORECORE_CANNOT_TRIM */ -#endif /* DEFAULT_TRIM_THRESHOLD */ +#endif /* MORECORE_CANNOT_TRIM */ +#endif /* DEFAULT_TRIM_THRESHOLD */ #ifndef DEFAULT_MMAP_THRESHOLD #if HAVE_MMAP #define DEFAULT_MMAP_THRESHOLD ((size_t)256U * (size_t)1024U) -#else /* HAVE_MMAP */ +#else /* HAVE_MMAP */ #define DEFAULT_MMAP_THRESHOLD MAX_SIZE_T -#endif /* HAVE_MMAP */ -#endif /* DEFAULT_MMAP_THRESHOLD */ +#endif /* HAVE_MMAP */ +#endif /* DEFAULT_MMAP_THRESHOLD */ #ifndef USE_BUILTIN_FFS #define USE_BUILTIN_FFS 0 -#endif /* USE_BUILTIN_FFS */ +#endif /* USE_BUILTIN_FFS */ #ifndef USE_DEV_RANDOM #define USE_DEV_RANDOM 0 -#endif /* USE_DEV_RANDOM */ +#endif /* USE_DEV_RANDOM */ #ifndef NO_MALLINFO #define NO_MALLINFO 0 -#endif /* NO_MALLINFO */ +#endif /* NO_MALLINFO */ #ifndef MALLINFO_FIELD_TYPE #define MALLINFO_FIELD_TYPE size_t -#endif /* MALLINFO_FIELD_TYPE */ +#endif /* MALLINFO_FIELD_TYPE */ #define memset SDL_memset #define memcpy SDL_memcpy @@ -658,25 +658,27 @@ DEFAULT_MMAP_THRESHOLD default: 256K #include "/usr/include/malloc.h" #else /* HAVE_USR_INCLUDE_MALLOC_H */ -struct mallinfo { - MALLINFO_FIELD_TYPE arena; /* non-mmapped space allocated from system */ - MALLINFO_FIELD_TYPE ordblks; /* number of free chunks */ - MALLINFO_FIELD_TYPE smblks; /* always 0 */ - MALLINFO_FIELD_TYPE hblks; /* always 0 */ - MALLINFO_FIELD_TYPE hblkhd; /* space in mmapped regions */ - MALLINFO_FIELD_TYPE usmblks; /* maximum total allocated space */ - MALLINFO_FIELD_TYPE fsmblks; /* always 0 */ - MALLINFO_FIELD_TYPE uordblks; /* total allocated space */ - MALLINFO_FIELD_TYPE fordblks; /* total free space */ - MALLINFO_FIELD_TYPE keepcost; /* releasable (via malloc_trim) space */ +struct mallinfo +{ + MALLINFO_FIELD_TYPE arena; /* non-mmapped space allocated from system */ + MALLINFO_FIELD_TYPE ordblks; /* number of free chunks */ + MALLINFO_FIELD_TYPE smblks; /* always 0 */ + MALLINFO_FIELD_TYPE hblks; /* always 0 */ + MALLINFO_FIELD_TYPE hblkhd; /* space in mmapped regions */ + MALLINFO_FIELD_TYPE usmblks; /* maximum total allocated space */ + MALLINFO_FIELD_TYPE fsmblks; /* always 0 */ + MALLINFO_FIELD_TYPE uordblks; /* total allocated space */ + MALLINFO_FIELD_TYPE fordblks; /* total free space */ + MALLINFO_FIELD_TYPE keepcost; /* releasable (via malloc_trim) space */ }; #endif /* HAVE_USR_INCLUDE_MALLOC_H */ #endif /* NO_MALLINFO */ #ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ +extern "C" +{ +#endif /* __cplusplus */ #if !ONLY_MSPACES @@ -699,7 +701,7 @@ extern "C" { #define dlmalloc_max_footprint malloc_max_footprint #define dlindependent_calloc independent_calloc #define dlindependent_comalloc independent_comalloc -#endif /* USE_DL_PREFIX */ +#endif /* USE_DL_PREFIX */ /* @@ -716,7 +718,7 @@ extern "C" { maximum supported value of n differs across systems, but is in all cases less than the maximum representable value of a size_t. */ -void* dlmalloc(size_t); + void *dlmalloc(size_t); /* free(void* p) @@ -725,14 +727,14 @@ void* dlmalloc(size_t); It has no effect if p is null. If p was not malloced or already freed, free(p) will by default cause the current program to abort. */ -void dlfree(void*); + void dlfree(void *); /* calloc(size_t n_elements, size_t element_size); Returns a pointer to n_elements * element_size bytes, with all locations set to zero. */ -void* dlcalloc(size_t, size_t); + void *dlcalloc(size_t, size_t); /* realloc(void* p, size_t n) @@ -757,7 +759,7 @@ void* dlcalloc(size_t, size_t); to be used as an argument to realloc is not supported. */ -void* dlrealloc(void*, size_t); + void *dlrealloc(void *, size_t); /* memalign(size_t alignment, size_t n); @@ -771,14 +773,14 @@ void* dlrealloc(void*, size_t); Overreliance on memalign is a sure way to fragment space. */ -void* dlmemalign(size_t, size_t); + void *dlmemalign(size_t, size_t); /* valloc(size_t n); Equivalent to memalign(pagesize, n), where pagesize is the page size of the system. If the pagesize is unknown, 4096 is used. */ -void* dlvalloc(size_t); + void *dlvalloc(size_t); /* mallopt(int parameter_number, int parameter_value) @@ -798,7 +800,7 @@ void* dlvalloc(size_t); M_GRANULARITY -2 page size any power of 2 >= page size M_MMAP_THRESHOLD -3 256*1024 any (or 0 if no MMAP support) */ -int dlmallopt(int, int); + int dlmallopt(int, int); /* malloc_footprint(); @@ -809,7 +811,7 @@ int dlmallopt(int, int); Even if locks are otherwise defined, this function does not use them, so results might not be up to date. */ -size_t dlmalloc_footprint(void); + size_t dlmalloc_footprint(void); /* malloc_max_footprint(); @@ -822,7 +824,7 @@ size_t dlmalloc_footprint(void); otherwise defined, this function does not use them, so results might not be up to date. */ -size_t dlmalloc_max_footprint(void); + size_t dlmalloc_max_footprint(void); #if !NO_MALLINFO /* @@ -847,8 +849,8 @@ size_t dlmalloc_max_footprint(void); be kept as longs, the reported values may wrap around zero and thus be inaccurate. */ -struct mallinfo dlmallinfo(void); -#endif /* NO_MALLINFO */ + struct mallinfo dlmallinfo(void); +#endif /* NO_MALLINFO */ /* independent_calloc(size_t n_elements, size_t element_size, void* chunks[]); @@ -902,7 +904,7 @@ struct mallinfo dlmallinfo(void); return first; } */ -void** dlindependent_calloc(size_t, size_t, void**); + void **dlindependent_calloc(size_t, size_t, void **); /* independent_comalloc(size_t n_elements, size_t sizes[], void* chunks[]); @@ -963,7 +965,7 @@ void** dlindependent_calloc(size_t, size_t, void**); since it cannot reuse existing noncontiguous small chunks that might be available for some of the elements. */ -void** dlindependent_comalloc(size_t, size_t*, void**); + void **dlindependent_comalloc(size_t, size_t *, void **); /* @@ -971,7 +973,7 @@ void** dlindependent_comalloc(size_t, size_t*, void**); Equivalent to valloc(minimum-page-that-holds(n)), that is, round up n to nearest pagesize. */ -void* dlpvalloc(size_t); + void *dlpvalloc(size_t); /* malloc_trim(size_t pad); @@ -994,7 +996,7 @@ void* dlpvalloc(size_t); Malloc_trim returns 1 if it actually released any memory, else 0. */ -int dlmalloc_trim(size_t); + int dlmalloc_trim(size_t); /* malloc_usable_size(void* p); @@ -1010,7 +1012,7 @@ int dlmalloc_trim(size_t); p = malloc(n); assert(malloc_usable_size(p) >= 256); */ -size_t dlmalloc_usable_size(void*); + size_t dlmalloc_usable_size(void *); /* malloc_stats(); @@ -1031,9 +1033,9 @@ size_t dlmalloc_usable_size(void*); malloc_stats prints only the most commonly interesting statistics. More information can be obtained by calling mallinfo. */ -void dlmalloc_stats(void); + void dlmalloc_stats(void); -#endif /* ONLY_MSPACES */ +#endif /* ONLY_MSPACES */ #if MSPACES @@ -1041,7 +1043,7 @@ void dlmalloc_stats(void); mspace is an opaque type representing an independent region of space that supports mspace_malloc, etc. */ -typedef void* mspace; + typedef void *mspace; /* create_mspace creates and returns a new independent space with the @@ -1054,7 +1056,7 @@ typedef void* mspace; compiling with a different DEFAULT_GRANULARITY or dynamically setting with mallopt(M_GRANULARITY, value). */ -mspace create_mspace(size_t capacity, int locked); + mspace create_mspace(size_t capacity, int locked); /* destroy_mspace destroys the given space, and attempts to return all @@ -1062,7 +1064,7 @@ mspace create_mspace(size_t capacity, int locked); bytes freed. After destruction, the results of access to all memory used by the space become undefined. */ -size_t destroy_mspace(mspace msp); + size_t destroy_mspace(mspace msp); /* create_mspace_with_base uses the memory supplied as the initial base @@ -1073,13 +1075,13 @@ size_t destroy_mspace(mspace msp); Destroying this space will deallocate all additionally allocated space (if possible) but not the initial base. */ -mspace create_mspace_with_base(void* base, size_t capacity, int locked); + mspace create_mspace_with_base(void *base, size_t capacity, int locked); /* mspace_malloc behaves as malloc, but operates within the given space. */ -void* mspace_malloc(mspace msp, size_t bytes); + void *mspace_malloc(mspace msp, size_t bytes); /* mspace_free behaves as free, but operates within @@ -1089,7 +1091,7 @@ void* mspace_malloc(mspace msp, size_t bytes); free may be called instead of mspace_free because freed chunks from any space are handled by their originating spaces. */ -void mspace_free(mspace msp, void* mem); + void mspace_free(mspace msp, void *mem); /* mspace_realloc behaves as realloc, but operates within @@ -1100,45 +1102,45 @@ void mspace_free(mspace msp, void* mem); realloced chunks from any space are handled by their originating spaces. */ -void* mspace_realloc(mspace msp, void* mem, size_t newsize); + void *mspace_realloc(mspace msp, void *mem, size_t newsize); /* mspace_calloc behaves as calloc, but operates within the given space. */ -void* mspace_calloc(mspace msp, size_t n_elements, size_t elem_size); + void *mspace_calloc(mspace msp, size_t n_elements, size_t elem_size); /* mspace_memalign behaves as memalign, but operates within the given space. */ -void* mspace_memalign(mspace msp, size_t alignment, size_t bytes); + void *mspace_memalign(mspace msp, size_t alignment, size_t bytes); /* mspace_independent_calloc behaves as independent_calloc, but operates within the given space. */ -void** mspace_independent_calloc(mspace msp, size_t n_elements, - size_t elem_size, void* chunks[]); + void **mspace_independent_calloc(mspace msp, size_t n_elements, + size_t elem_size, void *chunks[]); /* mspace_independent_comalloc behaves as independent_comalloc, but operates within the given space. */ -void** mspace_independent_comalloc(mspace msp, size_t n_elements, - size_t sizes[], void* chunks[]); + void **mspace_independent_comalloc(mspace msp, size_t n_elements, + size_t sizes[], void *chunks[]); /* mspace_footprint() returns the number of bytes obtained from the system for this space. */ -size_t mspace_footprint(mspace msp); + size_t mspace_footprint(mspace msp); /* mspace_max_footprint() returns the peak number of bytes obtained from the system for this space. */ -size_t mspace_max_footprint(mspace msp); + size_t mspace_max_footprint(mspace msp); #if !NO_MALLINFO @@ -1146,30 +1148,30 @@ size_t mspace_max_footprint(mspace msp); mspace_mallinfo behaves as mallinfo, but reports properties of the given space. */ -struct mallinfo mspace_mallinfo(mspace msp); -#endif /* NO_MALLINFO */ + struct mallinfo mspace_mallinfo(mspace msp); +#endif /* NO_MALLINFO */ /* mspace_malloc_stats behaves as malloc_stats, but reports properties of the given space. */ -void mspace_malloc_stats(mspace msp); + void mspace_malloc_stats(mspace msp); /* mspace_trim behaves as malloc_trim, but operates within the given space. */ -int mspace_trim(mspace msp, size_t pad); + int mspace_trim(mspace msp, size_t pad); /* An alias for mallopt. */ -int mspace_mallopt(int, int); + int mspace_mallopt(int, int); -#endif /* MSPACES */ +#endif /* MSPACES */ #ifdef __cplusplus -}; /* end of extern "C" */ +}; /* end of extern "C" */ #endif /* __cplusplus */ /* @@ -1185,21 +1187,21 @@ int mspace_mallopt(int, int); /*------------------------------ internal #includes ---------------------- */ #ifdef _MSC_VER -#pragma warning( disable : 4146 ) /* no "unsigned" warnings */ +#pragma warning( disable : 4146 ) /* no "unsigned" warnings */ #endif /* _MSC_VER */ #ifndef LACKS_STDIO_H -#include /* for printing in malloc_stats */ +#include /* for printing in malloc_stats */ #endif #ifndef LACKS_ERRNO_H -#include /* for MALLOC_FAILURE_ACTION */ +#include /* for MALLOC_FAILURE_ACTION */ #endif /* LACKS_ERRNO_H */ #if FOOTERS -#include /* for magic initialization */ +#include /* for magic initialization */ #endif /* FOOTERS */ #ifndef LACKS_STDLIB_H -#include /* for abort() */ +#include /* for abort() */ #endif /* LACKS_STDLIB_H */ #ifdef DEBUG #if ABORT_ON_ASSERT_FAILURE @@ -1207,20 +1209,20 @@ int mspace_mallopt(int, int); #else /* ABORT_ON_ASSERT_FAILURE */ #include #endif /* ABORT_ON_ASSERT_FAILURE */ -#else /* DEBUG */ +#else /* DEBUG */ #define assert(x) #endif /* DEBUG */ #ifndef LACKS_STRING_H -#include /* for memset etc */ -#endif /* LACKS_STRING_H */ +#include /* for memset etc */ +#endif /* LACKS_STRING_H */ #if USE_BUILTIN_FFS #ifndef LACKS_STRINGS_H -#include /* for ffs */ +#include /* for ffs */ #endif /* LACKS_STRINGS_H */ #endif /* USE_BUILTIN_FFS */ #if HAVE_MMAP #ifndef LACKS_SYS_MMAN_H -#include /* for mmap */ +#include /* for mmap */ #endif /* LACKS_SYS_MMAN_H */ #ifndef LACKS_FCNTL_H #include @@ -1228,17 +1230,17 @@ int mspace_mallopt(int, int); #endif /* HAVE_MMAP */ #if HAVE_MORECORE #ifndef LACKS_UNISTD_H -#include /* for sbrk */ +#include /* for sbrk */ #else /* LACKS_UNISTD_H */ #if !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__) -extern void* sbrk(ptrdiff_t); +extern void *sbrk(ptrdiff_t); #endif /* FreeBSD etc */ #endif /* LACKS_UNISTD_H */ #endif /* HAVE_MMAP */ #ifndef WIN32 #ifndef malloc_getpagesize -# ifdef _SC_PAGESIZE /* some SVR4 systems omit an underscore */ +# ifdef _SC_PAGESIZE /* some SVR4 systems omit an underscore */ # ifndef _SC_PAGE_SIZE # define _SC_PAGE_SIZE _SC_PAGESIZE # endif @@ -1247,10 +1249,10 @@ extern void* sbrk(ptrdiff_t); # define malloc_getpagesize sysconf(_SC_PAGE_SIZE) # else # if defined(BSD) || defined(DGUX) || defined(HAVE_GETPAGESIZE) - extern size_t getpagesize(); +extern size_t getpagesize(); # define malloc_getpagesize getpagesize() # else -# ifdef WIN32 /* use supplied emulation of getpagesize */ +# ifdef WIN32 /* use supplied emulation of getpagesize */ # define malloc_getpagesize getpagesize() # else # ifndef LACKS_SYS_PARAM_H @@ -1321,7 +1323,7 @@ extern void* sbrk(ptrdiff_t); /* MORECORE and MMAP must return MFAIL on failure */ #define MFAIL ((void*)(MAX_SIZE_T)) -#define CMFAIL ((char*)(MFAIL)) /* defined for convenience */ +#define CMFAIL ((char*)(MFAIL)) /* defined for convenience */ #if !HAVE_MMAP #define IS_MMAPPED_BIT (SIZE_T_ZERO) @@ -1349,7 +1351,7 @@ extern void* sbrk(ptrdiff_t); is unlikely to be needed, but is supplied just in case. */ #define MMAP_FLAGS (MAP_PRIVATE) -static int dev_zero_fd = -1; /* Cached file descriptor for /dev/zero. */ +static int dev_zero_fd = -1; /* Cached file descriptor for /dev/zero. */ #define CALL_MMAP(s) ((dev_zero_fd < 0) ? \ (dev_zero_fd = open("/dev/zero", O_RDWR), \ mmap(0, (s), MMAP_PROT, MMAP_FLAGS, dev_zero_fd, 0)) : \ @@ -1360,34 +1362,41 @@ static int dev_zero_fd = -1; /* Cached file descriptor for /dev/zero. */ #else /* WIN32 */ /* Win32 MMAP via VirtualAlloc */ -static void* win32mmap(size_t size) { - void* ptr = VirtualAlloc(0, size, MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE); - return (ptr != 0)? ptr: MFAIL; +static void * +win32mmap(size_t size) +{ + void *ptr = + VirtualAlloc(0, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + return (ptr != 0) ? ptr : MFAIL; } /* For direct MMAP, use MEM_TOP_DOWN to minimize interference */ -static void* win32direct_mmap(size_t size) { - void* ptr = VirtualAlloc(0, size, MEM_RESERVE|MEM_COMMIT|MEM_TOP_DOWN, - PAGE_READWRITE); - return (ptr != 0)? ptr: MFAIL; +static void * +win32direct_mmap(size_t size) +{ + void *ptr = VirtualAlloc(0, size, MEM_RESERVE | MEM_COMMIT | MEM_TOP_DOWN, + PAGE_READWRITE); + return (ptr != 0) ? ptr : MFAIL; } /* This function supports releasing coalesed segments */ -static int win32munmap(void* ptr, size_t size) { - MEMORY_BASIC_INFORMATION minfo; - char* cptr = ptr; - while (size) { - if (VirtualQuery(cptr, &minfo, sizeof(minfo)) == 0) - return -1; - if (minfo.BaseAddress != cptr || minfo.AllocationBase != cptr || - minfo.State != MEM_COMMIT || minfo.RegionSize > size) - return -1; - if (VirtualFree(cptr, 0, MEM_RELEASE) == 0) - return -1; - cptr += minfo.RegionSize; - size -= minfo.RegionSize; - } - return 0; +static int +win32munmap(void *ptr, size_t size) +{ + MEMORY_BASIC_INFORMATION minfo; + char *cptr = ptr; + while (size) { + if (VirtualQuery(cptr, &minfo, sizeof(minfo)) == 0) + return -1; + if (minfo.BaseAddress != cptr || minfo.AllocationBase != cptr || + minfo.State != MEM_COMMIT || minfo.RegionSize > size) + return -1; + if (VirtualFree(cptr, 0, MEM_RELEASE) == 0) + return -1; + cptr += minfo.RegionSize; + size -= minfo.RegionSize; + } + return 0; } #define CALL_MMAP(s) win32mmap(s) @@ -1398,13 +1407,13 @@ static int win32munmap(void* ptr, size_t size) { #if HAVE_MMAP && HAVE_MREMAP #define CALL_MREMAP(addr, osz, nsz, mv) mremap((addr), (osz), (nsz), (mv)) -#else /* HAVE_MMAP && HAVE_MREMAP */ +#else /* HAVE_MMAP && HAVE_MREMAP */ #define CALL_MREMAP(addr, osz, nsz, mv) MFAIL #endif /* HAVE_MMAP && HAVE_MREMAP */ #if HAVE_MORECORE #define CALL_MORECORE(S) MORECORE(S) -#else /* HAVE_MORECORE */ +#else /* HAVE_MORECORE */ #define CALL_MORECORE(S) MFAIL #endif /* HAVE_MORECORE */ @@ -1454,21 +1463,25 @@ static MLOCK_T magic_init_mutex = PTHREAD_MUTEX_INITIALIZER; */ #define MLOCK_T long -static int win32_acquire_lock (MLOCK_T *sl) { - for (;;) { +static int +win32_acquire_lock(MLOCK_T * sl) +{ + for (;;) { #ifdef InterlockedCompareExchangePointer - if (!InterlockedCompareExchange(sl, 1, 0)) - return 0; -#else /* Use older void* version */ - if (!InterlockedCompareExchange((void**)sl, (void*)1, (void*)0)) - return 0; + if (!InterlockedCompareExchange(sl, 1, 0)) + return 0; +#else /* Use older void* version */ + if (!InterlockedCompareExchange((void **) sl, (void *) 1, (void *) 0)) + return 0; #endif /* InterlockedCompareExchangePointer */ - Sleep (0); - } + Sleep(0); + } } -static void win32_release_lock (MLOCK_T *sl) { - InterlockedExchange (sl, 0); +static void +win32_release_lock(MLOCK_T * sl) +{ + InterlockedExchange(sl, 0); } #define INITIAL_LOCK(l) *(l)=0 @@ -1481,7 +1494,7 @@ static MLOCK_T magic_init_mutex; #endif /* WIN32 */ #define USE_LOCK_BIT (2U) -#else /* USE_LOCKS */ +#else /* USE_LOCKS */ #define USE_LOCK_BIT (0U) #define INITIAL_LOCK(l) #endif /* USE_LOCKS */ @@ -1497,7 +1510,7 @@ static MLOCK_T magic_init_mutex; #if USE_LOCKS #define ACQUIRE_MAGIC_INIT_LOCK() ACQUIRE_LOCK(&magic_init_mutex); #define RELEASE_MAGIC_INIT_LOCK() RELEASE_LOCK(&magic_init_mutex); -#else /* USE_LOCKS */ +#else /* USE_LOCKS */ #define ACQUIRE_MAGIC_INIT_LOCK() #define RELEASE_MAGIC_INIT_LOCK() #endif /* USE_LOCKS */ @@ -1640,19 +1653,20 @@ static MLOCK_T magic_init_mutex; */ -struct malloc_chunk { - size_t prev_foot; /* Size of previous chunk (if free). */ - size_t head; /* Size and inuse bits. */ - struct malloc_chunk* fd; /* double links -- used only if free. */ - struct malloc_chunk* bk; +struct malloc_chunk +{ + size_t prev_foot; /* Size of previous chunk (if free). */ + size_t head; /* Size and inuse bits. */ + struct malloc_chunk *fd; /* double links -- used only if free. */ + struct malloc_chunk *bk; }; -typedef struct malloc_chunk mchunk; -typedef struct malloc_chunk* mchunkptr; -typedef struct malloc_chunk* sbinptr; /* The type of bins of chunks */ -typedef size_t bindex_t; /* Described below */ -typedef unsigned int binmap_t; /* Described below */ -typedef unsigned int flag_t; /* The type of various bit flag sets */ +typedef struct malloc_chunk mchunk; +typedef struct malloc_chunk *mchunkptr; +typedef struct malloc_chunk *sbinptr; /* The type of bins of chunks */ +typedef size_t bindex_t; /* Described below */ +typedef unsigned int binmap_t; /* Described below */ +typedef unsigned int flag_t; /* The type of various bit flag sets */ /* ------------------- Chunks sizes and alignments ----------------------- */ @@ -1845,21 +1859,22 @@ nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ is of course much better. */ -struct malloc_tree_chunk { - /* The first four fields must be compatible with malloc_chunk */ - size_t prev_foot; - size_t head; - struct malloc_tree_chunk* fd; - struct malloc_tree_chunk* bk; - - struct malloc_tree_chunk* child[2]; - struct malloc_tree_chunk* parent; - bindex_t index; +struct malloc_tree_chunk +{ + /* The first four fields must be compatible with malloc_chunk */ + size_t prev_foot; + size_t head; + struct malloc_tree_chunk *fd; + struct malloc_tree_chunk *bk; + + struct malloc_tree_chunk *child[2]; + struct malloc_tree_chunk *parent; + bindex_t index; }; -typedef struct malloc_tree_chunk tchunk; -typedef struct malloc_tree_chunk* tchunkptr; -typedef struct malloc_tree_chunk* tbinptr; /* The type of bins of trees */ +typedef struct malloc_tree_chunk tchunk; +typedef struct malloc_tree_chunk *tchunkptr; +typedef struct malloc_tree_chunk *tbinptr; /* The type of bins of trees */ /* A little helper macro for trees */ #define leftmost_child(t) ((t)->child[0] != 0? (t)->child[0] : (t)->child[1]) @@ -1921,18 +1936,19 @@ typedef struct malloc_tree_chunk* tbinptr; /* The type of bins of trees */ and deallocated/trimmed using MORECORE with negative arguments. */ -struct malloc_segment { - char* base; /* base address */ - size_t size; /* allocated size */ - struct malloc_segment* next; /* ptr to next segment */ - flag_t sflags; /* mmap and extern flag */ +struct malloc_segment +{ + char *base; /* base address */ + size_t size; /* allocated size */ + struct malloc_segment *next; /* ptr to next segment */ + flag_t sflags; /* mmap and extern flag */ }; #define is_mmapped_segment(S) ((S)->sflags & IS_MMAPPED_BIT) #define is_extern_segment(S) ((S)->sflags & EXTERN_BIT) -typedef struct malloc_segment msegment; -typedef struct malloc_segment* msegmentptr; +typedef struct malloc_segment msegment; +typedef struct malloc_segment *msegmentptr; /* ---------------------------- malloc_state ----------------------------- */ @@ -2019,28 +2035,29 @@ typedef struct malloc_segment* msegmentptr; #define MAX_SMALL_SIZE (MIN_LARGE_SIZE - SIZE_T_ONE) #define MAX_SMALL_REQUEST (MAX_SMALL_SIZE - CHUNK_ALIGN_MASK - CHUNK_OVERHEAD) -struct malloc_state { - binmap_t smallmap; - binmap_t treemap; - size_t dvsize; - size_t topsize; - char* least_addr; - mchunkptr dv; - mchunkptr top; - size_t trim_check; - size_t magic; - mchunkptr smallbins[(NSMALLBINS+1)*2]; - tbinptr treebins[NTREEBINS]; - size_t footprint; - size_t max_footprint; - flag_t mflags; +struct malloc_state +{ + binmap_t smallmap; + binmap_t treemap; + size_t dvsize; + size_t topsize; + char *least_addr; + mchunkptr dv; + mchunkptr top; + size_t trim_check; + size_t magic; + mchunkptr smallbins[(NSMALLBINS + 1) * 2]; + tbinptr treebins[NTREEBINS]; + size_t footprint; + size_t max_footprint; + flag_t mflags; #if USE_LOCKS - MLOCK_T mutex; /* locate lock among fields that rarely change */ -#endif /* USE_LOCKS */ - msegment seg; + MLOCK_T mutex; /* locate lock among fields that rarely change */ +#endif /* USE_LOCKS */ + msegment seg; }; -typedef struct malloc_state* mstate; +typedef struct malloc_state *mstate; /* ------------- Global malloc_state and malloc_params ------------------- */ @@ -2050,13 +2067,14 @@ typedef struct malloc_state* mstate; initialized in init_mparams. */ -struct malloc_params { - size_t magic; - size_t page_size; - size_t granularity; - size_t mmap_threshold; - size_t trim_threshold; - flag_t default_mflags; +struct malloc_params +{ + size_t magic; + size_t page_size; + size_t granularity; + size_t mmap_threshold; + size_t trim_threshold; + flag_t default_mflags; }; static struct malloc_params mparams; @@ -2105,30 +2123,34 @@ static struct malloc_state _gm_; ((char*)(A) >= S->base && (char*)(A) < S->base + S->size) /* Return segment holding given address */ -static msegmentptr segment_holding(mstate m, char* addr) { - msegmentptr sp = &m->seg; - for (;;) { - if (addr >= sp->base && addr < sp->base + sp->size) - return sp; - if ((sp = sp->next) == 0) - return 0; - } +static msegmentptr +segment_holding(mstate m, char *addr) +{ + msegmentptr sp = &m->seg; + for (;;) { + if (addr >= sp->base && addr < sp->base + sp->size) + return sp; + if ((sp = sp->next) == 0) + return 0; + } } /* Return true if segment contains a segment link */ -static int has_segment_link(mstate m, msegmentptr ss) { - msegmentptr sp = &m->seg; - for (;;) { - if ((char*)sp >= ss->base && (char*)sp < ss->base + ss->size) - return 1; - if ((sp = sp->next) == 0) - return 0; - } +static int +has_segment_link(mstate m, msegmentptr ss) +{ + msegmentptr sp = &m->seg; + for (;;) { + if ((char *) sp >= ss->base && (char *) sp < ss->base + ss->size) + return 1; + if ((sp = sp->next) == 0) + return 0; + } } #ifndef MORECORE_CANNOT_TRIM #define should_trim(M,s) ((s) > (M)->trim_check) -#else /* MORECORE_CANNOT_TRIM */ +#else /* MORECORE_CANNOT_TRIM */ #define should_trim(M,s) (0) #endif /* MORECORE_CANNOT_TRIM */ @@ -2160,11 +2182,11 @@ static int has_segment_link(mstate m, msegmentptr ss) { #ifndef PREACTION #define PREACTION(M) (0) -#endif /* PREACTION */ +#endif /* PREACTION */ #ifndef POSTACTION #define POSTACTION(M) -#endif /* POSTACTION */ +#endif /* POSTACTION */ #endif /* USE_LOCKS */ @@ -2218,17 +2240,17 @@ static void reset_on_error(mstate m); #define check_mmapped_chunk(M,P) do_check_mmapped_chunk(M,P) #define check_malloc_state(M) do_check_malloc_state(M) -static void do_check_any_chunk(mstate m, mchunkptr p); -static void do_check_top_chunk(mstate m, mchunkptr p); -static void do_check_mmapped_chunk(mstate m, mchunkptr p); -static void do_check_inuse_chunk(mstate m, mchunkptr p); -static void do_check_free_chunk(mstate m, mchunkptr p); -static void do_check_malloced_chunk(mstate m, void* mem, size_t s); -static void do_check_tree(mstate m, tchunkptr t); -static void do_check_treebin(mstate m, bindex_t i); -static void do_check_smallbin(mstate m, bindex_t i); -static void do_check_malloc_state(mstate m); -static int bin_find(mstate m, mchunkptr x); +static void do_check_any_chunk(mstate m, mchunkptr p); +static void do_check_top_chunk(mstate m, mchunkptr p); +static void do_check_mmapped_chunk(mstate m, mchunkptr p); +static void do_check_inuse_chunk(mstate m, mchunkptr p); +static void do_check_free_chunk(mstate m, mchunkptr p); +static void do_check_malloced_chunk(mstate m, void *mem, size_t s); +static void do_check_tree(mstate m, tchunkptr t); +static void do_check_treebin(mstate m, bindex_t i); +static void do_check_smallbin(mstate m, bindex_t i); +static void do_check_malloc_state(mstate m); +static int bin_find(mstate m, mchunkptr x); static size_t traverse_and_check(mstate m); #endif /* DEBUG */ @@ -2394,7 +2416,7 @@ static size_t traverse_and_check(mstate m); #if (FOOTERS && !INSECURE) /* Check if (alleged) mstate m has expected magic field */ #define ok_magic(M) ((M)->magic == mparams.magic) -#else /* (FOOTERS && !INSECURE) */ +#else /* (FOOTERS && !INSECURE) */ #define ok_magic(M) (1) #endif /* (FOOTERS && !INSECURE) */ @@ -2459,446 +2481,477 @@ static size_t traverse_and_check(mstate m); /* ---------------------------- setting mparams -------------------------- */ /* Initialize mparams */ -static int init_mparams(void) { - if (mparams.page_size == 0) { - size_t s; - - mparams.mmap_threshold = DEFAULT_MMAP_THRESHOLD; - mparams.trim_threshold = DEFAULT_TRIM_THRESHOLD; +static int +init_mparams(void) +{ + if (mparams.page_size == 0) { + size_t s; + + mparams.mmap_threshold = DEFAULT_MMAP_THRESHOLD; + mparams.trim_threshold = DEFAULT_TRIM_THRESHOLD; #if MORECORE_CONTIGUOUS - mparams.default_mflags = USE_LOCK_BIT|USE_MMAP_BIT; -#else /* MORECORE_CONTIGUOUS */ - mparams.default_mflags = USE_LOCK_BIT|USE_MMAP_BIT|USE_NONCONTIGUOUS_BIT; + mparams.default_mflags = USE_LOCK_BIT | USE_MMAP_BIT; +#else /* MORECORE_CONTIGUOUS */ + mparams.default_mflags = + USE_LOCK_BIT | USE_MMAP_BIT | USE_NONCONTIGUOUS_BIT; #endif /* MORECORE_CONTIGUOUS */ #if (FOOTERS && !INSECURE) - { + { #if USE_DEV_RANDOM - int fd; - unsigned char buf[sizeof(size_t)]; - /* Try to use /dev/urandom, else fall back on using time */ - if ((fd = open("/dev/urandom", O_RDONLY)) >= 0 && - read(fd, buf, sizeof(buf)) == sizeof(buf)) { - s = *((size_t *) buf); - close(fd); - } - else + int fd; + unsigned char buf[sizeof(size_t)]; + /* Try to use /dev/urandom, else fall back on using time */ + if ((fd = open("/dev/urandom", O_RDONLY)) >= 0 && + read(fd, buf, sizeof(buf)) == sizeof(buf)) { + s = *((size_t *) buf); + close(fd); + } else #endif /* USE_DEV_RANDOM */ - s = (size_t)(time(0) ^ (size_t)0x55555555U); + s = (size_t) (time(0) ^ (size_t) 0x55555555U); - s |= (size_t)8U; /* ensure nonzero */ - s &= ~(size_t)7U; /* improve chances of fault for bad values */ + s |= (size_t) 8U; /* ensure nonzero */ + s &= ~(size_t) 7U; /* improve chances of fault for bad values */ - } + } #else /* (FOOTERS && !INSECURE) */ - s = (size_t)0x58585858U; + s = (size_t) 0x58585858U; #endif /* (FOOTERS && !INSECURE) */ - ACQUIRE_MAGIC_INIT_LOCK(); - if (mparams.magic == 0) { - mparams.magic = s; - /* Set up lock for main malloc area */ - INITIAL_LOCK(&gm->mutex); - gm->mflags = mparams.default_mflags; - } - RELEASE_MAGIC_INIT_LOCK(); + ACQUIRE_MAGIC_INIT_LOCK(); + if (mparams.magic == 0) { + mparams.magic = s; + /* Set up lock for main malloc area */ + INITIAL_LOCK(&gm->mutex); + gm->mflags = mparams.default_mflags; + } + RELEASE_MAGIC_INIT_LOCK(); #ifndef WIN32 - mparams.page_size = malloc_getpagesize; - mparams.granularity = ((DEFAULT_GRANULARITY != 0)? - DEFAULT_GRANULARITY : mparams.page_size); + mparams.page_size = malloc_getpagesize; + mparams.granularity = ((DEFAULT_GRANULARITY != 0) ? + DEFAULT_GRANULARITY : mparams.page_size); #else /* WIN32 */ - { - SYSTEM_INFO system_info; - GetSystemInfo(&system_info); - mparams.page_size = system_info.dwPageSize; - mparams.granularity = system_info.dwAllocationGranularity; - } + { + SYSTEM_INFO system_info; + GetSystemInfo(&system_info); + mparams.page_size = system_info.dwPageSize; + mparams.granularity = system_info.dwAllocationGranularity; + } #endif /* WIN32 */ - /* Sanity-check configuration: - size_t must be unsigned and as wide as pointer type. - ints must be at least 4 bytes. - alignment must be at least 8. - Alignment, min chunk size, and page size must all be powers of 2. - */ - if ((sizeof(size_t) != sizeof(char*)) || - (MAX_SIZE_T < MIN_CHUNK_SIZE) || - (sizeof(int) < 4) || - (MALLOC_ALIGNMENT < (size_t)8U) || - ((MALLOC_ALIGNMENT & (MALLOC_ALIGNMENT-SIZE_T_ONE)) != 0) || - ((MCHUNK_SIZE & (MCHUNK_SIZE-SIZE_T_ONE)) != 0) || - ((mparams.granularity & (mparams.granularity-SIZE_T_ONE)) != 0) || - ((mparams.page_size & (mparams.page_size-SIZE_T_ONE)) != 0)) - ABORT; - } - return 0; + /* Sanity-check configuration: + size_t must be unsigned and as wide as pointer type. + ints must be at least 4 bytes. + alignment must be at least 8. + Alignment, min chunk size, and page size must all be powers of 2. + */ + if ((sizeof(size_t) != sizeof(char *)) || + (MAX_SIZE_T < MIN_CHUNK_SIZE) || + (sizeof(int) < 4) || + (MALLOC_ALIGNMENT < (size_t) 8U) || + ((MALLOC_ALIGNMENT & (MALLOC_ALIGNMENT - SIZE_T_ONE)) != 0) || + ((MCHUNK_SIZE & (MCHUNK_SIZE - SIZE_T_ONE)) != 0) || + ((mparams.granularity & (mparams.granularity - SIZE_T_ONE)) != 0) + || ((mparams.page_size & (mparams.page_size - SIZE_T_ONE)) != 0)) + ABORT; + } + return 0; } /* support for mallopt */ -static int change_mparam(int param_number, int value) { - size_t val = (size_t)value; - init_mparams(); - switch(param_number) { - case M_TRIM_THRESHOLD: - mparams.trim_threshold = val; - return 1; - case M_GRANULARITY: - if (val >= mparams.page_size && ((val & (val-1)) == 0)) { - mparams.granularity = val; - return 1; +static int +change_mparam(int param_number, int value) +{ + size_t val = (size_t) value; + init_mparams(); + switch (param_number) { + case M_TRIM_THRESHOLD: + mparams.trim_threshold = val; + return 1; + case M_GRANULARITY: + if (val >= mparams.page_size && ((val & (val - 1)) == 0)) { + mparams.granularity = val; + return 1; + } else + return 0; + case M_MMAP_THRESHOLD: + mparams.mmap_threshold = val; + return 1; + default: + return 0; } - else - return 0; - case M_MMAP_THRESHOLD: - mparams.mmap_threshold = val; - return 1; - default: - return 0; - } } #if DEBUG /* ------------------------- Debugging Support --------------------------- */ /* Check properties of any chunk, whether free, inuse, mmapped etc */ -static void do_check_any_chunk(mstate m, mchunkptr p) { - assert((is_aligned(chunk2mem(p))) || (p->head == FENCEPOST_HEAD)); - assert(ok_address(m, p)); +static void +do_check_any_chunk(mstate m, mchunkptr p) +{ + assert((is_aligned(chunk2mem(p))) || (p->head == FENCEPOST_HEAD)); + assert(ok_address(m, p)); } /* Check properties of top chunk */ -static void do_check_top_chunk(mstate m, mchunkptr p) { - msegmentptr sp = segment_holding(m, (char*)p); - size_t sz = chunksize(p); - assert(sp != 0); - assert((is_aligned(chunk2mem(p))) || (p->head == FENCEPOST_HEAD)); - assert(ok_address(m, p)); - assert(sz == m->topsize); - assert(sz > 0); - assert(sz == ((sp->base + sp->size) - (char*)p) - TOP_FOOT_SIZE); - assert(pinuse(p)); - assert(!next_pinuse(p)); +static void +do_check_top_chunk(mstate m, mchunkptr p) +{ + msegmentptr sp = segment_holding(m, (char *) p); + size_t sz = chunksize(p); + assert(sp != 0); + assert((is_aligned(chunk2mem(p))) || (p->head == FENCEPOST_HEAD)); + assert(ok_address(m, p)); + assert(sz == m->topsize); + assert(sz > 0); + assert(sz == ((sp->base + sp->size) - (char *) p) - TOP_FOOT_SIZE); + assert(pinuse(p)); + assert(!next_pinuse(p)); } /* Check properties of (inuse) mmapped chunks */ -static void do_check_mmapped_chunk(mstate m, mchunkptr p) { - size_t sz = chunksize(p); - size_t len = (sz + (p->prev_foot & ~IS_MMAPPED_BIT) + MMAP_FOOT_PAD); - assert(is_mmapped(p)); - assert(use_mmap(m)); - assert((is_aligned(chunk2mem(p))) || (p->head == FENCEPOST_HEAD)); - assert(ok_address(m, p)); - assert(!is_small(sz)); - assert((len & (mparams.page_size-SIZE_T_ONE)) == 0); - assert(chunk_plus_offset(p, sz)->head == FENCEPOST_HEAD); - assert(chunk_plus_offset(p, sz+SIZE_T_SIZE)->head == 0); +static void +do_check_mmapped_chunk(mstate m, mchunkptr p) +{ + size_t sz = chunksize(p); + size_t len = (sz + (p->prev_foot & ~IS_MMAPPED_BIT) + MMAP_FOOT_PAD); + assert(is_mmapped(p)); + assert(use_mmap(m)); + assert((is_aligned(chunk2mem(p))) || (p->head == FENCEPOST_HEAD)); + assert(ok_address(m, p)); + assert(!is_small(sz)); + assert((len & (mparams.page_size - SIZE_T_ONE)) == 0); + assert(chunk_plus_offset(p, sz)->head == FENCEPOST_HEAD); + assert(chunk_plus_offset(p, sz + SIZE_T_SIZE)->head == 0); } /* Check properties of inuse chunks */ -static void do_check_inuse_chunk(mstate m, mchunkptr p) { - do_check_any_chunk(m, p); - assert(cinuse(p)); - assert(next_pinuse(p)); - /* If not pinuse and not mmapped, previous chunk has OK offset */ - assert(is_mmapped(p) || pinuse(p) || next_chunk(prev_chunk(p)) == p); - if (is_mmapped(p)) - do_check_mmapped_chunk(m, p); +static void +do_check_inuse_chunk(mstate m, mchunkptr p) +{ + do_check_any_chunk(m, p); + assert(cinuse(p)); + assert(next_pinuse(p)); + /* If not pinuse and not mmapped, previous chunk has OK offset */ + assert(is_mmapped(p) || pinuse(p) || next_chunk(prev_chunk(p)) == p); + if (is_mmapped(p)) + do_check_mmapped_chunk(m, p); } /* Check properties of free chunks */ -static void do_check_free_chunk(mstate m, mchunkptr p) { - size_t sz = p->head & ~(PINUSE_BIT|CINUSE_BIT); - mchunkptr next = chunk_plus_offset(p, sz); - do_check_any_chunk(m, p); - assert(!cinuse(p)); - assert(!next_pinuse(p)); - assert (!is_mmapped(p)); - if (p != m->dv && p != m->top) { - if (sz >= MIN_CHUNK_SIZE) { - assert((sz & CHUNK_ALIGN_MASK) == 0); - assert(is_aligned(chunk2mem(p))); - assert(next->prev_foot == sz); - assert(pinuse(p)); - assert (next == m->top || cinuse(next)); - assert(p->fd->bk == p); - assert(p->bk->fd == p); +static void +do_check_free_chunk(mstate m, mchunkptr p) +{ + size_t sz = p->head & ~(PINUSE_BIT | CINUSE_BIT); + mchunkptr next = chunk_plus_offset(p, sz); + do_check_any_chunk(m, p); + assert(!cinuse(p)); + assert(!next_pinuse(p)); + assert(!is_mmapped(p)); + if (p != m->dv && p != m->top) { + if (sz >= MIN_CHUNK_SIZE) { + assert((sz & CHUNK_ALIGN_MASK) == 0); + assert(is_aligned(chunk2mem(p))); + assert(next->prev_foot == sz); + assert(pinuse(p)); + assert(next == m->top || cinuse(next)); + assert(p->fd->bk == p); + assert(p->bk->fd == p); + } else /* markers are always of size SIZE_T_SIZE */ + assert(sz == SIZE_T_SIZE); } - else /* markers are always of size SIZE_T_SIZE */ - assert(sz == SIZE_T_SIZE); - } } /* Check properties of malloced chunks at the point they are malloced */ -static void do_check_malloced_chunk(mstate m, void* mem, size_t s) { - if (mem != 0) { - mchunkptr p = mem2chunk(mem); - size_t sz = p->head & ~(PINUSE_BIT|CINUSE_BIT); - do_check_inuse_chunk(m, p); - assert((sz & CHUNK_ALIGN_MASK) == 0); - assert(sz >= MIN_CHUNK_SIZE); - assert(sz >= s); - /* unless mmapped, size is less than MIN_CHUNK_SIZE more than request */ - assert(is_mmapped(p) || sz < (s + MIN_CHUNK_SIZE)); - } +static void +do_check_malloced_chunk(mstate m, void *mem, size_t s) +{ + if (mem != 0) { + mchunkptr p = mem2chunk(mem); + size_t sz = p->head & ~(PINUSE_BIT | CINUSE_BIT); + do_check_inuse_chunk(m, p); + assert((sz & CHUNK_ALIGN_MASK) == 0); + assert(sz >= MIN_CHUNK_SIZE); + assert(sz >= s); + /* unless mmapped, size is less than MIN_CHUNK_SIZE more than request */ + assert(is_mmapped(p) || sz < (s + MIN_CHUNK_SIZE)); + } } /* Check a tree and its subtrees. */ -static void do_check_tree(mstate m, tchunkptr t) { - tchunkptr head = 0; - tchunkptr u = t; - bindex_t tindex = t->index; - size_t tsize = chunksize(t); - bindex_t idx; - compute_tree_index(tsize, idx); - assert(tindex == idx); - assert(tsize >= MIN_LARGE_SIZE); - assert(tsize >= minsize_for_tree_index(idx)); - assert((idx == NTREEBINS-1) || (tsize < minsize_for_tree_index((idx+1)))); - - do { /* traverse through chain of same-sized nodes */ - do_check_any_chunk(m, ((mchunkptr)u)); - assert(u->index == tindex); - assert(chunksize(u) == tsize); - assert(!cinuse(u)); - assert(!next_pinuse(u)); - assert(u->fd->bk == u); - assert(u->bk->fd == u); - if (u->parent == 0) { - assert(u->child[0] == 0); - assert(u->child[1] == 0); - } - else { - assert(head == 0); /* only one node on chain has parent */ - head = u; - assert(u->parent != u); - assert (u->parent->child[0] == u || - u->parent->child[1] == u || - *((tbinptr*)(u->parent)) == u); - if (u->child[0] != 0) { - assert(u->child[0]->parent == u); - assert(u->child[0] != u); - do_check_tree(m, u->child[0]); - } - if (u->child[1] != 0) { - assert(u->child[1]->parent == u); - assert(u->child[1] != u); - do_check_tree(m, u->child[1]); - } - if (u->child[0] != 0 && u->child[1] != 0) { - assert(chunksize(u->child[0]) < chunksize(u->child[1])); - } +static void +do_check_tree(mstate m, tchunkptr t) +{ + tchunkptr head = 0; + tchunkptr u = t; + bindex_t tindex = t->index; + size_t tsize = chunksize(t); + bindex_t idx; + compute_tree_index(tsize, idx); + assert(tindex == idx); + assert(tsize >= MIN_LARGE_SIZE); + assert(tsize >= minsize_for_tree_index(idx)); + assert((idx == NTREEBINS - 1) + || (tsize < minsize_for_tree_index((idx + 1)))); + + do { /* traverse through chain of same-sized nodes */ + do_check_any_chunk(m, ((mchunkptr) u)); + assert(u->index == tindex); + assert(chunksize(u) == tsize); + assert(!cinuse(u)); + assert(!next_pinuse(u)); + assert(u->fd->bk == u); + assert(u->bk->fd == u); + if (u->parent == 0) { + assert(u->child[0] == 0); + assert(u->child[1] == 0); + } else { + assert(head == 0); /* only one node on chain has parent */ + head = u; + assert(u->parent != u); + assert(u->parent->child[0] == u || + u->parent->child[1] == u || + *((tbinptr *) (u->parent)) == u); + if (u->child[0] != 0) { + assert(u->child[0]->parent == u); + assert(u->child[0] != u); + do_check_tree(m, u->child[0]); + } + if (u->child[1] != 0) { + assert(u->child[1]->parent == u); + assert(u->child[1] != u); + do_check_tree(m, u->child[1]); + } + if (u->child[0] != 0 && u->child[1] != 0) { + assert(chunksize(u->child[0]) < chunksize(u->child[1])); + } + } + u = u->fd; } - u = u->fd; - } while (u != t); - assert(head != 0); + while (u != t); + assert(head != 0); } /* Check all the chunks in a treebin. */ -static void do_check_treebin(mstate m, bindex_t i) { - tbinptr* tb = treebin_at(m, i); - tchunkptr t = *tb; - int empty = (m->treemap & (1U << i)) == 0; - if (t == 0) - assert(empty); - if (!empty) - do_check_tree(m, t); +static void +do_check_treebin(mstate m, bindex_t i) +{ + tbinptr *tb = treebin_at(m, i); + tchunkptr t = *tb; + int empty = (m->treemap & (1U << i)) == 0; + if (t == 0) + assert(empty); + if (!empty) + do_check_tree(m, t); } /* Check all the chunks in a smallbin. */ -static void do_check_smallbin(mstate m, bindex_t i) { - sbinptr b = smallbin_at(m, i); - mchunkptr p = b->bk; - unsigned int empty = (m->smallmap & (1U << i)) == 0; - if (p == b) - assert(empty); - if (!empty) { - for (; p != b; p = p->bk) { - size_t size = chunksize(p); - mchunkptr q; - /* each chunk claims to be free */ - do_check_free_chunk(m, p); - /* chunk belongs in bin */ - assert(small_index(size) == i); - assert(p->bk == b || chunksize(p->bk) == chunksize(p)); - /* chunk is followed by an inuse chunk */ - q = next_chunk(p); - if (q->head != FENCEPOST_HEAD) - do_check_inuse_chunk(m, q); +static void +do_check_smallbin(mstate m, bindex_t i) +{ + sbinptr b = smallbin_at(m, i); + mchunkptr p = b->bk; + unsigned int empty = (m->smallmap & (1U << i)) == 0; + if (p == b) + assert(empty); + if (!empty) { + for (; p != b; p = p->bk) { + size_t size = chunksize(p); + mchunkptr q; + /* each chunk claims to be free */ + do_check_free_chunk(m, p); + /* chunk belongs in bin */ + assert(small_index(size) == i); + assert(p->bk == b || chunksize(p->bk) == chunksize(p)); + /* chunk is followed by an inuse chunk */ + q = next_chunk(p); + if (q->head != FENCEPOST_HEAD) + do_check_inuse_chunk(m, q); + } } - } } /* Find x in a bin. Used in other check functions. */ -static int bin_find(mstate m, mchunkptr x) { - size_t size = chunksize(x); - if (is_small(size)) { - bindex_t sidx = small_index(size); - sbinptr b = smallbin_at(m, sidx); - if (smallmap_is_marked(m, sidx)) { - mchunkptr p = b; - do { - if (p == x) - return 1; - } while ((p = p->fd) != b); - } - } - else { - bindex_t tidx; - compute_tree_index(size, tidx); - if (treemap_is_marked(m, tidx)) { - tchunkptr t = *treebin_at(m, tidx); - size_t sizebits = size << leftshift_for_tree_index(tidx); - while (t != 0 && chunksize(t) != size) { - t = t->child[(sizebits >> (SIZE_T_BITSIZE-SIZE_T_ONE)) & 1]; - sizebits <<= 1; - } - if (t != 0) { - tchunkptr u = t; - do { - if (u == (tchunkptr)x) - return 1; - } while ((u = u->fd) != t); - } +static int +bin_find(mstate m, mchunkptr x) +{ + size_t size = chunksize(x); + if (is_small(size)) { + bindex_t sidx = small_index(size); + sbinptr b = smallbin_at(m, sidx); + if (smallmap_is_marked(m, sidx)) { + mchunkptr p = b; + do { + if (p == x) + return 1; + } + while ((p = p->fd) != b); + } + } else { + bindex_t tidx; + compute_tree_index(size, tidx); + if (treemap_is_marked(m, tidx)) { + tchunkptr t = *treebin_at(m, tidx); + size_t sizebits = size << leftshift_for_tree_index(tidx); + while (t != 0 && chunksize(t) != size) { + t = t->child[(sizebits >> (SIZE_T_BITSIZE - SIZE_T_ONE)) & 1]; + sizebits <<= 1; + } + if (t != 0) { + tchunkptr u = t; + do { + if (u == (tchunkptr) x) + return 1; + } + while ((u = u->fd) != t); + } + } } - } - return 0; + return 0; } /* Traverse each chunk and check it; return total */ -static size_t traverse_and_check(mstate m) { - size_t sum = 0; - if (is_initialized(m)) { - msegmentptr s = &m->seg; - sum += m->topsize + TOP_FOOT_SIZE; - while (s != 0) { - mchunkptr q = align_as_chunk(s->base); - mchunkptr lastq = 0; - assert(pinuse(q)); - while (segment_holds(s, q) && - q != m->top && q->head != FENCEPOST_HEAD) { - sum += chunksize(q); - if (cinuse(q)) { - assert(!bin_find(m, q)); - do_check_inuse_chunk(m, q); - } - else { - assert(q == m->dv || bin_find(m, q)); - assert(lastq == 0 || cinuse(lastq)); /* Not 2 consecutive free */ - do_check_free_chunk(m, q); +static size_t +traverse_and_check(mstate m) +{ + size_t sum = 0; + if (is_initialized(m)) { + msegmentptr s = &m->seg; + sum += m->topsize + TOP_FOOT_SIZE; + while (s != 0) { + mchunkptr q = align_as_chunk(s->base); + mchunkptr lastq = 0; + assert(pinuse(q)); + while (segment_holds(s, q) && + q != m->top && q->head != FENCEPOST_HEAD) { + sum += chunksize(q); + if (cinuse(q)) { + assert(!bin_find(m, q)); + do_check_inuse_chunk(m, q); + } else { + assert(q == m->dv || bin_find(m, q)); + assert(lastq == 0 || cinuse(lastq)); /* Not 2 consecutive free */ + do_check_free_chunk(m, q); + } + lastq = q; + q = next_chunk(q); + } + s = s->next; } - lastq = q; - q = next_chunk(q); - } - s = s->next; } - } - return sum; + return sum; } /* Check all properties of malloc_state. */ -static void do_check_malloc_state(mstate m) { - bindex_t i; - size_t total; - /* check bins */ - for (i = 0; i < NSMALLBINS; ++i) - do_check_smallbin(m, i); - for (i = 0; i < NTREEBINS; ++i) - do_check_treebin(m, i); - - if (m->dvsize != 0) { /* check dv chunk */ - do_check_any_chunk(m, m->dv); - assert(m->dvsize == chunksize(m->dv)); - assert(m->dvsize >= MIN_CHUNK_SIZE); - assert(bin_find(m, m->dv) == 0); - } +static void +do_check_malloc_state(mstate m) +{ + bindex_t i; + size_t total; + /* check bins */ + for (i = 0; i < NSMALLBINS; ++i) + do_check_smallbin(m, i); + for (i = 0; i < NTREEBINS; ++i) + do_check_treebin(m, i); + + if (m->dvsize != 0) { /* check dv chunk */ + do_check_any_chunk(m, m->dv); + assert(m->dvsize == chunksize(m->dv)); + assert(m->dvsize >= MIN_CHUNK_SIZE); + assert(bin_find(m, m->dv) == 0); + } - if (m->top != 0) { /* check top chunk */ - do_check_top_chunk(m, m->top); - assert(m->topsize == chunksize(m->top)); - assert(m->topsize > 0); - assert(bin_find(m, m->top) == 0); - } + if (m->top != 0) { /* check top chunk */ + do_check_top_chunk(m, m->top); + assert(m->topsize == chunksize(m->top)); + assert(m->topsize > 0); + assert(bin_find(m, m->top) == 0); + } - total = traverse_and_check(m); - assert(total <= m->footprint); - assert(m->footprint <= m->max_footprint); + total = traverse_and_check(m); + assert(total <= m->footprint); + assert(m->footprint <= m->max_footprint); } #endif /* DEBUG */ /* ----------------------------- statistics ------------------------------ */ #if !NO_MALLINFO -static struct mallinfo internal_mallinfo(mstate m) { - struct mallinfo nm = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; - if (!PREACTION(m)) { - check_malloc_state(m); - if (is_initialized(m)) { - size_t nfree = SIZE_T_ONE; /* top always free */ - size_t mfree = m->topsize + TOP_FOOT_SIZE; - size_t sum = mfree; - msegmentptr s = &m->seg; - while (s != 0) { - mchunkptr q = align_as_chunk(s->base); - while (segment_holds(s, q) && - q != m->top && q->head != FENCEPOST_HEAD) { - size_t sz = chunksize(q); - sum += sz; - if (!cinuse(q)) { - mfree += sz; - ++nfree; - } - q = next_chunk(q); +static struct mallinfo +internal_mallinfo(mstate m) +{ + struct mallinfo nm = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; + if (!PREACTION(m)) { + check_malloc_state(m); + if (is_initialized(m)) { + size_t nfree = SIZE_T_ONE; /* top always free */ + size_t mfree = m->topsize + TOP_FOOT_SIZE; + size_t sum = mfree; + msegmentptr s = &m->seg; + while (s != 0) { + mchunkptr q = align_as_chunk(s->base); + while (segment_holds(s, q) && + q != m->top && q->head != FENCEPOST_HEAD) { + size_t sz = chunksize(q); + sum += sz; + if (!cinuse(q)) { + mfree += sz; + ++nfree; + } + q = next_chunk(q); + } + s = s->next; + } + + nm.arena = sum; + nm.ordblks = nfree; + nm.hblkhd = m->footprint - sum; + nm.usmblks = m->max_footprint; + nm.uordblks = m->footprint - mfree; + nm.fordblks = mfree; + nm.keepcost = m->topsize; } - s = s->next; - } - nm.arena = sum; - nm.ordblks = nfree; - nm.hblkhd = m->footprint - sum; - nm.usmblks = m->max_footprint; - nm.uordblks = m->footprint - mfree; - nm.fordblks = mfree; - nm.keepcost = m->topsize; + POSTACTION(m); } - - POSTACTION(m); - } - return nm; + return nm; } #endif /* !NO_MALLINFO */ -static void internal_malloc_stats(mstate m) { - if (!PREACTION(m)) { - size_t maxfp = 0; - size_t fp = 0; - size_t used = 0; - check_malloc_state(m); - if (is_initialized(m)) { - msegmentptr s = &m->seg; - maxfp = m->max_footprint; - fp = m->footprint; - used = fp - (m->topsize + TOP_FOOT_SIZE); - - while (s != 0) { - mchunkptr q = align_as_chunk(s->base); - while (segment_holds(s, q) && - q != m->top && q->head != FENCEPOST_HEAD) { - if (!cinuse(q)) - used -= chunksize(q); - q = next_chunk(q); +static void +internal_malloc_stats(mstate m) +{ + if (!PREACTION(m)) { + size_t maxfp = 0; + size_t fp = 0; + size_t used = 0; + check_malloc_state(m); + if (is_initialized(m)) { + msegmentptr s = &m->seg; + maxfp = m->max_footprint; + fp = m->footprint; + used = fp - (m->topsize + TOP_FOOT_SIZE); + + while (s != 0) { + mchunkptr q = align_as_chunk(s->base); + while (segment_holds(s, q) && + q != m->top && q->head != FENCEPOST_HEAD) { + if (!cinuse(q)) + used -= chunksize(q); + q = next_chunk(q); + } + s = s->next; + } } - s = s->next; - } - } - #ifndef LACKS_STDIO_H - fprintf(stderr, "max system bytes = %10lu\n", (unsigned long)(maxfp)); - fprintf(stderr, "system bytes = %10lu\n", (unsigned long)(fp)); - fprintf(stderr, "in use bytes = %10lu\n", (unsigned long)(used)); + fprintf(stderr, "max system bytes = %10lu\n", + (unsigned long) (maxfp)); + fprintf(stderr, "system bytes = %10lu\n", (unsigned long) (fp)); + fprintf(stderr, "in use bytes = %10lu\n", (unsigned long) (used)); #endif - POSTACTION(m); - } + POSTACTION(m); + } } /* ----------------------- Operations on smallbins ----------------------- */ @@ -3162,905 +3215,925 @@ static void internal_malloc_stats(mstate m) { */ /* Malloc using mmap */ -static void* mmap_alloc(mstate m, size_t nb) { - size_t mmsize = granularity_align(nb + SIX_SIZE_T_SIZES + CHUNK_ALIGN_MASK); - if (mmsize > nb) { /* Check for wrap around 0 */ - char* mm = (char*)(DIRECT_MMAP(mmsize)); - if (mm != CMFAIL) { - size_t offset = align_offset(chunk2mem(mm)); - size_t psize = mmsize - offset - MMAP_FOOT_PAD; - mchunkptr p = (mchunkptr)(mm + offset); - p->prev_foot = offset | IS_MMAPPED_BIT; - (p)->head = (psize|CINUSE_BIT); - mark_inuse_foot(m, p, psize); - chunk_plus_offset(p, psize)->head = FENCEPOST_HEAD; - chunk_plus_offset(p, psize+SIZE_T_SIZE)->head = 0; - - if (mm < m->least_addr) - m->least_addr = mm; - if ((m->footprint += mmsize) > m->max_footprint) - m->max_footprint = m->footprint; - assert(is_aligned(chunk2mem(p))); - check_mmapped_chunk(m, p); - return chunk2mem(p); +static void * +mmap_alloc(mstate m, size_t nb) +{ + size_t mmsize = + granularity_align(nb + SIX_SIZE_T_SIZES + CHUNK_ALIGN_MASK); + if (mmsize > nb) { /* Check for wrap around 0 */ + char *mm = (char *) (DIRECT_MMAP(mmsize)); + if (mm != CMFAIL) { + size_t offset = align_offset(chunk2mem(mm)); + size_t psize = mmsize - offset - MMAP_FOOT_PAD; + mchunkptr p = (mchunkptr) (mm + offset); + p->prev_foot = offset | IS_MMAPPED_BIT; + (p)->head = (psize | CINUSE_BIT); + mark_inuse_foot(m, p, psize); + chunk_plus_offset(p, psize)->head = FENCEPOST_HEAD; + chunk_plus_offset(p, psize + SIZE_T_SIZE)->head = 0; + + if (mm < m->least_addr) + m->least_addr = mm; + if ((m->footprint += mmsize) > m->max_footprint) + m->max_footprint = m->footprint; + assert(is_aligned(chunk2mem(p))); + check_mmapped_chunk(m, p); + return chunk2mem(p); + } } - } - return 0; + return 0; } /* Realloc using mmap */ -static mchunkptr mmap_resize(mstate m, mchunkptr oldp, size_t nb) { - size_t oldsize = chunksize(oldp); - if (is_small(nb)) /* Can't shrink mmap regions below small size */ - return 0; - /* Keep old chunk if big enough but not too big */ - if (oldsize >= nb + SIZE_T_SIZE && - (oldsize - nb) <= (mparams.granularity << 1)) - return oldp; - else { - size_t offset = oldp->prev_foot & ~IS_MMAPPED_BIT; - size_t oldmmsize = oldsize + offset + MMAP_FOOT_PAD; - size_t newmmsize = granularity_align(nb + SIX_SIZE_T_SIZES + - CHUNK_ALIGN_MASK); - char* cp = (char*)CALL_MREMAP((char*)oldp - offset, - oldmmsize, newmmsize, 1); - if (cp != CMFAIL) { - mchunkptr newp = (mchunkptr)(cp + offset); - size_t psize = newmmsize - offset - MMAP_FOOT_PAD; - newp->head = (psize|CINUSE_BIT); - mark_inuse_foot(m, newp, psize); - chunk_plus_offset(newp, psize)->head = FENCEPOST_HEAD; - chunk_plus_offset(newp, psize+SIZE_T_SIZE)->head = 0; - - if (cp < m->least_addr) - m->least_addr = cp; - if ((m->footprint += newmmsize - oldmmsize) > m->max_footprint) - m->max_footprint = m->footprint; - check_mmapped_chunk(m, newp); - return newp; +static mchunkptr +mmap_resize(mstate m, mchunkptr oldp, size_t nb) +{ + size_t oldsize = chunksize(oldp); + if (is_small(nb)) /* Can't shrink mmap regions below small size */ + return 0; + /* Keep old chunk if big enough but not too big */ + if (oldsize >= nb + SIZE_T_SIZE && + (oldsize - nb) <= (mparams.granularity << 1)) + return oldp; + else { + size_t offset = oldp->prev_foot & ~IS_MMAPPED_BIT; + size_t oldmmsize = oldsize + offset + MMAP_FOOT_PAD; + size_t newmmsize = granularity_align(nb + SIX_SIZE_T_SIZES + + CHUNK_ALIGN_MASK); + char *cp = (char *) CALL_MREMAP((char *) oldp - offset, + oldmmsize, newmmsize, 1); + if (cp != CMFAIL) { + mchunkptr newp = (mchunkptr) (cp + offset); + size_t psize = newmmsize - offset - MMAP_FOOT_PAD; + newp->head = (psize | CINUSE_BIT); + mark_inuse_foot(m, newp, psize); + chunk_plus_offset(newp, psize)->head = FENCEPOST_HEAD; + chunk_plus_offset(newp, psize + SIZE_T_SIZE)->head = 0; + + if (cp < m->least_addr) + m->least_addr = cp; + if ((m->footprint += newmmsize - oldmmsize) > m->max_footprint) + m->max_footprint = m->footprint; + check_mmapped_chunk(m, newp); + return newp; + } } - } - return 0; + return 0; } /* -------------------------- mspace management -------------------------- */ /* Initialize top chunk and its size */ -static void init_top(mstate m, mchunkptr p, size_t psize) { - /* Ensure alignment */ - size_t offset = align_offset(chunk2mem(p)); - p = (mchunkptr)((char*)p + offset); - psize -= offset; - - m->top = p; - m->topsize = psize; - p->head = psize | PINUSE_BIT; - /* set size of fake trailing chunk holding overhead space only once */ - chunk_plus_offset(p, psize)->head = TOP_FOOT_SIZE; - m->trim_check = mparams.trim_threshold; /* reset on each update */ +static void +init_top(mstate m, mchunkptr p, size_t psize) +{ + /* Ensure alignment */ + size_t offset = align_offset(chunk2mem(p)); + p = (mchunkptr) ((char *) p + offset); + psize -= offset; + + m->top = p; + m->topsize = psize; + p->head = psize | PINUSE_BIT; + /* set size of fake trailing chunk holding overhead space only once */ + chunk_plus_offset(p, psize)->head = TOP_FOOT_SIZE; + m->trim_check = mparams.trim_threshold; /* reset on each update */ } /* Initialize bins for a new mstate that is otherwise zeroed out */ -static void init_bins(mstate m) { - /* Establish circular links for smallbins */ - bindex_t i; - for (i = 0; i < NSMALLBINS; ++i) { - sbinptr bin = smallbin_at(m,i); - bin->fd = bin->bk = bin; - } +static void +init_bins(mstate m) +{ + /* Establish circular links for smallbins */ + bindex_t i; + for (i = 0; i < NSMALLBINS; ++i) { + sbinptr bin = smallbin_at(m, i); + bin->fd = bin->bk = bin; + } } #if PROCEED_ON_ERROR /* default corruption action */ -static void reset_on_error(mstate m) { - int i; - ++malloc_corruption_error_count; - /* Reinitialize fields to forget about all memory */ - m->smallbins = m->treebins = 0; - m->dvsize = m->topsize = 0; - m->seg.base = 0; - m->seg.size = 0; - m->seg.next = 0; - m->top = m->dv = 0; - for (i = 0; i < NTREEBINS; ++i) - *treebin_at(m, i) = 0; - init_bins(m); +static void +reset_on_error(mstate m) +{ + int i; + ++malloc_corruption_error_count; + /* Reinitialize fields to forget about all memory */ + m->smallbins = m->treebins = 0; + m->dvsize = m->topsize = 0; + m->seg.base = 0; + m->seg.size = 0; + m->seg.next = 0; + m->top = m->dv = 0; + for (i = 0; i < NTREEBINS; ++i) + *treebin_at(m, i) = 0; + init_bins(m); } #endif /* PROCEED_ON_ERROR */ /* Allocate chunk and prepend remainder with chunk in successor base. */ -static void* prepend_alloc(mstate m, char* newbase, char* oldbase, - size_t nb) { - mchunkptr p = align_as_chunk(newbase); - mchunkptr oldfirst = align_as_chunk(oldbase); - size_t psize = (char*)oldfirst - (char*)p; - mchunkptr q = chunk_plus_offset(p, nb); - size_t qsize = psize - nb; - set_size_and_pinuse_of_inuse_chunk(m, p, nb); - - assert((char*)oldfirst > (char*)q); - assert(pinuse(oldfirst)); - assert(qsize >= MIN_CHUNK_SIZE); - - /* consolidate remainder with first chunk of old base */ - if (oldfirst == m->top) { - size_t tsize = m->topsize += qsize; - m->top = q; - q->head = tsize | PINUSE_BIT; - check_top_chunk(m, q); - } - else if (oldfirst == m->dv) { - size_t dsize = m->dvsize += qsize; - m->dv = q; - set_size_and_pinuse_of_free_chunk(q, dsize); - } - else { - if (!cinuse(oldfirst)) { - size_t nsize = chunksize(oldfirst); - unlink_chunk(m, oldfirst, nsize); - oldfirst = chunk_plus_offset(oldfirst, nsize); - qsize += nsize; +static void * +prepend_alloc(mstate m, char *newbase, char *oldbase, size_t nb) +{ + mchunkptr p = align_as_chunk(newbase); + mchunkptr oldfirst = align_as_chunk(oldbase); + size_t psize = (char *) oldfirst - (char *) p; + mchunkptr q = chunk_plus_offset(p, nb); + size_t qsize = psize - nb; + set_size_and_pinuse_of_inuse_chunk(m, p, nb); + + assert((char *) oldfirst > (char *) q); + assert(pinuse(oldfirst)); + assert(qsize >= MIN_CHUNK_SIZE); + + /* consolidate remainder with first chunk of old base */ + if (oldfirst == m->top) { + size_t tsize = m->topsize += qsize; + m->top = q; + q->head = tsize | PINUSE_BIT; + check_top_chunk(m, q); + } else if (oldfirst == m->dv) { + size_t dsize = m->dvsize += qsize; + m->dv = q; + set_size_and_pinuse_of_free_chunk(q, dsize); + } else { + if (!cinuse(oldfirst)) { + size_t nsize = chunksize(oldfirst); + unlink_chunk(m, oldfirst, nsize); + oldfirst = chunk_plus_offset(oldfirst, nsize); + qsize += nsize; + } + set_free_with_pinuse(q, qsize, oldfirst); + insert_chunk(m, q, qsize); + check_free_chunk(m, q); } - set_free_with_pinuse(q, qsize, oldfirst); - insert_chunk(m, q, qsize); - check_free_chunk(m, q); - } - check_malloced_chunk(m, chunk2mem(p), nb); - return chunk2mem(p); + check_malloced_chunk(m, chunk2mem(p), nb); + return chunk2mem(p); } /* Add a segment to hold a new noncontiguous region */ -static void add_segment(mstate m, char* tbase, size_t tsize, flag_t mmapped) { - /* Determine locations and sizes of segment, fenceposts, old top */ - char* old_top = (char*)m->top; - msegmentptr oldsp = segment_holding(m, old_top); - char* old_end = oldsp->base + oldsp->size; - size_t ssize = pad_request(sizeof(struct malloc_segment)); - char* rawsp = old_end - (ssize + FOUR_SIZE_T_SIZES + CHUNK_ALIGN_MASK); - size_t offset = align_offset(chunk2mem(rawsp)); - char* asp = rawsp + offset; - char* csp = (asp < (old_top + MIN_CHUNK_SIZE))? old_top : asp; - mchunkptr sp = (mchunkptr)csp; - msegmentptr ss = (msegmentptr)(chunk2mem(sp)); - mchunkptr tnext = chunk_plus_offset(sp, ssize); - mchunkptr p = tnext; - int nfences = 0; - - /* reset top to new space */ - init_top(m, (mchunkptr)tbase, tsize - TOP_FOOT_SIZE); - - /* Set up segment record */ - assert(is_aligned(ss)); - set_size_and_pinuse_of_inuse_chunk(m, sp, ssize); - *ss = m->seg; /* Push current record */ - m->seg.base = tbase; - m->seg.size = tsize; - m->seg.sflags = mmapped; - m->seg.next = ss; - - /* Insert trailing fenceposts */ - for (;;) { - mchunkptr nextp = chunk_plus_offset(p, SIZE_T_SIZE); - p->head = FENCEPOST_HEAD; - ++nfences; - if ((char*)(&(nextp->head)) < old_end) - p = nextp; - else - break; - } - assert(nfences >= 2); - - /* Insert the rest of old top into a bin as an ordinary free chunk */ - if (csp != old_top) { - mchunkptr q = (mchunkptr)old_top; - size_t psize = csp - old_top; - mchunkptr tn = chunk_plus_offset(q, psize); - set_free_with_pinuse(q, psize, tn); - insert_chunk(m, q, psize); - } +static void +add_segment(mstate m, char *tbase, size_t tsize, flag_t mmapped) +{ + /* Determine locations and sizes of segment, fenceposts, old top */ + char *old_top = (char *) m->top; + msegmentptr oldsp = segment_holding(m, old_top); + char *old_end = oldsp->base + oldsp->size; + size_t ssize = pad_request(sizeof(struct malloc_segment)); + char *rawsp = old_end - (ssize + FOUR_SIZE_T_SIZES + CHUNK_ALIGN_MASK); + size_t offset = align_offset(chunk2mem(rawsp)); + char *asp = rawsp + offset; + char *csp = (asp < (old_top + MIN_CHUNK_SIZE)) ? old_top : asp; + mchunkptr sp = (mchunkptr) csp; + msegmentptr ss = (msegmentptr) (chunk2mem(sp)); + mchunkptr tnext = chunk_plus_offset(sp, ssize); + mchunkptr p = tnext; + int nfences = 0; + + /* reset top to new space */ + init_top(m, (mchunkptr) tbase, tsize - TOP_FOOT_SIZE); + + /* Set up segment record */ + assert(is_aligned(ss)); + set_size_and_pinuse_of_inuse_chunk(m, sp, ssize); + *ss = m->seg; /* Push current record */ + m->seg.base = tbase; + m->seg.size = tsize; + m->seg.sflags = mmapped; + m->seg.next = ss; + + /* Insert trailing fenceposts */ + for (;;) { + mchunkptr nextp = chunk_plus_offset(p, SIZE_T_SIZE); + p->head = FENCEPOST_HEAD; + ++nfences; + if ((char *) (&(nextp->head)) < old_end) + p = nextp; + else + break; + } + assert(nfences >= 2); + + /* Insert the rest of old top into a bin as an ordinary free chunk */ + if (csp != old_top) { + mchunkptr q = (mchunkptr) old_top; + size_t psize = csp - old_top; + mchunkptr tn = chunk_plus_offset(q, psize); + set_free_with_pinuse(q, psize, tn); + insert_chunk(m, q, psize); + } - check_top_chunk(m, m->top); + check_top_chunk(m, m->top); } /* -------------------------- System allocation -------------------------- */ /* Get memory from system using MORECORE or MMAP */ -static void* sys_alloc(mstate m, size_t nb) { - char* tbase = CMFAIL; - size_t tsize = 0; - flag_t mmap_flag = 0; - - init_mparams(); - - /* Directly map large chunks */ - if (use_mmap(m) && nb >= mparams.mmap_threshold) { - void* mem = mmap_alloc(m, nb); - if (mem != 0) - return mem; - } +static void * +sys_alloc(mstate m, size_t nb) +{ + char *tbase = CMFAIL; + size_t tsize = 0; + flag_t mmap_flag = 0; + + init_mparams(); + + /* Directly map large chunks */ + if (use_mmap(m) && nb >= mparams.mmap_threshold) { + void *mem = mmap_alloc(m, nb); + if (mem != 0) + return mem; + } - /* - Try getting memory in any of three ways (in most-preferred to - least-preferred order): - 1. A call to MORECORE that can normally contiguously extend memory. + /* + Try getting memory in any of three ways (in most-preferred to + least-preferred order): + 1. A call to MORECORE that can normally contiguously extend memory. (disabled if not MORECORE_CONTIGUOUS or not HAVE_MORECORE or or main space is mmapped or a previous contiguous call failed) - 2. A call to MMAP new space (disabled if not HAVE_MMAP). + 2. A call to MMAP new space (disabled if not HAVE_MMAP). Note that under the default settings, if MORECORE is unable to fulfill a request, and HAVE_MMAP is true, then mmap is used as a noncontiguous system allocator. This is a useful backup strategy for systems with holes in address spaces -- in this case sbrk cannot contiguously expand the heap, but mmap may be able to find space. - 3. A call to MORECORE that cannot usually contiguously extend memory. + 3. A call to MORECORE that cannot usually contiguously extend memory. (disabled if not HAVE_MORECORE) - */ - - if (MORECORE_CONTIGUOUS && !use_noncontiguous(m)) { - char* br = CMFAIL; - msegmentptr ss = (m->top == 0)? 0 : segment_holding(m, (char*)m->top); - size_t asize = 0; - ACQUIRE_MORECORE_LOCK(); - - if (ss == 0) { /* First time through or recovery */ - char* base = (char*)CALL_MORECORE(0); - if (base != CMFAIL) { - asize = granularity_align(nb + TOP_FOOT_SIZE + SIZE_T_ONE); - /* Adjust to end on a page boundary */ - if (!is_page_aligned(base)) - asize += (page_align((size_t)base) - (size_t)base); - /* Can't call MORECORE if size is negative when treated as signed */ - if (asize < HALF_MAX_SIZE_T && - (br = (char*)(CALL_MORECORE(asize))) == base) { - tbase = base; - tsize = asize; + */ + + if (MORECORE_CONTIGUOUS && !use_noncontiguous(m)) { + char *br = CMFAIL; + msegmentptr ss = + (m->top == 0) ? 0 : segment_holding(m, (char *) m->top); + size_t asize = 0; + ACQUIRE_MORECORE_LOCK(); + + if (ss == 0) { /* First time through or recovery */ + char *base = (char *) CALL_MORECORE(0); + if (base != CMFAIL) { + asize = granularity_align(nb + TOP_FOOT_SIZE + SIZE_T_ONE); + /* Adjust to end on a page boundary */ + if (!is_page_aligned(base)) + asize += (page_align((size_t) base) - (size_t) base); + /* Can't call MORECORE if size is negative when treated as signed */ + if (asize < HALF_MAX_SIZE_T && + (br = (char *) (CALL_MORECORE(asize))) == base) { + tbase = base; + tsize = asize; + } + } + } else { + /* Subtract out existing available top space from MORECORE request. */ + asize = + granularity_align(nb - m->topsize + TOP_FOOT_SIZE + + SIZE_T_ONE); + /* Use mem here only if it did continuously extend old space */ + if (asize < HALF_MAX_SIZE_T && + (br = + (char *) (CALL_MORECORE(asize))) == ss->base + ss->size) { + tbase = br; + tsize = asize; + } } - } - } - else { - /* Subtract out existing available top space from MORECORE request. */ - asize = granularity_align(nb - m->topsize + TOP_FOOT_SIZE + SIZE_T_ONE); - /* Use mem here only if it did continuously extend old space */ - if (asize < HALF_MAX_SIZE_T && - (br = (char*)(CALL_MORECORE(asize))) == ss->base+ss->size) { - tbase = br; - tsize = asize; - } - } - if (tbase == CMFAIL) { /* Cope with partial failure */ - if (br != CMFAIL) { /* Try to use/extend the space we did get */ - if (asize < HALF_MAX_SIZE_T && - asize < nb + TOP_FOOT_SIZE + SIZE_T_ONE) { - size_t esize = granularity_align(nb + TOP_FOOT_SIZE + SIZE_T_ONE - asize); - if (esize < HALF_MAX_SIZE_T) { - char* end = (char*)CALL_MORECORE(esize); - if (end != CMFAIL) - asize += esize; - else { /* Can't use; try to release */ - end = (char*)CALL_MORECORE(-asize); - br = CMFAIL; + if (tbase == CMFAIL) { /* Cope with partial failure */ + if (br != CMFAIL) { /* Try to use/extend the space we did get */ + if (asize < HALF_MAX_SIZE_T && + asize < nb + TOP_FOOT_SIZE + SIZE_T_ONE) { + size_t esize = + granularity_align(nb + TOP_FOOT_SIZE + + SIZE_T_ONE - asize); + if (esize < HALF_MAX_SIZE_T) { + char *end = (char *) CALL_MORECORE(esize); + if (end != CMFAIL) + asize += esize; + else { /* Can't use; try to release */ + end = (char *) CALL_MORECORE(-asize); + br = CMFAIL; + } + } + } } - } + if (br != CMFAIL) { /* Use the space we did get */ + tbase = br; + tsize = asize; + } else + disable_contiguous(m); /* Don't try contiguous path in the future */ } - } - if (br != CMFAIL) { /* Use the space we did get */ - tbase = br; - tsize = asize; - } - else - disable_contiguous(m); /* Don't try contiguous path in the future */ - } - RELEASE_MORECORE_LOCK(); - } - - if (HAVE_MMAP && tbase == CMFAIL) { /* Try MMAP */ - size_t req = nb + TOP_FOOT_SIZE + SIZE_T_ONE; - size_t rsize = granularity_align(req); - if (rsize > nb) { /* Fail if wraps around zero */ - char* mp = (char*)(CALL_MMAP(rsize)); - if (mp != CMFAIL) { - tbase = mp; - tsize = rsize; - mmap_flag = IS_MMAPPED_BIT; - } + RELEASE_MORECORE_LOCK(); } - } - if (HAVE_MORECORE && tbase == CMFAIL) { /* Try noncontiguous MORECORE */ - size_t asize = granularity_align(nb + TOP_FOOT_SIZE + SIZE_T_ONE); - if (asize < HALF_MAX_SIZE_T) { - char* br = CMFAIL; - char* end = CMFAIL; - ACQUIRE_MORECORE_LOCK(); - br = (char*)(CALL_MORECORE(asize)); - end = (char*)(CALL_MORECORE(0)); - RELEASE_MORECORE_LOCK(); - if (br != CMFAIL && end != CMFAIL && br < end) { - size_t ssize = end - br; - if (ssize > nb + TOP_FOOT_SIZE) { - tbase = br; - tsize = ssize; + if (HAVE_MMAP && tbase == CMFAIL) { /* Try MMAP */ + size_t req = nb + TOP_FOOT_SIZE + SIZE_T_ONE; + size_t rsize = granularity_align(req); + if (rsize > nb) { /* Fail if wraps around zero */ + char *mp = (char *) (CALL_MMAP(rsize)); + if (mp != CMFAIL) { + tbase = mp; + tsize = rsize; + mmap_flag = IS_MMAPPED_BIT; + } } - } } - } - if (tbase != CMFAIL) { - - if ((m->footprint += tsize) > m->max_footprint) - m->max_footprint = m->footprint; - - if (!is_initialized(m)) { /* first-time initialization */ - m->seg.base = m->least_addr = tbase; - m->seg.size = tsize; - m->seg.sflags = mmap_flag; - m->magic = mparams.magic; - init_bins(m); - if (is_global(m)) - init_top(m, (mchunkptr)tbase, tsize - TOP_FOOT_SIZE); - else { - /* Offset top by embedded malloc_state */ - mchunkptr mn = next_chunk(mem2chunk(m)); - init_top(m, mn, (size_t)((tbase + tsize) - (char*)mn) -TOP_FOOT_SIZE); - } + if (HAVE_MORECORE && tbase == CMFAIL) { /* Try noncontiguous MORECORE */ + size_t asize = granularity_align(nb + TOP_FOOT_SIZE + SIZE_T_ONE); + if (asize < HALF_MAX_SIZE_T) { + char *br = CMFAIL; + char *end = CMFAIL; + ACQUIRE_MORECORE_LOCK(); + br = (char *) (CALL_MORECORE(asize)); + end = (char *) (CALL_MORECORE(0)); + RELEASE_MORECORE_LOCK(); + if (br != CMFAIL && end != CMFAIL && br < end) { + size_t ssize = end - br; + if (ssize > nb + TOP_FOOT_SIZE) { + tbase = br; + tsize = ssize; + } + } + } } - else { - /* Try to merge with an existing segment */ - msegmentptr sp = &m->seg; - while (sp != 0 && tbase != sp->base + sp->size) - sp = sp->next; - if (sp != 0 && - !is_extern_segment(sp) && - (sp->sflags & IS_MMAPPED_BIT) == mmap_flag && - segment_holds(sp, m->top)) { /* append */ - sp->size += tsize; - init_top(m, m->top, m->topsize + tsize); - } - else { - if (tbase < m->least_addr) - m->least_addr = tbase; - sp = &m->seg; - while (sp != 0 && sp->base != tbase + tsize) - sp = sp->next; - if (sp != 0 && - !is_extern_segment(sp) && - (sp->sflags & IS_MMAPPED_BIT) == mmap_flag) { - char* oldbase = sp->base; - sp->base = tbase; - sp->size += tsize; - return prepend_alloc(m, tbase, oldbase, nb); + if (tbase != CMFAIL) { + + if ((m->footprint += tsize) > m->max_footprint) + m->max_footprint = m->footprint; + + if (!is_initialized(m)) { /* first-time initialization */ + m->seg.base = m->least_addr = tbase; + m->seg.size = tsize; + m->seg.sflags = mmap_flag; + m->magic = mparams.magic; + init_bins(m); + if (is_global(m)) + init_top(m, (mchunkptr) tbase, tsize - TOP_FOOT_SIZE); + else { + /* Offset top by embedded malloc_state */ + mchunkptr mn = next_chunk(mem2chunk(m)); + init_top(m, mn, + (size_t) ((tbase + tsize) - (char *) mn) - + TOP_FOOT_SIZE); + } + } + + else { + /* Try to merge with an existing segment */ + msegmentptr sp = &m->seg; + while (sp != 0 && tbase != sp->base + sp->size) + sp = sp->next; + if (sp != 0 && !is_extern_segment(sp) && (sp->sflags & IS_MMAPPED_BIT) == mmap_flag && segment_holds(sp, m->top)) { /* append */ + sp->size += tsize; + init_top(m, m->top, m->topsize + tsize); + } else { + if (tbase < m->least_addr) + m->least_addr = tbase; + sp = &m->seg; + while (sp != 0 && sp->base != tbase + tsize) + sp = sp->next; + if (sp != 0 && + !is_extern_segment(sp) && + (sp->sflags & IS_MMAPPED_BIT) == mmap_flag) { + char *oldbase = sp->base; + sp->base = tbase; + sp->size += tsize; + return prepend_alloc(m, tbase, oldbase, nb); + } else + add_segment(m, tbase, tsize, mmap_flag); + } } - else - add_segment(m, tbase, tsize, mmap_flag); - } - } - if (nb < m->topsize) { /* Allocate from new or extended top space */ - size_t rsize = m->topsize -= nb; - mchunkptr p = m->top; - mchunkptr r = m->top = chunk_plus_offset(p, nb); - r->head = rsize | PINUSE_BIT; - set_size_and_pinuse_of_inuse_chunk(m, p, nb); - check_top_chunk(m, m->top); - check_malloced_chunk(m, chunk2mem(p), nb); - return chunk2mem(p); + if (nb < m->topsize) { /* Allocate from new or extended top space */ + size_t rsize = m->topsize -= nb; + mchunkptr p = m->top; + mchunkptr r = m->top = chunk_plus_offset(p, nb); + r->head = rsize | PINUSE_BIT; + set_size_and_pinuse_of_inuse_chunk(m, p, nb); + check_top_chunk(m, m->top); + check_malloced_chunk(m, chunk2mem(p), nb); + return chunk2mem(p); + } } - } - MALLOC_FAILURE_ACTION; - return 0; + MALLOC_FAILURE_ACTION; + return 0; } /* ----------------------- system deallocation -------------------------- */ /* Unmap and unlink any mmapped segments that don't contain used chunks */ -static size_t release_unused_segments(mstate m) { - size_t released = 0; - msegmentptr pred = &m->seg; - msegmentptr sp = pred->next; - while (sp != 0) { - char* base = sp->base; - size_t size = sp->size; - msegmentptr next = sp->next; - if (is_mmapped_segment(sp) && !is_extern_segment(sp)) { - mchunkptr p = align_as_chunk(base); - size_t psize = chunksize(p); - /* Can unmap if first chunk holds entire segment and not pinned */ - if (!cinuse(p) && (char*)p + psize >= base + size - TOP_FOOT_SIZE) { - tchunkptr tp = (tchunkptr)p; - assert(segment_holds(sp, (char*)sp)); - if (p == m->dv) { - m->dv = 0; - m->dvsize = 0; - } - else { - unlink_large_chunk(m, tp); - } - if (CALL_MUNMAP(base, size) == 0) { - released += size; - m->footprint -= size; - /* unlink obsoleted record */ - sp = pred; - sp->next = next; - } - else { /* back out if cannot unmap */ - insert_large_chunk(m, tp, psize); +static size_t +release_unused_segments(mstate m) +{ + size_t released = 0; + msegmentptr pred = &m->seg; + msegmentptr sp = pred->next; + while (sp != 0) { + char *base = sp->base; + size_t size = sp->size; + msegmentptr next = sp->next; + if (is_mmapped_segment(sp) && !is_extern_segment(sp)) { + mchunkptr p = align_as_chunk(base); + size_t psize = chunksize(p); + /* Can unmap if first chunk holds entire segment and not pinned */ + if (!cinuse(p) + && (char *) p + psize >= base + size - TOP_FOOT_SIZE) { + tchunkptr tp = (tchunkptr) p; + assert(segment_holds(sp, (char *) sp)); + if (p == m->dv) { + m->dv = 0; + m->dvsize = 0; + } else { + unlink_large_chunk(m, tp); + } + if (CALL_MUNMAP(base, size) == 0) { + released += size; + m->footprint -= size; + /* unlink obsoleted record */ + sp = pred; + sp->next = next; + } else { /* back out if cannot unmap */ + insert_large_chunk(m, tp, psize); + } + } } - } + pred = sp; + sp = next; } - pred = sp; - sp = next; - } - return released; + return released; } -static int sys_trim(mstate m, size_t pad) { - size_t released = 0; - if (pad < MAX_REQUEST && is_initialized(m)) { - pad += TOP_FOOT_SIZE; /* ensure enough room for segment overhead */ - - if (m->topsize > pad) { - /* Shrink top space in granularity-size units, keeping at least one */ - size_t unit = mparams.granularity; - size_t extra = ((m->topsize - pad + (unit - SIZE_T_ONE)) / unit - - SIZE_T_ONE) * unit; - msegmentptr sp = segment_holding(m, (char*)m->top); - - if (!is_extern_segment(sp)) { - if (is_mmapped_segment(sp)) { - if (HAVE_MMAP && - sp->size >= extra && - !has_segment_link(m, sp)) { /* can't shrink if pinned */ - size_t newsize = sp->size - extra; - /* Prefer mremap, fall back to munmap */ - if ((CALL_MREMAP(sp->base, sp->size, newsize, 0) != MFAIL) || - (CALL_MUNMAP(sp->base + newsize, extra) == 0)) { - released = extra; +static int +sys_trim(mstate m, size_t pad) +{ + size_t released = 0; + if (pad < MAX_REQUEST && is_initialized(m)) { + pad += TOP_FOOT_SIZE; /* ensure enough room for segment overhead */ + + if (m->topsize > pad) { + /* Shrink top space in granularity-size units, keeping at least one */ + size_t unit = mparams.granularity; + size_t extra = + ((m->topsize - pad + (unit - SIZE_T_ONE)) / unit - + SIZE_T_ONE) * unit; + msegmentptr sp = segment_holding(m, (char *) m->top); + + if (!is_extern_segment(sp)) { + if (is_mmapped_segment(sp)) { + if (HAVE_MMAP && sp->size >= extra && !has_segment_link(m, sp)) { /* can't shrink if pinned */ + size_t newsize = sp->size - extra; + /* Prefer mremap, fall back to munmap */ + if ((CALL_MREMAP + (sp->base, sp->size, newsize, 0) != MFAIL) + || (CALL_MUNMAP(sp->base + newsize, extra) + == 0)) { + released = extra; + } + } + } else if (HAVE_MORECORE) { + if (extra >= HALF_MAX_SIZE_T) /* Avoid wrapping negative */ + extra = (HALF_MAX_SIZE_T) + SIZE_T_ONE - unit; + ACQUIRE_MORECORE_LOCK(); + { + /* Make sure end of memory is where we last set it. */ + char *old_br = (char *) (CALL_MORECORE(0)); + if (old_br == sp->base + sp->size) { + char *rel_br = (char *) (CALL_MORECORE(-extra)); + char *new_br = (char *) (CALL_MORECORE(0)); + if (rel_br != CMFAIL && new_br < old_br) + released = old_br - new_br; + } + } + RELEASE_MORECORE_LOCK(); + } } - } - } - else if (HAVE_MORECORE) { - if (extra >= HALF_MAX_SIZE_T) /* Avoid wrapping negative */ - extra = (HALF_MAX_SIZE_T) + SIZE_T_ONE - unit; - ACQUIRE_MORECORE_LOCK(); - { - /* Make sure end of memory is where we last set it. */ - char* old_br = (char*)(CALL_MORECORE(0)); - if (old_br == sp->base + sp->size) { - char* rel_br = (char*)(CALL_MORECORE(-extra)); - char* new_br = (char*)(CALL_MORECORE(0)); - if (rel_br != CMFAIL && new_br < old_br) - released = old_br - new_br; + + if (released != 0) { + sp->size -= released; + m->footprint -= released; + init_top(m, m->top, m->topsize - released); + check_top_chunk(m, m->top); } - } - RELEASE_MORECORE_LOCK(); } - } - - if (released != 0) { - sp->size -= released; - m->footprint -= released; - init_top(m, m->top, m->topsize - released); - check_top_chunk(m, m->top); - } - } - /* Unmap any unused mmapped segments */ - if (HAVE_MMAP) - released += release_unused_segments(m); + /* Unmap any unused mmapped segments */ + if (HAVE_MMAP) + released += release_unused_segments(m); - /* On failure, disable autotrim to avoid repeated failed future calls */ - if (released == 0) - m->trim_check = MAX_SIZE_T; - } + /* On failure, disable autotrim to avoid repeated failed future calls */ + if (released == 0) + m->trim_check = MAX_SIZE_T; + } - return (released != 0)? 1 : 0; + return (released != 0) ? 1 : 0; } /* ---------------------------- malloc support --------------------------- */ /* allocate a large request from the best fitting chunk in a treebin */ -static void* tmalloc_large(mstate m, size_t nb) { - tchunkptr v = 0; - size_t rsize = -nb; /* Unsigned negation */ - tchunkptr t; - bindex_t idx; - compute_tree_index(nb, idx); - - if ((t = *treebin_at(m, idx)) != 0) { - /* Traverse tree for this bin looking for node with size == nb */ - size_t sizebits = nb << leftshift_for_tree_index(idx); - tchunkptr rst = 0; /* The deepest untaken right subtree */ - for (;;) { - tchunkptr rt; - size_t trem = chunksize(t) - nb; - if (trem < rsize) { - v = t; - if ((rsize = trem) == 0) - break; - } - rt = t->child[1]; - t = t->child[(sizebits >> (SIZE_T_BITSIZE-SIZE_T_ONE)) & 1]; - if (rt != 0 && rt != t) - rst = rt; - if (t == 0) { - t = rst; /* set t to least subtree holding sizes > nb */ - break; - } - sizebits <<= 1; +static void * +tmalloc_large(mstate m, size_t nb) +{ + tchunkptr v = 0; + size_t rsize = -nb; /* Unsigned negation */ + tchunkptr t; + bindex_t idx; + compute_tree_index(nb, idx); + + if ((t = *treebin_at(m, idx)) != 0) { + /* Traverse tree for this bin looking for node with size == nb */ + size_t sizebits = nb << leftshift_for_tree_index(idx); + tchunkptr rst = 0; /* The deepest untaken right subtree */ + for (;;) { + tchunkptr rt; + size_t trem = chunksize(t) - nb; + if (trem < rsize) { + v = t; + if ((rsize = trem) == 0) + break; + } + rt = t->child[1]; + t = t->child[(sizebits >> (SIZE_T_BITSIZE - SIZE_T_ONE)) & 1]; + if (rt != 0 && rt != t) + rst = rt; + if (t == 0) { + t = rst; /* set t to least subtree holding sizes > nb */ + break; + } + sizebits <<= 1; + } } - } - if (t == 0 && v == 0) { /* set t to root of next non-empty treebin */ - binmap_t leftbits = left_bits(idx2bit(idx)) & m->treemap; - if (leftbits != 0) { - bindex_t i; - binmap_t leastbit = least_bit(leftbits); - compute_bit2idx(leastbit, i); - t = *treebin_at(m, i); + if (t == 0 && v == 0) { /* set t to root of next non-empty treebin */ + binmap_t leftbits = left_bits(idx2bit(idx)) & m->treemap; + if (leftbits != 0) { + bindex_t i; + binmap_t leastbit = least_bit(leftbits); + compute_bit2idx(leastbit, i); + t = *treebin_at(m, i); + } } - } - while (t != 0) { /* find smallest of tree or subtree */ - size_t trem = chunksize(t) - nb; - if (trem < rsize) { - rsize = trem; - v = t; + while (t != 0) { /* find smallest of tree or subtree */ + size_t trem = chunksize(t) - nb; + if (trem < rsize) { + rsize = trem; + v = t; + } + t = leftmost_child(t); } - t = leftmost_child(t); - } - /* If dv is a better fit, return 0 so malloc will use it */ - if (v != 0 && rsize < (size_t)(m->dvsize - nb)) { - if (RTCHECK(ok_address(m, v))) { /* split */ - mchunkptr r = chunk_plus_offset(v, nb); - assert(chunksize(v) == rsize + nb); - if (RTCHECK(ok_next(v, r))) { - unlink_large_chunk(m, v); - if (rsize < MIN_CHUNK_SIZE) - set_inuse_and_pinuse(m, v, (rsize + nb)); - else { - set_size_and_pinuse_of_inuse_chunk(m, v, nb); - set_size_and_pinuse_of_free_chunk(r, rsize); - insert_chunk(m, r, rsize); + /* If dv is a better fit, return 0 so malloc will use it */ + if (v != 0 && rsize < (size_t) (m->dvsize - nb)) { + if (RTCHECK(ok_address(m, v))) { /* split */ + mchunkptr r = chunk_plus_offset(v, nb); + assert(chunksize(v) == rsize + nb); + if (RTCHECK(ok_next(v, r))) { + unlink_large_chunk(m, v); + if (rsize < MIN_CHUNK_SIZE) + set_inuse_and_pinuse(m, v, (rsize + nb)); + else { + set_size_and_pinuse_of_inuse_chunk(m, v, nb); + set_size_and_pinuse_of_free_chunk(r, rsize); + insert_chunk(m, r, rsize); + } + return chunk2mem(v); + } } - return chunk2mem(v); - } + CORRUPTION_ERROR_ACTION(m); } - CORRUPTION_ERROR_ACTION(m); - } - return 0; + return 0; } /* allocate a small request from the best fitting chunk in a treebin */ -static void* tmalloc_small(mstate m, size_t nb) { - tchunkptr t, v; - size_t rsize; - bindex_t i; - binmap_t leastbit = least_bit(m->treemap); - compute_bit2idx(leastbit, i); - - v = t = *treebin_at(m, i); - rsize = chunksize(t) - nb; - - while ((t = leftmost_child(t)) != 0) { - size_t trem = chunksize(t) - nb; - if (trem < rsize) { - rsize = trem; - v = t; +static void * +tmalloc_small(mstate m, size_t nb) +{ + tchunkptr t, v; + size_t rsize; + bindex_t i; + binmap_t leastbit = least_bit(m->treemap); + compute_bit2idx(leastbit, i); + + v = t = *treebin_at(m, i); + rsize = chunksize(t) - nb; + + while ((t = leftmost_child(t)) != 0) { + size_t trem = chunksize(t) - nb; + if (trem < rsize) { + rsize = trem; + v = t; + } } - } - if (RTCHECK(ok_address(m, v))) { - mchunkptr r = chunk_plus_offset(v, nb); - assert(chunksize(v) == rsize + nb); - if (RTCHECK(ok_next(v, r))) { - unlink_large_chunk(m, v); - if (rsize < MIN_CHUNK_SIZE) - set_inuse_and_pinuse(m, v, (rsize + nb)); - else { - set_size_and_pinuse_of_inuse_chunk(m, v, nb); - set_size_and_pinuse_of_free_chunk(r, rsize); - replace_dv(m, r, rsize); - } - return chunk2mem(v); + if (RTCHECK(ok_address(m, v))) { + mchunkptr r = chunk_plus_offset(v, nb); + assert(chunksize(v) == rsize + nb); + if (RTCHECK(ok_next(v, r))) { + unlink_large_chunk(m, v); + if (rsize < MIN_CHUNK_SIZE) + set_inuse_and_pinuse(m, v, (rsize + nb)); + else { + set_size_and_pinuse_of_inuse_chunk(m, v, nb); + set_size_and_pinuse_of_free_chunk(r, rsize); + replace_dv(m, r, rsize); + } + return chunk2mem(v); + } } - } - CORRUPTION_ERROR_ACTION(m); - return 0; + CORRUPTION_ERROR_ACTION(m); + return 0; } /* --------------------------- realloc support --------------------------- */ -static void* internal_realloc(mstate m, void* oldmem, size_t bytes) { - if (bytes >= MAX_REQUEST) { - MALLOC_FAILURE_ACTION; - return 0; - } - if (!PREACTION(m)) { - mchunkptr oldp = mem2chunk(oldmem); - size_t oldsize = chunksize(oldp); - mchunkptr next = chunk_plus_offset(oldp, oldsize); - mchunkptr newp = 0; - void* extra = 0; - - /* Try to either shrink or extend into top. Else malloc-copy-free */ - - if (RTCHECK(ok_address(m, oldp) && ok_cinuse(oldp) && - ok_next(oldp, next) && ok_pinuse(next))) { - size_t nb = request2size(bytes); - if (is_mmapped(oldp)) - newp = mmap_resize(m, oldp, nb); - else if (oldsize >= nb) { /* already big enough */ - size_t rsize = oldsize - nb; - newp = oldp; - if (rsize >= MIN_CHUNK_SIZE) { - mchunkptr remainder = chunk_plus_offset(newp, nb); - set_inuse(m, newp, nb); - set_inuse(m, remainder, rsize); - extra = chunk2mem(remainder); - } - } - else if (next == m->top && oldsize + m->topsize > nb) { - /* Expand into top */ - size_t newsize = oldsize + m->topsize; - size_t newtopsize = newsize - nb; - mchunkptr newtop = chunk_plus_offset(oldp, nb); - set_inuse(m, oldp, nb); - newtop->head = newtopsize |PINUSE_BIT; - m->top = newtop; - m->topsize = newtopsize; - newp = oldp; - } - } - else { - USAGE_ERROR_ACTION(m, oldmem); - POSTACTION(m); - return 0; +static void * +internal_realloc(mstate m, void *oldmem, size_t bytes) +{ + if (bytes >= MAX_REQUEST) { + MALLOC_FAILURE_ACTION; + return 0; } + if (!PREACTION(m)) { + mchunkptr oldp = mem2chunk(oldmem); + size_t oldsize = chunksize(oldp); + mchunkptr next = chunk_plus_offset(oldp, oldsize); + mchunkptr newp = 0; + void *extra = 0; + + /* Try to either shrink or extend into top. Else malloc-copy-free */ + + if (RTCHECK(ok_address(m, oldp) && ok_cinuse(oldp) && + ok_next(oldp, next) && ok_pinuse(next))) { + size_t nb = request2size(bytes); + if (is_mmapped(oldp)) + newp = mmap_resize(m, oldp, nb); + else if (oldsize >= nb) { /* already big enough */ + size_t rsize = oldsize - nb; + newp = oldp; + if (rsize >= MIN_CHUNK_SIZE) { + mchunkptr remainder = chunk_plus_offset(newp, nb); + set_inuse(m, newp, nb); + set_inuse(m, remainder, rsize); + extra = chunk2mem(remainder); + } + } else if (next == m->top && oldsize + m->topsize > nb) { + /* Expand into top */ + size_t newsize = oldsize + m->topsize; + size_t newtopsize = newsize - nb; + mchunkptr newtop = chunk_plus_offset(oldp, nb); + set_inuse(m, oldp, nb); + newtop->head = newtopsize | PINUSE_BIT; + m->top = newtop; + m->topsize = newtopsize; + newp = oldp; + } + } else { + USAGE_ERROR_ACTION(m, oldmem); + POSTACTION(m); + return 0; + } - POSTACTION(m); + POSTACTION(m); - if (newp != 0) { - if (extra != 0) { - internal_free(m, extra); - } - check_inuse_chunk(m, newp); - return chunk2mem(newp); - } - else { - void* newmem = internal_malloc(m, bytes); - if (newmem != 0) { - size_t oc = oldsize - overhead_for(oldp); - memcpy(newmem, oldmem, (oc < bytes)? oc : bytes); - internal_free(m, oldmem); - } - return newmem; + if (newp != 0) { + if (extra != 0) { + internal_free(m, extra); + } + check_inuse_chunk(m, newp); + return chunk2mem(newp); + } else { + void *newmem = internal_malloc(m, bytes); + if (newmem != 0) { + size_t oc = oldsize - overhead_for(oldp); + memcpy(newmem, oldmem, (oc < bytes) ? oc : bytes); + internal_free(m, oldmem); + } + return newmem; + } } - } - return 0; + return 0; } /* --------------------------- memalign support -------------------------- */ -static void* internal_memalign(mstate m, size_t alignment, size_t bytes) { - if (alignment <= MALLOC_ALIGNMENT) /* Can just use malloc */ - return internal_malloc(m, bytes); - if (alignment < MIN_CHUNK_SIZE) /* must be at least a minimum chunk size */ - alignment = MIN_CHUNK_SIZE; - if ((alignment & (alignment-SIZE_T_ONE)) != 0) {/* Ensure a power of 2 */ - size_t a = MALLOC_ALIGNMENT << 1; - while (a < alignment) a <<= 1; - alignment = a; - } - - if (bytes >= MAX_REQUEST - alignment) { - if (m != 0) { /* Test isn't needed but avoids compiler warning */ - MALLOC_FAILURE_ACTION; +static void * +internal_memalign(mstate m, size_t alignment, size_t bytes) +{ + if (alignment <= MALLOC_ALIGNMENT) /* Can just use malloc */ + return internal_malloc(m, bytes); + if (alignment < MIN_CHUNK_SIZE) /* must be at least a minimum chunk size */ + alignment = MIN_CHUNK_SIZE; + if ((alignment & (alignment - SIZE_T_ONE)) != 0) { /* Ensure a power of 2 */ + size_t a = MALLOC_ALIGNMENT << 1; + while (a < alignment) + a <<= 1; + alignment = a; } - } - else { - size_t nb = request2size(bytes); - size_t req = nb + alignment + MIN_CHUNK_SIZE - CHUNK_OVERHEAD; - char* mem = (char*)internal_malloc(m, req); - if (mem != 0) { - void* leader = 0; - void* trailer = 0; - mchunkptr p = mem2chunk(mem); - - if (PREACTION(m)) return 0; - if ((((size_t)(mem)) % alignment) != 0) { /* misaligned */ - /* - Find an aligned spot inside chunk. Since we need to give - back leading space in a chunk of at least MIN_CHUNK_SIZE, if - the first calculation places us at a spot with less than - MIN_CHUNK_SIZE leader, we can move to the next aligned spot. - We've allocated enough total room so that this is always - possible. - */ - char* br = (char*)mem2chunk((size_t)(((size_t)(mem + - alignment - - SIZE_T_ONE)) & - -alignment)); - char* pos = ((size_t)(br - (char*)(p)) >= MIN_CHUNK_SIZE)? - br : br+alignment; - mchunkptr newp = (mchunkptr)pos; - size_t leadsize = pos - (char*)(p); - size_t newsize = chunksize(p) - leadsize; - - if (is_mmapped(p)) { /* For mmapped chunks, just adjust offset */ - newp->prev_foot = p->prev_foot + leadsize; - newp->head = (newsize|CINUSE_BIT); - } - else { /* Otherwise, give back leader, use the rest */ - set_inuse(m, newp, newsize); - set_inuse(m, p, leadsize); - leader = chunk2mem(p); - } - p = newp; - } - /* Give back spare room at the end */ - if (!is_mmapped(p)) { - size_t size = chunksize(p); - if (size > nb + MIN_CHUNK_SIZE) { - size_t remainder_size = size - nb; - mchunkptr remainder = chunk_plus_offset(p, nb); - set_inuse(m, p, nb); - set_inuse(m, remainder, remainder_size); - trailer = chunk2mem(remainder); + if (bytes >= MAX_REQUEST - alignment) { + if (m != 0) { /* Test isn't needed but avoids compiler warning */ + MALLOC_FAILURE_ACTION; } - } + } else { + size_t nb = request2size(bytes); + size_t req = nb + alignment + MIN_CHUNK_SIZE - CHUNK_OVERHEAD; + char *mem = (char *) internal_malloc(m, req); + if (mem != 0) { + void *leader = 0; + void *trailer = 0; + mchunkptr p = mem2chunk(mem); + + if (PREACTION(m)) + return 0; + if ((((size_t) (mem)) % alignment) != 0) { /* misaligned */ + /* + Find an aligned spot inside chunk. Since we need to give + back leading space in a chunk of at least MIN_CHUNK_SIZE, if + the first calculation places us at a spot with less than + MIN_CHUNK_SIZE leader, we can move to the next aligned spot. + We've allocated enough total room so that this is always + possible. + */ + char *br = (char *) + mem2chunk((size_t) + (((size_t) + (mem + alignment - + SIZE_T_ONE)) & -alignment)); + char *pos = + ((size_t) (br - (char *) (p)) >= + MIN_CHUNK_SIZE) ? br : br + alignment; + mchunkptr newp = (mchunkptr) pos; + size_t leadsize = pos - (char *) (p); + size_t newsize = chunksize(p) - leadsize; + + if (is_mmapped(p)) { /* For mmapped chunks, just adjust offset */ + newp->prev_foot = p->prev_foot + leadsize; + newp->head = (newsize | CINUSE_BIT); + } else { /* Otherwise, give back leader, use the rest */ + set_inuse(m, newp, newsize); + set_inuse(m, p, leadsize); + leader = chunk2mem(p); + } + p = newp; + } - assert (chunksize(p) >= nb); - assert((((size_t)(chunk2mem(p))) % alignment) == 0); - check_inuse_chunk(m, p); - POSTACTION(m); - if (leader != 0) { - internal_free(m, leader); - } - if (trailer != 0) { - internal_free(m, trailer); - } - return chunk2mem(p); + /* Give back spare room at the end */ + if (!is_mmapped(p)) { + size_t size = chunksize(p); + if (size > nb + MIN_CHUNK_SIZE) { + size_t remainder_size = size - nb; + mchunkptr remainder = chunk_plus_offset(p, nb); + set_inuse(m, p, nb); + set_inuse(m, remainder, remainder_size); + trailer = chunk2mem(remainder); + } + } + + assert(chunksize(p) >= nb); + assert((((size_t) (chunk2mem(p))) % alignment) == 0); + check_inuse_chunk(m, p); + POSTACTION(m); + if (leader != 0) { + internal_free(m, leader); + } + if (trailer != 0) { + internal_free(m, trailer); + } + return chunk2mem(p); + } } - } - return 0; + return 0; } /* ------------------------ comalloc/coalloc support --------------------- */ -static void** ialloc(mstate m, - size_t n_elements, - size_t* sizes, - int opts, - void* chunks[]) { - /* - This provides common support for independent_X routines, handling - all of the combinations that can result. - - The opts arg has: - bit 0 set if all elements are same size (using sizes[0]) - bit 1 set if elements should be zeroed - */ - - size_t element_size; /* chunksize of each element, if all same */ - size_t contents_size; /* total size of elements */ - size_t array_size; /* request size of pointer array */ - void* mem; /* malloced aggregate space */ - mchunkptr p; /* corresponding chunk */ - size_t remainder_size; /* remaining bytes while splitting */ - void** marray; /* either "chunks" or malloced ptr array */ - mchunkptr array_chunk; /* chunk for malloced ptr array */ - flag_t was_enabled; /* to disable mmap */ - size_t size; - size_t i; - - /* compute array length, if needed */ - if (chunks != 0) { - if (n_elements == 0) - return chunks; /* nothing to do */ - marray = chunks; - array_size = 0; - } - else { - /* if empty req, must still return chunk representing empty array */ - if (n_elements == 0) - return (void**)internal_malloc(m, 0); - marray = 0; - array_size = request2size(n_elements * (sizeof(void*))); - } - - /* compute total element size */ - if (opts & 0x1) { /* all-same-size */ - element_size = request2size(*sizes); - contents_size = n_elements * element_size; - } - else { /* add up all the sizes */ - element_size = 0; - contents_size = 0; - for (i = 0; i != n_elements; ++i) - contents_size += request2size(sizes[i]); - } - - size = contents_size + array_size; - - /* - Allocate the aggregate chunk. First disable direct-mmapping so - malloc won't use it, since we would not be able to later - free/realloc space internal to a segregated mmap region. - */ - was_enabled = use_mmap(m); - disable_mmap(m); - mem = internal_malloc(m, size - CHUNK_OVERHEAD); - if (was_enabled) - enable_mmap(m); - if (mem == 0) - return 0; - - if (PREACTION(m)) return 0; - p = mem2chunk(mem); - remainder_size = chunksize(p); - - assert(!is_mmapped(p)); +static void ** +ialloc(mstate m, size_t n_elements, size_t * sizes, int opts, void *chunks[]) +{ + /* + This provides common support for independent_X routines, handling + all of the combinations that can result. + + The opts arg has: + bit 0 set if all elements are same size (using sizes[0]) + bit 1 set if elements should be zeroed + */ + + size_t element_size; /* chunksize of each element, if all same */ + size_t contents_size; /* total size of elements */ + size_t array_size; /* request size of pointer array */ + void *mem; /* malloced aggregate space */ + mchunkptr p; /* corresponding chunk */ + size_t remainder_size; /* remaining bytes while splitting */ + void **marray; /* either "chunks" or malloced ptr array */ + mchunkptr array_chunk; /* chunk for malloced ptr array */ + flag_t was_enabled; /* to disable mmap */ + size_t size; + size_t i; + + /* compute array length, if needed */ + if (chunks != 0) { + if (n_elements == 0) + return chunks; /* nothing to do */ + marray = chunks; + array_size = 0; + } else { + /* if empty req, must still return chunk representing empty array */ + if (n_elements == 0) + return (void **) internal_malloc(m, 0); + marray = 0; + array_size = request2size(n_elements * (sizeof(void *))); + } - if (opts & 0x2) { /* optionally clear the elements */ - memset((size_t*)mem, 0, remainder_size - SIZE_T_SIZE - array_size); - } + /* compute total element size */ + if (opts & 0x1) { /* all-same-size */ + element_size = request2size(*sizes); + contents_size = n_elements * element_size; + } else { /* add up all the sizes */ + element_size = 0; + contents_size = 0; + for (i = 0; i != n_elements; ++i) + contents_size += request2size(sizes[i]); + } - /* If not provided, allocate the pointer array as final part of chunk */ - if (marray == 0) { - size_t array_chunk_size; - array_chunk = chunk_plus_offset(p, contents_size); - array_chunk_size = remainder_size - contents_size; - marray = (void**) (chunk2mem(array_chunk)); - set_size_and_pinuse_of_inuse_chunk(m, array_chunk, array_chunk_size); - remainder_size = contents_size; - } + size = contents_size + array_size; + + /* + Allocate the aggregate chunk. First disable direct-mmapping so + malloc won't use it, since we would not be able to later + free/realloc space internal to a segregated mmap region. + */ + was_enabled = use_mmap(m); + disable_mmap(m); + mem = internal_malloc(m, size - CHUNK_OVERHEAD); + if (was_enabled) + enable_mmap(m); + if (mem == 0) + return 0; + + if (PREACTION(m)) + return 0; + p = mem2chunk(mem); + remainder_size = chunksize(p); + + assert(!is_mmapped(p)); + + if (opts & 0x2) { /* optionally clear the elements */ + memset((size_t *) mem, 0, remainder_size - SIZE_T_SIZE - array_size); + } - /* split out elements */ - for (i = 0; ; ++i) { - marray[i] = chunk2mem(p); - if (i != n_elements-1) { - if (element_size != 0) - size = element_size; - else - size = request2size(sizes[i]); - remainder_size -= size; - set_size_and_pinuse_of_inuse_chunk(m, p, size); - p = chunk_plus_offset(p, size); + /* If not provided, allocate the pointer array as final part of chunk */ + if (marray == 0) { + size_t array_chunk_size; + array_chunk = chunk_plus_offset(p, contents_size); + array_chunk_size = remainder_size - contents_size; + marray = (void **) (chunk2mem(array_chunk)); + set_size_and_pinuse_of_inuse_chunk(m, array_chunk, array_chunk_size); + remainder_size = contents_size; } - else { /* the final element absorbs any overallocation slop */ - set_size_and_pinuse_of_inuse_chunk(m, p, remainder_size); - break; + + /* split out elements */ + for (i = 0;; ++i) { + marray[i] = chunk2mem(p); + if (i != n_elements - 1) { + if (element_size != 0) + size = element_size; + else + size = request2size(sizes[i]); + remainder_size -= size; + set_size_and_pinuse_of_inuse_chunk(m, p, size); + p = chunk_plus_offset(p, size); + } else { /* the final element absorbs any overallocation slop */ + set_size_and_pinuse_of_inuse_chunk(m, p, remainder_size); + break; + } } - } #if DEBUG - if (marray != chunks) { - /* final element must have exactly exhausted chunk */ - if (element_size != 0) { - assert(remainder_size == element_size); - } - else { - assert(remainder_size == request2size(sizes[i])); + if (marray != chunks) { + /* final element must have exactly exhausted chunk */ + if (element_size != 0) { + assert(remainder_size == element_size); + } else { + assert(remainder_size == request2size(sizes[i])); + } + check_inuse_chunk(m, mem2chunk(marray)); } - check_inuse_chunk(m, mem2chunk(marray)); - } - for (i = 0; i != n_elements; ++i) - check_inuse_chunk(m, mem2chunk(marray[i])); + for (i = 0; i != n_elements; ++i) + check_inuse_chunk(m, mem2chunk(marray[i])); #endif /* DEBUG */ - POSTACTION(m); - return marray; + POSTACTION(m); + return marray; } @@ -4068,343 +4141,369 @@ static void** ialloc(mstate m, #if !ONLY_MSPACES -void* dlmalloc(size_t bytes) { - /* - Basic algorithm: - If a small request (< 256 bytes minus per-chunk overhead): +void * +dlmalloc(size_t bytes) +{ + /* + Basic algorithm: + If a small request (< 256 bytes minus per-chunk overhead): 1. If one exists, use a remainderless chunk in associated smallbin. - (Remainderless means that there are too few excess bytes to - represent as a chunk.) + (Remainderless means that there are too few excess bytes to + represent as a chunk.) 2. If it is big enough, use the dv chunk, which is normally the - chunk adjacent to the one used for the most recent small request. + chunk adjacent to the one used for the most recent small request. 3. If one exists, split the smallest available chunk in a bin, - saving remainder in dv. + saving remainder in dv. 4. If it is big enough, use the top chunk. 5. If available, get memory from system and use it - Otherwise, for a large request: + Otherwise, for a large request: 1. Find the smallest available binned chunk that fits, and use it - if it is better fitting than dv chunk, splitting if necessary. + if it is better fitting than dv chunk, splitting if necessary. 2. If better fitting than any binned chunk, use the dv chunk. 3. If it is big enough, use the top chunk. 4. If request size >= mmap threshold, try to directly mmap this chunk. 5. If available, get memory from system and use it - The ugly goto's here ensure that postaction occurs along all paths. - */ - - if (!PREACTION(gm)) { - void* mem; - size_t nb; - if (bytes <= MAX_SMALL_REQUEST) { - bindex_t idx; - binmap_t smallbits; - nb = (bytes < MIN_REQUEST)? MIN_CHUNK_SIZE : pad_request(bytes); - idx = small_index(nb); - smallbits = gm->smallmap >> idx; - - if ((smallbits & 0x3U) != 0) { /* Remainderless fit to a smallbin. */ - mchunkptr b, p; - idx += ~smallbits & 1; /* Uses next bin if idx empty */ - b = smallbin_at(gm, idx); - p = b->fd; - assert(chunksize(p) == small_index2size(idx)); - unlink_first_small_chunk(gm, b, p, idx); - set_inuse_and_pinuse(gm, p, small_index2size(idx)); - mem = chunk2mem(p); - check_malloced_chunk(gm, mem, nb); - goto postaction; - } + The ugly goto's here ensure that postaction occurs along all paths. + */ + + if (!PREACTION(gm)) { + void *mem; + size_t nb; + if (bytes <= MAX_SMALL_REQUEST) { + bindex_t idx; + binmap_t smallbits; + nb = (bytes < MIN_REQUEST) ? MIN_CHUNK_SIZE : pad_request(bytes); + idx = small_index(nb); + smallbits = gm->smallmap >> idx; + + if ((smallbits & 0x3U) != 0) { /* Remainderless fit to a smallbin. */ + mchunkptr b, p; + idx += ~smallbits & 1; /* Uses next bin if idx empty */ + b = smallbin_at(gm, idx); + p = b->fd; + assert(chunksize(p) == small_index2size(idx)); + unlink_first_small_chunk(gm, b, p, idx); + set_inuse_and_pinuse(gm, p, small_index2size(idx)); + mem = chunk2mem(p); + check_malloced_chunk(gm, mem, nb); + goto postaction; + } - else if (nb > gm->dvsize) { - if (smallbits != 0) { /* Use chunk in next nonempty smallbin */ - mchunkptr b, p, r; - size_t rsize; - bindex_t i; - binmap_t leftbits = (smallbits << idx) & left_bits(idx2bit(idx)); - binmap_t leastbit = least_bit(leftbits); - compute_bit2idx(leastbit, i); - b = smallbin_at(gm, i); - p = b->fd; - assert(chunksize(p) == small_index2size(i)); - unlink_first_small_chunk(gm, b, p, i); - rsize = small_index2size(i) - nb; - /* Fit here cannot be remainderless if 4byte sizes */ - if (SIZE_T_SIZE != 4 && rsize < MIN_CHUNK_SIZE) - set_inuse_and_pinuse(gm, p, small_index2size(i)); - else { - set_size_and_pinuse_of_inuse_chunk(gm, p, nb); - r = chunk_plus_offset(p, nb); - set_size_and_pinuse_of_free_chunk(r, rsize); - replace_dv(gm, r, rsize); - } - mem = chunk2mem(p); - check_malloced_chunk(gm, mem, nb); - goto postaction; + else if (nb > gm->dvsize) { + if (smallbits != 0) { /* Use chunk in next nonempty smallbin */ + mchunkptr b, p, r; + size_t rsize; + bindex_t i; + binmap_t leftbits = + (smallbits << idx) & left_bits(idx2bit(idx)); + binmap_t leastbit = least_bit(leftbits); + compute_bit2idx(leastbit, i); + b = smallbin_at(gm, i); + p = b->fd; + assert(chunksize(p) == small_index2size(i)); + unlink_first_small_chunk(gm, b, p, i); + rsize = small_index2size(i) - nb; + /* Fit here cannot be remainderless if 4byte sizes */ + if (SIZE_T_SIZE != 4 && rsize < MIN_CHUNK_SIZE) + set_inuse_and_pinuse(gm, p, small_index2size(i)); + else { + set_size_and_pinuse_of_inuse_chunk(gm, p, nb); + r = chunk_plus_offset(p, nb); + set_size_and_pinuse_of_free_chunk(r, rsize); + replace_dv(gm, r, rsize); + } + mem = chunk2mem(p); + check_malloced_chunk(gm, mem, nb); + goto postaction; + } + + else if (gm->treemap != 0 + && (mem = tmalloc_small(gm, nb)) != 0) { + check_malloced_chunk(gm, mem, nb); + goto postaction; + } + } + } else if (bytes >= MAX_REQUEST) + nb = MAX_SIZE_T; /* Too big to allocate. Force failure (in sys alloc) */ + else { + nb = pad_request(bytes); + if (gm->treemap != 0 && (mem = tmalloc_large(gm, nb)) != 0) { + check_malloced_chunk(gm, mem, nb); + goto postaction; + } } - else if (gm->treemap != 0 && (mem = tmalloc_small(gm, nb)) != 0) { - check_malloced_chunk(gm, mem, nb); - goto postaction; + if (nb <= gm->dvsize) { + size_t rsize = gm->dvsize - nb; + mchunkptr p = gm->dv; + if (rsize >= MIN_CHUNK_SIZE) { /* split dv */ + mchunkptr r = gm->dv = chunk_plus_offset(p, nb); + gm->dvsize = rsize; + set_size_and_pinuse_of_free_chunk(r, rsize); + set_size_and_pinuse_of_inuse_chunk(gm, p, nb); + } else { /* exhaust dv */ + size_t dvs = gm->dvsize; + gm->dvsize = 0; + gm->dv = 0; + set_inuse_and_pinuse(gm, p, dvs); + } + mem = chunk2mem(p); + check_malloced_chunk(gm, mem, nb); + goto postaction; } - } - } - else if (bytes >= MAX_REQUEST) - nb = MAX_SIZE_T; /* Too big to allocate. Force failure (in sys alloc) */ - else { - nb = pad_request(bytes); - if (gm->treemap != 0 && (mem = tmalloc_large(gm, nb)) != 0) { - check_malloced_chunk(gm, mem, nb); - goto postaction; - } - } - - if (nb <= gm->dvsize) { - size_t rsize = gm->dvsize - nb; - mchunkptr p = gm->dv; - if (rsize >= MIN_CHUNK_SIZE) { /* split dv */ - mchunkptr r = gm->dv = chunk_plus_offset(p, nb); - gm->dvsize = rsize; - set_size_and_pinuse_of_free_chunk(r, rsize); - set_size_and_pinuse_of_inuse_chunk(gm, p, nb); - } - else { /* exhaust dv */ - size_t dvs = gm->dvsize; - gm->dvsize = 0; - gm->dv = 0; - set_inuse_and_pinuse(gm, p, dvs); - } - mem = chunk2mem(p); - check_malloced_chunk(gm, mem, nb); - goto postaction; - } - else if (nb < gm->topsize) { /* Split top */ - size_t rsize = gm->topsize -= nb; - mchunkptr p = gm->top; - mchunkptr r = gm->top = chunk_plus_offset(p, nb); - r->head = rsize | PINUSE_BIT; - set_size_and_pinuse_of_inuse_chunk(gm, p, nb); - mem = chunk2mem(p); - check_top_chunk(gm, gm->top); - check_malloced_chunk(gm, mem, nb); - goto postaction; - } + else if (nb < gm->topsize) { /* Split top */ + size_t rsize = gm->topsize -= nb; + mchunkptr p = gm->top; + mchunkptr r = gm->top = chunk_plus_offset(p, nb); + r->head = rsize | PINUSE_BIT; + set_size_and_pinuse_of_inuse_chunk(gm, p, nb); + mem = chunk2mem(p); + check_top_chunk(gm, gm->top); + check_malloced_chunk(gm, mem, nb); + goto postaction; + } - mem = sys_alloc(gm, nb); + mem = sys_alloc(gm, nb); - postaction: - POSTACTION(gm); - return mem; - } + postaction: + POSTACTION(gm); + return mem; + } - return 0; + return 0; } -void dlfree(void* mem) { - /* - Consolidate freed chunks with preceeding or succeeding bordering - free chunks, if they exist, and then place in a bin. Intermixed - with special cases for top, dv, mmapped chunks, and usage errors. - */ +void +dlfree(void *mem) +{ + /* + Consolidate freed chunks with preceeding or succeeding bordering + free chunks, if they exist, and then place in a bin. Intermixed + with special cases for top, dv, mmapped chunks, and usage errors. + */ - if (mem != 0) { - mchunkptr p = mem2chunk(mem); + if (mem != 0) { + mchunkptr p = mem2chunk(mem); #if FOOTERS - mstate fm = get_mstate_for(p); - if (!ok_magic(fm)) { - USAGE_ERROR_ACTION(fm, p); - return; - } + mstate fm = get_mstate_for(p); + if (!ok_magic(fm)) { + USAGE_ERROR_ACTION(fm, p); + return; + } #else /* FOOTERS */ #define fm gm #endif /* FOOTERS */ - if (!PREACTION(fm)) { - check_inuse_chunk(fm, p); - if (RTCHECK(ok_address(fm, p) && ok_cinuse(p))) { - size_t psize = chunksize(p); - mchunkptr next = chunk_plus_offset(p, psize); - if (!pinuse(p)) { - size_t prevsize = p->prev_foot; - if ((prevsize & IS_MMAPPED_BIT) != 0) { - prevsize &= ~IS_MMAPPED_BIT; - psize += prevsize + MMAP_FOOT_PAD; - if (CALL_MUNMAP((char*)p - prevsize, psize) == 0) - fm->footprint -= psize; - goto postaction; - } - else { - mchunkptr prev = chunk_minus_offset(p, prevsize); - psize += prevsize; - p = prev; - if (RTCHECK(ok_address(fm, prev))) { /* consolidate backward */ - if (p != fm->dv) { - unlink_chunk(fm, p, prevsize); - } - else if ((next->head & INUSE_BITS) == INUSE_BITS) { - fm->dvsize = psize; - set_free_with_pinuse(p, psize, next); - goto postaction; - } + if (!PREACTION(fm)) { + check_inuse_chunk(fm, p); + if (RTCHECK(ok_address(fm, p) && ok_cinuse(p))) { + size_t psize = chunksize(p); + mchunkptr next = chunk_plus_offset(p, psize); + if (!pinuse(p)) { + size_t prevsize = p->prev_foot; + if ((prevsize & IS_MMAPPED_BIT) != 0) { + prevsize &= ~IS_MMAPPED_BIT; + psize += prevsize + MMAP_FOOT_PAD; + if (CALL_MUNMAP((char *) p - prevsize, psize) == 0) + fm->footprint -= psize; + goto postaction; + } else { + mchunkptr prev = chunk_minus_offset(p, prevsize); + psize += prevsize; + p = prev; + if (RTCHECK(ok_address(fm, prev))) { /* consolidate backward */ + if (p != fm->dv) { + unlink_chunk(fm, p, prevsize); + } else if ((next->head & INUSE_BITS) == + INUSE_BITS) { + fm->dvsize = psize; + set_free_with_pinuse(p, psize, next); + goto postaction; + } + } else + goto erroraction; + } + } + + if (RTCHECK(ok_next(p, next) && ok_pinuse(next))) { + if (!cinuse(next)) { /* consolidate forward */ + if (next == fm->top) { + size_t tsize = fm->topsize += psize; + fm->top = p; + p->head = tsize | PINUSE_BIT; + if (p == fm->dv) { + fm->dv = 0; + fm->dvsize = 0; + } + if (should_trim(fm, tsize)) + sys_trim(fm, 0); + goto postaction; + } else if (next == fm->dv) { + size_t dsize = fm->dvsize += psize; + fm->dv = p; + set_size_and_pinuse_of_free_chunk(p, dsize); + goto postaction; + } else { + size_t nsize = chunksize(next); + psize += nsize; + unlink_chunk(fm, next, nsize); + set_size_and_pinuse_of_free_chunk(p, psize); + if (p == fm->dv) { + fm->dvsize = psize; + goto postaction; + } + } + } else + set_free_with_pinuse(p, psize, next); + insert_chunk(fm, p, psize); + check_free_chunk(fm, p); + goto postaction; + } } - else - goto erroraction; - } + erroraction: + USAGE_ERROR_ACTION(fm, p); + postaction: + POSTACTION(fm); } - - if (RTCHECK(ok_next(p, next) && ok_pinuse(next))) { - if (!cinuse(next)) { /* consolidate forward */ - if (next == fm->top) { - size_t tsize = fm->topsize += psize; - fm->top = p; - p->head = tsize | PINUSE_BIT; - if (p == fm->dv) { - fm->dv = 0; - fm->dvsize = 0; - } - if (should_trim(fm, tsize)) - sys_trim(fm, 0); - goto postaction; - } - else if (next == fm->dv) { - size_t dsize = fm->dvsize += psize; - fm->dv = p; - set_size_and_pinuse_of_free_chunk(p, dsize); - goto postaction; - } - else { - size_t nsize = chunksize(next); - psize += nsize; - unlink_chunk(fm, next, nsize); - set_size_and_pinuse_of_free_chunk(p, psize); - if (p == fm->dv) { - fm->dvsize = psize; - goto postaction; - } - } - } - else - set_free_with_pinuse(p, psize, next); - insert_chunk(fm, p, psize); - check_free_chunk(fm, p); - goto postaction; - } - } - erroraction: - USAGE_ERROR_ACTION(fm, p); - postaction: - POSTACTION(fm); } - } #if !FOOTERS #undef fm #endif /* FOOTERS */ } -void* dlcalloc(size_t n_elements, size_t elem_size) { - void* mem; - size_t req = 0; - if (n_elements != 0) { - req = n_elements * elem_size; - if (((n_elements | elem_size) & ~(size_t)0xffff) && - (req / n_elements != elem_size)) - req = MAX_SIZE_T; /* force downstream failure on overflow */ - } - mem = dlmalloc(req); - if (mem != 0 && calloc_must_clear(mem2chunk(mem))) - memset(mem, 0, req); - return mem; +void * +dlcalloc(size_t n_elements, size_t elem_size) +{ + void *mem; + size_t req = 0; + if (n_elements != 0) { + req = n_elements * elem_size; + if (((n_elements | elem_size) & ~(size_t) 0xffff) && + (req / n_elements != elem_size)) + req = MAX_SIZE_T; /* force downstream failure on overflow */ + } + mem = dlmalloc(req); + if (mem != 0 && calloc_must_clear(mem2chunk(mem))) + memset(mem, 0, req); + return mem; } -void* dlrealloc(void* oldmem, size_t bytes) { - if (oldmem == 0) - return dlmalloc(bytes); +void * +dlrealloc(void *oldmem, size_t bytes) +{ + if (oldmem == 0) + return dlmalloc(bytes); #ifdef REALLOC_ZERO_BYTES_FREES - if (bytes == 0) { - dlfree(oldmem); - return 0; - } + if (bytes == 0) { + dlfree(oldmem); + return 0; + } #endif /* REALLOC_ZERO_BYTES_FREES */ - else { + else { #if ! FOOTERS - mstate m = gm; + mstate m = gm; #else /* FOOTERS */ - mstate m = get_mstate_for(mem2chunk(oldmem)); - if (!ok_magic(m)) { - USAGE_ERROR_ACTION(m, oldmem); - return 0; - } + mstate m = get_mstate_for(mem2chunk(oldmem)); + if (!ok_magic(m)) { + USAGE_ERROR_ACTION(m, oldmem); + return 0; + } #endif /* FOOTERS */ - return internal_realloc(m, oldmem, bytes); - } + return internal_realloc(m, oldmem, bytes); + } } -void* dlmemalign(size_t alignment, size_t bytes) { - return internal_memalign(gm, alignment, bytes); +void * +dlmemalign(size_t alignment, size_t bytes) +{ + return internal_memalign(gm, alignment, bytes); } -void** dlindependent_calloc(size_t n_elements, size_t elem_size, - void* chunks[]) { - size_t sz = elem_size; /* serves as 1-element array */ - return ialloc(gm, n_elements, &sz, 3, chunks); +void ** +dlindependent_calloc(size_t n_elements, size_t elem_size, void *chunks[]) +{ + size_t sz = elem_size; /* serves as 1-element array */ + return ialloc(gm, n_elements, &sz, 3, chunks); } -void** dlindependent_comalloc(size_t n_elements, size_t sizes[], - void* chunks[]) { - return ialloc(gm, n_elements, sizes, 0, chunks); +void ** +dlindependent_comalloc(size_t n_elements, size_t sizes[], void *chunks[]) +{ + return ialloc(gm, n_elements, sizes, 0, chunks); } -void* dlvalloc(size_t bytes) { - size_t pagesz; - init_mparams(); - pagesz = mparams.page_size; - return dlmemalign(pagesz, bytes); +void * +dlvalloc(size_t bytes) +{ + size_t pagesz; + init_mparams(); + pagesz = mparams.page_size; + return dlmemalign(pagesz, bytes); } -void* dlpvalloc(size_t bytes) { - size_t pagesz; - init_mparams(); - pagesz = mparams.page_size; - return dlmemalign(pagesz, (bytes + pagesz - SIZE_T_ONE) & ~(pagesz - SIZE_T_ONE)); +void * +dlpvalloc(size_t bytes) +{ + size_t pagesz; + init_mparams(); + pagesz = mparams.page_size; + return dlmemalign(pagesz, + (bytes + pagesz - SIZE_T_ONE) & ~(pagesz - SIZE_T_ONE)); } -int dlmalloc_trim(size_t pad) { - int result = 0; - if (!PREACTION(gm)) { - result = sys_trim(gm, pad); - POSTACTION(gm); - } - return result; +int +dlmalloc_trim(size_t pad) +{ + int result = 0; + if (!PREACTION(gm)) { + result = sys_trim(gm, pad); + POSTACTION(gm); + } + return result; } -size_t dlmalloc_footprint(void) { - return gm->footprint; +size_t +dlmalloc_footprint(void) +{ + return gm->footprint; } -size_t dlmalloc_max_footprint(void) { - return gm->max_footprint; +size_t +dlmalloc_max_footprint(void) +{ + return gm->max_footprint; } #if !NO_MALLINFO -struct mallinfo dlmallinfo(void) { - return internal_mallinfo(gm); +struct mallinfo +dlmallinfo(void) +{ + return internal_mallinfo(gm); } #endif /* NO_MALLINFO */ -void dlmalloc_stats() { - internal_malloc_stats(gm); +void +dlmalloc_stats() +{ + internal_malloc_stats(gm); } -size_t dlmalloc_usable_size(void* mem) { - if (mem != 0) { - mchunkptr p = mem2chunk(mem); - if (cinuse(p)) - return chunksize(p) - overhead_for(p); - } - return 0; +size_t +dlmalloc_usable_size(void *mem) +{ + if (mem != 0) { + mchunkptr p = mem2chunk(mem); + if (cinuse(p)) + return chunksize(p) - overhead_for(p); + } + return 0; } -int dlmallopt(int param_number, int value) { - return change_mparam(param_number, value); +int +dlmallopt(int param_number, int value) +{ + return change_mparam(param_number, value); } #endif /* !ONLY_MSPACES */ @@ -4413,78 +4512,85 @@ int dlmallopt(int param_number, int value) { #if MSPACES -static mstate init_user_mstate(char* tbase, size_t tsize) { - size_t msize = pad_request(sizeof(struct malloc_state)); - mchunkptr mn; - mchunkptr msp = align_as_chunk(tbase); - mstate m = (mstate)(chunk2mem(msp)); - memset(m, 0, msize); - INITIAL_LOCK(&m->mutex); - msp->head = (msize|PINUSE_BIT|CINUSE_BIT); - m->seg.base = m->least_addr = tbase; - m->seg.size = m->footprint = m->max_footprint = tsize; - m->magic = mparams.magic; - m->mflags = mparams.default_mflags; - disable_contiguous(m); - init_bins(m); - mn = next_chunk(mem2chunk(m)); - init_top(m, mn, (size_t)((tbase + tsize) - (char*)mn) - TOP_FOOT_SIZE); - check_top_chunk(m, m->top); - return m; +static mstate +init_user_mstate(char *tbase, size_t tsize) +{ + size_t msize = pad_request(sizeof(struct malloc_state)); + mchunkptr mn; + mchunkptr msp = align_as_chunk(tbase); + mstate m = (mstate) (chunk2mem(msp)); + memset(m, 0, msize); + INITIAL_LOCK(&m->mutex); + msp->head = (msize | PINUSE_BIT | CINUSE_BIT); + m->seg.base = m->least_addr = tbase; + m->seg.size = m->footprint = m->max_footprint = tsize; + m->magic = mparams.magic; + m->mflags = mparams.default_mflags; + disable_contiguous(m); + init_bins(m); + mn = next_chunk(mem2chunk(m)); + init_top(m, mn, (size_t) ((tbase + tsize) - (char *) mn) - TOP_FOOT_SIZE); + check_top_chunk(m, m->top); + return m; } -mspace create_mspace(size_t capacity, int locked) { - mstate m = 0; - size_t msize = pad_request(sizeof(struct malloc_state)); - init_mparams(); /* Ensure pagesize etc initialized */ - - if (capacity < (size_t) -(msize + TOP_FOOT_SIZE + mparams.page_size)) { - size_t rs = ((capacity == 0)? mparams.granularity : - (capacity + TOP_FOOT_SIZE + msize)); - size_t tsize = granularity_align(rs); - char* tbase = (char*)(CALL_MMAP(tsize)); - if (tbase != CMFAIL) { - m = init_user_mstate(tbase, tsize); - m->seg.sflags = IS_MMAPPED_BIT; - set_lock(m, locked); +mspace +create_mspace(size_t capacity, int locked) +{ + mstate m = 0; + size_t msize = pad_request(sizeof(struct malloc_state)); + init_mparams(); /* Ensure pagesize etc initialized */ + + if (capacity < (size_t) - (msize + TOP_FOOT_SIZE + mparams.page_size)) { + size_t rs = ((capacity == 0) ? mparams.granularity : + (capacity + TOP_FOOT_SIZE + msize)); + size_t tsize = granularity_align(rs); + char *tbase = (char *) (CALL_MMAP(tsize)); + if (tbase != CMFAIL) { + m = init_user_mstate(tbase, tsize); + m->seg.sflags = IS_MMAPPED_BIT; + set_lock(m, locked); + } } - } - return (mspace)m; + return (mspace) m; } -mspace create_mspace_with_base(void* base, size_t capacity, int locked) { - mstate m = 0; - size_t msize = pad_request(sizeof(struct malloc_state)); - init_mparams(); /* Ensure pagesize etc initialized */ - - if (capacity > msize + TOP_FOOT_SIZE && - capacity < (size_t) -(msize + TOP_FOOT_SIZE + mparams.page_size)) { - m = init_user_mstate((char*)base, capacity); - m->seg.sflags = EXTERN_BIT; - set_lock(m, locked); - } - return (mspace)m; +mspace +create_mspace_with_base(void *base, size_t capacity, int locked) +{ + mstate m = 0; + size_t msize = pad_request(sizeof(struct malloc_state)); + init_mparams(); /* Ensure pagesize etc initialized */ + + if (capacity > msize + TOP_FOOT_SIZE && + capacity < (size_t) - (msize + TOP_FOOT_SIZE + mparams.page_size)) { + m = init_user_mstate((char *) base, capacity); + m->seg.sflags = EXTERN_BIT; + set_lock(m, locked); + } + return (mspace) m; } -size_t destroy_mspace(mspace msp) { - size_t freed = 0; - mstate ms = (mstate)msp; - if (ok_magic(ms)) { - msegmentptr sp = &ms->seg; - while (sp != 0) { - char* base = sp->base; - size_t size = sp->size; - flag_t flag = sp->sflags; - sp = sp->next; - if ((flag & IS_MMAPPED_BIT) && !(flag & EXTERN_BIT) && - CALL_MUNMAP(base, size) == 0) - freed += size; +size_t +destroy_mspace(mspace msp) +{ + size_t freed = 0; + mstate ms = (mstate) msp; + if (ok_magic(ms)) { + msegmentptr sp = &ms->seg; + while (sp != 0) { + char *base = sp->base; + size_t size = sp->size; + flag_t flag = sp->sflags; + sp = sp->next; + if ((flag & IS_MMAPPED_BIT) && !(flag & EXTERN_BIT) && + CALL_MUNMAP(base, size) == 0) + freed += size; + } + } else { + USAGE_ERROR_ACTION(ms, ms); } - } - else { - USAGE_ERROR_ACTION(ms,ms); - } - return freed; + return freed; } /* @@ -4493,344 +4599,363 @@ size_t destroy_mspace(mspace msp) { */ -void* mspace_malloc(mspace msp, size_t bytes) { - mstate ms = (mstate)msp; - if (!ok_magic(ms)) { - USAGE_ERROR_ACTION(ms,ms); - return 0; - } - if (!PREACTION(ms)) { - void* mem; - size_t nb; - if (bytes <= MAX_SMALL_REQUEST) { - bindex_t idx; - binmap_t smallbits; - nb = (bytes < MIN_REQUEST)? MIN_CHUNK_SIZE : pad_request(bytes); - idx = small_index(nb); - smallbits = ms->smallmap >> idx; - - if ((smallbits & 0x3U) != 0) { /* Remainderless fit to a smallbin. */ - mchunkptr b, p; - idx += ~smallbits & 1; /* Uses next bin if idx empty */ - b = smallbin_at(ms, idx); - p = b->fd; - assert(chunksize(p) == small_index2size(idx)); - unlink_first_small_chunk(ms, b, p, idx); - set_inuse_and_pinuse(ms, p, small_index2size(idx)); - mem = chunk2mem(p); - check_malloced_chunk(ms, mem, nb); - goto postaction; - } +void * +mspace_malloc(mspace msp, size_t bytes) +{ + mstate ms = (mstate) msp; + if (!ok_magic(ms)) { + USAGE_ERROR_ACTION(ms, ms); + return 0; + } + if (!PREACTION(ms)) { + void *mem; + size_t nb; + if (bytes <= MAX_SMALL_REQUEST) { + bindex_t idx; + binmap_t smallbits; + nb = (bytes < MIN_REQUEST) ? MIN_CHUNK_SIZE : pad_request(bytes); + idx = small_index(nb); + smallbits = ms->smallmap >> idx; + + if ((smallbits & 0x3U) != 0) { /* Remainderless fit to a smallbin. */ + mchunkptr b, p; + idx += ~smallbits & 1; /* Uses next bin if idx empty */ + b = smallbin_at(ms, idx); + p = b->fd; + assert(chunksize(p) == small_index2size(idx)); + unlink_first_small_chunk(ms, b, p, idx); + set_inuse_and_pinuse(ms, p, small_index2size(idx)); + mem = chunk2mem(p); + check_malloced_chunk(ms, mem, nb); + goto postaction; + } - else if (nb > ms->dvsize) { - if (smallbits != 0) { /* Use chunk in next nonempty smallbin */ - mchunkptr b, p, r; - size_t rsize; - bindex_t i; - binmap_t leftbits = (smallbits << idx) & left_bits(idx2bit(idx)); - binmap_t leastbit = least_bit(leftbits); - compute_bit2idx(leastbit, i); - b = smallbin_at(ms, i); - p = b->fd; - assert(chunksize(p) == small_index2size(i)); - unlink_first_small_chunk(ms, b, p, i); - rsize = small_index2size(i) - nb; - /* Fit here cannot be remainderless if 4byte sizes */ - if (SIZE_T_SIZE != 4 && rsize < MIN_CHUNK_SIZE) - set_inuse_and_pinuse(ms, p, small_index2size(i)); - else { - set_size_and_pinuse_of_inuse_chunk(ms, p, nb); - r = chunk_plus_offset(p, nb); - set_size_and_pinuse_of_free_chunk(r, rsize); - replace_dv(ms, r, rsize); - } - mem = chunk2mem(p); - check_malloced_chunk(ms, mem, nb); - goto postaction; + else if (nb > ms->dvsize) { + if (smallbits != 0) { /* Use chunk in next nonempty smallbin */ + mchunkptr b, p, r; + size_t rsize; + bindex_t i; + binmap_t leftbits = + (smallbits << idx) & left_bits(idx2bit(idx)); + binmap_t leastbit = least_bit(leftbits); + compute_bit2idx(leastbit, i); + b = smallbin_at(ms, i); + p = b->fd; + assert(chunksize(p) == small_index2size(i)); + unlink_first_small_chunk(ms, b, p, i); + rsize = small_index2size(i) - nb; + /* Fit here cannot be remainderless if 4byte sizes */ + if (SIZE_T_SIZE != 4 && rsize < MIN_CHUNK_SIZE) + set_inuse_and_pinuse(ms, p, small_index2size(i)); + else { + set_size_and_pinuse_of_inuse_chunk(ms, p, nb); + r = chunk_plus_offset(p, nb); + set_size_and_pinuse_of_free_chunk(r, rsize); + replace_dv(ms, r, rsize); + } + mem = chunk2mem(p); + check_malloced_chunk(ms, mem, nb); + goto postaction; + } + + else if (ms->treemap != 0 + && (mem = tmalloc_small(ms, nb)) != 0) { + check_malloced_chunk(ms, mem, nb); + goto postaction; + } + } + } else if (bytes >= MAX_REQUEST) + nb = MAX_SIZE_T; /* Too big to allocate. Force failure (in sys alloc) */ + else { + nb = pad_request(bytes); + if (ms->treemap != 0 && (mem = tmalloc_large(ms, nb)) != 0) { + check_malloced_chunk(ms, mem, nb); + goto postaction; + } } - else if (ms->treemap != 0 && (mem = tmalloc_small(ms, nb)) != 0) { - check_malloced_chunk(ms, mem, nb); - goto postaction; + if (nb <= ms->dvsize) { + size_t rsize = ms->dvsize - nb; + mchunkptr p = ms->dv; + if (rsize >= MIN_CHUNK_SIZE) { /* split dv */ + mchunkptr r = ms->dv = chunk_plus_offset(p, nb); + ms->dvsize = rsize; + set_size_and_pinuse_of_free_chunk(r, rsize); + set_size_and_pinuse_of_inuse_chunk(ms, p, nb); + } else { /* exhaust dv */ + size_t dvs = ms->dvsize; + ms->dvsize = 0; + ms->dv = 0; + set_inuse_and_pinuse(ms, p, dvs); + } + mem = chunk2mem(p); + check_malloced_chunk(ms, mem, nb); + goto postaction; } - } - } - else if (bytes >= MAX_REQUEST) - nb = MAX_SIZE_T; /* Too big to allocate. Force failure (in sys alloc) */ - else { - nb = pad_request(bytes); - if (ms->treemap != 0 && (mem = tmalloc_large(ms, nb)) != 0) { - check_malloced_chunk(ms, mem, nb); - goto postaction; - } - } - if (nb <= ms->dvsize) { - size_t rsize = ms->dvsize - nb; - mchunkptr p = ms->dv; - if (rsize >= MIN_CHUNK_SIZE) { /* split dv */ - mchunkptr r = ms->dv = chunk_plus_offset(p, nb); - ms->dvsize = rsize; - set_size_and_pinuse_of_free_chunk(r, rsize); - set_size_and_pinuse_of_inuse_chunk(ms, p, nb); - } - else { /* exhaust dv */ - size_t dvs = ms->dvsize; - ms->dvsize = 0; - ms->dv = 0; - set_inuse_and_pinuse(ms, p, dvs); - } - mem = chunk2mem(p); - check_malloced_chunk(ms, mem, nb); - goto postaction; - } - - else if (nb < ms->topsize) { /* Split top */ - size_t rsize = ms->topsize -= nb; - mchunkptr p = ms->top; - mchunkptr r = ms->top = chunk_plus_offset(p, nb); - r->head = rsize | PINUSE_BIT; - set_size_and_pinuse_of_inuse_chunk(ms, p, nb); - mem = chunk2mem(p); - check_top_chunk(ms, ms->top); - check_malloced_chunk(ms, mem, nb); - goto postaction; - } + else if (nb < ms->topsize) { /* Split top */ + size_t rsize = ms->topsize -= nb; + mchunkptr p = ms->top; + mchunkptr r = ms->top = chunk_plus_offset(p, nb); + r->head = rsize | PINUSE_BIT; + set_size_and_pinuse_of_inuse_chunk(ms, p, nb); + mem = chunk2mem(p); + check_top_chunk(ms, ms->top); + check_malloced_chunk(ms, mem, nb); + goto postaction; + } - mem = sys_alloc(ms, nb); + mem = sys_alloc(ms, nb); - postaction: - POSTACTION(ms); - return mem; - } + postaction: + POSTACTION(ms); + return mem; + } - return 0; + return 0; } -void mspace_free(mspace msp, void* mem) { - if (mem != 0) { - mchunkptr p = mem2chunk(mem); +void +mspace_free(mspace msp, void *mem) +{ + if (mem != 0) { + mchunkptr p = mem2chunk(mem); #if FOOTERS - mstate fm = get_mstate_for(p); + mstate fm = get_mstate_for(p); #else /* FOOTERS */ - mstate fm = (mstate)msp; + mstate fm = (mstate) msp; #endif /* FOOTERS */ - if (!ok_magic(fm)) { - USAGE_ERROR_ACTION(fm, p); - return; - } - if (!PREACTION(fm)) { - check_inuse_chunk(fm, p); - if (RTCHECK(ok_address(fm, p) && ok_cinuse(p))) { - size_t psize = chunksize(p); - mchunkptr next = chunk_plus_offset(p, psize); - if (!pinuse(p)) { - size_t prevsize = p->prev_foot; - if ((prevsize & IS_MMAPPED_BIT) != 0) { - prevsize &= ~IS_MMAPPED_BIT; - psize += prevsize + MMAP_FOOT_PAD; - if (CALL_MUNMAP((char*)p - prevsize, psize) == 0) - fm->footprint -= psize; - goto postaction; - } - else { - mchunkptr prev = chunk_minus_offset(p, prevsize); - psize += prevsize; - p = prev; - if (RTCHECK(ok_address(fm, prev))) { /* consolidate backward */ - if (p != fm->dv) { - unlink_chunk(fm, p, prevsize); - } - else if ((next->head & INUSE_BITS) == INUSE_BITS) { - fm->dvsize = psize; - set_free_with_pinuse(p, psize, next); - goto postaction; - } - } - else - goto erroraction; - } + if (!ok_magic(fm)) { + USAGE_ERROR_ACTION(fm, p); + return; } - - if (RTCHECK(ok_next(p, next) && ok_pinuse(next))) { - if (!cinuse(next)) { /* consolidate forward */ - if (next == fm->top) { - size_t tsize = fm->topsize += psize; - fm->top = p; - p->head = tsize | PINUSE_BIT; - if (p == fm->dv) { - fm->dv = 0; - fm->dvsize = 0; - } - if (should_trim(fm, tsize)) - sys_trim(fm, 0); - goto postaction; - } - else if (next == fm->dv) { - size_t dsize = fm->dvsize += psize; - fm->dv = p; - set_size_and_pinuse_of_free_chunk(p, dsize); - goto postaction; + if (!PREACTION(fm)) { + check_inuse_chunk(fm, p); + if (RTCHECK(ok_address(fm, p) && ok_cinuse(p))) { + size_t psize = chunksize(p); + mchunkptr next = chunk_plus_offset(p, psize); + if (!pinuse(p)) { + size_t prevsize = p->prev_foot; + if ((prevsize & IS_MMAPPED_BIT) != 0) { + prevsize &= ~IS_MMAPPED_BIT; + psize += prevsize + MMAP_FOOT_PAD; + if (CALL_MUNMAP((char *) p - prevsize, psize) == 0) + fm->footprint -= psize; + goto postaction; + } else { + mchunkptr prev = chunk_minus_offset(p, prevsize); + psize += prevsize; + p = prev; + if (RTCHECK(ok_address(fm, prev))) { /* consolidate backward */ + if (p != fm->dv) { + unlink_chunk(fm, p, prevsize); + } else if ((next->head & INUSE_BITS) == + INUSE_BITS) { + fm->dvsize = psize; + set_free_with_pinuse(p, psize, next); + goto postaction; + } + } else + goto erroraction; + } + } + + if (RTCHECK(ok_next(p, next) && ok_pinuse(next))) { + if (!cinuse(next)) { /* consolidate forward */ + if (next == fm->top) { + size_t tsize = fm->topsize += psize; + fm->top = p; + p->head = tsize | PINUSE_BIT; + if (p == fm->dv) { + fm->dv = 0; + fm->dvsize = 0; + } + if (should_trim(fm, tsize)) + sys_trim(fm, 0); + goto postaction; + } else if (next == fm->dv) { + size_t dsize = fm->dvsize += psize; + fm->dv = p; + set_size_and_pinuse_of_free_chunk(p, dsize); + goto postaction; + } else { + size_t nsize = chunksize(next); + psize += nsize; + unlink_chunk(fm, next, nsize); + set_size_and_pinuse_of_free_chunk(p, psize); + if (p == fm->dv) { + fm->dvsize = psize; + goto postaction; + } + } + } else + set_free_with_pinuse(p, psize, next); + insert_chunk(fm, p, psize); + check_free_chunk(fm, p); + goto postaction; + } } - else { - size_t nsize = chunksize(next); - psize += nsize; - unlink_chunk(fm, next, nsize); - set_size_and_pinuse_of_free_chunk(p, psize); - if (p == fm->dv) { - fm->dvsize = psize; - goto postaction; - } - } - } - else - set_free_with_pinuse(p, psize, next); - insert_chunk(fm, p, psize); - check_free_chunk(fm, p); - goto postaction; + erroraction: + USAGE_ERROR_ACTION(fm, p); + postaction: + POSTACTION(fm); } - } - erroraction: - USAGE_ERROR_ACTION(fm, p); - postaction: - POSTACTION(fm); } - } } -void* mspace_calloc(mspace msp, size_t n_elements, size_t elem_size) { - void* mem; - size_t req = 0; - mstate ms = (mstate)msp; - if (!ok_magic(ms)) { - USAGE_ERROR_ACTION(ms,ms); - return 0; - } - if (n_elements != 0) { - req = n_elements * elem_size; - if (((n_elements | elem_size) & ~(size_t)0xffff) && - (req / n_elements != elem_size)) - req = MAX_SIZE_T; /* force downstream failure on overflow */ - } - mem = internal_malloc(ms, req); - if (mem != 0 && calloc_must_clear(mem2chunk(mem))) - memset(mem, 0, req); - return mem; +void * +mspace_calloc(mspace msp, size_t n_elements, size_t elem_size) +{ + void *mem; + size_t req = 0; + mstate ms = (mstate) msp; + if (!ok_magic(ms)) { + USAGE_ERROR_ACTION(ms, ms); + return 0; + } + if (n_elements != 0) { + req = n_elements * elem_size; + if (((n_elements | elem_size) & ~(size_t) 0xffff) && + (req / n_elements != elem_size)) + req = MAX_SIZE_T; /* force downstream failure on overflow */ + } + mem = internal_malloc(ms, req); + if (mem != 0 && calloc_must_clear(mem2chunk(mem))) + memset(mem, 0, req); + return mem; } -void* mspace_realloc(mspace msp, void* oldmem, size_t bytes) { - if (oldmem == 0) - return mspace_malloc(msp, bytes); +void * +mspace_realloc(mspace msp, void *oldmem, size_t bytes) +{ + if (oldmem == 0) + return mspace_malloc(msp, bytes); #ifdef REALLOC_ZERO_BYTES_FREES - if (bytes == 0) { - mspace_free(msp, oldmem); - return 0; - } + if (bytes == 0) { + mspace_free(msp, oldmem); + return 0; + } #endif /* REALLOC_ZERO_BYTES_FREES */ - else { + else { #if FOOTERS - mchunkptr p = mem2chunk(oldmem); - mstate ms = get_mstate_for(p); + mchunkptr p = mem2chunk(oldmem); + mstate ms = get_mstate_for(p); #else /* FOOTERS */ - mstate ms = (mstate)msp; + mstate ms = (mstate) msp; #endif /* FOOTERS */ - if (!ok_magic(ms)) { - USAGE_ERROR_ACTION(ms,ms); - return 0; + if (!ok_magic(ms)) { + USAGE_ERROR_ACTION(ms, ms); + return 0; + } + return internal_realloc(ms, oldmem, bytes); } - return internal_realloc(ms, oldmem, bytes); - } } -void* mspace_memalign(mspace msp, size_t alignment, size_t bytes) { - mstate ms = (mstate)msp; - if (!ok_magic(ms)) { - USAGE_ERROR_ACTION(ms,ms); - return 0; - } - return internal_memalign(ms, alignment, bytes); +void * +mspace_memalign(mspace msp, size_t alignment, size_t bytes) +{ + mstate ms = (mstate) msp; + if (!ok_magic(ms)) { + USAGE_ERROR_ACTION(ms, ms); + return 0; + } + return internal_memalign(ms, alignment, bytes); } -void** mspace_independent_calloc(mspace msp, size_t n_elements, - size_t elem_size, void* chunks[]) { - size_t sz = elem_size; /* serves as 1-element array */ - mstate ms = (mstate)msp; - if (!ok_magic(ms)) { - USAGE_ERROR_ACTION(ms,ms); - return 0; - } - return ialloc(ms, n_elements, &sz, 3, chunks); +void ** +mspace_independent_calloc(mspace msp, size_t n_elements, + size_t elem_size, void *chunks[]) +{ + size_t sz = elem_size; /* serves as 1-element array */ + mstate ms = (mstate) msp; + if (!ok_magic(ms)) { + USAGE_ERROR_ACTION(ms, ms); + return 0; + } + return ialloc(ms, n_elements, &sz, 3, chunks); } -void** mspace_independent_comalloc(mspace msp, size_t n_elements, - size_t sizes[], void* chunks[]) { - mstate ms = (mstate)msp; - if (!ok_magic(ms)) { - USAGE_ERROR_ACTION(ms,ms); - return 0; - } - return ialloc(ms, n_elements, sizes, 0, chunks); +void ** +mspace_independent_comalloc(mspace msp, size_t n_elements, + size_t sizes[], void *chunks[]) +{ + mstate ms = (mstate) msp; + if (!ok_magic(ms)) { + USAGE_ERROR_ACTION(ms, ms); + return 0; + } + return ialloc(ms, n_elements, sizes, 0, chunks); } -int mspace_trim(mspace msp, size_t pad) { - int result = 0; - mstate ms = (mstate)msp; - if (ok_magic(ms)) { - if (!PREACTION(ms)) { - result = sys_trim(ms, pad); - POSTACTION(ms); +int +mspace_trim(mspace msp, size_t pad) +{ + int result = 0; + mstate ms = (mstate) msp; + if (ok_magic(ms)) { + if (!PREACTION(ms)) { + result = sys_trim(ms, pad); + POSTACTION(ms); + } + } else { + USAGE_ERROR_ACTION(ms, ms); } - } - else { - USAGE_ERROR_ACTION(ms,ms); - } - return result; + return result; } -void mspace_malloc_stats(mspace msp) { - mstate ms = (mstate)msp; - if (ok_magic(ms)) { - internal_malloc_stats(ms); - } - else { - USAGE_ERROR_ACTION(ms,ms); - } +void +mspace_malloc_stats(mspace msp) +{ + mstate ms = (mstate) msp; + if (ok_magic(ms)) { + internal_malloc_stats(ms); + } else { + USAGE_ERROR_ACTION(ms, ms); + } } -size_t mspace_footprint(mspace msp) { - size_t result; - mstate ms = (mstate)msp; - if (ok_magic(ms)) { - result = ms->footprint; - } - USAGE_ERROR_ACTION(ms,ms); - return result; +size_t +mspace_footprint(mspace msp) +{ + size_t result; + mstate ms = (mstate) msp; + if (ok_magic(ms)) { + result = ms->footprint; + } + USAGE_ERROR_ACTION(ms, ms); + return result; } -size_t mspace_max_footprint(mspace msp) { - size_t result; - mstate ms = (mstate)msp; - if (ok_magic(ms)) { - result = ms->max_footprint; - } - USAGE_ERROR_ACTION(ms,ms); - return result; +size_t +mspace_max_footprint(mspace msp) +{ + size_t result; + mstate ms = (mstate) msp; + if (ok_magic(ms)) { + result = ms->max_footprint; + } + USAGE_ERROR_ACTION(ms, ms); + return result; } #if !NO_MALLINFO -struct mallinfo mspace_mallinfo(mspace msp) { - mstate ms = (mstate)msp; - if (!ok_magic(ms)) { - USAGE_ERROR_ACTION(ms,ms); - } - return internal_mallinfo(ms); +struct mallinfo +mspace_mallinfo(mspace msp) +{ + mstate ms = (mstate) msp; + if (!ok_magic(ms)) { + USAGE_ERROR_ACTION(ms, ms); + } + return internal_mallinfo(ms); } #endif /* NO_MALLINFO */ -int mspace_mallopt(int param_number, int value) { - return change_mparam(param_number, value); +int +mspace_mallopt(int param_number, int value) +{ + return change_mparam(param_number, value); } #endif /* MSPACES */ @@ -5109,3 +5234,4 @@ int mspace_mallopt(int param_number, int value) { */ #endif /* !HAVE_MALLOC */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/stdlib/SDL_qsort.c b/src/stdlib/SDL_qsort.c index 9278d2579..11be41f3e 100644 --- a/src/stdlib/SDL_qsort.c +++ b/src/stdlib/SDL_qsort.c @@ -60,7 +60,7 @@ #ifndef HAVE_QSORT -static char _ID[]=""; +static char _ID[] = ""; /* How many bytes are there per word? (Must be a power of 2, * and must in fact equal sizeof(int).) @@ -81,7 +81,7 @@ static char _ID[]=""; */ #define TRUNC_nonaligned 12 #define TRUNC_aligned 12 -#define TRUNC_words 12*WORD_BYTES /* nb different meaning */ +#define TRUNC_words 12*WORD_BYTES /* nb different meaning */ /* We use a simple pivoting algorithm for shortish sub-arrays * and a more complicated one for larger ones. The threshold @@ -89,7 +89,11 @@ static char _ID[]=""; */ #define PIVOT_THRESHOLD 40 -typedef struct { char * first; char * last; } stack_entry; +typedef struct +{ + char *first; + char *last; +} stack_entry; #define pushLeft {stack[stacktop].first=ffirst;stack[stacktop++].last=last;} #define pushRight {stack[stacktop].first=first;stack[stacktop++].last=llast;} #define doLeft {first=ffirst;llast=last;continue;} @@ -261,165 +265,187 @@ typedef struct { char * first; char * last; } stack_entry; /* ---------------------------------------------------------------------- */ -static char * pivot_big(char *first, char *mid, char *last, size_t size, - int compare(const void *, const void *)) { - size_t d=(((last-first)/size)>>3)*size; - char *m1,*m2,*m3; - { char *a=first, *b=first+d, *c=first+2*d; +static char * +pivot_big(char *first, char *mid, char *last, size_t size, + int compare(const void *, const void *)) +{ + size_t d = (((last - first) / size) >> 3) * size; + char *m1, *m2, *m3; + { + char *a = first, *b = first + d, *c = first + 2 * d; #ifdef DEBUG_QSORT -fprintf(stderr,"< %d %d %d\n",*(int*)a,*(int*)b,*(int*)c); + fprintf(stderr, "< %d %d %d\n", *(int *) a, *(int *) b, *(int *) c); #endif - m1 = compare(a,b)<0 ? - (compare(b,c)<0 ? b : (compare(a,c)<0 ? c : a)) - : (compare(a,c)<0 ? a : (compare(b,c)<0 ? c : b)); - } - { char *a=mid-d, *b=mid, *c=mid+d; + m1 = compare(a, b) < 0 ? + (compare(b, c) < 0 ? b : (compare(a, c) < 0 ? c : a)) + : (compare(a, c) < 0 ? a : (compare(b, c) < 0 ? c : b)); + } + { + char *a = mid - d, *b = mid, *c = mid + d; #ifdef DEBUG_QSORT -fprintf(stderr,". %d %d %d\n",*(int*)a,*(int*)b,*(int*)c); + fprintf(stderr, ". %d %d %d\n", *(int *) a, *(int *) b, *(int *) c); #endif - m2 = compare(a,b)<0 ? - (compare(b,c)<0 ? b : (compare(a,c)<0 ? c : a)) - : (compare(a,c)<0 ? a : (compare(b,c)<0 ? c : b)); - } - { char *a=last-2*d, *b=last-d, *c=last; + m2 = compare(a, b) < 0 ? + (compare(b, c) < 0 ? b : (compare(a, c) < 0 ? c : a)) + : (compare(a, c) < 0 ? a : (compare(b, c) < 0 ? c : b)); + } + { + char *a = last - 2 * d, *b = last - d, *c = last; #ifdef DEBUG_QSORT -fprintf(stderr,"> %d %d %d\n",*(int*)a,*(int*)b,*(int*)c); + fprintf(stderr, "> %d %d %d\n", *(int *) a, *(int *) b, *(int *) c); #endif - m3 = compare(a,b)<0 ? - (compare(b,c)<0 ? b : (compare(a,c)<0 ? c : a)) - : (compare(a,c)<0 ? a : (compare(b,c)<0 ? c : b)); - } + m3 = compare(a, b) < 0 ? + (compare(b, c) < 0 ? b : (compare(a, c) < 0 ? c : a)) + : (compare(a, c) < 0 ? a : (compare(b, c) < 0 ? c : b)); + } #ifdef DEBUG_QSORT -fprintf(stderr,"-> %d %d %d\n",*(int*)m1,*(int*)m2,*(int*)m3); + fprintf(stderr, "-> %d %d %d\n", *(int *) m1, *(int *) m2, *(int *) m3); #endif - return compare(m1,m2)<0 ? - (compare(m2,m3)<0 ? m2 : (compare(m1,m3)<0 ? m3 : m1)) - : (compare(m1,m3)<0 ? m1 : (compare(m2,m3)<0 ? m3 : m2)); + return compare(m1, m2) < 0 ? + (compare(m2, m3) < 0 ? m2 : (compare(m1, m3) < 0 ? m3 : m1)) + : (compare(m1, m3) < 0 ? m1 : (compare(m2, m3) < 0 ? m3 : m2)); } /* ---------------------------------------------------------------------- */ -static void qsort_nonaligned(void *base, size_t nmemb, size_t size, - int (*compare)(const void *, const void *)) { - - stack_entry stack[STACK_SIZE]; - int stacktop=0; - char *first,*last; - char *pivot=malloc(size); - size_t trunc=TRUNC_nonaligned*size; - assert(pivot!=0); - - first=(char*)base; last=first+(nmemb-1)*size; - - if ((size_t)(last-first)>trunc) { - char *ffirst=first, *llast=last; - while (1) { - /* Select pivot */ - { char * mid=first+size*((last-first)/size >> 1); - Pivot(SWAP_nonaligned,size); - memcpy(pivot,mid,size); - } - /* Partition. */ - Partition(SWAP_nonaligned,size); - /* Prepare to recurse/iterate. */ - Recurse(trunc) +static void +qsort_nonaligned(void *base, size_t nmemb, size_t size, + int (*compare) (const void *, const void *)) +{ + + stack_entry stack[STACK_SIZE]; + int stacktop = 0; + char *first, *last; + char *pivot = malloc(size); + size_t trunc = TRUNC_nonaligned * size; + assert(pivot != 0); + + first = (char *) base; + last = first + (nmemb - 1) * size; + + if ((size_t) (last - first) > trunc) { + char *ffirst = first, *llast = last; + while (1) { + /* Select pivot */ + { + char *mid = first + size * ((last - first) / size >> 1); + Pivot(SWAP_nonaligned, size); + memcpy(pivot, mid, size); + } + /* Partition. */ + Partition(SWAP_nonaligned, size); + /* Prepare to recurse/iterate. */ + Recurse(trunc)} } - } - PreInsertion(SWAP_nonaligned,TRUNC_nonaligned,size); - Insertion(SWAP_nonaligned); - free(pivot); + PreInsertion(SWAP_nonaligned, TRUNC_nonaligned, size); + Insertion(SWAP_nonaligned); + free(pivot); } -static void qsort_aligned(void *base, size_t nmemb, size_t size, - int (*compare)(const void *, const void *)) { - - stack_entry stack[STACK_SIZE]; - int stacktop=0; - char *first,*last; - char *pivot=malloc(size); - size_t trunc=TRUNC_aligned*size; - assert(pivot!=0); - - first=(char*)base; last=first+(nmemb-1)*size; - - if ((size_t)(last-first)>trunc) { - char *ffirst=first,*llast=last; - while (1) { - /* Select pivot */ - { char * mid=first+size*((last-first)/size >> 1); - Pivot(SWAP_aligned,size); - memcpy(pivot,mid,size); - } - /* Partition. */ - Partition(SWAP_aligned,size); - /* Prepare to recurse/iterate. */ - Recurse(trunc) +static void +qsort_aligned(void *base, size_t nmemb, size_t size, + int (*compare) (const void *, const void *)) +{ + + stack_entry stack[STACK_SIZE]; + int stacktop = 0; + char *first, *last; + char *pivot = malloc(size); + size_t trunc = TRUNC_aligned * size; + assert(pivot != 0); + + first = (char *) base; + last = first + (nmemb - 1) * size; + + if ((size_t) (last - first) > trunc) { + char *ffirst = first, *llast = last; + while (1) { + /* Select pivot */ + { + char *mid = first + size * ((last - first) / size >> 1); + Pivot(SWAP_aligned, size); + memcpy(pivot, mid, size); + } + /* Partition. */ + Partition(SWAP_aligned, size); + /* Prepare to recurse/iterate. */ + Recurse(trunc)} } - } - PreInsertion(SWAP_aligned,TRUNC_aligned,size); - Insertion(SWAP_aligned); - free(pivot); + PreInsertion(SWAP_aligned, TRUNC_aligned, size); + Insertion(SWAP_aligned); + free(pivot); } -static void qsort_words(void *base, size_t nmemb, - int (*compare)(const void *, const void *)) { +static void +qsort_words(void *base, size_t nmemb, + int (*compare) (const void *, const void *)) +{ - stack_entry stack[STACK_SIZE]; - int stacktop=0; - char *first,*last; - char *pivot=malloc(WORD_BYTES); - assert(pivot!=0); + stack_entry stack[STACK_SIZE]; + int stacktop = 0; + char *first, *last; + char *pivot = malloc(WORD_BYTES); + assert(pivot != 0); - first=(char*)base; last=first+(nmemb-1)*WORD_BYTES; + first = (char *) base; + last = first + (nmemb - 1) * WORD_BYTES; - if (last-first>TRUNC_words) { - char *ffirst=first, *llast=last; - while (1) { + if (last - first > TRUNC_words) { + char *ffirst = first, *llast = last; + while (1) { #ifdef DEBUG_QSORT -fprintf(stderr,"Doing %d:%d: ", - (first-(char*)base)/WORD_BYTES, - (last-(char*)base)/WORD_BYTES); + fprintf(stderr, "Doing %d:%d: ", + (first - (char *) base) / WORD_BYTES, + (last - (char *) base) / WORD_BYTES); #endif - /* Select pivot */ - { char * mid=first+WORD_BYTES*((last-first) / (2*WORD_BYTES)); - Pivot(SWAP_words,WORD_BYTES); - *(int*)pivot=*(int*)mid; - } + /* Select pivot */ + { + char *mid = + first + WORD_BYTES * ((last - first) / (2 * WORD_BYTES)); + Pivot(SWAP_words, WORD_BYTES); + *(int *) pivot = *(int *) mid; + } #ifdef DEBUG_QSORT -fprintf(stderr,"pivot=%d\n",*(int*)pivot); + fprintf(stderr, "pivot=%d\n", *(int *) pivot); #endif - /* Partition. */ - Partition(SWAP_words,WORD_BYTES); - /* Prepare to recurse/iterate. */ - Recurse(TRUNC_words) + /* Partition. */ + Partition(SWAP_words, WORD_BYTES); + /* Prepare to recurse/iterate. */ + Recurse(TRUNC_words)} } - } - PreInsertion(SWAP_words,(TRUNC_words/WORD_BYTES),WORD_BYTES); - /* Now do insertion sort. */ - last=((char*)base)+nmemb*WORD_BYTES; - for (first=((char*)base)+WORD_BYTES;first!=last;first+=WORD_BYTES) { - /* Find the right place for |first|. My apologies for var reuse */ - int *pl=(int*)(first-WORD_BYTES),*pr=(int*)first; - *(int*)pivot=*(int*)first; - for (;compare(pl,pivot)>0;pr=pl,--pl) { - *pr=*pl; } - if (pr!=(int*)first) *pr=*(int*)pivot; - } - free(pivot); + PreInsertion(SWAP_words, (TRUNC_words / WORD_BYTES), WORD_BYTES); + /* Now do insertion sort. */ + last = ((char *) base) + nmemb * WORD_BYTES; + for (first = ((char *) base) + WORD_BYTES; first != last; + first += WORD_BYTES) { + /* Find the right place for |first|. My apologies for var reuse */ + int *pl = (int *) (first - WORD_BYTES), *pr = (int *) first; + *(int *) pivot = *(int *) first; + for (; compare(pl, pivot) > 0; pr = pl, --pl) { + *pr = *pl; + } + if (pr != (int *) first) + *pr = *(int *) pivot; + } + free(pivot); } /* ---------------------------------------------------------------------- */ -void qsort(void *base, size_t nmemb, size_t size, - int (*compare)(const void *, const void *)) { - - if (nmemb<=1) return; - if (((uintptr_t)base|size)&(WORD_BYTES-1)) - qsort_nonaligned(base,nmemb,size,compare); - else if (size!=WORD_BYTES) - qsort_aligned(base,nmemb,size,compare); - else - qsort_words(base,nmemb,compare); +void +qsort(void *base, size_t nmemb, size_t size, + int (*compare) (const void *, const void *)) +{ + + if (nmemb <= 1) + return; + if (((uintptr_t) base | size) & (WORD_BYTES - 1)) + qsort_nonaligned(base, nmemb, size, compare); + else if (size != WORD_BYTES) + qsort_aligned(base, nmemb, size, compare); + else + qsort_words(base, nmemb, compare); } #endif /* !HAVE_QSORT */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/stdlib/SDL_stdlib.c b/src/stdlib/SDL_stdlib.c index b9c3bacc6..de17663af 100644 --- a/src/stdlib/SDL_stdlib.c +++ b/src/stdlib/SDL_stdlib.c @@ -33,588 +33,632 @@ #ifndef __FLTUSED__ #define __FLTUSED__ #ifdef __cplusplus - extern "C" +extern "C" #endif - __declspec(selectany) int _fltused=1; +__declspec(selectany) + int _fltused = 1; #endif /* Float to long */ -void __declspec(naked) _ftol() + void __declspec(naked) _ftol() { - __asm { - push ebp - mov ebp,esp - sub esp,20h - and esp,0FFFFFFF0h - fld st(0) - fst dword ptr [esp+18h] - fistp qword ptr [esp+10h] - fild qword ptr [esp+10h] - mov edx,dword ptr [esp+18h] - mov eax,dword ptr [esp+10h] - test eax,eax - je integer_QnaN_or_zero + /* *INDENT-OFF* */ + __asm { + push ebp + mov ebp,esp + sub esp,20h + and esp,0FFFFFFF0h + fld st(0) + fst dword ptr [esp+18h] + fistp qword ptr [esp+10h] + fild qword ptr [esp+10h] + mov edx,dword ptr [esp+18h] + mov eax,dword ptr [esp+10h] + test eax,eax + je integer_QnaN_or_zero arg_is_not_integer_QnaN: - fsubp st(1),st - test edx,edx - jns positive - fstp dword ptr [esp] - mov ecx,dword ptr [esp] - xor ecx,80000000h - add ecx,7FFFFFFFh - adc eax,0 - mov edx,dword ptr [esp+14h] - adc edx,0 - jmp localexit + fsubp st(1),st + test edx,edx + jns positive + fstp dword ptr [esp] + mov ecx,dword ptr [esp] + xor ecx,80000000h + add ecx,7FFFFFFFh + adc eax,0 + mov edx,dword ptr [esp+14h] + adc edx,0 + jmp localexit positive: - fstp dword ptr [esp] - mov ecx,dword ptr [esp] - add ecx,7FFFFFFFh - sbb eax,0 - mov edx,dword ptr [esp+14h] - sbb edx,0 - jmp localexit + fstp dword ptr [esp] + mov ecx,dword ptr [esp] + add ecx,7FFFFFFFh + sbb eax,0 + mov edx,dword ptr [esp+14h] + sbb edx,0 + jmp localexit integer_QnaN_or_zero: - mov edx,dword ptr [esp+14h] - test edx,7FFFFFFFh - jne arg_is_not_integer_QnaN - fstp dword ptr [esp+18h] - fstp dword ptr [esp+18h] + mov edx,dword ptr [esp+14h] + test edx,7FFFFFFFh + jne arg_is_not_integer_QnaN + fstp dword ptr [esp+18h] + fstp dword ptr [esp+18h] localexit: - leave - ret - } + leave + ret + } + /* *INDENT-ON* */ } -void __declspec(naked) _ftol2_sse() + +void +__declspec(naked) +_ftol2_sse() { - _ftol(); + _ftol(); } /* 64-bit math operators for 32-bit systems */ -void __declspec(naked) _allmul() +void +__declspec(naked) +_allmul() { - __asm { - push ebp - mov ebp,esp - push edi - push esi - push ebx - sub esp,0Ch - mov eax,dword ptr [ebp+10h] - mov edi,dword ptr [ebp+8] - mov ebx,eax - mov esi,eax - sar esi,1Fh - mov eax,dword ptr [ebp+8] - mul ebx - imul edi,esi - mov ecx,edx - mov dword ptr [ebp-18h],eax - mov edx,dword ptr [ebp+0Ch] - add ecx,edi - imul ebx,edx - mov eax,dword ptr [ebp-18h] - lea ebx,[ebx+ecx] - mov dword ptr [ebp-14h],ebx - mov edx,dword ptr [ebp-14h] - add esp,0Ch - pop ebx - pop esi - pop edi - pop ebp - ret - } + /* *INDENT-OFF* */ + __asm { + push ebp + mov ebp,esp + push edi + push esi + push ebx + sub esp,0Ch + mov eax,dword ptr [ebp+10h] + mov edi,dword ptr [ebp+8] + mov ebx,eax + mov esi,eax + sar esi,1Fh + mov eax,dword ptr [ebp+8] + mul ebx + imul edi,esi + mov ecx,edx + mov dword ptr [ebp-18h],eax + mov edx,dword ptr [ebp+0Ch] + add ecx,edi + imul ebx,edx + mov eax,dword ptr [ebp-18h] + lea ebx,[ebx+ecx] + mov dword ptr [ebp-14h],ebx + mov edx,dword ptr [ebp-14h] + add esp,0Ch + pop ebx + pop esi + pop edi + pop ebp + ret + } + /* *INDENT-ON* */ } -void __declspec(naked) _alldiv() +void +__declspec(naked) +_alldiv() { - __asm { - push edi - push esi - push ebx - xor edi,edi - mov eax,dword ptr [esp+14h] - or eax,eax - jge L1 - inc edi - mov edx,dword ptr [esp+10h] - neg eax - neg edx - sbb eax,0 - mov dword ptr [esp+14h],eax - mov dword ptr [esp+10h],edx + /* *INDENT-OFF* */ + __asm { + push edi + push esi + push ebx + xor edi,edi + mov eax,dword ptr [esp+14h] + or eax,eax + jge L1 + inc edi + mov edx,dword ptr [esp+10h] + neg eax + neg edx + sbb eax,0 + mov dword ptr [esp+14h],eax + mov dword ptr [esp+10h],edx L1: - mov eax,dword ptr [esp+1Ch] - or eax,eax - jge L2 - inc edi - mov edx,dword ptr [esp+18h] - neg eax - neg edx - sbb eax,0 - mov dword ptr [esp+1Ch],eax - mov dword ptr [esp+18h],edx + mov eax,dword ptr [esp+1Ch] + or eax,eax + jge L2 + inc edi + mov edx,dword ptr [esp+18h] + neg eax + neg edx + sbb eax,0 + mov dword ptr [esp+1Ch],eax + mov dword ptr [esp+18h],edx L2: - or eax,eax - jne L3 - mov ecx,dword ptr [esp+18h] - mov eax,dword ptr [esp+14h] - xor edx,edx - div ecx - mov ebx,eax - mov eax,dword ptr [esp+10h] - div ecx - mov edx,ebx - jmp L4 + or eax,eax + jne L3 + mov ecx,dword ptr [esp+18h] + mov eax,dword ptr [esp+14h] + xor edx,edx + div ecx + mov ebx,eax + mov eax,dword ptr [esp+10h] + div ecx + mov edx,ebx + jmp L4 L3: - mov ebx,eax - mov ecx,dword ptr [esp+18h] - mov edx,dword ptr [esp+14h] - mov eax,dword ptr [esp+10h] + mov ebx,eax + mov ecx,dword ptr [esp+18h] + mov edx,dword ptr [esp+14h] + mov eax,dword ptr [esp+10h] L5: - shr ebx,1 - rcr ecx,1 - shr edx,1 - rcr eax,1 - or ebx,ebx - jne L5 - div ecx - mov esi,eax - mul dword ptr [esp+1Ch] - mov ecx,eax - mov eax,dword ptr [esp+18h] - mul esi - add edx,ecx - jb L6 - cmp edx,dword ptr [esp+14h] - ja L6 - jb L7 - cmp eax,dword ptr [esp+10h] - jbe L7 + shr ebx,1 + rcr ecx,1 + shr edx,1 + rcr eax,1 + or ebx,ebx + jne L5 + div ecx + mov esi,eax + mul dword ptr [esp+1Ch] + mov ecx,eax + mov eax,dword ptr [esp+18h] + mul esi + add edx,ecx + jb L6 + cmp edx,dword ptr [esp+14h] + ja L6 + jb L7 + cmp eax,dword ptr [esp+10h] + jbe L7 L6: - dec esi + dec esi L7: - xor edx,edx - mov eax,esi + xor edx,edx + mov eax,esi L4: - dec edi - jne L8 - neg edx - neg eax - sbb edx,0 + dec edi + jne L8 + neg edx + neg eax + sbb edx,0 L8: - pop ebx - pop esi - pop edi - ret 10h - } + pop ebx + pop esi + pop edi + ret 10h + } + /* *INDENT-ON* */ } -void __declspec(naked) _aulldiv() +void +__declspec(naked) +_aulldiv() { - __asm { - push ebx - push esi - mov eax,dword ptr [esp+18h] - or eax,eax - jne L1 - mov ecx,dword ptr [esp+14h] - mov eax,dword ptr [esp+10h] - xor edx,edx - div ecx - mov ebx,eax - mov eax,dword ptr [esp+0Ch] - div ecx - mov edx,ebx - jmp L2 + /* *INDENT-OFF* */ + __asm { + push ebx + push esi + mov eax,dword ptr [esp+18h] + or eax,eax + jne L1 + mov ecx,dword ptr [esp+14h] + mov eax,dword ptr [esp+10h] + xor edx,edx + div ecx + mov ebx,eax + mov eax,dword ptr [esp+0Ch] + div ecx + mov edx,ebx + jmp L2 L1: - mov ecx,eax - mov ebx,dword ptr [esp+14h] - mov edx,dword ptr [esp+10h] - mov eax,dword ptr [esp+0Ch] + mov ecx,eax + mov ebx,dword ptr [esp+14h] + mov edx,dword ptr [esp+10h] + mov eax,dword ptr [esp+0Ch] L3: - shr ecx,1 - rcr ebx,1 - shr edx,1 - rcr eax,1 - or ecx,ecx - jne L3 - div ebx - mov esi,eax - mul dword ptr [esp+18h] - mov ecx,eax - mov eax,dword ptr [esp+14h] - mul esi - add edx,ecx - jb L4 - cmp edx,dword ptr [esp+10h] - ja L4 - jb L5 - cmp eax,dword ptr [esp+0Ch] - jbe L5 + shr ecx,1 + rcr ebx,1 + shr edx,1 + rcr eax,1 + or ecx,ecx + jne L3 + div ebx + mov esi,eax + mul dword ptr [esp+18h] + mov ecx,eax + mov eax,dword ptr [esp+14h] + mul esi + add edx,ecx + jb L4 + cmp edx,dword ptr [esp+10h] + ja L4 + jb L5 + cmp eax,dword ptr [esp+0Ch] + jbe L5 L4: - dec esi + dec esi L5: - xor edx,edx - mov eax,esi + xor edx,edx + mov eax,esi L2: - pop esi - pop ebx - ret 10h - } + pop esi + pop ebx + ret 10h + } + /* *INDENT-ON* */ } -void __declspec(naked) _allrem() +void +__declspec(naked) +_allrem() { - __asm { - push ebx - push edi - xor edi,edi - mov eax,dword ptr [esp+10h] - or eax,eax - jge L1 - inc edi - mov edx,dword ptr [esp+0Ch] - neg eax - neg edx - sbb eax,0 - mov dword ptr [esp+10h],eax - mov dword ptr [esp+0Ch],edx + /* *INDENT-OFF* */ + __asm { + push ebx + push edi + xor edi,edi + mov eax,dword ptr [esp+10h] + or eax,eax + jge L1 + inc edi + mov edx,dword ptr [esp+0Ch] + neg eax + neg edx + sbb eax,0 + mov dword ptr [esp+10h],eax + mov dword ptr [esp+0Ch],edx L1: - mov eax,dword ptr [esp+18h] - or eax,eax - jge L2 - mov edx,dword ptr [esp+14h] - neg eax - neg edx - sbb eax,0 - mov dword ptr [esp+18h],eax - mov dword ptr [esp+14h],edx + mov eax,dword ptr [esp+18h] + or eax,eax + jge L2 + mov edx,dword ptr [esp+14h] + neg eax + neg edx + sbb eax,0 + mov dword ptr [esp+18h],eax + mov dword ptr [esp+14h],edx L2: - or eax,eax - jne L3 - mov ecx,dword ptr [esp+14h] - mov eax,dword ptr [esp+10h] - xor edx,edx - div ecx - mov eax,dword ptr [esp+0Ch] - div ecx - mov eax,edx - xor edx,edx - dec edi - jns L4 - jmp L8 + or eax,eax + jne L3 + mov ecx,dword ptr [esp+14h] + mov eax,dword ptr [esp+10h] + xor edx,edx + div ecx + mov eax,dword ptr [esp+0Ch] + div ecx + mov eax,edx + xor edx,edx + dec edi + jns L4 + jmp L8 L3: - mov ebx,eax - mov ecx,dword ptr [esp+14h] - mov edx,dword ptr [esp+10h] - mov eax,dword ptr [esp+0Ch] + mov ebx,eax + mov ecx,dword ptr [esp+14h] + mov edx,dword ptr [esp+10h] + mov eax,dword ptr [esp+0Ch] L5: - shr ebx,1 - rcr ecx,1 - shr edx,1 - rcr eax,1 - or ebx,ebx - jne L5 - div ecx - mov ecx,eax - mul dword ptr [esp+18h] - xchg eax,ecx - mul dword ptr [esp+14h] - add edx,ecx - jb L6 - cmp edx,dword ptr [esp+10h] - ja L6 - jb L7 - cmp eax,dword ptr [esp+0Ch] - jbe L7 + shr ebx,1 + rcr ecx,1 + shr edx,1 + rcr eax,1 + or ebx,ebx + jne L5 + div ecx + mov ecx,eax + mul dword ptr [esp+18h] + xchg eax,ecx + mul dword ptr [esp+14h] + add edx,ecx + jb L6 + cmp edx,dword ptr [esp+10h] + ja L6 + jb L7 + cmp eax,dword ptr [esp+0Ch] + jbe L7 L6: - sub eax,dword ptr [esp+14h] - sbb edx,dword ptr [esp+18h] + sub eax,dword ptr [esp+14h] + sbb edx,dword ptr [esp+18h] L7: - sub eax,dword ptr [esp+0Ch] - sbb edx,dword ptr [esp+10h] - dec edi - jns L8 + sub eax,dword ptr [esp+0Ch] + sbb edx,dword ptr [esp+10h] + dec edi + jns L8 L4: - neg edx - neg eax - sbb edx,0 + neg edx + neg eax + sbb edx,0 L8: - pop edi - pop ebx - ret 10h - } + pop edi + pop ebx + ret 10h + } + /* *INDENT-ON* */ } -void __declspec(naked) _aullrem() +void +__declspec(naked) +_aullrem() { - __asm { - push ebx - mov eax,dword ptr [esp+14h] - or eax,eax - jne L1 - mov ecx,dword ptr [esp+10h] - mov eax,dword ptr [esp+0Ch] - xor edx,edx - div ecx - mov eax,dword ptr [esp+8] - div ecx - mov eax,edx - xor edx,edx - jmp L2 + /* *INDENT-OFF* */ + __asm { + push ebx + mov eax,dword ptr [esp+14h] + or eax,eax + jne L1 + mov ecx,dword ptr [esp+10h] + mov eax,dword ptr [esp+0Ch] + xor edx,edx + div ecx + mov eax,dword ptr [esp+8] + div ecx + mov eax,edx + xor edx,edx + jmp L2 L1: - mov ecx,eax - mov ebx,dword ptr [esp+10h] - mov edx,dword ptr [esp+0Ch] - mov eax,dword ptr [esp+8] + mov ecx,eax + mov ebx,dword ptr [esp+10h] + mov edx,dword ptr [esp+0Ch] + mov eax,dword ptr [esp+8] L3: - shr ecx,1 - rcr ebx,1 - shr edx,1 - rcr eax,1 - or ecx,ecx - jne L3 - div ebx - mov ecx,eax - mul dword ptr [esp+14h] - xchg eax,ecx - mul dword ptr [esp+10h] - add edx,ecx - jb L4 - cmp edx,dword ptr [esp+0Ch] - ja L4 - jb L5 - cmp eax,dword ptr [esp+8] - jbe L5 + shr ecx,1 + rcr ebx,1 + shr edx,1 + rcr eax,1 + or ecx,ecx + jne L3 + div ebx + mov ecx,eax + mul dword ptr [esp+14h] + xchg eax,ecx + mul dword ptr [esp+10h] + add edx,ecx + jb L4 + cmp edx,dword ptr [esp+0Ch] + ja L4 + jb L5 + cmp eax,dword ptr [esp+8] + jbe L5 L4: - sub eax,dword ptr [esp+10h] - sbb edx,dword ptr [esp+14h] + sub eax,dword ptr [esp+10h] + sbb edx,dword ptr [esp+14h] L5: - sub eax,dword ptr [esp+8] - sbb edx,dword ptr [esp+0Ch] - neg edx - neg eax - sbb edx,0 + sub eax,dword ptr [esp+8] + sbb edx,dword ptr [esp+0Ch] + neg edx + neg eax + sbb edx,0 L2: - pop ebx - ret 10h - } + pop ebx + ret 10h + } + /* *INDENT-ON* */ } -void __declspec(naked) _alldvrm() +void +__declspec(naked) +_alldvrm() { - __asm { - push edi - push esi - push ebp - xor edi,edi - xor ebp,ebp - mov eax,dword ptr [esp+14h] - or eax,eax - jge L1 - inc edi - inc ebp - mov edx,dword ptr [esp+10h] - neg eax - neg edx - sbb eax,0 - mov dword ptr [esp+14h],eax - mov dword ptr [esp+10h],edx + /* *INDENT-OFF* */ + __asm { + push edi + push esi + push ebp + xor edi,edi + xor ebp,ebp + mov eax,dword ptr [esp+14h] + or eax,eax + jge L1 + inc edi + inc ebp + mov edx,dword ptr [esp+10h] + neg eax + neg edx + sbb eax,0 + mov dword ptr [esp+14h],eax + mov dword ptr [esp+10h],edx L1: - mov eax,dword ptr [esp+1Ch] - or eax,eax - jge L2 - inc edi - mov edx,dword ptr [esp+18h] - neg eax - neg edx - sbb eax,0 - mov dword ptr [esp+1Ch],eax - mov dword ptr [esp+18h],edx + mov eax,dword ptr [esp+1Ch] + or eax,eax + jge L2 + inc edi + mov edx,dword ptr [esp+18h] + neg eax + neg edx + sbb eax,0 + mov dword ptr [esp+1Ch],eax + mov dword ptr [esp+18h],edx L2: - or eax,eax - jne L3 - mov ecx,dword ptr [esp+18h] - mov eax,dword ptr [esp+14h] - xor edx,edx - div ecx - mov ebx,eax - mov eax,dword ptr [esp+10h] - div ecx - mov esi,eax - mov eax,ebx - mul dword ptr [esp+18h] - mov ecx,eax - mov eax,esi - mul dword ptr [esp+18h] - add edx,ecx - jmp L4 + or eax,eax + jne L3 + mov ecx,dword ptr [esp+18h] + mov eax,dword ptr [esp+14h] + xor edx,edx + div ecx + mov ebx,eax + mov eax,dword ptr [esp+10h] + div ecx + mov esi,eax + mov eax,ebx + mul dword ptr [esp+18h] + mov ecx,eax + mov eax,esi + mul dword ptr [esp+18h] + add edx,ecx + jmp L4 L3: - mov ebx,eax - mov ecx,dword ptr [esp+18h] - mov edx,dword ptr [esp+14h] - mov eax,dword ptr [esp+10h] + mov ebx,eax + mov ecx,dword ptr [esp+18h] + mov edx,dword ptr [esp+14h] + mov eax,dword ptr [esp+10h] L5: - shr ebx,1 - rcr ecx,1 - shr edx,1 - rcr eax,1 - or ebx,ebx - jne L5 - div ecx - mov esi,eax - mul dword ptr [esp+1Ch] - mov ecx,eax - mov eax,dword ptr [esp+18h] - mul esi - add edx,ecx - jb L6 - cmp edx,dword ptr [esp+14h] - ja L6 - jb L7 - cmp eax,dword ptr [esp+10h] - jbe L7 + shr ebx,1 + rcr ecx,1 + shr edx,1 + rcr eax,1 + or ebx,ebx + jne L5 + div ecx + mov esi,eax + mul dword ptr [esp+1Ch] + mov ecx,eax + mov eax,dword ptr [esp+18h] + mul esi + add edx,ecx + jb L6 + cmp edx,dword ptr [esp+14h] + ja L6 + jb L7 + cmp eax,dword ptr [esp+10h] + jbe L7 L6: - dec esi - sub eax,dword ptr [esp+18h] - sbb edx,dword ptr [esp+1Ch] + dec esi + sub eax,dword ptr [esp+18h] + sbb edx,dword ptr [esp+1Ch] L7: - xor ebx,ebx + xor ebx,ebx L4: - sub eax,dword ptr [esp+10h] - sbb edx,dword ptr [esp+14h] - dec ebp - jns L9 - neg edx - neg eax - sbb edx,0 + sub eax,dword ptr [esp+10h] + sbb edx,dword ptr [esp+14h] + dec ebp + jns L9 + neg edx + neg eax + sbb edx,0 L9: - mov ecx,edx - mov edx,ebx - mov ebx,ecx - mov ecx,eax - mov eax,esi - dec edi - jne L8 - neg edx - neg eax - sbb edx,0 + mov ecx,edx + mov edx,ebx + mov ebx,ecx + mov ecx,eax + mov eax,esi + dec edi + jne L8 + neg edx + neg eax + sbb edx,0 L8: - pop ebp - pop esi - pop edi - ret 10h - } + pop ebp + pop esi + pop edi + ret 10h + } + /* *INDENT-ON* */ } -void __declspec(naked) _aulldvrm() +void +__declspec(naked) +_aulldvrm() { - __asm { - push esi - mov eax,dword ptr [esp+14h] - or eax,eax - jne L1 - mov ecx,dword ptr [esp+10h] - mov eax,dword ptr [esp+0Ch] - xor edx,edx - div ecx - mov ebx,eax - mov eax,dword ptr [esp+8] - div ecx - mov esi,eax - mov eax,ebx - mul dword ptr [esp+10h] - mov ecx,eax - mov eax,esi - mul dword ptr [esp+10h] - add edx,ecx - jmp L2 + /* *INDENT-OFF* */ + __asm { + push esi + mov eax,dword ptr [esp+14h] + or eax,eax + jne L1 + mov ecx,dword ptr [esp+10h] + mov eax,dword ptr [esp+0Ch] + xor edx,edx + div ecx + mov ebx,eax + mov eax,dword ptr [esp+8] + div ecx + mov esi,eax + mov eax,ebx + mul dword ptr [esp+10h] + mov ecx,eax + mov eax,esi + mul dword ptr [esp+10h] + add edx,ecx + jmp L2 L1: - mov ecx,eax - mov ebx,dword ptr [esp+10h] - mov edx,dword ptr [esp+0Ch] - mov eax,dword ptr [esp+8] + mov ecx,eax + mov ebx,dword ptr [esp+10h] + mov edx,dword ptr [esp+0Ch] + mov eax,dword ptr [esp+8] L3: - shr ecx,1 - rcr ebx,1 - shr edx,1 - rcr eax,1 - or ecx,ecx - jne L3 - div ebx - mov esi,eax - mul dword ptr [esp+14h] - mov ecx,eax - mov eax,dword ptr [esp+10h] - mul esi - add edx,ecx - jb L4 - cmp edx,dword ptr [esp+0Ch] - ja L4 - jb L5 - cmp eax,dword ptr [esp+8] - jbe L5 + shr ecx,1 + rcr ebx,1 + shr edx,1 + rcr eax,1 + or ecx,ecx + jne L3 + div ebx + mov esi,eax + mul dword ptr [esp+14h] + mov ecx,eax + mov eax,dword ptr [esp+10h] + mul esi + add edx,ecx + jb L4 + cmp edx,dword ptr [esp+0Ch] + ja L4 + jb L5 + cmp eax,dword ptr [esp+8] + jbe L5 L4: - dec esi - sub eax,dword ptr [esp+10h] - sbb edx,dword ptr [esp+14h] + dec esi + sub eax,dword ptr [esp+10h] + sbb edx,dword ptr [esp+14h] L5: - xor ebx,ebx + xor ebx,ebx L2: - sub eax,dword ptr [esp+8] - sbb edx,dword ptr [esp+0Ch] - neg edx - neg eax - sbb edx,0 - mov ecx,edx - mov edx,ebx - mov ebx,ecx - mov ecx,eax - mov eax,esi - pop esi - ret 10h - } + sub eax,dword ptr [esp+8] + sbb edx,dword ptr [esp+0Ch] + neg edx + neg eax + sbb edx,0 + mov ecx,edx + mov edx,ebx + mov ebx,ecx + mov ecx,eax + mov eax,esi + pop esi + ret 10h + } + /* *INDENT-ON* */ } -void __declspec(naked) _allshl() +void +__declspec(naked) +_allshl() { - __asm { - cmp cl,40h - jae RETZERO - cmp cl,20h - jae MORE32 - shld edx,eax,cl - shl eax,cl - ret + /* *INDENT-OFF* */ + __asm { + cmp cl,40h + jae RETZERO + cmp cl,20h + jae MORE32 + shld edx,eax,cl + shl eax,cl + ret MORE32: - mov edx,eax - xor eax,eax - and cl,1Fh - shl edx,cl - ret + mov edx,eax + xor eax,eax + and cl,1Fh + shl edx,cl + ret RETZERO: - xor eax,eax - xor edx,edx - ret - } + xor eax,eax + xor edx,edx + ret + } + /* *INDENT-ON* */ } -void __declspec(naked) _aullshr() +void +__declspec(naked) +_aullshr() { - __asm { - cmp cl,40h - jae RETZERO - cmp cl,20h - jae MORE32 - shrd eax,edx,cl - shr edx,cl - ret + /* *INDENT-OFF* */ + __asm { + cmp cl,40h + jae RETZERO + cmp cl,20h + jae MORE32 + shrd eax,edx,cl + shr edx,cl + ret MORE32: - mov eax,edx - xor edx,edx - and cl,1Fh - shr eax,cl - ret + mov eax,edx + xor edx,edx + and cl,1Fh + shr eax,cl + ret RETZERO: - xor eax,eax - xor edx,edx - ret - } + xor eax,eax + xor edx,edx + ret + } + /* *INDENT-ON* */ } #endif /* MSC_VER */ #endif /* !HAVE_LIBC */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/stdlib/SDL_string.c b/src/stdlib/SDL_string.c index 02a93a5d9..fa9672a3a 100644 --- a/src/stdlib/SDL_string.c +++ b/src/stdlib/SDL_string.c @@ -30,26 +30,27 @@ #define SDL_islowerhex(X) (((X) >= 'a') && ((X) <= 'f')) #if !defined(HAVE_SSCANF) || !defined(HAVE_STRTOL) -static size_t SDL_ScanLong(const char *text, int radix, long *valuep) +static size_t +SDL_ScanLong(const char *text, int radix, long *valuep) { const char *textstart = text; long value = 0; SDL_bool negative = SDL_FALSE; - if ( *text == '-' ) { + if (*text == '-') { negative = SDL_TRUE; ++text; } - if ( radix == 16 && SDL_strncmp(text, "0x", 2) == 0 ) { + if (radix == 16 && SDL_strncmp(text, "0x", 2) == 0) { text += 2; } - for ( ; ; ) { + for (;;) { int v; - if ( SDL_isdigit(*text) ) { + if (SDL_isdigit(*text)) { v = *text - '0'; - } else if ( radix == 16 && SDL_isupperhex(*text) ) { + } else if (radix == 16 && SDL_isupperhex(*text)) { v = 10 + (*text - 'A'); - } else if ( radix == 16 && SDL_islowerhex(*text) ) { + } else if (radix == 16 && SDL_islowerhex(*text)) { v = 10 + (*text - 'a'); } else { break; @@ -58,8 +59,8 @@ static size_t SDL_ScanLong(const char *text, int radix, long *valuep) value += v; ++text; } - if ( valuep ) { - if ( negative && value ) { + if (valuep) { + if (negative && value) { *valuep = -value; } else { *valuep = value; @@ -70,21 +71,22 @@ static size_t SDL_ScanLong(const char *text, int radix, long *valuep) #endif #if !defined(HAVE_SSCANF) || !defined(HAVE_STRTOUL) || !defined(HAVE_STRTOD) -static size_t SDL_ScanUnsignedLong(const char *text, int radix, unsigned long *valuep) +static size_t +SDL_ScanUnsignedLong(const char *text, int radix, unsigned long *valuep) { const char *textstart = text; unsigned long value = 0; - if ( radix == 16 && SDL_strncmp(text, "0x", 2) == 0 ) { + if (radix == 16 && SDL_strncmp(text, "0x", 2) == 0) { text += 2; } - for ( ; ; ) { + for (;;) { int v; - if ( SDL_isdigit(*text) ) { + if (SDL_isdigit(*text)) { v = *text - '0'; - } else if ( radix == 16 && SDL_isupperhex(*text) ) { + } else if (radix == 16 && SDL_isupperhex(*text)) { v = 10 + (*text - 'A'); - } else if ( radix == 16 && SDL_islowerhex(*text) ) { + } else if (radix == 16 && SDL_islowerhex(*text)) { v = 10 + (*text - 'a'); } else { break; @@ -93,7 +95,7 @@ static size_t SDL_ScanUnsignedLong(const char *text, int radix, unsigned long *v value += v; ++text; } - if ( valuep ) { + if (valuep) { *valuep = value; } return (text - textstart); @@ -101,21 +103,22 @@ static size_t SDL_ScanUnsignedLong(const char *text, int radix, unsigned long *v #endif #ifndef HAVE_SSCANF -static size_t SDL_ScanUintPtrT(const char *text, int radix, uintptr_t *valuep) +static size_t +SDL_ScanUintPtrT(const char *text, int radix, uintptr_t * valuep) { const char *textstart = text; uintptr_t value = 0; - if ( radix == 16 && SDL_strncmp(text, "0x", 2) == 0 ) { + if (radix == 16 && SDL_strncmp(text, "0x", 2) == 0) { text += 2; } - for ( ; ; ) { + for (;;) { int v; - if ( SDL_isdigit(*text) ) { + if (SDL_isdigit(*text)) { v = *text - '0'; - } else if ( radix == 16 && SDL_isupperhex(*text) ) { + } else if (radix == 16 && SDL_isupperhex(*text)) { v = 10 + (*text - 'A'); - } else if ( radix == 16 && SDL_islowerhex(*text) ) { + } else if (radix == 16 && SDL_islowerhex(*text)) { v = 10 + (*text - 'a'); } else { break; @@ -124,7 +127,7 @@ static size_t SDL_ScanUintPtrT(const char *text, int radix, uintptr_t *valuep) value += v; ++text; } - if ( valuep ) { + if (valuep) { *valuep = value; } return (text - textstart); @@ -133,26 +136,27 @@ static size_t SDL_ScanUintPtrT(const char *text, int radix, uintptr_t *valuep) #ifdef SDL_HAS_64BIT_TYPE #if !defined(HAVE_SSCANF) || !defined(HAVE_STRTOLL) -static size_t SDL_ScanLongLong(const char *text, int radix, Sint64 *valuep) +static size_t +SDL_ScanLongLong(const char *text, int radix, Sint64 * valuep) { const char *textstart = text; Sint64 value = 0; SDL_bool negative = SDL_FALSE; - if ( *text == '-' ) { + if (*text == '-') { negative = SDL_TRUE; ++text; } - if ( radix == 16 && SDL_strncmp(text, "0x", 2) == 0 ) { + if (radix == 16 && SDL_strncmp(text, "0x", 2) == 0) { text += 2; } - for ( ; ; ) { + for (;;) { int v; - if ( SDL_isdigit(*text) ) { + if (SDL_isdigit(*text)) { v = *text - '0'; - } else if ( radix == 16 && SDL_isupperhex(*text) ) { + } else if (radix == 16 && SDL_isupperhex(*text)) { v = 10 + (*text - 'A'); - } else if ( radix == 16 && SDL_islowerhex(*text) ) { + } else if (radix == 16 && SDL_islowerhex(*text)) { v = 10 + (*text - 'a'); } else { break; @@ -161,8 +165,8 @@ static size_t SDL_ScanLongLong(const char *text, int radix, Sint64 *valuep) value += v; ++text; } - if ( valuep ) { - if ( negative && value ) { + if (valuep) { + if (negative && value) { *valuep = -value; } else { *valuep = value; @@ -173,21 +177,22 @@ static size_t SDL_ScanLongLong(const char *text, int radix, Sint64 *valuep) #endif #if !defined(HAVE_SSCANF) || !defined(HAVE_STRTOULL) -static size_t SDL_ScanUnsignedLongLong(const char *text, int radix, Uint64 *valuep) +static size_t +SDL_ScanUnsignedLongLong(const char *text, int radix, Uint64 * valuep) { const char *textstart = text; Uint64 value = 0; - if ( radix == 16 && SDL_strncmp(text, "0x", 2) == 0 ) { + if (radix == 16 && SDL_strncmp(text, "0x", 2) == 0) { text += 2; } - for ( ; ; ) { + for (;;) { int v; - if ( SDL_isdigit(*text) ) { + if (SDL_isdigit(*text)) { v = *text - '0'; - } else if ( radix == 16 && SDL_isupperhex(*text) ) { + } else if (radix == 16 && SDL_isupperhex(*text)) { v = 10 + (*text - 'A'); - } else if ( radix == 16 && SDL_islowerhex(*text) ) { + } else if (radix == 16 && SDL_islowerhex(*text)) { v = 10 + (*text - 'a'); } else { break; @@ -196,7 +201,7 @@ static size_t SDL_ScanUnsignedLongLong(const char *text, int radix, Uint64 *valu value += v; ++text; } - if ( valuep ) { + if (valuep) { *valuep = value; } return (text - textstart); @@ -205,31 +210,32 @@ static size_t SDL_ScanUnsignedLongLong(const char *text, int radix, Uint64 *valu #endif /* SDL_HAS_64BIT_TYPE */ #if !defined(HAVE_SSCANF) || !defined(HAVE_STRTOD) -static size_t SDL_ScanFloat(const char *text, double *valuep) +static size_t +SDL_ScanFloat(const char *text, double *valuep) { const char *textstart = text; unsigned long lvalue = 0; double value = 0.0; SDL_bool negative = SDL_FALSE; - if ( *text == '-' ) { + if (*text == '-') { negative = SDL_TRUE; ++text; } text += SDL_ScanUnsignedLong(text, 10, &lvalue); value += lvalue; - if ( *text == '.' ) { + if (*text == '.') { int mult = 10; ++text; - while ( SDL_isdigit(*text) ) { + while (SDL_isdigit(*text)) { lvalue = *text - '0'; - value += (double)lvalue / mult; + value += (double) lvalue / mult; mult *= 10; ++text; } } - if ( valuep ) { - if ( negative && value ) { + if (valuep) { + if (negative && value) { *valuep = -value; } else { *valuep = value; @@ -240,31 +246,32 @@ static size_t SDL_ScanFloat(const char *text, double *valuep) #endif #ifndef SDL_memset -void *SDL_memset(void *dst, int c, size_t len) +void * +SDL_memset(void *dst, int c, size_t len) { size_t left = (len % 4); - if ( len >= 4 ) { + if (len >= 4) { Uint32 value = 0; - Uint32 *dstp = (Uint32 *)dst; + Uint32 *dstp = (Uint32 *) dst; int i; for (i = 0; i < 4; ++i) { value <<= 8; value |= c; } len /= 4; - while ( len-- ) { + while (len--) { *dstp++ = value; } } - if ( left > 0 ) { - Uint8 value = (Uint8)c; - Uint8 *dstp = (Uint8 *)dst; - switch(left) { - case 3: + if (left > 0) { + Uint8 value = (Uint8) c; + Uint8 *dstp = (Uint8 *) dst; + switch (left) { + case 3: *dstp++ = value; - case 2: + case 2: *dstp++ = value; - case 1: + case 1: *dstp++ = value; } } @@ -273,11 +280,12 @@ void *SDL_memset(void *dst, int c, size_t len) #endif #ifndef SDL_memcpy -void *SDL_memcpy(void *dst, const void *src, size_t len) +void * +SDL_memcpy(void *dst, const void *src, size_t len) { - char *srcp = (char *)src; - char *dstp = (char *)dst; - while ( len-- ) { + char *srcp = (char *) src; + char *dstp = (char *) dst; + while (len--) { *dstp++ = *srcp++; } return dst; @@ -285,13 +293,14 @@ void *SDL_memcpy(void *dst, const void *src, size_t len) #endif #ifndef SDL_revcpy -void *SDL_revcpy(void *dst, const void *src, size_t len) +void * +SDL_revcpy(void *dst, const void *src, size_t len) { - char *srcp = (char *)src; - char *dstp = (char *)dst; + char *srcp = (char *) src; + char *dstp = (char *) dst; srcp += len; dstp += len; - while ( len-- ) { + while (len--) { *dstp-- = *srcp--; } return dst; @@ -299,26 +308,28 @@ void *SDL_revcpy(void *dst, const void *src, size_t len) #endif #ifndef SDL_memcmp -int SDL_memcmp(const void *s1, const void *s2, size_t len) +int +SDL_memcmp(const void *s1, const void *s2, size_t len) { - char *s1p = (char *)s1; - char *s2p = (char *)s2; - while ( len-- ) { - if ( *s1p != *s2p ) { + char *s1p = (char *) s1; + char *s2p = (char *) s2; + while (len--) { + if (*s1p != *s2p) { return (*s1p - *s2p); - } - ++s1p; - ++s2p; + } + ++s1p; + ++s2p; } return 0; } #endif #ifndef HAVE_STRLEN -size_t SDL_strlen(const char *string) +size_t +SDL_strlen(const char *string) { size_t len = 0; - while ( *string++ ) { + while (*string++) { ++len; } return len; @@ -326,11 +337,12 @@ size_t SDL_strlen(const char *string) #endif #ifndef HAVE_STRLCPY -size_t SDL_strlcpy(char *dst, const char *src, size_t maxlen) +size_t +SDL_strlcpy(char *dst, const char *src, size_t maxlen) { size_t srclen = SDL_strlen(src); - if ( maxlen > 0 ) { - size_t len = SDL_min(srclen, maxlen-1); + if (maxlen > 0) { + size_t len = SDL_min(srclen, maxlen - 1); SDL_memcpy(dst, src, len); dst[len] = '\0'; } @@ -339,23 +351,25 @@ size_t SDL_strlcpy(char *dst, const char *src, size_t maxlen) #endif #ifndef HAVE_STRLCAT -size_t SDL_strlcat(char *dst, const char *src, size_t maxlen) +size_t +SDL_strlcat(char *dst, const char *src, size_t maxlen) { size_t dstlen = SDL_strlen(dst); size_t srclen = SDL_strlen(src); - if ( dstlen < maxlen ) { - SDL_strlcpy(dst+dstlen, src, maxlen-dstlen); + if (dstlen < maxlen) { + SDL_strlcpy(dst + dstlen, src, maxlen - dstlen); } - return dstlen+srclen; + return dstlen + srclen; } #endif #ifndef HAVE_STRDUP -char *SDL_strdup(const char *string) +char * +SDL_strdup(const char *string) { - size_t len = SDL_strlen(string)+1; + size_t len = SDL_strlen(string) + 1; char *newstr = SDL_malloc(len); - if ( newstr ) { + if (newstr) { SDL_strlcpy(newstr, string, len); } return newstr; @@ -363,13 +377,14 @@ char *SDL_strdup(const char *string) #endif #ifndef HAVE__STRREV -char *SDL_strrev(char *string) +char * +SDL_strrev(char *string) { size_t len = SDL_strlen(string); char *a = &string[0]; - char *b = &string[len-1]; + char *b = &string[len - 1]; len /= 2; - while ( len-- ) { + while (len--) { char c = *a; *a++ = *b; *b-- = c; @@ -379,65 +394,70 @@ char *SDL_strrev(char *string) #endif #ifndef HAVE__STRUPR -char *SDL_strupr(char *string) +char * +SDL_strupr(char *string) { char *bufp = string; - while ( *bufp ) { + while (*bufp) { *bufp = SDL_toupper(*bufp); - ++bufp; + ++bufp; } return string; } #endif #ifndef HAVE__STRLWR -char *SDL_strlwr(char *string) +char * +SDL_strlwr(char *string) { char *bufp = string; - while ( *bufp ) { + while (*bufp) { *bufp = SDL_tolower(*bufp); - ++bufp; + ++bufp; } return string; } #endif #ifndef HAVE_STRCHR -char *SDL_strchr(const char *string, int c) +char * +SDL_strchr(const char *string, int c) { - while ( *string ) { - if ( *string == c ) { - return (char *)string; + while (*string) { + if (*string == c) { + return (char *) string; } - ++string; + ++string; } return NULL; } #endif #ifndef HAVE_STRRCHR -char *SDL_strrchr(const char *string, int c) +char * +SDL_strrchr(const char *string, int c) { const char *bufp = string + SDL_strlen(string) - 1; - while ( bufp >= string ) { - if ( *bufp == c ) { - return (char *)bufp; + while (bufp >= string) { + if (*bufp == c) { + return (char *) bufp; } - --bufp; + --bufp; } return NULL; } #endif #ifndef HAVE_STRSTR -char *SDL_strstr(const char *haystack, const char *needle) +char * +SDL_strstr(const char *haystack, const char *needle) { size_t length = SDL_strlen(needle); - while ( *haystack ) { - if ( SDL_strncmp(haystack, needle, length) == 0 ) { - return (char *)haystack; + while (*haystack) { + if (SDL_strncmp(haystack, needle, length) == 0) { + return (char *) haystack; } - ++haystack; + ++haystack; } return NULL; } @@ -454,16 +474,17 @@ static const char ntoa_table[] = { #endif /* ntoa() conversion table */ #ifndef HAVE__LTOA -char *SDL_ltoa(long value, char *string, int radix) +char * +SDL_ltoa(long value, char *string, int radix) { char *bufp = string; - if ( value < 0 ) { + if (value < 0) { *bufp++ = '-'; value = -value; } - if ( value ) { - while ( value > 0 ) { + if (value) { + while (value > 0) { *bufp++ = ntoa_table[value % radix]; value /= radix; } @@ -473,8 +494,8 @@ char *SDL_ltoa(long value, char *string, int radix) *bufp = '\0'; /* The numbers went into the string backwards. :) */ - if ( *string == '-' ) { - SDL_strrev(string+1); + if (*string == '-') { + SDL_strrev(string + 1); } else { SDL_strrev(string); } @@ -484,12 +505,13 @@ char *SDL_ltoa(long value, char *string, int radix) #endif #ifndef HAVE__ULTOA -char *SDL_ultoa(unsigned long value, char *string, int radix) +char * +SDL_ultoa(unsigned long value, char *string, int radix) { char *bufp = string; - if ( value ) { - while ( value > 0 ) { + if (value) { + while (value > 0) { *bufp++ = ntoa_table[value % radix]; value /= radix; } @@ -506,13 +528,14 @@ char *SDL_ultoa(unsigned long value, char *string, int radix) #endif #ifndef HAVE_STRTOL -long SDL_strtol(const char *string, char **endp, int base) +long +SDL_strtol(const char *string, char **endp, int base) { size_t len; long value; - if ( !base ) { - if ( (SDL_strlen(string) > 2) && (SDL_strncmp(string, "0x", 2) == 0) ) { + if (!base) { + if ((SDL_strlen(string) > 2) && (SDL_strncmp(string, "0x", 2) == 0)) { base = 16; } else { base = 10; @@ -520,21 +543,22 @@ long SDL_strtol(const char *string, char **endp, int base) } len = SDL_ScanLong(string, base, &value); - if ( endp ) { - *endp = (char *)string + len; + if (endp) { + *endp = (char *) string + len; } return value; } #endif #ifndef HAVE_STRTOUL -unsigned long SDL_strtoul(const char *string, char **endp, int base) +unsigned long +SDL_strtoul(const char *string, char **endp, int base) { size_t len; unsigned long value; - if ( !base ) { - if ( (SDL_strlen(string) > 2) && (SDL_strncmp(string, "0x", 2) == 0) ) { + if (!base) { + if ((SDL_strlen(string) > 2) && (SDL_strncmp(string, "0x", 2) == 0)) { base = 16; } else { base = 10; @@ -542,8 +566,8 @@ unsigned long SDL_strtoul(const char *string, char **endp, int base) } len = SDL_ScanUnsignedLong(string, base, &value); - if ( endp ) { - *endp = (char *)string + len; + if (endp) { + *endp = (char *) string + len; } return value; } @@ -552,16 +576,17 @@ unsigned long SDL_strtoul(const char *string, char **endp, int base) #ifdef SDL_HAS_64BIT_TYPE #ifndef HAVE__I64TOA -char *SDL_lltoa(Sint64 value, char *string, int radix) +char * +SDL_lltoa(Sint64 value, char *string, int radix) { char *bufp = string; - if ( value < 0 ) { + if (value < 0) { *bufp++ = '-'; value = -value; } - if ( value ) { - while ( value > 0 ) { + if (value) { + while (value > 0) { *bufp++ = ntoa_table[value % radix]; value /= radix; } @@ -571,8 +596,8 @@ char *SDL_lltoa(Sint64 value, char *string, int radix) *bufp = '\0'; /* The numbers went into the string backwards. :) */ - if ( *string == '-' ) { - SDL_strrev(string+1); + if (*string == '-') { + SDL_strrev(string + 1); } else { SDL_strrev(string); } @@ -582,12 +607,13 @@ char *SDL_lltoa(Sint64 value, char *string, int radix) #endif #ifndef HAVE__UI64TOA -char *SDL_ulltoa(Uint64 value, char *string, int radix) +char * +SDL_ulltoa(Uint64 value, char *string, int radix) { char *bufp = string; - if ( value ) { - while ( value > 0 ) { + if (value) { + while (value > 0) { *bufp++ = ntoa_table[value % radix]; value /= radix; } @@ -604,13 +630,14 @@ char *SDL_ulltoa(Uint64 value, char *string, int radix) #endif #ifndef HAVE_STRTOLL -Sint64 SDL_strtoll(const char *string, char **endp, int base) +Sint64 +SDL_strtoll(const char *string, char **endp, int base) { size_t len; Sint64 value; - if ( !base ) { - if ( (SDL_strlen(string) > 2) && (SDL_strncmp(string, "0x", 2) == 0) ) { + if (!base) { + if ((SDL_strlen(string) > 2) && (SDL_strncmp(string, "0x", 2) == 0)) { base = 16; } else { base = 10; @@ -618,21 +645,22 @@ Sint64 SDL_strtoll(const char *string, char **endp, int base) } len = SDL_ScanLongLong(string, base, &value); - if ( endp ) { - *endp = (char *)string + len; + if (endp) { + *endp = (char *) string + len; } return value; } #endif #ifndef HAVE_STRTOULL -Uint64 SDL_strtoull(const char *string, char **endp, int base) +Uint64 +SDL_strtoull(const char *string, char **endp, int base) { size_t len; Uint64 value; - if ( !base ) { - if ( (SDL_strlen(string) > 2) && (SDL_strncmp(string, "0x", 2) == 0) ) { + if (!base) { + if ((SDL_strlen(string) > 2) && (SDL_strncmp(string, "0x", 2) == 0)) { base = 16; } else { base = 10; @@ -640,8 +668,8 @@ Uint64 SDL_strtoull(const char *string, char **endp, int base) } len = SDL_ScanUnsignedLongLong(string, base, &value); - if ( endp ) { - *endp = (char *)string + len; + if (endp) { + *endp = (char *) string + len; } return value; } @@ -650,104 +678,111 @@ Uint64 SDL_strtoull(const char *string, char **endp, int base) #endif /* SDL_HAS_64BIT_TYPE */ #ifndef HAVE_STRTOD -double SDL_strtod(const char *string, char **endp) +double +SDL_strtod(const char *string, char **endp) { size_t len; double value; len = SDL_ScanFloat(string, &value); - if ( endp ) { - *endp = (char *)string + len; + if (endp) { + *endp = (char *) string + len; } return value; } #endif #ifndef HAVE_STRCMP -int SDL_strcmp(const char *str1, const char *str2) +int +SDL_strcmp(const char *str1, const char *str2) { while (*str1 && *str2) { - if ( *str1 != *str2 ) + if (*str1 != *str2) break; ++str1; ++str2; } - return (int)((unsigned char)*str1 - (unsigned char)*str2); + return (int) ((unsigned char) *str1 - (unsigned char) *str2); } #endif #ifndef HAVE_STRNCMP -int SDL_strncmp(const char *str1, const char *str2, size_t maxlen) +int +SDL_strncmp(const char *str1, const char *str2, size_t maxlen) { - while ( *str1 && *str2 && maxlen ) { - if ( *str1 != *str2 ) + while (*str1 && *str2 && maxlen) { + if (*str1 != *str2) break; ++str1; ++str2; --maxlen; } - if ( ! maxlen ) { + if (!maxlen) { return 0; } - return (int)((unsigned char)*str1 - (unsigned char)*str2); + return (int) ((unsigned char) *str1 - (unsigned char) *str2); } #endif #if !defined(HAVE_STRCASECMP) && !defined(HAVE__STRICMP) -int SDL_strcasecmp(const char *str1, const char *str2) +int +SDL_strcasecmp(const char *str1, const char *str2) { char a = 0; char b = 0; - while ( *str1 && *str2 ) { + while (*str1 && *str2) { a = SDL_tolower(*str1); b = SDL_tolower(*str2); - if ( a != b ) + if (a != b) break; ++str1; ++str2; } - return (int)((unsigned char)a - (unsigned char)b); + return (int) ((unsigned char) a - (unsigned char) b); } #endif #if !defined(HAVE_STRNCASECMP) && !defined(HAVE__STRNICMP) -int SDL_strncasecmp(const char *str1, const char *str2, size_t maxlen) +int +SDL_strncasecmp(const char *str1, const char *str2, size_t maxlen) { char a = 0; char b = 0; - while ( *str1 && *str2 && maxlen ) { + while (*str1 && *str2 && maxlen) { a = SDL_tolower(*str1); b = SDL_tolower(*str2); - if ( a != b ) + if (a != b) break; ++str1; ++str2; --maxlen; } - return (int)((unsigned char)a - (unsigned char)b); + return (int) ((unsigned char) a - (unsigned char) b); } #endif #ifndef HAVE_SSCANF -int SDL_sscanf(const char *text, const char *fmt, ...) +int +SDL_sscanf(const char *text, const char *fmt, ...) { va_list ap; int retval = 0; va_start(ap, fmt); - while ( *fmt ) { - if ( *fmt == ' ' ) { - while ( SDL_isspace(*text) ) { + while (*fmt) { + if (*fmt == ' ') { + while (SDL_isspace(*text)) { ++text; } ++fmt; continue; } - if ( *fmt == '%' ) { + if (*fmt == '%') { SDL_bool done = SDL_FALSE; long count = 0; int radix = 10; - enum { + enum + { DO_SHORT, DO_INT, DO_LONG, @@ -756,31 +791,31 @@ int SDL_sscanf(const char *text, const char *fmt, ...) SDL_bool suppress = SDL_FALSE; ++fmt; - if ( *fmt == '%' ) { - if ( *text == '%' ) { + if (*fmt == '%') { + if (*text == '%') { ++text; ++fmt; continue; } break; } - if ( *fmt == '*' ) { + if (*fmt == '*') { suppress = SDL_TRUE; ++fmt; } fmt += SDL_ScanLong(fmt, 10, &count); - if ( *fmt == 'c' ) { - if ( ! count ) { + if (*fmt == 'c') { + if (!count) { count = 1; } - if ( suppress ) { - while ( count-- ) { + if (suppress) { + while (count--) { ++text; } } else { - char *valuep = va_arg(ap, char*); - while ( count-- ) { + char *valuep = va_arg(ap, char *); + while (count--) { *valuep++ = *text++; } ++retval; @@ -788,200 +823,204 @@ int SDL_sscanf(const char *text, const char *fmt, ...) continue; } - while ( SDL_isspace(*text) ) { + while (SDL_isspace(*text)) { ++text; } /* FIXME: implement more of the format specifiers */ while (!done) { - switch(*fmt) { - case '*': - suppress = SDL_TRUE; - break; - case 'h': - if ( inttype > DO_SHORT ) { - ++inttype; - } - break; - case 'l': - if ( inttype < DO_LONGLONG ) { - ++inttype; - } - break; - case 'I': - if ( SDL_strncmp(fmt, "I64", 3) == 0 ) { - fmt += 2; - inttype = DO_LONGLONG; + switch (*fmt) { + case '*': + suppress = SDL_TRUE; + break; + case 'h': + if (inttype > DO_SHORT) { + ++inttype; + } + break; + case 'l': + if (inttype < DO_LONGLONG) { + ++inttype; + } + break; + case 'I': + if (SDL_strncmp(fmt, "I64", 3) == 0) { + fmt += 2; + inttype = DO_LONGLONG; + } + break; + case 'i': + { + int index = 0; + if (text[index] == '-') { + ++index; } - break; - case 'i': - { - int index = 0; - if ( text[index] == '-' ) { - ++index; - } - if ( text[index] == '0' ) { - if ( SDL_tolower(text[index+1]) == 'x' ) { - radix = 16; - } else { - radix = 8; - } + if (text[index] == '0') { + if (SDL_tolower(text[index + 1]) == 'x') { + radix = 16; + } else { + radix = 8; } } - /* Fall through to %d handling */ - case 'd': + } + /* Fall through to %d handling */ + case 'd': #ifdef SDL_HAS_64BIT_TYPE - if ( inttype == DO_LONGLONG ) { - Sint64 value; - text += SDL_ScanLongLong(text, radix, &value); - if ( ! suppress ) { - Sint64 *valuep = va_arg(ap, Sint64*); - *valuep = value; - ++retval; - } + if (inttype == DO_LONGLONG) { + Sint64 value; + text += SDL_ScanLongLong(text, radix, &value); + if (!suppress) { + Sint64 *valuep = va_arg(ap, Sint64 *); + *valuep = value; + ++retval; } - else + } else #endif /* SDL_HAS_64BIT_TYPE */ - { - long value; - text += SDL_ScanLong(text, radix, &value); - if ( ! suppress ) { - switch (inttype) { - case DO_SHORT: - { short* valuep = va_arg(ap, short*); - *valuep = (short)value; - } - break; - case DO_INT: - { int* valuep = va_arg(ap, int*); - *valuep = (int)value; - } - break; - case DO_LONG: - { long* valuep = va_arg(ap, long*); - *valuep = value; - } - break; - case DO_LONGLONG: - /* Handled above */ - break; + { + long value; + text += SDL_ScanLong(text, radix, &value); + if (!suppress) { + switch (inttype) { + case DO_SHORT: + { + short *valuep = va_arg(ap, short *); + *valuep = (short) value; + } + break; + case DO_INT: + { + int *valuep = va_arg(ap, int *); + *valuep = (int) value; } - ++retval; + break; + case DO_LONG: + { + long *valuep = va_arg(ap, long *); + *valuep = value; + } + break; + case DO_LONGLONG: + /* Handled above */ + break; } + ++retval; } - done = SDL_TRUE; - break; - case 'o': - if ( radix == 10 ) { - radix = 8; - } - /* Fall through to unsigned handling */ - case 'x': - case 'X': - if ( radix == 10 ) { - radix = 16; - } - /* Fall through to unsigned handling */ - case 'u': + } + done = SDL_TRUE; + break; + case 'o': + if (radix == 10) { + radix = 8; + } + /* Fall through to unsigned handling */ + case 'x': + case 'X': + if (radix == 10) { + radix = 16; + } + /* Fall through to unsigned handling */ + case 'u': #ifdef SDL_HAS_64BIT_TYPE - if ( inttype == DO_LONGLONG ) { - Uint64 value; - text += SDL_ScanUnsignedLongLong(text, radix, &value); - if ( ! suppress ) { - Uint64 *valuep = va_arg(ap, Uint64*); - *valuep = value; - ++retval; - } + if (inttype == DO_LONGLONG) { + Uint64 value; + text += SDL_ScanUnsignedLongLong(text, radix, &value); + if (!suppress) { + Uint64 *valuep = va_arg(ap, Uint64 *); + *valuep = value; + ++retval; } - else + } else #endif /* SDL_HAS_64BIT_TYPE */ - { - unsigned long value; - text += SDL_ScanUnsignedLong(text, radix, &value); - if ( ! suppress ) { - switch (inttype) { - case DO_SHORT: - { short* valuep = va_arg(ap, short*); - *valuep = (short)value; - } - break; - case DO_INT: - { int* valuep = va_arg(ap, int*); - *valuep = (int)value; - } - break; - case DO_LONG: - { long* valuep = va_arg(ap, long*); - *valuep = value; - } - break; - case DO_LONGLONG: - /* Handled above */ - break; + { + unsigned long value; + text += SDL_ScanUnsignedLong(text, radix, &value); + if (!suppress) { + switch (inttype) { + case DO_SHORT: + { + short *valuep = va_arg(ap, short *); + *valuep = (short) value; + } + break; + case DO_INT: + { + int *valuep = va_arg(ap, int *); + *valuep = (int) value; } - ++retval; + break; + case DO_LONG: + { + long *valuep = va_arg(ap, long *); + *valuep = value; + } + break; + case DO_LONGLONG: + /* Handled above */ + break; } + ++retval; } - done = SDL_TRUE; - break; - case 'p': - { - uintptr_t value; - text += SDL_ScanUintPtrT(text, 16, &value); - if ( ! suppress ) { - void** valuep = va_arg(ap, void**); - *valuep = (void*)value; - ++retval; - } + } + done = SDL_TRUE; + break; + case 'p': + { + uintptr_t value; + text += SDL_ScanUintPtrT(text, 16, &value); + if (!suppress) { + void **valuep = va_arg(ap, void **); + *valuep = (void *) value; + ++retval; } - done = SDL_TRUE; - break; - case 'f': - { - double value; - text += SDL_ScanFloat(text, &value); - if ( ! suppress ) { - float* valuep = va_arg(ap, float*); - *valuep = (float)value; - ++retval; - } + } + done = SDL_TRUE; + break; + case 'f': + { + double value; + text += SDL_ScanFloat(text, &value); + if (!suppress) { + float *valuep = va_arg(ap, float *); + *valuep = (float) value; + ++retval; } - done = SDL_TRUE; - break; - case 's': - if ( suppress ) { - while ( !SDL_isspace(*text) ) { - ++text; - if ( count ) { - if ( --count == 0 ) { - break; - } + } + done = SDL_TRUE; + break; + case 's': + if (suppress) { + while (!SDL_isspace(*text)) { + ++text; + if (count) { + if (--count == 0) { + break; } } - } else { - char *valuep = va_arg(ap, char*); - while ( !SDL_isspace(*text) ) { - *valuep++ = *text++; - if ( count ) { - if ( --count == 0 ) { - break; - } + } + } else { + char *valuep = va_arg(ap, char *); + while (!SDL_isspace(*text)) { + *valuep++ = *text++; + if (count) { + if (--count == 0) { + break; } } - *valuep = '\0'; - ++retval; } - done = SDL_TRUE; - break; - default: - done = SDL_TRUE; - break; + *valuep = '\0'; + ++retval; + } + done = SDL_TRUE; + break; + default: + done = SDL_TRUE; + break; } ++fmt; } continue; } - if ( *text == *fmt ) { + if (*text == *fmt) { ++text; ++fmt; continue; @@ -996,7 +1035,8 @@ int SDL_sscanf(const char *text, const char *fmt, ...) #endif #ifndef HAVE_SNPRINTF -int SDL_snprintf(char *text, size_t maxlen, const char *fmt, ...) +int +SDL_snprintf(char *text, size_t maxlen, const char *fmt, ...) { va_list ap; int retval; @@ -1010,92 +1050,101 @@ int SDL_snprintf(char *text, size_t maxlen, const char *fmt, ...) #endif #ifndef HAVE_VSNPRINTF -static size_t SDL_PrintLong(char *text, long value, int radix, size_t maxlen) +static size_t +SDL_PrintLong(char *text, long value, int radix, size_t maxlen) { char num[130]; size_t size; SDL_ltoa(value, num, radix); size = SDL_strlen(num); - if ( size >= maxlen ) { - size = maxlen-1; + if (size >= maxlen) { + size = maxlen - 1; } - SDL_strlcpy(text, num, size+1); + SDL_strlcpy(text, num, size + 1); return size; } -static size_t SDL_PrintUnsignedLong(char *text, unsigned long value, int radix, size_t maxlen) + +static size_t +SDL_PrintUnsignedLong(char *text, unsigned long value, int radix, + size_t maxlen) { char num[130]; size_t size; SDL_ultoa(value, num, radix); size = SDL_strlen(num); - if ( size >= maxlen ) { - size = maxlen-1; + if (size >= maxlen) { + size = maxlen - 1; } - SDL_strlcpy(text, num, size+1); + SDL_strlcpy(text, num, size + 1); return size; } + #ifdef SDL_HAS_64BIT_TYPE -static size_t SDL_PrintLongLong(char *text, Sint64 value, int radix, size_t maxlen) +static size_t +SDL_PrintLongLong(char *text, Sint64 value, int radix, size_t maxlen) { char num[130]; size_t size; SDL_lltoa(value, num, radix); size = SDL_strlen(num); - if ( size >= maxlen ) { - size = maxlen-1; + if (size >= maxlen) { + size = maxlen - 1; } - SDL_strlcpy(text, num, size+1); + SDL_strlcpy(text, num, size + 1); return size; } -static size_t SDL_PrintUnsignedLongLong(char *text, Uint64 value, int radix, size_t maxlen) + +static size_t +SDL_PrintUnsignedLongLong(char *text, Uint64 value, int radix, size_t maxlen) { char num[130]; size_t size; SDL_ulltoa(value, num, radix); size = SDL_strlen(num); - if ( size >= maxlen ) { - size = maxlen-1; + if (size >= maxlen) { + size = maxlen - 1; } - SDL_strlcpy(text, num, size+1); + SDL_strlcpy(text, num, size + 1); return size; } #endif /* SDL_HAS_64BIT_TYPE */ -static size_t SDL_PrintFloat(char *text, double arg, size_t maxlen) +static size_t +SDL_PrintFloat(char *text, double arg, size_t maxlen) { char *textstart = text; - if ( arg ) { + if (arg) { /* This isn't especially accurate, but hey, it's easy. :) */ const double precision = 0.00000001; size_t len; unsigned long value; - if ( arg < 0 ) { + if (arg < 0) { *text++ = '-'; --maxlen; arg = -arg; } - value = (unsigned long)arg; + value = (unsigned long) arg; len = SDL_PrintUnsignedLong(text, value, 10, maxlen); text += len; maxlen -= len; arg -= value; - if ( arg > precision && maxlen ) { + if (arg > precision && maxlen) { int mult = 10; *text++ = '.'; - while ( (arg > precision) && maxlen ) { - value = (unsigned long)(arg * mult); + while ((arg > precision) && maxlen) { + value = (unsigned long) (arg * mult); len = SDL_PrintUnsignedLong(text, value, 10, maxlen); text += len; maxlen -= len; - arg -= (double)value / mult; + arg -= (double) value / mult; mult *= 10; } } @@ -1104,28 +1153,33 @@ static size_t SDL_PrintFloat(char *text, double arg, size_t maxlen) } return (text - textstart); } -static size_t SDL_PrintString(char *text, const char *string, size_t maxlen) + +static size_t +SDL_PrintString(char *text, const char *string, size_t maxlen) { char *textstart = text; - while ( *string && maxlen-- ) { + while (*string && maxlen--) { *text++ = *string++; } return (text - textstart); } -int SDL_vsnprintf(char *text, size_t maxlen, const char *fmt, va_list ap) + +int +SDL_vsnprintf(char *text, size_t maxlen, const char *fmt, va_list ap) { char *textstart = text; - if ( maxlen <= 0 ) { + if (maxlen <= 0) { return 0; } - --maxlen; /* For the trailing '\0' */ - while ( *fmt && maxlen ) { - if ( *fmt == '%' ) { + --maxlen; /* For the trailing '\0' */ + while (*fmt && maxlen) { + if (*fmt == '%') { SDL_bool done = SDL_FALSE; size_t len = 0; SDL_bool do_lowercase = SDL_FALSE; int radix = 10; - enum { + enum + { DO_INT, DO_LONG, DO_LONGLONG @@ -1133,104 +1187,132 @@ int SDL_vsnprintf(char *text, size_t maxlen, const char *fmt, va_list ap) ++fmt; /* FIXME: implement more of the format specifiers */ - while ( *fmt == '.' || (*fmt >= '0' && *fmt <= '9') ) { + while (*fmt == '.' || (*fmt >= '0' && *fmt <= '9')) { ++fmt; } while (!done) { - switch(*fmt) { - case '%': - *text = '%'; - len = 1; - done = SDL_TRUE; - break; - case 'c': - /* char is promoted to int when passed through (...) */ - *text = (char)va_arg(ap, int); - len = 1; - done = SDL_TRUE; - break; - case 'h': - /* short is promoted to int when passed through (...) */ - break; - case 'l': - if ( inttype < DO_LONGLONG ) { - ++inttype; - } + switch (*fmt) { + case '%': + *text = '%'; + len = 1; + done = SDL_TRUE; + break; + case 'c': + /* char is promoted to int when passed through (...) */ + *text = (char) va_arg(ap, int); + len = 1; + done = SDL_TRUE; + break; + case 'h': + /* short is promoted to int when passed through (...) */ + break; + case 'l': + if (inttype < DO_LONGLONG) { + ++inttype; + } + break; + case 'I': + if (SDL_strncmp(fmt, "I64", 3) == 0) { + fmt += 2; + inttype = DO_LONGLONG; + } + break; + case 'i': + case 'd': + switch (inttype) { + case DO_INT: + len = + SDL_PrintLong(text, + (long) va_arg(ap, int), + radix, maxlen); break; - case 'I': - if ( SDL_strncmp(fmt, "I64", 3) == 0 ) { - fmt += 2; - inttype = DO_LONGLONG; - } + case DO_LONG: + len = + SDL_PrintLong(text, va_arg(ap, long), + radix, maxlen); break; - case 'i': - case 'd': - switch (inttype) { - case DO_INT: - len = SDL_PrintLong(text, (long)va_arg(ap, int), radix, maxlen); - break; - case DO_LONG: - len = SDL_PrintLong(text, va_arg(ap, long), radix, maxlen); - break; - case DO_LONGLONG: + case DO_LONGLONG: #ifdef SDL_HAS_64BIT_TYPE - len = SDL_PrintLongLong(text, va_arg(ap, Sint64), radix, maxlen); + len = + SDL_PrintLongLong(text, + va_arg(ap, Sint64), + radix, maxlen); #else - len = SDL_PrintLong(text, va_arg(ap, long), radix, maxlen); + len = + SDL_PrintLong(text, va_arg(ap, long), + radix, maxlen); #endif - break; - } - done = SDL_TRUE; break; - case 'p': - case 'x': - do_lowercase = SDL_TRUE; - /* Fall through to 'X' handling */ - case 'X': - if ( radix == 10 ) { - radix = 16; - } - if ( *fmt == 'p' ) { - inttype = DO_LONG; - } - /* Fall through to unsigned handling */ - case 'o': - if ( radix == 10 ) { - radix = 8; - } - /* Fall through to unsigned handling */ - case 'u': - switch (inttype) { - case DO_INT: - len = SDL_PrintUnsignedLong(text, (unsigned long)va_arg(ap, unsigned int), radix, maxlen); - break; - case DO_LONG: - len = SDL_PrintUnsignedLong(text, va_arg(ap, unsigned long), radix, maxlen); - break; - case DO_LONGLONG: + } + done = SDL_TRUE; + break; + case 'p': + case 'x': + do_lowercase = SDL_TRUE; + /* Fall through to 'X' handling */ + case 'X': + if (radix == 10) { + radix = 16; + } + if (*fmt == 'p') { + inttype = DO_LONG; + } + /* Fall through to unsigned handling */ + case 'o': + if (radix == 10) { + radix = 8; + } + /* Fall through to unsigned handling */ + case 'u': + switch (inttype) { + case DO_INT: + len = SDL_PrintUnsignedLong(text, (unsigned long) + va_arg(ap, + unsigned + int), + radix, maxlen); + break; + case DO_LONG: + len = + SDL_PrintUnsignedLong(text, + va_arg(ap, + unsigned + long), + radix, maxlen); + break; + case DO_LONGLONG: #ifdef SDL_HAS_64BIT_TYPE - len = SDL_PrintUnsignedLongLong(text, va_arg(ap, Uint64), radix, maxlen); + len = + SDL_PrintUnsignedLongLong(text, + va_arg(ap, + Uint64), + radix, maxlen); #else - len = SDL_PrintUnsignedLong(text, va_arg(ap, unsigned long), radix, maxlen); + len = + SDL_PrintUnsignedLong(text, + va_arg(ap, + unsigned + long), + radix, maxlen); #endif - break; - } - if ( do_lowercase ) { - SDL_strlwr(text); - } - done = SDL_TRUE; - break; - case 'f': - len = SDL_PrintFloat(text, va_arg(ap, double), maxlen); - done = SDL_TRUE; - break; - case 's': - len = SDL_PrintString(text, va_arg(ap, char*), maxlen); - done = SDL_TRUE; - break; - default: - done = SDL_TRUE; break; + } + if (do_lowercase) { + SDL_strlwr(text); + } + done = SDL_TRUE; + break; + case 'f': + len = SDL_PrintFloat(text, va_arg(ap, double), maxlen); + done = SDL_TRUE; + break; + case 's': + len = SDL_PrintString(text, va_arg(ap, char *), maxlen); + done = SDL_TRUE; + break; + default: + done = SDL_TRUE; + break; } ++fmt; } @@ -1246,3 +1328,4 @@ int SDL_vsnprintf(char *text, size_t maxlen, const char *fmt, va_list ap) return (text - textstart); } #endif +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/thread/SDL_systhread.h b/src/thread/SDL_systhread.h index ab9545c54..32c545ceb 100644 --- a/src/thread/SDL_systhread.h +++ b/src/thread/SDL_systhread.h @@ -33,9 +33,11 @@ on success. */ #ifdef SDL_PASSED_BEGINTHREAD_ENDTHREAD -extern int SDL_SYS_CreateThread(SDL_Thread *thread, void *args, pfnSDL_CurrentBeginThread pfnBeginThread, pfnSDL_CurrentEndThread pfnEndThread); +extern int SDL_SYS_CreateThread(SDL_Thread * thread, void *args, + pfnSDL_CurrentBeginThread pfnBeginThread, + pfnSDL_CurrentEndThread pfnEndThread); #else -extern int SDL_SYS_CreateThread(SDL_Thread *thread, void *args); +extern int SDL_SYS_CreateThread(SDL_Thread * thread, void *args); #endif /* This function does any necessary setup in the child thread */ @@ -44,9 +46,10 @@ extern void SDL_SYS_SetupThread(void); /* This function waits for the thread to finish and frees any data allocated by SDL_SYS_CreateThread() */ -extern void SDL_SYS_WaitThread(SDL_Thread *thread); +extern void SDL_SYS_WaitThread(SDL_Thread * thread); /* This function kills the thread and returns */ -extern void SDL_SYS_KillThread(SDL_Thread *thread); +extern void SDL_SYS_KillThread(SDL_Thread * thread); #endif /* _SDL_systhread_h */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/thread/SDL_thread.c b/src/thread/SDL_thread.c index 09b07bb8f..2c889c429 100644 --- a/src/thread/SDL_thread.c +++ b/src/thread/SDL_thread.c @@ -38,16 +38,17 @@ static int SDL_numthreads = 0; static SDL_Thread **SDL_Threads = NULL; static SDL_mutex *thread_lock = NULL; -int SDL_ThreadsInit(void) +int +SDL_ThreadsInit(void) { - int retval; - - retval = 0; - thread_lock = SDL_CreateMutex(); - if ( thread_lock == NULL ) { - retval = -1; - } - return(retval); + int retval; + + retval = 0; + thread_lock = SDL_CreateMutex(); + if (thread_lock == NULL) { + retval = -1; + } + return (retval); } /* This should never be called... @@ -55,244 +56,260 @@ int SDL_ThreadsInit(void) clean up threads here. If any threads are still running after this call, they will no longer have access to any per-thread data. */ -void SDL_ThreadsQuit(void) +void +SDL_ThreadsQuit(void) { - SDL_mutex *mutex; + SDL_mutex *mutex; - mutex = thread_lock; - thread_lock = NULL; - if ( mutex != NULL ) { - SDL_DestroyMutex(mutex); - } + mutex = thread_lock; + thread_lock = NULL; + if (mutex != NULL) { + SDL_DestroyMutex(mutex); + } } /* Routines for manipulating the thread list */ -static void SDL_AddThread(SDL_Thread *thread) +static void +SDL_AddThread(SDL_Thread * thread) { - /* WARNING: - If the very first threads are created simultaneously, then - there could be a race condition causing memory corruption. - In practice, this isn't a problem because by definition there - is only one thread running the first time this is called. - */ - if ( !thread_lock ) { - if ( SDL_ThreadsInit() < 0 ) { - return; - } - } - SDL_mutexP(thread_lock); - - /* Expand the list of threads, if necessary */ + /* WARNING: + If the very first threads are created simultaneously, then + there could be a race condition causing memory corruption. + In practice, this isn't a problem because by definition there + is only one thread running the first time this is called. + */ + if (!thread_lock) { + if (SDL_ThreadsInit() < 0) { + return; + } + } + SDL_mutexP(thread_lock); + + /* Expand the list of threads, if necessary */ #ifdef DEBUG_THREADS - printf("Adding thread (%d already - %d max)\n", - SDL_numthreads, SDL_maxthreads); + printf("Adding thread (%d already - %d max)\n", + SDL_numthreads, SDL_maxthreads); #endif - if ( SDL_numthreads == SDL_maxthreads ) { - SDL_Thread **threads; - threads = (SDL_Thread **)SDL_realloc(SDL_Threads, - (SDL_maxthreads+ARRAY_CHUNKSIZE)*(sizeof *threads)); - if ( threads == NULL ) { - SDL_OutOfMemory(); - goto done; - } - SDL_maxthreads += ARRAY_CHUNKSIZE; - SDL_Threads = threads; - } - SDL_Threads[SDL_numthreads++] = thread; -done: - SDL_mutexV(thread_lock); + if (SDL_numthreads == SDL_maxthreads) { + SDL_Thread **threads; + threads = (SDL_Thread **) SDL_realloc(SDL_Threads, + (SDL_maxthreads + + ARRAY_CHUNKSIZE) * + (sizeof *threads)); + if (threads == NULL) { + SDL_OutOfMemory(); + goto done; + } + SDL_maxthreads += ARRAY_CHUNKSIZE; + SDL_Threads = threads; + } + SDL_Threads[SDL_numthreads++] = thread; + done: + SDL_mutexV(thread_lock); } -static void SDL_DelThread(SDL_Thread *thread) +static void +SDL_DelThread(SDL_Thread * thread) { - int i; - - if ( !thread_lock ) { - return; - } - SDL_mutexP(thread_lock); - for ( i=0; i 0 ) { - while ( i < SDL_numthreads ) { - SDL_Threads[i] = SDL_Threads[i+1]; - ++i; - } - } else { - SDL_maxthreads = 0; - SDL_free(SDL_Threads); - SDL_Threads = NULL; - } + int i; + + if (!thread_lock) { + return; + } + SDL_mutexP(thread_lock); + for (i = 0; i < SDL_numthreads; ++i) { + if (thread == SDL_Threads[i]) { + break; + } + } + if (i < SDL_numthreads) { + if (--SDL_numthreads > 0) { + while (i < SDL_numthreads) { + SDL_Threads[i] = SDL_Threads[i + 1]; + ++i; + } + } else { + SDL_maxthreads = 0; + SDL_free(SDL_Threads); + SDL_Threads = NULL; + } #ifdef DEBUG_THREADS - printf("Deleting thread (%d left - %d max)\n", - SDL_numthreads, SDL_maxthreads); + printf("Deleting thread (%d left - %d max)\n", + SDL_numthreads, SDL_maxthreads); #endif - } - SDL_mutexV(thread_lock); + } + SDL_mutexV(thread_lock); - if ( SDL_Threads == NULL ) { - SDL_ThreadsQuit(); - } + if (SDL_Threads == NULL) { + SDL_ThreadsQuit(); + } } /* The default (non-thread-safe) global error variable */ static SDL_error SDL_global_error; /* Routine to get the thread-specific error variable */ -SDL_error *SDL_GetErrBuf(void) +SDL_error * +SDL_GetErrBuf(void) { - SDL_error *errbuf; - - errbuf = &SDL_global_error; - if ( SDL_Threads ) { - int i; - Uint32 this_thread; - - this_thread = SDL_ThreadID(); - SDL_mutexP(thread_lock); - for ( i=0; ithreadid ) { - errbuf = &SDL_Threads[i]->errbuf; - break; - } - } - SDL_mutexV(thread_lock); - } - return(errbuf); + SDL_error *errbuf; + + errbuf = &SDL_global_error; + if (SDL_Threads) { + int i; + Uint32 this_thread; + + this_thread = SDL_ThreadID(); + SDL_mutexP(thread_lock); + for (i = 0; i < SDL_numthreads; ++i) { + if (this_thread == SDL_Threads[i]->threadid) { + errbuf = &SDL_Threads[i]->errbuf; + break; + } + } + SDL_mutexV(thread_lock); + } + return (errbuf); } /* Arguments and callback to setup and run the user thread function */ -typedef struct { - int (SDLCALL *func)(void *); - void *data; - SDL_Thread *info; - SDL_sem *wait; +typedef struct +{ + int (SDLCALL * func) (void *); + void *data; + SDL_Thread *info; + SDL_sem *wait; } thread_args; -void SDL_RunThread(void *data) +void +SDL_RunThread(void *data) { - thread_args *args; - int (SDLCALL *userfunc)(void *); - void *userdata; - int *statusloc; - - /* Perform any system-dependent setup - - this function cannot fail, and cannot use SDL_SetError() - */ - SDL_SYS_SetupThread(); - - /* Get the thread id */ - args = (thread_args *)data; - args->info->threadid = SDL_ThreadID(); - - /* Figure out what function to run */ - userfunc = args->func; - userdata = args->data; - statusloc = &args->info->status; - - /* Wake up the parent thread */ - SDL_SemPost(args->wait); - - /* Run the function */ - *statusloc = userfunc(userdata); + thread_args *args; + int (SDLCALL * userfunc) (void *); + void *userdata; + int *statusloc; + + /* Perform any system-dependent setup + - this function cannot fail, and cannot use SDL_SetError() + */ + SDL_SYS_SetupThread(); + + /* Get the thread id */ + args = (thread_args *) data; + args->info->threadid = SDL_ThreadID(); + + /* Figure out what function to run */ + userfunc = args->func; + userdata = args->data; + statusloc = &args->info->status; + + /* Wake up the parent thread */ + SDL_SemPost(args->wait); + + /* Run the function */ + *statusloc = userfunc(userdata); } #ifdef SDL_PASSED_BEGINTHREAD_ENDTHREAD #undef SDL_CreateThread -DECLSPEC SDL_Thread * SDLCALL SDL_CreateThread(int (SDLCALL *fn)(void *), void *data, pfnSDL_CurrentBeginThread pfnBeginThread, pfnSDL_CurrentEndThread pfnEndThread) +DECLSPEC SDL_Thread *SDLCALL +SDL_CreateThread(int (SDLCALL * fn) (void *), void *data, + pfnSDL_CurrentBeginThread pfnBeginThread, + pfnSDL_CurrentEndThread pfnEndThread) #else -DECLSPEC SDL_Thread * SDLCALL SDL_CreateThread(int (SDLCALL *fn)(void *), void *data) +DECLSPEC SDL_Thread *SDLCALL +SDL_CreateThread(int (SDLCALL * fn) (void *), void *data) #endif { - SDL_Thread *thread; - thread_args *args; - int ret; - - /* Allocate memory for the thread info structure */ - thread = (SDL_Thread *)SDL_malloc(sizeof(*thread)); - if ( thread == NULL ) { - SDL_OutOfMemory(); - return(NULL); - } - SDL_memset(thread, 0, (sizeof *thread)); - thread->status = -1; - - /* Set up the arguments for the thread */ - args = (thread_args *)SDL_malloc(sizeof(*args)); - if ( args == NULL ) { - SDL_OutOfMemory(); - SDL_free(thread); - return(NULL); - } - args->func = fn; - args->data = data; - args->info = thread; - args->wait = SDL_CreateSemaphore(0); - if ( args->wait == NULL ) { - SDL_free(thread); - SDL_free(args); - return(NULL); - } - - /* Add the thread to the list of available threads */ - SDL_AddThread(thread); - - /* Create the thread and go! */ + SDL_Thread *thread; + thread_args *args; + int ret; + + /* Allocate memory for the thread info structure */ + thread = (SDL_Thread *) SDL_malloc(sizeof(*thread)); + if (thread == NULL) { + SDL_OutOfMemory(); + return (NULL); + } + SDL_memset(thread, 0, (sizeof *thread)); + thread->status = -1; + + /* Set up the arguments for the thread */ + args = (thread_args *) SDL_malloc(sizeof(*args)); + if (args == NULL) { + SDL_OutOfMemory(); + SDL_free(thread); + return (NULL); + } + args->func = fn; + args->data = data; + args->info = thread; + args->wait = SDL_CreateSemaphore(0); + if (args->wait == NULL) { + SDL_free(thread); + SDL_free(args); + return (NULL); + } + + /* Add the thread to the list of available threads */ + SDL_AddThread(thread); + + /* Create the thread and go! */ #ifdef SDL_PASSED_BEGINTHREAD_ENDTHREAD - ret = SDL_SYS_CreateThread(thread, args, pfnBeginThread, pfnEndThread); + ret = SDL_SYS_CreateThread(thread, args, pfnBeginThread, pfnEndThread); #else - ret = SDL_SYS_CreateThread(thread, args); + ret = SDL_SYS_CreateThread(thread, args); #endif - if ( ret >= 0 ) { - /* Wait for the thread function to use arguments */ - SDL_SemWait(args->wait); - } else { - /* Oops, failed. Gotta free everything */ - SDL_DelThread(thread); - SDL_free(thread); - thread = NULL; - } - SDL_DestroySemaphore(args->wait); - SDL_free(args); - - /* Everything is running now */ - return(thread); + if (ret >= 0) { + /* Wait for the thread function to use arguments */ + SDL_SemWait(args->wait); + } else { + /* Oops, failed. Gotta free everything */ + SDL_DelThread(thread); + SDL_free(thread); + thread = NULL; + } + SDL_DestroySemaphore(args->wait); + SDL_free(args); + + /* Everything is running now */ + return (thread); } -void SDL_WaitThread(SDL_Thread *thread, int *status) +void +SDL_WaitThread(SDL_Thread * thread, int *status) { - if ( thread ) { - SDL_SYS_WaitThread(thread); - if ( status ) { - *status = thread->status; - } - SDL_DelThread(thread); - SDL_free(thread); - } + if (thread) { + SDL_SYS_WaitThread(thread); + if (status) { + *status = thread->status; + } + SDL_DelThread(thread); + SDL_free(thread); + } } -Uint32 SDL_GetThreadID(SDL_Thread *thread) +Uint32 +SDL_GetThreadID(SDL_Thread * thread) { - Uint32 id; - - if ( thread ) { - id = thread->threadid; - } else { - id = SDL_ThreadID(); - } - return(id); + Uint32 id; + + if (thread) { + id = thread->threadid; + } else { + id = SDL_ThreadID(); + } + return (id); } -void SDL_KillThread(SDL_Thread *thread) +void +SDL_KillThread(SDL_Thread * thread) { - if ( thread ) { - SDL_SYS_KillThread(thread); - SDL_WaitThread(thread, NULL); - } + if (thread) { + SDL_SYS_KillThread(thread); + SDL_WaitThread(thread, NULL); + } } +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/thread/SDL_thread_c.h b/src/thread/SDL_thread_c.h index 13501db6d..cf705990f 100644 --- a/src/thread/SDL_thread_c.h +++ b/src/thread/SDL_thread_c.h @@ -52,15 +52,17 @@ #include "../SDL_error_c.h" /* This is the system-independent thread info structure */ -struct SDL_Thread { - Uint32 threadid; - SYS_ThreadHandle handle; - int status; - SDL_error errbuf; - void *data; +struct SDL_Thread +{ + Uint32 threadid; + SYS_ThreadHandle handle; + int status; + SDL_error errbuf; + void *data; }; /* This is the function called to run a thread */ extern void SDL_RunThread(void *data); #endif /* _SDL_thread_c_h */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/thread/amigaos/SDL_syssem.c b/src/thread/amigaos/SDL_syssem.c index a31a2133b..3c479bf11 100644 --- a/src/thread/amigaos/SDL_syssem.c +++ b/src/thread/amigaos/SDL_syssem.c @@ -29,120 +29,126 @@ struct SDL_semaphore { - struct SignalSemaphore Sem; + struct SignalSemaphore Sem; }; #undef D #define D(x) -SDL_sem *SDL_CreateSemaphore(Uint32 initial_value) +SDL_sem * +SDL_CreateSemaphore(Uint32 initial_value) { - SDL_sem *sem; + SDL_sem *sem; - sem = (SDL_sem *)SDL_malloc(sizeof(*sem)); + sem = (SDL_sem *) SDL_malloc(sizeof(*sem)); - if ( ! sem ) { - SDL_OutOfMemory(); - return(0); - } + if (!sem) { + SDL_OutOfMemory(); + return (0); + } - D(bug("Creating semaphore %lx...\n",sem)); + D(bug("Creating semaphore %lx...\n", sem)); - SDL_memset(sem,0,sizeof(*sem)); + SDL_memset(sem, 0, sizeof(*sem)); - InitSemaphore(&sem->Sem); + InitSemaphore(&sem->Sem); - return(sem); + return (sem); } -void SDL_DestroySemaphore(SDL_sem *sem) +void +SDL_DestroySemaphore(SDL_sem * sem) { - D(bug("Destroying semaphore %lx...\n",sem)); + D(bug("Destroying semaphore %lx...\n", sem)); - if ( sem ) { + if (sem) { // Condizioni per liberare i task in attesa? - SDL_free(sem); - } + SDL_free(sem); + } } -int SDL_SemTryWait(SDL_sem *sem) +int +SDL_SemTryWait(SDL_sem * sem) { - if ( ! sem ) { - SDL_SetError("Passed a NULL semaphore"); - return -1; - } + if (!sem) { + SDL_SetError("Passed a NULL semaphore"); + return -1; + } - D(bug("TryWait semaphore...%lx\n",sem)); + D(bug("TryWait semaphore...%lx\n", sem)); - ObtainSemaphore(&sem->Sem); -// ReleaseSemaphore(&sem->Sem); + ObtainSemaphore(&sem->Sem); +// ReleaseSemaphore(&sem->Sem); - return 1; + return 1; } -int SDL_SemWaitTimeout(SDL_sem *sem, Uint32 timeout) +int +SDL_SemWaitTimeout(SDL_sem * sem, Uint32 timeout) { - int retval; - - - if ( ! sem ) { - SDL_SetError("Passed a NULL semaphore"); - return -1; - } - - D(bug("WaitTimeout (%ld) semaphore...%lx\n",timeout,sem)); - - /* A timeout of 0 is an easy case */ - if ( timeout == 0 ) { - ObtainSemaphore(&sem->Sem); - return 1; - } - if(!(retval=AttemptSemaphore(&sem->Sem))) - { - SDL_Delay(timeout); - retval=AttemptSemaphore(&sem->Sem); - } - - if(retval==TRUE) - { -// ReleaseSemaphore(&sem->Sem); - retval=1; - } - - return retval; + int retval; + + + if (!sem) { + SDL_SetError("Passed a NULL semaphore"); + return -1; + } + + D(bug("WaitTimeout (%ld) semaphore...%lx\n", timeout, sem)); + + /* A timeout of 0 is an easy case */ + if (timeout == 0) { + ObtainSemaphore(&sem->Sem); + return 1; + } + if (!(retval = AttemptSemaphore(&sem->Sem))) { + SDL_Delay(timeout); + retval = AttemptSemaphore(&sem->Sem); + } + + if (retval == TRUE) { +// ReleaseSemaphore(&sem->Sem); + retval = 1; + } + + return retval; } -int SDL_SemWait(SDL_sem *sem) +int +SDL_SemWait(SDL_sem * sem) { - ObtainSemaphore(&sem->Sem); - return 0; + ObtainSemaphore(&sem->Sem); + return 0; } -Uint32 SDL_SemValue(SDL_sem *sem) +Uint32 +SDL_SemValue(SDL_sem * sem) { - Uint32 value; - - value = 0; - if ( sem ) { - #ifdef STORMC4_WOS - value = sem->Sem.ssppc_SS.ss_NestCount; - #else - value = sem->Sem.ss_NestCount; - #endif - } - return value; + Uint32 value; + + value = 0; + if (sem) { +#ifdef STORMC4_WOS + value = sem->Sem.ssppc_SS.ss_NestCount; +#else + value = sem->Sem.ss_NestCount; +#endif + } + return value; } -int SDL_SemPost(SDL_sem *sem) +int +SDL_SemPost(SDL_sem * sem) { - if ( ! sem ) { - SDL_SetError("Passed a NULL semaphore"); - return -1; - } - D(bug("SemPost semaphore...%lx\n",sem)); - - ReleaseSemaphore(&sem->Sem); - return 0; + if (!sem) { + SDL_SetError("Passed a NULL semaphore"); + return -1; + } + D(bug("SemPost semaphore...%lx\n", sem)); + + ReleaseSemaphore(&sem->Sem); + return 0; } +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/thread/amigaos/SDL_systhread.c b/src/thread/amigaos/SDL_systhread.c index c6b42e776..71b292e7d 100644 --- a/src/thread/amigaos/SDL_systhread.c +++ b/src/thread/amigaos/SDL_systhread.c @@ -29,123 +29,137 @@ #include "../SDL_systhread.h" #include "mydebug.h" -typedef struct { - int (*func)(void *); - void *data; - SDL_Thread *info; - struct Task *wait; +typedef struct +{ + int (*func) (void *); + void *data; + SDL_Thread *info; + struct Task *wait; } thread_args; #ifndef MORPHOS -#if defined(__SASC) && !defined(__PPC__) -__saveds __asm Uint32 RunThread(register __a0 char *args ) +#if defined(__SASC) && !defined(__PPC__) +__saveds __asm Uint32 +RunThread(register __a0 char *args) #elif defined(__PPC__) -Uint32 RunThread(char *args) +Uint32 +RunThread(char *args) #else -Uint32 __saveds RunThread(char *args __asm("a0") ) +Uint32 __saveds +RunThread(char *args __asm("a0")) #endif { - #ifdef STORMC4_WOS - thread_args *data=(thread_args *)args; - #else - thread_args *data=(thread_args *)atol(args); - #endif +#ifdef STORMC4_WOS + thread_args *data = (thread_args *) args; +#else + thread_args *data = (thread_args *) atol(args); +#endif - struct Task *Father; + struct Task *Father; - D(bug("Received data: %lx\n",data)); - Father=data->wait; + D(bug("Received data: %lx\n", data)); + Father = data->wait; - SDL_RunThread(data); + SDL_RunThread(data); - Signal(Father,SIGBREAKF_CTRL_F); - D(bug("Thread with data %lx ended\n",data)); - return(0); + Signal(Father, SIGBREAKF_CTRL_F); + D(bug("Thread with data %lx ended\n", data)); + return (0); } #else #include -Uint32 RunTheThread(void) +Uint32 +RunTheThread(void) { - thread_args *data=(thread_args *)atol((char *)REG_A0); - struct Task *Father; + thread_args *data = (thread_args *) atol((char *) REG_A0); + struct Task *Father; - D(bug("Received data: %lx\n",data)); - Father=data->wait; + D(bug("Received data: %lx\n", data)); + Father = data->wait; - SDL_RunThread(data); + SDL_RunThread(data); - Signal(Father,SIGBREAKF_CTRL_F); - D(bug("Thread with data %lx ended\n",data)); - return(0); + Signal(Father, SIGBREAKF_CTRL_F); + D(bug("Thread with data %lx ended\n", data)); + return (0); } -struct EmulLibEntry RunThreadStruct= -{ - TRAP_LIB, - 0, - (ULONG)RunTheThread +struct EmulLibEntry RunThreadStruct = { + TRAP_LIB, + 0, + (ULONG) RunTheThread }; -void *RunThread=&RunThreadStruct; +void *RunThread = &RunThreadStruct; #endif -int SDL_SYS_CreateThread(SDL_Thread *thread, void *args) +int +SDL_SYS_CreateThread(SDL_Thread * thread, void *args) { - /* Create the thread and go! */ - char buffer[20]; - - D(bug("Sending %lx to the new thread...\n",args)); - - if(args) - SDL_snprintf(buffer, SDL_arraysize(buffer),"%ld",args); - - #ifdef STORMC4_WOS - thread->handle=CreateTaskPPCTags(TASKATTR_CODE, RunThread, - TASKATTR_NAME, "SDL subtask", - TASKATTR_STACKSIZE, 100000, - (args ? TASKATTR_R3 : TAG_IGNORE), args, - TASKATTR_INHERITR2, TRUE, - TAG_DONE); - #else - thread->handle=(struct Task *)CreateNewProcTags(NP_Output,Output(), - NP_Name,(ULONG)"SDL subtask", - NP_CloseOutput, FALSE, - NP_StackSize,20000, - NP_Entry,(ULONG)RunThread, - args ? NP_Arguments : TAG_IGNORE,(ULONG)buffer, - TAG_DONE); - #endif - - if(!thread->handle) - { - SDL_SetError("Not enough resources to create thread"); - return(-1); - } - - return(0); + /* Create the thread and go! */ + char buffer[20]; + + D(bug("Sending %lx to the new thread...\n", args)); + + if (args) + SDL_snprintf(buffer, SDL_arraysize(buffer), "%ld", args); + +#ifdef STORMC4_WOS + thread->handle = CreateTaskPPCTags(TASKATTR_CODE, RunThread, + TASKATTR_NAME, "SDL subtask", + TASKATTR_STACKSIZE, 100000, + (args ? TASKATTR_R3 : TAG_IGNORE), + args, TASKATTR_INHERITR2, TRUE, + TAG_DONE); +#else + thread->handle = (struct Task *) CreateNewProcTags(NP_Output, Output(), + NP_Name, + (ULONG) "SDL subtask", + NP_CloseOutput, FALSE, + NP_StackSize, 20000, + NP_Entry, + (ULONG) RunThread, + args ? NP_Arguments : + TAG_IGNORE, + (ULONG) buffer, + TAG_DONE); +#endif + + if (!thread->handle) { + SDL_SetError("Not enough resources to create thread"); + return (-1); + } + + return (0); } -void SDL_SYS_SetupThread(void) +void +SDL_SYS_SetupThread(void) { } -Uint32 SDL_ThreadID(void) +Uint32 +SDL_ThreadID(void) { - return((Uint32)FindTask(NULL)); + return ((Uint32) FindTask(NULL)); } -void SDL_SYS_WaitThread(SDL_Thread *thread) +void +SDL_SYS_WaitThread(SDL_Thread * thread) { - SetSignal(0L,SIGBREAKF_CTRL_F|SIGBREAKF_CTRL_C); - Wait(SIGBREAKF_CTRL_F|SIGBREAKF_CTRL_C); + SetSignal(0L, SIGBREAKF_CTRL_F | SIGBREAKF_CTRL_C); + Wait(SIGBREAKF_CTRL_F | SIGBREAKF_CTRL_C); } -void SDL_SYS_KillThread(SDL_Thread *thread) +void +SDL_SYS_KillThread(SDL_Thread * thread) { - Signal((struct Task *)thread->handle,SIGBREAKF_CTRL_C); + Signal((struct Task *) thread->handle, SIGBREAKF_CTRL_C); } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/thread/amigaos/SDL_systhread_c.h b/src/thread/amigaos/SDL_systhread_c.h index 53ba3c8c6..a5b879f03 100644 --- a/src/thread/amigaos/SDL_systhread_c.h +++ b/src/thread/amigaos/SDL_systhread_c.h @@ -57,5 +57,5 @@ extern struct DosLibrary *DOSBase; #else #define SYS_ThreadHandle struct Task * -#endif /*STORMC4_WOS*/ - +#endif /*STORMC4_WOS */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/thread/amigaos/SDL_thread.c b/src/thread/amigaos/SDL_thread.c index 7698f49f3..1ef7eb0e6 100644 --- a/src/thread/amigaos/SDL_thread.c +++ b/src/thread/amigaos/SDL_thread.c @@ -39,11 +39,12 @@ static SDL_Thread **SDL_Threads = NULL; static struct SignalSemaphore thread_lock; int thread_lock_created = 0; -int SDL_ThreadsInit(void) +int +SDL_ThreadsInit(void) { - InitSemaphore(&thread_lock); - thread_lock_created=1; - return 0; + InitSemaphore(&thread_lock); + thread_lock_created = 1; + return 0; } /* This should never be called... @@ -51,228 +52,240 @@ int SDL_ThreadsInit(void) clean up threads here. If any threads are still running after this call, they will no longer have access to any per-thread data. */ -void SDL_ThreadsQuit() +void +SDL_ThreadsQuit() { - thread_lock_created=0; + thread_lock_created = 0; } /* Routines for manipulating the thread list */ -static void SDL_AddThread(SDL_Thread *thread) +static void +SDL_AddThread(SDL_Thread * thread) { - SDL_Thread **threads; - - /* WARNING: - If the very first threads are created simultaneously, then - there could be a race condition causing memory corruption. - In practice, this isn't a problem because by definition there - is only one thread running the first time this is called. - */ - if ( !thread_lock_created ) { - if ( SDL_ThreadsInit() < 0 ) { - return; - } - } - ObtainSemaphore(&thread_lock); - - /* Expand the list of threads, if necessary */ + SDL_Thread **threads; + + /* WARNING: + If the very first threads are created simultaneously, then + there could be a race condition causing memory corruption. + In practice, this isn't a problem because by definition there + is only one thread running the first time this is called. + */ + if (!thread_lock_created) { + if (SDL_ThreadsInit() < 0) { + return; + } + } + ObtainSemaphore(&thread_lock); + + /* Expand the list of threads, if necessary */ #ifdef DEBUG_THREADS - printf("Adding thread (%d already - %d max)\n", - SDL_numthreads, SDL_maxthreads); + printf("Adding thread (%d already - %d max)\n", + SDL_numthreads, SDL_maxthreads); #endif - if ( SDL_numthreads == SDL_maxthreads ) { - threads=(SDL_Thread **)SDL_malloc((SDL_maxthreads+ARRAY_CHUNKSIZE)* - (sizeof *threads)); - if ( threads == NULL ) { - SDL_OutOfMemory(); - goto done; - } - SDL_memcpy(threads, SDL_Threads, SDL_numthreads*(sizeof *threads)); - SDL_maxthreads += ARRAY_CHUNKSIZE; - if ( SDL_Threads ) { - SDL_free(SDL_Threads); - } - SDL_Threads = threads; - } - SDL_Threads[SDL_numthreads++] = thread; -done: - ReleaseSemaphore(&thread_lock); + if (SDL_numthreads == SDL_maxthreads) { + threads = + (SDL_Thread **) SDL_malloc((SDL_maxthreads + ARRAY_CHUNKSIZE) * + (sizeof *threads)); + if (threads == NULL) { + SDL_OutOfMemory(); + goto done; + } + SDL_memcpy(threads, SDL_Threads, SDL_numthreads * (sizeof *threads)); + SDL_maxthreads += ARRAY_CHUNKSIZE; + if (SDL_Threads) { + SDL_free(SDL_Threads); + } + SDL_Threads = threads; + } + SDL_Threads[SDL_numthreads++] = thread; + done: + ReleaseSemaphore(&thread_lock); } -static void SDL_DelThread(SDL_Thread *thread) +static void +SDL_DelThread(SDL_Thread * thread) { - int i; - - if ( thread_lock_created ) { - ObtainSemaphore(&thread_lock); - for ( i=0; ithreadid ) { - errbuf = &SDL_Threads[i]->errbuf; - break; - } - } - ReleaseSemaphore(&thread_lock); - } - return(errbuf); + SDL_error *errbuf; + + errbuf = &SDL_global_error; + if (SDL_Threads) { + int i; + Uint32 this_thread; + + this_thread = SDL_ThreadID(); + ObtainSemaphore(&thread_lock); + for (i = 0; i < SDL_numthreads; ++i) { + if (this_thread == SDL_Threads[i]->threadid) { + errbuf = &SDL_Threads[i]->errbuf; + break; + } + } + ReleaseSemaphore(&thread_lock); + } + return (errbuf); } /* Arguments and callback to setup and run the user thread function */ -typedef struct { - int (*func)(void *); - void *data; - SDL_Thread *info; - struct Task *wait; +typedef struct +{ + int (*func) (void *); + void *data; + SDL_Thread *info; + struct Task *wait; } thread_args; -void SDL_RunThread(void *data) +void +SDL_RunThread(void *data) { - thread_args *args; - int (*userfunc)(void *); - void *userdata; - int *statusloc; - - /* Perform any system-dependent setup - - this function cannot fail, and cannot use SDL_SetError() - */ - SDL_SYS_SetupThread(); - - /* Get the thread id */ - args = (thread_args *)data; - args->info->threadid = SDL_ThreadID(); - - /* Figure out what function to run */ - userfunc = args->func; - userdata = args->data; - statusloc = &args->info->status; - - /* Wake up the parent thread */ - Signal(args->wait,SIGBREAKF_CTRL_E); - - /* Run the function */ - *statusloc = userfunc(userdata); + thread_args *args; + int (*userfunc) (void *); + void *userdata; + int *statusloc; + + /* Perform any system-dependent setup + - this function cannot fail, and cannot use SDL_SetError() + */ + SDL_SYS_SetupThread(); + + /* Get the thread id */ + args = (thread_args *) data; + args->info->threadid = SDL_ThreadID(); + + /* Figure out what function to run */ + userfunc = args->func; + userdata = args->data; + statusloc = &args->info->status; + + /* Wake up the parent thread */ + Signal(args->wait, SIGBREAKF_CTRL_E); + + /* Run the function */ + *statusloc = userfunc(userdata); } -SDL_Thread *SDL_CreateThread(int (*fn)(void *), void *data) +SDL_Thread * +SDL_CreateThread(int (*fn) (void *), void *data) { - SDL_Thread *thread; - thread_args *args; - int ret; - - /* Allocate memory for the thread info structure */ - thread = (SDL_Thread *)SDL_malloc(sizeof(*thread)); - if ( thread == NULL ) { - SDL_OutOfMemory(); - return(NULL); - } - SDL_memset(thread, 0, (sizeof *thread)); - thread->status = -1; - - /* Set up the arguments for the thread */ - args = (thread_args *)SDL_malloc(sizeof(*args)); - if ( args == NULL ) { - SDL_OutOfMemory(); - SDL_free(thread); - return(NULL); - } - args->func = fn; - args->data = data; - args->info = thread; - args->wait = FindTask(NULL); - if ( args->wait == NULL ) { - SDL_free(thread); - SDL_free(args); - SDL_OutOfMemory(); - return(NULL); - } - - /* Add the thread to the list of available threads */ - SDL_AddThread(thread); - - D(bug("Starting thread...\n")); - - /* Create the thread and go! */ - ret = SDL_SYS_CreateThread(thread, args); - if ( ret >= 0 ) { - D(bug("Waiting for thread CTRL_E...\n")); - /* Wait for the thread function to use arguments */ - Wait(SIGBREAKF_CTRL_E); - D(bug(" Arrived.")); - } else { - /* Oops, failed. Gotta free everything */ - SDL_DelThread(thread); - SDL_free(thread); - thread = NULL; - } - SDL_free(args); - - /* Everything is running now */ - return(thread); + SDL_Thread *thread; + thread_args *args; + int ret; + + /* Allocate memory for the thread info structure */ + thread = (SDL_Thread *) SDL_malloc(sizeof(*thread)); + if (thread == NULL) { + SDL_OutOfMemory(); + return (NULL); + } + SDL_memset(thread, 0, (sizeof *thread)); + thread->status = -1; + + /* Set up the arguments for the thread */ + args = (thread_args *) SDL_malloc(sizeof(*args)); + if (args == NULL) { + SDL_OutOfMemory(); + SDL_free(thread); + return (NULL); + } + args->func = fn; + args->data = data; + args->info = thread; + args->wait = FindTask(NULL); + if (args->wait == NULL) { + SDL_free(thread); + SDL_free(args); + SDL_OutOfMemory(); + return (NULL); + } + + /* Add the thread to the list of available threads */ + SDL_AddThread(thread); + + D(bug("Starting thread...\n")); + + /* Create the thread and go! */ + ret = SDL_SYS_CreateThread(thread, args); + if (ret >= 0) { + D(bug("Waiting for thread CTRL_E...\n")); + /* Wait for the thread function to use arguments */ + Wait(SIGBREAKF_CTRL_E); + D(bug(" Arrived.")); + } else { + /* Oops, failed. Gotta free everything */ + SDL_DelThread(thread); + SDL_free(thread); + thread = NULL; + } + SDL_free(args); + + /* Everything is running now */ + return (thread); } -void SDL_WaitThread(SDL_Thread *thread, int *status) +void +SDL_WaitThread(SDL_Thread * thread, int *status) { - if ( thread ) { - SDL_SYS_WaitThread(thread); - if ( status ) { - *status = thread->status; - } - SDL_DelThread(thread); - SDL_free(thread); - } + if (thread) { + SDL_SYS_WaitThread(thread); + if (status) { + *status = thread->status; + } + SDL_DelThread(thread); + SDL_free(thread); + } } -Uint32 SDL_GetThreadID(SDL_Thread *thread) +Uint32 +SDL_GetThreadID(SDL_Thread * thread) { - Uint32 id; - - if ( thread ) { - id = thread->threadid; - } else { - id = SDL_ThreadID(); - } - return(id); + Uint32 id; + + if (thread) { + id = thread->threadid; + } else { + id = SDL_ThreadID(); + } + return (id); } -void SDL_KillThread(SDL_Thread *thread) +void +SDL_KillThread(SDL_Thread * thread) { - if ( thread ) { - SDL_SYS_KillThread(thread); - SDL_WaitThread(thread, NULL); - } + if (thread) { + SDL_SYS_KillThread(thread); + SDL_WaitThread(thread, NULL); + } } +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/thread/beos/SDL_syssem.c b/src/thread/beos/SDL_syssem.c index 5ea4f3735..7082bbcef 100644 --- a/src/thread/beos/SDL_syssem.c +++ b/src/thread/beos/SDL_syssem.c @@ -28,115 +28,125 @@ #include "SDL_thread.h" -struct SDL_semaphore { - sem_id id; +struct SDL_semaphore +{ + sem_id id; }; /* Create a counting semaphore */ -SDL_sem *SDL_CreateSemaphore(Uint32 initial_value) +SDL_sem * +SDL_CreateSemaphore(Uint32 initial_value) { - SDL_sem *sem; - - sem = (SDL_sem *)SDL_malloc(sizeof(*sem)); - if ( sem ) { - sem->id = create_sem(initial_value, "SDL semaphore"); - if ( sem->id < B_NO_ERROR ) { - SDL_SetError("create_sem() failed"); - SDL_free(sem); - sem = NULL; - } - } else { - SDL_OutOfMemory(); - } - return(sem); + SDL_sem *sem; + + sem = (SDL_sem *) SDL_malloc(sizeof(*sem)); + if (sem) { + sem->id = create_sem(initial_value, "SDL semaphore"); + if (sem->id < B_NO_ERROR) { + SDL_SetError("create_sem() failed"); + SDL_free(sem); + sem = NULL; + } + } else { + SDL_OutOfMemory(); + } + return (sem); } /* Free the semaphore */ -void SDL_DestroySemaphore(SDL_sem *sem) +void +SDL_DestroySemaphore(SDL_sem * sem) { - if ( sem ) { - if ( sem->id >= B_NO_ERROR ) { - delete_sem(sem->id); - } - SDL_free(sem); - } + if (sem) { + if (sem->id >= B_NO_ERROR) { + delete_sem(sem->id); + } + SDL_free(sem); + } } -int SDL_SemWaitTimeout(SDL_sem *sem, Uint32 timeout) +int +SDL_SemWaitTimeout(SDL_sem * sem, Uint32 timeout) { - int32 val; - int retval; + int32 val; + int retval; - if ( ! sem ) { - SDL_SetError("Passed a NULL semaphore"); - return -1; - } + if (!sem) { + SDL_SetError("Passed a NULL semaphore"); + return -1; + } tryagain: - if ( timeout == SDL_MUTEX_MAXWAIT ) { - val = acquire_sem(sem->id); - } else { - timeout *= 1000; /* BeOS uses a timeout in microseconds */ - val = acquire_sem_etc(sem->id, 1, B_RELATIVE_TIMEOUT, timeout); - } - switch (val) { - case B_INTERRUPTED: - goto tryagain; - case B_NO_ERROR: - retval = 0; - break; - case B_TIMED_OUT: - retval = SDL_MUTEX_TIMEDOUT; - break; - case B_WOULD_BLOCK: - retval = SDL_MUTEX_TIMEDOUT; - break; - default: - SDL_SetError("acquire_sem() failed"); - retval = -1; - break; - } - - return retval; + if (timeout == SDL_MUTEX_MAXWAIT) { + val = acquire_sem(sem->id); + } else { + timeout *= 1000; /* BeOS uses a timeout in microseconds */ + val = acquire_sem_etc(sem->id, 1, B_RELATIVE_TIMEOUT, timeout); + } + switch (val) { + case B_INTERRUPTED: + goto tryagain; + case B_NO_ERROR: + retval = 0; + break; + case B_TIMED_OUT: + retval = SDL_MUTEX_TIMEDOUT; + break; + case B_WOULD_BLOCK: + retval = SDL_MUTEX_TIMEDOUT; + break; + default: + SDL_SetError("acquire_sem() failed"); + retval = -1; + break; + } + + return retval; } -int SDL_SemTryWait(SDL_sem *sem) +int +SDL_SemTryWait(SDL_sem * sem) { - return SDL_SemWaitTimeout(sem, 0); + return SDL_SemWaitTimeout(sem, 0); } -int SDL_SemWait(SDL_sem *sem) +int +SDL_SemWait(SDL_sem * sem) { - return SDL_SemWaitTimeout(sem, SDL_MUTEX_MAXWAIT); + return SDL_SemWaitTimeout(sem, SDL_MUTEX_MAXWAIT); } /* Returns the current count of the semaphore */ -Uint32 SDL_SemValue(SDL_sem *sem) +Uint32 +SDL_SemValue(SDL_sem * sem) { - int32 count; - Uint32 value; - - value = 0; - if ( sem ) { - get_sem_count(sem->id, &count); - if ( count > 0 ) { - value = (Uint32)count; - } - } - return value; + int32 count; + Uint32 value; + + value = 0; + if (sem) { + get_sem_count(sem->id, &count); + if (count > 0) { + value = (Uint32) count; + } + } + return value; } /* Atomically increases the semaphore's count (not blocking) */ -int SDL_SemPost(SDL_sem *sem) +int +SDL_SemPost(SDL_sem * sem) { - if ( ! sem ) { - SDL_SetError("Passed a NULL semaphore"); - return -1; - } - - if ( release_sem(sem->id) != B_NO_ERROR ) { - SDL_SetError("release_sem() failed"); - return -1; - } - return 0; + if (!sem) { + SDL_SetError("Passed a NULL semaphore"); + return -1; + } + + if (release_sem(sem->id) != B_NO_ERROR) { + SDL_SetError("release_sem() failed"); + return -1; + } + return 0; } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/thread/beos/SDL_systhread.c b/src/thread/beos/SDL_systhread.c index 904fcc770..f28f6a06e 100644 --- a/src/thread/beos/SDL_systhread.c +++ b/src/thread/beos/SDL_systhread.c @@ -34,63 +34,74 @@ static int sig_list[] = { - SIGHUP, SIGINT, SIGQUIT, SIGPIPE, SIGALRM, SIGTERM, SIGWINCH, 0 + SIGHUP, SIGINT, SIGQUIT, SIGPIPE, SIGALRM, SIGTERM, SIGWINCH, 0 }; -void SDL_MaskSignals(sigset_t *omask) +void +SDL_MaskSignals(sigset_t * omask) { - sigset_t mask; - int i; - - sigemptyset(&mask); - for ( i=0; sig_list[i]; ++i ) { - sigaddset(&mask, sig_list[i]); - } - sigprocmask(SIG_BLOCK, &mask, omask); + sigset_t mask; + int i; + + sigemptyset(&mask); + for (i = 0; sig_list[i]; ++i) { + sigaddset(&mask, sig_list[i]); + } + sigprocmask(SIG_BLOCK, &mask, omask); } -void SDL_UnmaskSignals(sigset_t *omask) + +void +SDL_UnmaskSignals(sigset_t * omask) { - sigprocmask(SIG_SETMASK, omask, NULL); + sigprocmask(SIG_SETMASK, omask, NULL); } -static int32 RunThread(void *data) +static int32 +RunThread(void *data) { - SDL_RunThread(data); - return(0); + SDL_RunThread(data); + return (0); } -int SDL_SYS_CreateThread(SDL_Thread *thread, void *args) +int +SDL_SYS_CreateThread(SDL_Thread * thread, void *args) { - /* Create the thread and go! */ - thread->handle=spawn_thread(RunThread, "SDL", B_NORMAL_PRIORITY, args); - if ( (thread->handle == B_NO_MORE_THREADS) || - (thread->handle == B_NO_MEMORY) ) { - SDL_SetError("Not enough resources to create thread"); - return(-1); - } - resume_thread(thread->handle); - return(0); + /* Create the thread and go! */ + thread->handle = spawn_thread(RunThread, "SDL", B_NORMAL_PRIORITY, args); + if ((thread->handle == B_NO_MORE_THREADS) || + (thread->handle == B_NO_MEMORY)) { + SDL_SetError("Not enough resources to create thread"); + return (-1); + } + resume_thread(thread->handle); + return (0); } -void SDL_SYS_SetupThread(void) +void +SDL_SYS_SetupThread(void) { - /* Mask asynchronous signals for this thread */ - SDL_MaskSignals(NULL); + /* Mask asynchronous signals for this thread */ + SDL_MaskSignals(NULL); } -Uint32 SDL_ThreadID(void) +Uint32 +SDL_ThreadID(void) { - return((Uint32)find_thread(NULL)); + return ((Uint32) find_thread(NULL)); } -void SDL_SYS_WaitThread(SDL_Thread *thread) +void +SDL_SYS_WaitThread(SDL_Thread * thread) { - status_t the_status; + status_t the_status; - wait_for_thread(thread->handle, &the_status); + wait_for_thread(thread->handle, &the_status); } -void SDL_SYS_KillThread(SDL_Thread *thread) +void +SDL_SYS_KillThread(SDL_Thread * thread) { - kill_thread(thread->handle); + kill_thread(thread->handle); } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/thread/beos/SDL_systhread_c.h b/src/thread/beos/SDL_systhread_c.h index 0d8d8546e..6ac24b4b8 100644 --- a/src/thread/beos/SDL_systhread_c.h +++ b/src/thread/beos/SDL_systhread_c.h @@ -27,5 +27,7 @@ typedef thread_id SYS_ThreadHandle; /* Functions needed to work with system threads in other portions of SDL */ -extern void SDL_MaskSignals(sigset_t *omask); -extern void SDL_UnmaskSignals(sigset_t *omask); +extern void SDL_MaskSignals(sigset_t * omask); +extern void SDL_UnmaskSignals(sigset_t * omask); + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/thread/dc/SDL_syscond.c b/src/thread/dc/SDL_syscond.c index 6a9d2dcc0..90ba8fed4 100644 --- a/src/thread/dc/SDL_syscond.c +++ b/src/thread/dc/SDL_syscond.c @@ -31,107 +31,111 @@ struct SDL_cond { - SDL_mutex *lock; - int waiting; - int signals; - SDL_sem *wait_sem; - SDL_sem *wait_done; + SDL_mutex *lock; + int waiting; + int signals; + SDL_sem *wait_sem; + SDL_sem *wait_done; }; /* Create a condition variable */ -SDL_cond * SDL_CreateCond(void) +SDL_cond * +SDL_CreateCond(void) { - SDL_cond *cond; - - cond = (SDL_cond *) SDL_malloc(sizeof(SDL_cond)); - if ( cond ) { - cond->lock = SDL_CreateMutex(); - cond->wait_sem = SDL_CreateSemaphore(0); - cond->wait_done = SDL_CreateSemaphore(0); - cond->waiting = cond->signals = 0; - if ( ! cond->lock || ! cond->wait_sem || ! cond->wait_done ) { - SDL_DestroyCond(cond); - cond = NULL; - } - } else { - SDL_OutOfMemory(); - } - return(cond); + SDL_cond *cond; + + cond = (SDL_cond *) SDL_malloc(sizeof(SDL_cond)); + if (cond) { + cond->lock = SDL_CreateMutex(); + cond->wait_sem = SDL_CreateSemaphore(0); + cond->wait_done = SDL_CreateSemaphore(0); + cond->waiting = cond->signals = 0; + if (!cond->lock || !cond->wait_sem || !cond->wait_done) { + SDL_DestroyCond(cond); + cond = NULL; + } + } else { + SDL_OutOfMemory(); + } + return (cond); } /* Destroy a condition variable */ -void SDL_DestroyCond(SDL_cond *cond) +void +SDL_DestroyCond(SDL_cond * cond) { - if ( cond ) { - if ( cond->wait_sem ) { - SDL_DestroySemaphore(cond->wait_sem); - } - if ( cond->wait_done ) { - SDL_DestroySemaphore(cond->wait_done); - } - if ( cond->lock ) { - SDL_DestroyMutex(cond->lock); - } - SDL_free(cond); - } + if (cond) { + if (cond->wait_sem) { + SDL_DestroySemaphore(cond->wait_sem); + } + if (cond->wait_done) { + SDL_DestroySemaphore(cond->wait_done); + } + if (cond->lock) { + SDL_DestroyMutex(cond->lock); + } + SDL_free(cond); + } } /* Restart one of the threads that are waiting on the condition variable */ -int SDL_CondSignal(SDL_cond *cond) +int +SDL_CondSignal(SDL_cond * cond) { - if ( ! cond ) { - SDL_SetError("Passed a NULL condition variable"); - return -1; - } - - /* If there are waiting threads not already signalled, then - signal the condition and wait for the thread to respond. - */ - SDL_LockMutex(cond->lock); - if ( cond->waiting > cond->signals ) { - ++cond->signals; - SDL_SemPost(cond->wait_sem); - SDL_UnlockMutex(cond->lock); - SDL_SemWait(cond->wait_done); - } else { - SDL_UnlockMutex(cond->lock); - } - - return 0; + if (!cond) { + SDL_SetError("Passed a NULL condition variable"); + return -1; + } + + /* If there are waiting threads not already signalled, then + signal the condition and wait for the thread to respond. + */ + SDL_LockMutex(cond->lock); + if (cond->waiting > cond->signals) { + ++cond->signals; + SDL_SemPost(cond->wait_sem); + SDL_UnlockMutex(cond->lock); + SDL_SemWait(cond->wait_done); + } else { + SDL_UnlockMutex(cond->lock); + } + + return 0; } /* Restart all threads that are waiting on the condition variable */ -int SDL_CondBroadcast(SDL_cond *cond) +int +SDL_CondBroadcast(SDL_cond * cond) { - if ( ! cond ) { - SDL_SetError("Passed a NULL condition variable"); - return -1; - } - - /* If there are waiting threads not already signalled, then - signal the condition and wait for the thread to respond. - */ - SDL_LockMutex(cond->lock); - if ( cond->waiting > cond->signals ) { - int i, num_waiting; - - num_waiting = (cond->waiting - cond->signals); - cond->signals = cond->waiting; - for ( i=0; iwait_sem); - } - /* Now all released threads are blocked here, waiting for us. - Collect them all (and win fabulous prizes!) :-) - */ - SDL_UnlockMutex(cond->lock); - for ( i=0; iwait_done); - } - } else { - SDL_UnlockMutex(cond->lock); - } - - return 0; + if (!cond) { + SDL_SetError("Passed a NULL condition variable"); + return -1; + } + + /* If there are waiting threads not already signalled, then + signal the condition and wait for the thread to respond. + */ + SDL_LockMutex(cond->lock); + if (cond->waiting > cond->signals) { + int i, num_waiting; + + num_waiting = (cond->waiting - cond->signals); + cond->signals = cond->waiting; + for (i = 0; i < num_waiting; ++i) { + SDL_SemPost(cond->wait_sem); + } + /* Now all released threads are blocked here, waiting for us. + Collect them all (and win fabulous prizes!) :-) + */ + SDL_UnlockMutex(cond->lock); + for (i = 0; i < num_waiting; ++i) { + SDL_SemWait(cond->wait_done); + } + } else { + SDL_UnlockMutex(cond->lock); + } + + return 0; } /* Wait on the condition variable for at most 'ms' milliseconds. @@ -154,62 +158,66 @@ Thread B: ... SDL_UnlockMutex(lock); */ -int SDL_CondWaitTimeout(SDL_cond *cond, SDL_mutex *mutex, Uint32 ms) +int +SDL_CondWaitTimeout(SDL_cond * cond, SDL_mutex * mutex, Uint32 ms) { - int retval; - - if ( ! cond ) { - SDL_SetError("Passed a NULL condition variable"); - return -1; - } - - /* Obtain the protection mutex, and increment the number of waiters. - This allows the signal mechanism to only perform a signal if there - are waiting threads. - */ - SDL_LockMutex(cond->lock); - ++cond->waiting; - SDL_UnlockMutex(cond->lock); - - /* Unlock the mutex, as is required by condition variable semantics */ - SDL_UnlockMutex(mutex); - - /* Wait for a signal */ - if ( ms == SDL_MUTEX_MAXWAIT ) { - retval = SDL_SemWait(cond->wait_sem); - } else { - retval = SDL_SemWaitTimeout(cond->wait_sem, ms); - } - - /* Let the signaler know we have completed the wait, otherwise - the signaler can race ahead and get the condition semaphore - if we are stopped between the mutex unlock and semaphore wait, - giving a deadlock. See the following URL for details: - http://www-classic.be.com/aboutbe/benewsletter/volume_III/Issue40.html - */ - SDL_LockMutex(cond->lock); - if ( cond->signals > 0 ) { - /* If we timed out, we need to eat a condition signal */ - if ( retval > 0 ) { - SDL_SemWait(cond->wait_sem); - } - /* We always notify the signal thread that we are done */ - SDL_SemPost(cond->wait_done); - - /* Signal handshake complete */ - --cond->signals; - } - --cond->waiting; - SDL_UnlockMutex(cond->lock); - - /* Lock the mutex, as is required by condition variable semantics */ - SDL_LockMutex(mutex); - - return retval; + int retval; + + if (!cond) { + SDL_SetError("Passed a NULL condition variable"); + return -1; + } + + /* Obtain the protection mutex, and increment the number of waiters. + This allows the signal mechanism to only perform a signal if there + are waiting threads. + */ + SDL_LockMutex(cond->lock); + ++cond->waiting; + SDL_UnlockMutex(cond->lock); + + /* Unlock the mutex, as is required by condition variable semantics */ + SDL_UnlockMutex(mutex); + + /* Wait for a signal */ + if (ms == SDL_MUTEX_MAXWAIT) { + retval = SDL_SemWait(cond->wait_sem); + } else { + retval = SDL_SemWaitTimeout(cond->wait_sem, ms); + } + + /* Let the signaler know we have completed the wait, otherwise + the signaler can race ahead and get the condition semaphore + if we are stopped between the mutex unlock and semaphore wait, + giving a deadlock. See the following URL for details: + http://www-classic.be.com/aboutbe/benewsletter/volume_III/Issue40.html + */ + SDL_LockMutex(cond->lock); + if (cond->signals > 0) { + /* If we timed out, we need to eat a condition signal */ + if (retval > 0) { + SDL_SemWait(cond->wait_sem); + } + /* We always notify the signal thread that we are done */ + SDL_SemPost(cond->wait_done); + + /* Signal handshake complete */ + --cond->signals; + } + --cond->waiting; + SDL_UnlockMutex(cond->lock); + + /* Lock the mutex, as is required by condition variable semantics */ + SDL_LockMutex(mutex); + + return retval; } /* Wait on the condition variable forever */ -int SDL_CondWait(SDL_cond *cond, SDL_mutex *mutex) +int +SDL_CondWait(SDL_cond * cond, SDL_mutex * mutex) { - return SDL_CondWaitTimeout(cond, mutex, SDL_MUTEX_MAXWAIT); + return SDL_CondWaitTimeout(cond, mutex, SDL_MUTEX_MAXWAIT); } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/thread/dc/SDL_syscond_c.h b/src/thread/dc/SDL_syscond_c.h index 27d55093a..8ab650f13 100644 --- a/src/thread/dc/SDL_syscond_c.h +++ b/src/thread/dc/SDL_syscond_c.h @@ -20,4 +20,4 @@ slouken@libsdl.org */ #include "SDL_config.h" - +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/thread/dc/SDL_sysmutex.c b/src/thread/dc/SDL_sysmutex.c index 8e3d5f7a4..5164ff9f6 100644 --- a/src/thread/dc/SDL_sysmutex.c +++ b/src/thread/dc/SDL_sysmutex.c @@ -28,95 +28,102 @@ #include -struct SDL_mutex { - int recursive; - Uint32 owner; - spinlock_t mutex; +struct SDL_mutex +{ + int recursive; + Uint32 owner; + spinlock_t mutex; }; /* Create a mutex */ -SDL_mutex *SDL_CreateMutex(void) +SDL_mutex * +SDL_CreateMutex(void) { - SDL_mutex *mutex; - - /* Allocate mutex memory */ - mutex = (SDL_mutex *)SDL_malloc(sizeof(*mutex)); - if ( mutex ) { - spinlock_init(&mutex->mutex); - mutex->recursive = 0; - mutex->owner = 0; - } else { - SDL_OutOfMemory(); - } - return mutex; + SDL_mutex *mutex; + + /* Allocate mutex memory */ + mutex = (SDL_mutex *) SDL_malloc(sizeof(*mutex)); + if (mutex) { + spinlock_init(&mutex->mutex); + mutex->recursive = 0; + mutex->owner = 0; + } else { + SDL_OutOfMemory(); + } + return mutex; } /* Free the mutex */ -void SDL_DestroyMutex(SDL_mutex *mutex) +void +SDL_DestroyMutex(SDL_mutex * mutex) { - if ( mutex ) { - SDL_free(mutex); - } + if (mutex) { + SDL_free(mutex); + } } /* Lock the semaphore */ -int SDL_mutexP(SDL_mutex *mutex) +int +SDL_mutexP(SDL_mutex * mutex) { #if SDL_THREADS_DISABLED - return SDL_arraysize(return ),0; + return SDL_arraysize(return), 0; #else - Uint32 this_thread; - - if ( mutex == NULL ) { - SDL_SetError("Passed a NULL mutex"); - return -1; - } - - this_thread = SDL_ThreadID(); - if ( mutex->owner == this_thread ) { - ++mutex->recursive; - } else { - /* The order of operations is important. - We set the locking thread id after we obtain the lock - so unlocks from other threads will fail. - */ - spinlock_lock(&mutex->mutex); - mutex->owner = this_thread; - mutex->recursive = 0; - } - - return 0; + Uint32 this_thread; + + if (mutex == NULL) { + SDL_SetError("Passed a NULL mutex"); + return -1; + } + + this_thread = SDL_ThreadID(); + if (mutex->owner == this_thread) { + ++mutex->recursive; + } else { + /* The order of operations is important. + We set the locking thread id after we obtain the lock + so unlocks from other threads will fail. + */ + spinlock_lock(&mutex->mutex); + mutex->owner = this_thread; + mutex->recursive = 0; + } + + return 0; #endif /* SDL_THREADS_DISABLED */ } /* Unlock the mutex */ -int SDL_mutexV(SDL_mutex *mutex) +int +SDL_mutexV(SDL_mutex * mutex) { #if SDL_THREADS_DISABLED - return 0; + return 0; #else - if ( mutex == NULL ) { - SDL_SetError("Passed a NULL mutex"); - return -1; - } - - /* If we don't own the mutex, we can't unlock it */ - if ( SDL_ThreadID() != mutex->owner ) { - SDL_SetError("mutex not owned by this thread"); - return -1; - } - - if ( mutex->recursive ) { - --mutex->recursive; - } else { - /* The order of operations is important. - First reset the owner so another thread doesn't lock - the mutex and set the ownership before we reset it, - then release the lock semaphore. - */ - mutex->owner = 0; - spinlock_unlock(&mutex->mutex); - } - return 0; + if (mutex == NULL) { + SDL_SetError("Passed a NULL mutex"); + return -1; + } + + /* If we don't own the mutex, we can't unlock it */ + if (SDL_ThreadID() != mutex->owner) { + SDL_SetError("mutex not owned by this thread"); + return -1; + } + + if (mutex->recursive) { + --mutex->recursive; + } else { + /* The order of operations is important. + First reset the owner so another thread doesn't lock + the mutex and set the ownership before we reset it, + then release the lock semaphore. + */ + mutex->owner = 0; + spinlock_unlock(&mutex->mutex); + } + return 0; #endif /* SDL_THREADS_DISABLED */ } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/thread/dc/SDL_sysmutex_c.h b/src/thread/dc/SDL_sysmutex_c.h index 27d55093a..8ab650f13 100644 --- a/src/thread/dc/SDL_sysmutex_c.h +++ b/src/thread/dc/SDL_sysmutex_c.h @@ -20,4 +20,4 @@ slouken@libsdl.org */ #include "SDL_config.h" - +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/thread/dc/SDL_syssem.c b/src/thread/dc/SDL_syssem.c index d9888f7a1..064a88828 100644 --- a/src/thread/dc/SDL_syssem.c +++ b/src/thread/dc/SDL_syssem.c @@ -19,9 +19,6 @@ Sam Lantinga slouken@libsdl.org */ - -#include - #include "SDL_config.h" /* An implementation of semaphores using mutexes and condition variables */ @@ -33,44 +30,51 @@ #if SDL_THREADS_DISABLED -SDL_sem *SDL_CreateSemaphore(Uint32 initial_value) +SDL_sem * +SDL_CreateSemaphore(Uint32 initial_value) { - SDL_SetError("SDL not configured with thread support"); - return (SDL_sem *)0; + SDL_SetError("SDL not configured with thread support"); + return (SDL_sem *) 0; } -void SDL_DestroySemaphore(SDL_sem *sem) +void +SDL_DestroySemaphore(SDL_sem * sem) { - return; + return; } -int SDL_SemTryWait(SDL_sem *sem) +int +SDL_SemTryWait(SDL_sem * sem) { - SDL_SetError("SDL not configured with thread support"); - return -1; + SDL_SetError("SDL not configured with thread support"); + return -1; } -int SDL_SemWaitTimeout(SDL_sem *sem, Uint32 timeout) +int +SDL_SemWaitTimeout(SDL_sem * sem, Uint32 timeout) { - SDL_SetError("SDL not configured with thread support"); - return -1; + SDL_SetError("SDL not configured with thread support"); + return -1; } -int SDL_SemWait(SDL_sem *sem) +int +SDL_SemWait(SDL_sem * sem) { - SDL_SetError("SDL not configured with thread support"); - return -1; + SDL_SetError("SDL not configured with thread support"); + return -1; } -Uint32 SDL_SemValue(SDL_sem *sem) +Uint32 +SDL_SemValue(SDL_sem * sem) { - return 0; + return 0; } -int SDL_SemPost(SDL_sem *sem) +int +SDL_SemPost(SDL_sem * sem) { - SDL_SetError("SDL not configured with thread support"); - return -1; + SDL_SetError("SDL not configured with thread support"); + return -1; } #else @@ -79,95 +83,104 @@ int SDL_SemPost(SDL_sem *sem) struct SDL_semaphore { - semaphore_t sem; + semaphore_t sem; }; -SDL_sem *SDL_CreateSemaphore(Uint32 initial_value) +SDL_sem * +SDL_CreateSemaphore(Uint32 initial_value) { - return (SDL_sem *)sem_create(initial_value); + return (SDL_sem *) sem_create(initial_value); } /* WARNING: You cannot call this function when another thread is using the semaphore. */ -void SDL_DestroySemaphore(SDL_sem *sem) +void +SDL_DestroySemaphore(SDL_sem * sem) { - if ( ! sem ) { - SDL_SetError("Passed a NULL semaphore"); - return; - } + if (!sem) { + SDL_SetError("Passed a NULL semaphore"); + return; + } - sem_destroy(&sem->sem); + sem_destroy(&sem->sem); } -int SDL_SemTryWait(SDL_sem *sem) +int +SDL_SemTryWait(SDL_sem * sem) { - int retval; + int retval; - if ( ! sem ) { - SDL_SetError("Passed a NULL semaphore"); - return -1; - } + if (!sem) { + SDL_SetError("Passed a NULL semaphore"); + return -1; + } - retval = sem_trywait(&sem->sem); - if (retval==0) return 0; - else return SDL_MUTEX_TIMEDOUT; + retval = sem_trywait(&sem->sem); + if (retval == 0) + return 0; + else + return SDL_MUTEX_TIMEDOUT; - return retval; + return retval; } -int SDL_SemWaitTimeout(SDL_sem *sem, Uint32 timeout) +int +SDL_SemWaitTimeout(SDL_sem * sem, Uint32 timeout) { - int retval; + int retval; - if ( ! sem ) { - SDL_SetError("Passed a NULL semaphore"); - return -1; - } + if (!sem) { + SDL_SetError("Passed a NULL semaphore"); + return -1; + } - /* A timeout of 0 is an easy case */ - if ( timeout == 0 ) { - return SDL_SemTryWait(sem); - } + /* A timeout of 0 is an easy case */ + if (timeout == 0) { + return SDL_SemTryWait(sem); + } - retval = sem_wait_timed(&sem->sem,timeout); - if (retval==-1) retval= SDL_MUTEX_TIMEDOUT; + retval = sem_wait_timed(&sem->sem, timeout); + if (retval == -1) + retval = SDL_MUTEX_TIMEDOUT; - return retval; + return retval; } -int SDL_SemWait(SDL_sem *sem) +int +SDL_SemWait(SDL_sem * sem) { - int retval; - - if ( ! sem ) { - SDL_SetError("Passed a NULL semaphore"); - return -1; - } + if (!sem) { + SDL_SetError("Passed a NULL semaphore"); + return -1; + } - while ( ((retval = sem_wait(&sem->sem)) == -1) && (errno == EINTR) ) {} - return retval; + sem_wait(&sem->sem); + return 0; } -Uint32 SDL_SemValue(SDL_sem *sem) +Uint32 +SDL_SemValue(SDL_sem * sem) { - if ( ! sem ) { - SDL_SetError("Passed a NULL semaphore"); - return -1; - } + if (!sem) { + SDL_SetError("Passed a NULL semaphore"); + return -1; + } - return sem_count(&sem->sem); + return sem_count(&sem->sem); } -int SDL_SemPost(SDL_sem *sem) +int +SDL_SemPost(SDL_sem * sem) { - if ( ! sem ) { - SDL_SetError("Passed a NULL semaphore"); - return -1; - } + if (!sem) { + SDL_SetError("Passed a NULL semaphore"); + return -1; + } - sem_signal(&sem->sem); - return 0; + sem_signal(&sem->sem); + return 0; } #endif /* SDL_THREADS_DISABLED */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/thread/dc/SDL_syssem_c.h b/src/thread/dc/SDL_syssem_c.h index 27d55093a..8ab650f13 100644 --- a/src/thread/dc/SDL_syssem_c.h +++ b/src/thread/dc/SDL_syssem_c.h @@ -20,4 +20,4 @@ slouken@libsdl.org */ #include "SDL_config.h" - +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/thread/dc/SDL_systhread.c b/src/thread/dc/SDL_systhread.c index 8c782cc62..49221ffd9 100644 --- a/src/thread/dc/SDL_systhread.c +++ b/src/thread/dc/SDL_systhread.c @@ -29,32 +29,39 @@ #include -int SDL_SYS_CreateThread(SDL_Thread *thread, void *args) +int +SDL_SYS_CreateThread(SDL_Thread * thread, void *args) { - thread->handle = thd_create(SDL_RunThread,args); - if (thread->handle == NULL) { - SDL_SetError("Not enough resources to create thread"); - return(-1); - } - return(0); + thread->handle = thd_create(SDL_RunThread, args); + if (thread->handle == NULL) { + SDL_SetError("Not enough resources to create thread"); + return (-1); + } + return (0); } -void SDL_SYS_SetupThread(void) +void +SDL_SYS_SetupThread(void) { - return; + return; } -Uint32 SDL_ThreadID(void) +Uint32 +SDL_ThreadID(void) { - return (Uint32)thd_get_current(); + return (Uint32) thd_get_current(); } -void SDL_SYS_WaitThread(SDL_Thread *thread) +void +SDL_SYS_WaitThread(SDL_Thread * thread) { - thd_wait(thread->handle); + thd_wait(thread->handle); } -void SDL_SYS_KillThread(SDL_Thread *thread) +void +SDL_SYS_KillThread(SDL_Thread * thread) { - thd_destroy(thread->handle); + thd_destroy(thread->handle); } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/thread/dc/SDL_systhread_c.h b/src/thread/dc/SDL_systhread_c.h index 8f9553fb0..98bdf0f8d 100644 --- a/src/thread/dc/SDL_systhread_c.h +++ b/src/thread/dc/SDL_systhread_c.h @@ -21,4 +21,5 @@ */ #include "SDL_config.h" -typedef struct kthread* SYS_ThreadHandle; +typedef struct kthread *SYS_ThreadHandle; +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/thread/epoc/SDL_systhread_c.h b/src/thread/epoc/SDL_systhread_c.h index 6f5fd943b..302e63608 100644 --- a/src/thread/epoc/SDL_systhread_c.h +++ b/src/thread/epoc/SDL_systhread_c.h @@ -28,4 +28,4 @@ */ typedef int SYS_ThreadHandle; - +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/thread/generic/SDL_syscond.c b/src/thread/generic/SDL_syscond.c index 6a9d2dcc0..90ba8fed4 100644 --- a/src/thread/generic/SDL_syscond.c +++ b/src/thread/generic/SDL_syscond.c @@ -31,107 +31,111 @@ struct SDL_cond { - SDL_mutex *lock; - int waiting; - int signals; - SDL_sem *wait_sem; - SDL_sem *wait_done; + SDL_mutex *lock; + int waiting; + int signals; + SDL_sem *wait_sem; + SDL_sem *wait_done; }; /* Create a condition variable */ -SDL_cond * SDL_CreateCond(void) +SDL_cond * +SDL_CreateCond(void) { - SDL_cond *cond; - - cond = (SDL_cond *) SDL_malloc(sizeof(SDL_cond)); - if ( cond ) { - cond->lock = SDL_CreateMutex(); - cond->wait_sem = SDL_CreateSemaphore(0); - cond->wait_done = SDL_CreateSemaphore(0); - cond->waiting = cond->signals = 0; - if ( ! cond->lock || ! cond->wait_sem || ! cond->wait_done ) { - SDL_DestroyCond(cond); - cond = NULL; - } - } else { - SDL_OutOfMemory(); - } - return(cond); + SDL_cond *cond; + + cond = (SDL_cond *) SDL_malloc(sizeof(SDL_cond)); + if (cond) { + cond->lock = SDL_CreateMutex(); + cond->wait_sem = SDL_CreateSemaphore(0); + cond->wait_done = SDL_CreateSemaphore(0); + cond->waiting = cond->signals = 0; + if (!cond->lock || !cond->wait_sem || !cond->wait_done) { + SDL_DestroyCond(cond); + cond = NULL; + } + } else { + SDL_OutOfMemory(); + } + return (cond); } /* Destroy a condition variable */ -void SDL_DestroyCond(SDL_cond *cond) +void +SDL_DestroyCond(SDL_cond * cond) { - if ( cond ) { - if ( cond->wait_sem ) { - SDL_DestroySemaphore(cond->wait_sem); - } - if ( cond->wait_done ) { - SDL_DestroySemaphore(cond->wait_done); - } - if ( cond->lock ) { - SDL_DestroyMutex(cond->lock); - } - SDL_free(cond); - } + if (cond) { + if (cond->wait_sem) { + SDL_DestroySemaphore(cond->wait_sem); + } + if (cond->wait_done) { + SDL_DestroySemaphore(cond->wait_done); + } + if (cond->lock) { + SDL_DestroyMutex(cond->lock); + } + SDL_free(cond); + } } /* Restart one of the threads that are waiting on the condition variable */ -int SDL_CondSignal(SDL_cond *cond) +int +SDL_CondSignal(SDL_cond * cond) { - if ( ! cond ) { - SDL_SetError("Passed a NULL condition variable"); - return -1; - } - - /* If there are waiting threads not already signalled, then - signal the condition and wait for the thread to respond. - */ - SDL_LockMutex(cond->lock); - if ( cond->waiting > cond->signals ) { - ++cond->signals; - SDL_SemPost(cond->wait_sem); - SDL_UnlockMutex(cond->lock); - SDL_SemWait(cond->wait_done); - } else { - SDL_UnlockMutex(cond->lock); - } - - return 0; + if (!cond) { + SDL_SetError("Passed a NULL condition variable"); + return -1; + } + + /* If there are waiting threads not already signalled, then + signal the condition and wait for the thread to respond. + */ + SDL_LockMutex(cond->lock); + if (cond->waiting > cond->signals) { + ++cond->signals; + SDL_SemPost(cond->wait_sem); + SDL_UnlockMutex(cond->lock); + SDL_SemWait(cond->wait_done); + } else { + SDL_UnlockMutex(cond->lock); + } + + return 0; } /* Restart all threads that are waiting on the condition variable */ -int SDL_CondBroadcast(SDL_cond *cond) +int +SDL_CondBroadcast(SDL_cond * cond) { - if ( ! cond ) { - SDL_SetError("Passed a NULL condition variable"); - return -1; - } - - /* If there are waiting threads not already signalled, then - signal the condition and wait for the thread to respond. - */ - SDL_LockMutex(cond->lock); - if ( cond->waiting > cond->signals ) { - int i, num_waiting; - - num_waiting = (cond->waiting - cond->signals); - cond->signals = cond->waiting; - for ( i=0; iwait_sem); - } - /* Now all released threads are blocked here, waiting for us. - Collect them all (and win fabulous prizes!) :-) - */ - SDL_UnlockMutex(cond->lock); - for ( i=0; iwait_done); - } - } else { - SDL_UnlockMutex(cond->lock); - } - - return 0; + if (!cond) { + SDL_SetError("Passed a NULL condition variable"); + return -1; + } + + /* If there are waiting threads not already signalled, then + signal the condition and wait for the thread to respond. + */ + SDL_LockMutex(cond->lock); + if (cond->waiting > cond->signals) { + int i, num_waiting; + + num_waiting = (cond->waiting - cond->signals); + cond->signals = cond->waiting; + for (i = 0; i < num_waiting; ++i) { + SDL_SemPost(cond->wait_sem); + } + /* Now all released threads are blocked here, waiting for us. + Collect them all (and win fabulous prizes!) :-) + */ + SDL_UnlockMutex(cond->lock); + for (i = 0; i < num_waiting; ++i) { + SDL_SemWait(cond->wait_done); + } + } else { + SDL_UnlockMutex(cond->lock); + } + + return 0; } /* Wait on the condition variable for at most 'ms' milliseconds. @@ -154,62 +158,66 @@ Thread B: ... SDL_UnlockMutex(lock); */ -int SDL_CondWaitTimeout(SDL_cond *cond, SDL_mutex *mutex, Uint32 ms) +int +SDL_CondWaitTimeout(SDL_cond * cond, SDL_mutex * mutex, Uint32 ms) { - int retval; - - if ( ! cond ) { - SDL_SetError("Passed a NULL condition variable"); - return -1; - } - - /* Obtain the protection mutex, and increment the number of waiters. - This allows the signal mechanism to only perform a signal if there - are waiting threads. - */ - SDL_LockMutex(cond->lock); - ++cond->waiting; - SDL_UnlockMutex(cond->lock); - - /* Unlock the mutex, as is required by condition variable semantics */ - SDL_UnlockMutex(mutex); - - /* Wait for a signal */ - if ( ms == SDL_MUTEX_MAXWAIT ) { - retval = SDL_SemWait(cond->wait_sem); - } else { - retval = SDL_SemWaitTimeout(cond->wait_sem, ms); - } - - /* Let the signaler know we have completed the wait, otherwise - the signaler can race ahead and get the condition semaphore - if we are stopped between the mutex unlock and semaphore wait, - giving a deadlock. See the following URL for details: - http://www-classic.be.com/aboutbe/benewsletter/volume_III/Issue40.html - */ - SDL_LockMutex(cond->lock); - if ( cond->signals > 0 ) { - /* If we timed out, we need to eat a condition signal */ - if ( retval > 0 ) { - SDL_SemWait(cond->wait_sem); - } - /* We always notify the signal thread that we are done */ - SDL_SemPost(cond->wait_done); - - /* Signal handshake complete */ - --cond->signals; - } - --cond->waiting; - SDL_UnlockMutex(cond->lock); - - /* Lock the mutex, as is required by condition variable semantics */ - SDL_LockMutex(mutex); - - return retval; + int retval; + + if (!cond) { + SDL_SetError("Passed a NULL condition variable"); + return -1; + } + + /* Obtain the protection mutex, and increment the number of waiters. + This allows the signal mechanism to only perform a signal if there + are waiting threads. + */ + SDL_LockMutex(cond->lock); + ++cond->waiting; + SDL_UnlockMutex(cond->lock); + + /* Unlock the mutex, as is required by condition variable semantics */ + SDL_UnlockMutex(mutex); + + /* Wait for a signal */ + if (ms == SDL_MUTEX_MAXWAIT) { + retval = SDL_SemWait(cond->wait_sem); + } else { + retval = SDL_SemWaitTimeout(cond->wait_sem, ms); + } + + /* Let the signaler know we have completed the wait, otherwise + the signaler can race ahead and get the condition semaphore + if we are stopped between the mutex unlock and semaphore wait, + giving a deadlock. See the following URL for details: + http://www-classic.be.com/aboutbe/benewsletter/volume_III/Issue40.html + */ + SDL_LockMutex(cond->lock); + if (cond->signals > 0) { + /* If we timed out, we need to eat a condition signal */ + if (retval > 0) { + SDL_SemWait(cond->wait_sem); + } + /* We always notify the signal thread that we are done */ + SDL_SemPost(cond->wait_done); + + /* Signal handshake complete */ + --cond->signals; + } + --cond->waiting; + SDL_UnlockMutex(cond->lock); + + /* Lock the mutex, as is required by condition variable semantics */ + SDL_LockMutex(mutex); + + return retval; } /* Wait on the condition variable forever */ -int SDL_CondWait(SDL_cond *cond, SDL_mutex *mutex) +int +SDL_CondWait(SDL_cond * cond, SDL_mutex * mutex) { - return SDL_CondWaitTimeout(cond, mutex, SDL_MUTEX_MAXWAIT); + return SDL_CondWaitTimeout(cond, mutex, SDL_MUTEX_MAXWAIT); } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/thread/generic/SDL_sysmutex.c b/src/thread/generic/SDL_sysmutex.c index 18099d24d..763d0f41f 100644 --- a/src/thread/generic/SDL_sysmutex.c +++ b/src/thread/generic/SDL_sysmutex.c @@ -27,103 +27,110 @@ #include "SDL_systhread_c.h" -struct SDL_mutex { - int recursive; - Uint32 owner; - SDL_sem *sem; +struct SDL_mutex +{ + int recursive; + Uint32 owner; + SDL_sem *sem; }; /* Create a mutex */ -SDL_mutex *SDL_CreateMutex(void) +SDL_mutex * +SDL_CreateMutex(void) { - SDL_mutex *mutex; - - /* Allocate mutex memory */ - mutex = (SDL_mutex *)SDL_malloc(sizeof(*mutex)); - if ( mutex ) { - /* Create the mutex semaphore, with initial value 1 */ - mutex->sem = SDL_CreateSemaphore(1); - mutex->recursive = 0; - mutex->owner = 0; - if ( ! mutex->sem ) { - SDL_free(mutex); - mutex = NULL; - } - } else { - SDL_OutOfMemory(); - } - return mutex; + SDL_mutex *mutex; + + /* Allocate mutex memory */ + mutex = (SDL_mutex *) SDL_malloc(sizeof(*mutex)); + if (mutex) { + /* Create the mutex semaphore, with initial value 1 */ + mutex->sem = SDL_CreateSemaphore(1); + mutex->recursive = 0; + mutex->owner = 0; + if (!mutex->sem) { + SDL_free(mutex); + mutex = NULL; + } + } else { + SDL_OutOfMemory(); + } + return mutex; } /* Free the mutex */ -void SDL_DestroyMutex(SDL_mutex *mutex) +void +SDL_DestroyMutex(SDL_mutex * mutex) { - if ( mutex ) { - if ( mutex->sem ) { - SDL_DestroySemaphore(mutex->sem); - } - SDL_free(mutex); - } + if (mutex) { + if (mutex->sem) { + SDL_DestroySemaphore(mutex->sem); + } + SDL_free(mutex); + } } /* Lock the semaphore */ -int SDL_mutexP(SDL_mutex *mutex) +int +SDL_mutexP(SDL_mutex * mutex) { #if SDL_THREADS_DISABLED - return 0; + return 0; #else - Uint32 this_thread; - - if ( mutex == NULL ) { - SDL_SetError("Passed a NULL mutex"); - return -1; - } - - this_thread = SDL_ThreadID(); - if ( mutex->owner == this_thread ) { - ++mutex->recursive; - } else { - /* The order of operations is important. - We set the locking thread id after we obtain the lock - so unlocks from other threads will fail. - */ - SDL_SemWait(mutex->sem); - mutex->owner = this_thread; - mutex->recursive = 0; - } - - return 0; + Uint32 this_thread; + + if (mutex == NULL) { + SDL_SetError("Passed a NULL mutex"); + return -1; + } + + this_thread = SDL_ThreadID(); + if (mutex->owner == this_thread) { + ++mutex->recursive; + } else { + /* The order of operations is important. + We set the locking thread id after we obtain the lock + so unlocks from other threads will fail. + */ + SDL_SemWait(mutex->sem); + mutex->owner = this_thread; + mutex->recursive = 0; + } + + return 0; #endif /* SDL_THREADS_DISABLED */ } /* Unlock the mutex */ -int SDL_mutexV(SDL_mutex *mutex) +int +SDL_mutexV(SDL_mutex * mutex) { #if SDL_THREADS_DISABLED - return 0; + return 0; #else - if ( mutex == NULL ) { - SDL_SetError("Passed a NULL mutex"); - return -1; - } - - /* If we don't own the mutex, we can't unlock it */ - if ( SDL_ThreadID() != mutex->owner ) { - SDL_SetError("mutex not owned by this thread"); - return -1; - } - - if ( mutex->recursive ) { - --mutex->recursive; - } else { - /* The order of operations is important. - First reset the owner so another thread doesn't lock - the mutex and set the ownership before we reset it, - then release the lock semaphore. - */ - mutex->owner = 0; - SDL_SemPost(mutex->sem); - } - return 0; + if (mutex == NULL) { + SDL_SetError("Passed a NULL mutex"); + return -1; + } + + /* If we don't own the mutex, we can't unlock it */ + if (SDL_ThreadID() != mutex->owner) { + SDL_SetError("mutex not owned by this thread"); + return -1; + } + + if (mutex->recursive) { + --mutex->recursive; + } else { + /* The order of operations is important. + First reset the owner so another thread doesn't lock + the mutex and set the ownership before we reset it, + then release the lock semaphore. + */ + mutex->owner = 0; + SDL_SemPost(mutex->sem); + } + return 0; #endif /* SDL_THREADS_DISABLED */ } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/thread/generic/SDL_sysmutex_c.h b/src/thread/generic/SDL_sysmutex_c.h index 27d55093a..8ab650f13 100644 --- a/src/thread/generic/SDL_sysmutex_c.h +++ b/src/thread/generic/SDL_sysmutex_c.h @@ -20,4 +20,4 @@ slouken@libsdl.org */ #include "SDL_config.h" - +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/thread/generic/SDL_syssem.c b/src/thread/generic/SDL_syssem.c index c3ffd3f25..61e96de5b 100644 --- a/src/thread/generic/SDL_syssem.c +++ b/src/thread/generic/SDL_syssem.c @@ -30,180 +30,195 @@ #if SDL_THREADS_DISABLED -SDL_sem *SDL_CreateSemaphore(Uint32 initial_value) +SDL_sem * +SDL_CreateSemaphore(Uint32 initial_value) { - SDL_SetError("SDL not configured with thread support"); - return (SDL_sem *)0; + SDL_SetError("SDL not configured with thread support"); + return (SDL_sem *) 0; } -void SDL_DestroySemaphore(SDL_sem *sem) +void +SDL_DestroySemaphore(SDL_sem * sem) { - return; + return; } -int SDL_SemTryWait(SDL_sem *sem) +int +SDL_SemTryWait(SDL_sem * sem) { - SDL_SetError("SDL not configured with thread support"); - return -1; + SDL_SetError("SDL not configured with thread support"); + return -1; } -int SDL_SemWaitTimeout(SDL_sem *sem, Uint32 timeout) +int +SDL_SemWaitTimeout(SDL_sem * sem, Uint32 timeout) { - SDL_SetError("SDL not configured with thread support"); - return -1; + SDL_SetError("SDL not configured with thread support"); + return -1; } -int SDL_SemWait(SDL_sem *sem) +int +SDL_SemWait(SDL_sem * sem) { - SDL_SetError("SDL not configured with thread support"); - return -1; + SDL_SetError("SDL not configured with thread support"); + return -1; } -Uint32 SDL_SemValue(SDL_sem *sem) +Uint32 +SDL_SemValue(SDL_sem * sem) { - return 0; + return 0; } -int SDL_SemPost(SDL_sem *sem) +int +SDL_SemPost(SDL_sem * sem) { - SDL_SetError("SDL not configured with thread support"); - return -1; + SDL_SetError("SDL not configured with thread support"); + return -1; } #else struct SDL_semaphore { - Uint32 count; - Uint32 waiters_count; - SDL_mutex *count_lock; - SDL_cond *count_nonzero; + Uint32 count; + Uint32 waiters_count; + SDL_mutex *count_lock; + SDL_cond *count_nonzero; }; -SDL_sem *SDL_CreateSemaphore(Uint32 initial_value) +SDL_sem * +SDL_CreateSemaphore(Uint32 initial_value) { - SDL_sem *sem; - - sem = (SDL_sem *)SDL_malloc(sizeof(*sem)); - if ( ! sem ) { - SDL_OutOfMemory(); - return NULL; - } - sem->count = initial_value; - sem->waiters_count = 0; - - sem->count_lock = SDL_CreateMutex(); - sem->count_nonzero = SDL_CreateCond(); - if ( ! sem->count_lock || ! sem->count_nonzero ) { - SDL_DestroySemaphore(sem); - return NULL; - } - - return sem; + SDL_sem *sem; + + sem = (SDL_sem *) SDL_malloc(sizeof(*sem)); + if (!sem) { + SDL_OutOfMemory(); + return NULL; + } + sem->count = initial_value; + sem->waiters_count = 0; + + sem->count_lock = SDL_CreateMutex(); + sem->count_nonzero = SDL_CreateCond(); + if (!sem->count_lock || !sem->count_nonzero) { + SDL_DestroySemaphore(sem); + return NULL; + } + + return sem; } /* WARNING: You cannot call this function when another thread is using the semaphore. */ -void SDL_DestroySemaphore(SDL_sem *sem) +void +SDL_DestroySemaphore(SDL_sem * sem) { - if ( sem ) { - sem->count = 0xFFFFFFFF; - while ( sem->waiters_count > 0) { - SDL_CondSignal(sem->count_nonzero); - SDL_Delay(10); - } - SDL_DestroyCond(sem->count_nonzero); - if ( sem->count_lock ) { - SDL_mutexP(sem->count_lock); - SDL_mutexV(sem->count_lock); - SDL_DestroyMutex(sem->count_lock); - } - SDL_free(sem); - } + if (sem) { + sem->count = 0xFFFFFFFF; + while (sem->waiters_count > 0) { + SDL_CondSignal(sem->count_nonzero); + SDL_Delay(10); + } + SDL_DestroyCond(sem->count_nonzero); + if (sem->count_lock) { + SDL_mutexP(sem->count_lock); + SDL_mutexV(sem->count_lock); + SDL_DestroyMutex(sem->count_lock); + } + SDL_free(sem); + } } -int SDL_SemTryWait(SDL_sem *sem) +int +SDL_SemTryWait(SDL_sem * sem) { - int retval; - - if ( ! sem ) { - SDL_SetError("Passed a NULL semaphore"); - return -1; - } - - retval = SDL_MUTEX_TIMEDOUT; - SDL_LockMutex(sem->count_lock); - if ( sem->count > 0 ) { - --sem->count; - retval = 0; - } - SDL_UnlockMutex(sem->count_lock); - - return retval; + int retval; + + if (!sem) { + SDL_SetError("Passed a NULL semaphore"); + return -1; + } + + retval = SDL_MUTEX_TIMEDOUT; + SDL_LockMutex(sem->count_lock); + if (sem->count > 0) { + --sem->count; + retval = 0; + } + SDL_UnlockMutex(sem->count_lock); + + return retval; } -int SDL_SemWaitTimeout(SDL_sem *sem, Uint32 timeout) +int +SDL_SemWaitTimeout(SDL_sem * sem, Uint32 timeout) { - int retval; - - if ( ! sem ) { - SDL_SetError("Passed a NULL semaphore"); - return -1; - } - - /* A timeout of 0 is an easy case */ - if ( timeout == 0 ) { - return SDL_SemTryWait(sem); - } - - SDL_LockMutex(sem->count_lock); - ++sem->waiters_count; - retval = 0; - while ( (sem->count == 0) && (retval != SDL_MUTEX_TIMEDOUT) ) { - retval = SDL_CondWaitTimeout(sem->count_nonzero, - sem->count_lock, timeout); - } - --sem->waiters_count; - --sem->count; - SDL_UnlockMutex(sem->count_lock); - - return retval; + int retval; + + if (!sem) { + SDL_SetError("Passed a NULL semaphore"); + return -1; + } + + /* A timeout of 0 is an easy case */ + if (timeout == 0) { + return SDL_SemTryWait(sem); + } + + SDL_LockMutex(sem->count_lock); + ++sem->waiters_count; + retval = 0; + while ((sem->count == 0) && (retval != SDL_MUTEX_TIMEDOUT)) { + retval = SDL_CondWaitTimeout(sem->count_nonzero, + sem->count_lock, timeout); + } + --sem->waiters_count; + --sem->count; + SDL_UnlockMutex(sem->count_lock); + + return retval; } -int SDL_SemWait(SDL_sem *sem) +int +SDL_SemWait(SDL_sem * sem) { - return SDL_SemWaitTimeout(sem, SDL_MUTEX_MAXWAIT); + return SDL_SemWaitTimeout(sem, SDL_MUTEX_MAXWAIT); } -Uint32 SDL_SemValue(SDL_sem *sem) +Uint32 +SDL_SemValue(SDL_sem * sem) { - Uint32 value; - - value = 0; - if ( sem ) { - SDL_LockMutex(sem->count_lock); - value = sem->count; - SDL_UnlockMutex(sem->count_lock); - } - return value; + Uint32 value; + + value = 0; + if (sem) { + SDL_LockMutex(sem->count_lock); + value = sem->count; + SDL_UnlockMutex(sem->count_lock); + } + return value; } -int SDL_SemPost(SDL_sem *sem) +int +SDL_SemPost(SDL_sem * sem) { - if ( ! sem ) { - SDL_SetError("Passed a NULL semaphore"); - return -1; - } - - SDL_LockMutex(sem->count_lock); - if ( sem->waiters_count > 0 ) { - SDL_CondSignal(sem->count_nonzero); - } - ++sem->count; - SDL_UnlockMutex(sem->count_lock); - - return 0; + if (!sem) { + SDL_SetError("Passed a NULL semaphore"); + return -1; + } + + SDL_LockMutex(sem->count_lock); + if (sem->waiters_count > 0) { + SDL_CondSignal(sem->count_nonzero); + } + ++sem->count; + SDL_UnlockMutex(sem->count_lock); + + return 0; } #endif /* SDL_THREADS_DISABLED */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/thread/generic/SDL_systhread.c b/src/thread/generic/SDL_systhread.c index 6739ad49d..3b766911e 100644 --- a/src/thread/generic/SDL_systhread.c +++ b/src/thread/generic/SDL_systhread.c @@ -26,29 +26,35 @@ #include "SDL_thread.h" #include "../SDL_systhread.h" -int SDL_SYS_CreateThread(SDL_Thread *thread, void *args) +int +SDL_SYS_CreateThread(SDL_Thread * thread, void *args) { - SDL_SetError("Threads are not supported on this platform"); - return(-1); + SDL_SetError("Threads are not supported on this platform"); + return (-1); } -void SDL_SYS_SetupThread(void) +void +SDL_SYS_SetupThread(void) { - return; + return; } -Uint32 SDL_ThreadID(void) +Uint32 +SDL_ThreadID(void) { - return(0); + return (0); } -void SDL_SYS_WaitThread(SDL_Thread *thread) +void +SDL_SYS_WaitThread(SDL_Thread * thread) { - return; + return; } -void SDL_SYS_KillThread(SDL_Thread *thread) +void +SDL_SYS_KillThread(SDL_Thread * thread) { - return; + return; } +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/thread/generic/SDL_systhread_c.h b/src/thread/generic/SDL_systhread_c.h index 7e876b066..a7d19d035 100644 --- a/src/thread/generic/SDL_systhread_c.h +++ b/src/thread/generic/SDL_systhread_c.h @@ -23,3 +23,4 @@ /* Stub until we implement threads on this platform */ typedef int SYS_ThreadHandle; +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/thread/irix/SDL_syssem.c b/src/thread/irix/SDL_syssem.c index 8b3311b58..00ed025a7 100644 --- a/src/thread/irix/SDL_syssem.c +++ b/src/thread/irix/SDL_syssem.c @@ -36,8 +36,9 @@ #include "SDL_thread.h" -struct SDL_semaphore { - int id; +struct SDL_semaphore +{ + int id; }; /* Not defined by many operating systems, use configure to detect */ @@ -52,168 +53,178 @@ union semun { */ static struct sembuf op_trywait[2] = { - { 0, -1, (IPC_NOWAIT|SEM_UNDO) } /* Decrement semaphore, no block */ + {0, -1, (IPC_NOWAIT | SEM_UNDO)} /* Decrement semaphore, no block */ }; static struct sembuf op_wait[2] = { - { 0, -1, SEM_UNDO } /* Decrement semaphore */ + {0, -1, SEM_UNDO} /* Decrement semaphore */ }; static struct sembuf op_post[1] = { - { 0, 1, (IPC_NOWAIT|SEM_UNDO) } /* Increment semaphore */ + {0, 1, (IPC_NOWAIT | SEM_UNDO)} /* Increment semaphore */ }; /* Create a blockable semaphore */ -SDL_sem *SDL_CreateSemaphore(Uint32 initial_value) +SDL_sem * +SDL_CreateSemaphore(Uint32 initial_value) { - extern int _creating_thread_lock; /* SDL_threads.c */ - SDL_sem *sem; - union semun init; - - sem = (SDL_sem *)SDL_malloc(sizeof(*sem)); - if ( sem == NULL ) { - SDL_OutOfMemory(); - return(NULL); - } - sem->id = semget(IPC_PRIVATE, 1, (0600|IPC_CREAT)); - if ( sem->id < 0 ) { - SDL_SetError("Couldn't create semaphore"); - SDL_free(sem); - return(NULL); - } - init.val = initial_value; /* Initialize semaphore */ - semctl(sem->id, 0, SETVAL, init); - return(sem); + extern int _creating_thread_lock; /* SDL_threads.c */ + SDL_sem *sem; + union semun init; + + sem = (SDL_sem *) SDL_malloc(sizeof(*sem)); + if (sem == NULL) { + SDL_OutOfMemory(); + return (NULL); + } + sem->id = semget(IPC_PRIVATE, 1, (0600 | IPC_CREAT)); + if (sem->id < 0) { + SDL_SetError("Couldn't create semaphore"); + SDL_free(sem); + return (NULL); + } + init.val = initial_value; /* Initialize semaphore */ + semctl(sem->id, 0, SETVAL, init); + return (sem); } -void SDL_DestroySemaphore(SDL_sem *sem) +void +SDL_DestroySemaphore(SDL_sem * sem) { - if ( sem ) { + if (sem) { #ifdef __IRIX__ - semctl(sem->id, 0, IPC_RMID); + semctl(sem->id, 0, IPC_RMID); #else - union semun dummy; - dummy.val = 0; - semctl(sem->id, 0, IPC_RMID, dummy); + union semun dummy; + dummy.val = 0; + semctl(sem->id, 0, IPC_RMID, dummy); #endif - SDL_free(sem); - } + SDL_free(sem); + } } -int SDL_SemTryWait(SDL_sem *sem) +int +SDL_SemTryWait(SDL_sem * sem) { - int retval; + int retval; - if ( ! sem ) { - SDL_SetError("Passed a NULL semaphore"); - return -1; - } + if (!sem) { + SDL_SetError("Passed a NULL semaphore"); + return -1; + } - retval = 0; + retval = 0; tryagain: - if ( semop(sem->id, op_trywait, 1) < 0 ) { - if ( errno == EINTR ) { - goto tryagain; - } - retval = SDL_MUTEX_TIMEDOUT; - } - return retval; + if (semop(sem->id, op_trywait, 1) < 0) { + if (errno == EINTR) { + goto tryagain; + } + retval = SDL_MUTEX_TIMEDOUT; + } + return retval; } -int SDL_SemWait(SDL_sem *sem) +int +SDL_SemWait(SDL_sem * sem) { - int retval; + int retval; - if ( ! sem ) { - SDL_SetError("Passed a NULL semaphore"); - return -1; - } + if (!sem) { + SDL_SetError("Passed a NULL semaphore"); + return -1; + } - retval = 0; + retval = 0; tryagain: - if ( semop(sem->id, op_wait, 1) < 0 ) { - if ( errno == EINTR ) { - goto tryagain; - } - SDL_SetError("Semaphore operation error"); - retval = -1; - } - return retval; + if (semop(sem->id, op_wait, 1) < 0) { + if (errno == EINTR) { + goto tryagain; + } + SDL_SetError("Semaphore operation error"); + retval = -1; + } + return retval; } -int SDL_SemWaitTimeout(SDL_sem *sem, Uint32 timeout) +int +SDL_SemWaitTimeout(SDL_sem * sem, Uint32 timeout) { - int retval; - - if ( ! sem ) { - SDL_SetError("Passed a NULL semaphore"); - return -1; - } - - /* Try the easy cases first */ - if ( timeout == 0 ) { - return SDL_SemTryWait(sem); - } - if ( timeout == SDL_MUTEX_MAXWAIT ) { - return SDL_SemWait(sem); - } - - /* Ack! We have to busy wait... */ - timeout += SDL_GetTicks(); - do { - retval = SDL_SemTryWait(sem); - if ( retval == 0 ) { - break; - } - SDL_Delay(1); - } while ( SDL_GetTicks() < timeout ); - - return retval; + int retval; + + if (!sem) { + SDL_SetError("Passed a NULL semaphore"); + return -1; + } + + /* Try the easy cases first */ + if (timeout == 0) { + return SDL_SemTryWait(sem); + } + if (timeout == SDL_MUTEX_MAXWAIT) { + return SDL_SemWait(sem); + } + + /* Ack! We have to busy wait... */ + timeout += SDL_GetTicks(); + do { + retval = SDL_SemTryWait(sem); + if (retval == 0) { + break; + } + SDL_Delay(1); + } + while (SDL_GetTicks() < timeout); + + return retval; } -Uint32 SDL_SemValue(SDL_sem *sem) +Uint32 +SDL_SemValue(SDL_sem * sem) { - int semval; - Uint32 value; - - value = 0; - if ( sem ) { - tryagain: + int semval; + Uint32 value; + + value = 0; + if (sem) { + tryagain: #ifdef __IRIX__ - semval = semctl(sem->id, 0, GETVAL); + semval = semctl(sem->id, 0, GETVAL); #else - { - union semun arg; - arg.val = 0; - semval = semctl(sem->id, 0, GETVAL, arg); - } + { + union semun arg; + arg.val = 0; + semval = semctl(sem->id, 0, GETVAL, arg); + } #endif - if ( semval < 0 ) { - if ( errno == EINTR ) { - goto tryagain; - } - } else { - value = (Uint32)semval; - } - } - return value; + if (semval < 0) { + if (errno == EINTR) { + goto tryagain; + } + } else { + value = (Uint32) semval; + } + } + return value; } -int SDL_SemPost(SDL_sem *sem) +int +SDL_SemPost(SDL_sem * sem) { - int retval; + int retval; - if ( ! sem ) { - SDL_SetError("Passed a NULL semaphore"); - return -1; - } + if (!sem) { + SDL_SetError("Passed a NULL semaphore"); + return -1; + } - retval = 0; + retval = 0; tryagain: - if ( semop(sem->id, op_post, 1) < 0 ) { - if ( errno == EINTR ) { - goto tryagain; - } - SDL_SetError("Semaphore operation error"); - retval = -1; - } - return retval; + if (semop(sem->id, op_post, 1) < 0) { + if (errno == EINTR) { + goto tryagain; + } + SDL_SetError("Semaphore operation error"); + retval = -1; + } + return retval; } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/thread/irix/SDL_systhread.c b/src/thread/irix/SDL_systhread.c index 16a865966..24ec87965 100644 --- a/src/thread/irix/SDL_systhread.c +++ b/src/thread/irix/SDL_systhread.c @@ -34,52 +34,58 @@ static int sig_list[] = { - SIGHUP, SIGINT, SIGQUIT, SIGPIPE, SIGALRM, SIGTERM, SIGCLD, SIGWINCH, - SIGVTALRM, SIGPROF, 0 + SIGHUP, SIGINT, SIGQUIT, SIGPIPE, SIGALRM, SIGTERM, SIGCLD, SIGWINCH, + SIGVTALRM, SIGPROF, 0 }; -int SDL_SYS_CreateThread(SDL_Thread *thread, void *args) +int +SDL_SYS_CreateThread(SDL_Thread * thread, void *args) { - /* Create the thread and go! */ - if ( sproc(SDL_RunThread, PR_SALL, args) < 0 ) { - SDL_SetError("Not enough resources to create thread"); - return(-1); - } - return(0); + /* Create the thread and go! */ + if (sproc(SDL_RunThread, PR_SALL, args) < 0) { + SDL_SetError("Not enough resources to create thread"); + return (-1); + } + return (0); } -void SDL_SYS_SetupThread(void) +void +SDL_SYS_SetupThread(void) { - int i; - sigset_t mask; - - /* Mask asynchronous signals for this thread */ - sigemptyset(&mask); - for ( i=0; sig_list[i]; ++i ) { - sigaddset(&mask, sig_list[i]); - } - sigprocmask(SIG_BLOCK, &mask, NULL); + int i; + sigset_t mask; + + /* Mask asynchronous signals for this thread */ + sigemptyset(&mask); + for (i = 0; sig_list[i]; ++i) { + sigaddset(&mask, sig_list[i]); + } + sigprocmask(SIG_BLOCK, &mask, NULL); } /* WARNING: This may not work for systems with 64-bit pid_t */ -Uint32 SDL_ThreadID(void) +Uint32 +SDL_ThreadID(void) { - return((Uint32)getpid()); + return ((Uint32) getpid()); } /* WARNING: This may not work for systems with 64-bit pid_t */ -void SDL_WaitThread(SDL_Thread *thread, int *status) +void +SDL_WaitThread(SDL_Thread * thread, int *status) { - errno = 0; - while ( errno != ECHILD ) { - waitpid(thread->handle, NULL, 0); - } + errno = 0; + while (errno != ECHILD) { + waitpid(thread->handle, NULL, 0); + } } /* WARNING: This may not work for systems with 64-bit pid_t */ -void SDL_KillThread(SDL_Thread *thread) +void +SDL_KillThread(SDL_Thread * thread) { - kill(thread->handle, SIGKILL); + kill(thread->handle, SIGKILL); } +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/thread/irix/SDL_systhread_c.h b/src/thread/irix/SDL_systhread_c.h index 76e141a7f..0541231d9 100644 --- a/src/thread/irix/SDL_systhread_c.h +++ b/src/thread/irix/SDL_systhread_c.h @@ -24,4 +24,4 @@ #include typedef pid_t SYS_ThreadHandle; - +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/thread/os2/SDL_syscond.c b/src/thread/os2/SDL_syscond.c index 25577e40d..48a0540f0 100644 --- a/src/thread/os2/SDL_syscond.c +++ b/src/thread/os2/SDL_syscond.c @@ -31,107 +31,111 @@ struct SDL_cond { - SDL_mutex *lock; - int waiting; - int signals; - SDL_sem *wait_sem; - SDL_sem *wait_done; + SDL_mutex *lock; + int waiting; + int signals; + SDL_sem *wait_sem; + SDL_sem *wait_done; }; /* Create a condition variable */ -DECLSPEC SDL_cond * SDLCALL SDL_CreateCond(void) +DECLSPEC SDL_cond *SDLCALL +SDL_CreateCond(void) { - SDL_cond *cond; - - cond = (SDL_cond *) SDL_malloc(sizeof(SDL_cond)); - if ( cond ) { - cond->lock = SDL_CreateMutex(); - cond->wait_sem = SDL_CreateSemaphore(0); - cond->wait_done = SDL_CreateSemaphore(0); - cond->waiting = cond->signals = 0; - if ( ! cond->lock || ! cond->wait_sem || ! cond->wait_done ) { - SDL_DestroyCond(cond); - cond = NULL; - } - } else { - SDL_OutOfMemory(); - } - return(cond); + SDL_cond *cond; + + cond = (SDL_cond *) SDL_malloc(sizeof(SDL_cond)); + if (cond) { + cond->lock = SDL_CreateMutex(); + cond->wait_sem = SDL_CreateSemaphore(0); + cond->wait_done = SDL_CreateSemaphore(0); + cond->waiting = cond->signals = 0; + if (!cond->lock || !cond->wait_sem || !cond->wait_done) { + SDL_DestroyCond(cond); + cond = NULL; + } + } else { + SDL_OutOfMemory(); + } + return (cond); } /* Destroy a condition variable */ -DECLSPEC void SDLCALL SDL_DestroyCond(SDL_cond *cond) +DECLSPEC void SDLCALL +SDL_DestroyCond(SDL_cond * cond) { - if ( cond ) { - if ( cond->wait_sem ) { - SDL_DestroySemaphore(cond->wait_sem); - } - if ( cond->wait_done ) { - SDL_DestroySemaphore(cond->wait_done); - } - if ( cond->lock ) { - SDL_DestroyMutex(cond->lock); - } - SDL_free(cond); - } + if (cond) { + if (cond->wait_sem) { + SDL_DestroySemaphore(cond->wait_sem); + } + if (cond->wait_done) { + SDL_DestroySemaphore(cond->wait_done); + } + if (cond->lock) { + SDL_DestroyMutex(cond->lock); + } + SDL_free(cond); + } } /* Restart one of the threads that are waiting on the condition variable */ -DECLSPEC int SDLCALL SDL_CondSignal(SDL_cond *cond) +DECLSPEC int SDLCALL +SDL_CondSignal(SDL_cond * cond) { - if ( ! cond ) { - SDL_SetError("Passed a NULL condition variable"); - return -1; - } - - /* If there are waiting threads not already signalled, then - signal the condition and wait for the thread to respond. - */ - SDL_LockMutex(cond->lock); - if ( cond->waiting > cond->signals ) { - ++cond->signals; - SDL_SemPost(cond->wait_sem); - SDL_UnlockMutex(cond->lock); - SDL_SemWait(cond->wait_done); - } else { - SDL_UnlockMutex(cond->lock); - } - - return 0; + if (!cond) { + SDL_SetError("Passed a NULL condition variable"); + return -1; + } + + /* If there are waiting threads not already signalled, then + signal the condition and wait for the thread to respond. + */ + SDL_LockMutex(cond->lock); + if (cond->waiting > cond->signals) { + ++cond->signals; + SDL_SemPost(cond->wait_sem); + SDL_UnlockMutex(cond->lock); + SDL_SemWait(cond->wait_done); + } else { + SDL_UnlockMutex(cond->lock); + } + + return 0; } /* Restart all threads that are waiting on the condition variable */ -DECLSPEC int SDLCALL SDL_CondBroadcast(SDL_cond *cond) +DECLSPEC int SDLCALL +SDL_CondBroadcast(SDL_cond * cond) { - if ( ! cond ) { - SDL_SetError("Passed a NULL condition variable"); - return -1; - } - - /* If there are waiting threads not already signalled, then - signal the condition and wait for the thread to respond. - */ - SDL_LockMutex(cond->lock); - if ( cond->waiting > cond->signals ) { - int i, num_waiting; - - num_waiting = (cond->waiting - cond->signals); - cond->signals = cond->waiting; - for ( i=0; iwait_sem); - } - /* Now all released threads are blocked here, waiting for us. - Collect them all (and win fabulous prizes!) :-) - */ - SDL_UnlockMutex(cond->lock); - for ( i=0; iwait_done); - } - } else { - SDL_UnlockMutex(cond->lock); - } - - return 0; + if (!cond) { + SDL_SetError("Passed a NULL condition variable"); + return -1; + } + + /* If there are waiting threads not already signalled, then + signal the condition and wait for the thread to respond. + */ + SDL_LockMutex(cond->lock); + if (cond->waiting > cond->signals) { + int i, num_waiting; + + num_waiting = (cond->waiting - cond->signals); + cond->signals = cond->waiting; + for (i = 0; i < num_waiting; ++i) { + SDL_SemPost(cond->wait_sem); + } + /* Now all released threads are blocked here, waiting for us. + Collect them all (and win fabulous prizes!) :-) + */ + SDL_UnlockMutex(cond->lock); + for (i = 0; i < num_waiting; ++i) { + SDL_SemWait(cond->wait_done); + } + } else { + SDL_UnlockMutex(cond->lock); + } + + return 0; } /* Wait on the condition variable for at most 'ms' milliseconds. @@ -154,62 +158,66 @@ Thread B: ... SDL_UnlockMutex(lock); */ -DECLSPEC int SDLCALL SDL_CondWaitTimeout(SDL_cond *cond, SDL_mutex *mutex, Uint32 ms) +DECLSPEC int SDLCALL +SDL_CondWaitTimeout(SDL_cond * cond, SDL_mutex * mutex, Uint32 ms) { - int retval; - - if ( ! cond ) { - SDL_SetError("Passed a NULL condition variable"); - return -1; - } - - /* Obtain the protection mutex, and increment the number of waiters. - This allows the signal mechanism to only perform a signal if there - are waiting threads. - */ - SDL_LockMutex(cond->lock); - ++cond->waiting; - SDL_UnlockMutex(cond->lock); - - /* Unlock the mutex, as is required by condition variable semantics */ - SDL_UnlockMutex(mutex); - - /* Wait for a signal */ - if ( ms == SDL_MUTEX_MAXWAIT ) { - retval = SDL_SemWait(cond->wait_sem); - } else { - retval = SDL_SemWaitTimeout(cond->wait_sem, ms); - } - - /* Let the signaler know we have completed the wait, otherwise - the signaler can race ahead and get the condition semaphore - if we are stopped between the mutex unlock and semaphore wait, - giving a deadlock. See the following URL for details: - http://www-classic.be.com/aboutbe/benewsletter/volume_III/Issue40.html - */ - SDL_LockMutex(cond->lock); - if ( cond->signals > 0 ) { - /* If we timed out, we need to eat a condition signal */ - if ( retval > 0 ) { - SDL_SemWait(cond->wait_sem); - } - /* We always notify the signal thread that we are done */ - SDL_SemPost(cond->wait_done); - - /* Signal handshake complete */ - --cond->signals; - } - --cond->waiting; - SDL_UnlockMutex(cond->lock); - - /* Lock the mutex, as is required by condition variable semantics */ - SDL_LockMutex(mutex); - - return retval; + int retval; + + if (!cond) { + SDL_SetError("Passed a NULL condition variable"); + return -1; + } + + /* Obtain the protection mutex, and increment the number of waiters. + This allows the signal mechanism to only perform a signal if there + are waiting threads. + */ + SDL_LockMutex(cond->lock); + ++cond->waiting; + SDL_UnlockMutex(cond->lock); + + /* Unlock the mutex, as is required by condition variable semantics */ + SDL_UnlockMutex(mutex); + + /* Wait for a signal */ + if (ms == SDL_MUTEX_MAXWAIT) { + retval = SDL_SemWait(cond->wait_sem); + } else { + retval = SDL_SemWaitTimeout(cond->wait_sem, ms); + } + + /* Let the signaler know we have completed the wait, otherwise + the signaler can race ahead and get the condition semaphore + if we are stopped between the mutex unlock and semaphore wait, + giving a deadlock. See the following URL for details: + http://www-classic.be.com/aboutbe/benewsletter/volume_III/Issue40.html + */ + SDL_LockMutex(cond->lock); + if (cond->signals > 0) { + /* If we timed out, we need to eat a condition signal */ + if (retval > 0) { + SDL_SemWait(cond->wait_sem); + } + /* We always notify the signal thread that we are done */ + SDL_SemPost(cond->wait_done); + + /* Signal handshake complete */ + --cond->signals; + } + --cond->waiting; + SDL_UnlockMutex(cond->lock); + + /* Lock the mutex, as is required by condition variable semantics */ + SDL_LockMutex(mutex); + + return retval; } /* Wait on the condition variable forever */ -DECLSPEC int SDLCALL SDL_CondWait(SDL_cond *cond, SDL_mutex *mutex) +DECLSPEC int SDLCALL +SDL_CondWait(SDL_cond * cond, SDL_mutex * mutex) { - return SDL_CondWaitTimeout(cond, mutex, SDL_MUTEX_MAXWAIT); + return SDL_CondWaitTimeout(cond, mutex, SDL_MUTEX_MAXWAIT); } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/thread/os2/SDL_syscond_c.h b/src/thread/os2/SDL_syscond_c.h index 27d55093a..8ab650f13 100644 --- a/src/thread/os2/SDL_syscond_c.h +++ b/src/thread/os2/SDL_syscond_c.h @@ -20,4 +20,4 @@ slouken@libsdl.org */ #include "SDL_config.h" - +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/thread/os2/SDL_sysmutex.c b/src/thread/os2/SDL_sysmutex.c index ea75ccee0..54fdd87a4 100644 --- a/src/thread/os2/SDL_sysmutex.c +++ b/src/thread/os2/SDL_sysmutex.c @@ -30,79 +30,78 @@ #include "SDL_mutex.h" -struct SDL_mutex { - HMTX hmtxID; +struct SDL_mutex +{ + HMTX hmtxID; }; /* Create a mutex */ -DECLSPEC SDL_mutex * SDLCALL SDL_CreateMutex(void) +DECLSPEC SDL_mutex *SDLCALL +SDL_CreateMutex(void) { - SDL_mutex *mutex; - APIRET ulrc; + SDL_mutex *mutex; + APIRET ulrc; - /* Allocate mutex memory */ - mutex = (SDL_mutex *)SDL_malloc(sizeof(*mutex)); - if (mutex) - { - /* Create the mutex, with initial value signaled */ - ulrc = DosCreateMutexSem(NULL, // Create unnamed semaphore - &(mutex->hmtxID), // Pointer to handle - 0L, // Flags: create it private (not shared) - FALSE); // Initial value: unowned - if (ulrc!=NO_ERROR) - { - SDL_SetError("Couldn't create mutex"); - SDL_free(mutex); - mutex = NULL; + /* Allocate mutex memory */ + mutex = (SDL_mutex *) SDL_malloc(sizeof(*mutex)); + if (mutex) { + /* Create the mutex, with initial value signaled */ + ulrc = DosCreateMutexSem(NULL, // Create unnamed semaphore + &(mutex->hmtxID), // Pointer to handle + 0L, // Flags: create it private (not shared) + FALSE); // Initial value: unowned + if (ulrc != NO_ERROR) { + SDL_SetError("Couldn't create mutex"); + SDL_free(mutex); + mutex = NULL; + } + } else { + SDL_OutOfMemory(); } - } else { - SDL_OutOfMemory(); - } - return(mutex); + return (mutex); } /* Free the mutex */ -DECLSPEC void SDLCALL SDL_DestroyMutex(SDL_mutex *mutex) +DECLSPEC void SDLCALL +SDL_DestroyMutex(SDL_mutex * mutex) { - if ( mutex ) - { - if ( mutex->hmtxID ) - { - DosCloseMutexSem(mutex->hmtxID); - mutex->hmtxID = 0; + if (mutex) { + if (mutex->hmtxID) { + DosCloseMutexSem(mutex->hmtxID); + mutex->hmtxID = 0; + } + SDL_free(mutex); } - SDL_free(mutex); - } } /* Lock the mutex */ -DECLSPEC int SDLCALL SDL_mutexP(SDL_mutex *mutex) +DECLSPEC int SDLCALL +SDL_mutexP(SDL_mutex * mutex) { - if ( mutex == NULL ) - { - SDL_SetError("Passed a NULL mutex"); - return -1; - } - if ( DosRequestMutexSem(mutex->hmtxID, SEM_INDEFINITE_WAIT) != NO_ERROR ) - { - SDL_SetError("Couldn't wait on mutex"); - return -1; - } - return(0); + if (mutex == NULL) { + SDL_SetError("Passed a NULL mutex"); + return -1; + } + if (DosRequestMutexSem(mutex->hmtxID, SEM_INDEFINITE_WAIT) != NO_ERROR) { + SDL_SetError("Couldn't wait on mutex"); + return -1; + } + return (0); } /* Unlock the mutex */ -DECLSPEC int SDLCALL SDL_mutexV(SDL_mutex *mutex) +DECLSPEC int SDLCALL +SDL_mutexV(SDL_mutex * mutex) { - if ( mutex == NULL ) - { - SDL_SetError("Passed a NULL mutex"); - return -1; - } - if ( DosReleaseMutexSem(mutex->hmtxID) != NO_ERROR ) - { - SDL_SetError("Couldn't release mutex"); - return -1; - } - return(0); + if (mutex == NULL) { + SDL_SetError("Passed a NULL mutex"); + return -1; + } + if (DosReleaseMutexSem(mutex->hmtxID) != NO_ERROR) { + SDL_SetError("Couldn't release mutex"); + return -1; + } + return (0); } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/thread/os2/SDL_syssem.c b/src/thread/os2/SDL_syssem.c index d44593403..689845f8c 100644 --- a/src/thread/os2/SDL_syssem.c +++ b/src/thread/os2/SDL_syssem.c @@ -32,161 +32,163 @@ #include "SDL_timer.h" -struct SDL_semaphore { - HMTX id; - HEV changed; - Uint32 value; +struct SDL_semaphore +{ + HMTX id; + HEV changed; + Uint32 value; }; /* Create a semaphore */ -DECLSPEC SDL_sem * SDLCALL SDL_CreateSemaphore(Uint32 initial_value) +DECLSPEC SDL_sem *SDLCALL +SDL_CreateSemaphore(Uint32 initial_value) { - SDL_sem *sem; - ULONG ulrc; - - /* Allocate sem memory */ - sem = (SDL_sem *)SDL_malloc(sizeof(*sem)); - if ( sem ) { - /* Create the mutex semaphore */ - ulrc = DosCreateMutexSem(NULL,&(sem->id),0,TRUE); - if ( ulrc ) { - SDL_SetError("Couldn't create semaphore"); - SDL_free(sem); - sem = NULL; - } else - { - DosCreateEventSem(NULL, &(sem->changed), 0, FALSE); - sem->value = initial_value; - DosReleaseMutexSem(sem->id); - } + SDL_sem *sem; + ULONG ulrc; + + /* Allocate sem memory */ + sem = (SDL_sem *) SDL_malloc(sizeof(*sem)); + if (sem) { + /* Create the mutex semaphore */ + ulrc = DosCreateMutexSem(NULL, &(sem->id), 0, TRUE); + if (ulrc) { + SDL_SetError("Couldn't create semaphore"); + SDL_free(sem); + sem = NULL; } else { - SDL_OutOfMemory(); + DosCreateEventSem(NULL, &(sem->changed), 0, FALSE); + sem->value = initial_value; + DosReleaseMutexSem(sem->id); } - return(sem); + } else { + SDL_OutOfMemory(); + } + return (sem); } /* Free the semaphore */ -DECLSPEC void SDLCALL SDL_DestroySemaphore(SDL_sem *sem) +DECLSPEC void SDLCALL +SDL_DestroySemaphore(SDL_sem * sem) { - if ( sem ) { - if ( sem->id ) { - DosCloseEventSem(sem->changed); - DosCloseMutexSem(sem->id); - sem->id = 0; - } - SDL_free(sem); + if (sem) { + if (sem->id) { + DosCloseEventSem(sem->changed); + DosCloseMutexSem(sem->id); + sem->id = 0; } + SDL_free(sem); + } } -DECLSPEC int SDLCALL SDL_SemWaitTimeout(SDL_sem *sem, Uint32 timeout) +DECLSPEC int SDLCALL +SDL_SemWaitTimeout(SDL_sem * sem, Uint32 timeout) { - ULONG ulrc; + ULONG ulrc; - if ( ! sem ) { - SDL_SetError("Passed a NULL sem"); - return -1; - } + if (!sem) { + SDL_SetError("Passed a NULL sem"); + return -1; + } - if ( timeout == SDL_MUTEX_MAXWAIT ) { - while (1) { - ulrc = DosRequestMutexSem(sem->id, SEM_INDEFINITE_WAIT); - if (ulrc) { - /* if error waiting mutex */ - SDL_SetError("DosRequestMutexSem() failed"); - return -1; - } else if (sem->value) { - sem->value--; - DosReleaseMutexSem(sem->id); - return 0; - } else { - ULONG ulPostCount; - DosResetEventSem(sem->changed, &ulPostCount); - DosReleaseMutexSem(sem->id); - /* continue waiting until somebody posts the semaphore */ - DosWaitEventSem(sem->changed, SEM_INDEFINITE_WAIT); - } - } - } else - if ( timeout == 0 ) - { + if (timeout == SDL_MUTEX_MAXWAIT) { + while (1) { ulrc = DosRequestMutexSem(sem->id, SEM_INDEFINITE_WAIT); - if (ulrc==NO_ERROR) - { - if (sem->value) - { - sem->value--; - DosReleaseMutexSem(sem->id); - return 0; - } else - { - DosReleaseMutexSem(sem->id); - return SDL_MUTEX_TIMEDOUT; - } - } else - { + if (ulrc) { + /* if error waiting mutex */ SDL_SetError("DosRequestMutexSem() failed"); return -1; - } - } else { - ulrc = DosRequestMutexSem(sem->id, SEM_INDEFINITE_WAIT); - if (ulrc) { - /* if error waiting mutex */ - SDL_SetError("DosRequestMutexSem() failed"); - return -1; - } else - if (sem->value) { + } else if (sem->value) { sem->value--; DosReleaseMutexSem(sem->id); return 0; - } else { + } else { ULONG ulPostCount; DosResetEventSem(sem->changed, &ulPostCount); DosReleaseMutexSem(sem->id); /* continue waiting until somebody posts the semaphore */ - ulrc = DosWaitEventSem(sem->changed, timeout); - if (ulrc==NO_ERROR) - return 0; - else - return SDL_MUTEX_TIMEDOUT; - } + DosWaitEventSem(sem->changed, SEM_INDEFINITE_WAIT); + } } - /* never reached */ - return -1; + } else if (timeout == 0) { + ulrc = DosRequestMutexSem(sem->id, SEM_INDEFINITE_WAIT); + if (ulrc == NO_ERROR) { + if (sem->value) { + sem->value--; + DosReleaseMutexSem(sem->id); + return 0; + } else { + DosReleaseMutexSem(sem->id); + return SDL_MUTEX_TIMEDOUT; + } + } else { + SDL_SetError("DosRequestMutexSem() failed"); + return -1; + } + } else { + ulrc = DosRequestMutexSem(sem->id, SEM_INDEFINITE_WAIT); + if (ulrc) { + /* if error waiting mutex */ + SDL_SetError("DosRequestMutexSem() failed"); + return -1; + } else if (sem->value) { + sem->value--; + DosReleaseMutexSem(sem->id); + return 0; + } else { + ULONG ulPostCount; + DosResetEventSem(sem->changed, &ulPostCount); + DosReleaseMutexSem(sem->id); + /* continue waiting until somebody posts the semaphore */ + ulrc = DosWaitEventSem(sem->changed, timeout); + if (ulrc == NO_ERROR) + return 0; + else + return SDL_MUTEX_TIMEDOUT; + } + } + /* never reached */ + return -1; } -DECLSPEC int SDLCALL SDL_SemTryWait(SDL_sem *sem) +DECLSPEC int SDLCALL +SDL_SemTryWait(SDL_sem * sem) { - return SDL_SemWaitTimeout(sem, 0); + return SDL_SemWaitTimeout(sem, 0); } -DECLSPEC int SDLCALL SDL_SemWait(SDL_sem *sem) +DECLSPEC int SDLCALL +SDL_SemWait(SDL_sem * sem) { - return SDL_SemWaitTimeout(sem, SDL_MUTEX_MAXWAIT); + return SDL_SemWaitTimeout(sem, SDL_MUTEX_MAXWAIT); } /* Returns the current count of the semaphore */ -DECLSPEC Uint32 SDLCALL SDL_SemValue(SDL_sem *sem) +DECLSPEC Uint32 SDLCALL +SDL_SemValue(SDL_sem * sem) { - if ( ! sem ) { - SDL_SetError("Passed a NULL sem"); - return 0; - } - return sem->value; + if (!sem) { + SDL_SetError("Passed a NULL sem"); + return 0; + } + return sem->value; } -DECLSPEC int SDLCALL SDL_SemPost(SDL_sem *sem) +DECLSPEC int SDLCALL +SDL_SemPost(SDL_sem * sem) { - if ( ! sem ) { - SDL_SetError("Passed a NULL sem"); - return -1; - } - if ( DosRequestMutexSem(sem->id,SEM_INDEFINITE_WAIT) ) { - SDL_SetError("DosRequestMutexSem() failed"); - return -1; - } - sem->value++; - DosPostEventSem(sem->changed); - DosReleaseMutexSem(sem->id); - return 0; + if (!sem) { + SDL_SetError("Passed a NULL sem"); + return -1; + } + if (DosRequestMutexSem(sem->id, SEM_INDEFINITE_WAIT)) { + SDL_SetError("DosRequestMutexSem() failed"); + return -1; + } + sem->value++; + DosPostEventSem(sem->changed); + DosReleaseMutexSem(sem->id); + return 0; } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/thread/os2/SDL_systhread.c b/src/thread/os2/SDL_systhread.c index 5a174d928..4dee320e9 100644 --- a/src/thread/os2/SDL_systhread.c +++ b/src/thread/os2/SDL_systhread.c @@ -34,75 +34,82 @@ typedef struct ThreadStartParms { - void *args; - pfnSDL_CurrentEndThread pfnCurrentEndThread; + void *args; + pfnSDL_CurrentEndThread pfnCurrentEndThread; } tThreadStartParms, *pThreadStartParms; -static void threadfunc(void *pparm) +static void +threadfunc(void *pparm) { - pThreadStartParms pThreadParms = pparm; - pfnSDL_CurrentEndThread pfnCurrentEndThread = NULL; - - // Call the thread function! - SDL_RunThread(pThreadParms->args); - - // Get the current endthread we have to use! - if (pThreadParms) - { - pfnCurrentEndThread = pThreadParms->pfnCurrentEndThread; - SDL_free(pThreadParms); - } - // Call endthread! - if (pfnCurrentEndThread) - (*pfnCurrentEndThread)(); + pThreadStartParms pThreadParms = pparm; + pfnSDL_CurrentEndThread pfnCurrentEndThread = NULL; + + // Call the thread function! + SDL_RunThread(pThreadParms->args); + + // Get the current endthread we have to use! + if (pThreadParms) { + pfnCurrentEndThread = pThreadParms->pfnCurrentEndThread; + SDL_free(pThreadParms); + } + // Call endthread! + if (pfnCurrentEndThread) + (*pfnCurrentEndThread) (); } -int SDL_SYS_CreateThread(SDL_Thread *thread, void *args, pfnSDL_CurrentBeginThread pfnBeginThread, pfnSDL_CurrentEndThread pfnEndThread) +int +SDL_SYS_CreateThread(SDL_Thread * thread, void *args, + pfnSDL_CurrentBeginThread pfnBeginThread, + pfnSDL_CurrentEndThread pfnEndThread) { - pThreadStartParms pThreadParms = SDL_malloc(sizeof(tThreadStartParms)); - if (!pThreadParms) - { - SDL_SetError("Not enough memory to create thread"); - return(-1); - } - - // Save the function which we will have to call to clear the RTL of calling app! - pThreadParms->pfnCurrentEndThread = pfnEndThread; - // Also save the real parameters we have to pass to thread function - pThreadParms->args = args; - // Start the thread using the runtime library of calling app! - thread->threadid = thread->handle = (*pfnBeginThread)(threadfunc, NULL, 512*1024, pThreadParms); - if ((int)thread->threadid <= 0) - { - SDL_SetError("Not enough resources to create thread"); - return(-1); - } - return(0); + pThreadStartParms pThreadParms = SDL_malloc(sizeof(tThreadStartParms)); + if (!pThreadParms) { + SDL_SetError("Not enough memory to create thread"); + return (-1); + } + // Save the function which we will have to call to clear the RTL of calling app! + pThreadParms->pfnCurrentEndThread = pfnEndThread; + // Also save the real parameters we have to pass to thread function + pThreadParms->args = args; + // Start the thread using the runtime library of calling app! + thread->threadid = thread->handle = + (*pfnBeginThread) (threadfunc, NULL, 512 * 1024, pThreadParms); + if ((int) thread->threadid <= 0) { + SDL_SetError("Not enough resources to create thread"); + return (-1); + } + return (0); } -void SDL_SYS_SetupThread(void) +void +SDL_SYS_SetupThread(void) { - return; + return; } -DECLSPEC Uint32 SDLCALL SDL_ThreadID(void) +DECLSPEC Uint32 SDLCALL +SDL_ThreadID(void) { - PTIB tib; - DosGetInfoBlocks(&tib, NULL); - return((Uint32) (tib->tib_ptib2->tib2_ultid)); + PTIB tib; + DosGetInfoBlocks(&tib, NULL); + return ((Uint32) (tib->tib_ptib2->tib2_ultid)); } -void SDL_SYS_WaitThread(SDL_Thread *thread) +void +SDL_SYS_WaitThread(SDL_Thread * thread) { - TID tid = thread->handle; - DosWaitThread(&tid, DCWW_WAIT); + TID tid = thread->handle; + DosWaitThread(&tid, DCWW_WAIT); } /* WARNING: This function is really a last resort. * Threads should be signaled and then exit by themselves. * TerminateThread() doesn't perform stack and DLL cleanup. */ -void SDL_SYS_KillThread(SDL_Thread *thread) +void +SDL_SYS_KillThread(SDL_Thread * thread) { - DosKillThread(thread->handle); + DosKillThread(thread->handle); } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/thread/os2/SDL_systhread_c.h b/src/thread/os2/SDL_systhread_c.h index 186419de7..9008830b2 100644 --- a/src/thread/os2/SDL_systhread_c.h +++ b/src/thread/os2/SDL_systhread_c.h @@ -25,4 +25,4 @@ #include typedef TID SYS_ThreadHandle; - +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/thread/pth/SDL_syscond.c b/src/thread/pth/SDL_syscond.c index 715aff118..083ee5239 100644 --- a/src/thread/pth/SDL_syscond.c +++ b/src/thread/pth/SDL_syscond.c @@ -34,69 +34,73 @@ struct SDL_cond { - pth_cond_t condpth_p; + pth_cond_t condpth_p; }; /* Create a condition variable */ -SDL_cond * SDL_CreateCond(void) +SDL_cond * +SDL_CreateCond(void) { - SDL_cond *cond; - - cond = (SDL_cond *) SDL_malloc(sizeof(SDL_cond)); - if ( cond ) { - if ( pth_cond_init(&(cond->condpth_p)) < 0 ) { - SDL_SetError("pthread_cond_init() failed"); - SDL_free(cond); - cond = NULL; - } - } else { - SDL_OutOfMemory(); - } - return(cond); + SDL_cond *cond; + + cond = (SDL_cond *) SDL_malloc(sizeof(SDL_cond)); + if (cond) { + if (pth_cond_init(&(cond->condpth_p)) < 0) { + SDL_SetError("pthread_cond_init() failed"); + SDL_free(cond); + cond = NULL; + } + } else { + SDL_OutOfMemory(); + } + return (cond); } /* Destroy a condition variable */ -void SDL_DestroyCond(SDL_cond *cond) +void +SDL_DestroyCond(SDL_cond * cond) { - if ( cond ) { - SDL_free(cond); - } + if (cond) { + SDL_free(cond); + } } /* Restart one of the threads that are waiting on the condition variable */ -int SDL_CondSignal(SDL_cond *cond) +int +SDL_CondSignal(SDL_cond * cond) { - int retval; - - if ( ! cond ) { - SDL_SetError("Passed a NULL condition variable"); - return -1; - } - - retval = 0; - if ( pth_cond_notify(&(cond->condpth_p), FALSE) != 0 ) { - SDL_SetError("pth_cond_notify() failed"); - retval = -1; - } - return retval; + int retval; + + if (!cond) { + SDL_SetError("Passed a NULL condition variable"); + return -1; + } + + retval = 0; + if (pth_cond_notify(&(cond->condpth_p), FALSE) != 0) { + SDL_SetError("pth_cond_notify() failed"); + retval = -1; + } + return retval; } /* Restart all threads that are waiting on the condition variable */ -int SDL_CondBroadcast(SDL_cond *cond) +int +SDL_CondBroadcast(SDL_cond * cond) { - int retval; - - if ( ! cond ) { - SDL_SetError("Passed a NULL condition variable"); - return -1; - } - - retval = 0; - if ( pth_cond_notify(&(cond->condpth_p), TRUE) != 0 ) { - SDL_SetError("pth_cond_notify() failed"); - retval = -1; - } - return retval; + int retval; + + if (!cond) { + SDL_SetError("Passed a NULL condition variable"); + return -1; + } + + retval = 0; + if (pth_cond_notify(&(cond->condpth_p), TRUE) != 0) { + SDL_SetError("pth_cond_notify() failed"); + retval = -1; + } + return retval; } /* Wait on the condition variable for at most 'ms' milliseconds. @@ -119,46 +123,51 @@ Thread B: ... SDL_UnlockMutex(lock); */ -int SDL_CondWaitTimeout(SDL_cond *cond, SDL_mutex *mutex, Uint32 ms) +int +SDL_CondWaitTimeout(SDL_cond * cond, SDL_mutex * mutex, Uint32 ms) { - int retval; - pth_event_t ev; - int sec; + int retval; + pth_event_t ev; + int sec; - if ( ! cond ) { - SDL_SetError("Passed a NULL condition variable"); - return -1; - } + if (!cond) { + SDL_SetError("Passed a NULL condition variable"); + return -1; + } - retval = 0; + retval = 0; - sec = ms/1000; - ev = pth_event(PTH_EVENT_TIME, pth_timeout(sec,(ms-sec*1000)*1000)); + sec = ms / 1000; + ev = pth_event(PTH_EVENT_TIME, + pth_timeout(sec, (ms - sec * 1000) * 1000)); - if ( pth_cond_await(&(cond->condpth_p), &(mutex->mutexpth_p), ev) != 0 ) { - SDL_SetError("pth_cond_await() failed"); - retval = -1; - } + if (pth_cond_await(&(cond->condpth_p), &(mutex->mutexpth_p), ev) != 0) { + SDL_SetError("pth_cond_await() failed"); + retval = -1; + } pth_event_free(ev, PTH_FREE_ALL); - return retval; + return retval; } /* Wait on the condition variable forever */ -int SDL_CondWait(SDL_cond *cond, SDL_mutex *mutex) +int +SDL_CondWait(SDL_cond * cond, SDL_mutex * mutex) { - int retval; - - if ( ! cond ) { - SDL_SetError("Passed a NULL condition variable"); - return -1; - } - - retval = 0; - if ( pth_cond_await(&(cond->condpth_p), &(mutex->mutexpth_p), NULL) != 0 ) { - SDL_SetError("pth_cond_await() failed"); - retval = -1; - } - return retval; + int retval; + + if (!cond) { + SDL_SetError("Passed a NULL condition variable"); + return -1; + } + + retval = 0; + if (pth_cond_await(&(cond->condpth_p), &(mutex->mutexpth_p), NULL) != 0) { + SDL_SetError("pth_cond_await() failed"); + retval = -1; + } + return retval; } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/thread/pth/SDL_sysmutex.c b/src/thread/pth/SDL_sysmutex.c index 9d5b197c5..d456a3194 100644 --- a/src/thread/pth/SDL_sysmutex.c +++ b/src/thread/pth/SDL_sysmutex.c @@ -33,55 +33,61 @@ #include "SDL_sysmutex_c.h" /* Create a mutex */ -SDL_mutex *SDL_CreateMutex(void) +SDL_mutex * +SDL_CreateMutex(void) { - SDL_mutex *mutex; - - /* Allocate mutex memory */ - mutex = (SDL_mutex *)SDL_malloc(sizeof(*mutex)); - if ( mutex ) { - /* Create the mutex, with initial value signaled */ - if (!pth_mutex_init(&(mutex->mutexpth_p))) { - SDL_SetError("Couldn't create mutex"); - SDL_free(mutex); - mutex = NULL; - } - } else { - SDL_OutOfMemory(); - } - return(mutex); + SDL_mutex *mutex; + + /* Allocate mutex memory */ + mutex = (SDL_mutex *) SDL_malloc(sizeof(*mutex)); + if (mutex) { + /* Create the mutex, with initial value signaled */ + if (!pth_mutex_init(&(mutex->mutexpth_p))) { + SDL_SetError("Couldn't create mutex"); + SDL_free(mutex); + mutex = NULL; + } + } else { + SDL_OutOfMemory(); + } + return (mutex); } /* Free the mutex */ -void SDL_DestroyMutex(SDL_mutex *mutex) +void +SDL_DestroyMutex(SDL_mutex * mutex) { - if ( mutex ) { - SDL_free(mutex); - } + if (mutex) { + SDL_free(mutex); + } } /* Lock the mutex */ -int SDL_mutexP(SDL_mutex *mutex) +int +SDL_mutexP(SDL_mutex * mutex) { - if ( mutex == NULL ) { - SDL_SetError("Passed a NULL mutex"); - return -1; - } + if (mutex == NULL) { + SDL_SetError("Passed a NULL mutex"); + return -1; + } - pth_mutex_acquire(&(mutex->mutexpth_p), FALSE, NULL); + pth_mutex_acquire(&(mutex->mutexpth_p), FALSE, NULL); - return(0); + return (0); } /* Unlock the mutex */ -int SDL_mutexV(SDL_mutex *mutex) +int +SDL_mutexV(SDL_mutex * mutex) { - if ( mutex == NULL ) { - SDL_SetError("Passed a NULL mutex"); - return -1; - } + if (mutex == NULL) { + SDL_SetError("Passed a NULL mutex"); + return -1; + } pth_mutex_release(&(mutex->mutexpth_p)); - return(0); + return (0); } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/thread/pth/SDL_sysmutex_c.h b/src/thread/pth/SDL_sysmutex_c.h index e0e9ef53a..aa60f52c6 100644 --- a/src/thread/pth/SDL_sysmutex_c.h +++ b/src/thread/pth/SDL_sysmutex_c.h @@ -24,8 +24,10 @@ #ifndef _SDL_SYSMUTEX_C_H_ #define _SDL_SYSMUTEX_C_H_ -struct SDL_mutex { - pth_mutex_t mutexpth_p; +struct SDL_mutex +{ + pth_mutex_t mutexpth_p; }; #endif /* _SDL_SYSMUTEX_C_H_ */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/thread/pth/SDL_systhread.c b/src/thread/pth/SDL_systhread.c index 284003a63..df70c9b8a 100644 --- a/src/thread/pth/SDL_systhread.c +++ b/src/thread/pth/SDL_systhread.c @@ -36,68 +36,76 @@ /* List of signals to mask in the subthreads */ static int sig_list[] = { - SIGHUP, SIGINT, SIGQUIT, SIGPIPE, SIGALRM, SIGTERM, SIGCHLD, SIGWINCH, - SIGVTALRM, SIGPROF, 0 + SIGHUP, SIGINT, SIGQUIT, SIGPIPE, SIGALRM, SIGTERM, SIGCHLD, SIGWINCH, + SIGVTALRM, SIGPROF, 0 }; -static void *RunThread(void *data) +static void * +RunThread(void *data) { - SDL_RunThread(data); - pth_exit((void*)0); - return((void *)0); /* Prevent compiler warning */ + SDL_RunThread(data); + pth_exit((void *) 0); + return ((void *) 0); /* Prevent compiler warning */ } -int SDL_SYS_CreateThread(SDL_Thread *thread, void *args) +int +SDL_SYS_CreateThread(SDL_Thread * thread, void *args) { - pth_attr_t type; - - /* Create a new attribute */ - type = pth_attr_new(); - if ( type == NULL ) { - SDL_SetError("Couldn't initialize pth attributes"); - return(-1); - } - pth_attr_set(type, PTH_ATTR_JOINABLE, TRUE); - - /* Create the thread and go! */ - thread->handle = pth_spawn(type, RunThread, args); - if ( thread->handle == NULL ) { - SDL_SetError("Not enough resources to create thread"); - return(-1); - } - return(0); + pth_attr_t type; + + /* Create a new attribute */ + type = pth_attr_new(); + if (type == NULL) { + SDL_SetError("Couldn't initialize pth attributes"); + return (-1); + } + pth_attr_set(type, PTH_ATTR_JOINABLE, TRUE); + + /* Create the thread and go! */ + thread->handle = pth_spawn(type, RunThread, args); + if (thread->handle == NULL) { + SDL_SetError("Not enough resources to create thread"); + return (-1); + } + return (0); } -void SDL_SYS_SetupThread(void) +void +SDL_SYS_SetupThread(void) { - int i; - sigset_t mask; - int oldstate; - - /* Mask asynchronous signals for this thread */ - sigemptyset(&mask); - for ( i=0; sig_list[i]; ++i ) { - sigaddset(&mask, sig_list[i]); - } - pth_sigmask(SIG_BLOCK, &mask, 0); - - /* Allow ourselves to be asynchronously cancelled */ - pth_cancel_state(PTH_CANCEL_ASYNCHRONOUS, &oldstate); + int i; + sigset_t mask; + int oldstate; + + /* Mask asynchronous signals for this thread */ + sigemptyset(&mask); + for (i = 0; sig_list[i]; ++i) { + sigaddset(&mask, sig_list[i]); + } + pth_sigmask(SIG_BLOCK, &mask, 0); + + /* Allow ourselves to be asynchronously cancelled */ + pth_cancel_state(PTH_CANCEL_ASYNCHRONOUS, &oldstate); } /* WARNING: This may not work for systems with 64-bit pid_t */ -Uint32 SDL_ThreadID(void) +Uint32 +SDL_ThreadID(void) { - return((Uint32)pth_self()); + return ((Uint32) pth_self()); } -void SDL_SYS_WaitThread(SDL_Thread *thread) +void +SDL_SYS_WaitThread(SDL_Thread * thread) { - pth_join(thread->handle, NULL); + pth_join(thread->handle, NULL); } -void SDL_SYS_KillThread(SDL_Thread *thread) +void +SDL_SYS_KillThread(SDL_Thread * thread) { - pth_cancel(thread->handle); - pth_join(thread->handle, NULL); + pth_cancel(thread->handle); + pth_join(thread->handle, NULL); } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/thread/pth/SDL_systhread_c.h b/src/thread/pth/SDL_systhread_c.h index 791eb1bdc..297d7838c 100644 --- a/src/thread/pth/SDL_systhread_c.h +++ b/src/thread/pth/SDL_systhread_c.h @@ -29,3 +29,4 @@ typedef pth_t SYS_ThreadHandle; #endif /* _SDL_SYSTHREAD_C_H_ */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/thread/pthread/SDL_syscond.c b/src/thread/pthread/SDL_syscond.c index 333f83c71..7f4c4bf17 100644 --- a/src/thread/pthread/SDL_syscond.c +++ b/src/thread/pthread/SDL_syscond.c @@ -31,125 +31,133 @@ struct SDL_cond { - pthread_cond_t cond; + pthread_cond_t cond; }; /* Create a condition variable */ -SDL_cond * SDL_CreateCond(void) +SDL_cond * +SDL_CreateCond(void) { - SDL_cond *cond; - - cond = (SDL_cond *) SDL_malloc(sizeof(SDL_cond)); - if ( cond ) { - if ( pthread_cond_init(&cond->cond, NULL) < 0 ) { - SDL_SetError("pthread_cond_init() failed"); - SDL_free(cond); - cond = NULL; - } - } - return(cond); + SDL_cond *cond; + + cond = (SDL_cond *) SDL_malloc(sizeof(SDL_cond)); + if (cond) { + if (pthread_cond_init(&cond->cond, NULL) < 0) { + SDL_SetError("pthread_cond_init() failed"); + SDL_free(cond); + cond = NULL; + } + } + return (cond); } /* Destroy a condition variable */ -void SDL_DestroyCond(SDL_cond *cond) +void +SDL_DestroyCond(SDL_cond * cond) { - if ( cond ) { - pthread_cond_destroy(&cond->cond); - SDL_free(cond); - } + if (cond) { + pthread_cond_destroy(&cond->cond); + SDL_free(cond); + } } /* Restart one of the threads that are waiting on the condition variable */ -int SDL_CondSignal(SDL_cond *cond) +int +SDL_CondSignal(SDL_cond * cond) { - int retval; - - if ( ! cond ) { - SDL_SetError("Passed a NULL condition variable"); - return -1; - } - - retval = 0; - if ( pthread_cond_signal(&cond->cond) != 0 ) { - SDL_SetError("pthread_cond_signal() failed"); - retval = -1; - } - return retval; + int retval; + + if (!cond) { + SDL_SetError("Passed a NULL condition variable"); + return -1; + } + + retval = 0; + if (pthread_cond_signal(&cond->cond) != 0) { + SDL_SetError("pthread_cond_signal() failed"); + retval = -1; + } + return retval; } /* Restart all threads that are waiting on the condition variable */ -int SDL_CondBroadcast(SDL_cond *cond) +int +SDL_CondBroadcast(SDL_cond * cond) { - int retval; - - if ( ! cond ) { - SDL_SetError("Passed a NULL condition variable"); - return -1; - } - - retval = 0; - if ( pthread_cond_broadcast(&cond->cond) != 0 ) { - SDL_SetError("pthread_cond_broadcast() failed"); - retval = -1; - } - return retval; + int retval; + + if (!cond) { + SDL_SetError("Passed a NULL condition variable"); + return -1; + } + + retval = 0; + if (pthread_cond_broadcast(&cond->cond) != 0) { + SDL_SetError("pthread_cond_broadcast() failed"); + retval = -1; + } + return retval; } -int SDL_CondWaitTimeout(SDL_cond *cond, SDL_mutex *mutex, Uint32 ms) +int +SDL_CondWaitTimeout(SDL_cond * cond, SDL_mutex * mutex, Uint32 ms) { - int retval; - struct timeval delta; - struct timespec abstime; - - if ( ! cond ) { - SDL_SetError("Passed a NULL condition variable"); - return -1; - } - - gettimeofday(&delta, NULL); - - abstime.tv_sec = delta.tv_sec + (ms/1000); - abstime.tv_nsec = (delta.tv_usec + (ms%1000) * 1000) * 1000; - if ( abstime.tv_nsec > 1000000000 ) { - abstime.tv_sec += 1; - abstime.tv_nsec -= 1000000000; - } + int retval; + struct timeval delta; + struct timespec abstime; + + if (!cond) { + SDL_SetError("Passed a NULL condition variable"); + return -1; + } + + gettimeofday(&delta, NULL); + + abstime.tv_sec = delta.tv_sec + (ms / 1000); + abstime.tv_nsec = (delta.tv_usec + (ms % 1000) * 1000) * 1000; + if (abstime.tv_nsec > 1000000000) { + abstime.tv_sec += 1; + abstime.tv_nsec -= 1000000000; + } tryagain: - retval = pthread_cond_timedwait(&cond->cond, &mutex->id, &abstime); - switch (retval) { - case EINTR: - goto tryagain; - break; - case ETIMEDOUT: - retval = SDL_MUTEX_TIMEDOUT; - break; - case 0: - break; - default: - SDL_SetError("pthread_cond_timedwait() failed"); - retval = -1; - break; - } - return retval; + retval = pthread_cond_timedwait(&cond->cond, &mutex->id, &abstime); + switch (retval) { + case EINTR: + goto tryagain; + break; + case ETIMEDOUT: + retval = SDL_MUTEX_TIMEDOUT; + break; + case 0: + break; + default: + SDL_SetError("pthread_cond_timedwait() failed"); + retval = -1; + break; + } + return retval; } /* Wait on the condition variable, unlocking the provided mutex. The mutex must be locked before entering this function! */ -int SDL_CondWait(SDL_cond *cond, SDL_mutex *mutex) +int +SDL_CondWait(SDL_cond * cond, SDL_mutex * mutex) { - int retval; - - if ( ! cond ) { - SDL_SetError("Passed a NULL condition variable"); - return -1; - } - - retval = 0; - if ( pthread_cond_wait(&cond->cond, &mutex->id) != 0 ) { - SDL_SetError("pthread_cond_wait() failed"); - retval = -1; - } - return retval; + int retval; + + if (!cond) { + SDL_SetError("Passed a NULL condition variable"); + return -1; + } + + retval = 0; + if (pthread_cond_wait(&cond->cond, &mutex->id) != 0) { + SDL_SetError("pthread_cond_wait() failed"); + retval = -1; + } + return retval; } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/thread/pthread/SDL_sysmutex.c b/src/thread/pthread/SDL_sysmutex.c index 42e99b4ee..a15f532c2 100644 --- a/src/thread/pthread/SDL_sysmutex.c +++ b/src/thread/pthread/SDL_sysmutex.c @@ -30,124 +30,131 @@ #define FAKE_RECURSIVE_MUTEX #endif -struct SDL_mutex { - pthread_mutex_t id; +struct SDL_mutex +{ + pthread_mutex_t id; #if FAKE_RECURSIVE_MUTEX - int recursive; - pthread_t owner; + int recursive; + pthread_t owner; #endif }; -SDL_mutex *SDL_CreateMutex (void) +SDL_mutex * +SDL_CreateMutex(void) { - SDL_mutex *mutex; - pthread_mutexattr_t attr; + SDL_mutex *mutex; + pthread_mutexattr_t attr; - /* Allocate the structure */ - mutex = (SDL_mutex *)SDL_calloc(1, sizeof(*mutex)); - if ( mutex ) { - pthread_mutexattr_init(&attr); + /* Allocate the structure */ + mutex = (SDL_mutex *) SDL_calloc(1, sizeof(*mutex)); + if (mutex) { + pthread_mutexattr_init(&attr); #if SDL_THREAD_PTHREAD_RECURSIVE_MUTEX - pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); + pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); #elif SDL_THREAD_PTHREAD_RECURSIVE_MUTEX_NP - pthread_mutexattr_setkind_np(&attr, PTHREAD_MUTEX_RECURSIVE_NP); + pthread_mutexattr_setkind_np(&attr, PTHREAD_MUTEX_RECURSIVE_NP); #else - /* No extra attributes necessary */ + /* No extra attributes necessary */ #endif - if ( pthread_mutex_init(&mutex->id, &attr) != 0 ) { - SDL_SetError("pthread_mutex_init() failed"); - SDL_free(mutex); - mutex = NULL; - } - } else { - SDL_OutOfMemory(); - } - return(mutex); + if (pthread_mutex_init(&mutex->id, &attr) != 0) { + SDL_SetError("pthread_mutex_init() failed"); + SDL_free(mutex); + mutex = NULL; + } + } else { + SDL_OutOfMemory(); + } + return (mutex); } -void SDL_DestroyMutex(SDL_mutex *mutex) +void +SDL_DestroyMutex(SDL_mutex * mutex) { - if ( mutex ) { - pthread_mutex_destroy(&mutex->id); - SDL_free(mutex); - } + if (mutex) { + pthread_mutex_destroy(&mutex->id); + SDL_free(mutex); + } } /* Lock the mutex */ -int SDL_mutexP(SDL_mutex *mutex) +int +SDL_mutexP(SDL_mutex * mutex) { - int retval; + int retval; #if FAKE_RECURSIVE_MUTEX - pthread_t this_thread; + pthread_t this_thread; #endif - if ( mutex == NULL ) { - SDL_SetError("Passed a NULL mutex"); - return -1; - } + if (mutex == NULL) { + SDL_SetError("Passed a NULL mutex"); + return -1; + } - retval = 0; + retval = 0; #if FAKE_RECURSIVE_MUTEX - this_thread = pthread_self(); - if ( mutex->owner == this_thread ) { - ++mutex->recursive; - } else { - /* The order of operations is important. - We set the locking thread id after we obtain the lock - so unlocks from other threads will fail. - */ - if ( pthread_mutex_lock(&mutex->id) == 0 ) { - mutex->owner = this_thread; - mutex->recursive = 0; - } else { - SDL_SetError("pthread_mutex_lock() failed"); - retval = -1; - } - } + this_thread = pthread_self(); + if (mutex->owner == this_thread) { + ++mutex->recursive; + } else { + /* The order of operations is important. + We set the locking thread id after we obtain the lock + so unlocks from other threads will fail. + */ + if (pthread_mutex_lock(&mutex->id) == 0) { + mutex->owner = this_thread; + mutex->recursive = 0; + } else { + SDL_SetError("pthread_mutex_lock() failed"); + retval = -1; + } + } #else - if ( pthread_mutex_lock(&mutex->id) < 0 ) { - SDL_SetError("pthread_mutex_lock() failed"); - retval = -1; - } + if (pthread_mutex_lock(&mutex->id) < 0) { + SDL_SetError("pthread_mutex_lock() failed"); + retval = -1; + } #endif - return retval; + return retval; } -int SDL_mutexV(SDL_mutex *mutex) +int +SDL_mutexV(SDL_mutex * mutex) { - int retval; + int retval; - if ( mutex == NULL ) { - SDL_SetError("Passed a NULL mutex"); - return -1; - } + if (mutex == NULL) { + SDL_SetError("Passed a NULL mutex"); + return -1; + } - retval = 0; + retval = 0; #if FAKE_RECURSIVE_MUTEX - /* We can only unlock the mutex if we own it */ - if ( pthread_self() == mutex->owner ) { - if ( mutex->recursive ) { - --mutex->recursive; - } else { - /* The order of operations is important. - First reset the owner so another thread doesn't lock - the mutex and set the ownership before we reset it, - then release the lock semaphore. - */ - mutex->owner = 0; - pthread_mutex_unlock(&mutex->id); - } - } else { - SDL_SetError("mutex not owned by this thread"); - retval = -1; - } + /* We can only unlock the mutex if we own it */ + if (pthread_self() == mutex->owner) { + if (mutex->recursive) { + --mutex->recursive; + } else { + /* The order of operations is important. + First reset the owner so another thread doesn't lock + the mutex and set the ownership before we reset it, + then release the lock semaphore. + */ + mutex->owner = 0; + pthread_mutex_unlock(&mutex->id); + } + } else { + SDL_SetError("mutex not owned by this thread"); + retval = -1; + } #else - if ( pthread_mutex_unlock(&mutex->id) < 0 ) { - SDL_SetError("pthread_mutex_unlock() failed"); - retval = -1; - } + if (pthread_mutex_unlock(&mutex->id) < 0) { + SDL_SetError("pthread_mutex_unlock() failed"); + retval = -1; + } #endif /* FAKE_RECURSIVE_MUTEX */ - return retval; + return retval; } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/thread/pthread/SDL_sysmutex_c.h b/src/thread/pthread/SDL_sysmutex_c.h index 187e7c83e..c5a129432 100644 --- a/src/thread/pthread/SDL_sysmutex_c.h +++ b/src/thread/pthread/SDL_sysmutex_c.h @@ -24,8 +24,10 @@ #ifndef _SDL_mutex_c_h #define _SDL_mutex_c_h -struct SDL_mutex { - pthread_mutex_t id; +struct SDL_mutex +{ + pthread_mutex_t id; }; #endif /* _SDL_mutex_c_h */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/thread/pthread/SDL_syssem.c b/src/thread/pthread/SDL_syssem.c index c43195ac6..ba335e3f7 100644 --- a/src/thread/pthread/SDL_syssem.c +++ b/src/thread/pthread/SDL_syssem.c @@ -23,7 +23,6 @@ #include #include -#include #include "SDL_thread.h" #include "SDL_timer.h" @@ -35,122 +34,132 @@ #include "../generic/SDL_syssem.c" #else -struct SDL_semaphore { - sem_t sem; +struct SDL_semaphore +{ + sem_t sem; }; /* Create a semaphore, initialized with value */ -SDL_sem *SDL_CreateSemaphore(Uint32 initial_value) +SDL_sem * +SDL_CreateSemaphore(Uint32 initial_value) { - SDL_sem *sem = (SDL_sem *) SDL_malloc(sizeof(SDL_sem)); - if ( sem ) { - if ( sem_init(&sem->sem, 0, initial_value) < 0 ) { - SDL_SetError("sem_init() failed"); - SDL_free(sem); - sem = NULL; - } - } else { - SDL_OutOfMemory(); - } - return sem; + SDL_sem *sem = (SDL_sem *) SDL_malloc(sizeof(SDL_sem)); + if (sem) { + if (sem_init(&sem->sem, 0, initial_value) < 0) { + SDL_SetError("sem_init() failed"); + SDL_free(sem); + sem = NULL; + } + } else { + SDL_OutOfMemory(); + } + return sem; } -void SDL_DestroySemaphore(SDL_sem *sem) +void +SDL_DestroySemaphore(SDL_sem * sem) { - if ( sem ) { - sem_destroy(&sem->sem); - SDL_free(sem); - } + if (sem) { + sem_destroy(&sem->sem); + SDL_free(sem); + } } -int SDL_SemTryWait(SDL_sem *sem) +int +SDL_SemTryWait(SDL_sem * sem) { - int retval; - - if ( ! sem ) { - SDL_SetError("Passed a NULL semaphore"); - return -1; - } - retval = SDL_MUTEX_TIMEDOUT; - if ( sem_trywait(&sem->sem) == 0 ) { - retval = 0; - } - return retval; + int retval; + + if (!sem) { + SDL_SetError("Passed a NULL semaphore"); + return -1; + } + retval = SDL_MUTEX_TIMEDOUT; + if (sem_trywait(&sem->sem) == 0) { + retval = 0; + } + return retval; } -int SDL_SemWait(SDL_sem *sem) +int +SDL_SemWait(SDL_sem * sem) { - int retval; - - if ( ! sem ) { - SDL_SetError("Passed a NULL semaphore"); - return -1; - } - - while ( ((retval = sem_wait(&sem->sem)) == -1) && (errno == EINTR) ) {} - if ( retval < 0 ) { - SDL_SetError("sem_wait() failed"); - } - return retval; + int retval; + + if (!sem) { + SDL_SetError("Passed a NULL semaphore"); + return -1; + } + + retval = sem_wait(&sem->sem); + if (retval < 0) { + SDL_SetError("sem_wait() failed"); + } + return retval; } -int SDL_SemWaitTimeout(SDL_sem *sem, Uint32 timeout) +int +SDL_SemWaitTimeout(SDL_sem * sem, Uint32 timeout) { - int retval; - - if ( ! sem ) { - SDL_SetError("Passed a NULL semaphore"); - return -1; - } - - /* Try the easy cases first */ - if ( timeout == 0 ) { - return SDL_SemTryWait(sem); - } - if ( timeout == SDL_MUTEX_MAXWAIT ) { - return SDL_SemWait(sem); - } - - /* Ack! We have to busy wait... */ - /* FIXME: Use sem_timedwait()? */ - timeout += SDL_GetTicks(); - do { - retval = SDL_SemTryWait(sem); - if ( retval == 0 ) { - break; - } - SDL_Delay(1); - } while ( SDL_GetTicks() < timeout ); - - return retval; + int retval; + + if (!sem) { + SDL_SetError("Passed a NULL semaphore"); + return -1; + } + + /* Try the easy cases first */ + if (timeout == 0) { + return SDL_SemTryWait(sem); + } + if (timeout == SDL_MUTEX_MAXWAIT) { + return SDL_SemWait(sem); + } + + /* Ack! We have to busy wait... */ + /* FIXME: Use sem_timedwait()? */ + timeout += SDL_GetTicks(); + do { + retval = SDL_SemTryWait(sem); + if (retval == 0) { + break; + } + SDL_Delay(1); + } + while (SDL_GetTicks() < timeout); + + return retval; } -Uint32 SDL_SemValue(SDL_sem *sem) +Uint32 +SDL_SemValue(SDL_sem * sem) { - int ret = 0; - if ( sem ) { - sem_getvalue(&sem->sem, &ret); - if ( ret < 0 ) { - ret = 0; - } - } - return (Uint32)ret; + int ret = 0; + if (sem) { + sem_getvalue(&sem->sem, &ret); + if (ret < 0) { + ret = 0; + } + } + return (Uint32) ret; } -int SDL_SemPost(SDL_sem *sem) +int +SDL_SemPost(SDL_sem * sem) { - int retval; - - if ( ! sem ) { - SDL_SetError("Passed a NULL semaphore"); - return -1; - } - - retval = sem_post(&sem->sem); - if ( retval < 0 ) { - SDL_SetError("sem_post() failed"); - } - return retval; + int retval; + + if (!sem) { + SDL_SetError("Passed a NULL semaphore"); + return -1; + } + + retval = sem_post(&sem->sem); + if (retval < 0) { + SDL_SetError("sem_post() failed"); + } + return retval; } #endif /* __MACOSX__ */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/thread/pthread/SDL_systhread.c b/src/thread/pthread/SDL_systhread.c index e9923facf..660906bb4 100644 --- a/src/thread/pthread/SDL_systhread.c +++ b/src/thread/pthread/SDL_systhread.c @@ -30,91 +30,99 @@ /* List of signals to mask in the subthreads */ static int sig_list[] = { - SIGHUP, SIGINT, SIGQUIT, SIGPIPE, SIGALRM, SIGTERM, SIGCHLD, SIGWINCH, - SIGVTALRM, SIGPROF, 0 + SIGHUP, SIGINT, SIGQUIT, SIGPIPE, SIGALRM, SIGTERM, SIGCHLD, SIGWINCH, + SIGVTALRM, SIGPROF, 0 }; #ifdef __RISCOS__ /* RISC OS needs to know the main thread for * it's timer and event processing. */ int riscos_using_threads = 0; -Uint32 riscos_main_thread = 0; /* Thread running events */ +Uint32 riscos_main_thread = 0; /* Thread running events */ #endif - -static void *RunThread(void *data) + +static void * +RunThread(void *data) { - SDL_RunThread(data); - pthread_exit((void*)0); - return((void *)0); /* Prevent compiler warning */ + SDL_RunThread(data); + pthread_exit((void *) 0); + return ((void *) 0); /* Prevent compiler warning */ } -int SDL_SYS_CreateThread(SDL_Thread *thread, void *args) +int +SDL_SYS_CreateThread(SDL_Thread * thread, void *args) { - pthread_attr_t type; - - /* Set the thread attributes */ - if ( pthread_attr_init(&type) != 0 ) { - SDL_SetError("Couldn't initialize pthread attributes"); - return(-1); - } - pthread_attr_setdetachstate(&type, PTHREAD_CREATE_JOINABLE); - - /* Create the thread and go! */ - if ( pthread_create(&thread->handle, &type, RunThread, args) != 0 ) { - SDL_SetError("Not enough resources to create thread"); - return(-1); - } - + pthread_attr_t type; + + /* Set the thread attributes */ + if (pthread_attr_init(&type) != 0) { + SDL_SetError("Couldn't initialize pthread attributes"); + return (-1); + } + pthread_attr_setdetachstate(&type, PTHREAD_CREATE_JOINABLE); + + /* Create the thread and go! */ + if (pthread_create(&thread->handle, &type, RunThread, args) != 0) { + SDL_SetError("Not enough resources to create thread"); + return (-1); + } #ifdef __RISCOS__ - if (riscos_using_threads == 0) { - riscos_using_threads = 1; - riscos_main_thread = SDL_ThreadID(); - } + if (riscos_using_threads == 0) { + riscos_using_threads = 1; + riscos_main_thread = SDL_ThreadID(); + } #endif - return(0); + return (0); } -void SDL_SYS_SetupThread(void) +void +SDL_SYS_SetupThread(void) { - int i; - sigset_t mask; + int i; + sigset_t mask; - /* Mask asynchronous signals for this thread */ - sigemptyset(&mask); - for ( i=0; sig_list[i]; ++i ) { - sigaddset(&mask, sig_list[i]); - } - pthread_sigmask(SIG_BLOCK, &mask, 0); + /* Mask asynchronous signals for this thread */ + sigemptyset(&mask); + for (i = 0; sig_list[i]; ++i) { + sigaddset(&mask, sig_list[i]); + } + pthread_sigmask(SIG_BLOCK, &mask, 0); #ifdef PTHREAD_CANCEL_ASYNCHRONOUS - /* Allow ourselves to be asynchronously cancelled */ - { int oldstate; - pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &oldstate); - } + /* Allow ourselves to be asynchronously cancelled */ + { + int oldstate; + pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &oldstate); + } #endif } /* WARNING: This may not work for systems with 64-bit pid_t */ -Uint32 SDL_ThreadID(void) +Uint32 +SDL_ThreadID(void) { - return((Uint32)pthread_self()); + return ((Uint32) pthread_self()); } -void SDL_SYS_WaitThread(SDL_Thread *thread) +void +SDL_SYS_WaitThread(SDL_Thread * thread) { - pthread_join(thread->handle, 0); + pthread_join(thread->handle, 0); } -void SDL_SYS_KillThread(SDL_Thread *thread) +void +SDL_SYS_KillThread(SDL_Thread * thread) { #ifdef PTHREAD_CANCEL_ASYNCHRONOUS - pthread_cancel(thread->handle); + pthread_cancel(thread->handle); #else #ifdef __FREEBSD__ #warning For some reason, this doesnt actually kill a thread - FreeBSD 3.2 #endif - pthread_kill(thread->handle, SIGKILL); + pthread_kill(thread->handle, SIGKILL); #endif } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/thread/pthread/SDL_systhread_c.h b/src/thread/pthread/SDL_systhread_c.h index 2aab23ab0..c1ef4bc16 100644 --- a/src/thread/pthread/SDL_systhread_c.h +++ b/src/thread/pthread/SDL_systhread_c.h @@ -24,3 +24,4 @@ #include typedef pthread_t SYS_ThreadHandle; +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/thread/riscos/SDL_syscond.c b/src/thread/riscos/SDL_syscond.c index c04739a98..ee528a746 100644 --- a/src/thread/riscos/SDL_syscond.c +++ b/src/thread/riscos/SDL_syscond.c @@ -35,126 +35,133 @@ struct SDL_cond { - pthread_cond_t cond; + pthread_cond_t cond; }; /* Create a condition variable */ -SDL_cond * SDL_CreateCond(void) +SDL_cond * +SDL_CreateCond(void) { - SDL_cond *cond; - - cond = (SDL_cond *) SDL_malloc(sizeof(SDL_cond)); - if ( cond ) { - if ( pthread_cond_init(&cond->cond, NULL) < 0 ) { - SDL_SetError("pthread_cond_init() failed"); - SDL_free(cond); - cond = NULL; - } - } - return(cond); + SDL_cond *cond; + + cond = (SDL_cond *) SDL_malloc(sizeof(SDL_cond)); + if (cond) { + if (pthread_cond_init(&cond->cond, NULL) < 0) { + SDL_SetError("pthread_cond_init() failed"); + SDL_free(cond); + cond = NULL; + } + } + return (cond); } /* Destroy a condition variable */ -void SDL_DestroyCond(SDL_cond *cond) +void +SDL_DestroyCond(SDL_cond * cond) { - if ( cond ) { - pthread_cond_destroy(&cond->cond); - SDL_free(cond); - } + if (cond) { + pthread_cond_destroy(&cond->cond); + SDL_free(cond); + } } /* Restart one of the threads that are waiting on the condition variable */ -int SDL_CondSignal(SDL_cond *cond) +int +SDL_CondSignal(SDL_cond * cond) { - int retval; - - if ( ! cond ) { - SDL_SetError("Passed a NULL condition variable"); - return -1; - } - - retval = 0; - if ( pthread_cond_signal(&cond->cond) != 0 ) { - SDL_SetError("pthread_cond_signal() failed"); - retval = -1; - } - return retval; + int retval; + + if (!cond) { + SDL_SetError("Passed a NULL condition variable"); + return -1; + } + + retval = 0; + if (pthread_cond_signal(&cond->cond) != 0) { + SDL_SetError("pthread_cond_signal() failed"); + retval = -1; + } + return retval; } /* Restart all threads that are waiting on the condition variable */ -int SDL_CondBroadcast(SDL_cond *cond) +int +SDL_CondBroadcast(SDL_cond * cond) { - int retval; - - if ( ! cond ) { - SDL_SetError("Passed a NULL condition variable"); - return -1; - } - - retval = 0; - if ( pthread_cond_broadcast(&cond->cond) != 0 ) { - SDL_SetError("pthread_cond_broadcast() failed"); - retval = -1; - } - return retval; + int retval; + + if (!cond) { + SDL_SetError("Passed a NULL condition variable"); + return -1; + } + + retval = 0; + if (pthread_cond_broadcast(&cond->cond) != 0) { + SDL_SetError("pthread_cond_broadcast() failed"); + retval = -1; + } + return retval; } -int SDL_CondWaitTimeout(SDL_cond *cond, SDL_mutex *mutex, Uint32 ms) +int +SDL_CondWaitTimeout(SDL_cond * cond, SDL_mutex * mutex, Uint32 ms) { - int retval; - struct timeval delta; - struct timespec abstime; - - if ( ! cond ) { - SDL_SetError("Passed a NULL condition variable"); - return -1; - } - - gettimeofday(&delta, NULL); - - abstime.tv_sec = delta.tv_sec + (ms/1000); - abstime.tv_nsec = (delta.tv_usec + (ms%1000) * 1000) * 1000; - if ( abstime.tv_nsec > 1000000000 ) { - abstime.tv_sec += 1; - abstime.tv_nsec -= 1000000000; - } + int retval; + struct timeval delta; + struct timespec abstime; + + if (!cond) { + SDL_SetError("Passed a NULL condition variable"); + return -1; + } + + gettimeofday(&delta, NULL); + + abstime.tv_sec = delta.tv_sec + (ms / 1000); + abstime.tv_nsec = (delta.tv_usec + (ms % 1000) * 1000) * 1000; + if (abstime.tv_nsec > 1000000000) { + abstime.tv_sec += 1; + abstime.tv_nsec -= 1000000000; + } tryagain: - retval = pthread_cond_timedwait(&cond->cond, &mutex->id, &abstime); - switch (retval) { - case EINTR: - goto tryagain; - break; - case ETIMEDOUT: - retval = SDL_MUTEX_TIMEDOUT; - break; - case 0: - break; - default: - SDL_SetError("pthread_cond_timedwait() failed"); - retval = -1; - break; - } - return retval; + retval = pthread_cond_timedwait(&cond->cond, &mutex->id, &abstime); + switch (retval) { + case EINTR: + goto tryagain; + break; + case ETIMEDOUT: + retval = SDL_MUTEX_TIMEDOUT; + break; + case 0: + break; + default: + SDL_SetError("pthread_cond_timedwait() failed"); + retval = -1; + break; + } + return retval; } /* Wait on the condition variable, unlocking the provided mutex. The mutex must be locked before entering this function! */ -int SDL_CondWait(SDL_cond *cond, SDL_mutex *mutex) +int +SDL_CondWait(SDL_cond * cond, SDL_mutex * mutex) { - int retval; - - if ( ! cond ) { - SDL_SetError("Passed a NULL condition variable"); - return -1; - } - - retval = 0; - if ( pthread_cond_wait(&cond->cond, &mutex->id) != 0 ) { - SDL_SetError("pthread_cond_wait() failed"); - retval = -1; - } - return retval; + int retval; + + if (!cond) { + SDL_SetError("Passed a NULL condition variable"); + return -1; + } + + retval = 0; + if (pthread_cond_wait(&cond->cond, &mutex->id) != 0) { + SDL_SetError("pthread_cond_wait() failed"); + retval = -1; + } + return retval; } #endif +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/thread/riscos/SDL_sysmutex.c b/src/thread/riscos/SDL_sysmutex.c index aa4d65ee9..73bd2bdce 100644 --- a/src/thread/riscos/SDL_sysmutex.c +++ b/src/thread/riscos/SDL_sysmutex.c @@ -31,123 +31,129 @@ #include -struct SDL_mutex { - pthread_mutex_t id; +struct SDL_mutex +{ + pthread_mutex_t id; #if SDL_THREAD_PTHREAD_NO_RECURSIVE_MUTEX - int recursive; - pthread_t owner; + int recursive; + pthread_t owner; #endif }; -SDL_mutex *SDL_CreateMutex (void) +SDL_mutex * +SDL_CreateMutex(void) { - SDL_mutex *mutex; - pthread_mutexattr_t attr; + SDL_mutex *mutex; + pthread_mutexattr_t attr; - /* Allocate the structure */ - mutex = (SDL_mutex *)SDL_calloc(1, sizeof(*mutex)); - if ( mutex ) { - pthread_mutexattr_init(&attr); + /* Allocate the structure */ + mutex = (SDL_mutex *) SDL_calloc(1, sizeof(*mutex)); + if (mutex) { + pthread_mutexattr_init(&attr); #if SDL_THREAD_PTHREAD_NO_RECURSIVE_MUTEX - /* No extra attributes necessary */ + /* No extra attributes necessary */ #else - pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); + pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); #endif /* SDL_THREAD_PTHREAD_NO_RECURSIVE_MUTEX */ - if ( pthread_mutex_init(&mutex->id, &attr) != 0 ) { - SDL_SetError("pthread_mutex_init() failed"); - SDL_free(mutex); - mutex = NULL; - } - } else { - SDL_OutOfMemory(); - } - return(mutex); + if (pthread_mutex_init(&mutex->id, &attr) != 0) { + SDL_SetError("pthread_mutex_init() failed"); + SDL_free(mutex); + mutex = NULL; + } + } else { + SDL_OutOfMemory(); + } + return (mutex); } -void SDL_DestroyMutex(SDL_mutex *mutex) +void +SDL_DestroyMutex(SDL_mutex * mutex) { - if ( mutex ) { - pthread_mutex_destroy(&mutex->id); - SDL_free(mutex); - } + if (mutex) { + pthread_mutex_destroy(&mutex->id); + SDL_free(mutex); + } } /* Lock the mutex */ -int SDL_mutexP(SDL_mutex *mutex) +int +SDL_mutexP(SDL_mutex * mutex) { - int retval; + int retval; #if SDL_THREAD_PTHREAD_NO_RECURSIVE_MUTEX - pthread_t this_thread; + pthread_t this_thread; #endif - if ( mutex == NULL ) { - SDL_SetError("Passed a NULL mutex"); - return -1; - } + if (mutex == NULL) { + SDL_SetError("Passed a NULL mutex"); + return -1; + } - retval = 0; + retval = 0; #if SDL_THREAD_PTHREAD_NO_RECURSIVE_MUTEX - this_thread = pthread_self(); - if ( mutex->owner == this_thread ) { - ++mutex->recursive; - } else { - /* The order of operations is important. - We set the locking thread id after we obtain the lock - so unlocks from other threads will fail. - */ - if ( pthread_mutex_lock(&mutex->id) == 0 ) { - mutex->owner = this_thread; - mutex->recursive = 0; - } else { - SDL_SetError("pthread_mutex_lock() failed"); - retval = -1; - } - } + this_thread = pthread_self(); + if (mutex->owner == this_thread) { + ++mutex->recursive; + } else { + /* The order of operations is important. + We set the locking thread id after we obtain the lock + so unlocks from other threads will fail. + */ + if (pthread_mutex_lock(&mutex->id) == 0) { + mutex->owner = this_thread; + mutex->recursive = 0; + } else { + SDL_SetError("pthread_mutex_lock() failed"); + retval = -1; + } + } #else - if ( pthread_mutex_lock(&mutex->id) < 0 ) { - SDL_SetError("pthread_mutex_lock() failed"); - retval = -1; - } + if (pthread_mutex_lock(&mutex->id) < 0) { + SDL_SetError("pthread_mutex_lock() failed"); + retval = -1; + } #endif - return retval; + return retval; } -int SDL_mutexV(SDL_mutex *mutex) +int +SDL_mutexV(SDL_mutex * mutex) { - int retval; + int retval; - if ( mutex == NULL ) { - SDL_SetError("Passed a NULL mutex"); - return -1; - } + if (mutex == NULL) { + SDL_SetError("Passed a NULL mutex"); + return -1; + } - retval = 0; + retval = 0; #if SDL_THREAD_PTHREAD_NO_RECURSIVE_MUTEX - /* We can only unlock the mutex if we own it */ - if ( pthread_self() == mutex->owner ) { - if ( mutex->recursive ) { - --mutex->recursive; - } else { - /* The order of operations is important. - First reset the owner so another thread doesn't lock - the mutex and set the ownership before we reset it, - then release the lock semaphore. - */ - mutex->owner = 0; - pthread_mutex_unlock(&mutex->id); - } - } else { - SDL_SetError("mutex not owned by this thread"); - retval = -1; - } + /* We can only unlock the mutex if we own it */ + if (pthread_self() == mutex->owner) { + if (mutex->recursive) { + --mutex->recursive; + } else { + /* The order of operations is important. + First reset the owner so another thread doesn't lock + the mutex and set the ownership before we reset it, + then release the lock semaphore. + */ + mutex->owner = 0; + pthread_mutex_unlock(&mutex->id); + } + } else { + SDL_SetError("mutex not owned by this thread"); + retval = -1; + } #else - if ( pthread_mutex_unlock(&mutex->id) < 0 ) { - SDL_SetError("pthread_mutex_unlock() failed"); - retval = -1; - } + if (pthread_mutex_unlock(&mutex->id) < 0) { + SDL_SetError("pthread_mutex_unlock() failed"); + retval = -1; + } #endif /* SDL_THREAD_PTHREAD_NO_RECURSIVE_MUTEX */ - return retval; + return retval; } #endif +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/thread/riscos/SDL_sysmutex_c.h b/src/thread/riscos/SDL_sysmutex_c.h index fcd03d256..65fc2e314 100644 --- a/src/thread/riscos/SDL_sysmutex_c.h +++ b/src/thread/riscos/SDL_sysmutex_c.h @@ -25,10 +25,12 @@ #define _SDL_mutex_c_h #if !SDL_THREADS_DISABLED -struct SDL_mutex { - pthread_mutex_t id; +struct SDL_mutex +{ + pthread_mutex_t id; }; #endif #endif /* _SDL_mutex_c_h */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/thread/riscos/SDL_syssem.c b/src/thread/riscos/SDL_syssem.c index 775eee355..23e8fb562 100644 --- a/src/thread/riscos/SDL_syssem.c +++ b/src/thread/riscos/SDL_syssem.c @@ -19,9 +19,6 @@ Sam Lantinga slouken@libsdl.org */ - -#include - #include "SDL_config.h" /* RISC OS semiphores based on linux code */ @@ -33,171 +30,188 @@ #if !SDL_THREADS_DISABLED -SDL_sem *SDL_CreateSemaphore(Uint32 initial_value) +SDL_sem * +SDL_CreateSemaphore(Uint32 initial_value) { - SDL_SetError("SDL not configured with thread support"); - return (SDL_sem *)0; + SDL_SetError("SDL not configured with thread support"); + return (SDL_sem *) 0; } -void SDL_DestroySemaphore(SDL_sem *sem) +void +SDL_DestroySemaphore(SDL_sem * sem) { - return; + return; } -int SDL_SemTryWait(SDL_sem *sem) +int +SDL_SemTryWait(SDL_sem * sem) { - SDL_SetError("SDL not configured with thread support"); - return -1; + SDL_SetError("SDL not configured with thread support"); + return -1; } -int SDL_SemWaitTimeout(SDL_sem *sem, Uint32 timeout) +int +SDL_SemWaitTimeout(SDL_sem * sem, Uint32 timeout) { - SDL_SetError("SDL not configured with thread support"); - return -1; + SDL_SetError("SDL not configured with thread support"); + return -1; } -int SDL_SemWait(SDL_sem *sem) +int +SDL_SemWait(SDL_sem * sem) { - SDL_SetError("SDL not configured with thread support"); - return -1; + SDL_SetError("SDL not configured with thread support"); + return -1; } -Uint32 SDL_SemValue(SDL_sem *sem) +Uint32 +SDL_SemValue(SDL_sem * sem) { - return 0; + return 0; } -int SDL_SemPost(SDL_sem *sem) +int +SDL_SemPost(SDL_sem * sem) { - SDL_SetError("SDL not configured with thread support"); - return -1; + SDL_SetError("SDL not configured with thread support"); + return -1; } #else -#include /* For getpid() */ +#include /* For getpid() */ #include #include -struct SDL_semaphore { - sem_t *sem; - sem_t sem_data; +struct SDL_semaphore +{ + sem_t *sem; + sem_t sem_data; }; /* Create a semaphore, initialized with value */ -SDL_sem *SDL_CreateSemaphore(Uint32 initial_value) +SDL_sem * +SDL_CreateSemaphore(Uint32 initial_value) { - SDL_sem *sem = (SDL_sem *) SDL_malloc(sizeof(SDL_sem)); - if ( sem ) { - if ( sem_init(&sem->sem_data, 0, initial_value) < 0 ) { - SDL_SetError("sem_init() failed"); - SDL_free(sem); - sem = NULL; - } else { - sem->sem = &sem->sem_data; - } - } else { - SDL_OutOfMemory(); - } - return sem; + SDL_sem *sem = (SDL_sem *) SDL_malloc(sizeof(SDL_sem)); + if (sem) { + if (sem_init(&sem->sem_data, 0, initial_value) < 0) { + SDL_SetError("sem_init() failed"); + SDL_free(sem); + sem = NULL; + } else { + sem->sem = &sem->sem_data; + } + } else { + SDL_OutOfMemory(); + } + return sem; } -void SDL_DestroySemaphore(SDL_sem *sem) +void +SDL_DestroySemaphore(SDL_sem * sem) { - if ( sem ) { - sem_destroy(sem->sem); - SDL_free(sem); - } + if (sem) { + sem_destroy(sem->sem); + SDL_free(sem); + } } -int SDL_SemTryWait(SDL_sem *sem) +int +SDL_SemTryWait(SDL_sem * sem) { - int retval; - - if ( ! sem ) { - SDL_SetError("Passed a NULL semaphore"); - return -1; - } - retval = SDL_MUTEX_TIMEDOUT; - if ( sem_trywait(sem->sem) == 0 ) { - retval = 0; - } - return retval; + int retval; + + if (!sem) { + SDL_SetError("Passed a NULL semaphore"); + return -1; + } + retval = SDL_MUTEX_TIMEDOUT; + if (sem_trywait(sem->sem) == 0) { + retval = 0; + } + return retval; } -int SDL_SemWait(SDL_sem *sem) +int +SDL_SemWait(SDL_sem * sem) { - int retval; - - if ( ! sem ) { - SDL_SetError("Passed a NULL semaphore"); - return -1; - } - - while ( ((retval = sem_wait(sem->sem)) == -1) && (errno == EINTR) ) {} - if ( retval < 0 ) { - SDL_SetError("sem_wait() failed"); - } - return retval; + int retval; + + if (!sem) { + SDL_SetError("Passed a NULL semaphore"); + return -1; + } + + retval = sem_wait(sem->sem); + if (retval < 0) { + SDL_SetError("sem_wait() failed"); + } + return retval; } -int SDL_SemWaitTimeout(SDL_sem *sem, Uint32 timeout) +int +SDL_SemWaitTimeout(SDL_sem * sem, Uint32 timeout) { - int retval; - - if ( ! sem ) { - SDL_SetError("Passed a NULL semaphore"); - return -1; - } - - /* Try the easy cases first */ - if ( timeout == 0 ) { - return SDL_SemTryWait(sem); - } - if ( timeout == SDL_MUTEX_MAXWAIT ) { - return SDL_SemWait(sem); - } - - /* Ack! We have to busy wait... */ - timeout += SDL_GetTicks(); - do { - retval = SDL_SemTryWait(sem); - if ( retval == 0 ) { - break; - } - SDL_Delay(1); - } while ( SDL_GetTicks() < timeout ); - - return retval; + int retval; + + if (!sem) { + SDL_SetError("Passed a NULL semaphore"); + return -1; + } + + /* Try the easy cases first */ + if (timeout == 0) { + return SDL_SemTryWait(sem); + } + if (timeout == SDL_MUTEX_MAXWAIT) { + return SDL_SemWait(sem); + } + + /* Ack! We have to busy wait... */ + timeout += SDL_GetTicks(); + do { + retval = SDL_SemTryWait(sem); + if (retval == 0) { + break; + } + SDL_Delay(1); + } + while (SDL_GetTicks() < timeout); + + return retval; } -Uint32 SDL_SemValue(SDL_sem *sem) +Uint32 +SDL_SemValue(SDL_sem * sem) { - int ret = 0; - if ( sem ) { - sem_getvalue(sem->sem, &ret); - if ( ret < 0 ) { - ret = 0; - } - } - return (Uint32)ret; + int ret = 0; + if (sem) { + sem_getvalue(sem->sem, &ret); + if (ret < 0) { + ret = 0; + } + } + return (Uint32) ret; } -int SDL_SemPost(SDL_sem *sem) +int +SDL_SemPost(SDL_sem * sem) { - int retval; - - if ( ! sem ) { - SDL_SetError("Passed a NULL semaphore"); - return -1; - } - - retval = sem_post(sem->sem); - if ( retval < 0 ) { - SDL_SetError("sem_post() failed"); - } - return retval; + int retval; + + if (!sem) { + SDL_SetError("Passed a NULL semaphore"); + return -1; + } + + retval = sem_post(sem->sem); + if (retval < 0) { + SDL_SetError("sem_post() failed"); + } + return retval; } #endif /* !SDL_THREADS_DISABLED */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/thread/riscos/SDL_systhread.c b/src/thread/riscos/SDL_systhread.c index 318bb9d60..1b9326e72 100644 --- a/src/thread/riscos/SDL_systhread.c +++ b/src/thread/riscos/SDL_systhread.c @@ -28,30 +28,36 @@ #if SDL_THREADS_DISABLED -int SDL_SYS_CreateThread(SDL_Thread *thread, void *args) +int +SDL_SYS_CreateThread(SDL_Thread * thread, void *args) { - SDL_SetError("Threads have not been compiled into this version of the library"); - return(-1); + SDL_SetError + ("Threads have not been compiled into this version of the library"); + return (-1); } -void SDL_SYS_SetupThread(void) +void +SDL_SYS_SetupThread(void) { - return; + return; } -Uint32 SDL_ThreadID(void) +Uint32 +SDL_ThreadID(void) { - return(0); + return (0); } -void SDL_SYS_WaitThread(SDL_Thread *thread) +void +SDL_SYS_WaitThread(SDL_Thread * thread) { - return; + return; } -void SDL_SYS_KillThread(SDL_Thread *thread) +void +SDL_SYS_KillThread(SDL_Thread * thread) { - return; + return; } #else @@ -60,85 +66,92 @@ void SDL_SYS_KillThread(SDL_Thread *thread) /* List of signals to mask in the subthreads */ static int sig_list[] = { - SIGHUP, SIGINT, SIGQUIT, SIGPIPE, SIGALRM, SIGTERM, SIGCHLD, SIGWINCH, - SIGVTALRM, SIGPROF, 0 + SIGHUP, SIGINT, SIGQUIT, SIGPIPE, SIGALRM, SIGTERM, SIGCHLD, SIGWINCH, + SIGVTALRM, SIGPROF, 0 }; #include int riscos_using_threads = 0; -Uint32 riscos_main_thread = 0; /* Thread running events */ +Uint32 riscos_main_thread = 0; /* Thread running events */ -static void *RunThread(void *data) +static void * +RunThread(void *data) { - SDL_RunThread(data); - pthread_exit((void*)0); - return((void *)0); /* Prevent compiler warning */ + SDL_RunThread(data); + pthread_exit((void *) 0); + return ((void *) 0); /* Prevent compiler warning */ } -int SDL_SYS_CreateThread(SDL_Thread *thread, void *args) +int +SDL_SYS_CreateThread(SDL_Thread * thread, void *args) { - pthread_attr_t type; - - /* Set the thread attributes */ - if ( pthread_attr_init(&type) != 0 ) { - SDL_SetError("Couldn't initialize pthread attributes"); - return(-1); - } - pthread_attr_setdetachstate(&type, PTHREAD_CREATE_JOINABLE); - - /* Create the thread and go! */ - if ( pthread_create(&thread->handle, &type, RunThread, args) != 0 ) { - SDL_SetError("Not enough resources to create thread"); - return(-1); - } - - if (riscos_using_threads == 0) - { - riscos_using_threads = 1; - riscos_main_thread = SDL_ThreadID(); - } - - return(0); + pthread_attr_t type; + + /* Set the thread attributes */ + if (pthread_attr_init(&type) != 0) { + SDL_SetError("Couldn't initialize pthread attributes"); + return (-1); + } + pthread_attr_setdetachstate(&type, PTHREAD_CREATE_JOINABLE); + + /* Create the thread and go! */ + if (pthread_create(&thread->handle, &type, RunThread, args) != 0) { + SDL_SetError("Not enough resources to create thread"); + return (-1); + } + + if (riscos_using_threads == 0) { + riscos_using_threads = 1; + riscos_main_thread = SDL_ThreadID(); + } + + return (0); } -void SDL_SYS_SetupThread(void) +void +SDL_SYS_SetupThread(void) { - int i; - sigset_t mask; - - /* Mask asynchronous signals for this thread */ - sigemptyset(&mask); - for ( i=0; sig_list[i]; ++i ) { - sigaddset(&mask, sig_list[i]); - } - pthread_sigmask(SIG_BLOCK, &mask, 0); - + int i; + sigset_t mask; + + /* Mask asynchronous signals for this thread */ + sigemptyset(&mask); + for (i = 0; sig_list[i]; ++i) { + sigaddset(&mask, sig_list[i]); + } + pthread_sigmask(SIG_BLOCK, &mask, 0); + #ifdef PTHREAD_CANCEL_ASYNCHRONOUS - /* Allow ourselves to be asynchronously cancelled */ - { int oldstate; - pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &oldstate); - } + /* Allow ourselves to be asynchronously cancelled */ + { + int oldstate; + pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &oldstate); + } #endif } -Uint32 SDL_ThreadID(void) +Uint32 +SDL_ThreadID(void) { - return((Uint32)pthread_self()); + return ((Uint32) pthread_self()); } -void SDL_SYS_WaitThread(SDL_Thread *thread) +void +SDL_SYS_WaitThread(SDL_Thread * thread) { - pthread_join(thread->handle, 0); + pthread_join(thread->handle, 0); } -void SDL_SYS_KillThread(SDL_Thread *thread) +void +SDL_SYS_KillThread(SDL_Thread * thread) { #ifdef PTHREAD_CANCEL_ASYNCHRONOUS - pthread_cancel(thread->handle); + pthread_cancel(thread->handle); #else - pthread_kill(thread->handle, SIGKILL); + pthread_kill(thread->handle, SIGKILL); #endif } #endif +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/thread/riscos/SDL_systhread_c.h b/src/thread/riscos/SDL_systhread_c.h index 22867a627..aa9357e5f 100644 --- a/src/thread/riscos/SDL_systhread_c.h +++ b/src/thread/riscos/SDL_systhread_c.h @@ -32,3 +32,4 @@ typedef int SYS_ThreadHandle; typedef pthread_t SYS_ThreadHandle; #endif +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/thread/win32/SDL_sysmutex.c b/src/thread/win32/SDL_sysmutex.c index da8382927..e133fc6e2 100644 --- a/src/thread/win32/SDL_sysmutex.c +++ b/src/thread/win32/SDL_sysmutex.c @@ -29,67 +29,74 @@ #include "SDL_mutex.h" -struct SDL_mutex { - HANDLE id; +struct SDL_mutex +{ + HANDLE id; }; /* Create a mutex */ -SDL_mutex *SDL_CreateMutex(void) +SDL_mutex * +SDL_CreateMutex(void) { - SDL_mutex *mutex; + SDL_mutex *mutex; - /* Allocate mutex memory */ - mutex = (SDL_mutex *)SDL_malloc(sizeof(*mutex)); - if ( mutex ) { - /* Create the mutex, with initial value signaled */ - mutex->id = CreateMutex(NULL, FALSE, NULL); - if ( ! mutex->id ) { - SDL_SetError("Couldn't create mutex"); - SDL_free(mutex); - mutex = NULL; - } - } else { - SDL_OutOfMemory(); - } - return(mutex); + /* Allocate mutex memory */ + mutex = (SDL_mutex *) SDL_malloc(sizeof(*mutex)); + if (mutex) { + /* Create the mutex, with initial value signaled */ + mutex->id = CreateMutex(NULL, FALSE, NULL); + if (!mutex->id) { + SDL_SetError("Couldn't create mutex"); + SDL_free(mutex); + mutex = NULL; + } + } else { + SDL_OutOfMemory(); + } + return (mutex); } /* Free the mutex */ -void SDL_DestroyMutex(SDL_mutex *mutex) +void +SDL_DestroyMutex(SDL_mutex * mutex) { - if ( mutex ) { - if ( mutex->id ) { - CloseHandle(mutex->id); - mutex->id = 0; - } - SDL_free(mutex); - } + if (mutex) { + if (mutex->id) { + CloseHandle(mutex->id); + mutex->id = 0; + } + SDL_free(mutex); + } } /* Lock the mutex */ -int SDL_mutexP(SDL_mutex *mutex) +int +SDL_mutexP(SDL_mutex * mutex) { - if ( mutex == NULL ) { - SDL_SetError("Passed a NULL mutex"); - return -1; - } - if ( WaitForSingleObject(mutex->id, INFINITE) == WAIT_FAILED ) { - SDL_SetError("Couldn't wait on mutex"); - return -1; - } - return(0); + if (mutex == NULL) { + SDL_SetError("Passed a NULL mutex"); + return -1; + } + if (WaitForSingleObject(mutex->id, INFINITE) == WAIT_FAILED) { + SDL_SetError("Couldn't wait on mutex"); + return -1; + } + return (0); } /* Unlock the mutex */ -int SDL_mutexV(SDL_mutex *mutex) +int +SDL_mutexV(SDL_mutex * mutex) { - if ( mutex == NULL ) { - SDL_SetError("Passed a NULL mutex"); - return -1; - } - if ( ReleaseMutex(mutex->id) == FALSE ) { - SDL_SetError("Couldn't release mutex"); - return -1; - } - return(0); + if (mutex == NULL) { + SDL_SetError("Passed a NULL mutex"); + return -1; + } + if (ReleaseMutex(mutex->id) == FALSE) { + SDL_SetError("Couldn't release mutex"); + return -1; + } + return (0); } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/thread/win32/SDL_syssem.c b/src/thread/win32/SDL_syssem.c index c7a1bfd53..c398c2c23 100644 --- a/src/thread/win32/SDL_syssem.c +++ b/src/thread/win32/SDL_syssem.c @@ -32,133 +32,143 @@ #endif -struct SDL_semaphore { +struct SDL_semaphore +{ #if defined(_WIN32_WCE) && (_WIN32_WCE < 300) - SYNCHHANDLE id; + SYNCHHANDLE id; #else - HANDLE id; + HANDLE id; #endif - Uint32 volatile count; + Uint32 volatile count; }; /* Create a semaphore */ -SDL_sem *SDL_CreateSemaphore(Uint32 initial_value) +SDL_sem * +SDL_CreateSemaphore(Uint32 initial_value) { - SDL_sem *sem; + SDL_sem *sem; - /* Allocate sem memory */ - sem = (SDL_sem *)SDL_malloc(sizeof(*sem)); - if ( sem ) { - /* Create the semaphore, with max value 32K */ + /* Allocate sem memory */ + sem = (SDL_sem *) SDL_malloc(sizeof(*sem)); + if (sem) { + /* Create the semaphore, with max value 32K */ #if defined(_WIN32_WCE) && (_WIN32_WCE < 300) - sem->id = CreateSemaphoreCE(NULL, initial_value, 32*1024, NULL); + sem->id = CreateSemaphoreCE(NULL, initial_value, 32 * 1024, NULL); #else - sem->id = CreateSemaphore(NULL, initial_value, 32*1024, NULL); + sem->id = CreateSemaphore(NULL, initial_value, 32 * 1024, NULL); #endif - sem->count = initial_value; - if ( ! sem->id ) { - SDL_SetError("Couldn't create semaphore"); - SDL_free(sem); - sem = NULL; - } - } else { - SDL_OutOfMemory(); - } - return(sem); + sem->count = initial_value; + if (!sem->id) { + SDL_SetError("Couldn't create semaphore"); + SDL_free(sem); + sem = NULL; + } + } else { + SDL_OutOfMemory(); + } + return (sem); } /* Free the semaphore */ -void SDL_DestroySemaphore(SDL_sem *sem) +void +SDL_DestroySemaphore(SDL_sem * sem) { - if ( sem ) { - if ( sem->id ) { + if (sem) { + if (sem->id) { #if defined(_WIN32_WCE) && (_WIN32_WCE < 300) - CloseSynchHandle(sem->id); + CloseSynchHandle(sem->id); #else - CloseHandle(sem->id); + CloseHandle(sem->id); #endif - sem->id = 0; - } - SDL_free(sem); - } + sem->id = 0; + } + SDL_free(sem); + } } -int SDL_SemWaitTimeout(SDL_sem *sem, Uint32 timeout) +int +SDL_SemWaitTimeout(SDL_sem * sem, Uint32 timeout) { - int retval; - DWORD dwMilliseconds; - - if ( ! sem ) { - SDL_SetError("Passed a NULL sem"); - return -1; - } - - if ( timeout == SDL_MUTEX_MAXWAIT ) { - dwMilliseconds = INFINITE; - } else { - dwMilliseconds = (DWORD)timeout; - } + int retval; + DWORD dwMilliseconds; + + if (!sem) { + SDL_SetError("Passed a NULL sem"); + return -1; + } + + if (timeout == SDL_MUTEX_MAXWAIT) { + dwMilliseconds = INFINITE; + } else { + dwMilliseconds = (DWORD) timeout; + } #if defined(_WIN32_WCE) && (_WIN32_WCE < 300) - switch (WaitForSemaphoreCE(sem->id, dwMilliseconds)) { + switch (WaitForSemaphoreCE(sem->id, dwMilliseconds)) { #else - switch (WaitForSingleObject(sem->id, dwMilliseconds)) { + switch (WaitForSingleObject(sem->id, dwMilliseconds)) { #endif - case WAIT_OBJECT_0: - --sem->count; - retval = 0; - break; - case WAIT_TIMEOUT: - retval = SDL_MUTEX_TIMEDOUT; - break; - default: - SDL_SetError("WaitForSingleObject() failed"); - retval = -1; - break; - } - return retval; + case WAIT_OBJECT_0: + --sem->count; + retval = 0; + break; + case WAIT_TIMEOUT: + retval = SDL_MUTEX_TIMEDOUT; + break; + default: + SDL_SetError("WaitForSingleObject() failed"); + retval = -1; + break; + } + return retval; } -int SDL_SemTryWait(SDL_sem *sem) +int +SDL_SemTryWait(SDL_sem * sem) { - return SDL_SemWaitTimeout(sem, 0); + return SDL_SemWaitTimeout(sem, 0); } -int SDL_SemWait(SDL_sem *sem) +int +SDL_SemWait(SDL_sem * sem) { - return SDL_SemWaitTimeout(sem, SDL_MUTEX_MAXWAIT); + return SDL_SemWaitTimeout(sem, SDL_MUTEX_MAXWAIT); } /* Returns the current count of the semaphore */ -Uint32 SDL_SemValue(SDL_sem *sem) +Uint32 +SDL_SemValue(SDL_sem * sem) { - if ( ! sem ) { - SDL_SetError("Passed a NULL sem"); - return 0; - } - return sem->count; + if (!sem) { + SDL_SetError("Passed a NULL sem"); + return 0; + } + return sem->count; } -int SDL_SemPost(SDL_sem *sem) +int +SDL_SemPost(SDL_sem * sem) { - if ( ! sem ) { - SDL_SetError("Passed a NULL sem"); - return -1; - } - /* Increase the counter in the first place, because - * after a successful release the semaphore may - * immediately get destroyed by another thread which - * is waiting for this semaphore. - */ - ++sem->count; + if (!sem) { + SDL_SetError("Passed a NULL sem"); + return -1; + } + /* Increase the counter in the first place, because + * after a successful release the semaphore may + * immediately get destroyed by another thread which + * is waiting for this semaphore. + */ + ++sem->count; #if defined(_WIN32_WCE) && (_WIN32_WCE < 300) - if ( ReleaseSemaphoreCE(sem->id, 1, NULL) == FALSE ) { + if (ReleaseSemaphoreCE(sem->id, 1, NULL) == FALSE) { #else - if ( ReleaseSemaphore(sem->id, 1, NULL) == FALSE ) { + if (ReleaseSemaphore(sem->id, 1, NULL) == FALSE) { #endif - --sem->count; /* restore */ - SDL_SetError("ReleaseSemaphore() failed"); - return -1; - } - return 0; + --sem->count; /* restore */ + SDL_SetError("ReleaseSemaphore() failed"); + return -1; + } + return 0; } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/thread/win32/SDL_systhread.c b/src/thread/win32/SDL_systhread.c index 67b176dfb..32273c334 100644 --- a/src/thread/win32/SDL_systhread.c +++ b/src/thread/win32/SDL_systhread.c @@ -37,114 +37,141 @@ #endif #if __GNUC__ -typedef unsigned long (__cdecl *pfnSDL_CurrentBeginThread) (void *, unsigned, - unsigned (__stdcall *func)(void *), void *arg, - unsigned, unsigned *threadID); -typedef void (__cdecl *pfnSDL_CurrentEndThread)(unsigned code); +typedef unsigned long (__cdecl * pfnSDL_CurrentBeginThread) (void *, unsigned, + unsigned + (__stdcall * + func) (void *), + void *arg, + unsigned, + unsigned + *threadID); +typedef void (__cdecl * pfnSDL_CurrentEndThread) (unsigned code); #elif defined(__WATCOMC__) /* This is for Watcom targets except OS2 */ #if __WATCOMC__ < 1240 #define __watcall #endif -typedef unsigned long (__watcall *pfnSDL_CurrentBeginThread) (void *, unsigned, - unsigned (__stdcall *func)(void *), void *arg, - unsigned, unsigned *threadID); -typedef void (__watcall *pfnSDL_CurrentEndThread)(unsigned code); +typedef unsigned long (__watcall * pfnSDL_CurrentBeginThread) (void *, + unsigned, + unsigned + (__stdcall * + func) (void + *), + void *arg, + unsigned, + unsigned + *threadID); +typedef void (__watcall * pfnSDL_CurrentEndThread) (unsigned code); #else -typedef uintptr_t (__cdecl *pfnSDL_CurrentBeginThread) (void *, unsigned, - unsigned (__stdcall *func)(void *), void *arg, - unsigned, unsigned *threadID); -typedef void (__cdecl *pfnSDL_CurrentEndThread)(unsigned code); +typedef uintptr_t(__cdecl * pfnSDL_CurrentBeginThread) (void *, unsigned, + unsigned (__stdcall * + func) (void + *), + void *arg, unsigned, + unsigned *threadID); +typedef void (__cdecl * pfnSDL_CurrentEndThread) (unsigned code); #endif #endif /* !SDL_PASSED_BEGINTHREAD_ENDTHREAD */ typedef struct ThreadStartParms { - void *args; - pfnSDL_CurrentEndThread pfnCurrentEndThread; + void *args; + pfnSDL_CurrentEndThread pfnCurrentEndThread; } tThreadStartParms, *pThreadStartParms; -static unsigned __stdcall RunThread(void *data) +static unsigned __stdcall +RunThread(void *data) { - pThreadStartParms pThreadParms = (pThreadStartParms)data; - pfnSDL_CurrentEndThread pfnCurrentEndThread = NULL; - - // Call the thread function! - SDL_RunThread(pThreadParms->args); - - // Get the current endthread we have to use! - if (pThreadParms) - { - pfnCurrentEndThread = pThreadParms->pfnCurrentEndThread; - SDL_free(pThreadParms); - } - // Call endthread! - if (pfnCurrentEndThread) - (*pfnCurrentEndThread)(0); - return(0); + pThreadStartParms pThreadParms = (pThreadStartParms) data; + pfnSDL_CurrentEndThread pfnCurrentEndThread = NULL; + + // Call the thread function! + SDL_RunThread(pThreadParms->args); + + // Get the current endthread we have to use! + if (pThreadParms) { + pfnCurrentEndThread = pThreadParms->pfnCurrentEndThread; + SDL_free(pThreadParms); + } + // Call endthread! + if (pfnCurrentEndThread) + (*pfnCurrentEndThread) (0); + return (0); } #ifdef SDL_PASSED_BEGINTHREAD_ENDTHREAD -int SDL_SYS_CreateThread(SDL_Thread *thread, void *args, pfnSDL_CurrentBeginThread pfnBeginThread, pfnSDL_CurrentEndThread pfnEndThread) +int +SDL_SYS_CreateThread(SDL_Thread * thread, void *args, + pfnSDL_CurrentBeginThread pfnBeginThread, + pfnSDL_CurrentEndThread pfnEndThread) { #else -int SDL_SYS_CreateThread(SDL_Thread *thread, void *args) +int +SDL_SYS_CreateThread(SDL_Thread * thread, void *args) { #ifdef _WIN32_WCE - pfnSDL_CurrentBeginThread pfnBeginThread = NULL; - pfnSDL_CurrentEndThread pfnEndThread = NULL; + pfnSDL_CurrentBeginThread pfnBeginThread = NULL; + pfnSDL_CurrentEndThread pfnEndThread = NULL; #else - pfnSDL_CurrentBeginThread pfnBeginThread = _beginthreadex; - pfnSDL_CurrentEndThread pfnEndThread = _endthreadex; + pfnSDL_CurrentBeginThread pfnBeginThread = _beginthreadex; + pfnSDL_CurrentEndThread pfnEndThread = _endthreadex; #endif #endif /* SDL_PASSED_BEGINTHREAD_ENDTHREAD */ - unsigned threadid; - pThreadStartParms pThreadParms = (pThreadStartParms)SDL_malloc(sizeof(tThreadStartParms)); - if (!pThreadParms) { - SDL_OutOfMemory(); - return(-1); - } - - // Save the function which we will have to call to clear the RTL of calling app! - pThreadParms->pfnCurrentEndThread = pfnEndThread; - // Also save the real parameters we have to pass to thread function - pThreadParms->args = args; - - if (pfnBeginThread) { - thread->handle = (SYS_ThreadHandle) pfnBeginThread(NULL, 0, RunThread, - pThreadParms, 0, &threadid); - } else { - thread->handle = CreateThread(NULL, 0, RunThread, pThreadParms, 0, &threadid); - } - if (thread->handle == NULL) { - SDL_SetError("Not enough resources to create thread"); - return(-1); - } - return(0); + unsigned threadid; + pThreadStartParms pThreadParms = + (pThreadStartParms) SDL_malloc(sizeof(tThreadStartParms)); + if (!pThreadParms) { + SDL_OutOfMemory(); + return (-1); + } + // Save the function which we will have to call to clear the RTL of calling app! + pThreadParms->pfnCurrentEndThread = pfnEndThread; + // Also save the real parameters we have to pass to thread function + pThreadParms->args = args; + + if (pfnBeginThread) { + thread->handle = + (SYS_ThreadHandle) pfnBeginThread(NULL, 0, RunThread, + pThreadParms, 0, &threadid); + } else { + thread->handle = + CreateThread(NULL, 0, RunThread, pThreadParms, 0, &threadid); + } + if (thread->handle == NULL) { + SDL_SetError("Not enough resources to create thread"); + return (-1); + } + return (0); } -void SDL_SYS_SetupThread(void) +void +SDL_SYS_SetupThread(void) { - return; + return; } -Uint32 SDL_ThreadID(void) +Uint32 +SDL_ThreadID(void) { - return((Uint32)GetCurrentThreadId()); + return ((Uint32) GetCurrentThreadId()); } -void SDL_SYS_WaitThread(SDL_Thread *thread) +void +SDL_SYS_WaitThread(SDL_Thread * thread) { - WaitForSingleObject(thread->handle, INFINITE); - CloseHandle(thread->handle); + WaitForSingleObject(thread->handle, INFINITE); + CloseHandle(thread->handle); } /* WARNING: This function is really a last resort. * Threads should be signaled and then exit by themselves. * TerminateThread() doesn't perform stack and DLL cleanup. */ -void SDL_SYS_KillThread(SDL_Thread *thread) +void +SDL_SYS_KillThread(SDL_Thread * thread) { - TerminateThread(thread->handle, FALSE); + TerminateThread(thread->handle, FALSE); } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/thread/win32/SDL_systhread_c.h b/src/thread/win32/SDL_systhread_c.h index 906a9586a..b1c719172 100644 --- a/src/thread/win32/SDL_systhread_c.h +++ b/src/thread/win32/SDL_systhread_c.h @@ -25,4 +25,4 @@ #include typedef HANDLE SYS_ThreadHandle; - +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/thread/win32/win_ce_semaphore.c b/src/thread/win32/win_ce_semaphore.c index 9db45c439..a44fc34f5 100644 --- a/src/thread/win32/win_ce_semaphore.c +++ b/src/thread/win32/win_ce_semaphore.c @@ -33,15 +33,13 @@ #include "win_ce_semaphore.h" -static SYNCHHANDLE CleanUp (SYNCHHANDLE hSynch, DWORD Flags); - -SYNCHHANDLE CreateSemaphoreCE ( - - LPSECURITY_ATTRIBUTES lpSemaphoreAttributes, /* pointer to security attributes */ - LONG lInitialCount, /* initial count */ - LONG lMaximumCount, /* maximum count */ - LPCTSTR lpName ) +static SYNCHHANDLE CleanUp(SYNCHHANDLE hSynch, DWORD Flags); +SYNCHHANDLE +CreateSemaphoreCE(LPSECURITY_ATTRIBUTES lpSemaphoreAttributes, /* pointer to security attributes */ + LONG lInitialCount, /* initial count */ + LONG lMaximumCount, /* maximum count */ + LPCTSTR lpName) /* Semaphore for use with Windows CE that does not support them directly. Requires a counter, a mutex to protect the counter, and an autoreset event. @@ -57,160 +55,174 @@ SYNCHHANDLE CreateSemaphoreCE ( 2. The event is in a signaled state if and only if the current semaphore count ("CurCount") is greater than zero. 3. The semaphore count is always >= 0 and <= the maximum count */ - { - SYNCHHANDLE hSynch = NULL, result = NULL; - - __try - { - if (lInitialCount > lMaximumCount || lMaximumCount < 0 || lInitialCount < 0) - { - /* Bad parameters */ - SetLastError (SYNCH_ERROR); - __leave; - } - - hSynch = HeapAlloc (GetProcessHeap(), HEAP_ZERO_MEMORY, SYNCH_HANDLE_SIZE); - if (hSynch == NULL) __leave; - - hSynch->MaxCount = lMaximumCount; - hSynch->CurCount = lInitialCount; - hSynch->lpName = lpName; - - hSynch->hMutex = CreateMutex (lpSemaphoreAttributes, FALSE, NULL); - - WaitForSingleObject (hSynch->hMutex, INFINITE); - /* Create the event. It is initially signaled if and only if the - initial count is > 0 */ - hSynch->hEvent = CreateEvent (lpSemaphoreAttributes, FALSE, - lInitialCount > 0, NULL); - ReleaseMutex (hSynch->hMutex); - hSynch->hSemph = NULL; - } - __finally - { - /* Return with the handle, or, if there was any error, return - a null after closing any open handles and freeing any allocated memory. */ - result=CleanUp(hSynch, 6 /* An event and a mutex, but no semaphore. */); - } - - return result; + SYNCHHANDLE hSynch = NULL, result = NULL; + + __try { + if (lInitialCount > lMaximumCount || lMaximumCount < 0 + || lInitialCount < 0) { + /* Bad parameters */ + SetLastError(SYNCH_ERROR); + __leave; + } + + hSynch = + HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, SYNCH_HANDLE_SIZE); + if (hSynch == NULL) + __leave; + + hSynch->MaxCount = lMaximumCount; + hSynch->CurCount = lInitialCount; + hSynch->lpName = lpName; + + hSynch->hMutex = CreateMutex(lpSemaphoreAttributes, FALSE, NULL); + + WaitForSingleObject(hSynch->hMutex, INFINITE); + /* Create the event. It is initially signaled if and only if the + initial count is > 0 */ + hSynch->hEvent = CreateEvent(lpSemaphoreAttributes, FALSE, + lInitialCount > 0, NULL); + ReleaseMutex(hSynch->hMutex); + hSynch->hSemph = NULL; + } + __finally { + /* Return with the handle, or, if there was any error, return + a null after closing any open handles and freeing any allocated memory. */ + result = + CleanUp(hSynch, 6 /* An event and a mutex, but no semaphore. */ ); + } + + return result; } -BOOL ReleaseSemaphoreCE (SYNCHHANDLE hSemCE, LONG cReleaseCount, LPLONG lpPreviousCount) +BOOL +ReleaseSemaphoreCE(SYNCHHANDLE hSemCE, LONG cReleaseCount, + LPLONG lpPreviousCount) /* Windows CE equivalent to ReleaseSemaphore. */ { - BOOL Result = TRUE; - - /* Gain access to the object to assure that the release count - would not cause the total count to exceed the maximum. */ - - __try - { - WaitForSingleObject (hSemCE->hMutex, INFINITE); - /* reply only if asked to */ - if (lpPreviousCount!=NULL) - *lpPreviousCount = hSemCE->CurCount; - if (hSemCE->CurCount + cReleaseCount > hSemCE->MaxCount || cReleaseCount <= 0) - { - SetLastError (SYNCH_ERROR); - Result = FALSE; - __leave; - } - hSemCE->CurCount += cReleaseCount; - - /* Set the autoreset event, releasing exactly one waiting thread, now or - in the future. */ - - SetEvent (hSemCE->hEvent); - } - __finally - { - ReleaseMutex (hSemCE->hMutex); - } - - return Result; + BOOL Result = TRUE; + + /* Gain access to the object to assure that the release count + would not cause the total count to exceed the maximum. */ + + __try { + WaitForSingleObject(hSemCE->hMutex, INFINITE); + /* reply only if asked to */ + if (lpPreviousCount != NULL) + *lpPreviousCount = hSemCE->CurCount; + if (hSemCE->CurCount + cReleaseCount > hSemCE->MaxCount + || cReleaseCount <= 0) { + SetLastError(SYNCH_ERROR); + Result = FALSE; + __leave; + } + hSemCE->CurCount += cReleaseCount; + + /* Set the autoreset event, releasing exactly one waiting thread, now or + in the future. */ + + SetEvent(hSemCE->hEvent); + } + __finally { + ReleaseMutex(hSemCE->hMutex); + } + + return Result; } -DWORD WaitForSemaphoreCE (SYNCHHANDLE hSemCE, DWORD dwMilliseconds) +DWORD +WaitForSemaphoreCE(SYNCHHANDLE hSemCE, DWORD dwMilliseconds) /* Windows CE semaphore equivalent of WaitForSingleObject. */ { - DWORD WaitResult; - - WaitResult = WaitForSingleObject (hSemCE->hMutex, dwMilliseconds); - if (WaitResult != WAIT_OBJECT_0 && WaitResult != WAIT_ABANDONED_0) return WaitResult; - while (hSemCE->CurCount <= 0) - { - - /* The count is 0, and the thread must wait on the event (which, by - the rules, is currently reset) for semaphore resources to become - available. First, of course, the mutex must be released so that another - thread will be capable of setting the event. */ - - ReleaseMutex (hSemCE->hMutex); - - /* Wait for the event to be signaled, indicating a semaphore state change. - The event is autoreset and signaled with a SetEvent (not PulseEvent) - so exactly one waiting thread (whether or not there is currently - a waiting thread) is released as a result of the SetEvent. */ - - WaitResult = WaitForSingleObject (hSemCE->hEvent, dwMilliseconds); - if (WaitResult != WAIT_OBJECT_0) return WaitResult; - - /* This is where the properties of setting of an autoreset event is critical - to assure that, even if the semaphore state changes between the - preceding Wait and the next, and even if NO threads are waiting - on the event at the time of the SetEvent, at least one thread - will be released. - Pulsing a manual reset event would appear to work, but it would have - a defect which could appear if the semaphore state changed between - the two waits. */ - - WaitResult = WaitForSingleObject (hSemCE->hMutex, dwMilliseconds); - if (WaitResult != WAIT_OBJECT_0 && WaitResult != WAIT_ABANDONED_0) return WaitResult; - - } - /* The count is not zero and this thread owns the mutex. */ - - hSemCE->CurCount--; - /* The event is now unsignaled, BUT, the semaphore count may not be - zero, in which case the event should be signaled again - before releasing the mutex. */ - - if (hSemCE->CurCount > 0) SetEvent (hSemCE->hEvent); - ReleaseMutex (hSemCE->hMutex); - return WaitResult; + DWORD WaitResult; + + WaitResult = WaitForSingleObject(hSemCE->hMutex, dwMilliseconds); + if (WaitResult != WAIT_OBJECT_0 && WaitResult != WAIT_ABANDONED_0) + return WaitResult; + while (hSemCE->CurCount <= 0) { + + /* The count is 0, and the thread must wait on the event (which, by + the rules, is currently reset) for semaphore resources to become + available. First, of course, the mutex must be released so that another + thread will be capable of setting the event. */ + + ReleaseMutex(hSemCE->hMutex); + + /* Wait for the event to be signaled, indicating a semaphore state change. + The event is autoreset and signaled with a SetEvent (not PulseEvent) + so exactly one waiting thread (whether or not there is currently + a waiting thread) is released as a result of the SetEvent. */ + + WaitResult = WaitForSingleObject(hSemCE->hEvent, dwMilliseconds); + if (WaitResult != WAIT_OBJECT_0) + return WaitResult; + + /* This is where the properties of setting of an autoreset event is critical + to assure that, even if the semaphore state changes between the + preceding Wait and the next, and even if NO threads are waiting + on the event at the time of the SetEvent, at least one thread + will be released. + Pulsing a manual reset event would appear to work, but it would have + a defect which could appear if the semaphore state changed between + the two waits. */ + + WaitResult = WaitForSingleObject(hSemCE->hMutex, dwMilliseconds); + if (WaitResult != WAIT_OBJECT_0 && WaitResult != WAIT_ABANDONED_0) + return WaitResult; + + } + /* The count is not zero and this thread owns the mutex. */ + + hSemCE->CurCount--; + /* The event is now unsignaled, BUT, the semaphore count may not be + zero, in which case the event should be signaled again + before releasing the mutex. */ + + if (hSemCE->CurCount > 0) + SetEvent(hSemCE->hEvent); + ReleaseMutex(hSemCE->hMutex); + return WaitResult; } -BOOL CloseSynchHandle (SYNCHHANDLE hSynch) +BOOL +CloseSynchHandle(SYNCHHANDLE hSynch) /* Close a synchronization handle. Improvement: Test for a valid handle before dereferencing the handle. */ { - BOOL Result = TRUE; - if (hSynch->hEvent != NULL) Result = Result && CloseHandle (hSynch->hEvent); - if (hSynch->hMutex != NULL) Result = Result && CloseHandle (hSynch->hMutex); - if (hSynch->hSemph != NULL) Result = Result && CloseHandle (hSynch->hSemph); - HeapFree (GetProcessHeap (), 0, hSynch); - return (Result); + BOOL Result = TRUE; + if (hSynch->hEvent != NULL) + Result = Result && CloseHandle(hSynch->hEvent); + if (hSynch->hMutex != NULL) + Result = Result && CloseHandle(hSynch->hMutex); + if (hSynch->hSemph != NULL) + Result = Result && CloseHandle(hSynch->hSemph); + HeapFree(GetProcessHeap(), 0, hSynch); + return (Result); } -static SYNCHHANDLE CleanUp (SYNCHHANDLE hSynch, DWORD Flags) -{ /* Prepare to return from a create of a synchronization handle. - If there was any failure, free any allocated resources. - "Flags" indicates which Win32 objects are required in the - synchronization handle. */ - - BOOL ok = TRUE; - - if (hSynch == NULL) return NULL; - if ((Flags & 4) == 1 && (hSynch->hEvent == NULL)) ok = FALSE; - if ((Flags & 2) == 1 && (hSynch->hMutex == NULL)) ok = FALSE; - if ((Flags & 1) == 1 && (hSynch->hEvent == NULL)) ok = FALSE; - if (!ok) - { - CloseSynchHandle (hSynch); - return NULL; - } - /* Everything worked */ - return hSynch; +static SYNCHHANDLE +CleanUp(SYNCHHANDLE hSynch, DWORD Flags) +{ /* Prepare to return from a create of a synchronization handle. + If there was any failure, free any allocated resources. + "Flags" indicates which Win32 objects are required in the + synchronization handle. */ + + BOOL ok = TRUE; + + if (hSynch == NULL) + return NULL; + if ((Flags & 4) == 1 && (hSynch->hEvent == NULL)) + ok = FALSE; + if ((Flags & 2) == 1 && (hSynch->hMutex == NULL)) + ok = FALSE; + if ((Flags & 1) == 1 && (hSynch->hEvent == NULL)) + ok = FALSE; + if (!ok) { + CloseSynchHandle(hSynch); + return NULL; + } + /* Everything worked */ + return hSynch; } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/thread/win32/win_ce_semaphore.h b/src/thread/win32/win_ce_semaphore.h index af2d7b613..b9f7402eb 100644 --- a/src/thread/win32/win_ce_semaphore.h +++ b/src/thread/win32/win_ce_semaphore.h @@ -1,22 +1,25 @@ /* win_ce_semaphore.h - header file to go with win_ce_semaphore.c */ -typedef struct _SYNCH_HANDLE_STRUCTURE { - HANDLE hEvent; - HANDLE hMutex; - HANDLE hSemph; - LONG MaxCount; - volatile LONG CurCount; - LPCTSTR lpName; +typedef struct _SYNCH_HANDLE_STRUCTURE +{ + HANDLE hEvent; + HANDLE hMutex; + HANDLE hSemph; + LONG MaxCount; + volatile LONG CurCount; + LPCTSTR lpName; } SYNCH_HANDLE_STRUCTURE, *SYNCHHANDLE; #define SYNCH_HANDLE_SIZE sizeof (SYNCH_HANDLE_STRUCTURE) /* Error codes - all must have bit 29 set */ -#define SYNCH_ERROR 0X20000000 /* EXERCISE - REFINE THE ERROR NUMBERS */ +#define SYNCH_ERROR 0X20000000 /* EXERCISE - REFINE THE ERROR NUMBERS */ -extern SYNCHHANDLE CreateSemaphoreCE (LPSECURITY_ATTRIBUTES, LONG, LONG, LPCTSTR); +extern SYNCHHANDLE CreateSemaphoreCE(LPSECURITY_ATTRIBUTES, LONG, LONG, + LPCTSTR); -extern BOOL ReleaseSemaphoreCE (SYNCHHANDLE, LONG, LPLONG); -extern DWORD WaitForSemaphoreCE (SYNCHHANDLE, DWORD); +extern BOOL ReleaseSemaphoreCE(SYNCHHANDLE, LONG, LPLONG); +extern DWORD WaitForSemaphoreCE(SYNCHHANDLE, DWORD); -extern BOOL CloseSynchHandle (SYNCHHANDLE); +extern BOOL CloseSynchHandle(SYNCHHANDLE); +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/timer/SDL_systimer.h b/src/timer/SDL_systimer.h index e9c7b3b30..3d9c0c135 100644 --- a/src/timer/SDL_systimer.h +++ b/src/timer/SDL_systimer.h @@ -38,3 +38,4 @@ extern int SDL_SYS_StartTimer(void); /* Stop a previously started timer */ extern void SDL_SYS_StopTimer(void); +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/timer/SDL_timer.c b/src/timer/SDL_timer.c index 2c98431ac..d425a7622 100644 --- a/src/timer/SDL_timer.c +++ b/src/timer/SDL_timer.c @@ -38,12 +38,13 @@ SDL_TimerCallback SDL_alarm_callback; /* Data used for a thread-based timer */ static int SDL_timer_threaded = 0; -struct _SDL_TimerID { - Uint32 interval; - SDL_NewTimerCallback cb; - void *param; - Uint32 last_alarm; - struct _SDL_TimerID *next; +struct _SDL_TimerID +{ + Uint32 interval; + SDL_NewTimerCallback cb; + void *param; + Uint32 last_alarm; + struct _SDL_TimerID *next; }; static SDL_TimerID SDL_timers = NULL; @@ -53,233 +54,247 @@ static volatile SDL_bool list_changed = SDL_FALSE; /* Set whether or not the timer should use a thread. This should not be called while the timer subsystem is running. */ -int SDL_SetTimerThreaded(int value) +int +SDL_SetTimerThreaded(int value) { - int retval; + int retval; - if ( SDL_timer_started ) { - SDL_SetError("Timer already initialized"); - retval = -1; - } else { - retval = 0; - SDL_timer_threaded = value; - } - return retval; + if (SDL_timer_started) { + SDL_SetError("Timer already initialized"); + retval = -1; + } else { + retval = 0; + SDL_timer_threaded = value; + } + return retval; } -int SDL_TimerInit(void) +int +SDL_TimerInit(void) { - int retval; + int retval; - retval = 0; - if ( SDL_timer_started ) { - SDL_TimerQuit(); - } - if ( ! SDL_timer_threaded ) { - retval = SDL_SYS_TimerInit(); - } - if ( SDL_timer_threaded ) { - SDL_timer_mutex = SDL_CreateMutex(); - } - if ( retval == 0 ) { - SDL_timer_started = 1; - } - return(retval); + retval = 0; + if (SDL_timer_started) { + SDL_TimerQuit(); + } + if (!SDL_timer_threaded) { + retval = SDL_SYS_TimerInit(); + } + if (SDL_timer_threaded) { + SDL_timer_mutex = SDL_CreateMutex(); + } + if (retval == 0) { + SDL_timer_started = 1; + } + return (retval); } -void SDL_TimerQuit(void) +void +SDL_TimerQuit(void) { - SDL_SetTimer(0, NULL); - if ( SDL_timer_threaded < 2 ) { - SDL_SYS_TimerQuit(); - } - if ( SDL_timer_threaded ) { - SDL_DestroyMutex(SDL_timer_mutex); - SDL_timer_mutex = NULL; - } - SDL_timer_started = 0; - SDL_timer_threaded = 0; + SDL_SetTimer(0, NULL); + if (SDL_timer_threaded < 2) { + SDL_SYS_TimerQuit(); + } + if (SDL_timer_threaded) { + SDL_DestroyMutex(SDL_timer_mutex); + SDL_timer_mutex = NULL; + } + SDL_timer_started = 0; + SDL_timer_threaded = 0; } -void SDL_ThreadedTimerCheck(void) +void +SDL_ThreadedTimerCheck(void) { - Uint32 now, ms; - SDL_TimerID t, prev, next; - SDL_bool removed; + Uint32 now, ms; + SDL_TimerID t, prev, next; + SDL_bool removed; - SDL_mutexP(SDL_timer_mutex); - list_changed = SDL_FALSE; - now = SDL_GetTicks(); - for ( prev = NULL, t = SDL_timers; t; t = next ) { - removed = SDL_FALSE; - ms = t->interval - SDL_TIMESLICE; - next = t->next; - if ( (int)(now - t->last_alarm) > (int)ms ) { - struct _SDL_TimerID timer; + SDL_mutexP(SDL_timer_mutex); + list_changed = SDL_FALSE; + now = SDL_GetTicks(); + for (prev = NULL, t = SDL_timers; t; t = next) { + removed = SDL_FALSE; + ms = t->interval - SDL_TIMESLICE; + next = t->next; + if ((int) (now - t->last_alarm) > (int) ms) { + struct _SDL_TimerID timer; - if ( (now - t->last_alarm) < t->interval ) { - t->last_alarm += t->interval; - } else { - t->last_alarm = now; - } + if ((now - t->last_alarm) < t->interval) { + t->last_alarm += t->interval; + } else { + t->last_alarm = now; + } #ifdef DEBUG_TIMERS - printf("Executing timer %p (thread = %d)\n", - t, SDL_ThreadID()); + printf("Executing timer %p (thread = %d)\n", t, SDL_ThreadID()); #endif - timer = *t; - SDL_mutexV(SDL_timer_mutex); - ms = timer.cb(timer.interval, timer.param); - SDL_mutexP(SDL_timer_mutex); - if ( list_changed ) { - /* Abort, list of timers modified */ - /* FIXME: what if ms was changed? */ - break; - } - if ( ms != t->interval ) { - if ( ms ) { - t->interval = ROUND_RESOLUTION(ms); - } else { - /* Remove timer from the list */ + timer = *t; + SDL_mutexV(SDL_timer_mutex); + ms = timer.cb(timer.interval, timer.param); + SDL_mutexP(SDL_timer_mutex); + if (list_changed) { + /* Abort, list of timers modified */ + /* FIXME: what if ms was changed? */ + break; + } + if (ms != t->interval) { + if (ms) { + t->interval = ROUND_RESOLUTION(ms); + } else { + /* Remove timer from the list */ #ifdef DEBUG_TIMERS - printf("SDL: Removing timer %p\n", t); + printf("SDL: Removing timer %p\n", t); #endif - if ( prev ) { - prev->next = next; - } else { - SDL_timers = next; - } - SDL_free(t); - --SDL_timer_running; - removed = SDL_TRUE; - } - } - } - /* Don't update prev if the timer has disappeared */ - if ( ! removed ) { - prev = t; - } - } - SDL_mutexV(SDL_timer_mutex); + if (prev) { + prev->next = next; + } else { + SDL_timers = next; + } + SDL_free(t); + --SDL_timer_running; + removed = SDL_TRUE; + } + } + } + /* Don't update prev if the timer has disappeared */ + if (!removed) { + prev = t; + } + } + SDL_mutexV(SDL_timer_mutex); } -static SDL_TimerID SDL_AddTimerInternal(Uint32 interval, SDL_NewTimerCallback callback, void *param) +static SDL_TimerID +SDL_AddTimerInternal(Uint32 interval, SDL_NewTimerCallback callback, + void *param) { - SDL_TimerID t; - t = (SDL_TimerID) SDL_malloc(sizeof(struct _SDL_TimerID)); - if ( t ) { - t->interval = ROUND_RESOLUTION(interval); - t->cb = callback; - t->param = param; - t->last_alarm = SDL_GetTicks(); - t->next = SDL_timers; - SDL_timers = t; - ++SDL_timer_running; - list_changed = SDL_TRUE; - } + SDL_TimerID t; + t = (SDL_TimerID) SDL_malloc(sizeof(struct _SDL_TimerID)); + if (t) { + t->interval = ROUND_RESOLUTION(interval); + t->cb = callback; + t->param = param; + t->last_alarm = SDL_GetTicks(); + t->next = SDL_timers; + SDL_timers = t; + ++SDL_timer_running; + list_changed = SDL_TRUE; + } #ifdef DEBUG_TIMERS - printf("SDL_AddTimer(%d) = %08x num_timers = %d\n", interval, (Uint32)t, SDL_timer_running); + printf("SDL_AddTimer(%d) = %08x num_timers = %d\n", interval, (Uint32) t, + SDL_timer_running); #endif - return t; + return t; } -SDL_TimerID SDL_AddTimer(Uint32 interval, SDL_NewTimerCallback callback, void *param) +SDL_TimerID +SDL_AddTimer(Uint32 interval, SDL_NewTimerCallback callback, void *param) { - SDL_TimerID t; - if ( ! SDL_timer_mutex ) { - if ( SDL_timer_started ) { - SDL_SetError("This platform doesn't support multiple timers"); - } else { - SDL_SetError("You must call SDL_Init(SDL_INIT_TIMER) first"); - } - return NULL; - } - if ( ! SDL_timer_threaded ) { - SDL_SetError("Multiple timers require threaded events!"); - return NULL; - } - SDL_mutexP(SDL_timer_mutex); - t = SDL_AddTimerInternal(interval, callback, param); - SDL_mutexV(SDL_timer_mutex); - return t; + SDL_TimerID t; + if (!SDL_timer_mutex) { + if (SDL_timer_started) { + SDL_SetError("This platform doesn't support multiple timers"); + } else { + SDL_SetError("You must call SDL_Init(SDL_INIT_TIMER) first"); + } + return NULL; + } + if (!SDL_timer_threaded) { + SDL_SetError("Multiple timers require threaded events!"); + return NULL; + } + SDL_mutexP(SDL_timer_mutex); + t = SDL_AddTimerInternal(interval, callback, param); + SDL_mutexV(SDL_timer_mutex); + return t; } -SDL_bool SDL_RemoveTimer(SDL_TimerID id) +SDL_bool +SDL_RemoveTimer(SDL_TimerID id) { - SDL_TimerID t, prev = NULL; - SDL_bool removed; + SDL_TimerID t, prev = NULL; + SDL_bool removed; - removed = SDL_FALSE; - SDL_mutexP(SDL_timer_mutex); - /* Look for id in the linked list of timers */ - for (t = SDL_timers; t; prev=t, t = t->next ) { - if ( t == id ) { - if(prev) { - prev->next = t->next; - } else { - SDL_timers = t->next; - } - SDL_free(t); - --SDL_timer_running; - removed = SDL_TRUE; - list_changed = SDL_TRUE; - break; - } - } + removed = SDL_FALSE; + SDL_mutexP(SDL_timer_mutex); + /* Look for id in the linked list of timers */ + for (t = SDL_timers; t; prev = t, t = t->next) { + if (t == id) { + if (prev) { + prev->next = t->next; + } else { + SDL_timers = t->next; + } + SDL_free(t); + --SDL_timer_running; + removed = SDL_TRUE; + list_changed = SDL_TRUE; + break; + } + } #ifdef DEBUG_TIMERS - printf("SDL_RemoveTimer(%08x) = %d num_timers = %d thread = %d\n", (Uint32)id, removed, SDL_timer_running, SDL_ThreadID()); + printf("SDL_RemoveTimer(%08x) = %d num_timers = %d thread = %d\n", + (Uint32) id, removed, SDL_timer_running, SDL_ThreadID()); #endif - SDL_mutexV(SDL_timer_mutex); - return removed; + SDL_mutexV(SDL_timer_mutex); + return removed; } /* Old style callback functions are wrapped through this */ -static Uint32 SDLCALL callback_wrapper(Uint32 ms, void *param) +static Uint32 SDLCALL +callback_wrapper(Uint32 ms, void *param) { - SDL_TimerCallback func = (SDL_TimerCallback) param; - return (*func)(ms); + SDL_TimerCallback func = (SDL_TimerCallback) param; + return (*func) (ms); } -int SDL_SetTimer(Uint32 ms, SDL_TimerCallback callback) +int +SDL_SetTimer(Uint32 ms, SDL_TimerCallback callback) { - int retval; + int retval; #ifdef DEBUG_TIMERS - printf("SDL_SetTimer(%d)\n", ms); + printf("SDL_SetTimer(%d)\n", ms); #endif - retval = 0; + retval = 0; - if ( SDL_timer_threaded ) { - SDL_mutexP(SDL_timer_mutex); - } - if ( SDL_timer_running ) { /* Stop any currently running timer */ - if ( SDL_timer_threaded ) { - while ( SDL_timers ) { - SDL_TimerID freeme = SDL_timers; - SDL_timers = SDL_timers->next; - SDL_free(freeme); - } - SDL_timer_running = 0; - list_changed = SDL_TRUE; - } else { - SDL_SYS_StopTimer(); - SDL_timer_running = 0; - } - } - if ( ms ) { - if ( SDL_timer_threaded ) { - if ( SDL_AddTimerInternal(ms, callback_wrapper, (void *)callback) == NULL ) { - retval = -1; - } - } else { - SDL_timer_running = 1; - SDL_alarm_interval = ms; - SDL_alarm_callback = callback; - retval = SDL_SYS_StartTimer(); - } - } - if ( SDL_timer_threaded ) { - SDL_mutexV(SDL_timer_mutex); - } + if (SDL_timer_threaded) { + SDL_mutexP(SDL_timer_mutex); + } + if (SDL_timer_running) { /* Stop any currently running timer */ + if (SDL_timer_threaded) { + while (SDL_timers) { + SDL_TimerID freeme = SDL_timers; + SDL_timers = SDL_timers->next; + SDL_free(freeme); + } + SDL_timer_running = 0; + list_changed = SDL_TRUE; + } else { + SDL_SYS_StopTimer(); + SDL_timer_running = 0; + } + } + if (ms) { + if (SDL_timer_threaded) { + if (SDL_AddTimerInternal + (ms, callback_wrapper, (void *) callback) == NULL) { + retval = -1; + } + } else { + SDL_timer_running = 1; + SDL_alarm_interval = ms; + SDL_alarm_callback = callback; + retval = SDL_SYS_StartTimer(); + } + } + if (SDL_timer_threaded) { + SDL_mutexV(SDL_timer_mutex); + } - return retval; + return retval; } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/timer/SDL_timer_c.h b/src/timer/SDL_timer_c.h index a69cd12ac..b42908d8a 100644 --- a/src/timer/SDL_timer_c.h +++ b/src/timer/SDL_timer_c.h @@ -44,3 +44,4 @@ extern void SDL_TimerQuit(void); /* This function is called from the SDL event thread if it is available */ extern void SDL_ThreadedTimerCheck(void); +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/timer/amigaos/SDL_systimer.c b/src/timer/amigaos/SDL_systimer.c index a213b6142..b5e0101d5 100644 --- a/src/timer/amigaos/SDL_systimer.c +++ b/src/timer/amigaos/SDL_systimer.c @@ -59,48 +59,48 @@ static struct GfxBase *GfxBase; #if !defined(__PPC__) || defined(STORMC4_WOS) || defined(MORPHOS) static clock_t start; -void SDL_StartTicks(void) +void +SDL_StartTicks(void) { - /* Set first ticks value */ - start=clock(); + /* Set first ticks value */ + start = clock(); } -Uint32 SDL_GetTicks (void) +Uint32 +SDL_GetTicks(void) { - clock_t ticks; + clock_t ticks; - ticks=clock()-start; + ticks = clock() - start; #ifdef __SASC // CLOCKS_PER_SEC == 1000 ! - return(ticks); + return (ticks); #else // CLOCKS_PER_SEC != 1000 ! - return ticks*(1000/CLOCKS_PER_SEC); + return ticks * (1000 / CLOCKS_PER_SEC); #endif } -void SDL_Delay (Uint32 ms) +void +SDL_Delay(Uint32 ms) { // Do a busy wait if time is less than 50ms - if(ms<50) - { - clock_t to_wait=clock(); + if (ms < 50) { + clock_t to_wait = clock(); #ifndef __SASC - ms*=(CLOCKS_PER_SEC/1000); + ms *= (CLOCKS_PER_SEC / 1000); #endif - to_wait+=ms; - - while(clock()>=10; - start[1]|=((result[0]&0x3ff)<<22); - start[0]>>=10; + /* Set first ticks value */ + if (!MyTimer) + PPC_TimerInit(); + + PPCGetTimerObject(MyTimer, PPCTIMERTAG_CURRENTTICKS, start); + start[1] >>= 10; + start[1] |= ((result[0] & 0x3ff) << 22); + start[0] >>= 10; } -Uint32 SDL_GetTicks (void) +Uint32 +SDL_GetTicks(void) { - ULONG result[2]; - PPCGetTimerObject(MyTimer,PPCTIMERTAG_CURRENTTICKS,result); + ULONG result[2]; + PPCGetTimerObject(MyTimer, PPCTIMERTAG_CURRENTTICKS, result); -// PPCAsr64p(result,10); +// PPCAsr64p(result,10); // Non va, la emulo: - result[1]>>=10; - result[1]|=((result[0]&0x3ff)<<22); + result[1] >>= 10; + result[1] |= ((result[0] & 0x3ff) << 22); // Non mi interessa piu' result[0] - return result[1]*1000/MY_CLOCKS_PER_SEC; + return result[1] * 1000 / MY_CLOCKS_PER_SEC; } -void SDL_Delay (Uint32 ms) +void +SDL_Delay(Uint32 ms) { // Do a busy wait if time is less than 50ms - if(ms<50) - { - ULONG to_wait[2],actual[2]; - PPCGetTimerObject(MyTimer,PPCTIMERTAG_CURRENTTICKS,result); - actual[1]=0; - to_wait[1]+=ms*1000/MY_CLOCKS_PER_SEC; - - while(actual[1]>=10; - result[1]|=((result[0]&0x3ff)<<22); - result[0]>>=10; - - D(bug("Shiftato TPS: %lu - %lu\n",result[0],result[1])); - MY_CLOCKS_PER_SEC=result[1]; - - PPCGetTimerObject(MyTimer,PPCTIMERTAG_CURRENTTICKS,result); - - D(bug("Current ticks: %lu - %lu\n",result[0],result[1])); - result[1]>>=10; - result[1]|=((result[0]&0x3ff)<<22); - result[0]>>=10; -// PPCAsr64p(result,10); - D(bug("Shiftato: %lu - %lu\n",result[0],result[1])); - } - else - { - D(bug("Errore nell'inizializzazione del timer!\n")); - } + struct TagItem tags[] = { + PPCTIMERTAG_CPU, TRUE, + TAG_DONE, 0 + }; + + + if (MyTimer = PPCCreateTimerObject(tags)) { + ULONG result[2]; + + PPCGetTimerObject(MyTimer, PPCTIMERTAG_TICKSPERSEC, result); + D(bug("Timer inizializzato, TPS: %lu - %lu\n", result[0], result[1])); +// PPCAsr64p(result,10); + result[1] >>= 10; + result[1] |= ((result[0] & 0x3ff) << 22); + result[0] >>= 10; + + D(bug("Shiftato TPS: %lu - %lu\n", result[0], result[1])); + MY_CLOCKS_PER_SEC = result[1]; + + PPCGetTimerObject(MyTimer, PPCTIMERTAG_CURRENTTICKS, result); + + D(bug("Current ticks: %lu - %lu\n", result[0], result[1])); + result[1] >>= 10; + result[1] |= ((result[0] & 0x3ff) << 22); + result[0] >>= 10; +// PPCAsr64p(result,10); + D(bug("Shiftato: %lu - %lu\n", result[0], result[1])); + } else { + D(bug("Errore nell'inizializzazione del timer!\n")); + } } #endif @@ -208,60 +204,65 @@ void PPC_TimerInit(void) static int timer_alive = 0; static SDL_Thread *timer_thread = NULL; -static int RunTimer(void *unused) +static int +RunTimer(void *unused) { - D(bug("SYSTimer: Entering RunTimer loop...")); - - if(GfxBase==NULL) - GfxBase=(struct GfxBase *)OpenLibrary("graphics.library",37); - - while ( timer_alive ) { - if ( SDL_timer_running ) { - SDL_ThreadedTimerCheck(); - } - if(GfxBase) - WaitTOF(); // Check the timer every fifth of seconds. Was SDL_Delay(1)->BusyWait! - else - Delay(1); - } - D(bug("SYSTimer: EXITING RunTimer loop...")); - return(0); + D(bug("SYSTimer: Entering RunTimer loop...")); + + if (GfxBase == NULL) + GfxBase = (struct GfxBase *) OpenLibrary("graphics.library", 37); + + while (timer_alive) { + if (SDL_timer_running) { + SDL_ThreadedTimerCheck(); + } + if (GfxBase) + WaitTOF(); // Check the timer every fifth of seconds. Was SDL_Delay(1)->BusyWait! + else + Delay(1); + } + D(bug("SYSTimer: EXITING RunTimer loop...")); + return (0); } /* This is only called if the event thread is not running */ -int SDL_SYS_TimerInit(void) +int +SDL_SYS_TimerInit(void) { - D(bug("Creating thread for the timer (NOITIMER)...\n")); + D(bug("Creating thread for the timer (NOITIMER)...\n")); - timer_alive = 1; - timer_thread = SDL_CreateThread(RunTimer, NULL); - if ( timer_thread == NULL ) - { - D(bug("Creazione del thread fallita...\n")); + timer_alive = 1; + timer_thread = SDL_CreateThread(RunTimer, NULL); + if (timer_thread == NULL) { + D(bug("Creazione del thread fallita...\n")); - return(-1); - } - return(SDL_SetTimerThreaded(1)); + return (-1); + } + return (SDL_SetTimerThreaded(1)); } -void SDL_SYS_TimerQuit(void) +void +SDL_SYS_TimerQuit(void) { - timer_alive = 0; - if ( timer_thread ) { - SDL_WaitThread(timer_thread, NULL); - timer_thread = NULL; - } + timer_alive = 0; + if (timer_thread) { + SDL_WaitThread(timer_thread, NULL); + timer_thread = NULL; + } } -int SDL_SYS_StartTimer(void) +int +SDL_SYS_StartTimer(void) { - SDL_SetError("Internal logic error: AmigaOS uses threaded timer"); - return(-1); + SDL_SetError("Internal logic error: AmigaOS uses threaded timer"); + return (-1); } -void SDL_SYS_StopTimer(void) +void +SDL_SYS_StopTimer(void) { - return; + return; } #endif /* SDL_TIMER_AMIGA */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/timer/beos/SDL_systimer.c b/src/timer/beos/SDL_systimer.c index 74ff7f6a4..6c62bee62 100644 --- a/src/timer/beos/SDL_systimer.c +++ b/src/timer/beos/SDL_systimer.c @@ -31,65 +31,74 @@ static bigtime_t start; -void SDL_StartTicks(void) +void +SDL_StartTicks(void) { - /* Set first ticks value */ - start = system_time(); + /* Set first ticks value */ + start = system_time(); } -Uint32 SDL_GetTicks(void) +Uint32 +SDL_GetTicks(void) { - return((system_time()-start)/1000); + return ((system_time() - start) / 1000); } -void SDL_Delay(Uint32 ms) +void +SDL_Delay(Uint32 ms) { - snooze(ms*1000); + snooze(ms * 1000); } /* Data to handle a single periodic alarm */ static int timer_alive = 0; static SDL_Thread *timer = NULL; -static int RunTimer(void *unused) +static int +RunTimer(void *unused) { - while ( timer_alive ) { - if ( SDL_timer_running ) { - SDL_ThreadedTimerCheck(); - } - SDL_Delay(10); - } - return(0); + while (timer_alive) { + if (SDL_timer_running) { + SDL_ThreadedTimerCheck(); + } + SDL_Delay(10); + } + return (0); } /* This is only called if the event thread is not running */ -int SDL_SYS_TimerInit(void) +int +SDL_SYS_TimerInit(void) { - timer_alive = 1; - timer = SDL_CreateThread(RunTimer, NULL); - if ( timer == NULL ) - return(-1); - return(SDL_SetTimerThreaded(1)); + timer_alive = 1; + timer = SDL_CreateThread(RunTimer, NULL); + if (timer == NULL) + return (-1); + return (SDL_SetTimerThreaded(1)); } -void SDL_SYS_TimerQuit(void) +void +SDL_SYS_TimerQuit(void) { - timer_alive = 0; - if ( timer ) { - SDL_WaitThread(timer, NULL); - timer = NULL; - } + timer_alive = 0; + if (timer) { + SDL_WaitThread(timer, NULL); + timer = NULL; + } } -int SDL_SYS_StartTimer(void) +int +SDL_SYS_StartTimer(void) { - SDL_SetError("Internal logic error: BeOS uses threaded timer"); - return(-1); + SDL_SetError("Internal logic error: BeOS uses threaded timer"); + return (-1); } -void SDL_SYS_StopTimer(void) +void +SDL_SYS_StopTimer(void) { - return; + return; } #endif /* SDL_TIMER_BEOS */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/timer/dc/SDL_systimer.c b/src/timer/dc/SDL_systimer.c index d04a6545d..84c74caa8 100644 --- a/src/timer/dc/SDL_systimer.c +++ b/src/timer/dc/SDL_systimer.c @@ -36,65 +36,74 @@ static unsigned start; ms = jif * 1000/HZ */ -void SDL_StartTicks(void) +void +SDL_StartTicks(void) { - /* Set first ticks value */ - start = jiffies; + /* Set first ticks value */ + start = jiffies; } -Uint32 SDL_GetTicks(void) +Uint32 +SDL_GetTicks(void) { - return((jiffies-start)*1000/HZ); + return ((jiffies - start) * 1000 / HZ); } -void SDL_Delay(Uint32 ms) +void +SDL_Delay(Uint32 ms) { - thd_sleep(ms); + thd_sleep(ms); } /* Data to handle a single periodic alarm */ static int timer_alive = 0; static SDL_Thread *timer = NULL; -static int RunTimer(void *unused) +static int +RunTimer(void *unused) { - while ( timer_alive ) { - if ( SDL_timer_running ) { - SDL_ThreadedTimerCheck(); - } - SDL_Delay(10); - } - return(0); + while (timer_alive) { + if (SDL_timer_running) { + SDL_ThreadedTimerCheck(); + } + SDL_Delay(10); + } + return (0); } /* This is only called if the event thread is not running */ -int SDL_SYS_TimerInit(void) +int +SDL_SYS_TimerInit(void) { - timer_alive = 1; - timer = SDL_CreateThread(RunTimer, NULL); - if ( timer == NULL ) - return(-1); - return(SDL_SetTimerThreaded(1)); + timer_alive = 1; + timer = SDL_CreateThread(RunTimer, NULL); + if (timer == NULL) + return (-1); + return (SDL_SetTimerThreaded(1)); } -void SDL_SYS_TimerQuit(void) +void +SDL_SYS_TimerQuit(void) { - timer_alive = 0; - if ( timer ) { - SDL_WaitThread(timer, NULL); - timer = NULL; - } + timer_alive = 0; + if (timer) { + SDL_WaitThread(timer, NULL); + timer = NULL; + } } -int SDL_SYS_StartTimer(void) +int +SDL_SYS_StartTimer(void) { - SDL_SetError("Internal logic error: DC uses threaded timer"); - return(-1); + SDL_SetError("Internal logic error: DC uses threaded timer"); + return (-1); } -void SDL_SYS_StopTimer(void) +void +SDL_SYS_StopTimer(void) { - return; + return; } #endif /* SDL_TIMER_DC */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/timer/dummy/SDL_systimer.c b/src/timer/dummy/SDL_systimer.c index f4dae0357..b1fc147c9 100644 --- a/src/timer/dummy/SDL_systimer.c +++ b/src/timer/dummy/SDL_systimer.c @@ -26,19 +26,22 @@ #include "SDL_timer.h" #include "../SDL_timer_c.h" -void SDL_StartTicks(void) +void +SDL_StartTicks(void) { } -Uint32 SDL_GetTicks (void) +Uint32 +SDL_GetTicks(void) { - SDL_Unsupported(); - return 0; + SDL_Unsupported(); + return 0; } -void SDL_Delay (Uint32 ms) +void +SDL_Delay(Uint32 ms) { - SDL_Unsupported(); + SDL_Unsupported(); } #include "SDL_thread.h" @@ -47,45 +50,51 @@ void SDL_Delay (Uint32 ms) static int timer_alive = 0; static SDL_Thread *timer = NULL; -static int RunTimer(void *unused) +static int +RunTimer(void *unused) { - while ( timer_alive ) { - if ( SDL_timer_running ) { - SDL_ThreadedTimerCheck(); - } - SDL_Delay(1); - } - return(0); + while (timer_alive) { + if (SDL_timer_running) { + SDL_ThreadedTimerCheck(); + } + SDL_Delay(1); + } + return (0); } /* This is only called if the event thread is not running */ -int SDL_SYS_TimerInit(void) +int +SDL_SYS_TimerInit(void) { - timer_alive = 1; - timer = SDL_CreateThread(RunTimer, NULL); - if ( timer == NULL ) - return(-1); - return(SDL_SetTimerThreaded(1)); + timer_alive = 1; + timer = SDL_CreateThread(RunTimer, NULL); + if (timer == NULL) + return (-1); + return (SDL_SetTimerThreaded(1)); } -void SDL_SYS_TimerQuit(void) +void +SDL_SYS_TimerQuit(void) { - timer_alive = 0; - if ( timer ) { - SDL_WaitThread(timer, NULL); - timer = NULL; - } + timer_alive = 0; + if (timer) { + SDL_WaitThread(timer, NULL); + timer = NULL; + } } -int SDL_SYS_StartTimer(void) +int +SDL_SYS_StartTimer(void) { - SDL_SetError("Internal logic error: threaded timer in use"); - return(-1); + SDL_SetError("Internal logic error: threaded timer in use"); + return (-1); } -void SDL_SYS_StopTimer(void) +void +SDL_SYS_StopTimer(void) { - return; + return; } #endif /* SDL_TIMER_DUMMY || SDL_TIMERS_DISABLED */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/timer/macos/FastTimes.c b/src/timer/macos/FastTimes.c index 8eb4260fb..536c862ff 100644 --- a/src/timer/macos/FastTimes.c +++ b/src/timer/macos/FastTimes.c @@ -20,7 +20,7 @@ #include "FastTimes.h" #ifdef TARGET_CPU_PPC -#undef GENERATINGPOWERPC /* stop whining */ +#undef GENERATINGPOWERPC /* stop whining */ #define GENERATINGPOWERPC TARGET_CPU_PPC #endif @@ -82,271 +82,267 @@ static asm UnsignedWide PollRTC(void); static asm UnsignedWide PollTBR(void); static Ptr FindFunctionInSharedLib(StringPtr libName, StringPtr funcName); -static Boolean gInited = false; -static Boolean gNative = false; -static Boolean gUseRTC = false; -static Boolean gUseTBR = false; -static double gScaleUSec = 1.0 / 1000.0; /* 1 / ( nsec / usec) */ -static double gScaleMSec = 1.0 / 1000000.0; /* 1 / ( nsec / msec) */ +static Boolean gInited = false; +static Boolean gNative = false; +static Boolean gUseRTC = false; +static Boolean gUseTBR = false; +static double gScaleUSec = 1.0 / 1000.0; /* 1 / ( nsec / usec) */ +static double gScaleMSec = 1.0 / 1000000.0; /* 1 / ( nsec / msec) */ /* Functions loaded from DriverServicesLib */ -typedef AbsoluteTime (*UpTimeProcPtr)(void); -typedef Nanoseconds (*A2NSProcPtr)(AbsoluteTime); -static UpTimeProcPtr gUpTime = NULL; -static A2NSProcPtr gA2NS = NULL; +typedef AbsoluteTime(*UpTimeProcPtr) (void); +typedef Nanoseconds(*A2NSProcPtr) (AbsoluteTime); +static UpTimeProcPtr gUpTime = NULL; +static A2NSProcPtr gA2NS = NULL; #endif /* GENERATINGPOWERPC */ /* **** **** **** **** **** **** **** **** **** **** **** **** **** **** **** */ /* **** **** **** **** **** **** **** **** **** **** **** **** **** **** **** */ -void FastInitialize() { - SInt32 result; +void +FastInitialize() +{ + SInt32 result; - if (!gInited) { + if (!gInited) { #if GENERATINGPOWERPC - /* Initialize the feature flags */ - gNative = gUseRTC = gUseTBR = false; - - /* We use CFM to find and load needed symbols from shared libraries, so - the application doesn't have to weak-link them, for convenience. */ - gUpTime = (UpTimeProcPtr) FindFunctionInSharedLib( - "\pDriverServicesLib", "\pUpTime"); - if (gUpTime) gA2NS = (A2NSProcPtr) FindFunctionInSharedLib( - "\pDriverServicesLib", "\pAbsoluteToNanoseconds"); - if (!gA2NS) gUpTime = nil; /* Pedantic but necessary */ - - if (gUpTime) { - /* If we loaded UpTime(), then we need to know if the system has - a native implementation of the Time Manager. If so, then it's - pointless to calculate a scale factor against the missing VIA */ - - /* gestaltNativeTimeMgr = 4 in some future version of the headers */ - if (!Gestalt(gestaltTimeMgrVersion, &result) && - (result > gestaltExtendedTimeMgr)) - gNative = true; - } - else { - /* If no DriverServicesLib, use Gestalt() to get the processor type. - Only NuBus PowerMacs with old System Software won't have DSL, so - we know it should either be a 601 or 603. */ - - /* Use the processor gestalt to determine which register to use */ - if (!Gestalt(gestaltNativeCPUtype, &result)) { - if (result == gestaltCPU601) gUseRTC = true; - else if (result > gestaltCPU601) gUseTBR = true; - } - } - - /* Now calculate a scale factor to keep us accurate. */ - if ((gUpTime && !gNative) || gUseRTC || gUseTBR) { - UInt64 tick, usec1, usec2; - UnsignedWide wide; - - /* Wait for the beginning of the very next tick */ - for(tick = MyLMGetTicks() + 1; tick > MyLMGetTicks(); ); - - /* Poll the selected timer and prepare it (since we have time) */ - wide = (gUpTime) ? (*gA2NS)((*gUpTime)()) : - ((gUseRTC) ? PollRTC() : PollTBR()); - usec1 = (gUseRTC) ? RTCToNano(wide) : WideTo64bit(wide); - - /* Wait for the exact 60th tick to roll over */ - while(tick + 60 > MyLMGetTicks()); - - /* Poll the selected timer again and prepare it */ - wide = (gUpTime) ? (*gA2NS)((*gUpTime)()) : - ((gUseRTC) ? PollRTC() : PollTBR()); - usec2 = (gUseRTC) ? RTCToNano(wide) : WideTo64bit(wide); - - /* Calculate a scale value that will give microseconds per second. - Remember, there are actually 60.15 ticks in a second, not 60. */ - gScaleUSec = (60.0 * 1000000.0) / ((usec2 - usec1) * 60.15); - gScaleMSec = gScaleUSec / 1000.0; - } - + /* Initialize the feature flags */ + gNative = gUseRTC = gUseTBR = false; + + /* We use CFM to find and load needed symbols from shared libraries, so + the application doesn't have to weak-link them, for convenience. */ + gUpTime = + (UpTimeProcPtr) FindFunctionInSharedLib("\pDriverServicesLib", + "\pUpTime"); + if (gUpTime) + gA2NS = (A2NSProcPtr) + FindFunctionInSharedLib("\pDriverServicesLib", + "\pAbsoluteToNanoseconds"); + if (!gA2NS) + gUpTime = nil; /* Pedantic but necessary */ + + if (gUpTime) { + /* If we loaded UpTime(), then we need to know if the system has + a native implementation of the Time Manager. If so, then it's + pointless to calculate a scale factor against the missing VIA */ + + /* gestaltNativeTimeMgr = 4 in some future version of the headers */ + if (!Gestalt(gestaltTimeMgrVersion, &result) && + (result > gestaltExtendedTimeMgr)) + gNative = true; + } else { + /* If no DriverServicesLib, use Gestalt() to get the processor type. + Only NuBus PowerMacs with old System Software won't have DSL, so + we know it should either be a 601 or 603. */ + + /* Use the processor gestalt to determine which register to use */ + if (!Gestalt(gestaltNativeCPUtype, &result)) { + if (result == gestaltCPU601) + gUseRTC = true; + else if (result > gestaltCPU601) + gUseTBR = true; + } + } + + /* Now calculate a scale factor to keep us accurate. */ + if ((gUpTime && !gNative) || gUseRTC || gUseTBR) { + UInt64 tick, usec1, usec2; + UnsignedWide wide; + + /* Wait for the beginning of the very next tick */ + for (tick = MyLMGetTicks() + 1; tick > MyLMGetTicks();); + + /* Poll the selected timer and prepare it (since we have time) */ + wide = (gUpTime) ? (*gA2NS) ((*gUpTime) ()) : + ((gUseRTC) ? PollRTC() : PollTBR()); + usec1 = (gUseRTC) ? RTCToNano(wide) : WideTo64bit(wide); + + /* Wait for the exact 60th tick to roll over */ + while (tick + 60 > MyLMGetTicks()); + + /* Poll the selected timer again and prepare it */ + wide = (gUpTime) ? (*gA2NS) ((*gUpTime) ()) : + ((gUseRTC) ? PollRTC() : PollTBR()); + usec2 = (gUseRTC) ? RTCToNano(wide) : WideTo64bit(wide); + + /* Calculate a scale value that will give microseconds per second. + Remember, there are actually 60.15 ticks in a second, not 60. */ + gScaleUSec = (60.0 * 1000000.0) / ((usec2 - usec1) * 60.15); + gScaleMSec = gScaleUSec / 1000.0; + } #endif /* GENERATINGPOWERPC */ - /* We've initialized our globals */ - gInited = true; - } - } + /* We've initialized our globals */ + gInited = true; + } +} /* **** **** **** **** **** **** **** **** **** **** **** **** **** **** **** */ /* **** **** **** **** **** **** **** **** **** **** **** **** **** **** **** */ -UInt64 FastMicroseconds() { - UnsignedWide wide; - UInt64 usec; - +UInt64 +FastMicroseconds() +{ + UnsignedWide wide; + UInt64 usec; + #if GENERATINGPOWERPC - /* Initialize globals the first time we are called */ - if (!gInited) FastInitialize(); - - if (gNative) { - /* Use DriverServices if it's available -- it's fast and compatible */ - wide = (*gA2NS)((*gUpTime)()); - usec = (double) WideTo64bit(wide) * gScaleUSec + 0.5; - } - else if (gUpTime) { - /* Use DriverServices if it's available -- it's fast and compatible */ - wide = (*gA2NS)((*gUpTime)()); - usec = (double) WideTo64bit(wide) * gScaleUSec + 0.5; - } - else if (gUseTBR) { - /* On a recent PowerPC, we poll the TBR directly */ - wide = PollTBR(); - usec = (double) WideTo64bit(wide) * gScaleUSec + 0.5; - } - else if (gUseRTC) { - /* On a 601, we can poll the RTC instead */ - wide = PollRTC(); - usec = (double) RTCToNano(wide) * gScaleUSec + 0.5; - } - else + /* Initialize globals the first time we are called */ + if (!gInited) + FastInitialize(); + + if (gNative) { + /* Use DriverServices if it's available -- it's fast and compatible */ + wide = (*gA2NS) ((*gUpTime) ()); + usec = (double) WideTo64bit(wide) * gScaleUSec + 0.5; + } else if (gUpTime) { + /* Use DriverServices if it's available -- it's fast and compatible */ + wide = (*gA2NS) ((*gUpTime) ()); + usec = (double) WideTo64bit(wide) * gScaleUSec + 0.5; + } else if (gUseTBR) { + /* On a recent PowerPC, we poll the TBR directly */ + wide = PollTBR(); + usec = (double) WideTo64bit(wide) * gScaleUSec + 0.5; + } else if (gUseRTC) { + /* On a 601, we can poll the RTC instead */ + wide = PollRTC(); + usec = (double) RTCToNano(wide) * gScaleUSec + 0.5; + } else #endif /* GENERATINGPOWERPC */ - { - /* If all else fails, suffer the mixed mode overhead */ - Microseconds(&wide); - usec = WideTo64bit(wide); - } + { + /* If all else fails, suffer the mixed mode overhead */ + Microseconds(&wide); + usec = WideTo64bit(wide); + } - return(usec); - } + return (usec); +} /* **** **** **** **** **** **** **** **** **** **** **** **** **** **** **** */ /* **** **** **** **** **** **** **** **** **** **** **** **** **** **** **** */ -UInt64 FastMilliseconds() { - UnsignedWide wide; - UInt64 msec; - +UInt64 +FastMilliseconds() +{ + UnsignedWide wide; + UInt64 msec; + #if GENERATINGPOWERPC - /* Initialize globals the first time we are called */ - if (!gInited) FastInitialize(); - - if (gNative) { - /* Use DriverServices if it's available -- it's fast and compatible */ - wide = (*gA2NS)((*gUpTime)()); - msec = (double) WideTo64bit(wide) * gScaleMSec + 0.5; - } - else if (gUpTime) { - /* Use DriverServices if it's available -- it's fast and compatible */ - wide = (*gA2NS)((*gUpTime)()); - msec = (double) WideTo64bit(wide) * gScaleMSec + 0.5; - } - else if (gUseTBR) { - /* On a recent PowerPC, we poll the TBR directly */ - wide = PollTBR(); - msec = (double) WideTo64bit(wide) * gScaleMSec + 0.5; - } - else if (gUseRTC) { - /* On a 601, we can poll the RTC instead */ - wide = PollRTC(); - msec = (double) RTCToNano(wide) * gScaleMSec + 0.5; - } - else + /* Initialize globals the first time we are called */ + if (!gInited) + FastInitialize(); + + if (gNative) { + /* Use DriverServices if it's available -- it's fast and compatible */ + wide = (*gA2NS) ((*gUpTime) ()); + msec = (double) WideTo64bit(wide) * gScaleMSec + 0.5; + } else if (gUpTime) { + /* Use DriverServices if it's available -- it's fast and compatible */ + wide = (*gA2NS) ((*gUpTime) ()); + msec = (double) WideTo64bit(wide) * gScaleMSec + 0.5; + } else if (gUseTBR) { + /* On a recent PowerPC, we poll the TBR directly */ + wide = PollTBR(); + msec = (double) WideTo64bit(wide) * gScaleMSec + 0.5; + } else if (gUseRTC) { + /* On a 601, we can poll the RTC instead */ + wide = PollRTC(); + msec = (double) RTCToNano(wide) * gScaleMSec + 0.5; + } else #endif /* GENERATINGPOWERPC */ - { - /* If all else fails, suffer the mixed mode overhead */ - Microseconds(&wide); - msec = ((double) WideTo64bit(wide) + 500.0) / 1000.0; - } + { + /* If all else fails, suffer the mixed mode overhead */ + Microseconds(&wide); + msec = ((double) WideTo64bit(wide) + 500.0) / 1000.0; + } - return(msec); - } + return (msec); +} /* **** **** **** **** **** **** **** **** **** **** **** **** **** **** **** */ /* **** **** **** **** **** **** **** **** **** **** **** **** **** **** **** */ -StringPtr FastMethod() { - StringPtr method = "\p"; +StringPtr +FastMethod() +{ + StringPtr method = "\p"; #if GENERATINGPOWERPC - /* Initialize globals the first time we are called */ - if (!gInited) FastInitialize(); - - if (gNative) { - /* The Time Manager and UpTime() are entirely native on this machine */ - method = "\pNative UpTime()"; - } - else if (gUpTime) { - /* Use DriverServices if it's available -- it's fast and compatible */ - method = "\pUpTime()"; - } - else if (gUseTBR) { - /* On a recent PowerPC, we poll the TBR directly */ - method = "\pPowerPC TBR"; - } - else if (gUseRTC) { - /* On a 601, we can poll the RTC instead */ - method = "\pPowerPC RTC"; - } - else + /* Initialize globals the first time we are called */ + if (!gInited) + FastInitialize(); + + if (gNative) { + /* The Time Manager and UpTime() are entirely native on this machine */ + method = "\pNative UpTime()"; + } else if (gUpTime) { + /* Use DriverServices if it's available -- it's fast and compatible */ + method = "\pUpTime()"; + } else if (gUseTBR) { + /* On a recent PowerPC, we poll the TBR directly */ + method = "\pPowerPC TBR"; + } else if (gUseRTC) { + /* On a 601, we can poll the RTC instead */ + method = "\pPowerPC RTC"; + } else #endif /* GENERATINGPOWERPC */ - { - /* If all else fails, suffer the mixed mode overhead */ - method = "\pMicroseconds()"; - } + { + /* If all else fails, suffer the mixed mode overhead */ + method = "\pMicroseconds()"; + } - return(method); - } + return (method); +} /* **** **** **** **** **** **** **** **** **** **** **** **** **** **** **** */ /* **** **** **** **** **** **** **** **** **** **** **** **** **** **** **** */ #pragma mark - #if GENERATINGPOWERPC -asm static UnsignedWide PollRTC_() { -entry PollRTC /* Avoid CodeWarrior glue */ - machine 601 -@AGAIN: - mfrtcu r4 /* RTCU = SPR 4 */ - mfrtcl r5 /* RTCL = SPR 5 */ - mfrtcu r6 - cmpw r4,r6 - bne @AGAIN - stw r4,0(r3) - stw r5,4(r3) - blr - } +asm static UnsignedWide +PollRTC_() +{ + entry PollRTC /* Avoid CodeWarrior glue */ + machine 601 @ AGAIN:mfrtcu r4 /* RTCU = SPR 4 */ + mfrtcl r5 /* RTCL = SPR 5 */ + mfrtcu r6 cmpw r4, r6 bne @ AGAIN stw r4, 0(r3) stw r5, 4(r3) blr} /* **** **** **** **** **** **** **** **** **** **** **** **** **** **** **** */ /* **** **** **** **** **** **** **** **** **** **** **** **** **** **** **** */ -asm static UnsignedWide PollTBR_() { -entry PollTBR /* Avoid CodeWarrior glue */ - machine 604 -@AGAIN: - mftbu r4 /* TBRU = SPR 268 */ - mftb r5 /* TBRL = SPR 269 */ - mftbu r6 - cmpw r4,r6 - bne @AGAIN - stw r4,0(r3) - stw r5,4(r3) - blr - } +asm static UnsignedWide +PollTBR_() +{ + entry PollTBR /* Avoid CodeWarrior glue */ + machine 604 @ AGAIN:mftbu r4 /* TBRU = SPR 268 */ + mftb r5 /* TBRL = SPR 269 */ + mftbu r6 cmpw r4, r6 bne @ AGAIN stw r4, 0(r3) stw r5, 4(r3) blr} /* **** **** **** **** **** **** **** **** **** **** **** **** **** **** **** */ /* **** **** **** **** **** **** **** **** **** **** **** **** **** **** **** */ -static Ptr FindFunctionInSharedLib(StringPtr libName, StringPtr funcName) { - OSErr error = noErr; - Str255 errorStr; - Ptr func = NULL; - Ptr entry = NULL; - CFragSymbolClass symClass; - CFragConnectionID connID; - - /* Find CFM containers for the current archecture -- CFM-PPC or CFM-68K */ - if (/* error = */ GetSharedLibrary(libName, kCompiledCFragArch, - kLoadCFrag, &connID, &entry, errorStr)) return(NULL); - if (/* error = */ FindSymbol(connID, funcName, &func, &symClass)) - return(NULL); - - return(func); - } +static Ptr +FindFunctionInSharedLib(StringPtr libName, StringPtr funcName) +{ + OSErr error = noErr; + Str255 errorStr; + Ptr func = NULL; + Ptr entry = NULL; + CFragSymbolClass symClass; + CFragConnectionID connID; + + /* Find CFM containers for the current archecture -- CFM-PPC or CFM-68K */ + if ( /* error = */ GetSharedLibrary(libName, kCompiledCFragArch, + kLoadCFrag, &connID, &entry, + errorStr)) + return (NULL); + if ( /* error = */ FindSymbol(connID, funcName, &func, &symClass)) + return (NULL); + + return (func); +} #endif /* GENERATINGPOWERPC */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/timer/macos/FastTimes.h b/src/timer/macos/FastTimes.h index bde8db763..556eb1307 100644 --- a/src/timer/macos/FastTimes.h +++ b/src/timer/macos/FastTimes.h @@ -16,12 +16,13 @@ /* **** **** **** **** **** **** **** **** **** **** **** **** **** **** **** */ /* **** **** **** **** **** **** **** **** **** **** **** **** **** **** **** */ -extern void FastInitialize(void); -extern UInt64 FastMicroseconds(void); -extern UInt64 FastMilliseconds(void); -extern StringPtr FastMethod(void); +extern void FastInitialize(void); +extern UInt64 FastMicroseconds(void); +extern UInt64 FastMilliseconds(void); +extern StringPtr FastMethod(void); /* **** **** **** **** **** **** **** **** **** **** **** **** **** **** **** */ /* **** **** **** **** **** **** **** **** **** **** **** **** **** **** **** */ #endif /* __FAST_TIMES_HEADER__ */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/timer/macos/SDL_MPWtimer.c b/src/timer/macos/SDL_MPWtimer.c index 7aee4aa17..707edc77a 100644 --- a/src/timer/macos/SDL_MPWtimer.c +++ b/src/timer/macos/SDL_MPWtimer.c @@ -34,7 +34,7 @@ #include "SDL_timer.h" #include "../SDL_timer_c.h" -#define MS_PER_TICK (1000/60) /* MacOS tick = 1/60 second */ +#define MS_PER_TICK (1000/60) /* MacOS tick = 1/60 second */ /* Note: This is only a step above the original 1/60s implementation. * For a good implementation, see FastTimes.[ch], by Matt Slot. @@ -44,42 +44,46 @@ UInt64 start; -void SDL_StartTicks(void) +void +SDL_StartTicks(void) { #ifdef USE_MICROSECONDS - UnsignedWide now; - - Microseconds(&now); - start = WideTo64bit(now); + UnsignedWide now; + + Microseconds(&now); + start = WideTo64bit(now); #else - /* FIXME: Should we implement a wrapping algorithm, like Win32? */ + /* FIXME: Should we implement a wrapping algorithm, like Win32? */ #endif } -Uint32 SDL_GetTicks(void) +Uint32 +SDL_GetTicks(void) { #ifdef USE_MICROSECONDS - UnsignedWide now; - - Microseconds(&now); - return (Uint32)((WideTo64bit(now)-start)/1000); + UnsignedWide now; + + Microseconds(&now); + return (Uint32) ((WideTo64bit(now) - start) / 1000); #else - return(LMGetTicks()*MS_PER_TICK); + return (LMGetTicks() * MS_PER_TICK); #endif } -void SDL_Delay(Uint32 ms) +void +SDL_Delay(Uint32 ms) { #ifdef USE_MICROSECONDS - Uint32 end_ms; - - end_ms = SDL_GetTicks() + ms; - do { - /* FIXME: Yield CPU? */ ; - } while ( SDL_GetTicks() < end_ms ); + Uint32 end_ms; + + end_ms = SDL_GetTicks() + ms; + do { + /* FIXME: Yield CPU? */ ; + } + while (SDL_GetTicks() < end_ms); #else - UInt32 unused; /* MJS */ - Delay(ms/MS_PER_TICK, &unused); + UInt32 unused; /* MJS */ + Delay(ms / MS_PER_TICK, &unused); #endif } @@ -87,66 +91,71 @@ void SDL_Delay(Uint32 ms) /* Data to handle a single periodic alarm */ typedef struct _ExtendedTimerRec { - TMTask tmTask; - ProcessSerialNumber taskPSN; + TMTask tmTask; + ProcessSerialNumber taskPSN; } ExtendedTimerRec, *ExtendedTimerPtr; static ExtendedTimerRec gExtendedTimerRec; -int SDL_SYS_TimerInit(void) +int +SDL_SYS_TimerInit(void) { - /* We don't need a setup? */ - return(0); + /* We don't need a setup? */ + return (0); } -void SDL_SYS_TimerQuit(void) +void +SDL_SYS_TimerQuit(void) { - /* We don't need a cleanup? */ - return; + /* We don't need a cleanup? */ + return; } /* Our Stub routine to set up and then call the real routine. */ -pascal void TimerCallbackProc(TMTaskPtr tmTaskPtr) +pascal void +TimerCallbackProc(TMTaskPtr tmTaskPtr) { - Uint32 ms; - - WakeUpProcess(&((ExtendedTimerPtr) tmTaskPtr)->taskPSN); - - ms = SDL_alarm_callback(SDL_alarm_interval); - if ( ms ) { - SDL_alarm_interval = ROUND_RESOLUTION(ms); - PrimeTime((QElemPtr)&gExtendedTimerRec.tmTask, - SDL_alarm_interval); - } else { - SDL_alarm_interval = 0; - } + Uint32 ms; + + WakeUpProcess(&((ExtendedTimerPtr) tmTaskPtr)->taskPSN); + + ms = SDL_alarm_callback(SDL_alarm_interval); + if (ms) { + SDL_alarm_interval = ROUND_RESOLUTION(ms); + PrimeTime((QElemPtr) & gExtendedTimerRec.tmTask, SDL_alarm_interval); + } else { + SDL_alarm_interval = 0; + } } -int SDL_SYS_StartTimer(void) +int +SDL_SYS_StartTimer(void) { - /* - * Configure the global structure that stores the timing information. - */ - gExtendedTimerRec.tmTask.qLink = NULL; - gExtendedTimerRec.tmTask.qType = 0; - gExtendedTimerRec.tmTask.tmAddr = NewTimerUPP(TimerCallbackProc); - gExtendedTimerRec.tmTask.tmCount = 0; - gExtendedTimerRec.tmTask.tmWakeUp = 0; - gExtendedTimerRec.tmTask.tmReserved = 0; - GetCurrentProcess(&gExtendedTimerRec.taskPSN); - - /* Install the task record */ - InsXTime((QElemPtr)&gExtendedTimerRec.tmTask); - - /* Go! */ - PrimeTime((QElemPtr)&gExtendedTimerRec.tmTask, SDL_alarm_interval); - return(0); + /* + * Configure the global structure that stores the timing information. + */ + gExtendedTimerRec.tmTask.qLink = NULL; + gExtendedTimerRec.tmTask.qType = 0; + gExtendedTimerRec.tmTask.tmAddr = NewTimerUPP(TimerCallbackProc); + gExtendedTimerRec.tmTask.tmCount = 0; + gExtendedTimerRec.tmTask.tmWakeUp = 0; + gExtendedTimerRec.tmTask.tmReserved = 0; + GetCurrentProcess(&gExtendedTimerRec.taskPSN); + + /* Install the task record */ + InsXTime((QElemPtr) & gExtendedTimerRec.tmTask); + + /* Go! */ + PrimeTime((QElemPtr) & gExtendedTimerRec.tmTask, SDL_alarm_interval); + return (0); } -void SDL_SYS_StopTimer(void) +void +SDL_SYS_StopTimer(void) { - RmvTime((QElemPtr)&gExtendedTimerRec.tmTask); + RmvTime((QElemPtr) & gExtendedTimerRec.tmTask); } #endif /* SDL_TIMER_MACOS */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/timer/macos/SDL_systimer.c b/src/timer/macos/SDL_systimer.c index 33fb664bf..54bb2a0ce 100644 --- a/src/timer/macos/SDL_systimer.c +++ b/src/timer/macos/SDL_systimer.c @@ -40,46 +40,50 @@ #define NewTimerProc NewTimerUPP #endif -#define MS_PER_TICK (1000.0/60.0) /* MacOS tick = 1/60 second */ +#define MS_PER_TICK (1000.0/60.0) /* MacOS tick = 1/60 second */ -#define kTwoPower32 (4294967296.0) /* 2^32 */ +#define kTwoPower32 (4294967296.0) /* 2^32 */ static double start_tick; -static int is_fast_inited = 0; +static int is_fast_inited = 0; -void SDL_StartTicks(void) +void +SDL_StartTicks(void) { - if ( ! is_fast_inited ) // important to check or FastTime may hang machine! - SDL_SYS_TimerInit(); + if (!is_fast_inited) // important to check or FastTime may hang machine! + SDL_SYS_TimerInit(); - start_tick = FastMicroseconds(); + start_tick = FastMicroseconds(); } -Uint32 SDL_GetTicks(void) +Uint32 +SDL_GetTicks(void) { - - if ( ! is_fast_inited ) - SDL_SYS_TimerInit(); - - return FastMilliseconds(); + + if (!is_fast_inited) + SDL_SYS_TimerInit(); + + return FastMilliseconds(); } -void SDL_Delay(Uint32 ms) +void +SDL_Delay(Uint32 ms) { - Uint32 stop, now; + Uint32 stop, now; - stop = SDL_GetTicks() + ms; - do { - #if TARGET_API_MAC_CARBON - MPYield(); - #else - SystemTask(); - #endif + stop = SDL_GetTicks() + ms; + do { +#if TARGET_API_MAC_CARBON + MPYield(); +#else + SystemTask(); +#endif - now = SDL_GetTicks(); + now = SDL_GetTicks(); - } while ( stop > now ); + } + while (stop > now); } /* @@ -115,72 +119,77 @@ void SDL_Delay(Uint32 ms) } }*/ - + /* Data to handle a single periodic alarm */ typedef struct _ExtendedTimerRec { - TMTask tmTask; - ProcessSerialNumber taskPSN; + TMTask tmTask; + ProcessSerialNumber taskPSN; } ExtendedTimerRec, *ExtendedTimerPtr; static ExtendedTimerRec gExtendedTimerRec; -int SDL_SYS_TimerInit(void) +int +SDL_SYS_TimerInit(void) { - FastInitialize (); - is_fast_inited = 1; - - return(0); + FastInitialize(); + is_fast_inited = 1; + + return (0); } -void SDL_SYS_TimerQuit(void) +void +SDL_SYS_TimerQuit(void) { - /* We don't need a cleanup? */ - return; + /* We don't need a cleanup? */ + return; } /* Our Stub routine to set up and then call the real routine. */ -pascal void TimerCallbackProc(TMTaskPtr tmTaskPtr) +pascal void +TimerCallbackProc(TMTaskPtr tmTaskPtr) { - Uint32 ms; + Uint32 ms; - WakeUpProcess(&((ExtendedTimerPtr) tmTaskPtr)->taskPSN); + WakeUpProcess(&((ExtendedTimerPtr) tmTaskPtr)->taskPSN); - ms = SDL_alarm_callback(SDL_alarm_interval); - if ( ms ) { - SDL_alarm_interval = ROUND_RESOLUTION(ms); - PrimeTime((QElemPtr)&gExtendedTimerRec.tmTask, - SDL_alarm_interval); - } else { - SDL_alarm_interval = 0; - } + ms = SDL_alarm_callback(SDL_alarm_interval); + if (ms) { + SDL_alarm_interval = ROUND_RESOLUTION(ms); + PrimeTime((QElemPtr) & gExtendedTimerRec.tmTask, SDL_alarm_interval); + } else { + SDL_alarm_interval = 0; + } } -int SDL_SYS_StartTimer(void) +int +SDL_SYS_StartTimer(void) { - /* - * Configure the global structure that stores the timing information. - */ - gExtendedTimerRec.tmTask.qLink = NULL; - gExtendedTimerRec.tmTask.qType = 0; - gExtendedTimerRec.tmTask.tmAddr = NewTimerProc(TimerCallbackProc); - gExtendedTimerRec.tmTask.tmCount = 0; - gExtendedTimerRec.tmTask.tmWakeUp = 0; - gExtendedTimerRec.tmTask.tmReserved = 0; - GetCurrentProcess(&gExtendedTimerRec.taskPSN); - - /* Install the task record */ - InsXTime((QElemPtr)&gExtendedTimerRec.tmTask); - - /* Go! */ - PrimeTime((QElemPtr)&gExtendedTimerRec.tmTask, SDL_alarm_interval); - return(0); + /* + * Configure the global structure that stores the timing information. + */ + gExtendedTimerRec.tmTask.qLink = NULL; + gExtendedTimerRec.tmTask.qType = 0; + gExtendedTimerRec.tmTask.tmAddr = NewTimerProc(TimerCallbackProc); + gExtendedTimerRec.tmTask.tmCount = 0; + gExtendedTimerRec.tmTask.tmWakeUp = 0; + gExtendedTimerRec.tmTask.tmReserved = 0; + GetCurrentProcess(&gExtendedTimerRec.taskPSN); + + /* Install the task record */ + InsXTime((QElemPtr) & gExtendedTimerRec.tmTask); + + /* Go! */ + PrimeTime((QElemPtr) & gExtendedTimerRec.tmTask, SDL_alarm_interval); + return (0); } -void SDL_SYS_StopTimer(void) +void +SDL_SYS_StopTimer(void) { - RmvTime((QElemPtr)&gExtendedTimerRec.tmTask); + RmvTime((QElemPtr) & gExtendedTimerRec.tmTask); } #endif /* SDL_TIMER_MACOS */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/timer/mint/SDL_systimer.c b/src/timer/mint/SDL_systimer.c index 8963ca0b7..69c8792fc 100644 --- a/src/timer/mint/SDL_systimer.c +++ b/src/timer/mint/SDL_systimer.c @@ -51,107 +51,116 @@ /* The first ticks value of the application */ static Uint32 start; static SDL_bool supervisor; -static int mint_present; /* can we use Syield() ? */ +static int mint_present; /* can we use Syield() ? */ -void SDL_StartTicks(void) +void +SDL_StartTicks(void) { - void *oldpile; - unsigned long dummy; + void *oldpile; + unsigned long dummy; - /* Set first ticks value */ - oldpile=(void *)Super(0); - start=*((volatile long *)_hz_200); - Super(oldpile); + /* Set first ticks value */ + oldpile = (void *) Super(0); + start = *((volatile long *) _hz_200); + Super(oldpile); - start *= 5; /* One _hz_200 tic is 5ms */ + start *= 5; /* One _hz_200 tic is 5ms */ - mint_present = (Getcookie(C_MiNT, &dummy) == C_FOUND); + mint_present = (Getcookie(C_MiNT, &dummy) == C_FOUND); } -Uint32 SDL_GetTicks (void) +Uint32 +SDL_GetTicks(void) { - Uint32 now; - void *oldpile=NULL; + Uint32 now; + void *oldpile = NULL; - /* Check if we are in supervisor mode - (this is the case when called from SDL_ThreadedTimerCheck, - which is called from RunTimer, running in the vbl vector) - */ - if (!supervisor) { - oldpile=(void *)Super(0); - } + /* Check if we are in supervisor mode + (this is the case when called from SDL_ThreadedTimerCheck, + which is called from RunTimer, running in the vbl vector) + */ + if (!supervisor) { + oldpile = (void *) Super(0); + } - now=*((volatile long *)_hz_200); + now = *((volatile long *) _hz_200); - if (!supervisor) { - Super(oldpile); - } + if (!supervisor) { + Super(oldpile); + } - return((now*5)-start); + return ((now * 5) - start); } -void SDL_Delay (Uint32 ms) +void +SDL_Delay(Uint32 ms) { - Uint32 now; - - now = SDL_GetTicks(); - while ((SDL_GetTicks()-now)= switch_priority) - switch_priority = 0; - if (switch_priority) - { - if (DosGetInfoBlocks(&tib, &pib)!=NO_ERROR) - switch_priority = 0; - else - { - /* In Warp3, to switch scheduling to 8ms step, one needs to do - DosAsyncTimer() in time-critical thread. On laters versions, - more and more cases of wait-for-something are covered. - - It turns out that on Warp3fp42 it is the priority at the time - of DosAsyncTimer() which matters. Let's hope that this works - with later versions too... XXXX - */ - priority = (tib->tib_ptib2->tib2_ulpri); - if ((priority & 0xFF00) == 0x0300) /* already time-critical */ - switch_priority = 0; - /* Make us time-critical. Just modifying TIB is not enough... */ - /* tib->tib_ptib2->tib2_ulpri = 0x0300;*/ - /* We do not want to run at high priority if a signal causes us - to longjmp() out of this section... */ - if (DosEnterMustComplete(&nesting)) + /* This is similar to DosSleep(), but has 8ms granularity in time-critical + threads even on Warp3. */ + HEV hevEvent1 = 0; /* Event semaphore handle */ + HTIMER htimerEvent1 = 0; /* Timer handle */ + APIRET rc = NO_ERROR; /* Return code */ + int ret = 1; + ULONG priority = 0, nesting; /* Shut down the warnings */ + PPIB pib; + PTIB tib; + char *e = NULL; + APIRET badrc; + int switch_priority = 50; + + DosCreateEventSem(NULL, /* Unnamed */ + &hevEvent1, /* Handle of semaphore returned */ + DC_SEM_SHARED, /* Shared needed for DosAsyncTimer */ + FALSE); /* Semaphore is in RESET state */ + + if (ms >= switch_priority) switch_priority = 0; - else - DosSetPriority(PRTYS_THREAD, PRTYC_TIMECRITICAL, 0, 0); + if (switch_priority) { + if (DosGetInfoBlocks(&tib, &pib) != NO_ERROR) + switch_priority = 0; + else { + /* In Warp3, to switch scheduling to 8ms step, one needs to do + DosAsyncTimer() in time-critical thread. On laters versions, + more and more cases of wait-for-something are covered. + + It turns out that on Warp3fp42 it is the priority at the time + of DosAsyncTimer() which matters. Let's hope that this works + with later versions too... XXXX + */ + priority = (tib->tib_ptib2->tib2_ulpri); + if ((priority & 0xFF00) == 0x0300) /* already time-critical */ + switch_priority = 0; + /* Make us time-critical. Just modifying TIB is not enough... */ + /* tib->tib_ptib2->tib2_ulpri = 0x0300; */ + /* We do not want to run at high priority if a signal causes us + to longjmp() out of this section... */ + if (DosEnterMustComplete(&nesting)) + switch_priority = 0; + else + DosSetPriority(PRTYS_THREAD, PRTYC_TIMECRITICAL, 0, 0); + } + } + + if ((badrc = DosAsyncTimer(ms, (HSEM) hevEvent1, /* Semaphore to post */ + &htimerEvent1))) /* Timer handler (returned) */ + e = "DosAsyncTimer"; + + if (switch_priority && tib->tib_ptib2->tib2_ulpri == 0x0300) { + /* Nobody switched priority while we slept... Ignore errors... */ + /* tib->tib_ptib2->tib2_ulpri = priority; *//* Get back... */ + if (! + (rc = DosSetPriority(PRTYS_THREAD, (priority >> 8) & 0xFF, 0, 0))) + rc = DosSetPriority(PRTYS_THREAD, 0, priority & 0xFF, 0); + } + if (switch_priority) + rc = DosExitMustComplete(&nesting); /* Ignore errors */ + + /* The actual blocking call is made with "normal" priority. This way we + should not bother with DosSleep(0) etc. to compensate for us interrupting + higher-priority threads. The goal is to prohibit the system spending too + much time halt()ing, not to run us "no matter what". */ + if (!e) /* Wait for AsyncTimer event */ + badrc = DosWaitEventSem(hevEvent1, SEM_INDEFINITE_WAIT); + + if (e); /* Do nothing */ + else if (badrc == ERROR_INTERRUPT) + ret = 0; + else if (badrc) + e = "DosWaitEventSem"; + if ((rc = DosCloseEventSem(hevEvent1)) && !e) { /* Get rid of semaphore */ + e = "DosCloseEventSem"; + badrc = rc; + } + if (e) { + SDL_SetError("[SDL_Delay] : Had error in %s(), rc is 0x%x\n", e, + badrc); } - } - - if ((badrc = DosAsyncTimer(ms, - (HSEM) hevEvent1, /* Semaphore to post */ - &htimerEvent1))) /* Timer handler (returned) */ - e = "DosAsyncTimer"; - - if (switch_priority && tib->tib_ptib2->tib2_ulpri == 0x0300) - { - /* Nobody switched priority while we slept... Ignore errors... */ - /* tib->tib_ptib2->tib2_ulpri = priority; */ /* Get back... */ - if (!(rc = DosSetPriority(PRTYS_THREAD, (priority>>8) & 0xFF, 0, 0))) - rc = DosSetPriority(PRTYS_THREAD, 0, priority & 0xFF, 0); - } - if (switch_priority) - rc = DosExitMustComplete(&nesting); /* Ignore errors */ - - /* The actual blocking call is made with "normal" priority. This way we - should not bother with DosSleep(0) etc. to compensate for us interrupting - higher-priority threads. The goal is to prohibit the system spending too - much time halt()ing, not to run us "no matter what". */ - if (!e) /* Wait for AsyncTimer event */ - badrc = DosWaitEventSem(hevEvent1, SEM_INDEFINITE_WAIT); - - if (e) ; /* Do nothing */ - else if (badrc == ERROR_INTERRUPT) - ret = 0; - else if (badrc) - e = "DosWaitEventSem"; - if ((rc = DosCloseEventSem(hevEvent1)) && !e) { /* Get rid of semaphore */ - e = "DosCloseEventSem"; - badrc = rc; - } - if (e) - { - SDL_SetError("[SDL_Delay] : Had error in %s(), rc is 0x%x\n", e, badrc); - } } /* Data to handle a single periodic alarm */ static int timer_alive = 0; static SDL_Thread *timer = NULL; -static int SDLCALL RunTimer(void *unused) +static int +RunTimer(void *unused) { - DosSetPriority(PRTYS_THREAD, PRTYC_TIMECRITICAL, 0, 0); - while ( timer_alive ) { - if ( SDL_timer_running ) { - SDL_ThreadedTimerCheck(); - } - SDL_Delay(10); + DosSetPriority(PRTYS_THREAD, PRTYC_TIMECRITICAL, 0, 0); + while (timer_alive) { + if (SDL_timer_running) { + SDL_ThreadedTimerCheck(); } - return(0); + SDL_Delay(10); + } + return (0); } /* This is only called if the event thread is not running */ -int SDL_SYS_TimerInit(void) +int +SDL_SYS_TimerInit(void) { - timer_alive = 1; - timer = SDL_CreateThread(RunTimer, NULL); - if ( timer == NULL ) - return(-1); - return(SDL_SetTimerThreaded(1)); + timer_alive = 1; + timer = SDL_CreateThread(RunTimer, NULL); + if (timer == NULL) + return (-1); + return (SDL_SetTimerThreaded(1)); } -void SDL_SYS_TimerQuit(void) +void +SDL_SYS_TimerQuit(void) { - timer_alive = 0; - if ( timer ) { - SDL_WaitThread(timer, NULL); - timer = NULL; - } + timer_alive = 0; + if (timer) { + SDL_WaitThread(timer, NULL); + timer = NULL; + } } -int SDL_SYS_StartTimer(void) +int +SDL_SYS_StartTimer(void) { - SDL_SetError("Internal logic error: OS/2 uses threaded timer"); - return(-1); + SDL_SetError("Internal logic error: OS/2 uses threaded timer"); + return (-1); } -void SDL_SYS_StopTimer(void) +void +SDL_SYS_StopTimer(void) { - return; + return; } #endif /* SDL_TIMER_OS2 */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/timer/riscos/SDL_systimer.c b/src/timer/riscos/SDL_systimer.c index b782f39ee..003f616a4 100644 --- a/src/timer/riscos/SDL_systimer.c +++ b/src/timer/riscos/SDL_systimer.c @@ -52,129 +52,139 @@ extern void RISCOS_BackgroundTasks(void); /* The first ticks value of the application */ clock_t start; -void SDL_StartTicks(void) +void +SDL_StartTicks(void) { - /* Set first ticks value */ - start = clock(); + /* Set first ticks value */ + start = clock(); } -Uint32 SDL_GetTicks (void) +Uint32 +SDL_GetTicks(void) { - clock_t ticks; + clock_t ticks; - ticks=clock()-start; + ticks = clock() - start; #if CLOCKS_PER_SEC == 1000 - return(ticks); + return (ticks); #elif CLOCKS_PER_SEC == 100 - return (ticks * 10); + return (ticks * 10); #else - return ticks*(1000/CLOCKS_PER_SEC); + return ticks * (1000 / CLOCKS_PER_SEC); #endif } -void SDL_Delay (Uint32 ms) +void +SDL_Delay(Uint32 ms) { - Uint32 now,then,elapsed; + Uint32 now, then, elapsed; #if !SDL_THREADS_DISABLED int is_event_thread; - if (riscos_using_threads) - { - is_event_thread = 0; - if (SDL_EventThreadID()) - { - if (SDL_EventThreadID() == SDL_ThreadID()) is_event_thread = 1; - } else if (SDL_ThreadID() == riscos_main_thread) is_event_thread = 1; - } else is_event_thread = 1; + if (riscos_using_threads) { + is_event_thread = 0; + if (SDL_EventThreadID()) { + if (SDL_EventThreadID() == SDL_ThreadID()) + is_event_thread = 1; + } else if (SDL_ThreadID() == riscos_main_thread) + is_event_thread = 1; + } else + is_event_thread = 1; #endif - /*TODO: Next version of Unixlib may allow us to use usleep here */ - /* for non event threads */ + /*TODO: Next version of Unixlib may allow us to use usleep here */ + /* for non event threads */ - /* Set the timeout interval - Linux only needs to do this once */ - then = SDL_GetTicks(); + /* Set the timeout interval - Linux only needs to do this once */ + then = SDL_GetTicks(); - do { - /* Do background tasks required while sleeping as we are not multithreaded */ + do { + /* Do background tasks required while sleeping as we are not multithreaded */ #if SDL_THREADS_DISABLED - RISCOS_BackgroundTasks(); + RISCOS_BackgroundTasks(); #else - /* For threaded build only run background tasks in event thread */ - if (is_event_thread) RISCOS_BackgroundTasks(); + /* For threaded build only run background tasks in event thread */ + if (is_event_thread) + RISCOS_BackgroundTasks(); #endif - /* Calculate the time interval left (in case of interrupt) */ - now = SDL_GetTicks(); - elapsed = (now-then); - then = now; - if ( elapsed >= ms ) { - break; - } - ms -= elapsed; + /* Calculate the time interval left (in case of interrupt) */ + now = SDL_GetTicks(); + elapsed = (now - then); + then = now; + if (elapsed >= ms) { + break; + } + ms -= elapsed; #if !SDL_THREADS_DISABLED - /* Need to yield to let other threads have a go */ - if (riscos_using_threads) pthread_yield(); + /* Need to yield to let other threads have a go */ + if (riscos_using_threads) + pthread_yield(); #endif - } while ( 1 ); + } + while (1); } #if SDL_THREADS_DISABLED /* Non-threaded version of timer */ -int SDL_SYS_TimerInit(void) +int +SDL_SYS_TimerInit(void) { - return(0); + return (0); } -void SDL_SYS_TimerQuit(void) +void +SDL_SYS_TimerQuit(void) { - SDL_SetTimer(0, NULL); + SDL_SetTimer(0, NULL); } -int SDL_SYS_StartTimer(void) +int +SDL_SYS_StartTimer(void) { - timerStart = SDL_GetTicks(); + timerStart = SDL_GetTicks(); - return(0); + return (0); } -void SDL_SYS_StopTimer(void) +void +SDL_SYS_StopTimer(void) { - /* Don't need to do anything as we use SDL_timer_running - to detect if we need to check the timer */ + /* Don't need to do anything as we use SDL_timer_running + to detect if we need to check the timer */ } -void RISCOS_CheckTimer() +void +RISCOS_CheckTimer() { - if (SDL_timer_running && SDL_GetTicks() - timerStart >= SDL_alarm_interval) - { - Uint32 ms; - - ms = SDL_alarm_callback(SDL_alarm_interval); - if ( ms != SDL_alarm_interval ) - { - if ( ms ) - { - SDL_alarm_interval = ROUND_RESOLUTION(ms); - } else - { - SDL_alarm_interval = 0; - SDL_timer_running = 0; - } - } - if (SDL_alarm_interval) timerStart = SDL_GetTicks(); - } + if (SDL_timer_running + && SDL_GetTicks() - timerStart >= SDL_alarm_interval) { + Uint32 ms; + + ms = SDL_alarm_callback(SDL_alarm_interval); + if (ms != SDL_alarm_interval) { + if (ms) { + SDL_alarm_interval = ROUND_RESOLUTION(ms); + } else { + SDL_alarm_interval = 0; + SDL_timer_running = 0; + } + } + if (SDL_alarm_interval) + timerStart = SDL_GetTicks(); + } } #else @@ -187,47 +197,53 @@ void RISCOS_CheckTimer() static int timer_alive = 0; static SDL_Thread *timer = NULL; -static int RunTimer(void *unused) +static int +RunTimer(void *unused) { - while ( timer_alive ) { - if ( SDL_timer_running ) { - SDL_ThreadedTimerCheck(); - } - SDL_Delay(1); - } - return(0); + while (timer_alive) { + if (SDL_timer_running) { + SDL_ThreadedTimerCheck(); + } + SDL_Delay(1); + } + return (0); } /* This is only called if the event thread is not running */ -int SDL_SYS_TimerInit(void) +int +SDL_SYS_TimerInit(void) { - timer_alive = 1; - timer = SDL_CreateThread(RunTimer, NULL); - if ( timer == NULL ) - return(-1); - return(SDL_SetTimerThreaded(1)); + timer_alive = 1; + timer = SDL_CreateThread(RunTimer, NULL); + if (timer == NULL) + return (-1); + return (SDL_SetTimerThreaded(1)); } -void SDL_SYS_TimerQuit(void) +void +SDL_SYS_TimerQuit(void) { - timer_alive = 0; - if ( timer ) { - SDL_WaitThread(timer, NULL); - timer = NULL; - } + timer_alive = 0; + if (timer) { + SDL_WaitThread(timer, NULL); + timer = NULL; + } } -int SDL_SYS_StartTimer(void) +int +SDL_SYS_StartTimer(void) { - SDL_SetError("Internal logic error: RISC OS uses threaded timer"); - return(-1); + SDL_SetError("Internal logic error: RISC OS uses threaded timer"); + return (-1); } -void SDL_SYS_StopTimer(void) +void +SDL_SYS_StopTimer(void) { - return; + return; } #endif /* SDL_THREADS_DISABLED */ #endif /* SDL_TIMER_RISCOS */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/timer/unix/SDL_systimer.c b/src/timer/unix/SDL_systimer.c index 58b53ed01..89b415739 100644 --- a/src/timer/unix/SDL_systimer.c +++ b/src/timer/unix/SDL_systimer.c @@ -58,132 +58,145 @@ static struct timeval start; #endif /* HAVE_CLOCK_GETTIME */ -void SDL_StartTicks(void) +void +SDL_StartTicks(void) { - /* Set first ticks value */ + /* Set first ticks value */ #if HAVE_CLOCK_GETTIME - clock_gettime(CLOCK_MONOTONIC,&start); + clock_gettime(CLOCK_MONOTONIC, &start); #else - gettimeofday(&start, NULL); + gettimeofday(&start, NULL); #endif } -Uint32 SDL_GetTicks (void) +Uint32 +SDL_GetTicks(void) { #if HAVE_CLOCK_GETTIME - Uint32 ticks; - struct timespec now; - clock_gettime(CLOCK_MONOTONIC,&now); - ticks=(now.tv_sec-start.tv_sec)*1000+(now.tv_nsec-start.tv_nsec)/1000000; - return(ticks); + Uint32 ticks; + struct timespec now; + clock_gettime(CLOCK_MONOTONIC, &now); + ticks = + (now.tv_sec - start.tv_sec) * 1000 + (now.tv_nsec - + start.tv_nsec) / 1000000; + return (ticks); #else - Uint32 ticks; - struct timeval now; - gettimeofday(&now, NULL); - ticks=(now.tv_sec-start.tv_sec)*1000+(now.tv_usec-start.tv_usec)/1000; - return(ticks); + Uint32 ticks; + struct timeval now; + gettimeofday(&now, NULL); + ticks = + (now.tv_sec - start.tv_sec) * 1000 + (now.tv_usec - + start.tv_usec) / 1000; + return (ticks); #endif } -void SDL_Delay (Uint32 ms) +void +SDL_Delay(Uint32 ms) { #if SDL_THREAD_PTH - pth_time_t tv; - tv.tv_sec = ms/1000; - tv.tv_usec = (ms%1000)*1000; - pth_nap(tv); + pth_time_t tv; + tv.tv_sec = ms / 1000; + tv.tv_usec = (ms % 1000) * 1000; + pth_nap(tv); #else - int was_error; + int was_error; #if HAVE_NANOSLEEP - struct timespec elapsed, tv; + struct timespec elapsed, tv; #else - struct timeval tv; - Uint32 then, now, elapsed; + struct timeval tv; + Uint32 then, now, elapsed; #endif - /* Set the timeout interval */ + /* Set the timeout interval */ #if HAVE_NANOSLEEP - elapsed.tv_sec = ms/1000; - elapsed.tv_nsec = (ms%1000)*1000000; + elapsed.tv_sec = ms / 1000; + elapsed.tv_nsec = (ms % 1000) * 1000000; #else - then = SDL_GetTicks(); + then = SDL_GetTicks(); #endif - do { - errno = 0; + do { + errno = 0; #if HAVE_NANOSLEEP - tv.tv_sec = elapsed.tv_sec; - tv.tv_nsec = elapsed.tv_nsec; - was_error = nanosleep(&tv, &elapsed); + tv.tv_sec = elapsed.tv_sec; + tv.tv_nsec = elapsed.tv_nsec; + was_error = nanosleep(&tv, &elapsed); #else - /* Calculate the time interval left (in case of interrupt) */ - now = SDL_GetTicks(); - elapsed = (now-then); - then = now; - if ( elapsed >= ms ) { - break; - } - ms -= elapsed; - tv.tv_sec = ms/1000; - tv.tv_usec = (ms%1000)*1000; - - was_error = select(0, NULL, NULL, NULL, &tv); + /* Calculate the time interval left (in case of interrupt) */ + now = SDL_GetTicks(); + elapsed = (now - then); + then = now; + if (elapsed >= ms) { + break; + } + ms -= elapsed; + tv.tv_sec = ms / 1000; + tv.tv_usec = (ms % 1000) * 1000; + + was_error = select(0, NULL, NULL, NULL, &tv); #endif /* HAVE_NANOSLEEP */ - } while ( was_error && (errno == EINTR) ); + } + while (was_error && (errno == EINTR)); #endif /* SDL_THREAD_PTH */ } #ifdef USE_ITIMER -static void HandleAlarm(int sig) +static void +HandleAlarm(int sig) { - Uint32 ms; - - if ( SDL_alarm_callback ) { - ms = (*SDL_alarm_callback)(SDL_alarm_interval); - if ( ms != SDL_alarm_interval ) { - SDL_SetTimer(ms, SDL_alarm_callback); - } - } + Uint32 ms; + + if (SDL_alarm_callback) { + ms = (*SDL_alarm_callback) (SDL_alarm_interval); + if (ms != SDL_alarm_interval) { + SDL_SetTimer(ms, SDL_alarm_callback); + } + } } -int SDL_SYS_TimerInit(void) +int +SDL_SYS_TimerInit(void) { - struct sigaction action; - - /* Set the alarm handler (Linux specific) */ - SDL_memset(&action, 0, sizeof(action)); - action.sa_handler = HandleAlarm; - action.sa_flags = SA_RESTART; - sigemptyset(&action.sa_mask); - sigaction(SIGALRM, &action, NULL); - return(0); + struct sigaction action; + + /* Set the alarm handler (Linux specific) */ + SDL_memset(&action, 0, sizeof(action)); + action.sa_handler = HandleAlarm; + action.sa_flags = SA_RESTART; + sigemptyset(&action.sa_mask); + sigaction(SIGALRM, &action, NULL); + return (0); } -void SDL_SYS_TimerQuit(void) +void +SDL_SYS_TimerQuit(void) { - SDL_SetTimer(0, NULL); + SDL_SetTimer(0, NULL); } -int SDL_SYS_StartTimer(void) +int +SDL_SYS_StartTimer(void) { - struct itimerval timer; - - timer.it_value.tv_sec = (SDL_alarm_interval/1000); - timer.it_value.tv_usec = (SDL_alarm_interval%1000)*1000; - timer.it_interval.tv_sec = (SDL_alarm_interval/1000); - timer.it_interval.tv_usec = (SDL_alarm_interval%1000)*1000; - setitimer(ITIMER_REAL, &timer, NULL); - return(0); + struct itimerval timer; + + timer.it_value.tv_sec = (SDL_alarm_interval / 1000); + timer.it_value.tv_usec = (SDL_alarm_interval % 1000) * 1000; + timer.it_interval.tv_sec = (SDL_alarm_interval / 1000); + timer.it_interval.tv_usec = (SDL_alarm_interval % 1000) * 1000; + setitimer(ITIMER_REAL, &timer, NULL); + return (0); } -void SDL_SYS_StopTimer(void) +void +SDL_SYS_StopTimer(void) { - struct itimerval timer; + struct itimerval timer; - SDL_memset(&timer, 0, (sizeof timer)); - setitimer(ITIMER_REAL, &timer, NULL); + SDL_memset(&timer, 0, (sizeof timer)); + setitimer(ITIMER_REAL, &timer, NULL); } #else /* USE_ITIMER */ @@ -194,47 +207,53 @@ void SDL_SYS_StopTimer(void) static int timer_alive = 0; static SDL_Thread *timer = NULL; -static int RunTimer(void *unused) +static int +RunTimer(void *unused) { - while ( timer_alive ) { - if ( SDL_timer_running ) { - SDL_ThreadedTimerCheck(); - } - SDL_Delay(1); - } - return(0); + while (timer_alive) { + if (SDL_timer_running) { + SDL_ThreadedTimerCheck(); + } + SDL_Delay(1); + } + return (0); } /* This is only called if the event thread is not running */ -int SDL_SYS_TimerInit(void) +int +SDL_SYS_TimerInit(void) { - timer_alive = 1; - timer = SDL_CreateThread(RunTimer, NULL); - if ( timer == NULL ) - return(-1); - return(SDL_SetTimerThreaded(1)); + timer_alive = 1; + timer = SDL_CreateThread(RunTimer, NULL); + if (timer == NULL) + return (-1); + return (SDL_SetTimerThreaded(1)); } -void SDL_SYS_TimerQuit(void) +void +SDL_SYS_TimerQuit(void) { - timer_alive = 0; - if ( timer ) { - SDL_WaitThread(timer, NULL); - timer = NULL; - } + timer_alive = 0; + if (timer) { + SDL_WaitThread(timer, NULL); + timer = NULL; + } } -int SDL_SYS_StartTimer(void) +int +SDL_SYS_StartTimer(void) { - SDL_SetError("Internal logic error: Linux uses threaded timer"); - return(-1); + SDL_SetError("Internal logic error: Linux uses threaded timer"); + return (-1); } -void SDL_SYS_StopTimer(void) +void +SDL_SYS_StopTimer(void) { - return; + return; } #endif /* USE_ITIMER */ #endif /* SDL_TIMER_UNIX */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/timer/win32/SDL_systimer.c b/src/timer/win32/SDL_systimer.c index 4a24d130f..865733ec8 100644 --- a/src/timer/win32/SDL_systimer.c +++ b/src/timer/win32/SDL_systimer.c @@ -31,7 +31,7 @@ #include "../SDL_timer_c.h" #ifdef _WIN32_WCE - #error This is WinCE. Please use src/timer/wince/SDL_systimer.c instead. +#error This is WinCE. Please use src/timer/wince/SDL_systimer.c instead. #endif #define TIME_WRAP_VALUE (~(DWORD)0) @@ -48,113 +48,118 @@ static LARGE_INTEGER hires_start_ticks; static LARGE_INTEGER hires_ticks_per_second; #endif -void SDL_StartTicks(void) +void +SDL_StartTicks(void) { - /* Set first ticks value */ + /* Set first ticks value */ #ifdef USE_GETTICKCOUNT - start = GetTickCount(); + start = GetTickCount(); #else -#if 0 /* Apparently there are problems with QPC on Win2K */ - if (QueryPerformanceFrequency(&hires_ticks_per_second) == TRUE) - { - hires_timer_available = TRUE; - QueryPerformanceCounter(&hires_start_ticks); - } - else +#if 0 /* Apparently there are problems with QPC on Win2K */ + if (QueryPerformanceFrequency(&hires_ticks_per_second) == TRUE) { + hires_timer_available = TRUE; + QueryPerformanceCounter(&hires_start_ticks); + } else #endif - { - hires_timer_available = FALSE; - timeBeginPeriod(1); /* use 1 ms timer precision */ - start = timeGetTime(); - } + { + hires_timer_available = FALSE; + timeBeginPeriod(1); /* use 1 ms timer precision */ + start = timeGetTime(); + } #endif } -Uint32 SDL_GetTicks(void) +Uint32 +SDL_GetTicks(void) { - DWORD now, ticks; + DWORD now, ticks; #ifndef USE_GETTICKCOUNT - LARGE_INTEGER hires_now; + LARGE_INTEGER hires_now; #endif #ifdef USE_GETTICKCOUNT - now = GetTickCount(); + now = GetTickCount(); #else - if (hires_timer_available) - { - QueryPerformanceCounter(&hires_now); - - hires_now.QuadPart -= hires_start_ticks.QuadPart; - hires_now.QuadPart *= 1000; - hires_now.QuadPart /= hires_ticks_per_second.QuadPart; - - return (DWORD)hires_now.QuadPart; - } - else - { - now = timeGetTime(); - } + if (hires_timer_available) { + QueryPerformanceCounter(&hires_now); + + hires_now.QuadPart -= hires_start_ticks.QuadPart; + hires_now.QuadPart *= 1000; + hires_now.QuadPart /= hires_ticks_per_second.QuadPart; + + return (DWORD) hires_now.QuadPart; + } else { + now = timeGetTime(); + } #endif - if ( now < start ) { - ticks = (TIME_WRAP_VALUE-start) + now; - } else { - ticks = (now - start); - } - return(ticks); + if (now < start) { + ticks = (TIME_WRAP_VALUE - start) + now; + } else { + ticks = (now - start); + } + return (ticks); } -void SDL_Delay(Uint32 ms) +void +SDL_Delay(Uint32 ms) { - Sleep(ms); + Sleep(ms); } /* Data to handle a single periodic alarm */ static UINT timerID = 0; -static void CALLBACK HandleAlarm(UINT uID, UINT uMsg, DWORD_PTR dwUser, - DWORD_PTR dw1, DWORD_PTR dw2) +static void CALLBACK +HandleAlarm(UINT uID, UINT uMsg, DWORD_PTR dwUser, + DWORD_PTR dw1, DWORD_PTR dw2) { - SDL_ThreadedTimerCheck(); + SDL_ThreadedTimerCheck(); } -int SDL_SYS_TimerInit(void) +int +SDL_SYS_TimerInit(void) { - MMRESULT result; - - /* Set timer resolution */ - result = timeBeginPeriod(TIMER_RESOLUTION); - if ( result != TIMERR_NOERROR ) { - SDL_SetError("Warning: Can't set %d ms timer resolution", - TIMER_RESOLUTION); - } - /* Allow 10 ms of drift so we don't chew on CPU */ - timerID = timeSetEvent(TIMER_RESOLUTION,1,HandleAlarm,0,TIME_PERIODIC); - if ( ! timerID ) { - SDL_SetError("timeSetEvent() failed"); - return(-1); - } - return(SDL_SetTimerThreaded(1)); + MMRESULT result; + + /* Set timer resolution */ + result = timeBeginPeriod(TIMER_RESOLUTION); + if (result != TIMERR_NOERROR) { + SDL_SetError("Warning: Can't set %d ms timer resolution", + TIMER_RESOLUTION); + } + /* Allow 10 ms of drift so we don't chew on CPU */ + timerID = + timeSetEvent(TIMER_RESOLUTION, 1, HandleAlarm, 0, TIME_PERIODIC); + if (!timerID) { + SDL_SetError("timeSetEvent() failed"); + return (-1); + } + return (SDL_SetTimerThreaded(1)); } -void SDL_SYS_TimerQuit(void) +void +SDL_SYS_TimerQuit(void) { - if ( timerID ) { - timeKillEvent(timerID); - } - timeEndPeriod(TIMER_RESOLUTION); + if (timerID) { + timeKillEvent(timerID); + } + timeEndPeriod(TIMER_RESOLUTION); } -int SDL_SYS_StartTimer(void) +int +SDL_SYS_StartTimer(void) { - SDL_SetError("Internal logic error: Win32 uses threaded timer"); - return(-1); + SDL_SetError("Internal logic error: Win32 uses threaded timer"); + return (-1); } -void SDL_SYS_StopTimer(void) +void +SDL_SYS_StopTimer(void) { - return; + return; } #endif /* SDL_TIMER_WIN32 */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/timer/wince/SDL_systimer.c b/src/timer/wince/SDL_systimer.c index 1e129db76..4883db7ac 100644 --- a/src/timer/wince/SDL_systimer.c +++ b/src/timer/wince/SDL_systimer.c @@ -34,62 +34,68 @@ static Uint64 start_date; static Uint64 start_ticks; -static Uint64 wce_ticks(void) +static Uint64 +wce_ticks(void) { - return((Uint64)GetTickCount()); + return ((Uint64) GetTickCount()); } -static Uint64 wce_date(void) +static Uint64 +wce_date(void) { - union - { - FILETIME ftime; - Uint64 itime; - } ftime; - SYSTEMTIME stime; - - GetSystemTime(&stime); - SystemTimeToFileTime(&stime,&ftime.ftime); - ftime.itime/=10000; // Convert 100ns intervals to 1ms intervals - // Remove ms portion, which can't be relied on - ftime.itime -= (ftime.itime % 1000); - return(ftime.itime); + union + { + FILETIME ftime; + Uint64 itime; + } ftime; + SYSTEMTIME stime; + + GetSystemTime(&stime); + SystemTimeToFileTime(&stime, &ftime.ftime); + ftime.itime /= 10000; // Convert 100ns intervals to 1ms intervals + // Remove ms portion, which can't be relied on + ftime.itime -= (ftime.itime % 1000); + return (ftime.itime); } -static Sint32 wce_rel_ticks(void) +static Sint32 +wce_rel_ticks(void) { - return((Sint32)(wce_ticks()-start_ticks)); + return ((Sint32) (wce_ticks() - start_ticks)); } -static Sint32 wce_rel_date(void) +static Sint32 +wce_rel_date(void) { - return((Sint32)(wce_date()-start_date)); + return ((Sint32) (wce_date() - start_date)); } /* Return time in ms relative to when SDL was started */ -Uint32 SDL_GetTicks() +Uint32 +SDL_GetTicks() { - Sint32 offset=wce_rel_date()-wce_rel_ticks(); - if((offset < -1000) || (offset > 1000)) - { + Sint32 offset = wce_rel_date() - wce_rel_ticks(); + if ((offset < -1000) || (offset > 1000)) { // fprintf(stderr,"Time desync(%+d), resyncing\n",offset/1000); - start_ticks-=offset; - } + start_ticks -= offset; + } - return((Uint32)wce_rel_ticks()); + return ((Uint32) wce_rel_ticks()); } /* Give up approx. givem milliseconds to the OS. */ -void SDL_Delay(Uint32 ms) +void +SDL_Delay(Uint32 ms) { - Sleep(ms); + Sleep(ms); } /* Recard start-time of application for reference */ -void SDL_StartTicks(void) +void +SDL_StartTicks(void) { - start_date=wce_date(); - start_ticks=wce_ticks(); + start_date = wce_date(); + start_ticks = wce_ticks(); } static UINT WIN_timer; @@ -99,46 +105,47 @@ static UINT WIN_timer; static HANDLE timersThread = 0; static HANDLE timersQuitEvent = 0; -DWORD TimersThreadProc(void *data) +DWORD +TimersThreadProc(void *data) { - while(WaitForSingleObject(timersQuitEvent, 10) == WAIT_TIMEOUT) - { - SDL_ThreadedTimerCheck(); - } - return 0; + while (WaitForSingleObject(timersQuitEvent, 10) == WAIT_TIMEOUT) { + SDL_ThreadedTimerCheck(); + } + return 0; } -int SDL_SYS_TimerInit(void) +int +SDL_SYS_TimerInit(void) { - // create a thread to process a threaded timers - // SetTimer does not suit the needs because - // TimerCallbackProc will be called only when WM_TIMER occured - - timersQuitEvent = CreateEvent(0, TRUE, FALSE, 0); - if( !timersQuitEvent ) - { - SDL_SetError("Cannot create event for timers thread"); - return -1; - } - timersThread = CreateThread(NULL, 0, TimersThreadProc, 0, 0, 0); - if( !timersThread ) - { - SDL_SetError("Cannot create timers thread, check amount of RAM available"); - return -1; - } - SetThreadPriority(timersThread, THREAD_PRIORITY_HIGHEST); - - return(SDL_SetTimerThreaded(1)); + // create a thread to process a threaded timers + // SetTimer does not suit the needs because + // TimerCallbackProc will be called only when WM_TIMER occured + + timersQuitEvent = CreateEvent(0, TRUE, FALSE, 0); + if (!timersQuitEvent) { + SDL_SetError("Cannot create event for timers thread"); + return -1; + } + timersThread = CreateThread(NULL, 0, TimersThreadProc, 0, 0, 0); + if (!timersThread) { + SDL_SetError + ("Cannot create timers thread, check amount of RAM available"); + return -1; + } + SetThreadPriority(timersThread, THREAD_PRIORITY_HIGHEST); + + return (SDL_SetTimerThreaded(1)); } -void SDL_SYS_TimerQuit(void) +void +SDL_SYS_TimerQuit(void) { - SetEvent(timersQuitEvent); - if( WaitForSingleObject(timersThread, 2000) == WAIT_TIMEOUT ) - TerminateThread(timersThread, 0); - CloseHandle(timersThread); - CloseHandle(timersQuitEvent); - return; + SetEvent(timersQuitEvent); + if (WaitForSingleObject(timersThread, 2000) == WAIT_TIMEOUT) + TerminateThread(timersThread, 0); + CloseHandle(timersThread); + CloseHandle(timersQuitEvent); + return; } #else @@ -148,51 +155,57 @@ void SDL_SYS_TimerQuit(void) /* Data to handle a single periodic alarm */ static UINT timerID = 0; -static void CALLBACK HandleAlarm(UINT uID, UINT uMsg, DWORD dwUser, - DWORD dw1, DWORD dw2) +static void CALLBACK +HandleAlarm(UINT uID, UINT uMsg, DWORD dwUser, DWORD dw1, DWORD dw2) { - SDL_ThreadedTimerCheck(); + SDL_ThreadedTimerCheck(); } -int SDL_SYS_TimerInit(void) +int +SDL_SYS_TimerInit(void) { - MMRESULT result; - - /* Set timer resolution */ - result = timeBeginPeriod(TIMER_RESOLUTION); - if ( result != TIMERR_NOERROR ) { - SDL_SetError("Warning: Can't set %d ms timer resolution", - TIMER_RESOLUTION); - } - /* Allow 10 ms of drift so we don't chew on CPU */ - timerID = timeSetEvent(TIMER_RESOLUTION,1,HandleAlarm,0,TIME_PERIODIC); - if ( ! timerID ) { - SDL_SetError("timeSetEvent() failed"); - return(-1); - } - return(SDL_SetTimerThreaded(1)); + MMRESULT result; + + /* Set timer resolution */ + result = timeBeginPeriod(TIMER_RESOLUTION); + if (result != TIMERR_NOERROR) { + SDL_SetError("Warning: Can't set %d ms timer resolution", + TIMER_RESOLUTION); + } + /* Allow 10 ms of drift so we don't chew on CPU */ + timerID = + timeSetEvent(TIMER_RESOLUTION, 1, HandleAlarm, 0, TIME_PERIODIC); + if (!timerID) { + SDL_SetError("timeSetEvent() failed"); + return (-1); + } + return (SDL_SetTimerThreaded(1)); } -void SDL_SYS_TimerQuit(void) +void +SDL_SYS_TimerQuit(void) { - if ( timerID ) { - timeKillEvent(timerID); - } - timeEndPeriod(TIMER_RESOLUTION); + if (timerID) { + timeKillEvent(timerID); + } + timeEndPeriod(TIMER_RESOLUTION); } #endif -int SDL_SYS_StartTimer(void) +int +SDL_SYS_StartTimer(void) { - SDL_SetError("Internal logic error: WinCE uses threaded timer"); - return(-1); + SDL_SetError("Internal logic error: WinCE uses threaded timer"); + return (-1); } -void SDL_SYS_StopTimer(void) +void +SDL_SYS_StopTimer(void) { - return; + return; } #endif /* SDL_TIMER_WINCE */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/SDL_RLEaccel.c b/src/video/SDL_RLEaccel.c index cf33352ba..3101dcf18 100644 --- a/src/video/SDL_RLEaccel.c +++ b/src/video/SDL_RLEaccel.c @@ -545,7 +545,7 @@ do { \ } while(0) #endif - + /* * Special case: 50% alpha (alpha=128) * This is treated specially because it can be optimized very well, and @@ -704,7 +704,7 @@ do { \ } while(0) #else - + #define CHOOSE_BLIT(blitter, alpha, fmt) \ do { \ if(alpha == 255) { \ @@ -779,8 +779,9 @@ do { \ * This takes care of the case when the surface is clipped on the left and/or * right. Top clipping has already been taken care of. */ -static void RLEClipBlit(int w, Uint8 *srcbuf, SDL_Surface *dst, - Uint8 *dstbuf, SDL_Rect *srcrect, unsigned alpha) +static void +RLEClipBlit(int w, Uint8 * srcbuf, SDL_Surface * dst, + Uint8 * dstbuf, SDL_Rect * srcrect, unsigned alpha) { SDL_PixelFormat *fmt = dst->format; @@ -836,34 +837,35 @@ static void RLEClipBlit(int w, Uint8 *srcbuf, SDL_Surface *dst, /* blit a colorkeyed RLE surface */ -int SDL_RLEBlit(SDL_Surface *src, SDL_Rect *srcrect, - SDL_Surface *dst, SDL_Rect *dstrect) +int +SDL_RLEBlit(SDL_Surface * src, SDL_Rect * srcrect, + SDL_Surface * dst, SDL_Rect * dstrect) { - Uint8 *dstbuf; - Uint8 *srcbuf; - int x, y; - int w = src->w; - unsigned alpha; - - /* Lock the destination if necessary */ - if ( SDL_MUSTLOCK(dst) ) { - if ( SDL_LockSurface(dst) < 0 ) { - return(-1); - } - } + Uint8 *dstbuf; + Uint8 *srcbuf; + int x, y; + int w = src->w; + unsigned alpha; - /* Set up the source and destination pointers */ - x = dstrect->x; - y = dstrect->y; - dstbuf = (Uint8 *)dst->pixels - + y * dst->pitch + x * src->format->BytesPerPixel; - srcbuf = (Uint8 *)src->map->sw_data->aux_data; + /* Lock the destination if necessary */ + if (SDL_MUSTLOCK(dst)) { + if (SDL_LockSurface(dst) < 0) { + return (-1); + } + } - { - /* skip lines at the top if neccessary */ - int vskip = srcrect->y; - int ofs = 0; - if(vskip) { + /* Set up the source and destination pointers */ + x = dstrect->x; + y = dstrect->y; + dstbuf = (Uint8 *) dst->pixels + + y * dst->pitch + x * src->format->BytesPerPixel; + srcbuf = (Uint8 *) src->map->sw_data->aux_data; + + { + /* skip lines at the top if neccessary */ + int vskip = srcrect->y; + int ofs = 0; + if (vskip) { #define RLESKIP(bpp, Type) \ for(;;) { \ @@ -883,25 +885,33 @@ int SDL_RLEBlit(SDL_Surface *src, SDL_Rect *srcrect, } \ } - switch(src->format->BytesPerPixel) { - case 1: RLESKIP(1, Uint8); break; - case 2: RLESKIP(2, Uint8); break; - case 3: RLESKIP(3, Uint8); break; - case 4: RLESKIP(4, Uint16); break; - } + switch (src->format->BytesPerPixel) { + case 1: + RLESKIP(1, Uint8); + break; + case 2: + RLESKIP(2, Uint8); + break; + case 3: + RLESKIP(3, Uint8); + break; + case 4: + RLESKIP(4, Uint16); + break; + } #undef RLESKIP - } - } + } + } - alpha = (src->flags & SDL_SRCALPHA) == SDL_SRCALPHA - ? src->format->alpha : 255; - /* if left or right edge clipping needed, call clip blit */ - if ( srcrect->x || srcrect->w != src->w ) { - RLEClipBlit(w, srcbuf, dst, dstbuf, srcrect, alpha); - } else { - SDL_PixelFormat *fmt = src->format; + alpha = (src->flags & SDL_SRCALPHA) == SDL_SRCALPHA + ? src->format->alpha : 255; + /* if left or right edge clipping needed, call clip blit */ + if (srcrect->x || srcrect->w != src->w) { + RLEClipBlit(w, srcbuf, dst, dstbuf, srcrect, alpha); + } else { + SDL_PixelFormat *fmt = src->format; #define RLEBLIT(bpp, Type, do_blit) \ do { \ @@ -927,17 +937,17 @@ int SDL_RLEBlit(SDL_Surface *src, SDL_Rect *srcrect, } \ } while(0) - CHOOSE_BLIT(RLEBLIT, alpha, fmt); + CHOOSE_BLIT(RLEBLIT, alpha, fmt); #undef RLEBLIT - } + } -done: - /* Unlock the destination if necessary */ - if ( SDL_MUSTLOCK(dst) ) { - SDL_UnlockSurface(dst); - } - return(0); + done: + /* Unlock the destination if necessary */ + if (SDL_MUSTLOCK(dst)) { + SDL_UnlockSurface(dst); + } + return (0); } #undef OPAQUE_BLIT @@ -995,24 +1005,26 @@ int SDL_RLEBlit(SDL_Surface *src, SDL_Rect *srcrect, /* used to save the destination format in the encoding. Designed to be macro-compatible with SDL_PixelFormat but without the unneeded fields */ -typedef struct { - Uint8 BytesPerPixel; - Uint8 Rloss; - Uint8 Gloss; - Uint8 Bloss; - Uint8 Rshift; - Uint8 Gshift; - Uint8 Bshift; - Uint8 Ashift; - Uint32 Rmask; - Uint32 Gmask; - Uint32 Bmask; - Uint32 Amask; +typedef struct +{ + Uint8 BytesPerPixel; + Uint8 Rloss; + Uint8 Gloss; + Uint8 Bloss; + Uint8 Rshift; + Uint8 Gshift; + Uint8 Bshift; + Uint8 Ashift; + Uint32 Rmask; + Uint32 Gmask; + Uint32 Bmask; + Uint32 Amask; } RLEDestFormat; /* blit a pixel-alpha RLE surface clipped at the right and/or left edges */ -static void RLEAlphaClipBlit(int w, Uint8 *srcbuf, SDL_Surface *dst, - Uint8 *dstbuf, SDL_Rect *srcrect) +static void +RLEAlphaClipBlit(int w, Uint8 * srcbuf, SDL_Surface * dst, + Uint8 * dstbuf, SDL_Rect * srcrect) { SDL_PixelFormat *df = dst->format; /* @@ -1088,23 +1100,23 @@ static void RLEAlphaClipBlit(int w, Uint8 *srcbuf, SDL_Surface *dst, } while(--linecount); \ } while(0) - switch(df->BytesPerPixel) { + switch (df->BytesPerPixel) { case 2: - if(df->Gmask == 0x07e0 || df->Rmask == 0x07e0 - || df->Bmask == 0x07e0) - RLEALPHACLIPBLIT(Uint16, Uint8, BLIT_TRANSL_565); - else - RLEALPHACLIPBLIT(Uint16, Uint8, BLIT_TRANSL_555); - break; + if (df->Gmask == 0x07e0 || df->Rmask == 0x07e0 || df->Bmask == 0x07e0) + RLEALPHACLIPBLIT(Uint16, Uint8, BLIT_TRANSL_565); + else + RLEALPHACLIPBLIT(Uint16, Uint8, BLIT_TRANSL_555); + break; case 4: - RLEALPHACLIPBLIT(Uint32, Uint16, BLIT_TRANSL_888); - break; + RLEALPHACLIPBLIT(Uint32, Uint16, BLIT_TRANSL_888); + break; } } /* blit a pixel-alpha RLE surface */ -int SDL_RLEAlphaBlit(SDL_Surface *src, SDL_Rect *srcrect, - SDL_Surface *dst, SDL_Rect *dstrect) +int +SDL_RLEAlphaBlit(SDL_Surface * src, SDL_Rect * srcrect, + SDL_Surface * dst, SDL_Rect * dstrect) { int x, y; int w = src->w; @@ -1112,84 +1124,88 @@ int SDL_RLEAlphaBlit(SDL_Surface *src, SDL_Rect *srcrect, SDL_PixelFormat *df = dst->format; /* Lock the destination if necessary */ - if ( SDL_MUSTLOCK(dst) ) { - if ( SDL_LockSurface(dst) < 0 ) { - return -1; - } + if (SDL_MUSTLOCK(dst)) { + if (SDL_LockSurface(dst) < 0) { + return -1; + } } x = dstrect->x; y = dstrect->y; - dstbuf = (Uint8 *)dst->pixels - + y * dst->pitch + x * df->BytesPerPixel; - srcbuf = (Uint8 *)src->map->sw_data->aux_data + sizeof(RLEDestFormat); + dstbuf = (Uint8 *) dst->pixels + y * dst->pitch + x * df->BytesPerPixel; + srcbuf = (Uint8 *) src->map->sw_data->aux_data + sizeof(RLEDestFormat); { - /* skip lines at the top if necessary */ - int vskip = srcrect->y; - if(vskip) { - int ofs; - if(df->BytesPerPixel == 2) { - /* the 16/32 interleaved format */ - do { - /* skip opaque line */ - ofs = 0; - do { - int run; - ofs += srcbuf[0]; - run = srcbuf[1]; - srcbuf += 2; - if(run) { - srcbuf += 2 * run; - ofs += run; - } else if(!ofs) - goto done; - } while(ofs < w); - - /* skip padding */ - srcbuf += (uintptr_t)srcbuf & 2; - - /* skip translucent line */ - ofs = 0; - do { - int run; - ofs += ((Uint16 *)srcbuf)[0]; - run = ((Uint16 *)srcbuf)[1]; - srcbuf += 4 * (run + 1); - ofs += run; - } while(ofs < w); - } while(--vskip); - } else { - /* the 32/32 interleaved format */ - vskip <<= 1; /* opaque and translucent have same format */ - do { - ofs = 0; - do { - int run; - ofs += ((Uint16 *)srcbuf)[0]; - run = ((Uint16 *)srcbuf)[1]; - srcbuf += 4; - if(run) { - srcbuf += 4 * run; - ofs += run; - } else if(!ofs) - goto done; - } while(ofs < w); - } while(--vskip); - } - } + /* skip lines at the top if necessary */ + int vskip = srcrect->y; + if (vskip) { + int ofs; + if (df->BytesPerPixel == 2) { + /* the 16/32 interleaved format */ + do { + /* skip opaque line */ + ofs = 0; + do { + int run; + ofs += srcbuf[0]; + run = srcbuf[1]; + srcbuf += 2; + if (run) { + srcbuf += 2 * run; + ofs += run; + } else if (!ofs) + goto done; + } + while (ofs < w); + + /* skip padding */ + srcbuf += (uintptr_t) srcbuf & 2; + + /* skip translucent line */ + ofs = 0; + do { + int run; + ofs += ((Uint16 *) srcbuf)[0]; + run = ((Uint16 *) srcbuf)[1]; + srcbuf += 4 * (run + 1); + ofs += run; + } + while (ofs < w); + } + while (--vskip); + } else { + /* the 32/32 interleaved format */ + vskip <<= 1; /* opaque and translucent have same format */ + do { + ofs = 0; + do { + int run; + ofs += ((Uint16 *) srcbuf)[0]; + run = ((Uint16 *) srcbuf)[1]; + srcbuf += 4; + if (run) { + srcbuf += 4 * run; + ofs += run; + } else if (!ofs) + goto done; + } + while (ofs < w); + } + while (--vskip); + } + } } /* if left or right edge clipping needed, call clip blit */ - if(srcrect->x || srcrect->w != src->w) { - RLEAlphaClipBlit(w, srcbuf, dst, dstbuf, srcrect); + if (srcrect->x || srcrect->w != src->w) { + RLEAlphaClipBlit(w, srcbuf, dst, dstbuf, srcrect); } else { - /* - * non-clipped blitter. Ptype is the destination pixel type, - * Ctype the translucent count type, and do_blend the - * macro to blend one pixel. - */ + /* + * non-clipped blitter. Ptype is the destination pixel type, + * Ctype the translucent count type, and do_blend the + * macro to blend one pixel. + */ #define RLEALPHABLIT(Ptype, Ctype, do_blend) \ do { \ int linecount = srcrect->h; \ @@ -1235,24 +1251,24 @@ int SDL_RLEAlphaBlit(SDL_Surface *src, SDL_Rect *srcrect, } while(--linecount); \ } while(0) - switch(df->BytesPerPixel) { - case 2: - if(df->Gmask == 0x07e0 || df->Rmask == 0x07e0 - || df->Bmask == 0x07e0) - RLEALPHABLIT(Uint16, Uint8, BLIT_TRANSL_565); - else - RLEALPHABLIT(Uint16, Uint8, BLIT_TRANSL_555); - break; - case 4: - RLEALPHABLIT(Uint32, Uint16, BLIT_TRANSL_888); - break; - } + switch (df->BytesPerPixel) { + case 2: + if (df->Gmask == 0x07e0 || df->Rmask == 0x07e0 + || df->Bmask == 0x07e0) + RLEALPHABLIT(Uint16, Uint8, BLIT_TRANSL_565); + else + RLEALPHABLIT(Uint16, Uint8, BLIT_TRANSL_555); + break; + case 4: + RLEALPHABLIT(Uint32, Uint16, BLIT_TRANSL_888); + break; + } } - done: + done: /* Unlock the destination if necessary */ - if ( SDL_MUSTLOCK(dst) ) { - SDL_UnlockSurface(dst); + if (SDL_MUSTLOCK(dst)) { + SDL_UnlockSurface(dst); } return 0; } @@ -1268,34 +1284,36 @@ int SDL_RLEAlphaBlit(SDL_Surface *src, SDL_Rect *srcrect, */ /* encode 32bpp rgb + a into 16bpp rgb, losing alpha */ -static int copy_opaque_16(void *dst, Uint32 *src, int n, - SDL_PixelFormat *sfmt, SDL_PixelFormat *dfmt) +static int +copy_opaque_16(void *dst, Uint32 * src, int n, + SDL_PixelFormat * sfmt, SDL_PixelFormat * dfmt) { int i; Uint16 *d = dst; - for(i = 0; i < n; i++) { - unsigned r, g, b; - RGB_FROM_PIXEL(*src, sfmt, r, g, b); - PIXEL_FROM_RGB(*d, dfmt, r, g, b); - src++; - d++; + for (i = 0; i < n; i++) { + unsigned r, g, b; + RGB_FROM_PIXEL(*src, sfmt, r, g, b); + PIXEL_FROM_RGB(*d, dfmt, r, g, b); + src++; + d++; } return n * 2; } /* decode opaque pixels from 16bpp to 32bpp rgb + a */ -static int uncopy_opaque_16(Uint32 *dst, void *src, int n, - RLEDestFormat *sfmt, SDL_PixelFormat *dfmt) +static int +uncopy_opaque_16(Uint32 * dst, void *src, int n, + RLEDestFormat * sfmt, SDL_PixelFormat * dfmt) { int i; Uint16 *s = src; unsigned alpha = dfmt->Amask ? 255 : 0; - for(i = 0; i < n; i++) { - unsigned r, g, b; - RGB_FROM_PIXEL(*s, sfmt, r, g, b); - PIXEL_FROM_RGBA(*dst, dfmt, r, g, b, alpha); - s++; - dst++; + for (i = 0; i < n; i++) { + unsigned r, g, b; + RGB_FROM_PIXEL(*s, sfmt, r, g, b); + PIXEL_FROM_RGBA(*dst, dfmt, r, g, b, alpha); + s++; + dst++; } return n * 2; } @@ -1303,89 +1321,94 @@ static int uncopy_opaque_16(Uint32 *dst, void *src, int n, /* encode 32bpp rgb + a into 32bpp G0RAB format for blitting into 565 */ -static int copy_transl_565(void *dst, Uint32 *src, int n, - SDL_PixelFormat *sfmt, SDL_PixelFormat *dfmt) +static int +copy_transl_565(void *dst, Uint32 * src, int n, + SDL_PixelFormat * sfmt, SDL_PixelFormat * dfmt) { int i; Uint32 *d = dst; - for(i = 0; i < n; i++) { - unsigned r, g, b, a; - Uint16 pix; - RGBA_FROM_8888(*src, sfmt, r, g, b, a); - PIXEL_FROM_RGB(pix, dfmt, r, g, b); - *d = ((pix & 0x7e0) << 16) | (pix & 0xf81f) | ((a << 2) & 0x7e0); - src++; - d++; + for (i = 0; i < n; i++) { + unsigned r, g, b, a; + Uint16 pix; + RGBA_FROM_8888(*src, sfmt, r, g, b, a); + PIXEL_FROM_RGB(pix, dfmt, r, g, b); + *d = ((pix & 0x7e0) << 16) | (pix & 0xf81f) | ((a << 2) & 0x7e0); + src++; + d++; } return n * 4; } /* encode 32bpp rgb + a into 32bpp G0RAB format for blitting into 555 */ -static int copy_transl_555(void *dst, Uint32 *src, int n, - SDL_PixelFormat *sfmt, SDL_PixelFormat *dfmt) +static int +copy_transl_555(void *dst, Uint32 * src, int n, + SDL_PixelFormat * sfmt, SDL_PixelFormat * dfmt) { int i; Uint32 *d = dst; - for(i = 0; i < n; i++) { - unsigned r, g, b, a; - Uint16 pix; - RGBA_FROM_8888(*src, sfmt, r, g, b, a); - PIXEL_FROM_RGB(pix, dfmt, r, g, b); - *d = ((pix & 0x3e0) << 16) | (pix & 0xfc1f) | ((a << 2) & 0x3e0); - src++; - d++; + for (i = 0; i < n; i++) { + unsigned r, g, b, a; + Uint16 pix; + RGBA_FROM_8888(*src, sfmt, r, g, b, a); + PIXEL_FROM_RGB(pix, dfmt, r, g, b); + *d = ((pix & 0x3e0) << 16) | (pix & 0xfc1f) | ((a << 2) & 0x3e0); + src++; + d++; } return n * 4; } /* decode translucent pixels from 32bpp GORAB to 32bpp rgb + a */ -static int uncopy_transl_16(Uint32 *dst, void *src, int n, - RLEDestFormat *sfmt, SDL_PixelFormat *dfmt) +static int +uncopy_transl_16(Uint32 * dst, void *src, int n, + RLEDestFormat * sfmt, SDL_PixelFormat * dfmt) { int i; Uint32 *s = src; - for(i = 0; i < n; i++) { - unsigned r, g, b, a; - Uint32 pix = *s++; - a = (pix & 0x3e0) >> 2; - pix = (pix & ~0x3e0) | pix >> 16; - RGB_FROM_PIXEL(pix, sfmt, r, g, b); - PIXEL_FROM_RGBA(*dst, dfmt, r, g, b, a); - dst++; + for (i = 0; i < n; i++) { + unsigned r, g, b, a; + Uint32 pix = *s++; + a = (pix & 0x3e0) >> 2; + pix = (pix & ~0x3e0) | pix >> 16; + RGB_FROM_PIXEL(pix, sfmt, r, g, b); + PIXEL_FROM_RGBA(*dst, dfmt, r, g, b, a); + dst++; } return n * 4; } /* encode 32bpp rgba into 32bpp rgba, keeping alpha (dual purpose) */ -static int copy_32(void *dst, Uint32 *src, int n, - SDL_PixelFormat *sfmt, SDL_PixelFormat *dfmt) +static int +copy_32(void *dst, Uint32 * src, int n, + SDL_PixelFormat * sfmt, SDL_PixelFormat * dfmt) { int i; Uint32 *d = dst; - for(i = 0; i < n; i++) { - unsigned r, g, b, a; - Uint32 pixel; - RGBA_FROM_8888(*src, sfmt, r, g, b, a); - PIXEL_FROM_RGB(pixel, dfmt, r, g, b); - *d++ = pixel | a << 24; - src++; + for (i = 0; i < n; i++) { + unsigned r, g, b, a; + Uint32 pixel; + RGBA_FROM_8888(*src, sfmt, r, g, b, a); + PIXEL_FROM_RGB(pixel, dfmt, r, g, b); + *d++ = pixel | a << 24; + src++; } return n * 4; } /* decode 32bpp rgba into 32bpp rgba, keeping alpha (dual purpose) */ -static int uncopy_32(Uint32 *dst, void *src, int n, - RLEDestFormat *sfmt, SDL_PixelFormat *dfmt) +static int +uncopy_32(Uint32 * dst, void *src, int n, + RLEDestFormat * sfmt, SDL_PixelFormat * dfmt) { int i; Uint32 *s = src; - for(i = 0; i < n; i++) { - unsigned r, g, b, a; - Uint32 pixel = *s++; - RGB_FROM_PIXEL(pixel, sfmt, r, g, b); - a = pixel >> 24; - PIXEL_FROM_RGBA(*dst, dfmt, r, g, b, a); - dst++; + for (i = 0; i < n; i++) { + unsigned r, g, b, a; + Uint32 pixel = *s++; + RGB_FROM_PIXEL(pixel, sfmt, r, g, b); + a = pixel >> 24; + PIXEL_FROM_RGBA(*dst, dfmt, r, g, b, a); + dst++; } return n * 4; } @@ -1396,7 +1419,8 @@ static int uncopy_32(Uint32 *dst, void *src, int n, ((unsigned)((((pixel) & fmt->Amask) >> fmt->Ashift) - 1U) < 254U) /* convert surface to be quickly alpha-blittable onto dest, if possible */ -static int RLEAlphaSurface(SDL_Surface *surface) +static int +RLEAlphaSurface(SDL_Surface * surface) { SDL_Surface *dest; SDL_PixelFormat *df; @@ -1405,97 +1429,97 @@ static int RLEAlphaSurface(SDL_Surface *surface) int max_transl_run = 65535; unsigned masksum; Uint8 *rlebuf, *dst; - int (*copy_opaque)(void *, Uint32 *, int, - SDL_PixelFormat *, SDL_PixelFormat *); - int (*copy_transl)(void *, Uint32 *, int, - SDL_PixelFormat *, SDL_PixelFormat *); + int (*copy_opaque) (void *, Uint32 *, int, + SDL_PixelFormat *, SDL_PixelFormat *); + int (*copy_transl) (void *, Uint32 *, int, + SDL_PixelFormat *, SDL_PixelFormat *); dest = surface->map->dst; - if(!dest) - return -1; + if (!dest) + return -1; df = dest->format; - if(surface->format->BitsPerPixel != 32) - return -1; /* only 32bpp source supported */ + if (surface->format->BitsPerPixel != 32) + return -1; /* only 32bpp source supported */ /* find out whether the destination is one we support, and determine the max size of the encoded result */ masksum = df->Rmask | df->Gmask | df->Bmask; - switch(df->BytesPerPixel) { + switch (df->BytesPerPixel) { case 2: - /* 16bpp: only support 565 and 555 formats */ - switch(masksum) { - case 0xffff: - if(df->Gmask == 0x07e0 - || df->Rmask == 0x07e0 || df->Bmask == 0x07e0) { - copy_opaque = copy_opaque_16; - copy_transl = copy_transl_565; - } else - return -1; - break; - case 0x7fff: - if(df->Gmask == 0x03e0 - || df->Rmask == 0x03e0 || df->Bmask == 0x03e0) { - copy_opaque = copy_opaque_16; - copy_transl = copy_transl_555; - } else - return -1; - break; - default: - return -1; - } - max_opaque_run = 255; /* runs stored as bytes */ - - /* worst case is alternating opaque and translucent pixels, - with room for alignment padding between lines */ - maxsize = surface->h * (2 + (4 + 2) * (surface->w + 1)) + 2; - break; + /* 16bpp: only support 565 and 555 formats */ + switch (masksum) { + case 0xffff: + if (df->Gmask == 0x07e0 + || df->Rmask == 0x07e0 || df->Bmask == 0x07e0) { + copy_opaque = copy_opaque_16; + copy_transl = copy_transl_565; + } else + return -1; + break; + case 0x7fff: + if (df->Gmask == 0x03e0 + || df->Rmask == 0x03e0 || df->Bmask == 0x03e0) { + copy_opaque = copy_opaque_16; + copy_transl = copy_transl_555; + } else + return -1; + break; + default: + return -1; + } + max_opaque_run = 255; /* runs stored as bytes */ + + /* worst case is alternating opaque and translucent pixels, + with room for alignment padding between lines */ + maxsize = surface->h * (2 + (4 + 2) * (surface->w + 1)) + 2; + break; case 4: - if(masksum != 0x00ffffff) - return -1; /* requires unused high byte */ - copy_opaque = copy_32; - copy_transl = copy_32; - max_opaque_run = 255; /* runs stored as short ints */ - - /* worst case is alternating opaque and translucent pixels */ - maxsize = surface->h * 2 * 4 * (surface->w + 1) + 4; - break; + if (masksum != 0x00ffffff) + return -1; /* requires unused high byte */ + copy_opaque = copy_32; + copy_transl = copy_32; + max_opaque_run = 255; /* runs stored as short ints */ + + /* worst case is alternating opaque and translucent pixels */ + maxsize = surface->h * 2 * 4 * (surface->w + 1) + 4; + break; default: - return -1; /* anything else unsupported right now */ + return -1; /* anything else unsupported right now */ } maxsize += sizeof(RLEDestFormat); - rlebuf = (Uint8 *)SDL_malloc(maxsize); - if(!rlebuf) { - SDL_OutOfMemory(); - return -1; + rlebuf = (Uint8 *) SDL_malloc(maxsize); + if (!rlebuf) { + SDL_OutOfMemory(); + return -1; } { - /* save the destination format so we can undo the encoding later */ - RLEDestFormat *r = (RLEDestFormat *)rlebuf; - r->BytesPerPixel = df->BytesPerPixel; - r->Rloss = df->Rloss; - r->Gloss = df->Gloss; - r->Bloss = df->Bloss; - r->Rshift = df->Rshift; - r->Gshift = df->Gshift; - r->Bshift = df->Bshift; - r->Ashift = df->Ashift; - r->Rmask = df->Rmask; - r->Gmask = df->Gmask; - r->Bmask = df->Bmask; - r->Amask = df->Amask; + /* save the destination format so we can undo the encoding later */ + RLEDestFormat *r = (RLEDestFormat *) rlebuf; + r->BytesPerPixel = df->BytesPerPixel; + r->Rloss = df->Rloss; + r->Gloss = df->Gloss; + r->Bloss = df->Bloss; + r->Rshift = df->Rshift; + r->Gshift = df->Gshift; + r->Bshift = df->Bshift; + r->Ashift = df->Ashift; + r->Rmask = df->Rmask; + r->Gmask = df->Gmask; + r->Bmask = df->Bmask; + r->Amask = df->Amask; } dst = rlebuf + sizeof(RLEDestFormat); /* Do the actual encoding */ { - int x, y; - int h = surface->h, w = surface->w; - SDL_PixelFormat *sf = surface->format; - Uint32 *src = (Uint32 *)surface->pixels; - Uint8 *lastline = dst; /* end of last non-blank line */ + int x, y; + int h = surface->h, w = surface->w; + SDL_PixelFormat *sf = surface->format; + Uint32 *src = (Uint32 *) surface->pixels; + Uint8 *lastline = dst; /* end of last non-blank line */ - /* opaque counts are 8 or 16 bits, depending on target depth */ + /* opaque counts are 8 or 16 bits, depending on target depth */ #define ADD_OPAQUE_COUNTS(n, m) \ if(df->BytesPerPixel == 4) { \ ((Uint16 *)dst)[0] = n; \ @@ -1507,119 +1531,123 @@ static int RLEAlphaSurface(SDL_Surface *surface) dst += 2; \ } - /* translucent counts are always 16 bit */ + /* translucent counts are always 16 bit */ #define ADD_TRANSL_COUNTS(n, m) \ (((Uint16 *)dst)[0] = n, ((Uint16 *)dst)[1] = m, dst += 4) - for(y = 0; y < h; y++) { - int runstart, skipstart; - int blankline = 0; - /* First encode all opaque pixels of a scan line */ - x = 0; - do { - int run, skip, len; - skipstart = x; - while(x < w && !ISOPAQUE(src[x], sf)) - x++; - runstart = x; - while(x < w && ISOPAQUE(src[x], sf)) - x++; - skip = runstart - skipstart; - if(skip == w) - blankline = 1; - run = x - runstart; - while(skip > max_opaque_run) { - ADD_OPAQUE_COUNTS(max_opaque_run, 0); - skip -= max_opaque_run; - } - len = MIN(run, max_opaque_run); - ADD_OPAQUE_COUNTS(skip, len); - dst += copy_opaque(dst, src + runstart, len, sf, df); - runstart += len; - run -= len; - while(run) { - len = MIN(run, max_opaque_run); - ADD_OPAQUE_COUNTS(0, len); - dst += copy_opaque(dst, src + runstart, len, sf, df); - runstart += len; - run -= len; - } - } while(x < w); - - /* Make sure the next output address is 32-bit aligned */ - dst += (uintptr_t)dst & 2; - - /* Next, encode all translucent pixels of the same scan line */ - x = 0; - do { - int run, skip, len; - skipstart = x; - while(x < w && !ISTRANSL(src[x], sf)) - x++; - runstart = x; - while(x < w && ISTRANSL(src[x], sf)) - x++; - skip = runstart - skipstart; - blankline &= (skip == w); - run = x - runstart; - while(skip > max_transl_run) { - ADD_TRANSL_COUNTS(max_transl_run, 0); - skip -= max_transl_run; - } - len = MIN(run, max_transl_run); - ADD_TRANSL_COUNTS(skip, len); - dst += copy_transl(dst, src + runstart, len, sf, df); - runstart += len; - run -= len; - while(run) { - len = MIN(run, max_transl_run); - ADD_TRANSL_COUNTS(0, len); - dst += copy_transl(dst, src + runstart, len, sf, df); - runstart += len; - run -= len; - } - if(!blankline) - lastline = dst; - } while(x < w); - - src += surface->pitch >> 2; - } - dst = lastline; /* back up past trailing blank lines */ - ADD_OPAQUE_COUNTS(0, 0); + for (y = 0; y < h; y++) { + int runstart, skipstart; + int blankline = 0; + /* First encode all opaque pixels of a scan line */ + x = 0; + do { + int run, skip, len; + skipstart = x; + while (x < w && !ISOPAQUE(src[x], sf)) + x++; + runstart = x; + while (x < w && ISOPAQUE(src[x], sf)) + x++; + skip = runstart - skipstart; + if (skip == w) + blankline = 1; + run = x - runstart; + while (skip > max_opaque_run) { + ADD_OPAQUE_COUNTS(max_opaque_run, 0); + skip -= max_opaque_run; + } + len = MIN(run, max_opaque_run); + ADD_OPAQUE_COUNTS(skip, len); + dst += copy_opaque(dst, src + runstart, len, sf, df); + runstart += len; + run -= len; + while (run) { + len = MIN(run, max_opaque_run); + ADD_OPAQUE_COUNTS(0, len); + dst += copy_opaque(dst, src + runstart, len, sf, df); + runstart += len; + run -= len; + } + } + while (x < w); + + /* Make sure the next output address is 32-bit aligned */ + dst += (uintptr_t) dst & 2; + + /* Next, encode all translucent pixels of the same scan line */ + x = 0; + do { + int run, skip, len; + skipstart = x; + while (x < w && !ISTRANSL(src[x], sf)) + x++; + runstart = x; + while (x < w && ISTRANSL(src[x], sf)) + x++; + skip = runstart - skipstart; + blankline &= (skip == w); + run = x - runstart; + while (skip > max_transl_run) { + ADD_TRANSL_COUNTS(max_transl_run, 0); + skip -= max_transl_run; + } + len = MIN(run, max_transl_run); + ADD_TRANSL_COUNTS(skip, len); + dst += copy_transl(dst, src + runstart, len, sf, df); + runstart += len; + run -= len; + while (run) { + len = MIN(run, max_transl_run); + ADD_TRANSL_COUNTS(0, len); + dst += copy_transl(dst, src + runstart, len, sf, df); + runstart += len; + run -= len; + } + if (!blankline) + lastline = dst; + } + while (x < w); + + src += surface->pitch >> 2; + } + dst = lastline; /* back up past trailing blank lines */ + ADD_OPAQUE_COUNTS(0, 0); } #undef ADD_OPAQUE_COUNTS #undef ADD_TRANSL_COUNTS /* Now that we have it encoded, release the original pixels */ - if((surface->flags & SDL_PREALLOC) != SDL_PREALLOC - && (surface->flags & SDL_HWSURFACE) != SDL_HWSURFACE) { - SDL_free( surface->pixels ); - surface->pixels = NULL; + if (!(surface->flags & SDL_PREALLOC) && !(surface->flags & SDL_HWSURFACE)) { + SDL_free(surface->pixels); + surface->pixels = NULL; } /* realloc the buffer to release unused memory */ { - Uint8 *p = SDL_realloc(rlebuf, dst - rlebuf); - if(!p) - p = rlebuf; - surface->map->sw_data->aux_data = p; + Uint8 *p = SDL_realloc(rlebuf, dst - rlebuf); + if (!p) + p = rlebuf; + surface->map->sw_data->aux_data = p; } return 0; } -static Uint32 getpix_8(Uint8 *srcbuf) +static Uint32 +getpix_8(Uint8 * srcbuf) { return *srcbuf; } -static Uint32 getpix_16(Uint8 *srcbuf) +static Uint32 +getpix_16(Uint8 * srcbuf) { - return *(Uint16 *)srcbuf; + return *(Uint16 *) srcbuf; } -static Uint32 getpix_24(Uint8 *srcbuf) +static Uint32 +getpix_24(Uint8 * srcbuf) { #if SDL_BYTEORDER == SDL_LIL_ENDIAN return srcbuf[0] + (srcbuf[1] << 8) + (srcbuf[2] << 16); @@ -1628,68 +1656,70 @@ static Uint32 getpix_24(Uint8 *srcbuf) #endif } -static Uint32 getpix_32(Uint8 *srcbuf) +static Uint32 +getpix_32(Uint8 * srcbuf) { - return *(Uint32 *)srcbuf; + return *(Uint32 *) srcbuf; } -typedef Uint32 (*getpix_func)(Uint8 *); +typedef Uint32(*getpix_func) (Uint8 *); static getpix_func getpixes[4] = { getpix_8, getpix_16, getpix_24, getpix_32 }; -static int RLEColorkeySurface(SDL_Surface *surface) +static int +RLEColorkeySurface(SDL_Surface * surface) { - Uint8 *rlebuf, *dst; - int maxn; - int y; - Uint8 *srcbuf, *curbuf, *lastline; - int maxsize = 0; - int skip, run; - int bpp = surface->format->BytesPerPixel; - getpix_func getpix; - Uint32 ckey, rgbmask; - int w, h; - - /* calculate the worst case size for the compressed surface */ - switch(bpp) { - case 1: - /* worst case is alternating opaque and transparent pixels, - starting with an opaque pixel */ - maxsize = surface->h * 3 * (surface->w / 2 + 1) + 2; - break; - case 2: - case 3: - /* worst case is solid runs, at most 255 pixels wide */ - maxsize = surface->h * (2 * (surface->w / 255 + 1) - + surface->w * bpp) + 2; - break; - case 4: - /* worst case is solid runs, at most 65535 pixels wide */ - maxsize = surface->h * (4 * (surface->w / 65535 + 1) - + surface->w * 4) + 4; - break; - } + Uint8 *rlebuf, *dst; + int maxn; + int y; + Uint8 *srcbuf, *curbuf, *lastline; + int maxsize = 0; + int skip, run; + int bpp = surface->format->BytesPerPixel; + getpix_func getpix; + Uint32 ckey, rgbmask; + int w, h; + + /* calculate the worst case size for the compressed surface */ + switch (bpp) { + case 1: + /* worst case is alternating opaque and transparent pixels, + starting with an opaque pixel */ + maxsize = surface->h * 3 * (surface->w / 2 + 1) + 2; + break; + case 2: + case 3: + /* worst case is solid runs, at most 255 pixels wide */ + maxsize = surface->h * (2 * (surface->w / 255 + 1) + + surface->w * bpp) + 2; + break; + case 4: + /* worst case is solid runs, at most 65535 pixels wide */ + maxsize = surface->h * (4 * (surface->w / 65535 + 1) + + surface->w * 4) + 4; + break; + } - rlebuf = (Uint8 *)SDL_malloc(maxsize); - if ( rlebuf == NULL ) { - SDL_OutOfMemory(); - return(-1); - } + rlebuf = (Uint8 *) SDL_malloc(maxsize); + if (rlebuf == NULL) { + SDL_OutOfMemory(); + return (-1); + } - /* Set up the conversion */ - srcbuf = (Uint8 *)surface->pixels; - curbuf = srcbuf; - maxn = bpp == 4 ? 65535 : 255; - skip = run = 0; - dst = rlebuf; - rgbmask = ~surface->format->Amask; - ckey = surface->format->colorkey & rgbmask; - lastline = dst; - getpix = getpixes[bpp - 1]; - w = surface->w; - h = surface->h; + /* Set up the conversion */ + srcbuf = (Uint8 *) surface->pixels; + curbuf = srcbuf; + maxn = bpp == 4 ? 65535 : 255; + skip = run = 0; + dst = rlebuf; + rgbmask = ~surface->format->Amask; + ckey = surface->format->colorkey & rgbmask; + lastline = dst; + getpix = getpixes[bpp - 1]; + w = surface->w; + h = surface->h; #define ADD_COUNTS(n, m) \ if(bpp == 4) { \ @@ -1702,118 +1732,119 @@ static int RLEColorkeySurface(SDL_Surface *surface) dst += 2; \ } - for(y = 0; y < h; y++) { - int x = 0; - int blankline = 0; - do { - int run, skip, len; - int runstart; - int skipstart = x; - - /* find run of transparent, then opaque pixels */ - while(x < w && (getpix(srcbuf + x * bpp) & rgbmask) == ckey) - x++; - runstart = x; - while(x < w && (getpix(srcbuf + x * bpp) & rgbmask) != ckey) - x++; - skip = runstart - skipstart; - if(skip == w) - blankline = 1; - run = x - runstart; - - /* encode segment */ - while(skip > maxn) { - ADD_COUNTS(maxn, 0); - skip -= maxn; - } - len = MIN(run, maxn); - ADD_COUNTS(skip, len); - SDL_memcpy(dst, srcbuf + runstart * bpp, len * bpp); - dst += len * bpp; - run -= len; - runstart += len; - while(run) { - len = MIN(run, maxn); - ADD_COUNTS(0, len); - SDL_memcpy(dst, srcbuf + runstart * bpp, len * bpp); - dst += len * bpp; - runstart += len; - run -= len; - } - if(!blankline) - lastline = dst; - } while(x < w); - - srcbuf += surface->pitch; - } - dst = lastline; /* back up bast trailing blank lines */ - ADD_COUNTS(0, 0); + for (y = 0; y < h; y++) { + int x = 0; + int blankline = 0; + do { + int run, skip, len; + int runstart; + int skipstart = x; + + /* find run of transparent, then opaque pixels */ + while (x < w && (getpix(srcbuf + x * bpp) & rgbmask) == ckey) + x++; + runstart = x; + while (x < w && (getpix(srcbuf + x * bpp) & rgbmask) != ckey) + x++; + skip = runstart - skipstart; + if (skip == w) + blankline = 1; + run = x - runstart; + + /* encode segment */ + while (skip > maxn) { + ADD_COUNTS(maxn, 0); + skip -= maxn; + } + len = MIN(run, maxn); + ADD_COUNTS(skip, len); + SDL_memcpy(dst, srcbuf + runstart * bpp, len * bpp); + dst += len * bpp; + run -= len; + runstart += len; + while (run) { + len = MIN(run, maxn); + ADD_COUNTS(0, len); + SDL_memcpy(dst, srcbuf + runstart * bpp, len * bpp); + dst += len * bpp; + runstart += len; + run -= len; + } + if (!blankline) + lastline = dst; + } + while (x < w); + + srcbuf += surface->pitch; + } + dst = lastline; /* back up bast trailing blank lines */ + ADD_COUNTS(0, 0); #undef ADD_COUNTS - /* Now that we have it encoded, release the original pixels */ - if((surface->flags & SDL_PREALLOC) != SDL_PREALLOC - && (surface->flags & SDL_HWSURFACE) != SDL_HWSURFACE) { - SDL_free( surface->pixels ); - surface->pixels = NULL; - } + /* Now that we have it encoded, release the original pixels */ + if (!(surface->flags & SDL_PREALLOC) && !(surface->flags & SDL_HWSURFACE)) { + SDL_free(surface->pixels); + surface->pixels = NULL; + } - /* realloc the buffer to release unused memory */ - { - /* If realloc returns NULL, the original block is left intact */ - Uint8 *p = SDL_realloc(rlebuf, dst - rlebuf); - if(!p) - p = rlebuf; - surface->map->sw_data->aux_data = p; - } + /* realloc the buffer to release unused memory */ + { + /* If realloc returns NULL, the original block is left intact */ + Uint8 *p = SDL_realloc(rlebuf, dst - rlebuf); + if (!p) + p = rlebuf; + surface->map->sw_data->aux_data = p; + } - return(0); + return (0); } -int SDL_RLESurface(SDL_Surface *surface) +int +SDL_RLESurface(SDL_Surface * surface) { - int retcode; + int retcode; - /* Clear any previous RLE conversion */ - if ( (surface->flags & SDL_RLEACCEL) == SDL_RLEACCEL ) { - SDL_UnRLESurface(surface, 1); - } + /* Clear any previous RLE conversion */ + if ((surface->flags & SDL_RLEACCEL) == SDL_RLEACCEL) { + SDL_UnRLESurface(surface, 1); + } - /* We don't support RLE encoding of bitmaps */ - if ( surface->format->BitsPerPixel < 8 ) { - return(-1); - } + /* We don't support RLE encoding of bitmaps */ + if (surface->format->BitsPerPixel < 8) { + return (-1); + } - /* Lock the surface if it's in hardware */ - if ( SDL_MUSTLOCK(surface) ) { - if ( SDL_LockSurface(surface) < 0 ) { - return(-1); - } - } + /* Lock the surface if it's in hardware */ + if (SDL_MUSTLOCK(surface)) { + if (SDL_LockSurface(surface) < 0) { + return (-1); + } + } - /* Encode */ - if((surface->flags & SDL_SRCCOLORKEY) == SDL_SRCCOLORKEY) { - retcode = RLEColorkeySurface(surface); - } else { - if((surface->flags & SDL_SRCALPHA) == SDL_SRCALPHA - && surface->format->Amask != 0) - retcode = RLEAlphaSurface(surface); - else - retcode = -1; /* no RLE for per-surface alpha sans ckey */ - } + /* Encode */ + if ((surface->flags & SDL_SRCCOLORKEY) == SDL_SRCCOLORKEY) { + retcode = RLEColorkeySurface(surface); + } else { + if ((surface->flags & SDL_SRCALPHA) == SDL_SRCALPHA + && surface->format->Amask != 0) + retcode = RLEAlphaSurface(surface); + else + retcode = -1; /* no RLE for per-surface alpha sans ckey */ + } - /* Unlock the surface if it's in hardware */ - if ( SDL_MUSTLOCK(surface) ) { - SDL_UnlockSurface(surface); - } + /* Unlock the surface if it's in hardware */ + if (SDL_MUSTLOCK(surface)) { + SDL_UnlockSurface(surface); + } - if(retcode < 0) - return -1; + if (retcode < 0) + return -1; - /* The surface is now accelerated */ - surface->flags |= SDL_RLEACCEL; + /* The surface is now accelerated */ + surface->flags |= SDL_RLEACCEL; - return(0); + return (0); } /* @@ -1822,122 +1853,126 @@ int SDL_RLESurface(SDL_Surface *surface) * completely transparent pixels will be lost, and colour and alpha depth * may have been reduced (when encoding for 16bpp targets). */ -static SDL_bool UnRLEAlpha(SDL_Surface *surface) +static SDL_bool +UnRLEAlpha(SDL_Surface * surface) { Uint8 *srcbuf; Uint32 *dst; SDL_PixelFormat *sf = surface->format; RLEDestFormat *df = surface->map->sw_data->aux_data; - int (*uncopy_opaque)(Uint32 *, void *, int, - RLEDestFormat *, SDL_PixelFormat *); - int (*uncopy_transl)(Uint32 *, void *, int, - RLEDestFormat *, SDL_PixelFormat *); + int (*uncopy_opaque) (Uint32 *, void *, int, + RLEDestFormat *, SDL_PixelFormat *); + int (*uncopy_transl) (Uint32 *, void *, int, + RLEDestFormat *, SDL_PixelFormat *); int w = surface->w; int bpp = df->BytesPerPixel; - if(bpp == 2) { - uncopy_opaque = uncopy_opaque_16; - uncopy_transl = uncopy_transl_16; + if (bpp == 2) { + uncopy_opaque = uncopy_opaque_16; + uncopy_transl = uncopy_transl_16; } else { - uncopy_opaque = uncopy_transl = uncopy_32; + uncopy_opaque = uncopy_transl = uncopy_32; } surface->pixels = SDL_malloc(surface->h * surface->pitch); - if ( !surface->pixels ) { - return(SDL_FALSE); + if (!surface->pixels) { + return (SDL_FALSE); } /* fill background with transparent pixels */ SDL_memset(surface->pixels, 0, surface->h * surface->pitch); dst = surface->pixels; - srcbuf = (Uint8 *)(df + 1); - for(;;) { - /* copy opaque pixels */ - int ofs = 0; - do { - unsigned run; - if(bpp == 2) { - ofs += srcbuf[0]; - run = srcbuf[1]; - srcbuf += 2; - } else { - ofs += ((Uint16 *)srcbuf)[0]; - run = ((Uint16 *)srcbuf)[1]; - srcbuf += 4; - } - if(run) { - srcbuf += uncopy_opaque(dst + ofs, srcbuf, run, df, sf); - ofs += run; - } else if(!ofs) - return(SDL_TRUE); - } while(ofs < w); - - /* skip padding if needed */ - if(bpp == 2) - srcbuf += (uintptr_t)srcbuf & 2; - - /* copy translucent pixels */ - ofs = 0; - do { - unsigned run; - ofs += ((Uint16 *)srcbuf)[0]; - run = ((Uint16 *)srcbuf)[1]; - srcbuf += 4; - if(run) { - srcbuf += uncopy_transl(dst + ofs, srcbuf, run, df, sf); - ofs += run; - } - } while(ofs < w); - dst += surface->pitch >> 2; + srcbuf = (Uint8 *) (df + 1); + for (;;) { + /* copy opaque pixels */ + int ofs = 0; + do { + unsigned run; + if (bpp == 2) { + ofs += srcbuf[0]; + run = srcbuf[1]; + srcbuf += 2; + } else { + ofs += ((Uint16 *) srcbuf)[0]; + run = ((Uint16 *) srcbuf)[1]; + srcbuf += 4; + } + if (run) { + srcbuf += uncopy_opaque(dst + ofs, srcbuf, run, df, sf); + ofs += run; + } else if (!ofs) + return (SDL_TRUE); + } + while (ofs < w); + + /* skip padding if needed */ + if (bpp == 2) + srcbuf += (uintptr_t) srcbuf & 2; + + /* copy translucent pixels */ + ofs = 0; + do { + unsigned run; + ofs += ((Uint16 *) srcbuf)[0]; + run = ((Uint16 *) srcbuf)[1]; + srcbuf += 4; + if (run) { + srcbuf += uncopy_transl(dst + ofs, srcbuf, run, df, sf); + ofs += run; + } + } + while (ofs < w); + dst += surface->pitch >> 2; } /* Make the compiler happy */ - return(SDL_TRUE); + return (SDL_TRUE); } -void SDL_UnRLESurface(SDL_Surface *surface, int recode) +void +SDL_UnRLESurface(SDL_Surface * surface, int recode) { - if ( (surface->flags & SDL_RLEACCEL) == SDL_RLEACCEL ) { - surface->flags &= ~SDL_RLEACCEL; - - if(recode && (surface->flags & SDL_PREALLOC) != SDL_PREALLOC - && (surface->flags & SDL_HWSURFACE) != SDL_HWSURFACE) { - if((surface->flags & SDL_SRCCOLORKEY) == SDL_SRCCOLORKEY) { - SDL_Rect full; - unsigned alpha_flag; - - /* re-create the original surface */ - surface->pixels = SDL_malloc(surface->h * surface->pitch); - if ( !surface->pixels ) { - /* Oh crap... */ - surface->flags |= SDL_RLEACCEL; - return; - } - - /* fill it with the background colour */ - SDL_FillRect(surface, NULL, surface->format->colorkey); - - /* now render the encoded surface */ - full.x = full.y = 0; - full.w = surface->w; - full.h = surface->h; - alpha_flag = surface->flags & SDL_SRCALPHA; - surface->flags &= ~SDL_SRCALPHA; /* opaque blit */ - SDL_RLEBlit(surface, &full, surface, &full); - surface->flags |= alpha_flag; - } else { - if ( !UnRLEAlpha(surface) ) { - /* Oh crap... */ - surface->flags |= SDL_RLEACCEL; - return; - } - } - } - - if ( surface->map && surface->map->sw_data->aux_data ) { - SDL_free(surface->map->sw_data->aux_data); - surface->map->sw_data->aux_data = NULL; - } + if ((surface->flags & SDL_RLEACCEL) == SDL_RLEACCEL) { + surface->flags &= ~SDL_RLEACCEL; + + if (recode && !(surface->flags & SDL_PREALLOC) + && !(surface->flags & SDL_HWSURFACE)) { + if ((surface->flags & SDL_SRCCOLORKEY) == SDL_SRCCOLORKEY) { + SDL_Rect full; + unsigned alpha_flag; + + /* re-create the original surface */ + surface->pixels = SDL_malloc(surface->h * surface->pitch); + if (!surface->pixels) { + /* Oh crap... */ + surface->flags |= SDL_RLEACCEL; + return; + } + + /* fill it with the background colour */ + SDL_FillRect(surface, NULL, surface->format->colorkey); + + /* now render the encoded surface */ + full.x = full.y = 0; + full.w = surface->w; + full.h = surface->h; + alpha_flag = surface->flags & SDL_SRCALPHA; + surface->flags &= ~SDL_SRCALPHA; /* opaque blit */ + SDL_RLEBlit(surface, &full, surface, &full); + surface->flags |= alpha_flag; + } else { + if (!UnRLEAlpha(surface)) { + /* Oh crap... */ + surface->flags |= SDL_RLEACCEL; + return; + } + } + } + + if (surface->map && surface->map->sw_data->aux_data) { + SDL_free(surface->map->sw_data->aux_data); + surface->map->sw_data->aux_data = NULL; + } } } - +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/SDL_RLEaccel_c.h b/src/video/SDL_RLEaccel_c.h index ba9d35d3f..702395b83 100644 --- a/src/video/SDL_RLEaccel_c.h +++ b/src/video/SDL_RLEaccel_c.h @@ -23,9 +23,10 @@ /* Useful functions and variables from SDL_RLEaccel.c */ -extern int SDL_RLESurface(SDL_Surface *surface); -extern int SDL_RLEBlit(SDL_Surface *src, SDL_Rect *srcrect, - SDL_Surface *dst, SDL_Rect *dstrect); -extern int SDL_RLEAlphaBlit(SDL_Surface *src, SDL_Rect *srcrect, - SDL_Surface *dst, SDL_Rect *dstrect); -extern void SDL_UnRLESurface(SDL_Surface *surface, int recode); +extern int SDL_RLESurface(SDL_Surface * surface); +extern int SDL_RLEBlit(SDL_Surface * src, SDL_Rect * srcrect, + SDL_Surface * dst, SDL_Rect * dstrect); +extern int SDL_RLEAlphaBlit(SDL_Surface * src, SDL_Rect * srcrect, + SDL_Surface * dst, SDL_Rect * dstrect); +extern void SDL_UnRLESurface(SDL_Surface * surface, int recode); +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/SDL_blit.c b/src/video/SDL_blit.c index d3fb7783e..b1bac06a5 100644 --- a/src/video/SDL_blit.c +++ b/src/video/SDL_blit.c @@ -37,316 +37,258 @@ #endif /* The general purpose software blit routine */ -static int SDL_SoftBlit(SDL_Surface *src, SDL_Rect *srcrect, - SDL_Surface *dst, SDL_Rect *dstrect) +static int +SDL_SoftBlit(SDL_Surface * src, SDL_Rect * srcrect, + SDL_Surface * dst, SDL_Rect * dstrect) { - int okay; - int src_locked; - int dst_locked; - - /* Everything is okay at the beginning... */ - okay = 1; - - /* Lock the destination if it's in hardware */ - dst_locked = 0; - if ( SDL_MUSTLOCK(dst) ) { - if ( SDL_LockSurface(dst) < 0 ) { - okay = 0; - } else { - dst_locked = 1; - } - } - /* Lock the source if it's in hardware */ - src_locked = 0; - if ( SDL_MUSTLOCK(src) ) { - if ( SDL_LockSurface(src) < 0 ) { - okay = 0; - } else { - src_locked = 1; - } - } - - /* Set up source and destination buffer pointers, and BLIT! */ - if ( okay && srcrect->w && srcrect->h ) { - SDL_BlitInfo info; - SDL_loblit RunBlit; - - /* Set up the blit information */ - info.s_pixels = (Uint8 *)src->pixels + - (Uint16)srcrect->y*src->pitch + - (Uint16)srcrect->x*src->format->BytesPerPixel; - info.s_width = srcrect->w; - info.s_height = srcrect->h; - info.s_skip=src->pitch-info.s_width*src->format->BytesPerPixel; - info.d_pixels = (Uint8 *)dst->pixels + - (Uint16)dstrect->y*dst->pitch + - (Uint16)dstrect->x*dst->format->BytesPerPixel; - info.d_width = dstrect->w; - info.d_height = dstrect->h; - info.d_skip=dst->pitch-info.d_width*dst->format->BytesPerPixel; - info.aux_data = src->map->sw_data->aux_data; - info.src = src->format; - info.table = src->map->table; - info.dst = dst->format; - RunBlit = src->map->sw_data->blit; - - /* Run the actual software blit */ - RunBlit(&info); - } - - /* We need to unlock the surfaces if they're locked */ - if ( dst_locked ) { - SDL_UnlockSurface(dst); - } - if ( src_locked ) { - SDL_UnlockSurface(src); - } - /* Blit is done! */ - return(okay ? 0 : -1); + int okay; + int src_locked; + int dst_locked; + + /* Everything is okay at the beginning... */ + okay = 1; + + /* Lock the destination if it's in hardware */ + dst_locked = 0; + if (SDL_MUSTLOCK(dst)) { + if (SDL_LockSurface(dst) < 0) { + okay = 0; + } else { + dst_locked = 1; + } + } + /* Lock the source if it's in hardware */ + src_locked = 0; + if (SDL_MUSTLOCK(src)) { + if (SDL_LockSurface(src) < 0) { + okay = 0; + } else { + src_locked = 1; + } + } + + /* Set up source and destination buffer pointers, and BLIT! */ + if (okay && srcrect->w && srcrect->h) { + SDL_BlitInfo info; + SDL_loblit RunBlit; + + /* Set up the blit information */ + info.s_pixels = (Uint8 *) src->pixels + + (Uint16) srcrect->y * src->pitch + + (Uint16) srcrect->x * src->format->BytesPerPixel; + info.s_width = srcrect->w; + info.s_height = srcrect->h; + info.s_skip = src->pitch - info.s_width * src->format->BytesPerPixel; + info.d_pixels = (Uint8 *) dst->pixels + + (Uint16) dstrect->y * dst->pitch + + (Uint16) dstrect->x * dst->format->BytesPerPixel; + info.d_width = dstrect->w; + info.d_height = dstrect->h; + info.d_skip = dst->pitch - info.d_width * dst->format->BytesPerPixel; + info.aux_data = src->map->sw_data->aux_data; + info.src = src->format; + info.table = src->map->table; + info.dst = dst->format; + RunBlit = src->map->sw_data->blit; + + /* Run the actual software blit */ + RunBlit(&info); + } + + /* We need to unlock the surfaces if they're locked */ + if (dst_locked) { + SDL_UnlockSurface(dst); + } + if (src_locked) { + SDL_UnlockSurface(src); + } + /* Blit is done! */ + return (okay ? 0 : -1); } #ifdef MMX_ASMBLIT -static __inline__ void SDL_memcpyMMX(Uint8 *to, const Uint8 *from, int len) +static __inline__ void +SDL_memcpyMMX(Uint8 * to, const Uint8 * from, int len) { - int i; - - for(i=0; id_width*info->dst->BytesPerPixel; - h = info->d_height; - src = info->s_pixels; - dst = info->d_pixels; - srcskip = w+info->s_skip; - dstskip = w+info->d_skip; + Uint8 *src, *dst; + int w, h; + int srcskip, dstskip; + + w = info->d_width * info->dst->BytesPerPixel; + h = info->d_height; + src = info->s_pixels; + dst = info->d_pixels; + srcskip = w + info->s_skip; + dstskip = w + info->d_skip; #ifdef MMX_ASMBLIT - if(SDL_HasSSE()) - { - while ( h-- ) { - SDL_memcpySSE(dst, src, w); - src += srcskip; - dst += dstskip; - } - __asm__ __volatile__ ( - " emms\n" - ::); - } - else - if(SDL_HasMMX()) - { - while ( h-- ) { - SDL_memcpyMMX(dst, src, w); - src += srcskip; - dst += dstskip; - } - __asm__ __volatile__ ( - " emms\n" - ::); - } - else + if (SDL_HasSSE()) { + while (h--) { + SDL_memcpySSE(dst, src, w); + src += srcskip; + dst += dstskip; + } + __asm__ __volatile__(" emms\n"::); + } else if (SDL_HasMMX()) { + while (h--) { + SDL_memcpyMMX(dst, src, w); + src += srcskip; + dst += dstskip; + } + __asm__ __volatile__(" emms\n"::); + } else #endif - while ( h-- ) { - SDL_memcpy(dst, src, w); - src += srcskip; - dst += dstskip; - } + while (h--) { + SDL_memcpy(dst, src, w); + src += srcskip; + dst += dstskip; + } } -static void SDL_BlitCopyOverlap(SDL_BlitInfo *info) +static void +SDL_BlitCopyOverlap(SDL_BlitInfo * info) { - Uint8 *src, *dst; - int w, h; - int srcskip, dstskip; - - w = info->d_width*info->dst->BytesPerPixel; - h = info->d_height; - src = info->s_pixels; - dst = info->d_pixels; - srcskip = w+info->s_skip; - dstskip = w+info->d_skip; - if ( dst < src ) { - while ( h-- ) { - SDL_memcpy(dst, src, w); - src += srcskip; - dst += dstskip; - } - } else { - src += ((h-1) * srcskip); - dst += ((h-1) * dstskip); - while ( h-- ) { - SDL_revcpy(dst, src, w); - src -= srcskip; - dst -= dstskip; - } - } + Uint8 *src, *dst; + int w, h; + int srcskip, dstskip; + + w = info->d_width * info->dst->BytesPerPixel; + h = info->d_height; + src = info->s_pixels; + dst = info->d_pixels; + srcskip = w + info->s_skip; + dstskip = w + info->d_skip; + if (dst < src) { + while (h--) { + SDL_memcpy(dst, src, w); + src += srcskip; + dst += dstskip; + } + } else { + src += ((h - 1) * srcskip); + dst += ((h - 1) * dstskip); + while (h--) { + SDL_revcpy(dst, src, w); + src -= srcskip; + dst -= dstskip; + } + } } /* Figure out which of many blit routines to set up on a surface */ -int SDL_CalculateBlit(SDL_Surface *surface) +int +SDL_CalculateBlit(SDL_Surface * surface) { - int blit_index; - - /* Clean everything out to start */ - if ( (surface->flags & SDL_RLEACCEL) == SDL_RLEACCEL ) { - SDL_UnRLESurface(surface, 1); - } - surface->map->sw_blit = NULL; - - /* Figure out if an accelerated hardware blit is possible */ - surface->flags &= ~SDL_HWACCEL; - if ( surface->map->identity ) { - int hw_blit_ok; - - if ( (surface->flags & SDL_HWSURFACE) == SDL_HWSURFACE ) { - /* We only support accelerated blitting to hardware */ - if ( surface->map->dst->flags & SDL_HWSURFACE ) { - hw_blit_ok = current_video->info.blit_hw; - } else { - hw_blit_ok = 0; - } - if (hw_blit_ok && (surface->flags & SDL_SRCCOLORKEY)) { - hw_blit_ok = current_video->info.blit_hw_CC; - } - if ( hw_blit_ok && (surface->flags & SDL_SRCALPHA) ) { - hw_blit_ok = current_video->info.blit_hw_A; - } - } else { - /* We only support accelerated blitting to hardware */ - if ( surface->map->dst->flags & SDL_HWSURFACE ) { - hw_blit_ok = current_video->info.blit_sw; - } else { - hw_blit_ok = 0; - } - if (hw_blit_ok && (surface->flags & SDL_SRCCOLORKEY)) { - hw_blit_ok = current_video->info.blit_sw_CC; - } - if ( hw_blit_ok && (surface->flags & SDL_SRCALPHA) ) { - hw_blit_ok = current_video->info.blit_sw_A; - } - } - if ( hw_blit_ok ) { - SDL_VideoDevice *video = current_video; - SDL_VideoDevice *this = current_video; - video->CheckHWBlit(this, surface, surface->map->dst); - } - } - - /* if an alpha pixel format is specified, we can accelerate alpha blits */ - if (((surface->flags & SDL_HWSURFACE) == SDL_HWSURFACE )&&(current_video->displayformatalphapixel)) - { - if ( (surface->flags & SDL_SRCALPHA) ) - if ( current_video->info.blit_hw_A ) { - SDL_VideoDevice *video = current_video; - SDL_VideoDevice *this = current_video; - video->CheckHWBlit(this, surface, surface->map->dst); - } - } - - /* Get the blit function index, based on surface mode */ - /* { 0 = nothing, 1 = colorkey, 2 = alpha, 3 = colorkey+alpha } */ - blit_index = 0; - blit_index |= (!!(surface->flags & SDL_SRCCOLORKEY)) << 0; - if ( surface->flags & SDL_SRCALPHA - && (surface->format->alpha != SDL_ALPHA_OPAQUE - || surface->format->Amask) ) { - blit_index |= 2; - } - - /* Check for special "identity" case -- copy blit */ - if ( surface->map->identity && blit_index == 0 ) { - surface->map->sw_data->blit = SDL_BlitCopy; - - /* Handle overlapping blits on the same surface */ - if ( surface == surface->map->dst ) { - surface->map->sw_data->blit = SDL_BlitCopyOverlap; - } - } else { - if ( surface->format->BitsPerPixel < 8 ) { - surface->map->sw_data->blit = - SDL_CalculateBlit0(surface, blit_index); - } else { - switch ( surface->format->BytesPerPixel ) { - case 1: - surface->map->sw_data->blit = - SDL_CalculateBlit1(surface, blit_index); - break; - case 2: - case 3: - case 4: - surface->map->sw_data->blit = - SDL_CalculateBlitN(surface, blit_index); - break; - default: - surface->map->sw_data->blit = NULL; - break; - } - } - } - /* Make sure we have a blit function */ - if ( surface->map->sw_data->blit == NULL ) { - SDL_InvalidateMap(surface->map); - SDL_SetError("Blit combination not supported"); - return(-1); - } - - /* Choose software blitting function */ - if(surface->flags & SDL_RLEACCELOK - && (surface->flags & SDL_HWACCEL) != SDL_HWACCEL) { - - if(surface->map->identity - && (blit_index == 1 - || (blit_index == 3 && !surface->format->Amask))) { - if ( SDL_RLESurface(surface) == 0 ) - surface->map->sw_blit = SDL_RLEBlit; - } else if(blit_index == 2 && surface->format->Amask) { - if ( SDL_RLESurface(surface) == 0 ) - surface->map->sw_blit = SDL_RLEAlphaBlit; - } - } - - if ( surface->map->sw_blit == NULL ) { - surface->map->sw_blit = SDL_SoftBlit; - } - return(0); + int blit_index; + + /* Clean everything out to start */ + if ((surface->flags & SDL_RLEACCEL) == SDL_RLEACCEL) { + SDL_UnRLESurface(surface, 1); + } + surface->map->sw_blit = NULL; + + /* Get the blit function index, based on surface mode */ + /* { 0 = nothing, 1 = colorkey, 2 = alpha, 3 = colorkey+alpha } */ + blit_index = 0; + blit_index |= (!!(surface->flags & SDL_SRCCOLORKEY)) << 0; + if (surface->flags & SDL_SRCALPHA + && (surface->format->alpha != SDL_ALPHA_OPAQUE + || surface->format->Amask)) { + blit_index |= 2; + } + + /* Check for special "identity" case -- copy blit */ + if (surface->map->identity && blit_index == 0) { + surface->map->sw_data->blit = SDL_BlitCopy; + + /* Handle overlapping blits on the same surface */ + if (surface == surface->map->dst) { + surface->map->sw_data->blit = SDL_BlitCopyOverlap; + } + } else { + if (surface->format->BitsPerPixel < 8) { + surface->map->sw_data->blit = + SDL_CalculateBlit0(surface, blit_index); + } else { + switch (surface->format->BytesPerPixel) { + case 1: + surface->map->sw_data->blit = + SDL_CalculateBlit1(surface, blit_index); + break; + case 2: + case 3: + case 4: + surface->map->sw_data->blit = + SDL_CalculateBlitN(surface, blit_index); + break; + default: + surface->map->sw_data->blit = NULL; + break; + } + } + } + /* Make sure we have a blit function */ + if (surface->map->sw_data->blit == NULL) { + SDL_InvalidateMap(surface->map); + SDL_SetError("Blit combination not supported"); + return (-1); + } + + /* Choose software blitting function */ + if (surface->flags & SDL_RLEACCELOK) { + if (surface->map->identity + && (blit_index == 1 + || (blit_index == 3 && !surface->format->Amask))) { + if (SDL_RLESurface(surface) == 0) + surface->map->sw_blit = SDL_RLEBlit; + } else if (blit_index == 2 && surface->format->Amask) { + if (SDL_RLESurface(surface) == 0) + surface->map->sw_blit = SDL_RLEAlphaBlit; + } + } + + if (surface->map->sw_blit == NULL) { + surface->map->sw_blit = SDL_SoftBlit; + } + return (0); } +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/SDL_blit.h b/src/video/SDL_blit.h index 0ef24825d..be1cf27cb 100644 --- a/src/video/SDL_blit.h +++ b/src/video/SDL_blit.h @@ -27,54 +27,55 @@ #include "SDL_endian.h" /* The structure passed to the low level blit functions */ -typedef struct { - Uint8 *s_pixels; - int s_width; - int s_height; - int s_skip; - Uint8 *d_pixels; - int d_width; - int d_height; - int d_skip; - void *aux_data; - SDL_PixelFormat *src; - Uint8 *table; - SDL_PixelFormat *dst; +typedef struct +{ + Uint8 *s_pixels; + int s_width; + int s_height; + int s_skip; + Uint8 *d_pixels; + int d_width; + int d_height; + int d_skip; + void *aux_data; + SDL_PixelFormat *src; + Uint8 *table; + SDL_PixelFormat *dst; } SDL_BlitInfo; /* The type definition for the low level blit functions */ -typedef void (*SDL_loblit)(SDL_BlitInfo *info); +typedef void (*SDL_loblit) (SDL_BlitInfo * info); /* This is the private info structure for software accelerated blits */ -struct private_swaccel { - SDL_loblit blit; - void *aux_data; +struct private_swaccel +{ + SDL_loblit blit; + void *aux_data; }; /* Blit mapping definition */ -typedef struct SDL_BlitMap { - SDL_Surface *dst; - int identity; - Uint8 *table; - SDL_blit hw_blit; - SDL_blit sw_blit; - struct private_hwaccel *hw_data; - struct private_swaccel *sw_data; - - /* the version count matches the destination; mismatch indicates - an invalid mapping */ - unsigned int format_version; +typedef struct SDL_BlitMap +{ + SDL_Surface *dst; + int identity; + Uint8 *table; + SDL_blit sw_blit; + struct private_swaccel *sw_data; + + /* the version count matches the destination; mismatch indicates + an invalid mapping */ + unsigned int format_version; } SDL_BlitMap; /* Functions found in SDL_blit.c */ -extern int SDL_CalculateBlit(SDL_Surface *surface); +extern int SDL_CalculateBlit(SDL_Surface * surface); /* Functions found in SDL_blit_{0,1,N,A}.c */ -extern SDL_loblit SDL_CalculateBlit0(SDL_Surface *surface, int complex); -extern SDL_loblit SDL_CalculateBlit1(SDL_Surface *surface, int complex); -extern SDL_loblit SDL_CalculateBlitN(SDL_Surface *surface, int complex); -extern SDL_loblit SDL_CalculateAlphaBlit(SDL_Surface *surface, int complex); +extern SDL_loblit SDL_CalculateBlit0(SDL_Surface * surface, int complex); +extern SDL_loblit SDL_CalculateBlit1(SDL_Surface * surface, int complex); +extern SDL_loblit SDL_CalculateBlitN(SDL_Surface * surface, int complex); +extern SDL_loblit SDL_CalculateAlphaBlit(SDL_Surface * surface, int complex); /* * Useful macros for blitting routines @@ -520,3 +521,4 @@ do { \ #endif #endif /* _SDL_blit_h */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/SDL_blit_0.c b/src/video/SDL_blit_0.c index 7cab3dfe4..ba4b4d654 100644 --- a/src/video/SDL_blit_0.c +++ b/src/video/SDL_blit_0.c @@ -26,446 +26,456 @@ /* Functions to blit from bitmaps to other surfaces */ -static void BlitBto1(SDL_BlitInfo *info) +static void +BlitBto1(SDL_BlitInfo * info) { - int c; - int width, height; - Uint8 *src, *map, *dst; - int srcskip, dstskip; - - /* Set up some basic variables */ - width = info->d_width; - height = info->d_height; - src = info->s_pixels; - srcskip = info->s_skip; - dst = info->d_pixels; - dstskip = info->d_skip; - map = info->table; - srcskip += width-(width+7)/8; - - if ( map ) { - while ( height-- ) { - Uint8 byte = 0, bit; - for ( c=0; c>7; - if ( 1 ) { - *dst = map[bit]; - } - dst++; - byte <<= 1; - } - src += srcskip; - dst += dstskip; - } - } else { - while ( height-- ) { - Uint8 byte = 0, bit; - for ( c=0; c>7; - if ( 1 ) { - *dst = bit; - } - dst++; - byte <<= 1; - } - src += srcskip; - dst += dstskip; - } - } + int c; + int width, height; + Uint8 *src, *map, *dst; + int srcskip, dstskip; + + /* Set up some basic variables */ + width = info->d_width; + height = info->d_height; + src = info->s_pixels; + srcskip = info->s_skip; + dst = info->d_pixels; + dstskip = info->d_skip; + map = info->table; + srcskip += width - (width + 7) / 8; + + if (map) { + while (height--) { + Uint8 byte = 0, bit; + for (c = 0; c < width; ++c) { + if ((c & 7) == 0) { + byte = *src++; + } + bit = (byte & 0x80) >> 7; + if (1) { + *dst = map[bit]; + } + dst++; + byte <<= 1; + } + src += srcskip; + dst += dstskip; + } + } else { + while (height--) { + Uint8 byte = 0, bit; + for (c = 0; c < width; ++c) { + if ((c & 7) == 0) { + byte = *src++; + } + bit = (byte & 0x80) >> 7; + if (1) { + *dst = bit; + } + dst++; + byte <<= 1; + } + src += srcskip; + dst += dstskip; + } + } } -static void BlitBto2(SDL_BlitInfo *info) +static void +BlitBto2(SDL_BlitInfo * info) { - int c; - int width, height; - Uint8 *src; - Uint16 *map, *dst; - int srcskip, dstskip; - - /* Set up some basic variables */ - width = info->d_width; - height = info->d_height; - src = info->s_pixels; - srcskip = info->s_skip; - dst = (Uint16 *)info->d_pixels; - dstskip = info->d_skip/2; - map = (Uint16 *)info->table; - srcskip += width-(width+7)/8; - - while ( height-- ) { - Uint8 byte = 0, bit; - for ( c=0; c>7; - if ( 1 ) { - *dst = map[bit]; - } - byte <<= 1; - dst++; - } - src += srcskip; - dst += dstskip; - } + int c; + int width, height; + Uint8 *src; + Uint16 *map, *dst; + int srcskip, dstskip; + + /* Set up some basic variables */ + width = info->d_width; + height = info->d_height; + src = info->s_pixels; + srcskip = info->s_skip; + dst = (Uint16 *) info->d_pixels; + dstskip = info->d_skip / 2; + map = (Uint16 *) info->table; + srcskip += width - (width + 7) / 8; + + while (height--) { + Uint8 byte = 0, bit; + for (c = 0; c < width; ++c) { + if ((c & 7) == 0) { + byte = *src++; + } + bit = (byte & 0x80) >> 7; + if (1) { + *dst = map[bit]; + } + byte <<= 1; + dst++; + } + src += srcskip; + dst += dstskip; + } } -static void BlitBto3(SDL_BlitInfo *info) +static void +BlitBto3(SDL_BlitInfo * info) { - int c, o; - int width, height; - Uint8 *src, *map, *dst; - int srcskip, dstskip; - - /* Set up some basic variables */ - width = info->d_width; - height = info->d_height; - src = info->s_pixels; - srcskip = info->s_skip; - dst = info->d_pixels; - dstskip = info->d_skip; - map = info->table; - srcskip += width-(width+7)/8; - - while ( height-- ) { - Uint8 byte = 0, bit; - for ( c=0; c>7; - if ( 1 ) { - o = bit * 4; - dst[0] = map[o++]; - dst[1] = map[o++]; - dst[2] = map[o++]; - } - byte <<= 1; - dst += 3; - } - src += srcskip; - dst += dstskip; - } + int c, o; + int width, height; + Uint8 *src, *map, *dst; + int srcskip, dstskip; + + /* Set up some basic variables */ + width = info->d_width; + height = info->d_height; + src = info->s_pixels; + srcskip = info->s_skip; + dst = info->d_pixels; + dstskip = info->d_skip; + map = info->table; + srcskip += width - (width + 7) / 8; + + while (height--) { + Uint8 byte = 0, bit; + for (c = 0; c < width; ++c) { + if ((c & 7) == 0) { + byte = *src++; + } + bit = (byte & 0x80) >> 7; + if (1) { + o = bit * 4; + dst[0] = map[o++]; + dst[1] = map[o++]; + dst[2] = map[o++]; + } + byte <<= 1; + dst += 3; + } + src += srcskip; + dst += dstskip; + } } -static void BlitBto4(SDL_BlitInfo *info) +static void +BlitBto4(SDL_BlitInfo * info) { - int width, height; - Uint8 *src; - Uint32 *map, *dst; - int srcskip, dstskip; - int c; - - /* Set up some basic variables */ - width = info->d_width; - height = info->d_height; - src = info->s_pixels; - srcskip = info->s_skip; - dst = (Uint32 *)info->d_pixels; - dstskip = info->d_skip/4; - map = (Uint32 *)info->table; - srcskip += width-(width+7)/8; - - while ( height-- ) { - Uint8 byte = 0, bit; - for ( c=0; c>7; - if ( 1 ) { - *dst = map[bit]; - } - byte <<= 1; - dst++; - } - src += srcskip; - dst += dstskip; - } + int width, height; + Uint8 *src; + Uint32 *map, *dst; + int srcskip, dstskip; + int c; + + /* Set up some basic variables */ + width = info->d_width; + height = info->d_height; + src = info->s_pixels; + srcskip = info->s_skip; + dst = (Uint32 *) info->d_pixels; + dstskip = info->d_skip / 4; + map = (Uint32 *) info->table; + srcskip += width - (width + 7) / 8; + + while (height--) { + Uint8 byte = 0, bit; + for (c = 0; c < width; ++c) { + if ((c & 7) == 0) { + byte = *src++; + } + bit = (byte & 0x80) >> 7; + if (1) { + *dst = map[bit]; + } + byte <<= 1; + dst++; + } + src += srcskip; + dst += dstskip; + } } -static void BlitBto1Key(SDL_BlitInfo *info) +static void +BlitBto1Key(SDL_BlitInfo * info) { - int width = info->d_width; - int height = info->d_height; - Uint8 *src = info->s_pixels; - Uint8 *dst = info->d_pixels; - int srcskip = info->s_skip; - int dstskip = info->d_skip; - Uint32 ckey = info->src->colorkey; - Uint8 *palmap = info->table; - int c; - - /* Set up some basic variables */ - srcskip += width-(width+7)/8; - - if ( palmap ) { - while ( height-- ) { - Uint8 byte = 0, bit; - for ( c=0; c>7; - if ( bit != ckey ) { - *dst = palmap[bit]; - } - dst++; - byte <<= 1; - } - src += srcskip; - dst += dstskip; - } - } else { - while ( height-- ) { - Uint8 byte = 0, bit; - for ( c=0; c>7; - if ( bit != ckey ) { - *dst = bit; - } - dst++; - byte <<= 1; - } - src += srcskip; - dst += dstskip; - } - } + int width = info->d_width; + int height = info->d_height; + Uint8 *src = info->s_pixels; + Uint8 *dst = info->d_pixels; + int srcskip = info->s_skip; + int dstskip = info->d_skip; + Uint32 ckey = info->src->colorkey; + Uint8 *palmap = info->table; + int c; + + /* Set up some basic variables */ + srcskip += width - (width + 7) / 8; + + if (palmap) { + while (height--) { + Uint8 byte = 0, bit; + for (c = 0; c < width; ++c) { + if ((c & 7) == 0) { + byte = *src++; + } + bit = (byte & 0x80) >> 7; + if (bit != ckey) { + *dst = palmap[bit]; + } + dst++; + byte <<= 1; + } + src += srcskip; + dst += dstskip; + } + } else { + while (height--) { + Uint8 byte = 0, bit; + for (c = 0; c < width; ++c) { + if ((c & 7) == 0) { + byte = *src++; + } + bit = (byte & 0x80) >> 7; + if (bit != ckey) { + *dst = bit; + } + dst++; + byte <<= 1; + } + src += srcskip; + dst += dstskip; + } + } } -static void BlitBto2Key(SDL_BlitInfo *info) +static void +BlitBto2Key(SDL_BlitInfo * info) { - int width = info->d_width; - int height = info->d_height; - Uint8 *src = info->s_pixels; - Uint16 *dstp = (Uint16 *)info->d_pixels; - int srcskip = info->s_skip; - int dstskip = info->d_skip; - Uint32 ckey = info->src->colorkey; - Uint8 *palmap = info->table; - int c; - - /* Set up some basic variables */ - srcskip += width-(width+7)/8; - dstskip /= 2; - - while ( height-- ) { - Uint8 byte = 0, bit; - for ( c=0; c>7; - if ( bit != ckey ) { - *dstp=((Uint16 *)palmap)[bit]; - } - byte <<= 1; - dstp++; - } - src += srcskip; - dstp += dstskip; - } + int width = info->d_width; + int height = info->d_height; + Uint8 *src = info->s_pixels; + Uint16 *dstp = (Uint16 *) info->d_pixels; + int srcskip = info->s_skip; + int dstskip = info->d_skip; + Uint32 ckey = info->src->colorkey; + Uint8 *palmap = info->table; + int c; + + /* Set up some basic variables */ + srcskip += width - (width + 7) / 8; + dstskip /= 2; + + while (height--) { + Uint8 byte = 0, bit; + for (c = 0; c < width; ++c) { + if ((c & 7) == 0) { + byte = *src++; + } + bit = (byte & 0x80) >> 7; + if (bit != ckey) { + *dstp = ((Uint16 *) palmap)[bit]; + } + byte <<= 1; + dstp++; + } + src += srcskip; + dstp += dstskip; + } } -static void BlitBto3Key(SDL_BlitInfo *info) +static void +BlitBto3Key(SDL_BlitInfo * info) { - int width = info->d_width; - int height = info->d_height; - Uint8 *src = info->s_pixels; - Uint8 *dst = info->d_pixels; - int srcskip = info->s_skip; - int dstskip = info->d_skip; - Uint32 ckey = info->src->colorkey; - Uint8 *palmap = info->table; - int c; - - /* Set up some basic variables */ - srcskip += width-(width+7)/8; - - while ( height-- ) { - Uint8 byte = 0, bit; - for ( c=0; c>7; - if ( bit != ckey ) { - SDL_memcpy(dst, &palmap[bit*4], 3); - } - byte <<= 1; - dst += 3; - } - src += srcskip; - dst += dstskip; - } + int width = info->d_width; + int height = info->d_height; + Uint8 *src = info->s_pixels; + Uint8 *dst = info->d_pixels; + int srcskip = info->s_skip; + int dstskip = info->d_skip; + Uint32 ckey = info->src->colorkey; + Uint8 *palmap = info->table; + int c; + + /* Set up some basic variables */ + srcskip += width - (width + 7) / 8; + + while (height--) { + Uint8 byte = 0, bit; + for (c = 0; c < width; ++c) { + if ((c & 7) == 0) { + byte = *src++; + } + bit = (byte & 0x80) >> 7; + if (bit != ckey) { + SDL_memcpy(dst, &palmap[bit * 4], 3); + } + byte <<= 1; + dst += 3; + } + src += srcskip; + dst += dstskip; + } } -static void BlitBto4Key(SDL_BlitInfo *info) +static void +BlitBto4Key(SDL_BlitInfo * info) { - int width = info->d_width; - int height = info->d_height; - Uint8 *src = info->s_pixels; - Uint32 *dstp = (Uint32 *)info->d_pixels; - int srcskip = info->s_skip; - int dstskip = info->d_skip; - Uint32 ckey = info->src->colorkey; - Uint8 *palmap = info->table; - int c; - - /* Set up some basic variables */ - srcskip += width-(width+7)/8; - dstskip /= 4; - - while ( height-- ) { - Uint8 byte = 0, bit; - for ( c=0; c>7; - if ( bit != ckey ) { - *dstp=((Uint32 *)palmap)[bit]; - } - byte <<= 1; - dstp++; - } - src += srcskip; - dstp += dstskip; - } + int width = info->d_width; + int height = info->d_height; + Uint8 *src = info->s_pixels; + Uint32 *dstp = (Uint32 *) info->d_pixels; + int srcskip = info->s_skip; + int dstskip = info->d_skip; + Uint32 ckey = info->src->colorkey; + Uint8 *palmap = info->table; + int c; + + /* Set up some basic variables */ + srcskip += width - (width + 7) / 8; + dstskip /= 4; + + while (height--) { + Uint8 byte = 0, bit; + for (c = 0; c < width; ++c) { + if ((c & 7) == 0) { + byte = *src++; + } + bit = (byte & 0x80) >> 7; + if (bit != ckey) { + *dstp = ((Uint32 *) palmap)[bit]; + } + byte <<= 1; + dstp++; + } + src += srcskip; + dstp += dstskip; + } } -static void BlitBtoNAlpha(SDL_BlitInfo *info) +static void +BlitBtoNAlpha(SDL_BlitInfo * info) { - int width = info->d_width; - int height = info->d_height; - Uint8 *src = info->s_pixels; - Uint8 *dst = info->d_pixels; - int srcskip = info->s_skip; - int dstskip = info->d_skip; - const SDL_Color *srcpal = info->src->palette->colors; - SDL_PixelFormat *dstfmt = info->dst; - int dstbpp; - int c; - const int A = info->src->alpha; - - /* Set up some basic variables */ - dstbpp = dstfmt->BytesPerPixel; - srcskip += width-(width+7)/8; - - while ( height-- ) { - Uint8 byte = 0, bit; - for ( c=0; c>7; - if ( 1 ) { - Uint32 pixel; - unsigned sR, sG, sB; - unsigned dR, dG, dB; - sR = srcpal[bit].r; - sG = srcpal[bit].g; - sB = srcpal[bit].b; - DISEMBLE_RGB(dst, dstbpp, dstfmt, - pixel, dR, dG, dB); - ALPHA_BLEND(sR, sG, sB, A, dR, dG, dB); - ASSEMBLE_RGB(dst, dstbpp, dstfmt, dR, dG, dB); - } - byte <<= 1; - dst += dstbpp; - } - src += srcskip; - dst += dstskip; - } + int width = info->d_width; + int height = info->d_height; + Uint8 *src = info->s_pixels; + Uint8 *dst = info->d_pixels; + int srcskip = info->s_skip; + int dstskip = info->d_skip; + const SDL_Color *srcpal = info->src->palette->colors; + SDL_PixelFormat *dstfmt = info->dst; + int dstbpp; + int c; + const int A = info->src->alpha; + + /* Set up some basic variables */ + dstbpp = dstfmt->BytesPerPixel; + srcskip += width - (width + 7) / 8; + + while (height--) { + Uint8 byte = 0, bit; + for (c = 0; c < width; ++c) { + if ((c & 7) == 0) { + byte = *src++; + } + bit = (byte & 0x80) >> 7; + if (1) { + Uint32 pixel; + unsigned sR, sG, sB; + unsigned dR, dG, dB; + sR = srcpal[bit].r; + sG = srcpal[bit].g; + sB = srcpal[bit].b; + DISEMBLE_RGB(dst, dstbpp, dstfmt, pixel, dR, dG, dB); + ALPHA_BLEND(sR, sG, sB, A, dR, dG, dB); + ASSEMBLE_RGB(dst, dstbpp, dstfmt, dR, dG, dB); + } + byte <<= 1; + dst += dstbpp; + } + src += srcskip; + dst += dstskip; + } } -static void BlitBtoNAlphaKey(SDL_BlitInfo *info) +static void +BlitBtoNAlphaKey(SDL_BlitInfo * info) { - int width = info->d_width; - int height = info->d_height; - Uint8 *src = info->s_pixels; - Uint8 *dst = info->d_pixels; - int srcskip = info->s_skip; - int dstskip = info->d_skip; - SDL_PixelFormat *srcfmt = info->src; - SDL_PixelFormat *dstfmt = info->dst; - const SDL_Color *srcpal = srcfmt->palette->colors; - int dstbpp; - int c; - const int A = srcfmt->alpha; - Uint32 ckey = srcfmt->colorkey; - - /* Set up some basic variables */ - dstbpp = dstfmt->BytesPerPixel; - srcskip += width-(width+7)/8; - - while ( height-- ) { - Uint8 byte = 0, bit; - for ( c=0; c>7; - if ( bit != ckey ) { - int sR, sG, sB; - int dR, dG, dB; - Uint32 pixel; - sR = srcpal[bit].r; - sG = srcpal[bit].g; - sB = srcpal[bit].b; - DISEMBLE_RGB(dst, dstbpp, dstfmt, - pixel, dR, dG, dB); - ALPHA_BLEND(sR, sG, sB, A, dR, dG, dB); - ASSEMBLE_RGB(dst, dstbpp, dstfmt, dR, dG, dB); - } - byte <<= 1; - dst += dstbpp; - } - src += srcskip; - dst += dstskip; - } + int width = info->d_width; + int height = info->d_height; + Uint8 *src = info->s_pixels; + Uint8 *dst = info->d_pixels; + int srcskip = info->s_skip; + int dstskip = info->d_skip; + SDL_PixelFormat *srcfmt = info->src; + SDL_PixelFormat *dstfmt = info->dst; + const SDL_Color *srcpal = srcfmt->palette->colors; + int dstbpp; + int c; + const int A = srcfmt->alpha; + Uint32 ckey = srcfmt->colorkey; + + /* Set up some basic variables */ + dstbpp = dstfmt->BytesPerPixel; + srcskip += width - (width + 7) / 8; + + while (height--) { + Uint8 byte = 0, bit; + for (c = 0; c < width; ++c) { + if ((c & 7) == 0) { + byte = *src++; + } + bit = (byte & 0x80) >> 7; + if (bit != ckey) { + int sR, sG, sB; + int dR, dG, dB; + Uint32 pixel; + sR = srcpal[bit].r; + sG = srcpal[bit].g; + sB = srcpal[bit].b; + DISEMBLE_RGB(dst, dstbpp, dstfmt, pixel, dR, dG, dB); + ALPHA_BLEND(sR, sG, sB, A, dR, dG, dB); + ASSEMBLE_RGB(dst, dstbpp, dstfmt, dR, dG, dB); + } + byte <<= 1; + dst += dstbpp; + } + src += srcskip; + dst += dstskip; + } } static SDL_loblit bitmap_blit[] = { - NULL, BlitBto1, BlitBto2, BlitBto3, BlitBto4 + NULL, BlitBto1, BlitBto2, BlitBto3, BlitBto4 }; static SDL_loblit colorkey_blit[] = { NULL, BlitBto1Key, BlitBto2Key, BlitBto3Key, BlitBto4Key }; -SDL_loblit SDL_CalculateBlit0(SDL_Surface *surface, int blit_index) +SDL_loblit +SDL_CalculateBlit0(SDL_Surface * surface, int blit_index) { - int which; - - if ( surface->format->BitsPerPixel != 1 ) { - /* We don't support sub 8-bit packed pixel modes */ - return NULL; - } - if ( surface->map->dst->format->BitsPerPixel < 8 ) { - which = 0; - } else { - which = surface->map->dst->format->BytesPerPixel; - } - switch(blit_index) { - case 0: /* copy */ - return bitmap_blit[which]; - - case 1: /* colorkey */ - return colorkey_blit[which]; - - case 2: /* alpha */ - return which >= 2 ? BlitBtoNAlpha : NULL; - - case 4: /* alpha + colorkey */ - return which >= 2 ? BlitBtoNAlphaKey : NULL; - } - return NULL; + int which; + + if (surface->format->BitsPerPixel != 1) { + /* We don't support sub 8-bit packed pixel modes */ + return NULL; + } + if (surface->map->dst->format->BitsPerPixel < 8) { + which = 0; + } else { + which = surface->map->dst->format->BytesPerPixel; + } + switch (blit_index) { + case 0: /* copy */ + return bitmap_blit[which]; + + case 1: /* colorkey */ + return colorkey_blit[which]; + + case 2: /* alpha */ + return which >= 2 ? BlitBtoNAlpha : NULL; + + case 4: /* alpha + colorkey */ + return which >= 2 ? BlitBtoNAlphaKey : NULL; + } + return NULL; } +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/SDL_blit_1.c b/src/video/SDL_blit_1.c index d31126b26..51e7dbed9 100644 --- a/src/video/SDL_blit_1.c +++ b/src/video/SDL_blit_1.c @@ -28,26 +28,28 @@ /* Functions to blit from 8-bit surfaces to other surfaces */ -static void Blit1to1(SDL_BlitInfo *info) +static void +Blit1to1(SDL_BlitInfo * info) { #ifndef USE_DUFFS_LOOP - int c; + int c; #endif - int width, height; - Uint8 *src, *map, *dst; - int srcskip, dstskip; - - /* Set up some basic variables */ - width = info->d_width; - height = info->d_height; - src = info->s_pixels; - srcskip = info->s_skip; - dst = info->d_pixels; - dstskip = info->d_skip; - map = info->table; - - while ( height-- ) { + int width, height; + Uint8 *src, *map, *dst; + int srcskip, dstskip; + + /* Set up some basic variables */ + width = info->d_width; + height = info->d_height; + src = info->s_pixels; + srcskip = info->s_skip; + dst = info->d_pixels; + dstskip = info->d_skip; + map = info->table; + + while (height--) { #ifdef USE_DUFFS_LOOP + /* *INDENT-OFF* */ DUFFS_LOOP( { *dst = map[*src]; @@ -55,17 +57,19 @@ static void Blit1to1(SDL_BlitInfo *info) dst++; src++; , width); + /* *INDENT-ON* */ #else - for ( c=width; c; --c ) { - *dst = map[*src]; - dst++; - src++; - } + for (c = width; c; --c) { + *dst = map[*src]; + dst++; + src++; + } #endif - src += srcskip; - dst += dstskip; - } + src += srcskip; + dst += dstskip; + } } + /* This is now endian dependent */ #if ( SDL_BYTEORDER == SDL_LIL_ENDIAN ) #define HI 1 @@ -74,136 +78,135 @@ static void Blit1to1(SDL_BlitInfo *info) #define HI 0 #define LO 1 #endif -static void Blit1to2(SDL_BlitInfo *info) +static void +Blit1to2(SDL_BlitInfo * info) { #ifndef USE_DUFFS_LOOP - int c; + int c; #endif - int width, height; - Uint8 *src, *dst; - Uint16 *map; - int srcskip, dstskip; - - /* Set up some basic variables */ - width = info->d_width; - height = info->d_height; - src = info->s_pixels; - srcskip = info->s_skip; - dst = info->d_pixels; - dstskip = info->d_skip; - map = (Uint16 *)info->table; + int width, height; + Uint8 *src, *dst; + Uint16 *map; + int srcskip, dstskip; + + /* Set up some basic variables */ + width = info->d_width; + height = info->d_height; + src = info->s_pixels; + srcskip = info->s_skip; + dst = info->d_pixels; + dstskip = info->d_skip; + map = (Uint16 *) info->table; #ifdef USE_DUFFS_LOOP - while ( height-- ) { + while (height--) { + /* *INDENT-OFF* */ DUFFS_LOOP( { *(Uint16 *)dst = map[*src++]; dst += 2; }, width); - src += srcskip; - dst += dstskip; - } + /* *INDENT-ON* */ + src += srcskip; + dst += dstskip; + } #else - /* Memory align at 4-byte boundary, if necessary */ - if ( (long)dst & 0x03 ) { - /* Don't do anything if width is 0 */ - if ( width == 0 ) { - return; - } - --width; - - while ( height-- ) { - /* Perform copy alignment */ - *(Uint16 *)dst = map[*src++]; - dst += 2; - - /* Copy in 4 pixel chunks */ - for ( c=width/4; c; --c ) { - *(Uint32 *)dst = - (map[src[HI]]<<16)|(map[src[LO]]); - src += 2; - dst += 4; - *(Uint32 *)dst = - (map[src[HI]]<<16)|(map[src[LO]]); - src += 2; - dst += 4; - } - /* Get any leftovers */ - switch (width & 3) { - case 3: - *(Uint16 *)dst = map[*src++]; - dst += 2; - case 2: - *(Uint32 *)dst = - (map[src[HI]]<<16)|(map[src[LO]]); - src += 2; - dst += 4; - break; - case 1: - *(Uint16 *)dst = map[*src++]; - dst += 2; - break; - } - src += srcskip; - dst += dstskip; - } - } else { - while ( height-- ) { - /* Copy in 4 pixel chunks */ - for ( c=width/4; c; --c ) { - *(Uint32 *)dst = - (map[src[HI]]<<16)|(map[src[LO]]); - src += 2; - dst += 4; - *(Uint32 *)dst = - (map[src[HI]]<<16)|(map[src[LO]]); - src += 2; - dst += 4; - } - /* Get any leftovers */ - switch (width & 3) { - case 3: - *(Uint16 *)dst = map[*src++]; - dst += 2; - case 2: - *(Uint32 *)dst = - (map[src[HI]]<<16)|(map[src[LO]]); - src += 2; - dst += 4; - break; - case 1: - *(Uint16 *)dst = map[*src++]; - dst += 2; - break; - } - src += srcskip; - dst += dstskip; - } - } + /* Memory align at 4-byte boundary, if necessary */ + if ((long) dst & 0x03) { + /* Don't do anything if width is 0 */ + if (width == 0) { + return; + } + --width; + + while (height--) { + /* Perform copy alignment */ + *(Uint16 *) dst = map[*src++]; + dst += 2; + + /* Copy in 4 pixel chunks */ + for (c = width / 4; c; --c) { + *(Uint32 *) dst = (map[src[HI]] << 16) | (map[src[LO]]); + src += 2; + dst += 4; + *(Uint32 *) dst = (map[src[HI]] << 16) | (map[src[LO]]); + src += 2; + dst += 4; + } + /* Get any leftovers */ + switch (width & 3) { + case 3: + *(Uint16 *) dst = map[*src++]; + dst += 2; + case 2: + *(Uint32 *) dst = (map[src[HI]] << 16) | (map[src[LO]]); + src += 2; + dst += 4; + break; + case 1: + *(Uint16 *) dst = map[*src++]; + dst += 2; + break; + } + src += srcskip; + dst += dstskip; + } + } else { + while (height--) { + /* Copy in 4 pixel chunks */ + for (c = width / 4; c; --c) { + *(Uint32 *) dst = (map[src[HI]] << 16) | (map[src[LO]]); + src += 2; + dst += 4; + *(Uint32 *) dst = (map[src[HI]] << 16) | (map[src[LO]]); + src += 2; + dst += 4; + } + /* Get any leftovers */ + switch (width & 3) { + case 3: + *(Uint16 *) dst = map[*src++]; + dst += 2; + case 2: + *(Uint32 *) dst = (map[src[HI]] << 16) | (map[src[LO]]); + src += 2; + dst += 4; + break; + case 1: + *(Uint16 *) dst = map[*src++]; + dst += 2; + break; + } + src += srcskip; + dst += dstskip; + } + } #endif /* USE_DUFFS_LOOP */ } -static void Blit1to3(SDL_BlitInfo *info) +static void +Blit1to3(SDL_BlitInfo * info) { #ifndef USE_DUFFS_LOOP - int c; + int c; #endif - int o; - int width, height; - Uint8 *src, *map, *dst; - int srcskip, dstskip; - - /* Set up some basic variables */ - width = info->d_width; - height = info->d_height; - src = info->s_pixels; - srcskip = info->s_skip; - dst = info->d_pixels; - dstskip = info->d_skip; - map = info->table; - - while ( height-- ) { + int o; + int width, height; + Uint8 *src, *map, *dst; + int srcskip, dstskip; + + /* Set up some basic variables */ + width = info->d_width; + height = info->d_height; + src = info->s_pixels; + srcskip = info->s_skip; + dst = info->d_pixels; + dstskip = info->d_skip; + map = info->table; + + while (height--) { #ifdef USE_DUFFS_LOOP + /* *INDENT-OFF* */ DUFFS_LOOP( { o = *src * 4; @@ -214,78 +217,84 @@ static void Blit1to3(SDL_BlitInfo *info) src++; dst += 3; , width); + /* *INDENT-ON* */ #else - for ( c=width; c; --c ) { - o = *src * 4; - dst[0] = map[o++]; - dst[1] = map[o++]; - dst[2] = map[o++]; - src++; - dst += 3; - } + for (c = width; c; --c) { + o = *src * 4; + dst[0] = map[o++]; + dst[1] = map[o++]; + dst[2] = map[o++]; + src++; + dst += 3; + } #endif /* USE_DUFFS_LOOP */ - src += srcskip; - dst += dstskip; - } + src += srcskip; + dst += dstskip; + } } -static void Blit1to4(SDL_BlitInfo *info) +static void +Blit1to4(SDL_BlitInfo * info) { #ifndef USE_DUFFS_LOOP - int c; + int c; #endif - int width, height; - Uint8 *src; - Uint32 *map, *dst; - int srcskip, dstskip; - - /* Set up some basic variables */ - width = info->d_width; - height = info->d_height; - src = info->s_pixels; - srcskip = info->s_skip; - dst = (Uint32 *)info->d_pixels; - dstskip = info->d_skip/4; - map = (Uint32 *)info->table; - - while ( height-- ) { + int width, height; + Uint8 *src; + Uint32 *map, *dst; + int srcskip, dstskip; + + /* Set up some basic variables */ + width = info->d_width; + height = info->d_height; + src = info->s_pixels; + srcskip = info->s_skip; + dst = (Uint32 *) info->d_pixels; + dstskip = info->d_skip / 4; + map = (Uint32 *) info->table; + + while (height--) { #ifdef USE_DUFFS_LOOP + /* *INDENT-OFF* */ DUFFS_LOOP( *dst++ = map[*src++]; , width); + /* *INDENT-ON* */ #else - for ( c=width/4; c; --c ) { - *dst++ = map[*src++]; - *dst++ = map[*src++]; - *dst++ = map[*src++]; - *dst++ = map[*src++]; - } - switch ( width & 3 ) { - case 3: - *dst++ = map[*src++]; - case 2: - *dst++ = map[*src++]; - case 1: - *dst++ = map[*src++]; - } + for (c = width / 4; c; --c) { + *dst++ = map[*src++]; + *dst++ = map[*src++]; + *dst++ = map[*src++]; + *dst++ = map[*src++]; + } + switch (width & 3) { + case 3: + *dst++ = map[*src++]; + case 2: + *dst++ = map[*src++]; + case 1: + *dst++ = map[*src++]; + } #endif /* USE_DUFFS_LOOP */ - src += srcskip; - dst += dstskip; - } + src += srcskip; + dst += dstskip; + } } -static void Blit1to1Key(SDL_BlitInfo *info) +static void +Blit1to1Key(SDL_BlitInfo * info) { - int width = info->d_width; - int height = info->d_height; - Uint8 *src = info->s_pixels; - int srcskip = info->s_skip; - Uint8 *dst = info->d_pixels; - int dstskip = info->d_skip; - Uint8 *palmap = info->table; - Uint32 ckey = info->src->colorkey; - - if ( palmap ) { - while ( height-- ) { + int width = info->d_width; + int height = info->d_height; + Uint8 *src = info->s_pixels; + int srcskip = info->s_skip; + Uint8 *dst = info->d_pixels; + int dstskip = info->d_skip; + Uint8 *palmap = info->table; + Uint32 ckey = info->src->colorkey; + + if (palmap) { + while (height--) { + /* *INDENT-OFF* */ DUFFS_LOOP( { if ( *src != ckey ) { @@ -295,11 +304,13 @@ static void Blit1to1Key(SDL_BlitInfo *info) src++; }, width); - src += srcskip; - dst += dstskip; - } - } else { - while ( height-- ) { + /* *INDENT-ON* */ + src += srcskip; + dst += dstskip; + } + } else { + while (height--) { + /* *INDENT-OFF* */ DUFFS_LOOP( { if ( *src != ckey ) { @@ -309,27 +320,30 @@ static void Blit1to1Key(SDL_BlitInfo *info) src++; }, width); - src += srcskip; - dst += dstskip; - } - } + /* *INDENT-ON* */ + src += srcskip; + dst += dstskip; + } + } } -static void Blit1to2Key(SDL_BlitInfo *info) +static void +Blit1to2Key(SDL_BlitInfo * info) { - int width = info->d_width; - int height = info->d_height; - Uint8 *src = info->s_pixels; - int srcskip = info->s_skip; - Uint16 *dstp = (Uint16 *)info->d_pixels; - int dstskip = info->d_skip; - Uint16 *palmap = (Uint16 *)info->table; - Uint32 ckey = info->src->colorkey; - - /* Set up some basic variables */ - dstskip /= 2; - - while ( height-- ) { + int width = info->d_width; + int height = info->d_height; + Uint8 *src = info->s_pixels; + int srcskip = info->s_skip; + Uint16 *dstp = (Uint16 *) info->d_pixels; + int dstskip = info->d_skip; + Uint16 *palmap = (Uint16 *) info->table; + Uint32 ckey = info->src->colorkey; + + /* Set up some basic variables */ + dstskip /= 2; + + while (height--) { + /* *INDENT-OFF* */ DUFFS_LOOP( { if ( *src != ckey ) { @@ -339,24 +353,27 @@ static void Blit1to2Key(SDL_BlitInfo *info) dstp++; }, width); - src += srcskip; - dstp += dstskip; - } + /* *INDENT-ON* */ + src += srcskip; + dstp += dstskip; + } } -static void Blit1to3Key(SDL_BlitInfo *info) +static void +Blit1to3Key(SDL_BlitInfo * info) { - int width = info->d_width; - int height = info->d_height; - Uint8 *src = info->s_pixels; - int srcskip = info->s_skip; - Uint8 *dst = info->d_pixels; - int dstskip = info->d_skip; - Uint8 *palmap = info->table; - Uint32 ckey = info->src->colorkey; - int o; - - while ( height-- ) { + int width = info->d_width; + int height = info->d_height; + Uint8 *src = info->s_pixels; + int srcskip = info->s_skip; + Uint8 *dst = info->d_pixels; + int dstskip = info->d_skip; + Uint8 *palmap = info->table; + Uint32 ckey = info->src->colorkey; + int o; + + while (height--) { + /* *INDENT-OFF* */ DUFFS_LOOP( { if ( *src != ckey ) { @@ -369,26 +386,29 @@ static void Blit1to3Key(SDL_BlitInfo *info) dst += 3; }, width); - src += srcskip; - dst += dstskip; - } + /* *INDENT-ON* */ + src += srcskip; + dst += dstskip; + } } -static void Blit1to4Key(SDL_BlitInfo *info) +static void +Blit1to4Key(SDL_BlitInfo * info) { - int width = info->d_width; - int height = info->d_height; - Uint8 *src = info->s_pixels; - int srcskip = info->s_skip; - Uint32 *dstp = (Uint32 *)info->d_pixels; - int dstskip = info->d_skip; - Uint32 *palmap = (Uint32 *)info->table; - Uint32 ckey = info->src->colorkey; - - /* Set up some basic variables */ - dstskip /= 4; - - while ( height-- ) { + int width = info->d_width; + int height = info->d_height; + Uint8 *src = info->s_pixels; + int srcskip = info->s_skip; + Uint32 *dstp = (Uint32 *) info->d_pixels; + int dstskip = info->d_skip; + Uint32 *palmap = (Uint32 *) info->table; + Uint32 ckey = info->src->colorkey; + + /* Set up some basic variables */ + dstskip /= 4; + + while (height--) { + /* *INDENT-OFF* */ DUFFS_LOOP( { if ( *src != ckey ) { @@ -398,30 +418,33 @@ static void Blit1to4Key(SDL_BlitInfo *info) dstp++; }, width); - src += srcskip; - dstp += dstskip; - } + /* *INDENT-ON* */ + src += srcskip; + dstp += dstskip; + } } -static void Blit1toNAlpha(SDL_BlitInfo *info) +static void +Blit1toNAlpha(SDL_BlitInfo * info) { - int width = info->d_width; - int height = info->d_height; - Uint8 *src = info->s_pixels; - int srcskip = info->s_skip; - Uint8 *dst = info->d_pixels; - int dstskip = info->d_skip; - SDL_PixelFormat *dstfmt = info->dst; - const SDL_Color *srcpal = info->src->palette->colors; - int dstbpp; - const int A = info->src->alpha; - - /* Set up some basic variables */ - dstbpp = dstfmt->BytesPerPixel; - - while ( height-- ) { - int sR, sG, sB; - int dR, dG, dB; + int width = info->d_width; + int height = info->d_height; + Uint8 *src = info->s_pixels; + int srcskip = info->s_skip; + Uint8 *dst = info->d_pixels; + int dstskip = info->d_skip; + SDL_PixelFormat *dstfmt = info->dst; + const SDL_Color *srcpal = info->src->palette->colors; + int dstbpp; + const int A = info->src->alpha; + + /* Set up some basic variables */ + dstbpp = dstfmt->BytesPerPixel; + + while (height--) { + int sR, sG, sB; + int dR, dG, dB; + /* *INDENT-OFF* */ DUFFS_LOOP4( { Uint32 pixel; @@ -436,32 +459,35 @@ static void Blit1toNAlpha(SDL_BlitInfo *info) dst += dstbpp; }, width); - src += srcskip; - dst += dstskip; - } + /* *INDENT-ON* */ + src += srcskip; + dst += dstskip; + } } -static void Blit1toNAlphaKey(SDL_BlitInfo *info) +static void +Blit1toNAlphaKey(SDL_BlitInfo * info) { - int width = info->d_width; - int height = info->d_height; - Uint8 *src = info->s_pixels; - int srcskip = info->s_skip; - Uint8 *dst = info->d_pixels; - int dstskip = info->d_skip; - SDL_PixelFormat *srcfmt = info->src; - SDL_PixelFormat *dstfmt = info->dst; - const SDL_Color *srcpal = info->src->palette->colors; - Uint32 ckey = srcfmt->colorkey; - int dstbpp; - const int A = srcfmt->alpha; - - /* Set up some basic variables */ - dstbpp = dstfmt->BytesPerPixel; - - while ( height-- ) { - int sR, sG, sB; - int dR, dG, dB; + int width = info->d_width; + int height = info->d_height; + Uint8 *src = info->s_pixels; + int srcskip = info->s_skip; + Uint8 *dst = info->d_pixels; + int dstskip = info->d_skip; + SDL_PixelFormat *srcfmt = info->src; + SDL_PixelFormat *dstfmt = info->dst; + const SDL_Color *srcpal = info->src->palette->colors; + Uint32 ckey = srcfmt->colorkey; + int dstbpp; + const int A = srcfmt->alpha; + + /* Set up some basic variables */ + dstbpp = dstfmt->BytesPerPixel; + + while (height--) { + int sR, sG, sB; + int dR, dG, dB; + /* *INDENT-OFF* */ DUFFS_LOOP( { if ( *src != ckey ) { @@ -478,46 +504,50 @@ static void Blit1toNAlphaKey(SDL_BlitInfo *info) dst += dstbpp; }, width); - src += srcskip; - dst += dstskip; - } + /* *INDENT-ON* */ + src += srcskip; + dst += dstskip; + } } static SDL_loblit one_blit[] = { - NULL, Blit1to1, Blit1to2, Blit1to3, Blit1to4 + NULL, Blit1to1, Blit1to2, Blit1to3, Blit1to4 }; static SDL_loblit one_blitkey[] = { - NULL, Blit1to1Key, Blit1to2Key, Blit1to3Key, Blit1to4Key + NULL, Blit1to1Key, Blit1to2Key, Blit1to3Key, Blit1to4Key }; -SDL_loblit SDL_CalculateBlit1(SDL_Surface *surface, int blit_index) +SDL_loblit +SDL_CalculateBlit1(SDL_Surface * surface, int blit_index) { - int which; - SDL_PixelFormat *dstfmt; - - dstfmt = surface->map->dst->format; - if ( dstfmt->BitsPerPixel < 8 ) { - which = 0; - } else { - which = dstfmt->BytesPerPixel; - } - switch(blit_index) { - case 0: /* copy */ - return one_blit[which]; - - case 1: /* colorkey */ - return one_blitkey[which]; - - case 2: /* alpha */ - /* Supporting 8bpp->8bpp alpha is doable but requires lots of - tables which consume space and takes time to precompute, - so is better left to the user */ - return which >= 2 ? Blit1toNAlpha : NULL; - - case 3: /* alpha + colorkey */ - return which >= 2 ? Blit1toNAlphaKey : NULL; - - } - return NULL; + int which; + SDL_PixelFormat *dstfmt; + + dstfmt = surface->map->dst->format; + if (dstfmt->BitsPerPixel < 8) { + which = 0; + } else { + which = dstfmt->BytesPerPixel; + } + switch (blit_index) { + case 0: /* copy */ + return one_blit[which]; + + case 1: /* colorkey */ + return one_blitkey[which]; + + case 2: /* alpha */ + /* Supporting 8bpp->8bpp alpha is doable but requires lots of + tables which consume space and takes time to precompute, + so is better left to the user */ + return which >= 2 ? Blit1toNAlpha : NULL; + + case 3: /* alpha + colorkey */ + return which >= 2 ? Blit1toNAlphaKey : NULL; + + } + return NULL; } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/SDL_blit_A.c b/src/video/SDL_blit_A.c index 71109a27a..0ab05eeda 100644 --- a/src/video/SDL_blit_A.c +++ b/src/video/SDL_blit_A.c @@ -46,22 +46,24 @@ /* Functions to perform alpha blended blitting */ /* N->1 blending with per-surface alpha */ -static void BlitNto1SurfaceAlpha(SDL_BlitInfo *info) +static void +BlitNto1SurfaceAlpha(SDL_BlitInfo * info) { - int width = info->d_width; - int height = info->d_height; - Uint8 *src = info->s_pixels; - int srcskip = info->s_skip; - Uint8 *dst = info->d_pixels; - int dstskip = info->d_skip; - Uint8 *palmap = info->table; - SDL_PixelFormat *srcfmt = info->src; - SDL_PixelFormat *dstfmt = info->dst; - int srcbpp = srcfmt->BytesPerPixel; - - const unsigned A = srcfmt->alpha; - - while ( height-- ) { + int width = info->d_width; + int height = info->d_height; + Uint8 *src = info->s_pixels; + int srcskip = info->s_skip; + Uint8 *dst = info->d_pixels; + int dstskip = info->d_skip; + Uint8 *palmap = info->table; + SDL_PixelFormat *srcfmt = info->src; + SDL_PixelFormat *dstfmt = info->dst; + int srcbpp = srcfmt->BytesPerPixel; + + const unsigned A = srcfmt->alpha; + + while (height--) { + /* *INDENT-OFF* */ DUFFS_LOOP4( { Uint32 Pixel; @@ -93,27 +95,30 @@ static void BlitNto1SurfaceAlpha(SDL_BlitInfo *info) src += srcbpp; }, width); - src += srcskip; - dst += dstskip; - } + /* *INDENT-ON* */ + src += srcskip; + dst += dstskip; + } } /* N->1 blending with pixel alpha */ -static void BlitNto1PixelAlpha(SDL_BlitInfo *info) +static void +BlitNto1PixelAlpha(SDL_BlitInfo * info) { - int width = info->d_width; - int height = info->d_height; - Uint8 *src = info->s_pixels; - int srcskip = info->s_skip; - Uint8 *dst = info->d_pixels; - int dstskip = info->d_skip; - Uint8 *palmap = info->table; - SDL_PixelFormat *srcfmt = info->src; - SDL_PixelFormat *dstfmt = info->dst; - int srcbpp = srcfmt->BytesPerPixel; - - /* FIXME: fix alpha bit field expansion here too? */ - while ( height-- ) { + int width = info->d_width; + int height = info->d_height; + Uint8 *src = info->s_pixels; + int srcskip = info->s_skip; + Uint8 *dst = info->d_pixels; + int dstskip = info->d_skip; + Uint8 *palmap = info->table; + SDL_PixelFormat *srcfmt = info->src; + SDL_PixelFormat *dstfmt = info->dst; + int srcbpp = srcfmt->BytesPerPixel; + + /* FIXME: fix alpha bit field expansion here too? */ + while (height--) { + /* *INDENT-OFF* */ DUFFS_LOOP4( { Uint32 Pixel; @@ -146,29 +151,32 @@ static void BlitNto1PixelAlpha(SDL_BlitInfo *info) src += srcbpp; }, width); - src += srcskip; - dst += dstskip; - } + /* *INDENT-ON* */ + src += srcskip; + dst += dstskip; + } } /* colorkeyed N->1 blending with per-surface alpha */ -static void BlitNto1SurfaceAlphaKey(SDL_BlitInfo *info) +static void +BlitNto1SurfaceAlphaKey(SDL_BlitInfo * info) { - int width = info->d_width; - int height = info->d_height; - Uint8 *src = info->s_pixels; - int srcskip = info->s_skip; - Uint8 *dst = info->d_pixels; - int dstskip = info->d_skip; - Uint8 *palmap = info->table; - SDL_PixelFormat *srcfmt = info->src; - SDL_PixelFormat *dstfmt = info->dst; - int srcbpp = srcfmt->BytesPerPixel; - Uint32 ckey = srcfmt->colorkey; - - const int A = srcfmt->alpha; - - while ( height-- ) { + int width = info->d_width; + int height = info->d_height; + Uint8 *src = info->s_pixels; + int srcskip = info->s_skip; + Uint8 *dst = info->d_pixels; + int dstskip = info->d_skip; + Uint8 *palmap = info->table; + SDL_PixelFormat *srcfmt = info->src; + SDL_PixelFormat *dstfmt = info->dst; + int srcbpp = srcfmt->BytesPerPixel; + Uint32 ckey = srcfmt->colorkey; + + const int A = srcfmt->alpha; + + while (height--) { + /* *INDENT-OFF* */ DUFFS_LOOP( { Uint32 Pixel; @@ -202,31 +210,34 @@ static void BlitNto1SurfaceAlphaKey(SDL_BlitInfo *info) src += srcbpp; }, width); - src += srcskip; - dst += dstskip; - } + /* *INDENT-ON* */ + src += srcskip; + dst += dstskip; + } } #if GCC_ASMBLIT /* fast RGB888->(A)RGB888 blending with surface alpha=128 special case */ -static void BlitRGBtoRGBSurfaceAlpha128MMX(SDL_BlitInfo *info) +static void +BlitRGBtoRGBSurfaceAlpha128MMX(SDL_BlitInfo * info) { - int width = info->d_width; - int height = info->d_height; - Uint32 *srcp = (Uint32 *)info->s_pixels; - int srcskip = info->s_skip >> 2; - Uint32 *dstp = (Uint32 *)info->d_pixels; - int dstskip = info->d_skip >> 2; - Uint32 dalpha = info->dst->Amask; - Uint8 load[8]; - - *(Uint64 *)load = 0x00fefefe00fefefeULL;/* alpha128 mask */ - movq_m2r(*load, mm4); /* alpha128 mask -> mm4 */ - *(Uint64 *)load = 0x0001010100010101ULL;/* !alpha128 mask */ - movq_m2r(*load, mm3); /* !alpha128 mask -> mm3 */ - movd_m2r(dalpha, mm7); /* dst alpha mask */ - punpckldq_r2r(mm7, mm7); /* dst alpha mask | dst alpha mask -> mm7 */ - while(height--) { + int width = info->d_width; + int height = info->d_height; + Uint32 *srcp = (Uint32 *) info->s_pixels; + int srcskip = info->s_skip >> 2; + Uint32 *dstp = (Uint32 *) info->d_pixels; + int dstskip = info->d_skip >> 2; + Uint32 dalpha = info->dst->Amask; + Uint8 load[8]; + + *(Uint64 *) load = 0x00fefefe00fefefeULL; /* alpha128 mask */ + movq_m2r(*load, mm4); /* alpha128 mask -> mm4 */ + *(Uint64 *) load = 0x0001010100010101ULL; /* !alpha128 mask */ + movq_m2r(*load, mm3); /* !alpha128 mask -> mm3 */ + movd_m2r(dalpha, mm7); /* dst alpha mask */ + punpckldq_r2r(mm7, mm7); /* dst alpha mask | dst alpha mask -> mm7 */ + while (height--) { + /* *INDENT-OFF* */ DUFFS_LOOP_DOUBLE2( { Uint32 s = *srcp++; @@ -253,43 +264,48 @@ static void BlitRGBtoRGBSurfaceAlpha128MMX(SDL_BlitInfo *info) dstp += 2; srcp += 2; }, width); - srcp += srcskip; - dstp += dstskip; - } - emms(); + /* *INDENT-ON* */ + srcp += srcskip; + dstp += dstskip; + } + emms(); } /* fast RGB888->(A)RGB888 blending with surface alpha */ -static void BlitRGBtoRGBSurfaceAlphaMMX(SDL_BlitInfo *info) +static void +BlitRGBtoRGBSurfaceAlphaMMX(SDL_BlitInfo * info) { - SDL_PixelFormat* df = info->dst; - unsigned alpha = info->src->alpha; - - if (alpha == 128 && (df->Rmask | df->Gmask | df->Bmask) == 0x00FFFFFF) { - /* only call a128 version when R,G,B occupy lower bits */ - BlitRGBtoRGBSurfaceAlpha128MMX(info); - } else { - int width = info->d_width; - int height = info->d_height; - Uint32 *srcp = (Uint32 *)info->s_pixels; - int srcskip = info->s_skip >> 2; - Uint32 *dstp = (Uint32 *)info->d_pixels; - int dstskip = info->d_skip >> 2; - - pxor_r2r(mm5, mm5); /* 0 -> mm5 */ - /* form the alpha mult */ - movd_m2r(alpha, mm4); /* 0000000A -> mm4 */ - punpcklwd_r2r(mm4, mm4); /* 00000A0A -> mm4 */ - punpckldq_r2r(mm4, mm4); /* 0A0A0A0A -> mm4 */ - alpha = (0xff << df->Rshift) | (0xff << df->Gshift) | (0xff << df->Bshift); - movd_m2r(alpha, mm0); /* 00000FFF -> mm0 */ - punpcklbw_r2r(mm0, mm0); /* 00FFFFFF -> mm0 */ - pand_r2r(mm0, mm4); /* 0A0A0A0A -> mm4, minus 1 chan */ - /* at this point mm4 can be 000A0A0A or 0A0A0A00 or another combo */ - movd_m2r(df->Amask, mm7); /* dst alpha mask */ - punpckldq_r2r(mm7, mm7); /* dst alpha mask | dst alpha mask -> mm7 */ - - while(height--) { + SDL_PixelFormat *df = info->dst; + unsigned alpha = info->src->alpha; + + if (alpha == 128 && (df->Rmask | df->Gmask | df->Bmask) == 0x00FFFFFF) { + /* only call a128 version when R,G,B occupy lower bits */ + BlitRGBtoRGBSurfaceAlpha128MMX(info); + } else { + int width = info->d_width; + int height = info->d_height; + Uint32 *srcp = (Uint32 *) info->s_pixels; + int srcskip = info->s_skip >> 2; + Uint32 *dstp = (Uint32 *) info->d_pixels; + int dstskip = info->d_skip >> 2; + + pxor_r2r(mm5, mm5); /* 0 -> mm5 */ + /* form the alpha mult */ + movd_m2r(alpha, mm4); /* 0000000A -> mm4 */ + punpcklwd_r2r(mm4, mm4); /* 00000A0A -> mm4 */ + punpckldq_r2r(mm4, mm4); /* 0A0A0A0A -> mm4 */ + alpha = + (0xff << df->Rshift) | (0xff << df->Gshift) | (0xff << df-> + Bshift); + movd_m2r(alpha, mm0); /* 00000FFF -> mm0 */ + punpcklbw_r2r(mm0, mm0); /* 00FFFFFF -> mm0 */ + pand_r2r(mm0, mm4); /* 0A0A0A0A -> mm4, minus 1 chan */ + /* at this point mm4 can be 000A0A0A or 0A0A0A00 or another combo */ + movd_m2r(df->Amask, mm7); /* dst alpha mask */ + punpckldq_r2r(mm7, mm7); /* dst alpha mask | dst alpha mask -> mm7 */ + + while (height--) { + /* *INDENT-OFF* */ DUFFS_LOOP_DOUBLE2({ /* One Pixel Blend */ movd_m2r((*srcp), mm1);/* src(ARGB) -> mm1 (0000ARGB)*/ @@ -337,41 +353,44 @@ static void BlitRGBtoRGBSurfaceAlphaMMX(SDL_BlitInfo *info) srcp += 2; dstp += 2; }, width); - srcp += srcskip; - dstp += dstskip; - } - emms(); - } + /* *INDENT-ON* */ + srcp += srcskip; + dstp += dstskip; + } + emms(); + } } /* fast ARGB888->(A)RGB888 blending with pixel alpha */ -static void BlitRGBtoRGBPixelAlphaMMX(SDL_BlitInfo *info) +static void +BlitRGBtoRGBPixelAlphaMMX(SDL_BlitInfo * info) { - int width = info->d_width; - int height = info->d_height; - Uint32 *srcp = (Uint32 *)info->s_pixels; - int srcskip = info->s_skip >> 2; - Uint32 *dstp = (Uint32 *)info->d_pixels; - int dstskip = info->d_skip >> 2; - SDL_PixelFormat* sf = info->src; - Uint32 amask = sf->Amask; - - pxor_r2r(mm6, mm6); /* 0 -> mm6 */ - /* form multiplication mask */ - movd_m2r(sf->Amask, mm7); /* 0000F000 -> mm7 */ - punpcklbw_r2r(mm7, mm7); /* FF000000 -> mm7 */ - pcmpeqb_r2r(mm0, mm0); /* FFFFFFFF -> mm0 */ - movq_r2r(mm0, mm3); /* FFFFFFFF -> mm3 (for later) */ - pxor_r2r(mm0, mm7); /* 00FFFFFF -> mm7 (mult mask) */ - /* form channel masks */ - movq_r2r(mm7, mm0); /* 00FFFFFF -> mm0 */ - packsswb_r2r(mm6, mm0); /* 00000FFF -> mm0 (channel mask) */ - packsswb_r2r(mm6, mm3); /* 0000FFFF -> mm3 */ - pxor_r2r(mm0, mm3); /* 0000F000 -> mm3 (~channel mask) */ - /* get alpha channel shift */ - movd_m2r(sf->Ashift, mm5); /* Ashift -> mm5 */ - - while(height--) { + int width = info->d_width; + int height = info->d_height; + Uint32 *srcp = (Uint32 *) info->s_pixels; + int srcskip = info->s_skip >> 2; + Uint32 *dstp = (Uint32 *) info->d_pixels; + int dstskip = info->d_skip >> 2; + SDL_PixelFormat *sf = info->src; + Uint32 amask = sf->Amask; + + pxor_r2r(mm6, mm6); /* 0 -> mm6 */ + /* form multiplication mask */ + movd_m2r(sf->Amask, mm7); /* 0000F000 -> mm7 */ + punpcklbw_r2r(mm7, mm7); /* FF000000 -> mm7 */ + pcmpeqb_r2r(mm0, mm0); /* FFFFFFFF -> mm0 */ + movq_r2r(mm0, mm3); /* FFFFFFFF -> mm3 (for later) */ + pxor_r2r(mm0, mm7); /* 00FFFFFF -> mm7 (mult mask) */ + /* form channel masks */ + movq_r2r(mm7, mm0); /* 00FFFFFF -> mm0 */ + packsswb_r2r(mm6, mm0); /* 00000FFF -> mm0 (channel mask) */ + packsswb_r2r(mm6, mm3); /* 0000FFFF -> mm3 */ + pxor_r2r(mm0, mm3); /* 0000F000 -> mm3 (~channel mask) */ + /* get alpha channel shift */ + movd_m2r(sf->Ashift, mm5); /* Ashift -> mm5 */ + + while (height--) { + /* *INDENT-OFF* */ DUFFS_LOOP4({ Uint32 alpha = *srcp & amask; /* FIXME: Here we special-case opaque alpha since the @@ -416,185 +435,195 @@ static void BlitRGBtoRGBPixelAlphaMMX(SDL_BlitInfo *info) ++srcp; ++dstp; }, width); - srcp += srcskip; - dstp += dstskip; - } - emms(); + /* *INDENT-ON* */ + srcp += srcskip; + dstp += dstskip; + } + emms(); } + /* End GCC_ASMBLIT */ #elif MSVC_ASMBLIT /* fast RGB888->(A)RGB888 blending with surface alpha=128 special case */ -static void BlitRGBtoRGBSurfaceAlpha128MMX(SDL_BlitInfo *info) +static void +BlitRGBtoRGBSurfaceAlpha128MMX(SDL_BlitInfo * info) { - int width = info->d_width; - int height = info->d_height; - Uint32 *srcp = (Uint32 *)info->s_pixels; - int srcskip = info->s_skip >> 2; - Uint32 *dstp = (Uint32 *)info->d_pixels; - int dstskip = info->d_skip >> 2; - Uint32 dalpha = info->dst->Amask; - - __m64 src1, src2, dst1, dst2, lmask, hmask, dsta; - - hmask = _mm_set_pi32(0x00fefefe, 0x00fefefe); /* alpha128 mask -> hmask */ - lmask = _mm_set_pi32(0x00010101, 0x00010101); /* !alpha128 mask -> lmask */ - dsta = _mm_set_pi32(dalpha, dalpha); /* dst alpha mask -> dsta */ - - while (height--) { - int n = width; - if ( n & 1 ) { - Uint32 s = *srcp++; - Uint32 d = *dstp; - *dstp++ = ((((s & 0x00fefefe) + (d & 0x00fefefe)) >> 1) - + (s & d & 0x00010101)) | dalpha; - n--; - } - - for (n >>= 1; n > 0; --n) { - dst1 = *(__m64*)dstp; /* 2 x dst -> dst1(ARGBARGB) */ - dst2 = dst1; /* 2 x dst -> dst2(ARGBARGB) */ - - src1 = *(__m64*)srcp; /* 2 x src -> src1(ARGBARGB) */ - src2 = src1; /* 2 x src -> src2(ARGBARGB) */ - - dst2 = _mm_and_si64(dst2, hmask); /* dst & mask -> dst2 */ - src2 = _mm_and_si64(src2, hmask); /* src & mask -> src2 */ - src2 = _mm_add_pi32(src2, dst2); /* dst2 + src2 -> src2 */ - src2 = _mm_srli_pi32(src2, 1); /* src2 >> 1 -> src2 */ - - dst1 = _mm_and_si64(dst1, src1); /* src & dst -> dst1 */ - dst1 = _mm_and_si64(dst1, lmask); /* dst1 & !mask -> dst1 */ - dst1 = _mm_add_pi32(dst1, src2); /* src2 + dst1 -> dst1 */ - dst1 = _mm_or_si64(dst1, dsta); /* dsta(full alpha) | dst1 -> dst1 */ - - *(__m64*)dstp = dst1; /* dst1 -> 2 x dst pixels */ - dstp += 2; - srcp += 2; - } - - srcp += srcskip; - dstp += dstskip; - } - _mm_empty(); + int width = info->d_width; + int height = info->d_height; + Uint32 *srcp = (Uint32 *) info->s_pixels; + int srcskip = info->s_skip >> 2; + Uint32 *dstp = (Uint32 *) info->d_pixels; + int dstskip = info->d_skip >> 2; + Uint32 dalpha = info->dst->Amask; + + __m64 src1, src2, dst1, dst2, lmask, hmask, dsta; + + hmask = _mm_set_pi32(0x00fefefe, 0x00fefefe); /* alpha128 mask -> hmask */ + lmask = _mm_set_pi32(0x00010101, 0x00010101); /* !alpha128 mask -> lmask */ + dsta = _mm_set_pi32(dalpha, dalpha); /* dst alpha mask -> dsta */ + + while (height--) { + int n = width; + if (n & 1) { + Uint32 s = *srcp++; + Uint32 d = *dstp; + *dstp++ = ((((s & 0x00fefefe) + (d & 0x00fefefe)) >> 1) + + (s & d & 0x00010101)) | dalpha; + n--; + } + + for (n >>= 1; n > 0; --n) { + dst1 = *(__m64 *) dstp; /* 2 x dst -> dst1(ARGBARGB) */ + dst2 = dst1; /* 2 x dst -> dst2(ARGBARGB) */ + + src1 = *(__m64 *) srcp; /* 2 x src -> src1(ARGBARGB) */ + src2 = src1; /* 2 x src -> src2(ARGBARGB) */ + + dst2 = _mm_and_si64(dst2, hmask); /* dst & mask -> dst2 */ + src2 = _mm_and_si64(src2, hmask); /* src & mask -> src2 */ + src2 = _mm_add_pi32(src2, dst2); /* dst2 + src2 -> src2 */ + src2 = _mm_srli_pi32(src2, 1); /* src2 >> 1 -> src2 */ + + dst1 = _mm_and_si64(dst1, src1); /* src & dst -> dst1 */ + dst1 = _mm_and_si64(dst1, lmask); /* dst1 & !mask -> dst1 */ + dst1 = _mm_add_pi32(dst1, src2); /* src2 + dst1 -> dst1 */ + dst1 = _mm_or_si64(dst1, dsta); /* dsta(full alpha) | dst1 -> dst1 */ + + *(__m64 *) dstp = dst1; /* dst1 -> 2 x dst pixels */ + dstp += 2; + srcp += 2; + } + + srcp += srcskip; + dstp += dstskip; + } + _mm_empty(); } /* fast RGB888->(A)RGB888 blending with surface alpha */ -static void BlitRGBtoRGBSurfaceAlphaMMX(SDL_BlitInfo *info) +static void +BlitRGBtoRGBSurfaceAlphaMMX(SDL_BlitInfo * info) { - SDL_PixelFormat* df = info->dst; - Uint32 chanmask = df->Rmask | df->Gmask | df->Bmask; - unsigned alpha = info->src->alpha; - - if (alpha == 128 && (df->Rmask | df->Gmask | df->Bmask) == 0x00FFFFFF) { - /* only call a128 version when R,G,B occupy lower bits */ - BlitRGBtoRGBSurfaceAlpha128MMX(info); - } else { - int width = info->d_width; - int height = info->d_height; - Uint32 *srcp = (Uint32 *)info->s_pixels; - int srcskip = info->s_skip >> 2; - Uint32 *dstp = (Uint32 *)info->d_pixels; - int dstskip = info->d_skip >> 2; - Uint32 dalpha = df->Amask; - Uint32 amult; - - __m64 src1, src2, dst1, dst2, mm_alpha, mm_zero, dsta; - - mm_zero = _mm_setzero_si64(); /* 0 -> mm_zero */ - /* form the alpha mult */ - amult = alpha | (alpha << 8); - amult = amult | (amult << 16); - chanmask = (0xff << df->Rshift) | (0xff << df->Gshift) | (0xff << df->Bshift); - mm_alpha = _mm_set_pi32(0, amult & chanmask); /* 0000AAAA -> mm_alpha, minus 1 chan */ - mm_alpha = _mm_unpacklo_pi8(mm_alpha, mm_zero); /* 0A0A0A0A -> mm_alpha, minus 1 chan */ - /* at this point mm_alpha can be 000A0A0A or 0A0A0A00 or another combo */ - dsta = _mm_set_pi32(dalpha, dalpha); /* dst alpha mask -> dsta */ - - while (height--) { - int n = width; - if (n & 1) { - /* One Pixel Blend */ - src2 = _mm_cvtsi32_si64(*srcp); /* src(ARGB) -> src2 (0000ARGB)*/ - src2 = _mm_unpacklo_pi8(src2, mm_zero); /* 0A0R0G0B -> src2 */ + SDL_PixelFormat *df = info->dst; + Uint32 chanmask = df->Rmask | df->Gmask | df->Bmask; + unsigned alpha = info->src->alpha; - dst1 = _mm_cvtsi32_si64(*dstp); /* dst(ARGB) -> dst1 (0000ARGB)*/ - dst1 = _mm_unpacklo_pi8(dst1, mm_zero); /* 0A0R0G0B -> dst1 */ + if (alpha == 128 && (df->Rmask | df->Gmask | df->Bmask) == 0x00FFFFFF) { + /* only call a128 version when R,G,B occupy lower bits */ + BlitRGBtoRGBSurfaceAlpha128MMX(info); + } else { + int width = info->d_width; + int height = info->d_height; + Uint32 *srcp = (Uint32 *) info->s_pixels; + int srcskip = info->s_skip >> 2; + Uint32 *dstp = (Uint32 *) info->d_pixels; + int dstskip = info->d_skip >> 2; + Uint32 dalpha = df->Amask; + Uint32 amult; + + __m64 src1, src2, dst1, dst2, mm_alpha, mm_zero, dsta; + + mm_zero = _mm_setzero_si64(); /* 0 -> mm_zero */ + /* form the alpha mult */ + amult = alpha | (alpha << 8); + amult = amult | (amult << 16); + chanmask = + (0xff << df->Rshift) | (0xff << df->Gshift) | (0xff << df-> + Bshift); + mm_alpha = _mm_set_pi32(0, amult & chanmask); /* 0000AAAA -> mm_alpha, minus 1 chan */ + mm_alpha = _mm_unpacklo_pi8(mm_alpha, mm_zero); /* 0A0A0A0A -> mm_alpha, minus 1 chan */ + /* at this point mm_alpha can be 000A0A0A or 0A0A0A00 or another combo */ + dsta = _mm_set_pi32(dalpha, dalpha); /* dst alpha mask -> dsta */ + + while (height--) { + int n = width; + if (n & 1) { + /* One Pixel Blend */ + src2 = _mm_cvtsi32_si64(*srcp); /* src(ARGB) -> src2 (0000ARGB) */ + src2 = _mm_unpacklo_pi8(src2, mm_zero); /* 0A0R0G0B -> src2 */ + + dst1 = _mm_cvtsi32_si64(*dstp); /* dst(ARGB) -> dst1 (0000ARGB) */ + dst1 = _mm_unpacklo_pi8(dst1, mm_zero); /* 0A0R0G0B -> dst1 */ + + src2 = _mm_sub_pi16(src2, dst1); /* src2 - dst2 -> src2 */ + src2 = _mm_mullo_pi16(src2, mm_alpha); /* src2 * alpha -> src2 */ + src2 = _mm_srli_pi16(src2, 8); /* src2 >> 8 -> src2 */ + dst1 = _mm_add_pi8(src2, dst1); /* src2 + dst1 -> dst1 */ + + dst1 = _mm_packs_pu16(dst1, mm_zero); /* 0000ARGB -> dst1 */ + dst1 = _mm_or_si64(dst1, dsta); /* dsta | dst1 -> dst1 */ + *dstp = _mm_cvtsi64_si32(dst1); /* dst1 -> pixel */ + + ++srcp; + ++dstp; + + n--; + } - src2 = _mm_sub_pi16(src2, dst1); /* src2 - dst2 -> src2 */ - src2 = _mm_mullo_pi16(src2, mm_alpha); /* src2 * alpha -> src2 */ - src2 = _mm_srli_pi16(src2, 8); /* src2 >> 8 -> src2 */ - dst1 = _mm_add_pi8(src2, dst1); /* src2 + dst1 -> dst1 */ - - dst1 = _mm_packs_pu16(dst1, mm_zero); /* 0000ARGB -> dst1 */ - dst1 = _mm_or_si64(dst1, dsta); /* dsta | dst1 -> dst1 */ - *dstp = _mm_cvtsi64_si32(dst1); /* dst1 -> pixel */ + for (n >>= 1; n > 0; --n) { + /* Two Pixels Blend */ + src1 = *(__m64 *) srcp; /* 2 x src -> src1(ARGBARGB) */ + src2 = src1; /* 2 x src -> src2(ARGBARGB) */ + src1 = _mm_unpacklo_pi8(src1, mm_zero); /* low - 0A0R0G0B -> src1 */ + src2 = _mm_unpackhi_pi8(src2, mm_zero); /* high - 0A0R0G0B -> src2 */ - ++srcp; - ++dstp; - - n--; - } + dst1 = *(__m64 *) dstp; /* 2 x dst -> dst1(ARGBARGB) */ + dst2 = dst1; /* 2 x dst -> dst2(ARGBARGB) */ + dst1 = _mm_unpacklo_pi8(dst1, mm_zero); /* low - 0A0R0G0B -> dst1 */ + dst2 = _mm_unpackhi_pi8(dst2, mm_zero); /* high - 0A0R0G0B -> dst2 */ - for (n >>= 1; n > 0; --n) { - /* Two Pixels Blend */ - src1 = *(__m64*)srcp; /* 2 x src -> src1(ARGBARGB)*/ - src2 = src1; /* 2 x src -> src2(ARGBARGB) */ - src1 = _mm_unpacklo_pi8(src1, mm_zero); /* low - 0A0R0G0B -> src1 */ - src2 = _mm_unpackhi_pi8(src2, mm_zero); /* high - 0A0R0G0B -> src2 */ - - dst1 = *(__m64*)dstp;/* 2 x dst -> dst1(ARGBARGB) */ - dst2 = dst1; /* 2 x dst -> dst2(ARGBARGB) */ - dst1 = _mm_unpacklo_pi8(dst1, mm_zero); /* low - 0A0R0G0B -> dst1 */ - dst2 = _mm_unpackhi_pi8(dst2, mm_zero); /* high - 0A0R0G0B -> dst2 */ - - src1 = _mm_sub_pi16(src1, dst1);/* src1 - dst1 -> src1 */ - src1 = _mm_mullo_pi16(src1, mm_alpha); /* src1 * alpha -> src1 */ - src1 = _mm_srli_pi16(src1, 8); /* src1 >> 8 -> src1 */ - dst1 = _mm_add_pi8(src1, dst1); /* src1 + dst1(dst1) -> dst1 */ - - src2 = _mm_sub_pi16(src2, dst2);/* src2 - dst2 -> src2 */ - src2 = _mm_mullo_pi16(src2, mm_alpha); /* src2 * alpha -> src2 */ - src2 = _mm_srli_pi16(src2, 8); /* src2 >> 8 -> src2 */ - dst2 = _mm_add_pi8(src2, dst2); /* src2 + dst2(dst2) -> dst2 */ - - dst1 = _mm_packs_pu16(dst1, dst2); /* 0A0R0G0B(res1), 0A0R0G0B(res2) -> dst1(ARGBARGB) */ - dst1 = _mm_or_si64(dst1, dsta); /* dsta | dst1 -> dst1 */ + src1 = _mm_sub_pi16(src1, dst1); /* src1 - dst1 -> src1 */ + src1 = _mm_mullo_pi16(src1, mm_alpha); /* src1 * alpha -> src1 */ + src1 = _mm_srli_pi16(src1, 8); /* src1 >> 8 -> src1 */ + dst1 = _mm_add_pi8(src1, dst1); /* src1 + dst1(dst1) -> dst1 */ - *(__m64*)dstp = dst1; /* dst1 -> 2 x pixel */ + src2 = _mm_sub_pi16(src2, dst2); /* src2 - dst2 -> src2 */ + src2 = _mm_mullo_pi16(src2, mm_alpha); /* src2 * alpha -> src2 */ + src2 = _mm_srli_pi16(src2, 8); /* src2 >> 8 -> src2 */ + dst2 = _mm_add_pi8(src2, dst2); /* src2 + dst2(dst2) -> dst2 */ - srcp += 2; - dstp += 2; - } - srcp += srcskip; - dstp += dstskip; - } - _mm_empty(); - } + dst1 = _mm_packs_pu16(dst1, dst2); /* 0A0R0G0B(res1), 0A0R0G0B(res2) -> dst1(ARGBARGB) */ + dst1 = _mm_or_si64(dst1, dsta); /* dsta | dst1 -> dst1 */ + + *(__m64 *) dstp = dst1; /* dst1 -> 2 x pixel */ + + srcp += 2; + dstp += 2; + } + srcp += srcskip; + dstp += dstskip; + } + _mm_empty(); + } } /* fast ARGB888->(A)RGB888 blending with pixel alpha */ -static void BlitRGBtoRGBPixelAlphaMMX(SDL_BlitInfo *info) +static void +BlitRGBtoRGBPixelAlphaMMX(SDL_BlitInfo * info) { - int width = info->d_width; - int height = info->d_height; - Uint32 *srcp = (Uint32 *)info->s_pixels; - int srcskip = info->s_skip >> 2; - Uint32 *dstp = (Uint32 *)info->d_pixels; - int dstskip = info->d_skip >> 2; - SDL_PixelFormat* sf = info->src; - Uint32 chanmask = sf->Rmask | sf->Gmask | sf->Bmask; - Uint32 amask = sf->Amask; - Uint32 ashift = sf->Ashift; - Uint64 multmask; - - __m64 src1, dst1, mm_alpha, mm_zero, dmask; - - mm_zero = _mm_setzero_si64(); /* 0 -> mm_zero */ - multmask = ~(0xFFFFi64 << (ashift * 2)); - dmask = *(__m64*) &multmask; /* dst alpha mask -> dmask */ - - while(height--) { + int width = info->d_width; + int height = info->d_height; + Uint32 *srcp = (Uint32 *) info->s_pixels; + int srcskip = info->s_skip >> 2; + Uint32 *dstp = (Uint32 *) info->d_pixels; + int dstskip = info->d_skip >> 2; + SDL_PixelFormat *sf = info->src; + Uint32 chanmask = sf->Rmask | sf->Gmask | sf->Bmask; + Uint32 amask = sf->Amask; + Uint32 ashift = sf->Ashift; + Uint64 multmask; + + __m64 src1, dst1, mm_alpha, mm_zero, dmask; + + mm_zero = _mm_setzero_si64(); /* 0 -> mm_zero */ + /* *INDENT-OFF* */ + multmask = ~(0xFFFFI64 << (ashift * 2)); + /* *INDENT-ON* */ + dmask = *(__m64 *) & multmask; /* dst alpha mask -> dmask */ + + while (height--) { + /* *INDENT-OFF* */ DUFFS_LOOP4({ Uint32 alpha = *srcp & amask; if (alpha == 0) { @@ -627,11 +656,13 @@ static void BlitRGBtoRGBPixelAlphaMMX(SDL_BlitInfo *info) ++srcp; ++dstp; }, width); - srcp += srcskip; - dstp += dstskip; - } - _mm_empty(); + /* *INDENT-ON* */ + srcp += srcskip; + dstp += dstskip; + } + _mm_empty(); } + /* End MSVC_ASMBLIT */ #endif /* GCC_ASMBLIT, MSVC_ASMBLIT */ @@ -646,14 +677,14 @@ static void BlitRGBtoRGBPixelAlphaMMX(SDL_BlitInfo *info) #include #if (defined(__MACOSX__) && (__GNUC__ < 4)) - #define VECUINT8_LITERAL(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p) \ +#define VECUINT8_LITERAL(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p) \ (vector unsigned char) ( a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p ) - #define VECUINT16_LITERAL(a,b,c,d,e,f,g,h) \ +#define VECUINT16_LITERAL(a,b,c,d,e,f,g,h) \ (vector unsigned short) ( a,b,c,d,e,f,g,h ) #else - #define VECUINT8_LITERAL(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p) \ +#define VECUINT8_LITERAL(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p) \ (vector unsigned char) { a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p } - #define VECUINT16_LITERAL(a,b,c,d,e,f,g,h) \ +#define VECUINT16_LITERAL(a,b,c,d,e,f,g,h) \ (vector unsigned short) { a,b,c,d,e,f,g,h } #endif @@ -678,7 +709,7 @@ static void BlitRGBtoRGBPixelAlphaMMX(SDL_BlitInfo *info) ? vec_lvsl(0, src) \ : vec_add(vec_lvsl(8, src), vec_splat_u8(8))) - + #define VEC_MULTIPLY_ALPHA(vs, vd, valpha, mergePermute, v1_16, v8_16) do { \ /* vtemp1 contains source AAGGAAGGAAGGAAGG */ \ vector unsigned short vtemp1 = vec_mule(vs, valpha); \ @@ -704,10 +735,10 @@ static void BlitRGBtoRGBPixelAlphaMMX(SDL_BlitInfo *info) /* (>>8) and get ARGBARGBARGBARGB */ \ vd = (vector unsigned char)vec_perm(vtemp1, vtemp2, mergePermute); \ } while (0) - + /* Calculate the permute vector used for 32->32 swizzling */ -static vector unsigned char calc_swizzle32(const SDL_PixelFormat *srcfmt, - const SDL_PixelFormat *dstfmt) +static vector unsigned char +calc_swizzle32(const SDL_PixelFormat * srcfmt, const SDL_PixelFormat * dstfmt) { /* * We have to assume that the bits that aren't used by other @@ -720,18 +751,19 @@ static vector unsigned char calc_swizzle32(const SDL_PixelFormat *srcfmt, 0, 0, 0, 0, 16, 8, 0, 24, 0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000, - 0, 0}; + 0, 0 + }; if (!srcfmt) { srcfmt = &default_pixel_format; } if (!dstfmt) { dstfmt = &default_pixel_format; } - const vector unsigned char plus = VECUINT8_LITERAL - ( 0x00, 0x00, 0x00, 0x00, - 0x04, 0x04, 0x04, 0x04, - 0x08, 0x08, 0x08, 0x08, - 0x0C, 0x0C, 0x0C, 0x0C ); + const vector unsigned char plus = VECUINT8_LITERAL(0x00, 0x00, 0x00, 0x00, + 0x04, 0x04, 0x04, 0x04, + 0x08, 0x08, 0x08, 0x08, + 0x0C, 0x0C, 0x0C, + 0x0C); vector unsigned char vswiz; vector unsigned int srcvec; #define RESHIFT(X) (3 - ((X) >> 3)) @@ -741,22 +773,27 @@ static vector unsigned char calc_swizzle32(const SDL_PixelFormat *srcfmt, Uint32 amask; /* Use zero for alpha if either surface doesn't have alpha */ if (dstfmt->Amask) { - amask = ((srcfmt->Amask) ? RESHIFT(srcfmt->Ashift) : 0x10) << (dstfmt->Ashift); + amask = + ((srcfmt->Amask) ? RESHIFT(srcfmt->Ashift) : 0x10) << (dstfmt-> + Ashift); } else { - amask = 0x10101010 & ((dstfmt->Rmask | dstfmt->Gmask | dstfmt->Bmask) ^ 0xFFFFFFFF); + amask = + 0x10101010 & ((dstfmt->Rmask | dstfmt->Gmask | dstfmt->Bmask) ^ + 0xFFFFFFFF); } -#undef RESHIFT - ((unsigned int *)(char*)&srcvec)[0] = (rmask | gmask | bmask | amask); - vswiz = vec_add(plus, (vector unsigned char)vec_splat(srcvec, 0)); - return(vswiz); +#undef RESHIFT + ((unsigned int *) (char *) &srcvec)[0] = (rmask | gmask | bmask | amask); + vswiz = vec_add(plus, (vector unsigned char) vec_splat(srcvec, 0)); + return (vswiz); } -static void Blit32to565PixelAlphaAltivec(SDL_BlitInfo *info) +static void +Blit32to565PixelAlphaAltivec(SDL_BlitInfo * info) { int height = info->d_height; - Uint8 *src = (Uint8 *)info->s_pixels; + Uint8 *src = (Uint8 *) info->s_pixels; int srcskip = info->s_skip; - Uint8 *dst = (Uint8 *)info->d_pixels; + Uint8 *dst = (Uint8 *) info->d_pixels; int dstskip = info->d_skip; SDL_PixelFormat *srcfmt = info->src; @@ -767,66 +804,63 @@ static void Blit32to565PixelAlphaAltivec(SDL_BlitInfo *info) vector unsigned short v3_16 = vec_splat_u16(3); vector unsigned int v8_32 = vec_splat_u32(8); vector unsigned int v16_32 = vec_add(v8_32, v8_32); - vector unsigned short v3f = VECUINT16_LITERAL( - 0x003f, 0x003f, 0x003f, 0x003f, - 0x003f, 0x003f, 0x003f, 0x003f); - vector unsigned short vfc = VECUINT16_LITERAL( - 0x00fc, 0x00fc, 0x00fc, 0x00fc, - 0x00fc, 0x00fc, 0x00fc, 0x00fc); + vector unsigned short v3f = + VECUINT16_LITERAL(0x003f, 0x003f, 0x003f, 0x003f, + 0x003f, 0x003f, 0x003f, 0x003f); + vector unsigned short vfc = + VECUINT16_LITERAL(0x00fc, 0x00fc, 0x00fc, 0x00fc, + 0x00fc, 0x00fc, 0x00fc, 0x00fc); /* - 0x10 - 0x1f is the alpha - 0x00 - 0x0e evens are the red - 0x01 - 0x0f odds are zero - */ - vector unsigned char vredalpha1 = VECUINT8_LITERAL( - 0x10, 0x00, 0x01, 0x01, - 0x10, 0x02, 0x01, 0x01, - 0x10, 0x04, 0x01, 0x01, - 0x10, 0x06, 0x01, 0x01 - ); - vector unsigned char vredalpha2 = (vector unsigned char)( - vec_add((vector unsigned int)vredalpha1, vec_sl(v8_32, v16_32)) - ); + 0x10 - 0x1f is the alpha + 0x00 - 0x0e evens are the red + 0x01 - 0x0f odds are zero + */ + vector unsigned char vredalpha1 = VECUINT8_LITERAL(0x10, 0x00, 0x01, 0x01, + 0x10, 0x02, 0x01, 0x01, + 0x10, 0x04, 0x01, 0x01, + 0x10, 0x06, 0x01, + 0x01); + vector unsigned char vredalpha2 = + (vector unsigned char) (vec_add((vector unsigned int) vredalpha1, + vec_sl(v8_32, v16_32)) + ); /* - 0x00 - 0x0f is ARxx ARxx ARxx ARxx - 0x11 - 0x0f odds are blue - */ - vector unsigned char vblue1 = VECUINT8_LITERAL( - 0x00, 0x01, 0x02, 0x11, - 0x04, 0x05, 0x06, 0x13, - 0x08, 0x09, 0x0a, 0x15, - 0x0c, 0x0d, 0x0e, 0x17 - ); - vector unsigned char vblue2 = (vector unsigned char)( - vec_add((vector unsigned int)vblue1, v8_32) - ); + 0x00 - 0x0f is ARxx ARxx ARxx ARxx + 0x11 - 0x0f odds are blue + */ + vector unsigned char vblue1 = VECUINT8_LITERAL(0x00, 0x01, 0x02, 0x11, + 0x04, 0x05, 0x06, 0x13, + 0x08, 0x09, 0x0a, 0x15, + 0x0c, 0x0d, 0x0e, 0x17); + vector unsigned char vblue2 = + (vector unsigned char) (vec_add((vector unsigned int) vblue1, v8_32) + ); /* - 0x00 - 0x0f is ARxB ARxB ARxB ARxB - 0x10 - 0x0e evens are green - */ - vector unsigned char vgreen1 = VECUINT8_LITERAL( - 0x00, 0x01, 0x10, 0x03, - 0x04, 0x05, 0x12, 0x07, - 0x08, 0x09, 0x14, 0x0b, - 0x0c, 0x0d, 0x16, 0x0f - ); - vector unsigned char vgreen2 = (vector unsigned char)( - vec_add((vector unsigned int)vgreen1, vec_sl(v8_32, v8_32)) - ); - vector unsigned char vgmerge = VECUINT8_LITERAL( - 0x00, 0x02, 0x00, 0x06, - 0x00, 0x0a, 0x00, 0x0e, - 0x00, 0x12, 0x00, 0x16, - 0x00, 0x1a, 0x00, 0x1e); + 0x00 - 0x0f is ARxB ARxB ARxB ARxB + 0x10 - 0x0e evens are green + */ + vector unsigned char vgreen1 = VECUINT8_LITERAL(0x00, 0x01, 0x10, 0x03, + 0x04, 0x05, 0x12, 0x07, + 0x08, 0x09, 0x14, 0x0b, + 0x0c, 0x0d, 0x16, 0x0f); + vector unsigned char vgreen2 = + (vector unsigned + char) (vec_add((vector unsigned int) vgreen1, vec_sl(v8_32, v8_32)) + ); + vector unsigned char vgmerge = VECUINT8_LITERAL(0x00, 0x02, 0x00, 0x06, + 0x00, 0x0a, 0x00, 0x0e, + 0x00, 0x12, 0x00, 0x16, + 0x00, 0x1a, 0x00, 0x1e); vector unsigned char mergePermute = VEC_MERGE_PERMUTE(); vector unsigned char vpermute = calc_swizzle32(srcfmt, NULL); - vector unsigned char valphaPermute = vec_and(vec_lvsl(0, (int *)NULL), vec_splat_u8(0xC)); + vector unsigned char valphaPermute = + vec_and(vec_lvsl(0, (int *) NULL), vec_splat_u8(0xC)); - vector unsigned short vf800 = (vector unsigned short)vec_splat_u8(-7); + vector unsigned short vf800 = (vector unsigned short) vec_splat_u8(-7); vf800 = vec_sl(vf800, vec_splat_u16(8)); - while(height--) { + while (height--) { int extrawidth; vector unsigned char valigner; vector unsigned char vsrc; @@ -855,7 +889,7 @@ static void Blit32to565PixelAlphaAltivec(SDL_BlitInfo *info) ONE_PIXEL_BLEND((UNALIGNED_PTR(dst)) && (width), width); extrawidth = (width % 8); valigner = VEC_ALIGNER(src); - vsrc = (vector unsigned char)vec_ld(0, src); + vsrc = (vector unsigned char) vec_ld(0, src); width -= extrawidth; while (width) { vector unsigned char valpha; @@ -865,44 +899,57 @@ static void Blit32to565PixelAlphaAltivec(SDL_BlitInfo *info) vector unsigned short vpixel, vrpixel, vgpixel, vbpixel; /* Load 8 pixels from src as ARGB */ - voverflow = (vector unsigned char)vec_ld(15, src); + voverflow = (vector unsigned char) vec_ld(15, src); vsrc = vec_perm(vsrc, voverflow, valigner); vsrc1 = vec_perm(vsrc, vsrc, vpermute); src += 16; - vsrc = (vector unsigned char)vec_ld(15, src); + vsrc = (vector unsigned char) vec_ld(15, src); voverflow = vec_perm(voverflow, vsrc, valigner); vsrc2 = vec_perm(voverflow, voverflow, vpermute); src += 16; /* Load 8 pixels from dst as XRGB */ voverflow = vec_ld(0, dst); - vR = vec_and((vector unsigned short)voverflow, vf800); - vB = vec_sl((vector unsigned short)voverflow, v3_16); + vR = vec_and((vector unsigned short) voverflow, vf800); + vB = vec_sl((vector unsigned short) voverflow, v3_16); vG = vec_sl(vB, v2_16); - vdst1 = (vector unsigned char)vec_perm((vector unsigned char)vR, (vector unsigned char)vR, vredalpha1); - vdst1 = vec_perm(vdst1, (vector unsigned char)vB, vblue1); - vdst1 = vec_perm(vdst1, (vector unsigned char)vG, vgreen1); - vdst2 = (vector unsigned char)vec_perm((vector unsigned char)vR, (vector unsigned char)vR, vredalpha2); - vdst2 = vec_perm(vdst2, (vector unsigned char)vB, vblue2); - vdst2 = vec_perm(vdst2, (vector unsigned char)vG, vgreen2); + vdst1 = + (vector unsigned char) vec_perm((vector unsigned char) vR, + (vector unsigned char) vR, + vredalpha1); + vdst1 = vec_perm(vdst1, (vector unsigned char) vB, vblue1); + vdst1 = vec_perm(vdst1, (vector unsigned char) vG, vgreen1); + vdst2 = + (vector unsigned char) vec_perm((vector unsigned char) vR, + (vector unsigned char) vR, + vredalpha2); + vdst2 = vec_perm(vdst2, (vector unsigned char) vB, vblue2); + vdst2 = vec_perm(vdst2, (vector unsigned char) vG, vgreen2); /* Alpha blend 8 pixels as ARGB */ valpha = vec_perm(vsrc1, v0, valphaPermute); - VEC_MULTIPLY_ALPHA(vsrc1, vdst1, valpha, mergePermute, v1_16, v8_16); + VEC_MULTIPLY_ALPHA(vsrc1, vdst1, valpha, mergePermute, v1_16, + v8_16); valpha = vec_perm(vsrc2, v0, valphaPermute); - VEC_MULTIPLY_ALPHA(vsrc2, vdst2, valpha, mergePermute, v1_16, v8_16); + VEC_MULTIPLY_ALPHA(vsrc2, vdst2, valpha, mergePermute, v1_16, + v8_16); /* Convert 8 pixels to 565 */ - vpixel = (vector unsigned short)vec_packpx((vector unsigned int)vdst1, (vector unsigned int)vdst2); - vgpixel = (vector unsigned short)vec_perm(vdst1, vdst2, vgmerge); + vpixel = (vector unsigned short) vec_packpx((vector unsigned int) + vdst1, + (vector unsigned int) + vdst2); + vgpixel = (vector unsigned short) vec_perm(vdst1, vdst2, vgmerge); vgpixel = vec_and(vgpixel, vfc); vgpixel = vec_sl(vgpixel, v3_16); vrpixel = vec_sl(vpixel, v1_16); vrpixel = vec_and(vrpixel, vf800); vbpixel = vec_and(vpixel, v3f); - vdst1 = vec_or((vector unsigned char)vrpixel, (vector unsigned char)vgpixel); - vdst1 = vec_or(vdst1, (vector unsigned char)vbpixel); - + vdst1 = + vec_or((vector unsigned char) vrpixel, + (vector unsigned char) vgpixel); + vdst1 = vec_or(vdst1, (vector unsigned char) vbpixel); + /* Store 8 pixels */ vec_st(vdst1, 0, dst); @@ -916,13 +963,14 @@ static void Blit32to565PixelAlphaAltivec(SDL_BlitInfo *info) } } -static void Blit32to32SurfaceAlphaKeyAltivec(SDL_BlitInfo *info) +static void +Blit32to32SurfaceAlphaKeyAltivec(SDL_BlitInfo * info) { unsigned alpha = info->src->alpha; int height = info->d_height; - Uint32 *srcp = (Uint32 *)info->s_pixels; + Uint32 *srcp = (Uint32 *) info->s_pixels; int srcskip = info->s_skip >> 2; - Uint32 *dstp = (Uint32 *)info->d_pixels; + Uint32 *dstp = (Uint32 *) info->d_pixels; int dstskip = info->d_skip >> 2; SDL_PixelFormat *srcfmt = info->src; SDL_PixelFormat *dstfmt = info->dst; @@ -956,17 +1004,17 @@ static void Blit32to32SurfaceAlphaKeyAltivec(SDL_BlitInfo *info) vsdstPermute = calc_swizzle32(dstfmt, NULL); /* set a vector full of alpha and 255-alpha */ - ((unsigned char *)&valpha)[0] = alpha; + ((unsigned char *) &valpha)[0] = alpha; valpha = vec_splat(valpha, 0); - vbits = (vector unsigned char)vec_splat_s8(-1); + vbits = (vector unsigned char) vec_splat_s8(-1); ckey &= rgbmask; - ((unsigned int *)(char*)&vckey)[0] = ckey; + ((unsigned int *) (char *) &vckey)[0] = ckey; vckey = vec_splat(vckey, 0); - ((unsigned int *)(char*)&vrgbmask)[0] = rgbmask; + ((unsigned int *) (char *) &vrgbmask)[0] = rgbmask; vrgbmask = vec_splat(vrgbmask, 0); - while(height--) { + while (height--) { int width = info->d_width; #define ONE_PIXEL_BLEND(condition, widthvar) \ while (condition) { \ @@ -987,7 +1035,7 @@ static void Blit32to32SurfaceAlphaKeyAltivec(SDL_BlitInfo *info) if (width > 0) { int extrawidth = (width % 4); vector unsigned char valigner = VEC_ALIGNER(srcp); - vector unsigned char vs = (vector unsigned char)vec_ld(0, srcp); + vector unsigned char vs = (vector unsigned char) vec_ld(0, srcp); width -= extrawidth; while (width) { vector unsigned char vsel; @@ -996,18 +1044,21 @@ static void Blit32to32SurfaceAlphaKeyAltivec(SDL_BlitInfo *info) vector unsigned char vd_orig; /* s = *srcp */ - voverflow = (vector unsigned char)vec_ld(15, srcp); + voverflow = (vector unsigned char) vec_ld(15, srcp); vs = vec_perm(vs, voverflow, valigner); - + /* vsel is set for items that match the key */ - vsel = (vector unsigned char)vec_and((vector unsigned int)vs, vrgbmask); - vsel = (vector unsigned char)vec_cmpeq((vector unsigned int)vsel, vckey); + vsel = + (vector unsigned char) vec_and((vector unsigned int) vs, + vrgbmask); + vsel = (vector unsigned char) vec_cmpeq((vector unsigned int) + vsel, vckey); /* permute to source format */ vs = vec_perm(vs, valpha, vsrcPermute); /* d = *dstp */ - vd = (vector unsigned char)vec_ld(0, dstp); + vd = (vector unsigned char) vec_ld(0, dstp); vd_orig = vd = vec_perm(vd, v0, vsdstPermute); VEC_MULTIPLY_ALPHA(vs, vd, valpha, mergePermute, v1, v8); @@ -1017,13 +1068,13 @@ static void Blit32to32SurfaceAlphaKeyAltivec(SDL_BlitInfo *info) /* mask out color key */ vd = vec_sel(vd, vd_orig, vsel); - + /* permute to dest format */ vd = vec_perm(vd, vbits, vdstPermute); /* *dstp = res */ - vec_st((vector unsigned int)vd, 0, dstp); - + vec_st((vector unsigned int) vd, 0, dstp); + srcp += 4; dstp += 4; width -= 4; @@ -1032,20 +1083,21 @@ static void Blit32to32SurfaceAlphaKeyAltivec(SDL_BlitInfo *info) ONE_PIXEL_BLEND((extrawidth), extrawidth); } #undef ONE_PIXEL_BLEND - + srcp += srcskip; dstp += dstskip; } } -static void Blit32to32PixelAlphaAltivec(SDL_BlitInfo *info) +static void +Blit32to32PixelAlphaAltivec(SDL_BlitInfo * info) { int width = info->d_width; int height = info->d_height; - Uint32 *srcp = (Uint32 *)info->s_pixels; + Uint32 *srcp = (Uint32 *) info->s_pixels; int srcskip = info->s_skip >> 2; - Uint32 *dstp = (Uint32 *)info->d_pixels; + Uint32 *dstp = (Uint32 *) info->d_pixels; int dstskip = info->d_skip >> 2; SDL_PixelFormat *srcfmt = info->src; SDL_PixelFormat *dstfmt = info->dst; @@ -1065,13 +1117,13 @@ static void Blit32to32PixelAlphaAltivec(SDL_BlitInfo *info) v8 = vec_splat_u16(8); mergePermute = VEC_MERGE_PERMUTE(); valphamask = VEC_ALPHA_MASK(); - valphaPermute = vec_and(vec_lvsl(0, (int *)NULL), vec_splat_u8(0xC)); + valphaPermute = vec_and(vec_lvsl(0, (int *) NULL), vec_splat_u8(0xC)); vpixelmask = vec_nor(valphamask, v0); vsrcPermute = calc_swizzle32(srcfmt, NULL); vdstPermute = calc_swizzle32(NULL, dstfmt); vsdstPermute = calc_swizzle32(dstfmt, NULL); - while ( height-- ) { + while (height--) { width = info->d_width; #define ONE_PIXEL_BLEND(condition, widthvar) while ((condition)) { \ Uint32 Pixel; \ @@ -1092,7 +1144,7 @@ static void Blit32to32PixelAlphaAltivec(SDL_BlitInfo *info) /* vdstPermute */ int extrawidth = (width % 4); vector unsigned char valigner = VEC_ALIGNER(srcp); - vector unsigned char vs = (vector unsigned char)vec_ld(0, srcp); + vector unsigned char vs = (vector unsigned char) vec_ld(0, srcp); width -= extrawidth; while (width) { vector unsigned char voverflow; @@ -1100,14 +1152,14 @@ static void Blit32to32PixelAlphaAltivec(SDL_BlitInfo *info) vector unsigned char valpha; vector unsigned char vdstalpha; /* s = *srcp */ - voverflow = (vector unsigned char)vec_ld(15, srcp); + voverflow = (vector unsigned char) vec_ld(15, srcp); vs = vec_perm(vs, voverflow, valigner); vs = vec_perm(vs, v0, vsrcPermute); valpha = vec_perm(vs, v0, valphaPermute); - + /* d = *dstp */ - vd = (vector unsigned char)vec_ld(0, dstp); + vd = (vector unsigned char) vec_ld(0, dstp); vd = vec_perm(vd, v0, vsdstPermute); vdstalpha = vec_and(vd, valphamask); @@ -1119,8 +1171,8 @@ static void Blit32to32PixelAlphaAltivec(SDL_BlitInfo *info) vd = vec_perm(vd, v0, vdstPermute); /* *dstp = res */ - vec_st((vector unsigned int)vd, 0, dstp); - + vec_st((vector unsigned int) vd, 0, dstp); + srcp += 4; dstp += 4; width -= 4; @@ -1129,21 +1181,22 @@ static void Blit32to32PixelAlphaAltivec(SDL_BlitInfo *info) } ONE_PIXEL_BLEND((extrawidth), extrawidth); } - srcp += srcskip; - dstp += dstskip; + srcp += srcskip; + dstp += dstskip; #undef ONE_PIXEL_BLEND - } + } } /* fast ARGB888->(A)RGB888 blending with pixel alpha */ -static void BlitRGBtoRGBPixelAlphaAltivec(SDL_BlitInfo *info) +static void +BlitRGBtoRGBPixelAlphaAltivec(SDL_BlitInfo * info) { - int width = info->d_width; - int height = info->d_height; - Uint32 *srcp = (Uint32 *)info->s_pixels; - int srcskip = info->s_skip >> 2; - Uint32 *dstp = (Uint32 *)info->d_pixels; - int dstskip = info->d_skip >> 2; + int width = info->d_width; + int height = info->d_height; + Uint32 *srcp = (Uint32 *) info->s_pixels; + int srcskip = info->s_skip >> 2; + Uint32 *dstp = (Uint32 *) info->d_pixels; + int dstskip = info->d_skip >> 2; vector unsigned char mergePermute; vector unsigned char valphaPermute; vector unsigned char valphamask; @@ -1156,11 +1209,11 @@ static void BlitRGBtoRGBPixelAlphaAltivec(SDL_BlitInfo *info) v8 = vec_splat_u16(8); mergePermute = VEC_MERGE_PERMUTE(); valphamask = VEC_ALPHA_MASK(); - valphaPermute = vec_and(vec_lvsl(0, (int *)NULL), vec_splat_u8(0xC)); - - + valphaPermute = vec_and(vec_lvsl(0, (int *) NULL), vec_splat_u8(0xC)); + + vpixelmask = vec_nor(valphamask, v0); - while(height--) { + while (height--) { width = info->d_width; #define ONE_PIXEL_BLEND(condition, widthvar) \ while ((condition)) { \ @@ -1193,7 +1246,7 @@ static void BlitRGBtoRGBPixelAlphaAltivec(SDL_BlitInfo *info) if (width > 0) { int extrawidth = (width % 4); vector unsigned char valigner = VEC_ALIGNER(srcp); - vector unsigned char vs = (vector unsigned char)vec_ld(0, srcp); + vector unsigned char vs = (vector unsigned char) vec_ld(0, srcp); width -= extrawidth; while (width) { vector unsigned char voverflow; @@ -1201,13 +1254,13 @@ static void BlitRGBtoRGBPixelAlphaAltivec(SDL_BlitInfo *info) vector unsigned char valpha; vector unsigned char vdstalpha; /* s = *srcp */ - voverflow = (vector unsigned char)vec_ld(15, srcp); + voverflow = (vector unsigned char) vec_ld(15, srcp); vs = vec_perm(vs, voverflow, valigner); valpha = vec_perm(vs, v0, valphaPermute); - + /* d = *dstp */ - vd = (vector unsigned char)vec_ld(0, dstp); + vd = (vector unsigned char) vec_ld(0, dstp); vdstalpha = vec_and(vd, valphamask); VEC_MULTIPLY_ALPHA(vs, vd, valpha, mergePermute, v1, v8); @@ -1217,8 +1270,8 @@ static void BlitRGBtoRGBPixelAlphaAltivec(SDL_BlitInfo *info) vd = vec_or(vd, vdstalpha); /* *dstp = res */ - vec_st((vector unsigned int)vd, 0, dstp); - + vec_st((vector unsigned int) vd, 0, dstp); + srcp += 4; dstp += 4; width -= 4; @@ -1226,25 +1279,26 @@ static void BlitRGBtoRGBPixelAlphaAltivec(SDL_BlitInfo *info) } ONE_PIXEL_BLEND((extrawidth), extrawidth); } - srcp += srcskip; - dstp += dstskip; - } + srcp += srcskip; + dstp += dstskip; + } #undef ONE_PIXEL_BLEND } -static void Blit32to32SurfaceAlphaAltivec(SDL_BlitInfo *info) +static void +Blit32to32SurfaceAlphaAltivec(SDL_BlitInfo * info) { /* XXX : 6 */ - unsigned alpha = info->src->alpha; + unsigned alpha = info->src->alpha; int height = info->d_height; - Uint32 *srcp = (Uint32 *)info->s_pixels; + Uint32 *srcp = (Uint32 *) info->s_pixels; int srcskip = info->s_skip >> 2; - Uint32 *dstp = (Uint32 *)info->d_pixels; + Uint32 *dstp = (Uint32 *) info->d_pixels; int dstskip = info->d_skip >> 2; SDL_PixelFormat *srcfmt = info->src; SDL_PixelFormat *dstfmt = info->dst; - unsigned sA = srcfmt->alpha; - unsigned dA = dstfmt->Amask ? SDL_ALPHA_OPAQUE : 0; + unsigned sA = srcfmt->alpha; + unsigned dA = dstfmt->Amask ? SDL_ALPHA_OPAQUE : 0; vector unsigned char mergePermute; vector unsigned char vsrcPermute; vector unsigned char vdstPermute; @@ -1267,11 +1321,11 @@ static void Blit32to32SurfaceAlphaAltivec(SDL_BlitInfo *info) vsdstPermute = calc_swizzle32(dstfmt, NULL); /* set a vector full of alpha and 255-alpha */ - ((unsigned char *)&valpha)[0] = alpha; + ((unsigned char *) &valpha)[0] = alpha; valpha = vec_splat(valpha, 0); - vbits = (vector unsigned char)vec_splat_s8(-1); + vbits = (vector unsigned char) vec_splat_s8(-1); - while(height--) { + while (height--) { int width = info->d_width; #define ONE_PIXEL_BLEND(condition, widthvar) while ((condition)) { \ Uint32 Pixel; \ @@ -1288,19 +1342,19 @@ static void Blit32to32SurfaceAlphaAltivec(SDL_BlitInfo *info) if (width > 0) { int extrawidth = (width % 4); vector unsigned char valigner = vec_lvsl(0, srcp); - vector unsigned char vs = (vector unsigned char)vec_ld(0, srcp); + vector unsigned char vs = (vector unsigned char) vec_ld(0, srcp); width -= extrawidth; while (width) { vector unsigned char voverflow; vector unsigned char vd; /* s = *srcp */ - voverflow = (vector unsigned char)vec_ld(15, srcp); + voverflow = (vector unsigned char) vec_ld(15, srcp); vs = vec_perm(vs, voverflow, valigner); vs = vec_perm(vs, valpha, vsrcPermute); - + /* d = *dstp */ - vd = (vector unsigned char)vec_ld(0, dstp); + vd = (vector unsigned char) vec_ld(0, dstp); vd = vec_perm(vd, vd, vsdstPermute); VEC_MULTIPLY_ALPHA(vs, vd, valpha, mergePermute, v1, v8); @@ -1310,8 +1364,8 @@ static void Blit32to32SurfaceAlphaAltivec(SDL_BlitInfo *info) vd = vec_perm(vd, vbits, vdstPermute); /* *dstp = res */ - vec_st((vector unsigned int)vd, 0, dstp); - + vec_st((vector unsigned int) vd, 0, dstp); + srcp += 4; dstp += 4; width -= 4; @@ -1320,7 +1374,7 @@ static void Blit32to32SurfaceAlphaAltivec(SDL_BlitInfo *info) ONE_PIXEL_BLEND((extrawidth), extrawidth); } #undef ONE_PIXEL_BLEND - + srcp += srcskip; dstp += dstskip; } @@ -1329,13 +1383,14 @@ static void Blit32to32SurfaceAlphaAltivec(SDL_BlitInfo *info) /* fast RGB888->(A)RGB888 blending */ -static void BlitRGBtoRGBSurfaceAlphaAltivec(SDL_BlitInfo *info) +static void +BlitRGBtoRGBSurfaceAlphaAltivec(SDL_BlitInfo * info) { - unsigned alpha = info->src->alpha; + unsigned alpha = info->src->alpha; int height = info->d_height; - Uint32 *srcp = (Uint32 *)info->s_pixels; + Uint32 *srcp = (Uint32 *) info->s_pixels; int srcskip = info->s_skip >> 2; - Uint32 *dstp = (Uint32 *)info->d_pixels; + Uint32 *dstp = (Uint32 *) info->d_pixels; int dstskip = info->d_skip >> 2; vector unsigned char mergePermute; vector unsigned char valpha; @@ -1351,10 +1406,10 @@ static void BlitRGBtoRGBSurfaceAlphaAltivec(SDL_BlitInfo *info) valphamask = VEC_ALPHA_MASK(); /* set a vector full of alpha and 255-alpha */ - ((unsigned char *)&valpha)[0] = alpha; + ((unsigned char *) &valpha)[0] = alpha; valpha = vec_splat(valpha, 0); - while(height--) { + while (height--) { int width = info->d_width; #define ONE_PIXEL_BLEND(condition, widthvar) while ((condition)) { \ Uint32 s = *srcp; \ @@ -1375,18 +1430,18 @@ static void BlitRGBtoRGBSurfaceAlphaAltivec(SDL_BlitInfo *info) if (width > 0) { int extrawidth = (width % 4); vector unsigned char valigner = VEC_ALIGNER(srcp); - vector unsigned char vs = (vector unsigned char)vec_ld(0, srcp); + vector unsigned char vs = (vector unsigned char) vec_ld(0, srcp); width -= extrawidth; while (width) { vector unsigned char voverflow; vector unsigned char vd; /* s = *srcp */ - voverflow = (vector unsigned char)vec_ld(15, srcp); + voverflow = (vector unsigned char) vec_ld(15, srcp); vs = vec_perm(vs, voverflow, valigner); - + /* d = *dstp */ - vd = (vector unsigned char)vec_ld(0, dstp); + vd = (vector unsigned char) vec_ld(0, dstp); VEC_MULTIPLY_ALPHA(vs, vd, valpha, mergePermute, v1, v8); @@ -1394,8 +1449,8 @@ static void BlitRGBtoRGBSurfaceAlphaAltivec(SDL_BlitInfo *info) vd = vec_or(vd, valphamask); /* *dstp = res */ - vec_st((vector unsigned int)vd, 0, dstp); - + vec_st((vector unsigned int) vd, 0, dstp); + srcp += 4; dstp += 4; width -= 4; @@ -1404,57 +1459,63 @@ static void BlitRGBtoRGBSurfaceAlphaAltivec(SDL_BlitInfo *info) ONE_PIXEL_BLEND((extrawidth), extrawidth); } #undef ONE_PIXEL_BLEND - + srcp += srcskip; dstp += dstskip; } } + #if __MWERKS__ #pragma altivec_model off #endif #endif /* SDL_ALTIVEC_BLITTERS */ /* fast RGB888->(A)RGB888 blending with surface alpha=128 special case */ -static void BlitRGBtoRGBSurfaceAlpha128(SDL_BlitInfo *info) +static void +BlitRGBtoRGBSurfaceAlpha128(SDL_BlitInfo * info) { - int width = info->d_width; - int height = info->d_height; - Uint32 *srcp = (Uint32 *)info->s_pixels; - int srcskip = info->s_skip >> 2; - Uint32 *dstp = (Uint32 *)info->d_pixels; - int dstskip = info->d_skip >> 2; - - while(height--) { + int width = info->d_width; + int height = info->d_height; + Uint32 *srcp = (Uint32 *) info->s_pixels; + int srcskip = info->s_skip >> 2; + Uint32 *dstp = (Uint32 *) info->d_pixels; + int dstskip = info->d_skip >> 2; + + while (height--) { + /* *INDENT-OFF* */ DUFFS_LOOP4({ Uint32 s = *srcp++; Uint32 d = *dstp; *dstp++ = ((((s & 0x00fefefe) + (d & 0x00fefefe)) >> 1) + (s & d & 0x00010101)) | 0xff000000; }, width); - srcp += srcskip; - dstp += dstskip; - } + /* *INDENT-ON* */ + srcp += srcskip; + dstp += dstskip; + } } /* fast RGB888->(A)RGB888 blending with surface alpha */ -static void BlitRGBtoRGBSurfaceAlpha(SDL_BlitInfo *info) +static void +BlitRGBtoRGBSurfaceAlpha(SDL_BlitInfo * info) { - unsigned alpha = info->src->alpha; - if(alpha == 128) { - BlitRGBtoRGBSurfaceAlpha128(info); - } else { - int width = info->d_width; - int height = info->d_height; - Uint32 *srcp = (Uint32 *)info->s_pixels; - int srcskip = info->s_skip >> 2; - Uint32 *dstp = (Uint32 *)info->d_pixels; - int dstskip = info->d_skip >> 2; - Uint32 s; - Uint32 d; - Uint32 s1; - Uint32 d1; - - while(height--) { + unsigned alpha = info->src->alpha; + if (alpha == 128) { + BlitRGBtoRGBSurfaceAlpha128(info); + } else { + int width = info->d_width; + int height = info->d_height; + Uint32 *srcp = (Uint32 *) info->s_pixels; + int srcskip = info->s_skip >> 2; + Uint32 *dstp = (Uint32 *) info->d_pixels; + int dstskip = info->d_skip >> 2; + Uint32 s; + Uint32 d; + Uint32 s1; + Uint32 d1; + + while (height--) { + /* *INDENT-OFF* */ DUFFS_LOOP_DOUBLE2({ /* One Pixel Blend */ s = *srcp; @@ -1499,23 +1560,26 @@ static void BlitRGBtoRGBSurfaceAlpha(SDL_BlitInfo *info) ++srcp; ++dstp; }, width); - srcp += srcskip; - dstp += dstskip; - } - } + /* *INDENT-ON* */ + srcp += srcskip; + dstp += dstskip; + } + } } /* fast ARGB888->(A)RGB888 blending with pixel alpha */ -static void BlitRGBtoRGBPixelAlpha(SDL_BlitInfo *info) +static void +BlitRGBtoRGBPixelAlpha(SDL_BlitInfo * info) { - int width = info->d_width; - int height = info->d_height; - Uint32 *srcp = (Uint32 *)info->s_pixels; - int srcskip = info->s_skip >> 2; - Uint32 *dstp = (Uint32 *)info->d_pixels; - int dstskip = info->d_skip >> 2; - - while(height--) { + int width = info->d_width; + int height = info->d_height; + Uint32 *srcp = (Uint32 *) info->s_pixels; + int srcskip = info->s_skip >> 2; + Uint32 *dstp = (Uint32 *) info->d_pixels; + int dstskip = info->d_skip >> 2; + + while (height--) { + /* *INDENT-OFF* */ DUFFS_LOOP4({ Uint32 dalpha; Uint32 d; @@ -1549,48 +1613,47 @@ static void BlitRGBtoRGBPixelAlpha(SDL_BlitInfo *info) ++srcp; ++dstp; }, width); - srcp += srcskip; - dstp += dstskip; - } + /* *INDENT-ON* */ + srcp += srcskip; + dstp += dstskip; + } } #if GCC_ASMBLIT /* fast (as in MMX with prefetch) ARGB888->(A)RGB888 blending with pixel alpha */ -inline static void BlitRGBtoRGBPixelAlphaMMX3DNOW(SDL_BlitInfo *info) +inline static void +BlitRGBtoRGBPixelAlphaMMX3DNOW(SDL_BlitInfo * info) { - int width = info->d_width; - int height = info->d_height; - Uint32 *srcp = (Uint32 *)info->s_pixels; - int srcskip = info->s_skip >> 2; - Uint32 *dstp = (Uint32 *)info->d_pixels; - int dstskip = info->d_skip >> 2; - SDL_PixelFormat* sf = info->src; - Uint32 amask = sf->Amask; - - __asm__ ( - /* make mm6 all zeros. */ - "pxor %%mm6, %%mm6\n" - - /* Make a mask to preserve the alpha. */ - "movd %0, %%mm7\n\t" /* 0000F000 -> mm7 */ - "punpcklbw %%mm7, %%mm7\n\t" /* FF000000 -> mm7 */ - "pcmpeqb %%mm4, %%mm4\n\t" /* FFFFFFFF -> mm4 */ - "movq %%mm4, %%mm3\n\t" /* FFFFFFFF -> mm3 (for later) */ - "pxor %%mm4, %%mm7\n\t" /* 00FFFFFF -> mm7 (mult mask) */ - - /* form channel masks */ - "movq %%mm7, %%mm4\n\t" /* 00FFFFFF -> mm4 */ - "packsswb %%mm6, %%mm4\n\t" /* 00000FFF -> mm4 (channel mask) */ - "packsswb %%mm6, %%mm3\n\t" /* 0000FFFF -> mm3 */ - "pxor %%mm4, %%mm3\n\t" /* 0000F000 -> mm3 (~channel mask) */ - - /* get alpha channel shift */ - "movd %1, %%mm5\n\t" /* Ashift -> mm5 */ - - : /* nothing */ : "m" (sf->Amask), "m" (sf->Ashift) ); - - while(height--) { - + int width = info->d_width; + int height = info->d_height; + Uint32 *srcp = (Uint32 *) info->s_pixels; + int srcskip = info->s_skip >> 2; + Uint32 *dstp = (Uint32 *) info->d_pixels; + int dstskip = info->d_skip >> 2; + SDL_PixelFormat *sf = info->src; + Uint32 amask = sf->Amask; + + __asm__( + /* make mm6 all zeros. */ + "pxor %%mm6, %%mm6\n" + /* Make a mask to preserve the alpha. */ + "movd %0, %%mm7\n\t" /* 0000F000 -> mm7 */ + "punpcklbw %%mm7, %%mm7\n\t" /* FF000000 -> mm7 */ + "pcmpeqb %%mm4, %%mm4\n\t" /* FFFFFFFF -> mm4 */ + "movq %%mm4, %%mm3\n\t" /* FFFFFFFF -> mm3 (for later) */ + "pxor %%mm4, %%mm7\n\t" /* 00FFFFFF -> mm7 (mult mask) */ + /* form channel masks */ + "movq %%mm7, %%mm4\n\t" /* 00FFFFFF -> mm4 */ + "packsswb %%mm6, %%mm4\n\t" /* 00000FFF -> mm4 (channel mask) */ + "packsswb %%mm6, %%mm3\n\t" /* 0000FFFF -> mm3 */ + "pxor %%mm4, %%mm3\n\t" /* 0000F000 -> mm3 (~channel mask) */ + /* get alpha channel shift */ + "movd %1, %%mm5\n\t" /* Ashift -> mm5 */ + : /* nothing */ : "m"(sf->Amask), "m"(sf->Ashift)); + + while (height--) { + + /* *INDENT-OFF* */ DUFFS_LOOP4({ Uint32 alpha; @@ -1662,39 +1725,43 @@ inline static void BlitRGBtoRGBPixelAlphaMMX3DNOW(SDL_BlitInfo *info) ++srcp; ++dstp; }, width); - srcp += srcskip; - dstp += dstskip; - } + /* *INDENT-ON* */ + srcp += srcskip; + dstp += dstskip; + } - __asm__ ( - "emms\n" - : ); + __asm__("emms\n":); } + /* End GCC_ASMBLIT*/ #elif MSVC_ASMBLIT /* fast (as in MMX with prefetch) ARGB888->(A)RGB888 blending with pixel alpha */ -static void BlitRGBtoRGBPixelAlphaMMX3DNOW(SDL_BlitInfo *info) +static void +BlitRGBtoRGBPixelAlphaMMX3DNOW(SDL_BlitInfo * info) { - int width = info->d_width; - int height = info->d_height; - Uint32 *srcp = (Uint32 *)info->s_pixels; - int srcskip = info->s_skip >> 2; - Uint32 *dstp = (Uint32 *)info->d_pixels; - int dstskip = info->d_skip >> 2; - SDL_PixelFormat* sf = info->src; - Uint32 chanmask = sf->Rmask | sf->Gmask | sf->Bmask; - Uint32 amask = sf->Amask; - Uint32 ashift = sf->Ashift; - Uint64 multmask; - - __m64 src1, dst1, mm_alpha, mm_zero, dmask; - - mm_zero = _mm_setzero_si64(); /* 0 -> mm_zero */ - multmask = ~(0xFFFFi64 << (ashift * 2)); - dmask = *(__m64*) &multmask; /* dst alpha mask -> dmask */ - - while(height--) { + int width = info->d_width; + int height = info->d_height; + Uint32 *srcp = (Uint32 *) info->s_pixels; + int srcskip = info->s_skip >> 2; + Uint32 *dstp = (Uint32 *) info->d_pixels; + int dstskip = info->d_skip >> 2; + SDL_PixelFormat *sf = info->src; + Uint32 chanmask = sf->Rmask | sf->Gmask | sf->Bmask; + Uint32 amask = sf->Amask; + Uint32 ashift = sf->Ashift; + Uint64 multmask; + + __m64 src1, dst1, mm_alpha, mm_zero, dmask; + + mm_zero = _mm_setzero_si64(); /* 0 -> mm_zero */ + /* *INDENT-OFF* */ + multmask = ~(0xFFFFI64 << (ashift * 2)); + /* *INDENT-ON* */ + dmask = *(__m64 *) & multmask; /* dst alpha mask -> dmask */ + + while (height--) { + /* *INDENT-OFF* */ DUFFS_LOOP4({ Uint32 alpha; @@ -1732,11 +1799,13 @@ static void BlitRGBtoRGBPixelAlphaMMX3DNOW(SDL_BlitInfo *info) ++srcp; ++dstp; }, width); - srcp += srcskip; - dstp += dstskip; - } - _mm_empty(); + /* *INDENT-ON* */ + srcp += srcskip; + dstp += dstskip; + } + _mm_empty(); } + /* End MSVC_ASMBLIT */ #endif /* GCC_ASMBLIT, MSVC_ASMBLIT */ @@ -1752,138 +1821,141 @@ static void BlitRGBtoRGBPixelAlphaMMX3DNOW(SDL_BlitInfo *info) (((s & (mask | mask << 16)) >> 1) + ((d & (mask | mask << 16)) >> 1) \ + (s & d & (~(mask | mask << 16)))) -static void Blit16to16SurfaceAlpha128(SDL_BlitInfo *info, Uint16 mask) +static void +Blit16to16SurfaceAlpha128(SDL_BlitInfo * info, Uint16 mask) { - int width = info->d_width; - int height = info->d_height; - Uint16 *srcp = (Uint16 *)info->s_pixels; - int srcskip = info->s_skip >> 1; - Uint16 *dstp = (Uint16 *)info->d_pixels; - int dstskip = info->d_skip >> 1; - - while(height--) { - if(((uintptr_t)srcp ^ (uintptr_t)dstp) & 2) { - /* - * Source and destination not aligned, pipeline it. - * This is mostly a win for big blits but no loss for - * small ones - */ - Uint32 prev_sw; - int w = width; - - /* handle odd destination */ - if((uintptr_t)dstp & 2) { - Uint16 d = *dstp, s = *srcp; - *dstp = BLEND16_50(d, s, mask); - dstp++; - srcp++; - w--; - } - srcp++; /* srcp is now 32-bit aligned */ - - /* bootstrap pipeline with first halfword */ - prev_sw = ((Uint32 *)srcp)[-1]; - - while(w > 1) { - Uint32 sw, dw, s; - sw = *(Uint32 *)srcp; - dw = *(Uint32 *)dstp; + int width = info->d_width; + int height = info->d_height; + Uint16 *srcp = (Uint16 *) info->s_pixels; + int srcskip = info->s_skip >> 1; + Uint16 *dstp = (Uint16 *) info->d_pixels; + int dstskip = info->d_skip >> 1; + + while (height--) { + if (((uintptr_t) srcp ^ (uintptr_t) dstp) & 2) { + /* + * Source and destination not aligned, pipeline it. + * This is mostly a win for big blits but no loss for + * small ones + */ + Uint32 prev_sw; + int w = width; + + /* handle odd destination */ + if ((uintptr_t) dstp & 2) { + Uint16 d = *dstp, s = *srcp; + *dstp = BLEND16_50(d, s, mask); + dstp++; + srcp++; + w--; + } + srcp++; /* srcp is now 32-bit aligned */ + + /* bootstrap pipeline with first halfword */ + prev_sw = ((Uint32 *) srcp)[-1]; + + while (w > 1) { + Uint32 sw, dw, s; + sw = *(Uint32 *) srcp; + dw = *(Uint32 *) dstp; #if SDL_BYTEORDER == SDL_BIG_ENDIAN - s = (prev_sw << 16) + (sw >> 16); + s = (prev_sw << 16) + (sw >> 16); #else - s = (prev_sw >> 16) + (sw << 16); + s = (prev_sw >> 16) + (sw << 16); #endif - prev_sw = sw; - *(Uint32 *)dstp = BLEND2x16_50(dw, s, mask); - dstp += 2; - srcp += 2; - w -= 2; - } - - /* final pixel if any */ - if(w) { - Uint16 d = *dstp, s; + prev_sw = sw; + *(Uint32 *) dstp = BLEND2x16_50(dw, s, mask); + dstp += 2; + srcp += 2; + w -= 2; + } + + /* final pixel if any */ + if (w) { + Uint16 d = *dstp, s; #if SDL_BYTEORDER == SDL_BIG_ENDIAN - s = (Uint16)prev_sw; + s = (Uint16) prev_sw; #else - s = (Uint16)(prev_sw >> 16); + s = (Uint16) (prev_sw >> 16); #endif - *dstp = BLEND16_50(d, s, mask); - srcp++; - dstp++; - } - srcp += srcskip - 1; - dstp += dstskip; - } else { - /* source and destination are aligned */ - int w = width; - - /* first odd pixel? */ - if((uintptr_t)srcp & 2) { - Uint16 d = *dstp, s = *srcp; - *dstp = BLEND16_50(d, s, mask); - srcp++; - dstp++; - w--; - } - /* srcp and dstp are now 32-bit aligned */ - - while(w > 1) { - Uint32 sw = *(Uint32 *)srcp; - Uint32 dw = *(Uint32 *)dstp; - *(Uint32 *)dstp = BLEND2x16_50(dw, sw, mask); - srcp += 2; - dstp += 2; - w -= 2; - } - - /* last odd pixel? */ - if(w) { - Uint16 d = *dstp, s = *srcp; - *dstp = BLEND16_50(d, s, mask); - srcp++; - dstp++; - } - srcp += srcskip; - dstp += dstskip; - } - } + *dstp = BLEND16_50(d, s, mask); + srcp++; + dstp++; + } + srcp += srcskip - 1; + dstp += dstskip; + } else { + /* source and destination are aligned */ + int w = width; + + /* first odd pixel? */ + if ((uintptr_t) srcp & 2) { + Uint16 d = *dstp, s = *srcp; + *dstp = BLEND16_50(d, s, mask); + srcp++; + dstp++; + w--; + } + /* srcp and dstp are now 32-bit aligned */ + + while (w > 1) { + Uint32 sw = *(Uint32 *) srcp; + Uint32 dw = *(Uint32 *) dstp; + *(Uint32 *) dstp = BLEND2x16_50(dw, sw, mask); + srcp += 2; + dstp += 2; + w -= 2; + } + + /* last odd pixel? */ + if (w) { + Uint16 d = *dstp, s = *srcp; + *dstp = BLEND16_50(d, s, mask); + srcp++; + dstp++; + } + srcp += srcskip; + dstp += dstskip; + } + } } #if GCC_ASMBLIT /* fast RGB565->RGB565 blending with surface alpha */ -static void Blit565to565SurfaceAlphaMMX(SDL_BlitInfo *info) +static void +Blit565to565SurfaceAlphaMMX(SDL_BlitInfo * info) { - unsigned alpha = info->src->alpha; /* downscale alpha to 5 bits */ - if(alpha == 128) { - Blit16to16SurfaceAlpha128(info, 0xf7de); - } else { - int width = info->d_width; - int height = info->d_height; - Uint16 *srcp = (Uint16 *)info->s_pixels; - int srcskip = info->s_skip >> 1; - Uint16 *dstp = (Uint16 *)info->d_pixels; - int dstskip = info->d_skip >> 1; - Uint32 s, d; - Uint8 load[8]; - - alpha &= ~(1+2+4); /* cut alpha to get the exact same behaviour */ - *(Uint64 *)load = alpha; - alpha >>= 3; /* downscale alpha to 5 bits */ - - movq_m2r(*load, mm0); /* alpha(0000000A) -> mm0 */ - punpcklwd_r2r(mm0, mm0); /* 00000A0A -> mm0 */ - punpcklwd_r2r(mm0, mm0); /* 0A0A0A0A -> mm0 */ - /* position alpha to allow for mullo and mulhi on diff channels - to reduce the number of operations */ - psllq_i2r(3, mm0); - - /* Setup the 565 color channel masks */ - *(Uint64 *)load = 0x07E007E007E007E0ULL; - movq_m2r(*load, mm4); /* MASKGREEN -> mm4 */ - *(Uint64 *)load = 0x001F001F001F001FULL; - movq_m2r(*load, mm7); /* MASKBLUE -> mm7 */ - while(height--) { + unsigned alpha = info->src->alpha; /* downscale alpha to 5 bits */ + if (alpha == 128) { + Blit16to16SurfaceAlpha128(info, 0xf7de); + } else { + int width = info->d_width; + int height = info->d_height; + Uint16 *srcp = (Uint16 *) info->s_pixels; + int srcskip = info->s_skip >> 1; + Uint16 *dstp = (Uint16 *) info->d_pixels; + int dstskip = info->d_skip >> 1; + Uint32 s, d; + Uint8 load[8]; + + alpha &= ~(1 + 2 + 4); /* cut alpha to get the exact same behaviour */ + *(Uint64 *) load = alpha; + alpha >>= 3; /* downscale alpha to 5 bits */ + + movq_m2r(*load, mm0); /* alpha(0000000A) -> mm0 */ + punpcklwd_r2r(mm0, mm0); /* 00000A0A -> mm0 */ + punpcklwd_r2r(mm0, mm0); /* 0A0A0A0A -> mm0 */ + /* position alpha to allow for mullo and mulhi on diff channels + to reduce the number of operations */ + psllq_i2r(3, mm0); + + /* Setup the 565 color channel masks */ + *(Uint64 *) load = 0x07E007E007E007E0ULL; + movq_m2r(*load, mm4); /* MASKGREEN -> mm4 */ + *(Uint64 *) load = 0x001F001F001F001FULL; + movq_m2r(*load, mm7); /* MASKBLUE -> mm7 */ + while (height--) { + /* *INDENT-OFF* */ DUFFS_LOOP_QUATRO2( { s = *srcp++; @@ -1983,46 +2055,49 @@ static void Blit565to565SurfaceAlphaMMX(SDL_BlitInfo *info) srcp += 4; dstp += 4; }, width); - srcp += srcskip; - dstp += dstskip; - } - emms(); - } + /* *INDENT-ON* */ + srcp += srcskip; + dstp += dstskip; + } + emms(); + } } /* fast RGB555->RGB555 blending with surface alpha */ -static void Blit555to555SurfaceAlphaMMX(SDL_BlitInfo *info) +static void +Blit555to555SurfaceAlphaMMX(SDL_BlitInfo * info) { - unsigned alpha = info->src->alpha; /* downscale alpha to 5 bits */ - if(alpha == 128) { - Blit16to16SurfaceAlpha128(info, 0xfbde); - } else { - int width = info->d_width; - int height = info->d_height; - Uint16 *srcp = (Uint16 *)info->s_pixels; - int srcskip = info->s_skip >> 1; - Uint16 *dstp = (Uint16 *)info->d_pixels; - int dstskip = info->d_skip >> 1; - Uint32 s, d; - Uint8 load[8]; - - alpha &= ~(1+2+4); /* cut alpha to get the exact same behaviour */ - *(Uint64 *)load = alpha; - alpha >>= 3; /* downscale alpha to 5 bits */ - - movq_m2r(*load, mm0); /* alpha(0000000A) -> mm0 */ - punpcklwd_r2r(mm0, mm0); /* 00000A0A -> mm0 */ - punpcklwd_r2r(mm0, mm0); /* 0A0A0A0A -> mm0 */ - /* position alpha to allow for mullo and mulhi on diff channels - to reduce the number of operations */ - psllq_i2r(3, mm0); - - /* Setup the 555 color channel masks */ - *(Uint64 *)load = 0x03E003E003E003E0ULL; - movq_m2r(*load, mm4); /* MASKGREEN -> mm4 */ - *(Uint64 *)load = 0x001F001F001F001FULL; - movq_m2r(*load, mm7); /* MASKBLUE -> mm7 */ - while(height--) { + unsigned alpha = info->src->alpha; /* downscale alpha to 5 bits */ + if (alpha == 128) { + Blit16to16SurfaceAlpha128(info, 0xfbde); + } else { + int width = info->d_width; + int height = info->d_height; + Uint16 *srcp = (Uint16 *) info->s_pixels; + int srcskip = info->s_skip >> 1; + Uint16 *dstp = (Uint16 *) info->d_pixels; + int dstskip = info->d_skip >> 1; + Uint32 s, d; + Uint8 load[8]; + + alpha &= ~(1 + 2 + 4); /* cut alpha to get the exact same behaviour */ + *(Uint64 *) load = alpha; + alpha >>= 3; /* downscale alpha to 5 bits */ + + movq_m2r(*load, mm0); /* alpha(0000000A) -> mm0 */ + punpcklwd_r2r(mm0, mm0); /* 00000A0A -> mm0 */ + punpcklwd_r2r(mm0, mm0); /* 0A0A0A0A -> mm0 */ + /* position alpha to allow for mullo and mulhi on diff channels + to reduce the number of operations */ + psllq_i2r(3, mm0); + + /* Setup the 555 color channel masks */ + *(Uint64 *) load = 0x03E003E003E003E0ULL; + movq_m2r(*load, mm4); /* MASKGREEN -> mm4 */ + *(Uint64 *) load = 0x001F001F001F001FULL; + movq_m2r(*load, mm7); /* MASKBLUE -> mm7 */ + while (height--) { + /* *INDENT-OFF* */ DUFFS_LOOP_QUATRO2( { s = *srcp++; @@ -2126,48 +2201,52 @@ static void Blit555to555SurfaceAlphaMMX(SDL_BlitInfo *info) srcp += 4; dstp += 4; - }, width); - srcp += srcskip; - dstp += dstskip; - } - emms(); - } + }, width); + /* *INDENT-ON* */ + srcp += srcskip; + dstp += dstskip; + } + emms(); + } } + /* End GCC_ASMBLIT */ #elif MSVC_ASMBLIT /* fast RGB565->RGB565 blending with surface alpha */ -static void Blit565to565SurfaceAlphaMMX(SDL_BlitInfo *info) +static void +Blit565to565SurfaceAlphaMMX(SDL_BlitInfo * info) { - unsigned alpha = info->src->alpha; - if(alpha == 128) { - Blit16to16SurfaceAlpha128(info, 0xf7de); - } else { - int width = info->d_width; - int height = info->d_height; - Uint16 *srcp = (Uint16 *)info->s_pixels; - int srcskip = info->s_skip >> 1; - Uint16 *dstp = (Uint16 *)info->d_pixels; - int dstskip = info->d_skip >> 1; - Uint32 s, d; - - __m64 src1, dst1, src2, dst2, gmask, bmask, mm_res, mm_alpha; - - alpha &= ~(1+2+4); /* cut alpha to get the exact same behaviour */ - mm_alpha = _mm_set_pi32(0, alpha); /* 0000000A -> mm_alpha */ - alpha >>= 3; /* downscale alpha to 5 bits */ - - mm_alpha = _mm_unpacklo_pi16(mm_alpha, mm_alpha); /* 00000A0A -> mm_alpha */ - mm_alpha = _mm_unpacklo_pi32(mm_alpha, mm_alpha); /* 0A0A0A0A -> mm_alpha */ - /* position alpha to allow for mullo and mulhi on diff channels - to reduce the number of operations */ - mm_alpha = _mm_slli_si64(mm_alpha, 3); - - /* Setup the 565 color channel masks */ - gmask = _mm_set_pi32(0x07E007E0, 0x07E007E0); /* MASKGREEN -> gmask */ - bmask = _mm_set_pi32(0x001F001F, 0x001F001F); /* MASKBLUE -> bmask */ - - while(height--) { + unsigned alpha = info->src->alpha; + if (alpha == 128) { + Blit16to16SurfaceAlpha128(info, 0xf7de); + } else { + int width = info->d_width; + int height = info->d_height; + Uint16 *srcp = (Uint16 *) info->s_pixels; + int srcskip = info->s_skip >> 1; + Uint16 *dstp = (Uint16 *) info->d_pixels; + int dstskip = info->d_skip >> 1; + Uint32 s, d; + + __m64 src1, dst1, src2, dst2, gmask, bmask, mm_res, mm_alpha; + + alpha &= ~(1 + 2 + 4); /* cut alpha to get the exact same behaviour */ + mm_alpha = _mm_set_pi32(0, alpha); /* 0000000A -> mm_alpha */ + alpha >>= 3; /* downscale alpha to 5 bits */ + + mm_alpha = _mm_unpacklo_pi16(mm_alpha, mm_alpha); /* 00000A0A -> mm_alpha */ + mm_alpha = _mm_unpacklo_pi32(mm_alpha, mm_alpha); /* 0A0A0A0A -> mm_alpha */ + /* position alpha to allow for mullo and mulhi on diff channels + to reduce the number of operations */ + mm_alpha = _mm_slli_si64(mm_alpha, 3); + + /* Setup the 565 color channel masks */ + gmask = _mm_set_pi32(0x07E007E0, 0x07E007E0); /* MASKGREEN -> gmask */ + bmask = _mm_set_pi32(0x001F001F, 0x001F001F); /* MASKBLUE -> bmask */ + + while (height--) { + /* *INDENT-OFF* */ DUFFS_LOOP_QUATRO2( { s = *srcp++; @@ -2262,47 +2341,50 @@ static void Blit565to565SurfaceAlphaMMX(SDL_BlitInfo *info) srcp += 4; dstp += 4; - }, width); - srcp += srcskip; - dstp += dstskip; - } - _mm_empty(); - } + }, width); + /* *INDENT-ON* */ + srcp += srcskip; + dstp += dstskip; + } + _mm_empty(); + } } /* fast RGB555->RGB555 blending with surface alpha */ -static void Blit555to555SurfaceAlphaMMX(SDL_BlitInfo *info) +static void +Blit555to555SurfaceAlphaMMX(SDL_BlitInfo * info) { - unsigned alpha = info->src->alpha; - if(alpha == 128) { - Blit16to16SurfaceAlpha128(info, 0xfbde); - } else { - int width = info->d_width; - int height = info->d_height; - Uint16 *srcp = (Uint16 *)info->s_pixels; - int srcskip = info->s_skip >> 1; - Uint16 *dstp = (Uint16 *)info->d_pixels; - int dstskip = info->d_skip >> 1; - Uint32 s, d; - - __m64 src1, dst1, src2, dst2, rmask, gmask, bmask, mm_res, mm_alpha; - - alpha &= ~(1+2+4); /* cut alpha to get the exact same behaviour */ - mm_alpha = _mm_set_pi32(0, alpha); /* 0000000A -> mm_alpha */ - alpha >>= 3; /* downscale alpha to 5 bits */ - - mm_alpha = _mm_unpacklo_pi16(mm_alpha, mm_alpha); /* 00000A0A -> mm_alpha */ - mm_alpha = _mm_unpacklo_pi32(mm_alpha, mm_alpha); /* 0A0A0A0A -> mm_alpha */ - /* position alpha to allow for mullo and mulhi on diff channels - to reduce the number of operations */ - mm_alpha = _mm_slli_si64(mm_alpha, 3); - - /* Setup the 555 color channel masks */ - rmask = _mm_set_pi32(0x7C007C00, 0x7C007C00); /* MASKRED -> rmask */ - gmask = _mm_set_pi32(0x03E003E0, 0x03E003E0); /* MASKGREEN -> gmask */ - bmask = _mm_set_pi32(0x001F001F, 0x001F001F); /* MASKBLUE -> bmask */ - - while(height--) { + unsigned alpha = info->src->alpha; + if (alpha == 128) { + Blit16to16SurfaceAlpha128(info, 0xfbde); + } else { + int width = info->d_width; + int height = info->d_height; + Uint16 *srcp = (Uint16 *) info->s_pixels; + int srcskip = info->s_skip >> 1; + Uint16 *dstp = (Uint16 *) info->d_pixels; + int dstskip = info->d_skip >> 1; + Uint32 s, d; + + __m64 src1, dst1, src2, dst2, rmask, gmask, bmask, mm_res, mm_alpha; + + alpha &= ~(1 + 2 + 4); /* cut alpha to get the exact same behaviour */ + mm_alpha = _mm_set_pi32(0, alpha); /* 0000000A -> mm_alpha */ + alpha >>= 3; /* downscale alpha to 5 bits */ + + mm_alpha = _mm_unpacklo_pi16(mm_alpha, mm_alpha); /* 00000A0A -> mm_alpha */ + mm_alpha = _mm_unpacklo_pi32(mm_alpha, mm_alpha); /* 0A0A0A0A -> mm_alpha */ + /* position alpha to allow for mullo and mulhi on diff channels + to reduce the number of operations */ + mm_alpha = _mm_slli_si64(mm_alpha, 3); + + /* Setup the 555 color channel masks */ + rmask = _mm_set_pi32(0x7C007C00, 0x7C007C00); /* MASKRED -> rmask */ + gmask = _mm_set_pi32(0x03E003E0, 0x03E003E0); /* MASKGREEN -> gmask */ + bmask = _mm_set_pi32(0x001F001F, 0x001F001F); /* MASKBLUE -> bmask */ + + while (height--) { + /* *INDENT-OFF* */ DUFFS_LOOP_QUATRO2( { s = *srcp++; @@ -2397,31 +2479,34 @@ static void Blit555to555SurfaceAlphaMMX(SDL_BlitInfo *info) srcp += 4; dstp += 4; - }, width); - srcp += srcskip; - dstp += dstskip; - } - _mm_empty(); - } + }, width); + /* *INDENT-ON* */ + srcp += srcskip; + dstp += dstskip; + } + _mm_empty(); + } } #endif /* GCC_ASMBLIT, MSVC_ASMBLIT */ /* fast RGB565->RGB565 blending with surface alpha */ -static void Blit565to565SurfaceAlpha(SDL_BlitInfo *info) +static void +Blit565to565SurfaceAlpha(SDL_BlitInfo * info) { - unsigned alpha = info->src->alpha; - if(alpha == 128) { - Blit16to16SurfaceAlpha128(info, 0xf7de); - } else { - int width = info->d_width; - int height = info->d_height; - Uint16 *srcp = (Uint16 *)info->s_pixels; - int srcskip = info->s_skip >> 1; - Uint16 *dstp = (Uint16 *)info->d_pixels; - int dstskip = info->d_skip >> 1; - alpha >>= 3; /* downscale alpha to 5 bits */ - - while(height--) { + unsigned alpha = info->src->alpha; + if (alpha == 128) { + Blit16to16SurfaceAlpha128(info, 0xf7de); + } else { + int width = info->d_width; + int height = info->d_height; + Uint16 *srcp = (Uint16 *) info->s_pixels; + int srcskip = info->s_skip >> 1; + Uint16 *dstp = (Uint16 *) info->d_pixels; + int dstskip = info->d_skip >> 1; + alpha >>= 3; /* downscale alpha to 5 bits */ + + while (height--) { + /* *INDENT-OFF* */ DUFFS_LOOP4({ Uint32 s = *srcp++; Uint32 d = *dstp; @@ -2436,28 +2521,31 @@ static void Blit565to565SurfaceAlpha(SDL_BlitInfo *info) d &= 0x07e0f81f; *dstp++ = (Uint16)(d | d >> 16); }, width); - srcp += srcskip; - dstp += dstskip; - } - } + /* *INDENT-ON* */ + srcp += srcskip; + dstp += dstskip; + } + } } /* fast RGB555->RGB555 blending with surface alpha */ -static void Blit555to555SurfaceAlpha(SDL_BlitInfo *info) +static void +Blit555to555SurfaceAlpha(SDL_BlitInfo * info) { - unsigned alpha = info->src->alpha; /* downscale alpha to 5 bits */ - if(alpha == 128) { - Blit16to16SurfaceAlpha128(info, 0xfbde); - } else { - int width = info->d_width; - int height = info->d_height; - Uint16 *srcp = (Uint16 *)info->s_pixels; - int srcskip = info->s_skip >> 1; - Uint16 *dstp = (Uint16 *)info->d_pixels; - int dstskip = info->d_skip >> 1; - alpha >>= 3; /* downscale alpha to 5 bits */ - - while(height--) { + unsigned alpha = info->src->alpha; /* downscale alpha to 5 bits */ + if (alpha == 128) { + Blit16to16SurfaceAlpha128(info, 0xfbde); + } else { + int width = info->d_width; + int height = info->d_height; + Uint16 *srcp = (Uint16 *) info->s_pixels; + int srcskip = info->s_skip >> 1; + Uint16 *dstp = (Uint16 *) info->d_pixels; + int dstskip = info->d_skip >> 1; + alpha >>= 3; /* downscale alpha to 5 bits */ + + while (height--) { + /* *INDENT-OFF* */ DUFFS_LOOP4({ Uint32 s = *srcp++; Uint32 d = *dstp; @@ -2472,23 +2560,26 @@ static void Blit555to555SurfaceAlpha(SDL_BlitInfo *info) d &= 0x03e07c1f; *dstp++ = (Uint16)(d | d >> 16); }, width); - srcp += srcskip; - dstp += dstskip; - } - } + /* *INDENT-ON* */ + srcp += srcskip; + dstp += dstskip; + } + } } /* fast ARGB8888->RGB565 blending with pixel alpha */ -static void BlitARGBto565PixelAlpha(SDL_BlitInfo *info) +static void +BlitARGBto565PixelAlpha(SDL_BlitInfo * info) { - int width = info->d_width; - int height = info->d_height; - Uint32 *srcp = (Uint32 *)info->s_pixels; - int srcskip = info->s_skip >> 2; - Uint16 *dstp = (Uint16 *)info->d_pixels; - int dstskip = info->d_skip >> 1; - - while(height--) { + int width = info->d_width; + int height = info->d_height; + Uint32 *srcp = (Uint32 *) info->s_pixels; + int srcskip = info->s_skip >> 2; + Uint16 *dstp = (Uint16 *) info->d_pixels; + int dstskip = info->d_skip >> 1; + + while (height--) { + /* *INDENT-OFF* */ DUFFS_LOOP4({ Uint32 s = *srcp; unsigned alpha = s >> 27; /* downscale alpha to 5 bits */ @@ -2516,22 +2607,25 @@ static void BlitARGBto565PixelAlpha(SDL_BlitInfo *info) srcp++; dstp++; }, width); - srcp += srcskip; - dstp += dstskip; - } + /* *INDENT-ON* */ + srcp += srcskip; + dstp += dstskip; + } } /* fast ARGB8888->RGB555 blending with pixel alpha */ -static void BlitARGBto555PixelAlpha(SDL_BlitInfo *info) +static void +BlitARGBto555PixelAlpha(SDL_BlitInfo * info) { - int width = info->d_width; - int height = info->d_height; - Uint32 *srcp = (Uint32 *)info->s_pixels; - int srcskip = info->s_skip >> 2; - Uint16 *dstp = (Uint16 *)info->d_pixels; - int dstskip = info->d_skip >> 1; - - while(height--) { + int width = info->d_width; + int height = info->d_height; + Uint32 *srcp = (Uint32 *) info->s_pixels; + int srcskip = info->s_skip >> 2; + Uint16 *dstp = (Uint16 *) info->d_pixels; + int dstskip = info->d_skip >> 1; + + while (height--) { + /* *INDENT-OFF* */ DUFFS_LOOP4({ unsigned alpha; Uint32 s = *srcp; @@ -2560,29 +2654,32 @@ static void BlitARGBto555PixelAlpha(SDL_BlitInfo *info) srcp++; dstp++; }, width); - srcp += srcskip; - dstp += dstskip; - } + /* *INDENT-ON* */ + srcp += srcskip; + dstp += dstskip; + } } /* General (slow) N->N blending with per-surface alpha */ -static void BlitNtoNSurfaceAlpha(SDL_BlitInfo *info) +static void +BlitNtoNSurfaceAlpha(SDL_BlitInfo * info) { - int width = info->d_width; - int height = info->d_height; - Uint8 *src = info->s_pixels; - int srcskip = info->s_skip; - Uint8 *dst = info->d_pixels; - int dstskip = info->d_skip; - SDL_PixelFormat *srcfmt = info->src; - SDL_PixelFormat *dstfmt = info->dst; - int srcbpp = srcfmt->BytesPerPixel; - int dstbpp = dstfmt->BytesPerPixel; - unsigned sA = srcfmt->alpha; - unsigned dA = dstfmt->Amask ? SDL_ALPHA_OPAQUE : 0; - - if(sA) { - while ( height-- ) { + int width = info->d_width; + int height = info->d_height; + Uint8 *src = info->s_pixels; + int srcskip = info->s_skip; + Uint8 *dst = info->d_pixels; + int dstskip = info->d_skip; + SDL_PixelFormat *srcfmt = info->src; + SDL_PixelFormat *dstfmt = info->dst; + int srcbpp = srcfmt->BytesPerPixel; + int dstbpp = dstfmt->BytesPerPixel; + unsigned sA = srcfmt->alpha; + unsigned dA = dstfmt->Amask ? SDL_ALPHA_OPAQUE : 0; + + if (sA) { + while (height--) { + /* *INDENT-OFF* */ DUFFS_LOOP4( { Uint32 Pixel; @@ -2600,30 +2697,33 @@ static void BlitNtoNSurfaceAlpha(SDL_BlitInfo *info) dst += dstbpp; }, width); - src += srcskip; - dst += dstskip; - } - } + /* *INDENT-ON* */ + src += srcskip; + dst += dstskip; + } + } } /* General (slow) colorkeyed N->N blending with per-surface alpha */ -static void BlitNtoNSurfaceAlphaKey(SDL_BlitInfo *info) +static void +BlitNtoNSurfaceAlphaKey(SDL_BlitInfo * info) { - int width = info->d_width; - int height = info->d_height; - Uint8 *src = info->s_pixels; - int srcskip = info->s_skip; - Uint8 *dst = info->d_pixels; - int dstskip = info->d_skip; - SDL_PixelFormat *srcfmt = info->src; - SDL_PixelFormat *dstfmt = info->dst; - Uint32 ckey = srcfmt->colorkey; - int srcbpp = srcfmt->BytesPerPixel; - int dstbpp = dstfmt->BytesPerPixel; - unsigned sA = srcfmt->alpha; - unsigned dA = dstfmt->Amask ? SDL_ALPHA_OPAQUE : 0; - - while ( height-- ) { + int width = info->d_width; + int height = info->d_height; + Uint8 *src = info->s_pixels; + int srcskip = info->s_skip; + Uint8 *dst = info->d_pixels; + int dstskip = info->d_skip; + SDL_PixelFormat *srcfmt = info->src; + SDL_PixelFormat *dstfmt = info->dst; + Uint32 ckey = srcfmt->colorkey; + int srcbpp = srcfmt->BytesPerPixel; + int dstbpp = dstfmt->BytesPerPixel; + unsigned sA = srcfmt->alpha; + unsigned dA = dstfmt->Amask ? SDL_ALPHA_OPAQUE : 0; + + while (height--) { + /* *INDENT-OFF* */ DUFFS_LOOP4( { Uint32 Pixel; @@ -2644,36 +2744,39 @@ static void BlitNtoNSurfaceAlphaKey(SDL_BlitInfo *info) dst += dstbpp; }, width); - src += srcskip; - dst += dstskip; - } + /* *INDENT-ON* */ + src += srcskip; + dst += dstskip; + } } /* General (slow) N->N blending with pixel alpha */ -static void BlitNtoNPixelAlpha(SDL_BlitInfo *info) +static void +BlitNtoNPixelAlpha(SDL_BlitInfo * info) { - int width = info->d_width; - int height = info->d_height; - Uint8 *src = info->s_pixels; - int srcskip = info->s_skip; - Uint8 *dst = info->d_pixels; - int dstskip = info->d_skip; - SDL_PixelFormat *srcfmt = info->src; - SDL_PixelFormat *dstfmt = info->dst; - - int srcbpp; - int dstbpp; - - /* Set up some basic variables */ - srcbpp = srcfmt->BytesPerPixel; - dstbpp = dstfmt->BytesPerPixel; - - /* FIXME: for 8bpp source alpha, this doesn't get opaque values - quite right. for <8bpp source alpha, it gets them very wrong - (check all macros!) - It is unclear whether there is a good general solution that doesn't - need a branch (or a divide). */ - while ( height-- ) { + int width = info->d_width; + int height = info->d_height; + Uint8 *src = info->s_pixels; + int srcskip = info->s_skip; + Uint8 *dst = info->d_pixels; + int dstskip = info->d_skip; + SDL_PixelFormat *srcfmt = info->src; + SDL_PixelFormat *dstfmt = info->dst; + + int srcbpp; + int dstbpp; + + /* Set up some basic variables */ + srcbpp = srcfmt->BytesPerPixel; + dstbpp = dstfmt->BytesPerPixel; + + /* FIXME: for 8bpp source alpha, this doesn't get opaque values + quite right. for <8bpp source alpha, it gets them very wrong + (check all macros!) + It is unclear whether there is a good general solution that doesn't + need a branch (or a divide). */ + while (height--) { + /* *INDENT-OFF* */ DUFFS_LOOP4( { Uint32 Pixel; @@ -2695,160 +2798,155 @@ static void BlitNtoNPixelAlpha(SDL_BlitInfo *info) dst += dstbpp; }, width); - src += srcskip; - dst += dstskip; - } + /* *INDENT-ON* */ + src += srcskip; + dst += dstskip; + } } -SDL_loblit SDL_CalculateAlphaBlit(SDL_Surface *surface, int blit_index) +SDL_loblit +SDL_CalculateAlphaBlit(SDL_Surface * surface, int blit_index) { SDL_PixelFormat *sf = surface->format; SDL_PixelFormat *df = surface->map->dst->format; - if(sf->Amask == 0) { - if((surface->flags & SDL_SRCCOLORKEY) == SDL_SRCCOLORKEY) { - if(df->BytesPerPixel == 1) - return BlitNto1SurfaceAlphaKey; - else + if (sf->Amask == 0) { + if ((surface->flags & SDL_SRCCOLORKEY) == SDL_SRCCOLORKEY) { + if (df->BytesPerPixel == 1) + return BlitNto1SurfaceAlphaKey; + else #if SDL_ALTIVEC_BLITTERS - if (sf->BytesPerPixel == 4 && df->BytesPerPixel == 4 && - !(surface->map->dst->flags & SDL_HWSURFACE) && SDL_HasAltiVec()) - return Blit32to32SurfaceAlphaKeyAltivec; - else + if (sf->BytesPerPixel == 4 && df->BytesPerPixel == 4 && + !(surface->map->dst->flags & SDL_HWSURFACE) + && SDL_HasAltiVec()) + return Blit32to32SurfaceAlphaKeyAltivec; + else #endif - return BlitNtoNSurfaceAlphaKey; - } else { - /* Per-surface alpha blits */ - switch(df->BytesPerPixel) { - case 1: - return BlitNto1SurfaceAlpha; - - case 2: - if(surface->map->identity) { - if(df->Gmask == 0x7e0) - { + return BlitNtoNSurfaceAlphaKey; + } else { + /* Per-surface alpha blits */ + switch (df->BytesPerPixel) { + case 1: + return BlitNto1SurfaceAlpha; + + case 2: + if (surface->map->identity) { + if (df->Gmask == 0x7e0) { #if MMX_ASMBLIT - if(SDL_HasMMX()) - return Blit565to565SurfaceAlphaMMX; - else + if (SDL_HasMMX()) + return Blit565to565SurfaceAlphaMMX; + else #endif - return Blit565to565SurfaceAlpha; - } - else if(df->Gmask == 0x3e0) - { + return Blit565to565SurfaceAlpha; + } else if (df->Gmask == 0x3e0) { #if MMX_ASMBLIT - if(SDL_HasMMX()) - return Blit555to555SurfaceAlphaMMX; - else + if (SDL_HasMMX()) + return Blit555to555SurfaceAlphaMMX; + else #endif - return Blit555to555SurfaceAlpha; - } - } - return BlitNtoNSurfaceAlpha; - - case 4: - if(sf->Rmask == df->Rmask - && sf->Gmask == df->Gmask - && sf->Bmask == df->Bmask - && sf->BytesPerPixel == 4) - { + return Blit555to555SurfaceAlpha; + } + } + return BlitNtoNSurfaceAlpha; + + case 4: + if (sf->Rmask == df->Rmask + && sf->Gmask == df->Gmask + && sf->Bmask == df->Bmask && sf->BytesPerPixel == 4) { #if MMX_ASMBLIT - if(sf->Rshift % 8 == 0 - && sf->Gshift % 8 == 0 - && sf->Bshift % 8 == 0 - && SDL_HasMMX()) - return BlitRGBtoRGBSurfaceAlphaMMX; + if (sf->Rshift % 8 == 0 + && sf->Gshift % 8 == 0 + && sf->Bshift % 8 == 0 && SDL_HasMMX()) + return BlitRGBtoRGBSurfaceAlphaMMX; #endif - if((sf->Rmask | sf->Gmask | sf->Bmask) == 0xffffff) - { + if ((sf->Rmask | sf->Gmask | sf->Bmask) == 0xffffff) { #if SDL_ALTIVEC_BLITTERS - if(!(surface->map->dst->flags & SDL_HWSURFACE) - && SDL_HasAltiVec()) - return BlitRGBtoRGBSurfaceAlphaAltivec; + if (!(surface->map->dst->flags & SDL_HWSURFACE) + && SDL_HasAltiVec()) + return BlitRGBtoRGBSurfaceAlphaAltivec; #endif - return BlitRGBtoRGBSurfaceAlpha; - } - } + return BlitRGBtoRGBSurfaceAlpha; + } + } #if SDL_ALTIVEC_BLITTERS - if((sf->BytesPerPixel == 4) && - !(surface->map->dst->flags & SDL_HWSURFACE) && SDL_HasAltiVec()) - return Blit32to32SurfaceAlphaAltivec; - else + if ((sf->BytesPerPixel == 4) && + !(surface->map->dst->flags & SDL_HWSURFACE) + && SDL_HasAltiVec()) + return Blit32to32SurfaceAlphaAltivec; + else #endif - return BlitNtoNSurfaceAlpha; + return BlitNtoNSurfaceAlpha; - case 3: - default: - return BlitNtoNSurfaceAlpha; - } - } + case 3: + default: + return BlitNtoNSurfaceAlpha; + } + } } else { - /* Per-pixel alpha blits */ - switch(df->BytesPerPixel) { - case 1: - return BlitNto1PixelAlpha; + /* Per-pixel alpha blits */ + switch (df->BytesPerPixel) { + case 1: + return BlitNto1PixelAlpha; - case 2: + case 2: #if SDL_ALTIVEC_BLITTERS - if(sf->BytesPerPixel == 4 && !(surface->map->dst->flags & SDL_HWSURFACE) && - df->Gmask == 0x7e0 && - df->Bmask == 0x1f && SDL_HasAltiVec()) - return Blit32to565PixelAlphaAltivec; - else + if (sf->BytesPerPixel == 4 + && !(surface->map->dst->flags & SDL_HWSURFACE) + && df->Gmask == 0x7e0 && df->Bmask == 0x1f + && SDL_HasAltiVec()) + return Blit32to565PixelAlphaAltivec; + else #endif - if(sf->BytesPerPixel == 4 && sf->Amask == 0xff000000 - && sf->Gmask == 0xff00 - && ((sf->Rmask == 0xff && df->Rmask == 0x1f) - || (sf->Bmask == 0xff && df->Bmask == 0x1f))) { - if(df->Gmask == 0x7e0) - return BlitARGBto565PixelAlpha; - else if(df->Gmask == 0x3e0) - return BlitARGBto555PixelAlpha; - } - return BlitNtoNPixelAlpha; + if (sf->BytesPerPixel == 4 && sf->Amask == 0xff000000 + && sf->Gmask == 0xff00 + && ((sf->Rmask == 0xff && df->Rmask == 0x1f) + || (sf->Bmask == 0xff && df->Bmask == 0x1f))) { + if (df->Gmask == 0x7e0) + return BlitARGBto565PixelAlpha; + else if (df->Gmask == 0x3e0) + return BlitARGBto555PixelAlpha; + } + return BlitNtoNPixelAlpha; - case 4: - if(sf->Rmask == df->Rmask - && sf->Gmask == df->Gmask - && sf->Bmask == df->Bmask - && sf->BytesPerPixel == 4) - { + case 4: + if (sf->Rmask == df->Rmask + && sf->Gmask == df->Gmask + && sf->Bmask == df->Bmask && sf->BytesPerPixel == 4) { #if MMX_ASMBLIT - if(sf->Rshift % 8 == 0 - && sf->Gshift % 8 == 0 - && sf->Bshift % 8 == 0 - && sf->Ashift % 8 == 0 - && sf->Aloss == 0) - { - if(SDL_Has3DNow()) - return BlitRGBtoRGBPixelAlphaMMX3DNOW; - if(SDL_HasMMX()) - return BlitRGBtoRGBPixelAlphaMMX; - } + if (sf->Rshift % 8 == 0 + && sf->Gshift % 8 == 0 + && sf->Bshift % 8 == 0 + && sf->Ashift % 8 == 0 && sf->Aloss == 0) { + if (SDL_Has3DNow()) + return BlitRGBtoRGBPixelAlphaMMX3DNOW; + if (SDL_HasMMX()) + return BlitRGBtoRGBPixelAlphaMMX; + } #endif - if(sf->Amask == 0xff000000) - { + if (sf->Amask == 0xff000000) { #if SDL_ALTIVEC_BLITTERS - if(!(surface->map->dst->flags & SDL_HWSURFACE) - && SDL_HasAltiVec()) - return BlitRGBtoRGBPixelAlphaAltivec; + if (!(surface->map->dst->flags & SDL_HWSURFACE) + && SDL_HasAltiVec()) + return BlitRGBtoRGBPixelAlphaAltivec; #endif - return BlitRGBtoRGBPixelAlpha; - } - } + return BlitRGBtoRGBPixelAlpha; + } + } #if SDL_ALTIVEC_BLITTERS - if (sf->Amask && sf->BytesPerPixel == 4 && - !(surface->map->dst->flags & SDL_HWSURFACE) && SDL_HasAltiVec()) - return Blit32to32PixelAlphaAltivec; - else + if (sf->Amask && sf->BytesPerPixel == 4 && + !(surface->map->dst->flags & SDL_HWSURFACE) + && SDL_HasAltiVec()) + return Blit32to32PixelAlphaAltivec; + else #endif - return BlitNtoNPixelAlpha; + return BlitNtoNPixelAlpha; - case 3: - default: - return BlitNtoNPixelAlpha; - } + case 3: + default: + return BlitNtoNPixelAlpha; + } } } +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/SDL_blit_N.c b/src/video/SDL_blit_N.c index 91d66ee6d..13bcd0be4 100644 --- a/src/video/SDL_blit_N.c +++ b/src/video/SDL_blit_N.c @@ -38,20 +38,23 @@ #define assert(X) #ifdef __MACOSX__ #include -static size_t GetL3CacheSize( void ) +static size_t +GetL3CacheSize(void) { const char key[] = "hw.l3cachesize"; u_int64_t result = 0; - size_t typeSize = sizeof( result ); + size_t typeSize = sizeof(result); - int err = sysctlbyname( key, &result, &typeSize, NULL, 0 ); - if( 0 != err ) return 0; + int err = sysctlbyname(key, &result, &typeSize, NULL, 0); + if (0 != err) + return 0; return result; } #else -static size_t GetL3CacheSize( void ) +static size_t +GetL3CacheSize(void) { /* XXX: Just guess G4 */ return 2097152; @@ -59,14 +62,14 @@ static size_t GetL3CacheSize( void ) #endif /* __MACOSX__ */ #if (defined(__MACOSX__) && (__GNUC__ < 4)) - #define VECUINT8_LITERAL(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p) \ +#define VECUINT8_LITERAL(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p) \ (vector unsigned char) ( a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p ) - #define VECUINT16_LITERAL(a,b,c,d,e,f,g,h) \ +#define VECUINT16_LITERAL(a,b,c,d,e,f,g,h) \ (vector unsigned short) ( a,b,c,d,e,f,g,h ) #else - #define VECUINT8_LITERAL(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p) \ +#define VECUINT8_LITERAL(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p) \ (vector unsigned char) { a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p } - #define VECUINT16_LITERAL(a,b,c,d,e,f,g,h) \ +#define VECUINT16_LITERAL(a,b,c,d,e,f,g,h) \ (vector unsigned short) { a,b,c,d,e,f,g,h } #endif @@ -101,11 +104,11 @@ static size_t GetL3CacheSize( void ) : vec_add(vec_lvsl(8, src), vec_splat_u8(8))) /* Calculate the permute vector used for 32->32 swizzling */ -static vector unsigned char calc_swizzle32(const SDL_PixelFormat *srcfmt, - const SDL_PixelFormat *dstfmt) +static vector unsigned char +calc_swizzle32(const SDL_PixelFormat * srcfmt, const SDL_PixelFormat * dstfmt) { /* - * We have to assume that the bits that aren't used by other + * We have to assume that the bits that aren't used by other * colors is alpha, and it's one complete byte, since some formats * leave alpha with a zero mask, but we should still swizzle the bits. */ @@ -115,18 +118,19 @@ static vector unsigned char calc_swizzle32(const SDL_PixelFormat *srcfmt, 0, 0, 0, 0, 16, 8, 0, 24, 0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000, - 0, 0}; + 0, 0 + }; if (!srcfmt) { srcfmt = &default_pixel_format; } if (!dstfmt) { dstfmt = &default_pixel_format; } - const vector unsigned char plus = VECUINT8_LITERAL( - 0x00, 0x00, 0x00, 0x00, - 0x04, 0x04, 0x04, 0x04, - 0x08, 0x08, 0x08, 0x08, - 0x0C, 0x0C, 0x0C, 0x0C ); + const vector unsigned char plus = VECUINT8_LITERAL(0x00, 0x00, 0x00, 0x00, + 0x04, 0x04, 0x04, 0x04, + 0x08, 0x08, 0x08, 0x08, + 0x0C, 0x0C, 0x0C, + 0x0C); vector unsigned char vswiz; vector unsigned int srcvec; #define RESHIFT(X) (3 - ((X) >> 3)) @@ -136,18 +140,24 @@ static vector unsigned char calc_swizzle32(const SDL_PixelFormat *srcfmt, Uint32 amask; /* Use zero for alpha if either surface doesn't have alpha */ if (dstfmt->Amask) { - amask = ((srcfmt->Amask) ? RESHIFT(srcfmt->Ashift) : 0x10) << (dstfmt->Ashift); - } else { - amask = 0x10101010 & ((dstfmt->Rmask | dstfmt->Gmask | dstfmt->Bmask) ^ 0xFFFFFFFF); - } -#undef RESHIFT - ((unsigned int *)(char*)&srcvec)[0] = (rmask | gmask | bmask | amask); - vswiz = vec_add(plus, (vector unsigned char)vec_splat(srcvec, 0)); - return(vswiz); + amask = + ((srcfmt->Amask) ? RESHIFT(srcfmt->Ashift) : 0x10) << (dstfmt-> + Ashift); + } else { + amask = + 0x10101010 & ((dstfmt->Rmask | dstfmt->Gmask | dstfmt->Bmask) ^ + 0xFFFFFFFF); + } +#undef RESHIFT + ((unsigned int *) (char *) &srcvec)[0] = (rmask | gmask | bmask | amask); + vswiz = vec_add(plus, (vector unsigned char) vec_splat(srcvec, 0)); + return (vswiz); } -static void Blit_RGB888_RGB565(SDL_BlitInfo *info); -static void Blit_RGB888_RGB565Altivec(SDL_BlitInfo *info) { +static void Blit_RGB888_RGB565(SDL_BlitInfo * info); +static void +Blit_RGB888_RGB565Altivec(SDL_BlitInfo * info) +{ int height = info->d_height; Uint8 *src = (Uint8 *) info->s_pixels; int srcskip = info->s_skip; @@ -156,20 +166,19 @@ static void Blit_RGB888_RGB565Altivec(SDL_BlitInfo *info) { SDL_PixelFormat *srcfmt = info->src; vector unsigned char valpha = vec_splat_u8(0); vector unsigned char vpermute = calc_swizzle32(srcfmt, NULL); - vector unsigned char vgmerge = VECUINT8_LITERAL( - 0x00, 0x02, 0x00, 0x06, - 0x00, 0x0a, 0x00, 0x0e, - 0x00, 0x12, 0x00, 0x16, - 0x00, 0x1a, 0x00, 0x1e); + vector unsigned char vgmerge = VECUINT8_LITERAL(0x00, 0x02, 0x00, 0x06, + 0x00, 0x0a, 0x00, 0x0e, + 0x00, 0x12, 0x00, 0x16, + 0x00, 0x1a, 0x00, 0x1e); vector unsigned short v1 = vec_splat_u16(1); vector unsigned short v3 = vec_splat_u16(3); - vector unsigned short v3f = VECUINT16_LITERAL( - 0x003f, 0x003f, 0x003f, 0x003f, - 0x003f, 0x003f, 0x003f, 0x003f); - vector unsigned short vfc = VECUINT16_LITERAL( - 0x00fc, 0x00fc, 0x00fc, 0x00fc, - 0x00fc, 0x00fc, 0x00fc, 0x00fc); - vector unsigned short vf800 = (vector unsigned short)vec_splat_u8(-7); + vector unsigned short v3f = + VECUINT16_LITERAL(0x003f, 0x003f, 0x003f, 0x003f, + 0x003f, 0x003f, 0x003f, 0x003f); + vector unsigned short vfc = + VECUINT16_LITERAL(0x00fc, 0x00fc, 0x00fc, 0x00fc, + 0x00fc, 0x00fc, 0x00fc, 0x00fc); + vector unsigned short vf800 = (vector unsigned short) vec_splat_u8(-7); vf800 = vec_sl(vf800, vec_splat_u16(8)); while (height--) { @@ -198,7 +207,7 @@ static void Blit_RGB888_RGB565Altivec(SDL_BlitInfo *info) { ONE_PIXEL_BLEND(((UNALIGNED_PTR(dst)) && (width)), width); /* After all that work, here's the vector part! */ - extrawidth = (width % 8); /* trailing unaligned stores */ + extrawidth = (width % 8); /* trailing unaligned stores */ width -= extrawidth; vsrc = vec_ld(0, src); valigner = VEC_ALIGNER(src); @@ -210,23 +219,25 @@ static void Blit_RGB888_RGB565Altivec(SDL_BlitInfo *info) { voverflow = vec_ld(15, src); vsrc = vec_perm(vsrc, voverflow, valigner); - vsrc1 = (vector unsigned int)vec_perm(vsrc, valpha, vpermute); + vsrc1 = (vector unsigned int) vec_perm(vsrc, valpha, vpermute); src += 16; vsrc = voverflow; voverflow = vec_ld(15, src); vsrc = vec_perm(vsrc, voverflow, valigner); - vsrc2 = (vector unsigned int)vec_perm(vsrc, valpha, vpermute); + vsrc2 = (vector unsigned int) vec_perm(vsrc, valpha, vpermute); /* 1555 */ - vpixel = (vector unsigned short)vec_packpx(vsrc1, vsrc2); - vgpixel = (vector unsigned short)vec_perm(vsrc1, vsrc2, vgmerge); + vpixel = (vector unsigned short) vec_packpx(vsrc1, vsrc2); + vgpixel = (vector unsigned short) vec_perm(vsrc1, vsrc2, vgmerge); vgpixel = vec_and(vgpixel, vfc); vgpixel = vec_sl(vgpixel, v3); vrpixel = vec_sl(vpixel, v1); vrpixel = vec_and(vrpixel, vf800); vbpixel = vec_and(vpixel, v3f); - vdst = vec_or((vector unsigned char)vrpixel, (vector unsigned char)vgpixel); + vdst = + vec_or((vector unsigned char) vrpixel, + (vector unsigned char) vgpixel); /* 565 */ - vdst = vec_or(vdst, (vector unsigned char)vbpixel); + vdst = vec_or(vdst, (vector unsigned char) vbpixel); vec_st(vdst, 0, dst); width -= 8; @@ -241,14 +252,16 @@ static void Blit_RGB888_RGB565Altivec(SDL_BlitInfo *info) { ONE_PIXEL_BLEND((extrawidth), extrawidth); #undef ONE_PIXEL_BLEND - src += srcskip; /* move to next row, accounting for pitch. */ + src += srcskip; /* move to next row, accounting for pitch. */ dst += dstskip; } } -static void Blit_RGB565_32Altivec(SDL_BlitInfo *info) { +static void +Blit_RGB565_32Altivec(SDL_BlitInfo * info) +{ int height = info->d_height; Uint8 *src = (Uint8 *) info->s_pixels; int srcskip = info->s_skip; @@ -265,55 +278,52 @@ static void Blit_RGB565_32Altivec(SDL_BlitInfo *info) { vector unsigned short v2 = vec_splat_u16(2); vector unsigned short v3 = vec_splat_u16(3); /* - 0x10 - 0x1f is the alpha - 0x00 - 0x0e evens are the red - 0x01 - 0x0f odds are zero - */ - vector unsigned char vredalpha1 = VECUINT8_LITERAL( - 0x10, 0x00, 0x01, 0x01, - 0x10, 0x02, 0x01, 0x01, - 0x10, 0x04, 0x01, 0x01, - 0x10, 0x06, 0x01, 0x01 - ); - vector unsigned char vredalpha2 = (vector unsigned char) ( - vec_add((vector unsigned int)vredalpha1, vec_sl(v8, v16)) - ); + 0x10 - 0x1f is the alpha + 0x00 - 0x0e evens are the red + 0x01 - 0x0f odds are zero + */ + vector unsigned char vredalpha1 = VECUINT8_LITERAL(0x10, 0x00, 0x01, 0x01, + 0x10, 0x02, 0x01, 0x01, + 0x10, 0x04, 0x01, 0x01, + 0x10, 0x06, 0x01, + 0x01); + vector unsigned char vredalpha2 = + (vector unsigned + char) (vec_add((vector unsigned int) vredalpha1, vec_sl(v8, v16)) + ); /* - 0x00 - 0x0f is ARxx ARxx ARxx ARxx - 0x11 - 0x0f odds are blue - */ - vector unsigned char vblue1 = VECUINT8_LITERAL( - 0x00, 0x01, 0x02, 0x11, - 0x04, 0x05, 0x06, 0x13, - 0x08, 0x09, 0x0a, 0x15, - 0x0c, 0x0d, 0x0e, 0x17 - ); - vector unsigned char vblue2 = (vector unsigned char)( - vec_add((vector unsigned int)vblue1, v8) - ); + 0x00 - 0x0f is ARxx ARxx ARxx ARxx + 0x11 - 0x0f odds are blue + */ + vector unsigned char vblue1 = VECUINT8_LITERAL(0x00, 0x01, 0x02, 0x11, + 0x04, 0x05, 0x06, 0x13, + 0x08, 0x09, 0x0a, 0x15, + 0x0c, 0x0d, 0x0e, 0x17); + vector unsigned char vblue2 = + (vector unsigned char) (vec_add((vector unsigned int) vblue1, v8) + ); /* - 0x00 - 0x0f is ARxB ARxB ARxB ARxB - 0x10 - 0x0e evens are green - */ - vector unsigned char vgreen1 = VECUINT8_LITERAL( - 0x00, 0x01, 0x10, 0x03, - 0x04, 0x05, 0x12, 0x07, - 0x08, 0x09, 0x14, 0x0b, - 0x0c, 0x0d, 0x16, 0x0f - ); - vector unsigned char vgreen2 = (vector unsigned char)( - vec_add((vector unsigned int)vgreen1, vec_sl(v8, v8)) - ); - + 0x00 - 0x0f is ARxB ARxB ARxB ARxB + 0x10 - 0x0e evens are green + */ + vector unsigned char vgreen1 = VECUINT8_LITERAL(0x00, 0x01, 0x10, 0x03, + 0x04, 0x05, 0x12, 0x07, + 0x08, 0x09, 0x14, 0x0b, + 0x0c, 0x0d, 0x16, 0x0f); + vector unsigned char vgreen2 = + (vector unsigned + char) (vec_add((vector unsigned int) vgreen1, vec_sl(v8, v8)) + ); + assert(srcfmt->BytesPerPixel == 2); assert(dstfmt->BytesPerPixel == 4); - vf800 = (vector unsigned short)vec_splat_u8(-7); + vf800 = (vector unsigned short) vec_splat_u8(-7); vf800 = vec_sl(vf800, vec_splat_u16(8)); if (dstfmt->Amask && srcfmt->alpha) { - ((unsigned char *)&valpha)[0] = alpha = srcfmt->alpha; + ((unsigned char *) &valpha)[0] = alpha = srcfmt->alpha; valpha = vec_splat(valpha, 0); } else { alpha = 0; @@ -345,7 +355,7 @@ static void Blit_RGB565_32Altivec(SDL_BlitInfo *info) { ONE_PIXEL_BLEND(((UNALIGNED_PTR(dst)) && (width)), width); /* After all that work, here's the vector part! */ - extrawidth = (width % 8); /* trailing unaligned stores */ + extrawidth = (width % 8); /* trailing unaligned stores */ width -= extrawidth; vsrc = vec_ld(0, src); valigner = VEC_ALIGNER(src); @@ -357,22 +367,26 @@ static void Blit_RGB565_32Altivec(SDL_BlitInfo *info) { voverflow = vec_ld(15, src); vsrc = vec_perm(vsrc, voverflow, valigner); - vR = vec_and((vector unsigned short)vsrc, vf800); - vB = vec_sl((vector unsigned short)vsrc, v3); + vR = vec_and((vector unsigned short) vsrc, vf800); + vB = vec_sl((vector unsigned short) vsrc, v3); vG = vec_sl(vB, v2); - vdst1 = (vector unsigned char)vec_perm((vector unsigned char)vR, valpha, vredalpha1); - vdst1 = vec_perm(vdst1, (vector unsigned char)vB, vblue1); - vdst1 = vec_perm(vdst1, (vector unsigned char)vG, vgreen1); + vdst1 = + (vector unsigned char) vec_perm((vector unsigned char) vR, + valpha, vredalpha1); + vdst1 = vec_perm(vdst1, (vector unsigned char) vB, vblue1); + vdst1 = vec_perm(vdst1, (vector unsigned char) vG, vgreen1); vdst1 = vec_perm(vdst1, valpha, vpermute); vec_st(vdst1, 0, dst); - vdst2 = (vector unsigned char)vec_perm((vector unsigned char)vR, valpha, vredalpha2); - vdst2 = vec_perm(vdst2, (vector unsigned char)vB, vblue2); - vdst2 = vec_perm(vdst2, (vector unsigned char)vG, vgreen2); + vdst2 = + (vector unsigned char) vec_perm((vector unsigned char) vR, + valpha, vredalpha2); + vdst2 = vec_perm(vdst2, (vector unsigned char) vB, vblue2); + vdst2 = vec_perm(vdst2, (vector unsigned char) vG, vgreen2); vdst2 = vec_perm(vdst2, valpha, vpermute); vec_st(vdst2, 16, dst); - + width -= 8; dst += 32; src += 16; @@ -386,14 +400,16 @@ static void Blit_RGB565_32Altivec(SDL_BlitInfo *info) { ONE_PIXEL_BLEND((extrawidth), extrawidth); #undef ONE_PIXEL_BLEND - src += srcskip; /* move to next row, accounting for pitch. */ + src += srcskip; /* move to next row, accounting for pitch. */ dst += dstskip; } } -static void Blit_RGB555_32Altivec(SDL_BlitInfo *info) { +static void +Blit_RGB555_32Altivec(SDL_BlitInfo * info) +{ int height = info->d_height; Uint8 *src = (Uint8 *) info->s_pixels; int srcskip = info->s_skip; @@ -410,55 +426,52 @@ static void Blit_RGB555_32Altivec(SDL_BlitInfo *info) { vector unsigned short v1 = vec_splat_u16(1); vector unsigned short v3 = vec_splat_u16(3); /* - 0x10 - 0x1f is the alpha - 0x00 - 0x0e evens are the red - 0x01 - 0x0f odds are zero - */ - vector unsigned char vredalpha1 = VECUINT8_LITERAL( - 0x10, 0x00, 0x01, 0x01, - 0x10, 0x02, 0x01, 0x01, - 0x10, 0x04, 0x01, 0x01, - 0x10, 0x06, 0x01, 0x01 - ); - vector unsigned char vredalpha2 = (vector unsigned char)( - vec_add((vector unsigned int)vredalpha1, vec_sl(v8, v16)) - ); + 0x10 - 0x1f is the alpha + 0x00 - 0x0e evens are the red + 0x01 - 0x0f odds are zero + */ + vector unsigned char vredalpha1 = VECUINT8_LITERAL(0x10, 0x00, 0x01, 0x01, + 0x10, 0x02, 0x01, 0x01, + 0x10, 0x04, 0x01, 0x01, + 0x10, 0x06, 0x01, + 0x01); + vector unsigned char vredalpha2 = + (vector unsigned + char) (vec_add((vector unsigned int) vredalpha1, vec_sl(v8, v16)) + ); /* - 0x00 - 0x0f is ARxx ARxx ARxx ARxx - 0x11 - 0x0f odds are blue - */ - vector unsigned char vblue1 = VECUINT8_LITERAL( - 0x00, 0x01, 0x02, 0x11, - 0x04, 0x05, 0x06, 0x13, - 0x08, 0x09, 0x0a, 0x15, - 0x0c, 0x0d, 0x0e, 0x17 - ); - vector unsigned char vblue2 = (vector unsigned char)( - vec_add((vector unsigned int)vblue1, v8) - ); + 0x00 - 0x0f is ARxx ARxx ARxx ARxx + 0x11 - 0x0f odds are blue + */ + vector unsigned char vblue1 = VECUINT8_LITERAL(0x00, 0x01, 0x02, 0x11, + 0x04, 0x05, 0x06, 0x13, + 0x08, 0x09, 0x0a, 0x15, + 0x0c, 0x0d, 0x0e, 0x17); + vector unsigned char vblue2 = + (vector unsigned char) (vec_add((vector unsigned int) vblue1, v8) + ); /* - 0x00 - 0x0f is ARxB ARxB ARxB ARxB - 0x10 - 0x0e evens are green - */ - vector unsigned char vgreen1 = VECUINT8_LITERAL( - 0x00, 0x01, 0x10, 0x03, - 0x04, 0x05, 0x12, 0x07, - 0x08, 0x09, 0x14, 0x0b, - 0x0c, 0x0d, 0x16, 0x0f - ); - vector unsigned char vgreen2 = (vector unsigned char)( - vec_add((vector unsigned int)vgreen1, vec_sl(v8, v8)) - ); - + 0x00 - 0x0f is ARxB ARxB ARxB ARxB + 0x10 - 0x0e evens are green + */ + vector unsigned char vgreen1 = VECUINT8_LITERAL(0x00, 0x01, 0x10, 0x03, + 0x04, 0x05, 0x12, 0x07, + 0x08, 0x09, 0x14, 0x0b, + 0x0c, 0x0d, 0x16, 0x0f); + vector unsigned char vgreen2 = + (vector unsigned + char) (vec_add((vector unsigned int) vgreen1, vec_sl(v8, v8)) + ); + assert(srcfmt->BytesPerPixel == 2); assert(dstfmt->BytesPerPixel == 4); - vf800 = (vector unsigned short)vec_splat_u8(-7); + vf800 = (vector unsigned short) vec_splat_u8(-7); vf800 = vec_sl(vf800, vec_splat_u16(8)); if (dstfmt->Amask && srcfmt->alpha) { - ((unsigned char *)&valpha)[0] = alpha = srcfmt->alpha; + ((unsigned char *) &valpha)[0] = alpha = srcfmt->alpha; valpha = vec_splat(valpha, 0); } else { alpha = 0; @@ -490,7 +503,7 @@ static void Blit_RGB555_32Altivec(SDL_BlitInfo *info) { ONE_PIXEL_BLEND(((UNALIGNED_PTR(dst)) && (width)), width); /* After all that work, here's the vector part! */ - extrawidth = (width % 8); /* trailing unaligned stores */ + extrawidth = (width % 8); /* trailing unaligned stores */ width -= extrawidth; vsrc = vec_ld(0, src); valigner = VEC_ALIGNER(src); @@ -502,22 +515,26 @@ static void Blit_RGB555_32Altivec(SDL_BlitInfo *info) { voverflow = vec_ld(15, src); vsrc = vec_perm(vsrc, voverflow, valigner); - vR = vec_and(vec_sl((vector unsigned short)vsrc,v1), vf800); - vB = vec_sl((vector unsigned short)vsrc, v3); + vR = vec_and(vec_sl((vector unsigned short) vsrc, v1), vf800); + vB = vec_sl((vector unsigned short) vsrc, v3); vG = vec_sl(vB, v3); - vdst1 = (vector unsigned char)vec_perm((vector unsigned char)vR, valpha, vredalpha1); - vdst1 = vec_perm(vdst1, (vector unsigned char)vB, vblue1); - vdst1 = vec_perm(vdst1, (vector unsigned char)vG, vgreen1); + vdst1 = + (vector unsigned char) vec_perm((vector unsigned char) vR, + valpha, vredalpha1); + vdst1 = vec_perm(vdst1, (vector unsigned char) vB, vblue1); + vdst1 = vec_perm(vdst1, (vector unsigned char) vG, vgreen1); vdst1 = vec_perm(vdst1, valpha, vpermute); vec_st(vdst1, 0, dst); - vdst2 = (vector unsigned char)vec_perm((vector unsigned char)vR, valpha, vredalpha2); - vdst2 = vec_perm(vdst2, (vector unsigned char)vB, vblue2); - vdst2 = vec_perm(vdst2, (vector unsigned char)vG, vgreen2); + vdst2 = + (vector unsigned char) vec_perm((vector unsigned char) vR, + valpha, vredalpha2); + vdst2 = vec_perm(vdst2, (vector unsigned char) vB, vblue2); + vdst2 = vec_perm(vdst2, (vector unsigned char) vG, vgreen2); vdst2 = vec_perm(vdst2, valpha, vpermute); vec_st(vdst2, 16, dst); - + width -= 8; dst += 32; src += 16; @@ -531,15 +548,16 @@ static void Blit_RGB555_32Altivec(SDL_BlitInfo *info) { ONE_PIXEL_BLEND((extrawidth), extrawidth); #undef ONE_PIXEL_BLEND - src += srcskip; /* move to next row, accounting for pitch. */ + src += srcskip; /* move to next row, accounting for pitch. */ dst += dstskip; } } -static void BlitNtoNKey(SDL_BlitInfo *info); -static void BlitNtoNKeyCopyAlpha(SDL_BlitInfo *info); -static void Blit32to32KeyAltivec(SDL_BlitInfo *info) +static void BlitNtoNKey(SDL_BlitInfo * info); +static void BlitNtoNKeyCopyAlpha(SDL_BlitInfo * info); +static void +Blit32to32KeyAltivec(SDL_BlitInfo * info) { int height = info->d_height; Uint32 *srcp = (Uint32 *) info->s_pixels; @@ -551,9 +569,9 @@ static void Blit32to32KeyAltivec(SDL_BlitInfo *info) SDL_PixelFormat *dstfmt = info->dst; int dstbpp = dstfmt->BytesPerPixel; int copy_alpha = (srcfmt->Amask && dstfmt->Amask); - unsigned alpha = dstfmt->Amask ? srcfmt->alpha : 0; + unsigned alpha = dstfmt->Amask ? srcfmt->alpha : 0; Uint32 rgbmask = srcfmt->Rmask | srcfmt->Gmask | srcfmt->Bmask; - Uint32 ckey = info->src->colorkey; + Uint32 ckey = info->src->colorkey; vector unsigned int valpha; vector unsigned char vpermute; vector unsigned char vzero; @@ -561,7 +579,7 @@ static void Blit32to32KeyAltivec(SDL_BlitInfo *info) vector unsigned int vrgbmask; vpermute = calc_swizzle32(srcfmt, dstfmt); if (info->d_width < 16) { - if(copy_alpha) { + if (copy_alpha) { BlitNtoNKeyCopyAlpha(info); } else { BlitNtoNKey(info); @@ -570,15 +588,16 @@ static void Blit32to32KeyAltivec(SDL_BlitInfo *info) } vzero = vec_splat_u8(0); if (alpha) { - ((unsigned char *)&valpha)[0] = (unsigned char)alpha; - valpha = (vector unsigned int)vec_splat((vector unsigned char)valpha, 0); + ((unsigned char *) &valpha)[0] = (unsigned char) alpha; + valpha = + (vector unsigned int) vec_splat((vector unsigned char) valpha, 0); } else { - valpha = (vector unsigned int)vzero; + valpha = (vector unsigned int) vzero; } ckey &= rgbmask; - ((unsigned int *)(char*)&vckey)[0] = ckey; + ((unsigned int *) (char *) &vckey)[0] = ckey; vckey = vec_splat(vckey, 0); - ((unsigned int *)(char*)&vrgbmask)[0] = rgbmask; + ((unsigned int *) (char *) &vrgbmask)[0] = rgbmask; vrgbmask = vec_splat(vrgbmask, 0); while (height--) { @@ -628,15 +647,17 @@ static void Blit32to32KeyAltivec(SDL_BlitInfo *info) /* load the source vec */ vs = vec_perm(vs, voverflow, valigner); /* vsel is set for items that match the key */ - vsel = (vector unsigned char)vec_and(vs, vrgbmask); - vsel = (vector unsigned char)vec_cmpeq(vs, vckey); + vsel = (vector unsigned char) vec_and(vs, vrgbmask); + vsel = (vector unsigned char) vec_cmpeq(vs, vckey); /* permute the src vec to the dest format */ vs = vec_perm(vs, valpha, vpermute); /* load the destination vec */ vd = vec_ld(0, dstp); /* select the source and dest into vs */ - vd = (vector unsigned int)vec_sel((vector unsigned char)vs, (vector unsigned char)vd, vsel); - + vd = (vector unsigned int) vec_sel((vector unsigned char) vs, + (vector unsigned char) vd, + vsel); + vec_st(vd, 0, dstp); srcp += 4; width -= 4; @@ -653,7 +674,8 @@ static void Blit32to32KeyAltivec(SDL_BlitInfo *info) /* Altivec code to swizzle one 32-bit surface to a different 32-bit format. */ /* Use this on a G5 */ -static void ConvertAltivec32to32_noprefetch(SDL_BlitInfo *info) +static void +ConvertAltivec32to32_noprefetch(SDL_BlitInfo * info) { int height = info->d_height; Uint32 *src = (Uint32 *) info->s_pixels; @@ -667,8 +689,8 @@ static void ConvertAltivec32to32_noprefetch(SDL_BlitInfo *info) if (dstfmt->Amask && !srcfmt->Amask) { if (srcfmt->alpha) { vector unsigned char valpha; - ((unsigned char *)&valpha)[0] = srcfmt->alpha; - vzero = (vector unsigned int)vec_splat(valpha, 0); + ((unsigned char *) &valpha)[0] = srcfmt->alpha; + vzero = (vector unsigned int) vec_splat(valpha, 0); } } @@ -699,13 +721,13 @@ static void ConvertAltivec32to32_noprefetch(SDL_BlitInfo *info) valigner = VEC_ALIGNER(src); vbits = vec_ld(0, src); - while (width) { + while (width) { voverflow = vec_ld(15, src); src += 4; width -= 4; - vbits = vec_perm(vbits, voverflow, valigner); /* src is ready. */ - vbits = vec_perm(vbits, vzero, vpermute); /* swizzle it. */ - vec_st(vbits, 0, dst); /* store it back out. */ + vbits = vec_perm(vbits, voverflow, valigner); /* src is ready. */ + vbits = vec_perm(vbits, vzero, vpermute); /* swizzle it. */ + vec_st(vbits, 0, dst); /* store it back out. */ dst += 4; vbits = voverflow; } @@ -714,13 +736,13 @@ static void ConvertAltivec32to32_noprefetch(SDL_BlitInfo *info) /* cover pixels at the end of the row that didn't fit in 16 bytes. */ while (extrawidth) { - bits = *(src++); /* max 7 pixels, don't bother with prefetch. */ + bits = *(src++); /* max 7 pixels, don't bother with prefetch. */ RGBA_FROM_8888(bits, srcfmt, r, g, b, a); *(dst++) = MAKE8888(dstfmt, r, g, b, a); extrawidth--; } - src += srcskip >> 2; /* move to next row, accounting for pitch. */ + src += srcskip >> 2; /* move to next row, accounting for pitch. */ dst += dstskip >> 2; } @@ -728,10 +750,11 @@ static void ConvertAltivec32to32_noprefetch(SDL_BlitInfo *info) /* Altivec code to swizzle one 32-bit surface to a different 32-bit format. */ /* Use this on a G4 */ -static void ConvertAltivec32to32_prefetch(SDL_BlitInfo *info) +static void +ConvertAltivec32to32_prefetch(SDL_BlitInfo * info) { - const int scalar_dst_lead = sizeof (Uint32) * 4; - const int vector_dst_lead = sizeof (Uint32) * 16; + const int scalar_dst_lead = sizeof(Uint32) * 4; + const int vector_dst_lead = sizeof(Uint32) * 16; int height = info->d_height; Uint32 *src = (Uint32 *) info->s_pixels; @@ -745,8 +768,8 @@ static void ConvertAltivec32to32_prefetch(SDL_BlitInfo *info) if (dstfmt->Amask && !srcfmt->Amask) { if (srcfmt->alpha) { vector unsigned char valpha; - ((unsigned char *)&valpha)[0] = srcfmt->alpha; - vzero = (vector unsigned int)vec_splat(valpha, 0); + ((unsigned char *) &valpha)[0] = srcfmt->alpha; + vzero = (vector unsigned int) vec_splat(valpha, 0); } } @@ -765,8 +788,10 @@ static void ConvertAltivec32to32_prefetch(SDL_BlitInfo *info) /* do scalar until we can align... */ while ((UNALIGNED_PTR(dst)) && (width)) { - vec_dstt(src+scalar_dst_lead, DST_CTRL(2,32,1024), DST_CHAN_SRC); - vec_dstst(dst+scalar_dst_lead, DST_CTRL(2,32,1024), DST_CHAN_DEST); + vec_dstt(src + scalar_dst_lead, DST_CTRL(2, 32, 1024), + DST_CHAN_SRC); + vec_dstst(dst + scalar_dst_lead, DST_CTRL(2, 32, 1024), + DST_CHAN_DEST); bits = *(src++); RGBA_FROM_8888(bits, srcfmt, r, g, b, a); *(dst++) = MAKE8888(dstfmt, r, g, b, a); @@ -780,29 +805,31 @@ static void ConvertAltivec32to32_prefetch(SDL_BlitInfo *info) vbits = vec_ld(0, src); while (width) { - vec_dstt(src+vector_dst_lead, DST_CTRL(2,32,1024), DST_CHAN_SRC); - vec_dstst(dst+vector_dst_lead, DST_CTRL(2,32,1024), DST_CHAN_DEST); + vec_dstt(src + vector_dst_lead, DST_CTRL(2, 32, 1024), + DST_CHAN_SRC); + vec_dstst(dst + vector_dst_lead, DST_CTRL(2, 32, 1024), + DST_CHAN_DEST); voverflow = vec_ld(15, src); src += 4; width -= 4; - vbits = vec_perm(vbits, voverflow, valigner); /* src is ready. */ - vbits = vec_perm(vbits, vzero, vpermute); /* swizzle it. */ - vec_st(vbits, 0, dst); /* store it back out. */ + vbits = vec_perm(vbits, voverflow, valigner); /* src is ready. */ + vbits = vec_perm(vbits, vzero, vpermute); /* swizzle it. */ + vec_st(vbits, 0, dst); /* store it back out. */ dst += 4; vbits = voverflow; } - + assert(width == 0); /* cover pixels at the end of the row that didn't fit in 16 bytes. */ while (extrawidth) { - bits = *(src++); /* max 7 pixels, don't bother with prefetch. */ + bits = *(src++); /* max 7 pixels, don't bother with prefetch. */ RGBA_FROM_8888(bits, srcfmt, r, g, b, a); *(dst++) = MAKE8888(dstfmt, r, g, b, a); extrawidth--; } - src += srcskip >> 2; /* move to next row, accounting for pitch. */ + src += srcskip >> 2; /* move to next row, accounting for pitch. */ dst += dstskip >> 2; } @@ -810,7 +837,8 @@ static void ConvertAltivec32to32_prefetch(SDL_BlitInfo *info) vec_dss(DST_CHAN_DEST); } -static Uint32 GetBlitFeatures( void ) +static Uint32 +GetBlitFeatures(void) { static Uint32 features = 0xffffffff; if (features == 0xffffffff) { @@ -820,19 +848,20 @@ static Uint32 GetBlitFeatures( void ) features = 0; SDL_sscanf(override, "%u", &features); } else { - features = ( 0 - /* Feature 1 is has-MMX */ - | ((SDL_HasMMX()) ? 1 : 0) - /* Feature 2 is has-AltiVec */ - | ((SDL_HasAltiVec()) ? 2 : 0) - /* Feature 4 is dont-use-prefetch */ - /* !!!! FIXME: Check for G5 or later, not the cache size! Always prefetch on a G4. */ - | ((GetL3CacheSize() == 0) ? 4 : 0) - ); + features = (0 + /* Feature 1 is has-MMX */ + | ((SDL_HasMMX())? 1 : 0) + /* Feature 2 is has-AltiVec */ + | ((SDL_HasAltiVec())? 2 : 0) + /* Feature 4 is dont-use-prefetch */ + /* !!!! FIXME: Check for G5 or later, not the cache size! Always prefetch on a G4. */ + | ((GetL3CacheSize() == 0) ? 4 : 0) + ); } } return features; } + #if __MWERKS__ #pragma altivec_model off #endif @@ -869,104 +898,110 @@ static Uint32 GetBlitFeatures( void ) (((src)&0x0000E000)>>11)| \ (((src)&0x000000C0)>>6)); \ } -static void Blit_RGB888_index8(SDL_BlitInfo *info) +static void +Blit_RGB888_index8(SDL_BlitInfo * info) { #ifndef USE_DUFFS_LOOP - int c; + int c; #endif - int width, height; - Uint32 *src; - const Uint8 *map; - Uint8 *dst; - int srcskip, dstskip; - - /* Set up some basic variables */ - width = info->d_width; - height = info->d_height; - src = (Uint32 *)info->s_pixels; - srcskip = info->s_skip/4; - dst = info->d_pixels; - dstskip = info->d_skip; - map = info->table; - - if ( map == NULL ) { - while ( height-- ) { + int width, height; + Uint32 *src; + const Uint8 *map; + Uint8 *dst; + int srcskip, dstskip; + + /* Set up some basic variables */ + width = info->d_width; + height = info->d_height; + src = (Uint32 *) info->s_pixels; + srcskip = info->s_skip / 4; + dst = info->d_pixels; + dstskip = info->d_skip; + map = info->table; + + if (map == NULL) { + while (height--) { #ifdef USE_DUFFS_LOOP + /* *INDENT-OFF* */ DUFFS_LOOP( RGB888_RGB332(*dst++, *src); , width); + /* *INDENT-ON* */ #else - for ( c=width/4; c; --c ) { - /* Pack RGB into 8bit pixel */ - ++src; - RGB888_RGB332(*dst++, *src); - ++src; - RGB888_RGB332(*dst++, *src); - ++src; - RGB888_RGB332(*dst++, *src); - ++src; - } - switch ( width & 3 ) { - case 3: - RGB888_RGB332(*dst++, *src); - ++src; - case 2: - RGB888_RGB332(*dst++, *src); - ++src; - case 1: - RGB888_RGB332(*dst++, *src); - ++src; - } + for (c = width / 4; c; --c) { + /* Pack RGB into 8bit pixel */ + ++src; + RGB888_RGB332(*dst++, *src); + ++src; + RGB888_RGB332(*dst++, *src); + ++src; + RGB888_RGB332(*dst++, *src); + ++src; + } + switch (width & 3) { + case 3: + RGB888_RGB332(*dst++, *src); + ++src; + case 2: + RGB888_RGB332(*dst++, *src); + ++src; + case 1: + RGB888_RGB332(*dst++, *src); + ++src; + } #endif /* USE_DUFFS_LOOP */ - src += srcskip; - dst += dstskip; - } - } else { - int Pixel; + src += srcskip; + dst += dstskip; + } + } else { + int Pixel; - while ( height-- ) { + while (height--) { #ifdef USE_DUFFS_LOOP + /* *INDENT-OFF* */ DUFFS_LOOP( RGB888_RGB332(Pixel, *src); *dst++ = map[Pixel]; ++src; , width); + /* *INDENT-ON* */ #else - for ( c=width/4; c; --c ) { - /* Pack RGB into 8bit pixel */ - RGB888_RGB332(Pixel, *src); - *dst++ = map[Pixel]; - ++src; - RGB888_RGB332(Pixel, *src); - *dst++ = map[Pixel]; - ++src; - RGB888_RGB332(Pixel, *src); - *dst++ = map[Pixel]; - ++src; - RGB888_RGB332(Pixel, *src); - *dst++ = map[Pixel]; - ++src; - } - switch ( width & 3 ) { - case 3: - RGB888_RGB332(Pixel, *src); - *dst++ = map[Pixel]; - ++src; - case 2: - RGB888_RGB332(Pixel, *src); - *dst++ = map[Pixel]; - ++src; - case 1: - RGB888_RGB332(Pixel, *src); - *dst++ = map[Pixel]; - ++src; - } + for (c = width / 4; c; --c) { + /* Pack RGB into 8bit pixel */ + RGB888_RGB332(Pixel, *src); + *dst++ = map[Pixel]; + ++src; + RGB888_RGB332(Pixel, *src); + *dst++ = map[Pixel]; + ++src; + RGB888_RGB332(Pixel, *src); + *dst++ = map[Pixel]; + ++src; + RGB888_RGB332(Pixel, *src); + *dst++ = map[Pixel]; + ++src; + } + switch (width & 3) { + case 3: + RGB888_RGB332(Pixel, *src); + *dst++ = map[Pixel]; + ++src; + case 2: + RGB888_RGB332(Pixel, *src); + *dst++ = map[Pixel]; + ++src; + case 1: + RGB888_RGB332(Pixel, *src); + *dst++ = map[Pixel]; + ++src; + } #endif /* USE_DUFFS_LOOP */ - src += srcskip; - dst += dstskip; - } - } + src += srcskip; + dst += dstskip; + } + } } + /* Special optimized blit for RGB 8-8-8 --> RGB 5-5-5 */ #define RGB888_RGB555(dst, src) { \ *(Uint16 *)(dst) = (Uint16)((((*src)&0x00F80000)>>9)| \ @@ -981,112 +1016,116 @@ static void Blit_RGB888_index8(SDL_BlitInfo *info) (((src[LO])&0x0000F800)>>6)| \ (((src[LO])&0x000000F8)>>3); \ } -static void Blit_RGB888_RGB555(SDL_BlitInfo *info) +static void +Blit_RGB888_RGB555(SDL_BlitInfo * info) { #ifndef USE_DUFFS_LOOP - int c; + int c; #endif - int width, height; - Uint32 *src; - Uint16 *dst; - int srcskip, dstskip; - - /* Set up some basic variables */ - width = info->d_width; - height = info->d_height; - src = (Uint32 *)info->s_pixels; - srcskip = info->s_skip/4; - dst = (Uint16 *)info->d_pixels; - dstskip = info->d_skip/2; + int width, height; + Uint32 *src; + Uint16 *dst; + int srcskip, dstskip; + + /* Set up some basic variables */ + width = info->d_width; + height = info->d_height; + src = (Uint32 *) info->s_pixels; + srcskip = info->s_skip / 4; + dst = (Uint16 *) info->d_pixels; + dstskip = info->d_skip / 2; #ifdef USE_DUFFS_LOOP - while ( height-- ) { + while (height--) { + /* *INDENT-OFF* */ DUFFS_LOOP( RGB888_RGB555(dst, src); ++src; ++dst; , width); - src += srcskip; - dst += dstskip; - } + /* *INDENT-ON* */ + src += srcskip; + dst += dstskip; + } #else - /* Memory align at 4-byte boundary, if necessary */ - if ( (long)dst & 0x03 ) { - /* Don't do anything if width is 0 */ - if ( width == 0 ) { - return; - } - --width; - - while ( height-- ) { - /* Perform copy alignment */ - RGB888_RGB555(dst, src); - ++src; - ++dst; - - /* Copy in 4 pixel chunks */ - for ( c=width/4; c; --c ) { - RGB888_RGB555_TWO(dst, src); - src += 2; - dst += 2; - RGB888_RGB555_TWO(dst, src); - src += 2; - dst += 2; - } - /* Get any leftovers */ - switch (width & 3) { - case 3: - RGB888_RGB555(dst, src); - ++src; - ++dst; - case 2: - RGB888_RGB555_TWO(dst, src); - src += 2; - dst += 2; - break; - case 1: - RGB888_RGB555(dst, src); - ++src; - ++dst; - break; - } - src += srcskip; - dst += dstskip; - } - } else { - while ( height-- ) { - /* Copy in 4 pixel chunks */ - for ( c=width/4; c; --c ) { - RGB888_RGB555_TWO(dst, src); - src += 2; - dst += 2; - RGB888_RGB555_TWO(dst, src); - src += 2; - dst += 2; - } - /* Get any leftovers */ - switch (width & 3) { - case 3: - RGB888_RGB555(dst, src); - ++src; - ++dst; - case 2: - RGB888_RGB555_TWO(dst, src); - src += 2; - dst += 2; - break; - case 1: - RGB888_RGB555(dst, src); - ++src; - ++dst; - break; - } - src += srcskip; - dst += dstskip; - } - } + /* Memory align at 4-byte boundary, if necessary */ + if ((long) dst & 0x03) { + /* Don't do anything if width is 0 */ + if (width == 0) { + return; + } + --width; + + while (height--) { + /* Perform copy alignment */ + RGB888_RGB555(dst, src); + ++src; + ++dst; + + /* Copy in 4 pixel chunks */ + for (c = width / 4; c; --c) { + RGB888_RGB555_TWO(dst, src); + src += 2; + dst += 2; + RGB888_RGB555_TWO(dst, src); + src += 2; + dst += 2; + } + /* Get any leftovers */ + switch (width & 3) { + case 3: + RGB888_RGB555(dst, src); + ++src; + ++dst; + case 2: + RGB888_RGB555_TWO(dst, src); + src += 2; + dst += 2; + break; + case 1: + RGB888_RGB555(dst, src); + ++src; + ++dst; + break; + } + src += srcskip; + dst += dstskip; + } + } else { + while (height--) { + /* Copy in 4 pixel chunks */ + for (c = width / 4; c; --c) { + RGB888_RGB555_TWO(dst, src); + src += 2; + dst += 2; + RGB888_RGB555_TWO(dst, src); + src += 2; + dst += 2; + } + /* Get any leftovers */ + switch (width & 3) { + case 3: + RGB888_RGB555(dst, src); + ++src; + ++dst; + case 2: + RGB888_RGB555_TWO(dst, src); + src += 2; + dst += 2; + break; + case 1: + RGB888_RGB555(dst, src); + ++src; + ++dst; + break; + } + src += srcskip; + dst += dstskip; + } + } #endif /* USE_DUFFS_LOOP */ } + /* Special optimized blit for RGB 8-8-8 --> RGB 5-6-5 */ #define RGB888_RGB565(dst, src) { \ *(Uint16 *)(dst) = (Uint16)((((*src)&0x00F80000)>>8)| \ @@ -1101,110 +1140,113 @@ static void Blit_RGB888_RGB555(SDL_BlitInfo *info) (((src[LO])&0x0000FC00)>>5)| \ (((src[LO])&0x000000F8)>>3); \ } -static void Blit_RGB888_RGB565(SDL_BlitInfo *info) +static void +Blit_RGB888_RGB565(SDL_BlitInfo * info) { #ifndef USE_DUFFS_LOOP - int c; + int c; #endif - int width, height; - Uint32 *src; - Uint16 *dst; - int srcskip, dstskip; - - /* Set up some basic variables */ - width = info->d_width; - height = info->d_height; - src = (Uint32 *)info->s_pixels; - srcskip = info->s_skip/4; - dst = (Uint16 *)info->d_pixels; - dstskip = info->d_skip/2; + int width, height; + Uint32 *src; + Uint16 *dst; + int srcskip, dstskip; + + /* Set up some basic variables */ + width = info->d_width; + height = info->d_height; + src = (Uint32 *) info->s_pixels; + srcskip = info->s_skip / 4; + dst = (Uint16 *) info->d_pixels; + dstskip = info->d_skip / 2; #ifdef USE_DUFFS_LOOP - while ( height-- ) { + while (height--) { + /* *INDENT-OFF* */ DUFFS_LOOP( RGB888_RGB565(dst, src); ++src; ++dst; , width); - src += srcskip; - dst += dstskip; - } + /* *INDENT-ON* */ + src += srcskip; + dst += dstskip; + } #else - /* Memory align at 4-byte boundary, if necessary */ - if ( (long)dst & 0x03 ) { - /* Don't do anything if width is 0 */ - if ( width == 0 ) { - return; - } - --width; - - while ( height-- ) { - /* Perform copy alignment */ - RGB888_RGB565(dst, src); - ++src; - ++dst; - - /* Copy in 4 pixel chunks */ - for ( c=width/4; c; --c ) { - RGB888_RGB565_TWO(dst, src); - src += 2; - dst += 2; - RGB888_RGB565_TWO(dst, src); - src += 2; - dst += 2; - } - /* Get any leftovers */ - switch (width & 3) { - case 3: - RGB888_RGB565(dst, src); - ++src; - ++dst; - case 2: - RGB888_RGB565_TWO(dst, src); - src += 2; - dst += 2; - break; - case 1: - RGB888_RGB565(dst, src); - ++src; - ++dst; - break; - } - src += srcskip; - dst += dstskip; - } - } else { - while ( height-- ) { - /* Copy in 4 pixel chunks */ - for ( c=width/4; c; --c ) { - RGB888_RGB565_TWO(dst, src); - src += 2; - dst += 2; - RGB888_RGB565_TWO(dst, src); - src += 2; - dst += 2; - } - /* Get any leftovers */ - switch (width & 3) { - case 3: - RGB888_RGB565(dst, src); - ++src; - ++dst; - case 2: - RGB888_RGB565_TWO(dst, src); - src += 2; - dst += 2; - break; - case 1: - RGB888_RGB565(dst, src); - ++src; - ++dst; - break; - } - src += srcskip; - dst += dstskip; - } - } + /* Memory align at 4-byte boundary, if necessary */ + if ((long) dst & 0x03) { + /* Don't do anything if width is 0 */ + if (width == 0) { + return; + } + --width; + + while (height--) { + /* Perform copy alignment */ + RGB888_RGB565(dst, src); + ++src; + ++dst; + + /* Copy in 4 pixel chunks */ + for (c = width / 4; c; --c) { + RGB888_RGB565_TWO(dst, src); + src += 2; + dst += 2; + RGB888_RGB565_TWO(dst, src); + src += 2; + dst += 2; + } + /* Get any leftovers */ + switch (width & 3) { + case 3: + RGB888_RGB565(dst, src); + ++src; + ++dst; + case 2: + RGB888_RGB565_TWO(dst, src); + src += 2; + dst += 2; + break; + case 1: + RGB888_RGB565(dst, src); + ++src; + ++dst; + break; + } + src += srcskip; + dst += dstskip; + } + } else { + while (height--) { + /* Copy in 4 pixel chunks */ + for (c = width / 4; c; --c) { + RGB888_RGB565_TWO(dst, src); + src += 2; + dst += 2; + RGB888_RGB565_TWO(dst, src); + src += 2; + dst += 2; + } + /* Get any leftovers */ + switch (width & 3) { + case 3: + RGB888_RGB565(dst, src); + ++src; + ++dst; + case 2: + RGB888_RGB565_TWO(dst, src); + src += 2; + dst += 2; + break; + case 1: + RGB888_RGB565(dst, src); + ++src; + ++dst; + break; + } + src += srcskip; + dst += dstskip; + } + } #endif /* USE_DUFFS_LOOP */ } @@ -1213,607 +1255,614 @@ static void Blit_RGB888_RGB565(SDL_BlitInfo *info) /* Special optimized blit for RGB 5-6-5 --> 32-bit RGB surfaces */ #define RGB565_32(dst, src, map) (map[src[LO]*2] + map[src[HI]*2+1]) -static void Blit_RGB565_32(SDL_BlitInfo *info, const Uint32 *map) +static void +Blit_RGB565_32(SDL_BlitInfo * info, const Uint32 * map) { #ifndef USE_DUFFS_LOOP - int c; + int c; #endif - int width, height; - Uint8 *src; - Uint32 *dst; - int srcskip, dstskip; - - /* Set up some basic variables */ - width = info->d_width; - height = info->d_height; - src = (Uint8 *)info->s_pixels; - srcskip = info->s_skip; - dst = (Uint32 *)info->d_pixels; - dstskip = info->d_skip/4; + int width, height; + Uint8 *src; + Uint32 *dst; + int srcskip, dstskip; + + /* Set up some basic variables */ + width = info->d_width; + height = info->d_height; + src = (Uint8 *) info->s_pixels; + srcskip = info->s_skip; + dst = (Uint32 *) info->d_pixels; + dstskip = info->d_skip / 4; #ifdef USE_DUFFS_LOOP - while ( height-- ) { + while (height--) { + /* *INDENT-OFF* */ DUFFS_LOOP( { *dst++ = RGB565_32(dst, src, map); src += 2; }, width); - src += srcskip; - dst += dstskip; - } + /* *INDENT-ON* */ + src += srcskip; + dst += dstskip; + } #else - while ( height-- ) { - /* Copy in 4 pixel chunks */ - for ( c=width/4; c; --c ) { - *dst++ = RGB565_32(dst, src, map); - src += 2; - *dst++ = RGB565_32(dst, src, map); - src += 2; - *dst++ = RGB565_32(dst, src, map); - src += 2; - *dst++ = RGB565_32(dst, src, map); - src += 2; - } - /* Get any leftovers */ - switch (width & 3) { - case 3: - *dst++ = RGB565_32(dst, src, map); - src += 2; - case 2: - *dst++ = RGB565_32(dst, src, map); - src += 2; - case 1: - *dst++ = RGB565_32(dst, src, map); - src += 2; - break; - } - src += srcskip; - dst += dstskip; - } + while (height--) { + /* Copy in 4 pixel chunks */ + for (c = width / 4; c; --c) { + *dst++ = RGB565_32(dst, src, map); + src += 2; + *dst++ = RGB565_32(dst, src, map); + src += 2; + *dst++ = RGB565_32(dst, src, map); + src += 2; + *dst++ = RGB565_32(dst, src, map); + src += 2; + } + /* Get any leftovers */ + switch (width & 3) { + case 3: + *dst++ = RGB565_32(dst, src, map); + src += 2; + case 2: + *dst++ = RGB565_32(dst, src, map); + src += 2; + case 1: + *dst++ = RGB565_32(dst, src, map); + src += 2; + break; + } + src += srcskip; + dst += dstskip; + } #endif /* USE_DUFFS_LOOP */ } /* Special optimized blit for RGB 5-6-5 --> ARGB 8-8-8-8 */ static const Uint32 RGB565_ARGB8888_LUT[512] = { - 0x00000000, 0xff000000, 0x00000008, 0xff002000, - 0x00000010, 0xff004000, 0x00000018, 0xff006100, - 0x00000020, 0xff008100, 0x00000029, 0xff00a100, - 0x00000031, 0xff00c200, 0x00000039, 0xff00e200, - 0x00000041, 0xff080000, 0x0000004a, 0xff082000, - 0x00000052, 0xff084000, 0x0000005a, 0xff086100, - 0x00000062, 0xff088100, 0x0000006a, 0xff08a100, - 0x00000073, 0xff08c200, 0x0000007b, 0xff08e200, - 0x00000083, 0xff100000, 0x0000008b, 0xff102000, - 0x00000094, 0xff104000, 0x0000009c, 0xff106100, - 0x000000a4, 0xff108100, 0x000000ac, 0xff10a100, - 0x000000b4, 0xff10c200, 0x000000bd, 0xff10e200, - 0x000000c5, 0xff180000, 0x000000cd, 0xff182000, - 0x000000d5, 0xff184000, 0x000000de, 0xff186100, - 0x000000e6, 0xff188100, 0x000000ee, 0xff18a100, - 0x000000f6, 0xff18c200, 0x000000ff, 0xff18e200, - 0x00000400, 0xff200000, 0x00000408, 0xff202000, - 0x00000410, 0xff204000, 0x00000418, 0xff206100, - 0x00000420, 0xff208100, 0x00000429, 0xff20a100, - 0x00000431, 0xff20c200, 0x00000439, 0xff20e200, - 0x00000441, 0xff290000, 0x0000044a, 0xff292000, - 0x00000452, 0xff294000, 0x0000045a, 0xff296100, - 0x00000462, 0xff298100, 0x0000046a, 0xff29a100, - 0x00000473, 0xff29c200, 0x0000047b, 0xff29e200, - 0x00000483, 0xff310000, 0x0000048b, 0xff312000, - 0x00000494, 0xff314000, 0x0000049c, 0xff316100, - 0x000004a4, 0xff318100, 0x000004ac, 0xff31a100, - 0x000004b4, 0xff31c200, 0x000004bd, 0xff31e200, - 0x000004c5, 0xff390000, 0x000004cd, 0xff392000, - 0x000004d5, 0xff394000, 0x000004de, 0xff396100, - 0x000004e6, 0xff398100, 0x000004ee, 0xff39a100, - 0x000004f6, 0xff39c200, 0x000004ff, 0xff39e200, - 0x00000800, 0xff410000, 0x00000808, 0xff412000, - 0x00000810, 0xff414000, 0x00000818, 0xff416100, - 0x00000820, 0xff418100, 0x00000829, 0xff41a100, - 0x00000831, 0xff41c200, 0x00000839, 0xff41e200, - 0x00000841, 0xff4a0000, 0x0000084a, 0xff4a2000, - 0x00000852, 0xff4a4000, 0x0000085a, 0xff4a6100, - 0x00000862, 0xff4a8100, 0x0000086a, 0xff4aa100, - 0x00000873, 0xff4ac200, 0x0000087b, 0xff4ae200, - 0x00000883, 0xff520000, 0x0000088b, 0xff522000, - 0x00000894, 0xff524000, 0x0000089c, 0xff526100, - 0x000008a4, 0xff528100, 0x000008ac, 0xff52a100, - 0x000008b4, 0xff52c200, 0x000008bd, 0xff52e200, - 0x000008c5, 0xff5a0000, 0x000008cd, 0xff5a2000, - 0x000008d5, 0xff5a4000, 0x000008de, 0xff5a6100, - 0x000008e6, 0xff5a8100, 0x000008ee, 0xff5aa100, - 0x000008f6, 0xff5ac200, 0x000008ff, 0xff5ae200, - 0x00000c00, 0xff620000, 0x00000c08, 0xff622000, - 0x00000c10, 0xff624000, 0x00000c18, 0xff626100, - 0x00000c20, 0xff628100, 0x00000c29, 0xff62a100, - 0x00000c31, 0xff62c200, 0x00000c39, 0xff62e200, - 0x00000c41, 0xff6a0000, 0x00000c4a, 0xff6a2000, - 0x00000c52, 0xff6a4000, 0x00000c5a, 0xff6a6100, - 0x00000c62, 0xff6a8100, 0x00000c6a, 0xff6aa100, - 0x00000c73, 0xff6ac200, 0x00000c7b, 0xff6ae200, - 0x00000c83, 0xff730000, 0x00000c8b, 0xff732000, - 0x00000c94, 0xff734000, 0x00000c9c, 0xff736100, - 0x00000ca4, 0xff738100, 0x00000cac, 0xff73a100, - 0x00000cb4, 0xff73c200, 0x00000cbd, 0xff73e200, - 0x00000cc5, 0xff7b0000, 0x00000ccd, 0xff7b2000, - 0x00000cd5, 0xff7b4000, 0x00000cde, 0xff7b6100, - 0x00000ce6, 0xff7b8100, 0x00000cee, 0xff7ba100, - 0x00000cf6, 0xff7bc200, 0x00000cff, 0xff7be200, - 0x00001000, 0xff830000, 0x00001008, 0xff832000, - 0x00001010, 0xff834000, 0x00001018, 0xff836100, - 0x00001020, 0xff838100, 0x00001029, 0xff83a100, - 0x00001031, 0xff83c200, 0x00001039, 0xff83e200, - 0x00001041, 0xff8b0000, 0x0000104a, 0xff8b2000, - 0x00001052, 0xff8b4000, 0x0000105a, 0xff8b6100, - 0x00001062, 0xff8b8100, 0x0000106a, 0xff8ba100, - 0x00001073, 0xff8bc200, 0x0000107b, 0xff8be200, - 0x00001083, 0xff940000, 0x0000108b, 0xff942000, - 0x00001094, 0xff944000, 0x0000109c, 0xff946100, - 0x000010a4, 0xff948100, 0x000010ac, 0xff94a100, - 0x000010b4, 0xff94c200, 0x000010bd, 0xff94e200, - 0x000010c5, 0xff9c0000, 0x000010cd, 0xff9c2000, - 0x000010d5, 0xff9c4000, 0x000010de, 0xff9c6100, - 0x000010e6, 0xff9c8100, 0x000010ee, 0xff9ca100, - 0x000010f6, 0xff9cc200, 0x000010ff, 0xff9ce200, - 0x00001400, 0xffa40000, 0x00001408, 0xffa42000, - 0x00001410, 0xffa44000, 0x00001418, 0xffa46100, - 0x00001420, 0xffa48100, 0x00001429, 0xffa4a100, - 0x00001431, 0xffa4c200, 0x00001439, 0xffa4e200, - 0x00001441, 0xffac0000, 0x0000144a, 0xffac2000, - 0x00001452, 0xffac4000, 0x0000145a, 0xffac6100, - 0x00001462, 0xffac8100, 0x0000146a, 0xffaca100, - 0x00001473, 0xffacc200, 0x0000147b, 0xfface200, - 0x00001483, 0xffb40000, 0x0000148b, 0xffb42000, - 0x00001494, 0xffb44000, 0x0000149c, 0xffb46100, - 0x000014a4, 0xffb48100, 0x000014ac, 0xffb4a100, - 0x000014b4, 0xffb4c200, 0x000014bd, 0xffb4e200, - 0x000014c5, 0xffbd0000, 0x000014cd, 0xffbd2000, - 0x000014d5, 0xffbd4000, 0x000014de, 0xffbd6100, - 0x000014e6, 0xffbd8100, 0x000014ee, 0xffbda100, - 0x000014f6, 0xffbdc200, 0x000014ff, 0xffbde200, - 0x00001800, 0xffc50000, 0x00001808, 0xffc52000, - 0x00001810, 0xffc54000, 0x00001818, 0xffc56100, - 0x00001820, 0xffc58100, 0x00001829, 0xffc5a100, - 0x00001831, 0xffc5c200, 0x00001839, 0xffc5e200, - 0x00001841, 0xffcd0000, 0x0000184a, 0xffcd2000, - 0x00001852, 0xffcd4000, 0x0000185a, 0xffcd6100, - 0x00001862, 0xffcd8100, 0x0000186a, 0xffcda100, - 0x00001873, 0xffcdc200, 0x0000187b, 0xffcde200, - 0x00001883, 0xffd50000, 0x0000188b, 0xffd52000, - 0x00001894, 0xffd54000, 0x0000189c, 0xffd56100, - 0x000018a4, 0xffd58100, 0x000018ac, 0xffd5a100, - 0x000018b4, 0xffd5c200, 0x000018bd, 0xffd5e200, - 0x000018c5, 0xffde0000, 0x000018cd, 0xffde2000, - 0x000018d5, 0xffde4000, 0x000018de, 0xffde6100, - 0x000018e6, 0xffde8100, 0x000018ee, 0xffdea100, - 0x000018f6, 0xffdec200, 0x000018ff, 0xffdee200, - 0x00001c00, 0xffe60000, 0x00001c08, 0xffe62000, - 0x00001c10, 0xffe64000, 0x00001c18, 0xffe66100, - 0x00001c20, 0xffe68100, 0x00001c29, 0xffe6a100, - 0x00001c31, 0xffe6c200, 0x00001c39, 0xffe6e200, - 0x00001c41, 0xffee0000, 0x00001c4a, 0xffee2000, - 0x00001c52, 0xffee4000, 0x00001c5a, 0xffee6100, - 0x00001c62, 0xffee8100, 0x00001c6a, 0xffeea100, - 0x00001c73, 0xffeec200, 0x00001c7b, 0xffeee200, - 0x00001c83, 0xfff60000, 0x00001c8b, 0xfff62000, - 0x00001c94, 0xfff64000, 0x00001c9c, 0xfff66100, - 0x00001ca4, 0xfff68100, 0x00001cac, 0xfff6a100, - 0x00001cb4, 0xfff6c200, 0x00001cbd, 0xfff6e200, - 0x00001cc5, 0xffff0000, 0x00001ccd, 0xffff2000, - 0x00001cd5, 0xffff4000, 0x00001cde, 0xffff6100, - 0x00001ce6, 0xffff8100, 0x00001cee, 0xffffa100, - 0x00001cf6, 0xffffc200, 0x00001cff, 0xffffe200 + 0x00000000, 0xff000000, 0x00000008, 0xff002000, + 0x00000010, 0xff004000, 0x00000018, 0xff006100, + 0x00000020, 0xff008100, 0x00000029, 0xff00a100, + 0x00000031, 0xff00c200, 0x00000039, 0xff00e200, + 0x00000041, 0xff080000, 0x0000004a, 0xff082000, + 0x00000052, 0xff084000, 0x0000005a, 0xff086100, + 0x00000062, 0xff088100, 0x0000006a, 0xff08a100, + 0x00000073, 0xff08c200, 0x0000007b, 0xff08e200, + 0x00000083, 0xff100000, 0x0000008b, 0xff102000, + 0x00000094, 0xff104000, 0x0000009c, 0xff106100, + 0x000000a4, 0xff108100, 0x000000ac, 0xff10a100, + 0x000000b4, 0xff10c200, 0x000000bd, 0xff10e200, + 0x000000c5, 0xff180000, 0x000000cd, 0xff182000, + 0x000000d5, 0xff184000, 0x000000de, 0xff186100, + 0x000000e6, 0xff188100, 0x000000ee, 0xff18a100, + 0x000000f6, 0xff18c200, 0x000000ff, 0xff18e200, + 0x00000400, 0xff200000, 0x00000408, 0xff202000, + 0x00000410, 0xff204000, 0x00000418, 0xff206100, + 0x00000420, 0xff208100, 0x00000429, 0xff20a100, + 0x00000431, 0xff20c200, 0x00000439, 0xff20e200, + 0x00000441, 0xff290000, 0x0000044a, 0xff292000, + 0x00000452, 0xff294000, 0x0000045a, 0xff296100, + 0x00000462, 0xff298100, 0x0000046a, 0xff29a100, + 0x00000473, 0xff29c200, 0x0000047b, 0xff29e200, + 0x00000483, 0xff310000, 0x0000048b, 0xff312000, + 0x00000494, 0xff314000, 0x0000049c, 0xff316100, + 0x000004a4, 0xff318100, 0x000004ac, 0xff31a100, + 0x000004b4, 0xff31c200, 0x000004bd, 0xff31e200, + 0x000004c5, 0xff390000, 0x000004cd, 0xff392000, + 0x000004d5, 0xff394000, 0x000004de, 0xff396100, + 0x000004e6, 0xff398100, 0x000004ee, 0xff39a100, + 0x000004f6, 0xff39c200, 0x000004ff, 0xff39e200, + 0x00000800, 0xff410000, 0x00000808, 0xff412000, + 0x00000810, 0xff414000, 0x00000818, 0xff416100, + 0x00000820, 0xff418100, 0x00000829, 0xff41a100, + 0x00000831, 0xff41c200, 0x00000839, 0xff41e200, + 0x00000841, 0xff4a0000, 0x0000084a, 0xff4a2000, + 0x00000852, 0xff4a4000, 0x0000085a, 0xff4a6100, + 0x00000862, 0xff4a8100, 0x0000086a, 0xff4aa100, + 0x00000873, 0xff4ac200, 0x0000087b, 0xff4ae200, + 0x00000883, 0xff520000, 0x0000088b, 0xff522000, + 0x00000894, 0xff524000, 0x0000089c, 0xff526100, + 0x000008a4, 0xff528100, 0x000008ac, 0xff52a100, + 0x000008b4, 0xff52c200, 0x000008bd, 0xff52e200, + 0x000008c5, 0xff5a0000, 0x000008cd, 0xff5a2000, + 0x000008d5, 0xff5a4000, 0x000008de, 0xff5a6100, + 0x000008e6, 0xff5a8100, 0x000008ee, 0xff5aa100, + 0x000008f6, 0xff5ac200, 0x000008ff, 0xff5ae200, + 0x00000c00, 0xff620000, 0x00000c08, 0xff622000, + 0x00000c10, 0xff624000, 0x00000c18, 0xff626100, + 0x00000c20, 0xff628100, 0x00000c29, 0xff62a100, + 0x00000c31, 0xff62c200, 0x00000c39, 0xff62e200, + 0x00000c41, 0xff6a0000, 0x00000c4a, 0xff6a2000, + 0x00000c52, 0xff6a4000, 0x00000c5a, 0xff6a6100, + 0x00000c62, 0xff6a8100, 0x00000c6a, 0xff6aa100, + 0x00000c73, 0xff6ac200, 0x00000c7b, 0xff6ae200, + 0x00000c83, 0xff730000, 0x00000c8b, 0xff732000, + 0x00000c94, 0xff734000, 0x00000c9c, 0xff736100, + 0x00000ca4, 0xff738100, 0x00000cac, 0xff73a100, + 0x00000cb4, 0xff73c200, 0x00000cbd, 0xff73e200, + 0x00000cc5, 0xff7b0000, 0x00000ccd, 0xff7b2000, + 0x00000cd5, 0xff7b4000, 0x00000cde, 0xff7b6100, + 0x00000ce6, 0xff7b8100, 0x00000cee, 0xff7ba100, + 0x00000cf6, 0xff7bc200, 0x00000cff, 0xff7be200, + 0x00001000, 0xff830000, 0x00001008, 0xff832000, + 0x00001010, 0xff834000, 0x00001018, 0xff836100, + 0x00001020, 0xff838100, 0x00001029, 0xff83a100, + 0x00001031, 0xff83c200, 0x00001039, 0xff83e200, + 0x00001041, 0xff8b0000, 0x0000104a, 0xff8b2000, + 0x00001052, 0xff8b4000, 0x0000105a, 0xff8b6100, + 0x00001062, 0xff8b8100, 0x0000106a, 0xff8ba100, + 0x00001073, 0xff8bc200, 0x0000107b, 0xff8be200, + 0x00001083, 0xff940000, 0x0000108b, 0xff942000, + 0x00001094, 0xff944000, 0x0000109c, 0xff946100, + 0x000010a4, 0xff948100, 0x000010ac, 0xff94a100, + 0x000010b4, 0xff94c200, 0x000010bd, 0xff94e200, + 0x000010c5, 0xff9c0000, 0x000010cd, 0xff9c2000, + 0x000010d5, 0xff9c4000, 0x000010de, 0xff9c6100, + 0x000010e6, 0xff9c8100, 0x000010ee, 0xff9ca100, + 0x000010f6, 0xff9cc200, 0x000010ff, 0xff9ce200, + 0x00001400, 0xffa40000, 0x00001408, 0xffa42000, + 0x00001410, 0xffa44000, 0x00001418, 0xffa46100, + 0x00001420, 0xffa48100, 0x00001429, 0xffa4a100, + 0x00001431, 0xffa4c200, 0x00001439, 0xffa4e200, + 0x00001441, 0xffac0000, 0x0000144a, 0xffac2000, + 0x00001452, 0xffac4000, 0x0000145a, 0xffac6100, + 0x00001462, 0xffac8100, 0x0000146a, 0xffaca100, + 0x00001473, 0xffacc200, 0x0000147b, 0xfface200, + 0x00001483, 0xffb40000, 0x0000148b, 0xffb42000, + 0x00001494, 0xffb44000, 0x0000149c, 0xffb46100, + 0x000014a4, 0xffb48100, 0x000014ac, 0xffb4a100, + 0x000014b4, 0xffb4c200, 0x000014bd, 0xffb4e200, + 0x000014c5, 0xffbd0000, 0x000014cd, 0xffbd2000, + 0x000014d5, 0xffbd4000, 0x000014de, 0xffbd6100, + 0x000014e6, 0xffbd8100, 0x000014ee, 0xffbda100, + 0x000014f6, 0xffbdc200, 0x000014ff, 0xffbde200, + 0x00001800, 0xffc50000, 0x00001808, 0xffc52000, + 0x00001810, 0xffc54000, 0x00001818, 0xffc56100, + 0x00001820, 0xffc58100, 0x00001829, 0xffc5a100, + 0x00001831, 0xffc5c200, 0x00001839, 0xffc5e200, + 0x00001841, 0xffcd0000, 0x0000184a, 0xffcd2000, + 0x00001852, 0xffcd4000, 0x0000185a, 0xffcd6100, + 0x00001862, 0xffcd8100, 0x0000186a, 0xffcda100, + 0x00001873, 0xffcdc200, 0x0000187b, 0xffcde200, + 0x00001883, 0xffd50000, 0x0000188b, 0xffd52000, + 0x00001894, 0xffd54000, 0x0000189c, 0xffd56100, + 0x000018a4, 0xffd58100, 0x000018ac, 0xffd5a100, + 0x000018b4, 0xffd5c200, 0x000018bd, 0xffd5e200, + 0x000018c5, 0xffde0000, 0x000018cd, 0xffde2000, + 0x000018d5, 0xffde4000, 0x000018de, 0xffde6100, + 0x000018e6, 0xffde8100, 0x000018ee, 0xffdea100, + 0x000018f6, 0xffdec200, 0x000018ff, 0xffdee200, + 0x00001c00, 0xffe60000, 0x00001c08, 0xffe62000, + 0x00001c10, 0xffe64000, 0x00001c18, 0xffe66100, + 0x00001c20, 0xffe68100, 0x00001c29, 0xffe6a100, + 0x00001c31, 0xffe6c200, 0x00001c39, 0xffe6e200, + 0x00001c41, 0xffee0000, 0x00001c4a, 0xffee2000, + 0x00001c52, 0xffee4000, 0x00001c5a, 0xffee6100, + 0x00001c62, 0xffee8100, 0x00001c6a, 0xffeea100, + 0x00001c73, 0xffeec200, 0x00001c7b, 0xffeee200, + 0x00001c83, 0xfff60000, 0x00001c8b, 0xfff62000, + 0x00001c94, 0xfff64000, 0x00001c9c, 0xfff66100, + 0x00001ca4, 0xfff68100, 0x00001cac, 0xfff6a100, + 0x00001cb4, 0xfff6c200, 0x00001cbd, 0xfff6e200, + 0x00001cc5, 0xffff0000, 0x00001ccd, 0xffff2000, + 0x00001cd5, 0xffff4000, 0x00001cde, 0xffff6100, + 0x00001ce6, 0xffff8100, 0x00001cee, 0xffffa100, + 0x00001cf6, 0xffffc200, 0x00001cff, 0xffffe200 }; -static void Blit_RGB565_ARGB8888(SDL_BlitInfo *info) +static void +Blit_RGB565_ARGB8888(SDL_BlitInfo * info) { Blit_RGB565_32(info, RGB565_ARGB8888_LUT); } /* Special optimized blit for RGB 5-6-5 --> ABGR 8-8-8-8 */ static const Uint32 RGB565_ABGR8888_LUT[512] = { - 0xff000000, 0x00000000, 0xff080000, 0x00002000, - 0xff100000, 0x00004000, 0xff180000, 0x00006100, - 0xff200000, 0x00008100, 0xff290000, 0x0000a100, - 0xff310000, 0x0000c200, 0xff390000, 0x0000e200, - 0xff410000, 0x00000008, 0xff4a0000, 0x00002008, - 0xff520000, 0x00004008, 0xff5a0000, 0x00006108, - 0xff620000, 0x00008108, 0xff6a0000, 0x0000a108, - 0xff730000, 0x0000c208, 0xff7b0000, 0x0000e208, - 0xff830000, 0x00000010, 0xff8b0000, 0x00002010, - 0xff940000, 0x00004010, 0xff9c0000, 0x00006110, - 0xffa40000, 0x00008110, 0xffac0000, 0x0000a110, - 0xffb40000, 0x0000c210, 0xffbd0000, 0x0000e210, - 0xffc50000, 0x00000018, 0xffcd0000, 0x00002018, - 0xffd50000, 0x00004018, 0xffde0000, 0x00006118, - 0xffe60000, 0x00008118, 0xffee0000, 0x0000a118, - 0xfff60000, 0x0000c218, 0xffff0000, 0x0000e218, - 0xff000400, 0x00000020, 0xff080400, 0x00002020, - 0xff100400, 0x00004020, 0xff180400, 0x00006120, - 0xff200400, 0x00008120, 0xff290400, 0x0000a120, - 0xff310400, 0x0000c220, 0xff390400, 0x0000e220, - 0xff410400, 0x00000029, 0xff4a0400, 0x00002029, - 0xff520400, 0x00004029, 0xff5a0400, 0x00006129, - 0xff620400, 0x00008129, 0xff6a0400, 0x0000a129, - 0xff730400, 0x0000c229, 0xff7b0400, 0x0000e229, - 0xff830400, 0x00000031, 0xff8b0400, 0x00002031, - 0xff940400, 0x00004031, 0xff9c0400, 0x00006131, - 0xffa40400, 0x00008131, 0xffac0400, 0x0000a131, - 0xffb40400, 0x0000c231, 0xffbd0400, 0x0000e231, - 0xffc50400, 0x00000039, 0xffcd0400, 0x00002039, - 0xffd50400, 0x00004039, 0xffde0400, 0x00006139, - 0xffe60400, 0x00008139, 0xffee0400, 0x0000a139, - 0xfff60400, 0x0000c239, 0xffff0400, 0x0000e239, - 0xff000800, 0x00000041, 0xff080800, 0x00002041, - 0xff100800, 0x00004041, 0xff180800, 0x00006141, - 0xff200800, 0x00008141, 0xff290800, 0x0000a141, - 0xff310800, 0x0000c241, 0xff390800, 0x0000e241, - 0xff410800, 0x0000004a, 0xff4a0800, 0x0000204a, - 0xff520800, 0x0000404a, 0xff5a0800, 0x0000614a, - 0xff620800, 0x0000814a, 0xff6a0800, 0x0000a14a, - 0xff730800, 0x0000c24a, 0xff7b0800, 0x0000e24a, - 0xff830800, 0x00000052, 0xff8b0800, 0x00002052, - 0xff940800, 0x00004052, 0xff9c0800, 0x00006152, - 0xffa40800, 0x00008152, 0xffac0800, 0x0000a152, - 0xffb40800, 0x0000c252, 0xffbd0800, 0x0000e252, - 0xffc50800, 0x0000005a, 0xffcd0800, 0x0000205a, - 0xffd50800, 0x0000405a, 0xffde0800, 0x0000615a, - 0xffe60800, 0x0000815a, 0xffee0800, 0x0000a15a, - 0xfff60800, 0x0000c25a, 0xffff0800, 0x0000e25a, - 0xff000c00, 0x00000062, 0xff080c00, 0x00002062, - 0xff100c00, 0x00004062, 0xff180c00, 0x00006162, - 0xff200c00, 0x00008162, 0xff290c00, 0x0000a162, - 0xff310c00, 0x0000c262, 0xff390c00, 0x0000e262, - 0xff410c00, 0x0000006a, 0xff4a0c00, 0x0000206a, - 0xff520c00, 0x0000406a, 0xff5a0c00, 0x0000616a, - 0xff620c00, 0x0000816a, 0xff6a0c00, 0x0000a16a, - 0xff730c00, 0x0000c26a, 0xff7b0c00, 0x0000e26a, - 0xff830c00, 0x00000073, 0xff8b0c00, 0x00002073, - 0xff940c00, 0x00004073, 0xff9c0c00, 0x00006173, - 0xffa40c00, 0x00008173, 0xffac0c00, 0x0000a173, - 0xffb40c00, 0x0000c273, 0xffbd0c00, 0x0000e273, - 0xffc50c00, 0x0000007b, 0xffcd0c00, 0x0000207b, - 0xffd50c00, 0x0000407b, 0xffde0c00, 0x0000617b, - 0xffe60c00, 0x0000817b, 0xffee0c00, 0x0000a17b, - 0xfff60c00, 0x0000c27b, 0xffff0c00, 0x0000e27b, - 0xff001000, 0x00000083, 0xff081000, 0x00002083, - 0xff101000, 0x00004083, 0xff181000, 0x00006183, - 0xff201000, 0x00008183, 0xff291000, 0x0000a183, - 0xff311000, 0x0000c283, 0xff391000, 0x0000e283, - 0xff411000, 0x0000008b, 0xff4a1000, 0x0000208b, - 0xff521000, 0x0000408b, 0xff5a1000, 0x0000618b, - 0xff621000, 0x0000818b, 0xff6a1000, 0x0000a18b, - 0xff731000, 0x0000c28b, 0xff7b1000, 0x0000e28b, - 0xff831000, 0x00000094, 0xff8b1000, 0x00002094, - 0xff941000, 0x00004094, 0xff9c1000, 0x00006194, - 0xffa41000, 0x00008194, 0xffac1000, 0x0000a194, - 0xffb41000, 0x0000c294, 0xffbd1000, 0x0000e294, - 0xffc51000, 0x0000009c, 0xffcd1000, 0x0000209c, - 0xffd51000, 0x0000409c, 0xffde1000, 0x0000619c, - 0xffe61000, 0x0000819c, 0xffee1000, 0x0000a19c, - 0xfff61000, 0x0000c29c, 0xffff1000, 0x0000e29c, - 0xff001400, 0x000000a4, 0xff081400, 0x000020a4, - 0xff101400, 0x000040a4, 0xff181400, 0x000061a4, - 0xff201400, 0x000081a4, 0xff291400, 0x0000a1a4, - 0xff311400, 0x0000c2a4, 0xff391400, 0x0000e2a4, - 0xff411400, 0x000000ac, 0xff4a1400, 0x000020ac, - 0xff521400, 0x000040ac, 0xff5a1400, 0x000061ac, - 0xff621400, 0x000081ac, 0xff6a1400, 0x0000a1ac, - 0xff731400, 0x0000c2ac, 0xff7b1400, 0x0000e2ac, - 0xff831400, 0x000000b4, 0xff8b1400, 0x000020b4, - 0xff941400, 0x000040b4, 0xff9c1400, 0x000061b4, - 0xffa41400, 0x000081b4, 0xffac1400, 0x0000a1b4, - 0xffb41400, 0x0000c2b4, 0xffbd1400, 0x0000e2b4, - 0xffc51400, 0x000000bd, 0xffcd1400, 0x000020bd, - 0xffd51400, 0x000040bd, 0xffde1400, 0x000061bd, - 0xffe61400, 0x000081bd, 0xffee1400, 0x0000a1bd, - 0xfff61400, 0x0000c2bd, 0xffff1400, 0x0000e2bd, - 0xff001800, 0x000000c5, 0xff081800, 0x000020c5, - 0xff101800, 0x000040c5, 0xff181800, 0x000061c5, - 0xff201800, 0x000081c5, 0xff291800, 0x0000a1c5, - 0xff311800, 0x0000c2c5, 0xff391800, 0x0000e2c5, - 0xff411800, 0x000000cd, 0xff4a1800, 0x000020cd, - 0xff521800, 0x000040cd, 0xff5a1800, 0x000061cd, - 0xff621800, 0x000081cd, 0xff6a1800, 0x0000a1cd, - 0xff731800, 0x0000c2cd, 0xff7b1800, 0x0000e2cd, - 0xff831800, 0x000000d5, 0xff8b1800, 0x000020d5, - 0xff941800, 0x000040d5, 0xff9c1800, 0x000061d5, - 0xffa41800, 0x000081d5, 0xffac1800, 0x0000a1d5, - 0xffb41800, 0x0000c2d5, 0xffbd1800, 0x0000e2d5, - 0xffc51800, 0x000000de, 0xffcd1800, 0x000020de, - 0xffd51800, 0x000040de, 0xffde1800, 0x000061de, - 0xffe61800, 0x000081de, 0xffee1800, 0x0000a1de, - 0xfff61800, 0x0000c2de, 0xffff1800, 0x0000e2de, - 0xff001c00, 0x000000e6, 0xff081c00, 0x000020e6, - 0xff101c00, 0x000040e6, 0xff181c00, 0x000061e6, - 0xff201c00, 0x000081e6, 0xff291c00, 0x0000a1e6, - 0xff311c00, 0x0000c2e6, 0xff391c00, 0x0000e2e6, - 0xff411c00, 0x000000ee, 0xff4a1c00, 0x000020ee, - 0xff521c00, 0x000040ee, 0xff5a1c00, 0x000061ee, - 0xff621c00, 0x000081ee, 0xff6a1c00, 0x0000a1ee, - 0xff731c00, 0x0000c2ee, 0xff7b1c00, 0x0000e2ee, - 0xff831c00, 0x000000f6, 0xff8b1c00, 0x000020f6, - 0xff941c00, 0x000040f6, 0xff9c1c00, 0x000061f6, - 0xffa41c00, 0x000081f6, 0xffac1c00, 0x0000a1f6, - 0xffb41c00, 0x0000c2f6, 0xffbd1c00, 0x0000e2f6, - 0xffc51c00, 0x000000ff, 0xffcd1c00, 0x000020ff, - 0xffd51c00, 0x000040ff, 0xffde1c00, 0x000061ff, - 0xffe61c00, 0x000081ff, 0xffee1c00, 0x0000a1ff, - 0xfff61c00, 0x0000c2ff, 0xffff1c00, 0x0000e2ff + 0xff000000, 0x00000000, 0xff080000, 0x00002000, + 0xff100000, 0x00004000, 0xff180000, 0x00006100, + 0xff200000, 0x00008100, 0xff290000, 0x0000a100, + 0xff310000, 0x0000c200, 0xff390000, 0x0000e200, + 0xff410000, 0x00000008, 0xff4a0000, 0x00002008, + 0xff520000, 0x00004008, 0xff5a0000, 0x00006108, + 0xff620000, 0x00008108, 0xff6a0000, 0x0000a108, + 0xff730000, 0x0000c208, 0xff7b0000, 0x0000e208, + 0xff830000, 0x00000010, 0xff8b0000, 0x00002010, + 0xff940000, 0x00004010, 0xff9c0000, 0x00006110, + 0xffa40000, 0x00008110, 0xffac0000, 0x0000a110, + 0xffb40000, 0x0000c210, 0xffbd0000, 0x0000e210, + 0xffc50000, 0x00000018, 0xffcd0000, 0x00002018, + 0xffd50000, 0x00004018, 0xffde0000, 0x00006118, + 0xffe60000, 0x00008118, 0xffee0000, 0x0000a118, + 0xfff60000, 0x0000c218, 0xffff0000, 0x0000e218, + 0xff000400, 0x00000020, 0xff080400, 0x00002020, + 0xff100400, 0x00004020, 0xff180400, 0x00006120, + 0xff200400, 0x00008120, 0xff290400, 0x0000a120, + 0xff310400, 0x0000c220, 0xff390400, 0x0000e220, + 0xff410400, 0x00000029, 0xff4a0400, 0x00002029, + 0xff520400, 0x00004029, 0xff5a0400, 0x00006129, + 0xff620400, 0x00008129, 0xff6a0400, 0x0000a129, + 0xff730400, 0x0000c229, 0xff7b0400, 0x0000e229, + 0xff830400, 0x00000031, 0xff8b0400, 0x00002031, + 0xff940400, 0x00004031, 0xff9c0400, 0x00006131, + 0xffa40400, 0x00008131, 0xffac0400, 0x0000a131, + 0xffb40400, 0x0000c231, 0xffbd0400, 0x0000e231, + 0xffc50400, 0x00000039, 0xffcd0400, 0x00002039, + 0xffd50400, 0x00004039, 0xffde0400, 0x00006139, + 0xffe60400, 0x00008139, 0xffee0400, 0x0000a139, + 0xfff60400, 0x0000c239, 0xffff0400, 0x0000e239, + 0xff000800, 0x00000041, 0xff080800, 0x00002041, + 0xff100800, 0x00004041, 0xff180800, 0x00006141, + 0xff200800, 0x00008141, 0xff290800, 0x0000a141, + 0xff310800, 0x0000c241, 0xff390800, 0x0000e241, + 0xff410800, 0x0000004a, 0xff4a0800, 0x0000204a, + 0xff520800, 0x0000404a, 0xff5a0800, 0x0000614a, + 0xff620800, 0x0000814a, 0xff6a0800, 0x0000a14a, + 0xff730800, 0x0000c24a, 0xff7b0800, 0x0000e24a, + 0xff830800, 0x00000052, 0xff8b0800, 0x00002052, + 0xff940800, 0x00004052, 0xff9c0800, 0x00006152, + 0xffa40800, 0x00008152, 0xffac0800, 0x0000a152, + 0xffb40800, 0x0000c252, 0xffbd0800, 0x0000e252, + 0xffc50800, 0x0000005a, 0xffcd0800, 0x0000205a, + 0xffd50800, 0x0000405a, 0xffde0800, 0x0000615a, + 0xffe60800, 0x0000815a, 0xffee0800, 0x0000a15a, + 0xfff60800, 0x0000c25a, 0xffff0800, 0x0000e25a, + 0xff000c00, 0x00000062, 0xff080c00, 0x00002062, + 0xff100c00, 0x00004062, 0xff180c00, 0x00006162, + 0xff200c00, 0x00008162, 0xff290c00, 0x0000a162, + 0xff310c00, 0x0000c262, 0xff390c00, 0x0000e262, + 0xff410c00, 0x0000006a, 0xff4a0c00, 0x0000206a, + 0xff520c00, 0x0000406a, 0xff5a0c00, 0x0000616a, + 0xff620c00, 0x0000816a, 0xff6a0c00, 0x0000a16a, + 0xff730c00, 0x0000c26a, 0xff7b0c00, 0x0000e26a, + 0xff830c00, 0x00000073, 0xff8b0c00, 0x00002073, + 0xff940c00, 0x00004073, 0xff9c0c00, 0x00006173, + 0xffa40c00, 0x00008173, 0xffac0c00, 0x0000a173, + 0xffb40c00, 0x0000c273, 0xffbd0c00, 0x0000e273, + 0xffc50c00, 0x0000007b, 0xffcd0c00, 0x0000207b, + 0xffd50c00, 0x0000407b, 0xffde0c00, 0x0000617b, + 0xffe60c00, 0x0000817b, 0xffee0c00, 0x0000a17b, + 0xfff60c00, 0x0000c27b, 0xffff0c00, 0x0000e27b, + 0xff001000, 0x00000083, 0xff081000, 0x00002083, + 0xff101000, 0x00004083, 0xff181000, 0x00006183, + 0xff201000, 0x00008183, 0xff291000, 0x0000a183, + 0xff311000, 0x0000c283, 0xff391000, 0x0000e283, + 0xff411000, 0x0000008b, 0xff4a1000, 0x0000208b, + 0xff521000, 0x0000408b, 0xff5a1000, 0x0000618b, + 0xff621000, 0x0000818b, 0xff6a1000, 0x0000a18b, + 0xff731000, 0x0000c28b, 0xff7b1000, 0x0000e28b, + 0xff831000, 0x00000094, 0xff8b1000, 0x00002094, + 0xff941000, 0x00004094, 0xff9c1000, 0x00006194, + 0xffa41000, 0x00008194, 0xffac1000, 0x0000a194, + 0xffb41000, 0x0000c294, 0xffbd1000, 0x0000e294, + 0xffc51000, 0x0000009c, 0xffcd1000, 0x0000209c, + 0xffd51000, 0x0000409c, 0xffde1000, 0x0000619c, + 0xffe61000, 0x0000819c, 0xffee1000, 0x0000a19c, + 0xfff61000, 0x0000c29c, 0xffff1000, 0x0000e29c, + 0xff001400, 0x000000a4, 0xff081400, 0x000020a4, + 0xff101400, 0x000040a4, 0xff181400, 0x000061a4, + 0xff201400, 0x000081a4, 0xff291400, 0x0000a1a4, + 0xff311400, 0x0000c2a4, 0xff391400, 0x0000e2a4, + 0xff411400, 0x000000ac, 0xff4a1400, 0x000020ac, + 0xff521400, 0x000040ac, 0xff5a1400, 0x000061ac, + 0xff621400, 0x000081ac, 0xff6a1400, 0x0000a1ac, + 0xff731400, 0x0000c2ac, 0xff7b1400, 0x0000e2ac, + 0xff831400, 0x000000b4, 0xff8b1400, 0x000020b4, + 0xff941400, 0x000040b4, 0xff9c1400, 0x000061b4, + 0xffa41400, 0x000081b4, 0xffac1400, 0x0000a1b4, + 0xffb41400, 0x0000c2b4, 0xffbd1400, 0x0000e2b4, + 0xffc51400, 0x000000bd, 0xffcd1400, 0x000020bd, + 0xffd51400, 0x000040bd, 0xffde1400, 0x000061bd, + 0xffe61400, 0x000081bd, 0xffee1400, 0x0000a1bd, + 0xfff61400, 0x0000c2bd, 0xffff1400, 0x0000e2bd, + 0xff001800, 0x000000c5, 0xff081800, 0x000020c5, + 0xff101800, 0x000040c5, 0xff181800, 0x000061c5, + 0xff201800, 0x000081c5, 0xff291800, 0x0000a1c5, + 0xff311800, 0x0000c2c5, 0xff391800, 0x0000e2c5, + 0xff411800, 0x000000cd, 0xff4a1800, 0x000020cd, + 0xff521800, 0x000040cd, 0xff5a1800, 0x000061cd, + 0xff621800, 0x000081cd, 0xff6a1800, 0x0000a1cd, + 0xff731800, 0x0000c2cd, 0xff7b1800, 0x0000e2cd, + 0xff831800, 0x000000d5, 0xff8b1800, 0x000020d5, + 0xff941800, 0x000040d5, 0xff9c1800, 0x000061d5, + 0xffa41800, 0x000081d5, 0xffac1800, 0x0000a1d5, + 0xffb41800, 0x0000c2d5, 0xffbd1800, 0x0000e2d5, + 0xffc51800, 0x000000de, 0xffcd1800, 0x000020de, + 0xffd51800, 0x000040de, 0xffde1800, 0x000061de, + 0xffe61800, 0x000081de, 0xffee1800, 0x0000a1de, + 0xfff61800, 0x0000c2de, 0xffff1800, 0x0000e2de, + 0xff001c00, 0x000000e6, 0xff081c00, 0x000020e6, + 0xff101c00, 0x000040e6, 0xff181c00, 0x000061e6, + 0xff201c00, 0x000081e6, 0xff291c00, 0x0000a1e6, + 0xff311c00, 0x0000c2e6, 0xff391c00, 0x0000e2e6, + 0xff411c00, 0x000000ee, 0xff4a1c00, 0x000020ee, + 0xff521c00, 0x000040ee, 0xff5a1c00, 0x000061ee, + 0xff621c00, 0x000081ee, 0xff6a1c00, 0x0000a1ee, + 0xff731c00, 0x0000c2ee, 0xff7b1c00, 0x0000e2ee, + 0xff831c00, 0x000000f6, 0xff8b1c00, 0x000020f6, + 0xff941c00, 0x000040f6, 0xff9c1c00, 0x000061f6, + 0xffa41c00, 0x000081f6, 0xffac1c00, 0x0000a1f6, + 0xffb41c00, 0x0000c2f6, 0xffbd1c00, 0x0000e2f6, + 0xffc51c00, 0x000000ff, 0xffcd1c00, 0x000020ff, + 0xffd51c00, 0x000040ff, 0xffde1c00, 0x000061ff, + 0xffe61c00, 0x000081ff, 0xffee1c00, 0x0000a1ff, + 0xfff61c00, 0x0000c2ff, 0xffff1c00, 0x0000e2ff }; -static void Blit_RGB565_ABGR8888(SDL_BlitInfo *info) +static void +Blit_RGB565_ABGR8888(SDL_BlitInfo * info) { Blit_RGB565_32(info, RGB565_ABGR8888_LUT); } /* Special optimized blit for RGB 5-6-5 --> RGBA 8-8-8-8 */ static const Uint32 RGB565_RGBA8888_LUT[512] = { - 0x000000ff, 0x00000000, 0x000008ff, 0x00200000, - 0x000010ff, 0x00400000, 0x000018ff, 0x00610000, - 0x000020ff, 0x00810000, 0x000029ff, 0x00a10000, - 0x000031ff, 0x00c20000, 0x000039ff, 0x00e20000, - 0x000041ff, 0x08000000, 0x00004aff, 0x08200000, - 0x000052ff, 0x08400000, 0x00005aff, 0x08610000, - 0x000062ff, 0x08810000, 0x00006aff, 0x08a10000, - 0x000073ff, 0x08c20000, 0x00007bff, 0x08e20000, - 0x000083ff, 0x10000000, 0x00008bff, 0x10200000, - 0x000094ff, 0x10400000, 0x00009cff, 0x10610000, - 0x0000a4ff, 0x10810000, 0x0000acff, 0x10a10000, - 0x0000b4ff, 0x10c20000, 0x0000bdff, 0x10e20000, - 0x0000c5ff, 0x18000000, 0x0000cdff, 0x18200000, - 0x0000d5ff, 0x18400000, 0x0000deff, 0x18610000, - 0x0000e6ff, 0x18810000, 0x0000eeff, 0x18a10000, - 0x0000f6ff, 0x18c20000, 0x0000ffff, 0x18e20000, - 0x000400ff, 0x20000000, 0x000408ff, 0x20200000, - 0x000410ff, 0x20400000, 0x000418ff, 0x20610000, - 0x000420ff, 0x20810000, 0x000429ff, 0x20a10000, - 0x000431ff, 0x20c20000, 0x000439ff, 0x20e20000, - 0x000441ff, 0x29000000, 0x00044aff, 0x29200000, - 0x000452ff, 0x29400000, 0x00045aff, 0x29610000, - 0x000462ff, 0x29810000, 0x00046aff, 0x29a10000, - 0x000473ff, 0x29c20000, 0x00047bff, 0x29e20000, - 0x000483ff, 0x31000000, 0x00048bff, 0x31200000, - 0x000494ff, 0x31400000, 0x00049cff, 0x31610000, - 0x0004a4ff, 0x31810000, 0x0004acff, 0x31a10000, - 0x0004b4ff, 0x31c20000, 0x0004bdff, 0x31e20000, - 0x0004c5ff, 0x39000000, 0x0004cdff, 0x39200000, - 0x0004d5ff, 0x39400000, 0x0004deff, 0x39610000, - 0x0004e6ff, 0x39810000, 0x0004eeff, 0x39a10000, - 0x0004f6ff, 0x39c20000, 0x0004ffff, 0x39e20000, - 0x000800ff, 0x41000000, 0x000808ff, 0x41200000, - 0x000810ff, 0x41400000, 0x000818ff, 0x41610000, - 0x000820ff, 0x41810000, 0x000829ff, 0x41a10000, - 0x000831ff, 0x41c20000, 0x000839ff, 0x41e20000, - 0x000841ff, 0x4a000000, 0x00084aff, 0x4a200000, - 0x000852ff, 0x4a400000, 0x00085aff, 0x4a610000, - 0x000862ff, 0x4a810000, 0x00086aff, 0x4aa10000, - 0x000873ff, 0x4ac20000, 0x00087bff, 0x4ae20000, - 0x000883ff, 0x52000000, 0x00088bff, 0x52200000, - 0x000894ff, 0x52400000, 0x00089cff, 0x52610000, - 0x0008a4ff, 0x52810000, 0x0008acff, 0x52a10000, - 0x0008b4ff, 0x52c20000, 0x0008bdff, 0x52e20000, - 0x0008c5ff, 0x5a000000, 0x0008cdff, 0x5a200000, - 0x0008d5ff, 0x5a400000, 0x0008deff, 0x5a610000, - 0x0008e6ff, 0x5a810000, 0x0008eeff, 0x5aa10000, - 0x0008f6ff, 0x5ac20000, 0x0008ffff, 0x5ae20000, - 0x000c00ff, 0x62000000, 0x000c08ff, 0x62200000, - 0x000c10ff, 0x62400000, 0x000c18ff, 0x62610000, - 0x000c20ff, 0x62810000, 0x000c29ff, 0x62a10000, - 0x000c31ff, 0x62c20000, 0x000c39ff, 0x62e20000, - 0x000c41ff, 0x6a000000, 0x000c4aff, 0x6a200000, - 0x000c52ff, 0x6a400000, 0x000c5aff, 0x6a610000, - 0x000c62ff, 0x6a810000, 0x000c6aff, 0x6aa10000, - 0x000c73ff, 0x6ac20000, 0x000c7bff, 0x6ae20000, - 0x000c83ff, 0x73000000, 0x000c8bff, 0x73200000, - 0x000c94ff, 0x73400000, 0x000c9cff, 0x73610000, - 0x000ca4ff, 0x73810000, 0x000cacff, 0x73a10000, - 0x000cb4ff, 0x73c20000, 0x000cbdff, 0x73e20000, - 0x000cc5ff, 0x7b000000, 0x000ccdff, 0x7b200000, - 0x000cd5ff, 0x7b400000, 0x000cdeff, 0x7b610000, - 0x000ce6ff, 0x7b810000, 0x000ceeff, 0x7ba10000, - 0x000cf6ff, 0x7bc20000, 0x000cffff, 0x7be20000, - 0x001000ff, 0x83000000, 0x001008ff, 0x83200000, - 0x001010ff, 0x83400000, 0x001018ff, 0x83610000, - 0x001020ff, 0x83810000, 0x001029ff, 0x83a10000, - 0x001031ff, 0x83c20000, 0x001039ff, 0x83e20000, - 0x001041ff, 0x8b000000, 0x00104aff, 0x8b200000, - 0x001052ff, 0x8b400000, 0x00105aff, 0x8b610000, - 0x001062ff, 0x8b810000, 0x00106aff, 0x8ba10000, - 0x001073ff, 0x8bc20000, 0x00107bff, 0x8be20000, - 0x001083ff, 0x94000000, 0x00108bff, 0x94200000, - 0x001094ff, 0x94400000, 0x00109cff, 0x94610000, - 0x0010a4ff, 0x94810000, 0x0010acff, 0x94a10000, - 0x0010b4ff, 0x94c20000, 0x0010bdff, 0x94e20000, - 0x0010c5ff, 0x9c000000, 0x0010cdff, 0x9c200000, - 0x0010d5ff, 0x9c400000, 0x0010deff, 0x9c610000, - 0x0010e6ff, 0x9c810000, 0x0010eeff, 0x9ca10000, - 0x0010f6ff, 0x9cc20000, 0x0010ffff, 0x9ce20000, - 0x001400ff, 0xa4000000, 0x001408ff, 0xa4200000, - 0x001410ff, 0xa4400000, 0x001418ff, 0xa4610000, - 0x001420ff, 0xa4810000, 0x001429ff, 0xa4a10000, - 0x001431ff, 0xa4c20000, 0x001439ff, 0xa4e20000, - 0x001441ff, 0xac000000, 0x00144aff, 0xac200000, - 0x001452ff, 0xac400000, 0x00145aff, 0xac610000, - 0x001462ff, 0xac810000, 0x00146aff, 0xaca10000, - 0x001473ff, 0xacc20000, 0x00147bff, 0xace20000, - 0x001483ff, 0xb4000000, 0x00148bff, 0xb4200000, - 0x001494ff, 0xb4400000, 0x00149cff, 0xb4610000, - 0x0014a4ff, 0xb4810000, 0x0014acff, 0xb4a10000, - 0x0014b4ff, 0xb4c20000, 0x0014bdff, 0xb4e20000, - 0x0014c5ff, 0xbd000000, 0x0014cdff, 0xbd200000, - 0x0014d5ff, 0xbd400000, 0x0014deff, 0xbd610000, - 0x0014e6ff, 0xbd810000, 0x0014eeff, 0xbda10000, - 0x0014f6ff, 0xbdc20000, 0x0014ffff, 0xbde20000, - 0x001800ff, 0xc5000000, 0x001808ff, 0xc5200000, - 0x001810ff, 0xc5400000, 0x001818ff, 0xc5610000, - 0x001820ff, 0xc5810000, 0x001829ff, 0xc5a10000, - 0x001831ff, 0xc5c20000, 0x001839ff, 0xc5e20000, - 0x001841ff, 0xcd000000, 0x00184aff, 0xcd200000, - 0x001852ff, 0xcd400000, 0x00185aff, 0xcd610000, - 0x001862ff, 0xcd810000, 0x00186aff, 0xcda10000, - 0x001873ff, 0xcdc20000, 0x00187bff, 0xcde20000, - 0x001883ff, 0xd5000000, 0x00188bff, 0xd5200000, - 0x001894ff, 0xd5400000, 0x00189cff, 0xd5610000, - 0x0018a4ff, 0xd5810000, 0x0018acff, 0xd5a10000, - 0x0018b4ff, 0xd5c20000, 0x0018bdff, 0xd5e20000, - 0x0018c5ff, 0xde000000, 0x0018cdff, 0xde200000, - 0x0018d5ff, 0xde400000, 0x0018deff, 0xde610000, - 0x0018e6ff, 0xde810000, 0x0018eeff, 0xdea10000, - 0x0018f6ff, 0xdec20000, 0x0018ffff, 0xdee20000, - 0x001c00ff, 0xe6000000, 0x001c08ff, 0xe6200000, - 0x001c10ff, 0xe6400000, 0x001c18ff, 0xe6610000, - 0x001c20ff, 0xe6810000, 0x001c29ff, 0xe6a10000, - 0x001c31ff, 0xe6c20000, 0x001c39ff, 0xe6e20000, - 0x001c41ff, 0xee000000, 0x001c4aff, 0xee200000, - 0x001c52ff, 0xee400000, 0x001c5aff, 0xee610000, - 0x001c62ff, 0xee810000, 0x001c6aff, 0xeea10000, - 0x001c73ff, 0xeec20000, 0x001c7bff, 0xeee20000, - 0x001c83ff, 0xf6000000, 0x001c8bff, 0xf6200000, - 0x001c94ff, 0xf6400000, 0x001c9cff, 0xf6610000, - 0x001ca4ff, 0xf6810000, 0x001cacff, 0xf6a10000, - 0x001cb4ff, 0xf6c20000, 0x001cbdff, 0xf6e20000, - 0x001cc5ff, 0xff000000, 0x001ccdff, 0xff200000, - 0x001cd5ff, 0xff400000, 0x001cdeff, 0xff610000, - 0x001ce6ff, 0xff810000, 0x001ceeff, 0xffa10000, - 0x001cf6ff, 0xffc20000, 0x001cffff, 0xffe20000, + 0x000000ff, 0x00000000, 0x000008ff, 0x00200000, + 0x000010ff, 0x00400000, 0x000018ff, 0x00610000, + 0x000020ff, 0x00810000, 0x000029ff, 0x00a10000, + 0x000031ff, 0x00c20000, 0x000039ff, 0x00e20000, + 0x000041ff, 0x08000000, 0x00004aff, 0x08200000, + 0x000052ff, 0x08400000, 0x00005aff, 0x08610000, + 0x000062ff, 0x08810000, 0x00006aff, 0x08a10000, + 0x000073ff, 0x08c20000, 0x00007bff, 0x08e20000, + 0x000083ff, 0x10000000, 0x00008bff, 0x10200000, + 0x000094ff, 0x10400000, 0x00009cff, 0x10610000, + 0x0000a4ff, 0x10810000, 0x0000acff, 0x10a10000, + 0x0000b4ff, 0x10c20000, 0x0000bdff, 0x10e20000, + 0x0000c5ff, 0x18000000, 0x0000cdff, 0x18200000, + 0x0000d5ff, 0x18400000, 0x0000deff, 0x18610000, + 0x0000e6ff, 0x18810000, 0x0000eeff, 0x18a10000, + 0x0000f6ff, 0x18c20000, 0x0000ffff, 0x18e20000, + 0x000400ff, 0x20000000, 0x000408ff, 0x20200000, + 0x000410ff, 0x20400000, 0x000418ff, 0x20610000, + 0x000420ff, 0x20810000, 0x000429ff, 0x20a10000, + 0x000431ff, 0x20c20000, 0x000439ff, 0x20e20000, + 0x000441ff, 0x29000000, 0x00044aff, 0x29200000, + 0x000452ff, 0x29400000, 0x00045aff, 0x29610000, + 0x000462ff, 0x29810000, 0x00046aff, 0x29a10000, + 0x000473ff, 0x29c20000, 0x00047bff, 0x29e20000, + 0x000483ff, 0x31000000, 0x00048bff, 0x31200000, + 0x000494ff, 0x31400000, 0x00049cff, 0x31610000, + 0x0004a4ff, 0x31810000, 0x0004acff, 0x31a10000, + 0x0004b4ff, 0x31c20000, 0x0004bdff, 0x31e20000, + 0x0004c5ff, 0x39000000, 0x0004cdff, 0x39200000, + 0x0004d5ff, 0x39400000, 0x0004deff, 0x39610000, + 0x0004e6ff, 0x39810000, 0x0004eeff, 0x39a10000, + 0x0004f6ff, 0x39c20000, 0x0004ffff, 0x39e20000, + 0x000800ff, 0x41000000, 0x000808ff, 0x41200000, + 0x000810ff, 0x41400000, 0x000818ff, 0x41610000, + 0x000820ff, 0x41810000, 0x000829ff, 0x41a10000, + 0x000831ff, 0x41c20000, 0x000839ff, 0x41e20000, + 0x000841ff, 0x4a000000, 0x00084aff, 0x4a200000, + 0x000852ff, 0x4a400000, 0x00085aff, 0x4a610000, + 0x000862ff, 0x4a810000, 0x00086aff, 0x4aa10000, + 0x000873ff, 0x4ac20000, 0x00087bff, 0x4ae20000, + 0x000883ff, 0x52000000, 0x00088bff, 0x52200000, + 0x000894ff, 0x52400000, 0x00089cff, 0x52610000, + 0x0008a4ff, 0x52810000, 0x0008acff, 0x52a10000, + 0x0008b4ff, 0x52c20000, 0x0008bdff, 0x52e20000, + 0x0008c5ff, 0x5a000000, 0x0008cdff, 0x5a200000, + 0x0008d5ff, 0x5a400000, 0x0008deff, 0x5a610000, + 0x0008e6ff, 0x5a810000, 0x0008eeff, 0x5aa10000, + 0x0008f6ff, 0x5ac20000, 0x0008ffff, 0x5ae20000, + 0x000c00ff, 0x62000000, 0x000c08ff, 0x62200000, + 0x000c10ff, 0x62400000, 0x000c18ff, 0x62610000, + 0x000c20ff, 0x62810000, 0x000c29ff, 0x62a10000, + 0x000c31ff, 0x62c20000, 0x000c39ff, 0x62e20000, + 0x000c41ff, 0x6a000000, 0x000c4aff, 0x6a200000, + 0x000c52ff, 0x6a400000, 0x000c5aff, 0x6a610000, + 0x000c62ff, 0x6a810000, 0x000c6aff, 0x6aa10000, + 0x000c73ff, 0x6ac20000, 0x000c7bff, 0x6ae20000, + 0x000c83ff, 0x73000000, 0x000c8bff, 0x73200000, + 0x000c94ff, 0x73400000, 0x000c9cff, 0x73610000, + 0x000ca4ff, 0x73810000, 0x000cacff, 0x73a10000, + 0x000cb4ff, 0x73c20000, 0x000cbdff, 0x73e20000, + 0x000cc5ff, 0x7b000000, 0x000ccdff, 0x7b200000, + 0x000cd5ff, 0x7b400000, 0x000cdeff, 0x7b610000, + 0x000ce6ff, 0x7b810000, 0x000ceeff, 0x7ba10000, + 0x000cf6ff, 0x7bc20000, 0x000cffff, 0x7be20000, + 0x001000ff, 0x83000000, 0x001008ff, 0x83200000, + 0x001010ff, 0x83400000, 0x001018ff, 0x83610000, + 0x001020ff, 0x83810000, 0x001029ff, 0x83a10000, + 0x001031ff, 0x83c20000, 0x001039ff, 0x83e20000, + 0x001041ff, 0x8b000000, 0x00104aff, 0x8b200000, + 0x001052ff, 0x8b400000, 0x00105aff, 0x8b610000, + 0x001062ff, 0x8b810000, 0x00106aff, 0x8ba10000, + 0x001073ff, 0x8bc20000, 0x00107bff, 0x8be20000, + 0x001083ff, 0x94000000, 0x00108bff, 0x94200000, + 0x001094ff, 0x94400000, 0x00109cff, 0x94610000, + 0x0010a4ff, 0x94810000, 0x0010acff, 0x94a10000, + 0x0010b4ff, 0x94c20000, 0x0010bdff, 0x94e20000, + 0x0010c5ff, 0x9c000000, 0x0010cdff, 0x9c200000, + 0x0010d5ff, 0x9c400000, 0x0010deff, 0x9c610000, + 0x0010e6ff, 0x9c810000, 0x0010eeff, 0x9ca10000, + 0x0010f6ff, 0x9cc20000, 0x0010ffff, 0x9ce20000, + 0x001400ff, 0xa4000000, 0x001408ff, 0xa4200000, + 0x001410ff, 0xa4400000, 0x001418ff, 0xa4610000, + 0x001420ff, 0xa4810000, 0x001429ff, 0xa4a10000, + 0x001431ff, 0xa4c20000, 0x001439ff, 0xa4e20000, + 0x001441ff, 0xac000000, 0x00144aff, 0xac200000, + 0x001452ff, 0xac400000, 0x00145aff, 0xac610000, + 0x001462ff, 0xac810000, 0x00146aff, 0xaca10000, + 0x001473ff, 0xacc20000, 0x00147bff, 0xace20000, + 0x001483ff, 0xb4000000, 0x00148bff, 0xb4200000, + 0x001494ff, 0xb4400000, 0x00149cff, 0xb4610000, + 0x0014a4ff, 0xb4810000, 0x0014acff, 0xb4a10000, + 0x0014b4ff, 0xb4c20000, 0x0014bdff, 0xb4e20000, + 0x0014c5ff, 0xbd000000, 0x0014cdff, 0xbd200000, + 0x0014d5ff, 0xbd400000, 0x0014deff, 0xbd610000, + 0x0014e6ff, 0xbd810000, 0x0014eeff, 0xbda10000, + 0x0014f6ff, 0xbdc20000, 0x0014ffff, 0xbde20000, + 0x001800ff, 0xc5000000, 0x001808ff, 0xc5200000, + 0x001810ff, 0xc5400000, 0x001818ff, 0xc5610000, + 0x001820ff, 0xc5810000, 0x001829ff, 0xc5a10000, + 0x001831ff, 0xc5c20000, 0x001839ff, 0xc5e20000, + 0x001841ff, 0xcd000000, 0x00184aff, 0xcd200000, + 0x001852ff, 0xcd400000, 0x00185aff, 0xcd610000, + 0x001862ff, 0xcd810000, 0x00186aff, 0xcda10000, + 0x001873ff, 0xcdc20000, 0x00187bff, 0xcde20000, + 0x001883ff, 0xd5000000, 0x00188bff, 0xd5200000, + 0x001894ff, 0xd5400000, 0x00189cff, 0xd5610000, + 0x0018a4ff, 0xd5810000, 0x0018acff, 0xd5a10000, + 0x0018b4ff, 0xd5c20000, 0x0018bdff, 0xd5e20000, + 0x0018c5ff, 0xde000000, 0x0018cdff, 0xde200000, + 0x0018d5ff, 0xde400000, 0x0018deff, 0xde610000, + 0x0018e6ff, 0xde810000, 0x0018eeff, 0xdea10000, + 0x0018f6ff, 0xdec20000, 0x0018ffff, 0xdee20000, + 0x001c00ff, 0xe6000000, 0x001c08ff, 0xe6200000, + 0x001c10ff, 0xe6400000, 0x001c18ff, 0xe6610000, + 0x001c20ff, 0xe6810000, 0x001c29ff, 0xe6a10000, + 0x001c31ff, 0xe6c20000, 0x001c39ff, 0xe6e20000, + 0x001c41ff, 0xee000000, 0x001c4aff, 0xee200000, + 0x001c52ff, 0xee400000, 0x001c5aff, 0xee610000, + 0x001c62ff, 0xee810000, 0x001c6aff, 0xeea10000, + 0x001c73ff, 0xeec20000, 0x001c7bff, 0xeee20000, + 0x001c83ff, 0xf6000000, 0x001c8bff, 0xf6200000, + 0x001c94ff, 0xf6400000, 0x001c9cff, 0xf6610000, + 0x001ca4ff, 0xf6810000, 0x001cacff, 0xf6a10000, + 0x001cb4ff, 0xf6c20000, 0x001cbdff, 0xf6e20000, + 0x001cc5ff, 0xff000000, 0x001ccdff, 0xff200000, + 0x001cd5ff, 0xff400000, 0x001cdeff, 0xff610000, + 0x001ce6ff, 0xff810000, 0x001ceeff, 0xffa10000, + 0x001cf6ff, 0xffc20000, 0x001cffff, 0xffe20000, }; -static void Blit_RGB565_RGBA8888(SDL_BlitInfo *info) +static void +Blit_RGB565_RGBA8888(SDL_BlitInfo * info) { Blit_RGB565_32(info, RGB565_RGBA8888_LUT); } /* Special optimized blit for RGB 5-6-5 --> BGRA 8-8-8-8 */ static const Uint32 RGB565_BGRA8888_LUT[512] = { - 0x00000000, 0x000000ff, 0x08000000, 0x002000ff, - 0x10000000, 0x004000ff, 0x18000000, 0x006100ff, - 0x20000000, 0x008100ff, 0x29000000, 0x00a100ff, - 0x31000000, 0x00c200ff, 0x39000000, 0x00e200ff, - 0x41000000, 0x000008ff, 0x4a000000, 0x002008ff, - 0x52000000, 0x004008ff, 0x5a000000, 0x006108ff, - 0x62000000, 0x008108ff, 0x6a000000, 0x00a108ff, - 0x73000000, 0x00c208ff, 0x7b000000, 0x00e208ff, - 0x83000000, 0x000010ff, 0x8b000000, 0x002010ff, - 0x94000000, 0x004010ff, 0x9c000000, 0x006110ff, - 0xa4000000, 0x008110ff, 0xac000000, 0x00a110ff, - 0xb4000000, 0x00c210ff, 0xbd000000, 0x00e210ff, - 0xc5000000, 0x000018ff, 0xcd000000, 0x002018ff, - 0xd5000000, 0x004018ff, 0xde000000, 0x006118ff, - 0xe6000000, 0x008118ff, 0xee000000, 0x00a118ff, - 0xf6000000, 0x00c218ff, 0xff000000, 0x00e218ff, - 0x00040000, 0x000020ff, 0x08040000, 0x002020ff, - 0x10040000, 0x004020ff, 0x18040000, 0x006120ff, - 0x20040000, 0x008120ff, 0x29040000, 0x00a120ff, - 0x31040000, 0x00c220ff, 0x39040000, 0x00e220ff, - 0x41040000, 0x000029ff, 0x4a040000, 0x002029ff, - 0x52040000, 0x004029ff, 0x5a040000, 0x006129ff, - 0x62040000, 0x008129ff, 0x6a040000, 0x00a129ff, - 0x73040000, 0x00c229ff, 0x7b040000, 0x00e229ff, - 0x83040000, 0x000031ff, 0x8b040000, 0x002031ff, - 0x94040000, 0x004031ff, 0x9c040000, 0x006131ff, - 0xa4040000, 0x008131ff, 0xac040000, 0x00a131ff, - 0xb4040000, 0x00c231ff, 0xbd040000, 0x00e231ff, - 0xc5040000, 0x000039ff, 0xcd040000, 0x002039ff, - 0xd5040000, 0x004039ff, 0xde040000, 0x006139ff, - 0xe6040000, 0x008139ff, 0xee040000, 0x00a139ff, - 0xf6040000, 0x00c239ff, 0xff040000, 0x00e239ff, - 0x00080000, 0x000041ff, 0x08080000, 0x002041ff, - 0x10080000, 0x004041ff, 0x18080000, 0x006141ff, - 0x20080000, 0x008141ff, 0x29080000, 0x00a141ff, - 0x31080000, 0x00c241ff, 0x39080000, 0x00e241ff, - 0x41080000, 0x00004aff, 0x4a080000, 0x00204aff, - 0x52080000, 0x00404aff, 0x5a080000, 0x00614aff, - 0x62080000, 0x00814aff, 0x6a080000, 0x00a14aff, - 0x73080000, 0x00c24aff, 0x7b080000, 0x00e24aff, - 0x83080000, 0x000052ff, 0x8b080000, 0x002052ff, - 0x94080000, 0x004052ff, 0x9c080000, 0x006152ff, - 0xa4080000, 0x008152ff, 0xac080000, 0x00a152ff, - 0xb4080000, 0x00c252ff, 0xbd080000, 0x00e252ff, - 0xc5080000, 0x00005aff, 0xcd080000, 0x00205aff, - 0xd5080000, 0x00405aff, 0xde080000, 0x00615aff, - 0xe6080000, 0x00815aff, 0xee080000, 0x00a15aff, - 0xf6080000, 0x00c25aff, 0xff080000, 0x00e25aff, - 0x000c0000, 0x000062ff, 0x080c0000, 0x002062ff, - 0x100c0000, 0x004062ff, 0x180c0000, 0x006162ff, - 0x200c0000, 0x008162ff, 0x290c0000, 0x00a162ff, - 0x310c0000, 0x00c262ff, 0x390c0000, 0x00e262ff, - 0x410c0000, 0x00006aff, 0x4a0c0000, 0x00206aff, - 0x520c0000, 0x00406aff, 0x5a0c0000, 0x00616aff, - 0x620c0000, 0x00816aff, 0x6a0c0000, 0x00a16aff, - 0x730c0000, 0x00c26aff, 0x7b0c0000, 0x00e26aff, - 0x830c0000, 0x000073ff, 0x8b0c0000, 0x002073ff, - 0x940c0000, 0x004073ff, 0x9c0c0000, 0x006173ff, - 0xa40c0000, 0x008173ff, 0xac0c0000, 0x00a173ff, - 0xb40c0000, 0x00c273ff, 0xbd0c0000, 0x00e273ff, - 0xc50c0000, 0x00007bff, 0xcd0c0000, 0x00207bff, - 0xd50c0000, 0x00407bff, 0xde0c0000, 0x00617bff, - 0xe60c0000, 0x00817bff, 0xee0c0000, 0x00a17bff, - 0xf60c0000, 0x00c27bff, 0xff0c0000, 0x00e27bff, - 0x00100000, 0x000083ff, 0x08100000, 0x002083ff, - 0x10100000, 0x004083ff, 0x18100000, 0x006183ff, - 0x20100000, 0x008183ff, 0x29100000, 0x00a183ff, - 0x31100000, 0x00c283ff, 0x39100000, 0x00e283ff, - 0x41100000, 0x00008bff, 0x4a100000, 0x00208bff, - 0x52100000, 0x00408bff, 0x5a100000, 0x00618bff, - 0x62100000, 0x00818bff, 0x6a100000, 0x00a18bff, - 0x73100000, 0x00c28bff, 0x7b100000, 0x00e28bff, - 0x83100000, 0x000094ff, 0x8b100000, 0x002094ff, - 0x94100000, 0x004094ff, 0x9c100000, 0x006194ff, - 0xa4100000, 0x008194ff, 0xac100000, 0x00a194ff, - 0xb4100000, 0x00c294ff, 0xbd100000, 0x00e294ff, - 0xc5100000, 0x00009cff, 0xcd100000, 0x00209cff, - 0xd5100000, 0x00409cff, 0xde100000, 0x00619cff, - 0xe6100000, 0x00819cff, 0xee100000, 0x00a19cff, - 0xf6100000, 0x00c29cff, 0xff100000, 0x00e29cff, - 0x00140000, 0x0000a4ff, 0x08140000, 0x0020a4ff, - 0x10140000, 0x0040a4ff, 0x18140000, 0x0061a4ff, - 0x20140000, 0x0081a4ff, 0x29140000, 0x00a1a4ff, - 0x31140000, 0x00c2a4ff, 0x39140000, 0x00e2a4ff, - 0x41140000, 0x0000acff, 0x4a140000, 0x0020acff, - 0x52140000, 0x0040acff, 0x5a140000, 0x0061acff, - 0x62140000, 0x0081acff, 0x6a140000, 0x00a1acff, - 0x73140000, 0x00c2acff, 0x7b140000, 0x00e2acff, - 0x83140000, 0x0000b4ff, 0x8b140000, 0x0020b4ff, - 0x94140000, 0x0040b4ff, 0x9c140000, 0x0061b4ff, - 0xa4140000, 0x0081b4ff, 0xac140000, 0x00a1b4ff, - 0xb4140000, 0x00c2b4ff, 0xbd140000, 0x00e2b4ff, - 0xc5140000, 0x0000bdff, 0xcd140000, 0x0020bdff, - 0xd5140000, 0x0040bdff, 0xde140000, 0x0061bdff, - 0xe6140000, 0x0081bdff, 0xee140000, 0x00a1bdff, - 0xf6140000, 0x00c2bdff, 0xff140000, 0x00e2bdff, - 0x00180000, 0x0000c5ff, 0x08180000, 0x0020c5ff, - 0x10180000, 0x0040c5ff, 0x18180000, 0x0061c5ff, - 0x20180000, 0x0081c5ff, 0x29180000, 0x00a1c5ff, - 0x31180000, 0x00c2c5ff, 0x39180000, 0x00e2c5ff, - 0x41180000, 0x0000cdff, 0x4a180000, 0x0020cdff, - 0x52180000, 0x0040cdff, 0x5a180000, 0x0061cdff, - 0x62180000, 0x0081cdff, 0x6a180000, 0x00a1cdff, - 0x73180000, 0x00c2cdff, 0x7b180000, 0x00e2cdff, - 0x83180000, 0x0000d5ff, 0x8b180000, 0x0020d5ff, - 0x94180000, 0x0040d5ff, 0x9c180000, 0x0061d5ff, - 0xa4180000, 0x0081d5ff, 0xac180000, 0x00a1d5ff, - 0xb4180000, 0x00c2d5ff, 0xbd180000, 0x00e2d5ff, - 0xc5180000, 0x0000deff, 0xcd180000, 0x0020deff, - 0xd5180000, 0x0040deff, 0xde180000, 0x0061deff, - 0xe6180000, 0x0081deff, 0xee180000, 0x00a1deff, - 0xf6180000, 0x00c2deff, 0xff180000, 0x00e2deff, - 0x001c0000, 0x0000e6ff, 0x081c0000, 0x0020e6ff, - 0x101c0000, 0x0040e6ff, 0x181c0000, 0x0061e6ff, - 0x201c0000, 0x0081e6ff, 0x291c0000, 0x00a1e6ff, - 0x311c0000, 0x00c2e6ff, 0x391c0000, 0x00e2e6ff, - 0x411c0000, 0x0000eeff, 0x4a1c0000, 0x0020eeff, - 0x521c0000, 0x0040eeff, 0x5a1c0000, 0x0061eeff, - 0x621c0000, 0x0081eeff, 0x6a1c0000, 0x00a1eeff, - 0x731c0000, 0x00c2eeff, 0x7b1c0000, 0x00e2eeff, - 0x831c0000, 0x0000f6ff, 0x8b1c0000, 0x0020f6ff, - 0x941c0000, 0x0040f6ff, 0x9c1c0000, 0x0061f6ff, - 0xa41c0000, 0x0081f6ff, 0xac1c0000, 0x00a1f6ff, - 0xb41c0000, 0x00c2f6ff, 0xbd1c0000, 0x00e2f6ff, - 0xc51c0000, 0x0000ffff, 0xcd1c0000, 0x0020ffff, - 0xd51c0000, 0x0040ffff, 0xde1c0000, 0x0061ffff, - 0xe61c0000, 0x0081ffff, 0xee1c0000, 0x00a1ffff, - 0xf61c0000, 0x00c2ffff, 0xff1c0000, 0x00e2ffff + 0x00000000, 0x000000ff, 0x08000000, 0x002000ff, + 0x10000000, 0x004000ff, 0x18000000, 0x006100ff, + 0x20000000, 0x008100ff, 0x29000000, 0x00a100ff, + 0x31000000, 0x00c200ff, 0x39000000, 0x00e200ff, + 0x41000000, 0x000008ff, 0x4a000000, 0x002008ff, + 0x52000000, 0x004008ff, 0x5a000000, 0x006108ff, + 0x62000000, 0x008108ff, 0x6a000000, 0x00a108ff, + 0x73000000, 0x00c208ff, 0x7b000000, 0x00e208ff, + 0x83000000, 0x000010ff, 0x8b000000, 0x002010ff, + 0x94000000, 0x004010ff, 0x9c000000, 0x006110ff, + 0xa4000000, 0x008110ff, 0xac000000, 0x00a110ff, + 0xb4000000, 0x00c210ff, 0xbd000000, 0x00e210ff, + 0xc5000000, 0x000018ff, 0xcd000000, 0x002018ff, + 0xd5000000, 0x004018ff, 0xde000000, 0x006118ff, + 0xe6000000, 0x008118ff, 0xee000000, 0x00a118ff, + 0xf6000000, 0x00c218ff, 0xff000000, 0x00e218ff, + 0x00040000, 0x000020ff, 0x08040000, 0x002020ff, + 0x10040000, 0x004020ff, 0x18040000, 0x006120ff, + 0x20040000, 0x008120ff, 0x29040000, 0x00a120ff, + 0x31040000, 0x00c220ff, 0x39040000, 0x00e220ff, + 0x41040000, 0x000029ff, 0x4a040000, 0x002029ff, + 0x52040000, 0x004029ff, 0x5a040000, 0x006129ff, + 0x62040000, 0x008129ff, 0x6a040000, 0x00a129ff, + 0x73040000, 0x00c229ff, 0x7b040000, 0x00e229ff, + 0x83040000, 0x000031ff, 0x8b040000, 0x002031ff, + 0x94040000, 0x004031ff, 0x9c040000, 0x006131ff, + 0xa4040000, 0x008131ff, 0xac040000, 0x00a131ff, + 0xb4040000, 0x00c231ff, 0xbd040000, 0x00e231ff, + 0xc5040000, 0x000039ff, 0xcd040000, 0x002039ff, + 0xd5040000, 0x004039ff, 0xde040000, 0x006139ff, + 0xe6040000, 0x008139ff, 0xee040000, 0x00a139ff, + 0xf6040000, 0x00c239ff, 0xff040000, 0x00e239ff, + 0x00080000, 0x000041ff, 0x08080000, 0x002041ff, + 0x10080000, 0x004041ff, 0x18080000, 0x006141ff, + 0x20080000, 0x008141ff, 0x29080000, 0x00a141ff, + 0x31080000, 0x00c241ff, 0x39080000, 0x00e241ff, + 0x41080000, 0x00004aff, 0x4a080000, 0x00204aff, + 0x52080000, 0x00404aff, 0x5a080000, 0x00614aff, + 0x62080000, 0x00814aff, 0x6a080000, 0x00a14aff, + 0x73080000, 0x00c24aff, 0x7b080000, 0x00e24aff, + 0x83080000, 0x000052ff, 0x8b080000, 0x002052ff, + 0x94080000, 0x004052ff, 0x9c080000, 0x006152ff, + 0xa4080000, 0x008152ff, 0xac080000, 0x00a152ff, + 0xb4080000, 0x00c252ff, 0xbd080000, 0x00e252ff, + 0xc5080000, 0x00005aff, 0xcd080000, 0x00205aff, + 0xd5080000, 0x00405aff, 0xde080000, 0x00615aff, + 0xe6080000, 0x00815aff, 0xee080000, 0x00a15aff, + 0xf6080000, 0x00c25aff, 0xff080000, 0x00e25aff, + 0x000c0000, 0x000062ff, 0x080c0000, 0x002062ff, + 0x100c0000, 0x004062ff, 0x180c0000, 0x006162ff, + 0x200c0000, 0x008162ff, 0x290c0000, 0x00a162ff, + 0x310c0000, 0x00c262ff, 0x390c0000, 0x00e262ff, + 0x410c0000, 0x00006aff, 0x4a0c0000, 0x00206aff, + 0x520c0000, 0x00406aff, 0x5a0c0000, 0x00616aff, + 0x620c0000, 0x00816aff, 0x6a0c0000, 0x00a16aff, + 0x730c0000, 0x00c26aff, 0x7b0c0000, 0x00e26aff, + 0x830c0000, 0x000073ff, 0x8b0c0000, 0x002073ff, + 0x940c0000, 0x004073ff, 0x9c0c0000, 0x006173ff, + 0xa40c0000, 0x008173ff, 0xac0c0000, 0x00a173ff, + 0xb40c0000, 0x00c273ff, 0xbd0c0000, 0x00e273ff, + 0xc50c0000, 0x00007bff, 0xcd0c0000, 0x00207bff, + 0xd50c0000, 0x00407bff, 0xde0c0000, 0x00617bff, + 0xe60c0000, 0x00817bff, 0xee0c0000, 0x00a17bff, + 0xf60c0000, 0x00c27bff, 0xff0c0000, 0x00e27bff, + 0x00100000, 0x000083ff, 0x08100000, 0x002083ff, + 0x10100000, 0x004083ff, 0x18100000, 0x006183ff, + 0x20100000, 0x008183ff, 0x29100000, 0x00a183ff, + 0x31100000, 0x00c283ff, 0x39100000, 0x00e283ff, + 0x41100000, 0x00008bff, 0x4a100000, 0x00208bff, + 0x52100000, 0x00408bff, 0x5a100000, 0x00618bff, + 0x62100000, 0x00818bff, 0x6a100000, 0x00a18bff, + 0x73100000, 0x00c28bff, 0x7b100000, 0x00e28bff, + 0x83100000, 0x000094ff, 0x8b100000, 0x002094ff, + 0x94100000, 0x004094ff, 0x9c100000, 0x006194ff, + 0xa4100000, 0x008194ff, 0xac100000, 0x00a194ff, + 0xb4100000, 0x00c294ff, 0xbd100000, 0x00e294ff, + 0xc5100000, 0x00009cff, 0xcd100000, 0x00209cff, + 0xd5100000, 0x00409cff, 0xde100000, 0x00619cff, + 0xe6100000, 0x00819cff, 0xee100000, 0x00a19cff, + 0xf6100000, 0x00c29cff, 0xff100000, 0x00e29cff, + 0x00140000, 0x0000a4ff, 0x08140000, 0x0020a4ff, + 0x10140000, 0x0040a4ff, 0x18140000, 0x0061a4ff, + 0x20140000, 0x0081a4ff, 0x29140000, 0x00a1a4ff, + 0x31140000, 0x00c2a4ff, 0x39140000, 0x00e2a4ff, + 0x41140000, 0x0000acff, 0x4a140000, 0x0020acff, + 0x52140000, 0x0040acff, 0x5a140000, 0x0061acff, + 0x62140000, 0x0081acff, 0x6a140000, 0x00a1acff, + 0x73140000, 0x00c2acff, 0x7b140000, 0x00e2acff, + 0x83140000, 0x0000b4ff, 0x8b140000, 0x0020b4ff, + 0x94140000, 0x0040b4ff, 0x9c140000, 0x0061b4ff, + 0xa4140000, 0x0081b4ff, 0xac140000, 0x00a1b4ff, + 0xb4140000, 0x00c2b4ff, 0xbd140000, 0x00e2b4ff, + 0xc5140000, 0x0000bdff, 0xcd140000, 0x0020bdff, + 0xd5140000, 0x0040bdff, 0xde140000, 0x0061bdff, + 0xe6140000, 0x0081bdff, 0xee140000, 0x00a1bdff, + 0xf6140000, 0x00c2bdff, 0xff140000, 0x00e2bdff, + 0x00180000, 0x0000c5ff, 0x08180000, 0x0020c5ff, + 0x10180000, 0x0040c5ff, 0x18180000, 0x0061c5ff, + 0x20180000, 0x0081c5ff, 0x29180000, 0x00a1c5ff, + 0x31180000, 0x00c2c5ff, 0x39180000, 0x00e2c5ff, + 0x41180000, 0x0000cdff, 0x4a180000, 0x0020cdff, + 0x52180000, 0x0040cdff, 0x5a180000, 0x0061cdff, + 0x62180000, 0x0081cdff, 0x6a180000, 0x00a1cdff, + 0x73180000, 0x00c2cdff, 0x7b180000, 0x00e2cdff, + 0x83180000, 0x0000d5ff, 0x8b180000, 0x0020d5ff, + 0x94180000, 0x0040d5ff, 0x9c180000, 0x0061d5ff, + 0xa4180000, 0x0081d5ff, 0xac180000, 0x00a1d5ff, + 0xb4180000, 0x00c2d5ff, 0xbd180000, 0x00e2d5ff, + 0xc5180000, 0x0000deff, 0xcd180000, 0x0020deff, + 0xd5180000, 0x0040deff, 0xde180000, 0x0061deff, + 0xe6180000, 0x0081deff, 0xee180000, 0x00a1deff, + 0xf6180000, 0x00c2deff, 0xff180000, 0x00e2deff, + 0x001c0000, 0x0000e6ff, 0x081c0000, 0x0020e6ff, + 0x101c0000, 0x0040e6ff, 0x181c0000, 0x0061e6ff, + 0x201c0000, 0x0081e6ff, 0x291c0000, 0x00a1e6ff, + 0x311c0000, 0x00c2e6ff, 0x391c0000, 0x00e2e6ff, + 0x411c0000, 0x0000eeff, 0x4a1c0000, 0x0020eeff, + 0x521c0000, 0x0040eeff, 0x5a1c0000, 0x0061eeff, + 0x621c0000, 0x0081eeff, 0x6a1c0000, 0x00a1eeff, + 0x731c0000, 0x00c2eeff, 0x7b1c0000, 0x00e2eeff, + 0x831c0000, 0x0000f6ff, 0x8b1c0000, 0x0020f6ff, + 0x941c0000, 0x0040f6ff, 0x9c1c0000, 0x0061f6ff, + 0xa41c0000, 0x0081f6ff, 0xac1c0000, 0x00a1f6ff, + 0xb41c0000, 0x00c2f6ff, 0xbd1c0000, 0x00e2f6ff, + 0xc51c0000, 0x0000ffff, 0xcd1c0000, 0x0020ffff, + 0xd51c0000, 0x0040ffff, 0xde1c0000, 0x0061ffff, + 0xe61c0000, 0x0081ffff, 0xee1c0000, 0x00a1ffff, + 0xf61c0000, 0x00c2ffff, 0xff1c0000, 0x00e2ffff }; -static void Blit_RGB565_BGRA8888(SDL_BlitInfo *info) +static void +Blit_RGB565_BGRA8888(SDL_BlitInfo * info) { Blit_RGB565_32(info, RGB565_BGRA8888_LUT); } @@ -1826,102 +1875,107 @@ static void Blit_RGB565_BGRA8888(SDL_BlitInfo *info) (((src)&0x000000C0)>>6); \ } #endif -static void Blit_RGB888_index8_map(SDL_BlitInfo *info) +static void +Blit_RGB888_index8_map(SDL_BlitInfo * info) { #ifndef USE_DUFFS_LOOP - int c; + int c; #endif - int Pixel; - int width, height; - Uint32 *src; - const Uint8 *map; - Uint8 *dst; - int srcskip, dstskip; - - /* Set up some basic variables */ - width = info->d_width; - height = info->d_height; - src = (Uint32 *)info->s_pixels; - srcskip = info->s_skip/4; - dst = info->d_pixels; - dstskip = info->d_skip; - map = info->table; + int Pixel; + int width, height; + Uint32 *src; + const Uint8 *map; + Uint8 *dst; + int srcskip, dstskip; + + /* Set up some basic variables */ + width = info->d_width; + height = info->d_height; + src = (Uint32 *) info->s_pixels; + srcskip = info->s_skip / 4; + dst = info->d_pixels; + dstskip = info->d_skip; + map = info->table; #ifdef USE_DUFFS_LOOP - while ( height-- ) { + while (height--) { + /* *INDENT-OFF* */ DUFFS_LOOP( RGB888_RGB332(Pixel, *src); *dst++ = map[Pixel]; ++src; , width); - src += srcskip; - dst += dstskip; - } + /* *INDENT-ON* */ + src += srcskip; + dst += dstskip; + } #else - while ( height-- ) { - for ( c=width/4; c; --c ) { - /* Pack RGB into 8bit pixel */ - RGB888_RGB332(Pixel, *src); - *dst++ = map[Pixel]; - ++src; - RGB888_RGB332(Pixel, *src); - *dst++ = map[Pixel]; - ++src; - RGB888_RGB332(Pixel, *src); - *dst++ = map[Pixel]; - ++src; - RGB888_RGB332(Pixel, *src); - *dst++ = map[Pixel]; - ++src; - } - switch ( width & 3 ) { - case 3: - RGB888_RGB332(Pixel, *src); - *dst++ = map[Pixel]; - ++src; - case 2: - RGB888_RGB332(Pixel, *src); - *dst++ = map[Pixel]; - ++src; - case 1: - RGB888_RGB332(Pixel, *src); - *dst++ = map[Pixel]; - ++src; - } - src += srcskip; - dst += dstskip; - } + while (height--) { + for (c = width / 4; c; --c) { + /* Pack RGB into 8bit pixel */ + RGB888_RGB332(Pixel, *src); + *dst++ = map[Pixel]; + ++src; + RGB888_RGB332(Pixel, *src); + *dst++ = map[Pixel]; + ++src; + RGB888_RGB332(Pixel, *src); + *dst++ = map[Pixel]; + ++src; + RGB888_RGB332(Pixel, *src); + *dst++ = map[Pixel]; + ++src; + } + switch (width & 3) { + case 3: + RGB888_RGB332(Pixel, *src); + *dst++ = map[Pixel]; + ++src; + case 2: + RGB888_RGB332(Pixel, *src); + *dst++ = map[Pixel]; + ++src; + case 1: + RGB888_RGB332(Pixel, *src); + *dst++ = map[Pixel]; + ++src; + } + src += srcskip; + dst += dstskip; + } #endif /* USE_DUFFS_LOOP */ } -static void BlitNto1(SDL_BlitInfo *info) +static void +BlitNto1(SDL_BlitInfo * info) { #ifndef USE_DUFFS_LOOP - int c; + int c; #endif - int width, height; - Uint8 *src; - const Uint8 *map; - Uint8 *dst; - int srcskip, dstskip; - int srcbpp; - Uint32 Pixel; - int sR, sG, sB; - SDL_PixelFormat *srcfmt; - - /* Set up some basic variables */ - width = info->d_width; - height = info->d_height; - src = info->s_pixels; - srcskip = info->s_skip; - dst = info->d_pixels; - dstskip = info->d_skip; - map = info->table; - srcfmt = info->src; - srcbpp = srcfmt->BytesPerPixel; - - if ( map == NULL ) { - while ( height-- ) { + int width, height; + Uint8 *src; + const Uint8 *map; + Uint8 *dst; + int srcskip, dstskip; + int srcbpp; + Uint32 Pixel; + int sR, sG, sB; + SDL_PixelFormat *srcfmt; + + /* Set up some basic variables */ + width = info->d_width; + height = info->d_height; + src = info->s_pixels; + srcskip = info->s_skip; + dst = info->d_pixels; + dstskip = info->d_skip; + map = info->table; + srcfmt = info->src; + srcbpp = srcfmt->BytesPerPixel; + + if (map == NULL) { + while (height--) { #ifdef USE_DUFFS_LOOP + /* *INDENT-OFF* */ DUFFS_LOOP( DISEMBLE_RGB(src, srcbpp, srcfmt, Pixel, sR, sG, sB); @@ -1934,26 +1988,26 @@ static void BlitNto1(SDL_BlitInfo *info) dst++; src += srcbpp; , width); + /* *INDENT-ON* */ #else - for ( c=width; c; --c ) { - DISEMBLE_RGB(src, srcbpp, srcfmt, Pixel, - sR, sG, sB); - if ( 1 ) { - /* Pack RGB into 8bit pixel */ - *dst = ((sR>>5)<<(3+2))| - ((sG>>5)<<(2)) | - ((sB>>6)<<(0)) ; - } - dst++; - src += srcbpp; - } + for (c = width; c; --c) { + DISEMBLE_RGB(src, srcbpp, srcfmt, Pixel, sR, sG, sB); + if (1) { + /* Pack RGB into 8bit pixel */ + *dst = ((sR >> 5) << (3 + 2)) | + ((sG >> 5) << (2)) | ((sB >> 6) << (0)); + } + dst++; + src += srcbpp; + } #endif - src += srcskip; - dst += dstskip; - } - } else { - while ( height-- ) { + src += srcskip; + dst += dstskip; + } + } else { + while (height--) { #ifdef USE_DUFFS_LOOP + /* *INDENT-OFF* */ DUFFS_LOOP( DISEMBLE_RGB(src, srcbpp, srcfmt, Pixel, sR, sG, sB); @@ -1966,43 +2020,44 @@ static void BlitNto1(SDL_BlitInfo *info) dst++; src += srcbpp; , width); + /* *INDENT-ON* */ #else - for ( c=width; c; --c ) { - DISEMBLE_RGB(src, srcbpp, srcfmt, Pixel, - sR, sG, sB); - if ( 1 ) { - /* Pack RGB into 8bit pixel */ - *dst = map[((sR>>5)<<(3+2))| - ((sG>>5)<<(2)) | - ((sB>>6)<<(0)) ]; - } - dst++; - src += srcbpp; - } + for (c = width; c; --c) { + DISEMBLE_RGB(src, srcbpp, srcfmt, Pixel, sR, sG, sB); + if (1) { + /* Pack RGB into 8bit pixel */ + *dst = map[((sR >> 5) << (3 + 2)) | + ((sG >> 5) << (2)) | ((sB >> 6) << (0))]; + } + dst++; + src += srcbpp; + } #endif /* USE_DUFFS_LOOP */ - src += srcskip; - dst += dstskip; - } - } + src += srcskip; + dst += dstskip; + } + } } /* blits 32 bit RGB<->RGBA with both surfaces having the same R,G,B fields */ -static void Blit4to4MaskAlpha(SDL_BlitInfo *info) +static void +Blit4to4MaskAlpha(SDL_BlitInfo * info) { - int width = info->d_width; - int height = info->d_height; - Uint32 *src = (Uint32 *)info->s_pixels; - int srcskip = info->s_skip; - Uint32 *dst = (Uint32 *)info->d_pixels; - int dstskip = info->d_skip; - SDL_PixelFormat *srcfmt = info->src; - SDL_PixelFormat *dstfmt = info->dst; - - if (dstfmt->Amask) { - /* RGB->RGBA, SET_ALPHA */ - Uint32 mask = (srcfmt->alpha >> dstfmt->Aloss) << dstfmt->Ashift; - - while ( height-- ) { + int width = info->d_width; + int height = info->d_height; + Uint32 *src = (Uint32 *) info->s_pixels; + int srcskip = info->s_skip; + Uint32 *dst = (Uint32 *) info->d_pixels; + int dstskip = info->d_skip; + SDL_PixelFormat *srcfmt = info->src; + SDL_PixelFormat *dstfmt = info->dst; + + if (dstfmt->Amask) { + /* RGB->RGBA, SET_ALPHA */ + Uint32 mask = (srcfmt->alpha >> dstfmt->Aloss) << dstfmt->Ashift; + + while (height--) { + /* *INDENT-OFF* */ DUFFS_LOOP( { *dst = *src | mask; @@ -2010,14 +2065,16 @@ static void Blit4to4MaskAlpha(SDL_BlitInfo *info) ++src; }, width); - src = (Uint32*)((Uint8*)src + srcskip); - dst = (Uint32*)((Uint8*)dst + dstskip); - } - } else { - /* RGBA->RGB, NO_ALPHA */ - Uint32 mask = srcfmt->Rmask | srcfmt->Gmask | srcfmt->Bmask; - - while ( height-- ) { + /* *INDENT-ON* */ + src = (Uint32 *) ((Uint8 *) src + srcskip); + dst = (Uint32 *) ((Uint8 *) dst + dstskip); + } + } else { + /* RGBA->RGB, NO_ALPHA */ + Uint32 mask = srcfmt->Rmask | srcfmt->Gmask | srcfmt->Bmask; + + while (height--) { + /* *INDENT-OFF* */ DUFFS_LOOP( { *dst = *src & mask; @@ -2025,27 +2082,30 @@ static void Blit4to4MaskAlpha(SDL_BlitInfo *info) ++src; }, width); - src = (Uint32*)((Uint8*)src + srcskip); - dst = (Uint32*)((Uint8*)dst + dstskip); - } - } + /* *INDENT-ON* */ + src = (Uint32 *) ((Uint8 *) src + srcskip); + dst = (Uint32 *) ((Uint8 *) dst + dstskip); + } + } } -static void BlitNtoN(SDL_BlitInfo *info) +static void +BlitNtoN(SDL_BlitInfo * info) { - int width = info->d_width; - int height = info->d_height; - Uint8 *src = info->s_pixels; - int srcskip = info->s_skip; - Uint8 *dst = info->d_pixels; - int dstskip = info->d_skip; - SDL_PixelFormat *srcfmt = info->src; - int srcbpp = srcfmt->BytesPerPixel; - SDL_PixelFormat *dstfmt = info->dst; - int dstbpp = dstfmt->BytesPerPixel; - unsigned alpha = dstfmt->Amask ? srcfmt->alpha : 0; - - while ( height-- ) { + int width = info->d_width; + int height = info->d_height; + Uint8 *src = info->s_pixels; + int srcskip = info->s_skip; + Uint8 *dst = info->d_pixels; + int dstskip = info->d_skip; + SDL_PixelFormat *srcfmt = info->src; + int srcbpp = srcfmt->BytesPerPixel; + SDL_PixelFormat *dstfmt = info->dst; + int dstbpp = dstfmt->BytesPerPixel; + unsigned alpha = dstfmt->Amask ? srcfmt->alpha : 0; + + while (height--) { + /* *INDENT-OFF* */ DUFFS_LOOP( { Uint32 Pixel; @@ -2058,64 +2118,66 @@ static void BlitNtoN(SDL_BlitInfo *info) src += srcbpp; }, width); - src += srcskip; - dst += dstskip; - } + /* *INDENT-ON* */ + src += srcskip; + dst += dstskip; + } } -static void BlitNtoNCopyAlpha(SDL_BlitInfo *info) +static void +BlitNtoNCopyAlpha(SDL_BlitInfo * info) { - int width = info->d_width; - int height = info->d_height; - Uint8 *src = info->s_pixels; - int srcskip = info->s_skip; - Uint8 *dst = info->d_pixels; - int dstskip = info->d_skip; - SDL_PixelFormat *srcfmt = info->src; - int srcbpp = srcfmt->BytesPerPixel; - SDL_PixelFormat *dstfmt = info->dst; - int dstbpp = dstfmt->BytesPerPixel; - int c; - - /* FIXME: should map alpha to [0..255] correctly! */ - while ( height-- ) { - for ( c=width; c; --c ) { - Uint32 Pixel; - unsigned sR, sG, sB, sA; - DISEMBLE_RGBA(src, srcbpp, srcfmt, Pixel, - sR, sG, sB, sA); - ASSEMBLE_RGBA(dst, dstbpp, dstfmt, - sR, sG, sB, sA); - dst += dstbpp; - src += srcbpp; - } - src += srcskip; - dst += dstskip; - } + int width = info->d_width; + int height = info->d_height; + Uint8 *src = info->s_pixels; + int srcskip = info->s_skip; + Uint8 *dst = info->d_pixels; + int dstskip = info->d_skip; + SDL_PixelFormat *srcfmt = info->src; + int srcbpp = srcfmt->BytesPerPixel; + SDL_PixelFormat *dstfmt = info->dst; + int dstbpp = dstfmt->BytesPerPixel; + int c; + + /* FIXME: should map alpha to [0..255] correctly! */ + while (height--) { + for (c = width; c; --c) { + Uint32 Pixel; + unsigned sR, sG, sB, sA; + DISEMBLE_RGBA(src, srcbpp, srcfmt, Pixel, sR, sG, sB, sA); + ASSEMBLE_RGBA(dst, dstbpp, dstfmt, sR, sG, sB, sA); + dst += dstbpp; + src += srcbpp; + } + src += srcskip; + dst += dstskip; + } } -static void BlitNto1Key(SDL_BlitInfo *info) +static void +BlitNto1Key(SDL_BlitInfo * info) { - int width = info->d_width; - int height = info->d_height; - Uint8 *src = info->s_pixels; - int srcskip = info->s_skip; - Uint8 *dst = info->d_pixels; - int dstskip = info->d_skip; - SDL_PixelFormat *srcfmt = info->src; - const Uint8 *palmap = info->table; - Uint32 ckey = srcfmt->colorkey; - Uint32 rgbmask = ~srcfmt->Amask; - int srcbpp; - Uint32 Pixel; - unsigned sR, sG, sB; - - /* Set up some basic variables */ - srcbpp = srcfmt->BytesPerPixel; - ckey &= rgbmask; - - if ( palmap == NULL ) { - while ( height-- ) { + int width = info->d_width; + int height = info->d_height; + Uint8 *src = info->s_pixels; + int srcskip = info->s_skip; + Uint8 *dst = info->d_pixels; + int dstskip = info->d_skip; + SDL_PixelFormat *srcfmt = info->src; + const Uint8 *palmap = info->table; + Uint32 ckey = srcfmt->colorkey; + Uint32 rgbmask = ~srcfmt->Amask; + int srcbpp; + Uint32 Pixel; + unsigned sR, sG, sB; + + /* Set up some basic variables */ + srcbpp = srcfmt->BytesPerPixel; + ckey &= rgbmask; + + if (palmap == NULL) { + while (height--) { + /* *INDENT-OFF* */ DUFFS_LOOP( { DISEMBLE_RGB(src, srcbpp, srcfmt, Pixel, @@ -2130,11 +2192,13 @@ static void BlitNto1Key(SDL_BlitInfo *info) src += srcbpp; }, width); - src += srcskip; - dst += dstskip; - } - } else { - while ( height-- ) { + /* *INDENT-ON* */ + src += srcskip; + dst += dstskip; + } + } else { + while (height--) { + /* *INDENT-OFF* */ DUFFS_LOOP( { DISEMBLE_RGB(src, srcbpp, srcfmt, Pixel, @@ -2149,29 +2213,32 @@ static void BlitNto1Key(SDL_BlitInfo *info) src += srcbpp; }, width); - src += srcskip; - dst += dstskip; - } - } + /* *INDENT-ON* */ + src += srcskip; + dst += dstskip; + } + } } -static void Blit2to2Key(SDL_BlitInfo *info) +static void +Blit2to2Key(SDL_BlitInfo * info) { - int width = info->d_width; - int height = info->d_height; - Uint16 *srcp = (Uint16 *)info->s_pixels; - int srcskip = info->s_skip; - Uint16 *dstp = (Uint16 *)info->d_pixels; - int dstskip = info->d_skip; - Uint32 ckey = info->src->colorkey; - Uint32 rgbmask = ~info->src->Amask; - - /* Set up some basic variables */ - srcskip /= 2; - dstskip /= 2; - ckey &= rgbmask; - - while ( height-- ) { + int width = info->d_width; + int height = info->d_height; + Uint16 *srcp = (Uint16 *) info->s_pixels; + int srcskip = info->s_skip; + Uint16 *dstp = (Uint16 *) info->d_pixels; + int dstskip = info->d_skip; + Uint32 ckey = info->src->colorkey; + Uint32 rgbmask = ~info->src->Amask; + + /* Set up some basic variables */ + srcskip /= 2; + dstskip /= 2; + ckey &= rgbmask; + + while (height--) { + /* *INDENT-OFF* */ DUFFS_LOOP( { if ( (*srcp & rgbmask) != ckey ) { @@ -2181,31 +2248,34 @@ static void Blit2to2Key(SDL_BlitInfo *info) srcp++; }, width); - srcp += srcskip; - dstp += dstskip; - } + /* *INDENT-ON* */ + srcp += srcskip; + dstp += dstskip; + } } -static void BlitNtoNKey(SDL_BlitInfo *info) +static void +BlitNtoNKey(SDL_BlitInfo * info) { - int width = info->d_width; - int height = info->d_height; - Uint8 *src = info->s_pixels; - int srcskip = info->s_skip; - Uint8 *dst = info->d_pixels; - int dstskip = info->d_skip; - Uint32 ckey = info->src->colorkey; - SDL_PixelFormat *srcfmt = info->src; - SDL_PixelFormat *dstfmt = info->dst; - int srcbpp = srcfmt->BytesPerPixel; - int dstbpp = dstfmt->BytesPerPixel; - unsigned alpha = dstfmt->Amask ? srcfmt->alpha : 0; - Uint32 rgbmask = ~srcfmt->Amask; - - /* Set up some basic variables */ - ckey &= rgbmask; - - while ( height-- ) { + int width = info->d_width; + int height = info->d_height; + Uint8 *src = info->s_pixels; + int srcskip = info->s_skip; + Uint8 *dst = info->d_pixels; + int dstskip = info->d_skip; + Uint32 ckey = info->src->colorkey; + SDL_PixelFormat *srcfmt = info->src; + SDL_PixelFormat *dstfmt = info->dst; + int srcbpp = srcfmt->BytesPerPixel; + int dstbpp = dstfmt->BytesPerPixel; + unsigned alpha = dstfmt->Amask ? srcfmt->alpha : 0; + Uint32 rgbmask = ~srcfmt->Amask; + + /* Set up some basic variables */ + ckey &= rgbmask; + + while (height--) { + /* *INDENT-OFF* */ DUFFS_LOOP( { Uint32 Pixel; @@ -2222,36 +2292,39 @@ static void BlitNtoNKey(SDL_BlitInfo *info) src += srcbpp; }, width); - src += srcskip; - dst += dstskip; - } + /* *INDENT-ON* */ + src += srcskip; + dst += dstskip; + } } -static void BlitNtoNKeyCopyAlpha(SDL_BlitInfo *info) +static void +BlitNtoNKeyCopyAlpha(SDL_BlitInfo * info) { - int width = info->d_width; - int height = info->d_height; - Uint8 *src = info->s_pixels; - int srcskip = info->s_skip; - Uint8 *dst = info->d_pixels; - int dstskip = info->d_skip; - Uint32 ckey = info->src->colorkey; - SDL_PixelFormat *srcfmt = info->src; - SDL_PixelFormat *dstfmt = info->dst; - Uint32 rgbmask = ~srcfmt->Amask; - - Uint8 srcbpp; - Uint8 dstbpp; - Uint32 Pixel; - unsigned sR, sG, sB, sA; - - /* Set up some basic variables */ - srcbpp = srcfmt->BytesPerPixel; - dstbpp = dstfmt->BytesPerPixel; - ckey &= rgbmask; - - /* FIXME: should map alpha to [0..255] correctly! */ - while ( height-- ) { + int width = info->d_width; + int height = info->d_height; + Uint8 *src = info->s_pixels; + int srcskip = info->s_skip; + Uint8 *dst = info->d_pixels; + int dstskip = info->d_skip; + Uint32 ckey = info->src->colorkey; + SDL_PixelFormat *srcfmt = info->src; + SDL_PixelFormat *dstfmt = info->dst; + Uint32 rgbmask = ~srcfmt->Amask; + + Uint8 srcbpp; + Uint8 dstbpp; + Uint32 Pixel; + unsigned sR, sG, sB, sA; + + /* Set up some basic variables */ + srcbpp = srcfmt->BytesPerPixel; + dstbpp = dstfmt->BytesPerPixel; + ckey &= rgbmask; + + /* FIXME: should map alpha to [0..255] correctly! */ + while (height--) { + /* *INDENT-OFF* */ DUFFS_LOOP( { DISEMBLE_RGBA(src, srcbpp, srcfmt, Pixel, @@ -2264,227 +2337,261 @@ static void BlitNtoNKeyCopyAlpha(SDL_BlitInfo *info) src += srcbpp; }, width); - src += srcskip; - dst += dstskip; - } + /* *INDENT-ON* */ + src += srcskip; + dst += dstskip; + } } /* Normal N to N optimized blitters */ -struct blit_table { - Uint32 srcR, srcG, srcB; - int dstbpp; - Uint32 dstR, dstG, dstB; - Uint32 blit_features; - void *aux_data; - SDL_loblit blitfunc; - enum { NO_ALPHA=1, SET_ALPHA=2, COPY_ALPHA=4 } alpha; +struct blit_table +{ + Uint32 srcR, srcG, srcB; + int dstbpp; + Uint32 dstR, dstG, dstB; + Uint32 blit_features; + void *aux_data; + SDL_loblit blitfunc; + enum + { NO_ALPHA = 1, SET_ALPHA = 2, COPY_ALPHA = 4 } alpha; }; static const struct blit_table normal_blit_1[] = { - /* Default for 8-bit RGB source, an invalid combination */ - { 0,0,0, 0, 0,0,0, 0, NULL, NULL }, + /* Default for 8-bit RGB source, an invalid combination */ + {0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL}, }; static const struct blit_table normal_blit_2[] = { #if SDL_HERMES_BLITTERS - { 0x0000F800,0x000007E0,0x0000001F, 2, 0x0000001F,0x000007E0,0x0000F800, - 0, ConvertX86p16_16BGR565, ConvertX86, NO_ALPHA }, - { 0x0000F800,0x000007E0,0x0000001F, 2, 0x00007C00,0x000003E0,0x0000001F, - 0, ConvertX86p16_16RGB555, ConvertX86, NO_ALPHA }, - { 0x0000F800,0x000007E0,0x0000001F, 2, 0x0000001F,0x000003E0,0x00007C00, - 0, ConvertX86p16_16BGR555, ConvertX86, NO_ALPHA }, + {0x0000F800, 0x000007E0, 0x0000001F, 2, 0x0000001F, 0x000007E0, + 0x0000F800, + 0, ConvertX86p16_16BGR565, ConvertX86, NO_ALPHA}, + {0x0000F800, 0x000007E0, 0x0000001F, 2, 0x00007C00, 0x000003E0, + 0x0000001F, + 0, ConvertX86p16_16RGB555, ConvertX86, NO_ALPHA}, + {0x0000F800, 0x000007E0, 0x0000001F, 2, 0x0000001F, 0x000003E0, + 0x00007C00, + 0, ConvertX86p16_16BGR555, ConvertX86, NO_ALPHA}, #elif SDL_ALTIVEC_BLITTERS /* has-altivec */ - { 0x0000F800,0x000007E0,0x0000001F, 4, 0x00000000,0x00000000,0x00000000, - 2, NULL, Blit_RGB565_32Altivec, NO_ALPHA | COPY_ALPHA | SET_ALPHA }, - { 0x00007C00,0x000003E0,0x0000001F, 4, 0x00000000,0x00000000,0x00000000, - 2, NULL, Blit_RGB555_32Altivec, NO_ALPHA | COPY_ALPHA | SET_ALPHA }, + {0x0000F800, 0x000007E0, 0x0000001F, 4, 0x00000000, 0x00000000, + 0x00000000, + 2, NULL, Blit_RGB565_32Altivec, NO_ALPHA | COPY_ALPHA | SET_ALPHA}, + {0x00007C00, 0x000003E0, 0x0000001F, 4, 0x00000000, 0x00000000, + 0x00000000, + 2, NULL, Blit_RGB555_32Altivec, NO_ALPHA | COPY_ALPHA | SET_ALPHA}, #endif - { 0x0000F800,0x000007E0,0x0000001F, 4, 0x00FF0000,0x0000FF00,0x000000FF, - 0, NULL, Blit_RGB565_ARGB8888, SET_ALPHA }, - { 0x0000F800,0x000007E0,0x0000001F, 4, 0x000000FF,0x0000FF00,0x00FF0000, - 0, NULL, Blit_RGB565_ABGR8888, SET_ALPHA }, - { 0x0000F800,0x000007E0,0x0000001F, 4, 0xFF000000,0x00FF0000,0x0000FF00, - 0, NULL, Blit_RGB565_RGBA8888, SET_ALPHA }, - { 0x0000F800,0x000007E0,0x0000001F, 4, 0x0000FF00,0x00FF0000,0xFF000000, - 0, NULL, Blit_RGB565_BGRA8888, SET_ALPHA }, + {0x0000F800, 0x000007E0, 0x0000001F, 4, 0x00FF0000, 0x0000FF00, + 0x000000FF, + 0, NULL, Blit_RGB565_ARGB8888, SET_ALPHA}, + {0x0000F800, 0x000007E0, 0x0000001F, 4, 0x000000FF, 0x0000FF00, + 0x00FF0000, + 0, NULL, Blit_RGB565_ABGR8888, SET_ALPHA}, + {0x0000F800, 0x000007E0, 0x0000001F, 4, 0xFF000000, 0x00FF0000, + 0x0000FF00, + 0, NULL, Blit_RGB565_RGBA8888, SET_ALPHA}, + {0x0000F800, 0x000007E0, 0x0000001F, 4, 0x0000FF00, 0x00FF0000, + 0xFF000000, + 0, NULL, Blit_RGB565_BGRA8888, SET_ALPHA}, /* Default for 16-bit RGB source, used if no other blitter matches */ - { 0,0,0, 0, 0,0,0, 0, NULL, BlitNtoN, 0 } + {0, 0, 0, 0, 0, 0, 0, 0, NULL, BlitNtoN, 0} }; static const struct blit_table normal_blit_3[] = { - /* Default for 24-bit RGB source, never optimized */ - { 0,0,0, 0, 0,0,0, 0, NULL, BlitNtoN, 0 } + /* Default for 24-bit RGB source, never optimized */ + {0, 0, 0, 0, 0, 0, 0, 0, NULL, BlitNtoN, 0} }; static const struct blit_table normal_blit_4[] = { #if SDL_HERMES_BLITTERS - { 0x00FF0000,0x0000FF00,0x000000FF, 2, 0x0000F800,0x000007E0,0x0000001F, - 1, ConvertMMXpII32_16RGB565, ConvertMMX, NO_ALPHA }, - { 0x00FF0000,0x0000FF00,0x000000FF, 2, 0x0000F800,0x000007E0,0x0000001F, - 0, ConvertX86p32_16RGB565, ConvertX86, NO_ALPHA }, - { 0x00FF0000,0x0000FF00,0x000000FF, 2, 0x0000001F,0x000007E0,0x0000F800, - 1, ConvertMMXpII32_16BGR565, ConvertMMX, NO_ALPHA }, - { 0x00FF0000,0x0000FF00,0x000000FF, 2, 0x0000001F,0x000007E0,0x0000F800, - 0, ConvertX86p32_16BGR565, ConvertX86, NO_ALPHA }, - { 0x00FF0000,0x0000FF00,0x000000FF, 2, 0x00007C00,0x000003E0,0x0000001F, - 1, ConvertMMXpII32_16RGB555, ConvertMMX, NO_ALPHA }, - { 0x00FF0000,0x0000FF00,0x000000FF, 2, 0x00007C00,0x000003E0,0x0000001F, - 0, ConvertX86p32_16RGB555, ConvertX86, NO_ALPHA }, - { 0x00FF0000,0x0000FF00,0x000000FF, 2, 0x0000001F,0x000003E0,0x00007C00, - 1, ConvertMMXpII32_16BGR555, ConvertMMX, NO_ALPHA }, - { 0x00FF0000,0x0000FF00,0x000000FF, 2, 0x0000001F,0x000003E0,0x00007C00, - 0, ConvertX86p32_16BGR555, ConvertX86, NO_ALPHA }, - { 0x00FF0000,0x0000FF00,0x000000FF, 3, 0x00FF0000,0x0000FF00,0x000000FF, - 0, ConvertX86p32_24RGB888, ConvertX86, NO_ALPHA }, - { 0x00FF0000,0x0000FF00,0x000000FF, 3, 0x000000FF,0x0000FF00,0x00FF0000, - 0, ConvertX86p32_24BGR888, ConvertX86, NO_ALPHA }, - { 0x00FF0000,0x0000FF00,0x000000FF, 4, 0x000000FF,0x0000FF00,0x00FF0000, - 0, ConvertX86p32_32BGR888, ConvertX86, NO_ALPHA }, - { 0x00FF0000,0x0000FF00,0x000000FF, 4, 0xFF000000,0x00FF0000,0x0000FF00, - 0, ConvertX86p32_32RGBA888, ConvertX86, NO_ALPHA }, - { 0x00FF0000,0x0000FF00,0x000000FF, 4, 0x0000FF00,0x00FF0000,0xFF000000, - 0, ConvertX86p32_32BGRA888, ConvertX86, NO_ALPHA }, + {0x00FF0000, 0x0000FF00, 0x000000FF, 2, 0x0000F800, 0x000007E0, + 0x0000001F, + 1, ConvertMMXpII32_16RGB565, ConvertMMX, NO_ALPHA}, + {0x00FF0000, 0x0000FF00, 0x000000FF, 2, 0x0000F800, 0x000007E0, + 0x0000001F, + 0, ConvertX86p32_16RGB565, ConvertX86, NO_ALPHA}, + {0x00FF0000, 0x0000FF00, 0x000000FF, 2, 0x0000001F, 0x000007E0, + 0x0000F800, + 1, ConvertMMXpII32_16BGR565, ConvertMMX, NO_ALPHA}, + {0x00FF0000, 0x0000FF00, 0x000000FF, 2, 0x0000001F, 0x000007E0, + 0x0000F800, + 0, ConvertX86p32_16BGR565, ConvertX86, NO_ALPHA}, + {0x00FF0000, 0x0000FF00, 0x000000FF, 2, 0x00007C00, 0x000003E0, + 0x0000001F, + 1, ConvertMMXpII32_16RGB555, ConvertMMX, NO_ALPHA}, + {0x00FF0000, 0x0000FF00, 0x000000FF, 2, 0x00007C00, 0x000003E0, + 0x0000001F, + 0, ConvertX86p32_16RGB555, ConvertX86, NO_ALPHA}, + {0x00FF0000, 0x0000FF00, 0x000000FF, 2, 0x0000001F, 0x000003E0, + 0x00007C00, + 1, ConvertMMXpII32_16BGR555, ConvertMMX, NO_ALPHA}, + {0x00FF0000, 0x0000FF00, 0x000000FF, 2, 0x0000001F, 0x000003E0, + 0x00007C00, + 0, ConvertX86p32_16BGR555, ConvertX86, NO_ALPHA}, + {0x00FF0000, 0x0000FF00, 0x000000FF, 3, 0x00FF0000, 0x0000FF00, + 0x000000FF, + 0, ConvertX86p32_24RGB888, ConvertX86, NO_ALPHA}, + {0x00FF0000, 0x0000FF00, 0x000000FF, 3, 0x000000FF, 0x0000FF00, + 0x00FF0000, + 0, ConvertX86p32_24BGR888, ConvertX86, NO_ALPHA}, + {0x00FF0000, 0x0000FF00, 0x000000FF, 4, 0x000000FF, 0x0000FF00, + 0x00FF0000, + 0, ConvertX86p32_32BGR888, ConvertX86, NO_ALPHA}, + {0x00FF0000, 0x0000FF00, 0x000000FF, 4, 0xFF000000, 0x00FF0000, + 0x0000FF00, + 0, ConvertX86p32_32RGBA888, ConvertX86, NO_ALPHA}, + {0x00FF0000, 0x0000FF00, 0x000000FF, 4, 0x0000FF00, 0x00FF0000, + 0xFF000000, + 0, ConvertX86p32_32BGRA888, ConvertX86, NO_ALPHA}, #else #if SDL_ALTIVEC_BLITTERS /* has-altivec | dont-use-prefetch */ - { 0x00000000,0x00000000,0x00000000, 4, 0x00000000,0x00000000,0x00000000, - 6, NULL, ConvertAltivec32to32_noprefetch, NO_ALPHA | COPY_ALPHA | SET_ALPHA }, + {0x00000000, 0x00000000, 0x00000000, 4, 0x00000000, 0x00000000, + 0x00000000, + 6, NULL, ConvertAltivec32to32_noprefetch, + NO_ALPHA | COPY_ALPHA | SET_ALPHA}, /* has-altivec */ - { 0x00000000,0x00000000,0x00000000, 4, 0x00000000,0x00000000,0x00000000, - 2, NULL, ConvertAltivec32to32_prefetch, NO_ALPHA | COPY_ALPHA | SET_ALPHA }, + {0x00000000, 0x00000000, 0x00000000, 4, 0x00000000, 0x00000000, + 0x00000000, + 2, NULL, ConvertAltivec32to32_prefetch, + NO_ALPHA | COPY_ALPHA | SET_ALPHA}, /* has-altivec */ - { 0x00000000,0x00000000,0x00000000, 2, 0x0000F800,0x000007E0,0x0000001F, - 2, NULL, Blit_RGB888_RGB565Altivec, NO_ALPHA }, + {0x00000000, 0x00000000, 0x00000000, 2, 0x0000F800, 0x000007E0, + 0x0000001F, + 2, NULL, Blit_RGB888_RGB565Altivec, NO_ALPHA}, #endif - { 0x00FF0000,0x0000FF00,0x000000FF, 2, 0x0000F800,0x000007E0,0x0000001F, - 0, NULL, Blit_RGB888_RGB565, NO_ALPHA }, - { 0x00FF0000,0x0000FF00,0x000000FF, 2, 0x00007C00,0x000003E0,0x0000001F, - 0, NULL, Blit_RGB888_RGB555, NO_ALPHA }, + {0x00FF0000, 0x0000FF00, 0x000000FF, 2, 0x0000F800, 0x000007E0, + 0x0000001F, + 0, NULL, Blit_RGB888_RGB565, NO_ALPHA}, + {0x00FF0000, 0x0000FF00, 0x000000FF, 2, 0x00007C00, 0x000003E0, + 0x0000001F, + 0, NULL, Blit_RGB888_RGB555, NO_ALPHA}, #endif - /* Default for 32-bit RGB source, used if no other blitter matches */ - { 0,0,0, 0, 0,0,0, 0, NULL, BlitNtoN, 0 } + /* Default for 32-bit RGB source, used if no other blitter matches */ + {0, 0, 0, 0, 0, 0, 0, 0, NULL, BlitNtoN, 0} }; static const struct blit_table *normal_blit[] = { - normal_blit_1, normal_blit_2, normal_blit_3, normal_blit_4 + normal_blit_1, normal_blit_2, normal_blit_3, normal_blit_4 }; /* Mask matches table, or table entry is zero */ #define MASKOK(x, y) (((x) == (y)) || ((y) == 0x00000000)) -SDL_loblit SDL_CalculateBlitN(SDL_Surface *surface, int blit_index) +SDL_loblit +SDL_CalculateBlitN(SDL_Surface * surface, int blit_index) { - struct private_swaccel *sdata; - SDL_PixelFormat *srcfmt; - SDL_PixelFormat *dstfmt; - const struct blit_table *table; - int which; - SDL_loblit blitfun; - - /* Set up data for choosing the blit */ - sdata = surface->map->sw_data; - srcfmt = surface->format; - dstfmt = surface->map->dst->format; - - if ( blit_index & 2 ) { - /* alpha or alpha+colorkey */ - return SDL_CalculateAlphaBlit(surface, blit_index); - } - - /* We don't support destinations less than 8-bits */ - if ( dstfmt->BitsPerPixel < 8 ) { - return(NULL); - } - - if(blit_index == 1) { - /* colorkey blit: Here we don't have too many options, mostly - because RLE is the preferred fast way to deal with this. - If a particular case turns out to be useful we'll add it. */ - - if(srcfmt->BytesPerPixel == 2 - && surface->map->identity) - return Blit2to2Key; - else if(dstfmt->BytesPerPixel == 1) - return BlitNto1Key; - else { + struct private_swaccel *sdata; + SDL_PixelFormat *srcfmt; + SDL_PixelFormat *dstfmt; + const struct blit_table *table; + int which; + SDL_loblit blitfun; + + /* Set up data for choosing the blit */ + sdata = surface->map->sw_data; + srcfmt = surface->format; + dstfmt = surface->map->dst->format; + + if (blit_index & 2) { + /* alpha or alpha+colorkey */ + return SDL_CalculateAlphaBlit(surface, blit_index); + } + + /* We don't support destinations less than 8-bits */ + if (dstfmt->BitsPerPixel < 8) { + return (NULL); + } + + if (blit_index == 1) { + /* colorkey blit: Here we don't have too many options, mostly + because RLE is the preferred fast way to deal with this. + If a particular case turns out to be useful we'll add it. */ + + if (srcfmt->BytesPerPixel == 2 && surface->map->identity) + return Blit2to2Key; + else if (dstfmt->BytesPerPixel == 1) + return BlitNto1Key; + else { #if SDL_ALTIVEC_BLITTERS - if((srcfmt->BytesPerPixel == 4) && (dstfmt->BytesPerPixel == 4) && SDL_HasAltiVec()) { - return Blit32to32KeyAltivec; - } else + if ((srcfmt->BytesPerPixel == 4) && (dstfmt->BytesPerPixel == 4) + && SDL_HasAltiVec()) { + return Blit32to32KeyAltivec; + } else #endif - if(srcfmt->Amask && dstfmt->Amask) - return BlitNtoNKeyCopyAlpha; - else - return BlitNtoNKey; - } - } - - blitfun = NULL; - if ( dstfmt->BitsPerPixel == 8 ) { - /* We assume 8-bit destinations are palettized */ - if ( (srcfmt->BytesPerPixel == 4) && - (srcfmt->Rmask == 0x00FF0000) && - (srcfmt->Gmask == 0x0000FF00) && - (srcfmt->Bmask == 0x000000FF) ) { - if ( surface->map->table ) { - blitfun = Blit_RGB888_index8_map; - } else { + if (srcfmt->Amask && dstfmt->Amask) + return BlitNtoNKeyCopyAlpha; + else + return BlitNtoNKey; + } + } + + blitfun = NULL; + if (dstfmt->BitsPerPixel == 8) { + /* We assume 8-bit destinations are palettized */ + if ((srcfmt->BytesPerPixel == 4) && + (srcfmt->Rmask == 0x00FF0000) && + (srcfmt->Gmask == 0x0000FF00) && (srcfmt->Bmask == 0x000000FF)) { + if (surface->map->table) { + blitfun = Blit_RGB888_index8_map; + } else { #if SDL_HERMES_BLITTERS - sdata->aux_data = ConvertX86p32_8RGB332; - blitfun = ConvertX86; + sdata->aux_data = ConvertX86p32_8RGB332; + blitfun = ConvertX86; #else - blitfun = Blit_RGB888_index8; + blitfun = Blit_RGB888_index8; #endif - } - } else { - blitfun = BlitNto1; - } - } else { - /* Now the meat, choose the blitter we want */ - int a_need = NO_ALPHA; - if(dstfmt->Amask) - a_need = srcfmt->Amask ? COPY_ALPHA : SET_ALPHA; - table = normal_blit[srcfmt->BytesPerPixel-1]; - for ( which=0; table[which].dstbpp; ++which ) { - if ( MASKOK(srcfmt->Rmask, table[which].srcR) && - MASKOK(srcfmt->Gmask, table[which].srcG) && - MASKOK(srcfmt->Bmask, table[which].srcB) && - MASKOK(dstfmt->Rmask, table[which].dstR) && - MASKOK(dstfmt->Gmask, table[which].dstG) && - MASKOK(dstfmt->Bmask, table[which].dstB) && - dstfmt->BytesPerPixel == table[which].dstbpp && - (a_need & table[which].alpha) == a_need && - ((table[which].blit_features & GetBlitFeatures()) == table[which].blit_features) ) - break; - } - sdata->aux_data = table[which].aux_data; - blitfun = table[which].blitfunc; - - if(blitfun == BlitNtoN) { /* default C fallback catch-all. Slow! */ - /* Fastpath C fallback: 32bit RGB<->RGBA blit with matching RGB */ - if ( srcfmt->BytesPerPixel == 4 && dstfmt->BytesPerPixel == 4 && - srcfmt->Rmask == dstfmt->Rmask && - srcfmt->Gmask == dstfmt->Gmask && - srcfmt->Bmask == dstfmt->Bmask ) { - blitfun = Blit4to4MaskAlpha; - } else if ( a_need == COPY_ALPHA ) { - blitfun = BlitNtoNCopyAlpha; - } - } - } + } + } else { + blitfun = BlitNto1; + } + } else { + /* Now the meat, choose the blitter we want */ + int a_need = NO_ALPHA; + if (dstfmt->Amask) + a_need = srcfmt->Amask ? COPY_ALPHA : SET_ALPHA; + table = normal_blit[srcfmt->BytesPerPixel - 1]; + for (which = 0; table[which].dstbpp; ++which) { + if (MASKOK(srcfmt->Rmask, table[which].srcR) && + MASKOK(srcfmt->Gmask, table[which].srcG) && + MASKOK(srcfmt->Bmask, table[which].srcB) && + MASKOK(dstfmt->Rmask, table[which].dstR) && + MASKOK(dstfmt->Gmask, table[which].dstG) && + MASKOK(dstfmt->Bmask, table[which].dstB) && + dstfmt->BytesPerPixel == table[which].dstbpp && + (a_need & table[which].alpha) == a_need && + ((table[which].blit_features & GetBlitFeatures()) == + table[which].blit_features)) + break; + } + sdata->aux_data = table[which].aux_data; + blitfun = table[which].blitfunc; + + if (blitfun == BlitNtoN) { /* default C fallback catch-all. Slow! */ + /* Fastpath C fallback: 32bit RGB<->RGBA blit with matching RGB */ + if (srcfmt->BytesPerPixel == 4 && dstfmt->BytesPerPixel == 4 && + srcfmt->Rmask == dstfmt->Rmask && + srcfmt->Gmask == dstfmt->Gmask && + srcfmt->Bmask == dstfmt->Bmask) { + blitfun = Blit4to4MaskAlpha; + } else if (a_need == COPY_ALPHA) { + blitfun = BlitNtoNCopyAlpha; + } + } + } #ifdef DEBUG_ASM #if SDL_HERMES_BLITTERS - if ( blitfun == ConvertMMX ) - fprintf(stderr, "Using mmx blit\n"); - else - if ( blitfun == ConvertX86 ) - fprintf(stderr, "Using asm blit\n"); - else + if (blitfun == ConvertMMX) + fprintf(stderr, "Using mmx blit\n"); + else if (blitfun == ConvertX86) + fprintf(stderr, "Using asm blit\n"); + else #endif - if ( (blitfun == BlitNtoN) || (blitfun == BlitNto1) ) - fprintf(stderr, "Using C blit\n"); - else - fprintf(stderr, "Using optimized C blit\n"); + if ((blitfun == BlitNtoN) || (blitfun == BlitNto1)) + fprintf(stderr, "Using C blit\n"); + else + fprintf(stderr, "Using optimized C blit\n"); #endif /* DEBUG_ASM */ - return(blitfun); + return (blitfun); } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/SDL_bmp.c b/src/video/SDL_bmp.c index 874cb2799..443f88465 100644 --- a/src/video/SDL_bmp.c +++ b/src/video/SDL_bmp.c @@ -45,476 +45,478 @@ #endif -SDL_Surface * SDL_LoadBMP_RW (SDL_RWops *src, int freesrc) +SDL_Surface * +SDL_LoadBMP_RW(SDL_RWops * src, int freesrc) { - int was_error; - long fp_offset; - int bmpPitch; - int i, pad; - SDL_Surface *surface; - Uint32 Rmask; - Uint32 Gmask; - Uint32 Bmask; - SDL_Palette *palette; - Uint8 *bits; - int ExpandBMP; - - /* The Win32 BMP file header (14 bytes) */ - char magic[2]; - Uint32 bfSize; - Uint16 bfReserved1; - Uint16 bfReserved2; - Uint32 bfOffBits; - - /* The Win32 BITMAPINFOHEADER struct (40 bytes) */ - Uint32 biSize; - Sint32 biWidth; - Sint32 biHeight; - Uint16 biPlanes; - Uint16 biBitCount; - Uint32 biCompression; - Uint32 biSizeImage; - Sint32 biXPelsPerMeter; - Sint32 biYPelsPerMeter; - Uint32 biClrUsed; - Uint32 biClrImportant; - - /* Make sure we are passed a valid data source */ - surface = NULL; - was_error = 0; - if ( src == NULL ) { - was_error = 1; - goto done; - } - - /* Read in the BMP file header */ - fp_offset = SDL_RWtell(src); - SDL_ClearError(); - if ( SDL_RWread(src, magic, 1, 2) != 2 ) { - SDL_Error(SDL_EFREAD); - was_error = 1; - goto done; - } - if ( SDL_strncmp(magic, "BM", 2) != 0 ) { - SDL_SetError("File is not a Windows BMP file"); - was_error = 1; - goto done; - } - bfSize = SDL_ReadLE32(src); - bfReserved1 = SDL_ReadLE16(src); - bfReserved2 = SDL_ReadLE16(src); - bfOffBits = SDL_ReadLE32(src); - - /* Read the Win32 BITMAPINFOHEADER */ - biSize = SDL_ReadLE32(src); - if ( biSize == 12 ) { - biWidth = (Uint32)SDL_ReadLE16(src); - biHeight = (Uint32)SDL_ReadLE16(src); - biPlanes = SDL_ReadLE16(src); - biBitCount = SDL_ReadLE16(src); - biCompression = BI_RGB; - biSizeImage = 0; - biXPelsPerMeter = 0; - biYPelsPerMeter = 0; - biClrUsed = 0; - biClrImportant = 0; - } else { - biWidth = SDL_ReadLE32(src); - biHeight = SDL_ReadLE32(src); - biPlanes = SDL_ReadLE16(src); - biBitCount = SDL_ReadLE16(src); - biCompression = SDL_ReadLE32(src); - biSizeImage = SDL_ReadLE32(src); - biXPelsPerMeter = SDL_ReadLE32(src); - biYPelsPerMeter = SDL_ReadLE32(src); - biClrUsed = SDL_ReadLE32(src); - biClrImportant = SDL_ReadLE32(src); - } - - /* Check for read error */ - if ( SDL_strcmp(SDL_GetError(), "") != 0 ) { - was_error = 1; - goto done; - } - - /* Expand 1 and 4 bit bitmaps to 8 bits per pixel */ - switch (biBitCount) { - case 1: - case 4: - ExpandBMP = biBitCount; - biBitCount = 8; - break; - default: - ExpandBMP = 0; - break; - } - - /* We don't support any BMP compression right now */ - Rmask = Gmask = Bmask = 0; - switch (biCompression) { - case BI_RGB: - /* If there are no masks, use the defaults */ - if ( bfOffBits == (14+biSize) ) { - /* Default values for the BMP format */ - switch (biBitCount) { - case 15: - case 16: - Rmask = 0x7C00; - Gmask = 0x03E0; - Bmask = 0x001F; - break; - case 24: + int was_error; + long fp_offset; + int bmpPitch; + int i, pad; + SDL_Surface *surface; + Uint32 Rmask; + Uint32 Gmask; + Uint32 Bmask; + SDL_Palette *palette; + Uint8 *bits; + int ExpandBMP; + + /* The Win32 BMP file header (14 bytes) */ + char magic[2]; + Uint32 bfSize; + Uint16 bfReserved1; + Uint16 bfReserved2; + Uint32 bfOffBits; + + /* The Win32 BITMAPINFOHEADER struct (40 bytes) */ + Uint32 biSize; + Sint32 biWidth; + Sint32 biHeight; + Uint16 biPlanes; + Uint16 biBitCount; + Uint32 biCompression; + Uint32 biSizeImage; + Sint32 biXPelsPerMeter; + Sint32 biYPelsPerMeter; + Uint32 biClrUsed; + Uint32 biClrImportant; + + /* Make sure we are passed a valid data source */ + surface = NULL; + was_error = 0; + if (src == NULL) { + was_error = 1; + goto done; + } + + /* Read in the BMP file header */ + fp_offset = SDL_RWtell(src); + SDL_ClearError(); + if (SDL_RWread(src, magic, 1, 2) != 2) { + SDL_Error(SDL_EFREAD); + was_error = 1; + goto done; + } + if (SDL_strncmp(magic, "BM", 2) != 0) { + SDL_SetError("File is not a Windows BMP file"); + was_error = 1; + goto done; + } + bfSize = SDL_ReadLE32(src); + bfReserved1 = SDL_ReadLE16(src); + bfReserved2 = SDL_ReadLE16(src); + bfOffBits = SDL_ReadLE32(src); + + /* Read the Win32 BITMAPINFOHEADER */ + biSize = SDL_ReadLE32(src); + if (biSize == 12) { + biWidth = (Uint32) SDL_ReadLE16(src); + biHeight = (Uint32) SDL_ReadLE16(src); + biPlanes = SDL_ReadLE16(src); + biBitCount = SDL_ReadLE16(src); + biCompression = BI_RGB; + biSizeImage = 0; + biXPelsPerMeter = 0; + biYPelsPerMeter = 0; + biClrUsed = 0; + biClrImportant = 0; + } else { + biWidth = SDL_ReadLE32(src); + biHeight = SDL_ReadLE32(src); + biPlanes = SDL_ReadLE16(src); + biBitCount = SDL_ReadLE16(src); + biCompression = SDL_ReadLE32(src); + biSizeImage = SDL_ReadLE32(src); + biXPelsPerMeter = SDL_ReadLE32(src); + biYPelsPerMeter = SDL_ReadLE32(src); + biClrUsed = SDL_ReadLE32(src); + biClrImportant = SDL_ReadLE32(src); + } + + /* Check for read error */ + if (SDL_strcmp(SDL_GetError(), "") != 0) { + was_error = 1; + goto done; + } + + /* Expand 1 and 4 bit bitmaps to 8 bits per pixel */ + switch (biBitCount) { + case 1: + case 4: + ExpandBMP = biBitCount; + biBitCount = 8; + break; + default: + ExpandBMP = 0; + break; + } + + /* We don't support any BMP compression right now */ + Rmask = Gmask = Bmask = 0; + switch (biCompression) { + case BI_RGB: + /* If there are no masks, use the defaults */ + if (bfOffBits == (14 + biSize)) { + /* Default values for the BMP format */ + switch (biBitCount) { + case 15: + case 16: + Rmask = 0x7C00; + Gmask = 0x03E0; + Bmask = 0x001F; + break; + case 24: #if SDL_BYTEORDER == SDL_BIG_ENDIAN - Rmask = 0x000000FF; - Gmask = 0x0000FF00; - Bmask = 0x00FF0000; - break; + Rmask = 0x000000FF; + Gmask = 0x0000FF00; + Bmask = 0x00FF0000; + break; #endif - case 32: - Rmask = 0x00FF0000; - Gmask = 0x0000FF00; - Bmask = 0x000000FF; - break; - default: - break; - } - break; - } - /* Fall through -- read the RGB masks */ - - case BI_BITFIELDS: - switch (biBitCount) { - case 15: - case 16: - case 32: - Rmask = SDL_ReadLE32(src); - Gmask = SDL_ReadLE32(src); - Bmask = SDL_ReadLE32(src); - break; - default: - break; - } - break; - default: - SDL_SetError("Compressed BMP files not supported"); - was_error = 1; - goto done; - } - - /* Create a compatible surface, note that the colors are RGB ordered */ - surface = SDL_CreateRGBSurface(SDL_SWSURFACE, - biWidth, biHeight, biBitCount, Rmask, Gmask, Bmask, 0); - if ( surface == NULL ) { - was_error = 1; - goto done; - } - - /* Load the palette, if any */ - palette = (surface->format)->palette; - if ( palette ) { - if ( biClrUsed == 0 ) { - biClrUsed = 1 << biBitCount; - } - if ( biSize == 12 ) { - for ( i = 0; i < (int)biClrUsed; ++i ) { - SDL_RWread(src, &palette->colors[i].b, 1, 1); - SDL_RWread(src, &palette->colors[i].g, 1, 1); - SDL_RWread(src, &palette->colors[i].r, 1, 1); - palette->colors[i].unused = 0; - } - } else { - for ( i = 0; i < (int)biClrUsed; ++i ) { - SDL_RWread(src, &palette->colors[i].b, 1, 1); - SDL_RWread(src, &palette->colors[i].g, 1, 1); - SDL_RWread(src, &palette->colors[i].r, 1, 1); - SDL_RWread(src, &palette->colors[i].unused, 1, 1); - } - } - palette->ncolors = biClrUsed; - } - - /* Read the surface pixels. Note that the bmp image is upside down */ - if ( SDL_RWseek(src, fp_offset+bfOffBits, RW_SEEK_SET) < 0 ) { - SDL_Error(SDL_EFSEEK); - was_error = 1; - goto done; - } - bits = (Uint8 *)surface->pixels+(surface->h*surface->pitch); - switch (ExpandBMP) { - case 1: - bmpPitch = (biWidth + 7) >> 3; - pad = (((bmpPitch)%4) ? (4-((bmpPitch)%4)) : 0); - break; - case 4: - bmpPitch = (biWidth + 1) >> 1; - pad = (((bmpPitch)%4) ? (4-((bmpPitch)%4)) : 0); - break; - default: - pad = ((surface->pitch%4) ? - (4-(surface->pitch%4)) : 0); - break; - } - while ( bits > (Uint8 *)surface->pixels ) { - bits -= surface->pitch; - switch (ExpandBMP) { - case 1: - case 4: { - Uint8 pixel = 0; - int shift = (8-ExpandBMP); - for ( i=0; iw; ++i ) { - if ( i%(8/ExpandBMP) == 0 ) { - if ( !SDL_RWread(src, &pixel, 1, 1) ) { - SDL_SetError( - "Error reading from BMP"); - was_error = 1; - goto done; - } - } - *(bits+i) = (pixel>>shift); - pixel <<= ExpandBMP; - } } - break; - - default: - if ( SDL_RWread(src, bits, 1, surface->pitch) - != surface->pitch ) { - SDL_Error(SDL_EFREAD); - was_error = 1; - goto done; - } + case 32: + Rmask = 0x00FF0000; + Gmask = 0x0000FF00; + Bmask = 0x000000FF; + break; + default: + break; + } + break; + } + /* Fall through -- read the RGB masks */ + + case BI_BITFIELDS: + switch (biBitCount) { + case 15: + case 16: + case 32: + Rmask = SDL_ReadLE32(src); + Gmask = SDL_ReadLE32(src); + Bmask = SDL_ReadLE32(src); + break; + default: + break; + } + break; + default: + SDL_SetError("Compressed BMP files not supported"); + was_error = 1; + goto done; + } + + /* Create a compatible surface, note that the colors are RGB ordered */ + surface = + SDL_CreateRGBSurface(0, biWidth, biHeight, biBitCount, Rmask, Gmask, + Bmask, 0); + if (surface == NULL) { + was_error = 1; + goto done; + } + + /* Load the palette, if any */ + palette = (surface->format)->palette; + if (palette) { + if (biClrUsed == 0) { + biClrUsed = 1 << biBitCount; + } + if (biSize == 12) { + for (i = 0; i < (int) biClrUsed; ++i) { + SDL_RWread(src, &palette->colors[i].b, 1, 1); + SDL_RWread(src, &palette->colors[i].g, 1, 1); + SDL_RWread(src, &palette->colors[i].r, 1, 1); + palette->colors[i].unused = SDL_ALPHA_OPAQUE; + } + } else { + for (i = 0; i < (int) biClrUsed; ++i) { + SDL_RWread(src, &palette->colors[i].b, 1, 1); + SDL_RWread(src, &palette->colors[i].g, 1, 1); + SDL_RWread(src, &palette->colors[i].r, 1, 1); + SDL_RWread(src, &palette->colors[i].unused, 1, 1); + } + } + } + + /* Read the surface pixels. Note that the bmp image is upside down */ + if (SDL_RWseek(src, fp_offset + bfOffBits, RW_SEEK_SET) < 0) { + SDL_Error(SDL_EFSEEK); + was_error = 1; + goto done; + } + bits = (Uint8 *) surface->pixels + (surface->h * surface->pitch); + switch (ExpandBMP) { + case 1: + bmpPitch = (biWidth + 7) >> 3; + pad = (((bmpPitch) % 4) ? (4 - ((bmpPitch) % 4)) : 0); + break; + case 4: + bmpPitch = (biWidth + 1) >> 1; + pad = (((bmpPitch) % 4) ? (4 - ((bmpPitch) % 4)) : 0); + break; + default: + pad = ((surface->pitch % 4) ? (4 - (surface->pitch % 4)) : 0); + break; + } + while (bits > (Uint8 *) surface->pixels) { + bits -= surface->pitch; + switch (ExpandBMP) { + case 1: + case 4: + { + Uint8 pixel = 0; + int shift = (8 - ExpandBMP); + for (i = 0; i < surface->w; ++i) { + if (i % (8 / ExpandBMP) == 0) { + if (!SDL_RWread(src, &pixel, 1, 1)) { + SDL_SetError("Error reading from BMP"); + was_error = 1; + goto done; + } + } + *(bits + i) = (pixel >> shift); + pixel <<= ExpandBMP; + } + } + break; + + default: + if (SDL_RWread(src, bits, 1, surface->pitch) + != surface->pitch) { + SDL_Error(SDL_EFREAD); + was_error = 1; + goto done; + } #if SDL_BYTEORDER == SDL_BIG_ENDIAN - /* Byte-swap the pixels if needed. Note that the 24bpp - case has already been taken care of above. */ - switch(biBitCount) { - case 15: - case 16: { - Uint16 *pix = (Uint16 *)bits; - for(i = 0; i < surface->w; i++) - pix[i] = SDL_Swap16(pix[i]); - break; - } - - case 32: { - Uint32 *pix = (Uint32 *)bits; - for(i = 0; i < surface->w; i++) - pix[i] = SDL_Swap32(pix[i]); - break; - } - } + /* Byte-swap the pixels if needed. Note that the 24bpp + case has already been taken care of above. */ + switch (biBitCount) { + case 15: + case 16: + { + Uint16 *pix = (Uint16 *) bits; + for (i = 0; i < surface->w; i++) + pix[i] = SDL_Swap16(pix[i]); + break; + } + + case 32: + { + Uint32 *pix = (Uint32 *) bits; + for (i = 0; i < surface->w; i++) + pix[i] = SDL_Swap32(pix[i]); + break; + } + } #endif - break; - } - /* Skip padding bytes, ugh */ - if ( pad ) { - Uint8 padbyte; - for ( i=0; iformat->palette ) { - if ( saveme->format->BitsPerPixel == 8 ) { - surface = saveme; - } else { - SDL_SetError("%d bpp BMP files not supported", - saveme->format->BitsPerPixel); - } - } - else if ( (saveme->format->BitsPerPixel == 24) && + long fp_offset; + int i, pad; + SDL_Surface *surface; + Uint8 *bits; + + /* The Win32 BMP file header (14 bytes) */ + char magic[2] = { 'B', 'M' }; + Uint32 bfSize; + Uint16 bfReserved1; + Uint16 bfReserved2; + Uint32 bfOffBits; + + /* The Win32 BITMAPINFOHEADER struct (40 bytes) */ + Uint32 biSize; + Sint32 biWidth; + Sint32 biHeight; + Uint16 biPlanes; + Uint16 biBitCount; + Uint32 biCompression; + Uint32 biSizeImage; + Sint32 biXPelsPerMeter; + Sint32 biYPelsPerMeter; + Uint32 biClrUsed; + Uint32 biClrImportant; + + /* Make sure we have somewhere to save */ + surface = NULL; + if (dst) { + if (saveme->format->palette) { + if (saveme->format->BitsPerPixel == 8) { + surface = saveme; + } else { + SDL_SetError("%d bpp BMP files not supported", + saveme->format->BitsPerPixel); + } + } else if ((saveme->format->BitsPerPixel == 24) && #if SDL_BYTEORDER == SDL_LIL_ENDIAN - (saveme->format->Rmask == 0x00FF0000) && - (saveme->format->Gmask == 0x0000FF00) && - (saveme->format->Bmask == 0x000000FF) + (saveme->format->Rmask == 0x00FF0000) && + (saveme->format->Gmask == 0x0000FF00) && + (saveme->format->Bmask == 0x000000FF) #else - (saveme->format->Rmask == 0x000000FF) && - (saveme->format->Gmask == 0x0000FF00) && - (saveme->format->Bmask == 0x00FF0000) + (saveme->format->Rmask == 0x000000FF) && + (saveme->format->Gmask == 0x0000FF00) && + (saveme->format->Bmask == 0x00FF0000) #endif - ) { - surface = saveme; - } else { - SDL_Rect bounds; - - /* Convert to 24 bits per pixel */ - surface = SDL_CreateRGBSurface(SDL_SWSURFACE, - saveme->w, saveme->h, 24, + ) { + surface = saveme; + } else { + SDL_Rect bounds; + + /* Convert to 24 bits per pixel */ + surface = SDL_CreateRGBSurface(0, saveme->w, saveme->h, 24, #if SDL_BYTEORDER == SDL_LIL_ENDIAN - 0x00FF0000, 0x0000FF00, 0x000000FF, + 0x00FF0000, 0x0000FF00, 0x000000FF, #else - 0x000000FF, 0x0000FF00, 0x00FF0000, + 0x000000FF, 0x0000FF00, 0x00FF0000, #endif - 0); - if ( surface != NULL ) { - bounds.x = 0; - bounds.y = 0; - bounds.w = saveme->w; - bounds.h = saveme->h; - if ( SDL_LowerBlit(saveme, &bounds, surface, - &bounds) < 0 ) { - SDL_FreeSurface(surface); - SDL_SetError( - "Couldn't convert image to 24 bpp"); - surface = NULL; - } - } - } - } - - if ( surface && (SDL_LockSurface(surface) == 0) ) { - const int bw = surface->w*surface->format->BytesPerPixel; - - /* Set the BMP file header values */ - bfSize = 0; /* We'll write this when we're done */ - bfReserved1 = 0; - bfReserved2 = 0; - bfOffBits = 0; /* We'll write this when we're done */ - - /* Write the BMP file header values */ - fp_offset = SDL_RWtell(dst); - SDL_ClearError(); - SDL_RWwrite(dst, magic, 2, 1); - SDL_WriteLE32(dst, bfSize); - SDL_WriteLE16(dst, bfReserved1); - SDL_WriteLE16(dst, bfReserved2); - SDL_WriteLE32(dst, bfOffBits); - - /* Set the BMP info values */ - biSize = 40; - biWidth = surface->w; - biHeight = surface->h; - biPlanes = 1; - biBitCount = surface->format->BitsPerPixel; - biCompression = BI_RGB; - biSizeImage = surface->h*surface->pitch; - biXPelsPerMeter = 0; - biYPelsPerMeter = 0; - if ( surface->format->palette ) { - biClrUsed = surface->format->palette->ncolors; - } else { - biClrUsed = 0; - } - biClrImportant = 0; - - /* Write the BMP info values */ - SDL_WriteLE32(dst, biSize); - SDL_WriteLE32(dst, biWidth); - SDL_WriteLE32(dst, biHeight); - SDL_WriteLE16(dst, biPlanes); - SDL_WriteLE16(dst, biBitCount); - SDL_WriteLE32(dst, biCompression); - SDL_WriteLE32(dst, biSizeImage); - SDL_WriteLE32(dst, biXPelsPerMeter); - SDL_WriteLE32(dst, biYPelsPerMeter); - SDL_WriteLE32(dst, biClrUsed); - SDL_WriteLE32(dst, biClrImportant); - - /* Write the palette (in BGR color order) */ - if ( surface->format->palette ) { - SDL_Color *colors; - int ncolors; - - colors = surface->format->palette->colors; - ncolors = surface->format->palette->ncolors; - for ( i=0; ipixels+(surface->h*surface->pitch); - pad = ((bw%4) ? (4-(bw%4)) : 0); - while ( bits > (Uint8 *)surface->pixels ) { - bits -= surface->pitch; - if ( SDL_RWwrite(dst, bits, 1, bw) != bw) { - SDL_Error(SDL_EFWRITE); - break; - } - if ( pad ) { - const Uint8 padbyte = 0; - for ( i=0; iw; + bounds.h = saveme->h; + if (SDL_LowerBlit(saveme, &bounds, surface, &bounds) < 0) { + SDL_FreeSurface(surface); + SDL_SetError("Couldn't convert image to 24 bpp"); + surface = NULL; + } + } + } + } + + if (surface && (SDL_LockSurface(surface) == 0)) { + const int bw = surface->w * surface->format->BytesPerPixel; + + /* Set the BMP file header values */ + bfSize = 0; /* We'll write this when we're done */ + bfReserved1 = 0; + bfReserved2 = 0; + bfOffBits = 0; /* We'll write this when we're done */ + + /* Write the BMP file header values */ + fp_offset = SDL_RWtell(dst); + SDL_ClearError(); + SDL_RWwrite(dst, magic, 2, 1); + SDL_WriteLE32(dst, bfSize); + SDL_WriteLE16(dst, bfReserved1); + SDL_WriteLE16(dst, bfReserved2); + SDL_WriteLE32(dst, bfOffBits); + + /* Set the BMP info values */ + biSize = 40; + biWidth = surface->w; + biHeight = surface->h; + biPlanes = 1; + biBitCount = surface->format->BitsPerPixel; + biCompression = BI_RGB; + biSizeImage = surface->h * surface->pitch; + biXPelsPerMeter = 0; + biYPelsPerMeter = 0; + if (surface->format->palette) { + biClrUsed = surface->format->palette->ncolors; + } else { + biClrUsed = 0; + } + biClrImportant = 0; + + /* Write the BMP info values */ + SDL_WriteLE32(dst, biSize); + SDL_WriteLE32(dst, biWidth); + SDL_WriteLE32(dst, biHeight); + SDL_WriteLE16(dst, biPlanes); + SDL_WriteLE16(dst, biBitCount); + SDL_WriteLE32(dst, biCompression); + SDL_WriteLE32(dst, biSizeImage); + SDL_WriteLE32(dst, biXPelsPerMeter); + SDL_WriteLE32(dst, biYPelsPerMeter); + SDL_WriteLE32(dst, biClrUsed); + SDL_WriteLE32(dst, biClrImportant); + + /* Write the palette (in BGR color order) */ + if (surface->format->palette) { + SDL_Color *colors; + int ncolors; + + colors = surface->format->palette->colors; + ncolors = surface->format->palette->ncolors; + for (i = 0; i < ncolors; ++i) { + SDL_RWwrite(dst, &colors[i].b, 1, 1); + SDL_RWwrite(dst, &colors[i].g, 1, 1); + SDL_RWwrite(dst, &colors[i].r, 1, 1); + SDL_RWwrite(dst, &colors[i].unused, 1, 1); + } + } + + /* Write the bitmap offset */ + bfOffBits = SDL_RWtell(dst) - fp_offset; + if (SDL_RWseek(dst, fp_offset + 10, RW_SEEK_SET) < 0) { + SDL_Error(SDL_EFSEEK); + } + SDL_WriteLE32(dst, bfOffBits); + if (SDL_RWseek(dst, fp_offset + bfOffBits, RW_SEEK_SET) < 0) { + SDL_Error(SDL_EFSEEK); + } + + /* Write the bitmap image upside down */ + bits = (Uint8 *) surface->pixels + (surface->h * surface->pitch); + pad = ((bw % 4) ? (4 - (bw % 4)) : 0); + while (bits > (Uint8 *) surface->pixels) { + bits -= surface->pitch; + if (SDL_RWwrite(dst, bits, 1, bw) != bw) { + SDL_Error(SDL_EFWRITE); + break; + } + if (pad) { + const Uint8 padbyte = 0; + for (i = 0; i < pad; ++i) { + SDL_RWwrite(dst, &padbyte, 1, 1); + } + } + } + + /* Write the BMP file size */ + bfSize = SDL_RWtell(dst) - fp_offset; + if (SDL_RWseek(dst, fp_offset + 2, RW_SEEK_SET) < 0) { + SDL_Error(SDL_EFSEEK); + } + SDL_WriteLE32(dst, bfSize); + if (SDL_RWseek(dst, fp_offset + bfSize, RW_SEEK_SET) < 0) { + SDL_Error(SDL_EFSEEK); + } + + /* Close it up.. */ + SDL_UnlockSurface(surface); + if (surface != saveme) { + SDL_FreeSurface(surface); + } + } + + if (freedst && dst) { + SDL_RWclose(dst); + } + return ((SDL_strcmp(SDL_GetError(), "") == 0) ? 0 : -1); } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/SDL_cursor.c b/src/video/SDL_cursor.c deleted file mode 100644 index 723040e0b..000000000 --- a/src/video/SDL_cursor.c +++ /dev/null @@ -1,751 +0,0 @@ -/* - SDL - Simple DirectMedia Layer - Copyright (C) 1997-2006 Sam Lantinga - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - - Sam Lantinga - slouken@libsdl.org -*/ -#include "SDL_config.h" - -/* General cursor handling code for SDL */ - -#include "SDL_mutex.h" -#include "SDL_video.h" -#include "SDL_mouse.h" -#include "SDL_blit.h" -#include "SDL_sysvideo.h" -#include "SDL_cursor_c.h" -#include "SDL_pixels_c.h" -#include "default_cursor.h" -#include "../events/SDL_sysevents.h" -#include "../events/SDL_events_c.h" - -/* These are static for our cursor handling code */ -volatile int SDL_cursorstate = CURSOR_VISIBLE; -SDL_Cursor *SDL_cursor = NULL; -static SDL_Cursor *SDL_defcursor = NULL; -SDL_mutex *SDL_cursorlock = NULL; - -/* Public functions */ -void SDL_CursorQuit(void) -{ - if ( SDL_cursor != NULL ) { - SDL_Cursor *cursor; - - SDL_cursorstate &= ~CURSOR_VISIBLE; - if ( SDL_cursor != SDL_defcursor ) { - SDL_FreeCursor(SDL_cursor); - } - SDL_cursor = NULL; - if ( SDL_defcursor != NULL ) { - cursor = SDL_defcursor; - SDL_defcursor = NULL; - SDL_FreeCursor(cursor); - } - } - if ( SDL_cursorlock != NULL ) { - SDL_DestroyMutex(SDL_cursorlock); - SDL_cursorlock = NULL; - } -} -int SDL_CursorInit(Uint32 multithreaded) -{ - /* We don't have mouse focus, and the cursor isn't drawn yet */ -#ifndef IPOD - SDL_cursorstate = CURSOR_VISIBLE; -#endif - - /* Create the default cursor */ - if ( SDL_defcursor == NULL ) { - SDL_defcursor = SDL_CreateCursor(default_cdata, default_cmask, - DEFAULT_CWIDTH, DEFAULT_CHEIGHT, - DEFAULT_CHOTX, DEFAULT_CHOTY); - SDL_SetCursor(SDL_defcursor); - } - - /* Create a lock if necessary */ - if ( multithreaded ) { - SDL_cursorlock = SDL_CreateMutex(); - } - - /* That's it! */ - return(0); -} - -/* Multi-thread support for cursors */ -#ifndef SDL_LockCursor -void SDL_LockCursor(void) -{ - if ( SDL_cursorlock ) { - SDL_mutexP(SDL_cursorlock); - } -} -#endif -#ifndef SDL_UnlockCursor -void SDL_UnlockCursor(void) -{ - if ( SDL_cursorlock ) { - SDL_mutexV(SDL_cursorlock); - } -} -#endif - -/* Software cursor drawing support */ -SDL_Cursor * SDL_CreateCursor (Uint8 *data, Uint8 *mask, - int w, int h, int hot_x, int hot_y) -{ - SDL_VideoDevice *video = current_video; - int savelen; - int i; - SDL_Cursor *cursor; - - /* Make sure the width is a multiple of 8 */ - w = ((w+7)&~7); - - /* Sanity check the hot spot */ - if ( (hot_x < 0) || (hot_y < 0) || (hot_x >= w) || (hot_y >= h) ) { - SDL_SetError("Cursor hot spot doesn't lie within cursor"); - return(NULL); - } - - /* Allocate memory for the cursor */ - cursor = (SDL_Cursor *)SDL_malloc(sizeof *cursor); - if ( cursor == NULL ) { - SDL_OutOfMemory(); - return(NULL); - } - savelen = (w*4)*h; - cursor->area.x = 0; - cursor->area.y = 0; - cursor->area.w = w; - cursor->area.h = h; - cursor->hot_x = hot_x; - cursor->hot_y = hot_y; - cursor->data = (Uint8 *)SDL_malloc((w/8)*h*2); - cursor->mask = cursor->data+((w/8)*h); - cursor->save[0] = (Uint8 *)SDL_malloc(savelen*2); - cursor->save[1] = cursor->save[0] + savelen; - cursor->wm_cursor = NULL; - if ( ! cursor->data || ! cursor->save[0] ) { - SDL_FreeCursor(cursor); - SDL_OutOfMemory(); - return(NULL); - } - for ( i=((w/8)*h)-1; i>=0; --i ) { - cursor->data[i] = data[i]; - cursor->mask[i] = mask[i] | data[i]; - } - SDL_memset(cursor->save[0], 0, savelen*2); - - /* If the window manager gives us a good cursor, we're done! */ - if ( video->CreateWMCursor ) { - cursor->wm_cursor = video->CreateWMCursor(video, data, mask, - w, h, hot_x, hot_y); - } else { - cursor->wm_cursor = NULL; - } - return(cursor); -} - -/* SDL_SetCursor(NULL) can be used to force the cursor redraw, - if this is desired for any reason. This is used when setting - the video mode and when the SDL window gains the mouse focus. - */ -void SDL_SetCursor (SDL_Cursor *cursor) -{ - SDL_VideoDevice *video = current_video; - SDL_VideoDevice *this = current_video; - - /* Make sure that the video subsystem has been initialized */ - if ( ! video ) { - return; - } - - /* Prevent the event thread from moving the mouse */ - SDL_LockCursor(); - - /* Set the new cursor */ - if ( cursor && (cursor != SDL_cursor) ) { - /* Erase the current mouse position */ - if ( SHOULD_DRAWCURSOR(SDL_cursorstate) ) { - SDL_EraseCursor(SDL_VideoSurface); - } else if ( video->MoveWMCursor ) { - /* If the video driver is moving the cursor directly, - it needs to hide the old cursor before (possibly) - showing the new one. (But don't erase NULL cursor) - */ - if ( SDL_cursor ) { - video->ShowWMCursor(this, NULL); - } - } - SDL_cursor = cursor; - } - - /* Draw the new mouse cursor */ - if ( SDL_cursor && (SDL_cursorstate&CURSOR_VISIBLE) ) { - /* Use window manager cursor if possible */ - if ( SDL_cursor->wm_cursor && - video->ShowWMCursor(this, SDL_cursor->wm_cursor) ) { - SDL_cursorstate &= ~CURSOR_USINGSW; - } else { - SDL_cursorstate |= CURSOR_USINGSW; - if ( video->ShowWMCursor ) { - video->ShowWMCursor(this, NULL); - } - { int x, y; - SDL_GetMouseState(&x, &y); - SDL_cursor->area.x = (x - SDL_cursor->hot_x); - SDL_cursor->area.y = (y - SDL_cursor->hot_y); - } - SDL_DrawCursor(SDL_VideoSurface); - } - } else { - /* Erase window manager mouse (cursor not visible) */ - if ( SDL_cursor && (SDL_cursorstate & CURSOR_USINGSW) ) { - SDL_EraseCursor(SDL_VideoSurface); - } else { - if ( video ) { - video->ShowWMCursor(this, NULL); - } - } - } - SDL_UnlockCursor(); -} - -SDL_Cursor * SDL_GetCursor (void) -{ - return(SDL_cursor); -} - -void SDL_FreeCursor (SDL_Cursor *cursor) -{ - if ( cursor ) { - if ( cursor == SDL_cursor ) { - SDL_SetCursor(SDL_defcursor); - } - if ( cursor != SDL_defcursor ) { - SDL_VideoDevice *video = current_video; - SDL_VideoDevice *this = current_video; - - if ( cursor->data ) { - SDL_free(cursor->data); - } - if ( cursor->save[0] ) { - SDL_free(cursor->save[0]); - } - if ( video && cursor->wm_cursor ) { - video->FreeWMCursor(this, cursor->wm_cursor); - } - SDL_free(cursor); - } - } -} - -int SDL_ShowCursor (int toggle) -{ - int showing; - - showing = (SDL_cursorstate & CURSOR_VISIBLE); - if ( toggle >= 0 ) { - SDL_LockCursor(); - if ( toggle ) { - SDL_cursorstate |= CURSOR_VISIBLE; - } else { - SDL_cursorstate &= ~CURSOR_VISIBLE; - } - SDL_UnlockCursor(); - if ( (SDL_cursorstate & CURSOR_VISIBLE) != showing ) { - SDL_VideoDevice *video = current_video; - SDL_VideoDevice *this = current_video; - - SDL_SetCursor(NULL); - if ( video && video->CheckMouseMode ) { - video->CheckMouseMode(this); - } - } - } else { - /* Query current state */ ; - } - return(showing ? 1 : 0); -} - -void SDL_WarpMouse (Uint16 x, Uint16 y) -{ - SDL_VideoDevice *video = current_video; - SDL_VideoDevice *this = current_video; - - if ( !video || !SDL_PublicSurface ) { - SDL_SetError("A video mode must be set before warping mouse"); - return; - } - - /* If we have an offset video mode, offset the mouse coordinates */ - if (this->screen->pitch == 0) { - x += this->screen->offset / this->screen->format->BytesPerPixel; - y += this->screen->offset; - } else { - x += (this->screen->offset % this->screen->pitch) / - this->screen->format->BytesPerPixel; - y += (this->screen->offset / this->screen->pitch); - } - - /* This generates a mouse motion event */ - if ( video->WarpWMCursor ) { - video->WarpWMCursor(this, x, y); - } else { - SDL_PrivateMouseMotion(0, 0, x, y); - } -} - -void SDL_MoveCursor(int x, int y) -{ - SDL_VideoDevice *video = current_video; - - /* Erase and update the current mouse position */ - if ( SHOULD_DRAWCURSOR(SDL_cursorstate) ) { - /* Erase and redraw mouse cursor in new position */ - SDL_LockCursor(); - SDL_EraseCursor(SDL_VideoSurface); - SDL_cursor->area.x = (x - SDL_cursor->hot_x); - SDL_cursor->area.y = (y - SDL_cursor->hot_y); - SDL_DrawCursor(SDL_VideoSurface); - SDL_UnlockCursor(); - } else if ( video->MoveWMCursor ) { - video->MoveWMCursor(video, x, y); - } -} - -/* Keep track of the current cursor colors */ -static int palette_changed = 1; -static Uint8 pixels8[2]; - -void SDL_CursorPaletteChanged(void) -{ - palette_changed = 1; -} - -void SDL_MouseRect(SDL_Rect *area) -{ - int clip_diff; - - *area = SDL_cursor->area; - if ( area->x < 0 ) { - area->w += area->x; - area->x = 0; - } - if ( area->y < 0 ) { - area->h += area->y; - area->y = 0; - } - clip_diff = (area->x+area->w)-SDL_VideoSurface->w; - if ( clip_diff > 0 ) { - area->w = area->w < clip_diff ? 0 : area->w-clip_diff; - } - clip_diff = (area->y+area->h)-SDL_VideoSurface->h; - if ( clip_diff > 0 ) { - area->h = area->h < clip_diff ? 0 : area->h-clip_diff; - } -} - -static void SDL_DrawCursorFast(SDL_Surface *screen, SDL_Rect *area) -{ - const Uint32 pixels[2] = { 0xFFFFFFFF, 0x00000000 }; - int i, w, h; - Uint8 *data, datab; - Uint8 *mask, maskb; - - data = SDL_cursor->data + area->y * SDL_cursor->area.w/8; - mask = SDL_cursor->mask + area->y * SDL_cursor->area.w/8; - switch (screen->format->BytesPerPixel) { - - case 1: { - Uint8 *dst; - int dstskip; - - if ( palette_changed ) { - pixels8[0] = (Uint8)SDL_MapRGB(screen->format, 255, 255, 255); - pixels8[1] = (Uint8)SDL_MapRGB(screen->format, 0, 0, 0); - palette_changed = 0; - } - dst = (Uint8 *)screen->pixels + - (SDL_cursor->area.y+area->y)*screen->pitch + - SDL_cursor->area.x; - dstskip = screen->pitch-area->w; - - for ( h=area->h; h; h-- ) { - for ( w=area->w/8; w; w-- ) { - maskb = *mask++; - datab = *data++; - for ( i=0; i<8; ++i ) { - if ( maskb & 0x80 ) { - *dst = pixels8[datab>>7]; - } - maskb <<= 1; - datab <<= 1; - dst++; - } - } - dst += dstskip; - } - } - break; - - case 2: { - Uint16 *dst; - int dstskip; - - dst = (Uint16 *)screen->pixels + - (SDL_cursor->area.y+area->y)*screen->pitch/2 + - SDL_cursor->area.x; - dstskip = (screen->pitch/2)-area->w; - - for ( h=area->h; h; h-- ) { - for ( w=area->w/8; w; w-- ) { - maskb = *mask++; - datab = *data++; - for ( i=0; i<8; ++i ) { - if ( maskb & 0x80 ) { - *dst = (Uint16)pixels[datab>>7]; - } - maskb <<= 1; - datab <<= 1; - dst++; - } - } - dst += dstskip; - } - } - break; - - case 3: { - Uint8 *dst; - int dstskip; - - dst = (Uint8 *)screen->pixels + - (SDL_cursor->area.y+area->y)*screen->pitch + - SDL_cursor->area.x*3; - dstskip = screen->pitch-area->w*3; - - for ( h=area->h; h; h-- ) { - for ( w=area->w/8; w; w-- ) { - maskb = *mask++; - datab = *data++; - for ( i=0; i<8; ++i ) { - if ( maskb & 0x80 ) { - SDL_memset(dst,pixels[datab>>7],3); - } - maskb <<= 1; - datab <<= 1; - dst += 3; - } - } - dst += dstskip; - } - } - break; - - case 4: { - Uint32 *dst; - int dstskip; - - dst = (Uint32 *)screen->pixels + - (SDL_cursor->area.y+area->y)*screen->pitch/4 + - SDL_cursor->area.x; - dstskip = (screen->pitch/4)-area->w; - - for ( h=area->h; h; h-- ) { - for ( w=area->w/8; w; w-- ) { - maskb = *mask++; - datab = *data++; - for ( i=0; i<8; ++i ) { - if ( maskb & 0x80 ) { - *dst = pixels[datab>>7]; - } - maskb <<= 1; - datab <<= 1; - dst++; - } - } - dst += dstskip; - } - } - break; - } -} - -static void SDL_DrawCursorSlow(SDL_Surface *screen, SDL_Rect *area) -{ - const Uint32 pixels[2] = { 0xFFFFFF, 0x000000 }; - int h; - int x, minx, maxx; - Uint8 *data, datab = 0; - Uint8 *mask, maskb = 0; - Uint8 *dst; - int dstbpp, dstskip; - - data = SDL_cursor->data + area->y * SDL_cursor->area.w/8; - mask = SDL_cursor->mask + area->y * SDL_cursor->area.w/8; - dstbpp = screen->format->BytesPerPixel; - dst = (Uint8 *)screen->pixels + - (SDL_cursor->area.y+area->y)*screen->pitch + - SDL_cursor->area.x*dstbpp; - dstskip = screen->pitch-SDL_cursor->area.w*dstbpp; - - minx = area->x; - maxx = area->x+area->w; - if ( screen->format->BytesPerPixel == 1 ) { - if ( palette_changed ) { - pixels8[0] = (Uint8)SDL_MapRGB(screen->format, 255, 255, 255); - pixels8[1] = (Uint8)SDL_MapRGB(screen->format, 0, 0, 0); - palette_changed = 0; - } - for ( h=area->h; h; h-- ) { - for ( x=0; xarea.w; ++x ) { - if ( (x%8) == 0 ) { - maskb = *mask++; - datab = *data++; - } - if ( (x >= minx) && (x < maxx) ) { - if ( maskb & 0x80 ) { - SDL_memset(dst, pixels8[datab>>7], dstbpp); - } - } - maskb <<= 1; - datab <<= 1; - dst += dstbpp; - } - dst += dstskip; - } - } else { - for ( h=area->h; h; h-- ) { - for ( x=0; xarea.w; ++x ) { - if ( (x%8) == 0 ) { - maskb = *mask++; - datab = *data++; - } - if ( (x >= minx) && (x < maxx) ) { - if ( maskb & 0x80 ) { - SDL_memset(dst, pixels[datab>>7], dstbpp); - } - } - maskb <<= 1; - datab <<= 1; - dst += dstbpp; - } - dst += dstskip; - } - } -} - -/* This handles the ugly work of converting the saved cursor background from - the pixel format of the shadow surface to that of the video surface. - This is only necessary when blitting from a shadow surface of a different - pixel format than the video surface, and using a software rendered cursor. -*/ -static void SDL_ConvertCursorSave(SDL_Surface *screen, int w, int h) -{ - SDL_BlitInfo info; - SDL_loblit RunBlit; - - /* Make sure we can steal the blit mapping */ - if ( screen->map->dst != SDL_VideoSurface ) { - return; - } - - /* Set up the blit information */ - info.s_pixels = SDL_cursor->save[1]; - info.s_width = w; - info.s_height = h; - info.s_skip = 0; - info.d_pixels = SDL_cursor->save[0]; - info.d_width = w; - info.d_height = h; - info.d_skip = 0; - info.aux_data = screen->map->sw_data->aux_data; - info.src = screen->format; - info.table = screen->map->table; - info.dst = SDL_VideoSurface->format; - RunBlit = screen->map->sw_data->blit; - - /* Run the actual software blit */ - RunBlit(&info); -} - -void SDL_DrawCursorNoLock(SDL_Surface *screen) -{ - SDL_Rect area; - - /* Get the mouse rectangle, clipped to the screen */ - SDL_MouseRect(&area); - if ( (area.w == 0) || (area.h == 0) ) { - return; - } - - /* Copy mouse background */ - { int w, h, screenbpp; - Uint8 *src, *dst; - - /* Set up the copy pointers */ - screenbpp = screen->format->BytesPerPixel; - if ( (screen == SDL_VideoSurface) || - FORMAT_EQUAL(screen->format, SDL_VideoSurface->format) ) { - dst = SDL_cursor->save[0]; - } else { - dst = SDL_cursor->save[1]; - } - src = (Uint8 *)screen->pixels + area.y * screen->pitch + - area.x * screenbpp; - - /* Perform the copy */ - w = area.w*screenbpp; - h = area.h; - while ( h-- ) { - SDL_memcpy(dst, src, w); - dst += w; - src += screen->pitch; - } - } - - /* Draw the mouse cursor */ - area.x -= SDL_cursor->area.x; - area.y -= SDL_cursor->area.y; - if ( (area.x == 0) && (area.w == SDL_cursor->area.w) ) { - SDL_DrawCursorFast(screen, &area); - } else { - SDL_DrawCursorSlow(screen, &area); - } -} - -void SDL_DrawCursor(SDL_Surface *screen) -{ - /* Lock the screen if necessary */ - if ( screen == NULL ) { - return; - } - if ( SDL_MUSTLOCK(screen) ) { - if ( SDL_LockSurface(screen) < 0 ) { - return; - } - } - - SDL_DrawCursorNoLock(screen); - - /* Unlock the screen and update if necessary */ - if ( SDL_MUSTLOCK(screen) ) { - SDL_UnlockSurface(screen); - } - if ( (screen == SDL_VideoSurface) && - ((screen->flags & SDL_HWSURFACE) != SDL_HWSURFACE) ) { - SDL_VideoDevice *video = current_video; - SDL_VideoDevice *this = current_video; - SDL_Rect area; - - SDL_MouseRect(&area); - - /* This can be called before a video mode is set */ - if ( video->UpdateRects ) { - video->UpdateRects(this, 1, &area); - } - } -} - -void SDL_EraseCursorNoLock(SDL_Surface *screen) -{ - SDL_Rect area; - - /* Get the mouse rectangle, clipped to the screen */ - SDL_MouseRect(&area); - if ( (area.w == 0) || (area.h == 0) ) { - return; - } - - /* Copy mouse background */ - { int w, h, screenbpp; - Uint8 *src, *dst; - - /* Set up the copy pointers */ - screenbpp = screen->format->BytesPerPixel; - if ( (screen == SDL_VideoSurface) || - FORMAT_EQUAL(screen->format, SDL_VideoSurface->format) ) { - src = SDL_cursor->save[0]; - } else { - src = SDL_cursor->save[1]; - } - dst = (Uint8 *)screen->pixels + area.y * screen->pitch + - area.x * screenbpp; - - /* Perform the copy */ - w = area.w*screenbpp; - h = area.h; - while ( h-- ) { - SDL_memcpy(dst, src, w); - src += w; - dst += screen->pitch; - } - - /* Perform pixel conversion on cursor background */ - if ( src > SDL_cursor->save[1] ) { - SDL_ConvertCursorSave(screen, area.w, area.h); - } - } -} - -void SDL_EraseCursor(SDL_Surface *screen) -{ - /* Lock the screen if necessary */ - if ( screen == NULL ) { - return; - } - if ( SDL_MUSTLOCK(screen) ) { - if ( SDL_LockSurface(screen) < 0 ) { - return; - } - } - - SDL_EraseCursorNoLock(screen); - - /* Unlock the screen and update if necessary */ - if ( SDL_MUSTLOCK(screen) ) { - SDL_UnlockSurface(screen); - } - if ( (screen == SDL_VideoSurface) && - ((screen->flags & SDL_HWSURFACE) != SDL_HWSURFACE) ) { - SDL_VideoDevice *video = current_video; - SDL_VideoDevice *this = current_video; - SDL_Rect area; - - SDL_MouseRect(&area); - if ( video->UpdateRects ) { - video->UpdateRects(this, 1, &area); - } - } -} - -/* Reset the cursor on video mode change - FIXME: Keep track of all cursors, and reset them all. - */ -void SDL_ResetCursor(void) -{ - int savelen; - - if ( SDL_cursor ) { - savelen = SDL_cursor->area.w*4*SDL_cursor->area.h; - SDL_cursor->area.x = 0; - SDL_cursor->area.y = 0; - SDL_memset(SDL_cursor->save[0], 0, savelen); - } -} diff --git a/src/video/SDL_cursor_c.h b/src/video/SDL_cursor_c.h deleted file mode 100644 index fc983e2d0..000000000 --- a/src/video/SDL_cursor_c.h +++ /dev/null @@ -1,73 +0,0 @@ -/* - SDL - Simple DirectMedia Layer - Copyright (C) 1997-2006 Sam Lantinga - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - - Sam Lantinga - slouken@libsdl.org -*/ -#include "SDL_config.h" - -/* Useful variables and functions from SDL_cursor.c */ -#include "SDL_mouse.h" - -extern int SDL_CursorInit(Uint32 flags); -extern void SDL_CursorPaletteChanged(void); -extern void SDL_DrawCursor(SDL_Surface *screen); -extern void SDL_DrawCursorNoLock(SDL_Surface *screen); -extern void SDL_EraseCursor(SDL_Surface *screen); -extern void SDL_EraseCursorNoLock(SDL_Surface *screen); -extern void SDL_UpdateCursor(SDL_Surface *screen); -extern void SDL_ResetCursor(void); -extern void SDL_MoveCursor(int x, int y); -extern void SDL_CursorQuit(void); - -#define INLINE_MOUSELOCK -#ifdef INLINE_MOUSELOCK -/* Inline (macro) versions of the mouse lock functions */ -#include "SDL_mutex.h" - -extern SDL_mutex *SDL_cursorlock; - -#define SDL_LockCursor() \ - do { \ - if ( SDL_cursorlock ) { \ - SDL_mutexP(SDL_cursorlock); \ - } \ - } while ( 0 ) -#define SDL_UnlockCursor() \ - do { \ - if ( SDL_cursorlock ) { \ - SDL_mutexV(SDL_cursorlock); \ - } \ - } while ( 0 ) -#else -extern void SDL_LockCursor(void); -extern void SDL_UnlockCursor(void); -#endif /* INLINE_MOUSELOCK */ - -/* Only for low-level mouse cursor drawing */ -extern SDL_Cursor *SDL_cursor; -extern void SDL_MouseRect(SDL_Rect *area); - -/* State definitions for the SDL cursor */ -#define CURSOR_VISIBLE 0x01 -#define CURSOR_USINGSW 0x10 -#define SHOULD_DRAWCURSOR(X) \ - (((X)&(CURSOR_VISIBLE|CURSOR_USINGSW)) == \ - (CURSOR_VISIBLE|CURSOR_USINGSW)) - -extern volatile int SDL_cursorstate; diff --git a/src/video/SDL_gamma.c b/src/video/SDL_gamma.c index a70a1f573..cd1dd1bc2 100644 --- a/src/video/SDL_gamma.c +++ b/src/video/SDL_gamma.c @@ -24,7 +24,7 @@ /* Gamma correction support */ #ifdef HAVE_MATH_H -#include /* Used for calculating gamma ramps */ +#include /* Used for calculating gamma ramps */ #else /* Math routines from uClibc: http://www.uclibc.org */ #include "math_private.h" @@ -38,196 +38,177 @@ #include "SDL_sysvideo.h" -static void CalculateGammaRamp(float gamma, Uint16 *ramp) +static void +CalculateGammaRamp(float gamma, Uint16 * ramp) { - int i; - - /* 0.0 gamma is all black */ - if ( gamma <= 0.0f ) { - for ( i=0; i<256; ++i ) { - ramp[i] = 0; - } - return; - } else - /* 1.0 gamma is identity */ - if ( gamma == 1.0f ) { - for ( i=0; i<256; ++i ) { - ramp[i] = (i << 8) | i; - } - return; - } else - /* Calculate a real gamma ramp */ - { int value; - gamma = 1.0f / gamma; - for ( i=0; i<256; ++i ) { - value = (int)(pow((double)i/256.0, gamma)*65535.0+0.5); - if ( value > 65535 ) { - value = 65535; - } - ramp[i] = (Uint16)value; - } - } + int i; + + /* 0.0 gamma is all black */ + if (gamma <= 0.0f) { + for (i = 0; i < 256; ++i) { + ramp[i] = 0; + } + return; + } else + /* 1.0 gamma is identity */ + if (gamma == 1.0f) { + for (i = 0; i < 256; ++i) { + ramp[i] = (i << 8) | i; + } + return; + } else + /* Calculate a real gamma ramp */ + { + int value; + gamma = 1.0f / gamma; + for (i = 0; i < 256; ++i) { + value = (int) (pow((double) i / 256.0, gamma) * 65535.0 + 0.5); + if (value > 65535) { + value = 65535; + } + ramp[i] = (Uint16) value; + } + } } -static void CalculateGammaFromRamp(float *gamma, Uint16 *ramp) +static void +CalculateGammaFromRamp(float *gamma, Uint16 * ramp) { - /* The following is adapted from a post by Garrett Bass on OpenGL - Gamedev list, March 4, 2000. - */ - float sum = 0.0f; - int i, count = 0; - - *gamma = 1.0; - for ( i = 1; i < 256; ++i ) { - if ( (ramp[i] != 0) && (ramp[i] != 65535) ) { - double B = (double)i / 256.0; - double A = ramp[i] / 65535.0; - sum += (float) ( log(A) / log(B) ); - count++; - } - } - if ( count && sum > 0.0f ) { - *gamma = 1.0f / (sum / count); - } + /* The following is adapted from a post by Garrett Bass on OpenGL + Gamedev list, March 4, 2000. + */ + float sum = 0.0f; + int i, count = 0; + + *gamma = 1.0; + for (i = 1; i < 256; ++i) { + if ((ramp[i] != 0) && (ramp[i] != 65535)) { + double B = (double) i / 256.0; + double A = ramp[i] / 65535.0; + sum += (float) (log(A) / log(B)); + count++; + } + } + if (count && sum > 0.0f) { + *gamma = 1.0f / (sum / count); + } } -int SDL_SetGamma(float red, float green, float blue) +int +SDL_SetGamma(float red, float green, float blue) { - int succeeded; - SDL_VideoDevice *video = current_video; - SDL_VideoDevice *this = current_video; - - succeeded = -1; - /* Prefer using SetGammaRamp(), as it's more flexible */ - { - Uint16 ramp[3][256]; - - CalculateGammaRamp(red, ramp[0]); - CalculateGammaRamp(green, ramp[1]); - CalculateGammaRamp(blue, ramp[2]); - succeeded = SDL_SetGammaRamp(ramp[0], ramp[1], ramp[2]); - } - if ( (succeeded < 0) && video->SetGamma ) { - SDL_ClearError(); - succeeded = video->SetGamma(this, red, green, blue); - } - return succeeded; + Uint16 ramp[3][256]; + + CalculateGammaRamp(red, ramp[0]); + CalculateGammaRamp(green, ramp[1]); + CalculateGammaRamp(blue, ramp[2]); + + return SDL_SetGammaRamp(ramp[0], ramp[1], ramp[2]); } /* Calculating the gamma by integrating the gamma ramps isn't exact, so this function isn't officially supported. */ -int SDL_GetGamma(float *red, float *green, float *blue) +int +SDL_GetGamma(float *red, float *green, float *blue) { - int succeeded; - SDL_VideoDevice *video = current_video; - SDL_VideoDevice *this = current_video; - - succeeded = -1; - /* Prefer using GetGammaRamp(), as it's more flexible */ - { - Uint16 ramp[3][256]; - - succeeded = SDL_GetGammaRamp(ramp[0], ramp[1], ramp[2]); - if ( succeeded >= 0 ) { - CalculateGammaFromRamp(red, ramp[0]); - CalculateGammaFromRamp(green, ramp[1]); - CalculateGammaFromRamp(blue, ramp[2]); - } - } - if ( (succeeded < 0) && video->GetGamma ) { - SDL_ClearError(); - succeeded = video->GetGamma(this, red, green, blue); - } - return succeeded; + int succeeded; + Uint16 ramp[3][256]; + + succeeded = SDL_GetGammaRamp(ramp[0], ramp[1], ramp[2]); + if (succeeded >= 0) { + CalculateGammaFromRamp(red, ramp[0]); + CalculateGammaFromRamp(green, ramp[1]); + CalculateGammaFromRamp(blue, ramp[2]); + } + return succeeded; } -int SDL_SetGammaRamp(const Uint16 *red, const Uint16 *green, const Uint16 *blue) +int +SDL_SetGammaRamp(const Uint16 * red, const Uint16 * green, + const Uint16 * blue) { - int succeeded; - SDL_VideoDevice *video = current_video; - SDL_VideoDevice *this = current_video; - SDL_Surface *screen = SDL_PublicSurface; - - /* Verify the screen parameter */ - if ( !screen ) { - SDL_SetError("No video mode has been set"); - return -1; - } - - /* Lazily allocate the gamma tables */ - if ( ! video->gamma ) { - SDL_GetGammaRamp(0, 0, 0); - } - - /* Fill the gamma table with the new values */ - if ( red ) { - SDL_memcpy(&video->gamma[0*256], red, 256*sizeof(*video->gamma)); - } - if ( green ) { - SDL_memcpy(&video->gamma[1*256], green, 256*sizeof(*video->gamma)); - } - if ( blue ) { - SDL_memcpy(&video->gamma[2*256], blue, 256*sizeof(*video->gamma)); - } - - /* Gamma correction always possible on split palettes */ - if ( (screen->flags & SDL_HWPALETTE) == SDL_HWPALETTE ) { - SDL_Palette *pal = screen->format->palette; - - /* If physical palette has been set independently, use it */ - if(video->physpal) - pal = video->physpal; - - SDL_SetPalette(screen, SDL_PHYSPAL, - pal->colors, 0, pal->ncolors); - return 0; - } - - /* Try to set the gamma ramp in the driver */ - succeeded = -1; - if ( video->SetGammaRamp ) { - succeeded = video->SetGammaRamp(this, video->gamma); - } else { - SDL_SetError("Gamma ramp manipulation not supported"); - } - return succeeded; + SDL_VideoDevice *_this = SDL_GetVideoDevice(); + int succeeded; + + /* Lazily allocate the gamma tables */ + if (!SDL_CurrentDisplay.gamma) { + SDL_GetGammaRamp(NULL, NULL, NULL); + } + + /* Fill the gamma table with the new values */ + if (red) { + SDL_memcpy(&SDL_CurrentDisplay.gamma[0 * 256], red, + 256 * sizeof(*SDL_CurrentDisplay.gamma)); + } + if (green) { + SDL_memcpy(&SDL_CurrentDisplay.gamma[1 * 256], green, + 256 * sizeof(*SDL_CurrentDisplay.gamma)); + } + if (blue) { + SDL_memcpy(&SDL_CurrentDisplay.gamma[2 * 256], blue, + 256 * sizeof(*SDL_CurrentDisplay.gamma)); + } + + /* Try to set the gamma ramp in the driver */ + succeeded = -1; + if (_this && _this->SetDisplayGammaRamp) { + if (SDL_GetFocusWindow()) { + succeeded = + _this->SetDisplayGammaRamp(_this, SDL_CurrentDisplay.gamma); + } else { + succeeded = 0; + } + } else { + SDL_SetError("Gamma ramp manipulation not supported"); + } + return succeeded; } -int SDL_GetGammaRamp(Uint16 *red, Uint16 *green, Uint16 *blue) +int +SDL_GetGammaRamp(Uint16 * red, Uint16 * green, Uint16 * blue) { - SDL_VideoDevice *video = current_video; - SDL_VideoDevice *this = current_video; - - /* Lazily allocate the gamma table */ - if ( ! video->gamma ) { - video->gamma = SDL_malloc(3*256*sizeof(*video->gamma)); - if ( ! video->gamma ) { - SDL_OutOfMemory(); - return -1; - } - if ( video->GetGammaRamp ) { - /* Get the real hardware gamma */ - video->GetGammaRamp(this, video->gamma); - } else { - /* Assume an identity gamma */ - int i; - for ( i=0; i<256; ++i ) { - video->gamma[0*256+i] = (i << 8) | i; - video->gamma[1*256+i] = (i << 8) | i; - video->gamma[2*256+i] = (i << 8) | i; - } - } - } - - /* Just copy from our internal table */ - if ( red ) { - SDL_memcpy(red, &video->gamma[0*256], 256*sizeof(*red)); - } - if ( green ) { - SDL_memcpy(green, &video->gamma[1*256], 256*sizeof(*green)); - } - if ( blue ) { - SDL_memcpy(blue, &video->gamma[2*256], 256*sizeof(*blue)); - } - return 0; + SDL_VideoDevice *_this = SDL_GetVideoDevice(); + + /* Lazily allocate the gamma table */ + if (!SDL_CurrentDisplay.gamma) { + size_t rampsize = (3 * 256 * sizeof(*SDL_CurrentDisplay.gamma)); + + SDL_CurrentDisplay.gamma = SDL_malloc(rampsize * 2); + if (!SDL_CurrentDisplay.gamma) { + SDL_OutOfMemory(); + return -1; + } + if (_this && _this->GetDisplayGammaRamp) { + /* Get the real hardware gamma */ + _this->GetDisplayGammaRamp(_this, SDL_CurrentDisplay.gamma); + } else { + /* Assume an identity gamma */ + int i; + for (i = 0; i < 256; ++i) { + SDL_CurrentDisplay.gamma[0 * 256 + i] = (i << 8) | i; + SDL_CurrentDisplay.gamma[1 * 256 + i] = (i << 8) | i; + SDL_CurrentDisplay.gamma[2 * 256 + i] = (i << 8) | i; + } + } + SDL_CurrentDisplay.saved_gamma = SDL_CurrentDisplay.gamma + (3 * 256); + SDL_memcpy(SDL_CurrentDisplay.saved_gamma, SDL_CurrentDisplay.gamma, + rampsize); + } + + /* Just copy from our internal table */ + if (red) { + SDL_memcpy(red, &SDL_CurrentDisplay.gamma[0 * 256], + 256 * sizeof(*red)); + } + if (green) { + SDL_memcpy(green, &SDL_CurrentDisplay.gamma[1 * 256], + 256 * sizeof(*green)); + } + if (blue) { + SDL_memcpy(blue, &SDL_CurrentDisplay.gamma[2 * 256], + 256 * sizeof(*blue)); + } + return 0; } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/SDL_glfuncs.h b/src/video/SDL_glfuncs.h index fb2d96487..8460db628 100644 --- a/src/video/SDL_glfuncs.h +++ b/src/video/SDL_glfuncs.h @@ -3,339 +3,452 @@ change it's entry from SDL_PROC_UNUSED to SDL_PROC and rebuild. */ #define SDL_PROC_UNUSED(ret,func,params) -SDL_PROC_UNUSED(void,glAccum,(GLenum,GLfloat)) -SDL_PROC_UNUSED(void,glAlphaFunc,(GLenum,GLclampf)) -SDL_PROC_UNUSED(GLboolean,glAreTexturesResident,(GLsizei,const GLuint*,GLboolean*)) -SDL_PROC_UNUSED(void,glArrayElement,(GLint)) -SDL_PROC(void,glBegin,(GLenum)) -SDL_PROC(void,glBindTexture,(GLenum,GLuint)) -SDL_PROC_UNUSED(void,glBitmap,(GLsizei,GLsizei,GLfloat,GLfloat,GLfloat,GLfloat,const GLubyte*)) -SDL_PROC(void,glBlendFunc,(GLenum,GLenum)) -SDL_PROC_UNUSED(void,glCallList,(GLuint)) -SDL_PROC_UNUSED(void,glCallLists,(GLsizei,GLenum,const GLvoid*)) -SDL_PROC_UNUSED(void,glClear,(GLbitfield)) -SDL_PROC_UNUSED(void,glClearAccum,(GLfloat,GLfloat,GLfloat,GLfloat)) -SDL_PROC_UNUSED(void,glClearColor,(GLclampf,GLclampf,GLclampf,GLclampf)) -SDL_PROC_UNUSED(void,glClearDepth,(GLclampd)) -SDL_PROC_UNUSED(void,glClearIndex,(GLfloat)) -SDL_PROC_UNUSED(void,glClearStencil,(GLint)) -SDL_PROC_UNUSED(void,glClipPlane,(GLenum,const GLdouble*)) -SDL_PROC_UNUSED(void,glColor3b,(GLbyte,GLbyte,GLbyte)) -SDL_PROC_UNUSED(void,glColor3bv,(const GLbyte*)) -SDL_PROC_UNUSED(void,glColor3d,(GLdouble,GLdouble,GLdouble)) -SDL_PROC_UNUSED(void,glColor3dv,(const GLdouble*)) -SDL_PROC_UNUSED(void,glColor3f,(GLfloat,GLfloat,GLfloat)) -SDL_PROC_UNUSED(void,glColor3fv,(const GLfloat*)) -SDL_PROC_UNUSED(void,glColor3i,(GLint,GLint,GLint)) -SDL_PROC_UNUSED(void,glColor3iv,(const GLint*)) -SDL_PROC_UNUSED(void,glColor3s,(GLshort,GLshort,GLshort)) -SDL_PROC_UNUSED(void,glColor3sv,(const GLshort*)) -SDL_PROC_UNUSED(void,glColor3ub,(GLubyte,GLubyte,GLubyte)) -SDL_PROC_UNUSED(void,glColor3ubv,(const GLubyte*)) -SDL_PROC_UNUSED(void,glColor3ui,(GLuint,GLuint,GLuint)) -SDL_PROC_UNUSED(void,glColor3uiv,(const GLuint*)) -SDL_PROC_UNUSED(void,glColor3us,(GLushort,GLushort,GLushort)) -SDL_PROC_UNUSED(void,glColor3usv,(const GLushort*)) -SDL_PROC_UNUSED(void,glColor4b,(GLbyte,GLbyte,GLbyte,GLbyte)) -SDL_PROC_UNUSED(void,glColor4bv,(const GLbyte*)) -SDL_PROC_UNUSED(void,glColor4d,(GLdouble,GLdouble,GLdouble,GLdouble)) -SDL_PROC_UNUSED(void,glColor4dv,(const GLdouble*)) -SDL_PROC(void,glColor4f,(GLfloat,GLfloat,GLfloat,GLfloat)) -SDL_PROC_UNUSED(void,glColor4fv,(const GLfloat*)) -SDL_PROC_UNUSED(void,glColor4i,(GLint,GLint,GLint,GLint)) -SDL_PROC_UNUSED(void,glColor4iv,(const GLint*)) -SDL_PROC_UNUSED(void,glColor4s,(GLshort,GLshort,GLshort,GLshort)) -SDL_PROC_UNUSED(void,glColor4sv,(const GLshort*)) -SDL_PROC_UNUSED(void,glColor4ub,(GLubyte red, GLubyte green, GLubyte blue, GLubyte alpha)) -SDL_PROC_UNUSED(void,glColor4ubv,(const GLubyte *v)) -SDL_PROC_UNUSED(void,glColor4ui,(GLuint red, GLuint green, GLuint blue, GLuint alpha)) -SDL_PROC_UNUSED(void,glColor4uiv,(const GLuint *v)) -SDL_PROC_UNUSED(void,glColor4us,(GLushort red, GLushort green, GLushort blue, GLushort alpha)) -SDL_PROC_UNUSED(void,glColor4usv,(const GLushort *v)) -SDL_PROC_UNUSED(void,glColorMask,(GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha)) -SDL_PROC_UNUSED(void,glColorMaterial,(GLenum face, GLenum mode)) -SDL_PROC_UNUSED(void,glColorPointer,(GLint size, GLenum type, GLsizei stride, const GLvoid *pointer)) -SDL_PROC_UNUSED(void,glCopyPixels,(GLint x, GLint y, GLsizei width, GLsizei height, GLenum type)) -SDL_PROC_UNUSED(void,glCopyTexImage1D,(GLenum target, GLint level, GLenum internalFormat, GLint x, GLint y, GLsizei width, GLint border)) -SDL_PROC_UNUSED(void,glCopyTexImage2D,(GLenum target, GLint level, GLenum internalFormat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border)) -SDL_PROC_UNUSED(void,glCopyTexSubImage1D,(GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width)) -SDL_PROC_UNUSED(void,glCopyTexSubImage2D,(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height)) -SDL_PROC_UNUSED(void,glCullFace,(GLenum mode)) -SDL_PROC_UNUSED(void,glDeleteLists,(GLuint list, GLsizei range)) -SDL_PROC_UNUSED(void,glDeleteTextures,(GLsizei n, const GLuint *textures)) -SDL_PROC_UNUSED(void,glDepthFunc,(GLenum func)) -SDL_PROC_UNUSED(void,glDepthMask,(GLboolean flag)) -SDL_PROC_UNUSED(void,glDepthRange,(GLclampd zNear, GLclampd zFar)) -SDL_PROC(void,glDisable,(GLenum cap)) -SDL_PROC_UNUSED(void,glDisableClientState,(GLenum array)) -SDL_PROC_UNUSED(void,glDrawArrays,(GLenum mode, GLint first, GLsizei count)) -SDL_PROC_UNUSED(void,glDrawBuffer,(GLenum mode)) -SDL_PROC_UNUSED(void,glDrawElements,(GLenum mode, GLsizei count, GLenum type, const GLvoid *indices)) -SDL_PROC_UNUSED(void,glDrawPixels,(GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *pixels)) -SDL_PROC_UNUSED(void,glEdgeFlag,(GLboolean flag)) -SDL_PROC_UNUSED(void,glEdgeFlagPointer,(GLsizei stride, const GLvoid *pointer)) -SDL_PROC_UNUSED(void,glEdgeFlagv,(const GLboolean *flag)) -SDL_PROC(void,glEnable,(GLenum cap)) -SDL_PROC_UNUSED(void,glEnableClientState,(GLenum array)) -SDL_PROC(void,glEnd,(void)) -SDL_PROC_UNUSED(void,glEndList,(void)) -SDL_PROC_UNUSED(void,glEvalCoord1d,(GLdouble u)) -SDL_PROC_UNUSED(void,glEvalCoord1dv,(const GLdouble *u)) -SDL_PROC_UNUSED(void,glEvalCoord1f,(GLfloat u)) -SDL_PROC_UNUSED(void,glEvalCoord1fv,(const GLfloat *u)) -SDL_PROC_UNUSED(void,glEvalCoord2d,(GLdouble u, GLdouble v)) -SDL_PROC_UNUSED(void,glEvalCoord2dv,(const GLdouble *u)) -SDL_PROC_UNUSED(void,glEvalCoord2f,(GLfloat u, GLfloat v)) -SDL_PROC_UNUSED(void,glEvalCoord2fv,(const GLfloat *u)) -SDL_PROC_UNUSED(void,glEvalMesh1,(GLenum mode, GLint i1, GLint i2)) -SDL_PROC_UNUSED(void,glEvalMesh2,(GLenum mode, GLint i1, GLint i2, GLint j1, GLint j2)) -SDL_PROC_UNUSED(void,glEvalPoint1,(GLint i)) -SDL_PROC_UNUSED(void,glEvalPoint2,(GLint i, GLint j)) -SDL_PROC_UNUSED(void,glFeedbackBuffer,(GLsizei size, GLenum type, GLfloat *buffer)) -SDL_PROC_UNUSED(void,glFinish,(void)) -SDL_PROC(void,glFlush,(void)) -SDL_PROC_UNUSED(void,glFogf,(GLenum pname, GLfloat param)) -SDL_PROC_UNUSED(void,glFogfv,(GLenum pname, const GLfloat *params)) -SDL_PROC_UNUSED(void,glFogi,(GLenum pname, GLint param)) -SDL_PROC_UNUSED(void,glFogiv,(GLenum pname, const GLint *params)) -SDL_PROC_UNUSED(void,glFrontFace,(GLenum mode)) -SDL_PROC_UNUSED(void,glFrustum,(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar)) -SDL_PROC_UNUSED(GLuint,glGenLists,(GLsizei range)) -SDL_PROC(void,glGenTextures,(GLsizei n, GLuint *textures)) -SDL_PROC_UNUSED(void,glGetBooleanv,(GLenum pname, GLboolean *params)) -SDL_PROC_UNUSED(void,glGetClipPlane,(GLenum plane, GLdouble *equation)) -SDL_PROC_UNUSED(void,glGetDoublev,(GLenum pname, GLdouble *params)) -SDL_PROC_UNUSED(GLenum,glGetError,(void)) -SDL_PROC_UNUSED(void,glGetFloatv,(GLenum pname, GLfloat *params)) -SDL_PROC_UNUSED(void,glGetIntegerv,(GLenum pname, GLint *params)) -SDL_PROC_UNUSED(void,glGetLightfv,(GLenum light, GLenum pname, GLfloat *params)) -SDL_PROC_UNUSED(void,glGetLightiv,(GLenum light, GLenum pname, GLint *params)) -SDL_PROC_UNUSED(void,glGetMapdv,(GLenum target, GLenum query, GLdouble *v)) -SDL_PROC_UNUSED(void,glGetMapfv,(GLenum target, GLenum query, GLfloat *v)) -SDL_PROC_UNUSED(void,glGetMapiv,(GLenum target, GLenum query, GLint *v)) -SDL_PROC_UNUSED(void,glGetMaterialfv,(GLenum face, GLenum pname, GLfloat *params)) -SDL_PROC_UNUSED(void,glGetMaterialiv,(GLenum face, GLenum pname, GLint *params)) -SDL_PROC_UNUSED(void,glGetPixelMapfv,(GLenum map, GLfloat *values)) -SDL_PROC_UNUSED(void,glGetPixelMapuiv,(GLenum map, GLuint *values)) -SDL_PROC_UNUSED(void,glGetPixelMapusv,(GLenum map, GLushort *values)) -SDL_PROC_UNUSED(void,glGetPointerv,(GLenum pname, GLvoid* *params)) -SDL_PROC_UNUSED(void,glGetPolygonStipple,(GLubyte *mask)) -SDL_PROC(const GLubyte *,glGetString,(GLenum name)) -SDL_PROC_UNUSED(void,glGetTexEnvfv,(GLenum target, GLenum pname, GLfloat *params)) -SDL_PROC_UNUSED(void,glGetTexEnviv,(GLenum target, GLenum pname, GLint *params)) -SDL_PROC_UNUSED(void,glGetTexGendv,(GLenum coord, GLenum pname, GLdouble *params)) -SDL_PROC_UNUSED(void,glGetTexGenfv,(GLenum coord, GLenum pname, GLfloat *params)) -SDL_PROC_UNUSED(void,glGetTexGeniv,(GLenum coord, GLenum pname, GLint *params)) -SDL_PROC_UNUSED(void,glGetTexImage,(GLenum target, GLint level, GLenum format, GLenum type, GLvoid *pixels)) -SDL_PROC_UNUSED(void,glGetTexLevelParameterfv,(GLenum target, GLint level, GLenum pname, GLfloat *params)) -SDL_PROC_UNUSED(void,glGetTexLevelParameteriv,(GLenum target, GLint level, GLenum pname, GLint *params)) -SDL_PROC_UNUSED(void,glGetTexParameterfv,(GLenum target, GLenum pname, GLfloat *params)) -SDL_PROC_UNUSED(void,glGetTexParameteriv,(GLenum target, GLenum pname, GLint *params)) -SDL_PROC_UNUSED(void,glHint,(GLenum target, GLenum mode)) -SDL_PROC_UNUSED(void,glIndexMask,(GLuint mask)) -SDL_PROC_UNUSED(void,glIndexPointer,(GLenum type, GLsizei stride, const GLvoid *pointer)) -SDL_PROC_UNUSED(void,glIndexd,(GLdouble c)) -SDL_PROC_UNUSED(void,glIndexdv,(const GLdouble *c)) -SDL_PROC_UNUSED(void,glIndexf,(GLfloat c)) -SDL_PROC_UNUSED(void,glIndexfv,(const GLfloat *c)) -SDL_PROC_UNUSED(void,glIndexi,(GLint c)) -SDL_PROC_UNUSED(void,glIndexiv,(const GLint *c)) -SDL_PROC_UNUSED(void,glIndexs,(GLshort c)) -SDL_PROC_UNUSED(void,glIndexsv,(const GLshort *c)) -SDL_PROC_UNUSED(void,glIndexub,(GLubyte c)) -SDL_PROC_UNUSED(void,glIndexubv,(const GLubyte *c)) -SDL_PROC_UNUSED(void,glInitNames,(void)) -SDL_PROC_UNUSED(void,glInterleavedArrays,(GLenum format, GLsizei stride, const GLvoid *pointer)) -SDL_PROC_UNUSED(GLboolean,glIsEnabled,(GLenum cap)) -SDL_PROC_UNUSED(GLboolean,glIsList,(GLuint list)) -SDL_PROC_UNUSED(GLboolean,glIsTexture,(GLuint texture)) -SDL_PROC_UNUSED(void,glLightModelf,(GLenum pname, GLfloat param)) -SDL_PROC_UNUSED(void,glLightModelfv,(GLenum pname, const GLfloat *params)) -SDL_PROC_UNUSED(void,glLightModeli,(GLenum pname, GLint param)) -SDL_PROC_UNUSED(void,glLightModeliv,(GLenum pname, const GLint *params)) -SDL_PROC_UNUSED(void,glLightf,(GLenum light, GLenum pname, GLfloat param)) -SDL_PROC_UNUSED(void,glLightfv,(GLenum light, GLenum pname, const GLfloat *params)) -SDL_PROC_UNUSED(void,glLighti,(GLenum light, GLenum pname, GLint param)) -SDL_PROC_UNUSED(void,glLightiv,(GLenum light, GLenum pname, const GLint *params)) -SDL_PROC_UNUSED(void,glLineStipple,(GLint factor, GLushort pattern)) -SDL_PROC_UNUSED(void,glLineWidth,(GLfloat width)) -SDL_PROC_UNUSED(void,glListBase,(GLuint base)) -SDL_PROC(void,glLoadIdentity,(void)) -SDL_PROC_UNUSED(void,glLoadMatrixd,(const GLdouble *m)) -SDL_PROC_UNUSED(void,glLoadMatrixf,(const GLfloat *m)) -SDL_PROC_UNUSED(void,glLoadName,(GLuint name)) -SDL_PROC_UNUSED(void,glLogicOp,(GLenum opcode)) -SDL_PROC_UNUSED(void,glMap1d,(GLenum target, GLdouble u1, GLdouble u2, GLint stride, GLint order, const GLdouble *points)) -SDL_PROC_UNUSED(void,glMap1f,(GLenum target, GLfloat u1, GLfloat u2, GLint stride, GLint order, const GLfloat *points)) -SDL_PROC_UNUSED(void,glMap2d,(GLenum target, GLdouble u1, GLdouble u2, GLint ustride, GLint uorder, GLdouble v1, GLdouble v2, GLint vstride, GLint vorder, const GLdouble *points)) -SDL_PROC_UNUSED(void,glMap2f,(GLenum target, GLfloat u1, GLfloat u2, GLint ustride, GLint uorder, GLfloat v1, GLfloat v2, GLint vstride, GLint vorder, const GLfloat *points)) -SDL_PROC_UNUSED(void,glMapGrid1d,(GLint un, GLdouble u1, GLdouble u2)) -SDL_PROC_UNUSED(void,glMapGrid1f,(GLint un, GLfloat u1, GLfloat u2)) -SDL_PROC_UNUSED(void,glMapGrid2d,(GLint un, GLdouble u1, GLdouble u2, GLint vn, GLdouble v1, GLdouble v2)) -SDL_PROC_UNUSED(void,glMapGrid2f,(GLint un, GLfloat u1, GLfloat u2, GLint vn, GLfloat v1, GLfloat v2)) -SDL_PROC_UNUSED(void,glMaterialf,(GLenum face, GLenum pname, GLfloat param)) -SDL_PROC_UNUSED(void,glMaterialfv,(GLenum face, GLenum pname, const GLfloat *params)) -SDL_PROC_UNUSED(void,glMateriali,(GLenum face, GLenum pname, GLint param)) -SDL_PROC_UNUSED(void,glMaterialiv,(GLenum face, GLenum pname, const GLint *params)) -SDL_PROC(void,glMatrixMode,(GLenum mode)) -SDL_PROC_UNUSED(void,glMultMatrixd,(const GLdouble *m)) -SDL_PROC_UNUSED(void,glMultMatrixf,(const GLfloat *m)) -SDL_PROC_UNUSED(void,glNewList,(GLuint list, GLenum mode)) -SDL_PROC_UNUSED(void,glNormal3b,(GLbyte nx, GLbyte ny, GLbyte nz)) -SDL_PROC_UNUSED(void,glNormal3bv,(const GLbyte *v)) -SDL_PROC_UNUSED(void,glNormal3d,(GLdouble nx, GLdouble ny, GLdouble nz)) -SDL_PROC_UNUSED(void,glNormal3dv,(const GLdouble *v)) -SDL_PROC_UNUSED(void,glNormal3f,(GLfloat nx, GLfloat ny, GLfloat nz)) -SDL_PROC_UNUSED(void,glNormal3fv,(const GLfloat *v)) -SDL_PROC_UNUSED(void,glNormal3i,(GLint nx, GLint ny, GLint nz)) -SDL_PROC_UNUSED(void,glNormal3iv,(const GLint *v)) -SDL_PROC_UNUSED(void,glNormal3s,(GLshort nx, GLshort ny, GLshort nz)) -SDL_PROC_UNUSED(void,glNormal3sv,(const GLshort *v)) -SDL_PROC_UNUSED(void,glNormalPointer,(GLenum type, GLsizei stride, const GLvoid *pointer)) -SDL_PROC(void,glOrtho,(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar)) -SDL_PROC_UNUSED(void,glPassThrough,(GLfloat token)) -SDL_PROC_UNUSED(void,glPixelMapfv,(GLenum map, GLsizei mapsize, const GLfloat *values)) -SDL_PROC_UNUSED(void,glPixelMapuiv,(GLenum map, GLsizei mapsize, const GLuint *values)) -SDL_PROC_UNUSED(void,glPixelMapusv,(GLenum map, GLsizei mapsize, const GLushort *values)) -SDL_PROC_UNUSED(void,glPixelStoref,(GLenum pname, GLfloat param)) -SDL_PROC(void,glPixelStorei,(GLenum pname, GLint param)) -SDL_PROC_UNUSED(void,glPixelTransferf,(GLenum pname, GLfloat param)) -SDL_PROC_UNUSED(void,glPixelTransferi,(GLenum pname, GLint param)) -SDL_PROC_UNUSED(void,glPixelZoom,(GLfloat xfactor, GLfloat yfactor)) -SDL_PROC_UNUSED(void,glPointSize,(GLfloat size)) -SDL_PROC_UNUSED(void,glPolygonMode,(GLenum face, GLenum mode)) -SDL_PROC_UNUSED(void,glPolygonOffset,(GLfloat factor, GLfloat units)) -SDL_PROC_UNUSED(void,glPolygonStipple,(const GLubyte *mask)) -SDL_PROC(void,glPopAttrib,(void)) -SDL_PROC(void,glPopClientAttrib,(void)) -SDL_PROC(void,glPopMatrix,(void)) -SDL_PROC_UNUSED(void,glPopName,(void)) -SDL_PROC_UNUSED(void,glPrioritizeTextures,(GLsizei n, const GLuint *textures, const GLclampf *priorities)) -SDL_PROC(void,glPushAttrib,(GLbitfield mask)) -SDL_PROC(void,glPushClientAttrib,(GLbitfield mask)) -SDL_PROC(void,glPushMatrix,(void)) -SDL_PROC_UNUSED(void,glPushName,(GLuint name)) -SDL_PROC_UNUSED(void,glRasterPos2d,(GLdouble x, GLdouble y)) -SDL_PROC_UNUSED(void,glRasterPos2dv,(const GLdouble *v)) -SDL_PROC_UNUSED(void,glRasterPos2f,(GLfloat x, GLfloat y)) -SDL_PROC_UNUSED(void,glRasterPos2fv,(const GLfloat *v)) -SDL_PROC_UNUSED(void,glRasterPos2i,(GLint x, GLint y)) -SDL_PROC_UNUSED(void,glRasterPos2iv,(const GLint *v)) -SDL_PROC_UNUSED(void,glRasterPos2s,(GLshort x, GLshort y)) -SDL_PROC_UNUSED(void,glRasterPos2sv,(const GLshort *v)) -SDL_PROC_UNUSED(void,glRasterPos3d,(GLdouble x, GLdouble y, GLdouble z)) -SDL_PROC_UNUSED(void,glRasterPos3dv,(const GLdouble *v)) -SDL_PROC_UNUSED(void,glRasterPos3f,(GLfloat x, GLfloat y, GLfloat z)) -SDL_PROC_UNUSED(void,glRasterPos3fv,(const GLfloat *v)) -SDL_PROC_UNUSED(void,glRasterPos3i,(GLint x, GLint y, GLint z)) -SDL_PROC_UNUSED(void,glRasterPos3iv,(const GLint *v)) -SDL_PROC_UNUSED(void,glRasterPos3s,(GLshort x, GLshort y, GLshort z)) -SDL_PROC_UNUSED(void,glRasterPos3sv,(const GLshort *v)) -SDL_PROC_UNUSED(void,glRasterPos4d,(GLdouble x, GLdouble y, GLdouble z, GLdouble w)) -SDL_PROC_UNUSED(void,glRasterPos4dv,(const GLdouble *v)) -SDL_PROC_UNUSED(void,glRasterPos4f,(GLfloat x, GLfloat y, GLfloat z, GLfloat w)) -SDL_PROC_UNUSED(void,glRasterPos4fv,(const GLfloat *v)) -SDL_PROC_UNUSED(void,glRasterPos4i,(GLint x, GLint y, GLint z, GLint w)) -SDL_PROC_UNUSED(void,glRasterPos4iv,(const GLint *v)) -SDL_PROC_UNUSED(void,glRasterPos4s,(GLshort x, GLshort y, GLshort z, GLshort w)) -SDL_PROC_UNUSED(void,glRasterPos4sv,(const GLshort *v)) -SDL_PROC_UNUSED(void,glReadBuffer,(GLenum mode)) -SDL_PROC_UNUSED(void,glReadPixels,(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLvoid *pixels)) -SDL_PROC_UNUSED(void,glRectd,(GLdouble x1, GLdouble y1, GLdouble x2, GLdouble y2)) -SDL_PROC_UNUSED(void,glRectdv,(const GLdouble *v1, const GLdouble *v2)) -SDL_PROC_UNUSED(void,glRectf,(GLfloat x1, GLfloat y1, GLfloat x2, GLfloat y2)) -SDL_PROC_UNUSED(void,glRectfv,(const GLfloat *v1, const GLfloat *v2)) -SDL_PROC_UNUSED(void,glRecti,(GLint x1, GLint y1, GLint x2, GLint y2)) -SDL_PROC_UNUSED(void,glRectiv,(const GLint *v1, const GLint *v2)) -SDL_PROC_UNUSED(void,glRects,(GLshort x1, GLshort y1, GLshort x2, GLshort y2)) -SDL_PROC_UNUSED(void,glRectsv,(const GLshort *v1, const GLshort *v2)) -SDL_PROC_UNUSED(GLint,glRenderMode,(GLenum mode)) -SDL_PROC_UNUSED(void,glRotated,(GLdouble angle, GLdouble x, GLdouble y, GLdouble z)) -SDL_PROC_UNUSED(void,glRotatef,(GLfloat angle, GLfloat x, GLfloat y, GLfloat z)) -SDL_PROC_UNUSED(void,glScaled,(GLdouble x, GLdouble y, GLdouble z)) -SDL_PROC_UNUSED(void,glScalef,(GLfloat x, GLfloat y, GLfloat z)) -SDL_PROC_UNUSED(void,glScissor,(GLint x, GLint y, GLsizei width, GLsizei height)) -SDL_PROC_UNUSED(void,glSelectBuffer,(GLsizei size, GLuint *buffer)) -SDL_PROC_UNUSED(void,glShadeModel,(GLenum mode)) -SDL_PROC_UNUSED(void,glStencilFunc,(GLenum func, GLint ref, GLuint mask)) -SDL_PROC_UNUSED(void,glStencilMask,(GLuint mask)) -SDL_PROC_UNUSED(void,glStencilOp,(GLenum fail, GLenum zfail, GLenum zpass)) -SDL_PROC_UNUSED(void,glTexCoord1d,(GLdouble s)) -SDL_PROC_UNUSED(void,glTexCoord1dv,(const GLdouble *v)) -SDL_PROC_UNUSED(void,glTexCoord1f,(GLfloat s)) -SDL_PROC_UNUSED(void,glTexCoord1fv,(const GLfloat *v)) -SDL_PROC_UNUSED(void,glTexCoord1i,(GLint s)) -SDL_PROC_UNUSED(void,glTexCoord1iv,(const GLint *v)) -SDL_PROC_UNUSED(void,glTexCoord1s,(GLshort s)) -SDL_PROC_UNUSED(void,glTexCoord1sv,(const GLshort *v)) -SDL_PROC_UNUSED(void,glTexCoord2d,(GLdouble s, GLdouble t)) -SDL_PROC_UNUSED(void,glTexCoord2dv,(const GLdouble *v)) -SDL_PROC(void,glTexCoord2f,(GLfloat s, GLfloat t)) -SDL_PROC_UNUSED(void,glTexCoord2fv,(const GLfloat *v)) -SDL_PROC_UNUSED(void,glTexCoord2i,(GLint s, GLint t)) -SDL_PROC_UNUSED(void,glTexCoord2iv,(const GLint *v)) -SDL_PROC_UNUSED(void,glTexCoord2s,(GLshort s, GLshort t)) -SDL_PROC_UNUSED(void,glTexCoord2sv,(const GLshort *v)) -SDL_PROC_UNUSED(void,glTexCoord3d,(GLdouble s, GLdouble t, GLdouble r)) -SDL_PROC_UNUSED(void,glTexCoord3dv,(const GLdouble *v)) -SDL_PROC_UNUSED(void,glTexCoord3f,(GLfloat s, GLfloat t, GLfloat r)) -SDL_PROC_UNUSED(void,glTexCoord3fv,(const GLfloat *v)) -SDL_PROC_UNUSED(void,glTexCoord3i,(GLint s, GLint t, GLint r)) -SDL_PROC_UNUSED(void,glTexCoord3iv,(const GLint *v)) -SDL_PROC_UNUSED(void,glTexCoord3s,(GLshort s, GLshort t, GLshort r)) -SDL_PROC_UNUSED(void,glTexCoord3sv,(const GLshort *v)) -SDL_PROC_UNUSED(void,glTexCoord4d,(GLdouble s, GLdouble t, GLdouble r, GLdouble q)) -SDL_PROC_UNUSED(void,glTexCoord4dv,(const GLdouble *v)) -SDL_PROC_UNUSED(void,glTexCoord4f,(GLfloat s, GLfloat t, GLfloat r, GLfloat q)) -SDL_PROC_UNUSED(void,glTexCoord4fv,(const GLfloat *v)) -SDL_PROC_UNUSED(void,glTexCoord4i,(GLint s, GLint t, GLint r, GLint q)) -SDL_PROC_UNUSED(void,glTexCoord4iv,(const GLint *v)) -SDL_PROC_UNUSED(void,glTexCoord4s,(GLshort s, GLshort t, GLshort r, GLshort q)) -SDL_PROC_UNUSED(void,glTexCoord4sv,(const GLshort *v)) -SDL_PROC_UNUSED(void,glTexCoordPointer,(GLint size, GLenum type, GLsizei stride, const GLvoid *pointer)) -SDL_PROC(void,glTexEnvf,(GLenum target, GLenum pname, GLfloat param)) -SDL_PROC_UNUSED(void,glTexEnvfv,(GLenum target, GLenum pname, const GLfloat *params)) -SDL_PROC_UNUSED(void,glTexEnvi,(GLenum target, GLenum pname, GLint param)) -SDL_PROC_UNUSED(void,glTexEnviv,(GLenum target, GLenum pname, const GLint *params)) -SDL_PROC_UNUSED(void,glTexGend,(GLenum coord, GLenum pname, GLdouble param)) -SDL_PROC_UNUSED(void,glTexGendv,(GLenum coord, GLenum pname, const GLdouble *params)) -SDL_PROC_UNUSED(void,glTexGenf,(GLenum coord, GLenum pname, GLfloat param)) -SDL_PROC_UNUSED(void,glTexGenfv,(GLenum coord, GLenum pname, const GLfloat *params)) -SDL_PROC_UNUSED(void,glTexGeni,(GLenum coord, GLenum pname, GLint param)) -SDL_PROC_UNUSED(void,glTexGeniv,(GLenum coord, GLenum pname, const GLint *params)) -SDL_PROC_UNUSED(void,glTexImage1D,(GLenum target, GLint level, GLint internalformat, GLsizei width, GLint border, GLenum format, GLenum type, const GLvoid *pixels)) -SDL_PROC(void,glTexImage2D,(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid *pixels)) -SDL_PROC_UNUSED(void,glTexParameterf,(GLenum target, GLenum pname, GLfloat param)) -SDL_PROC_UNUSED(void,glTexParameterfv,(GLenum target, GLenum pname, const GLfloat *params)) -SDL_PROC(void,glTexParameteri,(GLenum target, GLenum pname, GLint param)) -SDL_PROC_UNUSED(void,glTexParameteriv,(GLenum target, GLenum pname, const GLint *params)) -SDL_PROC_UNUSED(void,glTexSubImage1D,(GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const GLvoid *pixels)) -SDL_PROC(void,glTexSubImage2D,(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *pixels)) -SDL_PROC_UNUSED(void,glTranslated,(GLdouble x, GLdouble y, GLdouble z)) -SDL_PROC_UNUSED(void,glTranslatef,(GLfloat x, GLfloat y, GLfloat z)) -SDL_PROC_UNUSED(void,glVertex2d,(GLdouble x, GLdouble y)) -SDL_PROC_UNUSED(void,glVertex2dv,(const GLdouble *v)) -SDL_PROC_UNUSED(void,glVertex2f,(GLfloat x, GLfloat y)) -SDL_PROC_UNUSED(void,glVertex2fv,(const GLfloat *v)) -SDL_PROC(void,glVertex2i,(GLint x, GLint y)) -SDL_PROC_UNUSED(void,glVertex2iv,(const GLint *v)) -SDL_PROC_UNUSED(void,glVertex2s,(GLshort x, GLshort y)) -SDL_PROC_UNUSED(void,glVertex2sv,(const GLshort *v)) -SDL_PROC_UNUSED(void,glVertex3d,(GLdouble x, GLdouble y, GLdouble z)) -SDL_PROC_UNUSED(void,glVertex3dv,(const GLdouble *v)) -SDL_PROC_UNUSED(void,glVertex3f,(GLfloat x, GLfloat y, GLfloat z)) -SDL_PROC_UNUSED(void,glVertex3fv,(const GLfloat *v)) -SDL_PROC_UNUSED(void,glVertex3i,(GLint x, GLint y, GLint z)) -SDL_PROC_UNUSED(void,glVertex3iv,(const GLint *v)) -SDL_PROC_UNUSED(void,glVertex3s,(GLshort x, GLshort y, GLshort z)) -SDL_PROC_UNUSED(void,glVertex3sv,(const GLshort *v)) -SDL_PROC_UNUSED(void,glVertex4d,(GLdouble x, GLdouble y, GLdouble z, GLdouble w)) -SDL_PROC_UNUSED(void,glVertex4dv,(const GLdouble *v)) -SDL_PROC_UNUSED(void,glVertex4f,(GLfloat x, GLfloat y, GLfloat z, GLfloat w)) -SDL_PROC_UNUSED(void,glVertex4fv,(const GLfloat *v)) -SDL_PROC_UNUSED(void,glVertex4i,(GLint x, GLint y, GLint z, GLint w)) -SDL_PROC_UNUSED(void,glVertex4iv,(const GLint *v)) -SDL_PROC_UNUSED(void,glVertex4s,(GLshort x, GLshort y, GLshort z, GLshort w)) -SDL_PROC_UNUSED(void,glVertex4sv,(const GLshort *v)) -SDL_PROC_UNUSED(void,glVertexPointer,(GLint size, GLenum type, GLsizei stride, const GLvoid *pointer)) -SDL_PROC(void,glViewport,(GLint x, GLint y, GLsizei width, GLsizei height)) +SDL_PROC_UNUSED(void, glAccum, (GLenum, GLfloat)) +SDL_PROC_UNUSED(void, glAlphaFunc, (GLenum, GLclampf)) +SDL_PROC_UNUSED(GLboolean, glAreTexturesResident, + (GLsizei, const GLuint *, GLboolean *)) +SDL_PROC_UNUSED(void, glArrayElement, (GLint)) +SDL_PROC(void, glBegin, (GLenum)) +SDL_PROC(void, glBindTexture, (GLenum, GLuint)) +SDL_PROC_UNUSED(void, glBitmap, + (GLsizei, GLsizei, GLfloat, GLfloat, GLfloat, GLfloat, + const GLubyte *)) +SDL_PROC(void, glBlendFunc, (GLenum, GLenum)) +SDL_PROC_UNUSED(void, glCallList, (GLuint)) +SDL_PROC_UNUSED(void, glCallLists, (GLsizei, GLenum, const GLvoid *)) +SDL_PROC_UNUSED(void, glClear, (GLbitfield)) +SDL_PROC_UNUSED(void, glClearAccum, (GLfloat, GLfloat, GLfloat, GLfloat)) +SDL_PROC_UNUSED(void, glClearColor, (GLclampf, GLclampf, GLclampf, GLclampf)) +SDL_PROC_UNUSED(void, glClearDepth, (GLclampd)) +SDL_PROC_UNUSED(void, glClearIndex, (GLfloat)) +SDL_PROC_UNUSED(void, glClearStencil, (GLint)) +SDL_PROC_UNUSED(void, glClipPlane, (GLenum, const GLdouble *)) +SDL_PROC_UNUSED(void, glColor3b, (GLbyte, GLbyte, GLbyte)) +SDL_PROC_UNUSED(void, glColor3bv, (const GLbyte *)) +SDL_PROC_UNUSED(void, glColor3d, (GLdouble, GLdouble, GLdouble)) +SDL_PROC_UNUSED(void, glColor3dv, (const GLdouble *)) +SDL_PROC_UNUSED(void, glColor3f, (GLfloat, GLfloat, GLfloat)) +SDL_PROC_UNUSED(void, glColor3fv, (const GLfloat *)) +SDL_PROC_UNUSED(void, glColor3i, (GLint, GLint, GLint)) +SDL_PROC_UNUSED(void, glColor3iv, (const GLint *)) +SDL_PROC_UNUSED(void, glColor3s, (GLshort, GLshort, GLshort)) +SDL_PROC_UNUSED(void, glColor3sv, (const GLshort *)) +SDL_PROC(void, glColor3ub, (GLubyte, GLubyte, GLubyte)) +SDL_PROC_UNUSED(void, glColor3ubv, (const GLubyte *)) +SDL_PROC_UNUSED(void, glColor3ui, (GLuint, GLuint, GLuint)) +SDL_PROC_UNUSED(void, glColor3uiv, (const GLuint *)) +SDL_PROC_UNUSED(void, glColor3us, (GLushort, GLushort, GLushort)) +SDL_PROC_UNUSED(void, glColor3usv, (const GLushort *)) +SDL_PROC_UNUSED(void, glColor4b, (GLbyte, GLbyte, GLbyte, GLbyte)) +SDL_PROC_UNUSED(void, glColor4bv, (const GLbyte *)) +SDL_PROC_UNUSED(void, glColor4d, (GLdouble, GLdouble, GLdouble, GLdouble)) +SDL_PROC_UNUSED(void, glColor4dv, (const GLdouble *)) +SDL_PROC(void, glColor4f, (GLfloat, GLfloat, GLfloat, GLfloat)) +SDL_PROC_UNUSED(void, glColor4fv, (const GLfloat *)) +SDL_PROC_UNUSED(void, glColor4i, (GLint, GLint, GLint, GLint)) +SDL_PROC_UNUSED(void, glColor4iv, (const GLint *)) +SDL_PROC_UNUSED(void, glColor4s, (GLshort, GLshort, GLshort, GLshort)) +SDL_PROC_UNUSED(void, glColor4sv, (const GLshort *)) +SDL_PROC(void, glColor4ub, + (GLubyte red, GLubyte green, GLubyte blue, GLubyte alpha)) +SDL_PROC_UNUSED(void, glColor4ubv, (const GLubyte * v)) +SDL_PROC_UNUSED(void, glColor4ui, + (GLuint red, GLuint green, GLuint blue, GLuint alpha)) +SDL_PROC_UNUSED(void, glColor4uiv, (const GLuint * v)) +SDL_PROC_UNUSED(void, glColor4us, + (GLushort red, GLushort green, GLushort blue, GLushort alpha)) +SDL_PROC_UNUSED(void, glColor4usv, (const GLushort * v)) +SDL_PROC_UNUSED(void, glColorMask, + (GLboolean red, GLboolean green, GLboolean blue, + GLboolean alpha)) +SDL_PROC_UNUSED(void, glColorMaterial, (GLenum face, GLenum mode)) +SDL_PROC_UNUSED(void, glColorPointer, + (GLint size, GLenum type, GLsizei stride, + const GLvoid * pointer)) +SDL_PROC_UNUSED(void, glCopyPixels, + (GLint x, GLint y, GLsizei width, GLsizei height, + GLenum type)) +SDL_PROC_UNUSED(void, glCopyTexImage1D, + (GLenum target, GLint level, GLenum internalFormat, GLint x, + GLint y, GLsizei width, GLint border)) +SDL_PROC_UNUSED(void, glCopyTexImage2D, + (GLenum target, GLint level, GLenum internalFormat, GLint x, + GLint y, GLsizei width, GLsizei height, GLint border)) +SDL_PROC_UNUSED(void, glCopyTexSubImage1D, + (GLenum target, GLint level, GLint xoffset, GLint x, GLint y, + GLsizei width)) +SDL_PROC_UNUSED(void, glCopyTexSubImage2D, + (GLenum target, GLint level, GLint xoffset, GLint yoffset, + GLint x, GLint y, GLsizei width, GLsizei height)) +SDL_PROC_UNUSED(void, glCullFace, (GLenum mode)) +SDL_PROC_UNUSED(void, glDeleteLists, (GLuint list, GLsizei range)) +SDL_PROC(void, glDeleteTextures, (GLsizei n, const GLuint * textures)) +SDL_PROC_UNUSED(void, glDepthFunc, (GLenum func)) +SDL_PROC_UNUSED(void, glDepthMask, (GLboolean flag)) +SDL_PROC_UNUSED(void, glDepthRange, (GLclampd zNear, GLclampd zFar)) +SDL_PROC(void, glDisable, (GLenum cap)) +SDL_PROC_UNUSED(void, glDisableClientState, (GLenum array)) +SDL_PROC_UNUSED(void, glDrawArrays, (GLenum mode, GLint first, GLsizei count)) +SDL_PROC(void, glDrawBuffer, (GLenum mode)) +SDL_PROC_UNUSED(void, glDrawElements, + (GLenum mode, GLsizei count, GLenum type, + const GLvoid * indices)) +SDL_PROC_UNUSED(void, glDrawPixels, + (GLsizei width, GLsizei height, GLenum format, GLenum type, + const GLvoid * pixels)) +SDL_PROC_UNUSED(void, glEdgeFlag, (GLboolean flag)) +SDL_PROC_UNUSED(void, glEdgeFlagPointer, + (GLsizei stride, const GLvoid * pointer)) +SDL_PROC_UNUSED(void, glEdgeFlagv, (const GLboolean * flag)) +SDL_PROC(void, glEnable, (GLenum cap)) +SDL_PROC_UNUSED(void, glEnableClientState, (GLenum array)) +SDL_PROC(void, glEnd, (void)) +SDL_PROC_UNUSED(void, glEndList, (void)) +SDL_PROC_UNUSED(void, glEvalCoord1d, (GLdouble u)) +SDL_PROC_UNUSED(void, glEvalCoord1dv, (const GLdouble * u)) +SDL_PROC_UNUSED(void, glEvalCoord1f, (GLfloat u)) +SDL_PROC_UNUSED(void, glEvalCoord1fv, (const GLfloat * u)) +SDL_PROC_UNUSED(void, glEvalCoord2d, (GLdouble u, GLdouble v)) +SDL_PROC_UNUSED(void, glEvalCoord2dv, (const GLdouble * u)) +SDL_PROC_UNUSED(void, glEvalCoord2f, (GLfloat u, GLfloat v)) +SDL_PROC_UNUSED(void, glEvalCoord2fv, (const GLfloat * u)) +SDL_PROC_UNUSED(void, glEvalMesh1, (GLenum mode, GLint i1, GLint i2)) +SDL_PROC_UNUSED(void, glEvalMesh2, + (GLenum mode, GLint i1, GLint i2, GLint j1, GLint j2)) +SDL_PROC_UNUSED(void, glEvalPoint1, (GLint i)) +SDL_PROC_UNUSED(void, glEvalPoint2, (GLint i, GLint j)) +SDL_PROC_UNUSED(void, glFeedbackBuffer, + (GLsizei size, GLenum type, GLfloat * buffer)) +SDL_PROC(void, glFinish, (void)) +SDL_PROC(void, glFlush, (void)) +SDL_PROC_UNUSED(void, glFogf, (GLenum pname, GLfloat param)) +SDL_PROC_UNUSED(void, glFogfv, (GLenum pname, const GLfloat * params)) +SDL_PROC_UNUSED(void, glFogi, (GLenum pname, GLint param)) +SDL_PROC_UNUSED(void, glFogiv, (GLenum pname, const GLint * params)) +SDL_PROC_UNUSED(void, glFrontFace, (GLenum mode)) +SDL_PROC_UNUSED(void, glFrustum, + (GLdouble left, GLdouble right, GLdouble bottom, + GLdouble top, GLdouble zNear, GLdouble zFar)) +SDL_PROC_UNUSED(GLuint, glGenLists, (GLsizei range)) +SDL_PROC(void, glGenTextures, (GLsizei n, GLuint * textures)) +SDL_PROC_UNUSED(void, glGetBooleanv, (GLenum pname, GLboolean * params)) +SDL_PROC_UNUSED(void, glGetClipPlane, (GLenum plane, GLdouble * equation)) +SDL_PROC_UNUSED(void, glGetDoublev, (GLenum pname, GLdouble * params)) +SDL_PROC(GLenum, glGetError, (void)) +SDL_PROC_UNUSED(void, glGetFloatv, (GLenum pname, GLfloat * params)) +SDL_PROC(void, glGetIntegerv, (GLenum pname, GLint * params)) +SDL_PROC_UNUSED(void, glGetLightfv, + (GLenum light, GLenum pname, GLfloat * params)) +SDL_PROC_UNUSED(void, glGetLightiv, + (GLenum light, GLenum pname, GLint * params)) +SDL_PROC_UNUSED(void, glGetMapdv, (GLenum target, GLenum query, GLdouble * v)) +SDL_PROC_UNUSED(void, glGetMapfv, (GLenum target, GLenum query, GLfloat * v)) +SDL_PROC_UNUSED(void, glGetMapiv, (GLenum target, GLenum query, GLint * v)) +SDL_PROC_UNUSED(void, glGetMaterialfv, + (GLenum face, GLenum pname, GLfloat * params)) +SDL_PROC_UNUSED(void, glGetMaterialiv, + (GLenum face, GLenum pname, GLint * params)) +SDL_PROC_UNUSED(void, glGetPixelMapfv, (GLenum map, GLfloat * values)) +SDL_PROC_UNUSED(void, glGetPixelMapuiv, (GLenum map, GLuint * values)) +SDL_PROC_UNUSED(void, glGetPixelMapusv, (GLenum map, GLushort * values)) +SDL_PROC_UNUSED(void, glGetPointerv, (GLenum pname, GLvoid * *params)) +SDL_PROC_UNUSED(void, glGetPolygonStipple, (GLubyte * mask)) +SDL_PROC(const GLubyte *, glGetString, (GLenum name)) +SDL_PROC_UNUSED(void, glGetTexEnvfv, + (GLenum target, GLenum pname, GLfloat * params)) +SDL_PROC_UNUSED(void, glGetTexEnviv, + (GLenum target, GLenum pname, GLint * params)) +SDL_PROC_UNUSED(void, glGetTexGendv, + (GLenum coord, GLenum pname, GLdouble * params)) +SDL_PROC_UNUSED(void, glGetTexGenfv, + (GLenum coord, GLenum pname, GLfloat * params)) +SDL_PROC_UNUSED(void, glGetTexGeniv, + (GLenum coord, GLenum pname, GLint * params)) +SDL_PROC_UNUSED(void, glGetTexImage, + (GLenum target, GLint level, GLenum format, GLenum type, + GLvoid * pixels)) +SDL_PROC_UNUSED(void, glGetTexLevelParameterfv, + (GLenum target, GLint level, GLenum pname, GLfloat * params)) +SDL_PROC_UNUSED(void, glGetTexLevelParameteriv, + (GLenum target, GLint level, GLenum pname, GLint * params)) +SDL_PROC_UNUSED(void, glGetTexParameterfv, + (GLenum target, GLenum pname, GLfloat * params)) +SDL_PROC_UNUSED(void, glGetTexParameteriv, + (GLenum target, GLenum pname, GLint * params)) +SDL_PROC_UNUSED(void, glHint, (GLenum target, GLenum mode)) +SDL_PROC_UNUSED(void, glIndexMask, (GLuint mask)) +SDL_PROC_UNUSED(void, glIndexPointer, + (GLenum type, GLsizei stride, const GLvoid * pointer)) +SDL_PROC_UNUSED(void, glIndexd, (GLdouble c)) +SDL_PROC_UNUSED(void, glIndexdv, (const GLdouble * c)) +SDL_PROC_UNUSED(void, glIndexf, (GLfloat c)) +SDL_PROC_UNUSED(void, glIndexfv, (const GLfloat * c)) +SDL_PROC_UNUSED(void, glIndexi, (GLint c)) +SDL_PROC_UNUSED(void, glIndexiv, (const GLint * c)) +SDL_PROC_UNUSED(void, glIndexs, (GLshort c)) +SDL_PROC_UNUSED(void, glIndexsv, (const GLshort * c)) +SDL_PROC_UNUSED(void, glIndexub, (GLubyte c)) +SDL_PROC_UNUSED(void, glIndexubv, (const GLubyte * c)) +SDL_PROC_UNUSED(void, glInitNames, (void)) +SDL_PROC_UNUSED(void, glInterleavedArrays, + (GLenum format, GLsizei stride, const GLvoid * pointer)) +SDL_PROC_UNUSED(GLboolean, glIsEnabled, (GLenum cap)) +SDL_PROC_UNUSED(GLboolean, glIsList, (GLuint list)) +SDL_PROC_UNUSED(GLboolean, glIsTexture, (GLuint texture)) +SDL_PROC_UNUSED(void, glLightModelf, (GLenum pname, GLfloat param)) +SDL_PROC_UNUSED(void, glLightModelfv, (GLenum pname, const GLfloat * params)) +SDL_PROC_UNUSED(void, glLightModeli, (GLenum pname, GLint param)) +SDL_PROC_UNUSED(void, glLightModeliv, (GLenum pname, const GLint * params)) +SDL_PROC_UNUSED(void, glLightf, (GLenum light, GLenum pname, GLfloat param)) +SDL_PROC_UNUSED(void, glLightfv, + (GLenum light, GLenum pname, const GLfloat * params)) +SDL_PROC_UNUSED(void, glLighti, (GLenum light, GLenum pname, GLint param)) +SDL_PROC_UNUSED(void, glLightiv, + (GLenum light, GLenum pname, const GLint * params)) +SDL_PROC_UNUSED(void, glLineStipple, (GLint factor, GLushort pattern)) +SDL_PROC_UNUSED(void, glLineWidth, (GLfloat width)) +SDL_PROC_UNUSED(void, glListBase, (GLuint base)) +SDL_PROC(void, glLoadIdentity, (void)) +SDL_PROC_UNUSED(void, glLoadMatrixd, (const GLdouble * m)) +SDL_PROC_UNUSED(void, glLoadMatrixf, (const GLfloat * m)) +SDL_PROC_UNUSED(void, glLoadName, (GLuint name)) +SDL_PROC_UNUSED(void, glLogicOp, (GLenum opcode)) +SDL_PROC_UNUSED(void, glMap1d, + (GLenum target, GLdouble u1, GLdouble u2, GLint stride, + GLint order, const GLdouble * points)) +SDL_PROC_UNUSED(void, glMap1f, + (GLenum target, GLfloat u1, GLfloat u2, GLint stride, + GLint order, const GLfloat * points)) +SDL_PROC_UNUSED(void, glMap2d, + (GLenum target, GLdouble u1, GLdouble u2, GLint ustride, + GLint uorder, GLdouble v1, GLdouble v2, GLint vstride, + GLint vorder, const GLdouble * points)) +SDL_PROC_UNUSED(void, glMap2f, + (GLenum target, GLfloat u1, GLfloat u2, GLint ustride, + GLint uorder, GLfloat v1, GLfloat v2, GLint vstride, + GLint vorder, const GLfloat * points)) +SDL_PROC_UNUSED(void, glMapGrid1d, (GLint un, GLdouble u1, GLdouble u2)) +SDL_PROC_UNUSED(void, glMapGrid1f, (GLint un, GLfloat u1, GLfloat u2)) +SDL_PROC_UNUSED(void, glMapGrid2d, + (GLint un, GLdouble u1, GLdouble u2, GLint vn, GLdouble v1, + GLdouble v2)) +SDL_PROC_UNUSED(void, glMapGrid2f, + (GLint un, GLfloat u1, GLfloat u2, GLint vn, GLfloat v1, + GLfloat v2)) +SDL_PROC_UNUSED(void, glMaterialf, (GLenum face, GLenum pname, GLfloat param)) +SDL_PROC_UNUSED(void, glMaterialfv, + (GLenum face, GLenum pname, const GLfloat * params)) +SDL_PROC_UNUSED(void, glMateriali, (GLenum face, GLenum pname, GLint param)) +SDL_PROC_UNUSED(void, glMaterialiv, + (GLenum face, GLenum pname, const GLint * params)) +SDL_PROC(void, glMatrixMode, (GLenum mode)) +SDL_PROC_UNUSED(void, glMultMatrixd, (const GLdouble * m)) +SDL_PROC_UNUSED(void, glMultMatrixf, (const GLfloat * m)) +SDL_PROC_UNUSED(void, glNewList, (GLuint list, GLenum mode)) +SDL_PROC_UNUSED(void, glNormal3b, (GLbyte nx, GLbyte ny, GLbyte nz)) +SDL_PROC_UNUSED(void, glNormal3bv, (const GLbyte * v)) +SDL_PROC_UNUSED(void, glNormal3d, (GLdouble nx, GLdouble ny, GLdouble nz)) +SDL_PROC_UNUSED(void, glNormal3dv, (const GLdouble * v)) +SDL_PROC_UNUSED(void, glNormal3f, (GLfloat nx, GLfloat ny, GLfloat nz)) +SDL_PROC_UNUSED(void, glNormal3fv, (const GLfloat * v)) +SDL_PROC_UNUSED(void, glNormal3i, (GLint nx, GLint ny, GLint nz)) +SDL_PROC_UNUSED(void, glNormal3iv, (const GLint * v)) +SDL_PROC_UNUSED(void, glNormal3s, (GLshort nx, GLshort ny, GLshort nz)) +SDL_PROC_UNUSED(void, glNormal3sv, (const GLshort * v)) +SDL_PROC_UNUSED(void, glNormalPointer, + (GLenum type, GLsizei stride, const GLvoid * pointer)) +SDL_PROC(void, glOrtho, + (GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, + GLdouble zNear, GLdouble zFar)) +SDL_PROC_UNUSED(void, glPassThrough, (GLfloat token)) +SDL_PROC_UNUSED(void, glPixelMapfv, + (GLenum map, GLsizei mapsize, const GLfloat * values)) +SDL_PROC_UNUSED(void, glPixelMapuiv, + (GLenum map, GLsizei mapsize, const GLuint * values)) +SDL_PROC_UNUSED(void, glPixelMapusv, + (GLenum map, GLsizei mapsize, const GLushort * values)) +SDL_PROC_UNUSED(void, glPixelStoref, (GLenum pname, GLfloat param)) +SDL_PROC(void, glPixelStorei, (GLenum pname, GLint param)) +SDL_PROC_UNUSED(void, glPixelTransferf, (GLenum pname, GLfloat param)) +SDL_PROC_UNUSED(void, glPixelTransferi, (GLenum pname, GLint param)) +SDL_PROC_UNUSED(void, glPixelZoom, (GLfloat xfactor, GLfloat yfactor)) +SDL_PROC_UNUSED(void, glPointSize, (GLfloat size)) +SDL_PROC_UNUSED(void, glPolygonMode, (GLenum face, GLenum mode)) +SDL_PROC_UNUSED(void, glPolygonOffset, (GLfloat factor, GLfloat units)) +SDL_PROC_UNUSED(void, glPolygonStipple, (const GLubyte * mask)) +SDL_PROC(void, glPopAttrib, (void)) +SDL_PROC(void, glPopClientAttrib, (void)) +SDL_PROC(void, glPopMatrix, (void)) +SDL_PROC_UNUSED(void, glPopName, (void)) +SDL_PROC_UNUSED(void, glPrioritizeTextures, + (GLsizei n, const GLuint * textures, + const GLclampf * priorities)) +SDL_PROC(void, glPushAttrib, (GLbitfield mask)) +SDL_PROC(void, glPushClientAttrib, (GLbitfield mask)) +SDL_PROC(void, glPushMatrix, (void)) +SDL_PROC_UNUSED(void, glPushName, (GLuint name)) +SDL_PROC_UNUSED(void, glRasterPos2d, (GLdouble x, GLdouble y)) +SDL_PROC_UNUSED(void, glRasterPos2dv, (const GLdouble * v)) +SDL_PROC_UNUSED(void, glRasterPos2f, (GLfloat x, GLfloat y)) +SDL_PROC_UNUSED(void, glRasterPos2fv, (const GLfloat * v)) +SDL_PROC_UNUSED(void, glRasterPos2i, (GLint x, GLint y)) +SDL_PROC_UNUSED(void, glRasterPos2iv, (const GLint * v)) +SDL_PROC_UNUSED(void, glRasterPos2s, (GLshort x, GLshort y)) +SDL_PROC_UNUSED(void, glRasterPos2sv, (const GLshort * v)) +SDL_PROC_UNUSED(void, glRasterPos3d, (GLdouble x, GLdouble y, GLdouble z)) +SDL_PROC_UNUSED(void, glRasterPos3dv, (const GLdouble * v)) +SDL_PROC_UNUSED(void, glRasterPos3f, (GLfloat x, GLfloat y, GLfloat z)) +SDL_PROC_UNUSED(void, glRasterPos3fv, (const GLfloat * v)) +SDL_PROC_UNUSED(void, glRasterPos3i, (GLint x, GLint y, GLint z)) +SDL_PROC_UNUSED(void, glRasterPos3iv, (const GLint * v)) +SDL_PROC_UNUSED(void, glRasterPos3s, (GLshort x, GLshort y, GLshort z)) +SDL_PROC_UNUSED(void, glRasterPos3sv, (const GLshort * v)) +SDL_PROC_UNUSED(void, glRasterPos4d, + (GLdouble x, GLdouble y, GLdouble z, GLdouble w)) +SDL_PROC_UNUSED(void, glRasterPos4dv, (const GLdouble * v)) +SDL_PROC_UNUSED(void, glRasterPos4f, + (GLfloat x, GLfloat y, GLfloat z, GLfloat w)) +SDL_PROC_UNUSED(void, glRasterPos4fv, (const GLfloat * v)) +SDL_PROC_UNUSED(void, glRasterPos4i, (GLint x, GLint y, GLint z, GLint w)) +SDL_PROC_UNUSED(void, glRasterPos4iv, (const GLint * v)) +SDL_PROC_UNUSED(void, glRasterPos4s, + (GLshort x, GLshort y, GLshort z, GLshort w)) +SDL_PROC_UNUSED(void, glRasterPos4sv, (const GLshort * v)) +SDL_PROC_UNUSED(void, glReadBuffer, (GLenum mode)) +SDL_PROC(void, glReadPixels, + (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, + GLenum type, GLvoid * pixels)) +SDL_PROC_UNUSED(void, glRectd, + (GLdouble x1, GLdouble y1, GLdouble x2, GLdouble y2)) +SDL_PROC_UNUSED(void, glRectdv, (const GLdouble * v1, const GLdouble * v2)) +SDL_PROC_UNUSED(void, glRectf, + (GLfloat x1, GLfloat y1, GLfloat x2, GLfloat y2)) +SDL_PROC_UNUSED(void, glRectfv, (const GLfloat * v1, const GLfloat * v2)) +SDL_PROC_UNUSED(void, glRecti, (GLint x1, GLint y1, GLint x2, GLint y2)) +SDL_PROC_UNUSED(void, glRectiv, (const GLint * v1, const GLint * v2)) +SDL_PROC_UNUSED(void, glRects, + (GLshort x1, GLshort y1, GLshort x2, GLshort y2)) +SDL_PROC_UNUSED(void, glRectsv, (const GLshort * v1, const GLshort * v2)) +SDL_PROC_UNUSED(GLint, glRenderMode, (GLenum mode)) +SDL_PROC_UNUSED(void, glRotated, + (GLdouble angle, GLdouble x, GLdouble y, GLdouble z)) +SDL_PROC_UNUSED(void, glRotatef, + (GLfloat angle, GLfloat x, GLfloat y, GLfloat z)) +SDL_PROC_UNUSED(void, glScaled, (GLdouble x, GLdouble y, GLdouble z)) +SDL_PROC_UNUSED(void, glScalef, (GLfloat x, GLfloat y, GLfloat z)) +SDL_PROC_UNUSED(void, glScissor, + (GLint x, GLint y, GLsizei width, GLsizei height)) +SDL_PROC_UNUSED(void, glSelectBuffer, (GLsizei size, GLuint * buffer)) +SDL_PROC_UNUSED(void, glShadeModel, (GLenum mode)) +SDL_PROC_UNUSED(void, glStencilFunc, (GLenum func, GLint ref, GLuint mask)) +SDL_PROC_UNUSED(void, glStencilMask, (GLuint mask)) +SDL_PROC_UNUSED(void, glStencilOp, (GLenum fail, GLenum zfail, GLenum zpass)) +SDL_PROC_UNUSED(void, glTexCoord1d, (GLdouble s)) +SDL_PROC_UNUSED(void, glTexCoord1dv, (const GLdouble * v)) +SDL_PROC_UNUSED(void, glTexCoord1f, (GLfloat s)) +SDL_PROC_UNUSED(void, glTexCoord1fv, (const GLfloat * v)) +SDL_PROC_UNUSED(void, glTexCoord1i, (GLint s)) +SDL_PROC_UNUSED(void, glTexCoord1iv, (const GLint * v)) +SDL_PROC_UNUSED(void, glTexCoord1s, (GLshort s)) +SDL_PROC_UNUSED(void, glTexCoord1sv, (const GLshort * v)) +SDL_PROC_UNUSED(void, glTexCoord2d, (GLdouble s, GLdouble t)) +SDL_PROC_UNUSED(void, glTexCoord2dv, (const GLdouble * v)) +SDL_PROC(void, glTexCoord2f, (GLfloat s, GLfloat t)) +SDL_PROC_UNUSED(void, glTexCoord2fv, (const GLfloat * v)) +SDL_PROC_UNUSED(void, glTexCoord2i, (GLint s, GLint t)) +SDL_PROC_UNUSED(void, glTexCoord2iv, (const GLint * v)) +SDL_PROC_UNUSED(void, glTexCoord2s, (GLshort s, GLshort t)) +SDL_PROC_UNUSED(void, glTexCoord2sv, (const GLshort * v)) +SDL_PROC_UNUSED(void, glTexCoord3d, (GLdouble s, GLdouble t, GLdouble r)) +SDL_PROC_UNUSED(void, glTexCoord3dv, (const GLdouble * v)) +SDL_PROC_UNUSED(void, glTexCoord3f, (GLfloat s, GLfloat t, GLfloat r)) +SDL_PROC_UNUSED(void, glTexCoord3fv, (const GLfloat * v)) +SDL_PROC_UNUSED(void, glTexCoord3i, (GLint s, GLint t, GLint r)) +SDL_PROC_UNUSED(void, glTexCoord3iv, (const GLint * v)) +SDL_PROC_UNUSED(void, glTexCoord3s, (GLshort s, GLshort t, GLshort r)) +SDL_PROC_UNUSED(void, glTexCoord3sv, (const GLshort * v)) +SDL_PROC_UNUSED(void, glTexCoord4d, + (GLdouble s, GLdouble t, GLdouble r, GLdouble q)) +SDL_PROC_UNUSED(void, glTexCoord4dv, (const GLdouble * v)) +SDL_PROC_UNUSED(void, glTexCoord4f, + (GLfloat s, GLfloat t, GLfloat r, GLfloat q)) +SDL_PROC_UNUSED(void, glTexCoord4fv, (const GLfloat * v)) +SDL_PROC_UNUSED(void, glTexCoord4i, (GLint s, GLint t, GLint r, GLint q)) +SDL_PROC_UNUSED(void, glTexCoord4iv, (const GLint * v)) +SDL_PROC_UNUSED(void, glTexCoord4s, + (GLshort s, GLshort t, GLshort r, GLshort q)) +SDL_PROC_UNUSED(void, glTexCoord4sv, (const GLshort * v)) +SDL_PROC_UNUSED(void, glTexCoordPointer, + (GLint size, GLenum type, GLsizei stride, + const GLvoid * pointer)) +SDL_PROC(void, glTexEnvf, (GLenum target, GLenum pname, GLfloat param)) +SDL_PROC_UNUSED(void, glTexEnvfv, + (GLenum target, GLenum pname, const GLfloat * params)) +SDL_PROC_UNUSED(void, glTexEnvi, (GLenum target, GLenum pname, GLint param)) +SDL_PROC_UNUSED(void, glTexEnviv, + (GLenum target, GLenum pname, const GLint * params)) +SDL_PROC_UNUSED(void, glTexGend, (GLenum coord, GLenum pname, GLdouble param)) +SDL_PROC_UNUSED(void, glTexGendv, + (GLenum coord, GLenum pname, const GLdouble * params)) +SDL_PROC_UNUSED(void, glTexGenf, (GLenum coord, GLenum pname, GLfloat param)) +SDL_PROC_UNUSED(void, glTexGenfv, + (GLenum coord, GLenum pname, const GLfloat * params)) +SDL_PROC_UNUSED(void, glTexGeni, (GLenum coord, GLenum pname, GLint param)) +SDL_PROC_UNUSED(void, glTexGeniv, + (GLenum coord, GLenum pname, const GLint * params)) +SDL_PROC_UNUSED(void, glTexImage1D, + (GLenum target, GLint level, GLint internalformat, + GLsizei width, GLint border, GLenum format, GLenum type, + const GLvoid * pixels)) +SDL_PROC(void, glTexImage2D, + (GLenum target, GLint level, GLint internalformat, GLsizei width, + GLsizei height, GLint border, GLenum format, GLenum type, + const GLvoid * pixels)) +SDL_PROC_UNUSED(void, glTexParameterf, + (GLenum target, GLenum pname, GLfloat param)) +SDL_PROC_UNUSED(void, glTexParameterfv, + (GLenum target, GLenum pname, const GLfloat * params)) +SDL_PROC(void, glTexParameteri, (GLenum target, GLenum pname, GLint param)) +SDL_PROC_UNUSED(void, glTexParameteriv, + (GLenum target, GLenum pname, const GLint * params)) +SDL_PROC_UNUSED(void, glTexSubImage1D, + (GLenum target, GLint level, GLint xoffset, GLsizei width, + GLenum format, GLenum type, const GLvoid * pixels)) +SDL_PROC(void, glTexSubImage2D, + (GLenum target, GLint level, GLint xoffset, GLint yoffset, + GLsizei width, GLsizei height, GLenum format, GLenum type, + const GLvoid * pixels)) +SDL_PROC(void, glTranslated, (GLdouble x, GLdouble y, GLdouble z)) +SDL_PROC_UNUSED(void, glTranslatef, (GLfloat x, GLfloat y, GLfloat z)) +SDL_PROC_UNUSED(void, glVertex2d, (GLdouble x, GLdouble y)) +SDL_PROC_UNUSED(void, glVertex2dv, (const GLdouble * v)) +SDL_PROC_UNUSED(void, glVertex2f, (GLfloat x, GLfloat y)) +SDL_PROC_UNUSED(void, glVertex2fv, (const GLfloat * v)) +SDL_PROC(void, glVertex2i, (GLint x, GLint y)) +SDL_PROC_UNUSED(void, glVertex2iv, (const GLint * v)) +SDL_PROC_UNUSED(void, glVertex2s, (GLshort x, GLshort y)) +SDL_PROC_UNUSED(void, glVertex2sv, (const GLshort * v)) +SDL_PROC_UNUSED(void, glVertex3d, (GLdouble x, GLdouble y, GLdouble z)) +SDL_PROC_UNUSED(void, glVertex3dv, (const GLdouble * v)) +SDL_PROC_UNUSED(void, glVertex3f, (GLfloat x, GLfloat y, GLfloat z)) +SDL_PROC_UNUSED(void, glVertex3fv, (const GLfloat * v)) +SDL_PROC_UNUSED(void, glVertex3i, (GLint x, GLint y, GLint z)) +SDL_PROC_UNUSED(void, glVertex3iv, (const GLint * v)) +SDL_PROC_UNUSED(void, glVertex3s, (GLshort x, GLshort y, GLshort z)) +SDL_PROC_UNUSED(void, glVertex3sv, (const GLshort * v)) +SDL_PROC_UNUSED(void, glVertex4d, + (GLdouble x, GLdouble y, GLdouble z, GLdouble w)) +SDL_PROC_UNUSED(void, glVertex4dv, (const GLdouble * v)) +SDL_PROC_UNUSED(void, glVertex4f, + (GLfloat x, GLfloat y, GLfloat z, GLfloat w)) +SDL_PROC_UNUSED(void, glVertex4fv, (const GLfloat * v)) +SDL_PROC_UNUSED(void, glVertex4i, (GLint x, GLint y, GLint z, GLint w)) +SDL_PROC_UNUSED(void, glVertex4iv, (const GLint * v)) +SDL_PROC_UNUSED(void, glVertex4s, + (GLshort x, GLshort y, GLshort z, GLshort w)) +SDL_PROC_UNUSED(void, glVertex4sv, (const GLshort * v)) +SDL_PROC_UNUSED(void, glVertexPointer, + (GLint size, GLenum type, GLsizei stride, + const GLvoid * pointer)) +SDL_PROC(void, glViewport, (GLint x, GLint y, GLsizei width, GLsizei height)) +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/SDL_leaks.h b/src/video/SDL_leaks.h index 5151646fd..be400ee7f 100644 --- a/src/video/SDL_leaks.h +++ b/src/video/SDL_leaks.h @@ -29,3 +29,4 @@ #ifdef CHECK_LEAKS extern int surfaces_allocated; #endif +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/SDL_pixels.c b/src/video/SDL_pixels.c index 9b8a1257e..839a3eca9 100644 --- a/src/video/SDL_pixels.c +++ b/src/video/SDL_pixels.c @@ -31,591 +31,804 @@ #include "SDL_RLEaccel_c.h" /* Helper functions */ + +SDL_bool +SDL_PixelFormatEnumToMasks(Uint32 format, int *bpp, Uint32 * Rmask, + Uint32 * Gmask, Uint32 * Bmask, Uint32 * Amask) +{ + Uint32 masks[4]; + + /* Initialize the values here */ + if (SDL_BITSPERPIXEL(format) == 24) { + *bpp = SDL_BYTESPERPIXEL(format) * 8; + } else { + *bpp = SDL_BITSPERPIXEL(format); + } + *Rmask = *Gmask = *Bmask = *Amask = 0; + + if (SDL_PIXELTYPE(format) != SDL_PixelType_Packed8 && + SDL_PIXELTYPE(format) != SDL_PixelType_Packed16 && + SDL_PIXELTYPE(format) != SDL_PixelType_Packed32) { + /* Not a format that uses masks */ + return SDL_TRUE; + } + + switch (SDL_PIXELLAYOUT(format)) { + case SDL_PackedLayout_332: + masks[0] = 0x00000000; + masks[1] = 0x000000E0; + masks[2] = 0x0000001C; + masks[3] = 0x00000003; + break; + case SDL_PackedLayout_4444: + masks[0] = 0x0000F000; + masks[1] = 0x00000F00; + masks[2] = 0x000000F0; + masks[3] = 0x0000000F; + break; + case SDL_PackedLayout_1555: + masks[0] = 0x00008000; + masks[1] = 0x00007C00; + masks[2] = 0x000003E0; + masks[3] = 0x0000001F; + break; + case SDL_PackedLayout_565: + masks[0] = 0x00000000; + masks[1] = 0x0000F800; + masks[2] = 0x000007E0; + masks[3] = 0x0000001F; + break; + case SDL_PackedLayout_8888: + masks[0] = 0xFF000000; + masks[1] = 0x00FF0000; + masks[2] = 0x0000FF00; + masks[3] = 0x000000FF; + break; + case SDL_PackedLayout_2101010: + masks[0] = 0xC0000000; + masks[1] = 0x3FF00000; + masks[2] = 0x000FFC00; + masks[3] = 0x000003FF; + break; + default: + /* Unknown layout */ + return SDL_FALSE; + } + + switch (SDL_PIXELORDER(format)) { + case SDL_PackedOrder_XRGB: + *Rmask = masks[1]; + *Gmask = masks[2]; + *Bmask = masks[3]; + break; + case SDL_PackedOrder_RGBX: + *Rmask = masks[0]; + *Gmask = masks[1]; + *Bmask = masks[2]; + break; + case SDL_PackedOrder_ARGB: + *Amask = masks[0]; + *Rmask = masks[1]; + *Gmask = masks[2]; + *Bmask = masks[3]; + break; + case SDL_PackedOrder_RGBA: + *Rmask = masks[0]; + *Gmask = masks[1]; + *Bmask = masks[2]; + *Amask = masks[3]; + break; + case SDL_PackedOrder_XBGR: + *Bmask = masks[1]; + *Gmask = masks[2]; + *Rmask = masks[3]; + break; + case SDL_PackedOrder_BGRX: + *Bmask = masks[0]; + *Gmask = masks[1]; + *Rmask = masks[2]; + break; + case SDL_PackedOrder_BGRA: + *Bmask = masks[0]; + *Gmask = masks[1]; + *Rmask = masks[2]; + *Amask = masks[3]; + break; + case SDL_PackedOrder_ABGR: + *Amask = masks[0]; + *Bmask = masks[1]; + *Gmask = masks[2]; + *Rmask = masks[3]; + break; + default: + /* Unknown order */ + return SDL_FALSE; + } + return SDL_TRUE; +} + +Uint32 +SDL_MasksToPixelFormatEnum(int bpp, Uint32 Rmask, Uint32 Gmask, Uint32 Bmask, + Uint32 Amask) +{ + switch (bpp) { + case 8: + switch (Rmask) { + case 0: + return SDL_PixelFormat_Index8; + case 0xE0: + return SDL_PixelFormat_RGB332; + } + break; + case 12: + switch (Rmask) { + case 0x0F00: + return SDL_PixelFormat_RGB444; + } + break; + case 15: + switch (Rmask) { + case 0x7C00: + return SDL_PixelFormat_RGB555; + } + break; + case 16: + switch (Rmask) { + case 0x0F00: + return SDL_PixelFormat_ARGB4444; + case 0x7C00: + return SDL_PixelFormat_ARGB1555; + case 0xF800: + return SDL_PixelFormat_RGB565; + } + break; + case 32: + switch (Rmask) { + case 0xFF000000: + if (Amask == 0x000000FF) { + return SDL_PixelFormat_RGBA8888; + } + break; + case 0x00FF0000: + if (Amask == 0xFF000000) { + return SDL_PixelFormat_ARGB8888; + } else { + return SDL_PixelFormat_RGB888; + } + break; + case 0x0000FF00: + if (Amask == 0x000000FF) { + return SDL_PixelFormat_BGRA8888; + } + break; + case 0x000000FF: + if (Amask == 0xFF000000) { + return SDL_PixelFormat_ABGR8888; + } else { + return SDL_PixelFormat_BGR888; + } + break; + case 0x3FF00000: + return SDL_PixelFormat_ARGB2101010; + } + } + return SDL_PixelFormat_Unknown; +} + + +SDL_Palette * +SDL_AllocPalette(int ncolors) +{ + SDL_Palette *palette; + + palette = (SDL_Palette *) SDL_malloc(sizeof(*palette)); + if (!palette) { + SDL_OutOfMemory(); + return NULL; + } + palette->colors = + (SDL_Color *) SDL_malloc(ncolors * sizeof(*palette->colors)); + if (!palette->colors) { + SDL_free(palette); + return NULL; + } + palette->ncolors = ncolors; + palette->watch = NULL; + palette->refcount = 1; + + SDL_memset(palette->colors, 0xFF, ncolors * sizeof(*palette->colors)); + + return palette; +} + +int +SDL_AddPaletteWatch(SDL_Palette * palette, SDL_PaletteChangedFunc callback, + void *userdata) +{ + SDL_PaletteWatch *watch; + + if (!palette) { + return -1; + } + + watch = (SDL_PaletteWatch *) SDL_malloc(sizeof(*watch)); + if (!watch) { + SDL_OutOfMemory(); + return -1; + } + + watch->callback = callback; + watch->userdata = userdata; + watch->next = palette->watch; + palette->watch = watch; + ++palette->refcount; + return 0; +} + +void +SDL_DelPaletteWatch(SDL_Palette * palette, SDL_PaletteChangedFunc callback, + void *userdata) +{ + SDL_PaletteWatch *prev, *watch; + + if (!palette) { + return; + } + + for (prev = NULL, watch = palette->watch; watch; + prev = watch, watch = watch->next) { + if (watch->callback == callback && watch->userdata == userdata) { + if (prev) { + prev->next = watch->next; + } else { + palette->watch = watch->next; + } + SDL_free(watch); + SDL_FreePalette(palette); + return; + } + } +} + +int +SDL_SetPaletteColors(SDL_Palette * palette, const SDL_Color * colors, + int firstcolor, int ncolors) +{ + SDL_PaletteWatch *watch; + int status = 0; + + /* Verify the parameters */ + if (!palette) { + return -1; + } + if (ncolors > (palette->ncolors - firstcolor)) { + ncolors = (palette->ncolors - firstcolor); + status = -1; + } + + if (colors != (palette->colors + firstcolor)) { + SDL_memcpy(palette->colors + firstcolor, colors, + ncolors * sizeof(*colors)); + } + + for (watch = palette->watch; watch; watch = watch->next) { + if (watch->callback(watch->userdata, palette) < 0) { + status = -1; + } + } + + return status; +} + +void +SDL_FreePalette(SDL_Palette * palette) +{ + if (!palette) { + return; + } + if (--palette->refcount > 0) { + return; + } + if (palette->colors) { + SDL_free(palette->colors); + } + SDL_free(palette); +} + /* * Allocate a pixel format structure and fill it according to the given info. */ -SDL_PixelFormat *SDL_AllocFormat(int bpp, - Uint32 Rmask, Uint32 Gmask, Uint32 Bmask, Uint32 Amask) +SDL_PixelFormat * +SDL_AllocFormat(int bpp, + Uint32 Rmask, Uint32 Gmask, Uint32 Bmask, Uint32 Amask) { - SDL_PixelFormat *format; - Uint32 mask; - - /* Allocate an empty pixel format structure */ - format = SDL_malloc(sizeof(*format)); - if ( format == NULL ) { - SDL_OutOfMemory(); - return(NULL); - } - SDL_memset(format, 0, sizeof(*format)); - format->alpha = SDL_ALPHA_OPAQUE; - - /* Set up the format */ - format->BitsPerPixel = bpp; - format->BytesPerPixel = (bpp+7)/8; - if ( Rmask || Bmask || Gmask ) { /* Packed pixels with custom mask */ - format->palette = NULL; - format->Rshift = 0; - format->Rloss = 8; - if ( Rmask ) { - for ( mask = Rmask; !(mask&0x01); mask >>= 1 ) - ++format->Rshift; - for ( ; (mask&0x01); mask >>= 1 ) - --format->Rloss; - } - format->Gshift = 0; - format->Gloss = 8; - if ( Gmask ) { - for ( mask = Gmask; !(mask&0x01); mask >>= 1 ) - ++format->Gshift; - for ( ; (mask&0x01); mask >>= 1 ) - --format->Gloss; - } - format->Bshift = 0; - format->Bloss = 8; - if ( Bmask ) { - for ( mask = Bmask; !(mask&0x01); mask >>= 1 ) - ++format->Bshift; - for ( ; (mask&0x01); mask >>= 1 ) - --format->Bloss; - } - format->Ashift = 0; - format->Aloss = 8; - if ( Amask ) { - for ( mask = Amask; !(mask&0x01); mask >>= 1 ) - ++format->Ashift; - for ( ; (mask&0x01); mask >>= 1 ) - --format->Aloss; - } - format->Rmask = Rmask; - format->Gmask = Gmask; - format->Bmask = Bmask; - format->Amask = Amask; - } else if ( bpp > 8 ) { /* Packed pixels with standard mask */ - /* R-G-B */ - if ( bpp > 24 ) - bpp = 24; - format->Rloss = 8-(bpp/3); - format->Gloss = 8-(bpp/3)-(bpp%3); - format->Bloss = 8-(bpp/3); - format->Rshift = ((bpp/3)+(bpp%3))+(bpp/3); - format->Gshift = (bpp/3); - format->Bshift = 0; - format->Rmask = ((0xFF>>format->Rloss)<Rshift); - format->Gmask = ((0xFF>>format->Gloss)<Gshift); - format->Bmask = ((0xFF>>format->Bloss)<Bshift); - } else { - /* Palettized formats have no mask info */ - format->Rloss = 8; - format->Gloss = 8; - format->Bloss = 8; - format->Aloss = 8; - format->Rshift = 0; - format->Gshift = 0; - format->Bshift = 0; - format->Ashift = 0; - format->Rmask = 0; - format->Gmask = 0; - format->Bmask = 0; - format->Amask = 0; - } - if ( bpp <= 8 ) { /* Palettized mode */ - int ncolors = 1<palette = (SDL_Palette *)SDL_malloc(sizeof(SDL_Palette)); - if ( format->palette == NULL ) { - SDL_FreeFormat(format); - SDL_OutOfMemory(); - return(NULL); - } - (format->palette)->ncolors = ncolors; - (format->palette)->colors = (SDL_Color *)SDL_malloc( - (format->palette)->ncolors*sizeof(SDL_Color)); - if ( (format->palette)->colors == NULL ) { - SDL_FreeFormat(format); - SDL_OutOfMemory(); - return(NULL); - } - if ( Rmask || Bmask || Gmask ) { - /* create palette according to masks */ - int i; - int Rm=0,Gm=0,Bm=0; - int Rw=0,Gw=0,Bw=0; -#ifdef ENABLE_PALETTE_ALPHA - int Am=0,Aw=0; -#endif - if(Rmask) - { - Rw=8-format->Rloss; - for(i=format->Rloss;i>0;i-=Rw) - Rm|=1<Gloss; - for(i=format->Gloss;i>0;i-=Gw) - Gm|=1<Bloss; - for(i=format->Bloss;i>0;i-=Bw) - Bm|=1<Aloss; - for(i=format->Aloss;i>0;i-=Aw) - Am|=1<>format->Rshift; - r=(r<Rloss)|((r*Rm)>>Rw); - format->palette->colors[i].r=r; - - g=(i&Gmask)>>format->Gshift; - g=(g<Gloss)|((g*Gm)>>Gw); - format->palette->colors[i].g=g; - - b=(i&Bmask)>>format->Bshift; - b=(b<Bloss)|((b*Bm)>>Bw); - format->palette->colors[i].b=b; - -#ifdef ENABLE_PALETTE_ALPHA - a=(i&Amask)>>format->Ashift; - a=(a<Aloss)|((a*Am)>>Aw); - format->palette->colors[i].unused=a; -#else - format->palette->colors[i].unused=0; -#endif - } - } else if ( ncolors == 2 ) { - /* Create a black and white bitmap palette */ - format->palette->colors[0].r = 0xFF; - format->palette->colors[0].g = 0xFF; - format->palette->colors[0].b = 0xFF; - format->palette->colors[1].r = 0x00; - format->palette->colors[1].g = 0x00; - format->palette->colors[1].b = 0x00; - } else { - /* Create an empty palette */ - SDL_memset((format->palette)->colors, 0, - (format->palette)->ncolors*sizeof(SDL_Color)); - } - } - return(format); -} -SDL_PixelFormat *SDL_ReallocFormat(SDL_Surface *surface, int bpp, - Uint32 Rmask, Uint32 Gmask, Uint32 Bmask, Uint32 Amask) -{ - if ( surface->format ) { - SDL_FreeFormat(surface->format); - SDL_FormatChanged(surface); - } - surface->format = SDL_AllocFormat(bpp, Rmask, Gmask, Bmask, Amask); - return surface->format; + SDL_PixelFormat *format; + Uint32 mask; + + /* Allocate an empty pixel format structure */ + format = SDL_malloc(sizeof(*format)); + if (format == NULL) { + SDL_OutOfMemory(); + return (NULL); + } + SDL_memset(format, 0, sizeof(*format)); + format->alpha = SDL_ALPHA_OPAQUE; + + /* Set up the format */ + format->BitsPerPixel = bpp; + format->BytesPerPixel = (bpp + 7) / 8; + if (Rmask || Bmask || Gmask) { /* Packed pixels with custom mask */ + format->Rshift = 0; + format->Rloss = 8; + if (Rmask) { + for (mask = Rmask; !(mask & 0x01); mask >>= 1) + ++format->Rshift; + for (; (mask & 0x01); mask >>= 1) + --format->Rloss; + } + format->Gshift = 0; + format->Gloss = 8; + if (Gmask) { + for (mask = Gmask; !(mask & 0x01); mask >>= 1) + ++format->Gshift; + for (; (mask & 0x01); mask >>= 1) + --format->Gloss; + } + format->Bshift = 0; + format->Bloss = 8; + if (Bmask) { + for (mask = Bmask; !(mask & 0x01); mask >>= 1) + ++format->Bshift; + for (; (mask & 0x01); mask >>= 1) + --format->Bloss; + } + format->Ashift = 0; + format->Aloss = 8; + if (Amask) { + for (mask = Amask; !(mask & 0x01); mask >>= 1) + ++format->Ashift; + for (; (mask & 0x01); mask >>= 1) + --format->Aloss; + } + format->Rmask = Rmask; + format->Gmask = Gmask; + format->Bmask = Bmask; + format->Amask = Amask; + } else if (bpp > 8) { /* Packed pixels with standard mask */ + /* R-G-B */ + if (bpp > 24) + bpp = 24; + format->Rloss = 8 - (bpp / 3); + format->Gloss = 8 - (bpp / 3) - (bpp % 3); + format->Bloss = 8 - (bpp / 3); + format->Rshift = ((bpp / 3) + (bpp % 3)) + (bpp / 3); + format->Gshift = (bpp / 3); + format->Bshift = 0; + format->Rmask = ((0xFF >> format->Rloss) << format->Rshift); + format->Gmask = ((0xFF >> format->Gloss) << format->Gshift); + format->Bmask = ((0xFF >> format->Bloss) << format->Bshift); + } else { + /* Palettized formats have no mask info */ + format->Rloss = 8; + format->Gloss = 8; + format->Bloss = 8; + format->Aloss = 8; + format->Rshift = 0; + format->Gshift = 0; + format->Bshift = 0; + format->Ashift = 0; + format->Rmask = 0; + format->Gmask = 0; + format->Bmask = 0; + format->Amask = 0; + } + format->palette = NULL; + + return (format); } /* * Change any previous mappings from/to the new surface format */ -void SDL_FormatChanged(SDL_Surface *surface) +void +SDL_FormatChanged(SDL_Surface * surface) { - static int format_version = 0; - ++format_version; - if ( format_version < 0 ) { /* It wrapped... */ - format_version = 1; - } - surface->format_version = format_version; - SDL_InvalidateMap(surface->map); + static int format_version = 0; + ++format_version; + if (format_version < 0) { /* It wrapped... */ + format_version = 1; + } + surface->format_version = format_version; + SDL_InvalidateMap(surface->map); } + /* * Free a previously allocated format structure */ -void SDL_FreeFormat(SDL_PixelFormat *format) +void +SDL_FreeFormat(SDL_PixelFormat * format) { - if ( format ) { - if ( format->palette ) { - if ( format->palette->colors ) { - SDL_free(format->palette->colors); - } - SDL_free(format->palette); - } - SDL_free(format); - } + if (!format) { + return; + } + SDL_free(format); } + /* * Calculate an 8-bit (3 red, 3 green, 2 blue) dithered palette of colors */ -void SDL_DitherColors(SDL_Color *colors, int bpp) +void +SDL_DitherColors(SDL_Color * colors, int bpp) { - int i; - if(bpp != 8) - return; /* only 8bpp supported right now */ - - for(i = 0; i < 256; i++) { - int r, g, b; - /* map each bit field to the full [0, 255] interval, - so 0 is mapped to (0, 0, 0) and 255 to (255, 255, 255) */ - r = i & 0xe0; - r |= r >> 3 | r >> 6; - colors[i].r = r; - g = (i << 3) & 0xe0; - g |= g >> 3 | g >> 6; - colors[i].g = g; - b = i & 0x3; - b |= b << 2; - b |= b << 4; - colors[i].b = b; - } + int i; + if (bpp != 8) + return; /* only 8bpp supported right now */ + + for (i = 0; i < 256; i++) { + int r, g, b; + /* map each bit field to the full [0, 255] interval, + so 0 is mapped to (0, 0, 0) and 255 to (255, 255, 255) */ + r = i & 0xe0; + r |= r >> 3 | r >> 6; + colors[i].r = r; + g = (i << 3) & 0xe0; + g |= g >> 3 | g >> 6; + colors[i].g = g; + b = i & 0x3; + b |= b << 2; + b |= b << 4; + colors[i].b = b; + colors[i].unused = SDL_ALPHA_OPAQUE; + } } + /* * Calculate the pad-aligned scanline width of a surface */ -Uint16 SDL_CalculatePitch(SDL_Surface *surface) +int +SDL_CalculatePitch(SDL_Surface * surface) { - Uint16 pitch; - - /* Surface should be 4-byte aligned for speed */ - pitch = surface->w*surface->format->BytesPerPixel; - switch (surface->format->BitsPerPixel) { - case 1: - pitch = (pitch+7)/8; - break; - case 4: - pitch = (pitch+1)/2; - break; - default: - break; - } - pitch = (pitch + 3) & ~3; /* 4-byte aligning */ - return(pitch); + int pitch; + + /* Surface should be 4-byte aligned for speed */ + pitch = surface->w * surface->format->BytesPerPixel; + switch (surface->format->BitsPerPixel) { + case 1: + pitch = (pitch + 7) / 8; + break; + case 4: + pitch = (pitch + 1) / 2; + break; + default: + break; + } + pitch = (pitch + 3) & ~3; /* 4-byte aligning */ + return (pitch); } + /* * Match an RGB value to a particular palette index */ -Uint8 SDL_FindColor(SDL_Palette *pal, Uint8 r, Uint8 g, Uint8 b) +Uint8 +SDL_FindColor(SDL_Palette * pal, Uint8 r, Uint8 g, Uint8 b) { - /* Do colorspace distance matching */ - unsigned int smallest; - unsigned int distance; - int rd, gd, bd; - int i; - Uint8 pixel=0; - - smallest = ~0; - for ( i=0; incolors; ++i ) { - rd = pal->colors[i].r - r; - gd = pal->colors[i].g - g; - bd = pal->colors[i].b - b; - distance = (rd*rd)+(gd*gd)+(bd*bd); - if ( distance < smallest ) { - pixel = i; - if ( distance == 0 ) { /* Perfect match! */ - break; - } - smallest = distance; - } - } - return(pixel); + /* Do colorspace distance matching */ + unsigned int smallest; + unsigned int distance; + int rd, gd, bd; + int i; + Uint8 pixel = 0; + + smallest = ~0; + for (i = 0; i < pal->ncolors; ++i) { + rd = pal->colors[i].r - r; + gd = pal->colors[i].g - g; + bd = pal->colors[i].b - b; + distance = (rd * rd) + (gd * gd) + (bd * bd); + if (distance < smallest) { + pixel = i; + if (distance == 0) { /* Perfect match! */ + break; + } + smallest = distance; + } + } + return (pixel); } /* Find the opaque pixel value corresponding to an RGB triple */ -Uint32 SDL_MapRGB(SDL_PixelFormat *format, Uint8 r, Uint8 g, Uint8 b) +Uint32 +SDL_MapRGB(SDL_PixelFormat * format, Uint8 r, Uint8 g, Uint8 b) { - if ( format->palette == NULL ) { - return (r >> format->Rloss) << format->Rshift - | (g >> format->Gloss) << format->Gshift - | (b >> format->Bloss) << format->Bshift - | format->Amask; - } else { - return SDL_FindColor(format->palette, r, g, b); - } + if (format->palette == NULL) { + return (r >> format->Rloss) << format->Rshift + | (g >> format->Gloss) << format->Gshift + | (b >> format->Bloss) << format->Bshift | format->Amask; + } else { + return SDL_FindColor(format->palette, r, g, b); + } } /* Find the pixel value corresponding to an RGBA quadruple */ -Uint32 SDL_MapRGBA(SDL_PixelFormat *format, Uint8 r, Uint8 g, Uint8 b, Uint8 a) +Uint32 +SDL_MapRGBA(SDL_PixelFormat * format, Uint8 r, Uint8 g, Uint8 b, Uint8 a) { - if ( format->palette == NULL ) { - return (r >> format->Rloss) << format->Rshift - | (g >> format->Gloss) << format->Gshift - | (b >> format->Bloss) << format->Bshift - | ((a >> format->Aloss) << format->Ashift & format->Amask); - } else { - return SDL_FindColor(format->palette, r, g, b); - } + if (format->palette == NULL) { + return (r >> format->Rloss) << format->Rshift + | (g >> format->Gloss) << format->Gshift + | (b >> format->Bloss) << format->Bshift + | ((a >> format->Aloss) << format->Ashift & format->Amask); + } else { + return SDL_FindColor(format->palette, r, g, b); + } } -void SDL_GetRGBA(Uint32 pixel, SDL_PixelFormat *fmt, - Uint8 *r, Uint8 *g, Uint8 *b, Uint8 *a) +void +SDL_GetRGBA(Uint32 pixel, SDL_PixelFormat * fmt, + Uint8 * r, Uint8 * g, Uint8 * b, Uint8 * a) { - if ( fmt->palette == NULL ) { - /* - * This makes sure that the result is mapped to the - * interval [0..255], and the maximum value for each - * component is 255. This is important to make sure - * that white is indeed reported as (255, 255, 255), - * and that opaque alpha is 255. - * This only works for RGB bit fields at least 4 bit - * wide, which is almost always the case. - */ - unsigned v; - v = (pixel & fmt->Rmask) >> fmt->Rshift; - *r = (v << fmt->Rloss) + (v >> (8 - (fmt->Rloss << 1))); - v = (pixel & fmt->Gmask) >> fmt->Gshift; - *g = (v << fmt->Gloss) + (v >> (8 - (fmt->Gloss << 1))); - v = (pixel & fmt->Bmask) >> fmt->Bshift; - *b = (v << fmt->Bloss) + (v >> (8 - (fmt->Bloss << 1))); - if(fmt->Amask) { - v = (pixel & fmt->Amask) >> fmt->Ashift; - *a = (v << fmt->Aloss) + (v >> (8 - (fmt->Aloss << 1))); - } else { - *a = SDL_ALPHA_OPAQUE; - } - } else { - *r = fmt->palette->colors[pixel].r; - *g = fmt->palette->colors[pixel].g; - *b = fmt->palette->colors[pixel].b; - *a = SDL_ALPHA_OPAQUE; - } + if (fmt->palette == NULL) { + /* + * This makes sure that the result is mapped to the + * interval [0..255], and the maximum value for each + * component is 255. This is important to make sure + * that white is indeed reported as (255, 255, 255), + * and that opaque alpha is 255. + * This only works for RGB bit fields at least 4 bit + * wide, which is almost always the case. + */ + unsigned v; + v = (pixel & fmt->Rmask) >> fmt->Rshift; + *r = (v << fmt->Rloss) + (v >> (8 - (fmt->Rloss << 1))); + v = (pixel & fmt->Gmask) >> fmt->Gshift; + *g = (v << fmt->Gloss) + (v >> (8 - (fmt->Gloss << 1))); + v = (pixel & fmt->Bmask) >> fmt->Bshift; + *b = (v << fmt->Bloss) + (v >> (8 - (fmt->Bloss << 1))); + if (fmt->Amask) { + v = (pixel & fmt->Amask) >> fmt->Ashift; + *a = (v << fmt->Aloss) + (v >> (8 - (fmt->Aloss << 1))); + } else { + *a = SDL_ALPHA_OPAQUE; + } + } else { + *r = fmt->palette->colors[pixel].r; + *g = fmt->palette->colors[pixel].g; + *b = fmt->palette->colors[pixel].b; + *a = SDL_ALPHA_OPAQUE; + } } -void SDL_GetRGB(Uint32 pixel, SDL_PixelFormat *fmt, Uint8 *r,Uint8 *g,Uint8 *b) +void +SDL_GetRGB(Uint32 pixel, SDL_PixelFormat * fmt, Uint8 * r, Uint8 * g, + Uint8 * b) { - if ( fmt->palette == NULL ) { - /* the note for SDL_GetRGBA above applies here too */ - unsigned v; - v = (pixel & fmt->Rmask) >> fmt->Rshift; - *r = (v << fmt->Rloss) + (v >> (8 - (fmt->Rloss << 1))); - v = (pixel & fmt->Gmask) >> fmt->Gshift; - *g = (v << fmt->Gloss) + (v >> (8 - (fmt->Gloss << 1))); - v = (pixel & fmt->Bmask) >> fmt->Bshift; - *b = (v << fmt->Bloss) + (v >> (8 - (fmt->Bloss << 1))); - } else { - *r = fmt->palette->colors[pixel].r; - *g = fmt->palette->colors[pixel].g; - *b = fmt->palette->colors[pixel].b; - } + if (fmt->palette == NULL) { + /* the note for SDL_GetRGBA above applies here too */ + unsigned v; + v = (pixel & fmt->Rmask) >> fmt->Rshift; + *r = (v << fmt->Rloss) + (v >> (8 - (fmt->Rloss << 1))); + v = (pixel & fmt->Gmask) >> fmt->Gshift; + *g = (v << fmt->Gloss) + (v >> (8 - (fmt->Gloss << 1))); + v = (pixel & fmt->Bmask) >> fmt->Bshift; + *b = (v << fmt->Bloss) + (v >> (8 - (fmt->Bloss << 1))); + } else { + *r = fmt->palette->colors[pixel].r; + *g = fmt->palette->colors[pixel].g; + *b = fmt->palette->colors[pixel].b; + } } /* Apply gamma to a set of colors - this is easy. :) */ -void SDL_ApplyGamma(Uint16 *gamma, SDL_Color *colors, SDL_Color *output, - int ncolors) +void +SDL_ApplyGamma(Uint16 * gamma, SDL_Color * colors, SDL_Color * output, + int ncolors) { - int i; + int i; - for ( i=0; i> 8; - output[i].g = gamma[1*256 + colors[i].g] >> 8; - output[i].b = gamma[2*256 + colors[i].b] >> 8; - } + for (i = 0; i < ncolors; ++i) { + output[i].r = gamma[0 * 256 + colors[i].r] >> 8; + output[i].g = gamma[1 * 256 + colors[i].g] >> 8; + output[i].b = gamma[2 * 256 + colors[i].b] >> 8; + } } /* Map from Palette to Palette */ -static Uint8 *Map1to1(SDL_Palette *src, SDL_Palette *dst, int *identical) +static Uint8 * +Map1to1(SDL_Palette * src, SDL_Palette * dst, int *identical) { - Uint8 *map; - int i; - - if ( identical ) { - if ( src->ncolors <= dst->ncolors ) { - /* If an identical palette, no need to map */ - if ( SDL_memcmp(src->colors, dst->colors, src->ncolors* - sizeof(SDL_Color)) == 0 ) { - *identical = 1; - return(NULL); - } - } - *identical = 0; - } - map = (Uint8 *)SDL_malloc(src->ncolors); - if ( map == NULL ) { - SDL_OutOfMemory(); - return(NULL); - } - for ( i=0; incolors; ++i ) { - map[i] = SDL_FindColor(dst, - src->colors[i].r, src->colors[i].g, src->colors[i].b); - } - return(map); + Uint8 *map; + int i; + + if (identical) { + if (src->ncolors <= dst->ncolors) { + /* If an identical palette, no need to map */ + if (src == dst + || + (SDL_memcmp + (src->colors, dst->colors, + src->ncolors * sizeof(SDL_Color)) == 0)) { + *identical = 1; + return (NULL); + } + } + *identical = 0; + } + map = (Uint8 *) SDL_malloc(src->ncolors); + if (map == NULL) { + SDL_OutOfMemory(); + return (NULL); + } + for (i = 0; i < src->ncolors; ++i) { + map[i] = SDL_FindColor(dst, + src->colors[i].r, src->colors[i].g, + src->colors[i].b); + } + return (map); } + /* Map from Palette to BitField */ -static Uint8 *Map1toN(SDL_PixelFormat *src, SDL_PixelFormat *dst) +static Uint8 * +Map1toN(SDL_PixelFormat * src, SDL_PixelFormat * dst) { - Uint8 *map; - int i; - int bpp; - unsigned alpha; - SDL_Palette *pal = src->palette; - - bpp = ((dst->BytesPerPixel == 3) ? 4 : dst->BytesPerPixel); - map = (Uint8 *)SDL_malloc(pal->ncolors*bpp); - if ( map == NULL ) { - SDL_OutOfMemory(); - return(NULL); - } - - alpha = dst->Amask ? src->alpha : 0; - /* We memory copy to the pixel map so the endianness is preserved */ - for ( i=0; incolors; ++i ) { - ASSEMBLE_RGBA(&map[i*bpp], dst->BytesPerPixel, dst, - pal->colors[i].r, pal->colors[i].g, - pal->colors[i].b, alpha); - } - return(map); + Uint8 *map; + int i; + int bpp; + unsigned alpha; + SDL_Palette *pal = src->palette; + + bpp = ((dst->BytesPerPixel == 3) ? 4 : dst->BytesPerPixel); + map = (Uint8 *) SDL_malloc(pal->ncolors * bpp); + if (map == NULL) { + SDL_OutOfMemory(); + return (NULL); + } + + alpha = dst->Amask ? src->alpha : 0; + /* We memory copy to the pixel map so the endianness is preserved */ + for (i = 0; i < pal->ncolors; ++i) { + ASSEMBLE_RGBA(&map[i * bpp], dst->BytesPerPixel, dst, + pal->colors[i].r, pal->colors[i].g, + pal->colors[i].b, alpha); + } + return (map); } + /* Map from BitField to Dithered-Palette to Palette */ -static Uint8 *MapNto1(SDL_PixelFormat *src, SDL_PixelFormat *dst, int *identical) +static Uint8 * +MapNto1(SDL_PixelFormat * src, SDL_PixelFormat * dst, int *identical) { - /* Generate a 256 color dither palette */ - SDL_Palette dithered; - SDL_Color colors[256]; - SDL_Palette *pal = dst->palette; - - /* SDL_DitherColors does not initialize the 'unused' component of colors, - but Map1to1 compares it against pal, so we should initialize it. */ - SDL_memset(colors, 0, sizeof(colors)); - - dithered.ncolors = 256; - SDL_DitherColors(colors, 8); - dithered.colors = colors; - return(Map1to1(&dithered, pal, identical)); + /* Generate a 256 color dither palette */ + SDL_Palette dithered; + SDL_Color colors[256]; + SDL_Palette *pal = dst->palette; + + dithered.ncolors = 256; + SDL_DitherColors(colors, 8); + dithered.colors = colors; + return (Map1to1(&dithered, pal, identical)); } -SDL_BlitMap *SDL_AllocBlitMap(void) +SDL_BlitMap * +SDL_AllocBlitMap(void) { - SDL_BlitMap *map; - - /* Allocate the empty map */ - map = (SDL_BlitMap *)SDL_malloc(sizeof(*map)); - if ( map == NULL ) { - SDL_OutOfMemory(); - return(NULL); - } - SDL_memset(map, 0, sizeof(*map)); - - /* Allocate the software blit data */ - map->sw_data = (struct private_swaccel *)SDL_malloc(sizeof(*map->sw_data)); - if ( map->sw_data == NULL ) { - SDL_FreeBlitMap(map); - SDL_OutOfMemory(); - return(NULL); - } - SDL_memset(map->sw_data, 0, sizeof(*map->sw_data)); - - /* It's ready to go */ - return(map); + SDL_BlitMap *map; + + /* Allocate the empty map */ + map = (SDL_BlitMap *) SDL_malloc(sizeof(*map)); + if (map == NULL) { + SDL_OutOfMemory(); + return (NULL); + } + SDL_memset(map, 0, sizeof(*map)); + + /* Allocate the software blit data */ + map->sw_data = + (struct private_swaccel *) SDL_malloc(sizeof(*map->sw_data)); + if (map->sw_data == NULL) { + SDL_FreeBlitMap(map); + SDL_OutOfMemory(); + return (NULL); + } + SDL_memset(map->sw_data, 0, sizeof(*map->sw_data)); + + /* It's ready to go */ + return (map); } -void SDL_InvalidateMap(SDL_BlitMap *map) + +void +SDL_InvalidateMap(SDL_BlitMap * map) { - if ( ! map ) { - return; - } - map->dst = NULL; - map->format_version = (unsigned int)-1; - if ( map->table ) { - SDL_free(map->table); - map->table = NULL; - } + if (!map) { + return; + } + map->dst = NULL; + map->format_version = (unsigned int) -1; + if (map->table) { + SDL_free(map->table); + map->table = NULL; + } } -int SDL_MapSurface (SDL_Surface *src, SDL_Surface *dst) +int +SDL_MapSurface(SDL_Surface * src, SDL_Surface * dst) { - SDL_PixelFormat *srcfmt; - SDL_PixelFormat *dstfmt; - SDL_BlitMap *map; - - /* Clear out any previous mapping */ - map = src->map; - if ( (src->flags & SDL_RLEACCEL) == SDL_RLEACCEL ) { - SDL_UnRLESurface(src, 1); - } - SDL_InvalidateMap(map); - - /* Figure out what kind of mapping we're doing */ - map->identity = 0; - srcfmt = src->format; - dstfmt = dst->format; - switch (srcfmt->BytesPerPixel) { - case 1: - switch (dstfmt->BytesPerPixel) { - case 1: - /* Palette --> Palette */ - /* If both SDL_HWSURFACE, assume have same palette */ - if ( ((src->flags & SDL_HWSURFACE) == SDL_HWSURFACE) && - ((dst->flags & SDL_HWSURFACE) == SDL_HWSURFACE) ) { - map->identity = 1; - } else { - map->table = Map1to1(srcfmt->palette, - dstfmt->palette, &map->identity); - } - if ( ! map->identity ) { - if ( map->table == NULL ) { - return(-1); - } - } - if (srcfmt->BitsPerPixel!=dstfmt->BitsPerPixel) - map->identity = 0; - break; - - default: - /* Palette --> BitField */ - map->table = Map1toN(srcfmt, dstfmt); - if ( map->table == NULL ) { - return(-1); - } - break; - } - break; - default: - switch (dstfmt->BytesPerPixel) { - case 1: - /* BitField --> Palette */ - map->table = MapNto1(srcfmt, dstfmt, &map->identity); - if ( ! map->identity ) { - if ( map->table == NULL ) { - return(-1); - } - } - map->identity = 0; /* Don't optimize to copy */ - break; - default: - /* BitField --> BitField */ - if ( FORMAT_EQUAL(srcfmt, dstfmt) ) - map->identity = 1; - break; - } - break; - } - - map->dst = dst; - map->format_version = dst->format_version; - - /* Choose your blitters wisely */ - return(SDL_CalculateBlit(src)); + SDL_PixelFormat *srcfmt; + SDL_PixelFormat *dstfmt; + SDL_BlitMap *map; + + /* Clear out any previous mapping */ + map = src->map; + if ((src->flags & SDL_RLEACCEL) == SDL_RLEACCEL) { + SDL_UnRLESurface(src, 1); + } + SDL_InvalidateMap(map); + + /* Figure out what kind of mapping we're doing */ + map->identity = 0; + srcfmt = src->format; + dstfmt = dst->format; + switch (srcfmt->BytesPerPixel) { + case 1: + switch (dstfmt->BytesPerPixel) { + case 1: + /* Palette --> Palette */ + map->table = + Map1to1(srcfmt->palette, dstfmt->palette, &map->identity); + if (!map->identity) { + if (map->table == NULL) { + return (-1); + } + } + if (srcfmt->BitsPerPixel != dstfmt->BitsPerPixel) + map->identity = 0; + break; + + default: + /* Palette --> BitField */ + map->table = Map1toN(srcfmt, dstfmt); + if (map->table == NULL) { + return (-1); + } + break; + } + break; + default: + switch (dstfmt->BytesPerPixel) { + case 1: + /* BitField --> Palette */ + map->table = MapNto1(srcfmt, dstfmt, &map->identity); + if (!map->identity) { + if (map->table == NULL) { + return (-1); + } + } + map->identity = 0; /* Don't optimize to copy */ + break; + default: + /* BitField --> BitField */ + if (FORMAT_EQUAL(srcfmt, dstfmt)) + map->identity = 1; + break; + } + break; + } + + map->dst = dst; + map->format_version = dst->format_version; + + /* Choose your blitters wisely */ + return (SDL_CalculateBlit(src)); } -void SDL_FreeBlitMap(SDL_BlitMap *map) + +void +SDL_FreeBlitMap(SDL_BlitMap * map) { - if ( map ) { - SDL_InvalidateMap(map); - if ( map->sw_data != NULL ) { - SDL_free(map->sw_data); - } - SDL_free(map); - } + if (map) { + SDL_InvalidateMap(map); + if (map->sw_data != NULL) { + SDL_free(map->sw_data); + } + SDL_free(map); + } } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/SDL_pixels_c.h b/src/video/SDL_pixels_c.h index 6ab56b173..3d0520454 100644 --- a/src/video/SDL_pixels_c.h +++ b/src/video/SDL_pixels_c.h @@ -27,20 +27,21 @@ /* Pixel format functions */ extern SDL_PixelFormat *SDL_AllocFormat(int bpp, - Uint32 Rmask, Uint32 Gmask, Uint32 Bmask, Uint32 Amask); -extern SDL_PixelFormat *SDL_ReallocFormat(SDL_Surface *surface, int bpp, - Uint32 Rmask, Uint32 Gmask, Uint32 Bmask, Uint32 Amask); -extern void SDL_FormatChanged(SDL_Surface *surface); -extern void SDL_FreeFormat(SDL_PixelFormat *format); + Uint32 Rmask, Uint32 Gmask, + Uint32 Bmask, Uint32 Amask); +extern void SDL_FormatChanged(SDL_Surface * surface); +extern void SDL_FreeFormat(SDL_PixelFormat * format); /* Blit mapping functions */ extern SDL_BlitMap *SDL_AllocBlitMap(void); -extern void SDL_InvalidateMap(SDL_BlitMap *map); -extern int SDL_MapSurface (SDL_Surface *src, SDL_Surface *dst); -extern void SDL_FreeBlitMap(SDL_BlitMap *map); +extern void SDL_InvalidateMap(SDL_BlitMap * map); +extern int SDL_MapSurface(SDL_Surface * src, SDL_Surface * dst); +extern void SDL_FreeBlitMap(SDL_BlitMap * map); /* Miscellaneous functions */ -extern Uint16 SDL_CalculatePitch(SDL_Surface *surface); -extern void SDL_DitherColors(SDL_Color *colors, int bpp); -extern Uint8 SDL_FindColor(SDL_Palette *pal, Uint8 r, Uint8 g, Uint8 b); -extern void SDL_ApplyGamma(Uint16 *gamma, SDL_Color *colors, SDL_Color *output, int ncolors); +extern int SDL_CalculatePitch(SDL_Surface * surface); +extern void SDL_DitherColors(SDL_Color * colors, int bpp); +extern Uint8 SDL_FindColor(SDL_Palette * pal, Uint8 r, Uint8 g, Uint8 b); +extern void SDL_ApplyGamma(Uint16 * gamma, SDL_Color * colors, + SDL_Color * output, int ncolors); +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/SDL_rect.c b/src/video/SDL_rect.c new file mode 100644 index 000000000..27c3ad86f --- /dev/null +++ b/src/video/SDL_rect.c @@ -0,0 +1,189 @@ +/* + SDL - Simple DirectMedia Layer + Copyright (C) 1997-2006 Sam Lantinga + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + Sam Lantinga + slouken@libsdl.org +*/ +#include "SDL_config.h" + +#include "SDL_video.h" +#include "SDL_rect_c.h" + +SDL_bool +SDL_HasIntersection(const SDL_Rect * A, const SDL_Rect * B) +{ + int Amin, Amax, Bmin, Bmax; + + /* Horizontal intersection */ + Amin = A->x; + Amax = Amin + A->w; + Bmin = B->x; + Bmax = Bmin + B->w; + if (Bmin > Amin) + Amin = Bmin; + if (Bmax < Amax) + Amax = Bmax; + if (Amax <= Amin) + return SDL_FALSE; + + /* Vertical intersection */ + Amin = A->y; + Amax = Amin + A->h; + Bmin = B->y; + Bmax = Bmin + B->h; + if (Bmin > Amin) + Amin = Bmin; + if (Bmax < Amax) + Amax = Bmax; + if (Amax <= Amin) + return SDL_FALSE; + + return SDL_TRUE; +} + +SDL_bool +SDL_IntersectRect(const SDL_Rect * A, const SDL_Rect * B, SDL_Rect * result) +{ + int Amin, Amax, Bmin, Bmax; + + /* Horizontal intersection */ + Amin = A->x; + Amax = Amin + A->w; + Bmin = B->x; + Bmax = Bmin + B->w; + if (Bmin > Amin) + Amin = Bmin; + result->x = Amin; + if (Bmax < Amax) + Amax = Bmax; + result->w = Amax - Amin; + + /* Vertical intersection */ + Amin = A->y; + Amax = Amin + A->h; + Bmin = B->y; + Bmax = Bmin + B->h; + if (Bmin > Amin) + Amin = Bmin; + result->y = Amin; + if (Bmax < Amax) + Amax = Bmax; + result->h = Amax - Amin; + + return !SDL_RectEmpty(result); +} + +void +SDL_UnionRect(const SDL_Rect * A, const SDL_Rect * B, SDL_Rect * result) +{ + int Amin, Amax, Bmin, Bmax; + + /* Horizontal union */ + Amin = A->x; + Amax = Amin + A->w; + Bmin = B->x; + Bmax = Bmin + B->w; + if (Bmin < Amin) + Amin = Bmin; + result->x = Amin; + if (Bmax > Amax) + Amax = Bmax; + result->w = Amax - Amin; + + /* Vertical intersection */ + Amin = A->y; + Amax = Amin + A->h; + Bmin = B->y; + Bmax = Bmin + B->h; + if (Bmin < Amin) + Amin = Bmin; + result->y = Amin; + if (Bmax > Amax) + Amax = Bmax; + result->h = Amax - Amin; +} + +void +SDL_AddDirtyRect(SDL_DirtyRectList * list, const SDL_Rect * rect) +{ + SDL_DirtyRect *dirty; + SDL_DirtyRect *check, *prev, *next; + + if (list->free) { + dirty = list->free; + list->free = dirty->next; + } else { + dirty = (SDL_DirtyRect *) SDL_malloc(sizeof(*dirty)); + if (!dirty) { + return; + } + } + dirty->rect = *rect; + + /* FIXME: At what point is this optimization too expensive? */ + for (prev = NULL, check = list->list; check; check = next) { + next = check->next; + + if (SDL_HasIntersection(&dirty->rect, &check->rect)) { + SDL_UnionRect(&dirty->rect, &check->rect, &dirty->rect); + if (prev) { + prev->next = next; + } else { + list->list = next; + } + check->next = list->free; + list->free = check; + --list->count; + } else { + prev = check; + } + } + + dirty->next = list->list; + list->list = dirty; + ++list->count; +} + +void +SDL_ClearDirtyRects(SDL_DirtyRectList * list) +{ + while (list->list) { + SDL_DirtyRect *elem = list->list; + list->list = elem->next; + elem->next = list->free; + list->free = elem; + } + list->count = 0; +} + +void +SDL_FreeDirtyRects(SDL_DirtyRectList * list) +{ + while (list->list) { + SDL_DirtyRect *elem = list->list; + list->list = elem->next; + SDL_free(elem); + } + while (list->free) { + SDL_DirtyRect *elem = list->free; + list->free = elem->next; + SDL_free(elem); + } +} + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/SDL_rect_c.h b/src/video/SDL_rect_c.h new file mode 100644 index 000000000..0f4d3bf06 --- /dev/null +++ b/src/video/SDL_rect_c.h @@ -0,0 +1,41 @@ +/* + SDL - Simple DirectMedia Layer + Copyright (C) 1997-2006 Sam Lantinga + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + Sam Lantinga + slouken@libsdl.org +*/ +#include "SDL_config.h" + +typedef struct SDL_DirtyRect +{ + SDL_Rect rect; + struct SDL_DirtyRect *next; +} SDL_DirtyRect; + +typedef struct SDL_DirtyRectList +{ + int count; + SDL_DirtyRect *list; + SDL_DirtyRect *free; +} SDL_DirtyRectList; + +extern void SDL_AddDirtyRect(SDL_DirtyRectList * list, const SDL_Rect * rect); +extern void SDL_ClearDirtyRects(SDL_DirtyRectList * list); +extern void SDL_FreeDirtyRects(SDL_DirtyRectList * list); + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/SDL_renderer_sw.c b/src/video/SDL_renderer_sw.c new file mode 100644 index 000000000..4cbbd4ca2 --- /dev/null +++ b/src/video/SDL_renderer_sw.c @@ -0,0 +1,533 @@ +/* + SDL - Simple DirectMedia Layer + Copyright (C) 1997-2006 Sam Lantinga + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + Sam Lantinga + slouken@libsdl.org +*/ +#include "SDL_config.h" + +#include "SDL_video.h" +#include "SDL_sysvideo.h" +#include "SDL_rect_c.h" +#include "SDL_yuv_sw_c.h" + + +/* SDL surface based renderer implementation */ + +static SDL_Renderer *SDL_SW_CreateRenderer(SDL_Window * window, Uint32 flags); +static int SDL_SW_CreateTexture(SDL_Renderer * renderer, + SDL_Texture * texture); +static int SDL_SW_QueryTexturePixels(SDL_Renderer * renderer, + SDL_Texture * texture, void **pixels, + int *pitch); +static int SDL_SW_SetTexturePalette(SDL_Renderer * renderer, + SDL_Texture * texture, + const SDL_Color * colors, int firstcolor, + int ncolors); +static int SDL_SW_GetTexturePalette(SDL_Renderer * renderer, + SDL_Texture * texture, SDL_Color * colors, + int firstcolor, int ncolors); +static int SDL_SW_UpdateTexture(SDL_Renderer * renderer, + SDL_Texture * texture, const SDL_Rect * rect, + const void *pixels, int pitch); +static int SDL_SW_LockTexture(SDL_Renderer * renderer, SDL_Texture * texture, + const SDL_Rect * rect, int markDirty, + void **pixels, int *pitch); +static void SDL_SW_UnlockTexture(SDL_Renderer * renderer, + SDL_Texture * texture); +static void SDL_SW_DirtyTexture(SDL_Renderer * renderer, + SDL_Texture * texture, int numrects, + const SDL_Rect * rects); +static void SDL_SW_SelectRenderTexture(SDL_Renderer * renderer, + SDL_Texture * texture); +static int SDL_SW_RenderFill(SDL_Renderer * renderer, const SDL_Rect * rect, + Uint32 color); +static int SDL_SW_RenderCopy(SDL_Renderer * renderer, SDL_Texture * texture, + const SDL_Rect * srcrect, + const SDL_Rect * dstrect, int blendMode, + int scaleMode); +static int SDL_SW_RenderReadPixels(SDL_Renderer * renderer, + const SDL_Rect * rect, void *pixels, + int pitch); +static int SDL_SW_RenderWritePixels(SDL_Renderer * renderer, + const SDL_Rect * rect, const void *pixels, + int pitch); +static void SDL_SW_RenderPresent(SDL_Renderer * renderer); +static void SDL_SW_DestroyTexture(SDL_Renderer * renderer, + SDL_Texture * texture); +static void SDL_SW_DestroyRenderer(SDL_Renderer * renderer); + + +SDL_RenderDriver SDL_SW_RenderDriver = { + SDL_SW_CreateRenderer, + { + "software", + (SDL_Renderer_PresentDiscard | + SDL_Renderer_PresentCopy | + SDL_Renderer_PresentFlip2 | + SDL_Renderer_PresentFlip3 | SDL_Renderer_RenderTarget), + (SDL_TextureBlendMode_None | + SDL_TextureBlendMode_Mask | SDL_TextureBlendMode_Blend), + (SDL_TextureScaleMode_None | SDL_TextureScaleMode_Fast), + 11, + { + SDL_PixelFormat_Index8, + SDL_PixelFormat_RGB555, + SDL_PixelFormat_RGB565, + SDL_PixelFormat_RGB888, + SDL_PixelFormat_BGR888, + SDL_PixelFormat_ARGB8888, + SDL_PixelFormat_RGBA8888, + SDL_PixelFormat_ABGR8888, + SDL_PixelFormat_BGRA8888, + SDL_PixelFormat_YUY2, + SDL_PixelFormat_UYVY}, + 0, + 0} +}; + +typedef struct +{ + int current_screen; + SDL_Surface *screens[3]; + SDL_Surface *target; + SDL_Renderer *renderer; + SDL_DirtyRectList dirty; +} SDL_SW_RenderData; + +SDL_Renderer * +SDL_SW_CreateRenderer(SDL_Window * window, Uint32 flags) +{ + SDL_VideoDisplay *display = SDL_GetDisplayFromWindow(window); + SDL_DisplayMode *displayMode = &display->current_mode; + SDL_Renderer *renderer; + SDL_SW_RenderData *data; + int i, n; + int bpp; + Uint32 Rmask, Gmask, Bmask, Amask; + + if (!SDL_PixelFormatEnumToMasks + (displayMode->format, &bpp, &Rmask, &Gmask, &Bmask, &Amask)) { + SDL_SetError("Unknown display format"); + return NULL; + } + + renderer = (SDL_Renderer *) SDL_calloc(1, sizeof(*renderer)); + if (!renderer) { + SDL_OutOfMemory(); + return NULL; + } + + data = (SDL_SW_RenderData *) SDL_malloc(sizeof(*data)); + if (!data) { + SDL_SW_DestroyRenderer(renderer); + SDL_OutOfMemory(); + return NULL; + } + SDL_zerop(data); + + renderer->CreateTexture = SDL_SW_CreateTexture; + renderer->QueryTexturePixels = SDL_SW_QueryTexturePixels; + renderer->SetTexturePalette = SDL_SW_SetTexturePalette; + renderer->GetTexturePalette = SDL_SW_GetTexturePalette; + renderer->UpdateTexture = SDL_SW_UpdateTexture; + renderer->LockTexture = SDL_SW_LockTexture; + renderer->UnlockTexture = SDL_SW_UnlockTexture; + renderer->DirtyTexture = SDL_SW_DirtyTexture; + renderer->SelectRenderTexture = SDL_SW_SelectRenderTexture; + renderer->RenderFill = SDL_SW_RenderFill; + renderer->RenderCopy = SDL_SW_RenderCopy; + renderer->RenderReadPixels = SDL_SW_RenderReadPixels; + renderer->RenderWritePixels = SDL_SW_RenderWritePixels; + renderer->RenderPresent = SDL_SW_RenderPresent; + renderer->DestroyTexture = SDL_SW_DestroyTexture; + renderer->DestroyRenderer = SDL_SW_DestroyRenderer; + renderer->info = SDL_SW_RenderDriver.info; + renderer->window = window->id; + renderer->driverdata = data; + + renderer->info.flags = SDL_Renderer_RenderTarget; + + if (flags & SDL_Renderer_PresentFlip2) { + renderer->info.flags |= SDL_Renderer_PresentFlip2; + n = 2; + } else if (flags & SDL_Renderer_PresentFlip3) { + renderer->info.flags |= SDL_Renderer_PresentFlip3; + n = 3; + } else { + renderer->info.flags |= SDL_Renderer_PresentCopy; + n = 1; + } + for (i = 0; i < n; ++i) { + data->screens[i] = + SDL_CreateRGBSurface(0, window->w, window->h, bpp, Rmask, Gmask, + Bmask, Amask); + if (!data->screens[i]) { + SDL_SW_DestroyRenderer(renderer); + return NULL; + } + SDL_SetSurfacePalette(data->screens[i], display->palette); + } + data->current_screen = 0; + data->target = data->screens[0]; + + /* Find a render driver that we can use to display data */ + for (i = 0; i < display->num_render_drivers; ++i) { + SDL_RenderDriver *driver = &display->render_drivers[i]; + if (driver->info.name != SDL_SW_RenderDriver.info.name) { + data->renderer = + driver->CreateRenderer(window, SDL_Renderer_PresentDiscard); + if (data->renderer) { + break; + } + } + } + if (i == display->num_render_drivers) { + SDL_SW_DestroyRenderer(renderer); + SDL_SetError("Couldn't find display render driver"); + return NULL; + } + return renderer; +} + +static int +SDL_SW_CreateTexture(SDL_Renderer * renderer, SDL_Texture * texture) +{ + if (SDL_ISPIXELFORMAT_FOURCC(texture->format)) { + if (texture->access == SDL_TextureAccess_Render) { + SDL_SetError("Rendering to YUV format textures is not supported"); + return -1; + } + texture->driverdata = SDL_SW_CreateYUVTexture(texture); + } else { + int bpp; + Uint32 Rmask, Gmask, Bmask, Amask; + + if (!SDL_PixelFormatEnumToMasks + (texture->format, &bpp, &Rmask, &Gmask, &Bmask, &Amask)) { + SDL_SetError("Unknown texture format"); + return -1; + } + + texture->driverdata = + SDL_CreateRGBSurface(0, texture->w, texture->h, bpp, Rmask, Gmask, + Bmask, Amask); + } + + if (!texture->driverdata) { + return -1; + } + return 0; +} + +static int +SDL_SW_QueryTexturePixels(SDL_Renderer * renderer, SDL_Texture * texture, + void **pixels, int *pitch) +{ + if (SDL_ISPIXELFORMAT_FOURCC(texture->format)) { + return SDL_SW_QueryYUVTexturePixels((SDL_SW_YUVTexture *) texture-> + driverdata, pixels, pitch); + } else { + SDL_Surface *surface = (SDL_Surface *) texture->driverdata; + + *pixels = surface->pixels; + *pitch = surface->pitch; + return 0; + } +} + +static int +SDL_SW_SetTexturePalette(SDL_Renderer * renderer, SDL_Texture * texture, + const SDL_Color * colors, int firstcolor, + int ncolors) +{ + if (SDL_ISPIXELFORMAT_FOURCC(texture->format)) { + SDL_SetError("YUV textures don't have a palette"); + return -1; + } else { + SDL_Surface *surface = (SDL_Surface *) texture->driverdata; + + return SDL_SetPaletteColors(surface->format->palette, colors, + firstcolor, ncolors); + } +} + +static int +SDL_SW_GetTexturePalette(SDL_Renderer * renderer, SDL_Texture * texture, + SDL_Color * colors, int firstcolor, int ncolors) +{ + if (SDL_ISPIXELFORMAT_FOURCC(texture->format)) { + SDL_SetError("YUV textures don't have a palette"); + return -1; + } else { + SDL_Surface *surface = (SDL_Surface *) texture->driverdata; + + SDL_memcpy(colors, &surface->format->palette->colors[firstcolor], + ncolors * sizeof(*colors)); + return 0; + } +} + +static int +SDL_SW_UpdateTexture(SDL_Renderer * renderer, SDL_Texture * texture, + const SDL_Rect * rect, const void *pixels, int pitch) +{ + if (SDL_ISPIXELFORMAT_FOURCC(texture->format)) { + return SDL_SW_UpdateYUVTexture((SDL_SW_YUVTexture *) texture-> + driverdata, rect, pixels, pitch); + } else { + SDL_Surface *surface = (SDL_Surface *) texture->driverdata; + Uint8 *src, *dst; + int row; + size_t length; + + src = (Uint8 *) pixels; + dst = + (Uint8 *) surface->pixels + rect->y * surface->pitch + + rect->x * surface->format->BytesPerPixel; + length = rect->w * surface->format->BytesPerPixel; + for (row = 0; row < rect->h; ++row) { + SDL_memcpy(dst, src, length); + src += pitch; + dst += surface->pitch; + } + return 0; + } +} + +static int +SDL_SW_LockTexture(SDL_Renderer * renderer, SDL_Texture * texture, + const SDL_Rect * rect, int markDirty, void **pixels, + int *pitch) +{ + if (SDL_ISPIXELFORMAT_FOURCC(texture->format)) { + return SDL_SW_LockYUVTexture((SDL_SW_YUVTexture *) texture-> + driverdata, rect, markDirty, pixels, + pitch); + } else { + SDL_Surface *surface = (SDL_Surface *) texture->driverdata; + + *pixels = + (void *) ((Uint8 *) surface->pixels + rect->y * surface->pitch + + rect->x * surface->format->BytesPerPixel); + *pitch = surface->pitch; + return 0; + } +} + +static void +SDL_SW_UnlockTexture(SDL_Renderer * renderer, SDL_Texture * texture) +{ + if (SDL_ISPIXELFORMAT_FOURCC(texture->format)) { + SDL_SW_UnlockYUVTexture((SDL_SW_YUVTexture *) texture->driverdata); + } +} + +static void +SDL_SW_DirtyTexture(SDL_Renderer * renderer, SDL_Texture * texture, + int numrects, const SDL_Rect * rects) +{ +} + +static void +SDL_SW_SelectRenderTexture(SDL_Renderer * renderer, SDL_Texture * texture) +{ + SDL_SW_RenderData *data = (SDL_SW_RenderData *) renderer->driverdata; + + if (texture) { + data->target = (SDL_Surface *) texture->driverdata; + } else { + data->target = data->screens[data->current_screen]; + } +} + +static int +SDL_SW_RenderFill(SDL_Renderer * renderer, const SDL_Rect * rect, + Uint32 color) +{ + SDL_SW_RenderData *data = (SDL_SW_RenderData *) renderer->driverdata; + SDL_Rect real_rect = *rect; + Uint8 r, g, b, a; + + SDL_AddDirtyRect(&data->dirty, rect); + + a = (Uint8) ((color >> 24) & 0xFF); + r = (Uint8) ((color >> 16) & 0xFF); + g = (Uint8) ((color >> 8) & 0xFF); + b = (Uint8) (color & 0xFF); + color = SDL_MapRGBA(data->target->format, r, g, b, a); + + return SDL_FillRect(data->target, &real_rect, color); +} + +static int +SDL_SW_RenderCopy(SDL_Renderer * renderer, SDL_Texture * texture, + const SDL_Rect * srcrect, const SDL_Rect * dstrect, + int blendMode, int scaleMode) +{ + SDL_SW_RenderData *data = (SDL_SW_RenderData *) renderer->driverdata; + SDL_Window *window = SDL_GetWindowFromID(renderer->window); + SDL_VideoDisplay *display = SDL_GetDisplayFromWindow(window); + + SDL_AddDirtyRect(&data->dirty, dstrect); + + if (SDL_ISPIXELFORMAT_FOURCC(texture->format)) { + SDL_Surface *target = data->target; + void *pixels = + (Uint8 *) target->pixels + dstrect->y * target->pitch + + dstrect->x * target->format->BytesPerPixel; + return SDL_SW_CopyYUVToRGB((SDL_SW_YUVTexture *) texture->driverdata, + srcrect, display->current_mode.format, + dstrect->w, dstrect->h, pixels, + target->pitch); + } else { + SDL_Surface *surface = (SDL_Surface *) texture->driverdata; + SDL_Rect real_srcrect = *srcrect; + SDL_Rect real_dstrect = *dstrect; + + if (blendMode & + (SDL_TextureBlendMode_Mask | SDL_TextureBlendMode_Blend)) { + SDL_SetAlpha(surface, SDL_SRCALPHA, 0); + } else { + SDL_SetAlpha(surface, 0, 0); + } + if (scaleMode != SDL_TextureScaleMode_None && + (srcrect->w != dstrect->w || srcrect->h != dstrect->h)) { + return SDL_SoftStretch(surface, &real_srcrect, data->target, + &real_dstrect); + } else { + return SDL_LowerBlit(surface, &real_srcrect, data->target, + &real_dstrect); + } + } +} + +static int +SDL_SW_RenderReadPixels(SDL_Renderer * renderer, const SDL_Rect * rect, + void *pixels, int pitch) +{ + SDL_SW_RenderData *data = (SDL_SW_RenderData *) renderer->driverdata; + SDL_Surface *surface = data->target; + Uint8 *src, *dst; + int row; + size_t length; + + src = + (Uint8 *) surface->pixels + rect->y * surface->pitch + + rect->x * surface->format->BytesPerPixel; + dst = (Uint8 *) pixels; + length = rect->w * surface->format->BytesPerPixel; + for (row = 0; row < rect->h; ++row) { + SDL_memcpy(dst, src, length); + src += surface->pitch; + dst += pitch; + } + return 0; +} + +static int +SDL_SW_RenderWritePixels(SDL_Renderer * renderer, const SDL_Rect * rect, + const void *pixels, int pitch) +{ + SDL_SW_RenderData *data = (SDL_SW_RenderData *) renderer->driverdata; + SDL_Surface *surface = data->target; + Uint8 *src, *dst; + int row; + size_t length; + + SDL_AddDirtyRect(&data->dirty, rect); + + src = (Uint8 *) pixels; + dst = + (Uint8 *) surface->pixels + rect->y * surface->pitch + + rect->x * surface->format->BytesPerPixel; + length = rect->w * surface->format->BytesPerPixel; + for (row = 0; row < rect->h; ++row) { + SDL_memcpy(dst, src, length); + src += pitch; + dst += surface->pitch; + } + return 0; +} + +static void +SDL_SW_RenderPresent(SDL_Renderer * renderer) +{ + SDL_SW_RenderData *data = (SDL_SW_RenderData *) renderer->driverdata; + SDL_Surface *surface = data->screens[data->current_screen]; + SDL_DirtyRect *dirty; + int new_screen; + + /* Send the data to the display */ + for (dirty = data->dirty.list; dirty; dirty = dirty->next) { + void *pixels = + (void *) ((Uint8 *) surface->pixels + + dirty->rect.y * surface->pitch + + dirty->rect.x * surface->format->BytesPerPixel); + data->renderer->RenderWritePixels(data->renderer, &dirty->rect, + pixels, surface->pitch); + } + SDL_ClearDirtyRects(&data->dirty); + data->renderer->RenderPresent(data->renderer); + + + /* Update the flipping chain, if any */ + if (renderer->info.flags & SDL_Renderer_PresentFlip2) { + new_screen = (data->current_screen + 1) % 2; + } else if (renderer->info.flags & SDL_Renderer_PresentFlip3) { + new_screen = (data->current_screen + 1) % 3; + } else { + new_screen = 0; + } + if (data->target == data->screens[data->current_screen]) { + data->target = data->screens[new_screen]; + } + data->current_screen = new_screen; +} + +static void +SDL_SW_DestroyTexture(SDL_Renderer * renderer, SDL_Texture * texture) +{ + if (SDL_ISPIXELFORMAT_FOURCC(texture->format)) { + SDL_SW_DestroyYUVTexture((SDL_SW_YUVTexture *) texture->driverdata); + } else { + SDL_Surface *surface = (SDL_Surface *) texture->driverdata; + + SDL_FreeSurface(surface); + } +} + +static void +SDL_SW_DestroyRenderer(SDL_Renderer * renderer) +{ + SDL_SW_RenderData *data = (SDL_SW_RenderData *) renderer->driverdata; + int i; + + if (data) { + for (i = 0; i < SDL_arraysize(data->screens); ++i) { + if (data->screens[i]) { + SDL_FreeSurface(data->screens[i]); + } + } + SDL_FreeDirtyRects(&data->dirty); + SDL_free(data); + } + SDL_free(renderer); +} + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/include/SDL_byteorder.h b/src/video/SDL_renderer_sw.h similarity index 84% rename from include/SDL_byteorder.h rename to src/video/SDL_renderer_sw.h index 3871cfed5..6dcdb44de 100644 --- a/include/SDL_byteorder.h +++ b/src/video/SDL_renderer_sw.h @@ -19,6 +19,10 @@ Sam Lantinga slouken@libsdl.org */ +#include "SDL_config.h" -/* DEPRECATED */ -#include "SDL_endian.h" +/* SDL surface based renderer implementation */ + +extern SDL_RenderDriver SDL_SW_RenderDriver; + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/SDL_stretch.c b/src/video/SDL_stretch.c index 2e08c10f3..45b914c6a 100644 --- a/src/video/SDL_stretch.c +++ b/src/video/SDL_stretch.c @@ -55,67 +55,68 @@ static unsigned char copy_row[4096]; -static int generate_rowbytes(int src_w, int dst_w, int bpp) +static int +generate_rowbytes(int src_w, int dst_w, int bpp) { - static struct { - int bpp; - int src_w; - int dst_w; - } last; - - int i; - int pos, inc; - unsigned char *eip; - unsigned char load, store; - - /* See if we need to regenerate the copy buffer */ - if ( (src_w == last.src_w) && - (dst_w == last.dst_w) && (bpp == last.bpp) ) { - return(0); - } - last.bpp = bpp; - last.src_w = src_w; - last.dst_w = dst_w; - - switch (bpp) { - case 1: - load = LOAD_BYTE; - store = STORE_BYTE; - break; - case 2: - case 4: - load = LOAD_WORD; - store = STORE_WORD; - break; - default: - SDL_SetError("ASM stretch of %d bytes isn't supported\n", bpp); - return(-1); - } - pos = 0x10000; - inc = (src_w << 16) / dst_w; - eip = copy_row; - for ( i=0; i= 0x10000L ) { - if ( bpp == 2 ) { - *eip++ = PREFIX16; - } - *eip++ = load; - pos -= 0x10000L; - } - if ( bpp == 2 ) { - *eip++ = PREFIX16; - } - *eip++ = store; - pos += inc; - } - *eip++ = RETURN; - - /* Verify that we didn't overflow (too late) */ - if ( eip > (copy_row+sizeof(copy_row)) ) { - SDL_SetError("Copy buffer overflow"); - return(-1); - } - return(0); + static struct + { + int bpp; + int src_w; + int dst_w; + } last; + + int i; + int pos, inc; + unsigned char *eip; + unsigned char load, store; + + /* See if we need to regenerate the copy buffer */ + if ((src_w == last.src_w) && (dst_w == last.dst_w) && (bpp == last.bpp)) { + return (0); + } + last.bpp = bpp; + last.src_w = src_w; + last.dst_w = dst_w; + + switch (bpp) { + case 1: + load = LOAD_BYTE; + store = STORE_BYTE; + break; + case 2: + case 4: + load = LOAD_WORD; + store = STORE_WORD; + break; + default: + SDL_SetError("ASM stretch of %d bytes isn't supported\n", bpp); + return (-1); + } + pos = 0x10000; + inc = (src_w << 16) / dst_w; + eip = copy_row; + for (i = 0; i < dst_w; ++i) { + while (pos >= 0x10000L) { + if (bpp == 2) { + *eip++ = PREFIX16; + } + *eip++ = load; + pos -= 0x10000L; + } + if (bpp == 2) { + *eip++ = PREFIX16; + } + *eip++ = store; + pos += inc; + } + *eip++ = RETURN; + + /* Verify that we didn't overflow (too late) */ + if (eip > (copy_row + sizeof(copy_row))) { + SDL_SetError("Copy buffer overflow"); + return (-1); + } + return (0); } #else @@ -139,196 +140,186 @@ void name(type *src, int src_w, type *dst, int dst_w) \ } \ } DEFINE_COPY_ROW(copy_row1, Uint8) -DEFINE_COPY_ROW(copy_row2, Uint16) -DEFINE_COPY_ROW(copy_row4, Uint32) - + DEFINE_COPY_ROW(copy_row2, Uint16) DEFINE_COPY_ROW(copy_row4, Uint32) #endif /* USE_ASM_STRETCH */ - /* The ASM code doesn't handle 24-bpp stretch blits */ -void copy_row3(Uint8 *src, int src_w, Uint8 *dst, int dst_w) + void + copy_row3(Uint8 * src, int src_w, Uint8 * dst, int dst_w) { - int i; - int pos, inc; - Uint8 pixel[3] = { 0, 0, 0 }; - - pos = 0x10000; - inc = (src_w << 16) / dst_w; - for ( i=dst_w; i>0; --i ) { - while ( pos >= 0x10000L ) { - pixel[0] = *src++; - pixel[1] = *src++; - pixel[2] = *src++; - pos -= 0x10000L; - } - *dst++ = pixel[0]; - *dst++ = pixel[1]; - *dst++ = pixel[2]; - pos += inc; - } + int i; + int pos, inc; + Uint8 pixel[3]; + + pos = 0x10000; + inc = (src_w << 16) / dst_w; + for (i = dst_w; i > 0; --i) { + while (pos >= 0x10000L) { + pixel[0] = *src++; + pixel[1] = *src++; + pixel[2] = *src++; + pos -= 0x10000L; + } + *dst++ = pixel[0]; + *dst++ = pixel[1]; + *dst++ = pixel[2]; + pos += inc; + } } /* Perform a stretch blit between two surfaces of the same format. NOTE: This function is not safe to call from multiple threads! */ -int SDL_SoftStretch(SDL_Surface *src, SDL_Rect *srcrect, - SDL_Surface *dst, SDL_Rect *dstrect) +int +SDL_SoftStretch(SDL_Surface * src, SDL_Rect * srcrect, + SDL_Surface * dst, SDL_Rect * dstrect) { - int src_locked; - int dst_locked; - int pos, inc; - int dst_width; - int dst_maxrow; - int src_row, dst_row; - Uint8 *srcp = NULL; - Uint8 *dstp; - SDL_Rect full_src; - SDL_Rect full_dst; + int src_locked; + int dst_locked; + int pos, inc; + int dst_width; + int dst_maxrow; + int src_row, dst_row; + Uint8 *srcp = NULL; + Uint8 *dstp; + SDL_Rect full_src; + SDL_Rect full_dst; #if defined(USE_ASM_STRETCH) && defined(__GNUC__) - int u1, u2; + int u1, u2; #endif - const int bpp = dst->format->BytesPerPixel; - - if ( src->format->BitsPerPixel != dst->format->BitsPerPixel ) { - SDL_SetError("Only works with same format surfaces"); - return(-1); - } - - /* Verify the blit rectangles */ - if ( srcrect ) { - if ( (srcrect->x < 0) || (srcrect->y < 0) || - ((srcrect->x+srcrect->w) > src->w) || - ((srcrect->y+srcrect->h) > src->h) ) { - SDL_SetError("Invalid source blit rectangle"); - return(-1); - } - } else { - full_src.x = 0; - full_src.y = 0; - full_src.w = src->w; - full_src.h = src->h; - srcrect = &full_src; - } - if ( dstrect ) { - if ( (dstrect->x < 0) || (dstrect->y < 0) || - ((dstrect->x+dstrect->w) > dst->w) || - ((dstrect->y+dstrect->h) > dst->h) ) { - SDL_SetError("Invalid destination blit rectangle"); - return(-1); - } - } else { - full_dst.x = 0; - full_dst.y = 0; - full_dst.w = dst->w; - full_dst.h = dst->h; - dstrect = &full_dst; - } - - /* Lock the destination if it's in hardware */ - dst_locked = 0; - if ( SDL_MUSTLOCK(dst) ) { - if ( SDL_LockSurface(dst) < 0 ) { - SDL_SetError("Unable to lock destination surface"); - return(-1); - } - dst_locked = 1; - } - /* Lock the source if it's in hardware */ - src_locked = 0; - if ( SDL_MUSTLOCK(src) ) { - if ( SDL_LockSurface(src) < 0 ) { - if ( dst_locked ) { - SDL_UnlockSurface(dst); - } - SDL_SetError("Unable to lock source surface"); - return(-1); - } - src_locked = 1; - } - - /* Set up the data... */ - pos = 0x10000; - inc = (srcrect->h << 16) / dstrect->h; - src_row = srcrect->y; - dst_row = dstrect->y; - dst_width = dstrect->w*bpp; + const int bpp = dst->format->BytesPerPixel; + + if (src->format->BitsPerPixel != dst->format->BitsPerPixel) { + SDL_SetError("Only works with same format surfaces"); + return (-1); + } + + /* Verify the blit rectangles */ + if (srcrect) { + if ((srcrect->x < 0) || (srcrect->y < 0) || + ((srcrect->x + srcrect->w) > src->w) || + ((srcrect->y + srcrect->h) > src->h)) { + SDL_SetError("Invalid source blit rectangle"); + return (-1); + } + } else { + full_src.x = 0; + full_src.y = 0; + full_src.w = src->w; + full_src.h = src->h; + srcrect = &full_src; + } + if (dstrect) { + if ((dstrect->x < 0) || (dstrect->y < 0) || + ((dstrect->x + dstrect->w) > dst->w) || + ((dstrect->y + dstrect->h) > dst->h)) { + SDL_SetError("Invalid destination blit rectangle"); + return (-1); + } + } else { + full_dst.x = 0; + full_dst.y = 0; + full_dst.w = dst->w; + full_dst.h = dst->h; + dstrect = &full_dst; + } + + /* Lock the destination if it's in hardware */ + dst_locked = 0; + if (SDL_MUSTLOCK(dst)) { + if (SDL_LockSurface(dst) < 0) { + SDL_SetError("Unable to lock destination surface"); + return (-1); + } + dst_locked = 1; + } + /* Lock the source if it's in hardware */ + src_locked = 0; + if (SDL_MUSTLOCK(src)) { + if (SDL_LockSurface(src) < 0) { + if (dst_locked) { + SDL_UnlockSurface(dst); + } + SDL_SetError("Unable to lock source surface"); + return (-1); + } + src_locked = 1; + } + + /* Set up the data... */ + pos = 0x10000; + inc = (srcrect->h << 16) / dstrect->h; + src_row = srcrect->y; + dst_row = dstrect->y; + dst_width = dstrect->w * bpp; #ifdef USE_ASM_STRETCH - /* Write the opcodes for this stretch */ - if ( (bpp != 3) && - (generate_rowbytes(srcrect->w, dstrect->w, bpp) < 0) ) { - return(-1); - } + /* Write the opcodes for this stretch */ + if ((bpp != 3) && (generate_rowbytes(srcrect->w, dstrect->w, bpp) < 0)) { + return (-1); + } #endif - /* Perform the stretch blit */ - for ( dst_maxrow = dst_row+dstrect->h; dst_rowpixels + (dst_row*dst->pitch) - + (dstrect->x*bpp); - while ( pos >= 0x10000L ) { - srcp = (Uint8 *)src->pixels + (src_row*src->pitch) - + (srcrect->x*bpp); - ++src_row; - pos -= 0x10000L; - } + /* Perform the stretch blit */ + for (dst_maxrow = dst_row + dstrect->h; dst_row < dst_maxrow; ++dst_row) { + dstp = (Uint8 *) dst->pixels + (dst_row * dst->pitch) + + (dstrect->x * bpp); + while (pos >= 0x10000L) { + srcp = (Uint8 *) src->pixels + (src_row * src->pitch) + + (srcrect->x * bpp); + ++src_row; + pos -= 0x10000L; + } #ifdef USE_ASM_STRETCH - switch (bpp) { - case 3: - copy_row3(srcp, srcrect->w, dstp, dstrect->w); - break; - default: + switch (bpp) { + case 3: + copy_row3(srcp, srcrect->w, dstp, dstrect->w); + break; + default: #ifdef __GNUC__ - __asm__ __volatile__ ( - "call *%4" - : "=&D" (u1), "=&S" (u2) - : "0" (dstp), "1" (srcp), "r" (copy_row) - : "memory" ); + __asm__ __volatile__("call *%4": "=&D"(u1), "=&S"(u2): "0"(dstp), "1"(srcp), "r"(copy_row):"memory"); #elif defined(_MSC_VER) || defined(__WATCOMC__) - { void *code = copy_row; - __asm { - push edi - push esi - - mov edi, dstp - mov esi, srcp - call dword ptr code - - pop esi - pop edi - } - } + { + void *code = copy_row; + __asm { + push edi + push esi + mov edi, dstp + mov esi, srcp call dword ptr code pop esi pop edi} + } #else #error Need inline assembly for this compiler #endif - break; - } + break; + } #else - switch (bpp) { - case 1: - copy_row1(srcp, srcrect->w, dstp, dstrect->w); - break; - case 2: - copy_row2((Uint16 *)srcp, srcrect->w, - (Uint16 *)dstp, dstrect->w); - break; - case 3: - copy_row3(srcp, srcrect->w, dstp, dstrect->w); - break; - case 4: - copy_row4((Uint32 *)srcp, srcrect->w, - (Uint32 *)dstp, dstrect->w); - break; - } + switch (bpp) { + case 1: + copy_row1(srcp, srcrect->w, dstp, dstrect->w); + break; + case 2: + copy_row2((Uint16 *) srcp, srcrect->w, + (Uint16 *) dstp, dstrect->w); + break; + case 3: + copy_row3(srcp, srcrect->w, dstp, dstrect->w); + break; + case 4: + copy_row4((Uint32 *) srcp, srcrect->w, + (Uint32 *) dstp, dstrect->w); + break; + } #endif - pos += inc; - } - - /* We need to unlock the surfaces if they're locked */ - if ( dst_locked ) { - SDL_UnlockSurface(dst); - } - if ( src_locked ) { - SDL_UnlockSurface(src); - } - return(0); + pos += inc; + } + + /* We need to unlock the surfaces if they're locked */ + if (dst_locked) { + SDL_UnlockSurface(dst); + } + if (src_locked) { + SDL_UnlockSurface(src); + } + return (0); } +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/SDL_stretch_c.h b/src/video/SDL_stretch_c.h index ee06b264f..48d82fdc3 100644 --- a/src/video/SDL_stretch_c.h +++ b/src/video/SDL_stretch_c.h @@ -24,6 +24,6 @@ /* Perform a stretch blit between two surfaces of the same format. NOTE: This function is not safe to call from multiple threads! */ -extern int SDL_SoftStretch(SDL_Surface *src, SDL_Rect *srcrect, - SDL_Surface *dst, SDL_Rect *dstrect); - +extern int SDL_SoftStretch(SDL_Surface * src, SDL_Rect * srcrect, + SDL_Surface * dst, SDL_Rect * dstrect); +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/SDL_surface.c b/src/video/SDL_surface.c index 7ef8565cb..87eae187a 100644 --- a/src/video/SDL_surface.c +++ b/src/video/SDL_surface.c @@ -22,8 +22,8 @@ #include "SDL_config.h" #include "SDL_video.h" +#include "SDL_compat.h" #include "SDL_sysvideo.h" -#include "SDL_cursor_c.h" #include "SDL_blit.h" #include "SDL_RLEaccel_c.h" #include "SDL_pixels_c.h" @@ -34,365 +34,414 @@ /* * Create an empty RGB surface of the appropriate depth */ -SDL_Surface * SDL_CreateRGBSurface (Uint32 flags, - int width, int height, int depth, - Uint32 Rmask, Uint32 Gmask, Uint32 Bmask, Uint32 Amask) +SDL_Surface * +SDL_CreateRGBSurface(Uint32 flags, + int width, int height, int depth, + Uint32 Rmask, Uint32 Gmask, Uint32 Bmask, Uint32 Amask) { - SDL_VideoDevice *video = current_video; - SDL_VideoDevice *this = current_video; - SDL_Surface *screen; - SDL_Surface *surface; - - /* Make sure the size requested doesn't overflow our datatypes */ - /* Next time I write a library like SDL, I'll use int for size. :) */ - if ( width >= 16384 || height >= 65536 ) { - SDL_SetError("Width or height is too large"); - return(NULL); - } - - /* Check to see if we desire the surface in video memory */ - if ( video ) { - screen = SDL_PublicSurface; - } else { - screen = NULL; - } - if ( screen && ((screen->flags&SDL_HWSURFACE) == SDL_HWSURFACE) ) { - if ( (flags&(SDL_SRCCOLORKEY|SDL_SRCALPHA)) != 0 ) { - flags |= SDL_HWSURFACE; - } - if ( (flags & SDL_SRCCOLORKEY) == SDL_SRCCOLORKEY ) { - if ( ! current_video->info.blit_hw_CC ) { - flags &= ~SDL_HWSURFACE; - } - } - if ( (flags & SDL_SRCALPHA) == SDL_SRCALPHA ) { - if ( ! current_video->info.blit_hw_A ) { - flags &= ~SDL_HWSURFACE; - } - } - } else { - flags &= ~SDL_HWSURFACE; - } - - /* Allocate the surface */ - surface = (SDL_Surface *)SDL_malloc(sizeof(*surface)); - if ( surface == NULL ) { - SDL_OutOfMemory(); - return(NULL); - } - surface->flags = SDL_SWSURFACE; - if ( (flags & SDL_HWSURFACE) == SDL_HWSURFACE ) { - if ((Amask) && (video->displayformatalphapixel)) - { - depth = video->displayformatalphapixel->BitsPerPixel; - Rmask = video->displayformatalphapixel->Rmask; - Gmask = video->displayformatalphapixel->Gmask; - Bmask = video->displayformatalphapixel->Bmask; - Amask = video->displayformatalphapixel->Amask; - } - else - { - depth = screen->format->BitsPerPixel; - Rmask = screen->format->Rmask; - Gmask = screen->format->Gmask; - Bmask = screen->format->Bmask; - Amask = screen->format->Amask; - } - } - surface->format = SDL_AllocFormat(depth, Rmask, Gmask, Bmask, Amask); - if ( surface->format == NULL ) { - SDL_free(surface); - return(NULL); - } - if ( Amask ) { - surface->flags |= SDL_SRCALPHA; - } - surface->w = width; - surface->h = height; - surface->pitch = SDL_CalculatePitch(surface); - surface->pixels = NULL; - surface->offset = 0; - surface->hwdata = NULL; - surface->locked = 0; - surface->map = NULL; - surface->unused1 = 0; - SDL_SetClipRect(surface, NULL); - SDL_FormatChanged(surface); - - /* Get the pixels */ - if ( ((flags&SDL_HWSURFACE) == SDL_SWSURFACE) || - (video->AllocHWSurface(this, surface) < 0) ) { - if ( surface->w && surface->h ) { - surface->pixels = SDL_malloc(surface->h*surface->pitch); - if ( surface->pixels == NULL ) { - SDL_FreeSurface(surface); - SDL_OutOfMemory(); - return(NULL); - } - /* This is important for bitmaps */ - SDL_memset(surface->pixels, 0, surface->h*surface->pitch); - } - } - - /* Allocate an empty mapping */ - surface->map = SDL_AllocBlitMap(); - if ( surface->map == NULL ) { - SDL_FreeSurface(surface); - return(NULL); - } - - /* The surface is ready to go */ - surface->refcount = 1; + SDL_Surface *surface; + + /* Allocate the surface */ + surface = (SDL_Surface *) SDL_malloc(sizeof(*surface)); + if (surface == NULL) { + SDL_OutOfMemory(); + return NULL; + } + SDL_zerop(surface); + + surface->format = SDL_AllocFormat(depth, Rmask, Gmask, Bmask, Amask); + if (!surface->format) { + SDL_FreeSurface(surface); + return NULL; + } + if (Amask) { + surface->flags |= SDL_SRCALPHA; + } + surface->w = width; + surface->h = height; + surface->pitch = SDL_CalculatePitch(surface); + SDL_SetClipRect(surface, NULL); + + if (surface->format->BitsPerPixel <= 8) { + SDL_Palette *palette = + SDL_AllocPalette((1 << surface->format->BitsPerPixel)); + if (!palette) { + SDL_FreeSurface(surface); + return NULL; + } + if (Rmask || Bmask || Gmask) { + const SDL_PixelFormat *format = surface->format; + + /* create palette according to masks */ + int i; + int Rm = 0, Gm = 0, Bm = 0; + int Rw = 0, Gw = 0, Bw = 0; + + if (Rmask) { + Rw = 8 - format->Rloss; + for (i = format->Rloss; i > 0; i -= Rw) + Rm |= 1 << i; + } + if (Gmask) { + Gw = 8 - format->Gloss; + for (i = format->Gloss; i > 0; i -= Gw) + Gm |= 1 << i; + } + if (Bmask) { + Bw = 8 - format->Bloss; + for (i = format->Bloss; i > 0; i -= Bw) + Bm |= 1 << i; + } + for (i = 0; i < palette->ncolors; ++i) { + int r, g, b; + r = (i & Rmask) >> format->Rshift; + r = (r << format->Rloss) | ((r * Rm) >> Rw); + palette->colors[i].r = r; + + g = (i & Gmask) >> format->Gshift; + g = (g << format->Gloss) | ((g * Gm) >> Gw); + palette->colors[i].g = g; + + b = (i & Bmask) >> format->Bshift; + b = (b << format->Bloss) | ((b * Bm) >> Bw); + palette->colors[i].b = b; + } + } else if (palette->ncolors == 2) { + /* Create a black and white bitmap palette */ + palette->colors[0].r = 0xFF; + palette->colors[0].g = 0xFF; + palette->colors[0].b = 0xFF; + palette->colors[1].r = 0x00; + palette->colors[1].g = 0x00; + palette->colors[1].b = 0x00; + } + SDL_SetSurfacePalette(surface, palette); + SDL_FreePalette(palette); + } + + /* Get the pixels */ + if (surface->w && surface->h) { + surface->pixels = SDL_malloc(surface->h * surface->pitch); + if (!surface->pixels) { + SDL_FreeSurface(surface); + SDL_OutOfMemory(); + return NULL; + } + /* This is important for bitmaps */ + SDL_memset(surface->pixels, 0, surface->h * surface->pitch); + } + + /* Allocate an empty mapping */ + surface->map = SDL_AllocBlitMap(); + if (!surface->map) { + SDL_FreeSurface(surface); + return NULL; + } + SDL_FormatChanged(surface); + + /* The surface is ready to go */ + surface->refcount = 1; #ifdef CHECK_LEAKS - ++surfaces_allocated; + ++surfaces_allocated; #endif - return(surface); + return surface; } + /* * Create an RGB surface from an existing memory buffer */ -SDL_Surface * SDL_CreateRGBSurfaceFrom (void *pixels, - int width, int height, int depth, int pitch, - Uint32 Rmask, Uint32 Gmask, Uint32 Bmask, Uint32 Amask) +SDL_Surface * +SDL_CreateRGBSurfaceFrom(void *pixels, + int width, int height, int depth, int pitch, + Uint32 Rmask, Uint32 Gmask, Uint32 Bmask, + Uint32 Amask) +{ + SDL_Surface *surface; + + surface = + SDL_CreateRGBSurface(0, 0, 0, depth, Rmask, Gmask, Bmask, Amask); + if (surface != NULL) { + surface->flags |= SDL_PREALLOC; + surface->pixels = pixels; + surface->w = width; + surface->h = height; + surface->pitch = pitch; + SDL_SetClipRect(surface, NULL); + } + return surface; +} + +SDL_Surface * +SDL_CreateRGBSurfaceFromTexture(SDL_TextureID textureID) +{ + SDL_Surface *surface; + Uint32 format; + int w, h; + int bpp; + Uint32 Rmask, Gmask, Bmask, Amask; + void *pixels; + int pitch; + + if (SDL_QueryTexture(textureID, &format, NULL, &w, &h) < 0) { + return NULL; + } + + if (!SDL_PixelFormatEnumToMasks + (format, &bpp, &Rmask, &Gmask, &Bmask, &Amask)) { + SDL_SetError("Unknown texture format"); + return NULL; + } + + if (SDL_QueryTexturePixels(textureID, &pixels, &pitch) == 0) { + surface = + SDL_CreateRGBSurfaceFrom(pixels, w, h, bpp, pitch, Rmask, Gmask, + Bmask, Amask); + } else { + surface = + SDL_CreateRGBSurface(0, 0, 0, bpp, Rmask, Gmask, Bmask, Amask); + if (surface) { + surface->flags |= SDL_HWSURFACE; + surface->w = w; + surface->h = h; + surface->pitch = SDL_CalculatePitch(surface); + SDL_SetClipRect(surface, NULL); + } + } + if (surface) { + surface->textureID = textureID; + } + + return surface; +} + +static int +SDL_SurfacePaletteChanged(void *userdata, SDL_Palette * palette) +{ + SDL_Surface *surface = (SDL_Surface *) userdata; + + if (surface->textureID) { + if (SDL_SetTexturePalette + (surface->textureID, palette->colors, 0, palette->ncolors) < 0) { + SDL_GetTexturePalette(surface->textureID, palette->colors, 0, + palette->ncolors); + return -1; + } + } + SDL_FormatChanged(surface); + + return 0; +} + +int +SDL_SetSurfacePalette(SDL_Surface * surface, SDL_Palette * palette) { - SDL_Surface *surface; - - surface = SDL_CreateRGBSurface(SDL_SWSURFACE, 0, 0, depth, - Rmask, Gmask, Bmask, Amask); - if ( surface != NULL ) { - surface->flags |= SDL_PREALLOC; - surface->pixels = pixels; - surface->w = width; - surface->h = height; - surface->pitch = pitch; - SDL_SetClipRect(surface, NULL); - } - return(surface); + if (!surface || !surface->format) { + SDL_SetError("SDL_SetSurfacePalette() passed a NULL surface"); + return -1; + } + + if (palette && palette->ncolors != (1 << surface->format->BitsPerPixel)) { + SDL_SetError + ("SDL_SetSurfacePalette() passed a palette that doesn't match the surface format"); + return -1; + } + + if (surface->format->palette == palette) { + return 0; + } + + if (surface->format->palette) { + SDL_DelPaletteWatch(surface->format->palette, + SDL_SurfacePaletteChanged, surface); + } + + surface->format->palette = palette; + + if (surface->format->palette) { + SDL_AddPaletteWatch(surface->format->palette, + SDL_SurfacePaletteChanged, surface); + } + return 0; } + /* * Set the color key in a blittable surface */ -int SDL_SetColorKey (SDL_Surface *surface, Uint32 flag, Uint32 key) +int +SDL_SetColorKey(SDL_Surface * surface, Uint32 flag, Uint32 key) { - /* Sanity check the flag as it gets passed in */ - if ( flag & SDL_SRCCOLORKEY ) { - if ( flag & (SDL_RLEACCEL|SDL_RLEACCELOK) ) { - flag = (SDL_SRCCOLORKEY | SDL_RLEACCELOK); - } else { - flag = SDL_SRCCOLORKEY; - } - } else { - flag = 0; - } - - /* Optimize away operations that don't change anything */ - if ( (flag == (surface->flags & (SDL_SRCCOLORKEY|SDL_RLEACCELOK))) && - (key == surface->format->colorkey) ) { - return(0); - } - - /* UnRLE surfaces before we change the colorkey */ - if ( surface->flags & SDL_RLEACCEL ) { - SDL_UnRLESurface(surface, 1); - } - - if ( flag ) { - SDL_VideoDevice *video = current_video; - SDL_VideoDevice *this = current_video; - - - surface->flags |= SDL_SRCCOLORKEY; - surface->format->colorkey = key; - if ( (surface->flags & SDL_HWACCEL) == SDL_HWACCEL ) { - if ( (video->SetHWColorKey == NULL) || - (video->SetHWColorKey(this, surface, key) < 0) ) { - surface->flags &= ~SDL_HWACCEL; - } - } - if ( flag & SDL_RLEACCELOK ) { - surface->flags |= SDL_RLEACCELOK; - } else { - surface->flags &= ~SDL_RLEACCELOK; - } - } else { - surface->flags &= ~(SDL_SRCCOLORKEY|SDL_RLEACCELOK); - surface->format->colorkey = 0; - } - SDL_InvalidateMap(surface->map); - return(0); + /* Sanity check the flag as it gets passed in */ + if (flag & SDL_SRCCOLORKEY) { + if (flag & (SDL_RLEACCEL | SDL_RLEACCELOK)) { + flag = (SDL_SRCCOLORKEY | SDL_RLEACCELOK); + } else { + flag = SDL_SRCCOLORKEY; + } + } else { + flag = 0; + } + + /* Optimize away operations that don't change anything */ + if ((flag == (surface->flags & (SDL_SRCCOLORKEY | SDL_RLEACCELOK))) && + (key == surface->format->colorkey)) { + return (0); + } + + /* UnRLE surfaces before we change the colorkey */ + if (surface->flags & SDL_RLEACCEL) { + SDL_UnRLESurface(surface, 1); + } + + if (flag) { + surface->flags |= SDL_SRCCOLORKEY; + surface->format->colorkey = key; + if (flag & SDL_RLEACCELOK) { + surface->flags |= SDL_RLEACCELOK; + } else { + surface->flags &= ~SDL_RLEACCELOK; + } + } else { + surface->flags &= ~(SDL_SRCCOLORKEY | SDL_RLEACCELOK); + surface->format->colorkey = 0; + } + SDL_InvalidateMap(surface->map); + return (0); } + /* This function sets the alpha channel of a surface */ -int SDL_SetAlpha (SDL_Surface *surface, Uint32 flag, Uint8 value) +int +SDL_SetAlpha(SDL_Surface * surface, Uint32 flag, Uint8 value) { - Uint32 oldflags = surface->flags; - Uint32 oldalpha = surface->format->alpha; - - /* Sanity check the flag as it gets passed in */ - if ( flag & SDL_SRCALPHA ) { - if ( flag & (SDL_RLEACCEL|SDL_RLEACCELOK) ) { - flag = (SDL_SRCALPHA | SDL_RLEACCELOK); - } else { - flag = SDL_SRCALPHA; - } - } else { - flag = 0; - } - - /* Optimize away operations that don't change anything */ - if ( (flag == (surface->flags & (SDL_SRCALPHA|SDL_RLEACCELOK))) && - (!flag || value == oldalpha) ) { - return(0); - } - - if(!(flag & SDL_RLEACCELOK) && (surface->flags & SDL_RLEACCEL)) - SDL_UnRLESurface(surface, 1); - - if ( flag ) { - SDL_VideoDevice *video = current_video; - SDL_VideoDevice *this = current_video; - - surface->flags |= SDL_SRCALPHA; - surface->format->alpha = value; - if ( (surface->flags & SDL_HWACCEL) == SDL_HWACCEL ) { - if ( (video->SetHWAlpha == NULL) || - (video->SetHWAlpha(this, surface, value) < 0) ) { - surface->flags &= ~SDL_HWACCEL; - } - } - if ( flag & SDL_RLEACCELOK ) { - surface->flags |= SDL_RLEACCELOK; - } else { - surface->flags &= ~SDL_RLEACCELOK; - } - } else { - surface->flags &= ~SDL_SRCALPHA; - surface->format->alpha = SDL_ALPHA_OPAQUE; - } - /* - * The representation for software surfaces is independent of - * per-surface alpha, so no need to invalidate the blit mapping - * if just the alpha value was changed. (If either is 255, we still - * need to invalidate.) - */ - if((surface->flags & SDL_HWACCEL) == SDL_HWACCEL - || oldflags != surface->flags - || (((oldalpha + 1) ^ (value + 1)) & 0x100)) - SDL_InvalidateMap(surface->map); - return(0); + Uint32 oldflags = surface->flags; + Uint32 oldalpha = surface->format->alpha; + + /* Sanity check the flag as it gets passed in */ + if (flag & SDL_SRCALPHA) { + if (flag & (SDL_RLEACCEL | SDL_RLEACCELOK)) { + flag = (SDL_SRCALPHA | SDL_RLEACCELOK); + } else { + flag = SDL_SRCALPHA; + } + } else { + flag = 0; + } + + /* Optimize away operations that don't change anything */ + if ((flag == (surface->flags & (SDL_SRCALPHA | SDL_RLEACCELOK))) && + (!flag || value == oldalpha)) { + return (0); + } + + if (!(flag & SDL_RLEACCELOK) && (surface->flags & SDL_RLEACCEL)) + SDL_UnRLESurface(surface, 1); + + if (flag) { + surface->flags |= SDL_SRCALPHA; + surface->format->alpha = value; + if (flag & SDL_RLEACCELOK) { + surface->flags |= SDL_RLEACCELOK; + } else { + surface->flags &= ~SDL_RLEACCELOK; + } + } else { + surface->flags &= ~SDL_SRCALPHA; + surface->format->alpha = SDL_ALPHA_OPAQUE; + } + /* + * The representation for software surfaces is independent of + * per-surface alpha, so no need to invalidate the blit mapping + * if just the alpha value was changed. (If either is 255, we still + * need to invalidate.) + */ + if (oldflags != surface->flags + || (((oldalpha + 1) ^ (value + 1)) & 0x100)) { + SDL_InvalidateMap(surface->map); + } + return (0); } -int SDL_SetAlphaChannel(SDL_Surface *surface, Uint8 value) -{ - int row, col; - int offset; - Uint8 *buf; - - if ( (surface->format->Amask != 0xFF000000) && - (surface->format->Amask != 0x000000FF) ) { - SDL_SetError("Unsupported surface alpha mask format"); - return -1; - } +int +SDL_SetAlphaChannel(SDL_Surface * surface, Uint8 value) +{ + int row, col; + int offset; + Uint8 *buf; + + if ((surface->format->Amask != 0xFF000000) && + (surface->format->Amask != 0x000000FF)) { + SDL_SetError("Unsupported surface alpha mask format"); + return -1; + } #if SDL_BYTEORDER == SDL_LIL_ENDIAN - if ( surface->format->Amask == 0xFF000000 ) { - offset = 3; - } else { - offset = 0; - } + if (surface->format->Amask == 0xFF000000) { + offset = 3; + } else { + offset = 0; + } #else - if ( surface->format->Amask == 0xFF000000 ) { - offset = 0; - } else { - offset = 3; - } + if (surface->format->Amask == 0xFF000000) { + offset = 0; + } else { + offset = 3; + } #endif /* Byte ordering */ - /* Quickly set the alpha channel of an RGBA or ARGB surface */ - if ( SDL_MUSTLOCK(surface) ) { - if ( SDL_LockSurface(surface) < 0 ) { - return -1; - } - } - row = surface->h; - while (row--) { - col = surface->w; - buf = (Uint8 *)surface->pixels + row * surface->pitch + offset; - while(col--) { - *buf = value; - buf += 4; - } - } - if ( SDL_MUSTLOCK(surface) ) { - SDL_UnlockSurface(surface); - } - return 0; + /* Quickly set the alpha channel of an RGBA or ARGB surface */ + if (SDL_MUSTLOCK(surface)) { + if (SDL_LockSurface(surface) < 0) { + return -1; + } + } + row = surface->h; + while (row--) { + col = surface->w; + buf = (Uint8 *) surface->pixels + row * surface->pitch + offset; + while (col--) { + *buf = value; + buf += 4; + } + } + if (SDL_MUSTLOCK(surface)) { + SDL_UnlockSurface(surface); + } + return 0; } -/* - * A function to calculate the intersection of two rectangles: - * return true if the rectangles intersect, false otherwise - */ -static __inline__ -SDL_bool SDL_IntersectRect(const SDL_Rect *A, const SDL_Rect *B, SDL_Rect *intersection) -{ - int Amin, Amax, Bmin, Bmax; - - /* Horizontal intersection */ - Amin = A->x; - Amax = Amin + A->w; - Bmin = B->x; - Bmax = Bmin + B->w; - if(Bmin > Amin) - Amin = Bmin; - intersection->x = Amin; - if(Bmax < Amax) - Amax = Bmax; - intersection->w = Amax - Amin > 0 ? Amax - Amin : 0; - - /* Vertical intersection */ - Amin = A->y; - Amax = Amin + A->h; - Bmin = B->y; - Bmax = Bmin + B->h; - if(Bmin > Amin) - Amin = Bmin; - intersection->y = Amin; - if(Bmax < Amax) - Amax = Bmax; - intersection->h = Amax - Amin > 0 ? Amax - Amin : 0; - - return (intersection->w && intersection->h); -} /* * Set the clipping rectangle for a blittable surface */ -SDL_bool SDL_SetClipRect(SDL_Surface *surface, const SDL_Rect *rect) +SDL_bool +SDL_SetClipRect(SDL_Surface * surface, const SDL_Rect * rect) { - SDL_Rect full_rect; - - /* Don't do anything if there's no surface to act on */ - if ( ! surface ) { - return SDL_FALSE; - } - - /* Set up the full surface rectangle */ - full_rect.x = 0; - full_rect.y = 0; - full_rect.w = surface->w; - full_rect.h = surface->h; - - /* Set the clipping rectangle */ - if ( ! rect ) { - surface->clip_rect = full_rect; - return 1; - } - return SDL_IntersectRect(rect, &full_rect, &surface->clip_rect); + SDL_Rect full_rect; + + /* Don't do anything if there's no surface to act on */ + if (!surface) { + return SDL_FALSE; + } + + /* Set up the full surface rectangle */ + full_rect.x = 0; + full_rect.y = 0; + full_rect.w = surface->w; + full_rect.h = surface->h; + + /* Set the clipping rectangle */ + if (!rect) { + surface->clip_rect = full_rect; + return 1; + } + return SDL_IntersectRect(rect, &full_rect, &surface->clip_rect); } -void SDL_GetClipRect(SDL_Surface *surface, SDL_Rect *rect) + +void +SDL_GetClipRect(SDL_Surface * surface, SDL_Rect * rect) { - if ( surface && rect ) { - *rect = surface->clip_rect; - } + if (surface && rect) { + *rect = surface->clip_rect; + } } + /* * Set up a blit between two surfaces -- split into three parts: * The upper part, SDL_UpperBlit(), performs clipping and rectangle @@ -404,538 +453,494 @@ void SDL_GetClipRect(SDL_Surface *surface, SDL_Rect *rect) * you know exactly what you are doing, you can optimize your code * by calling the one(s) you need. */ -int SDL_LowerBlit (SDL_Surface *src, SDL_Rect *srcrect, - SDL_Surface *dst, SDL_Rect *dstrect) +int +SDL_LowerBlit(SDL_Surface * src, SDL_Rect * srcrect, + SDL_Surface * dst, SDL_Rect * dstrect) { - SDL_blit do_blit; - SDL_Rect hw_srcrect; - SDL_Rect hw_dstrect; - - /* Check to make sure the blit mapping is valid */ - if ( (src->map->dst != dst) || - (src->map->dst->format_version != src->map->format_version) ) { - if ( SDL_MapSurface(src, dst) < 0 ) { - return(-1); - } - } - - /* Figure out which blitter to use */ - if ( (src->flags & SDL_HWACCEL) == SDL_HWACCEL ) { - if ( src == SDL_VideoSurface ) { - hw_srcrect = *srcrect; - hw_srcrect.x += current_video->offset_x; - hw_srcrect.y += current_video->offset_y; - srcrect = &hw_srcrect; - } - if ( dst == SDL_VideoSurface ) { - hw_dstrect = *dstrect; - hw_dstrect.x += current_video->offset_x; - hw_dstrect.y += current_video->offset_y; - dstrect = &hw_dstrect; - } - do_blit = src->map->hw_blit; - } else { - do_blit = src->map->sw_blit; - } - return(do_blit(src, srcrect, dst, dstrect)); + /* Check to make sure the blit mapping is valid */ + if ((src->map->dst != dst) || + (src->map->dst->format_version != src->map->format_version)) { + if (SDL_MapSurface(src, dst) < 0) { + return (-1); + } + } + return (src->map->sw_blit(src, srcrect, dst, dstrect)); } -int SDL_UpperBlit (SDL_Surface *src, SDL_Rect *srcrect, - SDL_Surface *dst, SDL_Rect *dstrect) +int +SDL_UpperBlit(SDL_Surface * src, SDL_Rect * srcrect, + SDL_Surface * dst, SDL_Rect * dstrect) { - SDL_Rect fulldst; - int srcx, srcy, w, h; - - /* Make sure the surfaces aren't locked */ - if ( ! src || ! dst ) { - SDL_SetError("SDL_UpperBlit: passed a NULL surface"); - return(-1); - } - if ( src->locked || dst->locked ) { - SDL_SetError("Surfaces must not be locked during blit"); - return(-1); - } - - /* If the destination rectangle is NULL, use the entire dest surface */ - if ( dstrect == NULL ) { - fulldst.x = fulldst.y = 0; - dstrect = &fulldst; - } - - /* clip the source rectangle to the source surface */ - if(srcrect) { - int maxw, maxh; - - srcx = srcrect->x; - w = srcrect->w; - if(srcx < 0) { - w += srcx; - dstrect->x -= srcx; - srcx = 0; - } - maxw = src->w - srcx; - if(maxw < w) - w = maxw; - - srcy = srcrect->y; - h = srcrect->h; - if(srcy < 0) { - h += srcy; - dstrect->y -= srcy; - srcy = 0; - } - maxh = src->h - srcy; - if(maxh < h) - h = maxh; - - } else { - srcx = srcy = 0; - w = src->w; - h = src->h; - } - - /* clip the destination rectangle against the clip rectangle */ - { - SDL_Rect *clip = &dst->clip_rect; - int dx, dy; - - dx = clip->x - dstrect->x; - if(dx > 0) { - w -= dx; - dstrect->x += dx; - srcx += dx; - } - dx = dstrect->x + w - clip->x - clip->w; - if(dx > 0) - w -= dx; - - dy = clip->y - dstrect->y; - if(dy > 0) { - h -= dy; - dstrect->y += dy; - srcy += dy; - } - dy = dstrect->y + h - clip->y - clip->h; - if(dy > 0) - h -= dy; - } - - if(w > 0 && h > 0) { - SDL_Rect sr; - sr.x = srcx; - sr.y = srcy; - sr.w = dstrect->w = w; - sr.h = dstrect->h = h; - return SDL_LowerBlit(src, &sr, dst, dstrect); - } - dstrect->w = dstrect->h = 0; - return 0; + SDL_Rect fulldst; + int srcx, srcy, w, h; + + /* Make sure the surfaces aren't locked */ + if (!src || !dst) { + SDL_SetError("SDL_UpperBlit: passed a NULL surface"); + return (-1); + } + if (src->locked || dst->locked) { + SDL_SetError("Surfaces must not be locked during blit"); + return (-1); + } + + /* If the destination rectangle is NULL, use the entire dest surface */ + if (dstrect == NULL) { + fulldst.x = fulldst.y = 0; + dstrect = &fulldst; + } + + /* clip the source rectangle to the source surface */ + if (srcrect) { + int maxw, maxh; + + srcx = srcrect->x; + w = srcrect->w; + if (srcx < 0) { + w += srcx; + dstrect->x -= srcx; + srcx = 0; + } + maxw = src->w - srcx; + if (maxw < w) + w = maxw; + + srcy = srcrect->y; + h = srcrect->h; + if (srcy < 0) { + h += srcy; + dstrect->y -= srcy; + srcy = 0; + } + maxh = src->h - srcy; + if (maxh < h) + h = maxh; + + } else { + srcx = srcy = 0; + w = src->w; + h = src->h; + } + + /* clip the destination rectangle against the clip rectangle */ + { + SDL_Rect *clip = &dst->clip_rect; + int dx, dy; + + dx = clip->x - dstrect->x; + if (dx > 0) { + w -= dx; + dstrect->x += dx; + srcx += dx; + } + dx = dstrect->x + w - clip->x - clip->w; + if (dx > 0) + w -= dx; + + dy = clip->y - dstrect->y; + if (dy > 0) { + h -= dy; + dstrect->y += dy; + srcy += dy; + } + dy = dstrect->y + h - clip->y - clip->h; + if (dy > 0) + h -= dy; + } + + if (w > 0 && h > 0) { + SDL_Rect sr; + sr.x = srcx; + sr.y = srcy; + sr.w = dstrect->w = w; + sr.h = dstrect->h = h; + return SDL_LowerBlit(src, &sr, dst, dstrect); + } + dstrect->w = dstrect->h = 0; + return 0; } -static int SDL_FillRect1(SDL_Surface *dst, SDL_Rect *dstrect, Uint32 color) +static int +SDL_FillRect1(SDL_Surface * dst, SDL_Rect * dstrect, Uint32 color) { - /* FIXME: We have to worry about packing order.. *sigh* */ - SDL_SetError("1-bpp rect fill not yet implemented"); - return -1; + /* FIXME: We have to worry about packing order.. *sigh* */ + SDL_SetError("1-bpp rect fill not yet implemented"); + return -1; } -static int SDL_FillRect4(SDL_Surface *dst, SDL_Rect *dstrect, Uint32 color) +static int +SDL_FillRect4(SDL_Surface * dst, SDL_Rect * dstrect, Uint32 color) { - /* FIXME: We have to worry about packing order.. *sigh* */ - SDL_SetError("4-bpp rect fill not yet implemented"); - return -1; + /* FIXME: We have to worry about packing order.. *sigh* */ + SDL_SetError("4-bpp rect fill not yet implemented"); + return -1; } /* * This function performs a fast fill of the given rectangle with 'color' */ -int SDL_FillRect(SDL_Surface *dst, SDL_Rect *dstrect, Uint32 color) +int +SDL_FillRect(SDL_Surface * dst, SDL_Rect * dstrect, Uint32 color) { - SDL_VideoDevice *video = current_video; - SDL_VideoDevice *this = current_video; - int x, y; - Uint8 *row; - - /* This function doesn't work on surfaces < 8 bpp */ - if ( dst->format->BitsPerPixel < 8 ) { - switch(dst->format->BitsPerPixel) { - case 1: - return SDL_FillRect1(dst, dstrect, color); - break; - case 4: - return SDL_FillRect4(dst, dstrect, color); - break; - default: - SDL_SetError("Fill rect on unsupported surface format"); - return(-1); - break; - } - } - - /* If 'dstrect' == NULL, then fill the whole surface */ - if ( dstrect ) { - /* Perform clipping */ - if ( !SDL_IntersectRect(dstrect, &dst->clip_rect, dstrect) ) { - return(0); - } - } else { - dstrect = &dst->clip_rect; - } - - /* Check for hardware acceleration */ - if ( ((dst->flags & SDL_HWSURFACE) == SDL_HWSURFACE) && - video->info.blit_fill ) { - SDL_Rect hw_rect; - if ( dst == SDL_VideoSurface ) { - hw_rect = *dstrect; - hw_rect.x += current_video->offset_x; - hw_rect.y += current_video->offset_y; - dstrect = &hw_rect; - } - return(video->FillHWRect(this, dst, dstrect, color)); - } - - /* Perform software fill */ - if ( SDL_LockSurface(dst) != 0 ) { - return(-1); - } - row = (Uint8 *)dst->pixels+dstrect->y*dst->pitch+ - dstrect->x*dst->format->BytesPerPixel; - if ( dst->format->palette || (color == 0) ) { - x = dstrect->w*dst->format->BytesPerPixel; - if ( !color && !((uintptr_t)row&3) && !(x&3) && !(dst->pitch&3) ) { - int n = x >> 2; - for ( y=dstrect->h; y; --y ) { - SDL_memset4(row, 0, n); - row += dst->pitch; - } - } else { + int x, y; + Uint8 *row; + + /* This function doesn't work on surfaces < 8 bpp */ + if (dst->format->BitsPerPixel < 8) { + switch (dst->format->BitsPerPixel) { + case 1: + return SDL_FillRect1(dst, dstrect, color); + break; + case 4: + return SDL_FillRect4(dst, dstrect, color); + break; + default: + SDL_SetError("Fill rect on unsupported surface format"); + return (-1); + break; + } + } + + /* If 'dstrect' == NULL, then fill the whole surface */ + if (dstrect) { + /* Perform clipping */ + if (!SDL_IntersectRect(dstrect, &dst->clip_rect, dstrect)) { + return (0); + } + } else { + dstrect = &dst->clip_rect; + } + + /* Perform software fill */ + if (SDL_LockSurface(dst) != 0) { + return (-1); + } + row = (Uint8 *) dst->pixels + dstrect->y * dst->pitch + + dstrect->x * dst->format->BytesPerPixel; + if (dst->format->palette || (color == 0)) { + x = dstrect->w * dst->format->BytesPerPixel; + if (!color && !((uintptr_t) row & 3) && !(x & 3) + && !(dst->pitch & 3)) { + int n = x >> 2; + for (y = dstrect->h; y; --y) { + SDL_memset4(row, 0, n); + row += dst->pitch; + } + } else { #ifdef __powerpc__ - /* - * SDL_memset() on PPC (both glibc and codewarrior) uses - * the dcbz (Data Cache Block Zero) instruction, which - * causes an alignment exception if the destination is - * uncachable, so only use it on software surfaces - */ - if((dst->flags & SDL_HWSURFACE) == SDL_HWSURFACE) { - if(dstrect->w >= 8) { - /* - * 64-bit stores are probably most - * efficient to uncached video memory - */ - double fill; - SDL_memset(&fill, color, (sizeof fill)); - for(y = dstrect->h; y; y--) { - Uint8 *d = row; - unsigned n = x; - unsigned nn; - Uint8 c = color; - double f = fill; - while((unsigned long)d - & (sizeof(double) - 1)) { - *d++ = c; - n--; - } - nn = n / (sizeof(double) * 4); - while(nn) { - ((double *)d)[0] = f; - ((double *)d)[1] = f; - ((double *)d)[2] = f; - ((double *)d)[3] = f; - d += 4*sizeof(double); - nn--; - } - n &= ~(sizeof(double) * 4 - 1); - nn = n / sizeof(double); - while(nn) { - *(double *)d = f; - d += sizeof(double); - nn--; - } - n &= ~(sizeof(double) - 1); - while(n) { - *d++ = c; - n--; - } - row += dst->pitch; - } - } else { - /* narrow boxes */ - for(y = dstrect->h; y; y--) { - Uint8 *d = row; - Uint8 c = color; - int n = x; - while(n) { - *d++ = c; - n--; - } - row += dst->pitch; - } - } - } else + /* + * SDL_memset() on PPC (both glibc and codewarrior) uses + * the dcbz (Data Cache Block Zero) instruction, which + * causes an alignment exception if the destination is + * uncachable, so only use it on software surfaces + */ + if (dst->flags & SDL_HWSURFACE) { + if (dstrect->w >= 8) { + /* + * 64-bit stores are probably most + * efficient to uncached video memory + */ + double fill; + SDL_memset(&fill, color, (sizeof fill)); + for (y = dstrect->h; y; y--) { + Uint8 *d = row; + unsigned n = x; + unsigned nn; + Uint8 c = color; + double f = fill; + while ((unsigned long) d & (sizeof(double) - 1)) { + *d++ = c; + n--; + } + nn = n / (sizeof(double) * 4); + while (nn) { + ((double *) d)[0] = f; + ((double *) d)[1] = f; + ((double *) d)[2] = f; + ((double *) d)[3] = f; + d += 4 * sizeof(double); + nn--; + } + n &= ~(sizeof(double) * 4 - 1); + nn = n / sizeof(double); + while (nn) { + *(double *) d = f; + d += sizeof(double); + nn--; + } + n &= ~(sizeof(double) - 1); + while (n) { + *d++ = c; + n--; + } + row += dst->pitch; + } + } else { + /* narrow boxes */ + for (y = dstrect->h; y; y--) { + Uint8 *d = row; + Uint8 c = color; + int n = x; + while (n) { + *d++ = c; + n--; + } + row += dst->pitch; + } + } + } else #endif /* __powerpc__ */ - { - for(y = dstrect->h; y; y--) { - SDL_memset(row, color, x); - row += dst->pitch; - } - } - } - } else { - switch (dst->format->BytesPerPixel) { - case 2: - for ( y=dstrect->h; y; --y ) { - Uint16 *pixels = (Uint16 *)row; - Uint16 c = (Uint16)color; - Uint32 cc = (Uint32)c << 16 | c; - int n = dstrect->w; - if((uintptr_t)pixels & 3) { - *pixels++ = c; - n--; - } - if(n >> 1) - SDL_memset4(pixels, cc, n >> 1); - if(n & 1) - pixels[n - 1] = c; - row += dst->pitch; - } - break; - - case 3: - #if SDL_BYTEORDER == SDL_BIG_ENDIAN - color <<= 8; - #endif - for ( y=dstrect->h; y; --y ) { - Uint8 *pixels = row; - for ( x=dstrect->w; x; --x ) { - SDL_memcpy(pixels, &color, 3); - pixels += 3; - } - row += dst->pitch; - } - break; - - case 4: - for(y = dstrect->h; y; --y) { - SDL_memset4(row, color, dstrect->w); - row += dst->pitch; - } - break; - } - } - SDL_UnlockSurface(dst); - - /* We're done! */ - return(0); + { + for (y = dstrect->h; y; y--) { + SDL_memset(row, color, x); + row += dst->pitch; + } + } + } + } else { + switch (dst->format->BytesPerPixel) { + case 2: + for (y = dstrect->h; y; --y) { + Uint16 *pixels = (Uint16 *) row; + Uint16 c = (Uint16) color; + Uint32 cc = (Uint32) c << 16 | c; + int n = dstrect->w; + if ((uintptr_t) pixels & 3) { + *pixels++ = c; + n--; + } + if (n >> 1) + SDL_memset4(pixels, cc, n >> 1); + if (n & 1) + pixels[n - 1] = c; + row += dst->pitch; + } + break; + + case 3: +#if SDL_BYTEORDER == SDL_BIG_ENDIAN + color <<= 8; +#endif + for (y = dstrect->h; y; --y) { + Uint8 *pixels = row; + for (x = dstrect->w; x; --x) { + SDL_memcpy(pixels, &color, 3); + pixels += 3; + } + row += dst->pitch; + } + break; + + case 4: + for (y = dstrect->h; y; --y) { + SDL_memset4(row, color, dstrect->w); + row += dst->pitch; + } + break; + } + } + SDL_UnlockSurface(dst); + + /* We're done! */ + return (0); } /* * Lock a surface to directly access the pixels */ -int SDL_LockSurface (SDL_Surface *surface) +int +SDL_LockSurface(SDL_Surface * surface) { - if ( ! surface->locked ) { - /* Perform the lock */ - if ( surface->flags & (SDL_HWSURFACE|SDL_ASYNCBLIT) ) { - SDL_VideoDevice *video = current_video; - SDL_VideoDevice *this = current_video; - if ( video->LockHWSurface(this, surface) < 0 ) { - return(-1); - } - } - if ( surface->flags & SDL_RLEACCEL ) { - SDL_UnRLESurface(surface, 1); - surface->flags |= SDL_RLEACCEL; /* save accel'd state */ - } - /* This needs to be done here in case pixels changes value */ - surface->pixels = (Uint8 *)surface->pixels + surface->offset; - } - - /* Increment the surface lock count, for recursive locks */ - ++surface->locked; - - /* Ready to go.. */ - return(0); + if (!surface->locked) { + /* Perform the lock */ + if (surface->flags & SDL_HWSURFACE) { + if (SDL_LockTexture + (surface->textureID, NULL, 1, &surface->pixels, + &surface->pitch) < 0) { + return (-1); + } + } + if (surface->flags & SDL_RLEACCEL) { + SDL_UnRLESurface(surface, 1); + surface->flags |= SDL_RLEACCEL; /* save accel'd state */ + } + } + + /* Increment the surface lock count, for recursive locks */ + ++surface->locked; + + /* Ready to go.. */ + return (0); } + /* * Unlock a previously locked surface */ -void SDL_UnlockSurface (SDL_Surface *surface) +void +SDL_UnlockSurface(SDL_Surface * surface) { - /* Only perform an unlock if we are locked */ - if ( ! surface->locked || (--surface->locked > 0) ) { - return; - } - - /* Perform the unlock */ - surface->pixels = (Uint8 *)surface->pixels - surface->offset; - - /* Unlock hardware or accelerated surfaces */ - if ( surface->flags & (SDL_HWSURFACE|SDL_ASYNCBLIT) ) { - SDL_VideoDevice *video = current_video; - SDL_VideoDevice *this = current_video; - video->UnlockHWSurface(this, surface); - } else { - /* Update RLE encoded surface with new data */ - if ( (surface->flags & SDL_RLEACCEL) == SDL_RLEACCEL ) { - surface->flags &= ~SDL_RLEACCEL; /* stop lying */ - SDL_RLESurface(surface); - } - } + /* Only perform an unlock if we are locked */ + if (!surface->locked || (--surface->locked > 0)) { + return; + } + + /* Unlock hardware or accelerated surfaces */ + if (surface->flags & SDL_HWSURFACE) { + SDL_UnlockTexture(surface->textureID); + } + + /* Update RLE encoded surface with new data */ + if ((surface->flags & SDL_RLEACCEL) == SDL_RLEACCEL) { + surface->flags &= ~SDL_RLEACCEL; /* stop lying */ + SDL_RLESurface(surface); + } } /* * Convert a surface into the specified pixel format. */ -SDL_Surface * SDL_ConvertSurface (SDL_Surface *surface, - SDL_PixelFormat *format, Uint32 flags) +SDL_Surface * +SDL_ConvertSurface(SDL_Surface * surface, + SDL_PixelFormat * format, Uint32 flags) { - SDL_Surface *convert; - Uint32 colorkey = 0; - Uint8 alpha = 0; - Uint32 surface_flags; - SDL_Rect bounds; - - /* Check for empty destination palette! (results in empty image) */ - if ( format->palette != NULL ) { - int i; - for ( i=0; ipalette->ncolors; ++i ) { - if ( (format->palette->colors[i].r != 0) || - (format->palette->colors[i].g != 0) || - (format->palette->colors[i].b != 0) ) - break; - } - if ( i == format->palette->ncolors ) { - SDL_SetError("Empty destination palette"); - return(NULL); - } - } - - /* Only create hw surfaces with alpha channel if hw alpha blits - are supported */ - if(format->Amask != 0 && (flags & SDL_HWSURFACE)) { - const SDL_VideoInfo *vi = SDL_GetVideoInfo(); - if(!vi || !vi->blit_hw_A) - flags &= ~SDL_HWSURFACE; - } - - /* Create a new surface with the desired format */ - convert = SDL_CreateRGBSurface(flags, - surface->w, surface->h, format->BitsPerPixel, - format->Rmask, format->Gmask, format->Bmask, format->Amask); - if ( convert == NULL ) { - return(NULL); - } - - /* Copy the palette if any */ - if ( format->palette && convert->format->palette ) { - SDL_memcpy(convert->format->palette->colors, - format->palette->colors, - format->palette->ncolors*sizeof(SDL_Color)); - convert->format->palette->ncolors = format->palette->ncolors; - } - - /* Save the original surface color key and alpha */ - surface_flags = surface->flags; - if ( (surface_flags & SDL_SRCCOLORKEY) == SDL_SRCCOLORKEY ) { - /* Convert colourkeyed surfaces to RGBA if requested */ - if((flags & SDL_SRCCOLORKEY) != SDL_SRCCOLORKEY - && format->Amask) { - surface_flags &= ~SDL_SRCCOLORKEY; - } else { - colorkey = surface->format->colorkey; - SDL_SetColorKey(surface, 0, 0); - } - } - if ( (surface_flags & SDL_SRCALPHA) == SDL_SRCALPHA ) { - /* Copy over the alpha channel to RGBA if requested */ - if ( format->Amask ) { - surface->flags &= ~SDL_SRCALPHA; - } else { - alpha = surface->format->alpha; - SDL_SetAlpha(surface, 0, 0); - } - } - - /* Copy over the image data */ - bounds.x = 0; - bounds.y = 0; - bounds.w = surface->w; - bounds.h = surface->h; - SDL_LowerBlit(surface, &bounds, convert, &bounds); - - /* Clean up the original surface, and update converted surface */ - if ( convert != NULL ) { - SDL_SetClipRect(convert, &surface->clip_rect); - } - if ( (surface_flags & SDL_SRCCOLORKEY) == SDL_SRCCOLORKEY ) { - Uint32 cflags = surface_flags&(SDL_SRCCOLORKEY|SDL_RLEACCELOK); - if ( convert != NULL ) { - Uint8 keyR, keyG, keyB; - - SDL_GetRGB(colorkey,surface->format,&keyR,&keyG,&keyB); - SDL_SetColorKey(convert, cflags|(flags&SDL_RLEACCELOK), - SDL_MapRGB(convert->format, keyR, keyG, keyB)); - } - SDL_SetColorKey(surface, cflags, colorkey); - } - if ( (surface_flags & SDL_SRCALPHA) == SDL_SRCALPHA ) { - Uint32 aflags = surface_flags&(SDL_SRCALPHA|SDL_RLEACCELOK); - if ( convert != NULL ) { - SDL_SetAlpha(convert, aflags|(flags&SDL_RLEACCELOK), - alpha); - } - if ( format->Amask ) { - surface->flags |= SDL_SRCALPHA; - } else { - SDL_SetAlpha(surface, aflags, alpha); - } - } - - /* We're ready to go! */ - return(convert); + SDL_Surface *convert; + Uint32 colorkey = 0; + Uint8 alpha = 0; + Uint32 surface_flags; + SDL_Rect bounds; + + /* Check for empty destination palette! (results in empty image) */ + if (format->palette != NULL) { + int i; + for (i = 0; i < format->palette->ncolors; ++i) { + if ((format->palette->colors[i].r != 0xFF) || + (format->palette->colors[i].g != 0xFF) || + (format->palette->colors[i].b != 0xFF)) + break; + } + if (i == format->palette->ncolors) { + SDL_SetError("Empty destination palette"); + return (NULL); + } + } + + /* Create a new surface with the desired format */ + convert = SDL_CreateRGBSurface(flags, + surface->w, surface->h, + format->BitsPerPixel, format->Rmask, + format->Gmask, format->Bmask, + format->Amask); + if (convert == NULL) { + return (NULL); + } + + /* Copy the palette if any */ + if (format->palette && convert->format->palette) { + SDL_memcpy(convert->format->palette->colors, + format->palette->colors, + format->palette->ncolors * sizeof(SDL_Color)); + convert->format->palette->ncolors = format->palette->ncolors; + } + + /* Save the original surface color key and alpha */ + surface_flags = surface->flags; + if ((surface_flags & SDL_SRCCOLORKEY) == SDL_SRCCOLORKEY) { + /* Convert colourkeyed surfaces to RGBA if requested */ + if ((flags & SDL_SRCCOLORKEY) != SDL_SRCCOLORKEY && format->Amask) { + surface_flags &= ~SDL_SRCCOLORKEY; + } else { + colorkey = surface->format->colorkey; + SDL_SetColorKey(surface, 0, 0); + } + } + if ((surface_flags & SDL_SRCALPHA) == SDL_SRCALPHA) { + /* Copy over the alpha channel to RGBA if requested */ + if (format->Amask) { + surface->flags &= ~SDL_SRCALPHA; + } else { + alpha = surface->format->alpha; + SDL_SetAlpha(surface, 0, 0); + } + } + + /* Copy over the image data */ + bounds.x = 0; + bounds.y = 0; + bounds.w = surface->w; + bounds.h = surface->h; + SDL_LowerBlit(surface, &bounds, convert, &bounds); + + /* Clean up the original surface, and update converted surface */ + if (convert != NULL) { + SDL_SetClipRect(convert, &surface->clip_rect); + } + if ((surface_flags & SDL_SRCCOLORKEY) == SDL_SRCCOLORKEY) { + Uint32 cflags = surface_flags & (SDL_SRCCOLORKEY | SDL_RLEACCELOK); + if (convert != NULL) { + Uint8 keyR, keyG, keyB; + + SDL_GetRGB(colorkey, surface->format, &keyR, &keyG, &keyB); + SDL_SetColorKey(convert, cflags | (flags & SDL_RLEACCELOK), + SDL_MapRGB(convert->format, keyR, keyG, keyB)); + } + SDL_SetColorKey(surface, cflags, colorkey); + } + if ((surface_flags & SDL_SRCALPHA) == SDL_SRCALPHA) { + Uint32 aflags = surface_flags & (SDL_SRCALPHA | SDL_RLEACCELOK); + if (convert != NULL) { + SDL_SetAlpha(convert, aflags | (flags & SDL_RLEACCELOK), alpha); + } + if (format->Amask) { + surface->flags |= SDL_SRCALPHA; + } else { + SDL_SetAlpha(surface, aflags, alpha); + } + } + + /* We're ready to go! */ + return (convert); } /* * Free a surface created by the above function. */ -void SDL_FreeSurface (SDL_Surface *surface) +void +SDL_FreeSurface(SDL_Surface * surface) { - /* Free anything that's not NULL, and not the screen surface */ - if ((surface == NULL) || - (current_video && - ((surface == SDL_ShadowSurface)||(surface == SDL_VideoSurface)))) { - return; - } - if ( --surface->refcount > 0 ) { - return; - } - while ( surface->locked > 0 ) { - SDL_UnlockSurface(surface); - } - if ( (surface->flags & SDL_RLEACCEL) == SDL_RLEACCEL ) { - SDL_UnRLESurface(surface, 0); - } - if ( surface->format ) { - SDL_FreeFormat(surface->format); - surface->format = NULL; - } - if ( surface->map != NULL ) { - SDL_FreeBlitMap(surface->map); - surface->map = NULL; - } - if ( surface->hwdata ) { - SDL_VideoDevice *video = current_video; - SDL_VideoDevice *this = current_video; - video->FreeHWSurface(this, surface); - } - if ( surface->pixels && - ((surface->flags & SDL_PREALLOC) != SDL_PREALLOC) ) { - SDL_free(surface->pixels); - } - SDL_free(surface); + if (surface == NULL) { + return; + } + if (--surface->refcount > 0) { + return; + } + while (surface->locked > 0) { + SDL_UnlockSurface(surface); + } + if (surface->flags & SDL_RLEACCEL) { + SDL_UnRLESurface(surface, 0); + } + if (surface->format) { + SDL_SetSurfacePalette(surface, NULL); + SDL_FreeFormat(surface->format); + surface->format = NULL; + } + if (surface->map != NULL) { + SDL_FreeBlitMap(surface->map); + surface->map = NULL; + } + /* Should we destroy the texture too? + if (surface->textureID) { + SDL_DestroyTexture(surface->textureID); + } + */ + if (surface->pixels && ((surface->flags & SDL_PREALLOC) != SDL_PREALLOC)) { + SDL_free(surface->pixels); + } + SDL_free(surface); #ifdef CHECK_LEAKS - --surfaces_allocated; + --surfaces_allocated; #endif } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/SDL_sysvideo.h b/src/video/SDL_sysvideo.h index e1568a7db..5a31d56ae 100644 --- a/src/video/SDL_sysvideo.h +++ b/src/video/SDL_sysvideo.h @@ -25,296 +25,296 @@ #define _SDL_sysvideo_h #include "SDL_mouse.h" -#define SDL_PROTOTYPES_ONLY -#include "SDL_syswm.h" -#undef SDL_PROTOTYPES_ONLY -/* This file prototypes the video driver implementation. - This is designed to be easily converted to C++ in the future. +/* The SDL video driver */ + +typedef struct SDL_Window SDL_Window; +typedef struct SDL_Texture SDL_Texture; +typedef struct SDL_Renderer SDL_Renderer; +typedef struct SDL_RenderDriver SDL_RenderDriver; +typedef struct SDL_VideoDisplay SDL_VideoDisplay; +typedef struct SDL_VideoDevice SDL_VideoDevice; + +/* Define the SDL texture structure */ +struct SDL_Texture +{ + Uint32 id; + + Uint32 format; /**< The pixel format of the texture */ + int access; /**< SDL_TextureAccess */ + int w; /**< The width of the texture */ + int h; /**< The height of the texture */ + + SDL_Renderer *renderer; + + void *driverdata; /**< Driver specific texture representation */ + + SDL_Texture *next; +}; + +/* Define the SDL renderer structure */ +struct SDL_Renderer +{ + int (*CreateTexture) (SDL_Renderer * renderer, SDL_Texture * texture); + int (*QueryTexturePixels) (SDL_Renderer * renderer, SDL_Texture * texture, + void **pixels, int *pitch); + int (*SetTexturePalette) (SDL_Renderer * renderer, SDL_Texture * texture, + const SDL_Color * colors, int firstcolor, + int ncolors); + int (*GetTexturePalette) (SDL_Renderer * renderer, SDL_Texture * texture, + SDL_Color * colors, int firstcolor, + int ncolors); + int (*UpdateTexture) (SDL_Renderer * renderer, SDL_Texture * texture, + const SDL_Rect * rect, const void *pixels, + int pitch); + int (*LockTexture) (SDL_Renderer * renderer, SDL_Texture * texture, + const SDL_Rect * rect, int markDirty, void **pixels, + int *pitch); + void (*UnlockTexture) (SDL_Renderer * renderer, SDL_Texture * texture); + void (*DirtyTexture) (SDL_Renderer * renderer, SDL_Texture * texture, + int numrects, const SDL_Rect * rects); + void (*SelectRenderTexture) (SDL_Renderer * renderer, + SDL_Texture * texture); + int (*RenderFill) (SDL_Renderer * renderer, const SDL_Rect * rect, + Uint32 color); + int (*RenderCopy) (SDL_Renderer * renderer, SDL_Texture * texture, + const SDL_Rect * srcrect, const SDL_Rect * dstrect, + int blendMode, int scaleMode); + int (*RenderReadPixels) (SDL_Renderer * renderer, const SDL_Rect * rect, + void *pixels, int pitch); + int (*RenderWritePixels) (SDL_Renderer * renderer, const SDL_Rect * rect, + const void *pixels, int pitch); + void (*RenderPresent) (SDL_Renderer * renderer); + void (*DestroyTexture) (SDL_Renderer * renderer, SDL_Texture * texture); + + void (*DestroyRenderer) (SDL_Renderer * renderer); + + /* The current renderer info */ + SDL_RendererInfo info; + + /* The window associated with the renderer */ + SDL_WindowID window; + + void *driverdata; +}; + +/* Define the SDL render driver structure */ +struct SDL_RenderDriver +{ + SDL_Renderer *(*CreateRenderer) (SDL_Window * window, Uint32 flags); + + /* Info about the renderer capabilities */ + SDL_RendererInfo info; +}; + +/* Define the SDL window structure, corresponding to toplevel windows */ +struct SDL_Window +{ + Uint32 id; + + char *title; + int x, y; + int w, h; + Uint32 flags; + + int display; + SDL_Renderer *renderer; + + void *userdata; + void *driverdata; +}; +#define FULLSCREEN_VISIBLE(W) \ + (((W)->flags & SDL_WINDOW_FULLSCREEN) && \ + ((W)->flags & SDL_WINDOW_SHOWN) && \ + !((W)->flags & SDL_WINDOW_MINIMIZED)) + +/* Define the SDL display structure + This corresponds to physical monitors attached to the system. */ +struct SDL_VideoDisplay +{ + int max_display_modes; + int num_display_modes; + SDL_DisplayMode *display_modes; + SDL_DisplayMode desktop_mode; + SDL_DisplayMode current_mode; + SDL_DisplayMode desired_mode; + SDL_DisplayMode *fullscreen_mode; + SDL_Palette *palette; -#if SDL_VIDEO_OPENGL -#include "SDL_opengl.h" -#endif /* SDL_VIDEO_OPENGL */ + Uint16 *gamma; + Uint16 *saved_gamma; /* (just offset into gamma) */ -/* The SDL video driver */ -typedef struct SDL_VideoDevice SDL_VideoDevice; + int num_render_drivers; + SDL_RenderDriver *render_drivers; -/* Define the SDL video driver structure */ -#define _THIS SDL_VideoDevice *_this -#ifndef _STATUS -#define _STATUS SDL_status *status -#endif -struct SDL_VideoDevice { - /* * * */ - /* The name of this video driver */ - const char *name; - - /* * * */ - /* Initialization/Query functions */ - - /* Initialize the native video subsystem, filling 'vformat' with the - "best" display pixel format, returning 0 or -1 if there's an error. - */ - int (*VideoInit)(_THIS, SDL_PixelFormat *vformat); - - /* List the available video modes for the given pixel format, sorted - from largest to smallest. - */ - SDL_Rect **(*ListModes)(_THIS, SDL_PixelFormat *format, Uint32 flags); - - /* Set the requested video mode, returning a surface which will be - set to the SDL_VideoSurface. The width and height will already - be verified by ListModes(), and the video subsystem is free to - set the mode to a supported bit depth different from the one - specified -- the desired bpp will be emulated with a shadow - surface if necessary. If a new mode is returned, this function - should take care of cleaning up the current mode. - */ - SDL_Surface *(*SetVideoMode)(_THIS, SDL_Surface *current, - int width, int height, int bpp, Uint32 flags); - - /* Toggle the fullscreen mode */ - int (*ToggleFullScreen)(_THIS, int on); - - /* This is called after the video mode has been set, to get the - initial mouse state. It should queue events as necessary to - properly represent the current mouse focus and position. - */ - void (*UpdateMouse)(_THIS); - - /* Create a YUV video surface (possibly overlay) of the given - format. The hardware should be able to perform at least 2x - scaling on display. - */ - SDL_Overlay *(*CreateYUVOverlay)(_THIS, int width, int height, - Uint32 format, SDL_Surface *display); - - /* Sets the color entries { firstcolor .. (firstcolor+ncolors-1) } - of the physical palette to those in 'colors'. If the device is - using a software palette (SDL_HWPALETTE not set), then the - changes are reflected in the logical palette of the screen - as well. - The return value is 1 if all entries could be set properly - or 0 otherwise. - */ - int (*SetColors)(_THIS, int firstcolor, int ncolors, - SDL_Color *colors); - - /* This pointer should exist in the native video subsystem and should - point to an appropriate update function for the current video mode - */ - void (*UpdateRects)(_THIS, int numrects, SDL_Rect *rects); - - /* Reverse the effects VideoInit() -- called if VideoInit() fails - or if the application is shutting down the video subsystem. - */ - void (*VideoQuit)(_THIS); - - /* * * */ - /* Hardware acceleration functions */ - - /* Information about the video hardware */ - SDL_VideoInfo info; - - /* The pixel format used when SDL_CreateRGBSurface creates SDL_HWSURFACEs with alpha */ - SDL_PixelFormat* displayformatalphapixel; - - /* Allocates a surface in video memory */ - int (*AllocHWSurface)(_THIS, SDL_Surface *surface); - - /* Sets the hardware accelerated blit function, if any, based - on the current flags of the surface (colorkey, alpha, etc.) - */ - int (*CheckHWBlit)(_THIS, SDL_Surface *src, SDL_Surface *dst); - - /* Fills a surface rectangle with the given color */ - int (*FillHWRect)(_THIS, SDL_Surface *dst, SDL_Rect *rect, Uint32 color); - - /* Sets video mem colorkey and accelerated blit function */ - int (*SetHWColorKey)(_THIS, SDL_Surface *surface, Uint32 key); - - /* Sets per surface hardware alpha value */ - int (*SetHWAlpha)(_THIS, SDL_Surface *surface, Uint8 value); - - /* Returns a readable/writable surface */ - int (*LockHWSurface)(_THIS, SDL_Surface *surface); - void (*UnlockHWSurface)(_THIS, SDL_Surface *surface); - - /* Performs hardware flipping */ - int (*FlipHWSurface)(_THIS, SDL_Surface *surface); - - /* Frees a previously allocated video surface */ - void (*FreeHWSurface)(_THIS, SDL_Surface *surface); - - /* * * */ - /* Gamma support */ - - Uint16 *gamma; - - /* Set the gamma correction directly (emulated with gamma ramps) */ - int (*SetGamma)(_THIS, float red, float green, float blue); - - /* Get the gamma correction directly (emulated with gamma ramps) */ - int (*GetGamma)(_THIS, float *red, float *green, float *blue); - - /* Set the gamma ramp */ - int (*SetGammaRamp)(_THIS, Uint16 *ramp); - - /* Get the gamma ramp */ - int (*GetGammaRamp)(_THIS, Uint16 *ramp); - - /* * * */ - /* OpenGL support */ - - /* Sets the dll to use for OpenGL and loads it */ - int (*GL_LoadLibrary)(_THIS, const char *path); + int num_windows; + SDL_Window *windows; - /* Retrieves the address of a function in the gl library */ - void* (*GL_GetProcAddress)(_THIS, const char *proc); + SDL_Renderer *current_renderer; - /* Get attribute information from the windowing system. */ - int (*GL_GetAttribute)(_THIS, SDL_GLattr attrib, int* value); + /* The hash list of textures */ + SDL_Texture *textures[64]; - /* Make the context associated with this driver current */ - int (*GL_MakeCurrent)(_THIS); + SDL_VideoDevice *device; - /* Swap the current buffers in double buffer mode. */ - void (*GL_SwapBuffers)(_THIS); + void *driverdata; +}; - /* OpenGL functions for SDL_OPENGLBLIT */ -#if SDL_VIDEO_OPENGL -#if !defined(__WIN32__) -#define WINAPI -#endif -#define SDL_PROC(ret,func,params) ret (WINAPI *func) params; -#include "SDL_glfuncs.h" -#undef SDL_PROC +/* Define the SDL video driver structure */ +#define _THIS SDL_VideoDevice *_this - /* Texture id */ - GLuint texture; -#endif - int is_32bit; - - /* * * */ - /* Window manager functions */ - - /* Set the title and icon text */ - void (*SetCaption)(_THIS, const char *title, const char *icon); - - /* Set the window icon image */ - void (*SetIcon)(_THIS, SDL_Surface *icon, Uint8 *mask); - - /* Iconify the window. - This function returns 1 if there is a window manager and the - window was actually iconified, it returns 0 otherwise. - */ - int (*IconifyWindow)(_THIS); - - /* Grab or ungrab keyboard and mouse input */ - SDL_GrabMode (*GrabInput)(_THIS, SDL_GrabMode mode); - - /* Get some platform dependent window information */ - int (*GetWMInfo)(_THIS, SDL_SysWMinfo *info); - - /* * * */ - /* Cursor manager functions */ - - /* Free a window manager cursor - This function can be NULL if CreateWMCursor is also NULL. - */ - void (*FreeWMCursor)(_THIS, WMcursor *cursor); - - /* If not NULL, create a black/white window manager cursor */ - WMcursor *(*CreateWMCursor)(_THIS, - Uint8 *data, Uint8 *mask, int w, int h, int hot_x, int hot_y); - - /* Show the specified cursor, or hide if cursor is NULL */ - int (*ShowWMCursor)(_THIS, WMcursor *cursor); - - /* Warp the window manager cursor to (x,y) - If NULL, a mouse motion event is posted internally. - */ - void (*WarpWMCursor)(_THIS, Uint16 x, Uint16 y); - - /* If not NULL, this is called when a mouse motion event occurs */ - void (*MoveWMCursor)(_THIS, int x, int y); - - /* Determine whether the mouse should be in relative mode or not. - This function is called when the input grab state or cursor - visibility state changes. - If the cursor is not visible, and the input is grabbed, the - driver can place the mouse in relative mode, which may result - in higher accuracy sampling of the pointer motion. - */ - void (*CheckMouseMode)(_THIS); - - /* * * */ - /* Event manager functions */ - - /* Initialize keyboard mapping for this driver */ - void (*InitOSKeymap)(_THIS); - - /* Handle any queued OS events */ - void (*PumpEvents)(_THIS); - - /* * * */ - /* Data common to all drivers */ - SDL_Surface *screen; - SDL_Surface *shadow; - SDL_Surface *visible; - SDL_Palette *physpal; /* physical palette, if != logical palette */ - SDL_Color *gammacols; /* gamma-corrected colours, or NULL */ - char *wm_title; - char *wm_icon; - int offset_x; - int offset_y; - SDL_GrabMode input_grab; - - /* Driver information flags */ - int handles_any_size; /* Driver handles any size video mode */ - - /* * * */ - /* Data used by the GL drivers */ - struct { - int red_size; - int green_size; - int blue_size; - int alpha_size; - int depth_size; - int buffer_size; - int stencil_size; - int double_buffer; - int accum_red_size; - int accum_green_size; - int accum_blue_size; - int accum_alpha_size; - int stereo; - int multisamplebuffers; - int multisamplesamples; - int accelerated; - int swap_control; - int driver_loaded; - char driver_path[256]; - void* dll_handle; - } gl_config; - - /* * * */ - /* Data private to this driver */ - struct SDL_PrivateVideoData *hidden; - struct SDL_PrivateGLData *gl_data; - - /* * * */ - /* The function used to dispose of this structure */ - void (*free)(_THIS); +struct SDL_VideoDevice +{ + /* * * */ + /* The name of this video driver */ + const char *name; + + /* * * */ + /* Initialization/Query functions */ + + /* Initialize the native video subsystem, filling in the list + of displays for this driver, returning 0 or -1 if there's an error. + */ + int (*VideoInit) (_THIS); + + /* * * */ + /* Display functions + */ + + /* Get a list of the available display modes. + * e.g. SDL_AddDisplayMode(_this->current_display, mode) + */ + void (*GetDisplayModes) (_THIS); + + /* Setting the display mode is independent of creating windows, + * so when the display mode is changed, all existing windows + * should have their data updated accordingly, including the + * display surfaces associated with them. + */ + int (*SetDisplayMode) (_THIS, SDL_DisplayMode * mode); + + /* Set the color entries of the display palette */ + int (*SetDisplayPalette) (_THIS, SDL_Palette * palette); + + /* Get the color entries of the display palette */ + int (*GetDisplayPalette) (_THIS, SDL_Palette * palette); + + /* Set the gamma ramp */ + int (*SetDisplayGammaRamp) (_THIS, Uint16 * ramp); + + /* Get the gamma ramp */ + int (*GetDisplayGammaRamp) (_THIS, Uint16 * ramp); + + /* * * */ + /* Window functions + */ + int (*CreateWindow) (_THIS, SDL_Window * window); + int (*CreateWindowFrom) (_THIS, SDL_Window * window, const void *data); + void (*SetWindowTitle) (_THIS, SDL_Window * window); + void (*SetWindowPosition) (_THIS, SDL_Window * window); + void (*SetWindowSize) (_THIS, SDL_Window * window); + void (*ShowWindow) (_THIS, SDL_Window * window); + void (*HideWindow) (_THIS, SDL_Window * window); + void (*RaiseWindow) (_THIS, SDL_Window * window); + void (*MaximizeWindow) (_THIS, SDL_Window * window); + void (*MinimizeWindow) (_THIS, SDL_Window * window); + void (*RestoreWindow) (_THIS, SDL_Window * window); + void (*SetWindowGrab) (_THIS, SDL_Window * window); + void (*DestroyWindow) (_THIS, SDL_Window * window); + + /* Get some platform dependent window information */ + SDL_bool(*GetWindowWMInfo) (_THIS, SDL_Window * window, + struct SDL_SysWMinfo * info); + + /* Reverse the effects VideoInit() -- called if VideoInit() fails + or if the application is shutting down the video subsystem. + */ + void (*VideoQuit) (_THIS); + + /* * * */ + /* OpenGL support */ + + /* Sets the dll to use for OpenGL and loads it */ + int (*GL_LoadLibrary) (_THIS, const char *path); + + /* Retrieves the address of a function in the gl library */ + void *(*GL_GetProcAddress) (_THIS, const char *proc); + + /* Get attribute information from the windowing system. */ + int (*GL_GetAttribute) (_THIS, SDL_GLattr attrib, int *value); + + /* Make the context associated with this driver current */ + int (*GL_MakeCurrent) (_THIS); + + /* Swap the current buffers in double buffer mode. */ + void (*GL_SwapBuffers) (_THIS); + + /* Determine whether the mouse should be in relative mode or not. + This function is called when the input grab state or cursor + visibility state changes. + If the cursor is not visible, and the input is grabbed, the + driver can place the mouse in relative mode, which may result + in higher accuracy sampling of the pointer motion. + */ + void (*CheckMouseMode) (_THIS); + + /* * * */ + /* Event manager functions */ + + /* Handle any queued OS events */ + void (*PumpEvents) (_THIS); + + /* * * */ + /* Data common to all drivers */ + int num_displays; + SDL_VideoDisplay *displays; + int current_display; + Uint32 next_object_id; + + /* Driver information flags */ + + /* * * */ + /* Data used by the GL drivers */ + struct + { + int red_size; + int green_size; + int blue_size; + int alpha_size; + int depth_size; + int buffer_size; + int stencil_size; + int double_buffer; + int accum_red_size; + int accum_green_size; + int accum_blue_size; + int accum_alpha_size; + int stereo; + int multisamplebuffers; + int multisamplesamples; + int accelerated; + int driver_loaded; + char driver_path[256]; + void *dll_handle; + } gl_config; + + /* * * */ + /* Data private to this driver */ + void *driverdata; + struct SDL_PrivateGLData *gl_data; + + /* * * */ + /* The function used to dispose of this structure */ + void (*free) (_THIS); }; -#undef _THIS -typedef struct VideoBootStrap { - const char *name; - const char *desc; - int (*available)(void); - SDL_VideoDevice *(*create)(int devindex); +typedef struct VideoBootStrap +{ + const char *name; + const char *desc; + int (*available) (void); + SDL_VideoDevice *(*create) (int devindex); } VideoBootStrap; #if SDL_VIDEO_DRIVER_QUARTZ @@ -359,11 +359,8 @@ extern VideoBootStrap SVGALIB_bootstrap; #if SDL_VIDEO_DRIVER_GAPI extern VideoBootStrap GAPI_bootstrap; #endif -#if SDL_VIDEO_DRIVER_WINDIB -extern VideoBootStrap WINDIB_bootstrap; -#endif -#if SDL_VIDEO_DRIVER_DDRAW -extern VideoBootStrap DIRECTX_bootstrap; +#if SDL_VIDEO_DRIVER_WIN32 +extern VideoBootStrap WIN32_bootstrap; #endif #if SDL_VIDEO_DRIVER_BWINDOW extern VideoBootStrap BWINDOW_bootstrap; @@ -407,12 +404,29 @@ extern VideoBootStrap AALIB_bootstrap; #if SDL_VIDEO_DRIVER_DUMMY extern VideoBootStrap DUMMY_bootstrap; #endif +#if SDL_VIDEO_DRIVER_GLSDL +extern VideoBootStrap glSDL_bootstrap; +#endif + +#define SDL_CurrentDisplay (_this->displays[_this->current_display]) -/* This is the current video device */ -extern SDL_VideoDevice *current_video; +extern SDL_VideoDevice *SDL_GetVideoDevice(); +extern int SDL_AddBasicVideoDisplay(const SDL_DisplayMode * desktop_mode); +extern int SDL_AddVideoDisplay(const SDL_VideoDisplay * display); +extern SDL_bool SDL_AddDisplayMode(int displayIndex, + const SDL_DisplayMode * mode); +extern void SDL_AddRenderDriver(int displayIndex, + const SDL_RenderDriver * driver); -#define SDL_VideoSurface (current_video->screen) -#define SDL_ShadowSurface (current_video->shadow) -#define SDL_PublicSurface (current_video->visible) +extern SDL_Window *SDL_GetWindowFromID(SDL_WindowID windowID); +extern SDL_VideoDisplay *SDL_GetDisplayFromWindow(SDL_Window * window); + +extern void SDL_OnWindowShown(SDL_Window * window); +extern void SDL_OnWindowHidden(SDL_Window * window); +extern void SDL_OnWindowFocusGained(SDL_Window * window); +extern void SDL_OnWindowFocusLost(SDL_Window * window); +extern SDL_WindowID SDL_GetFocusWindow(void); #endif /* _SDL_sysvideo_h */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/SDL_video.c b/src/video/SDL_video.c index 322b2f0e0..9b76c2069 100644 --- a/src/video/SDL_video.c +++ b/src/video/SDL_video.c @@ -27,1924 +27,2240 @@ #include "SDL_sysvideo.h" #include "SDL_blit.h" #include "SDL_pixels_c.h" -#include "SDL_cursor_c.h" +#include "SDL_renderer_sw.h" #include "../events/SDL_sysevents.h" #include "../events/SDL_events_c.h" /* Available video drivers */ static VideoBootStrap *bootstrap[] = { #if SDL_VIDEO_DRIVER_QUARTZ - &QZ_bootstrap, + &QZ_bootstrap, #endif #if SDL_VIDEO_DRIVER_X11 - &X11_bootstrap, + &X11_bootstrap, #endif #if SDL_VIDEO_DRIVER_DGA - &DGA_bootstrap, + &DGA_bootstrap, #endif #if SDL_VIDEO_DRIVER_NANOX - &NX_bootstrap, + &NX_bootstrap, #endif #if SDL_VIDEO_DRIVER_IPOD - &iPod_bootstrap, + &iPod_bootstrap, #endif #if SDL_VIDEO_DRIVER_QTOPIA - &Qtopia_bootstrap, + &Qtopia_bootstrap, #endif #if SDL_VIDEO_DRIVER_WSCONS - &WSCONS_bootstrap, + &WSCONS_bootstrap, #endif #if SDL_VIDEO_DRIVER_FBCON - &FBCON_bootstrap, + &FBCON_bootstrap, #endif #if SDL_VIDEO_DRIVER_DIRECTFB - &DirectFB_bootstrap, + &DirectFB_bootstrap, #endif #if SDL_VIDEO_DRIVER_PS2GS - &PS2GS_bootstrap, + &PS2GS_bootstrap, #endif #if SDL_VIDEO_DRIVER_GGI - &GGI_bootstrap, + &GGI_bootstrap, #endif #if SDL_VIDEO_DRIVER_VGL - &VGL_bootstrap, + &VGL_bootstrap, #endif #if SDL_VIDEO_DRIVER_SVGALIB - &SVGALIB_bootstrap, + &SVGALIB_bootstrap, #endif #if SDL_VIDEO_DRIVER_GAPI - &GAPI_bootstrap, + &GAPI_bootstrap, #endif -#if SDL_VIDEO_DRIVER_WINDIB - &WINDIB_bootstrap, -#endif -#if SDL_VIDEO_DRIVER_DDRAW - &DIRECTX_bootstrap, +#if SDL_VIDEO_DRIVER_WIN32 + &WIN32_bootstrap, #endif #if SDL_VIDEO_DRIVER_BWINDOW - &BWINDOW_bootstrap, + &BWINDOW_bootstrap, #endif #if SDL_VIDEO_DRIVER_TOOLBOX - &TOOLBOX_bootstrap, + &TOOLBOX_bootstrap, #endif #if SDL_VIDEO_DRIVER_DRAWSPROCKET - &DSp_bootstrap, + &DSp_bootstrap, #endif #if SDL_VIDEO_DRIVER_CYBERGRAPHICS - &CGX_bootstrap, + &CGX_bootstrap, #endif #if SDL_VIDEO_DRIVER_PHOTON - &ph_bootstrap, + &ph_bootstrap, #endif #if SDL_VIDEO_DRIVER_EPOC - &EPOC_bootstrap, + &EPOC_bootstrap, #endif #if SDL_VIDEO_DRIVER_XBIOS - &XBIOS_bootstrap, + &XBIOS_bootstrap, #endif #if SDL_VIDEO_DRIVER_GEM - &GEM_bootstrap, + &GEM_bootstrap, #endif #if SDL_VIDEO_DRIVER_PICOGUI - &PG_bootstrap, + &PG_bootstrap, #endif #if SDL_VIDEO_DRIVER_DC - &DC_bootstrap, + &DC_bootstrap, #endif #if SDL_VIDEO_DRIVER_RISCOS - &RISCOS_bootstrap, + &RISCOS_bootstrap, #endif #if SDL_VIDEO_DRIVER_OS2FS - &OS2FSLib_bootstrap, + &OS2FSLib_bootstrap, #endif #if SDL_VIDEO_DRIVER_AALIB - &AALIB_bootstrap, + &AALIB_bootstrap, #endif #if SDL_VIDEO_DRIVER_DUMMY - &DUMMY_bootstrap, + &DUMMY_bootstrap, +#endif +#if SDL_VIDEO_DRIVER_GLSDL + &glSDL_bootstrap, #endif - NULL + NULL }; -SDL_VideoDevice *current_video = NULL; +static SDL_VideoDevice *_this = NULL; /* Various local functions */ int SDL_VideoInit(const char *driver_name, Uint32 flags); void SDL_VideoQuit(void); -void SDL_GL_UpdateRectsLock(SDL_VideoDevice* this, int numrects, SDL_Rect* rects); -static SDL_GrabMode SDL_WM_GrabInputOff(void); -#if SDL_VIDEO_OPENGL -static int lock_count = 0; -#endif +static int +cmpmodes(const void *A, const void *B) +{ + SDL_DisplayMode a = *(const SDL_DisplayMode *) A; + SDL_DisplayMode b = *(const SDL_DisplayMode *) B; + + if (a.w != b.w) { + return b.w - a.w; + } + if (a.h != b.h) { + return b.h - a.h; + } + if (SDL_BITSPERPIXEL(a.format) != SDL_BITSPERPIXEL(b.format)) { + return SDL_BITSPERPIXEL(b.format) - SDL_BITSPERPIXEL(a.format); + } + if (a.refresh_rate != b.refresh_rate) { + return b.refresh_rate - a.refresh_rate; + } + return 0; +} +int +SDL_GetNumVideoDrivers(void) +{ + return SDL_arraysize(bootstrap) - 1; +} + +const char * +SDL_GetVideoDriver(int index) +{ + if (index >= 0 && index < SDL_GetNumVideoDrivers()) { + return bootstrap[index]->name; + } + return NULL; +} /* * Initialize the video and event subsystems -- determine native pixel format */ -int SDL_VideoInit (const char *driver_name, Uint32 flags) +int +SDL_VideoInit(const char *driver_name, Uint32 flags) { - SDL_VideoDevice *video; - int index; - int i; - SDL_PixelFormat vformat; - Uint32 video_flags; + SDL_VideoDevice *video; + int index; + int i; - /* Toggle the event thread flags, based on OS requirements */ + /* Toggle the event thread flags, based on OS requirements */ #if defined(MUST_THREAD_EVENTS) - flags |= SDL_INIT_EVENTTHREAD; + flags |= SDL_INIT_EVENTTHREAD; #elif defined(CANT_THREAD_EVENTS) - if ( (flags & SDL_INIT_EVENTTHREAD) == SDL_INIT_EVENTTHREAD ) { - SDL_SetError("OS doesn't support threaded events"); - return(-1); - } + if ((flags & SDL_INIT_EVENTTHREAD) == SDL_INIT_EVENTTHREAD) { + SDL_SetError("OS doesn't support threaded events"); + return -1; + } #endif - /* Check to make sure we don't overwrite 'current_video' */ - if ( current_video != NULL ) { - SDL_VideoQuit(); - } - - /* Select the proper video driver */ - index = 0; - video = NULL; - if ( driver_name != NULL ) { -#if 0 /* This will be replaced with a better driver selection API */ - if ( SDL_strrchr(driver_name, ':') != NULL ) { - index = atoi(SDL_strrchr(driver_name, ':')+1); - } -#endif - for ( i=0; bootstrap[i]; ++i ) { - if ( SDL_strncmp(bootstrap[i]->name, driver_name, - SDL_strlen(bootstrap[i]->name)) == 0 ) { - if ( bootstrap[i]->available() ) { - video = bootstrap[i]->create(index); - break; - } - } - } - } else { - for ( i=0; bootstrap[i]; ++i ) { - if ( bootstrap[i]->available() ) { - video = bootstrap[i]->create(index); - if ( video != NULL ) { - break; - } - } - } - } - if ( video == NULL ) { - SDL_SetError("No available video device"); - return(-1); - } - current_video = video; - current_video->name = bootstrap[i]->name; - - /* Do some basic variable initialization */ - video->screen = NULL; - video->shadow = NULL; - video->visible = NULL; - video->physpal = NULL; - video->gammacols = NULL; - video->gamma = NULL; - video->wm_title = NULL; - video->wm_icon = NULL; - video->offset_x = 0; - video->offset_y = 0; - SDL_memset(&video->info, 0, (sizeof video->info)); - - video->displayformatalphapixel = NULL; - - /* Set some very sane GL defaults */ - video->gl_config.driver_loaded = 0; - video->gl_config.dll_handle = NULL; - video->gl_config.red_size = 3; - video->gl_config.green_size = 3; - video->gl_config.blue_size = 2; - video->gl_config.alpha_size = 0; - video->gl_config.buffer_size = 0; - video->gl_config.depth_size = 16; - video->gl_config.stencil_size = 0; - video->gl_config.double_buffer = 1; - video->gl_config.accum_red_size = 0; - video->gl_config.accum_green_size = 0; - video->gl_config.accum_blue_size = 0; - video->gl_config.accum_alpha_size = 0; - video->gl_config.stereo = 0; - video->gl_config.multisamplebuffers = 0; - video->gl_config.multisamplesamples = 0; - video->gl_config.accelerated = -1; /* not known, don't set */ - video->gl_config.swap_control = -1; /* not known, don't set */ - - /* Initialize the video subsystem */ - SDL_memset(&vformat, 0, sizeof(vformat)); - if ( video->VideoInit(video, &vformat) < 0 ) { - SDL_VideoQuit(); - return(-1); - } - - /* Create a zero sized video surface of the appropriate format */ - video_flags = SDL_SWSURFACE; - SDL_VideoSurface = SDL_CreateRGBSurface(video_flags, 0, 0, - vformat.BitsPerPixel, - vformat.Rmask, vformat.Gmask, vformat.Bmask, 0); - if ( SDL_VideoSurface == NULL ) { - SDL_VideoQuit(); - return(-1); - } - SDL_PublicSurface = NULL; /* Until SDL_SetVideoMode() */ - -#if 0 /* Don't change the current palette - may be used by other programs. - * The application can't do anything with the display surface until - * a video mode has been set anyway. :) - */ - /* If we have a palettized surface, create a default palette */ - if ( SDL_VideoSurface->format->palette ) { - SDL_PixelFormat *vf = SDL_VideoSurface->format; - SDL_DitherColors(vf->palette->colors, vf->BitsPerPixel); - video->SetColors(video, - 0, vf->palette->ncolors, vf->palette->colors); - } -#endif - video->info.vfmt = SDL_VideoSurface->format; + /* Start the event loop */ + if (SDL_StartEventLoop(flags) < 0) { + return -1; + } + + /* Check to make sure we don't overwrite '_this' */ + if (_this != NULL) { + SDL_VideoQuit(); + } + + /* Select the proper video driver */ + index = 0; + video = NULL; + if (driver_name != NULL) { + for (i = 0; bootstrap[i]; ++i) { + if (SDL_strncmp(bootstrap[i]->name, driver_name, + SDL_strlen(bootstrap[i]->name)) == 0) { + if (bootstrap[i]->available()) { + video = bootstrap[i]->create(index); + } + break; + } + } + } else { + for (i = 0; bootstrap[i]; ++i) { + if (bootstrap[i]->available()) { + video = bootstrap[i]->create(index); + if (video != NULL) { + break; + } + } + } + } + if (video == NULL) { + if (driver_name) { + SDL_SetError("%s not available", driver_name); + } else { + SDL_SetError("No available video device"); + } + return -1; + } + _this = video; + _this->name = bootstrap[i]->name; + _this->next_object_id = 1; + + + /* Set some very sane GL defaults */ + _this->gl_config.driver_loaded = 0; + _this->gl_config.dll_handle = NULL; + _this->gl_config.red_size = 3; + _this->gl_config.green_size = 3; + _this->gl_config.blue_size = 2; + _this->gl_config.alpha_size = 0; + _this->gl_config.buffer_size = 0; + _this->gl_config.depth_size = 16; + _this->gl_config.stencil_size = 0; + _this->gl_config.double_buffer = 1; + _this->gl_config.accum_red_size = 0; + _this->gl_config.accum_green_size = 0; + _this->gl_config.accum_blue_size = 0; + _this->gl_config.accum_alpha_size = 0; + _this->gl_config.stereo = 0; + _this->gl_config.multisamplebuffers = 0; + _this->gl_config.multisamplesamples = 0; + _this->gl_config.accelerated = -1; /* not known, don't set */ + + /* Initialize the video subsystem */ + if (_this->VideoInit(_this) < 0) { + SDL_VideoQuit(); + return -1; + } + + /* Make sure some displays were added */ + if (_this->num_displays == 0) { + SDL_SetError("The video driver did not add any displays"); + SDL_VideoQuit(); + return (-1); + } + + /* The software renderer is always available */ + for (i = 0; i < _this->num_displays; ++i) { + if (_this->displays[i].num_render_drivers > 0) { + SDL_AddRenderDriver(i, &SDL_SW_RenderDriver); + } + } + + /* We're ready to go! */ + return 0; +} - /* Start the event loop */ - if ( SDL_StartEventLoop(flags) < 0 ) { - SDL_VideoQuit(); - return(-1); - } - SDL_CursorInit(flags & SDL_INIT_EVENTTHREAD); +const char * +SDL_GetCurrentVideoDriver() +{ + if (!_this) { + return NULL; + } + return _this->name; +} - /* We're ready to go! */ - return(0); +SDL_VideoDevice * +SDL_GetVideoDevice() +{ + return _this; } -char *SDL_VideoDriverName(char *namebuf, int maxlen) +int +SDL_AddBasicVideoDisplay(const SDL_DisplayMode * desktop_mode) { - if ( current_video != NULL ) { - SDL_strlcpy(namebuf, current_video->name, maxlen); - return(namebuf); - } - return(NULL); + SDL_VideoDisplay display; + + SDL_zero(display); + if (desktop_mode) { + display.desktop_mode = *desktop_mode; + } + display.current_mode = display.desktop_mode; + + return SDL_AddVideoDisplay(&display); } -/* - * Get the current display surface - */ -SDL_Surface *SDL_GetVideoSurface(void) +int +SDL_AddVideoDisplay(const SDL_VideoDisplay * display) { - SDL_Surface *visible; + SDL_VideoDisplay *displays; + int index = -1; + + displays = + SDL_realloc(_this->displays, + (_this->num_displays + 1) * sizeof(*displays)); + if (displays) { + index = _this->num_displays++; + displays[index] = *display; + displays[index].device = _this; + _this->displays = displays; + } else { + SDL_OutOfMemory(); + } + return index; +} - visible = NULL; - if ( current_video ) { - visible = current_video->visible; - } - return(visible); +int +SDL_GetNumVideoDisplays(void) +{ + if (!_this) { + return 0; + } + return _this->num_displays; } -/* - * Get the current information about the video hardware - */ -const SDL_VideoInfo *SDL_GetVideoInfo(void) +int +SDL_SelectVideoDisplay(int index) { - const SDL_VideoInfo *info; + if (!_this) { + SDL_SetError("Video subsystem has not been initialized"); + return (-1); + } + if (index >= 0) { + if (index >= _this->num_displays) { + SDL_SetError("index must be in the range 0 - %d", + _this->num_displays - 1); + return -1; + } + _this->current_display = index; + } + return _this->current_display; +} - info = NULL; - if ( current_video ) { - info = ¤t_video->info; - } - return(info); +SDL_bool +SDL_AddDisplayMode(int displayIndex, const SDL_DisplayMode * mode) +{ + SDL_VideoDisplay *display = &_this->displays[displayIndex]; + SDL_DisplayMode *modes; + int i, nmodes; + + /* Make sure we don't already have the mode in the list */ + modes = display->display_modes; + nmodes = display->num_display_modes; + for (i = nmodes; i--;) { + if (SDL_memcmp(mode, &modes[i], sizeof(*mode)) == 0) { + return SDL_FALSE; + } + } + + /* Go ahead and add the new mode */ + if (nmodes == display->max_display_modes) { + modes = + SDL_realloc(modes, + (display->max_display_modes + 32) * sizeof(*modes)); + if (!modes) { + return SDL_FALSE; + } + display->display_modes = modes; + display->max_display_modes += 32; + } + modes[nmodes] = *mode; + display->num_display_modes++; + + return SDL_TRUE; } -/* - * Return a pointer to an array of available screen dimensions for the - * given format, sorted largest to smallest. Returns NULL if there are - * no dimensions available for a particular format, or (SDL_Rect **)-1 - * if any dimension is okay for the given format. If 'format' is NULL, - * the mode list will be for the format given by SDL_GetVideoInfo()->vfmt - */ -SDL_Rect ** SDL_ListModes (SDL_PixelFormat *format, Uint32 flags) +int +SDL_GetNumDisplayModes() { - SDL_VideoDevice *video = current_video; - SDL_VideoDevice *this = current_video; - SDL_Rect **modes; + if (_this) { + SDL_VideoDisplay *display = &SDL_CurrentDisplay; + if (!display->num_display_modes && _this->GetDisplayModes) { + _this->GetDisplayModes(_this); + SDL_qsort(display->display_modes, display->num_display_modes, + sizeof(SDL_DisplayMode), cmpmodes); + } + return display->num_display_modes; + } + return 0; +} - modes = NULL; - if ( SDL_VideoSurface ) { - if ( format == NULL ) { - format = SDL_VideoSurface->format; - } - modes = video->ListModes(this, format, flags); - } - return(modes); +const SDL_DisplayMode * +SDL_GetDisplayMode(int index) +{ + if (index < 0 || index >= SDL_GetNumDisplayModes()) { + SDL_SetError("index must be in the range of 0 - %d", + SDL_GetNumDisplayModes() - 1); + return NULL; + } + return &SDL_CurrentDisplay.display_modes[index]; } -/* - * Check to see if a particular video mode is supported. - * It returns 0 if the requested mode is not supported under any bit depth, - * or returns the bits-per-pixel of the closest available mode with the - * given width and height. If this bits-per-pixel is different from the - * one used when setting the video mode, SDL_SetVideoMode() will succeed, - * but will emulate the requested bits-per-pixel with a shadow surface. - */ -static Uint8 SDL_closest_depths[4][8] = { - /* 8 bit closest depth ordering */ - { 0, 8, 16, 15, 32, 24, 0, 0 }, - /* 15,16 bit closest depth ordering */ - { 0, 16, 15, 32, 24, 8, 0, 0 }, - /* 24 bit closest depth ordering */ - { 0, 24, 32, 16, 15, 8, 0, 0 }, - /* 32 bit closest depth ordering */ - { 0, 32, 16, 15, 24, 8, 0, 0 } -}; +const SDL_DisplayMode * +SDL_GetDesktopDisplayMode(void) +{ + if (_this) { + return &SDL_CurrentDisplay.desktop_mode; + } + return NULL; +} +const SDL_DisplayMode * +SDL_GetCurrentDisplayMode(void) +{ + if (_this) { + return &SDL_CurrentDisplay.current_mode; + } + return NULL; +} -#ifdef __MACOS__ /* MPW optimization bug? */ -#define NEGATIVE_ONE 0xFFFFFFFF -#else -#define NEGATIVE_ONE -1 -#endif +SDL_DisplayMode * +SDL_GetClosestDisplayMode(const SDL_DisplayMode * mode, + SDL_DisplayMode * closest) +{ + Uint32 target_format; + int target_refresh_rate; + int i; + SDL_DisplayMode *current, *match; + + if (!_this || !mode || !closest) { + return NULL; + } + + /* Default to the desktop format */ + if (mode->format) { + target_format = mode->format; + } else { + target_format = SDL_CurrentDisplay.desktop_mode.format; + } + + /* Default to the desktop refresh rate */ + if (mode->refresh_rate) { + target_refresh_rate = mode->refresh_rate; + } else { + target_refresh_rate = SDL_CurrentDisplay.desktop_mode.refresh_rate; + } + + match = NULL; + for (i = 0; i < SDL_GetNumDisplayModes(); ++i) { + current = &SDL_CurrentDisplay.display_modes[i]; + + if ((current->w && current->h) && + (current->w < mode->w || current->h < mode->h)) { + /* Out of sorted modes large enough here */ + break; + } + if (!match || current->w < match->w || current->h < match->h) { + match = current; + continue; + } + if (current->format != match->format) { + /* Sorted highest depth to lowest */ + if (current->format == target_format || + (SDL_BITSPERPIXEL(current->format) >= + SDL_BITSPERPIXEL(target_format) + && SDL_PIXELTYPE(current->format) == + SDL_PIXELTYPE(target_format))) { + match = current; + } + continue; + } + if (current->refresh_rate != match->refresh_rate) { + /* Sorted highest refresh to lowest */ + if (current->refresh_rate >= target_refresh_rate) { + match = current; + } + } + } + if (match) { + if (match->format) { + closest->format = match->format; + } else { + closest->format = mode->format; + } + if (match->w && match->h) { + closest->w = match->w; + closest->h = match->h; + } else { + closest->w = mode->w; + closest->h = mode->h; + } + if (match->refresh_rate) { + closest->refresh_rate = match->refresh_rate; + } else { + closest->refresh_rate = mode->refresh_rate; + } + closest->driverdata = match->driverdata; + + /* Pick some reasonable defaults if the app and driver don't care */ + if (!closest->format) { + closest->format = SDL_PixelFormat_RGB888; + } + if (!closest->w) { + closest->w = 640; + } + if (!closest->h) { + closest->h = 480; + } + return closest; + } + return NULL; +} -int SDL_VideoModeOK (int width, int height, int bpp, Uint32 flags) -{ - int table, b, i; - int supported; - SDL_PixelFormat format; - SDL_Rect **sizes; - - /* Currently 1 and 4 bpp are not supported */ - if ( bpp < 8 || bpp > 32 ) { - return(0); - } - if ( (width <= 0) || (height <= 0) ) { - return(0); - } - - /* Search through the list valid of modes */ - SDL_memset(&format, 0, sizeof(format)); - supported = 0; - table = ((bpp+7)/8)-1; - SDL_closest_depths[table][0] = bpp; - SDL_closest_depths[table][7] = 0; - for ( b = 0; !supported && SDL_closest_depths[table][b]; ++b ) { - format.BitsPerPixel = SDL_closest_depths[table][b]; - sizes = SDL_ListModes(&format, flags); - if ( sizes == (SDL_Rect **)0 ) { - /* No sizes supported at this bit-depth */ - continue; - } else - if (sizes == (SDL_Rect **)NEGATIVE_ONE) { - /* Any size supported at this bit-depth */ - supported = 1; - continue; - } else if (current_video->handles_any_size) { - /* Driver can center a smaller surface to simulate fullscreen */ - for ( i=0; sizes[i]; ++i ) { - if ((sizes[i]->w >= width) && (sizes[i]->h >= height)) { - supported = 1; /* this mode can fit the centered window. */ - break; - } - } - } else - for ( i=0; sizes[i]; ++i ) { - if ((sizes[i]->w == width) && (sizes[i]->h == height)) { - supported = 1; - break; - } - } - } - if ( supported ) { - --b; - return(SDL_closest_depths[table][b]); - } else { - return(0); - } +int +SDL_SetDisplayMode(const SDL_DisplayMode * mode) +{ + SDL_VideoDisplay *display; + SDL_DisplayMode display_mode; + int i, ncolors; + + if (!_this) { + SDL_SetError("Video subsystem has not been initialized"); + return -1; + } + + if (!mode) { + mode = SDL_GetDesktopDisplayMode(); + } + display = &SDL_CurrentDisplay; + display_mode = *mode; + + /* Default to the current mode */ + if (!display_mode.format) { + display_mode.format = display->current_mode.format; + } + if (!display_mode.w) { + display_mode.w = display->current_mode.w; + } + if (!display_mode.h) { + display_mode.h = display->current_mode.h; + } + if (!display_mode.refresh_rate) { + display_mode.refresh_rate = display->current_mode.refresh_rate; + } + + /* Get a good video mode, the closest one possible */ + if (!SDL_GetClosestDisplayMode(&display_mode, &display_mode)) { + SDL_SetError("No video mode large enough for %dx%d", + display_mode.w, display_mode.h); + return -1; + } + + /* See if there's anything left to do */ + if (SDL_memcmp + (&display_mode, SDL_GetCurrentDisplayMode(), + sizeof(display_mode)) == 0) { + return 0; + } + + /* Actually change the display mode */ + if (_this->SetDisplayMode(_this, &display_mode) < 0) { + return -1; + } + display->current_mode = display_mode; + + /* Set up a palette, if necessary */ + if (SDL_ISPIXELFORMAT_INDEXED(display_mode.format)) { + ncolors = (1 << SDL_BITSPERPIXEL(display_mode.format)); + } else { + ncolors = 0; + } + if ((!ncolors && display->palette) || (ncolors && !display->palette) + || (ncolors && ncolors != display->palette->ncolors)) { + if (display->palette) { + SDL_FreePalette(display->palette); + display->palette = NULL; + } + if (ncolors) { + display->palette = SDL_AllocPalette(ncolors); + if (!display->palette) { + return -1; + } + SDL_DitherColors(display->palette->colors, + SDL_BITSPERPIXEL(display_mode.format)); + } + } + + /* Move any fullscreen windows into position */ + for (i = 0; i < display->num_windows; ++i) { + SDL_Window *window = &display->windows[i]; + if (FULLSCREEN_VISIBLE(window)) { + SDL_SetWindowPosition(window->id, + ((display_mode.w - window->w) / 2), + ((display_mode.h - window->h) / 2)); + } + } + + return 0; } -/* - * Get the closest non-emulated video mode to the one requested - */ -static int SDL_GetVideoMode (int *w, int *h, int *BitsPerPixel, Uint32 flags) -{ - int table, b, i; - int supported; - int native_bpp; - SDL_PixelFormat format; - SDL_Rect **sizes; - - /* Check parameters */ - if ( *BitsPerPixel < 8 || *BitsPerPixel > 32 ) { - SDL_SetError("Invalid bits per pixel (range is {8...32})"); - return(0); - } - if ((*w <= 0) || (*h <= 0)) { - SDL_SetError("Invalid width or height"); - return(0); - } - - /* Try the original video mode, get the closest depth */ - native_bpp = SDL_VideoModeOK(*w, *h, *BitsPerPixel, flags); - if ( native_bpp == *BitsPerPixel ) { - return(1); - } - if ( native_bpp > 0 ) { - *BitsPerPixel = native_bpp; - return(1); - } - - /* No exact size match at any depth, look for closest match */ - SDL_memset(&format, 0, sizeof(format)); - supported = 0; - table = ((*BitsPerPixel+7)/8)-1; - SDL_closest_depths[table][0] = *BitsPerPixel; - SDL_closest_depths[table][7] = SDL_VideoSurface->format->BitsPerPixel; - for ( b = 0; !supported && SDL_closest_depths[table][b]; ++b ) { - int best; - - format.BitsPerPixel = SDL_closest_depths[table][b]; - sizes = SDL_ListModes(&format, flags); - if ( sizes == (SDL_Rect **)0 ) { - /* No sizes supported at this bit-depth */ - continue; - } - best=0; - for ( i=0; sizes[i]; ++i ) { - /* Mode with both dimensions bigger or equal than asked ? */ - if ((sizes[i]->w >= *w) && (sizes[i]->h >= *h)) { - /* Mode with any dimension smaller or equal than current best ? */ - if ((sizes[i]->w <= sizes[best]->w) || (sizes[i]->h <= sizes[best]->h)) { - /* Now choose the mode that has less pixels */ - if ((sizes[i]->w * sizes[i]->h) <= (sizes[best]->w * sizes[best]->h)) { - best=i; - supported = 1; - } - } - } - } - if (supported) { - *w=sizes[best]->w; - *h=sizes[best]->h; - *BitsPerPixel = SDL_closest_depths[table][b]; - } - } - if ( ! supported ) { - SDL_SetError("No video mode large enough for %dx%d", *w, *h); - } - return(supported); -} - -/* This should probably go somewhere else -- like SDL_surface.c */ -static void SDL_ClearSurface(SDL_Surface *surface) -{ - Uint32 black; - - black = SDL_MapRGB(surface->format, 0, 0, 0); - SDL_FillRect(surface, NULL, black); - if ((surface->flags&SDL_HWSURFACE) && (surface->flags&SDL_DOUBLEBUF)) { - SDL_Flip(surface); - SDL_FillRect(surface, NULL, black); - } - SDL_Flip(surface); +int +SDL_SetFullscreenDisplayMode(const SDL_DisplayMode * mode) +{ + SDL_VideoDisplay *display; + int i; + + if (!_this) { + SDL_SetError("Video subsystem has not been initialized"); + return -1; + } + + display = &SDL_CurrentDisplay; + if (mode) { + SDL_GetClosestDisplayMode(mode, &display->desired_mode); + display->fullscreen_mode = &display->desired_mode; + } else { + display->fullscreen_mode = NULL; + } + + /* Actually set the mode if we have a fullscreen window visible */ + for (i = 0; i < display->num_windows; ++i) { + SDL_Window *window = &display->windows[i]; + if (FULLSCREEN_VISIBLE(window)) { + return SDL_SetDisplayMode(display->fullscreen_mode); + } + } + return 0; } -/* - * Create a shadow surface suitable for fooling the app. :-) - */ -static void SDL_CreateShadowSurface(int depth) -{ - Uint32 Rmask, Gmask, Bmask; - - /* Allocate the shadow surface */ - if ( depth == (SDL_VideoSurface->format)->BitsPerPixel ) { - Rmask = (SDL_VideoSurface->format)->Rmask; - Gmask = (SDL_VideoSurface->format)->Gmask; - Bmask = (SDL_VideoSurface->format)->Bmask; - } else { - Rmask = Gmask = Bmask = 0; - } - SDL_ShadowSurface = SDL_CreateRGBSurface(SDL_SWSURFACE, - SDL_VideoSurface->w, SDL_VideoSurface->h, - depth, Rmask, Gmask, Bmask, 0); - if ( SDL_ShadowSurface == NULL ) { - return; - } - - /* 8-bit shadow surfaces report that they have exclusive palette */ - if ( SDL_ShadowSurface->format->palette ) { - SDL_ShadowSurface->flags |= SDL_HWPALETTE; - if ( depth == (SDL_VideoSurface->format)->BitsPerPixel ) { - SDL_memcpy(SDL_ShadowSurface->format->palette->colors, - SDL_VideoSurface->format->palette->colors, - SDL_VideoSurface->format->palette->ncolors* - sizeof(SDL_Color)); - } else { - SDL_DitherColors( - SDL_ShadowSurface->format->palette->colors, depth); - } - } - - /* If the video surface is resizable, the shadow should say so */ - if ( (SDL_VideoSurface->flags & SDL_RESIZABLE) == SDL_RESIZABLE ) { - SDL_ShadowSurface->flags |= SDL_RESIZABLE; - } - /* If the video surface has no frame, the shadow should say so */ - if ( (SDL_VideoSurface->flags & SDL_NOFRAME) == SDL_NOFRAME ) { - SDL_ShadowSurface->flags |= SDL_NOFRAME; - } - /* If the video surface is fullscreen, the shadow should say so */ - if ( (SDL_VideoSurface->flags & SDL_FULLSCREEN) == SDL_FULLSCREEN ) { - SDL_ShadowSurface->flags |= SDL_FULLSCREEN; - } - /* If the video surface is flippable, the shadow should say so */ - if ( (SDL_VideoSurface->flags & SDL_DOUBLEBUF) == SDL_DOUBLEBUF ) { - SDL_ShadowSurface->flags |= SDL_DOUBLEBUF; - } - return; -} - -#ifdef __QNXNTO__ - #include -#endif /* __QNXNTO__ */ +const SDL_DisplayMode * +SDL_GetFullscreenDisplayMode(void) +{ + if (_this) { + return SDL_CurrentDisplay.fullscreen_mode; + } + return NULL; +} -/* - * Set the requested video mode, allocating a shadow buffer if necessary. - */ -SDL_Surface * SDL_SetVideoMode (int width, int height, int bpp, Uint32 flags) -{ - SDL_VideoDevice *video, *this; - SDL_Surface *prev_mode, *mode; - int video_w; - int video_h; - int video_bpp; - int is_opengl; - SDL_GrabMode saved_grab; - - /* Start up the video driver, if necessary.. - WARNING: This is the only function protected this way! - */ - if ( ! current_video ) { - if ( SDL_Init(SDL_INIT_VIDEO|SDL_INIT_NOPARACHUTE) < 0 ) { - return(NULL); - } - } - this = video = current_video; - - /* Default to the current width and height */ - if ( width == 0 ) { - width = video->info.current_w; - } - if ( height == 0 ) { - height = video->info.current_h; - } - /* Default to the current video bpp */ - if ( bpp == 0 ) { - flags |= SDL_ANYFORMAT; - bpp = SDL_VideoSurface->format->BitsPerPixel; - } - - /* Get a good video mode, the closest one possible */ - video_w = width; - video_h = height; - video_bpp = bpp; - if ( ! SDL_GetVideoMode(&video_w, &video_h, &video_bpp, flags) ) { - return(NULL); - } - - /* Check the requested flags */ - /* There's no palette in > 8 bits-per-pixel mode */ - if ( video_bpp > 8 ) { - flags &= ~SDL_HWPALETTE; - } -#if 0 - if ( (flags&SDL_FULLSCREEN) != SDL_FULLSCREEN ) { - /* There's no windowed double-buffering */ - flags &= ~SDL_DOUBLEBUF; - } -#endif - if ( (flags&SDL_DOUBLEBUF) == SDL_DOUBLEBUF ) { - /* Use hardware surfaces when double-buffering */ - flags |= SDL_HWSURFACE; - } - - is_opengl = ( ( flags & SDL_OPENGL ) == SDL_OPENGL ); - if ( is_opengl ) { - /* These flags are for 2D video modes only */ - flags &= ~(SDL_HWSURFACE|SDL_DOUBLEBUF); - } - - /* Reset the keyboard here so event callbacks can run */ - SDL_ResetKeyboard(); - SDL_ResetMouse(); - SDL_cursorstate &= ~CURSOR_USINGSW; - - /* Clean up any previous video mode */ - if ( SDL_PublicSurface != NULL ) { - SDL_PublicSurface = NULL; - } - if ( SDL_ShadowSurface != NULL ) { - SDL_Surface *ready_to_go; - ready_to_go = SDL_ShadowSurface; - SDL_ShadowSurface = NULL; - SDL_FreeSurface(ready_to_go); - } - if ( video->physpal ) { - SDL_free(video->physpal->colors); - SDL_free(video->physpal); - video->physpal = NULL; - } - if( video->gammacols) { - SDL_free(video->gammacols); - video->gammacols = NULL; - } - - /* Save the previous grab state and turn off grab for mode switch */ - saved_grab = SDL_WM_GrabInputOff(); - - /* Try to set the video mode, along with offset and clipping */ - prev_mode = SDL_VideoSurface; - SDL_LockCursor(); - SDL_VideoSurface = NULL; /* In case it's freed by driver */ - mode = video->SetVideoMode(this, prev_mode,video_w,video_h,video_bpp,flags); - if ( mode ) { /* Prevent resize events from mode change */ - /* But not on OS/2 */ -#ifndef __OS2__ - SDL_PrivateResize(mode->w, mode->h); -#endif +int +SDL_SetDisplayPalette(const SDL_Color * colors, int firstcolor, int ncolors) +{ + SDL_Palette *palette; + int status = 0; + + if (!_this) { + SDL_SetError("Video subsystem has not been initialized"); + return -1; + } + palette = SDL_CurrentDisplay.palette; + if (!palette) { + SDL_SetError("Display mode does not have a palette"); + return -1; + } + + status = SDL_SetPaletteColors(palette, colors, firstcolor, ncolors); + + if (_this->SetDisplayPalette) { + if (_this->SetDisplayPalette(_this, palette) < 0) { + status = -1; + } + } + return status; +} - /* Sam - If we asked for OpenGL mode, and didn't get it, fail */ - if ( is_opengl && !(mode->flags & SDL_OPENGL) ) { - mode = NULL; - SDL_SetError("OpenGL not available"); - } - } - /* - * rcg11292000 - * If you try to set an SDL_OPENGL surface, and fail to find a - * matching visual, then the next call to SDL_SetVideoMode() - * will segfault, since we no longer point to a dummy surface, - * but rather NULL. - * Sam 11/29/00 - * WARNING, we need to make sure that the previous mode hasn't - * already been freed by the video driver. What do we do in - * that case? Should we call SDL_VideoInit() again? - */ - SDL_VideoSurface = (mode != NULL) ? mode : prev_mode; - - if ( (mode != NULL) && (!is_opengl) ) { - /* Sanity check */ - if ( (mode->w < width) || (mode->h < height) ) { - SDL_SetError("Video mode smaller than requested"); - return(NULL); - } - - /* If we have a palettized surface, create a default palette */ - if ( mode->format->palette ) { - SDL_PixelFormat *vf = mode->format; - SDL_DitherColors(vf->palette->colors, vf->BitsPerPixel); - video->SetColors(this, 0, vf->palette->ncolors, - vf->palette->colors); - } - - /* Clear the surface to black */ - video->offset_x = 0; - video->offset_y = 0; - mode->offset = 0; - SDL_SetClipRect(mode, NULL); - SDL_ClearSurface(mode); - - /* Now adjust the offsets to match the desired mode */ - video->offset_x = (mode->w-width)/2; - video->offset_y = (mode->h-height)/2; - mode->offset = video->offset_y*mode->pitch + - video->offset_x*mode->format->BytesPerPixel; -#ifdef DEBUG_VIDEO - fprintf(stderr, - "Requested mode: %dx%dx%d, obtained mode %dx%dx%d (offset %d)\n", - width, height, bpp, - mode->w, mode->h, mode->format->BitsPerPixel, mode->offset); -#endif - mode->w = width; - mode->h = height; - SDL_SetClipRect(mode, NULL); - } - SDL_ResetCursor(); - SDL_UnlockCursor(); - - /* If we failed setting a video mode, return NULL... (Uh Oh!) */ - if ( mode == NULL ) { - return(NULL); - } - - /* If there is no window manager, set the SDL_NOFRAME flag */ - if ( ! video->info.wm_available ) { - mode->flags |= SDL_NOFRAME; - } - - /* Reset the mouse cursor and grab for new video mode */ - SDL_SetCursor(NULL); - if ( video->UpdateMouse ) { - video->UpdateMouse(this); - } - SDL_WM_GrabInput(saved_grab); - SDL_GetRelativeMouseState(NULL, NULL); /* Clear first large delta */ - -#if SDL_VIDEO_OPENGL - /* Load GL symbols (before MakeCurrent, where we need glGetString). */ - if ( flags & (SDL_OPENGL | SDL_OPENGLBLIT) ) { - -#if defined(__QNXNTO__) && (_NTO_VERSION < 630) -#define __SDL_NOGETPROCADDR__ -#elif defined(__MINT__) -#define __SDL_NOGETPROCADDR__ -#endif -#ifdef __SDL_NOGETPROCADDR__ - #define SDL_PROC(ret,func,params) video->func=func; -#else - #define SDL_PROC(ret,func,params) \ - do { \ - video->func = SDL_GL_GetProcAddress(#func); \ - if ( ! video->func ) { \ - SDL_SetError("Couldn't load GL function %s: %s\n", #func, SDL_GetError()); \ - return(NULL); \ - } \ - } while ( 0 ); - -#endif /* __SDL_NOGETPROCADDR__ */ - -#include "SDL_glfuncs.h" -#undef SDL_PROC - } -#endif /* SDL_VIDEO_OPENGL */ - - /* If we're running OpenGL, make the context current */ - if ( (video->screen->flags & SDL_OPENGL) && - video->GL_MakeCurrent ) { - if ( video->GL_MakeCurrent(this) < 0 ) { - return(NULL); - } - } - - /* Set up a fake SDL surface for OpenGL "blitting" */ - if ( (flags & SDL_OPENGLBLIT) == SDL_OPENGLBLIT ) { - /* Load GL functions for performing the texture updates */ -#if SDL_VIDEO_OPENGL - - /* Create a software surface for blitting */ -#ifdef GL_VERSION_1_2 - /* If the implementation either supports the packed pixels - extension, or implements the core OpenGL 1.2 API, it will - support the GL_UNSIGNED_SHORT_5_6_5 texture format. - */ - if ( (bpp == 16) && - (SDL_strstr((const char *)video->glGetString(GL_EXTENSIONS), "GL_EXT_packed_pixels") || - (SDL_atof((const char *)video->glGetString(GL_VERSION)) >= 1.2f)) - ) { - video->is_32bit = 0; - SDL_VideoSurface = SDL_CreateRGBSurface( - flags, - width, - height, - 16, - 31 << 11, - 63 << 5, - 31, - 0 - ); - } - else -#endif /* OpenGL 1.2 */ - { - video->is_32bit = 1; - SDL_VideoSurface = SDL_CreateRGBSurface( - flags, - width, - height, - 32, -#if SDL_BYTEORDER == SDL_LIL_ENDIAN - 0x000000FF, - 0x0000FF00, - 0x00FF0000, - 0xFF000000 -#else - 0xFF000000, - 0x00FF0000, - 0x0000FF00, - 0x000000FF -#endif - ); - } - if ( ! SDL_VideoSurface ) { - return(NULL); - } - SDL_VideoSurface->flags = mode->flags | SDL_OPENGLBLIT; - - /* Free the original video mode surface (is this safe?) */ - SDL_FreeSurface(mode); - - /* Set the surface completely opaque & white by default */ - SDL_memset( SDL_VideoSurface->pixels, 255, SDL_VideoSurface->h * SDL_VideoSurface->pitch ); - video->glGenTextures( 1, &video->texture ); - video->glBindTexture( GL_TEXTURE_2D, video->texture ); - video->glTexImage2D( - GL_TEXTURE_2D, - 0, - video->is_32bit ? GL_RGBA : GL_RGB, - 256, - 256, - 0, - video->is_32bit ? GL_RGBA : GL_RGB, -#ifdef GL_VERSION_1_2 - video->is_32bit ? GL_UNSIGNED_BYTE : GL_UNSIGNED_SHORT_5_6_5, -#else - GL_UNSIGNED_BYTE, -#endif - NULL); +int +SDL_GetDisplayPalette(SDL_Color * colors, int firstcolor, int ncolors) +{ + SDL_Palette *palette; + + if (!_this) { + SDL_SetError("Video subsystem has not been initialized"); + return -1; + } + + palette = SDL_CurrentDisplay.palette; + if (!palette->ncolors) { + SDL_SetError("Display mode does not have a palette"); + return -1; + } + + if (firstcolor < 0 || (firstcolor + ncolors) > palette->ncolors) { + SDL_SetError("Palette indices are out of range"); + return -1; + } + + SDL_memcpy(colors, &palette->colors[firstcolor], + ncolors * sizeof(*colors)); + return 0; +} - video->UpdateRects = SDL_GL_UpdateRectsLock; -#else - SDL_SetError("Somebody forgot to #define SDL_VIDEO_OPENGL"); - return(NULL); -#endif - } - - /* Create a shadow surface if necessary */ - /* There are three conditions under which we create a shadow surface: - 1. We need a particular bits-per-pixel that we didn't get. - 2. We need a hardware palette and didn't get one. - 3. We need a software surface and got a hardware surface. - */ - if ( !(SDL_VideoSurface->flags & SDL_OPENGL) && - ( - ( !(flags&SDL_ANYFORMAT) && - (SDL_VideoSurface->format->BitsPerPixel != bpp)) || - ( (flags&SDL_HWPALETTE) && - !(SDL_VideoSurface->flags&SDL_HWPALETTE)) || - /* If the surface is in hardware, video writes are visible - as soon as they are performed, so we need to buffer them - */ - ( ((flags&SDL_HWSURFACE) == SDL_SWSURFACE) && - (SDL_VideoSurface->flags&SDL_HWSURFACE)) || - ( (flags&SDL_DOUBLEBUF) && - (SDL_VideoSurface->flags&SDL_HWSURFACE) && - !(SDL_VideoSurface->flags&SDL_DOUBLEBUF)) - ) ) { - SDL_CreateShadowSurface(bpp); - if ( SDL_ShadowSurface == NULL ) { - SDL_SetError("Couldn't create shadow surface"); - return(NULL); - } - SDL_PublicSurface = SDL_ShadowSurface; - } else { - SDL_PublicSurface = SDL_VideoSurface; - } - video->info.vfmt = SDL_VideoSurface->format; - video->info.current_w = SDL_VideoSurface->w; - video->info.current_h = SDL_VideoSurface->h; - - /* We're done! */ - return(SDL_PublicSurface); -} - -/* - * Convert a surface into the video pixel format. - */ -SDL_Surface * SDL_DisplayFormat (SDL_Surface *surface) -{ - Uint32 flags; - - if ( ! SDL_PublicSurface ) { - SDL_SetError("No video mode has been set"); - return(NULL); - } - /* Set the flags appropriate for copying to display surface */ - if (((SDL_PublicSurface->flags&SDL_HWSURFACE) == SDL_HWSURFACE) && current_video->info.blit_hw) - flags = SDL_HWSURFACE; - else - flags = SDL_SWSURFACE; -#ifdef AUTORLE_DISPLAYFORMAT - flags |= (surface->flags & (SDL_SRCCOLORKEY|SDL_SRCALPHA)); - flags |= SDL_RLEACCELOK; -#else - flags |= surface->flags & (SDL_SRCCOLORKEY|SDL_SRCALPHA|SDL_RLEACCELOK); -#endif - return(SDL_ConvertSurface(surface, SDL_PublicSurface->format, flags)); +SDL_WindowID +SDL_CreateWindow(const char *title, int x, int y, int w, int h, Uint32 flags) +{ + const Uint32 allowed_flags = (SDL_WINDOW_FULLSCREEN | + SDL_WINDOW_OPENGL | + SDL_WINDOW_SHOWN | + SDL_WINDOW_BORDERLESS | + SDL_WINDOW_RESIZABLE | + SDL_WINDOW_MAXIMIZED | + SDL_WINDOW_MINIMIZED | + SDL_WINDOW_INPUT_GRABBED); + SDL_VideoDisplay *display; + SDL_Window window; + int num_windows; + SDL_Window *windows; + + if (!_this) { + SDL_SetError("Video subsystem has not been initialized"); + return 0; + } + + SDL_zero(window); + window.id = _this->next_object_id++; + window.title = title ? SDL_strdup(title) : NULL; + window.x = x; + window.y = y; + window.w = w; + window.h = h; + window.flags = (flags & allowed_flags); + window.display = _this->current_display; + + if (_this->CreateWindow && _this->CreateWindow(_this, &window) < 0) { + if (window.title) { + SDL_free(window.title); + } + return 0; + } + + display = &SDL_CurrentDisplay; + num_windows = display->num_windows; + windows = + SDL_realloc(display->windows, (num_windows + 1) * sizeof(*windows)); + if (!windows) { + if (_this->DestroyWindow) { + _this->DestroyWindow(_this, &window); + } + if (window.title) { + SDL_free(window.title); + } + return 0; + } + windows[num_windows] = window; + display->windows = windows; + display->num_windows++; + + if (FULLSCREEN_VISIBLE(&window)) { + /* Hide any other fullscreen windows */ + int i; + for (i = 0; i < display->num_windows; ++i) { + SDL_Window *other = &display->windows[i]; + if (other->id != window.id && FULLSCREEN_VISIBLE(other)) { + SDL_MinimizeWindow(other->id); + } + } + SDL_SetDisplayMode(display->fullscreen_mode); + } + + return window.id; } -/* - * Convert a surface into a format that's suitable for blitting to - * the screen, but including an alpha channel. - */ -SDL_Surface *SDL_DisplayFormatAlpha(SDL_Surface *surface) -{ - SDL_PixelFormat *vf; - SDL_PixelFormat *format; - SDL_Surface *converted; - Uint32 flags; - /* default to ARGB8888 */ - Uint32 amask = 0xff000000; - Uint32 rmask = 0x00ff0000; - Uint32 gmask = 0x0000ff00; - Uint32 bmask = 0x000000ff; - - if ( ! SDL_PublicSurface ) { - SDL_SetError("No video mode has been set"); - return(NULL); - } - vf = SDL_PublicSurface->format; - - switch(vf->BytesPerPixel) { - case 2: - /* For XGY5[56]5, use, AXGY8888, where {X, Y} = {R, B}. - For anything else (like ARGB4444) it doesn't matter - since we have no special code for it anyway */ - if ( (vf->Rmask == 0x1f) && - (vf->Bmask == 0xf800 || vf->Bmask == 0x7c00)) { - rmask = 0xff; - bmask = 0xff0000; - } - break; - - case 3: - case 4: - /* Keep the video format, as long as the high 8 bits are - unused or alpha */ - if ( (vf->Rmask == 0xff) && (vf->Bmask == 0xff0000) ) { - rmask = 0xff; - bmask = 0xff0000; - } - break; - - default: - /* We have no other optimised formats right now. When/if a new - optimised alpha format is written, add the converter here */ - break; - } - format = SDL_AllocFormat(32, rmask, gmask, bmask, amask); - flags = SDL_PublicSurface->flags & SDL_HWSURFACE; - flags |= surface->flags & (SDL_SRCALPHA | SDL_RLEACCELOK); - converted = SDL_ConvertSurface(surface, format, flags); - SDL_FreeFormat(format); - return(converted); +SDL_WindowID +SDL_CreateWindowFrom(const void *data) +{ + SDL_VideoDisplay *display; + SDL_Window window; + int num_windows; + SDL_Window *windows; + + if (!_this) { + SDL_SetError("Video subsystem has not been initialized"); + return (0); + } + + SDL_zero(window); + window.id = _this->next_object_id++; + window.display = _this->current_display; + + if (!_this->CreateWindowFrom || + _this->CreateWindowFrom(_this, &window, data) < 0) { + return 0; + } + + display = &SDL_CurrentDisplay; + num_windows = display->num_windows; + windows = + SDL_realloc(display->windows, (num_windows + 1) * sizeof(*windows)); + if (!windows) { + if (_this->DestroyWindow) { + _this->DestroyWindow(_this, &window); + } + if (window.title) { + SDL_free(window.title); + } + return 0; + } + windows[num_windows] = window; + display->windows = windows; + display->num_windows++; + + return window.id; } -/* - * Update a specific portion of the physical screen - */ -void SDL_UpdateRect(SDL_Surface *screen, Sint32 x, Sint32 y, Uint32 w, Uint32 h) -{ - if ( screen ) { - SDL_Rect rect; - - /* Perform some checking */ - if ( w == 0 ) - w = screen->w; - if ( h == 0 ) - h = screen->h; - if ( (int)(x+w) > screen->w ) - return; - if ( (int)(y+h) > screen->h ) - return; - - /* Fill the rectangle */ - rect.x = (Sint16)x; - rect.y = (Sint16)y; - rect.w = (Uint16)w; - rect.h = (Uint16)h; - SDL_UpdateRects(screen, 1, &rect); - } -} -void SDL_UpdateRects (SDL_Surface *screen, int numrects, SDL_Rect *rects) -{ - int i; - SDL_VideoDevice *video = current_video; - SDL_VideoDevice *this = current_video; - - if ( (screen->flags & (SDL_OPENGL | SDL_OPENGLBLIT)) == SDL_OPENGL ) { - SDL_SetError("OpenGL active, use SDL_GL_SwapBuffers()"); - return; - } - if ( screen == SDL_ShadowSurface ) { - /* Blit the shadow surface using saved mapping */ - SDL_Palette *pal = screen->format->palette; - SDL_Color *saved_colors = NULL; - if ( pal && !(SDL_VideoSurface->flags & SDL_HWPALETTE) ) { - /* simulated 8bpp, use correct physical palette */ - saved_colors = pal->colors; - if ( video->gammacols ) { - /* gamma-corrected palette */ - pal->colors = video->gammacols; - } else if ( video->physpal ) { - /* physical palette different from logical */ - pal->colors = video->physpal->colors; - } - } - if ( SHOULD_DRAWCURSOR(SDL_cursorstate) ) { - SDL_LockCursor(); - SDL_DrawCursor(SDL_ShadowSurface); - for ( i=0; icolors = saved_colors; - } - - /* Fall through to video surface update */ - screen = SDL_VideoSurface; - } - if ( screen == SDL_VideoSurface ) { - /* Update the video surface */ - if ( screen->offset ) { - for ( i=0; ioffset_x; - rects[i].y += video->offset_y; - } - video->UpdateRects(this, numrects, rects); - for ( i=0; ioffset_x; - rects[i].y -= video->offset_y; - } - } else { - video->UpdateRects(this, numrects, rects); - } - } +SDL_Window * +SDL_GetWindowFromID(SDL_WindowID windowID) +{ + int i, j; + + if (!_this) { + return NULL; + } + + for (i = 0; i < _this->num_displays; ++i) { + SDL_VideoDisplay *display = &_this->displays[i]; + for (j = 0; j < display->num_windows; ++j) { + SDL_Window *window = &display->windows[j]; + if (window->id == windowID) { + return window; + } + } + } + return NULL; } -/* - * Performs hardware double buffering, if possible, or a full update if not. - */ -int SDL_Flip(SDL_Surface *screen) -{ - SDL_VideoDevice *video = current_video; - /* Copy the shadow surface to the video surface */ - if ( screen == SDL_ShadowSurface ) { - SDL_Rect rect; - SDL_Palette *pal = screen->format->palette; - SDL_Color *saved_colors = NULL; - if ( pal && !(SDL_VideoSurface->flags & SDL_HWPALETTE) ) { - /* simulated 8bpp, use correct physical palette */ - saved_colors = pal->colors; - if ( video->gammacols ) { - /* gamma-corrected palette */ - pal->colors = video->gammacols; - } else if ( video->physpal ) { - /* physical palette different from logical */ - pal->colors = video->physpal->colors; - } - } - - rect.x = 0; - rect.y = 0; - rect.w = screen->w; - rect.h = screen->h; - if ( SHOULD_DRAWCURSOR(SDL_cursorstate) ) { - SDL_LockCursor(); - SDL_DrawCursor(SDL_ShadowSurface); - SDL_LowerBlit(SDL_ShadowSurface, &rect, - SDL_VideoSurface, &rect); - SDL_EraseCursor(SDL_ShadowSurface); - SDL_UnlockCursor(); - } else { - SDL_LowerBlit(SDL_ShadowSurface, &rect, - SDL_VideoSurface, &rect); - } - if ( saved_colors ) { - pal->colors = saved_colors; - } - - /* Fall through to video surface update */ - screen = SDL_VideoSurface; - } - if ( (screen->flags & SDL_DOUBLEBUF) == SDL_DOUBLEBUF ) { - SDL_VideoDevice *this = current_video; - return(video->FlipHWSurface(this, SDL_VideoSurface)); - } else { - SDL_UpdateRect(screen, 0, 0, 0, 0); - } - return(0); -} - -static void SetPalette_logical(SDL_Surface *screen, SDL_Color *colors, - int firstcolor, int ncolors) -{ - SDL_Palette *pal = screen->format->palette; - SDL_Palette *vidpal; - - if ( colors != (pal->colors + firstcolor) ) { - SDL_memcpy(pal->colors + firstcolor, colors, - ncolors * sizeof(*colors)); - } - - vidpal = SDL_VideoSurface->format->palette; - if ( (screen == SDL_ShadowSurface) && vidpal ) { - /* - * This is a shadow surface, and the physical - * framebuffer is also indexed. Propagate the - * changes to its logical palette so that - * updates are always identity blits - */ - SDL_memcpy(vidpal->colors + firstcolor, colors, - ncolors * sizeof(*colors)); - } - SDL_FormatChanged(screen); -} - -static int SetPalette_physical(SDL_Surface *screen, - SDL_Color *colors, int firstcolor, int ncolors) -{ - SDL_VideoDevice *video = current_video; - int gotall = 1; - - if ( video->physpal ) { - /* We need to copy the new colors, since we haven't - * already done the copy in the logical set above. - */ - SDL_memcpy(video->physpal->colors + firstcolor, - colors, ncolors * sizeof(*colors)); - } - if ( screen == SDL_ShadowSurface ) { - if ( SDL_VideoSurface->flags & SDL_HWPALETTE ) { - /* - * The real screen is also indexed - set its physical - * palette. The physical palette does not include the - * gamma modification, we apply it directly instead, - * but this only happens if we have hardware palette. - */ - screen = SDL_VideoSurface; - } else { - /* - * The video surface is not indexed - invalidate any - * active shadow-to-video blit mappings. - */ - if ( screen->map->dst == SDL_VideoSurface ) { - SDL_InvalidateMap(screen->map); - } - if ( video->gamma ) { - if( ! video->gammacols ) { - SDL_Palette *pp = video->physpal; - if(!pp) - pp = screen->format->palette; - video->gammacols = SDL_malloc(pp->ncolors - * sizeof(SDL_Color)); - SDL_ApplyGamma(video->gamma, - pp->colors, - video->gammacols, - pp->ncolors); - } else { - SDL_ApplyGamma(video->gamma, colors, - video->gammacols - + firstcolor, - ncolors); - } - } - SDL_UpdateRect(screen, 0, 0, 0, 0); - } - } - - if ( screen == SDL_VideoSurface ) { - SDL_Color gcolors[256]; - - if ( video->gamma ) { - SDL_ApplyGamma(video->gamma, colors, gcolors, ncolors); - colors = gcolors; - } - gotall = video->SetColors(video, firstcolor, ncolors, colors); - if ( ! gotall ) { - /* The video flags shouldn't have SDL_HWPALETTE, and - the video driver is responsible for copying back the - correct colors into the video surface palette. - */ - ; - } - SDL_CursorPaletteChanged(); - } - return gotall; +SDL_VideoDisplay * +SDL_GetDisplayFromWindow(SDL_Window * window) +{ + if (!_this) { + return NULL; + } + return &_this->displays[window->display]; } -/* - * Set the physical and/or logical colormap of a surface: - * Only the screen has a physical colormap. It determines what is actually - * sent to the display. - * The logical colormap is used to map blits to/from the surface. - * 'which' is one or both of SDL_LOGPAL, SDL_PHYSPAL - * - * Return nonzero if all colours were set as requested, or 0 otherwise. - */ -int SDL_SetPalette(SDL_Surface *screen, int which, - SDL_Color *colors, int firstcolor, int ncolors) -{ - SDL_Palette *pal; - int gotall; - int palsize; - - if ( ! current_video ) { - return 0; - } - if ( screen != SDL_PublicSurface ) { - /* only screens have physical palettes */ - which &= ~SDL_PHYSPAL; - } else if( (screen->flags & SDL_HWPALETTE) != SDL_HWPALETTE ) { - /* hardware palettes required for split colormaps */ - which |= SDL_PHYSPAL | SDL_LOGPAL; - } - - /* Verify the parameters */ - pal = screen->format->palette; - if( !pal ) { - return 0; /* not a palettized surface */ - } - gotall = 1; - palsize = 1 << screen->format->BitsPerPixel; - if ( ncolors > (palsize - firstcolor) ) { - ncolors = (palsize - firstcolor); - gotall = 0; - } - - if ( which & SDL_LOGPAL ) { - /* - * Logical palette change: The actual screen isn't affected, - * but the internal colormap is altered so that the - * interpretation of the pixel values (for blits etc) is - * changed. - */ - SetPalette_logical(screen, colors, firstcolor, ncolors); - } - if ( which & SDL_PHYSPAL ) { - SDL_VideoDevice *video = current_video; - /* - * Physical palette change: This doesn't affect the - * program's idea of what the screen looks like, but changes - * its actual appearance. - */ - if(!video) - return gotall; /* video not yet initialized */ - if(!video->physpal && !(which & SDL_LOGPAL) ) { - /* Lazy physical palette allocation */ - int size; - SDL_Palette *pp = SDL_malloc(sizeof(*pp)); - if ( !pp ) { - return 0; - } - current_video->physpal = pp; - pp->ncolors = pal->ncolors; - size = pp->ncolors * sizeof(SDL_Color); - pp->colors = SDL_malloc(size); - if ( !pp->colors ) { - return 0; - } - SDL_memcpy(pp->colors, pal->colors, size); - } - if ( ! SetPalette_physical(screen, - colors, firstcolor, ncolors) ) { - gotall = 0; - } - } - return gotall; -} - -int SDL_SetColors(SDL_Surface *screen, SDL_Color *colors, int firstcolor, - int ncolors) -{ - return SDL_SetPalette(screen, SDL_LOGPAL | SDL_PHYSPAL, - colors, firstcolor, ncolors); +Uint32 +SDL_GetWindowFlags(SDL_WindowID windowID) +{ + SDL_Window *window = SDL_GetWindowFromID(windowID); + + if (!window) { + return 0; + } + return window->flags; } -/* - * Clean up the video subsystem - */ -void SDL_VideoQuit (void) -{ - SDL_Surface *ready_to_go; - - if ( current_video ) { - SDL_VideoDevice *video = current_video; - SDL_VideoDevice *this = current_video; - - /* Halt event processing before doing anything else */ - SDL_StopEventLoop(); - - /* Clean up allocated window manager items */ - if ( SDL_PublicSurface ) { - SDL_PublicSurface = NULL; - } - SDL_CursorQuit(); - - /* Just in case... */ - SDL_WM_GrabInputOff(); - - /* Clean up the system video */ - video->VideoQuit(this); - - /* Free any lingering surfaces */ - ready_to_go = SDL_ShadowSurface; - SDL_ShadowSurface = NULL; - SDL_FreeSurface(ready_to_go); - if ( SDL_VideoSurface != NULL ) { - ready_to_go = SDL_VideoSurface; - SDL_VideoSurface = NULL; - SDL_FreeSurface(ready_to_go); - } - SDL_PublicSurface = NULL; - - /* Clean up miscellaneous memory */ - if ( video->physpal ) { - SDL_free(video->physpal->colors); - SDL_free(video->physpal); - video->physpal = NULL; - } - if ( video->gammacols ) { - SDL_free(video->gammacols); - video->gammacols = NULL; - } - if ( video->gamma ) { - SDL_free(video->gamma); - video->gamma = NULL; - } - if ( video->wm_title != NULL ) { - SDL_free(video->wm_title); - video->wm_title = NULL; - } - if ( video->wm_icon != NULL ) { - SDL_free(video->wm_icon); - video->wm_icon = NULL; - } - - /* Finish cleaning up video subsystem */ - video->free(this); - current_video = NULL; - } - return; +void +SDL_SetWindowTitle(SDL_WindowID windowID, const char *title) +{ + SDL_Window *window = SDL_GetWindowFromID(windowID); + + if (!window) { + return; + } + if (window->title) { + SDL_free(window->title); + } + window->title = SDL_strdup(title); + + if (_this->SetWindowTitle) { + _this->SetWindowTitle(_this, window); + } } -/* Load the GL driver library */ -int SDL_GL_LoadLibrary(const char *path) -{ - SDL_VideoDevice *video = current_video; - SDL_VideoDevice *this = current_video; - int retval; - - retval = -1; - if ( video == NULL ) { - SDL_SetError("Video subsystem has not been initialized"); - } else { - if ( video->GL_LoadLibrary ) { - retval = video->GL_LoadLibrary(this, path); - } else { - SDL_SetError("No dynamic GL support in video driver"); - } - } - return(retval); -} - -void *SDL_GL_GetProcAddress(const char* proc) -{ - SDL_VideoDevice *video = current_video; - SDL_VideoDevice *this = current_video; - void *func; - - func = NULL; - if ( video->GL_GetProcAddress ) { - if ( video->gl_config.driver_loaded ) { - func = video->GL_GetProcAddress(this, proc); - } else { - SDL_SetError("No GL driver has been loaded"); - } - } else { - SDL_SetError("No dynamic GL support in video driver"); - } - return func; +const char * +SDL_GetWindowTitle(SDL_WindowID windowID) +{ + SDL_Window *window = SDL_GetWindowFromID(windowID); + + if (!window) { + return NULL; + } + return window->title; } -/* Set the specified GL attribute for setting up a GL video mode */ -int SDL_GL_SetAttribute( SDL_GLattr attr, int value ) -{ - int retval; - SDL_VideoDevice *video = current_video; - - retval = 0; - switch (attr) { - case SDL_GL_RED_SIZE: - video->gl_config.red_size = value; - break; - case SDL_GL_GREEN_SIZE: - video->gl_config.green_size = value; - break; - case SDL_GL_BLUE_SIZE: - video->gl_config.blue_size = value; - break; - case SDL_GL_ALPHA_SIZE: - video->gl_config.alpha_size = value; - break; - case SDL_GL_DOUBLEBUFFER: - video->gl_config.double_buffer = value; - break; - case SDL_GL_BUFFER_SIZE: - video->gl_config.buffer_size = value; - break; - case SDL_GL_DEPTH_SIZE: - video->gl_config.depth_size = value; - break; - case SDL_GL_STENCIL_SIZE: - video->gl_config.stencil_size = value; - break; - case SDL_GL_ACCUM_RED_SIZE: - video->gl_config.accum_red_size = value; - break; - case SDL_GL_ACCUM_GREEN_SIZE: - video->gl_config.accum_green_size = value; - break; - case SDL_GL_ACCUM_BLUE_SIZE: - video->gl_config.accum_blue_size = value; - break; - case SDL_GL_ACCUM_ALPHA_SIZE: - video->gl_config.accum_alpha_size = value; - break; - case SDL_GL_STEREO: - video->gl_config.stereo = value; - break; - case SDL_GL_MULTISAMPLEBUFFERS: - video->gl_config.multisamplebuffers = value; - break; - case SDL_GL_MULTISAMPLESAMPLES: - video->gl_config.multisamplesamples = value; - break; - case SDL_GL_ACCELERATED_VISUAL: - video->gl_config.accelerated = value; - break; - case SDL_GL_SWAP_CONTROL: - video->gl_config.swap_control = value; - break; - default: - SDL_SetError("Unknown OpenGL attribute"); - retval = -1; - break; - } - return(retval); +void +SDL_SetWindowData(SDL_WindowID windowID, void *userdata) +{ + SDL_Window *window = SDL_GetWindowFromID(windowID); + + if (!window) { + return; + } + window->userdata = userdata; } -/* Retrieve an attribute value from the windowing system. */ -int SDL_GL_GetAttribute(SDL_GLattr attr, int* value) +void * +SDL_GetWindowData(SDL_WindowID windowID) { - int retval = -1; - SDL_VideoDevice* video = current_video; - SDL_VideoDevice* this = current_video; + SDL_Window *window = SDL_GetWindowFromID(windowID); - if ( video->GL_GetAttribute ) { - retval = this->GL_GetAttribute(this, attr, value); - } else { - *value = 0; - SDL_SetError("GL_GetAttribute not supported"); - } - return retval; + if (!window) { + return NULL; + } + return window->userdata; } -/* Perform a GL buffer swap on the current GL context */ -void SDL_GL_SwapBuffers(void) -{ - SDL_VideoDevice *video = current_video; - SDL_VideoDevice *this = current_video; - - if ( video->screen->flags & SDL_OPENGL ) { - video->GL_SwapBuffers(this); - } else { - SDL_SetError("OpenGL video mode has not been set"); - } -} - -/* Update rects with locking */ -void SDL_GL_UpdateRectsLock(SDL_VideoDevice* this, int numrects, SDL_Rect *rects) -{ - SDL_GL_Lock(); - SDL_GL_UpdateRects(numrects, rects); - SDL_GL_Unlock(); -} - -/* Update rects without state setting and changing (the caller is responsible for it) */ -void SDL_GL_UpdateRects(int numrects, SDL_Rect *rects) -{ -#if SDL_VIDEO_OPENGL - SDL_VideoDevice *this = current_video; - SDL_Rect update, tmp; - int x, y, i; - - for ( i = 0; i < numrects; i++ ) - { - tmp.y = rects[i].y; - tmp.h = rects[i].h; - for ( y = 0; y <= rects[i].h / 256; y++ ) - { - tmp.x = rects[i].x; - tmp.w = rects[i].w; - for ( x = 0; x <= rects[i].w / 256; x++ ) - { - update.x = tmp.x; - update.y = tmp.y; - update.w = tmp.w; - update.h = tmp.h; - - if ( update.w > 256 ) - update.w = 256; - - if ( update.h > 256 ) - update.h = 256; - - this->glFlush(); - this->glTexSubImage2D( - GL_TEXTURE_2D, - 0, - 0, - 0, - update.w, - update.h, - this->is_32bit? GL_RGBA : GL_RGB, -#ifdef GL_VERSION_1_2 - this->is_32bit ? GL_UNSIGNED_BYTE : GL_UNSIGNED_SHORT_5_6_5, -#else - GL_UNSIGNED_BYTE, -#endif - (Uint8 *)this->screen->pixels + - this->screen->format->BytesPerPixel * update.x + - update.y * this->screen->pitch ); - - this->glFlush(); - /* - * Note the parens around the function name: - * This is because some OpenGL implementations define glTexCoord etc - * as macros, and we don't want them expanded here. - */ - this->glBegin(GL_TRIANGLE_STRIP); - (this->glTexCoord2f)( 0.0, 0.0 ); - (this->glVertex2i)( update.x, update.y ); - (this->glTexCoord2f)( (float)(update.w / 256.0), 0.0 ); - (this->glVertex2i)( update.x + update.w, update.y ); - (this->glTexCoord2f)( 0.0, (float)(update.h / 256.0) ); - (this->glVertex2i)( update.x, update.y + update.h ); - (this->glTexCoord2f)( (float)(update.w / 256.0), (float)(update.h / 256.0) ); - (this->glVertex2i)( update.x + update.w , update.y + update.h ); - this->glEnd(); - - tmp.x += 256; - tmp.w -= 256; - } - tmp.y += 256; - tmp.h -= 256; - } - } -#endif +void +SDL_SetWindowPosition(SDL_WindowID windowID, int x, int y) +{ + SDL_Window *window = SDL_GetWindowFromID(windowID); + + if (!window) { + return; + } + + if (x != SDL_WINDOWPOS_UNDEFINED) { + window->x = x; + } + if (y != SDL_WINDOWPOS_UNDEFINED) { + window->y = y; + } + + if (_this->SetWindowPosition) { + _this->SetWindowPosition(_this, window); + } } -/* Lock == save current state */ -void SDL_GL_Lock() +void +SDL_GetWindowPosition(SDL_WindowID windowID, int *x, int *y) { -#if SDL_VIDEO_OPENGL - lock_count--; - if (lock_count==-1) - { - SDL_VideoDevice *this = current_video; + SDL_Window *window = SDL_GetWindowFromID(windowID); + + if (!window) { + return; + } + if (x) { + *x = window->x; + } + if (y) { + *y = window->y; + } +} - this->glPushAttrib( GL_ALL_ATTRIB_BITS ); /* TODO: narrow range of what is saved */ -#ifdef GL_CLIENT_PIXEL_STORE_BIT - this->glPushClientAttrib( GL_CLIENT_PIXEL_STORE_BIT ); -#endif +void +SDL_SetWindowSize(SDL_WindowID windowID, int w, int h) +{ + SDL_Window *window = SDL_GetWindowFromID(windowID); - this->glEnable(GL_TEXTURE_2D); - this->glEnable(GL_BLEND); - this->glDisable(GL_FOG); - this->glDisable(GL_ALPHA_TEST); - this->glDisable(GL_DEPTH_TEST); - this->glDisable(GL_SCISSOR_TEST); - this->glDisable(GL_STENCIL_TEST); - this->glDisable(GL_CULL_FACE); - - this->glBindTexture( GL_TEXTURE_2D, this->texture ); - this->glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ); - this->glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST ); - this->glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST ); - this->glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT ); - this->glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT ); - - this->glPixelStorei( GL_UNPACK_ROW_LENGTH, this->screen->pitch / this->screen->format->BytesPerPixel ); - this->glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - (this->glColor4f)(1.0, 1.0, 1.0, 1.0); /* Solaris workaround */ - - this->glViewport(0, 0, this->screen->w, this->screen->h); - this->glMatrixMode(GL_PROJECTION); - this->glPushMatrix(); - this->glLoadIdentity(); - - this->glOrtho(0.0, (GLdouble) this->screen->w, (GLdouble) this->screen->h, 0.0, 0.0, 1.0); - - this->glMatrixMode(GL_MODELVIEW); - this->glPushMatrix(); - this->glLoadIdentity(); - } -#endif + if (!window) { + return; + } + + window->w = w; + window->h = h; + + if (_this->SetWindowSize) { + _this->SetWindowSize(_this, window); + } +} + +void +SDL_GetWindowSize(SDL_WindowID windowID, int *w, int *h) +{ + SDL_Window *window = SDL_GetWindowFromID(windowID); + + if (!window) { + return; + } + if (w) { + *w = window->w; + } + if (h) { + *h = window->h; + } } -/* Unlock == restore saved state */ -void SDL_GL_Unlock() +void +SDL_ShowWindow(SDL_WindowID windowID) { -#if SDL_VIDEO_OPENGL - lock_count++; - if (lock_count==0) - { - SDL_VideoDevice *this = current_video; + SDL_Window *window = SDL_GetWindowFromID(windowID); - this->glPopMatrix(); - this->glMatrixMode(GL_PROJECTION); - this->glPopMatrix(); + if (!window || (window->flags & SDL_WINDOW_SHOWN)) { + return; + } - this->glPopClientAttrib(); - this->glPopAttrib(); - } -#endif + SDL_SendWindowEvent(window->id, SDL_WINDOWEVENT_SHOWN, 0, 0); + + if (_this->ShowWindow) { + _this->ShowWindow(_this, window); + } } -/* - * Sets/Gets the title and icon text of the display window, if any. - */ -void SDL_WM_SetCaption (const char *title, const char *icon) -{ - SDL_VideoDevice *video = current_video; - SDL_VideoDevice *this = current_video; - - if ( video ) { - if ( title ) { - if ( video->wm_title ) { - SDL_free(video->wm_title); - } - video->wm_title = SDL_strdup(title); - } - if ( icon ) { - if ( video->wm_icon ) { - SDL_free(video->wm_icon); - } - video->wm_icon = SDL_strdup(icon); - } - if ( (title || icon) && (video->SetCaption != NULL) ) { - video->SetCaption(this, video->wm_title,video->wm_icon); - } - } -} -void SDL_WM_GetCaption (char **title, char **icon) -{ - SDL_VideoDevice *video = current_video; - - if ( video ) { - if ( title ) { - *title = video->wm_title; - } - if ( icon ) { - *icon = video->wm_icon; - } - } +void +SDL_HideWindow(SDL_WindowID windowID) +{ + SDL_Window *window = SDL_GetWindowFromID(windowID); + + if (!window || !(window->flags & SDL_WINDOW_SHOWN)) { + return; + } + + SDL_SendWindowEvent(window->id, SDL_WINDOWEVENT_HIDDEN, 0, 0); + + if (_this->HideWindow) { + _this->HideWindow(_this, window); + } } -/* Utility function used by SDL_WM_SetIcon(); - * flags & 1 for color key, flags & 2 for alpha channel. */ -static void CreateMaskFromColorKeyOrAlpha(SDL_Surface *icon, Uint8 *mask, int flags) +void +SDL_RaiseWindow(SDL_WindowID windowID) { - int x, y; - Uint32 colorkey; -#define SET_MASKBIT(icon, x, y, mask) \ - mask[(y*((icon->w+7)/8))+(x/8)] &= ~(0x01<<(7-(x%8))) + SDL_Window *window = SDL_GetWindowFromID(windowID); - colorkey = icon->format->colorkey; - switch (icon->format->BytesPerPixel) { - case 1: { Uint8 *pixels; - for ( y=0; yh; ++y ) { - pixels = (Uint8 *)icon->pixels + y*icon->pitch; - for ( x=0; xw; ++x ) { - if ( *pixels++ == colorkey ) { - SET_MASKBIT(icon, x, y, mask); - } - } - } - } - break; - - case 2: { Uint16 *pixels; - for ( y=0; yh; ++y ) { - pixels = (Uint16 *)icon->pixels + - y*icon->pitch/2; - for ( x=0; xw; ++x ) { - if ( (flags & 1) && *pixels == colorkey ) { - SET_MASKBIT(icon, x, y, mask); - } else if((flags & 2) && (*pixels & icon->format->Amask) == 0) { - SET_MASKBIT(icon, x, y, mask); - } - pixels++; - } - } - } - break; - - case 4: { Uint32 *pixels; - for ( y=0; yh; ++y ) { - pixels = (Uint32 *)icon->pixels + - y*icon->pitch/4; - for ( x=0; xw; ++x ) { - if ( (flags & 1) && *pixels == colorkey ) { - SET_MASKBIT(icon, x, y, mask); - } else if((flags & 2) && (*pixels & icon->format->Amask) == 0) { - SET_MASKBIT(icon, x, y, mask); - } - pixels++; - } - } - } - break; - } + if (!window) { + return; + } + + if (_this->RaiseWindow) { + _this->RaiseWindow(_this, window); + } } -/* - * Sets the window manager icon for the display window. - */ -void SDL_WM_SetIcon (SDL_Surface *icon, Uint8 *mask) -{ - SDL_VideoDevice *video = current_video; - SDL_VideoDevice *this = current_video; - - if ( icon && video->SetIcon ) { - /* Generate a mask if necessary, and create the icon! */ - if ( mask == NULL ) { - int mask_len = icon->h*(icon->w+7)/8; - int flags = 0; - mask = (Uint8 *)SDL_malloc(mask_len); - if ( mask == NULL ) { - return; - } - SDL_memset(mask, ~0, mask_len); - if ( icon->flags & SDL_SRCCOLORKEY ) flags |= 1; - if ( icon->flags & SDL_SRCALPHA ) flags |= 2; - if( flags ) { - CreateMaskFromColorKeyOrAlpha(icon, mask, flags); - } - video->SetIcon(video, icon, mask); - SDL_free(mask); - } else { - video->SetIcon(this, icon, mask); - } - } +void +SDL_MaximizeWindow(SDL_WindowID windowID) +{ + SDL_Window *window = SDL_GetWindowFromID(windowID); + + if (!window || (window->flags & SDL_WINDOW_MAXIMIZED)) { + return; + } + + SDL_SendWindowEvent(window->id, SDL_WINDOWEVENT_MAXIMIZED, 0, 0); + + if (_this->MaximizeWindow) { + _this->MaximizeWindow(_this, window); + } } -/* - * Grab or ungrab the keyboard and mouse input. - * This function returns the final grab mode after calling the - * driver dependent function. - */ -static SDL_GrabMode SDL_WM_GrabInputRaw(SDL_GrabMode mode) +void +SDL_MinimizeWindow(SDL_WindowID windowID) { - SDL_VideoDevice *video = current_video; - SDL_VideoDevice *this = current_video; + SDL_Window *window = SDL_GetWindowFromID(windowID); - /* Only do something if we have support for grabs */ - if ( video->GrabInput == NULL ) { - return(video->input_grab); - } + if (!window || (window->flags & SDL_WINDOW_MINIMIZED)) { + return; + } - /* If the final grab mode if off, only then do we actually grab */ -#ifdef DEBUG_GRAB - printf("SDL_WM_GrabInputRaw(%d) ... ", mode); -#endif - if ( mode == SDL_GRAB_OFF ) { - if ( video->input_grab != SDL_GRAB_OFF ) { - mode = video->GrabInput(this, mode); - } - } else { - if ( video->input_grab == SDL_GRAB_OFF ) { - mode = video->GrabInput(this, mode); - } - } - if ( mode != video->input_grab ) { - video->input_grab = mode; - if ( video->CheckMouseMode ) { - video->CheckMouseMode(this); - } - } -#ifdef DEBUG_GRAB - printf("Final mode %d\n", video->input_grab); -#endif + SDL_SendWindowEvent(window->id, SDL_WINDOWEVENT_MINIMIZED, 0, 0); - /* Return the final grab state */ - if ( mode >= SDL_GRAB_FULLSCREEN ) { - mode -= SDL_GRAB_FULLSCREEN; - } - return(mode); + if (_this->MinimizeWindow) { + _this->MinimizeWindow(_this, window); + } } -SDL_GrabMode SDL_WM_GrabInput(SDL_GrabMode mode) + +void +SDL_RestoreWindow(SDL_WindowID windowID) { - SDL_VideoDevice *video = current_video; + SDL_Window *window = SDL_GetWindowFromID(windowID); - /* If the video isn't initialized yet, we can't do anything */ - if ( ! video ) { - return SDL_GRAB_OFF; - } + if (!window + || (window->flags & (SDL_WINDOW_MAXIMIZED | SDL_WINDOW_MINIMIZED))) { + return; + } - /* Return the current mode on query */ - if ( mode == SDL_GRAB_QUERY ) { - mode = video->input_grab; - if ( mode >= SDL_GRAB_FULLSCREEN ) { - mode -= SDL_GRAB_FULLSCREEN; - } - return(mode); - } + SDL_SendWindowEvent(window->id, SDL_WINDOWEVENT_RESTORED, 0, 0); -#ifdef DEBUG_GRAB - printf("SDL_WM_GrabInput(%d) ... ", mode); -#endif - /* If the video surface is fullscreen, we always grab */ - if ( mode >= SDL_GRAB_FULLSCREEN ) { - mode -= SDL_GRAB_FULLSCREEN; - } - if ( SDL_VideoSurface && (SDL_VideoSurface->flags & SDL_FULLSCREEN) ) { - mode += SDL_GRAB_FULLSCREEN; - } - return(SDL_WM_GrabInputRaw(mode)); + if (_this->RestoreWindow) { + _this->RestoreWindow(_this, window); + } +} + +int +SDL_SetWindowFullscreen(SDL_WindowID windowID, int fullscreen) +{ + SDL_Window *window = SDL_GetWindowFromID(windowID); + + if (!window) { + return -1; + } + + if (fullscreen) { + fullscreen = SDL_WINDOW_FULLSCREEN; + } + if ((window->flags & SDL_WINDOW_FULLSCREEN) == fullscreen) { + return 0; + } + + if (fullscreen) { + window->flags |= SDL_WINDOW_FULLSCREEN; + + if (FULLSCREEN_VISIBLE(window)) { + SDL_VideoDisplay *display = SDL_GetDisplayFromWindow(window); + + /* Hide any other fullscreen windows */ + int i; + for (i = 0; i < display->num_windows; ++i) { + SDL_Window *other = &display->windows[i]; + if (other->id != windowID && FULLSCREEN_VISIBLE(other)) { + SDL_MinimizeWindow(other->id); + } + } + + SDL_SetDisplayMode(display->fullscreen_mode); + } + } else { + window->flags &= ~SDL_WINDOW_FULLSCREEN; + + if (FULLSCREEN_VISIBLE(window)) { + SDL_SetDisplayMode(NULL); + } + } + return 0; } -static SDL_GrabMode SDL_WM_GrabInputOff(void) + +void +SDL_SetWindowGrab(SDL_WindowID windowID, int mode) { - SDL_GrabMode mode; + SDL_Window *window = SDL_GetWindowFromID(windowID); - /* First query the current grab state */ - mode = SDL_WM_GrabInput(SDL_GRAB_QUERY); + if (!window || (!!mode == !!(window->flags & SDL_WINDOW_INPUT_GRABBED))) { + return; + } - /* Now explicitly turn off input grab */ - SDL_WM_GrabInputRaw(SDL_GRAB_OFF); + if (mode) { + window->flags |= SDL_WINDOW_INPUT_GRABBED; + } else { + window->flags &= ~SDL_WINDOW_INPUT_GRABBED; + } - /* Return the old state */ - return(mode); + if ((window->flags & SDL_WINDOW_INPUT_FOCUS) && _this->SetWindowGrab) { + _this->SetWindowGrab(_this, window); + } } -/* - * Iconify the window in window managed environments. - * A successful iconification will result in an SDL_APPACTIVE loss event. - */ -int SDL_WM_IconifyWindow(void) +int +SDL_GetWindowGrab(SDL_WindowID windowID) { - SDL_VideoDevice *video = current_video; - SDL_VideoDevice *this = current_video; - int retval; + SDL_Window *window = SDL_GetWindowFromID(windowID); - retval = 0; - if ( video->IconifyWindow ) { - retval = video->IconifyWindow(this); - } - return(retval); + if (!window) { + return 0; + } + + return ((window->flags & SDL_WINDOW_INPUT_GRABBED) != 0); } -/* - * Toggle fullscreen mode - */ -int SDL_WM_ToggleFullScreen(SDL_Surface *surface) -{ - SDL_VideoDevice *video = current_video; - SDL_VideoDevice *this = current_video; - int toggled; - - toggled = 0; - if ( SDL_PublicSurface && (surface == SDL_PublicSurface) && - video->ToggleFullScreen ) { - if ( surface->flags & SDL_FULLSCREEN ) { - toggled = video->ToggleFullScreen(this, 0); - if ( toggled ) { - SDL_VideoSurface->flags &= ~SDL_FULLSCREEN; - SDL_PublicSurface->flags &= ~SDL_FULLSCREEN; - } - } else { - toggled = video->ToggleFullScreen(this, 1); - if ( toggled ) { - SDL_VideoSurface->flags |= SDL_FULLSCREEN; - SDL_PublicSurface->flags |= SDL_FULLSCREEN; - } - } - /* Double-check the grab state inside SDL_WM_GrabInput() */ - if ( toggled ) { - SDL_WM_GrabInput(video->input_grab); - } - } - return(toggled); +void +SDL_OnWindowShown(SDL_Window * window) +{ +} + +void +SDL_OnWindowHidden(SDL_Window * window) +{ +} + +void +SDL_OnWindowFocusGained(SDL_Window * window) +{ + SDL_VideoDisplay *display = SDL_GetDisplayFromWindow(window); + + if (window->flags & SDL_WINDOW_FULLSCREEN) { + SDL_SetDisplayMode(display->fullscreen_mode); + } + if (display->gamma && _this->SetDisplayGammaRamp) { + _this->SetDisplayGammaRamp(_this, display->gamma); + } + if ((window->flags & SDL_WINDOW_INPUT_GRABBED) && _this->SetWindowGrab) { + _this->SetWindowGrab(_this, window); + } +} + +void +SDL_OnWindowFocusLost(SDL_Window * window) +{ + SDL_VideoDisplay *display = SDL_GetDisplayFromWindow(window); + + if (window->flags & SDL_WINDOW_FULLSCREEN) { + SDL_MinimizeWindow(window->id); + SDL_SetDisplayMode(NULL); + } + if (display->gamma && _this->SetDisplayGammaRamp) { + _this->SetDisplayGammaRamp(_this, display->saved_gamma); + } + if ((window->flags & SDL_WINDOW_INPUT_GRABBED) && _this->SetWindowGrab) { + _this->SetWindowGrab(_this, window); + } +} + +SDL_WindowID +SDL_GetFocusWindow(void) +{ + SDL_VideoDisplay *display; + int i; + + if (!_this) { + return 0; + } + + display = &SDL_CurrentDisplay; + for (i = 0; i < display->num_windows; ++i) { + SDL_Window *window = &display->windows[i]; + + if (window->flags & SDL_WINDOW_INPUT_FOCUS) { + return window->id; + } + } + return 0; +} + +void +SDL_DestroyWindow(SDL_WindowID windowID) +{ + int i, j; + + if (!_this) { + return; + } + + /* Restore video mode, etc. */ + SDL_SendWindowEvent(windowID, SDL_WINDOWEVENT_FOCUS_LOST, 0, 0); + + for (i = 0; i < _this->num_displays; ++i) { + SDL_VideoDisplay *display = &_this->displays[i]; + for (j = 0; j < display->num_windows; ++j) { + SDL_Window *window = &display->windows[j]; + if (window->id != windowID) { + continue; + } + if (window->renderer) { + SDL_DestroyRenderer(window->id); + } + if (_this->DestroyWindow) { + _this->DestroyWindow(_this, window); + } + if (window->title) { + SDL_free(window->title); + } + if (j != display->num_windows - 1) { + SDL_memcpy(&display->windows[i], + &display->windows[i + 1], + (display->num_windows - i - 1) * sizeof(*window)); + } + --display->num_windows; + return; + } + } +} + +void +SDL_AddRenderDriver(int displayIndex, const SDL_RenderDriver * driver) +{ + SDL_VideoDisplay *display = &_this->displays[displayIndex]; + SDL_RenderDriver *render_drivers; + + render_drivers = + SDL_realloc(display->render_drivers, + (display->num_render_drivers + + 1) * sizeof(*render_drivers)); + if (render_drivers) { + render_drivers[display->num_render_drivers] = *driver; + display->render_drivers = render_drivers; + display->num_render_drivers++; + } +} + +int +SDL_GetNumRenderers(void) +{ + if (_this) { + return SDL_CurrentDisplay.num_render_drivers; + } + return 0; +} + +int +SDL_GetRendererInfo(int index, SDL_RendererInfo * info) +{ + if (index < 0 || index >= SDL_GetNumRenderers()) { + SDL_SetError("index must be in the range of 0 - %d", + SDL_GetNumRenderers() - 1); + return -1; + } + *info = SDL_CurrentDisplay.render_drivers[index].info; + return 0; +} + +int +SDL_CreateRenderer(SDL_WindowID windowID, int index, Uint32 flags) +{ + SDL_Window *window = SDL_GetWindowFromID(windowID); + + if (!window) { + return 0; + } + + if (index < 0) { + int n = SDL_GetNumRenderers(); + for (index = 0; index < n; ++index) { + SDL_RenderDriver *driver = + &SDL_CurrentDisplay.render_drivers[index]; + + /* Skip minimal drivers in automatic scans */ + if (!(flags & SDL_Renderer_Minimal) + && (driver->info.flags & SDL_Renderer_Minimal)) { + continue; + } + if ((driver->info.flags & flags) == flags) { + break; + } + } + if (index == n) { + SDL_SetError("Couldn't find matching render driver"); + return -1; + } + } + + if (index >= SDL_GetNumRenderers()) { + SDL_SetError("index must be -1 or in the range of 0 - %d", + SDL_GetNumRenderers() - 1); + return -1; + } + + /* Free any existing renderer */ + SDL_DestroyRenderer(windowID); + + /* Create a new renderer instance */ + window->renderer = + SDL_CurrentDisplay.render_drivers[index].CreateRenderer(window, + flags); + if (!window->renderer) { + return -1; + } + SDL_CurrentDisplay.current_renderer = window->renderer; + + return 0; +} + +int +SDL_SelectRenderer(SDL_WindowID windowID) +{ + SDL_Window *window = SDL_GetWindowFromID(windowID); + + if (!window || !window->renderer) { + return -1; + } + SDL_CurrentDisplay.current_renderer = window->renderer; + return 0; +} + +SDL_TextureID +SDL_CreateTexture(Uint32 format, int access, int w, int h) +{ + int hash; + SDL_Renderer *renderer; + SDL_Texture *texture; + + if (!_this) { + return 0; + } + + renderer = SDL_CurrentDisplay.current_renderer; + if (!renderer || !renderer->CreateTexture) { + return 0; + } + + texture = (SDL_Texture *) SDL_malloc(sizeof(*texture)); + if (!texture) { + SDL_OutOfMemory(); + return 0; + } + + SDL_zerop(texture); + texture->id = _this->next_object_id++; + texture->format = format; + texture->access = access; + texture->w = w; + texture->h = h; + texture->renderer = renderer; + + if (renderer->CreateTexture(renderer, texture) < 0) { + SDL_free(texture); + return 0; + } + + hash = (texture->id % SDL_arraysize(SDL_CurrentDisplay.textures)); + texture->next = SDL_CurrentDisplay.textures[hash]; + SDL_CurrentDisplay.textures[hash] = texture; + + return texture->id; +} + +SDL_TextureID +SDL_CreateTextureFromSurface(Uint32 format, int access, SDL_Surface * surface) +{ + SDL_TextureID textureID; + Uint32 surface_flags = surface->flags; + SDL_PixelFormat *fmt = surface->format; + Uint8 alpha; + SDL_Rect bounds; + SDL_Surface dst; + int bpp; + Uint32 Rmask, Gmask, Bmask, Amask; + + if (!surface) { + SDL_SetError("SDL_CreateTextureFromSurface() passed NULL surface"); + return 0; + } + + if (format) { + if (!SDL_PixelFormatEnumToMasks + (format, &bpp, &Rmask, &Gmask, &Bmask, &Amask)) { + SDL_SetError("Unknown pixel format"); + return 0; + } + } else { + if (fmt->Amask || !(surface_flags & (SDL_SRCCOLORKEY | SDL_SRCALPHA))) { + bpp = fmt->BitsPerPixel; + Rmask = fmt->Rmask; + Gmask = fmt->Gmask; + Bmask = fmt->Bmask; + Amask = fmt->Amask; + } else { + /* Need a format with alpha */ + bpp = 32; + Rmask = 0x00FF0000; + Gmask = 0x0000FF00; + Bmask = 0x000000FF; + Amask = 0xFF000000; + } + format = SDL_MasksToPixelFormatEnum(bpp, Rmask, Gmask, Bmask, Amask); + if (!format) { + SDL_SetError("Unknown pixel format"); + return 0; + } + } + + textureID = SDL_CreateTexture(format, access, surface->w, surface->h); + if (!textureID) { + return 0; + } + + /* Set up a destination surface for the texture update */ + SDL_zero(dst); + dst.format = SDL_AllocFormat(bpp, Rmask, Gmask, Bmask, Amask); + if (!dst.format) { + SDL_DestroyTexture(textureID); + return 0; + } + dst.w = surface->w; + dst.h = surface->h; + if (SDL_LockTexture(textureID, NULL, 1, &dst.pixels, &dst.pitch) == 0) { + dst.flags |= SDL_PREALLOC; + } else { + dst.pitch = SDL_CalculatePitch(&dst); + dst.pixels = SDL_malloc(dst.h * dst.pitch); + if (!dst.pixels) { + SDL_DestroyTexture(textureID); + SDL_FreeFormat(dst.format); + SDL_OutOfMemory(); + return 0; + } + } + + /* Copy the palette if any */ + if (SDL_ISPIXELFORMAT_INDEXED(format)) { + if (fmt->palette) { + SDL_SetTexturePalette(textureID, fmt->palette->colors, 0, + fmt->palette->ncolors); + SDL_SetSurfacePalette(&dst, fmt->palette); + } else { + dst.format->palette = + SDL_AllocPalette((1 << SDL_BITSPERPIXEL(format))); + if (!dst.format->palette) { + SDL_DestroyTexture(textureID); + SDL_FreeFormat(dst.format); + return 0; + } + SDL_DitherColors(dst.format->palette->colors, + SDL_BITSPERPIXEL(format)); + } + } + + /* Make the texture transparent if the surface has colorkey */ + if (surface_flags & SDL_SRCCOLORKEY) { + int row; + int length = dst.w * dst.format->BytesPerPixel; + Uint8 *p = (Uint8 *) dst.pixels; + for (row = 0; row < dst.h; ++row) { + SDL_memset(p, 0, length); + p += dst.pitch; + } + } + + /* Copy over the alpha channel */ + if (surface_flags & SDL_SRCALPHA) { + if (fmt->Amask) { + surface->flags &= ~SDL_SRCALPHA; + } else { + /* FIXME: Need to make sure the texture has an alpha channel + * and copy 'alpha' into the texture alpha channel. + */ + alpha = surface->format->alpha; + SDL_SetAlpha(surface, 0, 0); + } + } + + /* Copy over the image data */ + bounds.x = 0; + bounds.y = 0; + bounds.w = surface->w; + bounds.h = surface->h; + SDL_LowerBlit(surface, &bounds, &dst, &bounds); + + /* Clean up the original surface */ + if ((surface_flags & SDL_SRCALPHA) == SDL_SRCALPHA) { + Uint32 aflags = surface_flags & (SDL_SRCALPHA | SDL_RLEACCELOK); + if (fmt->Amask) { + surface->flags |= SDL_SRCALPHA; + } else { + SDL_SetAlpha(surface, aflags, alpha); + } + } + + /* Update the texture */ + if (dst.flags & SDL_PREALLOC) { + SDL_UnlockTexture(textureID); + } else { + SDL_UpdateTexture(textureID, NULL, dst.pixels, dst.pitch); + SDL_free(dst.pixels); + } + SDL_FreeFormat(dst.format); + + return textureID; +} + +static __inline__ SDL_Texture * +SDL_GetTextureFromID(SDL_TextureID textureID) +{ + int hash; + SDL_Texture *texture; + + if (!_this) { + return NULL; + } + + hash = (textureID % SDL_arraysize(SDL_CurrentDisplay.textures)); + for (texture = SDL_CurrentDisplay.textures[hash]; texture; + texture = texture->next) { + if (texture->id == textureID) { + return texture; + } + } + return NULL; +} + +int +SDL_QueryTexture(SDL_TextureID textureID, Uint32 * format, int *access, + int *w, int *h) +{ + SDL_Texture *texture = SDL_GetTextureFromID(textureID); + + if (!texture) { + return -1; + } + + if (format) { + *format = texture->format; + } + if (access) { + *access = texture->access; + } + if (w) { + *w = texture->w; + } + if (h) { + *h = texture->h; + } + return 0; +} + +int +SDL_QueryTexturePixels(SDL_TextureID textureID, void **pixels, int *pitch) +{ + SDL_Texture *texture = SDL_GetTextureFromID(textureID); + SDL_Renderer *renderer; + + if (!texture) { + return -1; + } + + renderer = texture->renderer; + if (!renderer->QueryTexturePixels) { + return -1; + } + return renderer->QueryTexturePixels(renderer, texture, pixels, pitch); +} + +int +SDL_SetTexturePalette(SDL_TextureID textureID, const SDL_Color * colors, + int firstcolor, int ncolors) +{ + SDL_Texture *texture = SDL_GetTextureFromID(textureID); + SDL_Renderer *renderer; + + if (!texture) { + return -1; + } + + renderer = texture->renderer; + if (!renderer->SetTexturePalette) { + return -1; + } + return renderer->SetTexturePalette(renderer, texture, colors, firstcolor, + ncolors); +} + +int +SDL_GetTexturePalette(SDL_TextureID textureID, SDL_Color * colors, + int firstcolor, int ncolors) +{ + SDL_Texture *texture = SDL_GetTextureFromID(textureID); + SDL_Renderer *renderer; + + if (!texture) { + return -1; + } + + renderer = texture->renderer; + if (!renderer->GetTexturePalette) { + return -1; + } + return renderer->GetTexturePalette(renderer, texture, colors, firstcolor, + ncolors); +} + +int +SDL_UpdateTexture(SDL_TextureID textureID, const SDL_Rect * rect, + const void *pixels, int pitch) +{ + SDL_Texture *texture = SDL_GetTextureFromID(textureID); + SDL_Renderer *renderer; + SDL_Rect full_rect; + + if (!texture) { + return -1; + } + + renderer = texture->renderer; + if (!renderer->UpdateTexture) { + return -1; + } + + if (!rect) { + full_rect.x = 0; + full_rect.y = 0; + full_rect.w = texture->w; + full_rect.h = texture->h; + rect = &full_rect; + } + + return renderer->UpdateTexture(renderer, texture, rect, pixels, pitch); +} + +int +SDL_LockTexture(SDL_TextureID textureID, const SDL_Rect * rect, int markDirty, + void **pixels, int *pitch) +{ + SDL_Texture *texture = SDL_GetTextureFromID(textureID); + SDL_Renderer *renderer; + SDL_Rect full_rect; + + if (!texture) { + return -1; + } + + renderer = texture->renderer; + if (!renderer->LockTexture) { + return -1; + } + + if (!rect) { + full_rect.x = 0; + full_rect.y = 0; + full_rect.w = texture->w; + full_rect.h = texture->h; + rect = &full_rect; + } + + return renderer->LockTexture(renderer, texture, rect, markDirty, pixels, + pitch); +} + +void +SDL_UnlockTexture(SDL_TextureID textureID) +{ + SDL_Texture *texture = SDL_GetTextureFromID(textureID); + SDL_Renderer *renderer; + + if (!texture) { + return; + } + + renderer = texture->renderer; + if (!renderer->UnlockTexture) { + return; + } + renderer->UnlockTexture(renderer, texture); +} + +void +SDL_DirtyTexture(SDL_TextureID textureID, int numrects, + const SDL_Rect * rects) +{ + SDL_Texture *texture = SDL_GetTextureFromID(textureID); + SDL_Renderer *renderer; + + if (!texture) { + return; + } + + renderer = texture->renderer; + if (!renderer->DirtyTexture) { + return; + } + renderer->DirtyTexture(renderer, texture, numrects, rects); +} + +void +SDL_SelectRenderTexture(SDL_TextureID textureID) +{ + SDL_Texture *texture = SDL_GetTextureFromID(textureID); + SDL_Renderer *renderer; + + if (!texture || texture->access != SDL_TextureAccess_Render) { + return; + } + renderer = texture->renderer; + if (!renderer->SelectRenderTexture) { + return; + } + renderer->SelectRenderTexture(renderer, texture); +} + +int +SDL_RenderFill(const SDL_Rect * rect, Uint32 color) +{ + SDL_Renderer *renderer; + SDL_Window *window; + SDL_Rect real_rect; + + if (!_this) { + return -1; + } + + renderer = SDL_CurrentDisplay.current_renderer; + if (!renderer || !renderer->RenderFill) { + return -1; + } + + window = SDL_GetWindowFromID(renderer->window); + real_rect.x = 0; + real_rect.y = 0; + real_rect.w = window->w; + real_rect.h = window->h; + if (rect) { + if (!SDL_IntersectRect(rect, &real_rect, &real_rect)) { + return 0; + } + } + rect = &real_rect; + + return renderer->RenderFill(renderer, rect, color); +} + +int +SDL_RenderCopy(SDL_TextureID textureID, const SDL_Rect * srcrect, + const SDL_Rect * dstrect, int blendMode, int scaleMode) +{ + SDL_Texture *texture = SDL_GetTextureFromID(textureID); + SDL_Renderer *renderer; + SDL_Window *window; + SDL_Rect real_srcrect; + SDL_Rect real_dstrect; + + if (!texture || texture->renderer != SDL_CurrentDisplay.current_renderer) { + return -1; + } + + renderer = SDL_CurrentDisplay.current_renderer; + if (!renderer || !renderer->RenderCopy) { + return -1; + } + + /* FIXME: implement clipping */ + window = SDL_GetWindowFromID(renderer->window); + real_srcrect.x = 0; + real_srcrect.y = 0; + real_srcrect.w = texture->w; + real_srcrect.h = texture->h; + real_dstrect.x = 0; + real_dstrect.y = 0; + real_dstrect.w = window->w; + real_dstrect.h = window->h; + if (!srcrect) { + srcrect = &real_srcrect; + } + if (!dstrect) { + dstrect = &real_dstrect; + } + + return renderer->RenderCopy(renderer, texture, srcrect, dstrect, + blendMode, scaleMode); +} + +int +SDL_RenderReadPixels(const SDL_Rect * rect, void *pixels, int pitch) +{ + SDL_Renderer *renderer; + SDL_Rect full_rect; + + if (!_this) { + return -1; + } + + renderer = SDL_CurrentDisplay.current_renderer; + if (!renderer || !renderer->RenderReadPixels) { + return -1; + } + + if (!rect) { + SDL_Window *window = SDL_GetWindowFromID(renderer->window); + full_rect.x = 0; + full_rect.y = 0; + full_rect.w = window->w; + full_rect.h = window->h; + rect = &full_rect; + } + + return renderer->RenderReadPixels(renderer, rect, pixels, pitch); +} + +int +SDL_RenderWritePixels(const SDL_Rect * rect, const void *pixels, int pitch) +{ + SDL_Renderer *renderer; + SDL_Rect full_rect; + + if (!_this) { + return -1; + } + + renderer = SDL_CurrentDisplay.current_renderer; + if (!renderer || !renderer->RenderWritePixels) { + return -1; + } + + if (!rect) { + SDL_Window *window = SDL_GetWindowFromID(renderer->window); + full_rect.x = 0; + full_rect.y = 0; + full_rect.w = window->w; + full_rect.h = window->h; + rect = &full_rect; + } + + return renderer->RenderWritePixels(renderer, rect, pixels, pitch); +} + +void +SDL_RenderPresent(void) +{ + SDL_Renderer *renderer; + + if (!_this) { + return; + } + + renderer = SDL_CurrentDisplay.current_renderer; + if (!renderer || !renderer->RenderPresent) { + return; + } + + renderer->RenderPresent(renderer); +} + +void +SDL_DestroyTexture(SDL_TextureID textureID) +{ + int hash; + SDL_Texture *prev, *texture; + SDL_Renderer *renderer; + + if (!_this) { + return; + } + + /* Look up the texture in the hash table */ + hash = (textureID % SDL_arraysize(SDL_CurrentDisplay.textures)); + prev = NULL; + for (texture = SDL_CurrentDisplay.textures[hash]; texture; + prev = texture, texture = texture->next) { + if (texture->id == textureID) { + break; + } + } + if (!texture) { + return; + } + + /* Unlink the texture from the list */ + if (prev) { + prev->next = texture->next; + } else { + SDL_CurrentDisplay.textures[hash] = texture->next; + } + + /* Free the texture */ + renderer = texture->renderer; + renderer->DestroyTexture(renderer, texture); + SDL_free(texture); +} + +void +SDL_DestroyRenderer(SDL_WindowID windowID) +{ + SDL_Window *window = SDL_GetWindowFromID(windowID); + SDL_Renderer *renderer; + int i; + + if (!window) { + return; + } + + renderer = window->renderer; + if (!renderer) { + return; + } + + /* Free existing textures for this renderer */ + for (i = 0; i < SDL_arraysize(SDL_CurrentDisplay.textures); ++i) { + SDL_Texture *texture; + SDL_Texture *prev = NULL; + SDL_Texture *next; + for (texture = SDL_CurrentDisplay.textures[i]; texture; + texture = next) { + next = texture->next; + if (texture->renderer == renderer) { + if (prev) { + prev->next = next; + } else { + SDL_CurrentDisplay.textures[i] = next; + } + renderer->DestroyTexture(renderer, texture); + SDL_free(texture); + } else { + prev = texture; + } + } + } + + /* Free the renderer instance */ + renderer->DestroyRenderer(renderer); + + /* Clear references */ + window->renderer = NULL; + if (SDL_CurrentDisplay.current_renderer == renderer) { + SDL_CurrentDisplay.current_renderer = NULL; + } +} + +void +SDL_VideoQuit(void) +{ + int i, j; + + if (!_this) { + return; + } + + /* Halt event processing before doing anything else */ + SDL_StopEventLoop(); + + /* Clean up the system video */ + for (i = _this->num_displays; i--;) { + SDL_VideoDisplay *display = &_this->displays[i]; + for (j = display->num_windows; j--;) { + SDL_DestroyWindow(display->windows[i].id); + } + if (display->windows) { + SDL_free(display->windows); + display->windows = NULL; + } + display->num_windows = 0; + } + _this->VideoQuit(_this); + + for (i = _this->num_displays; i--;) { + SDL_VideoDisplay *display = &_this->displays[i]; + for (j = display->num_display_modes; j--;) { + if (display->display_modes[j].driverdata) { + SDL_free(display->display_modes[j].driverdata); + display->display_modes[j].driverdata = NULL; + } + } + if (display->display_modes) { + SDL_free(display->display_modes); + display->display_modes = NULL; + } + if (display->desktop_mode.driverdata) { + SDL_free(display->desktop_mode.driverdata); + display->desktop_mode.driverdata = NULL; + } + if (display->palette) { + SDL_FreePalette(display->palette); + display->palette = NULL; + } + if (display->gamma) { + SDL_free(display->gamma); + } + if (display->driverdata) { + SDL_free(display->driverdata); + } + } + if (_this->displays) { + SDL_free(_this->displays); + _this->displays = NULL; + } + _this->free(_this); + _this = NULL; +} + +/* Load the GL driver library */ +int +SDL_GL_LoadLibrary(const char *path) +{ + int retval; + + retval = -1; + if (_this == NULL) { + SDL_SetError("Video subsystem has not been initialized"); + } else { + if (_this->GL_LoadLibrary) { + retval = _this->GL_LoadLibrary(_this, path); + } else { + SDL_SetError("No dynamic GL support in video driver"); + } + } + return (retval); +} + +void * +SDL_GL_GetProcAddress(const char *proc) +{ + void *func; + + func = NULL; + if (_this->GL_GetProcAddress) { + if (_this->gl_config.driver_loaded) { + func = _this->GL_GetProcAddress(_this, proc); + } else { + SDL_SetError("No GL driver has been loaded"); + } + } else { + SDL_SetError("No dynamic GL support in video driver"); + } + return func; +} + +/* Set the specified GL attribute for setting up a GL video mode */ +int +SDL_GL_SetAttribute(SDL_GLattr attr, int value) +{ + int retval; + + retval = 0; + switch (attr) { + case SDL_GL_RED_SIZE: + _this->gl_config.red_size = value; + break; + case SDL_GL_GREEN_SIZE: + _this->gl_config.green_size = value; + break; + case SDL_GL_BLUE_SIZE: + _this->gl_config.blue_size = value; + break; + case SDL_GL_ALPHA_SIZE: + _this->gl_config.alpha_size = value; + break; + case SDL_GL_DOUBLEBUFFER: + _this->gl_config.double_buffer = value; + break; + case SDL_GL_BUFFER_SIZE: + _this->gl_config.buffer_size = value; + break; + case SDL_GL_DEPTH_SIZE: + _this->gl_config.depth_size = value; + break; + case SDL_GL_STENCIL_SIZE: + _this->gl_config.stencil_size = value; + break; + case SDL_GL_ACCUM_RED_SIZE: + _this->gl_config.accum_red_size = value; + break; + case SDL_GL_ACCUM_GREEN_SIZE: + _this->gl_config.accum_green_size = value; + break; + case SDL_GL_ACCUM_BLUE_SIZE: + _this->gl_config.accum_blue_size = value; + break; + case SDL_GL_ACCUM_ALPHA_SIZE: + _this->gl_config.accum_alpha_size = value; + break; + case SDL_GL_STEREO: + _this->gl_config.stereo = value; + break; + case SDL_GL_MULTISAMPLEBUFFERS: + _this->gl_config.multisamplebuffers = value; + break; + case SDL_GL_MULTISAMPLESAMPLES: + _this->gl_config.multisamplesamples = value; + break; + case SDL_GL_ACCELERATED_VISUAL: + _this->gl_config.accelerated = value; + break; + default: + SDL_SetError("Unknown OpenGL attribute"); + retval = -1; + break; + } + return (retval); +} + +/* Retrieve an attribute value from the windowing system. */ +int +SDL_GL_GetAttribute(SDL_GLattr attr, int *value) +{ + int retval = -1; + + if (_this->GL_GetAttribute) { + retval = _this->GL_GetAttribute(_this, attr, value); + } else { + *value = 0; + SDL_SetError("GL_GetAttribute not supported"); + } + return retval; +} + +/* Perform a GL buffer swap on the current GL context */ +void +SDL_GL_SwapBuffers(void) +{ + // FIXME: Track the current window context - do we provide N contexts, and match them to M windows, or is there a one-to-one mapping? + _this->GL_SwapBuffers(_this); +} + +#if 0 // FIXME +/* Utility function used by SDL_WM_SetIcon(); + * flags & 1 for color key, flags & 2 for alpha channel. */ +static void +CreateMaskFromColorKeyOrAlpha(SDL_Surface * icon, Uint8 * mask, int flags) +{ + int x, y; + Uint32 colorkey; +#define SET_MASKBIT(icon, x, y, mask) \ + mask[(y*((icon->w+7)/8))+(x/8)] &= ~(0x01<<(7-(x%8))) + + colorkey = icon->format->colorkey; + switch (icon->format->BytesPerPixel) { + case 1: + { + Uint8 *pixels; + for (y = 0; y < icon->h; ++y) { + pixels = (Uint8 *) icon->pixels + y * icon->pitch; + for (x = 0; x < icon->w; ++x) { + if (*pixels++ == colorkey) { + SET_MASKBIT(icon, x, y, mask); + } + } + } + } + break; + + case 2: + { + Uint16 *pixels; + for (y = 0; y < icon->h; ++y) { + pixels = (Uint16 *) icon->pixels + y * icon->pitch / 2; + for (x = 0; x < icon->w; ++x) { + if ((flags & 1) && *pixels == colorkey) { + SET_MASKBIT(icon, x, y, mask); + } else if ((flags & 2) + && (*pixels & icon->format->Amask) == 0) { + SET_MASKBIT(icon, x, y, mask); + } + pixels++; + } + } + } + break; + + case 4: + { + Uint32 *pixels; + for (y = 0; y < icon->h; ++y) { + pixels = (Uint32 *) icon->pixels + y * icon->pitch / 4; + for (x = 0; x < icon->w; ++x) { + if ((flags & 1) && *pixels == colorkey) { + SET_MASKBIT(icon, x, y, mask); + } else if ((flags & 2) + && (*pixels & icon->format->Amask) == 0) { + SET_MASKBIT(icon, x, y, mask); + } + pixels++; + } + } + } + break; + } } /* - * Get some platform dependent window manager information + * Sets the window manager icon for the display window. */ -int SDL_GetWMInfo (SDL_SysWMinfo *info) +void +SDL_WM_SetIcon(SDL_Surface * icon, Uint8 * mask) +{ + if (icon && _this->SetIcon) { + /* Generate a mask if necessary, and create the icon! */ + if (mask == NULL) { + int mask_len = icon->h * (icon->w + 7) / 8; + int flags = 0; + mask = (Uint8 *) SDL_malloc(mask_len); + if (mask == NULL) { + return; + } + SDL_memset(mask, ~0, mask_len); + if (icon->flags & SDL_SRCCOLORKEY) + flags |= 1; + if (icon->flags & SDL_SRCALPHA) + flags |= 2; + if (flags) { + CreateMaskFromColorKeyOrAlpha(icon, mask, flags); + } + _this->SetIcon(_this, icon, mask); + SDL_free(mask); + } else { + _this->SetIcon(_this, icon, mask); + } + } +} +#endif + +SDL_bool +SDL_GetWindowWMInfo(SDL_WindowID windowID, struct SDL_SysWMinfo *info) { - SDL_VideoDevice *video = current_video; - SDL_VideoDevice *this = current_video; + SDL_Window *window = SDL_GetWindowFromID(windowID); - if ( video && video->GetWMInfo ) { - return(video->GetWMInfo(this, info)); - } else { - return(0); - } + if (!window || !_this->GetWindowWMInfo) { + return SDL_FALSE; + } + return (_this->GetWindowWMInfo(_this, window, info)); } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/SDL_yuv.c b/src/video/SDL_yuv.c deleted file mode 100644 index 396b7c0f5..000000000 --- a/src/video/SDL_yuv.c +++ /dev/null @@ -1,137 +0,0 @@ -/* - SDL - Simple DirectMedia Layer - Copyright (C) 1997-2006 Sam Lantinga - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - - Sam Lantinga - slouken@libsdl.org -*/ -#include "SDL_config.h" - -/* This is the implementation of the YUV video surface support */ - -#include "SDL_video.h" -#include "SDL_sysvideo.h" -#include "SDL_yuvfuncs.h" -#include "SDL_yuv_sw_c.h" - - -SDL_Overlay *SDL_CreateYUVOverlay(int w, int h, Uint32 format, - SDL_Surface *display) -{ - SDL_VideoDevice *video = current_video; - SDL_VideoDevice *this = current_video; - const char *yuv_hwaccel; - SDL_Overlay *overlay; - - if ( (display->flags & SDL_OPENGL) == SDL_OPENGL ) { - SDL_SetError("YUV overlays are not supported in OpenGL mode"); - return NULL; - } - - /* Display directly on video surface, if possible */ - if ( SDL_getenv("SDL_VIDEO_YUV_DIRECT") ) { - if ( (display == SDL_PublicSurface) && - ((SDL_VideoSurface->format->BytesPerPixel == 2) || - (SDL_VideoSurface->format->BytesPerPixel == 4)) ) { - display = SDL_VideoSurface; - } - } - overlay = NULL; - yuv_hwaccel = SDL_getenv("SDL_VIDEO_YUV_HWACCEL"); - if ( ((display == SDL_VideoSurface) && video->CreateYUVOverlay) && - (!yuv_hwaccel || (SDL_atoi(yuv_hwaccel) > 0)) ) { - overlay = video->CreateYUVOverlay(this, w, h, format, display); - } - /* If hardware YUV overlay failed ... */ - if ( overlay == NULL ) { - overlay = SDL_CreateYUV_SW(this, w, h, format, display); - } - return overlay; -} - -int SDL_LockYUVOverlay(SDL_Overlay *overlay) -{ - return overlay->hwfuncs->Lock(current_video, overlay); -} - -void SDL_UnlockYUVOverlay(SDL_Overlay *overlay) -{ - overlay->hwfuncs->Unlock(current_video, overlay); -} - -int SDL_DisplayYUVOverlay(SDL_Overlay *overlay, SDL_Rect *dstrect) -{ - SDL_Rect src, dst; - int srcx, srcy, srcw, srch; - int dstx, dsty, dstw, dsth; - - /* Clip the rectangle to the screen area */ - srcx = 0; - srcy = 0; - srcw = overlay->w; - srch = overlay->h; - dstx = dstrect->x; - dsty = dstrect->y; - dstw = dstrect->w; - dsth = dstrect->h; - if ( dstx < 0 ) { - srcw += (dstx * overlay->w) / dstrect->w; - dstw += dstx; - srcx -= (dstx * overlay->w) / dstrect->w; - dstx = 0; - } - if ( (dstx+dstw) > current_video->screen->w ) { - int extra = (dstx+dstw - current_video->screen->w); - srcw -= (extra * overlay->w) / dstrect->w; - dstw -= extra; - } - if ( dsty < 0 ) { - srch += (dsty * overlay->h) / dstrect->h; - dsth += dsty; - srcy -= (dsty * overlay->h) / dstrect->h; - dsty = 0; - } - if ( (dsty+dsth) > current_video->screen->h ) { - int extra = (dsty+dsth - current_video->screen->h); - srch -= (extra * overlay->h) / dstrect->h; - dsth -= extra; - } - if ( srcw <= 0 || srch <= 0 || - srch <= 0 || dsth <= 0 ) { - return 0; - } - /* Ugh, I can't wait for SDL_Rect to be int values */ - src.x = srcx; - src.y = srcy; - src.w = srcw; - src.h = srch; - dst.x = dstx; - dst.y = dsty; - dst.w = dstw; - dst.h = dsth; - return overlay->hwfuncs->Display(current_video, overlay, &src, &dst); -} - -void SDL_FreeYUVOverlay(SDL_Overlay *overlay) -{ - if ( overlay ) { - if ( overlay->hwfuncs ) { - overlay->hwfuncs->FreeHW(current_video, overlay); - } - SDL_free(overlay); - } -} diff --git a/src/video/SDL_yuv_mmx.c b/src/video/SDL_yuv_mmx.c index 4a9fb1d67..c06d7682c 100644 --- a/src/video/SDL_yuv_mmx.c +++ b/src/video/SDL_yuv_mmx.c @@ -21,36 +21,55 @@ */ #include "SDL_config.h" -#if 0 /* FIXME: This code needs to be rewritten to reference the static data using relocatable addresses (e.g. http://www.gentoo.org/proj/en/hardened/pic-fix-guide.xml or http://nasm.sourceforge.net/doc/html/nasmdoc8.html#section-8.2) This code currently breaks on systems with readonly text segments (hardened Linux / Intel Mac) */ +#if 0 /* FIXME: This code needs to be rewritten to reference the static data using relocatable addresses (e.g. http://www.gentoo.org/proj/en/hardened/pic-fix-guide.xml or http://nasm.sourceforge.net/doc/html/nasmdoc8.html#section-8.2) This code currently breaks on systems with readonly text segments (hardened Linux / Intel Mac) */ #if defined(__GNUC__) && defined(__i386__) && SDL_ASSEMBLY_ROUTINES #include "SDL_stdinc.h" #define ASM_ARRAY(x) x[] __asm__("_" #x) __attribute__((used)) - -static unsigned int ASM_ARRAY(MMX_0080w) = {0x00800080, 0x00800080}; -static unsigned int ASM_ARRAY(MMX_00FFw) = {0x00ff00ff, 0x00ff00ff}; -static unsigned int ASM_ARRAY(MMX_FF00w) = {0xff00ff00, 0xff00ff00}; -static unsigned short ASM_ARRAY(MMX_Ycoeff) = {0x004a, 0x004a, 0x004a, 0x004a}; - -static unsigned short ASM_ARRAY(MMX_UbluRGB) = {0x0072, 0x0072, 0x0072, 0x0072}; -static unsigned short ASM_ARRAY(MMX_VredRGB) = {0x0059, 0x0059, 0x0059, 0x0059}; -static unsigned short ASM_ARRAY(MMX_UgrnRGB) = {0xffea, 0xffea, 0xffea, 0xffea}; -static unsigned short ASM_ARRAY(MMX_VgrnRGB) = {0xffd2, 0xffd2, 0xffd2, 0xffd2}; - -static unsigned short ASM_ARRAY(MMX_Ublu5x5) = {0x0081, 0x0081, 0x0081, 0x0081}; -static unsigned short ASM_ARRAY(MMX_Vred5x5) = {0x0066, 0x0066, 0x0066, 0x0066}; -static unsigned short ASM_ARRAY(MMX_Ugrn555) = {0xffe7, 0xffe7, 0xffe7, 0xffe7}; -static unsigned short ASM_ARRAY(MMX_Vgrn555) = {0xffcc, 0xffcc, 0xffcc, 0xffcc}; -static unsigned short ASM_ARRAY(MMX_Ugrn565) = {0xffe8, 0xffe8, 0xffe8, 0xffe8}; -static unsigned short ASM_ARRAY(MMX_Vgrn565) = {0xffcd, 0xffcd, 0xffcd, 0xffcd}; - -static unsigned short ASM_ARRAY(MMX_red555) = {0x7c00, 0x7c00, 0x7c00, 0x7c00}; -static unsigned short ASM_ARRAY(MMX_red565) = {0xf800, 0xf800, 0xf800, 0xf800}; -static unsigned short ASM_ARRAY(MMX_grn555) = {0x03e0, 0x03e0, 0x03e0, 0x03e0}; -static unsigned short ASM_ARRAY(MMX_grn565) = {0x07e0, 0x07e0, 0x07e0, 0x07e0}; -static unsigned short ASM_ARRAY(MMX_blu5x5) = {0x001f, 0x001f, 0x001f, 0x001f}; +static unsigned int ASM_ARRAY(MMX_0080w) = { +0x00800080, 0x00800080}; +static unsigned int ASM_ARRAY(MMX_00FFw) = { +0x00ff00ff, 0x00ff00ff}; +static unsigned int ASM_ARRAY(MMX_FF00w) = { +0xff00ff00, 0xff00ff00}; + +static unsigned short ASM_ARRAY(MMX_Ycoeff) = { +0x004a, 0x004a, 0x004a, 0x004a}; + +static unsigned short ASM_ARRAY(MMX_UbluRGB) = { +0x0072, 0x0072, 0x0072, 0x0072}; +static unsigned short ASM_ARRAY(MMX_VredRGB) = { +0x0059, 0x0059, 0x0059, 0x0059}; +static unsigned short ASM_ARRAY(MMX_UgrnRGB) = { +0xffea, 0xffea, 0xffea, 0xffea}; +static unsigned short ASM_ARRAY(MMX_VgrnRGB) = { +0xffd2, 0xffd2, 0xffd2, 0xffd2}; + +static unsigned short ASM_ARRAY(MMX_Ublu5x5) = { +0x0081, 0x0081, 0x0081, 0x0081}; +static unsigned short ASM_ARRAY(MMX_Vred5x5) = { +0x0066, 0x0066, 0x0066, 0x0066}; +static unsigned short ASM_ARRAY(MMX_Ugrn555) = { +0xffe7, 0xffe7, 0xffe7, 0xffe7}; +static unsigned short ASM_ARRAY(MMX_Vgrn555) = { +0xffcc, 0xffcc, 0xffcc, 0xffcc}; +static unsigned short ASM_ARRAY(MMX_Ugrn565) = { +0xffe8, 0xffe8, 0xffe8, 0xffe8}; +static unsigned short ASM_ARRAY(MMX_Vgrn565) = { +0xffcd, 0xffcd, 0xffcd, 0xffcd}; + +static unsigned short ASM_ARRAY(MMX_red555) = { +0x7c00, 0x7c00, 0x7c00, 0x7c00}; +static unsigned short ASM_ARRAY(MMX_red565) = { +0xf800, 0xf800, 0xf800, 0xf800}; +static unsigned short ASM_ARRAY(MMX_grn555) = { +0x03e0, 0x03e0, 0x03e0, 0x03e0}; +static unsigned short ASM_ARRAY(MMX_grn565) = { +0x07e0, 0x07e0, 0x07e0, 0x07e0}; +static unsigned short ASM_ARRAY(MMX_blu5x5) = { +0x001f, 0x001f, 0x001f, 0x001f}; /** This MMX assembler is my first assembler/MMX program ever. @@ -81,330 +100,234 @@ static unsigned short ASM_ARRAY(MMX_blu5x5) = {0x001f, 0x001f, 0x001f, 0x001f}; */ -void ColorRGBDitherYV12MMX1X( int *colortab, Uint32 *rgb_2_pix, - unsigned char *lum, unsigned char *cr, - unsigned char *cb, unsigned char *out, - int rows, int cols, int mod ) +void +ColorRGBDitherYV12MMX1X(int *colortab, Uint32 * rgb_2_pix, + unsigned char *lum, unsigned char *cr, + unsigned char *cb, unsigned char *out, + int rows, int cols, int mod) { Uint32 *row1; Uint32 *row2; - unsigned char* y = lum +cols*rows; // Pointer to the end - int x=0; - row1 = (Uint32 *)out; // 32 bit target - row2 = (Uint32 *)out+cols+mod; // start of second row - mod = (mod+cols+mod)*4; // increment for row1 in byte + unsigned char *y = lum + cols * rows; // Pointer to the end + int x = 0; + row1 = (Uint32 *) out; // 32 bit target + row2 = (Uint32 *) out + cols + mod; // start of second row + mod = (mod + cols + mod) * 4; // increment for row1 in byte - __asm__ __volatile__ ( + __asm__ __volatile__( /* We don't really care about PIC - the code should be rewritten to use relative addressing for the static tables, so right now we take the COW hit on the pages this code resides. Big deal. This spill is just to reduce register pressure in the PIC case. */ - "pushl %%ebx\n" - "movl %0, %%ebx\n" - - ".align 8\n" - "1:\n" - - // create Cr (result in mm1) - "movd (%%ebx), %%mm1\n" // 0 0 0 0 v3 v2 v1 v0 - "pxor %%mm7,%%mm7\n" // 00 00 00 00 00 00 00 00 - "movd (%2), %%mm2\n" // 0 0 0 0 l3 l2 l1 l0 - "punpcklbw %%mm7,%%mm1\n" // 0 v3 0 v2 00 v1 00 v0 - "punpckldq %%mm1,%%mm1\n" // 00 v1 00 v0 00 v1 00 v0 - "psubw _MMX_0080w,%%mm1\n" // mm1-128:r1 r1 r0 r0 r1 r1 r0 r0 - - // create Cr_g (result in mm0) - "movq %%mm1,%%mm0\n" // r1 r1 r0 r0 r1 r1 r0 r0 - "pmullw _MMX_VgrnRGB,%%mm0\n"// red*-46dec=0.7136*64 - "pmullw _MMX_VredRGB,%%mm1\n"// red*89dec=1.4013*64 - "psraw $6, %%mm0\n" // red=red/64 - "psraw $6, %%mm1\n" // red=red/64 - - // create L1 L2 (result in mm2,mm4) - // L2=lum+cols - "movq (%2,%4),%%mm3\n" // 0 0 0 0 L3 L2 L1 L0 - "punpckldq %%mm3,%%mm2\n" // L3 L2 L1 L0 l3 l2 l1 l0 - "movq %%mm2,%%mm4\n" // L3 L2 L1 L0 l3 l2 l1 l0 - "pand _MMX_FF00w,%%mm2\n" // L3 0 L1 0 l3 0 l1 0 - "pand _MMX_00FFw,%%mm4\n" // 0 L2 0 L0 0 l2 0 l0 - "psrlw $8,%%mm2\n" // 0 L3 0 L1 0 l3 0 l1 - - // create R (result in mm6) - "movq %%mm2,%%mm5\n" // 0 L3 0 L1 0 l3 0 l1 - "movq %%mm4,%%mm6\n" // 0 L2 0 L0 0 l2 0 l0 - "paddsw %%mm1, %%mm5\n" // lum1+red:x R3 x R1 x r3 x r1 - "paddsw %%mm1, %%mm6\n" // lum1+red:x R2 x R0 x r2 x r0 - "packuswb %%mm5,%%mm5\n" // R3 R1 r3 r1 R3 R1 r3 r1 - "packuswb %%mm6,%%mm6\n" // R2 R0 r2 r0 R2 R0 r2 r0 - "pxor %%mm7,%%mm7\n" // 00 00 00 00 00 00 00 00 - "punpcklbw %%mm5,%%mm6\n" // R3 R2 R1 R0 r3 r2 r1 r0 - - // create Cb (result in mm1) - "movd (%1), %%mm1\n" // 0 0 0 0 u3 u2 u1 u0 - "punpcklbw %%mm7,%%mm1\n" // 0 u3 0 u2 00 u1 00 u0 - "punpckldq %%mm1,%%mm1\n" // 00 u1 00 u0 00 u1 00 u0 - "psubw _MMX_0080w,%%mm1\n" // mm1-128:u1 u1 u0 u0 u1 u1 u0 u0 - // create Cb_g (result in mm5) - "movq %%mm1,%%mm5\n" // u1 u1 u0 u0 u1 u1 u0 u0 - "pmullw _MMX_UgrnRGB,%%mm5\n" // blue*-109dec=1.7129*64 - "pmullw _MMX_UbluRGB,%%mm1\n" // blue*114dec=1.78125*64 - "psraw $6, %%mm5\n" // blue=red/64 - "psraw $6, %%mm1\n" // blue=blue/64 - - // create G (result in mm7) - "movq %%mm2,%%mm3\n" // 0 L3 0 L1 0 l3 0 l1 - "movq %%mm4,%%mm7\n" // 0 L2 0 L0 0 l2 0 l1 - "paddsw %%mm5, %%mm3\n" // lum1+Cb_g:x G3t x G1t x g3t x g1t - "paddsw %%mm5, %%mm7\n" // lum1+Cb_g:x G2t x G0t x g2t x g0t - "paddsw %%mm0, %%mm3\n" // lum1+Cr_g:x G3 x G1 x g3 x g1 - "paddsw %%mm0, %%mm7\n" // lum1+blue:x G2 x G0 x g2 x g0 - "packuswb %%mm3,%%mm3\n" // G3 G1 g3 g1 G3 G1 g3 g1 - "packuswb %%mm7,%%mm7\n" // G2 G0 g2 g0 G2 G0 g2 g0 - "punpcklbw %%mm3,%%mm7\n" // G3 G2 G1 G0 g3 g2 g1 g0 - - // create B (result in mm5) - "movq %%mm2,%%mm3\n" // 0 L3 0 L1 0 l3 0 l1 - "movq %%mm4,%%mm5\n" // 0 L2 0 L0 0 l2 0 l1 - "paddsw %%mm1, %%mm3\n" // lum1+blue:x B3 x B1 x b3 x b1 - "paddsw %%mm1, %%mm5\n" // lum1+blue:x B2 x B0 x b2 x b0 - "packuswb %%mm3,%%mm3\n" // B3 B1 b3 b1 B3 B1 b3 b1 - "packuswb %%mm5,%%mm5\n" // B2 B0 b2 b0 B2 B0 b2 b0 - "punpcklbw %%mm3,%%mm5\n" // B3 B2 B1 B0 b3 b2 b1 b0 - - // fill destination row1 (needed are mm6=Rr,mm7=Gg,mm5=Bb) - - "pxor %%mm2,%%mm2\n" // 0 0 0 0 0 0 0 0 - "pxor %%mm4,%%mm4\n" // 0 0 0 0 0 0 0 0 - "movq %%mm6,%%mm1\n" // R3 R2 R1 R0 r3 r2 r1 r0 - "movq %%mm5,%%mm3\n" // B3 B2 B1 B0 b3 b2 b1 b0 - // process lower lum - "punpcklbw %%mm4,%%mm1\n" // 0 r3 0 r2 0 r1 0 r0 - "punpcklbw %%mm4,%%mm3\n" // 0 b3 0 b2 0 b1 0 b0 - "movq %%mm1,%%mm2\n" // 0 r3 0 r2 0 r1 0 r0 - "movq %%mm3,%%mm0\n" // 0 b3 0 b2 0 b1 0 b0 - "punpcklwd %%mm1,%%mm3\n" // 0 r1 0 b1 0 r0 0 b0 - "punpckhwd %%mm2,%%mm0\n" // 0 r3 0 b3 0 r2 0 b2 - - "pxor %%mm2,%%mm2\n" // 0 0 0 0 0 0 0 0 - "movq %%mm7,%%mm1\n" // G3 G2 G1 G0 g3 g2 g1 g0 - "punpcklbw %%mm1,%%mm2\n" // g3 0 g2 0 g1 0 g0 0 - "punpcklwd %%mm4,%%mm2\n" // 0 0 g1 0 0 0 g0 0 - "por %%mm3, %%mm2\n" // 0 r1 g1 b1 0 r0 g0 b0 - "movq %%mm2,(%3)\n" // wrote out ! row1 - - "pxor %%mm2,%%mm2\n" // 0 0 0 0 0 0 0 0 - "punpcklbw %%mm1,%%mm4\n" // g3 0 g2 0 g1 0 g0 0 - "punpckhwd %%mm2,%%mm4\n" // 0 0 g3 0 0 0 g2 0 - "por %%mm0, %%mm4\n" // 0 r3 g3 b3 0 r2 g2 b2 - "movq %%mm4,8(%3)\n" // wrote out ! row1 - - // fill destination row2 (needed are mm6=Rr,mm7=Gg,mm5=Bb) - // this can be done "destructive" - "pxor %%mm2,%%mm2\n" // 0 0 0 0 0 0 0 0 - "punpckhbw %%mm2,%%mm6\n" // 0 R3 0 R2 0 R1 0 R0 - "punpckhbw %%mm1,%%mm5\n" // G3 B3 G2 B2 G1 B1 G0 B0 - "movq %%mm5,%%mm1\n" // G3 B3 G2 B2 G1 B1 G0 B0 - "punpcklwd %%mm6,%%mm1\n" // 0 R1 G1 B1 0 R0 G0 B0 - "movq %%mm1,(%5)\n" // wrote out ! row2 - "punpckhwd %%mm6,%%mm5\n" // 0 R3 G3 B3 0 R2 G2 B2 - "movq %%mm5,8(%5)\n" // wrote out ! row2 - - "addl $4,%2\n" // lum+4 - "leal 16(%3),%3\n" // row1+16 - "leal 16(%5),%5\n" // row2+16 - "addl $2, %%ebx\n" // cr+2 - "addl $2, %1\n" // cb+2 - - "addl $4,%6\n" // x+4 - "cmpl %4,%6\n" - - "jl 1b\n" - "addl %4, %2\n" // lum += cols - "addl %8, %3\n" // row1+= mod - "addl %8, %5\n" // row2+= mod - "movl $0, %6\n" // x=0 - "cmpl %7, %2\n" - "jl 1b\n" - "emms\n" - "popl %%ebx\n" - : - : "m" (cr), "r"(cb),"r"(lum), - "r"(row1),"r"(cols),"r"(row2),"m"(x),"m"(y),"m"(mod)); + "pushl %%ebx\n" + "movl %0, %%ebx\n" ".align 8\n" "1:\n" + // create Cr (result in mm1) + "movd (%%ebx), %%mm1\n" // 0 0 0 0 v3 v2 v1 v0 + "pxor %%mm7,%%mm7\n" // 00 00 00 00 00 00 00 00 + "movd (%2), %%mm2\n" // 0 0 0 0 l3 l2 l1 l0 + "punpcklbw %%mm7,%%mm1\n" // 0 v3 0 v2 00 v1 00 v0 + "punpckldq %%mm1,%%mm1\n" // 00 v1 00 v0 00 v1 00 v0 + "psubw _MMX_0080w,%%mm1\n" // mm1-128:r1 r1 r0 r0 r1 r1 r0 r0 + // create Cr_g (result in mm0) + "movq %%mm1,%%mm0\n" // r1 r1 r0 r0 r1 r1 r0 r0 + "pmullw _MMX_VgrnRGB,%%mm0\n" // red*-46dec=0.7136*64 + "pmullw _MMX_VredRGB,%%mm1\n" // red*89dec=1.4013*64 + "psraw $6, %%mm0\n" // red=red/64 + "psraw $6, %%mm1\n" // red=red/64 + // create L1 L2 (result in mm2,mm4) + // L2=lum+cols + "movq (%2,%4),%%mm3\n" // 0 0 0 0 L3 L2 L1 L0 + "punpckldq %%mm3,%%mm2\n" // L3 L2 L1 L0 l3 l2 l1 l0 + "movq %%mm2,%%mm4\n" // L3 L2 L1 L0 l3 l2 l1 l0 + "pand _MMX_FF00w,%%mm2\n" // L3 0 L1 0 l3 0 l1 0 + "pand _MMX_00FFw,%%mm4\n" // 0 L2 0 L0 0 l2 0 l0 + "psrlw $8,%%mm2\n" // 0 L3 0 L1 0 l3 0 l1 + // create R (result in mm6) + "movq %%mm2,%%mm5\n" // 0 L3 0 L1 0 l3 0 l1 + "movq %%mm4,%%mm6\n" // 0 L2 0 L0 0 l2 0 l0 + "paddsw %%mm1, %%mm5\n" // lum1+red:x R3 x R1 x r3 x r1 + "paddsw %%mm1, %%mm6\n" // lum1+red:x R2 x R0 x r2 x r0 + "packuswb %%mm5,%%mm5\n" // R3 R1 r3 r1 R3 R1 r3 r1 + "packuswb %%mm6,%%mm6\n" // R2 R0 r2 r0 R2 R0 r2 r0 + "pxor %%mm7,%%mm7\n" // 00 00 00 00 00 00 00 00 + "punpcklbw %%mm5,%%mm6\n" // R3 R2 R1 R0 r3 r2 r1 r0 + // create Cb (result in mm1) + "movd (%1), %%mm1\n" // 0 0 0 0 u3 u2 u1 u0 + "punpcklbw %%mm7,%%mm1\n" // 0 u3 0 u2 00 u1 00 u0 + "punpckldq %%mm1,%%mm1\n" // 00 u1 00 u0 00 u1 00 u0 + "psubw _MMX_0080w,%%mm1\n" // mm1-128:u1 u1 u0 u0 u1 u1 u0 u0 + // create Cb_g (result in mm5) + "movq %%mm1,%%mm5\n" // u1 u1 u0 u0 u1 u1 u0 u0 + "pmullw _MMX_UgrnRGB,%%mm5\n" // blue*-109dec=1.7129*64 + "pmullw _MMX_UbluRGB,%%mm1\n" // blue*114dec=1.78125*64 + "psraw $6, %%mm5\n" // blue=red/64 + "psraw $6, %%mm1\n" // blue=blue/64 + // create G (result in mm7) + "movq %%mm2,%%mm3\n" // 0 L3 0 L1 0 l3 0 l1 + "movq %%mm4,%%mm7\n" // 0 L2 0 L0 0 l2 0 l1 + "paddsw %%mm5, %%mm3\n" // lum1+Cb_g:x G3t x G1t x g3t x g1t + "paddsw %%mm5, %%mm7\n" // lum1+Cb_g:x G2t x G0t x g2t x g0t + "paddsw %%mm0, %%mm3\n" // lum1+Cr_g:x G3 x G1 x g3 x g1 + "paddsw %%mm0, %%mm7\n" // lum1+blue:x G2 x G0 x g2 x g0 + "packuswb %%mm3,%%mm3\n" // G3 G1 g3 g1 G3 G1 g3 g1 + "packuswb %%mm7,%%mm7\n" // G2 G0 g2 g0 G2 G0 g2 g0 + "punpcklbw %%mm3,%%mm7\n" // G3 G2 G1 G0 g3 g2 g1 g0 + // create B (result in mm5) + "movq %%mm2,%%mm3\n" // 0 L3 0 L1 0 l3 0 l1 + "movq %%mm4,%%mm5\n" // 0 L2 0 L0 0 l2 0 l1 + "paddsw %%mm1, %%mm3\n" // lum1+blue:x B3 x B1 x b3 x b1 + "paddsw %%mm1, %%mm5\n" // lum1+blue:x B2 x B0 x b2 x b0 + "packuswb %%mm3,%%mm3\n" // B3 B1 b3 b1 B3 B1 b3 b1 + "packuswb %%mm5,%%mm5\n" // B2 B0 b2 b0 B2 B0 b2 b0 + "punpcklbw %%mm3,%%mm5\n" // B3 B2 B1 B0 b3 b2 b1 b0 + // fill destination row1 (needed are mm6=Rr,mm7=Gg,mm5=Bb) + "pxor %%mm2,%%mm2\n" // 0 0 0 0 0 0 0 0 + "pxor %%mm4,%%mm4\n" // 0 0 0 0 0 0 0 0 + "movq %%mm6,%%mm1\n" // R3 R2 R1 R0 r3 r2 r1 r0 + "movq %%mm5,%%mm3\n" // B3 B2 B1 B0 b3 b2 b1 b0 + // process lower lum + "punpcklbw %%mm4,%%mm1\n" // 0 r3 0 r2 0 r1 0 r0 + "punpcklbw %%mm4,%%mm3\n" // 0 b3 0 b2 0 b1 0 b0 + "movq %%mm1,%%mm2\n" // 0 r3 0 r2 0 r1 0 r0 + "movq %%mm3,%%mm0\n" // 0 b3 0 b2 0 b1 0 b0 + "punpcklwd %%mm1,%%mm3\n" // 0 r1 0 b1 0 r0 0 b0 + "punpckhwd %%mm2,%%mm0\n" // 0 r3 0 b3 0 r2 0 b2 + "pxor %%mm2,%%mm2\n" // 0 0 0 0 0 0 0 0 + "movq %%mm7,%%mm1\n" // G3 G2 G1 G0 g3 g2 g1 g0 + "punpcklbw %%mm1,%%mm2\n" // g3 0 g2 0 g1 0 g0 0 + "punpcklwd %%mm4,%%mm2\n" // 0 0 g1 0 0 0 g0 0 + "por %%mm3, %%mm2\n" // 0 r1 g1 b1 0 r0 g0 b0 + "movq %%mm2,(%3)\n" // wrote out ! row1 + "pxor %%mm2,%%mm2\n" // 0 0 0 0 0 0 0 0 + "punpcklbw %%mm1,%%mm4\n" // g3 0 g2 0 g1 0 g0 0 + "punpckhwd %%mm2,%%mm4\n" // 0 0 g3 0 0 0 g2 0 + "por %%mm0, %%mm4\n" // 0 r3 g3 b3 0 r2 g2 b2 + "movq %%mm4,8(%3)\n" // wrote out ! row1 + // fill destination row2 (needed are mm6=Rr,mm7=Gg,mm5=Bb) + // this can be done "destructive" + "pxor %%mm2,%%mm2\n" // 0 0 0 0 0 0 0 0 + "punpckhbw %%mm2,%%mm6\n" // 0 R3 0 R2 0 R1 0 R0 + "punpckhbw %%mm1,%%mm5\n" // G3 B3 G2 B2 G1 B1 G0 B0 + "movq %%mm5,%%mm1\n" // G3 B3 G2 B2 G1 B1 G0 B0 + "punpcklwd %%mm6,%%mm1\n" // 0 R1 G1 B1 0 R0 G0 B0 + "movq %%mm1,(%5)\n" // wrote out ! row2 + "punpckhwd %%mm6,%%mm5\n" // 0 R3 G3 B3 0 R2 G2 B2 + "movq %%mm5,8(%5)\n" // wrote out ! row2 + "addl $4,%2\n" // lum+4 + "leal 16(%3),%3\n" // row1+16 + "leal 16(%5),%5\n" // row2+16 + "addl $2, %%ebx\n" // cr+2 + "addl $2, %1\n" // cb+2 + "addl $4,%6\n" // x+4 + "cmpl %4,%6\n" "jl 1b\n" "addl %4, %2\n" // lum += cols + "addl %8, %3\n" // row1+= mod + "addl %8, %5\n" // row2+= mod + "movl $0, %6\n" // x=0 + "cmpl %7, %2\n" + "jl 1b\n" + "emms\n" + "popl %%ebx\n"::"m"(cr), "r"(cb), "r"(lum), + "r"(row1), "r"(cols), "r"(row2), "m"(x), + "m"(y), "m"(mod)); } -void Color565DitherYV12MMX1X( int *colortab, Uint32 *rgb_2_pix, - unsigned char *lum, unsigned char *cr, - unsigned char *cb, unsigned char *out, - int rows, int cols, int mod ) +void +Color565DitherYV12MMX1X(int *colortab, Uint32 * rgb_2_pix, + unsigned char *lum, unsigned char *cr, + unsigned char *cb, unsigned char *out, + int rows, int cols, int mod) { Uint16 *row1; Uint16 *row2; - unsigned char* y = lum +cols*rows; /* Pointer to the end */ - int x=0; - row1 = (Uint16 *)out; /* 16 bit target */ - row2 = (Uint16 *)out+cols+mod; /* start of second row */ - mod = (mod+cols+mod)*2; /* increment for row1 in byte */ - - - __asm__ __volatile__( - "pushl %%ebx\n" - "movl %0, %%ebx\n" - - ".align 8\n" - "1:\n" - "movd (%1), %%mm0\n" // 4 Cb 0 0 0 0 u3 u2 u1 u0 - "pxor %%mm7, %%mm7\n" - "movd (%%ebx), %%mm1\n" // 4 Cr 0 0 0 0 v3 v2 v1 v0 - "punpcklbw %%mm7, %%mm0\n" // 4 W cb 0 u3 0 u2 0 u1 0 u0 - "punpcklbw %%mm7, %%mm1\n" // 4 W cr 0 v3 0 v2 0 v1 0 v0 - "psubw _MMX_0080w, %%mm0\n" - "psubw _MMX_0080w, %%mm1\n" - "movq %%mm0, %%mm2\n" // Cb 0 u3 0 u2 0 u1 0 u0 - "movq %%mm1, %%mm3\n" // Cr - "pmullw _MMX_Ugrn565, %%mm2\n" // Cb2green 0 R3 0 R2 0 R1 0 R0 - "movq (%2), %%mm6\n" // L1 l7 L6 L5 L4 L3 L2 L1 L0 - "pmullw _MMX_Ublu5x5, %%mm0\n" // Cb2blue - "pand _MMX_00FFw, %%mm6\n" // L1 00 L6 00 L4 00 L2 00 L0 - "pmullw _MMX_Vgrn565, %%mm3\n" // Cr2green - "movq (%2), %%mm7\n" // L2 - "pmullw _MMX_Vred5x5, %%mm1\n" // Cr2red - "psrlw $8, %%mm7\n" // L2 00 L7 00 L5 00 L3 00 L1 - "pmullw _MMX_Ycoeff, %%mm6\n" // lum1 - "paddw %%mm3, %%mm2\n" // Cb2green + Cr2green == green - "pmullw _MMX_Ycoeff, %%mm7\n" // lum2 - - "movq %%mm6, %%mm4\n" // lum1 - "paddw %%mm0, %%mm6\n" // lum1 +blue 00 B6 00 B4 00 B2 00 B0 - "movq %%mm4, %%mm5\n" // lum1 - "paddw %%mm1, %%mm4\n" // lum1 +red 00 R6 00 R4 00 R2 00 R0 - "paddw %%mm2, %%mm5\n" // lum1 +green 00 G6 00 G4 00 G2 00 G0 - "psraw $6, %%mm4\n" // R1 0 .. 64 - "movq %%mm7, %%mm3\n" // lum2 00 L7 00 L5 00 L3 00 L1 - "psraw $6, %%mm5\n" // G1 - .. + - "paddw %%mm0, %%mm7\n" // Lum2 +blue 00 B7 00 B5 00 B3 00 B1 - "psraw $6, %%mm6\n" // B1 0 .. 64 - "packuswb %%mm4, %%mm4\n" // R1 R1 - "packuswb %%mm5, %%mm5\n" // G1 G1 - "packuswb %%mm6, %%mm6\n" // B1 B1 - "punpcklbw %%mm4, %%mm4\n" - "punpcklbw %%mm5, %%mm5\n" - - "pand _MMX_red565, %%mm4\n" - "psllw $3, %%mm5\n" // GREEN 1 - "punpcklbw %%mm6, %%mm6\n" - "pand _MMX_grn565, %%mm5\n" - "pand _MMX_red565, %%mm6\n" - "por %%mm5, %%mm4\n" // - "psrlw $11, %%mm6\n" // BLUE 1 - "movq %%mm3, %%mm5\n" // lum2 - "paddw %%mm1, %%mm3\n" // lum2 +red 00 R7 00 R5 00 R3 00 R1 - "paddw %%mm2, %%mm5\n" // lum2 +green 00 G7 00 G5 00 G3 00 G1 - "psraw $6, %%mm3\n" // R2 - "por %%mm6, %%mm4\n" // MM4 - "psraw $6, %%mm5\n" // G2 - "movq (%2, %4), %%mm6\n" // L3 load lum2 - "psraw $6, %%mm7\n" - "packuswb %%mm3, %%mm3\n" - "packuswb %%mm5, %%mm5\n" - "packuswb %%mm7, %%mm7\n" - "pand _MMX_00FFw, %%mm6\n" // L3 - "punpcklbw %%mm3, %%mm3\n" - "punpcklbw %%mm5, %%mm5\n" - "pmullw _MMX_Ycoeff, %%mm6\n" // lum3 - "punpcklbw %%mm7, %%mm7\n" - "psllw $3, %%mm5\n" // GREEN 2 - "pand _MMX_red565, %%mm7\n" - "pand _MMX_red565, %%mm3\n" - "psrlw $11, %%mm7\n" // BLUE 2 - "pand _MMX_grn565, %%mm5\n" - "por %%mm7, %%mm3\n" - "movq (%2,%4), %%mm7\n" // L4 load lum2 - "por %%mm5, %%mm3\n" // - "psrlw $8, %%mm7\n" // L4 - "movq %%mm4, %%mm5\n" - "punpcklwd %%mm3, %%mm4\n" - "pmullw _MMX_Ycoeff, %%mm7\n" // lum4 - "punpckhwd %%mm3, %%mm5\n" - - "movq %%mm4, (%3)\n" // write row1 - "movq %%mm5, 8(%3)\n" // write row1 - - "movq %%mm6, %%mm4\n" // Lum3 - "paddw %%mm0, %%mm6\n" // Lum3 +blue - - "movq %%mm4, %%mm5\n" // Lum3 - "paddw %%mm1, %%mm4\n" // Lum3 +red - "paddw %%mm2, %%mm5\n" // Lum3 +green - "psraw $6, %%mm4\n" - "movq %%mm7, %%mm3\n" // Lum4 - "psraw $6, %%mm5\n" - "paddw %%mm0, %%mm7\n" // Lum4 +blue - "psraw $6, %%mm6\n" // Lum3 +blue - "movq %%mm3, %%mm0\n" // Lum4 - "packuswb %%mm4, %%mm4\n" - "paddw %%mm1, %%mm3\n" // Lum4 +red - "packuswb %%mm5, %%mm5\n" - "paddw %%mm2, %%mm0\n" // Lum4 +green - "packuswb %%mm6, %%mm6\n" - "punpcklbw %%mm4, %%mm4\n" - "punpcklbw %%mm5, %%mm5\n" - "punpcklbw %%mm6, %%mm6\n" - "psllw $3, %%mm5\n" // GREEN 3 - "pand _MMX_red565, %%mm4\n" - "psraw $6, %%mm3\n" // psr 6 - "psraw $6, %%mm0\n" - "pand _MMX_red565, %%mm6\n" // BLUE - "pand _MMX_grn565, %%mm5\n" - "psrlw $11, %%mm6\n" // BLUE 3 - "por %%mm5, %%mm4\n" - "psraw $6, %%mm7\n" - "por %%mm6, %%mm4\n" - "packuswb %%mm3, %%mm3\n" - "packuswb %%mm0, %%mm0\n" - "packuswb %%mm7, %%mm7\n" - "punpcklbw %%mm3, %%mm3\n" - "punpcklbw %%mm0, %%mm0\n" - "punpcklbw %%mm7, %%mm7\n" - "pand _MMX_red565, %%mm3\n" - "pand _MMX_red565, %%mm7\n" // BLUE - "psllw $3, %%mm0\n" // GREEN 4 - "psrlw $11, %%mm7\n" - "pand _MMX_grn565, %%mm0\n" - "por %%mm7, %%mm3\n" - "por %%mm0, %%mm3\n" - - "movq %%mm4, %%mm5\n" - - "punpcklwd %%mm3, %%mm4\n" - "punpckhwd %%mm3, %%mm5\n" - - "movq %%mm4, (%5)\n" - "movq %%mm5, 8(%5)\n" - - "addl $8, %6\n" - "addl $8, %2\n" - "addl $4, %%ebx\n" - "addl $4, %1\n" - "cmpl %4, %6\n" - "leal 16(%3), %3\n" - "leal 16(%5),%5\n" // row2+16 - - - "jl 1b\n" - "addl %4, %2\n" // lum += cols - "addl %8, %3\n" // row1+= mod - "addl %8, %5\n" // row2+= mod - "movl $0, %6\n" // x=0 - "cmpl %7, %2\n" - "jl 1b\n" - "emms\n" - "popl %%ebx\n" - : - :"m" (cr), "r"(cb),"r"(lum), - "r"(row1),"r"(cols),"r"(row2),"m"(x),"m"(y),"m"(mod)); + unsigned char *y = lum + cols * rows; /* Pointer to the end */ + int x = 0; + row1 = (Uint16 *) out; /* 16 bit target */ + row2 = (Uint16 *) out + cols + mod; /* start of second row */ + mod = (mod + cols + mod) * 2; /* increment for row1 in byte */ + + + __asm__ __volatile__("pushl %%ebx\n" "movl %0, %%ebx\n" ".align 8\n" "1:\n" "movd (%1), %%mm0\n" // 4 Cb 0 0 0 0 u3 u2 u1 u0 + "pxor %%mm7, %%mm7\n" "movd (%%ebx), %%mm1\n" // 4 Cr 0 0 0 0 v3 v2 v1 v0 + "punpcklbw %%mm7, %%mm0\n" // 4 W cb 0 u3 0 u2 0 u1 0 u0 + "punpcklbw %%mm7, %%mm1\n" // 4 W cr 0 v3 0 v2 0 v1 0 v0 + "psubw _MMX_0080w, %%mm0\n" "psubw _MMX_0080w, %%mm1\n" "movq %%mm0, %%mm2\n" // Cb 0 u3 0 u2 0 u1 0 u0 + "movq %%mm1, %%mm3\n" // Cr + "pmullw _MMX_Ugrn565, %%mm2\n" // Cb2green 0 R3 0 R2 0 R1 0 R0 + "movq (%2), %%mm6\n" // L1 l7 L6 L5 L4 L3 L2 L1 L0 + "pmullw _MMX_Ublu5x5, %%mm0\n" // Cb2blue + "pand _MMX_00FFw, %%mm6\n" // L1 00 L6 00 L4 00 L2 00 L0 + "pmullw _MMX_Vgrn565, %%mm3\n" // Cr2green + "movq (%2), %%mm7\n" // L2 + "pmullw _MMX_Vred5x5, %%mm1\n" // Cr2red + "psrlw $8, %%mm7\n" // L2 00 L7 00 L5 00 L3 00 L1 + "pmullw _MMX_Ycoeff, %%mm6\n" // lum1 + "paddw %%mm3, %%mm2\n" // Cb2green + Cr2green == green + "pmullw _MMX_Ycoeff, %%mm7\n" // lum2 + "movq %%mm6, %%mm4\n" // lum1 + "paddw %%mm0, %%mm6\n" // lum1 +blue 00 B6 00 B4 00 B2 00 B0 + "movq %%mm4, %%mm5\n" // lum1 + "paddw %%mm1, %%mm4\n" // lum1 +red 00 R6 00 R4 00 R2 00 R0 + "paddw %%mm2, %%mm5\n" // lum1 +green 00 G6 00 G4 00 G2 00 G0 + "psraw $6, %%mm4\n" // R1 0 .. 64 + "movq %%mm7, %%mm3\n" // lum2 00 L7 00 L5 00 L3 00 L1 + "psraw $6, %%mm5\n" // G1 - .. + + "paddw %%mm0, %%mm7\n" // Lum2 +blue 00 B7 00 B5 00 B3 00 B1 + "psraw $6, %%mm6\n" // B1 0 .. 64 + "packuswb %%mm4, %%mm4\n" // R1 R1 + "packuswb %%mm5, %%mm5\n" // G1 G1 + "packuswb %%mm6, %%mm6\n" // B1 B1 + "punpcklbw %%mm4, %%mm4\n" "punpcklbw %%mm5, %%mm5\n" "pand _MMX_red565, %%mm4\n" "psllw $3, %%mm5\n" // GREEN 1 + "punpcklbw %%mm6, %%mm6\n" "pand _MMX_grn565, %%mm5\n" "pand _MMX_red565, %%mm6\n" "por %%mm5, %%mm4\n" // + "psrlw $11, %%mm6\n" // BLUE 1 + "movq %%mm3, %%mm5\n" // lum2 + "paddw %%mm1, %%mm3\n" // lum2 +red 00 R7 00 R5 00 R3 00 R1 + "paddw %%mm2, %%mm5\n" // lum2 +green 00 G7 00 G5 00 G3 00 G1 + "psraw $6, %%mm3\n" // R2 + "por %%mm6, %%mm4\n" // MM4 + "psraw $6, %%mm5\n" // G2 + "movq (%2, %4), %%mm6\n" // L3 load lum2 + "psraw $6, %%mm7\n" "packuswb %%mm3, %%mm3\n" "packuswb %%mm5, %%mm5\n" "packuswb %%mm7, %%mm7\n" "pand _MMX_00FFw, %%mm6\n" // L3 + "punpcklbw %%mm3, %%mm3\n" "punpcklbw %%mm5, %%mm5\n" "pmullw _MMX_Ycoeff, %%mm6\n" // lum3 + "punpcklbw %%mm7, %%mm7\n" "psllw $3, %%mm5\n" // GREEN 2 + "pand _MMX_red565, %%mm7\n" "pand _MMX_red565, %%mm3\n" "psrlw $11, %%mm7\n" // BLUE 2 + "pand _MMX_grn565, %%mm5\n" "por %%mm7, %%mm3\n" "movq (%2,%4), %%mm7\n" // L4 load lum2 + "por %%mm5, %%mm3\n" // + "psrlw $8, %%mm7\n" // L4 + "movq %%mm4, %%mm5\n" "punpcklwd %%mm3, %%mm4\n" "pmullw _MMX_Ycoeff, %%mm7\n" // lum4 + "punpckhwd %%mm3, %%mm5\n" "movq %%mm4, (%3)\n" // write row1 + "movq %%mm5, 8(%3)\n" // write row1 + "movq %%mm6, %%mm4\n" // Lum3 + "paddw %%mm0, %%mm6\n" // Lum3 +blue + "movq %%mm4, %%mm5\n" // Lum3 + "paddw %%mm1, %%mm4\n" // Lum3 +red + "paddw %%mm2, %%mm5\n" // Lum3 +green + "psraw $6, %%mm4\n" "movq %%mm7, %%mm3\n" // Lum4 + "psraw $6, %%mm5\n" "paddw %%mm0, %%mm7\n" // Lum4 +blue + "psraw $6, %%mm6\n" // Lum3 +blue + "movq %%mm3, %%mm0\n" // Lum4 + "packuswb %%mm4, %%mm4\n" "paddw %%mm1, %%mm3\n" // Lum4 +red + "packuswb %%mm5, %%mm5\n" "paddw %%mm2, %%mm0\n" // Lum4 +green + "packuswb %%mm6, %%mm6\n" "punpcklbw %%mm4, %%mm4\n" "punpcklbw %%mm5, %%mm5\n" "punpcklbw %%mm6, %%mm6\n" "psllw $3, %%mm5\n" // GREEN 3 + "pand _MMX_red565, %%mm4\n" "psraw $6, %%mm3\n" // psr 6 + "psraw $6, %%mm0\n" "pand _MMX_red565, %%mm6\n" // BLUE + "pand _MMX_grn565, %%mm5\n" "psrlw $11, %%mm6\n" // BLUE 3 + "por %%mm5, %%mm4\n" "psraw $6, %%mm7\n" "por %%mm6, %%mm4\n" "packuswb %%mm3, %%mm3\n" "packuswb %%mm0, %%mm0\n" "packuswb %%mm7, %%mm7\n" "punpcklbw %%mm3, %%mm3\n" "punpcklbw %%mm0, %%mm0\n" "punpcklbw %%mm7, %%mm7\n" "pand _MMX_red565, %%mm3\n" "pand _MMX_red565, %%mm7\n" // BLUE + "psllw $3, %%mm0\n" // GREEN 4 + "psrlw $11, %%mm7\n" "pand _MMX_grn565, %%mm0\n" "por %%mm7, %%mm3\n" "por %%mm0, %%mm3\n" "movq %%mm4, %%mm5\n" "punpcklwd %%mm3, %%mm4\n" "punpckhwd %%mm3, %%mm5\n" "movq %%mm4, (%5)\n" "movq %%mm5, 8(%5)\n" "addl $8, %6\n" "addl $8, %2\n" "addl $4, %%ebx\n" "addl $4, %1\n" "cmpl %4, %6\n" "leal 16(%3), %3\n" "leal 16(%5),%5\n" // row2+16 + "jl 1b\n" "addl %4, %2\n" // lum += cols + "addl %8, %3\n" // row1+= mod + "addl %8, %5\n" // row2+= mod + "movl $0, %6\n" // x=0 + "cmpl %7, %2\n" + "jl 1b\n" + "emms\n" + "popl %%ebx\n"::"m"(cr), "r"(cb), "r"(lum), + "r"(row1), "r"(cols), "r"(row2), "m"(x), + "m"(y), "m"(mod)); } #endif /* GCC i386 inline assembly */ #endif /* 0 */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/SDL_yuv_sw.c b/src/video/SDL_yuv_sw.c index c67d59296..8bf43e0ec 100644 --- a/src/video/SDL_yuv_sw.c +++ b/src/video/SDL_yuv_sw.c @@ -21,7 +21,7 @@ */ #include "SDL_config.h" -/* This is the software implementation of the YUV video overlay support */ +/* This is the software implementation of the YUV texture support */ /* This code was derived from code carrying the following copyright notices: @@ -86,108 +86,104 @@ #include "SDL_video.h" #include "SDL_cpuinfo.h" #include "SDL_stretch_c.h" -#include "SDL_yuvfuncs.h" #include "SDL_yuv_sw_c.h" -/* The functions used to manipulate software video overlays */ -static struct private_yuvhwfuncs sw_yuvfuncs = { - SDL_LockYUV_SW, - SDL_UnlockYUV_SW, - SDL_DisplayYUV_SW, - SDL_FreeYUV_SW -}; -/* RGB conversion lookup tables */ -struct private_yuvhwdata { - SDL_Surface *stretch; - SDL_Surface *display; - Uint8 *pixels; - int *colortab; - Uint32 *rgb_2_pix; - void (*Display1X)(int *colortab, Uint32 *rgb_2_pix, - unsigned char *lum, unsigned char *cr, - unsigned char *cb, unsigned char *out, - int rows, int cols, int mod ); - void (*Display2X)(int *colortab, Uint32 *rgb_2_pix, - unsigned char *lum, unsigned char *cr, - unsigned char *cb, unsigned char *out, - int rows, int cols, int mod ); - - /* These are just so we don't have to allocate them separately */ - Uint16 pitches[3]; - Uint8 *planes[3]; +struct SDL_SW_YUVTexture +{ + SDL_Texture *texture; + + Uint32 target_format; + Uint8 *pixels; + int *colortab; + Uint32 *rgb_2_pix; + void (*Display1X) (int *colortab, Uint32 * rgb_2_pix, + unsigned char *lum, unsigned char *cr, + unsigned char *cb, unsigned char *out, + int rows, int cols, int mod); + void (*Display2X) (int *colortab, Uint32 * rgb_2_pix, + unsigned char *lum, unsigned char *cr, + unsigned char *cb, unsigned char *out, + int rows, int cols, int mod); + + /* These are just so we don't have to allocate them separately */ + Uint16 pitches[3]; + Uint8 *planes[3]; + + /* This is a temporary surface in case we have to stretch copy */ + SDL_Surface *stretch; + SDL_Surface *display; }; - /* The colorspace conversion functions */ -#if 0 /*defined(__GNUC__) && defined(__i386__) && SDL_ASSEMBLY_ROUTINES*/ -extern void Color565DitherYV12MMX1X( int *colortab, Uint32 *rgb_2_pix, - unsigned char *lum, unsigned char *cr, - unsigned char *cb, unsigned char *out, - int rows, int cols, int mod ); -extern void ColorRGBDitherYV12MMX1X( int *colortab, Uint32 *rgb_2_pix, - unsigned char *lum, unsigned char *cr, - unsigned char *cb, unsigned char *out, - int rows, int cols, int mod ); -#endif - -static void Color16DitherYV12Mod1X( int *colortab, Uint32 *rgb_2_pix, +#if 0 /*defined(__GNUC__) && defined(__i386__) && SDL_ASSEMBLY_ROUTINES */ +extern void Color565DitherYV12MMX1X(int *colortab, Uint32 * rgb_2_pix, unsigned char *lum, unsigned char *cr, unsigned char *cb, unsigned char *out, - int rows, int cols, int mod ) + int rows, int cols, int mod); +extern void ColorRGBDitherYV12MMX1X(int *colortab, Uint32 * rgb_2_pix, + unsigned char *lum, unsigned char *cr, + unsigned char *cb, unsigned char *out, + int rows, int cols, int mod); +#endif + +static void +Color16DitherYV12Mod1X(int *colortab, Uint32 * rgb_2_pix, + unsigned char *lum, unsigned char *cr, + unsigned char *cb, unsigned char *out, + int rows, int cols, int mod) { - unsigned short* row1; - unsigned short* row2; - unsigned char* lum2; + unsigned short *row1; + unsigned short *row2; + unsigned char *lum2; int x, y; int cr_r; int crb_g; int cb_b; int cols_2 = cols / 2; - row1 = (unsigned short*) out; + row1 = (unsigned short *) out; row2 = row1 + cols + mod; lum2 = lum + cols; mod += cols + mod; y = rows / 2; - while( y-- ) - { + while (y--) { x = cols_2; - while( x-- ) - { + while (x--) { register int L; - cr_r = 0*768+256 + colortab[ *cr + 0*256 ]; - crb_g = 1*768+256 + colortab[ *cr + 1*256 ] - + colortab[ *cb + 2*256 ]; - cb_b = 2*768+256 + colortab[ *cb + 3*256 ]; - ++cr; ++cb; + cr_r = 0 * 768 + 256 + colortab[*cr + 0 * 256]; + crb_g = 1 * 768 + 256 + colortab[*cr + 1 * 256] + + colortab[*cb + 2 * 256]; + cb_b = 2 * 768 + 256 + colortab[*cb + 3 * 256]; + ++cr; + ++cb; L = *lum++; - *row1++ = (unsigned short)(rgb_2_pix[ L + cr_r ] | - rgb_2_pix[ L + crb_g ] | - rgb_2_pix[ L + cb_b ]); + *row1++ = (unsigned short) (rgb_2_pix[L + cr_r] | + rgb_2_pix[L + crb_g] | + rgb_2_pix[L + cb_b]); L = *lum++; - *row1++ = (unsigned short)(rgb_2_pix[ L + cr_r ] | - rgb_2_pix[ L + crb_g ] | - rgb_2_pix[ L + cb_b ]); + *row1++ = (unsigned short) (rgb_2_pix[L + cr_r] | + rgb_2_pix[L + crb_g] | + rgb_2_pix[L + cb_b]); /* Now, do second row. */ L = *lum2++; - *row2++ = (unsigned short)(rgb_2_pix[ L + cr_r ] | - rgb_2_pix[ L + crb_g ] | - rgb_2_pix[ L + cb_b ]); + *row2++ = (unsigned short) (rgb_2_pix[L + cr_r] | + rgb_2_pix[L + crb_g] | + rgb_2_pix[L + cb_b]); L = *lum2++; - *row2++ = (unsigned short)(rgb_2_pix[ L + cr_r ] | - rgb_2_pix[ L + crb_g ] | - rgb_2_pix[ L + cb_b ]); + *row2++ = (unsigned short) (rgb_2_pix[L + cr_r] | + rgb_2_pix[L + crb_g] | + rgb_2_pix[L + cb_b]); } /* @@ -195,22 +191,23 @@ static void Color16DitherYV12Mod1X( int *colortab, Uint32 *rgb_2_pix, * to the ++'s above),but they need to be at the start * of the line after that. */ - lum += cols; + lum += cols; lum2 += cols; row1 += mod; row2 += mod; } } -static void Color24DitherYV12Mod1X( int *colortab, Uint32 *rgb_2_pix, - unsigned char *lum, unsigned char *cr, - unsigned char *cb, unsigned char *out, - int rows, int cols, int mod ) +static void +Color24DitherYV12Mod1X(int *colortab, Uint32 * rgb_2_pix, + unsigned char *lum, unsigned char *cr, + unsigned char *cb, unsigned char *out, + int rows, int cols, int mod) { unsigned int value; - unsigned char* row1; - unsigned char* row2; - unsigned char* lum2; + unsigned char *row1; + unsigned char *row2; + unsigned char *lum2; int x, y; int cr_r; int crb_g; @@ -218,59 +215,54 @@ static void Color24DitherYV12Mod1X( int *colortab, Uint32 *rgb_2_pix, int cols_2 = cols / 2; row1 = out; - row2 = row1 + cols*3 + mod*3; + row2 = row1 + cols * 3 + mod * 3; lum2 = lum + cols; mod += cols + mod; mod *= 3; y = rows / 2; - while( y-- ) - { + while (y--) { x = cols_2; - while( x-- ) - { + while (x--) { register int L; - cr_r = 0*768+256 + colortab[ *cr + 0*256 ]; - crb_g = 1*768+256 + colortab[ *cr + 1*256 ] - + colortab[ *cb + 2*256 ]; - cb_b = 2*768+256 + colortab[ *cb + 3*256 ]; - ++cr; ++cb; + cr_r = 0 * 768 + 256 + colortab[*cr + 0 * 256]; + crb_g = 1 * 768 + 256 + colortab[*cr + 1 * 256] + + colortab[*cb + 2 * 256]; + cb_b = 2 * 768 + 256 + colortab[*cb + 3 * 256]; + ++cr; + ++cb; L = *lum++; - value = (rgb_2_pix[ L + cr_r ] | - rgb_2_pix[ L + crb_g ] | - rgb_2_pix[ L + cb_b ]); - *row1++ = (value ) & 0xFF; - *row1++ = (value >> 8) & 0xFF; + value = (rgb_2_pix[L + cr_r] | + rgb_2_pix[L + crb_g] | rgb_2_pix[L + cb_b]); + *row1++ = (value) & 0xFF; + *row1++ = (value >> 8) & 0xFF; *row1++ = (value >> 16) & 0xFF; L = *lum++; - value = (rgb_2_pix[ L + cr_r ] | - rgb_2_pix[ L + crb_g ] | - rgb_2_pix[ L + cb_b ]); - *row1++ = (value ) & 0xFF; - *row1++ = (value >> 8) & 0xFF; + value = (rgb_2_pix[L + cr_r] | + rgb_2_pix[L + crb_g] | rgb_2_pix[L + cb_b]); + *row1++ = (value) & 0xFF; + *row1++ = (value >> 8) & 0xFF; *row1++ = (value >> 16) & 0xFF; /* Now, do second row. */ L = *lum2++; - value = (rgb_2_pix[ L + cr_r ] | - rgb_2_pix[ L + crb_g ] | - rgb_2_pix[ L + cb_b ]); - *row2++ = (value ) & 0xFF; - *row2++ = (value >> 8) & 0xFF; + value = (rgb_2_pix[L + cr_r] | + rgb_2_pix[L + crb_g] | rgb_2_pix[L + cb_b]); + *row2++ = (value) & 0xFF; + *row2++ = (value >> 8) & 0xFF; *row2++ = (value >> 16) & 0xFF; L = *lum2++; - value = (rgb_2_pix[ L + cr_r ] | - rgb_2_pix[ L + crb_g ] | - rgb_2_pix[ L + cb_b ]); - *row2++ = (value ) & 0xFF; - *row2++ = (value >> 8) & 0xFF; + value = (rgb_2_pix[L + cr_r] | + rgb_2_pix[L + crb_g] | rgb_2_pix[L + cb_b]); + *row2++ = (value) & 0xFF; + *row2++ = (value >> 8) & 0xFF; *row2++ = (value >> 16) & 0xFF; } @@ -279,69 +271,65 @@ static void Color24DitherYV12Mod1X( int *colortab, Uint32 *rgb_2_pix, * to the ++'s above),but they need to be at the start * of the line after that. */ - lum += cols; + lum += cols; lum2 += cols; row1 += mod; row2 += mod; } } -static void Color32DitherYV12Mod1X( int *colortab, Uint32 *rgb_2_pix, - unsigned char *lum, unsigned char *cr, - unsigned char *cb, unsigned char *out, - int rows, int cols, int mod ) +static void +Color32DitherYV12Mod1X(int *colortab, Uint32 * rgb_2_pix, + unsigned char *lum, unsigned char *cr, + unsigned char *cb, unsigned char *out, + int rows, int cols, int mod) { - unsigned int* row1; - unsigned int* row2; - unsigned char* lum2; + unsigned int *row1; + unsigned int *row2; + unsigned char *lum2; int x, y; int cr_r; int crb_g; int cb_b; int cols_2 = cols / 2; - row1 = (unsigned int*) out; + row1 = (unsigned int *) out; row2 = row1 + cols + mod; lum2 = lum + cols; mod += cols + mod; y = rows / 2; - while( y-- ) - { + while (y--) { x = cols_2; - while( x-- ) - { + while (x--) { register int L; - cr_r = 0*768+256 + colortab[ *cr + 0*256 ]; - crb_g = 1*768+256 + colortab[ *cr + 1*256 ] - + colortab[ *cb + 2*256 ]; - cb_b = 2*768+256 + colortab[ *cb + 3*256 ]; - ++cr; ++cb; + cr_r = 0 * 768 + 256 + colortab[*cr + 0 * 256]; + crb_g = 1 * 768 + 256 + colortab[*cr + 1 * 256] + + colortab[*cb + 2 * 256]; + cb_b = 2 * 768 + 256 + colortab[*cb + 3 * 256]; + ++cr; + ++cb; L = *lum++; - *row1++ = (rgb_2_pix[ L + cr_r ] | - rgb_2_pix[ L + crb_g ] | - rgb_2_pix[ L + cb_b ]); + *row1++ = (rgb_2_pix[L + cr_r] | + rgb_2_pix[L + crb_g] | rgb_2_pix[L + cb_b]); L = *lum++; - *row1++ = (rgb_2_pix[ L + cr_r ] | - rgb_2_pix[ L + crb_g ] | - rgb_2_pix[ L + cb_b ]); + *row1++ = (rgb_2_pix[L + cr_r] | + rgb_2_pix[L + crb_g] | rgb_2_pix[L + cb_b]); /* Now, do second row. */ L = *lum2++; - *row2++ = (rgb_2_pix[ L + cr_r ] | - rgb_2_pix[ L + crb_g ] | - rgb_2_pix[ L + cb_b ]); + *row2++ = (rgb_2_pix[L + cr_r] | + rgb_2_pix[L + crb_g] | rgb_2_pix[L + cb_b]); L = *lum2++; - *row2++ = (rgb_2_pix[ L + cr_r ] | - rgb_2_pix[ L + crb_g ] | - rgb_2_pix[ L + cb_b ]); + *row2++ = (rgb_2_pix[L + cr_r] | + rgb_2_pix[L + crb_g] | rgb_2_pix[L + cb_b]); } /* @@ -349,7 +337,7 @@ static void Color32DitherYV12Mod1X( int *colortab, Uint32 *rgb_2_pix, * to the ++'s above),but they need to be at the start * of the line after that. */ - lum += cols; + lum += cols; lum2 += cols; row1 += mod; row2 += mod; @@ -361,15 +349,16 @@ static void Color32DitherYV12Mod1X( int *colortab, Uint32 *rgb_2_pix, * 16 bits replicated in the upper 16. This means I can write ints and get * the horisontal doubling for free (almost). */ -static void Color16DitherYV12Mod2X( int *colortab, Uint32 *rgb_2_pix, - unsigned char *lum, unsigned char *cr, - unsigned char *cb, unsigned char *out, - int rows, int cols, int mod ) +static void +Color16DitherYV12Mod2X(int *colortab, Uint32 * rgb_2_pix, + unsigned char *lum, unsigned char *cr, + unsigned char *cb, unsigned char *out, + int rows, int cols, int mod) { - unsigned int* row1 = (unsigned int*) out; - const int next_row = cols+(mod/2); - unsigned int* row2 = row1 + 2*next_row; - unsigned char* lum2; + unsigned int *row1 = (unsigned int *) out; + const int next_row = cols + (mod / 2); + unsigned int *row2 = row1 + 2 * next_row; + unsigned char *lum2; int x, y; int cr_r; int crb_g; @@ -378,47 +367,46 @@ static void Color16DitherYV12Mod2X( int *colortab, Uint32 *rgb_2_pix, lum2 = lum + cols; - mod = (next_row * 3) + (mod/2); + mod = (next_row * 3) + (mod / 2); y = rows / 2; - while( y-- ) - { + while (y--) { x = cols_2; - while( x-- ) - { + while (x--) { register int L; - cr_r = 0*768+256 + colortab[ *cr + 0*256 ]; - crb_g = 1*768+256 + colortab[ *cr + 1*256 ] - + colortab[ *cb + 2*256 ]; - cb_b = 2*768+256 + colortab[ *cb + 3*256 ]; - ++cr; ++cb; + cr_r = 0 * 768 + 256 + colortab[*cr + 0 * 256]; + crb_g = 1 * 768 + 256 + colortab[*cr + 1 * 256] + + colortab[*cb + 2 * 256]; + cb_b = 2 * 768 + 256 + colortab[*cb + 3 * 256]; + ++cr; + ++cb; L = *lum++; - row1[0] = row1[next_row] = (rgb_2_pix[ L + cr_r ] | - rgb_2_pix[ L + crb_g ] | - rgb_2_pix[ L + cb_b ]); + row1[0] = row1[next_row] = (rgb_2_pix[L + cr_r] | + rgb_2_pix[L + crb_g] | + rgb_2_pix[L + cb_b]); row1++; L = *lum++; - row1[0] = row1[next_row] = (rgb_2_pix[ L + cr_r ] | - rgb_2_pix[ L + crb_g ] | - rgb_2_pix[ L + cb_b ]); + row1[0] = row1[next_row] = (rgb_2_pix[L + cr_r] | + rgb_2_pix[L + crb_g] | + rgb_2_pix[L + cb_b]); row1++; /* Now, do second row. */ L = *lum2++; - row2[0] = row2[next_row] = (rgb_2_pix[ L + cr_r ] | - rgb_2_pix[ L + crb_g ] | - rgb_2_pix[ L + cb_b ]); + row2[0] = row2[next_row] = (rgb_2_pix[L + cr_r] | + rgb_2_pix[L + crb_g] | + rgb_2_pix[L + cb_b]); row2++; L = *lum2++; - row2[0] = row2[next_row] = (rgb_2_pix[ L + cr_r ] | - rgb_2_pix[ L + crb_g ] | - rgb_2_pix[ L + cb_b ]); + row2[0] = row2[next_row] = (rgb_2_pix[L + cr_r] | + rgb_2_pix[L + crb_g] | + rgb_2_pix[L + cb_b]); row2++; } @@ -427,23 +415,24 @@ static void Color16DitherYV12Mod2X( int *colortab, Uint32 *rgb_2_pix, * to the ++'s above),but they need to be at the start * of the line after that. */ - lum += cols; + lum += cols; lum2 += cols; row1 += mod; row2 += mod; } } -static void Color24DitherYV12Mod2X( int *colortab, Uint32 *rgb_2_pix, - unsigned char *lum, unsigned char *cr, - unsigned char *cb, unsigned char *out, - int rows, int cols, int mod ) +static void +Color24DitherYV12Mod2X(int *colortab, Uint32 * rgb_2_pix, + unsigned char *lum, unsigned char *cr, + unsigned char *cb, unsigned char *out, + int rows, int cols, int mod) { unsigned int value; - unsigned char* row1 = out; - const int next_row = (cols*2 + mod) * 3; - unsigned char* row2 = row1 + 2*next_row; - unsigned char* lum2; + unsigned char *row1 = out; + const int next_row = (cols * 2 + mod) * 3; + unsigned char *row2 = row1 + 2 * next_row; + unsigned char *lum2; int x, y; int cr_r; int crb_g; @@ -452,72 +441,67 @@ static void Color24DitherYV12Mod2X( int *colortab, Uint32 *rgb_2_pix, lum2 = lum + cols; - mod = next_row*3 + mod*3; + mod = next_row * 3 + mod * 3; y = rows / 2; - while( y-- ) - { + while (y--) { x = cols_2; - while( x-- ) - { + while (x--) { register int L; - cr_r = 0*768+256 + colortab[ *cr + 0*256 ]; - crb_g = 1*768+256 + colortab[ *cr + 1*256 ] - + colortab[ *cb + 2*256 ]; - cb_b = 2*768+256 + colortab[ *cb + 3*256 ]; - ++cr; ++cb; + cr_r = 0 * 768 + 256 + colortab[*cr + 0 * 256]; + crb_g = 1 * 768 + 256 + colortab[*cr + 1 * 256] + + colortab[*cb + 2 * 256]; + cb_b = 2 * 768 + 256 + colortab[*cb + 3 * 256]; + ++cr; + ++cb; L = *lum++; - value = (rgb_2_pix[ L + cr_r ] | - rgb_2_pix[ L + crb_g ] | - rgb_2_pix[ L + cb_b ]); - row1[0+0] = row1[3+0] = row1[next_row+0] = row1[next_row+3+0] = - (value ) & 0xFF; - row1[0+1] = row1[3+1] = row1[next_row+1] = row1[next_row+3+1] = - (value >> 8) & 0xFF; - row1[0+2] = row1[3+2] = row1[next_row+2] = row1[next_row+3+2] = - (value >> 16) & 0xFF; - row1 += 2*3; + value = (rgb_2_pix[L + cr_r] | + rgb_2_pix[L + crb_g] | rgb_2_pix[L + cb_b]); + row1[0 + 0] = row1[3 + 0] = row1[next_row + 0] = + row1[next_row + 3 + 0] = (value) & 0xFF; + row1[0 + 1] = row1[3 + 1] = row1[next_row + 1] = + row1[next_row + 3 + 1] = (value >> 8) & 0xFF; + row1[0 + 2] = row1[3 + 2] = row1[next_row + 2] = + row1[next_row + 3 + 2] = (value >> 16) & 0xFF; + row1 += 2 * 3; L = *lum++; - value = (rgb_2_pix[ L + cr_r ] | - rgb_2_pix[ L + crb_g ] | - rgb_2_pix[ L + cb_b ]); - row1[0+0] = row1[3+0] = row1[next_row+0] = row1[next_row+3+0] = - (value ) & 0xFF; - row1[0+1] = row1[3+1] = row1[next_row+1] = row1[next_row+3+1] = - (value >> 8) & 0xFF; - row1[0+2] = row1[3+2] = row1[next_row+2] = row1[next_row+3+2] = - (value >> 16) & 0xFF; - row1 += 2*3; + value = (rgb_2_pix[L + cr_r] | + rgb_2_pix[L + crb_g] | rgb_2_pix[L + cb_b]); + row1[0 + 0] = row1[3 + 0] = row1[next_row + 0] = + row1[next_row + 3 + 0] = (value) & 0xFF; + row1[0 + 1] = row1[3 + 1] = row1[next_row + 1] = + row1[next_row + 3 + 1] = (value >> 8) & 0xFF; + row1[0 + 2] = row1[3 + 2] = row1[next_row + 2] = + row1[next_row + 3 + 2] = (value >> 16) & 0xFF; + row1 += 2 * 3; /* Now, do second row. */ L = *lum2++; - value = (rgb_2_pix[ L + cr_r ] | - rgb_2_pix[ L + crb_g ] | - rgb_2_pix[ L + cb_b ]); - row2[0+0] = row2[3+0] = row2[next_row+0] = row2[next_row+3+0] = - (value ) & 0xFF; - row2[0+1] = row2[3+1] = row2[next_row+1] = row2[next_row+3+1] = - (value >> 8) & 0xFF; - row2[0+2] = row2[3+2] = row2[next_row+2] = row2[next_row+3+2] = - (value >> 16) & 0xFF; - row2 += 2*3; + value = (rgb_2_pix[L + cr_r] | + rgb_2_pix[L + crb_g] | rgb_2_pix[L + cb_b]); + row2[0 + 0] = row2[3 + 0] = row2[next_row + 0] = + row2[next_row + 3 + 0] = (value) & 0xFF; + row2[0 + 1] = row2[3 + 1] = row2[next_row + 1] = + row2[next_row + 3 + 1] = (value >> 8) & 0xFF; + row2[0 + 2] = row2[3 + 2] = row2[next_row + 2] = + row2[next_row + 3 + 2] = (value >> 16) & 0xFF; + row2 += 2 * 3; L = *lum2++; - value = (rgb_2_pix[ L + cr_r ] | - rgb_2_pix[ L + crb_g ] | - rgb_2_pix[ L + cb_b ]); - row2[0+0] = row2[3+0] = row2[next_row+0] = row2[next_row+3+0] = - (value ) & 0xFF; - row2[0+1] = row2[3+1] = row2[next_row+1] = row2[next_row+3+1] = - (value >> 8) & 0xFF; - row2[0+2] = row2[3+2] = row2[next_row+2] = row2[next_row+3+2] = - (value >> 16) & 0xFF; - row2 += 2*3; + value = (rgb_2_pix[L + cr_r] | + rgb_2_pix[L + crb_g] | rgb_2_pix[L + cb_b]); + row2[0 + 0] = row2[3 + 0] = row2[next_row + 0] = + row2[next_row + 3 + 0] = (value) & 0xFF; + row2[0 + 1] = row2[3 + 1] = row2[next_row + 1] = + row2[next_row + 3 + 1] = (value >> 8) & 0xFF; + row2[0 + 2] = row2[3 + 2] = row2[next_row + 2] = + row2[next_row + 3 + 2] = (value >> 16) & 0xFF; + row2 += 2 * 3; } /* @@ -525,22 +509,23 @@ static void Color24DitherYV12Mod2X( int *colortab, Uint32 *rgb_2_pix, * to the ++'s above),but they need to be at the start * of the line after that. */ - lum += cols; + lum += cols; lum2 += cols; row1 += mod; row2 += mod; } } -static void Color32DitherYV12Mod2X( int *colortab, Uint32 *rgb_2_pix, - unsigned char *lum, unsigned char *cr, - unsigned char *cb, unsigned char *out, - int rows, int cols, int mod ) +static void +Color32DitherYV12Mod2X(int *colortab, Uint32 * rgb_2_pix, + unsigned char *lum, unsigned char *cr, + unsigned char *cb, unsigned char *out, + int rows, int cols, int mod) { - unsigned int* row1 = (unsigned int*) out; - const int next_row = cols*2+mod; - unsigned int* row2 = row1 + 2*next_row; - unsigned char* lum2; + unsigned int *row1 = (unsigned int *) out; + const int next_row = cols * 2 + mod; + unsigned int *row2 = row1 + 2 * next_row; + unsigned char *lum2; int x, y; int cr_r; int crb_g; @@ -552,48 +537,43 @@ static void Color32DitherYV12Mod2X( int *colortab, Uint32 *rgb_2_pix, mod = (next_row * 3) + mod; y = rows / 2; - while( y-- ) - { + while (y--) { x = cols_2; - while( x-- ) - { + while (x--) { register int L; - cr_r = 0*768+256 + colortab[ *cr + 0*256 ]; - crb_g = 1*768+256 + colortab[ *cr + 1*256 ] - + colortab[ *cb + 2*256 ]; - cb_b = 2*768+256 + colortab[ *cb + 3*256 ]; - ++cr; ++cb; + cr_r = 0 * 768 + 256 + colortab[*cr + 0 * 256]; + crb_g = 1 * 768 + 256 + colortab[*cr + 1 * 256] + + colortab[*cb + 2 * 256]; + cb_b = 2 * 768 + 256 + colortab[*cb + 3 * 256]; + ++cr; + ++cb; L = *lum++; - row1[0] = row1[1] = row1[next_row] = row1[next_row+1] = - (rgb_2_pix[ L + cr_r ] | - rgb_2_pix[ L + crb_g ] | - rgb_2_pix[ L + cb_b ]); + row1[0] = row1[1] = row1[next_row] = row1[next_row + 1] = + (rgb_2_pix[L + cr_r] | + rgb_2_pix[L + crb_g] | rgb_2_pix[L + cb_b]); row1 += 2; L = *lum++; - row1[0] = row1[1] = row1[next_row] = row1[next_row+1] = - (rgb_2_pix[ L + cr_r ] | - rgb_2_pix[ L + crb_g ] | - rgb_2_pix[ L + cb_b ]); + row1[0] = row1[1] = row1[next_row] = row1[next_row + 1] = + (rgb_2_pix[L + cr_r] | + rgb_2_pix[L + crb_g] | rgb_2_pix[L + cb_b]); row1 += 2; /* Now, do second row. */ L = *lum2++; - row2[0] = row2[1] = row2[next_row] = row2[next_row+1] = - (rgb_2_pix[ L + cr_r ] | - rgb_2_pix[ L + crb_g ] | - rgb_2_pix[ L + cb_b ]); + row2[0] = row2[1] = row2[next_row] = row2[next_row + 1] = + (rgb_2_pix[L + cr_r] | + rgb_2_pix[L + crb_g] | rgb_2_pix[L + cb_b]); row2 += 2; L = *lum2++; - row2[0] = row2[1] = row2[next_row] = row2[next_row+1] = - (rgb_2_pix[ L + cr_r ] | - rgb_2_pix[ L + crb_g ] | - rgb_2_pix[ L + cb_b ]); + row2[0] = row2[1] = row2[next_row] = row2[next_row + 1] = + (rgb_2_pix[L + cr_r] | + rgb_2_pix[L + crb_g] | rgb_2_pix[L + cb_b]); row2 += 2; } @@ -602,50 +582,52 @@ static void Color32DitherYV12Mod2X( int *colortab, Uint32 *rgb_2_pix, * to the ++'s above),but they need to be at the start * of the line after that. */ - lum += cols; + lum += cols; lum2 += cols; row1 += mod; row2 += mod; } } -static void Color16DitherYUY2Mod1X( int *colortab, Uint32 *rgb_2_pix, - unsigned char *lum, unsigned char *cr, - unsigned char *cb, unsigned char *out, - int rows, int cols, int mod ) +static void +Color16DitherYUY2Mod1X(int *colortab, Uint32 * rgb_2_pix, + unsigned char *lum, unsigned char *cr, + unsigned char *cb, unsigned char *out, + int rows, int cols, int mod) { - unsigned short* row; + unsigned short *row; int x, y; int cr_r; int crb_g; int cb_b; int cols_2 = cols / 2; - row = (unsigned short*) out; + row = (unsigned short *) out; y = rows; - while( y-- ) - { + while (y--) { x = cols_2; - while( x-- ) - { + while (x--) { register int L; - cr_r = 0*768+256 + colortab[ *cr + 0*256 ]; - crb_g = 1*768+256 + colortab[ *cr + 1*256 ] - + colortab[ *cb + 2*256 ]; - cb_b = 2*768+256 + colortab[ *cb + 3*256 ]; - cr += 4; cb += 4; - - L = *lum; lum += 2; - *row++ = (unsigned short)(rgb_2_pix[ L + cr_r ] | - rgb_2_pix[ L + crb_g ] | - rgb_2_pix[ L + cb_b ]); - - L = *lum; lum += 2; - *row++ = (unsigned short)(rgb_2_pix[ L + cr_r ] | - rgb_2_pix[ L + crb_g ] | - rgb_2_pix[ L + cb_b ]); + cr_r = 0 * 768 + 256 + colortab[*cr + 0 * 256]; + crb_g = 1 * 768 + 256 + colortab[*cr + 1 * 256] + + colortab[*cb + 2 * 256]; + cb_b = 2 * 768 + 256 + colortab[*cb + 3 * 256]; + cr += 4; + cb += 4; + + L = *lum; + lum += 2; + *row++ = (unsigned short) (rgb_2_pix[L + cr_r] | + rgb_2_pix[L + crb_g] | + rgb_2_pix[L + cb_b]); + + L = *lum; + lum += 2; + *row++ = (unsigned short) (rgb_2_pix[L + cr_r] | + rgb_2_pix[L + crb_g] | + rgb_2_pix[L + cb_b]); } @@ -653,49 +635,49 @@ static void Color16DitherYUY2Mod1X( int *colortab, Uint32 *rgb_2_pix, } } -static void Color24DitherYUY2Mod1X( int *colortab, Uint32 *rgb_2_pix, - unsigned char *lum, unsigned char *cr, - unsigned char *cb, unsigned char *out, - int rows, int cols, int mod ) +static void +Color24DitherYUY2Mod1X(int *colortab, Uint32 * rgb_2_pix, + unsigned char *lum, unsigned char *cr, + unsigned char *cb, unsigned char *out, + int rows, int cols, int mod) { unsigned int value; - unsigned char* row; + unsigned char *row; int x, y; int cr_r; int crb_g; int cb_b; int cols_2 = cols / 2; - row = (unsigned char*) out; + row = (unsigned char *) out; mod *= 3; y = rows; - while( y-- ) - { + while (y--) { x = cols_2; - while( x-- ) - { + while (x--) { register int L; - cr_r = 0*768+256 + colortab[ *cr + 0*256 ]; - crb_g = 1*768+256 + colortab[ *cr + 1*256 ] - + colortab[ *cb + 2*256 ]; - cb_b = 2*768+256 + colortab[ *cb + 3*256 ]; - cr += 4; cb += 4; - - L = *lum; lum += 2; - value = (rgb_2_pix[ L + cr_r ] | - rgb_2_pix[ L + crb_g ] | - rgb_2_pix[ L + cb_b ]); - *row++ = (value ) & 0xFF; - *row++ = (value >> 8) & 0xFF; + cr_r = 0 * 768 + 256 + colortab[*cr + 0 * 256]; + crb_g = 1 * 768 + 256 + colortab[*cr + 1 * 256] + + colortab[*cb + 2 * 256]; + cb_b = 2 * 768 + 256 + colortab[*cb + 3 * 256]; + cr += 4; + cb += 4; + + L = *lum; + lum += 2; + value = (rgb_2_pix[L + cr_r] | + rgb_2_pix[L + crb_g] | rgb_2_pix[L + cb_b]); + *row++ = (value) & 0xFF; + *row++ = (value >> 8) & 0xFF; *row++ = (value >> 16) & 0xFF; - L = *lum; lum += 2; - value = (rgb_2_pix[ L + cr_r ] | - rgb_2_pix[ L + crb_g ] | - rgb_2_pix[ L + cb_b ]); - *row++ = (value ) & 0xFF; - *row++ = (value >> 8) & 0xFF; + L = *lum; + lum += 2; + value = (rgb_2_pix[L + cr_r] | + rgb_2_pix[L + crb_g] | rgb_2_pix[L + cb_b]); + *row++ = (value) & 0xFF; + *row++ = (value >> 8) & 0xFF; *row++ = (value >> 16) & 0xFF; } @@ -703,42 +685,42 @@ static void Color24DitherYUY2Mod1X( int *colortab, Uint32 *rgb_2_pix, } } -static void Color32DitherYUY2Mod1X( int *colortab, Uint32 *rgb_2_pix, - unsigned char *lum, unsigned char *cr, - unsigned char *cb, unsigned char *out, - int rows, int cols, int mod ) +static void +Color32DitherYUY2Mod1X(int *colortab, Uint32 * rgb_2_pix, + unsigned char *lum, unsigned char *cr, + unsigned char *cb, unsigned char *out, + int rows, int cols, int mod) { - unsigned int* row; + unsigned int *row; int x, y; int cr_r; int crb_g; int cb_b; int cols_2 = cols / 2; - row = (unsigned int*) out; + row = (unsigned int *) out; y = rows; - while( y-- ) - { + while (y--) { x = cols_2; - while( x-- ) - { + while (x--) { register int L; - cr_r = 0*768+256 + colortab[ *cr + 0*256 ]; - crb_g = 1*768+256 + colortab[ *cr + 1*256 ] - + colortab[ *cb + 2*256 ]; - cb_b = 2*768+256 + colortab[ *cb + 3*256 ]; - cr += 4; cb += 4; + cr_r = 0 * 768 + 256 + colortab[*cr + 0 * 256]; + crb_g = 1 * 768 + 256 + colortab[*cr + 1 * 256] + + colortab[*cb + 2 * 256]; + cb_b = 2 * 768 + 256 + colortab[*cb + 3 * 256]; + cr += 4; + cb += 4; - L = *lum; lum += 2; - *row++ = (rgb_2_pix[ L + cr_r ] | - rgb_2_pix[ L + crb_g ] | - rgb_2_pix[ L + cb_b ]); + L = *lum; + lum += 2; + *row++ = (rgb_2_pix[L + cr_r] | + rgb_2_pix[L + crb_g] | rgb_2_pix[L + cb_b]); - L = *lum; lum += 2; - *row++ = (rgb_2_pix[ L + cr_r ] | - rgb_2_pix[ L + crb_g ] | - rgb_2_pix[ L + cb_b ]); + L = *lum; + lum += 2; + *row++ = (rgb_2_pix[L + cr_r] | + rgb_2_pix[L + crb_g] | rgb_2_pix[L + cb_b]); } @@ -751,13 +733,14 @@ static void Color32DitherYUY2Mod1X( int *colortab, Uint32 *rgb_2_pix, * 16 bits replicated in the upper 16. This means I can write ints and get * the horisontal doubling for free (almost). */ -static void Color16DitherYUY2Mod2X( int *colortab, Uint32 *rgb_2_pix, - unsigned char *lum, unsigned char *cr, - unsigned char *cb, unsigned char *out, - int rows, int cols, int mod ) +static void +Color16DitherYUY2Mod2X(int *colortab, Uint32 * rgb_2_pix, + unsigned char *lum, unsigned char *cr, + unsigned char *cb, unsigned char *out, + int rows, int cols, int mod) { - unsigned int* row = (unsigned int*) out; - const int next_row = cols+(mod/2); + unsigned int *row = (unsigned int *) out; + const int next_row = cols + (mod / 2); int x, y; int cr_r; int crb_g; @@ -765,29 +748,30 @@ static void Color16DitherYUY2Mod2X( int *colortab, Uint32 *rgb_2_pix, int cols_2 = cols / 2; y = rows; - while( y-- ) - { + while (y--) { x = cols_2; - while( x-- ) - { + while (x--) { register int L; - cr_r = 0*768+256 + colortab[ *cr + 0*256 ]; - crb_g = 1*768+256 + colortab[ *cr + 1*256 ] - + colortab[ *cb + 2*256 ]; - cb_b = 2*768+256 + colortab[ *cb + 3*256 ]; - cr += 4; cb += 4; - - L = *lum; lum += 2; - row[0] = row[next_row] = (rgb_2_pix[ L + cr_r ] | - rgb_2_pix[ L + crb_g ] | - rgb_2_pix[ L + cb_b ]); + cr_r = 0 * 768 + 256 + colortab[*cr + 0 * 256]; + crb_g = 1 * 768 + 256 + colortab[*cr + 1 * 256] + + colortab[*cb + 2 * 256]; + cb_b = 2 * 768 + 256 + colortab[*cb + 3 * 256]; + cr += 4; + cb += 4; + + L = *lum; + lum += 2; + row[0] = row[next_row] = (rgb_2_pix[L + cr_r] | + rgb_2_pix[L + crb_g] | + rgb_2_pix[L + cb_b]); row++; - L = *lum; lum += 2; - row[0] = row[next_row] = (rgb_2_pix[ L + cr_r ] | - rgb_2_pix[ L + crb_g ] | - rgb_2_pix[ L + cb_b ]); + L = *lum; + lum += 2; + row[0] = row[next_row] = (rgb_2_pix[L + cr_r] | + rgb_2_pix[L + crb_g] | + rgb_2_pix[L + cb_b]); row++; } @@ -795,101 +779,101 @@ static void Color16DitherYUY2Mod2X( int *colortab, Uint32 *rgb_2_pix, } } -static void Color24DitherYUY2Mod2X( int *colortab, Uint32 *rgb_2_pix, - unsigned char *lum, unsigned char *cr, - unsigned char *cb, unsigned char *out, - int rows, int cols, int mod ) +static void +Color24DitherYUY2Mod2X(int *colortab, Uint32 * rgb_2_pix, + unsigned char *lum, unsigned char *cr, + unsigned char *cb, unsigned char *out, + int rows, int cols, int mod) { unsigned int value; - unsigned char* row = out; - const int next_row = (cols*2 + mod) * 3; + unsigned char *row = out; + const int next_row = (cols * 2 + mod) * 3; int x, y; int cr_r; int crb_g; int cb_b; int cols_2 = cols / 2; y = rows; - while( y-- ) - { + while (y--) { x = cols_2; - while( x-- ) - { + while (x--) { register int L; - cr_r = 0*768+256 + colortab[ *cr + 0*256 ]; - crb_g = 1*768+256 + colortab[ *cr + 1*256 ] - + colortab[ *cb + 2*256 ]; - cb_b = 2*768+256 + colortab[ *cb + 3*256 ]; - cr += 4; cb += 4; - - L = *lum; lum += 2; - value = (rgb_2_pix[ L + cr_r ] | - rgb_2_pix[ L + crb_g ] | - rgb_2_pix[ L + cb_b ]); - row[0+0] = row[3+0] = row[next_row+0] = row[next_row+3+0] = - (value ) & 0xFF; - row[0+1] = row[3+1] = row[next_row+1] = row[next_row+3+1] = - (value >> 8) & 0xFF; - row[0+2] = row[3+2] = row[next_row+2] = row[next_row+3+2] = - (value >> 16) & 0xFF; - row += 2*3; - - L = *lum; lum += 2; - value = (rgb_2_pix[ L + cr_r ] | - rgb_2_pix[ L + crb_g ] | - rgb_2_pix[ L + cb_b ]); - row[0+0] = row[3+0] = row[next_row+0] = row[next_row+3+0] = - (value ) & 0xFF; - row[0+1] = row[3+1] = row[next_row+1] = row[next_row+3+1] = - (value >> 8) & 0xFF; - row[0+2] = row[3+2] = row[next_row+2] = row[next_row+3+2] = - (value >> 16) & 0xFF; - row += 2*3; + cr_r = 0 * 768 + 256 + colortab[*cr + 0 * 256]; + crb_g = 1 * 768 + 256 + colortab[*cr + 1 * 256] + + colortab[*cb + 2 * 256]; + cb_b = 2 * 768 + 256 + colortab[*cb + 3 * 256]; + cr += 4; + cb += 4; + + L = *lum; + lum += 2; + value = (rgb_2_pix[L + cr_r] | + rgb_2_pix[L + crb_g] | rgb_2_pix[L + cb_b]); + row[0 + 0] = row[3 + 0] = row[next_row + 0] = + row[next_row + 3 + 0] = (value) & 0xFF; + row[0 + 1] = row[3 + 1] = row[next_row + 1] = + row[next_row + 3 + 1] = (value >> 8) & 0xFF; + row[0 + 2] = row[3 + 2] = row[next_row + 2] = + row[next_row + 3 + 2] = (value >> 16) & 0xFF; + row += 2 * 3; + + L = *lum; + lum += 2; + value = (rgb_2_pix[L + cr_r] | + rgb_2_pix[L + crb_g] | rgb_2_pix[L + cb_b]); + row[0 + 0] = row[3 + 0] = row[next_row + 0] = + row[next_row + 3 + 0] = (value) & 0xFF; + row[0 + 1] = row[3 + 1] = row[next_row + 1] = + row[next_row + 3 + 1] = (value >> 8) & 0xFF; + row[0 + 2] = row[3 + 2] = row[next_row + 2] = + row[next_row + 3 + 2] = (value >> 16) & 0xFF; + row += 2 * 3; } row += next_row; } } -static void Color32DitherYUY2Mod2X( int *colortab, Uint32 *rgb_2_pix, - unsigned char *lum, unsigned char *cr, - unsigned char *cb, unsigned char *out, - int rows, int cols, int mod ) +static void +Color32DitherYUY2Mod2X(int *colortab, Uint32 * rgb_2_pix, + unsigned char *lum, unsigned char *cr, + unsigned char *cb, unsigned char *out, + int rows, int cols, int mod) { - unsigned int* row = (unsigned int*) out; - const int next_row = cols*2+mod; + unsigned int *row = (unsigned int *) out; + const int next_row = cols * 2 + mod; int x, y; int cr_r; int crb_g; int cb_b; int cols_2 = cols / 2; - mod+=mod; + mod += mod; y = rows; - while( y-- ) - { + while (y--) { x = cols_2; - while( x-- ) - { + while (x--) { register int L; - cr_r = 0*768+256 + colortab[ *cr + 0*256 ]; - crb_g = 1*768+256 + colortab[ *cr + 1*256 ] - + colortab[ *cb + 2*256 ]; - cb_b = 2*768+256 + colortab[ *cb + 3*256 ]; - cr += 4; cb += 4; - - L = *lum; lum += 2; - row[0] = row[1] = row[next_row] = row[next_row+1] = - (rgb_2_pix[ L + cr_r ] | - rgb_2_pix[ L + crb_g ] | - rgb_2_pix[ L + cb_b ]); + cr_r = 0 * 768 + 256 + colortab[*cr + 0 * 256]; + crb_g = 1 * 768 + 256 + colortab[*cr + 1 * 256] + + colortab[*cb + 2 * 256]; + cb_b = 2 * 768 + 256 + colortab[*cb + 3 * 256]; + cr += 4; + cb += 4; + + L = *lum; + lum += 2; + row[0] = row[1] = row[next_row] = row[next_row + 1] = + (rgb_2_pix[L + cr_r] | + rgb_2_pix[L + crb_g] | rgb_2_pix[L + cb_b]); row += 2; - L = *lum; lum += 2; - row[0] = row[1] = row[next_row] = row[next_row+1] = - (rgb_2_pix[ L + cr_r ] | - rgb_2_pix[ L + crb_g ] | - rgb_2_pix[ L + cb_b ]); + L = *lum; + lum += 2; + row[0] = row[1] = row[next_row] = row[next_row + 1] = + (rgb_2_pix[L + cr_r] | + rgb_2_pix[L + crb_g] | rgb_2_pix[L + cb_b]); row += 2; @@ -903,396 +887,465 @@ static void Color32DitherYUY2Mod2X( int *colortab, Uint32 *rgb_2_pix, * How many 1 bits are there in the Uint32. * Low performance, do not call often. */ -static int number_of_bits_set( Uint32 a ) +static int +number_of_bits_set(Uint32 a) { - if(!a) return 0; - if(a & 1) return 1 + number_of_bits_set(a >> 1); - return(number_of_bits_set(a >> 1)); + if (!a) + return 0; + if (a & 1) + return 1 + number_of_bits_set(a >> 1); + return (number_of_bits_set(a >> 1)); } /* * How many 0 bits are there at least significant end of Uint32. * Low performance, do not call often. */ -static int free_bits_at_bottom( Uint32 a ) +static int +free_bits_at_bottom(Uint32 a) { - /* assume char is 8 bits */ - if(!a) return sizeof(Uint32) * 8; - if(((Sint32)a) & 1l) return 0; - return 1 + free_bits_at_bottom ( a >> 1); + /* assume char is 8 bits */ + if (!a) + return sizeof(Uint32) * 8; + if (((Sint32) a) & 1l) + return 0; + return 1 + free_bits_at_bottom(a >> 1); } - -SDL_Overlay *SDL_CreateYUV_SW(_THIS, int width, int height, Uint32 format, SDL_Surface *display) +static int +SDL_SW_SetupYUVDisplay(SDL_SW_YUVTexture * swdata, Uint32 target_format) { - SDL_Overlay *overlay; - struct private_yuvhwdata *swdata; - int *Cr_r_tab; - int *Cr_g_tab; - int *Cb_g_tab; - int *Cb_b_tab; - Uint32 *r_2_pix_alloc; - Uint32 *g_2_pix_alloc; - Uint32 *b_2_pix_alloc; - int i; - int CR, CB; - Uint32 Rmask, Gmask, Bmask; - - /* Only RGB packed pixel conversion supported */ - if ( (display->format->BytesPerPixel != 2) && - (display->format->BytesPerPixel != 3) && - (display->format->BytesPerPixel != 4) ) { - SDL_SetError("Can't use YUV data on non 16/24/32 bit surfaces"); - return(NULL); - } - - /* Verify that we support the format */ - switch (format) { - case SDL_YV12_OVERLAY: - case SDL_IYUV_OVERLAY: - case SDL_YUY2_OVERLAY: - case SDL_UYVY_OVERLAY: - case SDL_YVYU_OVERLAY: - break; - default: - SDL_SetError("Unsupported YUV format"); - return(NULL); - } - - /* Create the overlay structure */ - overlay = (SDL_Overlay *)SDL_malloc(sizeof *overlay); - if ( overlay == NULL ) { - SDL_OutOfMemory(); - return(NULL); - } - SDL_memset(overlay, 0, (sizeof *overlay)); - - /* Fill in the basic members */ - overlay->format = format; - overlay->w = width; - overlay->h = height; - - /* Set up the YUV surface function structure */ - overlay->hwfuncs = &sw_yuvfuncs; - - /* Create the pixel data and lookup tables */ - swdata = (struct private_yuvhwdata *)SDL_malloc(sizeof *swdata); - overlay->hwdata = swdata; - if ( swdata == NULL ) { - SDL_OutOfMemory(); - SDL_FreeYUVOverlay(overlay); - return(NULL); - } - swdata->stretch = NULL; - swdata->display = display; - swdata->pixels = (Uint8 *) SDL_malloc(width*height*2); - swdata->colortab = (int *)SDL_malloc(4*256*sizeof(int)); - Cr_r_tab = &swdata->colortab[0*256]; - Cr_g_tab = &swdata->colortab[1*256]; - Cb_g_tab = &swdata->colortab[2*256]; - Cb_b_tab = &swdata->colortab[3*256]; - swdata->rgb_2_pix = (Uint32 *)SDL_malloc(3*768*sizeof(Uint32)); - r_2_pix_alloc = &swdata->rgb_2_pix[0*768]; - g_2_pix_alloc = &swdata->rgb_2_pix[1*768]; - b_2_pix_alloc = &swdata->rgb_2_pix[2*768]; - if ( ! swdata->pixels || ! swdata->colortab || ! swdata->rgb_2_pix ) { - SDL_OutOfMemory(); - SDL_FreeYUVOverlay(overlay); - return(NULL); - } - - /* Generate the tables for the display surface */ - for (i=0; i<256; i++) { - /* Gamma correction (luminescence table) and chroma correction - would be done here. See the Berkeley mpeg_play sources. - */ - CB = CR = (i-128); - Cr_r_tab[i] = (int) ( (0.419/0.299) * CR); - Cr_g_tab[i] = (int) (-(0.299/0.419) * CR); - Cb_g_tab[i] = (int) (-(0.114/0.331) * CB); - Cb_b_tab[i] = (int) ( (0.587/0.331) * CB); - } - - /* - * Set up entries 0-255 in rgb-to-pixel value tables. - */ - Rmask = display->format->Rmask; - Gmask = display->format->Gmask; - Bmask = display->format->Bmask; - for ( i=0; i<256; ++i ) { - r_2_pix_alloc[i+256] = i >> (8 - number_of_bits_set(Rmask)); - r_2_pix_alloc[i+256] <<= free_bits_at_bottom(Rmask); - g_2_pix_alloc[i+256] = i >> (8 - number_of_bits_set(Gmask)); - g_2_pix_alloc[i+256] <<= free_bits_at_bottom(Gmask); - b_2_pix_alloc[i+256] = i >> (8 - number_of_bits_set(Bmask)); - b_2_pix_alloc[i+256] <<= free_bits_at_bottom(Bmask); - } - - /* - * If we have 16-bit output depth, then we double the value - * in the top word. This means that we can write out both - * pixels in the pixel doubling mode with one op. It is - * harmless in the normal case as storing a 32-bit value - * through a short pointer will lose the top bits anyway. - */ - if( display->format->BytesPerPixel == 2 ) { - for ( i=0; i<256; ++i ) { - r_2_pix_alloc[i+256] |= (r_2_pix_alloc[i+256]) << 16; - g_2_pix_alloc[i+256] |= (g_2_pix_alloc[i+256]) << 16; - b_2_pix_alloc[i+256] |= (b_2_pix_alloc[i+256]) << 16; - } - } - - /* - * Spread out the values we have to the rest of the array so that - * we do not need to check for overflow. - */ - for ( i=0; i<256; ++i ) { - r_2_pix_alloc[i] = r_2_pix_alloc[256]; - r_2_pix_alloc[i+512] = r_2_pix_alloc[511]; - g_2_pix_alloc[i] = g_2_pix_alloc[256]; - g_2_pix_alloc[i+512] = g_2_pix_alloc[511]; - b_2_pix_alloc[i] = b_2_pix_alloc[256]; - b_2_pix_alloc[i+512] = b_2_pix_alloc[511]; - } - - /* You have chosen wisely... */ - switch (format) { - case SDL_YV12_OVERLAY: - case SDL_IYUV_OVERLAY: - if ( display->format->BytesPerPixel == 2 ) { -#if 0 /*defined(__GNUC__) && defined(__i386__) && SDL_ASSEMBLY_ROUTINES*/ - /* inline assembly functions */ - if ( SDL_HasMMX() && (Rmask == 0xF800) && - (Gmask == 0x07E0) && - (Bmask == 0x001F) && - (width & 15) == 0) { + Uint32 *r_2_pix_alloc; + Uint32 *g_2_pix_alloc; + Uint32 *b_2_pix_alloc; + int i; + int bpp; + Uint32 Rmask, Gmask, Bmask, Amask; + + if (!SDL_PixelFormatEnumToMasks + (target_format, &bpp, &Rmask, &Gmask, &Bmask, &Amask) || bpp < 15) { + SDL_SetError("Unsupported YUV destination format"); + return -1; + } + + swdata->target_format = target_format; + r_2_pix_alloc = &swdata->rgb_2_pix[0 * 768]; + g_2_pix_alloc = &swdata->rgb_2_pix[1 * 768]; + b_2_pix_alloc = &swdata->rgb_2_pix[2 * 768]; + + /* + * Set up entries 0-255 in rgb-to-pixel value tables. + */ + for (i = 0; i < 256; ++i) { + r_2_pix_alloc[i + 256] = i >> (8 - number_of_bits_set(Rmask)); + r_2_pix_alloc[i + 256] <<= free_bits_at_bottom(Rmask); + g_2_pix_alloc[i + 256] = i >> (8 - number_of_bits_set(Gmask)); + g_2_pix_alloc[i + 256] <<= free_bits_at_bottom(Gmask); + b_2_pix_alloc[i + 256] = i >> (8 - number_of_bits_set(Bmask)); + b_2_pix_alloc[i + 256] <<= free_bits_at_bottom(Bmask); + } + + /* + * If we have 16-bit output depth, then we double the value + * in the top word. This means that we can write out both + * pixels in the pixel doubling mode with one op. It is + * harmless in the normal case as storing a 32-bit value + * through a short pointer will lose the top bits anyway. + */ + if (SDL_BYTESPERPIXEL(target_format) == 2) { + for (i = 0; i < 256; ++i) { + r_2_pix_alloc[i + 256] |= (r_2_pix_alloc[i + 256]) << 16; + g_2_pix_alloc[i + 256] |= (g_2_pix_alloc[i + 256]) << 16; + b_2_pix_alloc[i + 256] |= (b_2_pix_alloc[i + 256]) << 16; + } + } + + /* + * Spread out the values we have to the rest of the array so that + * we do not need to check for overflow. + */ + for (i = 0; i < 256; ++i) { + r_2_pix_alloc[i] = r_2_pix_alloc[256]; + r_2_pix_alloc[i + 512] = r_2_pix_alloc[511]; + g_2_pix_alloc[i] = g_2_pix_alloc[256]; + g_2_pix_alloc[i + 512] = g_2_pix_alloc[511]; + b_2_pix_alloc[i] = b_2_pix_alloc[256]; + b_2_pix_alloc[i + 512] = b_2_pix_alloc[511]; + } + + /* You have chosen wisely... */ + switch (swdata->texture->format) { + case SDL_PixelFormat_YV12: + case SDL_PixelFormat_IYUV: + if (SDL_BYTESPERPIXEL(target_format) == 2) { +#if 0 /*defined(__GNUC__) && defined(__i386__) && SDL_ASSEMBLY_ROUTINES */ + /* inline assembly functions */ + if (SDL_HasMMX() && (Rmask == 0xF800) && + (Gmask == 0x07E0) && (Bmask == 0x001F) && (width & 15) == 0) { /*printf("Using MMX 16-bit 565 dither\n");*/ - swdata->Display1X = Color565DitherYV12MMX1X; - } else { + swdata->Display1X = Color565DitherYV12MMX1X; + } else { /*printf("Using C 16-bit dither\n");*/ - swdata->Display1X = Color16DitherYV12Mod1X; - } + swdata->Display1X = Color16DitherYV12Mod1X; + } #else - swdata->Display1X = Color16DitherYV12Mod1X; + swdata->Display1X = Color16DitherYV12Mod1X; #endif - swdata->Display2X = Color16DitherYV12Mod2X; - } - if ( display->format->BytesPerPixel == 3 ) { - swdata->Display1X = Color24DitherYV12Mod1X; - swdata->Display2X = Color24DitherYV12Mod2X; - } - if ( display->format->BytesPerPixel == 4 ) { -#if 0 /*defined(__GNUC__) && defined(__i386__) && SDL_ASSEMBLY_ROUTINES*/ - /* inline assembly functions */ - if ( SDL_HasMMX() && (Rmask == 0x00FF0000) && - (Gmask == 0x0000FF00) && - (Bmask == 0x000000FF) && - (width & 15) == 0) { + swdata->Display2X = Color16DitherYV12Mod2X; + } + if (SDL_BYTESPERPIXEL(target_format) == 3) { + swdata->Display1X = Color24DitherYV12Mod1X; + swdata->Display2X = Color24DitherYV12Mod2X; + } + if (SDL_BYTESPERPIXEL(target_format) == 4) { +#if 0 /*defined(__GNUC__) && defined(__i386__) && SDL_ASSEMBLY_ROUTINES */ + /* inline assembly functions */ + if (SDL_HasMMX() && (Rmask == 0x00FF0000) && + (Gmask == 0x0000FF00) && + (Bmask == 0x000000FF) && (width & 15) == 0) { /*printf("Using MMX 32-bit dither\n");*/ - swdata->Display1X = ColorRGBDitherYV12MMX1X; - } else { + swdata->Display1X = ColorRGBDitherYV12MMX1X; + } else { /*printf("Using C 32-bit dither\n");*/ - swdata->Display1X = Color32DitherYV12Mod1X; - } + swdata->Display1X = Color32DitherYV12Mod1X; + } #else - swdata->Display1X = Color32DitherYV12Mod1X; + swdata->Display1X = Color32DitherYV12Mod1X; #endif - swdata->Display2X = Color32DitherYV12Mod2X; - } - break; - case SDL_YUY2_OVERLAY: - case SDL_UYVY_OVERLAY: - case SDL_YVYU_OVERLAY: - if ( display->format->BytesPerPixel == 2 ) { - swdata->Display1X = Color16DitherYUY2Mod1X; - swdata->Display2X = Color16DitherYUY2Mod2X; - } - if ( display->format->BytesPerPixel == 3 ) { - swdata->Display1X = Color24DitherYUY2Mod1X; - swdata->Display2X = Color24DitherYUY2Mod2X; - } - if ( display->format->BytesPerPixel == 4 ) { - swdata->Display1X = Color32DitherYUY2Mod1X; - swdata->Display2X = Color32DitherYUY2Mod2X; - } - break; - default: - /* We should never get here (caught above) */ - break; - } - - /* Find the pitch and offset values for the overlay */ - overlay->pitches = swdata->pitches; - overlay->pixels = swdata->planes; - switch (format) { - case SDL_YV12_OVERLAY: - case SDL_IYUV_OVERLAY: - overlay->pitches[0] = overlay->w; - overlay->pitches[1] = overlay->pitches[0] / 2; - overlay->pitches[2] = overlay->pitches[0] / 2; - overlay->pixels[0] = swdata->pixels; - overlay->pixels[1] = overlay->pixels[0] + - overlay->pitches[0] * overlay->h; - overlay->pixels[2] = overlay->pixels[1] + - overlay->pitches[1] * overlay->h / 2; - overlay->planes = 3; - break; - case SDL_YUY2_OVERLAY: - case SDL_UYVY_OVERLAY: - case SDL_YVYU_OVERLAY: - overlay->pitches[0] = overlay->w*2; - overlay->pixels[0] = swdata->pixels; - overlay->planes = 1; - break; - default: - /* We should never get here (caught above) */ - break; - } - - /* We're all done.. */ - return(overlay); + swdata->Display2X = Color32DitherYV12Mod2X; + } + break; + case SDL_PixelFormat_YUY2: + case SDL_PixelFormat_UYVY: + case SDL_PixelFormat_YVYU: + if (SDL_BYTESPERPIXEL(target_format) == 2) { + swdata->Display1X = Color16DitherYUY2Mod1X; + swdata->Display2X = Color16DitherYUY2Mod2X; + } + if (SDL_BYTESPERPIXEL(target_format) == 3) { + swdata->Display1X = Color24DitherYUY2Mod1X; + swdata->Display2X = Color24DitherYUY2Mod2X; + } + if (SDL_BYTESPERPIXEL(target_format) == 4) { + swdata->Display1X = Color32DitherYUY2Mod1X; + swdata->Display2X = Color32DitherYUY2Mod2X; + } + break; + default: + /* We should never get here (caught above) */ + break; + } + + if (swdata->display) { + SDL_FreeSurface(swdata->display); + swdata->display = NULL; + } + return 0; +} + +SDL_SW_YUVTexture * +SDL_SW_CreateYUVTexture(SDL_Texture * texture) +{ + SDL_SW_YUVTexture *swdata; + int *Cr_r_tab; + int *Cr_g_tab; + int *Cb_g_tab; + int *Cb_b_tab; + int i; + int CR, CB; + + swdata = (SDL_SW_YUVTexture *) SDL_malloc(sizeof(*swdata)); + if (!swdata) { + SDL_OutOfMemory(); + return NULL; + } + SDL_zerop(swdata); + + switch (texture->format) { + case SDL_PixelFormat_YV12: + case SDL_PixelFormat_IYUV: + case SDL_PixelFormat_YUY2: + case SDL_PixelFormat_UYVY: + case SDL_PixelFormat_YVYU: + break; + default: + SDL_SetError("Unsupported YUV format"); + return NULL; + } + + swdata->texture = texture; + swdata->target_format = SDL_PixelFormat_Unknown; + swdata->pixels = (Uint8 *) SDL_malloc(texture->w * texture->h * 2); + swdata->colortab = (int *) SDL_malloc(4 * 256 * sizeof(int)); + swdata->rgb_2_pix = (Uint32 *) SDL_malloc(3 * 768 * sizeof(Uint32)); + if (!swdata->pixels || !swdata->colortab || !swdata->rgb_2_pix) { + SDL_OutOfMemory(); + SDL_SW_DestroyYUVTexture(swdata); + return NULL; + } + + /* Generate the tables for the display surface */ + Cr_r_tab = &swdata->colortab[0 * 256]; + Cr_g_tab = &swdata->colortab[1 * 256]; + Cb_g_tab = &swdata->colortab[2 * 256]; + Cb_b_tab = &swdata->colortab[3 * 256]; + for (i = 0; i < 256; i++) { + /* Gamma correction (luminescence table) and chroma correction + would be done here. See the Berkeley mpeg_play sources. + */ + CB = CR = (i - 128); + Cr_r_tab[i] = (int) ((0.419 / 0.299) * CR); + Cr_g_tab[i] = (int) (-(0.299 / 0.419) * CR); + Cb_g_tab[i] = (int) (-(0.114 / 0.331) * CB); + Cb_b_tab[i] = (int) ((0.587 / 0.331) * CB); + } + + /* Find the pitch and offset values for the overlay */ + switch (texture->format) { + case SDL_PixelFormat_YV12: + case SDL_PixelFormat_IYUV: + swdata->pitches[0] = texture->w; + swdata->pitches[1] = swdata->pitches[0] / 2; + swdata->pitches[2] = swdata->pitches[0] / 2; + swdata->planes[0] = swdata->pixels; + swdata->planes[1] = + swdata->planes[0] + swdata->pitches[0] * texture->h; + swdata->planes[2] = + swdata->planes[1] + swdata->pitches[1] * texture->h / 2; + break; + case SDL_PixelFormat_YUY2: + case SDL_PixelFormat_UYVY: + case SDL_PixelFormat_YVYU: + swdata->pitches[0] = texture->w * 2; + swdata->planes[0] = swdata->pixels; + break; + default: + /* We should never get here (caught above) */ + break; + } + + /* We're all done.. */ + return (swdata); +} + +int +SDL_SW_QueryYUVTexturePixels(SDL_SW_YUVTexture * swdata, void **pixels, + int *pitch) +{ + *pixels = swdata->planes[0]; + *pitch = swdata->pitches[0]; + return 0; +} + +int +SDL_SW_UpdateYUVTexture(SDL_SW_YUVTexture * swdata, const SDL_Rect * rect, + const void *pixels, int pitch) +{ + SDL_Texture *texture = swdata->texture; + + switch (texture->format) { + case SDL_PixelFormat_YV12: + case SDL_PixelFormat_IYUV: + if (rect + && (rect->x != 0 || rect->y != 0 || rect->w != texture->w + || rect->h != texture->h)) { + SDL_SetError + ("YV12 and IYUV textures only support full surface updates"); + return -1; + } + SDL_memcpy(swdata->pixels, pixels, texture->h * texture->w * 2); + break; + case SDL_PixelFormat_YUY2: + case SDL_PixelFormat_UYVY: + case SDL_PixelFormat_YVYU: + { + Uint8 *src, *dst; + int row; + size_t length; + + src = (Uint8 *) pixels; + dst = + swdata->planes[0] + rect->y * swdata->pitches[0] + + rect->x * 2; + length = rect->w * 2; + for (row = 0; row < rect->h; ++row) { + SDL_memcpy(dst, src, length); + src += pitch; + dst += swdata->pitches[0]; + } + } + break; + } + return 0; } -int SDL_LockYUV_SW(_THIS, SDL_Overlay *overlay) +int +SDL_SW_LockYUVTexture(SDL_SW_YUVTexture * swdata, const SDL_Rect * rect, + int markDirty, void **pixels, int *pitch) { - return(0); + SDL_Texture *texture = swdata->texture; + + switch (texture->format) { + case SDL_PixelFormat_YV12: + case SDL_PixelFormat_IYUV: + if (rect + && (rect->x != 0 || rect->y != 0 || rect->w != texture->w + || rect->h != texture->h)) { + SDL_SetError + ("YV12 and IYUV textures only support full surface locks"); + return -1; + } + break; + } + + *pixels = swdata->planes[0] + rect->y * swdata->pitches[0] + rect->x * 2; + *pitch = swdata->pitches[0]; + return 0; } -void SDL_UnlockYUV_SW(_THIS, SDL_Overlay *overlay) +void +SDL_SW_UnlockYUVTexture(SDL_SW_YUVTexture * swdata) { - return; } -int SDL_DisplayYUV_SW(_THIS, SDL_Overlay *overlay, SDL_Rect *src, SDL_Rect *dst) +int +SDL_SW_CopyYUVToRGB(SDL_SW_YUVTexture * swdata, const SDL_Rect * srcrect, + Uint32 target_format, int w, int h, void *pixels, + int pitch) { - struct private_yuvhwdata *swdata; - int stretch; - int scale_2x; - SDL_Surface *display; - Uint8 *lum, *Cr, *Cb; - Uint8 *dstp; - int mod; - - swdata = overlay->hwdata; - stretch = 0; - scale_2x = 0; - if ( src->x || src->y || src->w < overlay->w || src->h < overlay->h ) { - /* The source rectangle has been clipped. - Using a scratch surface is easier than adding clipped - source support to all the blitters, plus that would - slow them down in the general unclipped case. - */ - stretch = 1; - } else if ( (src->w != dst->w) || (src->h != dst->h) ) { - if ( (dst->w == 2*src->w) && - (dst->h == 2*src->h) ) { - scale_2x = 1; - } else { - stretch = 1; - } - } - if ( stretch ) { - if ( ! swdata->stretch ) { - display = swdata->display; - swdata->stretch = SDL_CreateRGBSurface( - SDL_SWSURFACE, - overlay->w, overlay->h, - display->format->BitsPerPixel, - display->format->Rmask, - display->format->Gmask, - display->format->Bmask, 0); - if ( ! swdata->stretch ) { - return(-1); - } - } - display = swdata->stretch; - } else { - display = swdata->display; - } - switch (overlay->format) { - case SDL_YV12_OVERLAY: - lum = overlay->pixels[0]; - Cr = overlay->pixels[1]; - Cb = overlay->pixels[2]; - break; - case SDL_IYUV_OVERLAY: - lum = overlay->pixels[0]; - Cr = overlay->pixels[2]; - Cb = overlay->pixels[1]; - break; - case SDL_YUY2_OVERLAY: - lum = overlay->pixels[0]; - Cr = lum + 3; - Cb = lum + 1; - break; - case SDL_UYVY_OVERLAY: - lum = overlay->pixels[0]+1; - Cr = lum + 1; - Cb = lum - 1; - break; - case SDL_YVYU_OVERLAY: - lum = overlay->pixels[0]; - Cr = lum + 1; - Cb = lum + 3; - break; - default: - SDL_SetError("Unsupported YUV format in blit"); - return(-1); - } - if ( SDL_MUSTLOCK(display) ) { - if ( SDL_LockSurface(display) < 0 ) { - return(-1); - } - } - if ( stretch ) { - dstp = (Uint8 *)swdata->stretch->pixels; - } else { - dstp = (Uint8 *)display->pixels - + dst->x * display->format->BytesPerPixel - + dst->y * display->pitch; - } - mod = (display->pitch / display->format->BytesPerPixel); - - if ( scale_2x ) { - mod -= (overlay->w * 2); - swdata->Display2X(swdata->colortab, swdata->rgb_2_pix, - lum, Cr, Cb, dstp, overlay->h, overlay->w, mod); - } else { - mod -= overlay->w; - swdata->Display1X(swdata->colortab, swdata->rgb_2_pix, - lum, Cr, Cb, dstp, overlay->h, overlay->w, mod); - } - if ( SDL_MUSTLOCK(display) ) { - SDL_UnlockSurface(display); - } - if ( stretch ) { - display = swdata->display; - SDL_SoftStretch(swdata->stretch, src, display, dst); - } - SDL_UpdateRects(display, 1, dst); - - return(0); + SDL_Texture *texture = swdata->texture; + int stretch; + int scale_2x; + Uint8 *lum, *Cr, *Cb; + int mod; + + /* Make sure we're set up to display in the desired format */ + if (target_format != swdata->target_format) { + if (SDL_SW_SetupYUVDisplay(swdata, target_format) < 0) { + return -1; + } + } + + stretch = 0; + scale_2x = 0; + if (srcrect->x || srcrect->y || srcrect->w < texture->w + || srcrect->h < texture->h) { + /* The source rectangle has been clipped. + Using a scratch surface is easier than adding clipped + source support to all the blitters, plus that would + slow them down in the general unclipped case. + */ + stretch = 1; + } else if ((srcrect->w != w) || (srcrect->h != h)) { + if ((w == 2 * srcrect->w) && (h == 2 * srcrect->h)) { + scale_2x = 1; + } else { + stretch = 1; + } + } + if (stretch) { + int bpp; + Uint32 Rmask, Gmask, Bmask, Amask; + + if (swdata->display) { + swdata->display->w = w; + swdata->display->h = h; + swdata->display->pixels = pixels; + swdata->display->pitch = pitch; + } else { + /* This must have succeeded in SDL_SW_SetupYUVDisplay() earlier */ + SDL_PixelFormatEnumToMasks(target_format, &bpp, &Rmask, &Gmask, + &Bmask, &Amask); + swdata->display = + SDL_CreateRGBSurfaceFrom(pixels, w, h, bpp, pitch, Rmask, + Gmask, Bmask, Amask); + if (!swdata->display) { + return (-1); + } + } + if (!swdata->stretch) { + /* This must have succeeded in SDL_SW_SetupYUVDisplay() earlier */ + SDL_PixelFormatEnumToMasks(target_format, &bpp, &Rmask, &Gmask, + &Bmask, &Amask); + swdata->stretch = + SDL_CreateRGBSurface(0, texture->w, texture->h, bpp, Rmask, + Gmask, Bmask, Amask); + if (!swdata->stretch) { + return (-1); + } + } + pixels = swdata->stretch->pixels; + pitch = swdata->stretch->pitch; + } + switch (texture->format) { + case SDL_PixelFormat_YV12: + lum = swdata->planes[0]; + Cr = swdata->planes[1]; + Cb = swdata->planes[2]; + break; + case SDL_PixelFormat_IYUV: + lum = swdata->planes[0]; + Cr = swdata->planes[2]; + Cb = swdata->planes[1]; + break; + case SDL_PixelFormat_YUY2: + lum = swdata->planes[0]; + Cr = lum + 3; + Cb = lum + 1; + break; + case SDL_PixelFormat_UYVY: + lum = swdata->planes[0] + 1; + Cr = lum + 1; + Cb = lum - 1; + break; + case SDL_PixelFormat_YVYU: + lum = swdata->planes[0]; + Cr = lum + 1; + Cb = lum + 3; + break; + default: + SDL_SetError("Unsupported YUV format in copy"); + return (-1); + } + mod = (pitch / SDL_BYTESPERPIXEL(target_format)); + + if (scale_2x) { + mod -= (texture->w * 2); + swdata->Display2X(swdata->colortab, swdata->rgb_2_pix, + lum, Cr, Cb, pixels, texture->h, texture->w, mod); + } else { + mod -= texture->w; + swdata->Display1X(swdata->colortab, swdata->rgb_2_pix, + lum, Cr, Cb, pixels, texture->h, texture->w, mod); + } + if (stretch) { + SDL_Rect rect = *srcrect; + SDL_SoftStretch(swdata->stretch, &rect, swdata->display, NULL); + } + return 0; } -void SDL_FreeYUV_SW(_THIS, SDL_Overlay *overlay) +void +SDL_SW_DestroyYUVTexture(SDL_SW_YUVTexture * swdata) { - struct private_yuvhwdata *swdata; - - swdata = overlay->hwdata; - if ( swdata ) { - if ( swdata->stretch ) { - SDL_FreeSurface(swdata->stretch); - } - if ( swdata->pixels ) { - SDL_free(swdata->pixels); - } - if ( swdata->colortab ) { - SDL_free(swdata->colortab); - } - if ( swdata->rgb_2_pix ) { - SDL_free(swdata->rgb_2_pix); - } - SDL_free(swdata); - } + if (swdata) { + if (swdata->pixels) { + SDL_free(swdata->pixels); + } + if (swdata->colortab) { + SDL_free(swdata->colortab); + } + if (swdata->rgb_2_pix) { + SDL_free(swdata->rgb_2_pix); + } + if (swdata->stretch) { + SDL_FreeSurface(swdata->stretch); + } + if (swdata->display) { + SDL_FreeSurface(swdata->display); + } + SDL_free(swdata); + } } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/SDL_yuv_sw_c.h b/src/video/SDL_yuv_sw_c.h index 39df51d7f..739679b9c 100644 --- a/src/video/SDL_yuv_sw_c.h +++ b/src/video/SDL_yuv_sw_c.h @@ -24,14 +24,21 @@ #include "SDL_video.h" #include "SDL_sysvideo.h" -/* This is the software implementation of the YUV video overlay support */ - -extern SDL_Overlay *SDL_CreateYUV_SW(_THIS, int width, int height, Uint32 format, SDL_Surface *display); - -extern int SDL_LockYUV_SW(_THIS, SDL_Overlay *overlay); - -extern void SDL_UnlockYUV_SW(_THIS, SDL_Overlay *overlay); - -extern int SDL_DisplayYUV_SW(_THIS, SDL_Overlay *overlay, SDL_Rect *src, SDL_Rect *dst); - -extern void SDL_FreeYUV_SW(_THIS, SDL_Overlay *overlay); +/* This is the software implementation of the YUV texture support */ + +typedef struct SDL_SW_YUVTexture SDL_SW_YUVTexture; + +SDL_SW_YUVTexture *SDL_SW_CreateYUVTexture(SDL_Texture * texture); +int SDL_SW_QueryYUVTexturePixels(SDL_SW_YUVTexture * swdata, void **pixels, + int *pitch); +int SDL_SW_UpdateYUVTexture(SDL_SW_YUVTexture * swdata, const SDL_Rect * rect, + const void *pixels, int pitch); +int SDL_SW_LockYUVTexture(SDL_SW_YUVTexture * swdata, const SDL_Rect * rect, + int markDirty, void **pixels, int *pitch); +void SDL_SW_UnlockYUVTexture(SDL_SW_YUVTexture * swdata); +int SDL_SW_CopyYUVToRGB(SDL_SW_YUVTexture * swdata, const SDL_Rect * srcrect, + Uint32 target_format, int w, int h, void *pixels, + int pitch); +void SDL_SW_DestroyYUVTexture(SDL_SW_YUVTexture * swdata); + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/Xext/XME/xme.c b/src/video/Xext/XME/xme.c index 0a7379642..ea0946694 100644 --- a/src/video/Xext/XME/xme.c +++ b/src/video/Xext/XME/xme.c @@ -49,124 +49,135 @@ /*******************************************************************/ -typedef struct { - CARD8 reqType; /* always codes->major_opcode */ - CARD8 xigmiscReqType; /* always X_XiGMiscQueryVersion */ - CARD16 length; - CARD16 major; - CARD16 minor; +typedef struct +{ + CARD8 reqType; /* always codes->major_opcode */ + CARD8 xigmiscReqType; /* always X_XiGMiscQueryVersion */ + CARD16 length; + CARD16 major; + CARD16 minor; } xXiGMiscQueryVersionReq; -typedef struct { - CARD8 reqType; /* always codes->major_opcode */ - CARD8 xigmiscReqType; /* always X_XiGMiscQueryViews */ - CARD16 length; - CARD8 screen; - CARD8 pad0; - CARD16 pad1; +typedef struct +{ + CARD8 reqType; /* always codes->major_opcode */ + CARD8 xigmiscReqType; /* always X_XiGMiscQueryViews */ + CARD16 length; + CARD8 screen; + CARD8 pad0; + CARD16 pad1; } xXiGMiscQueryViewsReq; -typedef struct { - CARD8 reqType; /* always codes->major_opcode */ - CARD8 xigmiscReqType; /* always X_XiGMiscQueryResolutions */ - CARD16 length; - CARD8 screen; - CARD8 view; - CARD16 pad0; +typedef struct +{ + CARD8 reqType; /* always codes->major_opcode */ + CARD8 xigmiscReqType; /* always X_XiGMiscQueryResolutions */ + CARD16 length; + CARD8 screen; + CARD8 view; + CARD16 pad0; } xXiGMiscQueryResolutionsReq; -typedef struct { - CARD8 reqType; /* always codes->major_opcode */ - CARD8 xigmiscReqType; /* always X_XiGMiscChangeResolution */ - CARD16 length; - CARD8 screen; - CARD8 view; - CARD16 pad0; - CARD16 width; - CARD16 height; - INT32 refresh; +typedef struct +{ + CARD8 reqType; /* always codes->major_opcode */ + CARD8 xigmiscReqType; /* always X_XiGMiscChangeResolution */ + CARD16 length; + CARD8 screen; + CARD8 view; + CARD16 pad0; + CARD16 width; + CARD16 height; + INT32 refresh; } xXiGMiscChangeResolutionReq; -typedef struct { - CARD8 reqType; /* always codes->major_opcode */ - CARD8 xigmiscReqType; /* always X_XiGMiscFullScreen */ - CARD16 length; - CARD8 screen; - CARD8 pad0; - CARD16 pad1; - CARD32 window; - CARD32 cmap; +typedef struct +{ + CARD8 reqType; /* always codes->major_opcode */ + CARD8 xigmiscReqType; /* always X_XiGMiscFullScreen */ + CARD16 length; + CARD8 screen; + CARD8 pad0; + CARD16 pad1; + CARD32 window; + CARD32 cmap; } xXiGMiscFullScreenReq; /*******************************************************************/ -typedef struct { - BYTE type; /* X_Reply */ - CARD8 pad0; - CARD16 sequenceNumber; - CARD32 length; - CARD16 major; - CARD16 minor; - CARD32 pad1; - CARD32 pad2; - CARD32 pad3; - CARD32 pad4; - CARD32 pad5; +typedef struct +{ + BYTE type; /* X_Reply */ + CARD8 pad0; + CARD16 sequenceNumber; + CARD32 length; + CARD16 major; + CARD16 minor; + CARD32 pad1; + CARD32 pad2; + CARD32 pad3; + CARD32 pad4; + CARD32 pad5; } xXiGMiscQueryVersionReply; -typedef struct { - BYTE type; /* X_Reply */ - CARD8 pad0; - CARD16 sequenceNumber; - CARD32 length; - CARD32 nviews; - CARD32 pad1; - CARD32 pad2; - CARD32 pad3; - CARD32 pad4; - CARD32 pad5; +typedef struct +{ + BYTE type; /* X_Reply */ + CARD8 pad0; + CARD16 sequenceNumber; + CARD32 length; + CARD32 nviews; + CARD32 pad1; + CARD32 pad2; + CARD32 pad3; + CARD32 pad4; + CARD32 pad5; } xXiGMiscQueryViewsReply; -typedef struct { - BYTE type; /* X_Reply */ - CARD8 pad0; - CARD16 sequenceNumber; - CARD32 length; - CARD16 active; - CARD16 nresolutions; - CARD32 pad1; - CARD32 pad2; - CARD32 pad3; - CARD32 pad4; - CARD32 pad5; +typedef struct +{ + BYTE type; /* X_Reply */ + CARD8 pad0; + CARD16 sequenceNumber; + CARD32 length; + CARD16 active; + CARD16 nresolutions; + CARD32 pad1; + CARD32 pad2; + CARD32 pad3; + CARD32 pad4; + CARD32 pad5; } xXiGMiscQueryResolutionsReply; -typedef struct { - BYTE type; /* X_Reply */ - BOOL success; - CARD16 sequenceNumber; - CARD32 length; - CARD32 pad1; - CARD32 pad2; - CARD32 pad3; - CARD32 pad4; - CARD32 pad5; - CARD32 pad6; +typedef struct +{ + BYTE type; /* X_Reply */ + BOOL success; + CARD16 sequenceNumber; + CARD32 length; + CARD32 pad1; + CARD32 pad2; + CARD32 pad3; + CARD32 pad4; + CARD32 pad5; + CARD32 pad6; } xXiGMiscFullScreenReply; /*******************************************************************/ -typedef struct { - INT16 x; - INT16 y; - CARD16 w; - CARD16 h; +typedef struct +{ + INT16 x; + INT16 y; + CARD16 w; + CARD16 h; } XiGMiscViewInfo; -typedef struct { - CARD16 width; - CARD16 height; - INT32 refresh; +typedef struct +{ + CARD16 width; + CARD16 height; + INT32 refresh; } XiGMiscResolutionInfo; /*****************************************************************************/ @@ -204,192 +215,197 @@ static char *xigmisc_extension_name = XIGMISC_PROTOCOL_NAME; static int XiGMiscCloseDisplay(); static XExtensionHooks xigmisc_extension_hooks = { - NULL, /* create_gc */ - NULL, /* copy_gc */ - NULL, /* flush_gc */ - NULL, /* free_gc */ - NULL, /* create_font */ - NULL, /* free_font */ - XiGMiscCloseDisplay, /* close_display */ - NULL, /* wire_to_event */ - NULL, /* event_to_wire */ - NULL, /* error */ - NULL, /* error_string */ + NULL, /* create_gc */ + NULL, /* copy_gc */ + NULL, /* flush_gc */ + NULL, /* free_gc */ + NULL, /* create_font */ + NULL, /* free_font */ + XiGMiscCloseDisplay, /* close_display */ + NULL, /* wire_to_event */ + NULL, /* event_to_wire */ + NULL, /* error */ + NULL, /* error_string */ }; -static XEXT_GENERATE_CLOSE_DISPLAY (XiGMiscCloseDisplay, xigmisc_info) - -static XEXT_GENERATE_FIND_DISPLAY (XiGMiscFindDisplay, xigmisc_info, - xigmisc_extension_name, - &xigmisc_extension_hooks, XiGMiscNumberEvents, NULL) - - +static +XEXT_GENERATE_CLOSE_DISPLAY(XiGMiscCloseDisplay, xigmisc_info) + static XEXT_GENERATE_FIND_DISPLAY(XiGMiscFindDisplay, xigmisc_info, + xigmisc_extension_name, + &xigmisc_extension_hooks, + XiGMiscNumberEvents, NULL) /*****************************************************************************/ - -Bool XiGMiscQueryVersion(Display *dpy, int *major, int *minor) + Bool XiGMiscQueryVersion(Display * dpy, int *major, int *minor) { - int opcode, event, error; - xXiGMiscQueryVersionReq *req; - xXiGMiscQueryVersionReply rep; - XExtDisplayInfo *info = XiGMiscFindDisplay(dpy); + int opcode, event, error; + xXiGMiscQueryVersionReq *req; + xXiGMiscQueryVersionReply rep; + XExtDisplayInfo *info = XiGMiscFindDisplay(dpy); - if (!XQueryExtension(dpy, XIGMISC_PROTOCOL_NAME, &opcode, &event, &error)) - return xFalse; + if (!XQueryExtension(dpy, XIGMISC_PROTOCOL_NAME, &opcode, &event, &error)) + return xFalse; - XiGMiscCheckExtension(dpy, info, xFalse); + XiGMiscCheckExtension(dpy, info, xFalse); - LockDisplay (dpy); - XiGMiscGetReq (XiGMiscQueryVersion, req, info); + LockDisplay(dpy); + XiGMiscGetReq(XiGMiscQueryVersion, req, info); - req->major = XIGMISC_MAJOR_VERSION; - req->minor = XIGMISC_MINOR_VERSION; + req->major = XIGMISC_MAJOR_VERSION; + req->minor = XIGMISC_MINOR_VERSION; - if (!_XReply (dpy, (xReply *)&rep, 0, xTrue)) { + if (!_XReply(dpy, (xReply *) & rep, 0, xTrue)) { + UnlockDisplay(dpy); + SyncHandle(); + return xFalse; + } + + *major = rep.major; + *minor = rep.minor; UnlockDisplay(dpy); SyncHandle(); - return xFalse; - } - *major = rep.major; - *minor = rep.minor; - UnlockDisplay(dpy); - SyncHandle(); - - return xTrue; + return xTrue; } -int XiGMiscQueryViews(Display *dpy, int screen, XiGMiscViewInfo **pviews) +int +XiGMiscQueryViews(Display * dpy, int screen, XiGMiscViewInfo ** pviews) { - int n, size; - XiGMiscViewInfo *views; - xXiGMiscQueryViewsReq *req; - xXiGMiscQueryViewsReply rep; - XExtDisplayInfo *info = XiGMiscFindDisplay(dpy); - XiGMiscCheckExtension(dpy, info, 0); - - LockDisplay (dpy); - XiGMiscGetReq (XiGMiscQueryViews, req, info); - req->screen = screen; - - if (!_XReply (dpy, (xReply *)&rep, 0, xFalse)) { - UnlockDisplay(dpy); - SyncHandle(); - return 0; - } - - n = rep.nviews; - - if (n > 0) { - size = sizeof(XiGMiscViewInfo) * n; - views = (XiGMiscViewInfo*)Xmalloc(size); - if (!views) { - _XEatData(dpy, (unsigned long)size); - UnlockDisplay(dpy); - SyncHandle(); - return 0; + int n, size; + XiGMiscViewInfo *views; + xXiGMiscQueryViewsReq *req; + xXiGMiscQueryViewsReply rep; + XExtDisplayInfo *info = XiGMiscFindDisplay(dpy); + XiGMiscCheckExtension(dpy, info, 0); + + LockDisplay(dpy); + XiGMiscGetReq(XiGMiscQueryViews, req, info); + req->screen = screen; + + if (!_XReply(dpy, (xReply *) & rep, 0, xFalse)) { + UnlockDisplay(dpy); + SyncHandle(); + return 0; } - _XReadPad(dpy, (void*)views, size); + n = rep.nviews; - *pviews = views; - } + if (n > 0) { + size = sizeof(XiGMiscViewInfo) * n; + views = (XiGMiscViewInfo *) Xmalloc(size); + if (!views) { + _XEatData(dpy, (unsigned long) size); + UnlockDisplay(dpy); + SyncHandle(); + return 0; + } - UnlockDisplay(dpy); - SyncHandle(); + _XReadPad(dpy, (void *) views, size); - return n; -} + *pviews = views; + } -int XiGMiscQueryResolutions(Display *dpy, int screen, int view, int *pactive, XiGMiscResolutionInfo **presolutions) -{ - int n, size; - XiGMiscResolutionInfo *resolutions; - xXiGMiscQueryResolutionsReq *req; - xXiGMiscQueryResolutionsReply rep; - XExtDisplayInfo *info = XiGMiscFindDisplay(dpy); - XiGMiscCheckExtension(dpy, info, 0); - - LockDisplay (dpy); - XiGMiscGetReq (XiGMiscQueryResolutions, req, info); - req->screen = screen; - req->view = view; - - if (!_XReply (dpy, (xReply *)&rep, 0, xFalse)) { UnlockDisplay(dpy); SyncHandle(); - return 0; - } - - n = rep.nresolutions; - - if (n > 0) { - size = sizeof(XiGMiscResolutionInfo) * n; - resolutions = (XiGMiscResolutionInfo*)Xmalloc(size); - if (!resolutions) { - _XEatData(dpy, (unsigned long)size); - UnlockDisplay(dpy); - SyncHandle(); - return 0; + + return n; +} + +int +XiGMiscQueryResolutions(Display * dpy, int screen, int view, int *pactive, + XiGMiscResolutionInfo ** presolutions) +{ + int n, size; + XiGMiscResolutionInfo *resolutions; + xXiGMiscQueryResolutionsReq *req; + xXiGMiscQueryResolutionsReply rep; + XExtDisplayInfo *info = XiGMiscFindDisplay(dpy); + XiGMiscCheckExtension(dpy, info, 0); + + LockDisplay(dpy); + XiGMiscGetReq(XiGMiscQueryResolutions, req, info); + req->screen = screen; + req->view = view; + + if (!_XReply(dpy, (xReply *) & rep, 0, xFalse)) { + UnlockDisplay(dpy); + SyncHandle(); + return 0; } - _XReadPad(dpy, (void*)resolutions, size); + n = rep.nresolutions; - *presolutions = resolutions; - *pactive = rep.active; - } + if (n > 0) { + size = sizeof(XiGMiscResolutionInfo) * n; + resolutions = (XiGMiscResolutionInfo *) Xmalloc(size); + if (!resolutions) { + _XEatData(dpy, (unsigned long) size); + UnlockDisplay(dpy); + SyncHandle(); + return 0; + } - UnlockDisplay(dpy); - SyncHandle(); + _XReadPad(dpy, (void *) resolutions, size); + + *presolutions = resolutions; + *pactive = rep.active; + } - return n; + UnlockDisplay(dpy); + SyncHandle(); + + return n; } -void XiGMiscChangeResolution(Display *dpy, int screen, int view, int width, int height, int refresh) +void +XiGMiscChangeResolution(Display * dpy, int screen, int view, int width, + int height, int refresh) { - xXiGMiscChangeResolutionReq *req; - XExtDisplayInfo *info = XiGMiscFindDisplay(dpy); + xXiGMiscChangeResolutionReq *req; + XExtDisplayInfo *info = XiGMiscFindDisplay(dpy); - XiGMiscSimpleCheckExtension(dpy, info); + XiGMiscSimpleCheckExtension(dpy, info); - LockDisplay (dpy); - XiGMiscGetReq (XiGMiscChangeResolution, req, info); - req->screen = screen; - req->view = view; - req->width = width; - req->height = height; - req->refresh = refresh; + LockDisplay(dpy); + XiGMiscGetReq(XiGMiscChangeResolution, req, info); + req->screen = screen; + req->view = view; + req->width = width; + req->height = height; + req->refresh = refresh; - UnlockDisplay(dpy); - SyncHandle(); + UnlockDisplay(dpy); + SyncHandle(); } -Bool XiGMiscFullScreen(Display *dpy, int screen, XID window, XID cmap) +Bool +XiGMiscFullScreen(Display * dpy, int screen, XID window, XID cmap) { - xXiGMiscFullScreenReq *req; - xXiGMiscFullScreenReply rep; - XExtDisplayInfo *info = XiGMiscFindDisplay(dpy); - - XiGMiscCheckExtension(dpy, info, xFalse); - - LockDisplay (dpy); - XiGMiscGetReq (XiGMiscFullScreen, req, info); - req->screen = screen; - req->pad0 = 0; - req->pad1 = 0; - req->window = window; - req->cmap = cmap; + xXiGMiscFullScreenReq *req; + xXiGMiscFullScreenReply rep; + XExtDisplayInfo *info = XiGMiscFindDisplay(dpy); + + XiGMiscCheckExtension(dpy, info, xFalse); + + LockDisplay(dpy); + XiGMiscGetReq(XiGMiscFullScreen, req, info); + req->screen = screen; + req->pad0 = 0; + req->pad1 = 0; + req->window = window; + req->cmap = cmap; + + if (!_XReply(dpy, (xReply *) & rep, 0, xTrue)) { + UnlockDisplay(dpy); + SyncHandle(); + return xFalse; + } - if (!_XReply (dpy, (xReply *)&rep, 0, xTrue)) { UnlockDisplay(dpy); SyncHandle(); - return xFalse; - } - - UnlockDisplay(dpy); - SyncHandle(); - return (rep.success ? xTrue : xFalse); + return (rep.success ? xTrue : xFalse); } +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/Xext/Xinerama/Xinerama.c b/src/video/Xext/Xinerama/Xinerama.c index 049be45c2..76b8ca977 100644 --- a/src/video/Xext/Xinerama/Xinerama.c +++ b/src/video/Xext/Xinerama/Xinerama.c @@ -31,9 +31,9 @@ Equipment Corporation. #include #include #include "../extensions/Xext.h" -#include "../extensions/extutil.h" /* in ../include */ +#include "../extensions/extutil.h" /* in ../include */ #include "../extensions/panoramiXext.h" -#include "../extensions/panoramiXproto.h" /* in ../include */ +#include "../extensions/panoramiXproto.h" /* in ../include */ #include "../extensions/Xinerama.h" static XExtensionInfo _panoramiX_ext_info_data; @@ -47,174 +47,163 @@ static /* const */ char *panoramiX_extension_name = PANORAMIX_PROTOCOL_NAME; static int close_display(); static /* const */ XExtensionHooks panoramiX_extension_hooks = { - NULL, /* create_gc */ - NULL, /* copy_gc */ - NULL, /* flush_gc */ - NULL, /* free_gc */ - NULL, /* create_font */ - NULL, /* free_font */ - close_display, /* close_display */ - NULL, /* wire_to_event */ - NULL, /* event_to_wire */ - NULL, /* error */ - NULL, /* error_string */ + NULL, /* create_gc */ + NULL, /* copy_gc */ + NULL, /* flush_gc */ + NULL, /* free_gc */ + NULL, /* create_font */ + NULL, /* free_font */ + close_display, /* close_display */ + NULL, /* wire_to_event */ + NULL, /* event_to_wire */ + NULL, /* error */ + NULL, /* error_string */ }; -static XEXT_GENERATE_FIND_DISPLAY (find_display, panoramiX_ext_info, - panoramiX_extension_name, - &panoramiX_extension_hooks, - 0, NULL) - -static XEXT_GENERATE_CLOSE_DISPLAY (close_display, panoramiX_ext_info) - - - +static +XEXT_GENERATE_FIND_DISPLAY(find_display, panoramiX_ext_info, + panoramiX_extension_name, + &panoramiX_extension_hooks, 0, NULL) + static XEXT_GENERATE_CLOSE_DISPLAY(close_display, panoramiX_ext_info) /**************************************************************************** * * * PanoramiX public interfaces * * * ****************************************************************************/ - -Bool SDL_NAME(XPanoramiXQueryExtension) ( - Display *dpy, - int *event_basep, - int *error_basep -) + Bool SDL_NAME(XPanoramiXQueryExtension) (Display * dpy, + int *event_basep, + int *error_basep) { - XExtDisplayInfo *info = find_display (dpy); + XExtDisplayInfo *info = find_display(dpy); if (XextHasExtension(info)) { - *event_basep = info->codes->first_event; - *error_basep = info->codes->first_error; - return True; + *event_basep = info->codes->first_event; + *error_basep = info->codes->first_error; + return True; } else { - return False; + return False; } } -Status SDL_NAME(XPanoramiXQueryVersion)( - Display *dpy, - int *major_versionp, - int *minor_versionp -) +Status SDL_NAME(XPanoramiXQueryVersion) (Display * dpy, + int *major_versionp, + int *minor_versionp) { - XExtDisplayInfo *info = find_display (dpy); - xPanoramiXQueryVersionReply rep; - register xPanoramiXQueryVersionReq *req; + XExtDisplayInfo *info = find_display(dpy); + xPanoramiXQueryVersionReply rep; + register xPanoramiXQueryVersionReq *req; - PanoramiXCheckExtension (dpy, info, 0); + PanoramiXCheckExtension(dpy, info, 0); - LockDisplay (dpy); - GetReq (PanoramiXQueryVersion, req); + LockDisplay(dpy); + GetReq(PanoramiXQueryVersion, req); req->reqType = info->codes->major_opcode; req->panoramiXReqType = X_PanoramiXQueryVersion; req->clientMajor = PANORAMIX_MAJOR_VERSION; req->clientMinor = PANORAMIX_MINOR_VERSION; - if (!_XReply (dpy, (xReply *) &rep, 0, xTrue)) { - UnlockDisplay (dpy); - SyncHandle (); - return 0; + if (!_XReply(dpy, (xReply *) & rep, 0, xTrue)) { + UnlockDisplay(dpy); + SyncHandle(); + return 0; } *major_versionp = rep.majorVersion; *minor_versionp = rep.minorVersion; - UnlockDisplay (dpy); - SyncHandle (); + UnlockDisplay(dpy); + SyncHandle(); return 1; } -SDL_NAME(XPanoramiXInfo) *SDL_NAME(XPanoramiXAllocInfo)(void) +SDL_NAME(XPanoramiXInfo) * SDL_NAME(XPanoramiXAllocInfo) (void) { - return (SDL_NAME(XPanoramiXInfo) *) Xmalloc (sizeof (SDL_NAME(XPanoramiXInfo))); + return (SDL_NAME(XPanoramiXInfo) *) + Xmalloc(sizeof(SDL_NAME(XPanoramiXInfo))); } -Status SDL_NAME(XPanoramiXGetState) ( - Display *dpy, - Drawable drawable, - SDL_NAME(XPanoramiXInfo) *panoramiX_info -) +Status SDL_NAME(XPanoramiXGetState) (Display * dpy, + Drawable drawable, + SDL_NAME(XPanoramiXInfo) * + panoramiX_info) { - XExtDisplayInfo *info = find_display (dpy); - xPanoramiXGetStateReply rep; - register xPanoramiXGetStateReq *req; + XExtDisplayInfo *info = find_display(dpy); + xPanoramiXGetStateReply rep; + register xPanoramiXGetStateReq *req; - PanoramiXCheckExtension (dpy, info, 0); + PanoramiXCheckExtension(dpy, info, 0); - LockDisplay (dpy); - GetReq (PanoramiXGetState, req); + LockDisplay(dpy); + GetReq(PanoramiXGetState, req); req->reqType = info->codes->major_opcode; req->panoramiXReqType = X_PanoramiXGetState; req->window = drawable; - if (!_XReply (dpy, (xReply *) &rep, 0, xTrue)) { - UnlockDisplay (dpy); - SyncHandle (); - return 0; + if (!_XReply(dpy, (xReply *) & rep, 0, xTrue)) { + UnlockDisplay(dpy); + SyncHandle(); + return 0; } - UnlockDisplay (dpy); - SyncHandle (); + UnlockDisplay(dpy); + SyncHandle(); panoramiX_info->window = rep.window; panoramiX_info->State = rep.state; return 1; } -Status SDL_NAME(XPanoramiXGetScreenCount) ( - Display *dpy, - Drawable drawable, - SDL_NAME(XPanoramiXInfo) *panoramiX_info -) +Status SDL_NAME(XPanoramiXGetScreenCount) (Display * dpy, + Drawable drawable, + SDL_NAME(XPanoramiXInfo) * + panoramiX_info) { - XExtDisplayInfo *info = find_display (dpy); - xPanoramiXGetScreenCountReply rep; - register xPanoramiXGetScreenCountReq *req; + XExtDisplayInfo *info = find_display(dpy); + xPanoramiXGetScreenCountReply rep; + register xPanoramiXGetScreenCountReq *req; - PanoramiXCheckExtension (dpy, info, 0); + PanoramiXCheckExtension(dpy, info, 0); - LockDisplay (dpy); - GetReq (PanoramiXGetScreenCount, req); + LockDisplay(dpy); + GetReq(PanoramiXGetScreenCount, req); req->reqType = info->codes->major_opcode; req->panoramiXReqType = X_PanoramiXGetScreenCount; req->window = drawable; - if (!_XReply (dpy, (xReply *) &rep, 0, xTrue)) { - UnlockDisplay (dpy); - SyncHandle (); - return 0; + if (!_XReply(dpy, (xReply *) & rep, 0, xTrue)) { + UnlockDisplay(dpy); + SyncHandle(); + return 0; } - UnlockDisplay (dpy); - SyncHandle (); + UnlockDisplay(dpy); + SyncHandle(); panoramiX_info->window = rep.window; panoramiX_info->ScreenCount = rep.ScreenCount; return 1; } -Status SDL_NAME(XPanoramiXGetScreenSize) ( - Display *dpy, - Drawable drawable, - int screen_num, - SDL_NAME(XPanoramiXInfo) *panoramiX_info -) +Status SDL_NAME(XPanoramiXGetScreenSize) (Display * dpy, + Drawable drawable, + int screen_num, + SDL_NAME(XPanoramiXInfo) * + panoramiX_info) { - XExtDisplayInfo *info = find_display (dpy); - xPanoramiXGetScreenSizeReply rep; - register xPanoramiXGetScreenSizeReq *req; + XExtDisplayInfo *info = find_display(dpy); + xPanoramiXGetScreenSizeReply rep; + register xPanoramiXGetScreenSizeReq *req; - PanoramiXCheckExtension (dpy, info, 0); + PanoramiXCheckExtension(dpy, info, 0); - LockDisplay (dpy); - GetReq (PanoramiXGetScreenSize, req); + LockDisplay(dpy); + GetReq(PanoramiXGetScreenSize, req); req->reqType = info->codes->major_opcode; req->panoramiXReqType = X_PanoramiXGetScreenSize; req->window = drawable; - req->screen = screen_num; /* need to define */ - if (!_XReply (dpy, (xReply *) &rep, 0, xTrue)) { - UnlockDisplay (dpy); - SyncHandle (); - return 0; + req->screen = screen_num; /* need to define */ + if (!_XReply(dpy, (xReply *) & rep, 0, xTrue)) { + UnlockDisplay(dpy); + SyncHandle(); + return 0; } - UnlockDisplay (dpy); - SyncHandle (); + UnlockDisplay(dpy); + SyncHandle(); panoramiX_info->window = rep.window; panoramiX_info->screen = rep.screen; - panoramiX_info->width = rep.width; + panoramiX_info->width = rep.width; panoramiX_info->height = rep.height; return 1; } @@ -225,95 +214,85 @@ Status SDL_NAME(XPanoramiXGetScreenSize) ( in the "Xinerama" namespace instead of "PanoramiX". \*******************************************************************/ -Bool SDL_NAME(XineramaQueryExtension) ( - Display *dpy, - int *event_base, - int *error_base -) +Bool SDL_NAME(XineramaQueryExtension) (Display * dpy, + int *event_base, int *error_base) { - return SDL_NAME(XPanoramiXQueryExtension)(dpy, event_base, error_base); + return SDL_NAME(XPanoramiXQueryExtension) (dpy, event_base, error_base); } -Status SDL_NAME(XineramaQueryVersion)( - Display *dpy, - int *major, - int *minor -) +Status SDL_NAME(XineramaQueryVersion) (Display * dpy, int *major, int *minor) { - return SDL_NAME(XPanoramiXQueryVersion)(dpy, major, minor); + return SDL_NAME(XPanoramiXQueryVersion) (dpy, major, minor); } -Bool SDL_NAME(XineramaIsActive)(Display *dpy) +Bool SDL_NAME(XineramaIsActive) (Display * dpy) { - xXineramaIsActiveReply rep; - xXineramaIsActiveReq *req; - XExtDisplayInfo *info = find_display (dpy); + xXineramaIsActiveReply rep; + xXineramaIsActiveReq *req; + XExtDisplayInfo *info = find_display(dpy); - if(!XextHasExtension(info)) - return False; /* server doesn't even have the extension */ + if (!XextHasExtension(info)) + return False; /* server doesn't even have the extension */ - LockDisplay (dpy); - GetReq (XineramaIsActive, req); + LockDisplay(dpy); + GetReq(XineramaIsActive, req); req->reqType = info->codes->major_opcode; req->panoramiXReqType = X_XineramaIsActive; - if (!_XReply (dpy, (xReply *) &rep, 0, xTrue)) { - UnlockDisplay (dpy); - SyncHandle (); - return False; + if (!_XReply(dpy, (xReply *) & rep, 0, xTrue)) { + UnlockDisplay(dpy); + SyncHandle(); + return False; } - UnlockDisplay (dpy); - SyncHandle (); + UnlockDisplay(dpy); + SyncHandle(); return rep.state; } #include -SDL_NAME(XineramaScreenInfo) * -SDL_NAME(XineramaQueryScreens)( - Display *dpy, - int *number -) +SDL_NAME(XineramaScreenInfo) * +SDL_NAME(XineramaQueryScreens) (Display * dpy, int *number) { - XExtDisplayInfo *info = find_display (dpy); - xXineramaQueryScreensReply rep; - xXineramaQueryScreensReq *req; - SDL_NAME(XineramaScreenInfo) *scrnInfo = NULL; + XExtDisplayInfo *info = find_display(dpy); + xXineramaQueryScreensReply rep; + xXineramaQueryScreensReq *req; + SDL_NAME(XineramaScreenInfo) * scrnInfo = NULL; - PanoramiXCheckExtension (dpy, info, 0); + PanoramiXCheckExtension(dpy, info, 0); - LockDisplay (dpy); - GetReq (XineramaQueryScreens, req); + LockDisplay(dpy); + GetReq(XineramaQueryScreens, req); req->reqType = info->codes->major_opcode; req->panoramiXReqType = X_XineramaQueryScreens; - if (!_XReply (dpy, (xReply *) &rep, 0, xFalse)) { - UnlockDisplay (dpy); - SyncHandle (); - return NULL; + if (!_XReply(dpy, (xReply *) & rep, 0, xFalse)) { + UnlockDisplay(dpy); + SyncHandle(); + return NULL; } - if(rep.number) { - if((scrnInfo = Xmalloc(sizeof(SDL_NAME(XineramaScreenInfo)) * rep.number))) { - xXineramaScreenInfo scratch; - int i; - - for(i = 0; i < rep.number; i++) { - _XRead(dpy, (char*)(&scratch), sz_XineramaScreenInfo); - scrnInfo[i].screen_number = i; - scrnInfo[i].x_org = scratch.x_org; - scrnInfo[i].y_org = scratch.y_org; - scrnInfo[i].width = scratch.width; - scrnInfo[i].height = scratch.height; - } - - *number = rep.number; - } else - _XEatData(dpy, rep.length << 2); + if (rep.number) { + if ((scrnInfo = + Xmalloc(sizeof(SDL_NAME(XineramaScreenInfo)) * rep.number))) { + xXineramaScreenInfo scratch; + int i; + + for (i = 0; i < rep.number; i++) { + _XRead(dpy, (char *) (&scratch), sz_XineramaScreenInfo); + scrnInfo[i].screen_number = i; + scrnInfo[i].x_org = scratch.x_org; + scrnInfo[i].y_org = scratch.y_org; + scrnInfo[i].width = scratch.width; + scrnInfo[i].height = scratch.height; + } + + *number = rep.number; + } else + _XEatData(dpy, rep.length << 2); } - UnlockDisplay (dpy); - SyncHandle (); + UnlockDisplay(dpy); + SyncHandle(); return scrnInfo; } - - +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/Xext/Xv/Xv.c b/src/video/Xext/Xv/Xv.c index 7147b9e8c..e7319e96e 100644 --- a/src/video/Xext/Xv/Xv.c +++ b/src/video/Xext/Xv/Xv.c @@ -68,1084 +68,1030 @@ static int xv_close_display(); static Bool xv_wire_to_event(); static XExtensionHooks xv_extension_hooks = { - NULL, /* create_gc */ - NULL, /* copy_gc */ - NULL, /* flush_gc */ - NULL, /* free_gc */ - NULL, /* create_font */ - NULL, /* free_font */ - xv_close_display, /* close_display */ - xv_wire_to_event, /* wire_to_event */ - NULL, /* event_to_wire */ - NULL, /* error */ - xv_error_string /* error_string */ + NULL, /* create_gc */ + NULL, /* copy_gc */ + NULL, /* flush_gc */ + NULL, /* free_gc */ + NULL, /* create_font */ + NULL, /* free_font */ + xv_close_display, /* close_display */ + xv_wire_to_event, /* wire_to_event */ + NULL, /* event_to_wire */ + NULL, /* error */ + xv_error_string /* error_string */ }; -static char *xv_error_list[] = -{ - "BadPort", /* XvBadPort */ - "BadEncoding", /* XvBadEncoding */ - "BadControl" /* XvBadControl */ +static char *xv_error_list[] = { + "BadPort", /* XvBadPort */ + "BadEncoding", /* XvBadEncoding */ + "BadControl" /* XvBadControl */ }; -static XEXT_GENERATE_CLOSE_DISPLAY (xv_close_display, xv_info) +static +XEXT_GENERATE_CLOSE_DISPLAY(xv_close_display, xv_info) + static XEXT_GENERATE_FIND_DISPLAY(xv_find_display, xv_info, + xv_extension_name, + &xv_extension_hooks, XvNumEvents, NULL) + static XEXT_GENERATE_ERROR_STRING(xv_error_string, xv_extension_name, + XvNumErrors, xv_error_list) + int SDL_NAME(XvQueryExtension) (Display * dpy, + unsigned int *p_version, + unsigned int *p_revision, + unsigned int *p_requestBase, + unsigned int *p_eventBase, + unsigned int *p_errorBase) +{ + XExtDisplayInfo *info = xv_find_display(dpy); + xvQueryExtensionReq *req; + xvQueryExtensionReply rep; + + XvCheckExtension(dpy, info, XvBadExtension); + LockDisplay(dpy); -static XEXT_GENERATE_FIND_DISPLAY (xv_find_display, xv_info, - xv_extension_name, - &xv_extension_hooks, - XvNumEvents, NULL) - + XvGetReq(QueryExtension, req); -static XEXT_GENERATE_ERROR_STRING (xv_error_string, xv_extension_name, - XvNumErrors, xv_error_list) + if (!_XReply(dpy, (xReply *) & rep, 0, xFalse)) { + UnlockDisplay(dpy); + SyncHandle(); + return XvBadExtension; + } + *p_version = rep.version; + *p_revision = rep.revision; + *p_requestBase = info->codes->major_opcode; + *p_eventBase = info->codes->first_event; + *p_errorBase = info->codes->first_error; -int -SDL_NAME(XvQueryExtension)( - Display *dpy, - unsigned int *p_version, - unsigned int *p_revision, - unsigned int *p_requestBase, - unsigned int *p_eventBase, - unsigned int *p_errorBase -){ - XExtDisplayInfo *info = xv_find_display(dpy); - xvQueryExtensionReq *req; - xvQueryExtensionReply rep; - - XvCheckExtension(dpy, info, XvBadExtension); - - LockDisplay(dpy); - - XvGetReq(QueryExtension, req); - - if (!_XReply(dpy, (xReply *)&rep, 0, xFalse)) { - UnlockDisplay(dpy); - SyncHandle(); - return XvBadExtension; - } - - *p_version = rep.version; - *p_revision = rep.revision; - *p_requestBase = info->codes->major_opcode; - *p_eventBase = info->codes->first_event; - *p_errorBase = info->codes->first_error; - - UnlockDisplay(dpy); - SyncHandle(); - - return Success; + UnlockDisplay(dpy); + SyncHandle(); + + return Success; } int -SDL_NAME(XvQueryAdaptors)( - Display *dpy, - Window window, - unsigned int *p_nAdaptors, - SDL_NAME(XvAdaptorInfo) **p_pAdaptors -){ - XExtDisplayInfo *info = xv_find_display(dpy); - xvQueryAdaptorsReq *req; - xvQueryAdaptorsReply rep; - int size,ii,jj; - char *name; - SDL_NAME(XvAdaptorInfo) *pas, *pa; - SDL_NAME(XvFormat) *pfs, *pf; - char *buffer; - union +SDL_NAME(XvQueryAdaptors) (Display * dpy, + Window window, + unsigned int *p_nAdaptors, + SDL_NAME(XvAdaptorInfo) ** p_pAdaptors) +{ + XExtDisplayInfo *info = xv_find_display(dpy); + xvQueryAdaptorsReq *req; + xvQueryAdaptorsReply rep; + int size, ii, jj; + char *name; + SDL_NAME(XvAdaptorInfo) * pas, *pa; + SDL_NAME(XvFormat) * pfs, *pf; + char *buffer; + union { - char *buffer; - char *string; - xvAdaptorInfo *pa; - xvFormat *pf; + char *buffer; + char *string; + xvAdaptorInfo *pa; + xvFormat *pf; } u; - - XvCheckExtension(dpy, info, XvBadExtension); - - LockDisplay(dpy); - - XvGetReq(QueryAdaptors, req); - req->window = window; - - /* READ THE REPLY */ - - if (_XReply(dpy, (xReply *)&rep, 0, xFalse) == 0) { - UnlockDisplay(dpy); - SyncHandle(); - return(XvBadReply); - } - - size = rep.length << 2; - if ( (buffer = (char *)Xmalloc ((unsigned) size)) == NULL) { - UnlockDisplay(dpy); - SyncHandle(); - return(XvBadAlloc); - } - _XRead (dpy, buffer, size); - - u.buffer = buffer; - - /* GET INPUT ADAPTORS */ - - if (rep.num_adaptors == 0) { - pas = NULL; - } else { - size = rep.num_adaptors*sizeof(SDL_NAME(XvAdaptorInfo)); - if ((pas=(SDL_NAME(XvAdaptorInfo) *)Xmalloc(size))==NULL) { - Xfree(buffer); - UnlockDisplay(dpy); - SyncHandle(); - return(XvBadAlloc); - } - } - - /* INIT ADAPTOR FIELDS */ - - pa = pas; - for (ii=0; iinum_adaptors = 0; - pa->name = (char *)NULL; - pa->formats = (SDL_NAME(XvFormat) *)NULL; - pa++; - } - - pa = pas; - for (ii=0; iitype = u.pa->type; - pa->base_id = u.pa->base_id; - pa->num_ports = u.pa->num_ports; - pa->num_formats = u.pa->num_formats; - pa->num_adaptors = rep.num_adaptors - ii; - - /* GET ADAPTOR NAME */ - - size = u.pa->name_size; - u.buffer += (sz_xvAdaptorInfo + 3) & ~3; - - if ( (name = (char *)Xmalloc(size+1)) == NULL) - { - SDL_NAME(XvFreeAdaptorInfo)(pas); - Xfree(buffer); - UnlockDisplay(dpy); - SyncHandle(); - return(XvBadAlloc); - } - SDL_strlcpy(name, u.string, size); - pa->name = name; - - u.buffer += (size + 3) & ~3; - - /* GET FORMATS */ - - size = pa->num_formats*sizeof(SDL_NAME(XvFormat)); - if ((pfs=(SDL_NAME(XvFormat) *)Xmalloc(size))==NULL) { - SDL_NAME(XvFreeAdaptorInfo)(pas); - Xfree(buffer); - UnlockDisplay(dpy); - SyncHandle(); - return(XvBadAlloc); - } - - pf = pfs; - for (jj=0; jjnum_formats; jj++) { - pf->depth = u.pf->depth; - pf->visual_id = u.pf->visual; - pf++; - - u.buffer += (sz_xvFormat + 3) & ~3; - } - - pa->formats = pfs; - - pa++; - - } - - *p_nAdaptors = rep.num_adaptors; - *p_pAdaptors = pas; - - Xfree(buffer); - UnlockDisplay(dpy); - SyncHandle(); - - return (Success); + + XvCheckExtension(dpy, info, XvBadExtension); + + LockDisplay(dpy); + + XvGetReq(QueryAdaptors, req); + req->window = window; + + /* READ THE REPLY */ + + if (_XReply(dpy, (xReply *) & rep, 0, xFalse) == 0) { + UnlockDisplay(dpy); + SyncHandle(); + return (XvBadReply); + } + + size = rep.length << 2; + if ((buffer = (char *) Xmalloc((unsigned) size)) == NULL) { + UnlockDisplay(dpy); + SyncHandle(); + return (XvBadAlloc); + } + _XRead(dpy, buffer, size); + + u.buffer = buffer; + + /* GET INPUT ADAPTORS */ + + if (rep.num_adaptors == 0) { + pas = NULL; + } else { + size = rep.num_adaptors * sizeof(SDL_NAME(XvAdaptorInfo)); + if ((pas = (SDL_NAME(XvAdaptorInfo) *) Xmalloc(size)) == NULL) { + Xfree(buffer); + UnlockDisplay(dpy); + SyncHandle(); + return (XvBadAlloc); + } + } + + /* INIT ADAPTOR FIELDS */ + + pa = pas; + for (ii = 0; ii < rep.num_adaptors; ii++) { + pa->num_adaptors = 0; + pa->name = (char *) NULL; + pa->formats = (SDL_NAME(XvFormat) *) NULL; + pa++; + } + + pa = pas; + for (ii = 0; ii < rep.num_adaptors; ii++) { + pa->type = u.pa->type; + pa->base_id = u.pa->base_id; + pa->num_ports = u.pa->num_ports; + pa->num_formats = u.pa->num_formats; + pa->num_adaptors = rep.num_adaptors - ii; + + /* GET ADAPTOR NAME */ + + size = u.pa->name_size; + u.buffer += (sz_xvAdaptorInfo + 3) & ~3; + + if ((name = (char *) Xmalloc(size + 1)) == NULL) { + SDL_NAME(XvFreeAdaptorInfo) (pas); + Xfree(buffer); + UnlockDisplay(dpy); + SyncHandle(); + return (XvBadAlloc); + } + SDL_strlcpy(name, u.string, size); + pa->name = name; + + u.buffer += (size + 3) & ~3; + + /* GET FORMATS */ + + size = pa->num_formats * sizeof(SDL_NAME(XvFormat)); + if ((pfs = (SDL_NAME(XvFormat) *) Xmalloc(size)) == NULL) { + SDL_NAME(XvFreeAdaptorInfo) (pas); + Xfree(buffer); + UnlockDisplay(dpy); + SyncHandle(); + return (XvBadAlloc); + } + + pf = pfs; + for (jj = 0; jj < pa->num_formats; jj++) { + pf->depth = u.pf->depth; + pf->visual_id = u.pf->visual; + pf++; + + u.buffer += (sz_xvFormat + 3) & ~3; + } + + pa->formats = pfs; + + pa++; + + } + + *p_nAdaptors = rep.num_adaptors; + *p_pAdaptors = pas; + + Xfree(buffer); + UnlockDisplay(dpy); + SyncHandle(); + + return (Success); } -void -SDL_NAME(XvFreeAdaptorInfo)(SDL_NAME(XvAdaptorInfo) *pAdaptors) +void SDL_NAME(XvFreeAdaptorInfo) (SDL_NAME(XvAdaptorInfo) * pAdaptors) { - SDL_NAME(XvAdaptorInfo) *pa; - int ii; + SDL_NAME(XvAdaptorInfo) * pa; + int ii; - if (!pAdaptors) return; + if (!pAdaptors) + return; - pa = pAdaptors; + pa = pAdaptors; - for (ii=0; iinum_adaptors; ii++, pa++) - { - if (pa->name) - { - Xfree(pa->name); - } - if (pa->formats) - { - Xfree(pa->formats); - } - } - - Xfree(pAdaptors); + for (ii = 0; ii < pAdaptors->num_adaptors; ii++, pa++) { + if (pa->name) { + Xfree(pa->name); + } + if (pa->formats) { + Xfree(pa->formats); + } + } + + Xfree(pAdaptors); } int -SDL_NAME(XvQueryEncodings)( - Display *dpy, - XvPortID port, - unsigned int *p_nEncodings, - SDL_NAME(XvEncodingInfo) **p_pEncodings -){ - XExtDisplayInfo *info = xv_find_display(dpy); - xvQueryEncodingsReq *req; - xvQueryEncodingsReply rep; - int size, jj; - char *name; - SDL_NAME(XvEncodingInfo) *pes, *pe; - char *buffer; - union +SDL_NAME(XvQueryEncodings) (Display * dpy, + XvPortID port, + unsigned int *p_nEncodings, + SDL_NAME(XvEncodingInfo) ** p_pEncodings) +{ + XExtDisplayInfo *info = xv_find_display(dpy); + xvQueryEncodingsReq *req; + xvQueryEncodingsReply rep; + int size, jj; + char *name; + SDL_NAME(XvEncodingInfo) * pes, *pe; + char *buffer; + union { - char *buffer; - char *string; - xvEncodingInfo *pe; + char *buffer; + char *string; + xvEncodingInfo *pe; } u; - - XvCheckExtension(dpy, info, XvBadExtension); - - LockDisplay(dpy); - - XvGetReq(QueryEncodings, req); - req->port = port; - - /* READ THE REPLY */ - - if (_XReply(dpy, (xReply *)&rep, 0, xFalse) == 0) { - UnlockDisplay(dpy); - SyncHandle(); - return(XvBadReply); - } - - size = rep.length << 2; - if ( (buffer = (char *)Xmalloc ((unsigned) size)) == NULL) { - UnlockDisplay(dpy); - SyncHandle(); - return(XvBadAlloc); - } - _XRead (dpy, buffer, size); - - u.buffer = buffer; - - /* GET ENCODINGS */ - - size = rep.num_encodings*sizeof(SDL_NAME(XvEncodingInfo)); - if ( (pes = (SDL_NAME(XvEncodingInfo) *)Xmalloc(size)) == NULL) { - Xfree(buffer); - UnlockDisplay(dpy); - SyncHandle(); - return(XvBadAlloc); - } - - /* INITIALIZE THE ENCODING POINTER */ - - pe = pes; - for (jj=0; jjname = (char *)NULL; - pe->num_encodings = 0; - pe++; - } - - pe = pes; - for (jj=0; jjencoding_id = u.pe->encoding; - pe->width = u.pe->width; - pe->height = u.pe->height; - pe->rate.numerator = u.pe->rate.numerator; - pe->rate.denominator = u.pe->rate.denominator; - pe->num_encodings = rep.num_encodings - jj; - - size = u.pe->name_size; - u.buffer += (sz_xvEncodingInfo + 3) & ~3; - - if ( (name = (char *)Xmalloc(size+1)) == NULL) { - Xfree(buffer); - UnlockDisplay(dpy); - SyncHandle(); - return(XvBadAlloc); - } - SDL_strlcpy(name, u.string, size); - pe->name = name; - pe++; - - u.buffer += (size + 3) & ~3; - } - - *p_nEncodings = rep.num_encodings; - *p_pEncodings = pes; - - Xfree(buffer); - UnlockDisplay(dpy); - SyncHandle(); - - return (Success); + + XvCheckExtension(dpy, info, XvBadExtension); + + LockDisplay(dpy); + + XvGetReq(QueryEncodings, req); + req->port = port; + + /* READ THE REPLY */ + + if (_XReply(dpy, (xReply *) & rep, 0, xFalse) == 0) { + UnlockDisplay(dpy); + SyncHandle(); + return (XvBadReply); + } + + size = rep.length << 2; + if ((buffer = (char *) Xmalloc((unsigned) size)) == NULL) { + UnlockDisplay(dpy); + SyncHandle(); + return (XvBadAlloc); + } + _XRead(dpy, buffer, size); + + u.buffer = buffer; + + /* GET ENCODINGS */ + + size = rep.num_encodings * sizeof(SDL_NAME(XvEncodingInfo)); + if ((pes = (SDL_NAME(XvEncodingInfo) *) Xmalloc(size)) == NULL) { + Xfree(buffer); + UnlockDisplay(dpy); + SyncHandle(); + return (XvBadAlloc); + } + + /* INITIALIZE THE ENCODING POINTER */ + + pe = pes; + for (jj = 0; jj < rep.num_encodings; jj++) { + pe->name = (char *) NULL; + pe->num_encodings = 0; + pe++; + } + + pe = pes; + for (jj = 0; jj < rep.num_encodings; jj++) { + pe->encoding_id = u.pe->encoding; + pe->width = u.pe->width; + pe->height = u.pe->height; + pe->rate.numerator = u.pe->rate.numerator; + pe->rate.denominator = u.pe->rate.denominator; + pe->num_encodings = rep.num_encodings - jj; + + size = u.pe->name_size; + u.buffer += (sz_xvEncodingInfo + 3) & ~3; + + if ((name = (char *) Xmalloc(size + 1)) == NULL) { + Xfree(buffer); + UnlockDisplay(dpy); + SyncHandle(); + return (XvBadAlloc); + } + SDL_strlcpy(name, u.string, size); + pe->name = name; + pe++; + + u.buffer += (size + 3) & ~3; + } + + *p_nEncodings = rep.num_encodings; + *p_pEncodings = pes; + + Xfree(buffer); + UnlockDisplay(dpy); + SyncHandle(); + + return (Success); } -void -SDL_NAME(XvFreeEncodingInfo)(SDL_NAME(XvEncodingInfo) *pEncodings) +void SDL_NAME(XvFreeEncodingInfo) (SDL_NAME(XvEncodingInfo) * pEncodings) { - SDL_NAME(XvEncodingInfo) *pe; - int ii; + SDL_NAME(XvEncodingInfo) * pe; + int ii; - if (!pEncodings) return; + if (!pEncodings) + return; - pe = pEncodings; + pe = pEncodings; - for (ii=0; iinum_encodings; ii++, pe++) { - if (pe->name) Xfree(pe->name); - } + for (ii = 0; ii < pEncodings->num_encodings; ii++, pe++) { + if (pe->name) + Xfree(pe->name); + } - Xfree(pEncodings); + Xfree(pEncodings); } int -SDL_NAME(XvPutVideo)( - Display *dpy, - XvPortID port, - Drawable d, - GC gc, - int vx, int vy, - unsigned int vw, unsigned int vh, - int dx, int dy, - unsigned int dw, unsigned int dh -){ - XExtDisplayInfo *info = xv_find_display(dpy); - xvPutVideoReq *req; - - XvCheckExtension(dpy, info, XvBadExtension); - - LockDisplay(dpy); - - FlushGC(dpy, gc); - - XvGetReq(PutVideo, req); - - req->port = port; - req->drawable = d; - req->gc = gc->gid; - req->vid_x = vx; - req->vid_y = vy; - req->vid_w = vw; - req->vid_h = vh; - req->drw_x = dx; - req->drw_y = dy; - req->drw_w = dw; - req->drw_h = dh; - - UnlockDisplay(dpy); - SyncHandle(); - - return Success; +SDL_NAME(XvPutVideo) (Display * dpy, + XvPortID port, + Drawable d, + GC gc, + int vx, int vy, + unsigned int vw, unsigned int vh, + int dx, int dy, unsigned int dw, unsigned int dh) +{ + XExtDisplayInfo *info = xv_find_display(dpy); + xvPutVideoReq *req; + + XvCheckExtension(dpy, info, XvBadExtension); + + LockDisplay(dpy); + + FlushGC(dpy, gc); + + XvGetReq(PutVideo, req); + + req->port = port; + req->drawable = d; + req->gc = gc->gid; + req->vid_x = vx; + req->vid_y = vy; + req->vid_w = vw; + req->vid_h = vh; + req->drw_x = dx; + req->drw_y = dy; + req->drw_w = dw; + req->drw_h = dh; + + UnlockDisplay(dpy); + SyncHandle(); + + return Success; } int -SDL_NAME(XvPutStill)( - Display *dpy, - XvPortID port, - Drawable d, - GC gc, - int vx, int vy, - unsigned int vw, unsigned int vh, - int dx, int dy, - unsigned int dw, unsigned int dh -){ - XExtDisplayInfo *info = xv_find_display(dpy); - xvPutStillReq *req; - - XvCheckExtension(dpy, info, XvBadExtension); - - LockDisplay(dpy); - - FlushGC(dpy, gc); - - XvGetReq(PutStill, req); - req->port = port; - req->drawable = d; - req->gc = gc->gid; - req->vid_x = vx; - req->vid_y = vy; - req->vid_w = vw; - req->vid_h = vh; - req->drw_x = dx; - req->drw_y = dy; - req->drw_w = dw; - req->drw_h = dh; - - UnlockDisplay(dpy); - SyncHandle(); - - return Success; +SDL_NAME(XvPutStill) (Display * dpy, + XvPortID port, + Drawable d, + GC gc, + int vx, int vy, + unsigned int vw, unsigned int vh, + int dx, int dy, unsigned int dw, unsigned int dh) +{ + XExtDisplayInfo *info = xv_find_display(dpy); + xvPutStillReq *req; + + XvCheckExtension(dpy, info, XvBadExtension); + + LockDisplay(dpy); + + FlushGC(dpy, gc); + + XvGetReq(PutStill, req); + req->port = port; + req->drawable = d; + req->gc = gc->gid; + req->vid_x = vx; + req->vid_y = vy; + req->vid_w = vw; + req->vid_h = vh; + req->drw_x = dx; + req->drw_y = dy; + req->drw_w = dw; + req->drw_h = dh; + + UnlockDisplay(dpy); + SyncHandle(); + + return Success; } int -SDL_NAME(XvGetVideo)( - Display *dpy, - XvPortID port, - Drawable d, - GC gc, - int vx, int vy, - unsigned int vw, unsigned int vh, - int dx, int dy, - unsigned int dw, unsigned int dh -){ - XExtDisplayInfo *info = xv_find_display(dpy); - xvGetVideoReq *req; - - XvCheckExtension(dpy, info, XvBadExtension); - - LockDisplay(dpy); - - FlushGC(dpy, gc); - - XvGetReq(GetVideo, req); - req->port = port; - req->drawable = d; - req->gc = gc->gid; - req->vid_x = vx; - req->vid_y = vy; - req->vid_w = vw; - req->vid_h = vh; - req->drw_x = dx; - req->drw_y = dy; - req->drw_w = dw; - req->drw_h = dh; - - UnlockDisplay(dpy); - SyncHandle(); - - return Success; +SDL_NAME(XvGetVideo) (Display * dpy, + XvPortID port, + Drawable d, + GC gc, + int vx, int vy, + unsigned int vw, unsigned int vh, + int dx, int dy, unsigned int dw, unsigned int dh) +{ + XExtDisplayInfo *info = xv_find_display(dpy); + xvGetVideoReq *req; + + XvCheckExtension(dpy, info, XvBadExtension); + + LockDisplay(dpy); + + FlushGC(dpy, gc); + + XvGetReq(GetVideo, req); + req->port = port; + req->drawable = d; + req->gc = gc->gid; + req->vid_x = vx; + req->vid_y = vy; + req->vid_w = vw; + req->vid_h = vh; + req->drw_x = dx; + req->drw_y = dy; + req->drw_w = dw; + req->drw_h = dh; + + UnlockDisplay(dpy); + SyncHandle(); + + return Success; } int -SDL_NAME(XvGetStill)( - Display *dpy, - XvPortID port, - Drawable d, - GC gc, - int vx, int vy, - unsigned int vw, unsigned int vh, - int dx, int dy, - unsigned int dw, unsigned int dh -){ - XExtDisplayInfo *info = xv_find_display(dpy); - xvGetStillReq *req; - - XvCheckExtension(dpy, info, XvBadExtension); - - LockDisplay(dpy); - - FlushGC(dpy, gc); - - XvGetReq(GetStill, req); - req->port = port; - req->drawable = d; - req->gc = gc->gid; - req->vid_x = vx; - req->vid_y = vy; - req->vid_w = vw; - req->vid_h = vh; - req->drw_x = dx; - req->drw_y = dy; - req->drw_w = dw; - req->drw_h = dh; - - UnlockDisplay(dpy); - SyncHandle(); - - return Success; +SDL_NAME(XvGetStill) (Display * dpy, + XvPortID port, + Drawable d, + GC gc, + int vx, int vy, + unsigned int vw, unsigned int vh, + int dx, int dy, unsigned int dw, unsigned int dh) +{ + XExtDisplayInfo *info = xv_find_display(dpy); + xvGetStillReq *req; + + XvCheckExtension(dpy, info, XvBadExtension); + + LockDisplay(dpy); + + FlushGC(dpy, gc); + + XvGetReq(GetStill, req); + req->port = port; + req->drawable = d; + req->gc = gc->gid; + req->vid_x = vx; + req->vid_y = vy; + req->vid_w = vw; + req->vid_h = vh; + req->drw_x = dx; + req->drw_y = dy; + req->drw_w = dw; + req->drw_h = dh; + + UnlockDisplay(dpy); + SyncHandle(); + + return Success; } -int -SDL_NAME(XvStopVideo)( - Display *dpy, - XvPortID port, - Drawable draw -){ - XExtDisplayInfo *info = xv_find_display(dpy); - xvStopVideoReq *req; +int SDL_NAME(XvStopVideo) (Display * dpy, XvPortID port, Drawable draw) +{ + XExtDisplayInfo *info = xv_find_display(dpy); + xvStopVideoReq *req; - XvCheckExtension(dpy, info, XvBadExtension); + XvCheckExtension(dpy, info, XvBadExtension); - LockDisplay(dpy); + LockDisplay(dpy); - XvGetReq(StopVideo, req); - req->port = port; - req->drawable = draw; + XvGetReq(StopVideo, req); + req->port = port; + req->drawable = draw; - UnlockDisplay(dpy); - SyncHandle(); + UnlockDisplay(dpy); + SyncHandle(); - return Success; + return Success; } -int -SDL_NAME(XvGrabPort)( - Display *dpy, - XvPortID port, - Time time -){ - XExtDisplayInfo *info = xv_find_display(dpy); - int result; - xvGrabPortReply rep; - xvGrabPortReq *req; +int SDL_NAME(XvGrabPort) (Display * dpy, XvPortID port, Time time) +{ + XExtDisplayInfo *info = xv_find_display(dpy); + int result; + xvGrabPortReply rep; + xvGrabPortReq *req; - XvCheckExtension(dpy, info, XvBadExtension); + XvCheckExtension(dpy, info, XvBadExtension); - LockDisplay(dpy); + LockDisplay(dpy); - XvGetReq(GrabPort, req); - req->port = port; - req->time = time; + XvGetReq(GrabPort, req); + req->port = port; + req->time = time; - if (_XReply (dpy, (xReply *) &rep, 0, xTrue) == 0) - rep.result = GrabSuccess; + if (_XReply(dpy, (xReply *) & rep, 0, xTrue) == 0) + rep.result = GrabSuccess; - result = rep.result; + result = rep.result; - UnlockDisplay(dpy); - SyncHandle(); + UnlockDisplay(dpy); + SyncHandle(); - return result; + return result; } -int -SDL_NAME(XvUngrabPort)( - Display *dpy, - XvPortID port, - Time time -){ - XExtDisplayInfo *info = xv_find_display(dpy); - xvUngrabPortReq *req; +int SDL_NAME(XvUngrabPort) (Display * dpy, XvPortID port, Time time) +{ + XExtDisplayInfo *info = xv_find_display(dpy); + xvUngrabPortReq *req; - XvCheckExtension(dpy, info, XvBadExtension); + XvCheckExtension(dpy, info, XvBadExtension); - LockDisplay(dpy); + LockDisplay(dpy); - XvGetReq(UngrabPort, req); - req->port = port; - req->time = time; + XvGetReq(UngrabPort, req); + req->port = port; + req->time = time; - UnlockDisplay(dpy); - SyncHandle(); + UnlockDisplay(dpy); + SyncHandle(); - return Success; + return Success; } int -SDL_NAME(XvSelectVideoNotify)( - Display *dpy, - Drawable drawable, - Bool onoff -){ - XExtDisplayInfo *info = xv_find_display(dpy); - xvSelectVideoNotifyReq *req; +SDL_NAME(XvSelectVideoNotify) (Display * dpy, Drawable drawable, Bool onoff) +{ + XExtDisplayInfo *info = xv_find_display(dpy); + xvSelectVideoNotifyReq *req; - XvCheckExtension(dpy, info, XvBadExtension); + XvCheckExtension(dpy, info, XvBadExtension); - LockDisplay(dpy); + LockDisplay(dpy); - XvGetReq(SelectVideoNotify, req); - req->drawable = drawable; - req->onoff = onoff; + XvGetReq(SelectVideoNotify, req); + req->drawable = drawable; + req->onoff = onoff; - UnlockDisplay(dpy); - SyncHandle(); + UnlockDisplay(dpy); + SyncHandle(); - return Success; + return Success; } -int -SDL_NAME(XvSelectPortNotify)( - Display *dpy, - XvPortID port, - Bool onoff -){ - XExtDisplayInfo *info = xv_find_display(dpy); - xvSelectPortNotifyReq *req; +int SDL_NAME(XvSelectPortNotify) (Display * dpy, XvPortID port, Bool onoff) +{ + XExtDisplayInfo *info = xv_find_display(dpy); + xvSelectPortNotifyReq *req; - XvCheckExtension(dpy, info, XvBadExtension); + XvCheckExtension(dpy, info, XvBadExtension); - LockDisplay(dpy); + LockDisplay(dpy); - XvGetReq(SelectPortNotify, req); - req->port = port; - req->onoff = onoff; + XvGetReq(SelectPortNotify, req); + req->port = port; + req->onoff = onoff; - UnlockDisplay(dpy); - SyncHandle(); + UnlockDisplay(dpy); + SyncHandle(); - return Success; + return Success; } int -SDL_NAME(XvSetPortAttribute) ( - Display *dpy, - XvPortID port, - Atom attribute, - int value -) +SDL_NAME(XvSetPortAttribute) (Display * dpy, + XvPortID port, Atom attribute, int value) { - XExtDisplayInfo *info = xv_find_display(dpy); - xvSetPortAttributeReq *req; + XExtDisplayInfo *info = xv_find_display(dpy); + xvSetPortAttributeReq *req; - XvCheckExtension(dpy, info, XvBadExtension); + XvCheckExtension(dpy, info, XvBadExtension); - LockDisplay(dpy); + LockDisplay(dpy); - XvGetReq(SetPortAttribute, req); - req->port = port; - req->attribute = attribute; - req->value = value; + XvGetReq(SetPortAttribute, req); + req->port = port; + req->attribute = attribute; + req->value = value; - UnlockDisplay(dpy); - SyncHandle(); + UnlockDisplay(dpy); + SyncHandle(); - return (Success); + return (Success); } int -SDL_NAME(XvGetPortAttribute) ( - Display *dpy, - XvPortID port, - Atom attribute, - int *p_value -) +SDL_NAME(XvGetPortAttribute) (Display * dpy, + XvPortID port, Atom attribute, int *p_value) { - XExtDisplayInfo *info = xv_find_display(dpy); - xvGetPortAttributeReq *req; - xvGetPortAttributeReply rep; + XExtDisplayInfo *info = xv_find_display(dpy); + xvGetPortAttributeReq *req; + xvGetPortAttributeReply rep; - XvCheckExtension(dpy, info, XvBadExtension); + XvCheckExtension(dpy, info, XvBadExtension); - LockDisplay(dpy); + LockDisplay(dpy); - XvGetReq(GetPortAttribute, req); - req->port = port; - req->attribute = attribute; + XvGetReq(GetPortAttribute, req); + req->port = port; + req->attribute = attribute; - /* READ THE REPLY */ + /* READ THE REPLY */ - if (_XReply(dpy, (xReply *)&rep, 0, xFalse) == 0) { - UnlockDisplay(dpy); - SyncHandle(); - return(XvBadReply); - } + if (_XReply(dpy, (xReply *) & rep, 0, xFalse) == 0) { + UnlockDisplay(dpy); + SyncHandle(); + return (XvBadReply); + } - *p_value = rep.value; - - UnlockDisplay(dpy); - SyncHandle(); + *p_value = rep.value; - return (Success); + UnlockDisplay(dpy); + SyncHandle(); + + return (Success); } int -SDL_NAME(XvQueryBestSize)( - Display *dpy, - XvPortID port, - Bool motion, - unsigned int vid_w, - unsigned int vid_h, - unsigned int drw_w, - unsigned int drw_h, - unsigned int *p_actual_width, - unsigned int *p_actual_height -) +SDL_NAME(XvQueryBestSize) (Display * dpy, + XvPortID port, + Bool motion, + unsigned int vid_w, + unsigned int vid_h, + unsigned int drw_w, + unsigned int drw_h, + unsigned int *p_actual_width, + unsigned int *p_actual_height) { - XExtDisplayInfo *info = xv_find_display(dpy); - xvQueryBestSizeReq *req; - xvQueryBestSizeReply rep; + XExtDisplayInfo *info = xv_find_display(dpy); + xvQueryBestSizeReq *req; + xvQueryBestSizeReply rep; - XvCheckExtension(dpy, info, XvBadExtension); + XvCheckExtension(dpy, info, XvBadExtension); - LockDisplay(dpy); + LockDisplay(dpy); - XvGetReq(QueryBestSize, req); - req->port = port; - req->motion = motion; - req->vid_w = vid_w; - req->vid_h = vid_h; - req->drw_w = drw_w; - req->drw_h = drw_h; + XvGetReq(QueryBestSize, req); + req->port = port; + req->motion = motion; + req->vid_w = vid_w; + req->vid_h = vid_h; + req->drw_w = drw_w; + req->drw_h = drw_h; - /* READ THE REPLY */ + /* READ THE REPLY */ - if (_XReply(dpy, (xReply *)&rep, 0, xFalse) == 0) { - UnlockDisplay(dpy); - SyncHandle(); - return(XvBadReply); - } + if (_XReply(dpy, (xReply *) & rep, 0, xFalse) == 0) { + UnlockDisplay(dpy); + SyncHandle(); + return (XvBadReply); + } - *p_actual_width = rep.actual_width; - *p_actual_height = rep.actual_height; + *p_actual_width = rep.actual_width; + *p_actual_height = rep.actual_height; - UnlockDisplay(dpy); - SyncHandle(); + UnlockDisplay(dpy); + SyncHandle(); - return (Success); + return (Success); } -SDL_NAME(XvAttribute)* -SDL_NAME(XvQueryPortAttributes)(Display *dpy, XvPortID port, int *num) +SDL_NAME(XvAttribute) * +SDL_NAME(XvQueryPortAttributes) (Display * dpy, XvPortID port, int *num) { - XExtDisplayInfo *info = xv_find_display(dpy); - xvQueryPortAttributesReq *req; - xvQueryPortAttributesReply rep; - SDL_NAME(XvAttribute) *ret = NULL; - - *num = 0; - - XvCheckExtension(dpy, info, NULL); - - LockDisplay(dpy); - - XvGetReq(QueryPortAttributes, req); - req->port = port; - - /* READ THE REPLY */ - - if (_XReply(dpy, (xReply *)&rep, 0, xFalse) == 0) { - UnlockDisplay(dpy); - SyncHandle(); - return ret; - } - - if(rep.num_attributes) { - int size = (rep.num_attributes * sizeof(SDL_NAME(XvAttribute))) + rep.text_size; - - if((ret = Xmalloc(size))) { - char* marker = (char*)(&ret[rep.num_attributes]); - xvAttributeInfo Info; - int i; - - for(i = 0; i < rep.num_attributes; i++) { - _XRead(dpy, (char*)(&Info), sz_xvAttributeInfo); - ret[i].flags = (int)Info.flags; - ret[i].min_value = Info.min; - ret[i].max_value = Info.max; - ret[i].name = marker; - _XRead(dpy, marker, Info.size); - marker += Info.size; - (*num)++; - } - } else - _XEatData(dpy, rep.length << 2); - } - - UnlockDisplay(dpy); - SyncHandle(); - - return ret; + XExtDisplayInfo *info = xv_find_display(dpy); + xvQueryPortAttributesReq *req; + xvQueryPortAttributesReply rep; + SDL_NAME(XvAttribute) * ret = NULL; + + *num = 0; + + XvCheckExtension(dpy, info, NULL); + + LockDisplay(dpy); + + XvGetReq(QueryPortAttributes, req); + req->port = port; + + /* READ THE REPLY */ + + if (_XReply(dpy, (xReply *) & rep, 0, xFalse) == 0) { + UnlockDisplay(dpy); + SyncHandle(); + return ret; + } + + if (rep.num_attributes) { + int size = + (rep.num_attributes * sizeof(SDL_NAME(XvAttribute))) + + rep.text_size; + + if ((ret = Xmalloc(size))) { + char *marker = (char *) (&ret[rep.num_attributes]); + xvAttributeInfo Info; + int i; + + for (i = 0; i < rep.num_attributes; i++) { + _XRead(dpy, (char *) (&Info), sz_xvAttributeInfo); + ret[i].flags = (int) Info.flags; + ret[i].min_value = Info.min; + ret[i].max_value = Info.max; + ret[i].name = marker; + _XRead(dpy, marker, Info.size); + marker += Info.size; + (*num)++; + } + } else + _XEatData(dpy, rep.length << 2); + } + + UnlockDisplay(dpy); + SyncHandle(); + + return ret; } -SDL_NAME(XvImageFormatValues) * SDL_NAME(XvListImageFormats) ( - Display *dpy, - XvPortID port, - int *num -){ - XExtDisplayInfo *info = xv_find_display(dpy); - xvListImageFormatsReq *req; - xvListImageFormatsReply rep; - SDL_NAME(XvImageFormatValues) *ret = NULL; - - *num = 0; - - XvCheckExtension(dpy, info, NULL); - - LockDisplay(dpy); - - XvGetReq(ListImageFormats, req); - req->port = port; - - /* READ THE REPLY */ - - if (_XReply(dpy, (xReply *)&rep, 0, xFalse) == 0) { - UnlockDisplay(dpy); - SyncHandle(); - return NULL; - } - - if(rep.num_formats) { - int size = (rep.num_formats * sizeof(SDL_NAME(XvImageFormatValues))); - - if((ret = Xmalloc(size))) { - xvImageFormatInfo Info; - int i; - - for(i = 0; i < rep.num_formats; i++) { - _XRead(dpy, (char*)(&Info), sz_xvImageFormatInfo); - ret[i].id = Info.id; - ret[i].type = Info.type; - ret[i].byte_order = Info.byte_order; - memcpy(&(ret[i].guid[0]), &(Info.guid[0]), 16); - ret[i].bits_per_pixel = Info.bpp; - ret[i].format = Info.format; - ret[i].num_planes = Info.num_planes; - ret[i].depth = Info.depth; - ret[i].red_mask = Info.red_mask; - ret[i].green_mask = Info.green_mask; - ret[i].blue_mask = Info.blue_mask; - ret[i].y_sample_bits = Info.y_sample_bits; - ret[i].u_sample_bits = Info.u_sample_bits; - ret[i].v_sample_bits = Info.v_sample_bits; - ret[i].horz_y_period = Info.horz_y_period; - ret[i].horz_u_period = Info.horz_u_period; - ret[i].horz_v_period = Info.horz_v_period; - ret[i].vert_y_period = Info.vert_y_period; - ret[i].vert_u_period = Info.vert_u_period; - ret[i].vert_v_period = Info.vert_v_period; - memcpy(&(ret[i].component_order[0]), &(Info.comp_order[0]), 32); - ret[i].scanline_order = Info.scanline_order; - (*num)++; - } - } else - _XEatData(dpy, rep.length << 2); - } - - UnlockDisplay(dpy); - SyncHandle(); - - return ret; +SDL_NAME(XvImageFormatValues) * SDL_NAME(XvListImageFormats) (Display * dpy, + XvPortID port, + int *num) +{ + XExtDisplayInfo *info = xv_find_display(dpy); + xvListImageFormatsReq *req; + xvListImageFormatsReply rep; + SDL_NAME(XvImageFormatValues) * ret = NULL; + + *num = 0; + + XvCheckExtension(dpy, info, NULL); + + LockDisplay(dpy); + + XvGetReq(ListImageFormats, req); + req->port = port; + + /* READ THE REPLY */ + + if (_XReply(dpy, (xReply *) & rep, 0, xFalse) == 0) { + UnlockDisplay(dpy); + SyncHandle(); + return NULL; + } + + if (rep.num_formats) { + int size = (rep.num_formats * sizeof(SDL_NAME(XvImageFormatValues))); + + if ((ret = Xmalloc(size))) { + xvImageFormatInfo Info; + int i; + + for (i = 0; i < rep.num_formats; i++) { + _XRead(dpy, (char *) (&Info), sz_xvImageFormatInfo); + ret[i].id = Info.id; + ret[i].type = Info.type; + ret[i].byte_order = Info.byte_order; + memcpy(&(ret[i].guid[0]), &(Info.guid[0]), 16); + ret[i].bits_per_pixel = Info.bpp; + ret[i].format = Info.format; + ret[i].num_planes = Info.num_planes; + ret[i].depth = Info.depth; + ret[i].red_mask = Info.red_mask; + ret[i].green_mask = Info.green_mask; + ret[i].blue_mask = Info.blue_mask; + ret[i].y_sample_bits = Info.y_sample_bits; + ret[i].u_sample_bits = Info.u_sample_bits; + ret[i].v_sample_bits = Info.v_sample_bits; + ret[i].horz_y_period = Info.horz_y_period; + ret[i].horz_u_period = Info.horz_u_period; + ret[i].horz_v_period = Info.horz_v_period; + ret[i].vert_y_period = Info.vert_y_period; + ret[i].vert_u_period = Info.vert_u_period; + ret[i].vert_v_period = Info.vert_v_period; + memcpy(&(ret[i].component_order[0]), + &(Info.comp_order[0]), 32); + ret[i].scanline_order = Info.scanline_order; + (*num)++; + } + } else + _XEatData(dpy, rep.length << 2); + } + + UnlockDisplay(dpy); + SyncHandle(); + + return ret; } -SDL_NAME(XvImage) * SDL_NAME(XvCreateImage) ( - Display *dpy, - XvPortID port, - int id, - char *data, - int width, - int height -) { - XExtDisplayInfo *info = xv_find_display(dpy); - xvQueryImageAttributesReq *req; - xvQueryImageAttributesReply rep; - SDL_NAME(XvImage) *ret = NULL; - - XvCheckExtension(dpy, info, NULL); - - LockDisplay(dpy); - - XvGetReq(QueryImageAttributes, req); - req->id = id; - req->port = port; - req->width = width; - req->height = height; - - /* READ THE REPLY */ - - if (!_XReply(dpy, (xReply *)&rep, 0, xFalse)) { - UnlockDisplay(dpy); - SyncHandle(); - return NULL; - } - - if((ret = (SDL_NAME(XvImage)*)Xmalloc(sizeof(SDL_NAME(XvImage)) + (rep.num_planes << 3)))) { - ret->id = id; - ret->width = rep.width; - ret->height = rep.height; - ret->data_size = rep.data_size; - ret->num_planes = rep.num_planes; - ret->pitches = (int*)(&ret[1]); - ret->offsets = ret->pitches + rep.num_planes; - ret->data = data; - ret->obdata = NULL; - _XRead(dpy, (char*)(ret->pitches), rep.num_planes << 2); - _XRead(dpy, (char*)(ret->offsets), rep.num_planes << 2); - } else - _XEatData(dpy, rep.length << 2); - - UnlockDisplay(dpy); - SyncHandle(); - return ret; +SDL_NAME(XvImage) * SDL_NAME(XvCreateImage) (Display * dpy, + XvPortID port, + int id, + char *data, + int width, int height) +{ + XExtDisplayInfo *info = xv_find_display(dpy); + xvQueryImageAttributesReq *req; + xvQueryImageAttributesReply rep; + SDL_NAME(XvImage) * ret = NULL; + + XvCheckExtension(dpy, info, NULL); + + LockDisplay(dpy); + + XvGetReq(QueryImageAttributes, req); + req->id = id; + req->port = port; + req->width = width; + req->height = height; + + /* READ THE REPLY */ + + if (!_XReply(dpy, (xReply *) & rep, 0, xFalse)) { + UnlockDisplay(dpy); + SyncHandle(); + return NULL; + } + + if ((ret = + (SDL_NAME(XvImage) *) Xmalloc(sizeof(SDL_NAME(XvImage)) + + (rep.num_planes << 3)))) { + ret->id = id; + ret->width = rep.width; + ret->height = rep.height; + ret->data_size = rep.data_size; + ret->num_planes = rep.num_planes; + ret->pitches = (int *) (&ret[1]); + ret->offsets = ret->pitches + rep.num_planes; + ret->data = data; + ret->obdata = NULL; + _XRead(dpy, (char *) (ret->pitches), rep.num_planes << 2); + _XRead(dpy, (char *) (ret->offsets), rep.num_planes << 2); + } else + _XEatData(dpy, rep.length << 2); + + UnlockDisplay(dpy); + SyncHandle(); + return ret; } -SDL_NAME(XvImage) * SDL_NAME(XvShmCreateImage) ( - Display *dpy, - XvPortID port, - int id, - char *data, - int width, - int height, - XShmSegmentInfo *shminfo -){ - SDL_NAME(XvImage) *ret; +SDL_NAME(XvImage) * SDL_NAME(XvShmCreateImage) (Display * dpy, + XvPortID port, + int id, + char *data, + int width, + int height, + XShmSegmentInfo * shminfo) +{ + SDL_NAME(XvImage) * ret; - ret = SDL_NAME(XvCreateImage)(dpy, port, id, data, width, height); + ret = SDL_NAME(XvCreateImage) (dpy, port, id, data, width, height); - if(ret) ret->obdata = (XPointer)shminfo; + if (ret) + ret->obdata = (XPointer) shminfo; - return ret; + return ret; } -int SDL_NAME(XvPutImage) ( - Display *dpy, - XvPortID port, - Drawable d, - GC gc, - SDL_NAME(XvImage) *image, - int src_x, - int src_y, - unsigned int src_w, - unsigned int src_h, - int dest_x, - int dest_y, - unsigned int dest_w, - unsigned int dest_h -){ - XExtDisplayInfo *info = xv_find_display(dpy); - xvPutImageReq *req; - int len; - - XvCheckExtension(dpy, info, XvBadExtension); - - LockDisplay(dpy); - - FlushGC(dpy, gc); - - XvGetReq(PutImage, req); - - req->port = port; - req->drawable = d; - req->gc = gc->gid; - req->id = image->id; - req->src_x = src_x; - req->src_y = src_y; - req->src_w = src_w; - req->src_h = src_h; - req->drw_x = dest_x; - req->drw_y = dest_y; - req->drw_w = dest_w; - req->drw_h = dest_h; - req->width = image->width; - req->height = image->height; - - len = (image->data_size + 3) >> 2; - SetReqLen(req, len, len); - - /* Yes it's kindof lame that we are sending the whole thing, - but for video all of it may be needed even if displaying - only a subsection, and I don't want to go through the - trouble of creating subregions to send */ - Data(dpy, (char *)image->data, image->data_size); - - UnlockDisplay(dpy); - SyncHandle(); - - return Success; +int SDL_NAME(XvPutImage) (Display * dpy, + XvPortID port, + Drawable d, + GC gc, + SDL_NAME(XvImage) * image, + int src_x, + int src_y, + unsigned int src_w, + unsigned int src_h, + int dest_x, + int dest_y, + unsigned int dest_w, unsigned int dest_h) +{ + XExtDisplayInfo *info = xv_find_display(dpy); + xvPutImageReq *req; + int len; + + XvCheckExtension(dpy, info, XvBadExtension); + + LockDisplay(dpy); + + FlushGC(dpy, gc); + + XvGetReq(PutImage, req); + + req->port = port; + req->drawable = d; + req->gc = gc->gid; + req->id = image->id; + req->src_x = src_x; + req->src_y = src_y; + req->src_w = src_w; + req->src_h = src_h; + req->drw_x = dest_x; + req->drw_y = dest_y; + req->drw_w = dest_w; + req->drw_h = dest_h; + req->width = image->width; + req->height = image->height; + + len = (image->data_size + 3) >> 2; + SetReqLen(req, len, len); + + /* Yes it's kindof lame that we are sending the whole thing, + but for video all of it may be needed even if displaying + only a subsection, and I don't want to go through the + trouble of creating subregions to send */ + Data(dpy, (char *) image->data, image->data_size); + + UnlockDisplay(dpy); + SyncHandle(); + + return Success; } -int SDL_NAME(XvShmPutImage) ( - Display *dpy, - XvPortID port, - Drawable d, - GC gc, - SDL_NAME(XvImage) *image, - int src_x, - int src_y, - unsigned int src_w, - unsigned int src_h, - int dest_x, - int dest_y, - unsigned int dest_w, - unsigned int dest_h, - Bool send_event -){ - XExtDisplayInfo *info = xv_find_display(dpy); - XShmSegmentInfo *shminfo = (XShmSegmentInfo *)image->obdata; - xvShmPutImageReq *req; - - XvCheckExtension(dpy, info, XvBadExtension); - - LockDisplay(dpy); - - FlushGC(dpy, gc); - - XvGetReq(ShmPutImage, req); - - req->port = port; - req->drawable = d; - req->gc = gc->gid; - req->shmseg = shminfo->shmseg; - req->id = image->id; - req->src_x = src_x; - req->src_y = src_y; - req->src_w = src_w; - req->src_h = src_h; - req->drw_x = dest_x; - req->drw_y = dest_y; - req->drw_w = dest_w; - req->drw_h = dest_h; - req->offset = image->data - shminfo->shmaddr; - req->width = image->width; - req->height = image->height; - req->send_event = send_event; - - UnlockDisplay(dpy); - SyncHandle(); - - return Success; +int SDL_NAME(XvShmPutImage) (Display * dpy, + XvPortID port, + Drawable d, + GC gc, + SDL_NAME(XvImage) * image, + int src_x, + int src_y, + unsigned int src_w, + unsigned int src_h, + int dest_x, + int dest_y, + unsigned int dest_w, + unsigned int dest_h, Bool send_event) +{ + XExtDisplayInfo *info = xv_find_display(dpy); + XShmSegmentInfo *shminfo = (XShmSegmentInfo *) image->obdata; + xvShmPutImageReq *req; + + XvCheckExtension(dpy, info, XvBadExtension); + + LockDisplay(dpy); + + FlushGC(dpy, gc); + + XvGetReq(ShmPutImage, req); + + req->port = port; + req->drawable = d; + req->gc = gc->gid; + req->shmseg = shminfo->shmseg; + req->id = image->id; + req->src_x = src_x; + req->src_y = src_y; + req->src_w = src_w; + req->src_h = src_h; + req->drw_x = dest_x; + req->drw_y = dest_y; + req->drw_w = dest_w; + req->drw_h = dest_h; + req->offset = image->data - shminfo->shmaddr; + req->width = image->width; + req->height = image->height; + req->send_event = send_event; + + UnlockDisplay(dpy); + SyncHandle(); + + return Success; } static Bool -xv_wire_to_event(Display *dpy, XEvent *host, xEvent *wire) +xv_wire_to_event(Display * dpy, XEvent * host, xEvent * wire) { - XExtDisplayInfo *info = xv_find_display(dpy); - SDL_NAME(XvEvent) *re = (SDL_NAME(XvEvent) *)host; - xvEvent *event = (xvEvent *)wire; + XExtDisplayInfo *info = xv_find_display(dpy); + SDL_NAME(XvEvent) * re = (SDL_NAME(XvEvent) *) host; + xvEvent *event = (xvEvent *) wire; - XvCheckExtension(dpy, info, False); + XvCheckExtension(dpy, info, False); - switch((event->u.u.type & 0x7F) - info->codes->first_event) - { + switch ((event->u.u.type & 0x7F) - info->codes->first_event) { case XvVideoNotify: - re->xvvideo.type = event->u.u.type & 0x7f; - re->xvvideo.serial = - _XSetLastRequestRead(dpy, (xGenericReply *)event); - re->xvvideo.send_event = ((event->u.u.type & 0x80) != 0); - re->xvvideo.display = dpy; - re->xvvideo.time = event->u.videoNotify.time; - re->xvvideo.reason = event->u.videoNotify.reason; - re->xvvideo.drawable = event->u.videoNotify.drawable; - re->xvvideo.port_id = event->u.videoNotify.port; - break; + re->xvvideo.type = event->u.u.type & 0x7f; + re->xvvideo.serial = + _XSetLastRequestRead(dpy, (xGenericReply *) event); + re->xvvideo.send_event = ((event->u.u.type & 0x80) != 0); + re->xvvideo.display = dpy; + re->xvvideo.time = event->u.videoNotify.time; + re->xvvideo.reason = event->u.videoNotify.reason; + re->xvvideo.drawable = event->u.videoNotify.drawable; + re->xvvideo.port_id = event->u.videoNotify.port; + break; case XvPortNotify: - re->xvport.type = event->u.u.type & 0x7f; - re->xvport.serial = - _XSetLastRequestRead(dpy, (xGenericReply *)event); - re->xvport.send_event = ((event->u.u.type & 0x80) != 0); - re->xvport.display = dpy; - re->xvport.time = event->u.portNotify.time; - re->xvport.port_id = event->u.portNotify.port; - re->xvport.attribute = event->u.portNotify.attribute; - re->xvport.value = event->u.portNotify.value; - break; + re->xvport.type = event->u.u.type & 0x7f; + re->xvport.serial = + _XSetLastRequestRead(dpy, (xGenericReply *) event); + re->xvport.send_event = ((event->u.u.type & 0x80) != 0); + re->xvport.display = dpy; + re->xvport.time = event->u.portNotify.time; + re->xvport.port_id = event->u.portNotify.port; + re->xvport.attribute = event->u.portNotify.attribute; + re->xvport.value = event->u.portNotify.value; + break; default: - return False; - } + return False; + } - return (True); + return (True); } - +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/Xext/Xv/Xvlibint.h b/src/video/Xext/Xv/Xvlibint.h index d0bb70836..61bb66dba 100644 --- a/src/video/Xext/Xv/Xvlibint.h +++ b/src/video/Xext/Xv/Xvlibint.h @@ -59,7 +59,7 @@ SOFTWARE. dpy->bufptr += SIZEOF(xv##name##Req);\ dpy->request++ -#else /* non-ANSI C uses empty comment instead of "##" for token concatenation */ +#else /* non-ANSI C uses empty comment instead of "##" for token concatenation */ #define XvGetReq(name, req) \ WORD64ALIGN\ if ((dpy->bufptr + SIZEOF(xv/**/name/**/Req)) > dpy->bufmax)\ @@ -74,3 +74,4 @@ SOFTWARE. #endif /* XVLIBINT_H */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/Xext/Xxf86dga/XF86DGA.c b/src/video/Xext/Xxf86dga/XF86DGA.c index 4e3d662ff..1203f6484 100644 --- a/src/video/Xext/Xxf86dga/XF86DGA.c +++ b/src/video/Xext/Xxf86dga/XF86DGA.c @@ -8,7 +8,7 @@ Copyright (c) 1995,1996 The XFree86 Project, Inc /* THIS IS NOT AN X CONSORTIUM STANDARD */ -#ifdef __EMX__ /* needed here to override certain constants in X headers */ +#ifdef __EMX__ /* needed here to override certain constants in X headers */ #define INCL_DOS #define INCL_DOSIOCTL #include @@ -18,8 +18,8 @@ Copyright (c) 1995,1996 The XFree86 Project, Inc #define HAS_MMAP_ANON #include #include -#include /* PAGE_SIZE */ -#define HAS_SC_PAGESIZE /* _SC_PAGESIZE may be an enum for Linux */ +#include /* PAGE_SIZE */ +#define HAS_SC_PAGESIZE /* _SC_PAGESIZE may be an enum for Linux */ #define HAS_GETPAGESIZE #endif /* linux */ @@ -45,8 +45,8 @@ Copyright (c) 1995,1996 The XFree86 Project, Inc #include #endif /* SVR4 && !DGUX */ -#if defined(sun) && !defined(SVR4) /* SunOS */ -#define MMAP_DEV_ZERO /* doesn't SunOS have MAP_ANON ?? */ +#if defined(sun) && !defined(SVR4) /* SunOS */ +#define MMAP_DEV_ZERO /* doesn't SunOS have MAP_ANON ?? */ #define HAS_GETPAGESIZE #include #include @@ -65,7 +65,7 @@ Copyright (c) 1995,1996 The XFree86 Project, Inc #include "../extensions/Xext.h" #include "../extensions/extutil.h" -extern XExtDisplayInfo* SDL_NAME(xdga_find_display)(Display*); +extern XExtDisplayInfo *SDL_NAME(xdga_find_display) (Display *); extern char *SDL_NAME(xdga_extension_name); #define XF86DGACheckExtension(dpy,i,val) \ @@ -77,67 +77,57 @@ extern char *SDL_NAME(xdga_extension_name); * * *****************************************************************************/ -Bool SDL_NAME(XF86DGAQueryExtension) ( - Display *dpy, - int *event_basep, - int *error_basep -){ - return SDL_NAME(XDGAQueryExtension)(dpy, event_basep, error_basep); +Bool SDL_NAME(XF86DGAQueryExtension) (Display * dpy, + int *event_basep, int *error_basep) +{ + return SDL_NAME(XDGAQueryExtension) (dpy, event_basep, error_basep); } -Bool SDL_NAME(XF86DGAQueryVersion)( - Display* dpy, - int* majorVersion, - int* minorVersion -){ - return SDL_NAME(XDGAQueryVersion)(dpy, majorVersion, minorVersion); +Bool SDL_NAME(XF86DGAQueryVersion) (Display * dpy, + int *majorVersion, int *minorVersion) +{ + return SDL_NAME(XDGAQueryVersion) (dpy, majorVersion, minorVersion); } -Bool SDL_NAME(XF86DGAGetVideoLL)( - Display* dpy, - int screen, - int *offset, - int *width, - int *bank_size, - int *ram_size -){ +Bool SDL_NAME(XF86DGAGetVideoLL) (Display * dpy, + int screen, + int *offset, + int *width, int *bank_size, int *ram_size) +{ XExtDisplayInfo *info = SDL_NAME(xdga_find_display) (dpy); xXF86DGAGetVideoLLReply rep; xXF86DGAGetVideoLLReq *req; - XF86DGACheckExtension (dpy, info, False); + XF86DGACheckExtension(dpy, info, False); LockDisplay(dpy); GetReq(XF86DGAGetVideoLL, req); req->reqType = info->codes->major_opcode; req->dgaReqType = X_XF86DGAGetVideoLL; req->screen = screen; - if (!_XReply(dpy, (xReply *)&rep, 0, xFalse)) { - UnlockDisplay(dpy); - SyncHandle(); - return False; + if (!_XReply(dpy, (xReply *) & rep, 0, xFalse)) { + UnlockDisplay(dpy); + SyncHandle(); + return False; } - *offset = /*(char *)*/rep.offset; + *offset = /*(char *) */ rep.offset; *width = rep.width; *bank_size = rep.bank_size; *ram_size = rep.ram_size; - + UnlockDisplay(dpy); SyncHandle(); return True; } - -Bool SDL_NAME(XF86DGADirectVideoLL)( - Display* dpy, - int screen, - int enable -){ + +Bool SDL_NAME(XF86DGADirectVideoLL) (Display * dpy, int screen, int enable) +{ XExtDisplayInfo *info = SDL_NAME(xdga_find_display) (dpy); xXF86DGADirectVideoReq *req; - XF86DGACheckExtension (dpy, info, False); + XF86DGACheckExtension(dpy, info, False); LockDisplay(dpy); GetReq(XF86DGADirectVideo, req); @@ -147,52 +137,45 @@ Bool SDL_NAME(XF86DGADirectVideoLL)( req->enable = enable; UnlockDisplay(dpy); SyncHandle(); - XSync(dpy,False); + XSync(dpy, False); return True; } -Bool SDL_NAME(XF86DGAGetViewPortSize)( - Display* dpy, - int screen, - int *width, - int *height -){ +Bool SDL_NAME(XF86DGAGetViewPortSize) (Display * dpy, + int screen, int *width, int *height) +{ XExtDisplayInfo *info = SDL_NAME(xdga_find_display) (dpy); xXF86DGAGetViewPortSizeReply rep; xXF86DGAGetViewPortSizeReq *req; - XF86DGACheckExtension (dpy, info, False); + XF86DGACheckExtension(dpy, info, False); LockDisplay(dpy); GetReq(XF86DGAGetViewPortSize, req); req->reqType = info->codes->major_opcode; req->dgaReqType = X_XF86DGAGetViewPortSize; req->screen = screen; - if (!_XReply(dpy, (xReply *)&rep, 0, xFalse)) { - UnlockDisplay(dpy); - SyncHandle(); - return False; + if (!_XReply(dpy, (xReply *) & rep, 0, xFalse)) { + UnlockDisplay(dpy); + SyncHandle(); + return False; } *width = rep.width; *height = rep.height; - + UnlockDisplay(dpy); SyncHandle(); return True; } - - -Bool SDL_NAME(XF86DGASetViewPort)( - Display* dpy, - int screen, - int x, - int y -){ + + +Bool SDL_NAME(XF86DGASetViewPort) (Display * dpy, int screen, int x, int y) +{ XExtDisplayInfo *info = SDL_NAME(xdga_find_display) (dpy); xXF86DGASetViewPortReq *req; - XF86DGACheckExtension (dpy, info, False); + XF86DGACheckExtension(dpy, info, False); LockDisplay(dpy); GetReq(XF86DGASetViewPort, req); @@ -203,31 +186,28 @@ Bool SDL_NAME(XF86DGASetViewPort)( req->y = y; UnlockDisplay(dpy); SyncHandle(); - XSync(dpy,False); + XSync(dpy, False); return True; } - -Bool SDL_NAME(XF86DGAGetVidPage)( - Display* dpy, - int screen, - int *vpage -){ + +Bool SDL_NAME(XF86DGAGetVidPage) (Display * dpy, int screen, int *vpage) +{ XExtDisplayInfo *info = SDL_NAME(xdga_find_display) (dpy); xXF86DGAGetVidPageReply rep; xXF86DGAGetVidPageReq *req; - XF86DGACheckExtension (dpy, info, False); + XF86DGACheckExtension(dpy, info, False); LockDisplay(dpy); GetReq(XF86DGAGetVidPage, req); req->reqType = info->codes->major_opcode; req->dgaReqType = X_XF86DGAGetVidPage; req->screen = screen; - if (!_XReply(dpy, (xReply *)&rep, 0, xFalse)) { - UnlockDisplay(dpy); - SyncHandle(); - return False; + if (!_XReply(dpy, (xReply *) & rep, 0, xFalse)) { + UnlockDisplay(dpy); + SyncHandle(); + return False; } *vpage = rep.vpage; @@ -236,16 +216,13 @@ Bool SDL_NAME(XF86DGAGetVidPage)( return True; } - -Bool SDL_NAME(XF86DGASetVidPage)( - Display* dpy, - int screen, - int vpage -){ + +Bool SDL_NAME(XF86DGASetVidPage) (Display * dpy, int screen, int vpage) +{ XExtDisplayInfo *info = SDL_NAME(xdga_find_display) (dpy); xXF86DGASetVidPageReq *req; - XF86DGACheckExtension (dpy, info, False); + XF86DGACheckExtension(dpy, info, False); LockDisplay(dpy); GetReq(XF86DGASetVidPage, req); @@ -255,19 +232,17 @@ Bool SDL_NAME(XF86DGASetVidPage)( req->vpage = vpage; UnlockDisplay(dpy); SyncHandle(); - XSync(dpy,False); + XSync(dpy, False); return True; } -Bool SDL_NAME(XF86DGAInstallColormap)( - Display* dpy, - int screen, - Colormap cmap -){ +Bool SDL_NAME(XF86DGAInstallColormap) (Display * dpy, + int screen, Colormap cmap) +{ XExtDisplayInfo *info = SDL_NAME(xdga_find_display) (dpy); xXF86DGAInstallColormapReq *req; - XF86DGACheckExtension (dpy, info, False); + XF86DGACheckExtension(dpy, info, False); LockDisplay(dpy); GetReq(XF86DGAInstallColormap, req); @@ -277,30 +252,27 @@ Bool SDL_NAME(XF86DGAInstallColormap)( req->id = cmap; UnlockDisplay(dpy); SyncHandle(); - XSync(dpy,False); + XSync(dpy, False); return True; } -Bool SDL_NAME(XF86DGAQueryDirectVideo)( - Display *dpy, - int screen, - int *flags -){ +Bool SDL_NAME(XF86DGAQueryDirectVideo) (Display * dpy, int screen, int *flags) +{ XExtDisplayInfo *info = SDL_NAME(xdga_find_display) (dpy); xXF86DGAQueryDirectVideoReply rep; xXF86DGAQueryDirectVideoReq *req; - XF86DGACheckExtension (dpy, info, False); + XF86DGACheckExtension(dpy, info, False); LockDisplay(dpy); GetReq(XF86DGAQueryDirectVideo, req); req->reqType = info->codes->major_opcode; req->dgaReqType = X_XF86DGAQueryDirectVideo; req->screen = screen; - if (!_XReply(dpy, (xReply *)&rep, 0, xFalse)) { - UnlockDisplay(dpy); - SyncHandle(); - return False; + if (!_XReply(dpy, (xReply *) & rep, 0, xFalse)) { + UnlockDisplay(dpy); + SyncHandle(); + return False; } *flags = rep.flags; UnlockDisplay(dpy); @@ -308,16 +280,13 @@ Bool SDL_NAME(XF86DGAQueryDirectVideo)( return True; } -Bool SDL_NAME(XF86DGAViewPortChanged)( - Display *dpy, - int screen, - int n -){ +Bool SDL_NAME(XF86DGAViewPortChanged) (Display * dpy, int screen, int n) +{ XExtDisplayInfo *info = SDL_NAME(xdga_find_display) (dpy); xXF86DGAViewPortChangedReply rep; xXF86DGAViewPortChangedReq *req; - XF86DGACheckExtension (dpy, info, False); + XF86DGACheckExtension(dpy, info, False); LockDisplay(dpy); GetReq(XF86DGAViewPortChanged, req); @@ -325,10 +294,10 @@ Bool SDL_NAME(XF86DGAViewPortChanged)( req->dgaReqType = X_XF86DGAViewPortChanged; req->screen = screen; req->n = n; - if (!_XReply(dpy, (xReply *)&rep, 0, xFalse)) { - UnlockDisplay(dpy); - SyncHandle(); - return False; + if (!_XReply(dpy, (xReply *) & rep, 0, xFalse)) { + UnlockDisplay(dpy); + SyncHandle(); + return False; } UnlockDisplay(dpy); SyncHandle(); @@ -344,7 +313,7 @@ Bool SDL_NAME(XF86DGAViewPortChanged)( #include #include #include -#if defined(ISC) +#if defined(ISC) # define HAS_SVR3_MMAP # include # include @@ -380,18 +349,20 @@ Bool SDL_NAME(XF86DGAViewPortChanged)( #define DEV_MEM "/dev/mem" #endif -typedef struct { - unsigned long physaddr; /* actual requested physical address */ - unsigned long size; /* actual requested map size */ - unsigned long delta; /* delta to account for page alignment */ - void * vaddr; /* mapped address, without the delta */ - int refcount; /* reference count */ +typedef struct +{ + unsigned long physaddr; /* actual requested physical address */ + unsigned long size; /* actual requested map size */ + unsigned long delta; /* delta to account for page alignment */ + void *vaddr; /* mapped address, without the delta */ + int refcount; /* reference count */ } MapRec, *MapPtr; -typedef struct { - Display * display; - int screen; - MapPtr map; +typedef struct +{ + Display *display; + int screen; + MapPtr map; } ScrRec, *ScrPtr; static int mapFd = -1; @@ -408,12 +379,12 @@ AddMap(void) old = mapList; mapList = realloc(mapList, sizeof(MapPtr) * (numMaps + 1)); if (!mapList) { - mapList = old; - return NULL; + mapList = old; + return NULL; } mapList[numMaps] = malloc(sizeof(MapRec)); if (!mapList[numMaps]) - return NULL; + return NULL; return mapList[numMaps++]; } @@ -425,12 +396,12 @@ AddScr(void) old = scrList; scrList = realloc(scrList, sizeof(ScrPtr) * (numScrs + 1)); if (!scrList) { - scrList = old; - return NULL; + scrList = old; + return NULL; } scrList[numScrs] = malloc(sizeof(ScrRec)); if (!scrList[numScrs]) - return NULL; + return NULL; return scrList[numScrs++]; } @@ -440,22 +411,20 @@ FindMap(unsigned long address, unsigned long size) int i; for (i = 0; i < numMaps; i++) { - if (mapList[i]->physaddr == address && - mapList[i]->size == size) - return mapList[i]; + if (mapList[i]->physaddr == address && mapList[i]->size == size) + return mapList[i]; } return NULL; } static ScrPtr -FindScr(Display *display, int screen) +FindScr(Display * display, int screen) { int i; for (i = 0; i < numScrs; i++) { - if (scrList[i]->display == display && - scrList[i]->screen == screen) - return scrList[i]; + if (scrList[i]->display == display && scrList[i]->screen == screen) + return scrList[i]; } return NULL; } @@ -476,43 +445,42 @@ MapPhysAddress(unsigned long address, unsigned long size) #endif if ((mp = FindMap(address, size))) { - mp->refcount++; - return (void *)((unsigned long)mp->vaddr + mp->delta); + mp->refcount++; + return (void *) ((unsigned long) mp->vaddr + mp->delta); } - #if defined(_SC_PAGESIZE) && defined(HAS_SC_PAGESIZE) pagesize = sysconf(_SC_PAGESIZE); #endif #ifdef _SC_PAGE_SIZE if (pagesize == -1) - pagesize = sysconf(_SC_PAGE_SIZE); + pagesize = sysconf(_SC_PAGE_SIZE); #endif #ifdef HAS_GETPAGESIZE if (pagesize == -1) - pagesize = getpagesize(); + pagesize = getpagesize(); #endif #ifdef PAGE_SIZE if (pagesize == -1) - pagesize = PAGE_SIZE; + pagesize = PAGE_SIZE; #endif if (pagesize == -1) - pagesize = 4096; + pagesize = 4096; - delta = address % pagesize; - offset = address - delta; + delta = address % pagesize; + offset = address - delta; #if defined(ISC) && defined(HAS_SVR3_MMAP) if (mapFd < 0) { - if ((mapFd = open("/dev/mmap", O_RDWR)) < 0) - return NULL; + if ((mapFd = open("/dev/mmap", O_RDWR)) < 0) + return NULL; } - mloc.vaddr = (char *)0; - mloc.physaddr = (char *)offset; + mloc.vaddr = (char *) 0; + mloc.physaddr = (char *) offset; mloc.length = size + delta; - mloc.ioflg=1; + mloc.ioflg = 1; - if ((vaddr = (void *)ioctl(mapFd, MAP, &mloc)) == (void *)-1) - return NULL; + if ((vaddr = (void *) ioctl(mapFd, MAP, &mloc)) == (void *) -1) + return NULL; #elif defined (__EMX__) /* * Dragon warning here! /dev/pmap$ is never closed, except on progam exit. @@ -521,59 +489,61 @@ MapPhysAddress(unsigned long address, unsigned long size) */ rc = DosOpen("/dev/pmap$", &hfd, &action, 0, FILE_NORMAL, FILE_OPEN, - OPEN_ACCESS_READWRITE | OPEN_SHARE_DENYNONE, (PEAOP2)NULL); + OPEN_ACCESS_READWRITE | OPEN_SHARE_DENYNONE, (PEAOP2) NULL); if (rc != 0) - return NULL; + return NULL; { - struct map_ioctl { - union { - ULONG phys; - void* user; - } a; - ULONG size; - } pmap,dmap; - ULONG plen,dlen; + struct map_ioctl + { + union + { + ULONG phys; + void *user; + } a; + ULONG size; + } pmap, dmap; + ULONG plen, dlen; #define XFREE86_PMAP 0x76 #define PMAP_MAP 0x44 - pmap.a.phys = offset; - pmap.size = size + delta; - rc = DosDevIOCtl(hfd, XFREE86_PMAP, PMAP_MAP, - (PULONG)&pmap, sizeof(pmap), &plen, - (PULONG)&dmap, sizeof(dmap), &dlen); - if (rc == 0) { - vaddr = dmap.a.user; - } - } - if (rc != 0) - return NULL; + pmap.a.phys = offset; + pmap.size = size + delta; + rc = DosDevIOCtl(hfd, XFREE86_PMAP, PMAP_MAP, + (PULONG) & pmap, sizeof(pmap), &plen, + (PULONG) & dmap, sizeof(dmap), &dlen); + if (rc == 0) { + vaddr = dmap.a.user; + } + } + if (rc != 0) + return NULL; #elif defined (Lynx) - vaddr = (void *)smem_create("XF86DGA", (char *)offset, - size + delta, SM_READ|SM_WRITE); + vaddr = (void *) smem_create("XF86DGA", (char *) offset, + size + delta, SM_READ | SM_WRITE); #else #ifndef MAP_FILE #define MAP_FILE 0 #endif if (mapFd < 0) { - if ((mapFd = open(DEV_MEM, O_RDWR)) < 0) - return NULL; + if ((mapFd = open(DEV_MEM, O_RDWR)) < 0) + return NULL; } - vaddr = (void *)mmap(NULL, size + delta, PROT_READ | PROT_WRITE, - MAP_FILE | MAP_SHARED, mapFd, (off_t)offset); - if (vaddr == (void *)-1) - return NULL; + vaddr = (void *) mmap(NULL, size + delta, PROT_READ | PROT_WRITE, + MAP_FILE | MAP_SHARED, mapFd, (off_t) offset); + if (vaddr == (void *) -1) + return NULL; #endif if (!vaddr) { - if (!(mp = AddMap())) - return NULL; - mp->physaddr = address; - mp->size = size; - mp->delta = delta; - mp->vaddr = vaddr; - mp->refcount = 1; + if (!(mp = AddMap())) + return NULL; + mp->physaddr = address; + mp->size = size; + mp->delta = delta; + mp->vaddr = vaddr; + mp->refcount = 1; } - return (void *)((unsigned long)vaddr + delta); + return (void *) ((unsigned long) vaddr + delta); } /* @@ -583,63 +553,58 @@ MapPhysAddress(unsigned long address, unsigned long size) * should restore text mode. */ -int -SDL_NAME(XF86DGAForkApp)(int screen) +int SDL_NAME(XF86DGAForkApp) (int screen) { pid_t pid; int status; int i; - /* fork the app, parent hangs around to clean up */ + /* fork the app, parent hangs around to clean up */ if ((pid = fork()) > 0) { - ScrPtr sp; - - waitpid(pid, &status, 0); - for (i = 0; i < numScrs; i++) { - sp = scrList[i]; - SDL_NAME(XF86DGADirectVideoLL)(sp->display, sp->screen, 0); - XSync(sp->display, False); - } + ScrPtr sp; + + waitpid(pid, &status, 0); + for (i = 0; i < numScrs; i++) { + sp = scrList[i]; + SDL_NAME(XF86DGADirectVideoLL) (sp->display, sp->screen, 0); + XSync(sp->display, False); + } if (WIFEXITED(status)) - _exit(0); - else - _exit(-1); + _exit(0); + else + _exit(-1); } return pid; } -Bool -SDL_NAME(XF86DGADirectVideo)( - Display *dis, - int screen, - int enable -){ +Bool SDL_NAME(XF86DGADirectVideo) (Display * dis, int screen, int enable) +{ ScrPtr sp; MapPtr mp = NULL; if ((sp = FindScr(dis, screen))) - mp = sp->map; + mp = sp->map; if (enable & XF86DGADirectGraphics) { #if !defined(ISC) && !defined(HAS_SVR3_MMAP) && !defined(Lynx) \ && !defined(__EMX__) - if (mp && mp->vaddr) - mprotect(mp->vaddr, mp->size + mp->delta, PROT_READ | PROT_WRITE); + if (mp && mp->vaddr) + mprotect(mp->vaddr, mp->size + mp->delta, PROT_READ | PROT_WRITE); #endif } else { #if !defined(ISC) && !defined(HAS_SVR3_MMAP) && !defined(Lynx) \ && !defined(__EMX__) - if (mp && mp->vaddr) - mprotect(mp->vaddr, mp->size + mp->delta, PROT_READ); + if (mp && mp->vaddr) + mprotect(mp->vaddr, mp->size + mp->delta, PROT_READ); #elif defined(Lynx) - /* XXX this doesn't allow enable after disable */ - smem_create(NULL, mp->vaddr, mp->size + mp->delta, SM_DETACH); - smem_remove("XF86DGA"); + /* XXX this doesn't allow enable after disable */ + smem_create(NULL, mp->vaddr, mp->size + mp->delta, SM_DETACH); + smem_remove("XF86DGA"); #endif } - SDL_NAME(XF86DGADirectVideoLL)(dis, screen, enable); + SDL_NAME(XF86DGADirectVideoLL) (dis, screen, enable); return 1; } @@ -652,65 +617,63 @@ XF86cleanup(int sig) static char beenhere = 0; if (beenhere) - _exit(3); + _exit(3); beenhere = 1; for (i = 0; i < numScrs; i++) { - sp = scrList[i]; - SDL_NAME(XF86DGADirectVideo)(sp->display, sp->screen, 0); - XSync(sp->display, False); + sp = scrList[i]; + SDL_NAME(XF86DGADirectVideo) (sp->display, sp->screen, 0); + XSync(sp->display, False); } _exit(3); } Bool -SDL_NAME(XF86DGAGetVideo)( - Display *dis, - int screen, - char **addr, - int *width, - int *bank, - int *ram -){ - /*unsigned long*/ int offset; +SDL_NAME(XF86DGAGetVideo) (Display * dis, + int screen, + char **addr, int *width, int *bank, int *ram) +{ + /*unsigned long */ int offset; static int beenHere = 0; ScrPtr sp; MapPtr mp; if (!(sp = FindScr(dis, screen))) { - if (!(sp = AddScr())) { - fprintf(stderr, "XF86DGAGetVideo: malloc failure\n"); - exit(-2); - } - sp->display = dis; - sp->screen = screen; - sp->map = NULL; + if (!(sp = AddScr())) { + fprintf(stderr, "XF86DGAGetVideo: malloc failure\n"); + exit(-2); + } + sp->display = dis; + sp->screen = screen; + sp->map = NULL; } - SDL_NAME(XF86DGAGetVideoLL)(dis, screen , &offset, width, bank, ram); + SDL_NAME(XF86DGAGetVideoLL) (dis, screen, &offset, width, bank, ram); *addr = MapPhysAddress(offset, *bank); if (*addr == NULL) { - fprintf(stderr, "XF86DGAGetVideo: failed to map video memory (%s)\n", - strerror(errno)); - exit(-2); + fprintf(stderr, + "XF86DGAGetVideo: failed to map video memory (%s)\n", + strerror(errno)); + exit(-2); } if ((mp = FindMap(offset, *bank))) - sp->map = mp; + sp->map = mp; if (!beenHere) { - beenHere = 1; - atexit((void(*)(void))XF86cleanup); - /* one shot XF86cleanup attempts */ - signal(SIGSEGV, XF86cleanup); + beenHere = 1; + atexit((void (*)(void)) XF86cleanup); + /* one shot XF86cleanup attempts */ + signal(SIGSEGV, XF86cleanup); #ifdef SIGBUS - signal(SIGBUS, XF86cleanup); + signal(SIGBUS, XF86cleanup); #endif - signal(SIGHUP, XF86cleanup); - signal(SIGFPE, XF86cleanup); + signal(SIGHUP, XF86cleanup); + signal(SIGFPE, XF86cleanup); } return 1; } +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/Xext/Xxf86dga/XF86DGA2.c b/src/video/Xext/Xxf86dga/XF86DGA2.c index 3acf9f8e7..b2e23386a 100644 --- a/src/video/Xext/Xxf86dga/XF86DGA2.c +++ b/src/video/Xext/Xxf86dga/XF86DGA2.c @@ -8,7 +8,7 @@ Copyright (c) 1995,1996 The XFree86 Project, Inc /* THIS IS NOT AN X CONSORTIUM STANDARD */ -#ifdef __EMX__ /* needed here to override certain constants in X headers */ +#ifdef __EMX__ /* needed here to override certain constants in X headers */ #define INCL_DOS #define INCL_DOSIOCTL #include @@ -24,7 +24,7 @@ Copyright (c) 1995,1996 The XFree86 Project, Inc #include "../extensions/extutil.h" #include -#if defined(ENABLE_FBCON) /* Needed for framebuffer console support */ +#if defined(ENABLE_FBCON) /* Needed for framebuffer console support */ #include #include #endif @@ -37,10 +37,11 @@ char *SDL_NAME(xdga_extension_name) = XF86DGANAME; static XExtensionInfo _xdga_info_data; static XExtensionInfo *xdga_info = &_xdga_info_data; - -Bool SDL_NAME(XDGAMapFramebuffer)(int, char *, unsigned char*, CARD32, CARD32, CARD32); -void SDL_NAME(XDGAUnmapFramebuffer)(int); -unsigned char* SDL_NAME(XDGAGetMappedMemory)(int); + +Bool SDL_NAME(XDGAMapFramebuffer) (int, char *, unsigned char *, CARD32, + CARD32, CARD32); +void SDL_NAME(XDGAUnmapFramebuffer) (int); +unsigned char *SDL_NAME(XDGAGetMappedMemory) (int); #define XDGACheckExtension(dpy,i,val) \ XextCheckExtension (dpy, i, SDL_NAME(xdga_extension_name), val) @@ -51,160 +52,143 @@ unsigned char* SDL_NAME(XDGAGetMappedMemory)(int); * * *****************************************************************************/ -static int xdga_close_display(Display *dpy, XExtCodes *codes); -static Bool xdga_wire_to_event(Display *dpy, XEvent *event, xEvent *wire_ev); -static Status xdga_event_to_wire(Display *dpy, XEvent *event, xEvent *wire_ev); +static int xdga_close_display(Display * dpy, XExtCodes * codes); +static Bool xdga_wire_to_event(Display * dpy, XEvent * event, + xEvent * wire_ev); +static Status xdga_event_to_wire(Display * dpy, XEvent * event, + xEvent * wire_ev); static XExtensionHooks xdga_extension_hooks = { - NULL, /* create_gc */ - NULL, /* copy_gc */ - NULL, /* flush_gc */ - NULL, /* free_gc */ - NULL, /* create_font */ - NULL, /* free_font */ - xdga_close_display, /* close_display */ - xdga_wire_to_event, /* wire_to_event */ - xdga_event_to_wire, /* event_to_wire */ - NULL, /* error */ - NULL, /* error_string */ + NULL, /* create_gc */ + NULL, /* copy_gc */ + NULL, /* flush_gc */ + NULL, /* free_gc */ + NULL, /* create_font */ + NULL, /* free_font */ + xdga_close_display, /* close_display */ + xdga_wire_to_event, /* wire_to_event */ + xdga_event_to_wire, /* event_to_wire */ + NULL, /* error */ + NULL, /* error_string */ }; -static XEXT_GENERATE_CLOSE_DISPLAY (xdga_close_display, xdga_info) - - -XEXT_GENERATE_FIND_DISPLAY (SDL_NAME(xdga_find_display), xdga_info, - "XFree86-DGA", - &xdga_extension_hooks, - 0, NULL) - - -static Status -xdga_event_to_wire( - Display *dpy, - XEvent *event, - xEvent *wire_ev -){ +static +XEXT_GENERATE_CLOSE_DISPLAY(xdga_close_display, xdga_info) +XEXT_GENERATE_FIND_DISPLAY(SDL_NAME(xdga_find_display), xdga_info, + "XFree86-DGA", &xdga_extension_hooks, 0, NULL) + static Status + xdga_event_to_wire(Display * dpy, XEvent * event, xEvent * wire_ev) +{ return True; } static Bool -xdga_wire_to_event( - Display *dpy, - XEvent *event, - xEvent *wire_ev -){ - dgaEvent *wire = (dgaEvent *) wire_ev; - SDL_NAME(XDGAButtonEvent) *bevent; - SDL_NAME(XDGAKeyEvent) *kevent; - SDL_NAME(XDGAMotionEvent) *mevent; - XExtDisplayInfo *info = SDL_NAME(xdga_find_display) (dpy); - - XDGACheckExtension (dpy, info, False); - - switch((wire->u.u.type & 0x7f) - info->codes->first_event) { - case MotionNotify: - mevent = (SDL_NAME(XDGAMotionEvent)*)event; - mevent->type = wire->u.u.type & 0x7F; - mevent->serial = _XSetLastRequestRead(dpy, (xGenericReply *)wire); - mevent->display = dpy; - mevent->screen = wire->u.event.screen; - mevent->time = wire->u.event.time; - mevent->state = wire->u.event.state; - mevent->dx = wire->u.event.dx; - mevent->dy = wire->u.event.dy; - return True; - case ButtonPress: - case ButtonRelease: - bevent = (SDL_NAME(XDGAButtonEvent)*)event; - bevent->type = wire->u.u.type & 0x7F; - bevent->serial = _XSetLastRequestRead(dpy, (xGenericReply *)wire); - bevent->display = dpy; - bevent->screen = wire->u.event.screen; - bevent->time = wire->u.event.time; - bevent->state = wire->u.event.state; - bevent->button = wire->u.u.detail; - return True; - case KeyPress: - case KeyRelease: - kevent = (SDL_NAME(XDGAKeyEvent)*)event; - kevent->type = wire->u.u.type & 0x7F; - kevent->serial = _XSetLastRequestRead(dpy, (xGenericReply *)wire); - kevent->display = dpy; - kevent->screen = wire->u.event.screen; - kevent->time = wire->u.event.time; - kevent->state = wire->u.event.state; - kevent->keycode = wire->u.u.detail; - return True; - } - - return False; +xdga_wire_to_event(Display * dpy, XEvent * event, xEvent * wire_ev) +{ + dgaEvent *wire = (dgaEvent *) wire_ev; + SDL_NAME(XDGAButtonEvent) * bevent; + SDL_NAME(XDGAKeyEvent) * kevent; + SDL_NAME(XDGAMotionEvent) * mevent; + XExtDisplayInfo *info = SDL_NAME(xdga_find_display) (dpy); + + XDGACheckExtension(dpy, info, False); + + switch ((wire->u.u.type & 0x7f) - info->codes->first_event) { + case MotionNotify: + mevent = (SDL_NAME(XDGAMotionEvent) *) event; + mevent->type = wire->u.u.type & 0x7F; + mevent->serial = _XSetLastRequestRead(dpy, (xGenericReply *) wire); + mevent->display = dpy; + mevent->screen = wire->u.event.screen; + mevent->time = wire->u.event.time; + mevent->state = wire->u.event.state; + mevent->dx = wire->u.event.dx; + mevent->dy = wire->u.event.dy; + return True; + case ButtonPress: + case ButtonRelease: + bevent = (SDL_NAME(XDGAButtonEvent) *) event; + bevent->type = wire->u.u.type & 0x7F; + bevent->serial = _XSetLastRequestRead(dpy, (xGenericReply *) wire); + bevent->display = dpy; + bevent->screen = wire->u.event.screen; + bevent->time = wire->u.event.time; + bevent->state = wire->u.event.state; + bevent->button = wire->u.u.detail; + return True; + case KeyPress: + case KeyRelease: + kevent = (SDL_NAME(XDGAKeyEvent) *) event; + kevent->type = wire->u.u.type & 0x7F; + kevent->serial = _XSetLastRequestRead(dpy, (xGenericReply *) wire); + kevent->display = dpy; + kevent->screen = wire->u.event.screen; + kevent->time = wire->u.event.time; + kevent->state = wire->u.event.state; + kevent->keycode = wire->u.u.detail; + return True; + } + + return False; } -Bool SDL_NAME(XDGAQueryExtension) ( - Display *dpy, - int *event_basep, - int *error_basep -){ +Bool SDL_NAME(XDGAQueryExtension) (Display * dpy, + int *event_basep, int *error_basep) +{ XExtDisplayInfo *info = SDL_NAME(xdga_find_display) (dpy); if (XextHasExtension(info)) { - *event_basep = info->codes->first_event; - *error_basep = info->codes->first_error; - return True; + *event_basep = info->codes->first_event; + *error_basep = info->codes->first_error; + return True; } else { - return False; + return False; } } -Bool SDL_NAME(XDGAQueryVersion)( - Display *dpy, - int *majorVersion, - int *minorVersion -){ +Bool SDL_NAME(XDGAQueryVersion) (Display * dpy, + int *majorVersion, int *minorVersion) +{ XExtDisplayInfo *info = SDL_NAME(xdga_find_display) (dpy); xXDGAQueryVersionReply rep; xXDGAQueryVersionReq *req; - XDGACheckExtension (dpy, info, False); + XDGACheckExtension(dpy, info, False); LockDisplay(dpy); GetReq(XDGAQueryVersion, req); req->reqType = info->codes->major_opcode; req->dgaReqType = X_XDGAQueryVersion; - if (!_XReply(dpy, (xReply *)&rep, 0, xFalse)) { - UnlockDisplay(dpy); - SyncHandle(); - return False; + if (!_XReply(dpy, (xReply *) & rep, 0, xFalse)) { + UnlockDisplay(dpy); + SyncHandle(); + return False; } *majorVersion = rep.majorVersion; *minorVersion = rep.minorVersion; UnlockDisplay(dpy); SyncHandle(); - if (*majorVersion >= 2) - { - int i, j; - - for (i = 0, j = info->codes->first_event; - i < XF86DGANumberEvents; - i++, j++) - { - XESetWireToEvent(dpy, j, xdga_wire_to_event); - XESetEventToWire(dpy, j, xdga_event_to_wire); - } - SDL_NAME(XDGASetClientVersion)(dpy); + if (*majorVersion >= 2) { + int i, j; + + for (i = 0, j = info->codes->first_event; + i < XF86DGANumberEvents; i++, j++) { + XESetWireToEvent(dpy, j, xdga_wire_to_event); + XESetEventToWire(dpy, j, xdga_event_to_wire); + } + SDL_NAME(XDGASetClientVersion) (dpy); } return True; } -Bool SDL_NAME(XDGASetClientVersion)( - Display *dpy -){ +Bool SDL_NAME(XDGASetClientVersion) (Display * dpy) +{ XExtDisplayInfo *info = SDL_NAME(xdga_find_display) (dpy); xXDGASetClientVersionReq *req; - XDGACheckExtension (dpy, info, False); + XDGACheckExtension(dpy, info, False); LockDisplay(dpy); GetReq(XDGASetClientVersion, req); @@ -217,56 +201,52 @@ Bool SDL_NAME(XDGASetClientVersion)( return True; } -Bool SDL_NAME(XDGAOpenFramebuffer)( - Display *dpy, - int screen -){ +Bool SDL_NAME(XDGAOpenFramebuffer) (Display * dpy, int screen) +{ XExtDisplayInfo *info = SDL_NAME(xdga_find_display) (dpy); xXDGAOpenFramebufferReply rep; xXDGAOpenFramebufferReq *req; char *deviceName = NULL; Bool ret; - XDGACheckExtension (dpy, info, False); + XDGACheckExtension(dpy, info, False); LockDisplay(dpy); GetReq(XDGAOpenFramebuffer, req); req->reqType = info->codes->major_opcode; req->dgaReqType = X_XDGAOpenFramebuffer; req->screen = screen; - if (!_XReply(dpy, (xReply *)&rep, 0, xFalse)) { - UnlockDisplay(dpy); - SyncHandle(); - return False; + if (!_XReply(dpy, (xReply *) & rep, 0, xFalse)) { + UnlockDisplay(dpy); + SyncHandle(); + return False; } - if(rep.length) { - deviceName = Xmalloc(rep.length << 2); - _XRead(dpy, deviceName, rep.length << 2); + if (rep.length) { + deviceName = Xmalloc(rep.length << 2); + _XRead(dpy, deviceName, rep.length << 2); } - ret = SDL_NAME(XDGAMapFramebuffer)(screen, deviceName, - (unsigned char*)(long)rep.mem1, - rep.size, rep.offset, rep.extra); + ret = SDL_NAME(XDGAMapFramebuffer) (screen, deviceName, + (unsigned char *) (long) rep.mem1, + rep.size, rep.offset, rep.extra); - if(deviceName) - Xfree(deviceName); + if (deviceName) + Xfree(deviceName); UnlockDisplay(dpy); SyncHandle(); return ret; } -void SDL_NAME(XDGACloseFramebuffer)( - Display *dpy, - int screen -){ +void SDL_NAME(XDGACloseFramebuffer) (Display * dpy, int screen) +{ XExtDisplayInfo *info = SDL_NAME(xdga_find_display) (dpy); xXDGACloseFramebufferReq *req; - XextSimpleCheckExtension (dpy, info, SDL_NAME(xdga_extension_name)); + XextSimpleCheckExtension(dpy, info, SDL_NAME(xdga_extension_name)); - SDL_NAME(XDGAUnmapFramebuffer)(screen); + SDL_NAME(XDGAUnmapFramebuffer) (screen); LockDisplay(dpy); GetReq(XDGACloseFramebuffer, req); @@ -279,19 +259,17 @@ void SDL_NAME(XDGACloseFramebuffer)( -SDL_NAME(XDGAMode)* SDL_NAME(XDGAQueryModes)( - Display *dpy, - int screen, - int *num -){ +SDL_NAME(XDGAMode) * SDL_NAME(XDGAQueryModes) (Display * dpy, + int screen, int *num) +{ XExtDisplayInfo *dinfo = SDL_NAME(xdga_find_display) (dpy); xXDGAQueryModesReply rep; xXDGAQueryModesReq *req; - SDL_NAME(XDGAMode) *modes = NULL; + SDL_NAME(XDGAMode) * modes = NULL; *num = 0; - XDGACheckExtension (dpy, dinfo, NULL); + XDGACheckExtension(dpy, dinfo, NULL); LockDisplay(dpy); GetReq(XDGAQueryModes, req); @@ -299,56 +277,57 @@ SDL_NAME(XDGAMode)* SDL_NAME(XDGAQueryModes)( req->dgaReqType = X_XDGAQueryModes; req->screen = screen; - if (_XReply(dpy, (xReply *)&rep, 0, xFalse)) { - if(rep.length) { - xXDGAModeInfo info; - int i, size; - char *offset; - - size = rep.length << 2; - size -= rep.number * sz_xXDGAModeInfo; /* find text size */ - modes = (SDL_NAME(XDGAMode)*)Xmalloc((rep.number * sizeof(SDL_NAME(XDGAMode))) + size); - offset = (char*)(&modes[rep.number]); /* start of text */ - - - if(modes) { - for(i = 0; i < rep.number; i++) { - _XRead(dpy, (char*)(&info), sz_xXDGAModeInfo); - - modes[i].num = info.num; - modes[i].verticalRefresh = - (float)info.vsync_num / (float)info.vsync_den; - modes[i].flags = info.flags; - modes[i].imageWidth = info.image_width; - modes[i].imageHeight = info.image_height; - modes[i].pixmapWidth = info.pixmap_width; - modes[i].pixmapHeight = info.pixmap_height; - modes[i].bytesPerScanline = info.bytes_per_scanline; - modes[i].byteOrder = info.byte_order; - modes[i].depth = info.depth; - modes[i].bitsPerPixel = info.bpp; - modes[i].redMask = info.red_mask; - modes[i].greenMask = info.green_mask; - modes[i].blueMask = info.blue_mask; - modes[i].visualClass = info.visual_class; - modes[i].viewportWidth = info.viewport_width; - modes[i].viewportHeight = info.viewport_height; - modes[i].xViewportStep = info.viewport_xstep; - modes[i].yViewportStep = info.viewport_ystep; - modes[i].maxViewportX = info.viewport_xmax; - modes[i].maxViewportY = info.viewport_ymax; - modes[i].viewportFlags = info.viewport_flags; - modes[i].reserved1 = info.reserved1; - modes[i].reserved2 = info.reserved2; - - _XRead(dpy, offset, info.name_size); - modes[i].name = offset; - offset += info.name_size; - } - *num = rep.number; - } else - _XEatData(dpy, rep.length << 2); - } + if (_XReply(dpy, (xReply *) & rep, 0, xFalse)) { + if (rep.length) { + xXDGAModeInfo info; + int i, size; + char *offset; + + size = rep.length << 2; + size -= rep.number * sz_xXDGAModeInfo; /* find text size */ + modes = (SDL_NAME(XDGAMode) *) + Xmalloc((rep.number * sizeof(SDL_NAME(XDGAMode))) + size); + offset = (char *) (&modes[rep.number]); /* start of text */ + + + if (modes) { + for (i = 0; i < rep.number; i++) { + _XRead(dpy, (char *) (&info), sz_xXDGAModeInfo); + + modes[i].num = info.num; + modes[i].verticalRefresh = + (float) info.vsync_num / (float) info.vsync_den; + modes[i].flags = info.flags; + modes[i].imageWidth = info.image_width; + modes[i].imageHeight = info.image_height; + modes[i].pixmapWidth = info.pixmap_width; + modes[i].pixmapHeight = info.pixmap_height; + modes[i].bytesPerScanline = info.bytes_per_scanline; + modes[i].byteOrder = info.byte_order; + modes[i].depth = info.depth; + modes[i].bitsPerPixel = info.bpp; + modes[i].redMask = info.red_mask; + modes[i].greenMask = info.green_mask; + modes[i].blueMask = info.blue_mask; + modes[i].visualClass = info.visual_class; + modes[i].viewportWidth = info.viewport_width; + modes[i].viewportHeight = info.viewport_height; + modes[i].xViewportStep = info.viewport_xstep; + modes[i].yViewportStep = info.viewport_ystep; + modes[i].maxViewportX = info.viewport_xmax; + modes[i].maxViewportY = info.viewport_ymax; + modes[i].viewportFlags = info.viewport_flags; + modes[i].reserved1 = info.reserved1; + modes[i].reserved2 = info.reserved2; + + _XRead(dpy, offset, info.name_size); + modes[i].name = offset; + offset += info.name_size; + } + *num = rep.number; + } else + _XEatData(dpy, rep.length << 2); + } } UnlockDisplay(dpy); @@ -358,19 +337,16 @@ SDL_NAME(XDGAMode)* SDL_NAME(XDGAQueryModes)( } -SDL_NAME(XDGADevice) * -SDL_NAME(XDGASetMode)( - Display *dpy, - int screen, - int mode -){ +SDL_NAME(XDGADevice) * +SDL_NAME(XDGASetMode) (Display * dpy, int screen, int mode) +{ XExtDisplayInfo *dinfo = SDL_NAME(xdga_find_display) (dpy); xXDGASetModeReply rep; xXDGASetModeReq *req; - SDL_NAME(XDGADevice) *dev = NULL; + SDL_NAME(XDGADevice) * dev = NULL; Pixmap pid; - XDGACheckExtension (dpy, dinfo, NULL); + XDGACheckExtension(dpy, dinfo, NULL); LockDisplay(dpy); GetReq(XDGASetMode, req); @@ -379,57 +355,58 @@ SDL_NAME(XDGASetMode)( req->screen = screen; req->mode = mode; req->pid = pid = XAllocID(dpy); - - if (_XReply(dpy, (xReply *)&rep, 0, xFalse)) { - if(rep.length) { - xXDGAModeInfo info; - int size; - - size = rep.length << 2; - size -= sz_xXDGAModeInfo; /* get text size */ - - dev = (SDL_NAME(XDGADevice)*)Xmalloc(sizeof(SDL_NAME(XDGADevice)) + size); - - if(dev) { - _XRead(dpy, (char*)(&info), sz_xXDGAModeInfo); - - dev->mode.num = info.num; - dev->mode.verticalRefresh = - (float)info.vsync_num / (float)info.vsync_den; - dev->mode.flags = info.flags; - dev->mode.imageWidth = info.image_width; - dev->mode.imageHeight = info.image_height; - dev->mode.pixmapWidth = info.pixmap_width; - dev->mode.pixmapHeight = info.pixmap_height; - dev->mode.bytesPerScanline = info.bytes_per_scanline; - dev->mode.byteOrder = info.byte_order; - dev->mode.depth = info.depth; - dev->mode.bitsPerPixel = info.bpp; - dev->mode.redMask = info.red_mask; - dev->mode.greenMask = info.green_mask; - dev->mode.blueMask = info.blue_mask; - dev->mode.visualClass = info.visual_class; - dev->mode.viewportWidth = info.viewport_width; - dev->mode.viewportHeight = info.viewport_height; - dev->mode.xViewportStep = info.viewport_xstep; - dev->mode.yViewportStep = info.viewport_ystep; - dev->mode.maxViewportX = info.viewport_xmax; - dev->mode.maxViewportY = info.viewport_ymax; - dev->mode.viewportFlags = info.viewport_flags; - dev->mode.reserved1 = info.reserved1; - dev->mode.reserved2 = info.reserved2; - - dev->mode.name = (char*)(&dev[1]); - _XRead(dpy, dev->mode.name, info.name_size); - - dev->pixmap = (rep.flags & XDGAPixmap) ? pid : 0; - dev->data = SDL_NAME(XDGAGetMappedMemory)(screen); - - if(dev->data) - dev->data += rep.offset; - } - /* not sure what to do if the allocation fails */ - } + + if (_XReply(dpy, (xReply *) & rep, 0, xFalse)) { + if (rep.length) { + xXDGAModeInfo info; + int size; + + size = rep.length << 2; + size -= sz_xXDGAModeInfo; /* get text size */ + + dev = (SDL_NAME(XDGADevice) *) + Xmalloc(sizeof(SDL_NAME(XDGADevice)) + size); + + if (dev) { + _XRead(dpy, (char *) (&info), sz_xXDGAModeInfo); + + dev->mode.num = info.num; + dev->mode.verticalRefresh = + (float) info.vsync_num / (float) info.vsync_den; + dev->mode.flags = info.flags; + dev->mode.imageWidth = info.image_width; + dev->mode.imageHeight = info.image_height; + dev->mode.pixmapWidth = info.pixmap_width; + dev->mode.pixmapHeight = info.pixmap_height; + dev->mode.bytesPerScanline = info.bytes_per_scanline; + dev->mode.byteOrder = info.byte_order; + dev->mode.depth = info.depth; + dev->mode.bitsPerPixel = info.bpp; + dev->mode.redMask = info.red_mask; + dev->mode.greenMask = info.green_mask; + dev->mode.blueMask = info.blue_mask; + dev->mode.visualClass = info.visual_class; + dev->mode.viewportWidth = info.viewport_width; + dev->mode.viewportHeight = info.viewport_height; + dev->mode.xViewportStep = info.viewport_xstep; + dev->mode.yViewportStep = info.viewport_ystep; + dev->mode.maxViewportX = info.viewport_xmax; + dev->mode.maxViewportY = info.viewport_ymax; + dev->mode.viewportFlags = info.viewport_flags; + dev->mode.reserved1 = info.reserved1; + dev->mode.reserved2 = info.reserved2; + + dev->mode.name = (char *) (&dev[1]); + _XRead(dpy, dev->mode.name, info.name_size); + + dev->pixmap = (rep.flags & XDGAPixmap) ? pid : 0; + dev->data = SDL_NAME(XDGAGetMappedMemory) (screen); + + if (dev->data) + dev->data += rep.offset; + } + /* not sure what to do if the allocation fails */ + } } UnlockDisplay(dpy); @@ -439,17 +416,13 @@ SDL_NAME(XDGASetMode)( } -void SDL_NAME(XDGASetViewport)( - Display *dpy, - int screen, - int x, - int y, - int flags -){ +void SDL_NAME(XDGASetViewport) (Display * dpy, + int screen, int x, int y, int flags) +{ XExtDisplayInfo *info = SDL_NAME(xdga_find_display) (dpy); xXDGASetViewportReq *req; - XextSimpleCheckExtension (dpy, info, SDL_NAME(xdga_extension_name)); + XextSimpleCheckExtension(dpy, info, SDL_NAME(xdga_extension_name)); LockDisplay(dpy); GetReq(XDGASetViewport, req); @@ -464,15 +437,12 @@ void SDL_NAME(XDGASetViewport)( } -void SDL_NAME(XDGAInstallColormap)( - Display *dpy, - int screen, - Colormap cmap -){ +void SDL_NAME(XDGAInstallColormap) (Display * dpy, int screen, Colormap cmap) +{ XExtDisplayInfo *info = SDL_NAME(xdga_find_display) (dpy); xXDGAInstallColormapReq *req; - XextSimpleCheckExtension (dpy, info, SDL_NAME(xdga_extension_name)); + XextSimpleCheckExtension(dpy, info, SDL_NAME(xdga_extension_name)); LockDisplay(dpy); GetReq(XDGAInstallColormap, req); @@ -484,15 +454,12 @@ void SDL_NAME(XDGAInstallColormap)( SyncHandle(); } -void SDL_NAME(XDGASelectInput)( - Display *dpy, - int screen, - long mask -){ +void SDL_NAME(XDGASelectInput) (Display * dpy, int screen, long mask) +{ XExtDisplayInfo *info = SDL_NAME(xdga_find_display) (dpy); xXDGASelectInputReq *req; - XextSimpleCheckExtension (dpy, info, SDL_NAME(xdga_extension_name)); + XextSimpleCheckExtension(dpy, info, SDL_NAME(xdga_extension_name)); LockDisplay(dpy); GetReq(XDGASelectInput, req); @@ -504,19 +471,17 @@ void SDL_NAME(XDGASelectInput)( SyncHandle(); } -void SDL_NAME(XDGAFillRectangle)( - Display *dpy, - int screen, - int x, - int y, - unsigned int width, - unsigned int height, - unsigned long color -){ +void SDL_NAME(XDGAFillRectangle) (Display * dpy, + int screen, + int x, + int y, + unsigned int width, + unsigned int height, unsigned long color) +{ XExtDisplayInfo *info = SDL_NAME(xdga_find_display) (dpy); xXDGAFillRectangleReq *req; - XextSimpleCheckExtension (dpy, info, SDL_NAME(xdga_extension_name)); + XextSimpleCheckExtension(dpy, info, SDL_NAME(xdga_extension_name)); LockDisplay(dpy); GetReq(XDGAFillRectangle, req); @@ -532,20 +497,17 @@ void SDL_NAME(XDGAFillRectangle)( SyncHandle(); } -void SDL_NAME(XDGACopyArea)( - Display *dpy, - int screen, - int srcx, - int srcy, - unsigned int width, - unsigned int height, - int dstx, - int dsty -){ +void SDL_NAME(XDGACopyArea) (Display * dpy, + int screen, + int srcx, + int srcy, + unsigned int width, + unsigned int height, int dstx, int dsty) +{ XExtDisplayInfo *info = SDL_NAME(xdga_find_display) (dpy); xXDGACopyAreaReq *req; - XextSimpleCheckExtension (dpy, info, SDL_NAME(xdga_extension_name)); + XextSimpleCheckExtension(dpy, info, SDL_NAME(xdga_extension_name)); LockDisplay(dpy); GetReq(XDGACopyArea, req); @@ -562,21 +524,18 @@ void SDL_NAME(XDGACopyArea)( SyncHandle(); } -void SDL_NAME(XDGACopyTransparentArea)( - Display *dpy, - int screen, - int srcx, - int srcy, - unsigned int width, - unsigned int height, - int dstx, - int dsty, - unsigned long key -){ +void SDL_NAME(XDGACopyTransparentArea) (Display * dpy, + int screen, + int srcx, + int srcy, + unsigned int width, + unsigned int height, + int dstx, int dsty, unsigned long key) +{ XExtDisplayInfo *info = SDL_NAME(xdga_find_display) (dpy); xXDGACopyTransparentAreaReq *req; - XextSimpleCheckExtension (dpy, info, SDL_NAME(xdga_extension_name)); + XextSimpleCheckExtension(dpy, info, SDL_NAME(xdga_extension_name)); LockDisplay(dpy); GetReq(XDGACopyTransparentArea, req); @@ -595,62 +554,54 @@ void SDL_NAME(XDGACopyTransparentArea)( } -int SDL_NAME(XDGAGetViewportStatus)( - Display *dpy, - int screen -){ +int SDL_NAME(XDGAGetViewportStatus) (Display * dpy, int screen) +{ XExtDisplayInfo *info = SDL_NAME(xdga_find_display) (dpy); xXDGAGetViewportStatusReply rep; xXDGAGetViewportStatusReq *req; int status = 0; - XDGACheckExtension (dpy, info, 0); + XDGACheckExtension(dpy, info, 0); LockDisplay(dpy); GetReq(XDGAGetViewportStatus, req); req->reqType = info->codes->major_opcode; req->dgaReqType = X_XDGAGetViewportStatus; req->screen = screen; - if (!_XReply(dpy, (xReply *)&rep, 0, xFalse)) - status = rep.status; + if (!_XReply(dpy, (xReply *) & rep, 0, xFalse)) + status = rep.status; UnlockDisplay(dpy); SyncHandle(); return status; } -void SDL_NAME(XDGASync)( - Display *dpy, - int screen -){ +void SDL_NAME(XDGASync) (Display * dpy, int screen) +{ XExtDisplayInfo *info = SDL_NAME(xdga_find_display) (dpy); xXDGASyncReply rep; xXDGASyncReq *req; - XextSimpleCheckExtension (dpy, info, SDL_NAME(xdga_extension_name)); + XextSimpleCheckExtension(dpy, info, SDL_NAME(xdga_extension_name)); LockDisplay(dpy); GetReq(XDGASync, req); req->reqType = info->codes->major_opcode; req->dgaReqType = X_XDGASync; req->screen = screen; - _XReply(dpy, (xReply *)&rep, 0, xFalse); + _XReply(dpy, (xReply *) & rep, 0, xFalse); UnlockDisplay(dpy); SyncHandle(); } -void SDL_NAME(XDGAChangePixmapMode)( - Display *dpy, - int screen, - int *x, - int *y, - int mode -){ +void SDL_NAME(XDGAChangePixmapMode) (Display * dpy, + int screen, int *x, int *y, int mode) +{ XExtDisplayInfo *info = SDL_NAME(xdga_find_display) (dpy); xXDGAChangePixmapModeReq *req; xXDGAChangePixmapModeReply rep; - XextSimpleCheckExtension (dpy, info, SDL_NAME(xdga_extension_name)); + XextSimpleCheckExtension(dpy, info, SDL_NAME(xdga_extension_name)); LockDisplay(dpy); GetReq(XDGAChangePixmapMode, req); @@ -660,24 +611,22 @@ void SDL_NAME(XDGAChangePixmapMode)( req->x = *x; req->y = *y; req->flags = mode; - _XReply(dpy, (xReply *)&rep, 0, xFalse); + _XReply(dpy, (xReply *) & rep, 0, xFalse); *x = rep.x; *y = rep.y; UnlockDisplay(dpy); SyncHandle(); } -Colormap SDL_NAME(XDGACreateColormap)( - Display *dpy, - int screen, - SDL_NAME(XDGADevice) *dev, - int alloc -){ +Colormap SDL_NAME(XDGACreateColormap) (Display * dpy, + int screen, + SDL_NAME(XDGADevice) * dev, int alloc) +{ XExtDisplayInfo *info = SDL_NAME(xdga_find_display) (dpy); xXDGACreateColormapReq *req; Colormap cid; - XDGACheckExtension (dpy, info, -1); + XDGACheckExtension(dpy, info, -1); LockDisplay(dpy); GetReq(XDGACreateColormap, req); @@ -694,10 +643,9 @@ Colormap SDL_NAME(XDGACreateColormap)( } -void SDL_NAME(XDGAKeyEventToXKeyEvent)( - SDL_NAME(XDGAKeyEvent)* dk, - XKeyEvent* xk -){ +void SDL_NAME(XDGAKeyEventToXKeyEvent) (SDL_NAME(XDGAKeyEvent) * dk, + XKeyEvent * xk) +{ xk->type = dk->type; xk->serial = dk->serial; xk->send_event = False; @@ -716,7 +664,7 @@ void SDL_NAME(XDGAKeyEventToXKeyEvent)( #include #include #include -#if defined(ISC) +#if defined(ISC) # define HAS_SVR3_MMAP # include # include @@ -754,115 +702,111 @@ void SDL_NAME(XDGAKeyEventToXKeyEvent)( -typedef struct _DGAMapRec{ - unsigned char *physical; - unsigned char *virtual; - CARD32 size; - int fd; - int screen; - struct _DGAMapRec *next; +typedef struct _DGAMapRec +{ + unsigned char *physical; + unsigned char *virtual; + CARD32 size; + int fd; + int screen; + struct _DGAMapRec *next; } DGAMapRec, *DGAMapPtr; static Bool -DGAMapPhysical(int, char*, unsigned char*, CARD32, CARD32, CARD32, DGAMapPtr); +DGAMapPhysical(int, char *, unsigned char *, CARD32, CARD32, CARD32, + DGAMapPtr); static void DGAUnmapPhysical(DGAMapPtr); static DGAMapPtr _Maps = NULL; -unsigned char* -SDL_NAME(XDGAGetMappedMemory)(int screen) +unsigned char *SDL_NAME(XDGAGetMappedMemory) (int screen) { DGAMapPtr pMap = _Maps; unsigned char *pntr = NULL; - while(pMap != NULL) { - if(pMap->screen == screen) { - pntr = pMap->virtual; - break; - } - pMap = pMap->next; + while (pMap != NULL) { + if (pMap->screen == screen) { + pntr = pMap->virtual; + break; + } + pMap = pMap->next; } return pntr; } -Bool -SDL_NAME(XDGAMapFramebuffer)( - int screen, - char *name, /* optional device name */ - unsigned char* base, /* physical memory */ - CARD32 size, /* size */ - CARD32 offset, /* optional offset */ - CARD32 extra /* optional extra data */ -){ - DGAMapPtr pMap = _Maps; - Bool result; - - /* is it already mapped ? */ - while(pMap != NULL) { - if(pMap->screen == screen) - return True; - pMap = pMap->next; - } - - if(extra & XDGANeedRoot) { - /* we should probably check if we have root permissions and - return False here */ - - } - - pMap = (DGAMapPtr)Xmalloc(sizeof(DGAMapRec)); - - result = DGAMapPhysical(screen, name, base, size, offset, extra, pMap); - - if(result) { - pMap->next = _Maps; - _Maps = pMap; - } else - Xfree(pMap); - - return result; +Bool SDL_NAME(XDGAMapFramebuffer) (int screen, char *name, /* optional device name */ + unsigned char *base, /* physical memory */ + CARD32 size, /* size */ + CARD32 offset, /* optional offset */ + CARD32 extra /* optional extra data */ + ) +{ + DGAMapPtr pMap = _Maps; + Bool result; + + /* is it already mapped ? */ + while (pMap != NULL) { + if (pMap->screen == screen) + return True; + pMap = pMap->next; + } + + if (extra & XDGANeedRoot) { + /* we should probably check if we have root permissions and + return False here */ + + } + + pMap = (DGAMapPtr) Xmalloc(sizeof(DGAMapRec)); + + result = DGAMapPhysical(screen, name, base, size, offset, extra, pMap); + + if (result) { + pMap->next = _Maps; + _Maps = pMap; + } else + Xfree(pMap); + + return result; } -void -SDL_NAME(XDGAUnmapFramebuffer)(int screen) +void SDL_NAME(XDGAUnmapFramebuffer) (int screen) { - DGAMapPtr pMap = _Maps; - DGAMapPtr pPrev = NULL; - - /* is it already mapped */ - while(pMap != NULL) { - if(pMap->screen == screen) - break; - pPrev = pMap; - pMap = pMap->next; + DGAMapPtr pMap = _Maps; + DGAMapPtr pPrev = NULL; + + /* is it already mapped */ + while (pMap != NULL) { + if (pMap->screen == screen) + break; + pPrev = pMap; + pMap = pMap->next; } - if(!pMap) - return; + if (!pMap) + return; DGAUnmapPhysical(pMap); - if(!pPrev) - _Maps = pMap->next; + if (!pPrev) + _Maps = pMap->next; else - pPrev->next = pMap->next; + pPrev->next = pMap->next; Xfree(pMap); } static Bool -DGAMapPhysical( - int screen, - char *name, /* optional device name */ - unsigned char* base, /* physical memory */ - CARD32 size, /* size */ - CARD32 offset, /* optional offset */ - CARD32 extra, /* optional extra data */ - DGAMapPtr pMap -) { +DGAMapPhysical(int screen, char *name, /* optional device name */ + unsigned char *base, /* physical memory */ + CARD32 size, /* size */ + CARD32 offset, /* optional offset */ + CARD32 extra, /* optional extra data */ + DGAMapPtr pMap) +{ #if defined(ISC) && defined(HAS_SVR3_MMAP) struct kd_memloc mloc; #elif defined(__EMX__) @@ -870,7 +814,7 @@ DGAMapPhysical( ULONG action; HFILE hfd; #endif - + base += offset; pMap->screen = screen; @@ -879,14 +823,14 @@ DGAMapPhysical( #if defined(ISC) && defined(HAS_SVR3_MMAP) if ((pMap->fd = open("/dev/mmap", O_RDWR)) < 0) - return False; - mloc.vaddr = (char *)0; - mloc.physaddr = (char *)base; + return False; + mloc.vaddr = (char *) 0; + mloc.physaddr = (char *) base; mloc.length = size; - mloc.ioflg=1; + mloc.ioflg = 1; - if ((pMap->virtual = (void *)ioctl(pMap->fd, MAP, &mloc)) == (void *)-1) - return False; + if ((pMap->virtual = (void *) ioctl(pMap->fd, MAP, &mloc)) == (void *) -1) + return False; #elif defined (__EMX__) /* * Dragon warning here! /dev/pmap$ is never closed, except on progam exit. @@ -895,43 +839,46 @@ DGAMapPhysical( */ rc = DosOpen("/dev/pmap$", &hfd, &action, 0, FILE_NORMAL, FILE_OPEN, - OPEN_ACCESS_READWRITE | OPEN_SHARE_DENYNONE, (PEAOP2)NULL); + OPEN_ACCESS_READWRITE | OPEN_SHARE_DENYNONE, (PEAOP2) NULL); if (rc != 0) - return False; + return False; { - struct map_ioctl { - union { - ULONG phys; - void* user; - } a; - ULONG size; - } pmap,dmap; - ULONG plen,dlen; + struct map_ioctl + { + union + { + ULONG phys; + void *user; + } a; + ULONG size; + } pmap, dmap; + ULONG plen, dlen; #define XFREE86_PMAP 0x76 #define PMAP_MAP 0x44 - pmap.a.phys = base; - pmap.size = size; - rc = DosDevIOCtl(hfd, XFREE86_PMAP, PMAP_MAP, - (PULONG)&pmap, sizeof(pmap), &plen, - (PULONG)&dmap, sizeof(dmap), &dlen); - if (rc == 0) { - pMap->virtual = dmap.a.user; - } - } - if (rc != 0) - return False; + pmap.a.phys = base; + pmap.size = size; + rc = DosDevIOCtl(hfd, XFREE86_PMAP, PMAP_MAP, + (PULONG) & pmap, sizeof(pmap), &plen, + (PULONG) & dmap, sizeof(dmap), &dlen); + if (rc == 0) { + pMap->virtual = dmap.a.user; + } + } + if (rc != 0) + return False; #elif defined (Lynx) - pMap->virtual = smem_create("XF86DGA", (char*)base, size, SM_READ|SM_WRITE); + pMap->virtual = + smem_create("XF86DGA", (char *) base, size, SM_READ | SM_WRITE); #else #ifndef MAP_FILE #define MAP_FILE 0 #endif if (!name) - name = DEV_MEM; + name = DEV_MEM; if ((pMap->fd = open(name, O_RDWR)) < 0) #if defined(ENABLE_FBCON) - { /* /dev/fb0 fallback added by Sam Lantinga */ + { /* /dev/fb0 fallback added by Sam Lantinga */ /* Try to fall back to /dev/fb on Linux - FIXME: verify the device */ struct fb_fix_screeninfo finfo; @@ -941,7 +888,7 @@ DGAMapPhysical( /* The useable framebuffer console memory may not be the whole framebuffer that X has access to. :-( */ - if ( ioctl(pMap->fd, FBIOGET_FSCREENINFO, &finfo) < 0 ) { + if (ioctl(pMap->fd, FBIOGET_FSCREENINFO, &finfo) < 0) { close(pMap->fd); return False; } @@ -953,12 +900,12 @@ DGAMapPhysical( size = pMap->size = finfo.smem_len; } #else - return False; + return False; #endif - pMap->virtual = mmap(NULL, size, PROT_READ | PROT_WRITE, - MAP_FILE | MAP_SHARED, pMap->fd, (off_t)base); - if (pMap->virtual == (void *)-1) - return False; + pMap->virtual = mmap(NULL, size, PROT_READ | PROT_WRITE, + MAP_FILE | MAP_SHARED, pMap->fd, (off_t) base); + if (pMap->virtual == (void *) -1) + return False; #endif #if !defined(ISC) && !defined(HAS_SVR3_MMAP) && !defined(Lynx) \ @@ -976,13 +923,15 @@ DGAUnmapPhysical(DGAMapPtr pMap) { #if !defined(ISC) && !defined(HAS_SVR3_MMAP) && !defined(Lynx) \ && !defined(__EMX__) - mprotect(pMap->virtual,pMap->size, PROT_READ); + mprotect(pMap->virtual, pMap->size, PROT_READ); #elif defined(Lynx) - /* XXX this doesn't allow enable after disable */ + /* XXX this doesn't allow enable after disable */ smem_create(NULL, pMap->virtual, pMap->size, SM_DETACH); smem_remove("XF86DGA"); #endif - /* We need to unmap and close too !!!!!!!!!!*/ + /* We need to unmap and close too !!!!!!!!!! */ } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/Xext/Xxf86vm/XF86VMode.c b/src/video/Xext/Xxf86vm/XF86VMode.c index 7901991fb..8fa2583ae 100644 --- a/src/video/Xext/Xxf86vm/XF86VMode.c +++ b/src/video/Xext/Xxf86vm/XF86VMode.c @@ -71,81 +71,78 @@ static char *xf86vidmode_extension_name = XF86VIDMODENAME; static XEXT_CLOSE_DISPLAY_PROTO(close_display); static /* const */ XExtensionHooks xf86vidmode_extension_hooks = { - NULL, /* create_gc */ - NULL, /* copy_gc */ - NULL, /* flush_gc */ - NULL, /* free_gc */ - NULL, /* create_font */ - NULL, /* free_font */ - close_display, /* close_display */ - NULL, /* wire_to_event */ - NULL, /* event_to_wire */ - NULL, /* error */ - NULL, /* error_string */ + NULL, /* create_gc */ + NULL, /* copy_gc */ + NULL, /* flush_gc */ + NULL, /* free_gc */ + NULL, /* create_font */ + NULL, /* free_font */ + close_display, /* close_display */ + NULL, /* wire_to_event */ + NULL, /* event_to_wire */ + NULL, /* error */ + NULL, /* error_string */ }; -static XEXT_GENERATE_FIND_DISPLAY (find_display, xf86vidmode_info, - xf86vidmode_extension_name, - &xf86vidmode_extension_hooks, - 0, NULL) - -static XEXT_GENERATE_CLOSE_DISPLAY (close_display, xf86vidmode_info) - - +static +XEXT_GENERATE_FIND_DISPLAY(find_display, xf86vidmode_info, + xf86vidmode_extension_name, + &xf86vidmode_extension_hooks, 0, NULL) + static XEXT_GENERATE_CLOSE_DISPLAY(close_display, xf86vidmode_info) /***************************************************************************** * * * public XFree86-VidMode Extension routines * * * *****************************************************************************/ - -Bool + Bool SDL_NAME(XF86VidModeQueryExtension) (dpy, event_basep, error_basep) - Display *dpy; - int *event_basep, *error_basep; + Display *dpy; + int *event_basep, *error_basep; { - XExtDisplayInfo *info = find_display (dpy); + XExtDisplayInfo *info = find_display(dpy); if (XextHasExtension(info)) { - *event_basep = info->codes->first_event; - *error_basep = info->codes->first_error; - return True; + *event_basep = info->codes->first_event; + *error_basep = info->codes->first_error; + return True; } else { - return False; + return False; } } -Bool -SDL_NAME(XF86VidModeQueryVersion)(dpy, majorVersion, minorVersion) - Display* dpy; - int* majorVersion; - int* minorVersion; +Bool SDL_NAME(XF86VidModeQueryVersion) (dpy, majorVersion, minorVersion) + Display * + dpy; + int * + majorVersion; + int * + minorVersion; { - XExtDisplayInfo *info = find_display (dpy); + XExtDisplayInfo *info = find_display(dpy); xXF86VidModeQueryVersionReply rep; xXF86VidModeQueryVersionReq *req; - XF86VidModeCheckExtension (dpy, info, False); + XF86VidModeCheckExtension(dpy, info, False); LockDisplay(dpy); GetReq(XF86VidModeQueryVersion, req); req->reqType = info->codes->major_opcode; req->xf86vidmodeReqType = X_XF86VidModeQueryVersion; - if (!_XReply(dpy, (xReply *)&rep, 0, xFalse)) { - UnlockDisplay(dpy); - SyncHandle(); - return False; + if (!_XReply(dpy, (xReply *) & rep, 0, xFalse)) { + UnlockDisplay(dpy); + SyncHandle(); + return False; } *majorVersion = rep.majorVersion; *minorVersion = rep.minorVersion; UnlockDisplay(dpy); SyncHandle(); if (*majorVersion >= 2) - SDL_NAME(XF86VidModeSetClientVersion)(dpy); + SDL_NAME(XF86VidModeSetClientVersion) (dpy); return True; } -Bool -SDL_NAME(XF86VidModeSetClientVersion)(Display *dpy) +Bool SDL_NAME(XF86VidModeSetClientVersion) (Display * dpy) { XExtDisplayInfo *info = find_display(dpy); xXF86VidModeSetClientVersionReq *req; @@ -164,7 +161,8 @@ SDL_NAME(XF86VidModeSetClientVersion)(Display *dpy) } Bool -SDL_NAME(XF86VidModeSetGamma)(Display *dpy, int screen, SDL_NAME(XF86VidModeGamma) *Gamma) +SDL_NAME(XF86VidModeSetGamma) (Display * dpy, int screen, + SDL_NAME(XF86VidModeGamma) * Gamma) { XExtDisplayInfo *info = find_display(dpy); xXF86VidModeSetGammaReq *req; @@ -176,112 +174,118 @@ SDL_NAME(XF86VidModeSetGamma)(Display *dpy, int screen, SDL_NAME(XF86VidModeGamm req->reqType = info->codes->major_opcode; req->xf86vidmodeReqType = X_XF86VidModeSetGamma; req->screen = screen; - req->red = (CARD32)(Gamma->red * 10000.); - req->green = (CARD32)(Gamma->green * 10000.); - req->blue = (CARD32)(Gamma->blue * 10000.); + req->red = (CARD32) (Gamma->red * 10000.); + req->green = (CARD32) (Gamma->green * 10000.); + req->blue = (CARD32) (Gamma->blue * 10000.); UnlockDisplay(dpy); SyncHandle(); return True; } Bool -SDL_NAME(XF86VidModeGetGamma)(Display *dpy, int screen, SDL_NAME(XF86VidModeGamma) *Gamma) +SDL_NAME(XF86VidModeGetGamma) (Display * dpy, int screen, + SDL_NAME(XF86VidModeGamma) * Gamma) { - XExtDisplayInfo *info = find_display (dpy); + XExtDisplayInfo *info = find_display(dpy); xXF86VidModeGetGammaReply rep; xXF86VidModeGetGammaReq *req; - XF86VidModeCheckExtension (dpy, info, False); + XF86VidModeCheckExtension(dpy, info, False); LockDisplay(dpy); GetReq(XF86VidModeGetGamma, req); req->reqType = info->codes->major_opcode; req->xf86vidmodeReqType = X_XF86VidModeGetGamma; req->screen = screen; - if (!_XReply(dpy, (xReply *)&rep, 0, xFalse)) { - UnlockDisplay(dpy); - SyncHandle(); - return False; + if (!_XReply(dpy, (xReply *) & rep, 0, xFalse)) { + UnlockDisplay(dpy); + SyncHandle(); + return False; } - Gamma->red = ((float)rep.red) / 10000.; - Gamma->green = ((float)rep.green) / 10000.; - Gamma->blue = ((float)rep.blue) / 10000.; + Gamma->red = ((float) rep.red) / 10000.; + Gamma->green = ((float) rep.green) / 10000.; + Gamma->blue = ((float) rep.blue) / 10000.; UnlockDisplay(dpy); SyncHandle(); return True; } -Bool -SDL_NAME(XF86VidModeGetModeLine)(dpy, screen, dotclock, modeline) - Display* dpy; - int screen; - int* dotclock; - SDL_NAME(XF86VidModeModeLine)* modeline; +Bool SDL_NAME(XF86VidModeGetModeLine) (dpy, screen, dotclock, modeline) + Display * + dpy; + int + screen; + int * + dotclock; +SDL_NAME(XF86VidModeModeLine) * modeline; { - XExtDisplayInfo *info = find_display (dpy); + XExtDisplayInfo *info = find_display(dpy); xXF86VidModeGetModeLineReply rep; xXF86OldVidModeGetModeLineReply oldrep; xXF86VidModeGetModeLineReq *req; int majorVersion, minorVersion; - XF86VidModeCheckExtension (dpy, info, False); - SDL_NAME(XF86VidModeQueryVersion)(dpy, &majorVersion, &minorVersion); + XF86VidModeCheckExtension(dpy, info, False); + SDL_NAME(XF86VidModeQueryVersion) (dpy, &majorVersion, &minorVersion); LockDisplay(dpy); GetReq(XF86VidModeGetModeLine, req); req->reqType = info->codes->major_opcode; req->xf86vidmodeReqType = X_XF86VidModeGetModeLine; req->screen = screen; - + if (majorVersion < 2) { - if (!_XReply(dpy, (xReply *)&oldrep, - (SIZEOF(xXF86OldVidModeGetModeLineReply) - SIZEOF(xReply)) >> 2, xFalse)) { - UnlockDisplay(dpy); - SyncHandle(); - return False; - } - *dotclock = oldrep.dotclock; - modeline->hdisplay = oldrep.hdisplay; - modeline->hsyncstart = oldrep.hsyncstart; - modeline->hsyncend = oldrep.hsyncend; - modeline->htotal = oldrep.htotal; - modeline->hskew = 0; - modeline->vdisplay = oldrep.vdisplay; - modeline->vsyncstart = oldrep.vsyncstart; - modeline->vsyncend = oldrep.vsyncend; - modeline->vtotal = oldrep.vtotal; - modeline->flags = oldrep.flags; - modeline->privsize = oldrep.privsize; + if (!_XReply(dpy, (xReply *) & oldrep, + (SIZEOF(xXF86OldVidModeGetModeLineReply) - + SIZEOF(xReply)) >> 2, xFalse)) { + UnlockDisplay(dpy); + SyncHandle(); + return False; + } + *dotclock = oldrep.dotclock; + modeline->hdisplay = oldrep.hdisplay; + modeline->hsyncstart = oldrep.hsyncstart; + modeline->hsyncend = oldrep.hsyncend; + modeline->htotal = oldrep.htotal; + modeline->hskew = 0; + modeline->vdisplay = oldrep.vdisplay; + modeline->vsyncstart = oldrep.vsyncstart; + modeline->vsyncend = oldrep.vsyncend; + modeline->vtotal = oldrep.vtotal; + modeline->flags = oldrep.flags; + modeline->privsize = oldrep.privsize; } else { - if (!_XReply(dpy, (xReply *)&rep, - (SIZEOF(xXF86VidModeGetModeLineReply) - SIZEOF(xReply)) >> 2, xFalse)) { - UnlockDisplay(dpy); - SyncHandle(); - return False; - } - *dotclock = rep.dotclock; - modeline->hdisplay = rep.hdisplay; - modeline->hsyncstart = rep.hsyncstart; - modeline->hsyncend = rep.hsyncend; - modeline->htotal = rep.htotal; - modeline->hskew = rep.hskew; - modeline->vdisplay = rep.vdisplay; - modeline->vsyncstart = rep.vsyncstart; - modeline->vsyncend = rep.vsyncend; - modeline->vtotal = rep.vtotal; - modeline->flags = rep.flags; - modeline->privsize = rep.privsize; + if (!_XReply(dpy, (xReply *) & rep, + (SIZEOF(xXF86VidModeGetModeLineReply) - + SIZEOF(xReply)) >> 2, xFalse)) { + UnlockDisplay(dpy); + SyncHandle(); + return False; + } + *dotclock = rep.dotclock; + modeline->hdisplay = rep.hdisplay; + modeline->hsyncstart = rep.hsyncstart; + modeline->hsyncend = rep.hsyncend; + modeline->htotal = rep.htotal; + modeline->hskew = rep.hskew; + modeline->vdisplay = rep.vdisplay; + modeline->vsyncstart = rep.vsyncstart; + modeline->vsyncend = rep.vsyncend; + modeline->vtotal = rep.vtotal; + modeline->flags = rep.flags; + modeline->privsize = rep.privsize; } - + if (modeline->privsize > 0) { - if (!(modeline->private = Xcalloc(modeline->privsize, sizeof(INT32)))) { - _XEatData(dpy, (modeline->privsize) * sizeof(INT32)); - Xfree(modeline->private); - return False; - } - _XRead(dpy, (char*)modeline->private, modeline->privsize * sizeof(INT32)); + if (!(modeline->private = Xcalloc(modeline->privsize, sizeof(INT32)))) { + _XEatData(dpy, (modeline->privsize) * sizeof(INT32)); + Xfree(modeline->private); + return False; + } + _XRead(dpy, (char *) modeline->private, + modeline->privsize * sizeof(INT32)); } else { - modeline->private = NULL; + modeline->private = NULL; } UnlockDisplay(dpy); SyncHandle(); @@ -289,23 +293,23 @@ SDL_NAME(XF86VidModeGetModeLine)(dpy, screen, dotclock, modeline) } Bool -SDL_NAME(XF86VidModeGetAllModeLines)(dpy, screen, modecount, modelinesPtr) - Display* dpy; - int screen; - int* modecount; - SDL_NAME(XF86VidModeModeInfo) ***modelinesPtr; +SDL_NAME(XF86VidModeGetAllModeLines) (dpy, screen, modecount, modelinesPtr) + Display *dpy; + int screen; + int *modecount; +SDL_NAME(XF86VidModeModeInfo) *** modelinesPtr; { - XExtDisplayInfo *info = find_display (dpy); + XExtDisplayInfo *info = find_display(dpy); xXF86VidModeGetAllModeLinesReply rep; xXF86VidModeGetAllModeLinesReq *req; - SDL_NAME(XF86VidModeModeInfo) *mdinfptr, **modelines; + SDL_NAME(XF86VidModeModeInfo) * mdinfptr, **modelines; xXF86VidModeModeInfo xmdline; xXF86OldVidModeModeInfo oldxmdline; int i; int majorVersion, minorVersion; Bool protocolBug = False; - XF86VidModeCheckExtension (dpy, info, False); + XF86VidModeCheckExtension(dpy, info, False); /* * Note: There was a bug in the protocol implementation in versions @@ -313,112 +317,122 @@ SDL_NAME(XF86VidModeGetAllModeLines)(dpy, screen, modecount, modelinesPtr) * Check the server's version, and accept the old format if appropriate. */ - SDL_NAME(XF86VidModeQueryVersion)(dpy, &majorVersion, &minorVersion); + SDL_NAME(XF86VidModeQueryVersion) (dpy, &majorVersion, &minorVersion); if (majorVersion == 0 && minorVersion < 8) { - protocolBug = True; + protocolBug = True; #ifdef DEBUG - fprintf(stderr, "XF86VidModeGetAllModeLines: Warning: Xserver is" - "running an old version (%d.%d)\n", majorVersion, - minorVersion); + fprintf(stderr, "XF86VidModeGetAllModeLines: Warning: Xserver is" + "running an old version (%d.%d)\n", majorVersion, + minorVersion); #endif } - + LockDisplay(dpy); GetReq(XF86VidModeGetAllModeLines, req); req->reqType = info->codes->major_opcode; req->xf86vidmodeReqType = X_XF86VidModeGetAllModeLines; req->screen = screen; - if (!_XReply(dpy, (xReply *)&rep, - (SIZEOF(xXF86VidModeGetAllModeLinesReply) - SIZEOF(xReply)) >> 2, xFalse)) { + if (!_XReply(dpy, (xReply *) & rep, + (SIZEOF(xXF86VidModeGetAllModeLinesReply) - + SIZEOF(xReply)) >> 2, xFalse)) { UnlockDisplay(dpy); - SyncHandle(); - return False; + SyncHandle(); + return False; } *modecount = rep.modecount; - if (!(modelines = (SDL_NAME(XF86VidModeModeInfo) **) Xcalloc(rep.modecount, - sizeof(SDL_NAME(XF86VidModeModeInfo) *) - +sizeof(SDL_NAME(XF86VidModeModeInfo))))) { - if (majorVersion < 2) + if (! + (modelines = + (SDL_NAME(XF86VidModeModeInfo) **) Xcalloc(rep.modecount, + sizeof(SDL_NAME + (XF86VidModeModeInfo) + *) + + sizeof(SDL_NAME + (XF86VidModeModeInfo))))) + { + if (majorVersion < 2) _XEatData(dpy, (rep.modecount) * sizeof(xXF86OldVidModeModeInfo)); - else + else _XEatData(dpy, (rep.modecount) * sizeof(xXF86VidModeModeInfo)); Xfree(modelines); UnlockDisplay(dpy); SyncHandle(); return False; } - mdinfptr = (SDL_NAME(XF86VidModeModeInfo) *) ( - (char *) modelines - + rep.modecount*sizeof(SDL_NAME(XF86VidModeModeInfo) *) - ); + mdinfptr = (SDL_NAME(XF86VidModeModeInfo) *) ((char *) modelines + + + rep.modecount * + sizeof(SDL_NAME + (XF86VidModeModeInfo) + *)); for (i = 0; i < rep.modecount; i++) { modelines[i] = mdinfptr++; - if (majorVersion < 2) { - _XRead(dpy, (char*)&oldxmdline, sizeof(xXF86OldVidModeModeInfo)); - modelines[i]->dotclock = oldxmdline.dotclock; - modelines[i]->hdisplay = oldxmdline.hdisplay; - modelines[i]->hsyncstart = oldxmdline.hsyncstart; - modelines[i]->hsyncend = oldxmdline.hsyncend; - modelines[i]->htotal = oldxmdline.htotal; - modelines[i]->hskew = 0; - modelines[i]->vdisplay = oldxmdline.vdisplay; - modelines[i]->vsyncstart = oldxmdline.vsyncstart; - modelines[i]->vsyncend = oldxmdline.vsyncend; - modelines[i]->vtotal = oldxmdline.vtotal; - modelines[i]->flags = oldxmdline.flags; - if (protocolBug) { - modelines[i]->privsize = 0; - modelines[i]->private = NULL; - } else { - modelines[i]->privsize = oldxmdline.privsize; - if (oldxmdline.privsize > 0) { - if (!(modelines[i]->private = - Xcalloc(oldxmdline.privsize, sizeof(INT32)))) { - _XEatData(dpy, (oldxmdline.privsize) * sizeof(INT32)); - Xfree(modelines[i]->private); - } else { - _XRead(dpy, (char*)modelines[i]->private, - oldxmdline.privsize * sizeof(INT32)); - } - } else { - modelines[i]->private = NULL; - } - } - } else { - _XRead(dpy, (char*)&xmdline, sizeof(xXF86VidModeModeInfo)); - modelines[i]->dotclock = xmdline.dotclock; - modelines[i]->hdisplay = xmdline.hdisplay; - modelines[i]->hsyncstart = xmdline.hsyncstart; - modelines[i]->hsyncend = xmdline.hsyncend; - modelines[i]->htotal = xmdline.htotal; - modelines[i]->hskew = xmdline.hskew; - modelines[i]->vdisplay = xmdline.vdisplay; - modelines[i]->vsyncstart = xmdline.vsyncstart; - modelines[i]->vsyncend = xmdline.vsyncend; - modelines[i]->vtotal = xmdline.vtotal; - modelines[i]->flags = xmdline.flags; - if (protocolBug) { - modelines[i]->privsize = 0; - modelines[i]->private = NULL; - } else { - modelines[i]->privsize = xmdline.privsize; - if (xmdline.privsize > 0) { - if (!(modelines[i]->private = - Xcalloc(xmdline.privsize, sizeof(INT32)))) { - _XEatData(dpy, (xmdline.privsize) * sizeof(INT32)); - Xfree(modelines[i]->private); - } else { - _XRead(dpy, (char*)modelines[i]->private, - xmdline.privsize * sizeof(INT32)); - } - } else { - modelines[i]->private = NULL; - } - } - } + if (majorVersion < 2) { + _XRead(dpy, (char *) &oldxmdline, + sizeof(xXF86OldVidModeModeInfo)); + modelines[i]->dotclock = oldxmdline.dotclock; + modelines[i]->hdisplay = oldxmdline.hdisplay; + modelines[i]->hsyncstart = oldxmdline.hsyncstart; + modelines[i]->hsyncend = oldxmdline.hsyncend; + modelines[i]->htotal = oldxmdline.htotal; + modelines[i]->hskew = 0; + modelines[i]->vdisplay = oldxmdline.vdisplay; + modelines[i]->vsyncstart = oldxmdline.vsyncstart; + modelines[i]->vsyncend = oldxmdline.vsyncend; + modelines[i]->vtotal = oldxmdline.vtotal; + modelines[i]->flags = oldxmdline.flags; + if (protocolBug) { + modelines[i]->privsize = 0; + modelines[i]->private = NULL; + } else { + modelines[i]->privsize = oldxmdline.privsize; + if (oldxmdline.privsize > 0) { + if (!(modelines[i]->private = + Xcalloc(oldxmdline.privsize, sizeof(INT32)))) { + _XEatData(dpy, (oldxmdline.privsize) * sizeof(INT32)); + Xfree(modelines[i]->private); + } else { + _XRead(dpy, (char *) modelines[i]->private, + oldxmdline.privsize * sizeof(INT32)); + } + } else { + modelines[i]->private = NULL; + } + } + } else { + _XRead(dpy, (char *) &xmdline, sizeof(xXF86VidModeModeInfo)); + modelines[i]->dotclock = xmdline.dotclock; + modelines[i]->hdisplay = xmdline.hdisplay; + modelines[i]->hsyncstart = xmdline.hsyncstart; + modelines[i]->hsyncend = xmdline.hsyncend; + modelines[i]->htotal = xmdline.htotal; + modelines[i]->hskew = xmdline.hskew; + modelines[i]->vdisplay = xmdline.vdisplay; + modelines[i]->vsyncstart = xmdline.vsyncstart; + modelines[i]->vsyncend = xmdline.vsyncend; + modelines[i]->vtotal = xmdline.vtotal; + modelines[i]->flags = xmdline.flags; + if (protocolBug) { + modelines[i]->privsize = 0; + modelines[i]->private = NULL; + } else { + modelines[i]->privsize = xmdline.privsize; + if (xmdline.privsize > 0) { + if (!(modelines[i]->private = + Xcalloc(xmdline.privsize, sizeof(INT32)))) { + _XEatData(dpy, (xmdline.privsize) * sizeof(INT32)); + Xfree(modelines[i]->private); + } else { + _XRead(dpy, (char *) modelines[i]->private, + xmdline.privsize * sizeof(INT32)); + } + } else { + modelines[i]->private = NULL; + } + } + } } *modelinesPtr = modelines; UnlockDisplay(dpy); @@ -440,7 +454,7 @@ SDL_NAME(XF86VidModeGetAllModeLines)(dpy, screen, modecount, modelinesPtr) dpy->bufptr += SIZEOF(x##oldname##Req);\ dpy->request++ -#else /* non-ANSI C uses empty comment instead of "##" for token concatenation */ +#else /* non-ANSI C uses empty comment instead of "##" for token concatenation */ #define GetOldReq(name, oldname, req) \ WORD64ALIGN\ if ((dpy->bufptr + SIZEOF(x/**/oldname/**/Req)) > dpy->bufmax)\ @@ -454,324 +468,331 @@ SDL_NAME(XF86VidModeGetAllModeLines)(dpy, screen, modecount, modelinesPtr) Bool SDL_NAME(XF86VidModeAddModeLine) (dpy, screen, newmodeline, aftermodeline) - Display *dpy; - int screen; - SDL_NAME(XF86VidModeModeInfo)* newmodeline; - SDL_NAME(XF86VidModeModeInfo)* aftermodeline; + Display *dpy; + int screen; +SDL_NAME(XF86VidModeModeInfo) * newmodeline; +SDL_NAME(XF86VidModeModeInfo) * aftermodeline; { - XExtDisplayInfo *info = find_display (dpy); + XExtDisplayInfo *info = find_display(dpy); xXF86VidModeAddModeLineReq *req; xXF86OldVidModeAddModeLineReq *oldreq; int majorVersion, minorVersion; - XF86VidModeCheckExtension (dpy, info, False); - SDL_NAME(XF86VidModeQueryVersion)(dpy, &majorVersion, &minorVersion); + XF86VidModeCheckExtension(dpy, info, False); + SDL_NAME(XF86VidModeQueryVersion) (dpy, &majorVersion, &minorVersion); LockDisplay(dpy); if (majorVersion < 2) { - GetOldReq(XF86VidModeAddModeLine, XF86OldVidModeAddModeLine, oldreq); - oldreq->reqType = info->codes->major_opcode; - oldreq->xf86vidmodeReqType = X_XF86VidModeAddModeLine; - oldreq->screen = screen; - oldreq->dotclock = newmodeline->dotclock; - oldreq->hdisplay = newmodeline->hdisplay; - oldreq->hsyncstart = newmodeline->hsyncstart; - oldreq->hsyncend = newmodeline->hsyncend; - oldreq->htotal = newmodeline->htotal; - oldreq->vdisplay = newmodeline->vdisplay; - oldreq->vsyncstart = newmodeline->vsyncstart; - oldreq->vsyncend = newmodeline->vsyncend; - oldreq->vtotal = newmodeline->vtotal; - oldreq->flags = newmodeline->flags; - oldreq->privsize = newmodeline->privsize; - if (aftermodeline != NULL) { - oldreq->after_dotclock = aftermodeline->dotclock; - oldreq->after_hdisplay = aftermodeline->hdisplay; - oldreq->after_hsyncstart = aftermodeline->hsyncstart; - oldreq->after_hsyncend = aftermodeline->hsyncend; - oldreq->after_htotal = aftermodeline->htotal; - oldreq->after_vdisplay = aftermodeline->vdisplay; - oldreq->after_vsyncstart = aftermodeline->vsyncstart; - oldreq->after_vsyncend = aftermodeline->vsyncend; - oldreq->after_vtotal = aftermodeline->vtotal; - oldreq->after_flags = aftermodeline->flags; - } else { - oldreq->after_dotclock = 0; - oldreq->after_hdisplay = 0; - oldreq->after_hsyncstart = 0; - oldreq->after_hsyncend = 0; - oldreq->after_htotal = 0; - oldreq->after_vdisplay = 0; - oldreq->after_vsyncstart = 0; - oldreq->after_vsyncend = 0; - oldreq->after_vtotal = 0; - oldreq->after_flags = 0; - } - if (newmodeline->privsize) { - oldreq->length += newmodeline->privsize; - Data32(dpy, (long *) newmodeline->private, - newmodeline->privsize * sizeof(INT32)); - } + GetOldReq(XF86VidModeAddModeLine, XF86OldVidModeAddModeLine, oldreq); + oldreq->reqType = info->codes->major_opcode; + oldreq->xf86vidmodeReqType = X_XF86VidModeAddModeLine; + oldreq->screen = screen; + oldreq->dotclock = newmodeline->dotclock; + oldreq->hdisplay = newmodeline->hdisplay; + oldreq->hsyncstart = newmodeline->hsyncstart; + oldreq->hsyncend = newmodeline->hsyncend; + oldreq->htotal = newmodeline->htotal; + oldreq->vdisplay = newmodeline->vdisplay; + oldreq->vsyncstart = newmodeline->vsyncstart; + oldreq->vsyncend = newmodeline->vsyncend; + oldreq->vtotal = newmodeline->vtotal; + oldreq->flags = newmodeline->flags; + oldreq->privsize = newmodeline->privsize; + if (aftermodeline != NULL) { + oldreq->after_dotclock = aftermodeline->dotclock; + oldreq->after_hdisplay = aftermodeline->hdisplay; + oldreq->after_hsyncstart = aftermodeline->hsyncstart; + oldreq->after_hsyncend = aftermodeline->hsyncend; + oldreq->after_htotal = aftermodeline->htotal; + oldreq->after_vdisplay = aftermodeline->vdisplay; + oldreq->after_vsyncstart = aftermodeline->vsyncstart; + oldreq->after_vsyncend = aftermodeline->vsyncend; + oldreq->after_vtotal = aftermodeline->vtotal; + oldreq->after_flags = aftermodeline->flags; + } else { + oldreq->after_dotclock = 0; + oldreq->after_hdisplay = 0; + oldreq->after_hsyncstart = 0; + oldreq->after_hsyncend = 0; + oldreq->after_htotal = 0; + oldreq->after_vdisplay = 0; + oldreq->after_vsyncstart = 0; + oldreq->after_vsyncend = 0; + oldreq->after_vtotal = 0; + oldreq->after_flags = 0; + } + if (newmodeline->privsize) { + oldreq->length += newmodeline->privsize; + Data32(dpy, (long *) newmodeline->private, + newmodeline->privsize * sizeof(INT32)); + } } else { - GetReq(XF86VidModeAddModeLine, req); - req->reqType = info->codes->major_opcode; - req->xf86vidmodeReqType = X_XF86VidModeAddModeLine; - req->screen = screen; - req->dotclock = newmodeline->dotclock; - req->hdisplay = newmodeline->hdisplay; - req->hsyncstart = newmodeline->hsyncstart; - req->hsyncend = newmodeline->hsyncend; - req->htotal = newmodeline->htotal; - req->hskew = newmodeline->hskew; - req->vdisplay = newmodeline->vdisplay; - req->vsyncstart = newmodeline->vsyncstart; - req->vsyncend = newmodeline->vsyncend; - req->vtotal = newmodeline->vtotal; - req->flags = newmodeline->flags; - req->privsize = newmodeline->privsize; - if (aftermodeline != NULL) { - req->after_dotclock = aftermodeline->dotclock; - req->after_hdisplay = aftermodeline->hdisplay; - req->after_hsyncstart = aftermodeline->hsyncstart; - req->after_hsyncend = aftermodeline->hsyncend; - req->after_htotal = aftermodeline->htotal; - req->after_hskew = aftermodeline->hskew; - req->after_vdisplay = aftermodeline->vdisplay; - req->after_vsyncstart = aftermodeline->vsyncstart; - req->after_vsyncend = aftermodeline->vsyncend; - req->after_vtotal = aftermodeline->vtotal; - req->after_flags = aftermodeline->flags; - } else { - req->after_dotclock = 0; - req->after_hdisplay = 0; - req->after_hsyncstart = 0; - req->after_hsyncend = 0; - req->after_htotal = 0; - req->after_hskew = 0; - req->after_vdisplay = 0; - req->after_vsyncstart = 0; - req->after_vsyncend = 0; - req->after_vtotal = 0; - req->after_flags = 0; - } - if (newmodeline->privsize) { - req->length += newmodeline->privsize; - Data32(dpy, (long *) newmodeline->private, - newmodeline->privsize * sizeof(INT32)); - } + GetReq(XF86VidModeAddModeLine, req); + req->reqType = info->codes->major_opcode; + req->xf86vidmodeReqType = X_XF86VidModeAddModeLine; + req->screen = screen; + req->dotclock = newmodeline->dotclock; + req->hdisplay = newmodeline->hdisplay; + req->hsyncstart = newmodeline->hsyncstart; + req->hsyncend = newmodeline->hsyncend; + req->htotal = newmodeline->htotal; + req->hskew = newmodeline->hskew; + req->vdisplay = newmodeline->vdisplay; + req->vsyncstart = newmodeline->vsyncstart; + req->vsyncend = newmodeline->vsyncend; + req->vtotal = newmodeline->vtotal; + req->flags = newmodeline->flags; + req->privsize = newmodeline->privsize; + if (aftermodeline != NULL) { + req->after_dotclock = aftermodeline->dotclock; + req->after_hdisplay = aftermodeline->hdisplay; + req->after_hsyncstart = aftermodeline->hsyncstart; + req->after_hsyncend = aftermodeline->hsyncend; + req->after_htotal = aftermodeline->htotal; + req->after_hskew = aftermodeline->hskew; + req->after_vdisplay = aftermodeline->vdisplay; + req->after_vsyncstart = aftermodeline->vsyncstart; + req->after_vsyncend = aftermodeline->vsyncend; + req->after_vtotal = aftermodeline->vtotal; + req->after_flags = aftermodeline->flags; + } else { + req->after_dotclock = 0; + req->after_hdisplay = 0; + req->after_hsyncstart = 0; + req->after_hsyncend = 0; + req->after_htotal = 0; + req->after_hskew = 0; + req->after_vdisplay = 0; + req->after_vsyncstart = 0; + req->after_vsyncend = 0; + req->after_vtotal = 0; + req->after_flags = 0; + } + if (newmodeline->privsize) { + req->length += newmodeline->privsize; + Data32(dpy, (long *) newmodeline->private, + newmodeline->privsize * sizeof(INT32)); + } } UnlockDisplay(dpy); SyncHandle(); return True; } -Bool -SDL_NAME(XF86VidModeDeleteModeLine) (dpy, screen, modeline) - Display *dpy; - int screen; - SDL_NAME(XF86VidModeModeInfo)* modeline; +Bool SDL_NAME(XF86VidModeDeleteModeLine) (dpy, screen, modeline) + Display * + dpy; + int + screen; +SDL_NAME(XF86VidModeModeInfo) * modeline; { - XExtDisplayInfo *info = find_display (dpy); + XExtDisplayInfo *info = find_display(dpy); xXF86VidModeDeleteModeLineReq *req; xXF86OldVidModeDeleteModeLineReq *oldreq; int majorVersion, minorVersion; - XF86VidModeCheckExtension (dpy, info, 0); - SDL_NAME(XF86VidModeQueryVersion)(dpy, &majorVersion, &minorVersion); + XF86VidModeCheckExtension(dpy, info, 0); + SDL_NAME(XF86VidModeQueryVersion) (dpy, &majorVersion, &minorVersion); LockDisplay(dpy); if (majorVersion < 2) { - GetOldReq(XF86VidModeDeleteModeLine, XF86OldVidModeDeleteModeLine, oldreq); - oldreq->reqType = info->codes->major_opcode; - oldreq->xf86vidmodeReqType = X_XF86VidModeDeleteModeLine; - oldreq->screen = screen; - oldreq->dotclock = modeline->dotclock; - oldreq->hdisplay = modeline->hdisplay; - oldreq->hsyncstart = modeline->hsyncstart; - oldreq->hsyncend = modeline->hsyncend; - oldreq->htotal = modeline->htotal; - oldreq->vdisplay = modeline->vdisplay; - oldreq->vsyncstart = modeline->vsyncstart; - oldreq->vsyncend = modeline->vsyncend; - oldreq->vtotal = modeline->vtotal; - oldreq->flags = modeline->flags; - oldreq->privsize = modeline->privsize; - if (modeline->privsize) { - oldreq->length += modeline->privsize; - Data32(dpy, (long *) modeline->private, - modeline->privsize * sizeof(INT32)); - } + GetOldReq(XF86VidModeDeleteModeLine, XF86OldVidModeDeleteModeLine, + oldreq); + oldreq->reqType = info->codes->major_opcode; + oldreq->xf86vidmodeReqType = X_XF86VidModeDeleteModeLine; + oldreq->screen = screen; + oldreq->dotclock = modeline->dotclock; + oldreq->hdisplay = modeline->hdisplay; + oldreq->hsyncstart = modeline->hsyncstart; + oldreq->hsyncend = modeline->hsyncend; + oldreq->htotal = modeline->htotal; + oldreq->vdisplay = modeline->vdisplay; + oldreq->vsyncstart = modeline->vsyncstart; + oldreq->vsyncend = modeline->vsyncend; + oldreq->vtotal = modeline->vtotal; + oldreq->flags = modeline->flags; + oldreq->privsize = modeline->privsize; + if (modeline->privsize) { + oldreq->length += modeline->privsize; + Data32(dpy, (long *) modeline->private, + modeline->privsize * sizeof(INT32)); + } } else { - GetReq(XF86VidModeDeleteModeLine, req); - req->reqType = info->codes->major_opcode; - req->xf86vidmodeReqType = X_XF86VidModeDeleteModeLine; - req->screen = screen; - req->dotclock = modeline->dotclock; - req->hdisplay = modeline->hdisplay; - req->hsyncstart = modeline->hsyncstart; - req->hsyncend = modeline->hsyncend; - req->htotal = modeline->htotal; - req->hskew = modeline->hskew; - req->vdisplay = modeline->vdisplay; - req->vsyncstart = modeline->vsyncstart; - req->vsyncend = modeline->vsyncend; - req->vtotal = modeline->vtotal; - req->flags = modeline->flags; - req->privsize = modeline->privsize; - if (modeline->privsize) { - req->length += modeline->privsize; - Data32(dpy, (long *) modeline->private, - modeline->privsize * sizeof(INT32)); - } + GetReq(XF86VidModeDeleteModeLine, req); + req->reqType = info->codes->major_opcode; + req->xf86vidmodeReqType = X_XF86VidModeDeleteModeLine; + req->screen = screen; + req->dotclock = modeline->dotclock; + req->hdisplay = modeline->hdisplay; + req->hsyncstart = modeline->hsyncstart; + req->hsyncend = modeline->hsyncend; + req->htotal = modeline->htotal; + req->hskew = modeline->hskew; + req->vdisplay = modeline->vdisplay; + req->vsyncstart = modeline->vsyncstart; + req->vsyncend = modeline->vsyncend; + req->vtotal = modeline->vtotal; + req->flags = modeline->flags; + req->privsize = modeline->privsize; + if (modeline->privsize) { + req->length += modeline->privsize; + Data32(dpy, (long *) modeline->private, + modeline->privsize * sizeof(INT32)); + } } UnlockDisplay(dpy); SyncHandle(); return True; } -Bool -SDL_NAME(XF86VidModeModModeLine) (dpy, screen, modeline) - Display *dpy; - int screen; - SDL_NAME(XF86VidModeModeLine)* modeline; +Bool SDL_NAME(XF86VidModeModModeLine) (dpy, screen, modeline) + Display * + dpy; + int + screen; +SDL_NAME(XF86VidModeModeLine) * modeline; { - XExtDisplayInfo *info = find_display (dpy); + XExtDisplayInfo *info = find_display(dpy); xXF86VidModeModModeLineReq *req; xXF86OldVidModeModModeLineReq *oldreq; int majorVersion, minorVersion; - XF86VidModeCheckExtension (dpy, info, 0); - SDL_NAME(XF86VidModeQueryVersion)(dpy, &majorVersion, &minorVersion); + XF86VidModeCheckExtension(dpy, info, 0); + SDL_NAME(XF86VidModeQueryVersion) (dpy, &majorVersion, &minorVersion); LockDisplay(dpy); if (majorVersion < 2) { - GetOldReq(XF86VidModeModModeLine, XF86OldVidModeModModeLine, oldreq); - oldreq->reqType = info->codes->major_opcode; - oldreq->xf86vidmodeReqType = X_XF86VidModeModModeLine; - oldreq->screen = screen; - oldreq->hdisplay = modeline->hdisplay; - oldreq->hsyncstart = modeline->hsyncstart; - oldreq->hsyncend = modeline->hsyncend; - oldreq->htotal = modeline->htotal; - oldreq->vdisplay = modeline->vdisplay; - oldreq->vsyncstart = modeline->vsyncstart; - oldreq->vsyncend = modeline->vsyncend; - oldreq->vtotal = modeline->vtotal; - oldreq->flags = modeline->flags; - oldreq->privsize = modeline->privsize; - if (modeline->privsize) { - oldreq->length += modeline->privsize; - Data32(dpy, (long *) modeline->private, - modeline->privsize * sizeof(INT32)); - } + GetOldReq(XF86VidModeModModeLine, XF86OldVidModeModModeLine, oldreq); + oldreq->reqType = info->codes->major_opcode; + oldreq->xf86vidmodeReqType = X_XF86VidModeModModeLine; + oldreq->screen = screen; + oldreq->hdisplay = modeline->hdisplay; + oldreq->hsyncstart = modeline->hsyncstart; + oldreq->hsyncend = modeline->hsyncend; + oldreq->htotal = modeline->htotal; + oldreq->vdisplay = modeline->vdisplay; + oldreq->vsyncstart = modeline->vsyncstart; + oldreq->vsyncend = modeline->vsyncend; + oldreq->vtotal = modeline->vtotal; + oldreq->flags = modeline->flags; + oldreq->privsize = modeline->privsize; + if (modeline->privsize) { + oldreq->length += modeline->privsize; + Data32(dpy, (long *) modeline->private, + modeline->privsize * sizeof(INT32)); + } } else { - GetReq(XF86VidModeModModeLine, req); - req->reqType = info->codes->major_opcode; - req->xf86vidmodeReqType = X_XF86VidModeModModeLine; - req->screen = screen; - req->hdisplay = modeline->hdisplay; - req->hsyncstart = modeline->hsyncstart; - req->hsyncend = modeline->hsyncend; - req->htotal = modeline->htotal; - req->hskew = modeline->hskew; - req->vdisplay = modeline->vdisplay; - req->vsyncstart = modeline->vsyncstart; - req->vsyncend = modeline->vsyncend; - req->vtotal = modeline->vtotal; - req->flags = modeline->flags; - req->privsize = modeline->privsize; - if (modeline->privsize) { - req->length += modeline->privsize; - Data32(dpy, (long *) modeline->private, - modeline->privsize * sizeof(INT32)); - } + GetReq(XF86VidModeModModeLine, req); + req->reqType = info->codes->major_opcode; + req->xf86vidmodeReqType = X_XF86VidModeModModeLine; + req->screen = screen; + req->hdisplay = modeline->hdisplay; + req->hsyncstart = modeline->hsyncstart; + req->hsyncend = modeline->hsyncend; + req->htotal = modeline->htotal; + req->hskew = modeline->hskew; + req->vdisplay = modeline->vdisplay; + req->vsyncstart = modeline->vsyncstart; + req->vsyncend = modeline->vsyncend; + req->vtotal = modeline->vtotal; + req->flags = modeline->flags; + req->privsize = modeline->privsize; + if (modeline->privsize) { + req->length += modeline->privsize; + Data32(dpy, (long *) modeline->private, + modeline->privsize * sizeof(INT32)); + } } UnlockDisplay(dpy); SyncHandle(); return True; } -Status -SDL_NAME(XF86VidModeValidateModeLine) (dpy, screen, modeline) - Display *dpy; - int screen; - SDL_NAME(XF86VidModeModeInfo)* modeline; +Status SDL_NAME(XF86VidModeValidateModeLine) (dpy, screen, modeline) + Display * + dpy; + int + screen; +SDL_NAME(XF86VidModeModeInfo) * modeline; { - XExtDisplayInfo *info = find_display (dpy); + XExtDisplayInfo *info = find_display(dpy); xXF86VidModeValidateModeLineReq *req; xXF86OldVidModeValidateModeLineReq *oldreq; xXF86VidModeValidateModeLineReply rep; int majorVersion, minorVersion; - XF86VidModeCheckExtension (dpy, info, 0); - SDL_NAME(XF86VidModeQueryVersion)(dpy, &majorVersion, &minorVersion); + XF86VidModeCheckExtension(dpy, info, 0); + SDL_NAME(XF86VidModeQueryVersion) (dpy, &majorVersion, &minorVersion); LockDisplay(dpy); if (majorVersion < 2) { - GetOldReq(XF86VidModeValidateModeLine, XF86OldVidModeValidateModeLine, oldreq); - oldreq->reqType = info->codes->major_opcode; - oldreq->xf86vidmodeReqType = X_XF86VidModeValidateModeLine; - oldreq->screen = screen; - oldreq->dotclock = modeline->dotclock; - oldreq->hdisplay = modeline->hdisplay; - oldreq->hsyncstart = modeline->hsyncstart; - oldreq->hsyncend = modeline->hsyncend; - oldreq->htotal = modeline->htotal; - oldreq->vdisplay = modeline->vdisplay; - oldreq->vsyncstart = modeline->vsyncstart; - oldreq->vsyncend = modeline->vsyncend; - oldreq->vtotal = modeline->vtotal; - oldreq->flags = modeline->flags; - oldreq->privsize = modeline->privsize; - if (modeline->privsize) { - oldreq->length += modeline->privsize; - Data32(dpy, (long *) modeline->private, - modeline->privsize * sizeof(INT32)); - } + GetOldReq(XF86VidModeValidateModeLine, + XF86OldVidModeValidateModeLine, oldreq); + oldreq->reqType = info->codes->major_opcode; + oldreq->xf86vidmodeReqType = X_XF86VidModeValidateModeLine; + oldreq->screen = screen; + oldreq->dotclock = modeline->dotclock; + oldreq->hdisplay = modeline->hdisplay; + oldreq->hsyncstart = modeline->hsyncstart; + oldreq->hsyncend = modeline->hsyncend; + oldreq->htotal = modeline->htotal; + oldreq->vdisplay = modeline->vdisplay; + oldreq->vsyncstart = modeline->vsyncstart; + oldreq->vsyncend = modeline->vsyncend; + oldreq->vtotal = modeline->vtotal; + oldreq->flags = modeline->flags; + oldreq->privsize = modeline->privsize; + if (modeline->privsize) { + oldreq->length += modeline->privsize; + Data32(dpy, (long *) modeline->private, + modeline->privsize * sizeof(INT32)); + } } else { - GetReq(XF86VidModeValidateModeLine, req); - req->reqType = info->codes->major_opcode; - req->xf86vidmodeReqType = X_XF86VidModeValidateModeLine; - req->screen = screen; - req->dotclock = modeline->dotclock; - req->hdisplay = modeline->hdisplay; - req->hsyncstart = modeline->hsyncstart; - req->hsyncend = modeline->hsyncend; - req->htotal = modeline->htotal; - req->hskew = modeline->hskew; - req->vdisplay = modeline->vdisplay; - req->vsyncstart = modeline->vsyncstart; - req->vsyncend = modeline->vsyncend; - req->vtotal = modeline->vtotal; - req->flags = modeline->flags; - req->privsize = modeline->privsize; - if (modeline->privsize) { - req->length += modeline->privsize; - Data32(dpy, (long *) modeline->private, - modeline->privsize * sizeof(INT32)); - } + GetReq(XF86VidModeValidateModeLine, req); + req->reqType = info->codes->major_opcode; + req->xf86vidmodeReqType = X_XF86VidModeValidateModeLine; + req->screen = screen; + req->dotclock = modeline->dotclock; + req->hdisplay = modeline->hdisplay; + req->hsyncstart = modeline->hsyncstart; + req->hsyncend = modeline->hsyncend; + req->htotal = modeline->htotal; + req->hskew = modeline->hskew; + req->vdisplay = modeline->vdisplay; + req->vsyncstart = modeline->vsyncstart; + req->vsyncend = modeline->vsyncend; + req->vtotal = modeline->vtotal; + req->flags = modeline->flags; + req->privsize = modeline->privsize; + if (modeline->privsize) { + req->length += modeline->privsize; + Data32(dpy, (long *) modeline->private, + modeline->privsize * sizeof(INT32)); + } } - if (!_XReply(dpy, (xReply *)&rep, 0, xFalse)) { - UnlockDisplay(dpy); - SyncHandle(); - return MODE_BAD; + if (!_XReply(dpy, (xReply *) & rep, 0, xFalse)) { + UnlockDisplay(dpy); + SyncHandle(); + return MODE_BAD; } UnlockDisplay(dpy); SyncHandle(); return rep.status; } -Bool -SDL_NAME(XF86VidModeSwitchMode)(dpy, screen, zoom) - Display* dpy; - int screen; - int zoom; +Bool SDL_NAME(XF86VidModeSwitchMode) (dpy, screen, zoom) + Display * + dpy; + int + screen; + int + zoom; { - XExtDisplayInfo *info = find_display (dpy); + XExtDisplayInfo *info = find_display(dpy); xXF86VidModeSwitchModeReq *req; - XF86VidModeCheckExtension (dpy, info, False); + XF86VidModeCheckExtension(dpy, info, False); LockDisplay(dpy); GetReq(XF86VidModeSwitchMode, req); @@ -783,20 +804,21 @@ SDL_NAME(XF86VidModeSwitchMode)(dpy, screen, zoom) SyncHandle(); return True; } - -Bool -SDL_NAME(XF86VidModeSwitchToMode)(dpy, screen, modeline) - Display* dpy; - int screen; - SDL_NAME(XF86VidModeModeInfo)* modeline; + +Bool SDL_NAME(XF86VidModeSwitchToMode) (dpy, screen, modeline) + Display * + dpy; + int + screen; +SDL_NAME(XF86VidModeModeInfo) * modeline; { - XExtDisplayInfo *info = find_display (dpy); + XExtDisplayInfo *info = find_display(dpy); xXF86VidModeSwitchToModeReq *req; xXF86OldVidModeSwitchToModeReq *oldreq; int majorVersion, minorVersion; Bool protocolBug = False; - XF86VidModeCheckExtension (dpy, info, False); + XF86VidModeCheckExtension(dpy, info, False); /* * Note: There was a bug in the protocol implementation in versions @@ -805,84 +827,87 @@ SDL_NAME(XF86VidModeSwitchToMode)(dpy, screen, modeline) * if appropriate. */ - SDL_NAME(XF86VidModeQueryVersion)(dpy, &majorVersion, &minorVersion); + SDL_NAME(XF86VidModeQueryVersion) (dpy, &majorVersion, &minorVersion); if (majorVersion == 0 && minorVersion < 8) { - protocolBug = True; + protocolBug = True; #ifdef DEBUG - fprintf(stderr, "XF86VidModeSwitchToMode: Warning: Xserver is" - "running an old version (%d.%d)\n", majorVersion, - minorVersion); + fprintf(stderr, "XF86VidModeSwitchToMode: Warning: Xserver is" + "running an old version (%d.%d)\n", majorVersion, + minorVersion); #endif } - + LockDisplay(dpy); if (majorVersion < 2) { - GetOldReq(XF86VidModeSwitchToMode, XF86OldVidModeSwitchToMode, oldreq); - oldreq->reqType = info->codes->major_opcode; - oldreq->xf86vidmodeReqType = X_XF86VidModeSwitchToMode; - oldreq->screen = screen; - oldreq->dotclock = modeline->dotclock; - oldreq->hdisplay = modeline->hdisplay; - oldreq->hsyncstart = modeline->hsyncstart; - oldreq->hsyncend = modeline->hsyncend; - oldreq->htotal = modeline->htotal; - oldreq->vdisplay = modeline->vdisplay; - oldreq->vsyncstart = modeline->vsyncstart; - oldreq->vsyncend = modeline->vsyncend; - oldreq->vtotal = modeline->vtotal; - oldreq->flags = modeline->flags; - if (protocolBug) { - oldreq->privsize = 0; - } else { - oldreq->privsize = modeline->privsize; - if (modeline->privsize) { - oldreq->length += modeline->privsize; - Data32(dpy, (long *) modeline->private, - modeline->privsize * sizeof(INT32)); - } - } + GetOldReq(XF86VidModeSwitchToMode, XF86OldVidModeSwitchToMode, + oldreq); + oldreq->reqType = info->codes->major_opcode; + oldreq->xf86vidmodeReqType = X_XF86VidModeSwitchToMode; + oldreq->screen = screen; + oldreq->dotclock = modeline->dotclock; + oldreq->hdisplay = modeline->hdisplay; + oldreq->hsyncstart = modeline->hsyncstart; + oldreq->hsyncend = modeline->hsyncend; + oldreq->htotal = modeline->htotal; + oldreq->vdisplay = modeline->vdisplay; + oldreq->vsyncstart = modeline->vsyncstart; + oldreq->vsyncend = modeline->vsyncend; + oldreq->vtotal = modeline->vtotal; + oldreq->flags = modeline->flags; + if (protocolBug) { + oldreq->privsize = 0; + } else { + oldreq->privsize = modeline->privsize; + if (modeline->privsize) { + oldreq->length += modeline->privsize; + Data32(dpy, (long *) modeline->private, + modeline->privsize * sizeof(INT32)); + } + } } else { - GetReq(XF86VidModeSwitchToMode, req); - req->reqType = info->codes->major_opcode; - req->xf86vidmodeReqType = X_XF86VidModeSwitchToMode; - req->screen = screen; - req->dotclock = modeline->dotclock; - req->hdisplay = modeline->hdisplay; - req->hsyncstart = modeline->hsyncstart; - req->hsyncend = modeline->hsyncend; - req->htotal = modeline->htotal; - req->hskew = modeline->hskew; - req->vdisplay = modeline->vdisplay; - req->vsyncstart = modeline->vsyncstart; - req->vsyncend = modeline->vsyncend; - req->vtotal = modeline->vtotal; - req->flags = modeline->flags; - if (protocolBug) { - req->privsize = 0; - } else { - req->privsize = modeline->privsize; - if (modeline->privsize) { - req->length += modeline->privsize; - Data32(dpy, (long *) modeline->private, - modeline->privsize * sizeof(INT32)); - } - } + GetReq(XF86VidModeSwitchToMode, req); + req->reqType = info->codes->major_opcode; + req->xf86vidmodeReqType = X_XF86VidModeSwitchToMode; + req->screen = screen; + req->dotclock = modeline->dotclock; + req->hdisplay = modeline->hdisplay; + req->hsyncstart = modeline->hsyncstart; + req->hsyncend = modeline->hsyncend; + req->htotal = modeline->htotal; + req->hskew = modeline->hskew; + req->vdisplay = modeline->vdisplay; + req->vsyncstart = modeline->vsyncstart; + req->vsyncend = modeline->vsyncend; + req->vtotal = modeline->vtotal; + req->flags = modeline->flags; + if (protocolBug) { + req->privsize = 0; + } else { + req->privsize = modeline->privsize; + if (modeline->privsize) { + req->length += modeline->privsize; + Data32(dpy, (long *) modeline->private, + modeline->privsize * sizeof(INT32)); + } + } } UnlockDisplay(dpy); SyncHandle(); return True; } - -Bool -SDL_NAME(XF86VidModeLockModeSwitch)(dpy, screen, lock) - Display* dpy; - int screen; - int lock; + +Bool SDL_NAME(XF86VidModeLockModeSwitch) (dpy, screen, lock) + Display * + dpy; + int + screen; + int + lock; { - XExtDisplayInfo *info = find_display (dpy); + XExtDisplayInfo *info = find_display(dpy); xXF86VidModeLockModeSwitchReq *req; - XF86VidModeCheckExtension (dpy, info, False); + XF86VidModeCheckExtension(dpy, info, False); LockDisplay(dpy); GetReq(XF86VidModeLockModeSwitch, req); @@ -894,121 +919,133 @@ SDL_NAME(XF86VidModeLockModeSwitch)(dpy, screen, lock) SyncHandle(); return True; } - -Bool -SDL_NAME(XF86VidModeGetMonitor)(dpy, screen, monitor) - Display* dpy; - int screen; - SDL_NAME(XF86VidModeMonitor)* monitor; + +Bool SDL_NAME(XF86VidModeGetMonitor) (dpy, screen, monitor) + Display * + dpy; + int + screen; +SDL_NAME(XF86VidModeMonitor) * monitor; { - XExtDisplayInfo *info = find_display (dpy); + XExtDisplayInfo *info = find_display(dpy); xXF86VidModeGetMonitorReply rep; xXF86VidModeGetMonitorReq *req; CARD32 syncrange; int i; - XF86VidModeCheckExtension (dpy, info, False); + XF86VidModeCheckExtension(dpy, info, False); LockDisplay(dpy); GetReq(XF86VidModeGetMonitor, req); req->reqType = info->codes->major_opcode; req->xf86vidmodeReqType = X_XF86VidModeGetMonitor; req->screen = screen; - if (!_XReply(dpy, (xReply *)&rep, 0, xFalse)) { - UnlockDisplay(dpy); - SyncHandle(); - return False; + if (!_XReply(dpy, (xReply *) & rep, 0, xFalse)) { + UnlockDisplay(dpy); + SyncHandle(); + return False; } monitor->nhsync = rep.nhsync; monitor->nvsync = rep.nvsync; #if 0 - monitor->bandwidth = (float)rep.bandwidth / 1e6; + monitor->bandwidth = (float) rep.bandwidth / 1e6; #endif if (rep.vendorLength) { - if (!(monitor->vendor = (char *)Xcalloc(rep.vendorLength + 1, 1))) { - _XEatData(dpy, (rep.nhsync + rep.nvsync) * 4 + - ((rep.vendorLength+3) & ~3) + ((rep.modelLength+3) & ~3)); + if (!(monitor->vendor = (char *) Xcalloc(rep.vendorLength + 1, 1))) { + _XEatData(dpy, (rep.nhsync + rep.nvsync) * 4 + + ((rep.vendorLength + 3) & ~3) + + ((rep.modelLength + 3) & ~3)); UnlockDisplay(dpy); SyncHandle(); - return False; - } + return False; + } } else { - monitor->vendor = NULL; + monitor->vendor = NULL; } if (rep.modelLength) { - if (!(monitor->model = Xcalloc(rep.modelLength + 1, 1))) { - _XEatData(dpy, (rep.nhsync + rep.nvsync) * 4 + - ((rep.vendorLength+3) & ~3) + ((rep.modelLength+3) & ~3)); - if (monitor->vendor) - Xfree(monitor->vendor); + if (!(monitor->model = Xcalloc(rep.modelLength + 1, 1))) { + _XEatData(dpy, (rep.nhsync + rep.nvsync) * 4 + + ((rep.vendorLength + 3) & ~3) + + ((rep.modelLength + 3) & ~3)); + if (monitor->vendor) + Xfree(monitor->vendor); UnlockDisplay(dpy); SyncHandle(); - return False; - } + return False; + } } else { - monitor->model = NULL; + monitor->model = NULL; } - if (!(monitor->hsync = Xcalloc(rep.nhsync, sizeof(SDL_NAME(XF86VidModeSyncRange))))) { - _XEatData(dpy, (rep.nhsync + rep.nvsync) * 4 + - ((rep.vendorLength+3) & ~3) + ((rep.modelLength+3) & ~3)); - - if (monitor->vendor) - Xfree(monitor->vendor); - if (monitor->model) - Xfree(monitor->model); + if (! + (monitor->hsync = + Xcalloc(rep.nhsync, sizeof(SDL_NAME(XF86VidModeSyncRange))))) { + _XEatData(dpy, (rep.nhsync + rep.nvsync) * 4 + + ((rep.vendorLength + 3) & ~3) + + ((rep.modelLength + 3) & ~3)); + + if (monitor->vendor) + Xfree(monitor->vendor); + if (monitor->model) + Xfree(monitor->model); UnlockDisplay(dpy); SyncHandle(); - return False; + return False; } - if (!(monitor->vsync = Xcalloc(rep.nvsync, sizeof(SDL_NAME(XF86VidModeSyncRange))))) { - _XEatData(dpy, (rep.nhsync + rep.nvsync) * 4 + - ((rep.vendorLength+3) & ~3) + ((rep.modelLength+3) & ~3)); - if (monitor->vendor) - Xfree(monitor->vendor); - if (monitor->model) - Xfree(monitor->model); - Xfree(monitor->hsync); + if (! + (monitor->vsync = + Xcalloc(rep.nvsync, sizeof(SDL_NAME(XF86VidModeSyncRange))))) { + _XEatData(dpy, (rep.nhsync + rep.nvsync) * 4 + + ((rep.vendorLength + 3) & ~3) + + ((rep.modelLength + 3) & ~3)); + if (monitor->vendor) + Xfree(monitor->vendor); + if (monitor->model) + Xfree(monitor->model); + Xfree(monitor->hsync); UnlockDisplay(dpy); SyncHandle(); - return False; + return False; } for (i = 0; i < rep.nhsync; i++) { - _XRead(dpy, (char *)&syncrange, 4); - monitor->hsync[i].lo = (float)(syncrange & 0xFFFF) / 100.0; - monitor->hsync[i].hi = (float)(syncrange >> 16) / 100.0; + _XRead(dpy, (char *) &syncrange, 4); + monitor->hsync[i].lo = (float) (syncrange & 0xFFFF) / 100.0; + monitor->hsync[i].hi = (float) (syncrange >> 16) / 100.0; } for (i = 0; i < rep.nvsync; i++) { - _XRead(dpy, (char *)&syncrange, 4); - monitor->vsync[i].lo = (float)(syncrange & 0xFFFF) / 100.0; - monitor->vsync[i].hi = (float)(syncrange >> 16) / 100.0; + _XRead(dpy, (char *) &syncrange, 4); + monitor->vsync[i].lo = (float) (syncrange & 0xFFFF) / 100.0; + monitor->vsync[i].hi = (float) (syncrange >> 16) / 100.0; } if (rep.vendorLength) - _XReadPad(dpy, monitor->vendor, rep.vendorLength); + _XReadPad(dpy, monitor->vendor, rep.vendorLength); else - monitor->vendor = ""; + monitor->vendor = ""; if (rep.modelLength) - _XReadPad(dpy, monitor->model, rep.modelLength); + _XReadPad(dpy, monitor->model, rep.modelLength); else - monitor->model = ""; - + monitor->model = ""; + UnlockDisplay(dpy); SyncHandle(); return True; } -Bool -SDL_NAME(XF86VidModeGetViewPort)(dpy, screen, x, y) - Display* dpy; - int screen; - int *x, *y; +Bool SDL_NAME(XF86VidModeGetViewPort) (dpy, screen, x, y) + Display * + dpy; + int + screen; + int * + x, * + y; { - XExtDisplayInfo *info = find_display (dpy); + XExtDisplayInfo *info = find_display(dpy); xXF86VidModeGetViewPortReply rep; xXF86VidModeGetViewPortReq *req; int majorVersion, minorVersion; Bool protocolBug = False; - XF86VidModeCheckExtension (dpy, info, False); + XF86VidModeCheckExtension(dpy, info, False); /* * Note: There was a bug in the protocol implementation in versions @@ -1017,13 +1054,13 @@ SDL_NAME(XF86VidModeGetViewPort)(dpy, screen, x, y) * versions. */ - SDL_NAME(XF86VidModeQueryVersion)(dpy, &majorVersion, &minorVersion); + SDL_NAME(XF86VidModeQueryVersion) (dpy, &majorVersion, &minorVersion); if (majorVersion == 0 && minorVersion < 8) { - protocolBug = True; + protocolBug = True; #ifdef DEBUG - fprintf(stderr, "XF86VidModeGetViewPort: Warning: Xserver is" - "running an old version (%d.%d)\n", majorVersion, - minorVersion); + fprintf(stderr, "XF86VidModeGetViewPort: Warning: Xserver is" + "running an old version (%d.%d)\n", majorVersion, + minorVersion); #endif } LockDisplay(dpy); @@ -1032,16 +1069,16 @@ SDL_NAME(XF86VidModeGetViewPort)(dpy, screen, x, y) req->xf86vidmodeReqType = X_XF86VidModeGetViewPort; req->screen = screen; if (protocolBug) { - *x = 0; - *y = 0; + *x = 0; + *y = 0; } else { - if (!_XReply(dpy, (xReply *)&rep, 0, xFalse)) { - UnlockDisplay(dpy); - SyncHandle(); - return False; - } - *x = rep.x; - *y = rep.y; + if (!_XReply(dpy, (xReply *) & rep, 0, xFalse)) { + UnlockDisplay(dpy); + SyncHandle(); + return False; + } + *x = rep.x; + *y = rep.y; } UnlockDisplay(dpy); @@ -1049,16 +1086,19 @@ SDL_NAME(XF86VidModeGetViewPort)(dpy, screen, x, y) return True; } -Bool -SDL_NAME(XF86VidModeSetViewPort)(dpy, screen, x, y) - Display* dpy; - int screen; - int x, y; +Bool SDL_NAME(XF86VidModeSetViewPort) (dpy, screen, x, y) + Display * + dpy; + int + screen; + int + x, + y; { - XExtDisplayInfo *info = find_display (dpy); + XExtDisplayInfo *info = find_display(dpy); xXF86VidModeSetViewPortReq *req; - XF86VidModeCheckExtension (dpy, info, False); + XF86VidModeCheckExtension(dpy, info, False); LockDisplay(dpy); GetReq(XF86VidModeSetViewPort, req); @@ -1074,37 +1114,38 @@ SDL_NAME(XF86VidModeSetViewPort)(dpy, screen, x, y) } Bool -SDL_NAME(XF86VidModeGetDotClocks)(dpy, screen, - flagsPtr, numclocksPtr, maxclocksPtr, clocksPtr) - Display* dpy; - int screen; - int *flagsPtr, *numclocksPtr, *maxclocksPtr, *clocksPtr[]; +SDL_NAME(XF86VidModeGetDotClocks) (dpy, screen, + flagsPtr, numclocksPtr, maxclocksPtr, + clocksPtr) + Display *dpy; + int screen; + int *flagsPtr, *numclocksPtr, *maxclocksPtr, *clocksPtr[]; { - XExtDisplayInfo *info = find_display (dpy); + XExtDisplayInfo *info = find_display(dpy); xXF86VidModeGetDotClocksReply rep; xXF86VidModeGetDotClocksReq *req; int i, *dotclocks; CARD32 dotclk; - XF86VidModeCheckExtension (dpy, info, False); + XF86VidModeCheckExtension(dpy, info, False); LockDisplay(dpy); GetReq(XF86VidModeGetDotClocks, req); req->reqType = info->codes->major_opcode; req->xf86vidmodeReqType = X_XF86VidModeGetDotClocks; req->screen = screen; - if (!_XReply(dpy, (xReply *)&rep, - (SIZEOF(xXF86VidModeGetDotClocksReply) - SIZEOF(xReply)) >> 2, xFalse)) - { + if (!_XReply(dpy, (xReply *) & rep, + (SIZEOF(xXF86VidModeGetDotClocksReply) - + SIZEOF(xReply)) >> 2, xFalse)) { UnlockDisplay(dpy); SyncHandle(); return False; } *numclocksPtr = rep.clocks; *maxclocksPtr = rep.maxclocks; - *flagsPtr = rep.flags; + *flagsPtr = rep.flags; - if (!(dotclocks = (int*) Xcalloc(rep.clocks, sizeof(int)))) { + if (!(dotclocks = (int *) Xcalloc(rep.clocks, sizeof(int)))) { _XEatData(dpy, (rep.clocks) * 4); Xfree(dotclocks); UnlockDisplay(dpy); @@ -1113,8 +1154,8 @@ SDL_NAME(XF86VidModeGetDotClocks)(dpy, screen, } for (i = 0; i < rep.clocks; i++) { - _XRead(dpy, (char*)&dotclk, 4); - dotclocks[i] = dotclk; + _XRead(dpy, (char *) &dotclk, 4); + dotclocks[i] = dotclk; } *clocksPtr = dotclocks; UnlockDisplay(dpy); @@ -1123,20 +1164,18 @@ SDL_NAME(XF86VidModeGetDotClocks)(dpy, screen, } Bool -SDL_NAME(XF86VidModeSetGammaRamp) ( - Display *dpy, - int screen, - int size, - unsigned short *red, - unsigned short *green, - unsigned short *blue -) +SDL_NAME(XF86VidModeSetGammaRamp) (Display * dpy, + int screen, + int size, + unsigned short *red, + unsigned short *green, + unsigned short *blue) { int length = (size + 1) & ~1; - XExtDisplayInfo *info = find_display (dpy); + XExtDisplayInfo *info = find_display(dpy); xXF86VidModeSetGammaRampReq *req; - XF86VidModeCheckExtension (dpy, info, False); + XF86VidModeCheckExtension(dpy, info, False); LockDisplay(dpy); GetReq(XF86VidModeSetGammaRamp, req); req->reqType = info->codes->major_opcode; @@ -1144,9 +1183,9 @@ SDL_NAME(XF86VidModeSetGammaRamp) ( req->screen = screen; req->length += (length >> 1) * 3; req->size = size; - _XSend(dpy, (char*)red, size * 2); - _XSend(dpy, (char*)green, size * 2); - _XSend(dpy, (char*)blue, size * 2); + _XSend(dpy, (char *) red, size * 2); + _XSend(dpy, (char *) green, size * 2); + _XSend(dpy, (char *) blue, size * 2); UnlockDisplay(dpy); SyncHandle(); return True; @@ -1154,20 +1193,18 @@ SDL_NAME(XF86VidModeSetGammaRamp) ( Bool -SDL_NAME(XF86VidModeGetGammaRamp) ( - Display *dpy, - int screen, - int size, - unsigned short *red, - unsigned short *green, - unsigned short *blue -) +SDL_NAME(XF86VidModeGetGammaRamp) (Display * dpy, + int screen, + int size, + unsigned short *red, + unsigned short *green, + unsigned short *blue) { - XExtDisplayInfo *info = find_display (dpy); + XExtDisplayInfo *info = find_display(dpy); xXF86VidModeGetGammaRampReq *req; xXF86VidModeGetGammaRampReply rep; - - XF86VidModeCheckExtension (dpy, info, False); + + XF86VidModeCheckExtension(dpy, info, False); LockDisplay(dpy); GetReq(XF86VidModeGetGammaRamp, req); @@ -1175,15 +1212,15 @@ SDL_NAME(XF86VidModeGetGammaRamp) ( req->xf86vidmodeReqType = X_XF86VidModeGetGammaRamp; req->screen = screen; req->size = size; - if (!_XReply (dpy, (xReply *) &rep, 0, xFalse)) { - UnlockDisplay (dpy); - SyncHandle (); + if (!_XReply(dpy, (xReply *) & rep, 0, xFalse)) { + UnlockDisplay(dpy); + SyncHandle(); return False; } - if(rep.size) { - _XRead(dpy, (char*)red, rep.size << 1); - _XRead(dpy, (char*)green, rep.size << 1); - _XRead(dpy, (char*)blue, rep.size << 1); + if (rep.size) { + _XRead(dpy, (char *) red, rep.size << 1); + _XRead(dpy, (char *) green, rep.size << 1); + _XRead(dpy, (char *) blue, rep.size << 1); } UnlockDisplay(dpy); @@ -1191,29 +1228,26 @@ SDL_NAME(XF86VidModeGetGammaRamp) ( return True; } -Bool SDL_NAME(XF86VidModeGetGammaRampSize)( - Display *dpy, - int screen, - int *size -) +Bool SDL_NAME(XF86VidModeGetGammaRampSize) (Display * dpy, + int screen, int *size) { - XExtDisplayInfo *info = find_display (dpy); + XExtDisplayInfo *info = find_display(dpy); xXF86VidModeGetGammaRampSizeReq *req; xXF86VidModeGetGammaRampSizeReply rep; - + *size = 0; - XF86VidModeCheckExtension (dpy, info, False); + XF86VidModeCheckExtension(dpy, info, False); LockDisplay(dpy); GetReq(XF86VidModeGetGammaRampSize, req); req->reqType = info->codes->major_opcode; req->xf86vidmodeReqType = X_XF86VidModeGetGammaRampSize; req->screen = screen; - if (!_XReply (dpy, (xReply *) &rep, 0, xTrue)) { - UnlockDisplay (dpy); - SyncHandle (); - return False; + if (!_XReply(dpy, (xReply *) & rep, 0, xTrue)) { + UnlockDisplay(dpy); + SyncHandle(); + return False; } *size = rep.size; UnlockDisplay(dpy); @@ -1221,3 +1255,4 @@ Bool SDL_NAME(XF86VidModeGetGammaRampSize)( return True; } +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/Xext/extensions/Xext.h b/src/video/Xext/extensions/Xext.h index 9edf3194b..092ac4369 100644 --- a/src/video/Xext/extensions/Xext.h +++ b/src/video/Xext/extensions/Xext.h @@ -29,22 +29,18 @@ in this Software without prior written authorization from The Open Group. #include _XFUNCPROTOBEGIN + typedef int (*XExtensionErrorHandler) (Display *, _Xconst char *, + _Xconst char *); -typedef int (*XExtensionErrorHandler)(Display *, _Xconst char *, - _Xconst char *); +extern XExtensionErrorHandler +XSetExtensionErrorHandler(XExtensionErrorHandler handler); -extern XExtensionErrorHandler XSetExtensionErrorHandler( - XExtensionErrorHandler handler -); - -extern int XMissingExtension( - Display* /* dpy */, - _Xconst char* /* ext_name */ -); +extern int XMissingExtension(Display * /* dpy */ , + _Xconst char * /* ext_name */ + ); _XFUNCPROTOEND - #define X_EXTENSION_UNKNOWN "unknown" #define X_EXTENSION_MISSING "missing" - #endif /* _XEXT_H_ */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/Xext/extensions/Xinerama.h b/src/video/Xext/extensions/Xinerama.h index 54f2fe17d..899f51f6f 100644 --- a/src/video/Xext/extensions/Xinerama.h +++ b/src/video/Xext/extensions/Xinerama.h @@ -5,27 +5,21 @@ #include "SDL_name.h" -typedef struct { - int screen_number; - short x_org; - short y_org; - short width; - short height; +typedef struct +{ + int screen_number; + short x_org; + short y_org; + short width; + short height; } SDL_NAME(XineramaScreenInfo); -Bool SDL_NAME(XineramaQueryExtension) ( - Display *dpy, - int *event_base, - int *error_base -); +Bool SDL_NAME(XineramaQueryExtension) (Display * dpy, + int *event_base, int *error_base); -Status SDL_NAME(XineramaQueryVersion)( - Display *dpy, - int *major, - int *minor -); +Status SDL_NAME(XineramaQueryVersion) (Display * dpy, int *major, int *minor); -Bool SDL_NAME(XineramaIsActive)(Display *dpy); +Bool SDL_NAME(XineramaIsActive) (Display * dpy); /* @@ -36,11 +30,8 @@ Bool SDL_NAME(XineramaIsActive)(Display *dpy); Returned array should be freed with XFree(). */ -SDL_NAME(XineramaScreenInfo) * -SDL_NAME(XineramaQueryScreens)( - Display *dpy, - int *number -); +SDL_NAME(XineramaScreenInfo) * +SDL_NAME(XineramaQueryScreens) (Display * dpy, int *number); #endif /* _Xinerama_h */ - +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/Xext/extensions/Xv.h b/src/video/Xext/extensions/Xv.h index a6a027195..ecbc7a3b6 100644 --- a/src/video/Xext/extensions/Xv.h +++ b/src/video/Xext/extensions/Xv.h @@ -126,4 +126,4 @@ typedef XID XvEncodingID; #define XvBadAlloc 5 #endif /* XV_H */ - +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/Xext/extensions/Xvlib.h b/src/video/Xext/extensions/Xvlib.h index 0d0a55da4..476e6c9bb 100644 --- a/src/video/Xext/extensions/Xvlib.h +++ b/src/video/Xext/extensions/Xvlib.h @@ -57,377 +57,399 @@ SOFTWARE. #include "Xv.h" #include "SDL_name.h" -typedef struct { - int numerator; - int denominator; +typedef struct +{ + int numerator; + int denominator; } SDL_NAME(XvRational); -typedef struct { - int flags; /* XvGettable, XvSettable */ - int min_value; - int max_value; - char *name; +typedef struct +{ + int flags; /* XvGettable, XvSettable */ + int min_value; + int max_value; + char *name; } SDL_NAME(XvAttribute); -typedef struct { - XvEncodingID encoding_id; - char *name; - unsigned long width; - unsigned long height; - SDL_NAME(XvRational) rate; - unsigned long num_encodings; +typedef struct +{ + XvEncodingID encoding_id; + char *name; + unsigned long width; + unsigned long height; + SDL_NAME(XvRational) rate; + unsigned long num_encodings; } SDL_NAME(XvEncodingInfo); -typedef struct { - char depth; - unsigned long visual_id; +typedef struct +{ + char depth; + unsigned long visual_id; } SDL_NAME(XvFormat); -typedef struct { - XvPortID base_id; - unsigned long num_ports; - char type; - char *name; - unsigned long num_formats; - SDL_NAME(XvFormat) *formats; - unsigned long num_adaptors; +typedef struct +{ + XvPortID base_id; + unsigned long num_ports; + char type; + char *name; + unsigned long num_formats; + SDL_NAME(XvFormat) * formats; + unsigned long num_adaptors; } SDL_NAME(XvAdaptorInfo); -typedef struct { - int type; - unsigned long serial; /* # of last request processed by server */ - Bool send_event; /* true if this came from a SendEvent request */ - Display *display; /* Display the event was read from */ - Drawable drawable; /* drawable */ - unsigned long reason; /* what generated this event */ - XvPortID port_id; /* what port */ - Time time; /* milliseconds */ +typedef struct +{ + int type; + unsigned long serial; /* # of last request processed by server */ + Bool send_event; /* true if this came from a SendEvent request */ + Display *display; /* Display the event was read from */ + Drawable drawable; /* drawable */ + unsigned long reason; /* what generated this event */ + XvPortID port_id; /* what port */ + Time time; /* milliseconds */ } SDL_NAME(XvVideoNotifyEvent); -typedef struct { - int type; - unsigned long serial; /* # of last request processed by server */ - Bool send_event; /* true if this came from a SendEvent request */ - Display *display; /* Display the event was read from */ - XvPortID port_id; /* what port */ - Time time; /* milliseconds */ - Atom attribute; /* atom that identifies attribute */ - long value; /* value of attribute */ +typedef struct +{ + int type; + unsigned long serial; /* # of last request processed by server */ + Bool send_event; /* true if this came from a SendEvent request */ + Display *display; /* Display the event was read from */ + XvPortID port_id; /* what port */ + Time time; /* milliseconds */ + Atom attribute; /* atom that identifies attribute */ + long value; /* value of attribute */ } SDL_NAME(XvPortNotifyEvent); -typedef union { - int type; - SDL_NAME(XvVideoNotifyEvent) xvvideo; - SDL_NAME(XvPortNotifyEvent) xvport; - long pad[24]; +typedef union +{ + int type; + SDL_NAME(XvVideoNotifyEvent) xvvideo; + SDL_NAME(XvPortNotifyEvent) xvport; + long pad[24]; } SDL_NAME(XvEvent); -typedef struct { - int id; /* Unique descriptor for the format */ - int type; /* XvRGB, XvYUV */ - int byte_order; /* LSBFirst, MSBFirst */ - char guid[16]; /* Globally Unique IDentifier */ - int bits_per_pixel; - int format; /* XvPacked, XvPlanar */ - int num_planes; - - /* for RGB formats only */ - int depth; - unsigned int red_mask; - unsigned int green_mask; - unsigned int blue_mask; - - /* for YUV formats only */ - unsigned int y_sample_bits; - unsigned int u_sample_bits; - unsigned int v_sample_bits; - unsigned int horz_y_period; - unsigned int horz_u_period; - unsigned int horz_v_period; - unsigned int vert_y_period; - unsigned int vert_u_period; - unsigned int vert_v_period; - char component_order[32]; /* eg. UYVY */ - int scanline_order; /* XvTopToBottom, XvBottomToTop */ -} SDL_NAME(XvImageFormatValues); - -typedef struct { - int id; - int width, height; - int data_size; /* bytes */ - int num_planes; - int *pitches; /* bytes */ - int *offsets; /* bytes */ - char *data; - XPointer obdata; +typedef struct +{ + int id; /* Unique descriptor for the format */ + int type; /* XvRGB, XvYUV */ + int byte_order; /* LSBFirst, MSBFirst */ + char guid[16]; /* Globally Unique IDentifier */ + int bits_per_pixel; + int format; /* XvPacked, XvPlanar */ + int num_planes; + + /* for RGB formats only */ + int depth; + unsigned int red_mask; + unsigned int green_mask; + unsigned int blue_mask; + + /* for YUV formats only */ + unsigned int y_sample_bits; + unsigned int u_sample_bits; + unsigned int v_sample_bits; + unsigned int horz_y_period; + unsigned int horz_u_period; + unsigned int horz_v_period; + unsigned int vert_y_period; + unsigned int vert_u_period; + unsigned int vert_v_period; + char component_order[32]; /* eg. UYVY */ + int scanline_order; /* XvTopToBottom, XvBottomToTop */ +} SDL_NAME(XvImageFormatValues); + +typedef struct +{ + int id; + int width, height; + int data_size; /* bytes */ + int num_planes; + int *pitches; /* bytes */ + int *offsets; /* bytes */ + char *data; + XPointer obdata; } SDL_NAME(XvImage); -_XFUNCPROTOBEGIN - -extern int SDL_NAME(XvQueryExtension)( +_XFUNCPROTOBEGIN extern int SDL_NAME(XvQueryExtension) ( #if NeedFunctionPrototypes - Display* /* display */, - unsigned int* /* p_version */, - unsigned int* /* p_revision */, - unsigned int* /* p_requestBase */, - unsigned int* /* p_eventBase */, - unsigned int* /* p_errorBase */ + Display * + /* display */ , + unsigned int * + /* p_version */ , + unsigned int * + /* p_revision */ , + unsigned int * + /* p_requestBase */ + , unsigned int * + /* p_eventBase */ + , unsigned int * /* p_errorBase */ #endif -); + ); -extern int SDL_NAME(XvQueryAdaptors)( +extern int SDL_NAME(XvQueryAdaptors) ( #if NeedFunctionPrototypes - Display* /* display */, - Window /* window */, - unsigned int* /* p_nAdaptors */, - SDL_NAME(XvAdaptorInfo)** /* p_pAdaptors */ + Display * /* display */ , + Window /* window */ , + unsigned int * /* p_nAdaptors */ , + SDL_NAME(XvAdaptorInfo) ** /* p_pAdaptors */ #endif -); + ); -extern int SDL_NAME(XvQueryEncodings)( +extern int SDL_NAME(XvQueryEncodings) ( #if NeedFunctionPrototypes - Display* /* display */, - XvPortID /* port */, - unsigned int* /* p_nEncoding */, - SDL_NAME(XvEncodingInfo)** /* p_pEncoding */ + Display * /* display */ , + XvPortID /* port */ , + unsigned int * /* p_nEncoding */ , + SDL_NAME(XvEncodingInfo) ** /* p_pEncoding */ #endif -); + ); -extern int SDL_NAME(XvPutVideo)( +extern int SDL_NAME(XvPutVideo) ( #if NeedFunctionPrototypes - Display* /* display */, - XvPortID /* port */, - Drawable /* d */, - GC /* gc */, - int /* vx */, - int /* vy */, - unsigned int /* vw */, - unsigned int /* vh */, - int /* dx */, - int /* dy */, - unsigned int /* dw */, - unsigned int /* dh */ + Display * /* display */ , + XvPortID /* port */ , + Drawable /* d */ , + GC /* gc */ , + int /* vx */ , + int /* vy */ , + unsigned int /* vw */ , + unsigned int /* vh */ , + int /* dx */ , + int /* dy */ , + unsigned int /* dw */ , + unsigned int /* dh */ #endif -); + ); -extern int SDL_NAME(XvPutStill)( +extern int SDL_NAME(XvPutStill) ( #if NeedFunctionPrototypes - Display* /* display */, - XvPortID /* port */, - Drawable /* d */, - GC /* gc */, - int /* vx */, - int /* vy */, - unsigned int /* vw */, - unsigned int /* vh */, - int /* dx */, - int /* dy */, - unsigned int /* dw */, - unsigned int /* dh */ + Display * /* display */ , + XvPortID /* port */ , + Drawable /* d */ , + GC /* gc */ , + int /* vx */ , + int /* vy */ , + unsigned int /* vw */ , + unsigned int /* vh */ , + int /* dx */ , + int /* dy */ , + unsigned int /* dw */ , + unsigned int /* dh */ #endif -); + ); -extern int SDL_NAME(XvGetVideo)( +extern int SDL_NAME(XvGetVideo) ( #if NeedFunctionPrototypes - Display* /* display */, - XvPortID /* port */, - Drawable /* d */, - GC /* gc */, - int /* vx */, - int /* vy */, - unsigned int /* vw */, - unsigned int /* vh */, - int /* dx */, - int /* dy */, - unsigned int /* dw */, - unsigned int /* dh */ + Display * /* display */ , + XvPortID /* port */ , + Drawable /* d */ , + GC /* gc */ , + int /* vx */ , + int /* vy */ , + unsigned int /* vw */ , + unsigned int /* vh */ , + int /* dx */ , + int /* dy */ , + unsigned int /* dw */ , + unsigned int /* dh */ #endif -); + ); -extern int SDL_NAME(XvGetStill)( +extern int SDL_NAME(XvGetStill) ( #if NeedFunctionPrototypes - Display* /* display */, - XvPortID /* port */, - Drawable /* d */, - GC /* gc */, - int /* vx */, - int /* vy */, - unsigned int /* vw */, - unsigned int /* vh */, - int /* dx */, - int /* dy */, - unsigned int /* dw */, - unsigned int /* dh */ + Display * /* display */ , + XvPortID /* port */ , + Drawable /* d */ , + GC /* gc */ , + int /* vx */ , + int /* vy */ , + unsigned int /* vw */ , + unsigned int /* vh */ , + int /* dx */ , + int /* dy */ , + unsigned int /* dw */ , + unsigned int /* dh */ #endif -); + ); -extern int SDL_NAME(XvStopVideo)( +extern int SDL_NAME(XvStopVideo) ( #if NeedFunctionPrototypes - Display* /* display */, - XvPortID /* port */, - Drawable /* drawable */ + Display * /* display */ , + XvPortID /* port */ , + Drawable /* drawable */ #endif -); + ); -extern int SDL_NAME(XvGrabPort)( +extern int SDL_NAME(XvGrabPort) ( #if NeedFunctionPrototypes - Display* /* display */, - XvPortID /* port */, - Time /* time */ + Display * /* display */ , + XvPortID /* port */ , + Time /* time */ #endif -); + ); -extern int SDL_NAME(XvUngrabPort)( +extern int SDL_NAME(XvUngrabPort) ( #if NeedFunctionPrototypes - Display* /* display */, - XvPortID /* port */, - Time /* time */ + Display * /* display */ , + XvPortID /* port */ , + Time /* time */ #endif -); + ); -extern int SDL_NAME(XvSelectVideoNotify)( +extern int SDL_NAME(XvSelectVideoNotify) ( #if NeedFunctionPrototypes - Display* /* display */, - Drawable /* drawable */, - Bool /* onoff */ + Display * /* display */ , + Drawable /* drawable */ , + Bool /* onoff */ #endif -); + ); -extern int SDL_NAME(XvSelectPortNotify)( +extern int SDL_NAME(XvSelectPortNotify) ( #if NeedFunctionPrototypes - Display* /* display */, - XvPortID /* port */, - Bool /* onoff */ + Display * /* display */ , + XvPortID /* port */ , + Bool /* onoff */ #endif -); + ); -extern int SDL_NAME(XvSetPortAttribute)( +extern int SDL_NAME(XvSetPortAttribute) ( #if NeedFunctionPrototypes - Display* /* display */, - XvPortID /* port */, - Atom /* attribute */, - int /* value */ + Display * /* display */ , + XvPortID /* port */ , + Atom /* attribute */ , + int /* value */ #endif -); + ); -extern int SDL_NAME(XvGetPortAttribute)( +extern int SDL_NAME(XvGetPortAttribute) ( #if NeedFunctionPrototypes - Display* /* display */, - XvPortID /* port */, - Atom /* attribute */, - int* /* p_value */ + Display * /* display */ , + XvPortID /* port */ , + Atom /* attribute */ , + int * /* p_value */ #endif -); + ); -extern int SDL_NAME(XvQueryBestSize)( +extern int SDL_NAME(XvQueryBestSize) ( #if NeedFunctionPrototypes - Display* /* display */, - XvPortID /* port */, - Bool /* motion */, - unsigned int /* vid_w */, - unsigned int /* vid_h */, - unsigned int /* drw_w */, - unsigned int /* drw_h */, - unsigned int* /* p_actual_width */, - unsigned int* /* p_actual_width */ + Display * /* display */ , + XvPortID /* port */ , + Bool /* motion */ , + unsigned int /* vid_w */ , + unsigned int /* vid_h */ , + unsigned int /* drw_w */ , + unsigned int /* drw_h */ , + unsigned int * /* p_actual_width */ + , unsigned int * /* p_actual_width */ #endif -); + ); -extern SDL_NAME(XvAttribute)* SDL_NAME(XvQueryPortAttributes)( +extern +SDL_NAME(XvAttribute) * +SDL_NAME(XvQueryPortAttributes) ( #if NeedFunctionPrototypes - Display* /* display */, - XvPortID /* port */, - int* /* number */ + Display * /* display */ , + XvPortID /* port */ , + int * /* number */ #endif -); + ); -extern void SDL_NAME(XvFreeAdaptorInfo)( + extern void SDL_NAME(XvFreeAdaptorInfo) ( #if NeedFunctionPrototypes - SDL_NAME(XvAdaptorInfo)* /* adaptors */ + SDL_NAME(XvAdaptorInfo) * /* adaptors */ #endif -); + ); -extern void SDL_NAME(XvFreeEncodingInfo)( + extern void SDL_NAME(XvFreeEncodingInfo) ( #if NeedFunctionPrototypes - SDL_NAME(XvEncodingInfo)* /* encodings */ + SDL_NAME(XvEncodingInfo) * /* encodings */ #endif -); + ); -extern SDL_NAME(XvImageFormatValues) * SDL_NAME(XvListImageFormats) ( + extern SDL_NAME(XvImageFormatValues) * SDL_NAME(XvListImageFormats) ( #if NeedFunctionPrototypes - Display *display, - XvPortID port_id, - int *count_return + Display + * + display, + XvPortID + port_id, + int + *count_return #endif -); + ); -extern SDL_NAME(XvImage) * SDL_NAME(XvCreateImage) ( + extern SDL_NAME(XvImage) * SDL_NAME(XvCreateImage) ( #if NeedFunctionPrototypes - Display *display, - XvPortID port, - int id, - char *data, - int width, - int height + Display * + display, + XvPortID port, + int id, + char *data, + int width, + int height #endif -); + ); -extern int SDL_NAME(XvPutImage) ( + extern int SDL_NAME(XvPutImage) ( #if NeedFunctionPrototypes - Display *display, - XvPortID id, - Drawable d, - GC gc, - SDL_NAME(XvImage) *image, - int src_x, - int src_y, - unsigned int src_w, - unsigned int src_h, - int dest_x, - int dest_y, - unsigned int dest_w, - unsigned int dest_h + Display * display, + XvPortID id, + Drawable d, + GC gc, + SDL_NAME(XvImage) * image, + int src_x, + int src_y, + unsigned int src_w, + unsigned int src_h, + int dest_x, + int dest_y, + unsigned int dest_w, + unsigned int dest_h #endif -); + ); -extern int SDL_NAME(XvShmPutImage) ( + extern int SDL_NAME(XvShmPutImage) ( #if NeedFunctionPrototypes - Display *display, - XvPortID id, - Drawable d, - GC gc, - SDL_NAME(XvImage) *image, - int src_x, - int src_y, - unsigned int src_w, - unsigned int src_h, - int dest_x, - int dest_y, - unsigned int dest_w, - unsigned int dest_h, - Bool send_event + Display * display, + XvPortID id, + Drawable d, + GC gc, + SDL_NAME(XvImage) * image, + int src_x, + int src_y, + unsigned int src_w, + unsigned int src_h, + int dest_x, + int dest_y, + unsigned int dest_w, + unsigned int dest_h, + Bool send_event #endif -); + ); #ifdef _XSHM_H_ -extern SDL_NAME(XvImage) * SDL_NAME(XvShmCreateImage) ( + extern SDL_NAME(XvImage) * SDL_NAME(XvShmCreateImage) ( #if NeedFunctionPrototypes - Display *display, - XvPortID port, - int id, - char* data, - int width, - int height, - XShmSegmentInfo *shminfo + Display * + display, + XvPortID + port, int id, + char *data, + int width, + int height, + XShmSegmentInfo + * shminfo #endif -); + ); #endif _XFUNCPROTOEND - #endif /* XVLIB_H */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/Xext/extensions/Xvproto.h b/src/video/Xext/extensions/Xvproto.h index b4d8f22cd..985aa8535 100644 --- a/src/video/Xext/extensions/Xvproto.h +++ b/src/video/Xext/extensions/Xvproto.h @@ -65,80 +65,86 @@ SOFTWARE. /* Structures */ -typedef struct { - INT32 numerator B32; - INT32 denominator B32; +typedef struct +{ + INT32 numerator B32; + INT32 denominator B32; } xvRational; #define sz_xvRational 8 -typedef struct { - XvPortID base_id B32; - CARD16 name_size B16; - CARD16 num_ports B16; - CARD16 num_formats B16; - CARD8 type; - CARD8 pad; +typedef struct +{ + XvPortID base_id B32; + CARD16 name_size B16; + CARD16 num_ports B16; + CARD16 num_formats B16; + CARD8 type; + CARD8 pad; } xvAdaptorInfo; #define sz_xvAdaptorInfo 12 -typedef struct { - XvEncodingID encoding B32; - CARD16 name_size B16; - CARD16 width B16, height B16; - xvRational rate; - CARD16 pad B16; +typedef struct +{ + XvEncodingID encoding B32; + CARD16 name_size B16; + CARD16 width B16, height B16; + xvRational rate; + CARD16 pad B16; } xvEncodingInfo; #define sz_xvEncodingInfo (12 + sz_xvRational) -typedef struct { - VisualID visual B32; - CARD8 depth; - CARD8 pad1; - CARD16 pad2 B16; +typedef struct +{ + VisualID visual B32; + CARD8 depth; + CARD8 pad1; + CARD16 pad2 B16; } xvFormat; #define sz_xvFormat 8 -typedef struct { - CARD32 flags B32; - INT32 min B32; - INT32 max B32; - CARD32 size B32; +typedef struct +{ + CARD32 flags B32; + INT32 min B32; + INT32 max B32; + CARD32 size B32; } xvAttributeInfo; #define sz_xvAttributeInfo 16 -typedef struct { - CARD32 id B32; - CARD8 type; - CARD8 byte_order; - CARD16 pad1 B16; - CARD8 guid[16]; - CARD8 bpp; - CARD8 num_planes; - CARD16 pad2 B16; - CARD8 depth; - CARD8 pad3; - CARD16 pad4 B16; - CARD32 red_mask B32; - CARD32 green_mask B32; - CARD32 blue_mask B32; - CARD8 format; - CARD8 pad5; - CARD16 pad6 B16; - CARD32 y_sample_bits B32; - CARD32 u_sample_bits B32; - CARD32 v_sample_bits B32; - CARD32 horz_y_period B32; - CARD32 horz_u_period B32; - CARD32 horz_v_period B32; - CARD32 vert_y_period B32; - CARD32 vert_u_period B32; - CARD32 vert_v_period B32; - CARD8 comp_order[32]; - CARD8 scanline_order; - CARD8 pad7; - CARD16 pad8 B16; - CARD32 pad9 B32; - CARD32 pad10 B32; +typedef struct +{ + CARD32 id B32; + CARD8 type; + CARD8 byte_order; + CARD16 pad1 B16; + CARD8 guid[16]; + CARD8 bpp; + CARD8 num_planes; + CARD16 pad2 B16; + CARD8 depth; + CARD8 pad3; + CARD16 pad4 B16; + CARD32 red_mask B32; + CARD32 green_mask B32; + CARD32 blue_mask B32; + CARD8 format; + CARD8 pad5; + CARD16 pad6 B16; + CARD32 y_sample_bits B32; + CARD32 u_sample_bits B32; + CARD32 v_sample_bits B32; + CARD32 horz_y_period B32; + CARD32 horz_u_period B32; + CARD32 horz_v_period B32; + CARD32 vert_y_period B32; + CARD32 vert_u_period B32; + CARD32 vert_v_period B32; + CARD8 comp_order[32]; + CARD8 scanline_order; + CARD8 pad7; + CARD16 pad8 B16; + CARD32 pad9 B32; + CARD32 pad10 B32; } xvImageFormatInfo; #define sz_xvImageFormatInfo 128 @@ -169,426 +175,460 @@ typedef struct { #define xvNumRequests (xv_LastRequest + 1) -typedef struct { - CARD8 reqType; - CARD8 xvReqType; - CARD16 length B16; +typedef struct +{ + CARD8 reqType; + CARD8 xvReqType; + CARD16 length B16; } xvQueryExtensionReq; #define sz_xvQueryExtensionReq 4 -typedef struct { - CARD8 reqType; - CARD8 xvReqType; - CARD16 length B16; - CARD32 window B32; +typedef struct +{ + CARD8 reqType; + CARD8 xvReqType; + CARD16 length B16; + CARD32 window B32; } xvQueryAdaptorsReq; #define sz_xvQueryAdaptorsReq 8 -typedef struct { - CARD8 reqType; - CARD8 xvReqType; - CARD16 length B16; - CARD32 port B32; +typedef struct +{ + CARD8 reqType; + CARD8 xvReqType; + CARD16 length B16; + CARD32 port B32; } xvQueryEncodingsReq; #define sz_xvQueryEncodingsReq 8 -typedef struct { - CARD8 reqType; - CARD8 xvReqType; - CARD16 length B16; - XvPortID port B32; - Drawable drawable B32; - GContext gc B32; - INT16 vid_x B16; - INT16 vid_y B16; - CARD16 vid_w B16; - CARD16 vid_h B16; - INT16 drw_x B16; - INT16 drw_y B16; - CARD16 drw_w B16; - CARD16 drw_h B16; +typedef struct +{ + CARD8 reqType; + CARD8 xvReqType; + CARD16 length B16; + XvPortID port B32; + Drawable drawable B32; + GContext gc B32; + INT16 vid_x B16; + INT16 vid_y B16; + CARD16 vid_w B16; + CARD16 vid_h B16; + INT16 drw_x B16; + INT16 drw_y B16; + CARD16 drw_w B16; + CARD16 drw_h B16; } xvPutVideoReq; #define sz_xvPutVideoReq 32 -typedef struct { - CARD8 reqType; - CARD8 xvReqType; - CARD16 length B16; - XvPortID port B32; - Drawable drawable B32; - GContext gc B32; - INT16 vid_x B16; - INT16 vid_y B16; - CARD16 vid_w B16; - CARD16 vid_h B16; - INT16 drw_x B16; - INT16 drw_y B16; - CARD16 drw_w B16; - CARD16 drw_h B16; +typedef struct +{ + CARD8 reqType; + CARD8 xvReqType; + CARD16 length B16; + XvPortID port B32; + Drawable drawable B32; + GContext gc B32; + INT16 vid_x B16; + INT16 vid_y B16; + CARD16 vid_w B16; + CARD16 vid_h B16; + INT16 drw_x B16; + INT16 drw_y B16; + CARD16 drw_w B16; + CARD16 drw_h B16; } xvPutStillReq; #define sz_xvPutStillReq 32 -typedef struct { - CARD8 reqType; - CARD8 xvReqType; - CARD16 length B16; - XvPortID port B32; - Drawable drawable B32; - GContext gc B32; - INT16 vid_x B16; - INT16 vid_y B16; - CARD16 vid_w B16; - CARD16 vid_h B16; - INT16 drw_x B16; - INT16 drw_y B16; - CARD16 drw_w B16; - CARD16 drw_h B16; +typedef struct +{ + CARD8 reqType; + CARD8 xvReqType; + CARD16 length B16; + XvPortID port B32; + Drawable drawable B32; + GContext gc B32; + INT16 vid_x B16; + INT16 vid_y B16; + CARD16 vid_w B16; + CARD16 vid_h B16; + INT16 drw_x B16; + INT16 drw_y B16; + CARD16 drw_w B16; + CARD16 drw_h B16; } xvGetVideoReq; #define sz_xvGetVideoReq 32 -typedef struct { - CARD8 reqType; - CARD8 xvReqType; - CARD16 length B16; - XvPortID port B32; - Drawable drawable B32; - GContext gc B32; - INT16 vid_x B16; - INT16 vid_y B16; - CARD16 vid_w B16; - CARD16 vid_h B16; - INT16 drw_x B16; - INT16 drw_y B16; - CARD16 drw_w B16; - CARD16 drw_h B16; +typedef struct +{ + CARD8 reqType; + CARD8 xvReqType; + CARD16 length B16; + XvPortID port B32; + Drawable drawable B32; + GContext gc B32; + INT16 vid_x B16; + INT16 vid_y B16; + CARD16 vid_w B16; + CARD16 vid_h B16; + INT16 drw_x B16; + INT16 drw_y B16; + CARD16 drw_w B16; + CARD16 drw_h B16; } xvGetStillReq; #define sz_xvGetStillReq 32 -typedef struct { - CARD8 reqType; - CARD8 xvReqType; - CARD16 length B16; - XvPortID port B32; - Time time B32; +typedef struct +{ + CARD8 reqType; + CARD8 xvReqType; + CARD16 length B16; + XvPortID port B32; + Time time B32; } xvGrabPortReq; #define sz_xvGrabPortReq 12 -typedef struct { - CARD8 reqType; - CARD8 xvReqType; - CARD16 length B16; - XvPortID port B32; - Time time B32; +typedef struct +{ + CARD8 reqType; + CARD8 xvReqType; + CARD16 length B16; + XvPortID port B32; + Time time B32; } xvUngrabPortReq; #define sz_xvUngrabPortReq 12 -typedef struct { - CARD8 reqType; - CARD8 xvReqType; - CARD16 length B16; - Drawable drawable B32; - BOOL onoff; - CARD8 pad1; - CARD16 pad2; +typedef struct +{ + CARD8 reqType; + CARD8 xvReqType; + CARD16 length B16; + Drawable drawable B32; + BOOL onoff; + CARD8 pad1; + CARD16 pad2; } xvSelectVideoNotifyReq; #define sz_xvSelectVideoNotifyReq 12 -typedef struct { - CARD8 reqType; - CARD8 xvReqType; - CARD16 length B16; - XvPortID port B32; - BOOL onoff; - CARD8 pad1; - CARD16 pad2; +typedef struct +{ + CARD8 reqType; + CARD8 xvReqType; + CARD16 length B16; + XvPortID port B32; + BOOL onoff; + CARD8 pad1; + CARD16 pad2; } xvSelectPortNotifyReq; #define sz_xvSelectPortNotifyReq 12 -typedef struct { - CARD8 reqType; - CARD8 xvReqType; - CARD16 length B16; - XvPortID port B32; - Drawable drawable B32; +typedef struct +{ + CARD8 reqType; + CARD8 xvReqType; + CARD16 length B16; + XvPortID port B32; + Drawable drawable B32; } xvStopVideoReq; #define sz_xvStopVideoReq 12 -typedef struct { - CARD8 reqType; - CARD8 xvReqType; - CARD16 length B16; - XvPortID port B32; - Atom attribute B32; - INT32 value B32; +typedef struct +{ + CARD8 reqType; + CARD8 xvReqType; + CARD16 length B16; + XvPortID port B32; + Atom attribute B32; + INT32 value B32; } xvSetPortAttributeReq; #define sz_xvSetPortAttributeReq 16 -typedef struct { - CARD8 reqType; - CARD8 xvReqType; - CARD16 length B16; - XvPortID port B32; - Atom attribute B32; +typedef struct +{ + CARD8 reqType; + CARD8 xvReqType; + CARD16 length B16; + XvPortID port B32; + Atom attribute B32; } xvGetPortAttributeReq; #define sz_xvGetPortAttributeReq 12 -typedef struct { - CARD8 reqType; - CARD8 xvReqType; - CARD16 length B16; - XvPortID port B32; - CARD16 vid_w B16; - CARD16 vid_h B16; - CARD16 drw_w B16; - CARD16 drw_h B16; - CARD8 motion; - CARD8 pad1; - CARD16 pad2 B16; +typedef struct +{ + CARD8 reqType; + CARD8 xvReqType; + CARD16 length B16; + XvPortID port B32; + CARD16 vid_w B16; + CARD16 vid_h B16; + CARD16 drw_w B16; + CARD16 drw_h B16; + CARD8 motion; + CARD8 pad1; + CARD16 pad2 B16; } xvQueryBestSizeReq; #define sz_xvQueryBestSizeReq 20 -typedef struct { - CARD8 reqType; - CARD8 xvReqType; - CARD16 length B16; - XvPortID port B32; +typedef struct +{ + CARD8 reqType; + CARD8 xvReqType; + CARD16 length B16; + XvPortID port B32; } xvQueryPortAttributesReq; #define sz_xvQueryPortAttributesReq 8 -typedef struct { - CARD8 reqType; - CARD8 xvReqType; - CARD16 length B16; - XvPortID port B32; - Drawable drawable B32; - GContext gc B32; - CARD32 id B32; - INT16 src_x B16; - INT16 src_y B16; - CARD16 src_w B16; - CARD16 src_h B16; - INT16 drw_x B16; - INT16 drw_y B16; - CARD16 drw_w B16; - CARD16 drw_h B16; - CARD16 width B16; - CARD16 height B16; +typedef struct +{ + CARD8 reqType; + CARD8 xvReqType; + CARD16 length B16; + XvPortID port B32; + Drawable drawable B32; + GContext gc B32; + CARD32 id B32; + INT16 src_x B16; + INT16 src_y B16; + CARD16 src_w B16; + CARD16 src_h B16; + INT16 drw_x B16; + INT16 drw_y B16; + CARD16 drw_w B16; + CARD16 drw_h B16; + CARD16 width B16; + CARD16 height B16; } xvPutImageReq; #define sz_xvPutImageReq 40 -typedef struct { - CARD8 reqType; - CARD8 xvReqType; - CARD16 length B16; - XvPortID port B32; - Drawable drawable B32; - GContext gc B32; - ShmSeg shmseg B32; - CARD32 id B32; - CARD32 offset B32; - INT16 src_x B16; - INT16 src_y B16; - CARD16 src_w B16; - CARD16 src_h B16; - INT16 drw_x B16; - INT16 drw_y B16; - CARD16 drw_w B16; - CARD16 drw_h B16; - CARD16 width B16; - CARD16 height B16; - CARD8 send_event; - CARD8 pad1; - CARD16 pad2 B16; +typedef struct +{ + CARD8 reqType; + CARD8 xvReqType; + CARD16 length B16; + XvPortID port B32; + Drawable drawable B32; + GContext gc B32; + ShmSeg shmseg B32; + CARD32 id B32; + CARD32 offset B32; + INT16 src_x B16; + INT16 src_y B16; + CARD16 src_w B16; + CARD16 src_h B16; + INT16 drw_x B16; + INT16 drw_y B16; + CARD16 drw_w B16; + CARD16 drw_h B16; + CARD16 width B16; + CARD16 height B16; + CARD8 send_event; + CARD8 pad1; + CARD16 pad2 B16; } xvShmPutImageReq; #define sz_xvShmPutImageReq 52 -typedef struct { - CARD8 reqType; - CARD8 xvReqType; - CARD16 length B16; - XvPortID port B32; +typedef struct +{ + CARD8 reqType; + CARD8 xvReqType; + CARD16 length B16; + XvPortID port B32; } xvListImageFormatsReq; #define sz_xvListImageFormatsReq 8 -typedef struct { - CARD8 reqType; - CARD8 xvReqType; - CARD16 length B16; - CARD32 port B32; - CARD32 id B32; - CARD16 width B16; - CARD16 height B16; +typedef struct +{ + CARD8 reqType; + CARD8 xvReqType; + CARD16 length B16; + CARD32 port B32; + CARD32 id B32; + CARD16 width B16; + CARD16 height B16; } xvQueryImageAttributesReq; #define sz_xvQueryImageAttributesReq 16 /* Replies */ -typedef struct _QueryExtensionReply { - BYTE type; /* X_Reply */ - CARD8 padb1; - CARD16 sequenceNumber B16; - CARD32 length B32; - CARD16 version B16; - CARD16 revision B16; - CARD32 padl4 B32; - CARD32 padl5 B32; - CARD32 padl6 B32; - CARD32 padl7 B32; - CARD32 padl8 B32; +typedef struct _QueryExtensionReply +{ + BYTE type; /* X_Reply */ + CARD8 padb1; + CARD16 sequenceNumber B16; + CARD32 length B32; + CARD16 version B16; + CARD16 revision B16; + CARD32 padl4 B32; + CARD32 padl5 B32; + CARD32 padl6 B32; + CARD32 padl7 B32; + CARD32 padl8 B32; } xvQueryExtensionReply; #define sz_xvQueryExtensionReply 32 -typedef struct _QueryAdaptorsReply { - BYTE type; /* X_Reply */ - CARD8 padb1; - CARD16 sequenceNumber B16; - CARD32 length B32; - CARD16 num_adaptors B16; - CARD16 pads3 B16; - CARD32 padl4 B32; - CARD32 padl5 B32; - CARD32 padl6 B32; - CARD32 padl7 B32; - CARD32 padl8 B32; +typedef struct _QueryAdaptorsReply +{ + BYTE type; /* X_Reply */ + CARD8 padb1; + CARD16 sequenceNumber B16; + CARD32 length B32; + CARD16 num_adaptors B16; + CARD16 pads3 B16; + CARD32 padl4 B32; + CARD32 padl5 B32; + CARD32 padl6 B32; + CARD32 padl7 B32; + CARD32 padl8 B32; } xvQueryAdaptorsReply; #define sz_xvQueryAdaptorsReply 32 -typedef struct _QueryEncodingsReply { - BYTE type; /* X_Reply */ - CARD8 padb1; - CARD16 sequenceNumber B16; - CARD32 length B32; - CARD16 num_encodings B16; - CARD32 padl3 B32; - CARD32 padl4 B32; - CARD32 padl5 B32; - CARD32 padl6 B32; - CARD32 padl7 B32; - CARD32 padl8 B32; +typedef struct _QueryEncodingsReply +{ + BYTE type; /* X_Reply */ + CARD8 padb1; + CARD16 sequenceNumber B16; + CARD32 length B32; + CARD16 num_encodings B16; + CARD32 padl3 B32; + CARD32 padl4 B32; + CARD32 padl5 B32; + CARD32 padl6 B32; + CARD32 padl7 B32; + CARD32 padl8 B32; } xvQueryEncodingsReply; #define sz_xvQueryEncodingsReply 32 -typedef struct { - BYTE type; /* X_Reply */ - BYTE result; - CARD16 sequenceNumber B16; - CARD32 length B32; /* 0 */ - CARD32 padl3 B32; - CARD32 padl4 B32; - CARD32 padl5 B32; - CARD32 padl6 B32; - CARD32 padl7 B32; - CARD32 padl8 B32; +typedef struct +{ + BYTE type; /* X_Reply */ + BYTE result; + CARD16 sequenceNumber B16; + CARD32 length B32; /* 0 */ + CARD32 padl3 B32; + CARD32 padl4 B32; + CARD32 padl5 B32; + CARD32 padl6 B32; + CARD32 padl7 B32; + CARD32 padl8 B32; } xvGrabPortReply; #define sz_xvGrabPortReply 32 -typedef struct { - BYTE type; /* X_Reply */ - BYTE padb1; - CARD16 sequenceNumber B16; - CARD32 length B32; /* 0 */ - INT32 value B32; - CARD32 padl4 B32; - CARD32 padl5 B32; - CARD32 padl6 B32; - CARD32 padl7 B32; - CARD32 padl8 B32; +typedef struct +{ + BYTE type; /* X_Reply */ + BYTE padb1; + CARD16 sequenceNumber B16; + CARD32 length B32; /* 0 */ + INT32 value B32; + CARD32 padl4 B32; + CARD32 padl5 B32; + CARD32 padl6 B32; + CARD32 padl7 B32; + CARD32 padl8 B32; } xvGetPortAttributeReply; #define sz_xvGetPortAttributeReply 32 -typedef struct { - BYTE type; /* X_Reply */ - BYTE padb1; - CARD16 sequenceNumber B16; - CARD32 length B32; /* 0 */ - CARD16 actual_width B16; - CARD16 actual_height B16; - CARD32 padl4 B32; - CARD32 padl5 B32; - CARD32 padl6 B32; - CARD32 padl7 B32; - CARD32 padl8 B32; +typedef struct +{ + BYTE type; /* X_Reply */ + BYTE padb1; + CARD16 sequenceNumber B16; + CARD32 length B32; /* 0 */ + CARD16 actual_width B16; + CARD16 actual_height B16; + CARD32 padl4 B32; + CARD32 padl5 B32; + CARD32 padl6 B32; + CARD32 padl7 B32; + CARD32 padl8 B32; } xvQueryBestSizeReply; #define sz_xvQueryBestSizeReply 32 -typedef struct { - BYTE type; /* X_Reply */ - BYTE padb1; - CARD16 sequenceNumber B16; - CARD32 length B32; /* 0 */ - CARD32 num_attributes B32; - CARD32 text_size B32; - CARD32 padl5 B32; - CARD32 padl6 B32; - CARD32 padl7 B32; - CARD32 padl8 B32; +typedef struct +{ + BYTE type; /* X_Reply */ + BYTE padb1; + CARD16 sequenceNumber B16; + CARD32 length B32; /* 0 */ + CARD32 num_attributes B32; + CARD32 text_size B32; + CARD32 padl5 B32; + CARD32 padl6 B32; + CARD32 padl7 B32; + CARD32 padl8 B32; } xvQueryPortAttributesReply; #define sz_xvQueryPortAttributesReply 32 -typedef struct { - BYTE type; /* X_Reply */ - BYTE padb1; - CARD16 sequenceNumber B16; - CARD32 length B32; - CARD32 num_formats B32; - CARD32 padl4 B32; - CARD32 padl5 B32; - CARD32 padl6 B32; - CARD32 padl7 B32; - CARD32 padl8 B32; +typedef struct +{ + BYTE type; /* X_Reply */ + BYTE padb1; + CARD16 sequenceNumber B16; + CARD32 length B32; + CARD32 num_formats B32; + CARD32 padl4 B32; + CARD32 padl5 B32; + CARD32 padl6 B32; + CARD32 padl7 B32; + CARD32 padl8 B32; } xvListImageFormatsReply; #define sz_xvListImageFormatsReply 32 -typedef struct { - BYTE type; /* X_Reply */ - BYTE padb1; - CARD16 sequenceNumber B16; - CARD32 length B32; - CARD32 num_planes B32; - CARD32 data_size B32; - CARD16 width B16; - CARD16 height B16; - CARD32 padl6 B32; - CARD32 padl7 B32; - CARD32 padl8 B32; +typedef struct +{ + BYTE type; /* X_Reply */ + BYTE padb1; + CARD16 sequenceNumber B16; + CARD32 length B32; + CARD32 num_planes B32; + CARD32 data_size B32; + CARD16 width B16; + CARD16 height B16; + CARD32 padl6 B32; + CARD32 padl7 B32; + CARD32 padl8 B32; } xvQueryImageAttributesReply; #define sz_xvQueryImageAttributesReply 32 /* DEFINE EVENT STRUCTURE */ -typedef struct { - union { - struct { - BYTE type; - BYTE detail; - CARD16 sequenceNumber B16; +typedef struct +{ + union + { + struct + { + BYTE type; + BYTE detail; + CARD16 sequenceNumber B16; + } u; + struct + { + BYTE type; + BYTE reason; + CARD16 sequenceNumber B16; + Time time B32; + Drawable drawable B32; + XvPortID port B32; + CARD32 padl5 B32; + CARD32 padl6 B32; + CARD32 padl7 B32; + CARD32 padl8 B32; + } videoNotify; + struct + { + BYTE type; + BYTE padb1; + CARD16 sequenceNumber B16; + Time time B32; + XvPortID port B32; + Atom attribute B32; + INT32 value B32; + CARD32 padl6 B32; + CARD32 padl7 B32; + CARD32 padl8 B32; + } portNotify; } u; - struct { - BYTE type; - BYTE reason; - CARD16 sequenceNumber B16; - Time time B32; - Drawable drawable B32; - XvPortID port B32; - CARD32 padl5 B32; - CARD32 padl6 B32; - CARD32 padl7 B32; - CARD32 padl8 B32; - } videoNotify; - struct { - BYTE type; - BYTE padb1; - CARD16 sequenceNumber B16; - Time time B32; - XvPortID port B32; - Atom attribute B32; - INT32 value B32; - CARD32 padl6 B32; - CARD32 padl7 B32; - CARD32 padl8 B32; - } portNotify; - } u; } xvEvent; #undef XvPortID @@ -601,4 +641,4 @@ typedef struct { #undef Atom #endif /* XVPROTO_H */ - +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/Xext/extensions/extutil.h b/src/video/Xext/extensions/extutil.h index f3a741ea2..1b78623e0 100644 --- a/src/video/Xext/extensions/extutil.h +++ b/src/video/Xext/extensions/extutil.h @@ -36,7 +36,7 @@ in this Software without prior written authorization from The Open Group. #ifndef _EXTUTIL_H_ #define _EXTUTIL_H_ -#include "SDL_stdinc.h" /* For portable string functions */ +#include "SDL_stdinc.h" /* For portable string functions */ #include "./Xext.h" @@ -45,133 +45,136 @@ in this Software without prior written authorization from The Open Group. * public. We also have to per-display info in a separate block since it isn't * stored directly in the Display structure. */ -typedef struct _XExtDisplayInfo { - struct _XExtDisplayInfo *next; /* keep a linked list */ - Display *display; /* which display this is */ - XExtCodes *codes; /* the extension protocol codes */ - XPointer data; /* extra data for extension to use */ +typedef struct _XExtDisplayInfo +{ + struct _XExtDisplayInfo *next; /* keep a linked list */ + Display *display; /* which display this is */ + XExtCodes *codes; /* the extension protocol codes */ + XPointer data; /* extra data for extension to use */ } XExtDisplayInfo; -typedef struct _XExtensionInfo { - XExtDisplayInfo *head; /* start of list */ - XExtDisplayInfo *cur; /* most recently used */ - int ndisplays; /* number of displays */ +typedef struct _XExtensionInfo +{ + XExtDisplayInfo *head; /* start of list */ + XExtDisplayInfo *cur; /* most recently used */ + int ndisplays; /* number of displays */ } XExtensionInfo; -typedef struct _XExtensionHooks { - int (*create_gc)( +typedef struct _XExtensionHooks +{ + int (*create_gc) ( #if NeedNestedPrototypes - Display* /* display */, - GC /* gc */, - XExtCodes* /* codes */ + Display * /* display */ , + GC /* gc */ , + XExtCodes * /* codes */ #endif -); - int (*copy_gc)( + ); + int (*copy_gc) ( #if NeedNestedPrototypes - Display* /* display */, - GC /* gc */, - XExtCodes* /* codes */ + Display * /* display */ , + GC /* gc */ , + XExtCodes * /* codes */ #endif -); - int (*flush_gc)( + ); + int (*flush_gc) ( #if NeedNestedPrototypes - Display* /* display */, - GC /* gc */, - XExtCodes* /* codes */ + Display * /* display */ , + GC /* gc */ , + XExtCodes * /* codes */ #endif -); - int (*free_gc)( + ); + int (*free_gc) ( #if NeedNestedPrototypes - Display* /* display */, - GC /* gc */, - XExtCodes* /* codes */ + Display * /* display */ , + GC /* gc */ , + XExtCodes * /* codes */ #endif -); - int (*create_font)( + ); + int (*create_font) ( #if NeedNestedPrototypes - Display* /* display */, - XFontStruct* /* fs */, - XExtCodes* /* codes */ + Display * /* display */ , + XFontStruct * /* fs */ , + XExtCodes * /* codes */ #endif -); - int (*free_font)( + ); + int (*free_font) ( #if NeedNestedPrototypes - Display* /* display */, - XFontStruct* /* fs */, - XExtCodes* /* codes */ + Display * /* display */ , + XFontStruct * /* fs */ , + XExtCodes * /* codes */ #endif -); - int (*close_display)( + ); + int (*close_display) ( #if NeedNestedPrototypes - Display* /* display */, - XExtCodes* /* codes */ + Display * /* display */ , + XExtCodes * /* codes */ #endif -); - Bool (*wire_to_event)( + ); + Bool(*wire_to_event) ( #if NeedNestedPrototypes - Display* /* display */, - XEvent* /* re */, - xEvent* /* event */ + Display * /* display */ , + XEvent * /* re */ , + xEvent * /* event */ #endif -); - Status (*event_to_wire)( + ); + Status(*event_to_wire) ( #if NeedNestedPrototypes - Display* /* display */, - XEvent* /* re */, - xEvent* /* event */ + Display * /* display */ , + XEvent * /* re */ , + xEvent * /* event */ #endif -); - int (*error)( + ); + int (*error) ( #if NeedNestedPrototypes - Display* /* display */, - xError* /* err */, - XExtCodes* /* codes */, - int* /* ret_code */ + Display * /* display */ , + xError * /* err */ , + XExtCodes * /* codes */ , + int * /* ret_code */ #endif -); - char *(*error_string)( + ); + char *(*error_string) ( #if NeedNestedPrototypes - Display* /* display */, - int /* code */, - XExtCodes* /* codes */, - char* /* buffer */, - int /* nbytes */ + Display * /* display */ , + int /* code */ , + XExtCodes * /* codes */ , + char * /* buffer */ , + int /* nbytes */ #endif -); + ); } XExtensionHooks; extern XExtensionInfo *XextCreateExtension( #if NeedFunctionPrototypes - void + void #endif -); + ); extern void XextDestroyExtension( #if NeedFunctionPrototypes - XExtensionInfo* /* info */ + XExtensionInfo * /* info */ #endif -); + ); extern XExtDisplayInfo *XextAddDisplay( #if NeedFunctionPrototypes - XExtensionInfo* /* extinfo */, - Display* /* dpy */, - char* /* ext_name */, - XExtensionHooks* /* hooks */, - int /* nevents */, - XPointer /* data */ -#endif -); + XExtensionInfo * /* extinfo */ , + Display * /* dpy */ , + char * /* ext_name */ , + XExtensionHooks * /* hooks */ , + int /* nevents */ , + XPointer /* data */ +#endif + ); extern int XextRemoveDisplay( #if NeedFunctionPrototypes - XExtensionInfo* /* extinfo */, - Display* /* dpy */ + XExtensionInfo * /* extinfo */ , + Display * /* dpy */ #endif -); + ); extern XExtDisplayInfo *XextFindDisplay( #if NeedFunctionPrototypes - XExtensionInfo* /* extinfo */, - Display* /* dpy */ + XExtensionInfo * /* extinfo */ , + Display * /* dpy */ #endif -); + ); #define XextHasExtension(i) ((i) && ((i)->codes)) #define XextCheckExtension(dpy,i,name,val) \ @@ -224,3 +227,4 @@ char *proc (Display *dpy, int code, XExtCodes *codes, char *buf, int n) \ #define XEXT_ERROR_STRING_PROTO(proc) \ char *proc(Display *dpy, int code, XExtCodes *codes, char *buf, int n) #endif +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/Xext/extensions/panoramiXext.h b/src/video/Xext/extensions/panoramiXext.h index e89d8917b..37d04a531 100644 --- a/src/video/Xext/extensions/panoramiXext.h +++ b/src/video/Xext/extensions/panoramiXext.h @@ -35,18 +35,22 @@ Equipment Corporation. #define PANORAMIX_MAJOR_VERSION 1 /* current version number */ #define PANORAMIX_MINOR_VERSION 1 -typedef struct { - Window window; /* PanoramiX window - may not exist */ - int screen; - int State; /* PanroamiXOff, PanoramiXOn */ - int width; /* width of this screen */ - int height; /* height of this screen */ - int ScreenCount; /* real physical number of screens */ - XID eventMask; /* selected events for this client */ -} SDL_NAME(XPanoramiXInfo); - -extern SDL_NAME(XPanoramiXInfo) *SDL_NAME(XPanoramiXAllocInfo) ( +typedef struct +{ + Window window; /* PanoramiX window - may not exist */ + int screen; + int State; /* PanroamiXOff, PanoramiXOn */ + int width; /* width of this screen */ + int height; /* height of this screen */ + int ScreenCount; /* real physical number of screens */ + XID eventMask; /* selected events for this client */ +} SDL_NAME(XPanoramiXInfo); + +extern +SDL_NAME(XPanoramiXInfo) * +SDL_NAME(XPanoramiXAllocInfo) ( #if NeedFunctionPrototypes - void + void #endif -); + ); +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/Xext/extensions/panoramiXproto.h b/src/video/Xext/extensions/panoramiXproto.h index fe3826eb3..69a0ce3f5 100644 --- a/src/video/Xext/extensions/panoramiXproto.h +++ b/src/video/Xext/extensions/panoramiXproto.h @@ -40,153 +40,167 @@ Equipment Corporation. #define X_XineramaIsActive 4 #define X_XineramaQueryScreens 5 -typedef struct _PanoramiXQueryVersion { - CARD8 reqType; /* always PanoramiXReqCode */ - CARD8 panoramiXReqType; /* always X_PanoramiXQueryVersion */ - CARD16 length B16; - CARD8 clientMajor; - CARD8 clientMinor; - CARD16 unused B16; +typedef struct _PanoramiXQueryVersion +{ + CARD8 reqType; /* always PanoramiXReqCode */ + CARD8 panoramiXReqType; /* always X_PanoramiXQueryVersion */ + CARD16 length B16; + CARD8 clientMajor; + CARD8 clientMinor; + CARD16 unused B16; } xPanoramiXQueryVersionReq; #define sz_xPanoramiXQueryVersionReq 8 -typedef struct { - CARD8 type; /* must be X_Reply */ - CARD8 pad1; /* unused */ - CARD16 sequenceNumber B16; /* last sequence number */ - CARD32 length B32; /* 0 */ - CARD16 majorVersion B16; - CARD16 minorVersion B16; - CARD32 pad2 B32; /* unused */ - CARD32 pad3 B32; /* unused */ - CARD32 pad4 B32; /* unused */ - CARD32 pad5 B32; /* unused */ - CARD32 pad6 B32; /* unused */ +typedef struct +{ + CARD8 type; /* must be X_Reply */ + CARD8 pad1; /* unused */ + CARD16 sequenceNumber B16; /* last sequence number */ + CARD32 length B32; /* 0 */ + CARD16 majorVersion B16; + CARD16 minorVersion B16; + CARD32 pad2 B32; /* unused */ + CARD32 pad3 B32; /* unused */ + CARD32 pad4 B32; /* unused */ + CARD32 pad5 B32; /* unused */ + CARD32 pad6 B32; /* unused */ } xPanoramiXQueryVersionReply; #define sz_xPanoramiXQueryVersionReply 32 -typedef struct _PanoramiXGetState { - CARD8 reqType; /* always PanoramiXReqCode */ - CARD8 panoramiXReqType; /* always X_PanoramiXGetState */ - CARD16 length B16; - CARD32 window B32; +typedef struct _PanoramiXGetState +{ + CARD8 reqType; /* always PanoramiXReqCode */ + CARD8 panoramiXReqType; /* always X_PanoramiXGetState */ + CARD16 length B16; + CARD32 window B32; } xPanoramiXGetStateReq; -#define sz_xPanoramiXGetStateReq 8 - -typedef struct { - BYTE type; - BYTE state; - CARD16 sequenceNumber B16; - CARD32 length B32; - CARD32 window B32; - CARD32 pad1 B32; /* unused */ - CARD32 pad2 B32; /* unused */ - CARD32 pad3 B32; /* unused */ - CARD32 pad4 B32; /* unused */ - CARD32 pad5 B32; /* unused */ +#define sz_xPanoramiXGetStateReq 8 + +typedef struct +{ + BYTE type; + BYTE state; + CARD16 sequenceNumber B16; + CARD32 length B32; + CARD32 window B32; + CARD32 pad1 B32; /* unused */ + CARD32 pad2 B32; /* unused */ + CARD32 pad3 B32; /* unused */ + CARD32 pad4 B32; /* unused */ + CARD32 pad5 B32; /* unused */ } xPanoramiXGetStateReply; #define sz_panoramiXGetStateReply 32 -typedef struct _PanoramiXGetScreenCount { - CARD8 reqType; /* always PanoramiXReqCode */ - CARD8 panoramiXReqType; /* always X_PanoramiXGetScreenCount */ - CARD16 length B16; - CARD32 window B32; +typedef struct _PanoramiXGetScreenCount +{ + CARD8 reqType; /* always PanoramiXReqCode */ + CARD8 panoramiXReqType; /* always X_PanoramiXGetScreenCount */ + CARD16 length B16; + CARD32 window B32; } xPanoramiXGetScreenCountReq; #define sz_xPanoramiXGetScreenCountReq 8 -typedef struct { - BYTE type; - BYTE ScreenCount; - CARD16 sequenceNumber B16; - CARD32 length B32; - CARD32 window B32; - CARD32 pad1 B32; /* unused */ - CARD32 pad2 B32; /* unused */ - CARD32 pad3 B32; /* unused */ - CARD32 pad4 B32; /* unused */ - CARD32 pad5 B32; /* unused */ +typedef struct +{ + BYTE type; + BYTE ScreenCount; + CARD16 sequenceNumber B16; + CARD32 length B32; + CARD32 window B32; + CARD32 pad1 B32; /* unused */ + CARD32 pad2 B32; /* unused */ + CARD32 pad3 B32; /* unused */ + CARD32 pad4 B32; /* unused */ + CARD32 pad5 B32; /* unused */ } xPanoramiXGetScreenCountReply; #define sz_panoramiXGetScreenCountReply 32 -typedef struct _PanoramiXGetScreenSize { - CARD8 reqType; /* always PanoramiXReqCode */ - CARD8 panoramiXReqType; /* always X_PanoramiXGetState */ - CARD16 length B16; - CARD32 window B32; - CARD32 screen B32; +typedef struct _PanoramiXGetScreenSize +{ + CARD8 reqType; /* always PanoramiXReqCode */ + CARD8 panoramiXReqType; /* always X_PanoramiXGetState */ + CARD16 length B16; + CARD32 window B32; + CARD32 screen B32; } xPanoramiXGetScreenSizeReq; -#define sz_xPanoramiXGetScreenSizeReq 12 - -typedef struct { - BYTE type; - CARD8 pad1; - CARD16 sequenceNumber B16; - CARD32 length B32; - CARD32 width B32; - CARD32 height B32; - CARD32 window B32; - CARD32 screen B32; - CARD32 pad2 B32; /* unused */ - CARD32 pad3 B32; /* unused */ +#define sz_xPanoramiXGetScreenSizeReq 12 + +typedef struct +{ + BYTE type; + CARD8 pad1; + CARD16 sequenceNumber B16; + CARD32 length B32; + CARD32 width B32; + CARD32 height B32; + CARD32 window B32; + CARD32 screen B32; + CARD32 pad2 B32; /* unused */ + CARD32 pad3 B32; /* unused */ } xPanoramiXGetScreenSizeReply; -#define sz_panoramiXGetScreenSizeReply 32 +#define sz_panoramiXGetScreenSizeReply 32 /************ Alternate protocol ******************/ -typedef struct { - CARD8 reqType; - CARD8 panoramiXReqType; - CARD16 length B16; +typedef struct +{ + CARD8 reqType; + CARD8 panoramiXReqType; + CARD16 length B16; } xXineramaIsActiveReq; #define sz_xXineramaIsActiveReq 4 -typedef struct { - BYTE type; - CARD8 pad1; - CARD16 sequenceNumber B16; - CARD32 length B32; - CARD32 state B32; - CARD32 pad2 B32; - CARD32 pad3 B32; - CARD32 pad4 B32; - CARD32 pad5 B32; - CARD32 pad6 B32; +typedef struct +{ + BYTE type; + CARD8 pad1; + CARD16 sequenceNumber B16; + CARD32 length B32; + CARD32 state B32; + CARD32 pad2 B32; + CARD32 pad3 B32; + CARD32 pad4 B32; + CARD32 pad5 B32; + CARD32 pad6 B32; } xXineramaIsActiveReply; -#define sz_XineramaIsActiveReply 32 +#define sz_XineramaIsActiveReply 32 -typedef struct { - CARD8 reqType; - CARD8 panoramiXReqType; - CARD16 length B16; +typedef struct +{ + CARD8 reqType; + CARD8 panoramiXReqType; + CARD16 length B16; } xXineramaQueryScreensReq; #define sz_xXineramaQueryScreensReq 4 -typedef struct { - BYTE type; - CARD8 pad1; - CARD16 sequenceNumber B16; - CARD32 length B32; - CARD32 number B32; - CARD32 pad2 B32; - CARD32 pad3 B32; - CARD32 pad4 B32; - CARD32 pad5 B32; - CARD32 pad6 B32; +typedef struct +{ + BYTE type; + CARD8 pad1; + CARD16 sequenceNumber B16; + CARD32 length B32; + CARD32 number B32; + CARD32 pad2 B32; + CARD32 pad3 B32; + CARD32 pad4 B32; + CARD32 pad5 B32; + CARD32 pad6 B32; } xXineramaQueryScreensReply; -#define sz_XineramaQueryScreensReply 32 - -typedef struct { - INT16 x_org B16; - INT16 y_org B16; - CARD16 width B16; - CARD16 height B16; +#define sz_XineramaQueryScreensReply 32 + +typedef struct +{ + INT16 x_org B16; + INT16 y_org B16; + CARD16 width B16; + CARD16 height B16; } xXineramaScreenInfo; #define sz_XineramaScreenInfo 8 -#endif +#endif +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/Xext/extensions/xf86dga.h b/src/video/Xext/extensions/xf86dga.h index c71ef4b14..e64056061 100644 --- a/src/video/Xext/extensions/xf86dga.h +++ b/src/video/Xext/extensions/xf86dga.h @@ -60,206 +60,162 @@ #define XF86DGANumberErrors (XF86DGAOperationNotSupported + 1) -typedef struct { - int num; /* A unique identifier for the mode (num > 0) */ - char *name; /* name of mode given in the XF86Config */ - float verticalRefresh; - int flags; /* DGA_CONCURRENT_ACCESS, etc... */ - int imageWidth; /* linear accessible portion (pixels) */ - int imageHeight; - int pixmapWidth; /* Xlib accessible portion (pixels) */ - int pixmapHeight; /* both fields ignored if no concurrent access */ - int bytesPerScanline; - int byteOrder; /* MSBFirst, LSBFirst */ - int depth; - int bitsPerPixel; - unsigned long redMask; - unsigned long greenMask; - unsigned long blueMask; - short visualClass; - int viewportWidth; - int viewportHeight; - int xViewportStep; /* viewport position granularity */ - int yViewportStep; - int maxViewportX; /* max viewport origin */ - int maxViewportY; - int viewportFlags; /* types of page flipping possible */ - int reserved1; - int reserved2; +typedef struct +{ + int num; /* A unique identifier for the mode (num > 0) */ + char *name; /* name of mode given in the XF86Config */ + float verticalRefresh; + int flags; /* DGA_CONCURRENT_ACCESS, etc... */ + int imageWidth; /* linear accessible portion (pixels) */ + int imageHeight; + int pixmapWidth; /* Xlib accessible portion (pixels) */ + int pixmapHeight; /* both fields ignored if no concurrent access */ + int bytesPerScanline; + int byteOrder; /* MSBFirst, LSBFirst */ + int depth; + int bitsPerPixel; + unsigned long redMask; + unsigned long greenMask; + unsigned long blueMask; + short visualClass; + int viewportWidth; + int viewportHeight; + int xViewportStep; /* viewport position granularity */ + int yViewportStep; + int maxViewportX; /* max viewport origin */ + int maxViewportY; + int viewportFlags; /* types of page flipping possible */ + int reserved1; + int reserved2; } SDL_NAME(XDGAMode); -typedef struct { - SDL_NAME(XDGAMode) mode; - unsigned char *data; - Pixmap pixmap; +typedef struct +{ + SDL_NAME(XDGAMode) mode; + unsigned char *data; + Pixmap pixmap; } SDL_NAME(XDGADevice); #ifndef _XF86DGA_SERVER_ -_XFUNCPROTOBEGIN - -typedef struct { - int type; - unsigned long serial; - Display *display; - int screen; - Time time; - unsigned int state; - unsigned int button; +_XFUNCPROTOBEGIN typedef struct +{ + int type; + unsigned long serial; + Display *display; + int screen; + Time time; + unsigned int state; + unsigned int button; } SDL_NAME(XDGAButtonEvent); -typedef struct { - int type; - unsigned long serial; - Display *display; - int screen; - Time time; - unsigned int state; - unsigned int keycode; +typedef struct +{ + int type; + unsigned long serial; + Display *display; + int screen; + Time time; + unsigned int state; + unsigned int keycode; } SDL_NAME(XDGAKeyEvent); -typedef struct { - int type; - unsigned long serial; - Display *display; - int screen; - Time time; - unsigned int state; - int dx; - int dy; +typedef struct +{ + int type; + unsigned long serial; + Display *display; + int screen; + Time time; + unsigned int state; + int dx; + int dy; } SDL_NAME(XDGAMotionEvent); -typedef union { - int type; - SDL_NAME(XDGAButtonEvent) xbutton; - SDL_NAME(XDGAKeyEvent) xkey; - SDL_NAME(XDGAMotionEvent) xmotion; - long pad[24]; +typedef union +{ + int type; + SDL_NAME(XDGAButtonEvent) xbutton; + SDL_NAME(XDGAKeyEvent) xkey; + SDL_NAME(XDGAMotionEvent) xmotion; + long pad[24]; } SDL_NAME(XDGAEvent); -Bool SDL_NAME(XDGAQueryExtension)( - Display *dpy, - int *eventBase, - int *erroBase -); - -Bool SDL_NAME(XDGAQueryVersion)( - Display *dpy, - int *majorVersion, - int *minorVersion -); - -SDL_NAME(XDGAMode)* SDL_NAME(XDGAQueryModes)( - Display *dpy, - int screen, - int *num -); - -SDL_NAME(XDGADevice)* SDL_NAME(XDGASetMode)( - Display *dpy, - int screen, - int mode -); - -Bool SDL_NAME(XDGAOpenFramebuffer)( - Display *dpy, - int screen -); - -void SDL_NAME(XDGACloseFramebuffer)( - Display *dpy, - int screen -); - -void SDL_NAME(XDGASetViewport)( - Display *dpy, - int screen, - int x, - int y, - int flags -); - -void SDL_NAME(XDGAInstallColormap)( - Display *dpy, - int screen, - Colormap cmap -); - -Colormap SDL_NAME(XDGACreateColormap)( - Display *dpy, - int screen, - SDL_NAME(XDGADevice) *device, - int alloc -); - -void SDL_NAME(XDGASelectInput)( - Display *dpy, - int screen, - long event_mask -); - -void SDL_NAME(XDGAFillRectangle)( - Display *dpy, - int screen, - int x, - int y, - unsigned int width, - unsigned int height, - unsigned long color -); - - -void SDL_NAME(XDGACopyArea)( - Display *dpy, - int screen, - int srcx, - int srcy, - unsigned int width, - unsigned int height, - int dstx, - int dsty -); - - -void SDL_NAME(XDGACopyTransparentArea)( - Display *dpy, - int screen, - int srcx, - int srcy, - unsigned int width, - unsigned int height, - int dstx, - int dsty, - unsigned long key -); - -int SDL_NAME(XDGAGetViewportStatus)( - Display *dpy, - int screen -); - -void SDL_NAME(XDGASync)( - Display *dpy, - int screen -); - -Bool SDL_NAME(XDGASetClientVersion)( - Display *dpy -); - -void SDL_NAME(XDGAChangePixmapMode)( - Display *dpy, - int screen, - int *x, - int *y, - int mode -); - - -void SDL_NAME(XDGAKeyEventToXKeyEvent)(SDL_NAME(XDGAKeyEvent)* dk, XKeyEvent* xk); +Bool SDL_NAME(XDGAQueryExtension) (Display * dpy, + int *eventBase, int *erroBase); + +Bool SDL_NAME(XDGAQueryVersion) (Display * dpy, + int *majorVersion, int *minorVersion); + +SDL_NAME(XDGAMode) * SDL_NAME(XDGAQueryModes) (Display * dpy, + int screen, int *num); + +SDL_NAME(XDGADevice) * SDL_NAME(XDGASetMode) (Display * dpy, + int screen, int mode); + +Bool +SDL_NAME(XDGAOpenFramebuffer) (Display * dpy, int screen); + + void SDL_NAME(XDGACloseFramebuffer) (Display * dpy, int screen); + + void SDL_NAME(XDGASetViewport) (Display * dpy, + int screen, int x, int y, int flags); + + void SDL_NAME(XDGAInstallColormap) (Display * dpy, + int screen, Colormap cmap); + +Colormap +SDL_NAME(XDGACreateColormap) (Display * dpy, + int screen, + SDL_NAME(XDGADevice) * device, int alloc); + + void SDL_NAME(XDGASelectInput) (Display * dpy, int screen, + long event_mask); + + void SDL_NAME(XDGAFillRectangle) (Display * dpy, + int screen, + int x, + int y, + unsigned int width, + unsigned int height, + unsigned long color); + + + void SDL_NAME(XDGACopyArea) (Display * dpy, + int screen, + int srcx, + int srcy, + unsigned int width, + unsigned int height, int dstx, int dsty); + + + void SDL_NAME(XDGACopyTransparentArea) (Display * dpy, + int screen, + int srcx, + int srcy, + unsigned int width, + unsigned int height, + int dstx, + int dsty, unsigned long key); + + int SDL_NAME(XDGAGetViewportStatus) (Display * dpy, int screen); + + void SDL_NAME(XDGASync) (Display * dpy, int screen); + +Bool +SDL_NAME(XDGASetClientVersion) (Display * dpy); + + void SDL_NAME(XDGAChangePixmapMode) (Display * dpy, + int screen, int *x, int *y, + int mode); + + + void SDL_NAME(XDGAKeyEventToXKeyEvent) (SDL_NAME(XDGAKeyEvent) * dk, + XKeyEvent * xk); _XFUNCPROTOEND #endif /* _XF86DGA_SERVER_ */ #endif /* _XF86DGA_H_ */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/Xext/extensions/xf86dga1.h b/src/video/Xext/extensions/xf86dga1.h index 4a49e9f38..976378743 100644 --- a/src/video/Xext/extensions/xf86dga1.h +++ b/src/video/Xext/extensions/xf86dga1.h @@ -41,129 +41,127 @@ Copyright (c) 1995 XFree86 Inc #ifndef _XF86DGA_SERVER_ -_XFUNCPROTOBEGIN - -Bool SDL_NAME(XF86DGAQueryVersion)( +_XFUNCPROTOBEGIN Bool SDL_NAME(XF86DGAQueryVersion) ( #if NeedFunctionPrototypes - Display* /* dpy */, - int* /* majorVersion */, - int* /* minorVersion */ + Display * /* dpy */ , + int * + /* majorVersion */ , + int * /* minorVersion */ #endif -); + ); -Bool SDL_NAME(XF86DGAQueryExtension)( +Bool SDL_NAME(XF86DGAQueryExtension) ( #if NeedFunctionPrototypes - Display* /* dpy */, - int* /* event_base */, - int* /* error_base */ + Display * /* dpy */ , + int * /* event_base */ , + int * /* error_base */ #endif -); + ); -Status SDL_NAME(XF86DGAGetVideoLL)( +Status SDL_NAME(XF86DGAGetVideoLL) ( #if NeedFunctionPrototypes - Display* /* dpy */, - int /* screen */, - int * /* base addr */, - int * /* width */, - int * /* bank_size */, - int * /* ram_size */ + Display * /* dpy */ , + int /* screen */ , + int * /* base addr */ , + int * /* width */ , + int * /* bank_size */ , + int * /* ram_size */ #endif -); + ); -Status SDL_NAME(XF86DGAGetVideo)( +Status SDL_NAME(XF86DGAGetVideo) ( #if NeedFunctionPrototypes - Display* /* dpy */, - int /* screen */, - char ** /* base addr */, - int * /* width */, - int * /* bank_size */, - int * /* ram_size */ + Display * /* dpy */ , + int /* screen */ , + char ** /* base addr */ , + int * /* width */ , + int * /* bank_size */ , + int * /* ram_size */ #endif -); + ); -Status SDL_NAME(XF86DGADirectVideo)( +Status SDL_NAME(XF86DGADirectVideo) ( #if NeedFunctionPrototypes - Display* /* dpy */, - int /* screen */, - int /* enable */ + Display * /* dpy */ , + int /* screen */ , + int /* enable */ #endif -); + ); -Status SDL_NAME(XF86DGADirectVideoLL)( +Status SDL_NAME(XF86DGADirectVideoLL) ( #if NeedFunctionPrototypes - Display* /* dpy */, - int /* screen */, - int /* enable */ + Display * /* dpy */ , + int /* screen */ , + int /* enable */ #endif -); + ); -Status SDL_NAME(XF86DGAGetViewPortSize)( +Status SDL_NAME(XF86DGAGetViewPortSize) ( #if NeedFunctionPrototypes - Display* /* dpy */, - int /* screen */, - int * /* width */, - int * /* height */ + Display * /* dpy */ , + int /* screen */ , + int * /* width */ , + int * /* height */ #endif -); + ); -Status SDL_NAME(XF86DGASetViewPort)( +Status SDL_NAME(XF86DGASetViewPort) ( #if NeedFunctionPrototypes - Display* /* dpy */, - int /* screen */, - int x /* X */, - int y /* Y */ + Display * /* dpy */ , + int /* screen */ , + int x /* X */ , + int y /* Y */ #endif -); + ); -Status SDL_NAME(XF86DGAGetVidPage)( +Status SDL_NAME(XF86DGAGetVidPage) ( #if NeedFunctionPrototypes - Display* /* dpy */, - int /* screen */, - int * /* vid page */ + Display * /* dpy */ , + int /* screen */ , + int * /* vid page */ #endif -); + ); -Status SDL_NAME(XF86DGASetVidPage)( +Status SDL_NAME(XF86DGASetVidPage) ( #if NeedFunctionPrototypes - Display* /* dpy */, - int /* screen */, - int /* vid page */ + Display * /* dpy */ , + int /* screen */ , + int /* vid page */ #endif -); + ); -Status SDL_NAME(XF86DGAInstallColormap)( +Status SDL_NAME(XF86DGAInstallColormap) ( #if NeedFunctionPrototypes - Display* /* dpy */, - int /* screen */, - Colormap /*Colormap */ + Display * /* dpy */ , + int /* screen */ , + Colormap /*Colormap */ #endif -); + ); -int SDL_NAME(XF86DGAForkApp)( +int SDL_NAME(XF86DGAForkApp) ( #if NeedFunctionPrototypes - int screen + int screen #endif -); + ); -Status SDL_NAME(XF86DGAQueryDirectVideo)( +Status SDL_NAME(XF86DGAQueryDirectVideo) ( #if NeedFunctionPrototypes - Display * /* dpy */, - int /* screen */, - int * /* flags */ + Display * /* dpy */ , + int /* screen */ , + int * /* flags */ #endif -); + ); -Bool SDL_NAME(XF86DGAViewPortChanged)( +Bool SDL_NAME(XF86DGAViewPortChanged) ( #if NeedFunctionPrototypes - Display * /* dpy */, - int /* screen */, - int /* n */ + Display * /* dpy */ , + int /* screen */ , + int /* n */ #endif -); + ); _XFUNCPROTOEND - #endif /* _XF86DGA_SERVER_ */ - #endif /* _XF86DGA1_H_ */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/Xext/extensions/xf86dga1str.h b/src/video/Xext/extensions/xf86dga1str.h index 5695fbd13..5ad889efc 100644 --- a/src/video/Xext/extensions/xf86dga1str.h +++ b/src/video/Xext/extensions/xf86dga1str.h @@ -9,186 +9,202 @@ Copyright (c) 1995 XFree86 Inc. #ifndef _XF86DGASTR1_H_ #define _XF86DGASTR1_H_ -typedef struct _XF86DGAQueryVersion { - CARD8 reqType; /* always DGAReqCode */ - CARD8 dgaReqType; /* always X_DGAQueryVersion */ - CARD16 length B16; +typedef struct _XF86DGAQueryVersion +{ + CARD8 reqType; /* always DGAReqCode */ + CARD8 dgaReqType; /* always X_DGAQueryVersion */ + CARD16 length B16; } xXF86DGAQueryVersionReq; #define sz_xXF86DGAQueryVersionReq 4 -typedef struct { - BYTE type; /* X_Reply */ - BOOL pad1; - CARD16 sequenceNumber B16; - CARD32 length B32; - CARD16 majorVersion B16; /* major version of DGA protocol */ - CARD16 minorVersion B16; /* minor version of DGA protocol */ - CARD32 pad2 B32; - CARD32 pad3 B32; - CARD32 pad4 B32; - CARD32 pad5 B32; - CARD32 pad6 B32; +typedef struct +{ + BYTE type; /* X_Reply */ + BOOL pad1; + CARD16 sequenceNumber B16; + CARD32 length B32; + CARD16 majorVersion B16; /* major version of DGA protocol */ + CARD16 minorVersion B16; /* minor version of DGA protocol */ + CARD32 pad2 B32; + CARD32 pad3 B32; + CARD32 pad4 B32; + CARD32 pad5 B32; + CARD32 pad6 B32; } xXF86DGAQueryVersionReply; #define sz_xXF86DGAQueryVersionReply 32 -typedef struct _XF86DGAGetVideoLL { - CARD8 reqType; /* always DGAReqCode */ - CARD8 dgaReqType; /* always X_XF86DGAGetVideoLL */ - CARD16 length B16; - CARD16 screen B16; - CARD16 pad B16; +typedef struct _XF86DGAGetVideoLL +{ + CARD8 reqType; /* always DGAReqCode */ + CARD8 dgaReqType; /* always X_XF86DGAGetVideoLL */ + CARD16 length B16; + CARD16 screen B16; + CARD16 pad B16; } xXF86DGAGetVideoLLReq; #define sz_xXF86DGAGetVideoLLReq 8 -typedef struct _XF86DGAInstallColormap{ - CARD8 reqType; - CARD8 dgaReqType; - CARD16 length B16; - CARD16 screen B16; - CARD16 pad2; - CARD32 id B32; /* colormap. */ +typedef struct _XF86DGAInstallColormap +{ + CARD8 reqType; + CARD8 dgaReqType; + CARD16 length B16; + CARD16 screen B16; + CARD16 pad2; + CARD32 id B32; /* colormap. */ } xXF86DGAInstallColormapReq; #define sz_xXF86DGAInstallColormapReq 12 -typedef struct { - BYTE type; - BOOL pad1; - CARD16 sequenceNumber B16; - CARD32 length B32; - CARD32 offset B32; - CARD32 width B32; - CARD32 bank_size B32; - CARD32 ram_size B32; - CARD32 pad4 B32; - CARD32 pad5 B32; +typedef struct +{ + BYTE type; + BOOL pad1; + CARD16 sequenceNumber B16; + CARD32 length B32; + CARD32 offset B32; + CARD32 width B32; + CARD32 bank_size B32; + CARD32 ram_size B32; + CARD32 pad4 B32; + CARD32 pad5 B32; } xXF86DGAGetVideoLLReply; #define sz_xXF86DGAGetVideoLLReply 32 -typedef struct _XF86DGADirectVideo { - CARD8 reqType; /* always DGAReqCode */ - CARD8 dgaReqType; /* always X_XF86DGADirectVideo */ - CARD16 length B16; - CARD16 screen B16; - CARD16 enable B16; +typedef struct _XF86DGADirectVideo +{ + CARD8 reqType; /* always DGAReqCode */ + CARD8 dgaReqType; /* always X_XF86DGADirectVideo */ + CARD16 length B16; + CARD16 screen B16; + CARD16 enable B16; } xXF86DGADirectVideoReq; #define sz_xXF86DGADirectVideoReq 8 -typedef struct _XF86DGAGetViewPortSize { - CARD8 reqType; /* always DGAReqCode */ - CARD8 dgaReqType; /* always X_XF86DGAGetViewPort */ - CARD16 length B16; - CARD16 screen B16; - CARD16 pad B16; +typedef struct _XF86DGAGetViewPortSize +{ + CARD8 reqType; /* always DGAReqCode */ + CARD8 dgaReqType; /* always X_XF86DGAGetViewPort */ + CARD16 length B16; + CARD16 screen B16; + CARD16 pad B16; } xXF86DGAGetViewPortSizeReq; #define sz_xXF86DGAGetViewPortSizeReq 8 -typedef struct { - BYTE type; - BOOL pad1; - CARD16 sequenceNumber B16; - CARD32 length B32; - CARD32 width B32; - CARD32 height B32; - CARD32 pad2 B32; - CARD32 pad3 B32; - CARD32 pad4 B32; - CARD32 pad5 B32; +typedef struct +{ + BYTE type; + BOOL pad1; + CARD16 sequenceNumber B16; + CARD32 length B32; + CARD32 width B32; + CARD32 height B32; + CARD32 pad2 B32; + CARD32 pad3 B32; + CARD32 pad4 B32; + CARD32 pad5 B32; } xXF86DGAGetViewPortSizeReply; #define sz_xXF86DGAGetViewPortSizeReply 32 -typedef struct _XF86DGASetViewPort { - CARD8 reqType; /* always DGAReqCode */ - CARD8 dgaReqType; /* always X_XF86DGASetViewPort */ - CARD16 length B16; - CARD16 screen B16; - CARD16 pad B16; - CARD32 x B32; - CARD32 y B32; +typedef struct _XF86DGASetViewPort +{ + CARD8 reqType; /* always DGAReqCode */ + CARD8 dgaReqType; /* always X_XF86DGASetViewPort */ + CARD16 length B16; + CARD16 screen B16; + CARD16 pad B16; + CARD32 x B32; + CARD32 y B32; } xXF86DGASetViewPortReq; #define sz_xXF86DGASetViewPortReq 16 -typedef struct _XF86DGAGetVidPage { - CARD8 reqType; /* always DGAReqCode */ - CARD8 dgaReqType; /* always X_XF86DGAGetVidPage */ - CARD16 length B16; - CARD16 screen B16; - CARD16 pad B16; +typedef struct _XF86DGAGetVidPage +{ + CARD8 reqType; /* always DGAReqCode */ + CARD8 dgaReqType; /* always X_XF86DGAGetVidPage */ + CARD16 length B16; + CARD16 screen B16; + CARD16 pad B16; } xXF86DGAGetVidPageReq; #define sz_xXF86DGAGetVidPageReq 8 -typedef struct { - BYTE type; - BOOL pad1; - CARD16 sequenceNumber B16; - CARD32 length B32; - CARD32 vpage B32; - CARD32 pad B32; - CARD32 pad2 B32; - CARD32 pad3 B32; - CARD32 pad4 B32; - CARD32 pad5 B32; +typedef struct +{ + BYTE type; + BOOL pad1; + CARD16 sequenceNumber B16; + CARD32 length B32; + CARD32 vpage B32; + CARD32 pad B32; + CARD32 pad2 B32; + CARD32 pad3 B32; + CARD32 pad4 B32; + CARD32 pad5 B32; } xXF86DGAGetVidPageReply; #define sz_xXF86DGAGetVidPageReply 32 -typedef struct _XF86DGASetVidPage { - CARD8 reqType; /* always DGAReqCode */ - CARD8 dgaReqType; /* always X_XF86DGASetVidPage */ - CARD16 length B16; - CARD16 screen B16; - CARD16 vpage B16; +typedef struct _XF86DGASetVidPage +{ + CARD8 reqType; /* always DGAReqCode */ + CARD8 dgaReqType; /* always X_XF86DGASetVidPage */ + CARD16 length B16; + CARD16 screen B16; + CARD16 vpage B16; } xXF86DGASetVidPageReq; #define sz_xXF86DGASetVidPageReq 8 -typedef struct _XF86DGAQueryDirectVideo { - CARD8 reqType; /* always DGAReqCode */ - CARD8 dgaReqType; /* always X_DGAQueryVersion */ - CARD16 length B16; - CARD16 screen B16; - CARD16 pad B16; +typedef struct _XF86DGAQueryDirectVideo +{ + CARD8 reqType; /* always DGAReqCode */ + CARD8 dgaReqType; /* always X_DGAQueryVersion */ + CARD16 length B16; + CARD16 screen B16; + CARD16 pad B16; } xXF86DGAQueryDirectVideoReq; #define sz_xXF86DGAQueryDirectVideoReq 8 -typedef struct { - BYTE type; - BOOL pad1; - CARD16 sequenceNumber B16; - CARD32 length B32; - CARD32 flags B32; - CARD32 pad B32; - CARD32 pad2 B32; - CARD32 pad3 B32; - CARD32 pad4 B32; - CARD32 pad5 B32; +typedef struct +{ + BYTE type; + BOOL pad1; + CARD16 sequenceNumber B16; + CARD32 length B32; + CARD32 flags B32; + CARD32 pad B32; + CARD32 pad2 B32; + CARD32 pad3 B32; + CARD32 pad4 B32; + CARD32 pad5 B32; } xXF86DGAQueryDirectVideoReply; #define sz_xXF86DGAQueryDirectVideoReply 32 -typedef struct _XF86DGAViewPortChanged { - CARD8 reqType; /* always DGAReqCode */ - CARD8 dgaReqType; /* always X_DGAQueryVersion */ - CARD16 length B16; - CARD16 screen B16; - CARD16 n B16; +typedef struct _XF86DGAViewPortChanged +{ + CARD8 reqType; /* always DGAReqCode */ + CARD8 dgaReqType; /* always X_DGAQueryVersion */ + CARD16 length B16; + CARD16 screen B16; + CARD16 n B16; } xXF86DGAViewPortChangedReq; #define sz_xXF86DGAViewPortChangedReq 8 -typedef struct { - BYTE type; - BOOL pad1; - CARD16 sequenceNumber B16; - CARD32 length B32; - CARD32 result B32; - CARD32 pad B32; - CARD32 pad2 B32; - CARD32 pad3 B32; - CARD32 pad4 B32; - CARD32 pad5 B32; +typedef struct +{ + BYTE type; + BOOL pad1; + CARD16 sequenceNumber B16; + CARD32 length B32; + CARD32 result B32; + CARD32 pad B32; + CARD32 pad2 B32; + CARD32 pad3 B32; + CARD32 pad4 B32; + CARD32 pad5 B32; } xXF86DGAViewPortChangedReply; #define sz_xXF86DGAViewPortChangedReply 32 #endif /* _XF86DGASTR1_H_ */ - +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/Xext/extensions/xf86dgastr.h b/src/video/Xext/extensions/xf86dgastr.h index b249feb3c..9546b4f8d 100644 --- a/src/video/Xext/extensions/xf86dgastr.h +++ b/src/video/Xext/extensions/xf86dgastr.h @@ -13,332 +13,360 @@ Copyright (c) 1995 XFree86 Inc. #define XF86DGANAME "XFree86-DGA" -#define XDGA_MAJOR_VERSION 2 /* current version numbers */ +#define XDGA_MAJOR_VERSION 2 /* current version numbers */ #define XDGA_MINOR_VERSION 0 -typedef struct _XDGAQueryVersion { - CARD8 reqType; /* always DGAReqCode */ - CARD8 dgaReqType; /* always X_DGAQueryVersion */ - CARD16 length B16; +typedef struct _XDGAQueryVersion +{ + CARD8 reqType; /* always DGAReqCode */ + CARD8 dgaReqType; /* always X_DGAQueryVersion */ + CARD16 length B16; } xXDGAQueryVersionReq; #define sz_xXDGAQueryVersionReq 4 -typedef struct { - BYTE type; /* X_Reply */ - BOOL pad1; - CARD16 sequenceNumber B16; - CARD32 length B32; - CARD16 majorVersion B16; /* major version of DGA protocol */ - CARD16 minorVersion B16; /* minor version of DGA protocol */ - CARD32 pad2 B32; - CARD32 pad3 B32; - CARD32 pad4 B32; - CARD32 pad5 B32; - CARD32 pad6 B32; +typedef struct +{ + BYTE type; /* X_Reply */ + BOOL pad1; + CARD16 sequenceNumber B16; + CARD32 length B32; + CARD16 majorVersion B16; /* major version of DGA protocol */ + CARD16 minorVersion B16; /* minor version of DGA protocol */ + CARD32 pad2 B32; + CARD32 pad3 B32; + CARD32 pad4 B32; + CARD32 pad5 B32; + CARD32 pad6 B32; } xXDGAQueryVersionReply; #define sz_xXDGAQueryVersionReply 32 -typedef struct _XDGAQueryModes { - CARD8 reqType; - CARD8 dgaReqType; - CARD16 length B16; - CARD32 screen B32; +typedef struct _XDGAQueryModes +{ + CARD8 reqType; + CARD8 dgaReqType; + CARD16 length B16; + CARD32 screen B32; } xXDGAQueryModesReq; #define sz_xXDGAQueryModesReq 8 -typedef struct { - BYTE type; /* X_Reply */ - BOOL pad1; - CARD16 sequenceNumber B16; - CARD32 length B32; - CARD32 number B32; /* number of modes available */ - CARD32 pad2 B32; - CARD32 pad3 B32; - CARD32 pad4 B32; - CARD32 pad5 B32; - CARD32 pad6 B32; +typedef struct +{ + BYTE type; /* X_Reply */ + BOOL pad1; + CARD16 sequenceNumber B16; + CARD32 length B32; + CARD32 number B32; /* number of modes available */ + CARD32 pad2 B32; + CARD32 pad3 B32; + CARD32 pad4 B32; + CARD32 pad5 B32; + CARD32 pad6 B32; } xXDGAQueryModesReply; #define sz_xXDGAQueryModesReply 32 -typedef struct _XDGASetMode { - CARD8 reqType; - CARD8 dgaReqType; - CARD16 length B16; - CARD32 screen B32; - CARD32 mode B32; /* mode number to init */ - CARD32 pid B32; /* Pixmap descriptor */ +typedef struct _XDGASetMode +{ + CARD8 reqType; + CARD8 dgaReqType; + CARD16 length B16; + CARD32 screen B32; + CARD32 mode B32; /* mode number to init */ + CARD32 pid B32; /* Pixmap descriptor */ } xXDGASetModeReq; #define sz_xXDGASetModeReq 16 -typedef struct { - BYTE type; /* X_Reply */ - BOOL pad1; - CARD16 sequenceNumber B16; - CARD32 length B32; - CARD32 offset B32; /* offset into framebuffer map */ - CARD32 flags B32; - CARD32 pad2 B32; - CARD32 pad3 B32; - CARD32 pad4 B32; - CARD32 pad5 B32; +typedef struct +{ + BYTE type; /* X_Reply */ + BOOL pad1; + CARD16 sequenceNumber B16; + CARD32 length B32; + CARD32 offset B32; /* offset into framebuffer map */ + CARD32 flags B32; + CARD32 pad2 B32; + CARD32 pad3 B32; + CARD32 pad4 B32; + CARD32 pad5 B32; } xXDGASetModeReply; #define sz_xXDGASetModeReply 32 -typedef struct { - CARD8 byte_order; - CARD8 depth; - CARD16 num B16; - CARD16 bpp B16; - CARD16 name_size B16; - CARD32 vsync_num B32; - CARD32 vsync_den B32; - CARD32 flags B32; - CARD16 image_width B16; - CARD16 image_height B16; - CARD16 pixmap_width B16; - CARD16 pixmap_height B16; - CARD32 bytes_per_scanline B32; - CARD32 red_mask B32; - CARD32 green_mask B32; - CARD32 blue_mask B32; - CARD16 visual_class B16; - CARD16 pad1 B16; - CARD16 viewport_width B16; - CARD16 viewport_height B16; - CARD16 viewport_xstep B16; - CARD16 viewport_ystep B16; - CARD16 viewport_xmax B16; - CARD16 viewport_ymax B16; - CARD32 viewport_flags B32; - CARD32 reserved1 B32; - CARD32 reserved2 B32; +typedef struct +{ + CARD8 byte_order; + CARD8 depth; + CARD16 num B16; + CARD16 bpp B16; + CARD16 name_size B16; + CARD32 vsync_num B32; + CARD32 vsync_den B32; + CARD32 flags B32; + CARD16 image_width B16; + CARD16 image_height B16; + CARD16 pixmap_width B16; + CARD16 pixmap_height B16; + CARD32 bytes_per_scanline B32; + CARD32 red_mask B32; + CARD32 green_mask B32; + CARD32 blue_mask B32; + CARD16 visual_class B16; + CARD16 pad1 B16; + CARD16 viewport_width B16; + CARD16 viewport_height B16; + CARD16 viewport_xstep B16; + CARD16 viewport_ystep B16; + CARD16 viewport_xmax B16; + CARD16 viewport_ymax B16; + CARD32 viewport_flags B32; + CARD32 reserved1 B32; + CARD32 reserved2 B32; } xXDGAModeInfo; #define sz_xXDGAModeInfo 72 -typedef struct _XDGAOpenFramebuffer { - CARD8 reqType; - CARD8 dgaReqType; - CARD16 length B16; - CARD32 screen B32; +typedef struct _XDGAOpenFramebuffer +{ + CARD8 reqType; + CARD8 dgaReqType; + CARD16 length B16; + CARD32 screen B32; } xXDGAOpenFramebufferReq; #define sz_xXDGAOpenFramebufferReq 8 -typedef struct { - BYTE type; /* X_Reply */ - BOOL pad1; - CARD16 sequenceNumber B16; - CARD32 length B32; /* device name size if there is one */ - CARD32 mem1 B32; /* physical memory */ - CARD32 mem2 B32; /* spillover for _alpha_ */ - CARD32 size B32; /* size of map in bytes */ - CARD32 offset B32; /* optional offset into device */ - CARD32 extra B32; /* extra info associated with the map */ - CARD32 pad2 B32; +typedef struct +{ + BYTE type; /* X_Reply */ + BOOL pad1; + CARD16 sequenceNumber B16; + CARD32 length B32; /* device name size if there is one */ + CARD32 mem1 B32; /* physical memory */ + CARD32 mem2 B32; /* spillover for _alpha_ */ + CARD32 size B32; /* size of map in bytes */ + CARD32 offset B32; /* optional offset into device */ + CARD32 extra B32; /* extra info associated with the map */ + CARD32 pad2 B32; } xXDGAOpenFramebufferReply; #define sz_xXDGAOpenFramebufferReply 32 -typedef struct _XDGACloseFramebuffer { - CARD8 reqType; - CARD8 dgaReqType; - CARD16 length B16; - CARD32 screen B32; +typedef struct _XDGACloseFramebuffer +{ + CARD8 reqType; + CARD8 dgaReqType; + CARD16 length B16; + CARD32 screen B32; } xXDGACloseFramebufferReq; #define sz_xXDGACloseFramebufferReq 8 -typedef struct _XDGASetViewport { - CARD8 reqType; - CARD8 dgaReqType; - CARD16 length B16; - CARD32 screen B32; - CARD16 x B16; - CARD16 y B16; - CARD32 flags B32; +typedef struct _XDGASetViewport +{ + CARD8 reqType; + CARD8 dgaReqType; + CARD16 length B16; + CARD32 screen B32; + CARD16 x B16; + CARD16 y B16; + CARD32 flags B32; } xXDGASetViewportReq; #define sz_xXDGASetViewportReq 16 -typedef struct _XDGAInstallColormap { - CARD8 reqType; - CARD8 dgaReqType; - CARD16 length B16; - CARD32 screen B32; - CARD32 cmap B32; +typedef struct _XDGAInstallColormap +{ + CARD8 reqType; + CARD8 dgaReqType; + CARD16 length B16; + CARD32 screen B32; + CARD32 cmap B32; } xXDGAInstallColormapReq; #define sz_xXDGAInstallColormapReq 12 -typedef struct _XDGASelectInput { - CARD8 reqType; - CARD8 dgaReqType; - CARD16 length B16; - CARD32 screen B32; - CARD32 mask B32; +typedef struct _XDGASelectInput +{ + CARD8 reqType; + CARD8 dgaReqType; + CARD16 length B16; + CARD32 screen B32; + CARD32 mask B32; } xXDGASelectInputReq; #define sz_xXDGASelectInputReq 12 -typedef struct _XDGAFillRectangle { - CARD8 reqType; - CARD8 dgaReqType; - CARD16 length B16; - CARD32 screen B32; - CARD16 x B16; - CARD16 y B16; - CARD16 width B16; - CARD16 height B16; - CARD32 color B32; +typedef struct _XDGAFillRectangle +{ + CARD8 reqType; + CARD8 dgaReqType; + CARD16 length B16; + CARD32 screen B32; + CARD16 x B16; + CARD16 y B16; + CARD16 width B16; + CARD16 height B16; + CARD32 color B32; } xXDGAFillRectangleReq; #define sz_xXDGAFillRectangleReq 20 -typedef struct _XDGACopyArea { - CARD8 reqType; - CARD8 dgaReqType; - CARD16 length B16; - CARD32 screen B32; - CARD16 srcx B16; - CARD16 srcy B16; - CARD16 width B16; - CARD16 height B16; - CARD16 dstx B16; - CARD16 dsty B16; +typedef struct _XDGACopyArea +{ + CARD8 reqType; + CARD8 dgaReqType; + CARD16 length B16; + CARD32 screen B32; + CARD16 srcx B16; + CARD16 srcy B16; + CARD16 width B16; + CARD16 height B16; + CARD16 dstx B16; + CARD16 dsty B16; } xXDGACopyAreaReq; #define sz_xXDGACopyAreaReq 20 -typedef struct _XDGACopyTransparentArea { - CARD8 reqType; - CARD8 dgaReqType; - CARD16 length B16; - CARD32 screen B32; - CARD16 srcx B16; - CARD16 srcy B16; - CARD16 width B16; - CARD16 height B16; - CARD16 dstx B16; - CARD16 dsty B16; - CARD32 key B32; +typedef struct _XDGACopyTransparentArea +{ + CARD8 reqType; + CARD8 dgaReqType; + CARD16 length B16; + CARD32 screen B32; + CARD16 srcx B16; + CARD16 srcy B16; + CARD16 width B16; + CARD16 height B16; + CARD16 dstx B16; + CARD16 dsty B16; + CARD32 key B32; } xXDGACopyTransparentAreaReq; #define sz_xXDGACopyTransparentAreaReq 24 -typedef struct _XDGAGetViewportStatus { - CARD8 reqType; - CARD8 dgaReqType; - CARD16 length B16; - CARD32 screen B32; +typedef struct _XDGAGetViewportStatus +{ + CARD8 reqType; + CARD8 dgaReqType; + CARD16 length B16; + CARD32 screen B32; } xXDGAGetViewportStatusReq; #define sz_xXDGAGetViewportStatusReq 8 -typedef struct { - BYTE type; - BOOL pad1; - CARD16 sequenceNumber B16; - CARD32 length B32; - CARD32 status B32; - CARD32 pad2 B32; - CARD32 pad3 B32; - CARD32 pad4 B32; - CARD32 pad5 B32; - CARD32 pad6 B32; +typedef struct +{ + BYTE type; + BOOL pad1; + CARD16 sequenceNumber B16; + CARD32 length B32; + CARD32 status B32; + CARD32 pad2 B32; + CARD32 pad3 B32; + CARD32 pad4 B32; + CARD32 pad5 B32; + CARD32 pad6 B32; } xXDGAGetViewportStatusReply; #define sz_xXDGAGetViewportStatusReply 32 -typedef struct _XDGASync { - CARD8 reqType; - CARD8 dgaReqType; - CARD16 length B16; - CARD32 screen B32; +typedef struct _XDGASync +{ + CARD8 reqType; + CARD8 dgaReqType; + CARD16 length B16; + CARD32 screen B32; } xXDGASyncReq; #define sz_xXDGASyncReq 8 -typedef struct { - BYTE type; - BOOL pad1; - CARD16 sequenceNumber B16; - CARD32 length B32; - CARD32 pad2 B32; - CARD32 pad3 B32; - CARD32 pad4 B32; - CARD32 pad5 B32; - CARD32 pad6 B32; - CARD32 pad7 B32; +typedef struct +{ + BYTE type; + BOOL pad1; + CARD16 sequenceNumber B16; + CARD32 length B32; + CARD32 pad2 B32; + CARD32 pad3 B32; + CARD32 pad4 B32; + CARD32 pad5 B32; + CARD32 pad6 B32; + CARD32 pad7 B32; } xXDGASyncReply; #define sz_xXDGASyncReply 32 -typedef struct _XDGASetClientVersion { - CARD8 reqType; - CARD8 dgaReqType; - CARD16 length B16; - CARD16 major B16; - CARD16 minor B16; +typedef struct _XDGASetClientVersion +{ + CARD8 reqType; + CARD8 dgaReqType; + CARD16 length B16; + CARD16 major B16; + CARD16 minor B16; } xXDGASetClientVersionReq; #define sz_xXDGASetClientVersionReq 8 -typedef struct { - CARD8 reqType; - CARD8 dgaReqType; - CARD16 length B16; - CARD32 screen B32; - CARD16 x B16; - CARD16 y B16; - CARD32 flags B32; +typedef struct +{ + CARD8 reqType; + CARD8 dgaReqType; + CARD16 length B16; + CARD32 screen B32; + CARD16 x B16; + CARD16 y B16; + CARD32 flags B32; } xXDGAChangePixmapModeReq; #define sz_xXDGAChangePixmapModeReq 16 -typedef struct { - BYTE type; - BOOL pad1; - CARD16 sequenceNumber B16; - CARD32 length B32; - CARD16 x B16; - CARD16 y B16; - CARD32 pad3 B32; - CARD32 pad4 B32; - CARD32 pad5 B32; - CARD32 pad6 B32; - CARD32 pad7 B32; +typedef struct +{ + BYTE type; + BOOL pad1; + CARD16 sequenceNumber B16; + CARD32 length B32; + CARD16 x B16; + CARD16 y B16; + CARD32 pad3 B32; + CARD32 pad4 B32; + CARD32 pad5 B32; + CARD32 pad6 B32; + CARD32 pad7 B32; } xXDGAChangePixmapModeReply; #define sz_xXDGAChangePixmapModeReply 32 -typedef struct _XDGACreateColormap { - CARD8 reqType; - CARD8 dgaReqType; - CARD16 length B16; - CARD32 screen B32; - CARD32 id B32; - CARD32 mode B32; - CARD8 alloc; - CARD8 pad1; - CARD16 pad2; +typedef struct _XDGACreateColormap +{ + CARD8 reqType; + CARD8 dgaReqType; + CARD16 length B16; + CARD32 screen B32; + CARD32 id B32; + CARD32 mode B32; + CARD8 alloc; + CARD8 pad1; + CARD16 pad2; } xXDGACreateColormapReq; #define sz_xXDGACreateColormapReq 20 -typedef struct { - union { - struct { - BYTE type; - BYTE detail; - CARD16 sequenceNumber B16; +typedef struct +{ + union + { + struct + { + BYTE type; + BYTE detail; + CARD16 sequenceNumber B16; + } u; + struct + { + CARD32 pad0 B32; + CARD32 time B32; + INT16 dx B16; + INT16 dy B16; + INT16 screen B16; + CARD16 state B16; + CARD32 pad1 B32; + CARD32 pad2 B32; + CARD32 pad3 B32; + CARD32 pad4 B32; + } event; } u; - struct { - CARD32 pad0 B32; - CARD32 time B32; - INT16 dx B16; - INT16 dy B16; - INT16 screen B16; - CARD16 state B16; - CARD32 pad1 B32; - CARD32 pad2 B32; - CARD32 pad3 B32; - CARD32 pad4 B32; - } event; - } u; } dgaEvent; #endif /* _XF86DGASTR_H_ */ - +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/Xext/extensions/xf86vmode.h b/src/video/Xext/extensions/xf86vmode.h index eb56c0e8d..bedb47a9d 100644 --- a/src/video/Xext/extensions/xf86vmode.h +++ b/src/video/Xext/extensions/xf86vmode.h @@ -86,78 +86,84 @@ from Kaleb S. KEITHLEY #ifndef _XF86VIDMODE_SERVER_ -typedef struct { - unsigned short hdisplay; - unsigned short hsyncstart; - unsigned short hsyncend; - unsigned short htotal; - unsigned short hskew; - unsigned short vdisplay; - unsigned short vsyncstart; - unsigned short vsyncend; - unsigned short vtotal; - unsigned int flags; - int privsize; +typedef struct +{ + unsigned short hdisplay; + unsigned short hsyncstart; + unsigned short hsyncend; + unsigned short htotal; + unsigned short hskew; + unsigned short vdisplay; + unsigned short vsyncstart; + unsigned short vsyncend; + unsigned short vtotal; + unsigned int flags; + int privsize; #if defined(__cplusplus) || defined(c_plusplus) /* private is a C++ reserved word */ - INT32 *c_private; + INT32 *c_private; #else - INT32 *private; + INT32 *private; #endif } SDL_NAME(XF86VidModeModeLine); -typedef struct { - unsigned int dotclock; - unsigned short hdisplay; - unsigned short hsyncstart; - unsigned short hsyncend; - unsigned short htotal; - unsigned short hskew; - unsigned short vdisplay; - unsigned short vsyncstart; - unsigned short vsyncend; - unsigned short vtotal; - unsigned int flags; - int privsize; +typedef struct +{ + unsigned int dotclock; + unsigned short hdisplay; + unsigned short hsyncstart; + unsigned short hsyncend; + unsigned short htotal; + unsigned short hskew; + unsigned short vdisplay; + unsigned short vsyncstart; + unsigned short vsyncend; + unsigned short vtotal; + unsigned int flags; + int privsize; #if defined(__cplusplus) || defined(c_plusplus) /* private is a C++ reserved word */ - INT32 *c_private; + INT32 *c_private; #else - INT32 *private; + INT32 *private; #endif } SDL_NAME(XF86VidModeModeInfo); -typedef struct { - float hi; - float lo; +typedef struct +{ + float hi; + float lo; } SDL_NAME(XF86VidModeSyncRange); -typedef struct { - char* vendor; - char* model; - float EMPTY; - unsigned char nhsync; - SDL_NAME(XF86VidModeSyncRange)* hsync; - unsigned char nvsync; - SDL_NAME(XF86VidModeSyncRange)* vsync; +typedef struct +{ + char *vendor; + char *model; + float EMPTY; + unsigned char nhsync; + SDL_NAME(XF86VidModeSyncRange) * hsync; + unsigned char nvsync; + SDL_NAME(XF86VidModeSyncRange) * vsync; } SDL_NAME(XF86VidModeMonitor); - -typedef struct { - int type; /* of event */ - unsigned long serial; /* # of last request processed by server */ - Bool send_event; /* true if this came from a SendEvent req */ - Display *display; /* Display the event was read from */ - Window root; /* root window of event screen */ - int state; /* What happened */ - int kind; /* What happened */ - Bool forced; /* extents of new region */ - Time time; /* event timestamp */ + +typedef struct +{ + int type; /* of event */ + unsigned long serial; /* # of last request processed by server */ + Bool send_event; /* true if this came from a SendEvent req */ + Display *display; /* Display the event was read from */ + Window root; /* root window of event screen */ + int state; /* What happened */ + int kind; /* What happened */ + Bool forced; /* extents of new region */ + Time time; /* event timestamp */ } SDL_NAME(XF86VidModeNotifyEvent); -typedef struct { - float red; /* Red Gamma value */ - float green; /* Green Gamma value */ - float blue; /* Blue Gamma value */ +typedef struct +{ + float red; /* Red Gamma value */ + float green; /* Green Gamma value */ + float blue; /* Blue Gamma value */ } SDL_NAME(XF86VidModeGamma); @@ -166,149 +172,127 @@ typedef struct { #define SDL_XF86VidModeSelectPrevMode(disp, scr) \ SDL_NAME(XF86VidModeSwitchMode)(disp, scr, -1) -_XFUNCPROTOBEGIN - -Bool SDL_NAME(XF86VidModeQueryVersion)( - Display* /* dpy */, - int* /* majorVersion */, - int* /* minorVersion */ -); - -Bool SDL_NAME(XF86VidModeQueryExtension)( - Display* /* dpy */, - int* /* event_base */, - int* /* error_base */ -); - -Bool SDL_NAME(XF86VidModeSetClientVersion)( - Display* /* dpy */ -); - -Bool SDL_NAME(XF86VidModeGetModeLine)( - Display* /* dpy */, - int /* screen */, - int* /* dotclock */, - SDL_NAME(XF86VidModeModeLine)* /* modeline */ -); - -Bool SDL_NAME(XF86VidModeGetAllModeLines)( - Display* /* dpy */, - int /* screen */, - int* /* modecount */, - SDL_NAME(XF86VidModeModeInfo)*** /* modelinesPtr */ -); - -Bool SDL_NAME(XF86VidModeAddModeLine)( - Display* /* dpy */, - int /* screen */, - SDL_NAME(XF86VidModeModeInfo)* /* new modeline */, - SDL_NAME(XF86VidModeModeInfo)* /* after modeline */ -); - -Bool SDL_NAME(XF86VidModeDeleteModeLine)( - Display* /* dpy */, - int /* screen */, - SDL_NAME(XF86VidModeModeInfo)* /* modeline */ -); - -Bool SDL_NAME(XF86VidModeModModeLine)( - Display* /* dpy */, - int /* screen */, - SDL_NAME(XF86VidModeModeLine)* /* modeline */ -); - -Status SDL_NAME(XF86VidModeValidateModeLine)( - Display* /* dpy */, - int /* screen */, - SDL_NAME(XF86VidModeModeInfo)* /* modeline */ -); - -Bool SDL_NAME(XF86VidModeSwitchMode)( - Display* /* dpy */, - int /* screen */, - int /* zoom */ -); - -Bool SDL_NAME(XF86VidModeSwitchToMode)( - Display* /* dpy */, - int /* screen */, - SDL_NAME(XF86VidModeModeInfo)* /* modeline */ -); - -Bool SDL_NAME(XF86VidModeLockModeSwitch)( - Display* /* dpy */, - int /* screen */, - int /* lock */ -); - -Bool SDL_NAME(XF86VidModeGetMonitor)( - Display* /* dpy */, - int /* screen */, - SDL_NAME(XF86VidModeMonitor)* /* monitor */ -); - -Bool SDL_NAME(XF86VidModeGetViewPort)( - Display* /* dpy */, - int /* screen */, - int* /* x return */, - int* /* y return */ -); - -Bool SDL_NAME(XF86VidModeSetViewPort)( - Display* /* dpy */, - int /* screen */, - int /* x */, - int /* y */ -); - -Bool SDL_NAME(XF86VidModeGetDotClocks)( - Display* /* dpy */, - int /* screen */, - int* /* flags return */, - int* /* number of clocks return */, - int* /* max dot clock return */, - int** /* clocks return */ -); - -Bool SDL_NAME(XF86VidModeGetGamma)( - Display* /* dpy */, - int /* screen */, - SDL_NAME(XF86VidModeGamma)* /* Gamma */ -); - -Bool SDL_NAME(XF86VidModeSetGamma)( - Display* /* dpy */, - int /* screen */, - SDL_NAME(XF86VidModeGamma)* /* Gamma */ -); - -Bool SDL_NAME(XF86VidModeSetGammaRamp)( - Display* /* dpy */, - int /* screen */, - int /* size */, - unsigned short* /* red array */, - unsigned short* /* green array */, - unsigned short* /* blue array */ -); - -Bool SDL_NAME(XF86VidModeGetGammaRamp)( - Display* /* dpy */, - int /* screen */, - int /* size */, - unsigned short* /* red array */, - unsigned short* /* green array */, - unsigned short* /* blue array */ -); - -Bool SDL_NAME(XF86VidModeGetGammaRampSize)( - Display* /* dpy */, - int /* screen */, - int* /* size */ -); +_XFUNCPROTOBEGIN Bool SDL_NAME(XF86VidModeQueryVersion) (Display * /* dpy */ , + int * + /* majorVersion */ , + int * /* minorVersion */ + ); + +Bool SDL_NAME(XF86VidModeQueryExtension) (Display * /* dpy */ , + int * /* event_base */ , + int * /* error_base */ + ); + +Bool SDL_NAME(XF86VidModeSetClientVersion) (Display * /* dpy */ + ); + +Bool SDL_NAME(XF86VidModeGetModeLine) (Display * /* dpy */ , + int /* screen */ , + int * /* dotclock */ , + SDL_NAME(XF86VidModeModeLine) * /* modeline */ + ); + +Bool SDL_NAME(XF86VidModeGetAllModeLines) (Display * /* dpy */ , + int /* screen */ , + int * /* modecount */ , + SDL_NAME(XF86VidModeModeInfo) *** /* modelinesPtr */ + ); + +Bool SDL_NAME(XF86VidModeAddModeLine) (Display * /* dpy */ , + int /* screen */ , + SDL_NAME(XF86VidModeModeInfo) * + /* new modeline */ , + SDL_NAME(XF86VidModeModeInfo) * /* after modeline */ + ); + +Bool SDL_NAME(XF86VidModeDeleteModeLine) (Display * /* dpy */ , + int /* screen */ , + SDL_NAME(XF86VidModeModeInfo) * /* modeline */ + ); + +Bool SDL_NAME(XF86VidModeModModeLine) (Display * /* dpy */ , + int /* screen */ , + SDL_NAME(XF86VidModeModeLine) * /* modeline */ + ); + +Status SDL_NAME(XF86VidModeValidateModeLine) (Display * /* dpy */ , + int /* screen */ , + SDL_NAME(XF86VidModeModeInfo) * /* modeline */ + ); + +Bool SDL_NAME(XF86VidModeSwitchMode) (Display * /* dpy */ , + int /* screen */ , + int /* zoom */ + ); + +Bool SDL_NAME(XF86VidModeSwitchToMode) (Display * /* dpy */ , + int /* screen */ , + SDL_NAME(XF86VidModeModeInfo) * /* modeline */ + ); + +Bool SDL_NAME(XF86VidModeLockModeSwitch) (Display * /* dpy */ , + int /* screen */ , + int /* lock */ + ); + +Bool SDL_NAME(XF86VidModeGetMonitor) (Display * /* dpy */ , + int /* screen */ , + SDL_NAME(XF86VidModeMonitor) * /* monitor */ + ); + +Bool SDL_NAME(XF86VidModeGetViewPort) (Display * /* dpy */ , + int /* screen */ , + int * /* x return */ , + int * /* y return */ + ); + +Bool SDL_NAME(XF86VidModeSetViewPort) (Display * /* dpy */ , + int /* screen */ , + int /* x */ , + int /* y */ + ); + +Bool SDL_NAME(XF86VidModeGetDotClocks) (Display * /* dpy */ , + int /* screen */ , + int * /* flags return */ , + int * /* number of clocks return */ , + int * /* max dot clock return */ , + int ** /* clocks return */ + ); + +Bool SDL_NAME(XF86VidModeGetGamma) (Display * /* dpy */ , + int /* screen */ , + SDL_NAME(XF86VidModeGamma) * /* Gamma */ + ); + +Bool SDL_NAME(XF86VidModeSetGamma) (Display * /* dpy */ , + int /* screen */ , + SDL_NAME(XF86VidModeGamma) * /* Gamma */ + ); + +Bool SDL_NAME(XF86VidModeSetGammaRamp) (Display * /* dpy */ , + int /* screen */ , + int /* size */ , + unsigned short * /* red array */ , + unsigned short * /* green array */ , + unsigned short * /* blue array */ + ); + +Bool SDL_NAME(XF86VidModeGetGammaRamp) (Display * /* dpy */ , + int /* screen */ , + int /* size */ , + unsigned short * /* red array */ , + unsigned short * /* green array */ , + unsigned short * /* blue array */ + ); + +Bool SDL_NAME(XF86VidModeGetGammaRampSize) (Display * /* dpy */ , + int /* screen */ , + int * /* size */ + ); _XFUNCPROTOEND - #endif - #endif +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/Xext/extensions/xf86vmstr.h b/src/video/Xext/extensions/xf86vmstr.h index 0c3078d5a..b1f476d51 100644 --- a/src/video/Xext/extensions/xf86vmstr.h +++ b/src/video/Xext/extensions/xf86vmstr.h @@ -39,7 +39,7 @@ from Kaleb S. KEITHLEY #define XF86VIDMODENAME "XFree86-VidModeExtension" -#define XF86VIDMODE_MAJOR_VERSION 2 /* current version numbers */ +#define XF86VIDMODE_MAJOR_VERSION 2 /* current version numbers */ #define XF86VIDMODE_MINOR_VERSION 1 /* * major version 0 == uses parameter-to-wire functions in XFree86 libXxf86vm. @@ -48,499 +48,526 @@ from Kaleb S. KEITHLEY * major version 2 == uses new protocol version in XFree86 4.0. */ -typedef struct _XF86VidModeQueryVersion { - CARD8 reqType; /* always XF86VidModeReqCode */ - CARD8 xf86vidmodeReqType; /* always X_XF86VidModeQueryVersion */ - CARD16 length B16; +typedef struct _XF86VidModeQueryVersion +{ + CARD8 reqType; /* always XF86VidModeReqCode */ + CARD8 xf86vidmodeReqType; /* always X_XF86VidModeQueryVersion */ + CARD16 length B16; } xXF86VidModeQueryVersionReq; #define sz_xXF86VidModeQueryVersionReq 4 -typedef struct { - BYTE type; /* X_Reply */ - BOOL pad1; - CARD16 sequenceNumber B16; - CARD32 length B32; - CARD16 majorVersion B16; /* major version of XF86VidMode */ - CARD16 minorVersion B16; /* minor version of XF86VidMode */ - CARD32 pad2 B32; - CARD32 pad3 B32; - CARD32 pad4 B32; - CARD32 pad5 B32; - CARD32 pad6 B32; +typedef struct +{ + BYTE type; /* X_Reply */ + BOOL pad1; + CARD16 sequenceNumber B16; + CARD32 length B32; + CARD16 majorVersion B16; /* major version of XF86VidMode */ + CARD16 minorVersion B16; /* minor version of XF86VidMode */ + CARD32 pad2 B32; + CARD32 pad3 B32; + CARD32 pad4 B32; + CARD32 pad5 B32; + CARD32 pad6 B32; } xXF86VidModeQueryVersionReply; #define sz_xXF86VidModeQueryVersionReply 32 -typedef struct _XF86VidModeGetModeLine { - CARD8 reqType; /* always XF86VidModeReqCode */ - CARD8 xf86vidmodeReqType; - CARD16 length B16; - CARD16 screen B16; - CARD16 pad B16; +typedef struct _XF86VidModeGetModeLine +{ + CARD8 reqType; /* always XF86VidModeReqCode */ + CARD8 xf86vidmodeReqType; + CARD16 length B16; + CARD16 screen B16; + CARD16 pad B16; } xXF86VidModeGetModeLineReq, - xXF86VidModeGetAllModeLinesReq, - xXF86VidModeGetMonitorReq, - xXF86VidModeGetViewPortReq, - xXF86VidModeGetDotClocksReq; + xXF86VidModeGetAllModeLinesReq, + xXF86VidModeGetMonitorReq, + xXF86VidModeGetViewPortReq, xXF86VidModeGetDotClocksReq; #define sz_xXF86VidModeGetModeLineReq 8 #define sz_xXF86VidModeGetAllModeLinesReq 8 #define sz_xXF86VidModeGetMonitorReq 8 #define sz_xXF86VidModeGetViewPortReq 8 #define sz_xXF86VidModeGetDotClocksReq 8 -typedef struct { - BYTE type; /* X_Reply */ - BOOL pad1; - CARD16 sequenceNumber B16; - CARD32 length B32; - CARD32 dotclock B32; - CARD16 hdisplay B16; - CARD16 hsyncstart B16; - CARD16 hsyncend B16; - CARD16 htotal B16; - CARD16 hskew B16; - CARD16 vdisplay B16; - CARD16 vsyncstart B16; - CARD16 vsyncend B16; - CARD16 vtotal B16; - CARD16 pad2 B16; - CARD32 flags B32; - CARD32 reserved1 B32; - CARD32 reserved2 B32; - CARD32 reserved3 B32; - CARD32 privsize B32; +typedef struct +{ + BYTE type; /* X_Reply */ + BOOL pad1; + CARD16 sequenceNumber B16; + CARD32 length B32; + CARD32 dotclock B32; + CARD16 hdisplay B16; + CARD16 hsyncstart B16; + CARD16 hsyncend B16; + CARD16 htotal B16; + CARD16 hskew B16; + CARD16 vdisplay B16; + CARD16 vsyncstart B16; + CARD16 vsyncend B16; + CARD16 vtotal B16; + CARD16 pad2 B16; + CARD32 flags B32; + CARD32 reserved1 B32; + CARD32 reserved2 B32; + CARD32 reserved3 B32; + CARD32 privsize B32; } xXF86VidModeGetModeLineReply; #define sz_xXF86VidModeGetModeLineReply 52 /* 0.x version */ -typedef struct { - BYTE type; /* X_Reply */ - BOOL pad1; - CARD16 sequenceNumber B16; - CARD32 length B32; - CARD32 dotclock B32; - CARD16 hdisplay B16; - CARD16 hsyncstart B16; - CARD16 hsyncend B16; - CARD16 htotal B16; - CARD16 vdisplay B16; - CARD16 vsyncstart B16; - CARD16 vsyncend B16; - CARD16 vtotal B16; - CARD32 flags B32; - CARD32 privsize B32; +typedef struct +{ + BYTE type; /* X_Reply */ + BOOL pad1; + CARD16 sequenceNumber B16; + CARD32 length B32; + CARD32 dotclock B32; + CARD16 hdisplay B16; + CARD16 hsyncstart B16; + CARD16 hsyncend B16; + CARD16 htotal B16; + CARD16 vdisplay B16; + CARD16 vsyncstart B16; + CARD16 vsyncend B16; + CARD16 vtotal B16; + CARD32 flags B32; + CARD32 privsize B32; } xXF86OldVidModeGetModeLineReply; #define sz_xXF86OldVidModeGetModeLineReply 36 -typedef struct { - CARD32 dotclock B32; - CARD16 hdisplay B16; - CARD16 hsyncstart B16; - CARD16 hsyncend B16; - CARD16 htotal B16; - CARD32 hskew B16; - CARD16 vdisplay B16; - CARD16 vsyncstart B16; - CARD16 vsyncend B16; - CARD16 vtotal B16; - CARD16 pad1 B16; - CARD32 flags B32; - CARD32 reserved1 B32; - CARD32 reserved2 B32; - CARD32 reserved3 B32; - CARD32 privsize B32; +typedef struct +{ + CARD32 dotclock B32; + CARD16 hdisplay B16; + CARD16 hsyncstart B16; + CARD16 hsyncend B16; + CARD16 htotal B16; + CARD32 hskew B16; + CARD16 vdisplay B16; + CARD16 vsyncstart B16; + CARD16 vsyncend B16; + CARD16 vtotal B16; + CARD16 pad1 B16; + CARD32 flags B32; + CARD32 reserved1 B32; + CARD32 reserved2 B32; + CARD32 reserved3 B32; + CARD32 privsize B32; } xXF86VidModeModeInfo; /* 0.x version */ -typedef struct { - CARD32 dotclock B32; - CARD16 hdisplay B16; - CARD16 hsyncstart B16; - CARD16 hsyncend B16; - CARD16 htotal B16; - CARD16 vdisplay B16; - CARD16 vsyncstart B16; - CARD16 vsyncend B16; - CARD16 vtotal B16; - CARD32 flags B32; - CARD32 privsize B32; +typedef struct +{ + CARD32 dotclock B32; + CARD16 hdisplay B16; + CARD16 hsyncstart B16; + CARD16 hsyncend B16; + CARD16 htotal B16; + CARD16 vdisplay B16; + CARD16 vsyncstart B16; + CARD16 vsyncend B16; + CARD16 vtotal B16; + CARD32 flags B32; + CARD32 privsize B32; } xXF86OldVidModeModeInfo; -typedef struct { - BYTE type; /* X_Reply */ - BOOL pad1; - CARD16 sequenceNumber B16; - CARD32 length B32; - CARD32 modecount B32; - CARD32 pad2 B32; - CARD32 pad3 B32; - CARD32 pad4 B32; - CARD32 pad5 B32; - CARD32 pad6 B32; +typedef struct +{ + BYTE type; /* X_Reply */ + BOOL pad1; + CARD16 sequenceNumber B16; + CARD32 length B32; + CARD32 modecount B32; + CARD32 pad2 B32; + CARD32 pad3 B32; + CARD32 pad4 B32; + CARD32 pad5 B32; + CARD32 pad6 B32; } xXF86VidModeGetAllModeLinesReply; #define sz_xXF86VidModeGetAllModeLinesReply 32 -typedef struct _XF86VidModeAddModeLine { - CARD8 reqType; /* always XF86VidModeReqCode */ - CARD8 xf86vidmodeReqType; /* always X_XF86VidModeAddMode */ - CARD16 length B16; - CARD32 screen B32; /* could be CARD16 but need the pad */ - CARD32 dotclock B32; - CARD16 hdisplay B16; - CARD16 hsyncstart B16; - CARD16 hsyncend B16; - CARD16 htotal B16; - CARD16 hskew B16; - CARD16 vdisplay B16; - CARD16 vsyncstart B16; - CARD16 vsyncend B16; - CARD16 vtotal B16; - CARD16 pad1 B16; - CARD32 flags B32; - CARD32 reserved1 B32; - CARD32 reserved2 B32; - CARD32 reserved3 B32; - CARD32 privsize B32; - CARD32 after_dotclock B32; - CARD16 after_hdisplay B16; - CARD16 after_hsyncstart B16; - CARD16 after_hsyncend B16; - CARD16 after_htotal B16; - CARD16 after_hskew B16; - CARD16 after_vdisplay B16; - CARD16 after_vsyncstart B16; - CARD16 after_vsyncend B16; - CARD16 after_vtotal B16; - CARD16 pad2 B16; - CARD32 after_flags B32; - CARD32 reserved4 B32; - CARD32 reserved5 B32; - CARD32 reserved6 B32; +typedef struct _XF86VidModeAddModeLine +{ + CARD8 reqType; /* always XF86VidModeReqCode */ + CARD8 xf86vidmodeReqType; /* always X_XF86VidModeAddMode */ + CARD16 length B16; + CARD32 screen B32; /* could be CARD16 but need the pad */ + CARD32 dotclock B32; + CARD16 hdisplay B16; + CARD16 hsyncstart B16; + CARD16 hsyncend B16; + CARD16 htotal B16; + CARD16 hskew B16; + CARD16 vdisplay B16; + CARD16 vsyncstart B16; + CARD16 vsyncend B16; + CARD16 vtotal B16; + CARD16 pad1 B16; + CARD32 flags B32; + CARD32 reserved1 B32; + CARD32 reserved2 B32; + CARD32 reserved3 B32; + CARD32 privsize B32; + CARD32 after_dotclock B32; + CARD16 after_hdisplay B16; + CARD16 after_hsyncstart B16; + CARD16 after_hsyncend B16; + CARD16 after_htotal B16; + CARD16 after_hskew B16; + CARD16 after_vdisplay B16; + CARD16 after_vsyncstart B16; + CARD16 after_vsyncend B16; + CARD16 after_vtotal B16; + CARD16 pad2 B16; + CARD32 after_flags B32; + CARD32 reserved4 B32; + CARD32 reserved5 B32; + CARD32 reserved6 B32; } xXF86VidModeAddModeLineReq; #define sz_xXF86VidModeAddModeLineReq 92 /* 0.x version */ -typedef struct _XF86OldVidModeAddModeLine { - CARD8 reqType; /* always XF86VidModeReqCode */ - CARD8 xf86vidmodeReqType; /* always X_XF86VidModeAddMode */ - CARD16 length B16; - CARD32 screen B32; /* could be CARD16 but need the pad */ - CARD32 dotclock B32; - CARD16 hdisplay B16; - CARD16 hsyncstart B16; - CARD16 hsyncend B16; - CARD16 htotal B16; - CARD16 vdisplay B16; - CARD16 vsyncstart B16; - CARD16 vsyncend B16; - CARD16 vtotal B16; - CARD32 flags B32; - CARD32 privsize B32; - CARD32 after_dotclock B32; - CARD16 after_hdisplay B16; - CARD16 after_hsyncstart B16; - CARD16 after_hsyncend B16; - CARD16 after_htotal B16; - CARD16 after_vdisplay B16; - CARD16 after_vsyncstart B16; - CARD16 after_vsyncend B16; - CARD16 after_vtotal B16; - CARD32 after_flags B32; +typedef struct _XF86OldVidModeAddModeLine +{ + CARD8 reqType; /* always XF86VidModeReqCode */ + CARD8 xf86vidmodeReqType; /* always X_XF86VidModeAddMode */ + CARD16 length B16; + CARD32 screen B32; /* could be CARD16 but need the pad */ + CARD32 dotclock B32; + CARD16 hdisplay B16; + CARD16 hsyncstart B16; + CARD16 hsyncend B16; + CARD16 htotal B16; + CARD16 vdisplay B16; + CARD16 vsyncstart B16; + CARD16 vsyncend B16; + CARD16 vtotal B16; + CARD32 flags B32; + CARD32 privsize B32; + CARD32 after_dotclock B32; + CARD16 after_hdisplay B16; + CARD16 after_hsyncstart B16; + CARD16 after_hsyncend B16; + CARD16 after_htotal B16; + CARD16 after_vdisplay B16; + CARD16 after_vsyncstart B16; + CARD16 after_vsyncend B16; + CARD16 after_vtotal B16; + CARD32 after_flags B32; } xXF86OldVidModeAddModeLineReq; #define sz_xXF86OldVidModeAddModeLineReq 60 -typedef struct _XF86VidModeModModeLine { - CARD8 reqType; /* always XF86VidModeReqCode */ - CARD8 xf86vidmodeReqType; /* always X_XF86VidModeModModeLine */ - CARD16 length B16; - CARD32 screen B32; /* could be CARD16 but need the pad */ - CARD16 hdisplay B16; - CARD16 hsyncstart B16; - CARD16 hsyncend B16; - CARD16 htotal B16; - CARD16 hskew B16; - CARD16 vdisplay B16; - CARD16 vsyncstart B16; - CARD16 vsyncend B16; - CARD16 vtotal B16; - CARD16 pad1 B16; - CARD32 flags B32; - CARD32 reserved1 B32; - CARD32 reserved2 B32; - CARD32 reserved3 B32; - CARD32 privsize B32; +typedef struct _XF86VidModeModModeLine +{ + CARD8 reqType; /* always XF86VidModeReqCode */ + CARD8 xf86vidmodeReqType; /* always X_XF86VidModeModModeLine */ + CARD16 length B16; + CARD32 screen B32; /* could be CARD16 but need the pad */ + CARD16 hdisplay B16; + CARD16 hsyncstart B16; + CARD16 hsyncend B16; + CARD16 htotal B16; + CARD16 hskew B16; + CARD16 vdisplay B16; + CARD16 vsyncstart B16; + CARD16 vsyncend B16; + CARD16 vtotal B16; + CARD16 pad1 B16; + CARD32 flags B32; + CARD32 reserved1 B32; + CARD32 reserved2 B32; + CARD32 reserved3 B32; + CARD32 privsize B32; } xXF86VidModeModModeLineReq; #define sz_xXF86VidModeModModeLineReq 48 /* 0.x version */ -typedef struct _XF86OldVidModeModModeLine { - CARD8 reqType; /* always XF86OldVidModeReqCode */ - CARD8 xf86vidmodeReqType; /* always X_XF86OldVidModeModModeLine */ - CARD16 length B16; - CARD32 screen B32; /* could be CARD16 but need the pad */ - CARD16 hdisplay B16; - CARD16 hsyncstart B16; - CARD16 hsyncend B16; - CARD16 htotal B16; - CARD16 vdisplay B16; - CARD16 vsyncstart B16; - CARD16 vsyncend B16; - CARD16 vtotal B16; - CARD32 flags B32; - CARD32 privsize B32; +typedef struct _XF86OldVidModeModModeLine +{ + CARD8 reqType; /* always XF86OldVidModeReqCode */ + CARD8 xf86vidmodeReqType; /* always X_XF86OldVidModeModModeLine */ + CARD16 length B16; + CARD32 screen B32; /* could be CARD16 but need the pad */ + CARD16 hdisplay B16; + CARD16 hsyncstart B16; + CARD16 hsyncend B16; + CARD16 htotal B16; + CARD16 vdisplay B16; + CARD16 vsyncstart B16; + CARD16 vsyncend B16; + CARD16 vtotal B16; + CARD32 flags B32; + CARD32 privsize B32; } xXF86OldVidModeModModeLineReq; #define sz_xXF86OldVidModeModModeLineReq 32 -typedef struct _XF86VidModeValidateModeLine { - CARD8 reqType; /* always XF86VidModeReqCode */ - CARD8 xf86vidmodeReqType; - CARD16 length B16; - CARD32 screen B32; /* could be CARD16 but need the pad */ - CARD32 dotclock B32; - CARD16 hdisplay B16; - CARD16 hsyncstart B16; - CARD16 hsyncend B16; - CARD16 htotal B16; - CARD16 hskew B16; - CARD16 vdisplay B16; - CARD16 vsyncstart B16; - CARD16 vsyncend B16; - CARD16 vtotal B16; - CARD16 pad1 B16; - CARD32 flags B32; - CARD32 reserved1 B32; - CARD32 reserved2 B32; - CARD32 reserved3 B32; - CARD32 privsize B32; +typedef struct _XF86VidModeValidateModeLine +{ + CARD8 reqType; /* always XF86VidModeReqCode */ + CARD8 xf86vidmodeReqType; + CARD16 length B16; + CARD32 screen B32; /* could be CARD16 but need the pad */ + CARD32 dotclock B32; + CARD16 hdisplay B16; + CARD16 hsyncstart B16; + CARD16 hsyncend B16; + CARD16 htotal B16; + CARD16 hskew B16; + CARD16 vdisplay B16; + CARD16 vsyncstart B16; + CARD16 vsyncend B16; + CARD16 vtotal B16; + CARD16 pad1 B16; + CARD32 flags B32; + CARD32 reserved1 B32; + CARD32 reserved2 B32; + CARD32 reserved3 B32; + CARD32 privsize B32; } xXF86VidModeDeleteModeLineReq, - xXF86VidModeValidateModeLineReq, - xXF86VidModeSwitchToModeReq; + xXF86VidModeValidateModeLineReq, xXF86VidModeSwitchToModeReq; #define sz_xXF86VidModeDeleteModeLineReq 52 #define sz_xXF86VidModeValidateModeLineReq 52 #define sz_xXF86VidModeSwitchToModeReq 52 /* 0.x version */ -typedef struct _XF86OldVidModeValidateModeLine { - CARD8 reqType; /* always XF86OldVidModeReqCode */ - CARD8 xf86vidmodeReqType; - CARD16 length B16; - CARD32 screen B32; /* could be CARD16 but need the pad */ - CARD32 dotclock B32; - CARD16 hdisplay B16; - CARD16 hsyncstart B16; - CARD16 hsyncend B16; - CARD16 htotal B16; - CARD16 vdisplay B16; - CARD16 vsyncstart B16; - CARD16 vsyncend B16; - CARD16 vtotal B16; - CARD32 flags B32; - CARD32 privsize B32; +typedef struct _XF86OldVidModeValidateModeLine +{ + CARD8 reqType; /* always XF86OldVidModeReqCode */ + CARD8 xf86vidmodeReqType; + CARD16 length B16; + CARD32 screen B32; /* could be CARD16 but need the pad */ + CARD32 dotclock B32; + CARD16 hdisplay B16; + CARD16 hsyncstart B16; + CARD16 hsyncend B16; + CARD16 htotal B16; + CARD16 vdisplay B16; + CARD16 vsyncstart B16; + CARD16 vsyncend B16; + CARD16 vtotal B16; + CARD32 flags B32; + CARD32 privsize B32; } xXF86OldVidModeDeleteModeLineReq, - xXF86OldVidModeValidateModeLineReq, - xXF86OldVidModeSwitchToModeReq; + xXF86OldVidModeValidateModeLineReq, xXF86OldVidModeSwitchToModeReq; #define sz_xXF86OldVidModeDeleteModeLineReq 36 #define sz_xXF86OldVidModeValidateModeLineReq 36 #define sz_xXF86OldVidModeSwitchToModeReq 36 -typedef struct _XF86VidModeSwitchMode { - CARD8 reqType; /* always XF86VidModeReqCode */ - CARD8 xf86vidmodeReqType; /* always X_XF86VidModeSwitchMode */ - CARD16 length B16; - CARD16 screen B16; - CARD16 zoom B16; +typedef struct _XF86VidModeSwitchMode +{ + CARD8 reqType; /* always XF86VidModeReqCode */ + CARD8 xf86vidmodeReqType; /* always X_XF86VidModeSwitchMode */ + CARD16 length B16; + CARD16 screen B16; + CARD16 zoom B16; } xXF86VidModeSwitchModeReq; #define sz_xXF86VidModeSwitchModeReq 8 -typedef struct _XF86VidModeLockModeSwitch { - CARD8 reqType; /* always XF86VidModeReqCode */ - CARD8 xf86vidmodeReqType; /* always X_XF86VidModeLockModeSwitch */ - CARD16 length B16; - CARD16 screen B16; - CARD16 lock B16; +typedef struct _XF86VidModeLockModeSwitch +{ + CARD8 reqType; /* always XF86VidModeReqCode */ + CARD8 xf86vidmodeReqType; /* always X_XF86VidModeLockModeSwitch */ + CARD16 length B16; + CARD16 screen B16; + CARD16 lock B16; } xXF86VidModeLockModeSwitchReq; #define sz_xXF86VidModeLockModeSwitchReq 8 -typedef struct { - BYTE type; /* X_Reply */ - BOOL pad1; - CARD16 sequenceNumber B16; - CARD32 length B32; - CARD32 status B32; - CARD32 pad2 B32; - CARD32 pad3 B32; - CARD32 pad4 B32; - CARD32 pad5 B32; - CARD32 pad6 B32; +typedef struct +{ + BYTE type; /* X_Reply */ + BOOL pad1; + CARD16 sequenceNumber B16; + CARD32 length B32; + CARD32 status B32; + CARD32 pad2 B32; + CARD32 pad3 B32; + CARD32 pad4 B32; + CARD32 pad5 B32; + CARD32 pad6 B32; } xXF86VidModeValidateModeLineReply; #define sz_xXF86VidModeValidateModeLineReply 32 -typedef struct { - BYTE type; /* X_Reply */ - BOOL pad1; - CARD16 sequenceNumber B16; - CARD32 length B32; - CARD8 vendorLength; - CARD8 modelLength; - CARD8 nhsync; - CARD8 nvsync; - CARD32 pad2 B32; - CARD32 pad3 B32; - CARD32 pad4 B32; - CARD32 pad5 B32; - CARD32 pad6 B32; +typedef struct +{ + BYTE type; /* X_Reply */ + BOOL pad1; + CARD16 sequenceNumber B16; + CARD32 length B32; + CARD8 vendorLength; + CARD8 modelLength; + CARD8 nhsync; + CARD8 nvsync; + CARD32 pad2 B32; + CARD32 pad3 B32; + CARD32 pad4 B32; + CARD32 pad5 B32; + CARD32 pad6 B32; } xXF86VidModeGetMonitorReply; #define sz_xXF86VidModeGetMonitorReply 32 -typedef struct { - BYTE type; - BOOL pad1; - CARD16 sequenceNumber B16; - CARD32 length B32; - CARD32 x B32; - CARD32 y B32; - CARD32 pad2 B32; - CARD32 pad3 B32; - CARD32 pad4 B32; - CARD32 pad5 B32; +typedef struct +{ + BYTE type; + BOOL pad1; + CARD16 sequenceNumber B16; + CARD32 length B32; + CARD32 x B32; + CARD32 y B32; + CARD32 pad2 B32; + CARD32 pad3 B32; + CARD32 pad4 B32; + CARD32 pad5 B32; } xXF86VidModeGetViewPortReply; #define sz_xXF86VidModeGetViewPortReply 32 -typedef struct _XF86VidModeSetViewPort { - CARD8 reqType; /* always VidModeReqCode */ - CARD8 xf86vidmodeReqType; /* always X_XF86VidModeSetViewPort */ - CARD16 length B16; - CARD16 screen B16; - CARD16 pad B16; - CARD32 x B32; - CARD32 y B32; +typedef struct _XF86VidModeSetViewPort +{ + CARD8 reqType; /* always VidModeReqCode */ + CARD8 xf86vidmodeReqType; /* always X_XF86VidModeSetViewPort */ + CARD16 length B16; + CARD16 screen B16; + CARD16 pad B16; + CARD32 x B32; + CARD32 y B32; } xXF86VidModeSetViewPortReq; #define sz_xXF86VidModeSetViewPortReq 16 -typedef struct { - BYTE type; - BOOL pad1; - CARD16 sequenceNumber B16; - CARD32 length B32; - CARD32 flags B32; - CARD32 clocks B32; - CARD32 maxclocks B32; - CARD32 pad2 B32; - CARD32 pad3 B32; - CARD32 pad4 B32; +typedef struct +{ + BYTE type; + BOOL pad1; + CARD16 sequenceNumber B16; + CARD32 length B32; + CARD32 flags B32; + CARD32 clocks B32; + CARD32 maxclocks B32; + CARD32 pad2 B32; + CARD32 pad3 B32; + CARD32 pad4 B32; } xXF86VidModeGetDotClocksReply; #define sz_xXF86VidModeGetDotClocksReply 32 -typedef struct _XF86VidModeSetClientVersion { - CARD8 reqType; /* always XF86VidModeReqCode */ - CARD8 xf86vidmodeReqType; - CARD16 length B16; - CARD16 major B16; - CARD16 minor B16; +typedef struct _XF86VidModeSetClientVersion +{ + CARD8 reqType; /* always XF86VidModeReqCode */ + CARD8 xf86vidmodeReqType; + CARD16 length B16; + CARD16 major B16; + CARD16 minor B16; } xXF86VidModeSetClientVersionReq; #define sz_xXF86VidModeSetClientVersionReq 8 -typedef struct _XF86VidModeGetGamma { - CARD8 reqType; /* always XF86VidModeReqCode */ - CARD8 xf86vidmodeReqType; - CARD16 length B16; - CARD16 screen B16; - CARD16 pad B16; - CARD32 pad1 B32; - CARD32 pad2 B32; - CARD32 pad3 B32; - CARD32 pad4 B32; - CARD32 pad5 B32; - CARD32 pad6 B32; +typedef struct _XF86VidModeGetGamma +{ + CARD8 reqType; /* always XF86VidModeReqCode */ + CARD8 xf86vidmodeReqType; + CARD16 length B16; + CARD16 screen B16; + CARD16 pad B16; + CARD32 pad1 B32; + CARD32 pad2 B32; + CARD32 pad3 B32; + CARD32 pad4 B32; + CARD32 pad5 B32; + CARD32 pad6 B32; } xXF86VidModeGetGammaReq; #define sz_xXF86VidModeGetGammaReq 32 -typedef struct { - BYTE type; - BOOL pad; - CARD16 sequenceNumber B16; - CARD32 length B32; - CARD32 red B32; - CARD32 green B32; - CARD32 blue B32; - CARD32 pad1 B32; - CARD32 pad2 B32; - CARD32 pad3 B32; +typedef struct +{ + BYTE type; + BOOL pad; + CARD16 sequenceNumber B16; + CARD32 length B32; + CARD32 red B32; + CARD32 green B32; + CARD32 blue B32; + CARD32 pad1 B32; + CARD32 pad2 B32; + CARD32 pad3 B32; } xXF86VidModeGetGammaReply; #define sz_xXF86VidModeGetGammaReply 32 -typedef struct _XF86VidModeSetGamma { - CARD8 reqType; /* always XF86VidModeReqCode */ - CARD8 xf86vidmodeReqType; - CARD16 length B16; - CARD16 screen B16; - CARD16 pad B16; - CARD32 red B32; - CARD32 green B32; - CARD32 blue B32; - CARD32 pad1 B32; - CARD32 pad2 B32; - CARD32 pad3 B32; +typedef struct _XF86VidModeSetGamma +{ + CARD8 reqType; /* always XF86VidModeReqCode */ + CARD8 xf86vidmodeReqType; + CARD16 length B16; + CARD16 screen B16; + CARD16 pad B16; + CARD32 red B32; + CARD32 green B32; + CARD32 blue B32; + CARD32 pad1 B32; + CARD32 pad2 B32; + CARD32 pad3 B32; } xXF86VidModeSetGammaReq; #define sz_xXF86VidModeSetGammaReq 32 -typedef struct _XF86VidModeSetGammaRamp { - CARD8 reqType; /* always XF86VidModeReqCode */ - CARD8 xf86vidmodeReqType; - CARD16 length B16; - CARD16 screen B16; - CARD16 size B16; +typedef struct _XF86VidModeSetGammaRamp +{ + CARD8 reqType; /* always XF86VidModeReqCode */ + CARD8 xf86vidmodeReqType; + CARD16 length B16; + CARD16 screen B16; + CARD16 size B16; } xXF86VidModeSetGammaRampReq; -#define sz_xXF86VidModeSetGammaRampReq 8 - -typedef struct _XF86VidModeGetGammaRamp { - CARD8 reqType; /* always XF86VidModeReqCode */ - CARD8 xf86vidmodeReqType; - CARD16 length B16; - CARD16 screen B16; - CARD16 size B16; +#define sz_xXF86VidModeSetGammaRampReq 8 + +typedef struct _XF86VidModeGetGammaRamp +{ + CARD8 reqType; /* always XF86VidModeReqCode */ + CARD8 xf86vidmodeReqType; + CARD16 length B16; + CARD16 screen B16; + CARD16 size B16; } xXF86VidModeGetGammaRampReq; #define sz_xXF86VidModeGetGammaRampReq 8 -typedef struct { - BYTE type; - BOOL pad; - CARD16 sequenceNumber B16; - CARD32 length B32; - CARD16 size B16; - CARD16 pad0 B16; - CARD32 pad1 B32; - CARD32 pad2 B32; - CARD32 pad3 B32; - CARD32 pad4 B32; - CARD32 pad5 B32; +typedef struct +{ + BYTE type; + BOOL pad; + CARD16 sequenceNumber B16; + CARD32 length B32; + CARD16 size B16; + CARD16 pad0 B16; + CARD32 pad1 B32; + CARD32 pad2 B32; + CARD32 pad3 B32; + CARD32 pad4 B32; + CARD32 pad5 B32; } xXF86VidModeGetGammaRampReply; #define sz_xXF86VidModeGetGammaRampReply 32 -typedef struct _XF86VidModeGetGammaRampSize { - CARD8 reqType; /* always XF86VidModeReqCode */ - CARD8 xf86vidmodeReqType; - CARD16 length B16; - CARD16 screen B16; - CARD16 pad B16; +typedef struct _XF86VidModeGetGammaRampSize +{ + CARD8 reqType; /* always XF86VidModeReqCode */ + CARD8 xf86vidmodeReqType; + CARD16 length B16; + CARD16 screen B16; + CARD16 pad B16; } xXF86VidModeGetGammaRampSizeReq; #define sz_xXF86VidModeGetGammaRampSizeReq 8 -typedef struct { - BYTE type; - BOOL pad; - CARD16 sequenceNumber B16; - CARD32 length B32; - CARD16 size B16; - CARD16 pad0 B16; - CARD32 pad1 B32; - CARD32 pad2 B32; - CARD32 pad3 B32; - CARD32 pad4 B32; - CARD32 pad5 B32; +typedef struct +{ + BYTE type; + BOOL pad; + CARD16 sequenceNumber B16; + CARD32 length B32; + CARD16 size B16; + CARD16 pad0 B16; + CARD32 pad1 B32; + CARD32 pad2 B32; + CARD32 pad3 B32; + CARD32 pad4 B32; + CARD32 pad5 B32; } xXF86VidModeGetGammaRampSizeReply; #define sz_xXF86VidModeGetGammaRampSizeReply 32 #endif /* _XF86VIDMODESTR_H_ */ - +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/Xext/extensions/xme.h b/src/video/Xext/extensions/xme.h index 41bb416ad..d86f46d4a 100644 --- a/src/video/Xext/extensions/xme.h +++ b/src/video/Xext/extensions/xme.h @@ -12,30 +12,31 @@ */ -#ifndef _XME_H_INCLUDED +#ifndef _XME_H_INCLUDED #define _XME_H_INCLUDED -typedef struct { - short x; - short y; - unsigned short w; - unsigned short h; +typedef struct +{ + short x; + short y; + unsigned short w; + unsigned short h; } XiGMiscViewInfo; -typedef struct { - unsigned short width; - unsigned short height; - int refresh; +typedef struct +{ + unsigned short width; + unsigned short height; + int refresh; } XiGMiscResolutionInfo; -extern Bool XiGMiscQueryVersion(Display *dpy, int *major, int *minor); -extern int XiGMiscQueryViews(Display *dpy, int screen, - XiGMiscViewInfo **pviews); -extern int XiGMiscQueryResolutions(Display *dpy, int screen, int view, - int *pactive, - XiGMiscResolutionInfo **presolutions); -extern void XiGMiscChangeResolution(Display *dpy, int screen, int view, - int width, int height, int refresh); +extern Bool XiGMiscQueryVersion(Display * dpy, int *major, int *minor); +extern int XiGMiscQueryViews(Display * dpy, int screen, + XiGMiscViewInfo ** pviews); +extern int XiGMiscQueryResolutions(Display * dpy, int screen, int view, + int *pactive, + XiGMiscResolutionInfo ** presolutions); +extern void XiGMiscChangeResolution(Display * dpy, int screen, int view, + int width, int height, int refresh); #endif /* _XME_H_INCLUDED */ - - +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/aalib/SDL_aaevents.c b/src/video/aalib/SDL_aaevents.c index 7811f1932..63b21dbd4 100644 --- a/src/video/aalib/SDL_aaevents.c +++ b/src/video/aalib/SDL_aaevents.c @@ -36,167 +36,178 @@ /* The translation tables from a console scancode to a SDL keysym */ static SDLKey keymap[401]; -static SDL_keysym *TranslateKey(int scancode, SDL_keysym *keysym); +static SDL_keysym *TranslateKey(int scancode, SDL_keysym * keysym); -void AA_PumpEvents(_THIS) +void +AA_PumpEvents(_THIS) { - int posted = 0; - int mouse_button, mouse_x, mouse_y; - int evt; - SDL_keysym keysym; - - static int prev_button = -1, prev_x = -1, prev_y = -1; - - if( ! this->screen ) /* Wait till we got the screen initialized */ - return; - - do { - posted = 0; - /* Gather events */ - - /* Get mouse status */ - SDL_mutexP(AA_mutex); - aa_getmouse (AA_context, &mouse_x, &mouse_y, &mouse_button); - SDL_mutexV(AA_mutex); - mouse_x = mouse_x * this->screen->w / aa_scrwidth (AA_context); - mouse_y = mouse_y * this->screen->h / aa_scrheight (AA_context); - - /* Compare against previous state and generate events */ - if( prev_button != mouse_button ) { - if( mouse_button & AA_BUTTON1 ) { - if ( ! (prev_button & AA_BUTTON1) ) { - posted += SDL_PrivateMouseButton(SDL_PRESSED, 1, 0, 0); - } - } else { - if ( prev_button & AA_BUTTON1 ) { - posted += SDL_PrivateMouseButton(SDL_RELEASED, 1, 0, 0); - } - } - if( mouse_button & AA_BUTTON2 ) { - if ( ! (prev_button & AA_BUTTON2) ) { - posted += SDL_PrivateMouseButton(SDL_PRESSED, 2, 0, 0); - } - } else { - if ( prev_button & AA_BUTTON2 ) { - posted += SDL_PrivateMouseButton(SDL_RELEASED, 2, 0, 0); - } - } - if( mouse_button & AA_BUTTON3 ) { - if ( ! (prev_button & AA_BUTTON3) ) { - posted += SDL_PrivateMouseButton(SDL_PRESSED, 3, 0, 0); - } - } else { - if ( prev_button & AA_BUTTON3 ) { - posted += SDL_PrivateMouseButton(SDL_RELEASED, 3, 0, 0); - } - } - } - if ( prev_x != mouse_x || prev_y != mouse_y ) { - posted += SDL_PrivateMouseMotion(0, 0, mouse_x, mouse_y); - } - - prev_button = mouse_button; - prev_x = mouse_x; prev_y = mouse_y; - - /* Get keyboard event */ - SDL_mutexP(AA_mutex); - evt = aa_getevent(AA_context, 0); - SDL_mutexV(AA_mutex); - if ( (evt > AA_NONE) && (evt < AA_RELEASE) && (evt != AA_MOUSE) && (evt != AA_RESIZE) ) { - /* Key pressed */ + int posted = 0; + int mouse_button, mouse_x, mouse_y; + int evt; + SDL_keysym keysym; + + static int prev_button = -1, prev_x = -1, prev_y = -1; + + if (!this->screen) /* Wait till we got the screen initialized */ + return; + + do { + posted = 0; + /* Gather events */ + + /* Get mouse status */ + SDL_mutexP(AA_mutex); + aa_getmouse(AA_context, &mouse_x, &mouse_y, &mouse_button); + SDL_mutexV(AA_mutex); + mouse_x = mouse_x * this->screen->w / aa_scrwidth(AA_context); + mouse_y = mouse_y * this->screen->h / aa_scrheight(AA_context); + + /* Compare against previous state and generate events */ + if (prev_button != mouse_button) { + if (mouse_button & AA_BUTTON1) { + if (!(prev_button & AA_BUTTON1)) { + posted += SDL_PrivateMouseButton(SDL_PRESSED, 1, 0, 0); + } + } else { + if (prev_button & AA_BUTTON1) { + posted += SDL_PrivateMouseButton(SDL_RELEASED, 1, 0, 0); + } + } + if (mouse_button & AA_BUTTON2) { + if (!(prev_button & AA_BUTTON2)) { + posted += SDL_PrivateMouseButton(SDL_PRESSED, 2, 0, 0); + } + } else { + if (prev_button & AA_BUTTON2) { + posted += SDL_PrivateMouseButton(SDL_RELEASED, 2, 0, 0); + } + } + if (mouse_button & AA_BUTTON3) { + if (!(prev_button & AA_BUTTON3)) { + posted += SDL_PrivateMouseButton(SDL_PRESSED, 3, 0, 0); + } + } else { + if (prev_button & AA_BUTTON3) { + posted += SDL_PrivateMouseButton(SDL_RELEASED, 3, 0, 0); + } + } + } + if (prev_x != mouse_x || prev_y != mouse_y) { + posted += SDL_PrivateMouseMotion(0, 0, mouse_x, mouse_y); + } + + prev_button = mouse_button; + prev_x = mouse_x; + prev_y = mouse_y; + + /* Get keyboard event */ + SDL_mutexP(AA_mutex); + evt = aa_getevent(AA_context, 0); + SDL_mutexV(AA_mutex); + if ((evt > AA_NONE) && (evt < AA_RELEASE) && (evt != AA_MOUSE) + && (evt != AA_RESIZE)) { + /* Key pressed */ /* printf("Key pressed: %d (%c)\n", evt, evt); */ - posted += SDL_PrivateKeyboard(SDL_PRESSED, TranslateKey(evt, &keysym)); - } else if ( evt >= AA_RELEASE ) { - /* Key released */ - evt &= ~AA_RELEASE; + posted += + SDL_PrivateKeyboard(SDL_PRESSED, TranslateKey(evt, &keysym)); + } else if (evt >= AA_RELEASE) { + /* Key released */ + evt &= ~AA_RELEASE; /* printf("Key released: %d (%c)\n", evt, evt); */ - posted += SDL_PrivateKeyboard(SDL_RELEASED, TranslateKey(evt, &keysym)); - } - } while ( posted ); + posted += + SDL_PrivateKeyboard(SDL_RELEASED, TranslateKey(evt, &keysym)); + } + } + while (posted); } -void AA_InitOSKeymap(_THIS) +void +AA_InitOSKeymap(_THIS) { - int i; - static const char *std_keys = " 01234567890&#'()_-|$*+-=/\\:;.,!?<>{}[]@~%^\x9"; - const char *std; - - /* Initialize the AAlib key translation table */ - for ( i=0; i{}[]@~%^\x9"; + const char *std; + + /* Initialize the AAlib key translation table */ + for (i = 0; i < SDL_arraysize(keymap); ++i) + keymap[i] = SDLK_UNKNOWN; + + /* Alphabet keys */ + for (i = 0; i < 26; ++i) { + keymap['a' + i] = SDLK_a + i; + keymap['A' + i] = SDLK_a + i; + } + /* Function keys */ + for (i = 0; i < 12; ++i) { + keymap[334 + i] = SDLK_F1 + i; + } + /* Keys that have the same symbols and don't have to be translated */ + for (std = std_keys; *std; std++) { + keymap[*std] = *std; + } + + keymap[13] = SDLK_RETURN; + keymap[AA_BACKSPACE] = SDLK_BACKSPACE; + + keymap[369] = SDLK_LSHIFT; + keymap[370] = SDLK_RSHIFT; + keymap[371] = SDLK_LCTRL; + keymap[372] = SDLK_RCTRL; + keymap[377] = SDLK_LALT; + keymap[270] = SDLK_RALT; + keymap[271] = SDLK_NUMLOCK; + keymap[373] = SDLK_CAPSLOCK; + keymap[164] = SDLK_SCROLLOCK; + + keymap[243] = SDLK_INSERT; + keymap[304] = SDLK_DELETE; + keymap[224] = SDLK_HOME; + keymap[231] = SDLK_END; + keymap[229] = SDLK_PAGEUP; + keymap[230] = SDLK_PAGEDOWN; + + keymap[241] = SDLK_PRINT; + keymap[163] = SDLK_BREAK; + + keymap[302] = SDLK_KP0; + keymap[300] = SDLK_KP1; + keymap[297] = SDLK_KP2; + keymap[299] = SDLK_KP3; + keymap[294] = SDLK_KP4; + keymap[301] = SDLK_KP5; + keymap[296] = SDLK_KP6; + keymap[293] = SDLK_KP7; + keymap[295] = SDLK_KP8; + keymap[298] = SDLK_KP9; + + keymap[AA_ESC] = SDLK_ESCAPE; + keymap[AA_UP] = SDLK_UP; + keymap[AA_DOWN] = SDLK_DOWN; + keymap[AA_LEFT] = SDLK_LEFT; + keymap[AA_RIGHT] = SDLK_RIGHT; } -static SDL_keysym *TranslateKey(int scancode, SDL_keysym *keysym) +static SDL_keysym * +TranslateKey(int scancode, SDL_keysym * keysym) { - /* Sanity check */ - if ( scancode >= SDL_arraysize(keymap) ) - scancode = AA_UNKNOWN; - - /* Set the keysym information */ - keysym->scancode = scancode; - keysym->sym = keymap[scancode]; - keysym->mod = KMOD_NONE; - - /* If UNICODE is on, get the UNICODE value for the key */ - keysym->unicode = 0; - if ( SDL_TranslateUNICODE ) { - /* Populate the unicode field with the ASCII value */ - keysym->unicode = scancode; - } - return(keysym); + /* Sanity check */ + if (scancode >= SDL_arraysize(keymap)) + scancode = AA_UNKNOWN; + + /* Set the keysym information */ + keysym->scancode = scancode; + keysym->sym = keymap[scancode]; + keysym->mod = KMOD_NONE; + + /* If UNICODE is on, get the UNICODE value for the key */ + keysym->unicode = 0; + if (SDL_TranslateUNICODE) { + /* Populate the unicode field with the ASCII value */ + keysym->unicode = scancode; + } + return (keysym); } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/aalib/SDL_aaevents_c.h b/src/video/aalib/SDL_aaevents_c.h index 37a1c2e30..fd25dbf6c 100644 --- a/src/video/aalib/SDL_aaevents_c.h +++ b/src/video/aalib/SDL_aaevents_c.h @@ -28,8 +28,9 @@ */ extern void AA_initkeymaps(int fd); extern void AA_mousecallback(int button, int dx, int dy, - int u1,int u2,int u3, int u4); + int u1, int u2, int u3, int u4); extern void AA_keyboardcallback(int scancode, int pressed); extern void AA_InitOSKeymap(_THIS); extern void AA_PumpEvents(_THIS); +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/aalib/SDL_aamouse.c b/src/video/aalib/SDL_aamouse.c index eed197d44..8a1a72d09 100644 --- a/src/video/aalib/SDL_aamouse.c +++ b/src/video/aalib/SDL_aamouse.c @@ -30,6 +30,8 @@ /* The implementation dependent data for the window manager cursor */ -struct WMcursor { - int unused; +struct WMcursor +{ + int unused; }; +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/aalib/SDL_aamouse_c.h b/src/video/aalib/SDL_aamouse_c.h index 8e06cf2ff..00752bea2 100644 --- a/src/video/aalib/SDL_aamouse_c.h +++ b/src/video/aalib/SDL_aamouse_c.h @@ -24,3 +24,4 @@ #include "SDL_aavideo.h" /* Functions to be exported */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/aalib/SDL_aavideo.c b/src/video/aalib/SDL_aavideo.c index 3ec322eab..518bbd97c 100644 --- a/src/video/aalib/SDL_aavideo.c +++ b/src/video/aalib/SDL_aavideo.c @@ -41,348 +41,385 @@ #include /* Initialization/Query functions */ -static int AA_VideoInit(_THIS, SDL_PixelFormat *vformat); -static SDL_Rect **AA_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags); -static SDL_Surface *AA_SetVideoMode(_THIS, SDL_Surface *current, int width, int height, int bpp, Uint32 flags); -static int AA_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color *colors); +static int AA_VideoInit(_THIS, SDL_PixelFormat * vformat); +static SDL_Rect **AA_ListModes(_THIS, SDL_PixelFormat * format, Uint32 flags); +static SDL_Surface *AA_SetVideoMode(_THIS, SDL_Surface * current, int width, + int height, int bpp, Uint32 flags); +static int AA_SetColors(_THIS, int firstcolor, int ncolors, + SDL_Color * colors); static void AA_VideoQuit(_THIS); /* Hardware surface functions */ -static int AA_AllocHWSurface(_THIS, SDL_Surface *surface); -static int AA_LockHWSurface(_THIS, SDL_Surface *surface); -static int AA_FlipHWSurface(_THIS, SDL_Surface *surface); -static void AA_UnlockHWSurface(_THIS, SDL_Surface *surface); -static void AA_FreeHWSurface(_THIS, SDL_Surface *surface); +static int AA_AllocHWSurface(_THIS, SDL_Surface * surface); +static int AA_LockHWSurface(_THIS, SDL_Surface * surface); +static int AA_FlipHWSurface(_THIS, SDL_Surface * surface); +static void AA_UnlockHWSurface(_THIS, SDL_Surface * surface); +static void AA_FreeHWSurface(_THIS, SDL_Surface * surface); /* Cache the VideoDevice struct */ static struct SDL_VideoDevice *local_this; /* AAlib driver bootstrap functions */ -static int AA_Available(void) +static int +AA_Available(void) { - return 1; /* Always available ! */ + return 1; /* Always available ! */ } -static void AA_DeleteDevice(SDL_VideoDevice *device) +static void +AA_DeleteDevice(SDL_VideoDevice * device) { - SDL_free(device->hidden); - SDL_free(device); + SDL_free(device->hidden); + SDL_free(device); } -static SDL_VideoDevice *AA_CreateDevice(int devindex) +static SDL_VideoDevice * +AA_CreateDevice(int devindex) { - SDL_VideoDevice *device; - - /* Initialize all variables that we clean on shutdown */ - device = (SDL_VideoDevice *)SDL_malloc(sizeof(SDL_VideoDevice)); - if ( device ) { - SDL_memset(device, 0, (sizeof *device)); - device->hidden = (struct SDL_PrivateVideoData *) - SDL_malloc((sizeof *device->hidden)); - } - if ( (device == NULL) || (device->hidden == NULL) ) { - SDL_OutOfMemory(); - if ( device ) { - SDL_free(device); - } - return(0); - } - SDL_memset(device->hidden, 0, (sizeof *device->hidden)); - - /* Set the function pointers */ - device->VideoInit = AA_VideoInit; - device->ListModes = AA_ListModes; - device->SetVideoMode = AA_SetVideoMode; - device->CreateYUVOverlay = NULL; - device->SetColors = AA_SetColors; - device->UpdateRects = NULL; - device->VideoQuit = AA_VideoQuit; - device->AllocHWSurface = AA_AllocHWSurface; - device->CheckHWBlit = NULL; - device->FillHWRect = NULL; - device->SetHWColorKey = NULL; - device->SetHWAlpha = NULL; - device->LockHWSurface = AA_LockHWSurface; - device->UnlockHWSurface = AA_UnlockHWSurface; - device->FlipHWSurface = NULL; - device->FreeHWSurface = AA_FreeHWSurface; - device->SetCaption = NULL; - device->SetIcon = NULL; - device->IconifyWindow = NULL; - device->GrabInput = NULL; - device->GetWMInfo = NULL; - device->InitOSKeymap = AA_InitOSKeymap; - device->PumpEvents = AA_PumpEvents; - - device->free = AA_DeleteDevice; - - return device; + SDL_VideoDevice *device; + + /* Initialize all variables that we clean on shutdown */ + device = (SDL_VideoDevice *) SDL_malloc(sizeof(SDL_VideoDevice)); + if (device) { + SDL_memset(device, 0, (sizeof *device)); + device->hidden = (struct SDL_PrivateVideoData *) + SDL_malloc((sizeof *device->hidden)); + } + if ((device == NULL) || (device->hidden == NULL)) { + SDL_OutOfMemory(); + if (device) { + SDL_free(device); + } + return (0); + } + SDL_memset(device->hidden, 0, (sizeof *device->hidden)); + + /* Set the function pointers */ + device->VideoInit = AA_VideoInit; + device->ListModes = AA_ListModes; + device->SetVideoMode = AA_SetVideoMode; + device->CreateYUVOverlay = NULL; + device->SetColors = AA_SetColors; + device->UpdateRects = NULL; + device->VideoQuit = AA_VideoQuit; + device->AllocHWSurface = AA_AllocHWSurface; + device->CheckHWBlit = NULL; + device->FillHWRect = NULL; + device->SetHWColorKey = NULL; + device->SetHWAlpha = NULL; + device->LockHWSurface = AA_LockHWSurface; + device->UnlockHWSurface = AA_UnlockHWSurface; + device->FlipHWSurface = NULL; + device->FreeHWSurface = AA_FreeHWSurface; + device->SetCaption = NULL; + device->SetIcon = NULL; + device->IconifyWindow = NULL; + device->GrabInput = NULL; + device->GetWMInfo = NULL; + device->InitOSKeymap = AA_InitOSKeymap; + device->PumpEvents = AA_PumpEvents; + + device->free = AA_DeleteDevice; + + return device; } VideoBootStrap AALIB_bootstrap = { - "aalib", "ASCII Art Library", - AA_Available, AA_CreateDevice + "aalib", "ASCII Art Library", + AA_Available, AA_CreateDevice }; static void AA_ResizeHandler(aa_context *); -int AA_VideoInit(_THIS, SDL_PixelFormat *vformat) +int +AA_VideoInit(_THIS, SDL_PixelFormat * vformat) { - int keyboard; - int i; - - /* Initialize all variables that we clean on shutdown */ - for ( i=0; ix = SDL_modelist[i]->y = 0; - } - /* Modes sorted largest to smallest */ - SDL_modelist[0]->w = 1024; SDL_modelist[0]->h = 768; - SDL_modelist[1]->w = 800; SDL_modelist[1]->h = 600; - SDL_modelist[2]->w = 640; SDL_modelist[2]->h = 480; - SDL_modelist[3]->w = 320; SDL_modelist[3]->h = 400; - SDL_modelist[4]->w = 320; SDL_modelist[4]->h = 240; - SDL_modelist[5]->w = 320; SDL_modelist[5]->h = 200; - SDL_modelist[6] = NULL; - - /* Initialize the library */ - - AA_mutex = SDL_CreateMutex(); - - aa_parseoptions (NULL, NULL, NULL, NULL); - - AA_context = aa_autoinit(&aa_defparams); - if ( ! AA_context ) { - SDL_SetError("Unable to initialize AAlib"); - return(-1); - } - - /* Enable mouse and keyboard support */ - - if ( ! aa_autoinitkbd (AA_context, AA_SENDRELEASE) ) { - SDL_SetError("Unable to initialize AAlib keyboard"); - return(-1); - } - if ( ! aa_autoinitmouse (AA_context, AA_SENDRELEASE) ) { - fprintf(stderr,"Warning: Unable to initialize AAlib mouse"); - } - AA_rparams = aa_getrenderparams(); - - local_this = this; - - aa_resizehandler(AA_context, AA_ResizeHandler); - - fprintf(stderr,"Using AAlib driver: %s (%s)\n", AA_context->driver->name, AA_context->driver->shortname); - - AA_in_x11 = (SDL_strcmp(AA_context->driver->shortname,"X11") == 0); - /* Determine the screen depth (use default 8-bit depth) */ - vformat->BitsPerPixel = 8; - vformat->BytesPerPixel = 1; - - /* We're done! */ - return(0); + int keyboard; + int i; + + /* Initialize all variables that we clean on shutdown */ + for (i = 0; i < SDL_NUMMODES; ++i) { + SDL_modelist[i] = SDL_malloc(sizeof(SDL_Rect)); + SDL_modelist[i]->x = SDL_modelist[i]->y = 0; + } + /* Modes sorted largest to smallest */ + SDL_modelist[0]->w = 1024; + SDL_modelist[0]->h = 768; + SDL_modelist[1]->w = 800; + SDL_modelist[1]->h = 600; + SDL_modelist[2]->w = 640; + SDL_modelist[2]->h = 480; + SDL_modelist[3]->w = 320; + SDL_modelist[3]->h = 400; + SDL_modelist[4]->w = 320; + SDL_modelist[4]->h = 240; + SDL_modelist[5]->w = 320; + SDL_modelist[5]->h = 200; + SDL_modelist[6] = NULL; + + /* Initialize the library */ + + AA_mutex = SDL_CreateMutex(); + + aa_parseoptions(NULL, NULL, NULL, NULL); + + AA_context = aa_autoinit(&aa_defparams); + if (!AA_context) { + SDL_SetError("Unable to initialize AAlib"); + return (-1); + } + + /* Enable mouse and keyboard support */ + + if (!aa_autoinitkbd(AA_context, AA_SENDRELEASE)) { + SDL_SetError("Unable to initialize AAlib keyboard"); + return (-1); + } + if (!aa_autoinitmouse(AA_context, AA_SENDRELEASE)) { + fprintf(stderr, "Warning: Unable to initialize AAlib mouse"); + } + AA_rparams = aa_getrenderparams(); + + local_this = this; + + aa_resizehandler(AA_context, AA_ResizeHandler); + + fprintf(stderr, "Using AAlib driver: %s (%s)\n", + AA_context->driver->name, AA_context->driver->shortname); + + AA_in_x11 = (SDL_strcmp(AA_context->driver->shortname, "X11") == 0); + /* Determine the screen depth (use default 8-bit depth) */ + vformat->BitsPerPixel = 8; + vformat->BytesPerPixel = 1; + + /* We're done! */ + return (0); } -SDL_Rect **AA_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags) +SDL_Rect ** +AA_ListModes(_THIS, SDL_PixelFormat * format, Uint32 flags) { - if(format->BitsPerPixel != 8) - return NULL; - - if ( flags & SDL_FULLSCREEN ) { - return SDL_modelist; - } else { - return (SDL_Rect **) -1; - } + if (format->BitsPerPixel != 8) + return NULL; + + if (flags & SDL_FULLSCREEN) { + return SDL_modelist; + } else { + return (SDL_Rect **) - 1; + } } /* From aavga.c AAlib does not give us the choice of the actual resolution, thus we have to simulate additional resolution by scaling down manually each frame */ -static void fastscale (register char *b1, register char *b2, int x1, int x2, int y1, int y2) +static void +fastscale(register char *b1, register char *b2, int x1, int x2, int y1, + int y2) { - register int ex, spx = 0, ddx, ddx1; - int ddy1, ddy, spy = 0, ey; - int x; - char *bb1 = b1; - if (!x1 || !x2 || !y1 || !y2) - return; - ddx = x1 + x1; - ddx1 = x2 + x2; - if (ddx1 < ddx) - spx = ddx / ddx1, ddx %= ddx1; - ddy = y1 + y1; - ddy1 = y2 + y2; - if (ddy1 < ddy) - spy = (ddy / ddy1) * x1, ddy %= ddy1; - ey = -ddy1; - for (; y2; y2--) { - ex = -ddx1; - for (x = x2; x; x--) { - *b2 = *b1; - b2++; - b1 += spx; - ex += ddx; - if (ex > 0) { - b1++; - ex -= ddx1; - } - } - bb1 += spy; - ey += ddy; - if (ey > 0) { - bb1 += x1; - ey -= ddy1; - } - b1 = bb1; - } + register int ex, spx = 0, ddx, ddx1; + int ddy1, ddy, spy = 0, ey; + int x; + char *bb1 = b1; + if (!x1 || !x2 || !y1 || !y2) + return; + ddx = x1 + x1; + ddx1 = x2 + x2; + if (ddx1 < ddx) + spx = ddx / ddx1, ddx %= ddx1; + ddy = y1 + y1; + ddy1 = y2 + y2; + if (ddy1 < ddy) + spy = (ddy / ddy1) * x1, ddy %= ddy1; + ey = -ddy1; + for (; y2; y2--) { + ex = -ddx1; + for (x = x2; x; x--) { + *b2 = *b1; + b2++; + b1 += spx; + ex += ddx; + if (ex > 0) { + b1++; + ex -= ddx1; + } + } + bb1 += spy; + ey += ddy; + if (ey > 0) { + bb1 += x1; + ey -= ddy1; + } + b1 = bb1; + } } /* Various screen update functions available */ -static void AA_DirectUpdate(_THIS, int numrects, SDL_Rect *rects); +static void AA_DirectUpdate(_THIS, int numrects, SDL_Rect * rects); -SDL_Surface *AA_SetVideoMode(_THIS, SDL_Surface *current, - int width, int height, int bpp, Uint32 flags) +SDL_Surface * +AA_SetVideoMode(_THIS, SDL_Surface * current, + int width, int height, int bpp, Uint32 flags) { - int mode; + int mode; - if ( AA_buffer ) { - SDL_free( AA_buffer ); - } + if (AA_buffer) { + SDL_free(AA_buffer); + } - AA_buffer = SDL_malloc(width * height); - if ( ! AA_buffer ) { - SDL_SetError("Couldn't allocate buffer for requested mode"); - return(NULL); - } + AA_buffer = SDL_malloc(width * height); + if (!AA_buffer) { + SDL_SetError("Couldn't allocate buffer for requested mode"); + return (NULL); + } /* printf("Setting mode %dx%d\n", width, height); */ - SDL_memset(aa_image(AA_context), 0, aa_imgwidth(AA_context) * aa_imgheight(AA_context)); - SDL_memset(AA_buffer, 0, width * height); + SDL_memset(aa_image(AA_context), 0, + aa_imgwidth(AA_context) * aa_imgheight(AA_context)); + SDL_memset(AA_buffer, 0, width * height); - /* Allocate the new pixel format for the screen */ - if ( ! SDL_ReallocFormat(current, 8, 0, 0, 0, 0) ) { - return(NULL); - } + /* Allocate the new pixel format for the screen */ + if (!SDL_ReallocFormat(current, 8, 0, 0, 0, 0)) { + return (NULL); + } - /* Set up the new mode framebuffer */ - current->flags = SDL_FULLSCREEN; - AA_w = current->w = width; - AA_h = current->h = height; - current->pitch = current->w; - current->pixels = AA_buffer; + /* Set up the new mode framebuffer */ + current->flags = SDL_FULLSCREEN; + AA_w = current->w = width; + AA_h = current->h = height; + current->pitch = current->w; + current->pixels = AA_buffer; - AA_x_ratio = ((double)aa_imgwidth(AA_context)) / ((double)width); - AA_y_ratio = ((double)aa_imgheight(AA_context)) / ((double)height); + AA_x_ratio = ((double) aa_imgwidth(AA_context)) / ((double) width); + AA_y_ratio = ((double) aa_imgheight(AA_context)) / ((double) height); - /* Set the blit function */ - this->UpdateRects = AA_DirectUpdate; + /* Set the blit function */ + this->UpdateRects = AA_DirectUpdate; - /* We're done */ - return(current); + /* We're done */ + return (current); } -static void AA_ResizeHandler(aa_context *context) +static void +AA_ResizeHandler(aa_context * context) { - aa_resize(context); - local_this->hidden->x_ratio = ((double)aa_imgwidth(context)) / ((double)local_this->screen->w); - local_this->hidden->y_ratio = ((double)aa_imgheight(context)) / ((double)local_this->screen->h); - - fastscale (local_this->hidden->buffer, aa_image(context), local_this->hidden->w, aa_imgwidth (context), local_this->hidden->h, aa_imgheight (context)); - aa_renderpalette(context, local_this->hidden->palette, local_this->hidden->rparams, 0, 0, aa_scrwidth(context), aa_scrheight(context)); - aa_flush(context); + aa_resize(context); + local_this->hidden->x_ratio = + ((double) aa_imgwidth(context)) / ((double) local_this->screen->w); + local_this->hidden->y_ratio = + ((double) aa_imgheight(context)) / ((double) local_this->screen->h); + + fastscale(local_this->hidden->buffer, aa_image(context), + local_this->hidden->w, aa_imgwidth(context), + local_this->hidden->h, aa_imgheight(context)); + aa_renderpalette(context, local_this->hidden->palette, + local_this->hidden->rparams, 0, 0, + aa_scrwidth(context), aa_scrheight(context)); + aa_flush(context); } /* We don't actually allow hardware surfaces other than the main one */ -static int AA_AllocHWSurface(_THIS, SDL_Surface *surface) +static int +AA_AllocHWSurface(_THIS, SDL_Surface * surface) { - return(-1); + return (-1); } -static void AA_FreeHWSurface(_THIS, SDL_Surface *surface) +static void +AA_FreeHWSurface(_THIS, SDL_Surface * surface) { - return; + return; } /* We need to wait for vertical retrace on page flipped displays */ -static int AA_LockHWSurface(_THIS, SDL_Surface *surface) +static int +AA_LockHWSurface(_THIS, SDL_Surface * surface) { - /* TODO ? */ - return(0); + /* TODO ? */ + return (0); } -static void AA_UnlockHWSurface(_THIS, SDL_Surface *surface) +static void +AA_UnlockHWSurface(_THIS, SDL_Surface * surface) { - return; + return; } /* FIXME: How is this done with AAlib? */ -static int AA_FlipHWSurface(_THIS, SDL_Surface *surface) +static int +AA_FlipHWSurface(_THIS, SDL_Surface * surface) { - SDL_mutexP(AA_mutex); - aa_flush(AA_context); - SDL_mutexV(AA_mutex); - return(0); + SDL_mutexP(AA_mutex); + aa_flush(AA_context); + SDL_mutexV(AA_mutex); + return (0); } -static void AA_DirectUpdate(_THIS, int numrects, SDL_Rect *rects) +static void +AA_DirectUpdate(_THIS, int numrects, SDL_Rect * rects) { - int i; - SDL_Rect *rect; + int i; + SDL_Rect *rect; - fastscale (AA_buffer, aa_image(AA_context), AA_w, aa_imgwidth (AA_context), AA_h, aa_imgheight (AA_context)); + fastscale(AA_buffer, aa_image(AA_context), AA_w, + aa_imgwidth(AA_context), AA_h, aa_imgheight(AA_context)); #if 1 - aa_renderpalette(AA_context, AA_palette, AA_rparams, 0, 0, aa_scrwidth(AA_context), aa_scrheight(AA_context)); + aa_renderpalette(AA_context, AA_palette, AA_rparams, 0, 0, + aa_scrwidth(AA_context), aa_scrheight(AA_context)); #else - /* Render only the rectangles in the list */ - printf("Update rects : "); - for ( i=0; i < numrects; ++i ) { - rect = &rects[i]; - printf("(%d,%d-%d,%d)", rect->x, rect->y, rect->w, rect->h); - aa_renderpalette(AA_context, AA_palette, AA_rparams, rect->x * AA_x_ratio, rect->y * AA_y_ratio, rect->w * AA_x_ratio, rect->h * AA_y_ratio); - } - printf("\n"); + /* Render only the rectangles in the list */ + printf("Update rects : "); + for (i = 0; i < numrects; ++i) { + rect = &rects[i]; + printf("(%d,%d-%d,%d)", rect->x, rect->y, rect->w, rect->h); + aa_renderpalette(AA_context, AA_palette, AA_rparams, + rect->x * AA_x_ratio, rect->y * AA_y_ratio, + rect->w * AA_x_ratio, rect->h * AA_y_ratio); + } + printf("\n"); #endif - SDL_mutexP(AA_mutex); - aa_flush(AA_context); - SDL_mutexV(AA_mutex); - return; + SDL_mutexP(AA_mutex); + aa_flush(AA_context); + SDL_mutexV(AA_mutex); + return; } -int AA_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color *colors) +int +AA_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color * colors) { - int i; - - for ( i=0; i < ncolors; i++ ) { - aa_setpalette(AA_palette, firstcolor + i, - colors[i].r>>2, - colors[i].g>>2, - colors[i].b>>2); - } - return(1); + int i; + + for (i = 0; i < ncolors; i++) { + aa_setpalette(AA_palette, firstcolor + i, + colors[i].r >> 2, colors[i].g >> 2, colors[i].b >> 2); + } + return (1); } /* Note: If we are terminated, this could be called in the middle of another SDL video routine -- notably UpdateRects. */ -void AA_VideoQuit(_THIS) +void +AA_VideoQuit(_THIS) { - int i; + int i; - aa_uninitkbd(AA_context); - aa_uninitmouse(AA_context); + aa_uninitkbd(AA_context); + aa_uninitmouse(AA_context); - /* Free video mode lists */ - for ( i=0; iscreen->pixels = NULL; + SDL_DestroyMutex(AA_mutex); + + this->screen->pixels = NULL; } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/aalib/SDL_aavideo.h b/src/video/aalib/SDL_aavideo.h index cd70c9f16..07f9d84af 100644 --- a/src/video/aalib/SDL_aavideo.h +++ b/src/video/aalib/SDL_aavideo.h @@ -36,12 +36,13 @@ #define SDL_NUMMODES 6 /* Private display data */ -struct SDL_PrivateVideoData { - SDL_Rect *SDL_modelist[SDL_NUMMODES+1]; - aa_context *context; - aa_palette palette; - aa_renderparams *rparams; - double x_ratio, y_ratio; +struct SDL_PrivateVideoData +{ + SDL_Rect *SDL_modelist[SDL_NUMMODES + 1]; + aa_context *context; + aa_palette palette; + aa_renderparams *rparams; + double x_ratio, y_ratio; int w, h; SDL_mutex *mutex; int in_x11; @@ -64,3 +65,4 @@ struct SDL_PrivateVideoData { #define AA_h (this->hidden->h) #endif /* _SDL_aavideo_h */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/ataricommon/SDL_ataric2p_s.h b/src/video/ataricommon/SDL_ataric2p_s.h index a8f97e2ef..e56e81657 100644 --- a/src/video/ataricommon/SDL_ataric2p_s.h +++ b/src/video/ataricommon/SDL_ataric2p_s.h @@ -30,46 +30,41 @@ /* Convert a chunky screen to bitplane screen */ -extern void (*SDL_Atari_C2pConvert)( - Uint8 *src, /* Source screen (one byte=one pixel) */ - Uint8 *dest, /* Destination (4/8 bits planes) */ - Uint32 width, /* Dimensions of screen to convert */ - Uint32 height, - Uint32 dblligne, /* Double the lines when converting ? */ - Uint32 srcpitch, /* Length of one source line in bytes */ - Uint32 dstpitch /* Length of one destination line in bytes */ -); +extern void (*SDL_Atari_C2pConvert) (Uint8 * src, /* Source screen (one byte=one pixel) */ + Uint8 * dest, /* Destination (4/8 bits planes) */ + Uint32 width, /* Dimensions of screen to convert */ + Uint32 height, Uint32 dblligne, /* Double the lines when converting ? */ + Uint32 srcpitch, /* Length of one source line in bytes */ + Uint32 dstpitch /* Length of one destination line in bytes */ + ); /*--- 8 bits functions ---*/ /* Convert a chunky screen to bitplane screen */ -void SDL_Atari_C2pConvert8( - Uint8 *src, /* Source screen (one byte=one pixel) */ - Uint8 *dest, /* Destination (8 bits planes) */ - Uint32 width, /* Dimensions of screen to convert */ - Uint32 height, - Uint32 dblligne, /* Double the lines when converting ? */ - Uint32 srcpitch, /* Length of one source line in bytes */ - Uint32 dstpitch /* Length of one destination line in bytes */ -); +void SDL_Atari_C2pConvert8(Uint8 * src, /* Source screen (one byte=one pixel) */ + Uint8 * dest, /* Destination (8 bits planes) */ + Uint32 width, /* Dimensions of screen to convert */ + Uint32 height, Uint32 dblligne, /* Double the lines when converting ? */ + Uint32 srcpitch, /* Length of one source line in bytes */ + Uint32 dstpitch /* Length of one destination line in bytes */ + ); /*--- 4 bits functions ---*/ /* Convert a chunky screen to bitplane screen */ -void SDL_Atari_C2pConvert4( - Uint8 *src, /* Source screen (one byte=one pixel) */ - Uint8 *dest, /* Destination (4 bits planes) */ - Uint32 width, /* Dimensions of screen to convert */ - Uint32 height, - Uint32 dblligne, /* Double the lines when converting ? */ - Uint32 srcpitch, /* Length of one source line in bytes */ - Uint32 dstpitch /* Length of one destination line in bytes */ -); +void SDL_Atari_C2pConvert4(Uint8 * src, /* Source screen (one byte=one pixel) */ + Uint8 * dest, /* Destination (4 bits planes) */ + Uint32 width, /* Dimensions of screen to convert */ + Uint32 height, Uint32 dblligne, /* Double the lines when converting ? */ + Uint32 srcpitch, /* Length of one source line in bytes */ + Uint32 dstpitch /* Length of one destination line in bytes */ + ); /* Conversion palette */ -void SDL_Atari_C2pConvert4_pal(Uint16 *lightpalette); +void SDL_Atari_C2pConvert4_pal(Uint16 * lightpalette); #endif /* _ATARI_C2P_h */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/ataricommon/SDL_ataridevmouse.c b/src/video/ataricommon/SDL_ataridevmouse.c index b1e735727..97fb5a829 100644 --- a/src/video/ataricommon/SDL_ataridevmouse.c +++ b/src/video/ataricommon/SDL_ataridevmouse.c @@ -44,116 +44,123 @@ static int mouseb, prev_mouseb; /* Functions */ -int SDL_AtariDevMouse_Open(void) +int +SDL_AtariDevMouse_Open(void) { - int r; - const char *mousedev; - - /* - TODO: Fix the MiNT device driver, that locks mouse for other - applications, so this is disabled till fixed - */ - return 0; - - /* First, try SDL_MOUSEDEV device */ - mousedev = SDL_getenv("SDL_MOUSEDEV"); - if (!mousedev) { - handle = open(mousedev, 0); - } - - /* Failed, try default device */ - if (handle<0) { - handle = open(DEVICE_NAME, 0); - } - - if (handle<0) { - handle = -1; - return 0; - } - - /* Set non blocking mode */ - r = fcntl(handle, F_GETFL, 0); - if (r<0) { - close(handle); - handle = -1; - return 0; - } - - r |= O_NDELAY; - - r = fcntl(handle, F_SETFL, r); - if (r<0) { - close(handle); - handle = -1; - return 0; - } - - prev_mouseb = 7; - return 1; + int r; + const char *mousedev; + + /* + TODO: Fix the MiNT device driver, that locks mouse for other + applications, so this is disabled till fixed + */ + return 0; + + /* First, try SDL_MOUSEDEV device */ + mousedev = SDL_getenv("SDL_MOUSEDEV"); + if (!mousedev) { + handle = open(mousedev, 0); + } + + /* Failed, try default device */ + if (handle < 0) { + handle = open(DEVICE_NAME, 0); + } + + if (handle < 0) { + handle = -1; + return 0; + } + + /* Set non blocking mode */ + r = fcntl(handle, F_GETFL, 0); + if (r < 0) { + close(handle); + handle = -1; + return 0; + } + + r |= O_NDELAY; + + r = fcntl(handle, F_SETFL, r); + if (r < 0) { + close(handle); + handle = -1; + return 0; + } + + prev_mouseb = 7; + return 1; } -void SDL_AtariDevMouse_Close(void) +void +SDL_AtariDevMouse_Close(void) { - if (handle>0) { - close(handle); - handle = -1; - } + if (handle > 0) { + close(handle); + handle = -1; + } } -static int atari_GetButton(int button) +static int +atari_GetButton(int button) { - switch(button) - { - case 0: - return SDL_BUTTON_RIGHT; - case 1: - return SDL_BUTTON_MIDDLE; - default: - break; - } - - return SDL_BUTTON_LEFT; + switch (button) { + case 0: + return SDL_BUTTON_RIGHT; + case 1: + return SDL_BUTTON_MIDDLE; + default: + break; + } + + return SDL_BUTTON_LEFT; } -void SDL_AtariDevMouse_PostMouseEvents(_THIS, SDL_bool buttonEvents) +void +SDL_AtariDevMouse_PostMouseEvents(_THIS, SDL_bool buttonEvents) { - unsigned char buffer[3]; - int mousex, mousey; - - if (handle<0) { - return; - } - - mousex = mousey = 0; - while (read(handle, buffer, sizeof(buffer))==sizeof(buffer)) { - mouseb = buffer[0] & 7; - mousex += (char) buffer[1]; - mousey += (char) buffer[2]; - - /* Mouse button events */ - if (buttonEvents && (mouseb != prev_mouseb)) { - int i; - - for (i=0;i<3;i++) { - int curbutton, prevbutton; - - curbutton = mouseb & (1<>= 16; - - /* Default is Ikbd, the faster except for clones */ - switch(cookie_mch) { - case MCH_ST: - case MCH_STE: - case MCH_TT: - case MCH_F30: - case MCH_ARANYM: - this->InitOSKeymap=AtariIkbd_InitOSKeymap; - this->PumpEvents=AtariIkbd_PumpEvents; - Atari_ShutdownEvents=AtariIkbd_ShutdownEvents; - break; - default: - this->InitOSKeymap=AtariGemdos_InitOSKeymap; - this->PumpEvents=AtariGemdos_PumpEvents; - Atari_ShutdownEvents=AtariGemdos_ShutdownEvents; - break; - } - - envr = SDL_getenv("SDL_ATARI_EVENTSDRIVER"); - - if (!envr) { - return; - } - - if (SDL_strcmp(envr, "ikbd") == 0) { - this->InitOSKeymap=AtariIkbd_InitOSKeymap; - this->PumpEvents=AtariIkbd_PumpEvents; - Atari_ShutdownEvents=AtariIkbd_ShutdownEvents; - } - - if (SDL_strcmp(envr, "gemdos") == 0) { - this->InitOSKeymap=AtariGemdos_InitOSKeymap; - this->PumpEvents=AtariGemdos_PumpEvents; - Atari_ShutdownEvents=AtariGemdos_ShutdownEvents; - } - - if (SDL_strcmp(envr, "bios") == 0) { - this->InitOSKeymap=AtariBios_InitOSKeymap; - this->PumpEvents=AtariBios_PumpEvents; - Atari_ShutdownEvents=AtariBios_ShutdownEvents; - } + const char *envr; + unsigned long cookie_mch; + + /* Test if we are on an Atari machine or not */ + if (Getcookie(C__MCH, &cookie_mch) == C_NOTFOUND) { + cookie_mch = 0; + } + cookie_mch >>= 16; + + /* Default is Ikbd, the faster except for clones */ + switch (cookie_mch) { + case MCH_ST: + case MCH_STE: + case MCH_TT: + case MCH_F30: + case MCH_ARANYM: + this->InitOSKeymap = AtariIkbd_InitOSKeymap; + this->PumpEvents = AtariIkbd_PumpEvents; + Atari_ShutdownEvents = AtariIkbd_ShutdownEvents; + break; + default: + this->InitOSKeymap = AtariGemdos_InitOSKeymap; + this->PumpEvents = AtariGemdos_PumpEvents; + Atari_ShutdownEvents = AtariGemdos_ShutdownEvents; + break; + } + + envr = SDL_getenv("SDL_ATARI_EVENTSDRIVER"); + + if (!envr) { + return; + } + + if (SDL_strcmp(envr, "ikbd") == 0) { + this->InitOSKeymap = AtariIkbd_InitOSKeymap; + this->PumpEvents = AtariIkbd_PumpEvents; + Atari_ShutdownEvents = AtariIkbd_ShutdownEvents; + } + + if (SDL_strcmp(envr, "gemdos") == 0) { + this->InitOSKeymap = AtariGemdos_InitOSKeymap; + this->PumpEvents = AtariGemdos_PumpEvents; + Atari_ShutdownEvents = AtariGemdos_ShutdownEvents; + } + + if (SDL_strcmp(envr, "bios") == 0) { + this->InitOSKeymap = AtariBios_InitOSKeymap; + this->PumpEvents = AtariBios_PumpEvents; + Atari_ShutdownEvents = AtariBios_ShutdownEvents; + } } -void Atari_InitOSKeymap(_THIS) +void +Atari_InitOSKeymap(_THIS) { - Atari_InitializeEvents(this); + Atari_InitializeEvents(this); - /* Call choosen routine */ - this->InitOSKeymap(this); + /* Call choosen routine */ + this->InitOSKeymap(this); } -void Atari_PumpEvents(_THIS) +void +Atari_PumpEvents(_THIS) { - Atari_InitializeEvents(this); + Atari_InitializeEvents(this); - /* Call choosen routine */ - this->PumpEvents(this); + /* Call choosen routine */ + this->PumpEvents(this); } /* Atari to Unicode charset translation table */ -Uint16 SDL_AtariToUnicodeTable[256]={ - /* Standard ASCII characters from 0x00 to 0x7e */ - /* Unicode stuff from 0x7f to 0xff */ - - 0x0000,0x0001,0x0002,0x0003,0x0004,0x0005,0x0006,0x0007, - 0x0008,0x0009,0x000A,0x000B,0x000C,0x000D,0x000E,0x000F, - 0x0010,0x0011,0x0012,0x0013,0x0014,0x0015,0x0016,0x0017, - 0x0018,0x0019,0x001A,0x001B,0x001C,0x001D,0x001E,0x001F, - 0x0020,0x0021,0x0022,0x0023,0x0024,0x0025,0x0026,0x0027, - 0x0028,0x0029,0x002A,0x002B,0x002C,0x002D,0x002E,0x002F, - 0x0030,0x0031,0x0032,0x0033,0x0034,0x0035,0x0036,0x0037, - 0x0038,0x0039,0x003A,0x003B,0x003C,0x003D,0x003E,0x003F, - - 0x0040,0x0041,0x0042,0x0043,0x0044,0x0045,0x0046,0x0047, - 0x0048,0x0049,0x004A,0x004B,0x004C,0x004D,0x004E,0x004F, - 0x0050,0x0051,0x0052,0x0053,0x0054,0x0055,0x0056,0x0057, - 0x0058,0x0059,0x005A,0x005B,0x005C,0x005D,0x005E,0x005F, - 0x0060,0x0061,0x0062,0x0063,0x0064,0x0065,0x0066,0x0067, - 0x0068,0x0069,0x006A,0x006B,0x006C,0x006D,0x006E,0x006F, - 0x0070,0x0071,0x0072,0x0073,0x0074,0x0075,0x0076,0x0077, - 0x0078,0x0079,0x007A,0x007B,0x007C,0x007D,0x007E,0x0394, - - 0x00C7,0x00FC,0x00E9,0x00E2,0x00E4,0x00E0,0x00E5,0x00E7, - 0x00EA,0x00EB,0x00E8,0x00EF,0x00EE,0x00EC,0x00C4,0x00C5, - 0x00C9,0x00E6,0x00C6,0x00F4,0x00F6,0x00F2,0x00FB,0x00F9, - 0x00FF,0x00D6,0x00DC,0x00A2,0x00A3,0x00A5,0x00DF,0x0192, - 0x00E1,0x00ED,0x00F3,0x00FA,0x00F1,0x00D1,0x00AA,0x00BA, - 0x00BF,0x2310,0x00AC,0x00BD,0x00BC,0x00A1,0x00AB,0x00BB, - 0x00C3,0x00F5,0x00D8,0x00F8,0x0153,0x0152,0x00C0,0x00C3, - 0x00D5,0x00A8,0x00B4,0x2020,0x00B6,0x00A9,0x00AE,0x2122, - - 0x0133,0x0132,0x05D0,0x05D1,0x05D2,0x05D3,0x05D4,0x05D5, - 0x05D6,0x05D7,0x05D8,0x05D9,0x05DB,0x05DC,0x05DE,0x05E0, - 0x05E1,0x05E2,0x05E4,0x05E6,0x05E7,0x05E8,0x05E9,0x05EA, - 0x05DF,0x05DA,0x05DD,0x05E3,0x05E5,0x00A7,0x2038,0x221E, - 0x03B1,0x03B2,0x0393,0x03C0,0x03A3,0x03C3,0x00B5,0x03C4, - 0x03A6,0x0398,0x03A9,0x03B4,0x222E,0x03C6,0x2208,0x2229, - 0x2261,0x00B1,0x2265,0x2264,0x2320,0x2321,0x00F7,0x2248, - 0x00B0,0x2022,0x00B7,0x221A,0x207F,0x00B2,0x00B3,0x00AF +Uint16 SDL_AtariToUnicodeTable[256] = { + /* Standard ASCII characters from 0x00 to 0x7e */ + /* Unicode stuff from 0x7f to 0xff */ + + 0x0000, 0x0001, 0x0002, 0x0003, 0x0004, 0x0005, 0x0006, 0x0007, + 0x0008, 0x0009, 0x000A, 0x000B, 0x000C, 0x000D, 0x000E, 0x000F, + 0x0010, 0x0011, 0x0012, 0x0013, 0x0014, 0x0015, 0x0016, 0x0017, + 0x0018, 0x0019, 0x001A, 0x001B, 0x001C, 0x001D, 0x001E, 0x001F, + 0x0020, 0x0021, 0x0022, 0x0023, 0x0024, 0x0025, 0x0026, 0x0027, + 0x0028, 0x0029, 0x002A, 0x002B, 0x002C, 0x002D, 0x002E, 0x002F, + 0x0030, 0x0031, 0x0032, 0x0033, 0x0034, 0x0035, 0x0036, 0x0037, + 0x0038, 0x0039, 0x003A, 0x003B, 0x003C, 0x003D, 0x003E, 0x003F, + + 0x0040, 0x0041, 0x0042, 0x0043, 0x0044, 0x0045, 0x0046, 0x0047, + 0x0048, 0x0049, 0x004A, 0x004B, 0x004C, 0x004D, 0x004E, 0x004F, + 0x0050, 0x0051, 0x0052, 0x0053, 0x0054, 0x0055, 0x0056, 0x0057, + 0x0058, 0x0059, 0x005A, 0x005B, 0x005C, 0x005D, 0x005E, 0x005F, + 0x0060, 0x0061, 0x0062, 0x0063, 0x0064, 0x0065, 0x0066, 0x0067, + 0x0068, 0x0069, 0x006A, 0x006B, 0x006C, 0x006D, 0x006E, 0x006F, + 0x0070, 0x0071, 0x0072, 0x0073, 0x0074, 0x0075, 0x0076, 0x0077, + 0x0078, 0x0079, 0x007A, 0x007B, 0x007C, 0x007D, 0x007E, 0x0394, + + 0x00C7, 0x00FC, 0x00E9, 0x00E2, 0x00E4, 0x00E0, 0x00E5, 0x00E7, + 0x00EA, 0x00EB, 0x00E8, 0x00EF, 0x00EE, 0x00EC, 0x00C4, 0x00C5, + 0x00C9, 0x00E6, 0x00C6, 0x00F4, 0x00F6, 0x00F2, 0x00FB, 0x00F9, + 0x00FF, 0x00D6, 0x00DC, 0x00A2, 0x00A3, 0x00A5, 0x00DF, 0x0192, + 0x00E1, 0x00ED, 0x00F3, 0x00FA, 0x00F1, 0x00D1, 0x00AA, 0x00BA, + 0x00BF, 0x2310, 0x00AC, 0x00BD, 0x00BC, 0x00A1, 0x00AB, 0x00BB, + 0x00C3, 0x00F5, 0x00D8, 0x00F8, 0x0153, 0x0152, 0x00C0, 0x00C3, + 0x00D5, 0x00A8, 0x00B4, 0x2020, 0x00B6, 0x00A9, 0x00AE, 0x2122, + + 0x0133, 0x0132, 0x05D0, 0x05D1, 0x05D2, 0x05D3, 0x05D4, 0x05D5, + 0x05D6, 0x05D7, 0x05D8, 0x05D9, 0x05DB, 0x05DC, 0x05DE, 0x05E0, + 0x05E1, 0x05E2, 0x05E4, 0x05E6, 0x05E7, 0x05E8, 0x05E9, 0x05EA, + 0x05DF, 0x05DA, 0x05DD, 0x05E3, 0x05E5, 0x00A7, 0x2038, 0x221E, + 0x03B1, 0x03B2, 0x0393, 0x03C0, 0x03A3, 0x03C3, 0x00B5, 0x03C4, + 0x03A6, 0x0398, 0x03A9, 0x03B4, 0x222E, 0x03C6, 0x2208, 0x2229, + 0x2261, 0x00B1, 0x2265, 0x2264, 0x2320, 0x2321, 0x00F7, 0x2248, + 0x00B0, 0x2022, 0x00B7, 0x221A, 0x207F, 0x00B2, 0x00B3, 0x00AF }; + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/ataricommon/SDL_atarievents_c.h b/src/video/ataricommon/SDL_atarievents_c.h index 527b91c15..8f6193633 100644 --- a/src/video/ataricommon/SDL_atarievents_c.h +++ b/src/video/ataricommon/SDL_atarievents_c.h @@ -35,7 +35,7 @@ /* Hidden "this" pointer for the video functions */ #define _THIS SDL_VideoDevice *this -extern void (*Atari_ShutdownEvents)(void); +extern void (*Atari_ShutdownEvents) (void); extern void Atari_InitOSKeymap(_THIS); extern void Atari_PumpEvents(_THIS); @@ -44,3 +44,4 @@ extern void Atari_PumpEvents(_THIS); extern Uint16 SDL_AtariToUnicodeTable[256]; #endif /* _SDL_ATARI_EVENTS_H_ */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/ataricommon/SDL_atarigl.c b/src/video/ataricommon/SDL_atarigl.c index 9cc8d2256..8c9538c4a 100644 --- a/src/video/ataricommon/SDL_atarigl.c +++ b/src/video/ataricommon/SDL_atarigl.c @@ -51,1038 +51,1077 @@ static void SDL_AtariGL_UnloadLibrary(_THIS); #if SDL_VIDEO_OPENGL -static void CopyShadowNull(_THIS, SDL_Surface *surface); -static void CopyShadowDirect(_THIS, SDL_Surface *surface); -static void CopyShadowRGBTo555(_THIS, SDL_Surface *surface); -static void CopyShadowRGBTo565(_THIS, SDL_Surface *surface); -static void CopyShadowRGBSwap(_THIS, SDL_Surface *surface); -static void CopyShadowRGBToARGB(_THIS, SDL_Surface *surface); -static void CopyShadowRGBToABGR(_THIS, SDL_Surface *surface); -static void CopyShadowRGBToBGRA(_THIS, SDL_Surface *surface); -static void CopyShadowRGBToRGBA(_THIS, SDL_Surface *surface); -static void CopyShadow8888To555(_THIS, SDL_Surface *surface); -static void CopyShadow8888To565(_THIS, SDL_Surface *surface); - -static void ConvertNull(_THIS, SDL_Surface *surface); -static void Convert565To555be(_THIS, SDL_Surface *surface); -static void Convert565To555le(_THIS, SDL_Surface *surface); -static void Convert565le(_THIS, SDL_Surface *surface); -static void ConvertBGRAToABGR(_THIS, SDL_Surface *surface); - -static int InitNew(_THIS, SDL_Surface *current); -static int InitOld(_THIS, SDL_Surface *current); +static void CopyShadowNull(_THIS, SDL_Surface * surface); +static void CopyShadowDirect(_THIS, SDL_Surface * surface); +static void CopyShadowRGBTo555(_THIS, SDL_Surface * surface); +static void CopyShadowRGBTo565(_THIS, SDL_Surface * surface); +static void CopyShadowRGBSwap(_THIS, SDL_Surface * surface); +static void CopyShadowRGBToARGB(_THIS, SDL_Surface * surface); +static void CopyShadowRGBToABGR(_THIS, SDL_Surface * surface); +static void CopyShadowRGBToBGRA(_THIS, SDL_Surface * surface); +static void CopyShadowRGBToRGBA(_THIS, SDL_Surface * surface); +static void CopyShadow8888To555(_THIS, SDL_Surface * surface); +static void CopyShadow8888To565(_THIS, SDL_Surface * surface); + +static void ConvertNull(_THIS, SDL_Surface * surface); +static void Convert565To555be(_THIS, SDL_Surface * surface); +static void Convert565To555le(_THIS, SDL_Surface * surface); +static void Convert565le(_THIS, SDL_Surface * surface); +static void ConvertBGRAToABGR(_THIS, SDL_Surface * surface); + +static int InitNew(_THIS, SDL_Surface * current); +static int InitOld(_THIS, SDL_Surface * current); #endif /*--- Public functions ---*/ -int SDL_AtariGL_Init(_THIS, SDL_Surface *current) +int +SDL_AtariGL_Init(_THIS, SDL_Surface * current) { #if SDL_VIDEO_OPENGL - if (gl_oldmesa) { - gl_active = InitOld(this, current); - } else { - gl_active = InitNew(this, current); - } + if (gl_oldmesa) { + gl_active = InitOld(this, current); + } else { + gl_active = InitNew(this, current); + } #endif - return (gl_active); + return (gl_active); } -void SDL_AtariGL_Quit(_THIS, SDL_bool unload) +void +SDL_AtariGL_Quit(_THIS, SDL_bool unload) { #if SDL_VIDEO_OPENGL - if (gl_oldmesa) { - /* Old mesa implementations */ - if (this->gl_data->OSMesaDestroyLDG) { - this->gl_data->OSMesaDestroyLDG(); - } - if (gl_shadow) { - Mfree(gl_shadow); - gl_shadow = NULL; - } - } else { - /* New mesa implementation */ - if (gl_ctx) { - if (this->gl_data->OSMesaDestroyContext) { - this->gl_data->OSMesaDestroyContext(gl_ctx); - } - gl_ctx = NULL; - } - } - - if (unload) { - SDL_AtariGL_UnloadLibrary(this); - } - + if (gl_oldmesa) { + /* Old mesa implementations */ + if (this->gl_data->OSMesaDestroyLDG) { + this->gl_data->OSMesaDestroyLDG(); + } + if (gl_shadow) { + Mfree(gl_shadow); + gl_shadow = NULL; + } + } else { + /* New mesa implementation */ + if (gl_ctx) { + if (this->gl_data->OSMesaDestroyContext) { + this->gl_data->OSMesaDestroyContext(gl_ctx); + } + gl_ctx = NULL; + } + } + + if (unload) { + SDL_AtariGL_UnloadLibrary(this); + } #endif /* SDL_VIDEO_OPENGL */ - gl_active = 0; + gl_active = 0; } -int SDL_AtariGL_LoadLibrary(_THIS, const char *path) +int +SDL_AtariGL_LoadLibrary(_THIS, const char *path) { #if SDL_VIDEO_OPENGL #if SDL_VIDEO_OPENGL_OSMESA_DYNAMIC - void *handle; - SDL_bool cancel_load; - - if (gl_active) { - SDL_SetError("OpenGL context already created"); - return -1; - } - - /* Unload previous driver */ - SDL_AtariGL_UnloadLibrary(this); - - /* Load library given by path */ - handle = SDL_LoadObject(path); - if (handle == NULL) { - /* Try to load another one */ - path = SDL_getenv("SDL_VIDEO_GL_DRIVER"); - if ( path != NULL ) { - handle = SDL_LoadObject(path); - } - - /* If it does not work, try some other */ - if (handle == NULL) { - path = PATH_OSMESA_LDG; - handle = SDL_LoadObject(path); - } - - if (handle == NULL) { - path = PATH_MESAGL_LDG; - handle = SDL_LoadObject(path); - } - - if (handle == NULL) { - path = PATH_TINYGL_LDG; - handle = SDL_LoadObject(path); - } - } - - if (handle == NULL) { - SDL_SetError("Could not load OpenGL library"); - return -1; - } - - this->gl_data->glGetIntegerv = SDL_LoadFunction(handle, "glGetIntegerv"); - this->gl_data->glFinish = SDL_LoadFunction(handle, "glFinish"); - this->gl_data->glFlush = SDL_LoadFunction(handle, "glFlush"); - - cancel_load = SDL_FALSE; - if (this->gl_data->glGetIntegerv == NULL) { - cancel_load = SDL_TRUE; - } else { - /* We need either glFinish (OSMesa) or glFlush (TinyGL) */ - if ((this->gl_data->glFinish == NULL) && - (this->gl_data->glFlush == NULL)) { - cancel_load = SDL_TRUE; - } - } - if (cancel_load) { - SDL_SetError("Could not retrieve OpenGL functions"); - SDL_UnloadObject(handle); - /* Restore pointers to static library */ - SDL_AtariGL_InitPointers(this); - return -1; - } - - /* Load functions pointers (osmesa.ldg) */ - this->gl_data->OSMesaCreateContextExt = SDL_LoadFunction(handle, "OSMesaCreateContextExt"); - this->gl_data->OSMesaDestroyContext = SDL_LoadFunction(handle, "OSMesaDestroyContext"); - this->gl_data->OSMesaMakeCurrent = SDL_LoadFunction(handle, "OSMesaMakeCurrent"); - this->gl_data->OSMesaPixelStore = SDL_LoadFunction(handle, "OSMesaPixelStore"); - this->gl_data->OSMesaGetProcAddress = SDL_LoadFunction(handle, "OSMesaGetProcAddress"); - - /* Load old functions pointers (mesa_gl.ldg, tiny_gl.ldg) */ - this->gl_data->OSMesaCreateLDG = SDL_LoadFunction(handle, "OSMesaCreateLDG"); - this->gl_data->OSMesaDestroyLDG = SDL_LoadFunction(handle, "OSMesaDestroyLDG"); - - gl_oldmesa = 0; - - if ( (this->gl_data->OSMesaCreateContextExt == NULL) || - (this->gl_data->OSMesaDestroyContext == NULL) || - (this->gl_data->OSMesaMakeCurrent == NULL) || - (this->gl_data->OSMesaPixelStore == NULL) || - (this->gl_data->OSMesaGetProcAddress == NULL)) { - /* Hum, maybe old library ? */ - if ( (this->gl_data->OSMesaCreateLDG == NULL) || - (this->gl_data->OSMesaDestroyLDG == NULL)) { - SDL_SetError("Could not retrieve OSMesa functions"); - SDL_UnloadObject(handle); - /* Restore pointers to static library */ - SDL_AtariGL_InitPointers(this); - return -1; - } else { - gl_oldmesa = 1; - } - } - - this->gl_config.dll_handle = handle; - if ( path ) { - SDL_strlcpy(this->gl_config.driver_path, path, - SDL_arraysize(this->gl_config.driver_path)); - } else { - *this->gl_config.driver_path = '\0'; - } + void *handle; + SDL_bool cancel_load; + + if (gl_active) { + SDL_SetError("OpenGL context already created"); + return -1; + } + + /* Unload previous driver */ + SDL_AtariGL_UnloadLibrary(this); + + /* Load library given by path */ + handle = SDL_LoadObject(path); + if (handle == NULL) { + /* Try to load another one */ + path = SDL_getenv("SDL_VIDEO_GL_DRIVER"); + if (path != NULL) { + handle = SDL_LoadObject(path); + } + + /* If it does not work, try some other */ + if (handle == NULL) { + path = PATH_OSMESA_LDG; + handle = SDL_LoadObject(path); + } + + if (handle == NULL) { + path = PATH_MESAGL_LDG; + handle = SDL_LoadObject(path); + } + + if (handle == NULL) { + path = PATH_TINYGL_LDG; + handle = SDL_LoadObject(path); + } + } + + if (handle == NULL) { + SDL_SetError("Could not load OpenGL library"); + return -1; + } + + this->gl_data->glGetIntegerv = SDL_LoadFunction(handle, "glGetIntegerv"); + this->gl_data->glFinish = SDL_LoadFunction(handle, "glFinish"); + this->gl_data->glFlush = SDL_LoadFunction(handle, "glFlush"); + + cancel_load = SDL_FALSE; + if (this->gl_data->glGetIntegerv == NULL) { + cancel_load = SDL_TRUE; + } else { + /* We need either glFinish (OSMesa) or glFlush (TinyGL) */ + if ((this->gl_data->glFinish == NULL) && + (this->gl_data->glFlush == NULL)) { + cancel_load = SDL_TRUE; + } + } + if (cancel_load) { + SDL_SetError("Could not retrieve OpenGL functions"); + SDL_UnloadObject(handle); + /* Restore pointers to static library */ + SDL_AtariGL_InitPointers(this); + return -1; + } + + /* Load functions pointers (osmesa.ldg) */ + this->gl_data->OSMesaCreateContextExt = + SDL_LoadFunction(handle, "OSMesaCreateContextExt"); + this->gl_data->OSMesaDestroyContext = + SDL_LoadFunction(handle, "OSMesaDestroyContext"); + this->gl_data->OSMesaMakeCurrent = + SDL_LoadFunction(handle, "OSMesaMakeCurrent"); + this->gl_data->OSMesaPixelStore = + SDL_LoadFunction(handle, "OSMesaPixelStore"); + this->gl_data->OSMesaGetProcAddress = + SDL_LoadFunction(handle, "OSMesaGetProcAddress"); + + /* Load old functions pointers (mesa_gl.ldg, tiny_gl.ldg) */ + this->gl_data->OSMesaCreateLDG = + SDL_LoadFunction(handle, "OSMesaCreateLDG"); + this->gl_data->OSMesaDestroyLDG = + SDL_LoadFunction(handle, "OSMesaDestroyLDG"); + + gl_oldmesa = 0; + + if ((this->gl_data->OSMesaCreateContextExt == NULL) || + (this->gl_data->OSMesaDestroyContext == NULL) || + (this->gl_data->OSMesaMakeCurrent == NULL) || + (this->gl_data->OSMesaPixelStore == NULL) || + (this->gl_data->OSMesaGetProcAddress == NULL)) { + /* Hum, maybe old library ? */ + if ((this->gl_data->OSMesaCreateLDG == NULL) || + (this->gl_data->OSMesaDestroyLDG == NULL)) { + SDL_SetError("Could not retrieve OSMesa functions"); + SDL_UnloadObject(handle); + /* Restore pointers to static library */ + SDL_AtariGL_InitPointers(this); + return -1; + } else { + gl_oldmesa = 1; + } + } + + this->gl_config.dll_handle = handle; + if (path) { + SDL_strlcpy(this->gl_config.driver_path, path, + SDL_arraysize(this->gl_config.driver_path)); + } else { + *this->gl_config.driver_path = '\0'; + } #endif - this->gl_config.driver_loaded = 1; + this->gl_config.driver_loaded = 1; - return 0; + return 0; #else - return -1; + return -1; #endif } -void *SDL_AtariGL_GetProcAddress(_THIS, const char *proc) +void * +SDL_AtariGL_GetProcAddress(_THIS, const char *proc) { - void *func = NULL; + void *func = NULL; #if SDL_VIDEO_OPENGL - if (this->gl_config.dll_handle) { - func = SDL_LoadFunction(this->gl_config.dll_handle, (void *)proc); - } else if (this->gl_data->OSMesaGetProcAddress) { - func = this->gl_data->OSMesaGetProcAddress(proc); - } - + if (this->gl_config.dll_handle) { + func = SDL_LoadFunction(this->gl_config.dll_handle, (void *) proc); + } else if (this->gl_data->OSMesaGetProcAddress) { + func = this->gl_data->OSMesaGetProcAddress(proc); + } #endif - return func; + return func; } -int SDL_AtariGL_GetAttribute(_THIS, SDL_GLattr attrib, int* value) +int +SDL_AtariGL_GetAttribute(_THIS, SDL_GLattr attrib, int *value) { #if SDL_VIDEO_OPENGL - GLenum mesa_attrib; - SDL_Surface *surface; - - if (!gl_active) { - return -1; - } - - switch(attrib) { - case SDL_GL_RED_SIZE: - mesa_attrib = GL_RED_BITS; - break; - case SDL_GL_GREEN_SIZE: - mesa_attrib = GL_GREEN_BITS; - break; - case SDL_GL_BLUE_SIZE: - mesa_attrib = GL_BLUE_BITS; - break; - case SDL_GL_ALPHA_SIZE: - mesa_attrib = GL_ALPHA_BITS; - break; - case SDL_GL_DOUBLEBUFFER: - surface = this->screen; - *value = ((surface->flags & SDL_DOUBLEBUF)==SDL_DOUBLEBUF); - return 0; - case SDL_GL_DEPTH_SIZE: - mesa_attrib = GL_DEPTH_BITS; - break; - case SDL_GL_STENCIL_SIZE: - mesa_attrib = GL_STENCIL_BITS; - break; - case SDL_GL_ACCUM_RED_SIZE: - mesa_attrib = GL_ACCUM_RED_BITS; - break; - case SDL_GL_ACCUM_GREEN_SIZE: - mesa_attrib = GL_ACCUM_GREEN_BITS; - break; - case SDL_GL_ACCUM_BLUE_SIZE: - mesa_attrib = GL_ACCUM_BLUE_BITS; - break; - case SDL_GL_ACCUM_ALPHA_SIZE: - mesa_attrib = GL_ACCUM_ALPHA_BITS; - break; - default : - return -1; - } - - this->gl_data->glGetIntegerv(mesa_attrib, value); - return 0; + GLenum mesa_attrib; + SDL_Surface *surface; + + if (!gl_active) { + return -1; + } + + switch (attrib) { + case SDL_GL_RED_SIZE: + mesa_attrib = GL_RED_BITS; + break; + case SDL_GL_GREEN_SIZE: + mesa_attrib = GL_GREEN_BITS; + break; + case SDL_GL_BLUE_SIZE: + mesa_attrib = GL_BLUE_BITS; + break; + case SDL_GL_ALPHA_SIZE: + mesa_attrib = GL_ALPHA_BITS; + break; + case SDL_GL_DOUBLEBUFFER: + surface = this->screen; + *value = ((surface->flags & SDL_DOUBLEBUF) == SDL_DOUBLEBUF); + return 0; + case SDL_GL_DEPTH_SIZE: + mesa_attrib = GL_DEPTH_BITS; + break; + case SDL_GL_STENCIL_SIZE: + mesa_attrib = GL_STENCIL_BITS; + break; + case SDL_GL_ACCUM_RED_SIZE: + mesa_attrib = GL_ACCUM_RED_BITS; + break; + case SDL_GL_ACCUM_GREEN_SIZE: + mesa_attrib = GL_ACCUM_GREEN_BITS; + break; + case SDL_GL_ACCUM_BLUE_SIZE: + mesa_attrib = GL_ACCUM_BLUE_BITS; + break; + case SDL_GL_ACCUM_ALPHA_SIZE: + mesa_attrib = GL_ACCUM_ALPHA_BITS; + break; + default: + return -1; + } + + this->gl_data->glGetIntegerv(mesa_attrib, value); + return 0; #else - return -1; + return -1; #endif } -int SDL_AtariGL_MakeCurrent(_THIS) +int +SDL_AtariGL_MakeCurrent(_THIS) { #if SDL_VIDEO_OPENGL - SDL_Surface *surface; - GLenum type; - - if (gl_oldmesa && gl_active) { - return 0; - } - - if (this->gl_config.dll_handle) { - if ((this->gl_data->OSMesaMakeCurrent == NULL) || - (this->gl_data->OSMesaPixelStore == NULL)) { - return -1; - } - } - - if (!gl_active) { - SDL_SetError("Invalid OpenGL context"); - return -1; - } - - surface = this->screen; - - if ((surface->format->BitsPerPixel == 15) || (surface->format->BitsPerPixel == 16)) { - type = GL_UNSIGNED_SHORT_5_6_5; - } else { - type = GL_UNSIGNED_BYTE; - } - - if (!(this->gl_data->OSMesaMakeCurrent(gl_ctx, surface->pixels, type, surface->w, surface->h))) { - SDL_SetError("Can not make OpenGL context current"); - return -1; - } - - /* OSMesa draws upside down */ - this->gl_data->OSMesaPixelStore(OSMESA_Y_UP, 0); - - return 0; + SDL_Surface *surface; + GLenum type; + + if (gl_oldmesa && gl_active) { + return 0; + } + + if (this->gl_config.dll_handle) { + if ((this->gl_data->OSMesaMakeCurrent == NULL) || + (this->gl_data->OSMesaPixelStore == NULL)) { + return -1; + } + } + + if (!gl_active) { + SDL_SetError("Invalid OpenGL context"); + return -1; + } + + surface = this->screen; + + if ((surface->format->BitsPerPixel == 15) + || (surface->format->BitsPerPixel == 16)) { + type = GL_UNSIGNED_SHORT_5_6_5; + } else { + type = GL_UNSIGNED_BYTE; + } + + if (! + (this->gl_data-> + OSMesaMakeCurrent(gl_ctx, surface->pixels, type, surface->w, + surface->h))) { + SDL_SetError("Can not make OpenGL context current"); + return -1; + } + + /* OSMesa draws upside down */ + this->gl_data->OSMesaPixelStore(OSMESA_Y_UP, 0); + + return 0; #else - return -1; + return -1; #endif } -void SDL_AtariGL_SwapBuffers(_THIS) +void +SDL_AtariGL_SwapBuffers(_THIS) { #if SDL_VIDEO_OPENGL - if (gl_active) { - if (this->gl_config.dll_handle) { - if (this->gl_data->glFinish) { - this->gl_data->glFinish(); - } else if (this->gl_data->glFlush) { - this->gl_data->glFlush(); - } - } else { - this->gl_data->glFinish(); - } - gl_copyshadow(this, this->screen); - gl_convert(this, this->screen); - } + if (gl_active) { + if (this->gl_config.dll_handle) { + if (this->gl_data->glFinish) { + this->gl_data->glFinish(); + } else if (this->gl_data->glFlush) { + this->gl_data->glFlush(); + } + } else { + this->gl_data->glFinish(); + } + gl_copyshadow(this, this->screen); + gl_convert(this, this->screen); + } #endif } -void SDL_AtariGL_InitPointers(_THIS) +void +SDL_AtariGL_InitPointers(_THIS) { #if SDL_VIDEO_OPENGL - this->gl_data->OSMesaCreateContextExt = OSMesaCreateContextExt; - this->gl_data->OSMesaDestroyContext = OSMesaDestroyContext; - this->gl_data->OSMesaMakeCurrent = OSMesaMakeCurrent; - this->gl_data->OSMesaPixelStore = OSMesaPixelStore; - this->gl_data->OSMesaGetProcAddress = OSMesaGetProcAddress; - - this->gl_data->glGetIntegerv = glGetIntegerv; - this->gl_data->glFinish = glFinish; - this->gl_data->glFlush = glFlush; - - this->gl_data->OSMesaCreateLDG = NULL; - this->gl_data->OSMesaDestroyLDG = NULL; + this->gl_data->OSMesaCreateContextExt = OSMesaCreateContextExt; + this->gl_data->OSMesaDestroyContext = OSMesaDestroyContext; + this->gl_data->OSMesaMakeCurrent = OSMesaMakeCurrent; + this->gl_data->OSMesaPixelStore = OSMesaPixelStore; + this->gl_data->OSMesaGetProcAddress = OSMesaGetProcAddress; + + this->gl_data->glGetIntegerv = glGetIntegerv; + this->gl_data->glFinish = glFinish; + this->gl_data->glFlush = glFlush; + + this->gl_data->OSMesaCreateLDG = NULL; + this->gl_data->OSMesaDestroyLDG = NULL; #endif } /*--- Private functions ---*/ -static void SDL_AtariGL_UnloadLibrary(_THIS) +static void +SDL_AtariGL_UnloadLibrary(_THIS) { #if SDL_VIDEO_OPENGL - if (this->gl_config.dll_handle) { - SDL_UnloadObject(this->gl_config.dll_handle); - this->gl_config.dll_handle = NULL; + if (this->gl_config.dll_handle) { + SDL_UnloadObject(this->gl_config.dll_handle); + this->gl_config.dll_handle = NULL; - /* Restore pointers to static library */ - SDL_AtariGL_InitPointers(this); - } + /* Restore pointers to static library */ + SDL_AtariGL_InitPointers(this); + } #endif } /*--- Creation of an OpenGL context using new/old functions ---*/ #if SDL_VIDEO_OPENGL -static int InitNew(_THIS, SDL_Surface *current) +static int +InitNew(_THIS, SDL_Surface * current) { - GLenum osmesa_format; - SDL_PixelFormat *pixel_format; - Uint32 redmask; - int recreatecontext; - GLint newaccumsize; - - if (this->gl_config.dll_handle) { - if (this->gl_data->OSMesaCreateContextExt == NULL) { - return 0; - } - } - - /* Init OpenGL context using OSMesa */ - gl_convert = ConvertNull; - gl_copyshadow = CopyShadowNull; - gl_upsidedown = SDL_FALSE; - - pixel_format = current->format; - redmask = pixel_format->Rmask; - switch (pixel_format->BitsPerPixel) { - case 15: - /* 1555, big and little endian, unsupported */ - gl_pixelsize = 2; - osmesa_format = OSMESA_RGB_565; - if (redmask == 31<<10) { - gl_convert = Convert565To555be; - } else { - gl_convert = Convert565To555le; - } - break; - case 16: - gl_pixelsize = 2; - if (redmask == 31<<11) { - osmesa_format = OSMESA_RGB_565; - } else { - /* 565, little endian, unsupported */ - osmesa_format = OSMESA_RGB_565; - gl_convert = Convert565le; - } - break; - case 24: - gl_pixelsize = 3; - if (redmask == 255<<16) { - osmesa_format = OSMESA_RGB; - } else { - osmesa_format = OSMESA_BGR; - } - break; - case 32: - gl_pixelsize = 4; - if (redmask == 255<<16) { - osmesa_format = OSMESA_ARGB; - } else if (redmask == 255<<8) { - osmesa_format = OSMESA_BGRA; - } else if (redmask == 255<<24) { - osmesa_format = OSMESA_RGBA; - } else { - /* ABGR format unsupported */ - osmesa_format = OSMESA_BGRA; - gl_convert = ConvertBGRAToABGR; - } - break; - default: - gl_pixelsize = 1; - osmesa_format = OSMESA_COLOR_INDEX; - break; - } - - /* Try to keep current context if possible */ - newaccumsize = - this->gl_config.accum_red_size + - this->gl_config.accum_green_size + - this->gl_config.accum_blue_size + - this->gl_config.accum_alpha_size; - recreatecontext=1; - if (gl_ctx && - (gl_curformat == osmesa_format) && - (gl_curdepth == this->gl_config.depth_size) && - (gl_curstencil == this->gl_config.stencil_size) && - (gl_curaccum == newaccumsize)) { - recreatecontext = 0; - } - if (recreatecontext) { - SDL_AtariGL_Quit(this, SDL_FALSE); - - gl_ctx = this->gl_data->OSMesaCreateContextExt( - osmesa_format, this->gl_config.depth_size, - this->gl_config.stencil_size, newaccumsize, NULL ); - - if (gl_ctx) { - gl_curformat = osmesa_format; - gl_curdepth = this->gl_config.depth_size; - gl_curstencil = this->gl_config.stencil_size; - gl_curaccum = newaccumsize; - } else { - gl_curformat = 0; - gl_curdepth = 0; - gl_curstencil = 0; - gl_curaccum = 0; - } - } - - return (gl_ctx != NULL); + GLenum osmesa_format; + SDL_PixelFormat *pixel_format; + Uint32 redmask; + int recreatecontext; + GLint newaccumsize; + + if (this->gl_config.dll_handle) { + if (this->gl_data->OSMesaCreateContextExt == NULL) { + return 0; + } + } + + /* Init OpenGL context using OSMesa */ + gl_convert = ConvertNull; + gl_copyshadow = CopyShadowNull; + gl_upsidedown = SDL_FALSE; + + pixel_format = current->format; + redmask = pixel_format->Rmask; + switch (pixel_format->BitsPerPixel) { + case 15: + /* 1555, big and little endian, unsupported */ + gl_pixelsize = 2; + osmesa_format = OSMESA_RGB_565; + if (redmask == 31 << 10) { + gl_convert = Convert565To555be; + } else { + gl_convert = Convert565To555le; + } + break; + case 16: + gl_pixelsize = 2; + if (redmask == 31 << 11) { + osmesa_format = OSMESA_RGB_565; + } else { + /* 565, little endian, unsupported */ + osmesa_format = OSMESA_RGB_565; + gl_convert = Convert565le; + } + break; + case 24: + gl_pixelsize = 3; + if (redmask == 255 << 16) { + osmesa_format = OSMESA_RGB; + } else { + osmesa_format = OSMESA_BGR; + } + break; + case 32: + gl_pixelsize = 4; + if (redmask == 255 << 16) { + osmesa_format = OSMESA_ARGB; + } else if (redmask == 255 << 8) { + osmesa_format = OSMESA_BGRA; + } else if (redmask == 255 << 24) { + osmesa_format = OSMESA_RGBA; + } else { + /* ABGR format unsupported */ + osmesa_format = OSMESA_BGRA; + gl_convert = ConvertBGRAToABGR; + } + break; + default: + gl_pixelsize = 1; + osmesa_format = OSMESA_COLOR_INDEX; + break; + } + + /* Try to keep current context if possible */ + newaccumsize = + this->gl_config.accum_red_size + + this->gl_config.accum_green_size + + this->gl_config.accum_blue_size + this->gl_config.accum_alpha_size; + recreatecontext = 1; + if (gl_ctx && + (gl_curformat == osmesa_format) && + (gl_curdepth == this->gl_config.depth_size) && + (gl_curstencil == this->gl_config.stencil_size) && + (gl_curaccum == newaccumsize)) { + recreatecontext = 0; + } + if (recreatecontext) { + SDL_AtariGL_Quit(this, SDL_FALSE); + + gl_ctx = + this->gl_data->OSMesaCreateContextExt(osmesa_format, + this->gl_config. + depth_size, + this->gl_config. + stencil_size, + newaccumsize, NULL); + + if (gl_ctx) { + gl_curformat = osmesa_format; + gl_curdepth = this->gl_config.depth_size; + gl_curstencil = this->gl_config.stencil_size; + gl_curaccum = newaccumsize; + } else { + gl_curformat = 0; + gl_curdepth = 0; + gl_curstencil = 0; + gl_curaccum = 0; + } + } + + return (gl_ctx != NULL); } -static int InitOld(_THIS, SDL_Surface *current) +static int +InitOld(_THIS, SDL_Surface * current) { - GLenum osmesa_format; - SDL_PixelFormat *pixel_format; - Uint32 redmask; - int recreatecontext, tinygl_present; - - if (this->gl_config.dll_handle) { - if (this->gl_data->OSMesaCreateLDG == NULL) { - return 0; - } - } - - /* TinyGL only supports VDI_RGB (OSMESA_RGB) */ - tinygl_present=0; - if (this->gl_config.dll_handle) { - if (this->gl_data->glFinish == NULL) { - tinygl_present=1; - } - } - - /* Init OpenGL context using OSMesa */ - gl_convert = ConvertNull; - gl_copyshadow = CopyShadowNull; - gl_upsidedown = SDL_FALSE; - - pixel_format = current->format; - redmask = pixel_format->Rmask; - switch (pixel_format->BitsPerPixel) { - case 15: - /* 15 bits unsupported */ - if (tinygl_present) { - gl_pixelsize = 3; - osmesa_format = VDI_RGB; - if (redmask == 31<<10) { - gl_copyshadow = CopyShadowRGBTo555; - } else { - gl_copyshadow = CopyShadowRGBTo565; - gl_convert = Convert565To555le; - } - } else { - gl_pixelsize = 4; - gl_upsidedown = SDL_TRUE; - osmesa_format = OSMESA_ARGB; - if (redmask == 31<<10) { - gl_copyshadow = CopyShadow8888To555; - } else { - gl_copyshadow = CopyShadow8888To565; - gl_convert = Convert565To555le; - } - } - break; - case 16: - /* 16 bits unsupported */ - if (tinygl_present) { - gl_pixelsize = 3; - osmesa_format = VDI_RGB; - gl_copyshadow = CopyShadowRGBTo565; - if (redmask != 31<<11) { - /* 565, little endian, unsupported */ - gl_convert = Convert565le; - } - } else { - gl_pixelsize = 4; - gl_upsidedown = SDL_TRUE; - osmesa_format = OSMESA_ARGB; - gl_copyshadow = CopyShadow8888To565; - if (redmask != 31<<11) { - /* 565, little endian, unsupported */ - gl_convert = Convert565le; - } - } - break; - case 24: - gl_pixelsize = 3; - if (tinygl_present) { - osmesa_format = VDI_RGB; - gl_copyshadow = CopyShadowDirect; - if (redmask != 255<<16) { - gl_copyshadow = CopyShadowRGBSwap; - } - } else { - gl_copyshadow = CopyShadowDirect; - gl_upsidedown = SDL_TRUE; - if (redmask == 255<<16) { - osmesa_format = OSMESA_RGB; - } else { - osmesa_format = OSMESA_BGR; - } - } - break; - case 32: - if (tinygl_present) { - gl_pixelsize = 3; - osmesa_format = VDI_RGB; - gl_copyshadow = CopyShadowRGBToARGB; - if (redmask == 255) { - gl_convert = CopyShadowRGBToABGR; - } else if (redmask == 255<<8) { - gl_convert = CopyShadowRGBToBGRA; - } else if (redmask == 255<<24) { - gl_convert = CopyShadowRGBToRGBA; - } - } else { - gl_pixelsize = 4; - gl_upsidedown = SDL_TRUE; - gl_copyshadow = CopyShadowDirect; - if (redmask == 255<<16) { - osmesa_format = OSMESA_ARGB; - } else if (redmask == 255<<8) { - osmesa_format = OSMESA_BGRA; - } else if (redmask == 255<<24) { - osmesa_format = OSMESA_RGBA; - } else { - /* ABGR format unsupported */ - osmesa_format = OSMESA_BGRA; - gl_convert = ConvertBGRAToABGR; - } - } - break; - default: - if (tinygl_present) { - SDL_AtariGL_Quit(this, SDL_FALSE); - return 0; - } - gl_pixelsize = 1; - gl_copyshadow = CopyShadowDirect; - osmesa_format = OSMESA_COLOR_INDEX; - break; - } - - /* Try to keep current context if possible */ - recreatecontext=1; - if (gl_shadow && - (gl_curformat == osmesa_format) && - (gl_curwidth == current->w) && - (gl_curheight == current->h)) { - recreatecontext = 0; - } - if (recreatecontext) { - SDL_AtariGL_Quit(this, SDL_FALSE); - - gl_shadow = this->gl_data->OSMesaCreateLDG( - osmesa_format, GL_UNSIGNED_BYTE, current->w, current->h - ); - - if (gl_shadow) { - gl_curformat = osmesa_format; - gl_curwidth = current->w; - gl_curheight = current->h; - } else { - gl_curformat = 0; - gl_curwidth = 0; - gl_curheight = 0; - } - } - - return (gl_shadow != NULL); + GLenum osmesa_format; + SDL_PixelFormat *pixel_format; + Uint32 redmask; + int recreatecontext, tinygl_present; + + if (this->gl_config.dll_handle) { + if (this->gl_data->OSMesaCreateLDG == NULL) { + return 0; + } + } + + /* TinyGL only supports VDI_RGB (OSMESA_RGB) */ + tinygl_present = 0; + if (this->gl_config.dll_handle) { + if (this->gl_data->glFinish == NULL) { + tinygl_present = 1; + } + } + + /* Init OpenGL context using OSMesa */ + gl_convert = ConvertNull; + gl_copyshadow = CopyShadowNull; + gl_upsidedown = SDL_FALSE; + + pixel_format = current->format; + redmask = pixel_format->Rmask; + switch (pixel_format->BitsPerPixel) { + case 15: + /* 15 bits unsupported */ + if (tinygl_present) { + gl_pixelsize = 3; + osmesa_format = VDI_RGB; + if (redmask == 31 << 10) { + gl_copyshadow = CopyShadowRGBTo555; + } else { + gl_copyshadow = CopyShadowRGBTo565; + gl_convert = Convert565To555le; + } + } else { + gl_pixelsize = 4; + gl_upsidedown = SDL_TRUE; + osmesa_format = OSMESA_ARGB; + if (redmask == 31 << 10) { + gl_copyshadow = CopyShadow8888To555; + } else { + gl_copyshadow = CopyShadow8888To565; + gl_convert = Convert565To555le; + } + } + break; + case 16: + /* 16 bits unsupported */ + if (tinygl_present) { + gl_pixelsize = 3; + osmesa_format = VDI_RGB; + gl_copyshadow = CopyShadowRGBTo565; + if (redmask != 31 << 11) { + /* 565, little endian, unsupported */ + gl_convert = Convert565le; + } + } else { + gl_pixelsize = 4; + gl_upsidedown = SDL_TRUE; + osmesa_format = OSMESA_ARGB; + gl_copyshadow = CopyShadow8888To565; + if (redmask != 31 << 11) { + /* 565, little endian, unsupported */ + gl_convert = Convert565le; + } + } + break; + case 24: + gl_pixelsize = 3; + if (tinygl_present) { + osmesa_format = VDI_RGB; + gl_copyshadow = CopyShadowDirect; + if (redmask != 255 << 16) { + gl_copyshadow = CopyShadowRGBSwap; + } + } else { + gl_copyshadow = CopyShadowDirect; + gl_upsidedown = SDL_TRUE; + if (redmask == 255 << 16) { + osmesa_format = OSMESA_RGB; + } else { + osmesa_format = OSMESA_BGR; + } + } + break; + case 32: + if (tinygl_present) { + gl_pixelsize = 3; + osmesa_format = VDI_RGB; + gl_copyshadow = CopyShadowRGBToARGB; + if (redmask == 255) { + gl_convert = CopyShadowRGBToABGR; + } else if (redmask == 255 << 8) { + gl_convert = CopyShadowRGBToBGRA; + } else if (redmask == 255 << 24) { + gl_convert = CopyShadowRGBToRGBA; + } + } else { + gl_pixelsize = 4; + gl_upsidedown = SDL_TRUE; + gl_copyshadow = CopyShadowDirect; + if (redmask == 255 << 16) { + osmesa_format = OSMESA_ARGB; + } else if (redmask == 255 << 8) { + osmesa_format = OSMESA_BGRA; + } else if (redmask == 255 << 24) { + osmesa_format = OSMESA_RGBA; + } else { + /* ABGR format unsupported */ + osmesa_format = OSMESA_BGRA; + gl_convert = ConvertBGRAToABGR; + } + } + break; + default: + if (tinygl_present) { + SDL_AtariGL_Quit(this, SDL_FALSE); + return 0; + } + gl_pixelsize = 1; + gl_copyshadow = CopyShadowDirect; + osmesa_format = OSMESA_COLOR_INDEX; + break; + } + + /* Try to keep current context if possible */ + recreatecontext = 1; + if (gl_shadow && + (gl_curformat == osmesa_format) && + (gl_curwidth == current->w) && (gl_curheight == current->h)) { + recreatecontext = 0; + } + if (recreatecontext) { + SDL_AtariGL_Quit(this, SDL_FALSE); + + gl_shadow = + this->gl_data->OSMesaCreateLDG(osmesa_format, GL_UNSIGNED_BYTE, + current->w, current->h); + + if (gl_shadow) { + gl_curformat = osmesa_format; + gl_curwidth = current->w; + gl_curheight = current->h; + } else { + gl_curformat = 0; + gl_curwidth = 0; + gl_curheight = 0; + } + } + + return (gl_shadow != NULL); } /*--- Conversions routines from shadow buffer to the screen ---*/ -static void CopyShadowNull(_THIS, SDL_Surface *surface) +static void +CopyShadowNull(_THIS, SDL_Surface * surface) { } -static void CopyShadowDirect(_THIS, SDL_Surface *surface) +static void +CopyShadowDirect(_THIS, SDL_Surface * surface) { - int y, srcpitch, dstpitch; - Uint8 *srcline, *dstline; - - srcline = gl_shadow; - srcpitch = surface->w * gl_pixelsize; - dstline = surface->pixels; - dstpitch = surface->pitch; - if (gl_upsidedown) { - srcline += (surface->h-1)*srcpitch; - srcpitch = -srcpitch; - } - - for (y=0; yh; y++) { - SDL_memcpy(dstline, srcline, srcpitch); - - srcline += srcpitch; - dstline += dstpitch; - } + int y, srcpitch, dstpitch; + Uint8 *srcline, *dstline; + + srcline = gl_shadow; + srcpitch = surface->w * gl_pixelsize; + dstline = surface->pixels; + dstpitch = surface->pitch; + if (gl_upsidedown) { + srcline += (surface->h - 1) * srcpitch; + srcpitch = -srcpitch; + } + + for (y = 0; y < surface->h; y++) { + SDL_memcpy(dstline, srcline, srcpitch); + + srcline += srcpitch; + dstline += dstpitch; + } } -static void CopyShadowRGBTo555(_THIS, SDL_Surface *surface) +static void +CopyShadowRGBTo555(_THIS, SDL_Surface * surface) { - int x,y, srcpitch, dstpitch; - Uint16 *dstline, *dstcol; - Uint8 *srcline, *srccol; - - srcline = (Uint8 *)gl_shadow; - srcpitch = surface->w * gl_pixelsize; - dstline = surface->pixels; - dstpitch = surface->pitch >>1; - if (gl_upsidedown) { - srcline += (surface->h-1)*srcpitch; - srcpitch = -srcpitch; - } - - for (y=0; yh; y++) { - srccol = srcline; - dstcol = dstline; - for (x=0; xw; x++) { - Uint16 dstcolor; - - dstcolor = ((*srccol++)<<7) & (31<<10); - dstcolor |= ((*srccol++)<<2) & (31<<5); - dstcolor |= ((*srccol++)>>3) & 31; - *dstcol++ = dstcolor; - } - - srcline += srcpitch; - dstline += dstpitch; - } + int x, y, srcpitch, dstpitch; + Uint16 *dstline, *dstcol; + Uint8 *srcline, *srccol; + + srcline = (Uint8 *) gl_shadow; + srcpitch = surface->w * gl_pixelsize; + dstline = surface->pixels; + dstpitch = surface->pitch >> 1; + if (gl_upsidedown) { + srcline += (surface->h - 1) * srcpitch; + srcpitch = -srcpitch; + } + + for (y = 0; y < surface->h; y++) { + srccol = srcline; + dstcol = dstline; + for (x = 0; x < surface->w; x++) { + Uint16 dstcolor; + + dstcolor = ((*srccol++) << 7) & (31 << 10); + dstcolor |= ((*srccol++) << 2) & (31 << 5); + dstcolor |= ((*srccol++) >> 3) & 31; + *dstcol++ = dstcolor; + } + + srcline += srcpitch; + dstline += dstpitch; + } } -static void CopyShadowRGBTo565(_THIS, SDL_Surface *surface) +static void +CopyShadowRGBTo565(_THIS, SDL_Surface * surface) { - int x,y, srcpitch, dstpitch; - Uint16 *dstline, *dstcol; - Uint8 *srcline, *srccol; - - srcline = (Uint8 *)gl_shadow; - srcpitch = surface->w * gl_pixelsize; - dstline = surface->pixels; - dstpitch = surface->pitch >>1; - if (gl_upsidedown) { - srcline += (surface->h-1)*srcpitch; - srcpitch = -srcpitch; - } - - for (y=0; yh; y++) { - srccol = srcline; - dstcol = dstline; - - for (x=0; xw; x++) { - Uint16 dstcolor; - - dstcolor = ((*srccol++)<<8) & (31<<11); - dstcolor |= ((*srccol++)<<3) & (63<<5); - dstcolor |= ((*srccol++)>>3) & 31; - *dstcol++ = dstcolor; - } - - srcline += srcpitch; - dstline += dstpitch; - } + int x, y, srcpitch, dstpitch; + Uint16 *dstline, *dstcol; + Uint8 *srcline, *srccol; + + srcline = (Uint8 *) gl_shadow; + srcpitch = surface->w * gl_pixelsize; + dstline = surface->pixels; + dstpitch = surface->pitch >> 1; + if (gl_upsidedown) { + srcline += (surface->h - 1) * srcpitch; + srcpitch = -srcpitch; + } + + for (y = 0; y < surface->h; y++) { + srccol = srcline; + dstcol = dstline; + + for (x = 0; x < surface->w; x++) { + Uint16 dstcolor; + + dstcolor = ((*srccol++) << 8) & (31 << 11); + dstcolor |= ((*srccol++) << 3) & (63 << 5); + dstcolor |= ((*srccol++) >> 3) & 31; + *dstcol++ = dstcolor; + } + + srcline += srcpitch; + dstline += dstpitch; + } } -static void CopyShadowRGBSwap(_THIS, SDL_Surface *surface) +static void +CopyShadowRGBSwap(_THIS, SDL_Surface * surface) { - int x,y, srcpitch, dstpitch; - Uint8 *dstline, *dstcol; - Uint8 *srcline, *srccol; - - srcline = (Uint8 *)gl_shadow; - srcpitch = surface->w * gl_pixelsize; - dstline = surface->pixels; - dstpitch = surface->pitch; - if (gl_upsidedown) { - srcline += (surface->h-1)*srcpitch; - srcpitch = -srcpitch; - } - - for (y=0; yh; y++) { - srccol = srcline; - dstcol = dstline; - - for (x=0; xw; x++) { - *dstcol++ = srccol[2]; - *dstcol++ = srccol[1]; - *dstcol++ = srccol[0]; - srccol += 3; - } - - srcline += srcpitch; - dstline += dstpitch; - } + int x, y, srcpitch, dstpitch; + Uint8 *dstline, *dstcol; + Uint8 *srcline, *srccol; + + srcline = (Uint8 *) gl_shadow; + srcpitch = surface->w * gl_pixelsize; + dstline = surface->pixels; + dstpitch = surface->pitch; + if (gl_upsidedown) { + srcline += (surface->h - 1) * srcpitch; + srcpitch = -srcpitch; + } + + for (y = 0; y < surface->h; y++) { + srccol = srcline; + dstcol = dstline; + + for (x = 0; x < surface->w; x++) { + *dstcol++ = srccol[2]; + *dstcol++ = srccol[1]; + *dstcol++ = srccol[0]; + srccol += 3; + } + + srcline += srcpitch; + dstline += dstpitch; + } } -static void CopyShadowRGBToARGB(_THIS, SDL_Surface *surface) +static void +CopyShadowRGBToARGB(_THIS, SDL_Surface * surface) { - int x,y, srcpitch, dstpitch; - Uint32 *dstline, *dstcol; - Uint8 *srcline, *srccol; - - srcline = (Uint8 *)gl_shadow; - srcpitch = surface->w * gl_pixelsize; - dstline = surface->pixels; - dstpitch = surface->pitch >>2; - if (gl_upsidedown) { - srcline += (surface->h-1)*srcpitch; - srcpitch = -srcpitch; - } - - for (y=0; yh; y++) { - srccol = srcline; - dstcol = dstline; - - for (x=0; xw; x++) { - Uint32 dstcolor; - - dstcolor = (*srccol++)<<16; - dstcolor |= (*srccol++)<<8; - dstcolor |= *srccol++; - - *dstcol++ = dstcolor; - } - - srcline += srcpitch; - dstline += dstpitch; - } + int x, y, srcpitch, dstpitch; + Uint32 *dstline, *dstcol; + Uint8 *srcline, *srccol; + + srcline = (Uint8 *) gl_shadow; + srcpitch = surface->w * gl_pixelsize; + dstline = surface->pixels; + dstpitch = surface->pitch >> 2; + if (gl_upsidedown) { + srcline += (surface->h - 1) * srcpitch; + srcpitch = -srcpitch; + } + + for (y = 0; y < surface->h; y++) { + srccol = srcline; + dstcol = dstline; + + for (x = 0; x < surface->w; x++) { + Uint32 dstcolor; + + dstcolor = (*srccol++) << 16; + dstcolor |= (*srccol++) << 8; + dstcolor |= *srccol++; + + *dstcol++ = dstcolor; + } + + srcline += srcpitch; + dstline += dstpitch; + } } -static void CopyShadowRGBToABGR(_THIS, SDL_Surface *surface) +static void +CopyShadowRGBToABGR(_THIS, SDL_Surface * surface) { - int x,y, srcpitch, dstpitch; - Uint32 *dstline, *dstcol; - Uint8 *srcline, *srccol; - - srcline = (Uint8 *)gl_shadow; - srcpitch = surface->w * gl_pixelsize; - dstline = surface->pixels; - dstpitch = surface->pitch >>2; - if (gl_upsidedown) { - srcline += (surface->h-1)*srcpitch; - srcpitch = -srcpitch; - } - - for (y=0; yh; y++) { - srccol = srcline; - dstcol = dstline; - - for (x=0; xw; x++) { - Uint32 dstcolor; - - dstcolor = *srccol++; - dstcolor |= (*srccol++)<<8; - dstcolor |= (*srccol++)<<16; - - *dstcol++ = dstcolor; - } - - srcline += srcpitch; - dstline += dstpitch; - } + int x, y, srcpitch, dstpitch; + Uint32 *dstline, *dstcol; + Uint8 *srcline, *srccol; + + srcline = (Uint8 *) gl_shadow; + srcpitch = surface->w * gl_pixelsize; + dstline = surface->pixels; + dstpitch = surface->pitch >> 2; + if (gl_upsidedown) { + srcline += (surface->h - 1) * srcpitch; + srcpitch = -srcpitch; + } + + for (y = 0; y < surface->h; y++) { + srccol = srcline; + dstcol = dstline; + + for (x = 0; x < surface->w; x++) { + Uint32 dstcolor; + + dstcolor = *srccol++; + dstcolor |= (*srccol++) << 8; + dstcolor |= (*srccol++) << 16; + + *dstcol++ = dstcolor; + } + + srcline += srcpitch; + dstline += dstpitch; + } } -static void CopyShadowRGBToBGRA(_THIS, SDL_Surface *surface) +static void +CopyShadowRGBToBGRA(_THIS, SDL_Surface * surface) { - int x,y, srcpitch, dstpitch; - Uint32 *dstline, *dstcol; - Uint8 *srcline, *srccol; - - srcline = (Uint8 *)gl_shadow; - srcpitch = surface->w * gl_pixelsize; - dstline = surface->pixels; - dstpitch = surface->pitch >>2; - if (gl_upsidedown) { - srcline += (surface->h-1)*srcpitch; - srcpitch = -srcpitch; - } - - for (y=0; yh; y++) { - srccol = srcline; - dstcol = dstline; - - for (x=0; xw; x++) { - Uint32 dstcolor; - - dstcolor = (*srccol++)<<8; - dstcolor |= (*srccol++)<<16; - dstcolor |= (*srccol++)<<24; - - *dstcol++ = dstcolor; - } - - srcline += srcpitch; - dstline += dstpitch; - } + int x, y, srcpitch, dstpitch; + Uint32 *dstline, *dstcol; + Uint8 *srcline, *srccol; + + srcline = (Uint8 *) gl_shadow; + srcpitch = surface->w * gl_pixelsize; + dstline = surface->pixels; + dstpitch = surface->pitch >> 2; + if (gl_upsidedown) { + srcline += (surface->h - 1) * srcpitch; + srcpitch = -srcpitch; + } + + for (y = 0; y < surface->h; y++) { + srccol = srcline; + dstcol = dstline; + + for (x = 0; x < surface->w; x++) { + Uint32 dstcolor; + + dstcolor = (*srccol++) << 8; + dstcolor |= (*srccol++) << 16; + dstcolor |= (*srccol++) << 24; + + *dstcol++ = dstcolor; + } + + srcline += srcpitch; + dstline += dstpitch; + } } -static void CopyShadowRGBToRGBA(_THIS, SDL_Surface *surface) +static void +CopyShadowRGBToRGBA(_THIS, SDL_Surface * surface) { - int x,y, srcpitch, dstpitch; - Uint32 *dstline, *dstcol; - Uint8 *srcline, *srccol; - - srcline = (Uint8 *)gl_shadow; - srcpitch = surface->w * gl_pixelsize; - dstline = surface->pixels; - dstpitch = surface->pitch >>2; - if (gl_upsidedown) { - srcline += (surface->h-1)*srcpitch; - srcpitch = -srcpitch; - } - - for (y=0; yh; y++) { - srccol = srcline; - dstcol = dstline; - - for (x=0; xw; x++) { - Uint32 dstcolor; - - dstcolor = (*srccol++)<<24; - dstcolor |= (*srccol++)<<16; - dstcolor |= (*srccol++)<<8; - - *dstcol++ = dstcolor; - } - - srcline += srcpitch; - dstline += dstpitch; - } + int x, y, srcpitch, dstpitch; + Uint32 *dstline, *dstcol; + Uint8 *srcline, *srccol; + + srcline = (Uint8 *) gl_shadow; + srcpitch = surface->w * gl_pixelsize; + dstline = surface->pixels; + dstpitch = surface->pitch >> 2; + if (gl_upsidedown) { + srcline += (surface->h - 1) * srcpitch; + srcpitch = -srcpitch; + } + + for (y = 0; y < surface->h; y++) { + srccol = srcline; + dstcol = dstline; + + for (x = 0; x < surface->w; x++) { + Uint32 dstcolor; + + dstcolor = (*srccol++) << 24; + dstcolor |= (*srccol++) << 16; + dstcolor |= (*srccol++) << 8; + + *dstcol++ = dstcolor; + } + + srcline += srcpitch; + dstline += dstpitch; + } } -static void CopyShadow8888To555(_THIS, SDL_Surface *surface) +static void +CopyShadow8888To555(_THIS, SDL_Surface * surface) { - int x,y, srcpitch, dstpitch; - Uint16 *dstline, *dstcol; - Uint32 *srcline, *srccol; - - srcline = (Uint32 *)gl_shadow; - srcpitch = (surface->w * gl_pixelsize) >>2; - dstline = surface->pixels; - dstpitch = surface->pitch >>1; - if (gl_upsidedown) { - srcline += (surface->h-1)*srcpitch; - srcpitch = -srcpitch; - } - - for (y=0; yh; y++) { - srccol = srcline; - dstcol = dstline; - for (x=0; xw; x++) { - Uint32 srccolor; - Uint16 dstcolor; - - srccolor = *srccol++; - dstcolor = (srccolor>>9) & (31<<10); - dstcolor |= (srccolor>>6) & (31<<5); - dstcolor |= (srccolor>>3) & 31; - *dstcol++ = dstcolor; - } - - srcline += srcpitch; - dstline += dstpitch; - } + int x, y, srcpitch, dstpitch; + Uint16 *dstline, *dstcol; + Uint32 *srcline, *srccol; + + srcline = (Uint32 *) gl_shadow; + srcpitch = (surface->w * gl_pixelsize) >> 2; + dstline = surface->pixels; + dstpitch = surface->pitch >> 1; + if (gl_upsidedown) { + srcline += (surface->h - 1) * srcpitch; + srcpitch = -srcpitch; + } + + for (y = 0; y < surface->h; y++) { + srccol = srcline; + dstcol = dstline; + for (x = 0; x < surface->w; x++) { + Uint32 srccolor; + Uint16 dstcolor; + + srccolor = *srccol++; + dstcolor = (srccolor >> 9) & (31 << 10); + dstcolor |= (srccolor >> 6) & (31 << 5); + dstcolor |= (srccolor >> 3) & 31; + *dstcol++ = dstcolor; + } + + srcline += srcpitch; + dstline += dstpitch; + } } -static void CopyShadow8888To565(_THIS, SDL_Surface *surface) +static void +CopyShadow8888To565(_THIS, SDL_Surface * surface) { - int x,y, srcpitch, dstpitch; - Uint16 *dstline, *dstcol; - Uint32 *srcline, *srccol; - - srcline = (Uint32 *)gl_shadow; - srcpitch = (surface->w * gl_pixelsize) >> 2; - dstline = surface->pixels; - dstpitch = surface->pitch >>1; - if (gl_upsidedown) { - srcline += (surface->h-1)*srcpitch; - srcpitch = -srcpitch; - } - - for (y=0; yh; y++) { - srccol = srcline; - dstcol = dstline; - - for (x=0; xw; x++) { - Uint32 srccolor; - Uint16 dstcolor; - - srccolor = *srccol++; - dstcolor = (srccolor>>8) & (31<<11); - dstcolor |= (srccolor>>5) & (63<<5); - dstcolor |= (srccolor>>3) & 31; - *dstcol++ = dstcolor; - } - - srcline += srcpitch; - dstline += dstpitch; - } + int x, y, srcpitch, dstpitch; + Uint16 *dstline, *dstcol; + Uint32 *srcline, *srccol; + + srcline = (Uint32 *) gl_shadow; + srcpitch = (surface->w * gl_pixelsize) >> 2; + dstline = surface->pixels; + dstpitch = surface->pitch >> 1; + if (gl_upsidedown) { + srcline += (surface->h - 1) * srcpitch; + srcpitch = -srcpitch; + } + + for (y = 0; y < surface->h; y++) { + srccol = srcline; + dstcol = dstline; + + for (x = 0; x < surface->w; x++) { + Uint32 srccolor; + Uint16 dstcolor; + + srccolor = *srccol++; + dstcolor = (srccolor >> 8) & (31 << 11); + dstcolor |= (srccolor >> 5) & (63 << 5); + dstcolor |= (srccolor >> 3) & 31; + *dstcol++ = dstcolor; + } + + srcline += srcpitch; + dstline += dstpitch; + } } /*--- Conversions routines in the screen ---*/ -static void ConvertNull(_THIS, SDL_Surface *surface) +static void +ConvertNull(_THIS, SDL_Surface * surface) { } -static void Convert565To555be(_THIS, SDL_Surface *surface) +static void +Convert565To555be(_THIS, SDL_Surface * surface) { - int x,y, pitch; - unsigned short *line, *pixel; + int x, y, pitch; + unsigned short *line, *pixel; - line = surface->pixels; - pitch = surface->pitch >> 1; - for (y=0; yh; y++) { - pixel = line; - for (x=0; xw; x++) { - unsigned short color = *pixel; + line = surface->pixels; + pitch = surface->pitch >> 1; + for (y = 0; y < surface->h; y++) { + pixel = line; + for (x = 0; x < surface->w; x++) { + unsigned short color = *pixel; - *pixel++ = (color & 0x1f)|((color>>1) & 0xffe0); - } + *pixel++ = (color & 0x1f) | ((color >> 1) & 0xffe0); + } - line += pitch; - } + line += pitch; + } } -static void Convert565To555le(_THIS, SDL_Surface *surface) +static void +Convert565To555le(_THIS, SDL_Surface * surface) { - int x,y, pitch; - unsigned short *line, *pixel; - - line = surface->pixels; - pitch = surface->pitch >>1; - for (y=0; yh; y++) { - pixel = line; - for (x=0; xw; x++) { - unsigned short color = *pixel; - - color = (color & 0x1f)|((color>>1) & 0xffe0); - *pixel++ = SDL_Swap16(color); - } - - line += pitch; - } + int x, y, pitch; + unsigned short *line, *pixel; + + line = surface->pixels; + pitch = surface->pitch >> 1; + for (y = 0; y < surface->h; y++) { + pixel = line; + for (x = 0; x < surface->w; x++) { + unsigned short color = *pixel; + + color = (color & 0x1f) | ((color >> 1) & 0xffe0); + *pixel++ = SDL_Swap16(color); + } + + line += pitch; + } } -static void Convert565le(_THIS, SDL_Surface *surface) +static void +Convert565le(_THIS, SDL_Surface * surface) { - int x,y, pitch; - unsigned short *line, *pixel; + int x, y, pitch; + unsigned short *line, *pixel; - line = surface->pixels; - pitch = surface->pitch >>1; - for (y=0; yh; y++) { - pixel = line; - for (x=0; xw; x++) { - unsigned short color = *pixel; + line = surface->pixels; + pitch = surface->pitch >> 1; + for (y = 0; y < surface->h; y++) { + pixel = line; + for (x = 0; x < surface->w; x++) { + unsigned short color = *pixel; - *pixel++ = SDL_Swap16(color); - } + *pixel++ = SDL_Swap16(color); + } - line += pitch; - } + line += pitch; + } } -static void ConvertBGRAToABGR(_THIS, SDL_Surface *surface) +static void +ConvertBGRAToABGR(_THIS, SDL_Surface * surface) { - int x,y, pitch; - unsigned long *line, *pixel; + int x, y, pitch; + unsigned long *line, *pixel; - line = surface->pixels; - pitch = surface->pitch >>2; - for (y=0; yh; y++) { - pixel = line; - for (x=0; xw; x++) { - unsigned long color = *pixel; + line = surface->pixels; + pitch = surface->pitch >> 2; + for (y = 0; y < surface->h; y++) { + pixel = line; + for (x = 0; x < surface->w; x++) { + unsigned long color = *pixel; - *pixel++ = (color<<24)|(color>>8); - } + *pixel++ = (color << 24) | (color >> 8); + } - line += pitch; - } + line += pitch; + } } #endif /* SDL_VIDEO_OPENGL */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/ataricommon/SDL_atarigl_c.h b/src/video/ataricommon/SDL_atarigl_c.h index 4626d446a..43a537750 100644 --- a/src/video/ataricommon/SDL_atarigl_c.h +++ b/src/video/ataricommon/SDL_atarigl_c.h @@ -35,47 +35,54 @@ /* Hidden "this" pointer for the video functions */ #define _THIS SDL_VideoDevice *this -struct SDL_PrivateGLData { +struct SDL_PrivateGLData +{ - int gl_active; /* to stop switching drivers while we have a valid context */ - - int gl_oldmesa; /* Old OpenGL support ? */ + int gl_active; /* to stop switching drivers while we have a valid context */ - int gl_pixelsize; /* for CopyShadow functions */ + int gl_oldmesa; /* Old OpenGL support ? */ - SDL_bool gl_upsidedown; /* Some implementations draw upside down */ + int gl_pixelsize; /* for CopyShadow functions */ - Uint8 *gl_shadow; /* Shadow buffer for old implementations */ + SDL_bool gl_upsidedown; /* Some implementations draw upside down */ - /* for unsupported OSMesa buffer formats */ - void (*ConvertSurface)(_THIS, SDL_Surface *surface); + Uint8 *gl_shadow; /* Shadow buffer for old implementations */ - /* to convert the shadow buffer to the screen format */ - void (*CopyShadow)(_THIS, SDL_Surface *surface); + /* for unsupported OSMesa buffer formats */ + void (*ConvertSurface) (_THIS, SDL_Surface * surface); + + /* to convert the shadow buffer to the screen format */ + void (*CopyShadow) (_THIS, SDL_Surface * surface); #if SDL_VIDEO_OPENGL - OSMesaContext ctx; - - /* OpenGL functions */ - void (*glGetIntegerv)( GLenum pname, GLint *value ); - void (*glFinish)(void); - void (*glFlush)(void); - - /* osmesa.ldg */ - OSMesaContext (*OSMesaCreateContextExt)( GLenum format, GLint depthBits, GLint stencilBits, GLint accumBits, OSMesaContext sharelist); - void (*OSMesaDestroyContext)( OSMesaContext ctx ); - GLboolean (*OSMesaMakeCurrent)( OSMesaContext ctx, void *buffer, GLenum type, GLsizei width, GLsizei height ); - void (*OSMesaPixelStore)( GLint pname, GLint value ); - void * (*OSMesaGetProcAddress)( const char *funcName ); - - /* mesa_gl.ldg, tiny_gl.ldg */ - void *(*OSMesaCreateLDG)( long format, long type, long width, long height ); - void (*OSMesaDestroyLDG)(void); - - /* Info needed to compare existing context with new asked one */ - int width, height; - GLenum format; - GLint depth,stencil,accum; + OSMesaContext ctx; + + /* OpenGL functions */ + void (*glGetIntegerv) (GLenum pname, GLint * value); + void (*glFinish) (void); + void (*glFlush) (void); + + /* osmesa.ldg */ + OSMesaContext(*OSMesaCreateContextExt) (GLenum format, GLint depthBits, + GLint stencilBits, + GLint accumBits, + OSMesaContext sharelist); + void (*OSMesaDestroyContext) (OSMesaContext ctx); + GLboolean(*OSMesaMakeCurrent) (OSMesaContext ctx, void *buffer, + GLenum type, GLsizei width, + GLsizei height); + void (*OSMesaPixelStore) (GLint pname, GLint value); + void *(*OSMesaGetProcAddress) (const char *funcName); + + /* mesa_gl.ldg, tiny_gl.ldg */ + void *(*OSMesaCreateLDG) (long format, long type, long width, + long height); + void (*OSMesaDestroyLDG) (void); + + /* Info needed to compare existing context with new asked one */ + int width, height; + GLenum format; + GLint depth, stencil, accum; #endif }; @@ -96,14 +103,15 @@ struct SDL_PrivateGLData { #define gl_curheight (this->gl_data->height) /* OpenGL functions */ -extern int SDL_AtariGL_Init(_THIS, SDL_Surface *current); +extern int SDL_AtariGL_Init(_THIS, SDL_Surface * current); extern void SDL_AtariGL_Quit(_THIS, SDL_bool unload); extern void SDL_AtariGL_InitPointers(_THIS); extern int SDL_AtariGL_LoadLibrary(_THIS, const char *path); extern void *SDL_AtariGL_GetProcAddress(_THIS, const char *proc); -extern int SDL_AtariGL_GetAttribute(_THIS, SDL_GLattr attrib, int* value); +extern int SDL_AtariGL_GetAttribute(_THIS, SDL_GLattr attrib, int *value); extern int SDL_AtariGL_MakeCurrent(_THIS); extern void SDL_AtariGL_SwapBuffers(_THIS); #endif /* _SDL_ATARIGL_H_ */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/ataricommon/SDL_atarikeys.h b/src/video/ataricommon/SDL_atarikeys.h index f5eee5a72..6010ec96b 100644 --- a/src/video/ataricommon/SDL_atarikeys.h +++ b/src/video/ataricommon/SDL_atarikeys.h @@ -27,7 +27,7 @@ */ #ifndef _SDL_ATARIKEYS_H_ -#define _SDL_ATARIKEYS_H_ +#define _SDL_ATARIKEYS_H_ /* --- Keyboard scancodes --- */ /* taken from svgalib/vgakeyboard.h */ @@ -138,3 +138,4 @@ #define SCANCODE_LEFT 0x4b #endif /* _SDL_ATARIKEYS_H_ */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/ataricommon/SDL_atarimxalloc.c b/src/video/ataricommon/SDL_atarimxalloc.c index 0e6b5aee8..1a746e46f 100644 --- a/src/video/ataricommon/SDL_atarimxalloc.c +++ b/src/video/ataricommon/SDL_atarimxalloc.c @@ -33,20 +33,24 @@ /*--- Variables ---*/ -static int atari_mxalloc_avail=-1; +static int atari_mxalloc_avail = -1; /*--- Functions ---*/ -void *Atari_SysMalloc(Uint32 size, Uint16 alloc_type) +void * +Atari_SysMalloc(Uint32 size, Uint16 alloc_type) { - /* Test if Mxalloc() available */ - if (atari_mxalloc_avail<0) { - atari_mxalloc_avail = ((Sversion()&0xFF)>=0x01) | (Sversion()>=0x1900); - } - - if (atari_mxalloc_avail) { - return (void *) Mxalloc(size, alloc_type); - } else { \ - return (void *) Malloc(size); - } + /* Test if Mxalloc() available */ + if (atari_mxalloc_avail < 0) { + atari_mxalloc_avail = + ((Sversion() & 0xFF) >= 0x01) | (Sversion() >= 0x1900); + } + + if (atari_mxalloc_avail) { + return (void *) Mxalloc(size, alloc_type); + } else { + return (void *) Malloc(size); + } } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/ataricommon/SDL_atarimxalloc_c.h b/src/video/ataricommon/SDL_atarimxalloc_c.h index 32e6e1a56..1450988b5 100644 --- a/src/video/ataricommon/SDL_atarimxalloc_c.h +++ b/src/video/ataricommon/SDL_atarimxalloc_c.h @@ -43,3 +43,4 @@ extern void *Atari_SysMalloc(Uint32 size, Uint16 alloc_type); #endif /* _SDL_ATARI_MXALLOC_H_ */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/ataricommon/SDL_biosevents.c b/src/video/ataricommon/SDL_biosevents.c index af4b7b72c..502b58355 100644 --- a/src/video/ataricommon/SDL_biosevents.c +++ b/src/video/ataricommon/SDL_biosevents.c @@ -48,122 +48,129 @@ static unsigned char bios_currentascii[ATARIBIOS_MAXKEYS]; static SDL_bool use_dev_mouse = SDL_FALSE; /* Special keys state */ -enum { - K_RSHIFT=0, - K_LSHIFT, - K_CTRL, - K_ALT, - K_CAPSLOCK, - K_CLRHOME, - K_INSERT +enum +{ + K_RSHIFT = 0, + K_LSHIFT, + K_CTRL, + K_ALT, + K_CAPSLOCK, + K_CLRHOME, + K_INSERT }; /* The translation tables from a console scancode to a SDL keysym */ static SDLKey keymap[ATARIBIOS_MAXKEYS]; -static SDL_keysym *TranslateKey(int scancode, int asciicode, SDL_keysym *keysym, - SDL_bool pressed); +static SDL_keysym *TranslateKey(int scancode, int asciicode, + SDL_keysym * keysym, SDL_bool pressed); static void UpdateSpecialKeys(int special_keys_state); -void AtariBios_InitOSKeymap(_THIS) +void +AtariBios_InitOSKeymap(_THIS) { - int i, vectors_mask; - unsigned long dummy; - - SDL_memset(bios_currentkeyboard, 0, sizeof(bios_currentkeyboard)); - SDL_memset(bios_previouskeyboard, 0, sizeof(bios_previouskeyboard)); - - /* Initialize keymap */ - for ( i=0; i> 16; - - bios_currentkeyboard[scancode]=0xFF; - bios_currentascii[scancode]=asciicode; - } - - /* Read special keys */ - UpdateSpecialKeys(Kbshift(-1)); - - /* Now generate events */ - for (i=0; i> 16; + + bios_currentkeyboard[scancode] = 0xFF; + bios_currentascii[scancode] = asciicode; + } + + /* Read special keys */ + UpdateSpecialKeys(Kbshift(-1)); + + /* Now generate events */ + for (i = 0; i < ATARIBIOS_MAXKEYS; i++) { + /* Key pressed ? */ + if (bios_currentkeyboard[i] && !bios_previouskeyboard[i]) + SDL_PrivateKeyboard(SDL_PRESSED, + TranslateKey(i, bios_currentascii[i], + &keysym, SDL_TRUE)); + + /* Key unpressed ? */ + if (bios_previouskeyboard[i] && !bios_currentkeyboard[i]) + SDL_PrivateKeyboard(SDL_RELEASED, + TranslateKey(i, bios_currentascii[i], + &keysym, SDL_FALSE)); + } + + if (use_dev_mouse) { + SDL_AtariDevMouse_PostMouseEvents(this, SDL_TRUE); + } else { + SDL_AtariXbios_PostMouseEvents(this, SDL_TRUE); + } + + /* Will be previous table */ + SDL_memcpy(bios_previouskeyboard, bios_currentkeyboard, + ATARIBIOS_MAXKEYS); } -static void UpdateSpecialKeys(int special_keys_state) +static void +UpdateSpecialKeys(int special_keys_state) { #define UPDATE_SPECIAL_KEYS(numbit,scancode) \ { \ @@ -173,37 +180,41 @@ static void UpdateSpecialKeys(int special_keys_state) } \ } - UPDATE_SPECIAL_KEYS(K_RSHIFT, SCANCODE_RIGHTSHIFT); - UPDATE_SPECIAL_KEYS(K_LSHIFT, SCANCODE_LEFTSHIFT); - UPDATE_SPECIAL_KEYS(K_CTRL, SCANCODE_LEFTCONTROL); - UPDATE_SPECIAL_KEYS(K_ALT, SCANCODE_LEFTALT); - UPDATE_SPECIAL_KEYS(K_CAPSLOCK, SCANCODE_CAPSLOCK); + UPDATE_SPECIAL_KEYS(K_RSHIFT, SCANCODE_RIGHTSHIFT); + UPDATE_SPECIAL_KEYS(K_LSHIFT, SCANCODE_LEFTSHIFT); + UPDATE_SPECIAL_KEYS(K_CTRL, SCANCODE_LEFTCONTROL); + UPDATE_SPECIAL_KEYS(K_ALT, SCANCODE_LEFTALT); + UPDATE_SPECIAL_KEYS(K_CAPSLOCK, SCANCODE_CAPSLOCK); } -static SDL_keysym *TranslateKey(int scancode, int asciicode, SDL_keysym *keysym, - SDL_bool pressed) +static SDL_keysym * +TranslateKey(int scancode, int asciicode, SDL_keysym * keysym, + SDL_bool pressed) { - /* Set the keysym information */ - keysym->scancode = scancode; - - if (asciicode) - keysym->sym = asciicode; - else - keysym->sym = keymap[scancode]; - - keysym->mod = KMOD_NONE; - keysym->unicode = 0; - if (SDL_TranslateUNICODE && pressed) { - keysym->unicode = SDL_AtariToUnicodeTable[asciicode]; - } + /* Set the keysym information */ + keysym->scancode = scancode; + + if (asciicode) + keysym->sym = asciicode; + else + keysym->sym = keymap[scancode]; + + keysym->mod = KMOD_NONE; + keysym->unicode = 0; + if (SDL_TranslateUNICODE && pressed) { + keysym->unicode = SDL_AtariToUnicodeTable[asciicode]; + } - return(keysym); + return (keysym); } -void AtariBios_ShutdownEvents(void) +void +AtariBios_ShutdownEvents(void) { - SDL_AtariXbios_RestoreVectors(); - if (use_dev_mouse) { - SDL_AtariDevMouse_Close(); - } + SDL_AtariXbios_RestoreVectors(); + if (use_dev_mouse) { + SDL_AtariDevMouse_Close(); + } } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/ataricommon/SDL_biosevents_c.h b/src/video/ataricommon/SDL_biosevents_c.h index e17ecf0f9..c2eb7069f 100644 --- a/src/video/ataricommon/SDL_biosevents_c.h +++ b/src/video/ataricommon/SDL_biosevents_c.h @@ -40,3 +40,4 @@ extern void AtariBios_PumpEvents(_THIS); extern void AtariBios_ShutdownEvents(void); #endif /* _SDL_ATARI_BIOSEVENTS_H_ */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/ataricommon/SDL_gemdosevents.c b/src/video/ataricommon/SDL_gemdosevents.c index 9f28ca9bc..364edb12f 100644 --- a/src/video/ataricommon/SDL_gemdosevents.c +++ b/src/video/ataricommon/SDL_gemdosevents.c @@ -48,126 +48,134 @@ static unsigned char gemdos_currentascii[ATARIBIOS_MAXKEYS]; static SDL_bool use_dev_mouse = SDL_FALSE; /* Special keys state */ -enum { - K_RSHIFT=0, - K_LSHIFT, - K_CTRL, - K_ALT, - K_CAPSLOCK, - K_CLRHOME, - K_INSERT +enum +{ + K_RSHIFT = 0, + K_LSHIFT, + K_CTRL, + K_ALT, + K_CAPSLOCK, + K_CLRHOME, + K_INSERT }; -enum { - DEV_BUSY=0, - DEV_READY +enum +{ + DEV_BUSY = 0, + DEV_READY }; /* The translation tables from a console scancode to a SDL keysym */ static SDLKey keymap[ATARIBIOS_MAXKEYS]; -static SDL_keysym *TranslateKey(int scancode, int asciicode, SDL_keysym *keysym, - SDL_bool pressed); +static SDL_keysym *TranslateKey(int scancode, int asciicode, + SDL_keysym * keysym, SDL_bool pressed); static void UpdateSpecialKeys(int special_keys_state); -void AtariGemdos_InitOSKeymap(_THIS) +void +AtariGemdos_InitOSKeymap(_THIS) { - int i, vectors_mask; - unsigned long dummy; - - SDL_memset(gemdos_currentkeyboard, 0, sizeof(gemdos_currentkeyboard)); - SDL_memset(gemdos_previouskeyboard, 0, sizeof(gemdos_previouskeyboard)); - - /* Initialize keymap */ - for ( i=0; i> 16; - - gemdos_currentkeyboard[scancode]=0xFF; - gemdos_currentascii[scancode]=asciicode; - } - - /* Read special keys */ - UpdateSpecialKeys(Kbshift(-1)); - - /* Now generate events */ - for (i=0; i> 16; + + gemdos_currentkeyboard[scancode] = 0xFF; + gemdos_currentascii[scancode] = asciicode; + } + + /* Read special keys */ + UpdateSpecialKeys(Kbshift(-1)); + + /* Now generate events */ + for (i = 0; i < ATARIBIOS_MAXKEYS; i++) { + /* Key pressed ? */ + if (gemdos_currentkeyboard[i] && !gemdos_previouskeyboard[i]) + SDL_PrivateKeyboard(SDL_PRESSED, + TranslateKey(i, gemdos_currentascii[i], + &keysym, SDL_TRUE)); + + /* Key unpressed ? */ + if (gemdos_previouskeyboard[i] && !gemdos_currentkeyboard[i]) + SDL_PrivateKeyboard(SDL_RELEASED, + TranslateKey(i, gemdos_currentascii[i], + &keysym, SDL_FALSE)); + } + + if (use_dev_mouse) { + SDL_AtariDevMouse_PostMouseEvents(this, SDL_TRUE); + } else { + SDL_AtariXbios_PostMouseEvents(this, SDL_TRUE); + } + + /* Will be previous table */ + SDL_memcpy(gemdos_previouskeyboard, gemdos_currentkeyboard, + ATARIBIOS_MAXKEYS); } -static void UpdateSpecialKeys(int special_keys_state) +static void +UpdateSpecialKeys(int special_keys_state) { #define UPDATE_SPECIAL_KEYS(numbit,scancode) \ { \ @@ -177,37 +185,41 @@ static void UpdateSpecialKeys(int special_keys_state) } \ } - UPDATE_SPECIAL_KEYS(K_RSHIFT, SCANCODE_RIGHTSHIFT); - UPDATE_SPECIAL_KEYS(K_LSHIFT, SCANCODE_LEFTSHIFT); - UPDATE_SPECIAL_KEYS(K_CTRL, SCANCODE_LEFTCONTROL); - UPDATE_SPECIAL_KEYS(K_ALT, SCANCODE_LEFTALT); - UPDATE_SPECIAL_KEYS(K_CAPSLOCK, SCANCODE_CAPSLOCK); + UPDATE_SPECIAL_KEYS(K_RSHIFT, SCANCODE_RIGHTSHIFT); + UPDATE_SPECIAL_KEYS(K_LSHIFT, SCANCODE_LEFTSHIFT); + UPDATE_SPECIAL_KEYS(K_CTRL, SCANCODE_LEFTCONTROL); + UPDATE_SPECIAL_KEYS(K_ALT, SCANCODE_LEFTALT); + UPDATE_SPECIAL_KEYS(K_CAPSLOCK, SCANCODE_CAPSLOCK); } -static SDL_keysym *TranslateKey(int scancode, int asciicode, SDL_keysym *keysym, - SDL_bool pressed) +static SDL_keysym * +TranslateKey(int scancode, int asciicode, SDL_keysym * keysym, + SDL_bool pressed) { - /* Set the keysym information */ - keysym->scancode = scancode; - - if (asciicode) - keysym->sym = asciicode; - else - keysym->sym = keymap[scancode]; - - keysym->mod = KMOD_NONE; - keysym->unicode = 0; - if (SDL_TranslateUNICODE && pressed) { - keysym->unicode = SDL_AtariToUnicodeTable[asciicode]; - } + /* Set the keysym information */ + keysym->scancode = scancode; + + if (asciicode) + keysym->sym = asciicode; + else + keysym->sym = keymap[scancode]; + + keysym->mod = KMOD_NONE; + keysym->unicode = 0; + if (SDL_TranslateUNICODE && pressed) { + keysym->unicode = SDL_AtariToUnicodeTable[asciicode]; + } - return(keysym); + return (keysym); } -void AtariGemdos_ShutdownEvents(void) +void +AtariGemdos_ShutdownEvents(void) { - SDL_AtariXbios_RestoreVectors(); - if (use_dev_mouse) { - SDL_AtariDevMouse_Close(); - } + SDL_AtariXbios_RestoreVectors(); + if (use_dev_mouse) { + SDL_AtariDevMouse_Close(); + } } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/ataricommon/SDL_gemdosevents_c.h b/src/video/ataricommon/SDL_gemdosevents_c.h index 815d9d668..52e90fbd1 100644 --- a/src/video/ataricommon/SDL_gemdosevents_c.h +++ b/src/video/ataricommon/SDL_gemdosevents_c.h @@ -40,3 +40,4 @@ extern void AtariGemdos_PumpEvents(_THIS); extern void AtariGemdos_ShutdownEvents(void); #endif /* _SDL_ATARI_GEMDOSEVENTS_H_ */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/ataricommon/SDL_ikbdevents.c b/src/video/ataricommon/SDL_ikbdevents.c index 5c0b8347b..ad39195bf 100644 --- a/src/video/ataricommon/SDL_ikbdevents.c +++ b/src/video/ataricommon/SDL_ikbdevents.c @@ -38,14 +38,15 @@ #include "SDL_ikbdinterrupt_s.h" /* Special keys state */ -enum { - K_RSHIFT=0, - K_LSHIFT, - K_CTRL, - K_ALT, - K_CAPSLOCK, - K_CLRHOME, - K_INSERT +enum +{ + K_RSHIFT = 0, + K_LSHIFT, + K_CTRL, + K_ALT, + K_CAPSLOCK, + K_CLRHOME, + K_INSERT }; #define ATARIBIOS_MAXKEYS 128 @@ -57,191 +58,201 @@ enum { /* The translation tables from a console scancode to a SDL keysym */ #define KT_NOCHANGE -1 -enum { - KT_UNSHIFT=0, - KT_SHIFT=1, - KT_CAPS=2 +enum +{ + KT_UNSHIFT = 0, + KT_SHIFT = 1, + KT_CAPS = 2 }; -static Uint16 atari_prevmouseb; /* save state of mouse buttons */ -static int caps_state; /* caps lock state */ +static Uint16 atari_prevmouseb; /* save state of mouse buttons */ +static int caps_state; /* caps lock state */ _KEYTAB *curtables; static unsigned char *tab_unshift, *tab_shift, *tab_caps; static SDLKey keymap[ATARIBIOS_MAXKEYS]; -static SDL_keysym *TranslateKey(int scancode, int numkeytable, SDL_keysym *keysym, - SDL_bool pressed); +static SDL_keysym *TranslateKey(int scancode, int numkeytable, + SDL_keysym * keysym, SDL_bool pressed); -void AtariIkbd_InitOSKeymap(_THIS) +void +AtariIkbd_InitOSKeymap(_THIS) { - int i; - - SDL_memset(SDL_AtariIkbd_keyboard, KEY_UNDEFINED, ATARIBIOS_MAXKEYS); - - /* Initialize keymap */ - for ( i=0; i ascii translation */ - curtables=Keytbl(KT_NOCHANGE, KT_NOCHANGE, KT_NOCHANGE); - tab_unshift=curtables->unshift; - tab_shift=curtables->shift; - tab_caps=curtables->caps; - - /* Set Caps lock initial state */ - caps_state=(Kbshift(-1) & (1< ascii translation */ + curtables = Keytbl(KT_NOCHANGE, KT_NOCHANGE, KT_NOCHANGE); + tab_unshift = curtables->unshift; + tab_shift = curtables->shift; + tab_caps = curtables->caps; + + /* Set Caps lock initial state */ + caps_state = (Kbshift(-1) & (1 << K_CAPSLOCK)); + + /* Now install our handler */ + SDL_AtariIkbd_mouseb = SDL_AtariIkbd_mousex = SDL_AtariIkbd_mousey = 0; + atari_prevmouseb = 0; + + Supexec(SDL_AtariIkbdInstall); } -static int atari_GetButton(int button) +static int +atari_GetButton(int button) { - switch(button) - { - case 0: - return SDL_BUTTON_RIGHT; - break; - case 1: - default: - return SDL_BUTTON_LEFT; - break; - } + switch (button) { + case 0: + return SDL_BUTTON_RIGHT; + break; + case 1: + default: + return SDL_BUTTON_LEFT; + break; + } } -void AtariIkbd_PumpEvents(_THIS) +void +AtariIkbd_PumpEvents(_THIS) { - int i; - SDL_keysym keysym; - int specialkeys; - - /*--- Send keyboard events ---*/ - - /* Update caps lock state */ - if (SDL_AtariIkbd_keyboard[SCANCODE_CAPSLOCK]==KEY_PRESSED) { - caps_state ^= 1; - } - - /* Choose the translation table */ - specialkeys=KT_UNSHIFT; - if ((SDL_AtariIkbd_keyboard[SCANCODE_LEFTSHIFT]==KEY_PRESSED) - || (SDL_AtariIkbd_keyboard[SCANCODE_RIGHTSHIFT]==KEY_PRESSED)) - { - specialkeys = KT_SHIFT; - } - if (caps_state) { - specialkeys = KT_CAPS; - } - - /* Now generate events */ - for (i=0; iscancode = scancode; - - asciicode=0; - switch(numkeytable) { - case KT_UNSHIFT: - asciicode=tab_unshift[scancode]; - break; - case KT_SHIFT: - asciicode=tab_shift[scancode]; - break; - case KT_CAPS: - asciicode=tab_caps[scancode]; - break; - } - - if (asciicode) - keysym->sym = asciicode; - else - keysym->sym = keymap[scancode]; - - keysym->mod = KMOD_NONE; - keysym->unicode = 0; - if (SDL_TranslateUNICODE && pressed) { - keysym->unicode = SDL_AtariToUnicodeTable[asciicode]; - } - - return(keysym); + unsigned char asciicode; + + /* Set the keysym information */ + keysym->scancode = scancode; + + asciicode = 0; + switch (numkeytable) { + case KT_UNSHIFT: + asciicode = tab_unshift[scancode]; + break; + case KT_SHIFT: + asciicode = tab_shift[scancode]; + break; + case KT_CAPS: + asciicode = tab_caps[scancode]; + break; + } + + if (asciicode) + keysym->sym = asciicode; + else + keysym->sym = keymap[scancode]; + + keysym->mod = KMOD_NONE; + keysym->unicode = 0; + if (SDL_TranslateUNICODE && pressed) { + keysym->unicode = SDL_AtariToUnicodeTable[asciicode]; + } + + return (keysym); } -void AtariIkbd_ShutdownEvents(void) +void +AtariIkbd_ShutdownEvents(void) { - Supexec(SDL_AtariIkbdUninstall); + Supexec(SDL_AtariIkbdUninstall); } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/ataricommon/SDL_ikbdevents_c.h b/src/video/ataricommon/SDL_ikbdevents_c.h index 48310df90..6570c33c0 100644 --- a/src/video/ataricommon/SDL_ikbdevents_c.h +++ b/src/video/ataricommon/SDL_ikbdevents_c.h @@ -40,3 +40,4 @@ extern void AtariIkbd_PumpEvents(_THIS); extern void AtariIkbd_ShutdownEvents(void); #endif /* _SDL_ATARI_IKBDEVENTS_H_ */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/ataricommon/SDL_ikbdinterrupt_s.h b/src/video/ataricommon/SDL_ikbdinterrupt_s.h index 78859c617..ab6e0c760 100644 --- a/src/video/ataricommon/SDL_ikbdinterrupt_s.h +++ b/src/video/ataricommon/SDL_ikbdinterrupt_s.h @@ -44,18 +44,19 @@ /* Variables */ -extern volatile Uint8 SDL_AtariIkbd_keyboard[128]; /* Keyboard table */ -extern volatile Uint16 SDL_AtariIkbd_mouseb; /* Mouse on port 0, buttons */ -extern volatile Sint16 SDL_AtariIkbd_mousex; /* Mouse X relative motion */ -extern volatile Sint16 SDL_AtariIkbd_mousey; /* Mouse Y relative motion */ -extern volatile Uint16 SDL_AtariIkbd_joystick; /* Joystick on port 1 */ +extern volatile Uint8 SDL_AtariIkbd_keyboard[128]; /* Keyboard table */ +extern volatile Uint16 SDL_AtariIkbd_mouseb; /* Mouse on port 0, buttons */ +extern volatile Sint16 SDL_AtariIkbd_mousex; /* Mouse X relative motion */ +extern volatile Sint16 SDL_AtariIkbd_mousey; /* Mouse Y relative motion */ +extern volatile Uint16 SDL_AtariIkbd_joystick; /* Joystick on port 1 */ /* For joystick driver to know if this is usable */ extern Uint16 SDL_AtariIkbd_enabled; - -/* Functions */ + +/* Functions */ extern void SDL_AtariIkbdInstall(void); extern void SDL_AtariIkbdUninstall(void); #endif /* _SDL_IKBDINTERRUPT_S_H_ */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/ataricommon/SDL_xbiosevents.c b/src/video/ataricommon/SDL_xbiosevents.c index b744252fc..02626a218 100644 --- a/src/video/ataricommon/SDL_xbiosevents.c +++ b/src/video/ataricommon/SDL_xbiosevents.c @@ -35,114 +35,120 @@ /* Variables */ -int SDL_AtariXbios_enabled=0; +int SDL_AtariXbios_enabled = 0; /* Local variables */ -static _KBDVECS *kbdvecs; /* Pointer to access system vectors */ -static Uint16 atari_prevmouseb; /* buttons */ +static _KBDVECS *kbdvecs; /* Pointer to access system vectors */ +static Uint16 atari_prevmouseb; /* buttons */ /* Functions */ -void SDL_AtariXbios_InstallVectors(int vectors_mask) +void +SDL_AtariXbios_InstallVectors(int vectors_mask) { - void *oldpile; + void *oldpile; - /* Clear variables */ - SDL_AtariXbios_mouseb = - SDL_AtariXbios_mousex = - SDL_AtariXbios_mousey = - SDL_AtariXbios_joystick = - atari_prevmouseb = 0; + /* Clear variables */ + SDL_AtariXbios_mouseb = + SDL_AtariXbios_mousex = + SDL_AtariXbios_mousey = + SDL_AtariXbios_joystick = atari_prevmouseb = 0; - if (vectors_mask==0) { - SDL_AtariXbios_enabled=0; - return; - } + if (vectors_mask == 0) { + SDL_AtariXbios_enabled = 0; + return; + } - /* Read IKBD vectors base */ - kbdvecs=Kbdvbase(); + /* Read IKBD vectors base */ + kbdvecs = Kbdvbase(); - /* Go to supervisor mode */ - oldpile=(void *)Super(0); + /* Go to supervisor mode */ + oldpile = (void *) Super(0); - /* Install our vectors */ - SDL_AtariXbios_Install( - kbdvecs, - (vectors_mask & ATARI_XBIOS_MOUSEEVENTS) ? SDL_AtariXbios_MouseVector : NULL, - (vectors_mask & ATARI_XBIOS_JOYSTICKEVENTS) ? SDL_AtariXbios_JoystickVector : NULL - ); + /* Install our vectors */ + SDL_AtariXbios_Install(kbdvecs, + (vectors_mask & ATARI_XBIOS_MOUSEEVENTS) ? + SDL_AtariXbios_MouseVector : NULL, + (vectors_mask & ATARI_XBIOS_JOYSTICKEVENTS) ? + SDL_AtariXbios_JoystickVector : NULL); - /* Back to user mode */ - Super(oldpile); + /* Back to user mode */ + Super(oldpile); - SDL_AtariXbios_enabled=1; + SDL_AtariXbios_enabled = 1; } -void SDL_AtariXbios_RestoreVectors(void) +void +SDL_AtariXbios_RestoreVectors(void) { - void *oldpile; + void *oldpile; - if (SDL_AtariXbios_enabled==0) { - return; - } + if (SDL_AtariXbios_enabled == 0) { + return; + } - /* Read IKBD vectors base */ - kbdvecs=Kbdvbase(); + /* Read IKBD vectors base */ + kbdvecs = Kbdvbase(); - /* Go to supervisor mode */ - oldpile=(void *)Super(NULL); + /* Go to supervisor mode */ + oldpile = (void *) Super(NULL); - /* Reinstall system vector */ - SDL_AtariXbios_Restore(kbdvecs); + /* Reinstall system vector */ + SDL_AtariXbios_Restore(kbdvecs); - /* Back to user mode */ - Super(oldpile); + /* Back to user mode */ + Super(oldpile); } -static int atari_GetButton(int button) +static int +atari_GetButton(int button) { - switch(button) - { - case 0: - return SDL_BUTTON_RIGHT; - break; - case 1: - default: - return SDL_BUTTON_LEFT; - break; - } + switch (button) { + case 0: + return SDL_BUTTON_RIGHT; + break; + case 1: + default: + return SDL_BUTTON_LEFT; + break; + } } -void SDL_AtariXbios_PostMouseEvents(_THIS, SDL_bool buttonEvents) +void +SDL_AtariXbios_PostMouseEvents(_THIS, SDL_bool buttonEvents) { - if (SDL_AtariXbios_enabled==0) { - return; - } - - /* Mouse motion ? */ - if (SDL_AtariXbios_mousex || SDL_AtariXbios_mousey) { - SDL_PrivateMouseMotion(0, 1, SDL_AtariXbios_mousex, SDL_AtariXbios_mousey); - SDL_AtariXbios_mousex = SDL_AtariXbios_mousey = 0; - } - - /* Mouse button ? */ - if (buttonEvents && (SDL_AtariXbios_mouseb != atari_prevmouseb)) { - int i; - - for (i=0;i<2;i++) { - int curbutton, prevbutton; - - curbutton = SDL_AtariXbios_mouseb & (1<Bounds(); - Draw(bounds); - } - } - - /* Drawing portion of this complete breakfast. :) */ - virtual void SetBitmap(BBitmap *bitmap) { - if ( image ) { - delete image; - } - image = bitmap; - } - virtual void Draw(BRect updateRect) { - if ( image ) { - if(xoff || yoff) { - BRect dest; - dest.top = updateRect.top + yoff; - dest.left = updateRect.left + xoff; - dest.bottom = updateRect.bottom + yoff; - dest.right = updateRect.right + xoff; - DrawBitmap(image, updateRect, dest); - } else { - DrawBitmap(image, updateRect, updateRect); - } - } - } - virtual void DrawAsync(BRect updateRect) { - if(xoff || yoff) { - BRect dest; - dest.top = updateRect.top + yoff; - dest.left = updateRect.left + xoff; - dest.bottom = updateRect.bottom + yoff; - dest.right = updateRect.right + xoff;; - DrawBitmapAsync(image, updateRect, dest); - } else { - DrawBitmapAsync(image, updateRect, updateRect); - } - } + public: + SDL_BView(BRect frame):BView(frame, "SDL View", B_FOLLOW_ALL_SIDES, + (B_WILL_DRAW | B_FRAME_EVENTS)) + { + image = NULL; + xoff = yoff = 0; + SetViewColor(0, 0, 0, 0); + SetHighColor(0, 0, 0, 0); + } + virtual ~ SDL_BView() + { + SetBitmap(NULL); + } + /* Set drawing offsets for fullscreen mode */ + virtual void SetXYOffset(int x, int y) + { + xoff = x; + yoff = y; + } + virtual void GetXYOffset(int &x, int &y) + { + x = xoff; + y = yoff; + } + /* The view changed size. If it means we're in fullscreen, we + * draw a nice black box in the entire view to get black borders. + */ + virtual void FrameResized(float width, float height) + { + BRect bounds; + bounds.top = bounds.left = 0; + bounds.right = width; + bounds.bottom = height; + /* Fill the entire view with black */ + FillRect(bounds, B_SOLID_HIGH); + /* And if there's an image, redraw it. */ + if (image) { + bounds = image->Bounds(); + Draw(bounds); + } + } + + /* Drawing portion of this complete breakfast. :) */ + virtual void SetBitmap(BBitmap * bitmap) + { + if (image) { + delete image; + } + image = bitmap; + } + virtual void Draw(BRect updateRect) + { + if (image) { + if (xoff || yoff) { + BRect dest; + dest.top = updateRect.top + yoff; + dest.left = updateRect.left + xoff; + dest.bottom = updateRect.bottom + yoff; + dest.right = updateRect.right + xoff; + DrawBitmap(image, updateRect, dest); + } else { + DrawBitmap(image, updateRect, updateRect); + } + } + } + virtual void DrawAsync(BRect updateRect) + { + if (xoff || yoff) { + BRect dest; + dest.top = updateRect.top + yoff; + dest.left = updateRect.left + xoff; + dest.bottom = updateRect.bottom + yoff; + dest.right = updateRect.right + xoff;; + DrawBitmapAsync(image, updateRect, dest); + } else { + DrawBitmapAsync(image, updateRect, updateRect); + } + } -private: - BBitmap *image; - int xoff, yoff; + private: + BBitmap * image; + int xoff, yoff; }; #endif /* _SDL_BView_h */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/bwindow/SDL_BWin.h b/src/video/bwindow/SDL_BWin.h index a6d3ef8d9..ef94ad54a 100644 --- a/src/video/bwindow/SDL_BWin.h +++ b/src/video/bwindow/SDL_BWin.h @@ -38,521 +38,556 @@ #include "SDL_events.h" #include "SDL_BView.h" -extern "C" { +extern "C" +{ #include "../../events/SDL_events_c.h" }; -class SDL_BWin : public BDirectWindow +class SDL_BWin:public BDirectWindow { -public: - SDL_BWin(BRect bounds) : - BDirectWindow(bounds, "Untitled", B_TITLED_WINDOW, 0) { - InitKeyboard(); - last_buttons = 0; - - the_view = NULL; + public: + SDL_BWin(BRect bounds):BDirectWindow(bounds, "Untitled", + B_TITLED_WINDOW, 0) + { + InitKeyboard(); + last_buttons = 0; + + the_view = NULL; #if SDL_VIDEO_OPENGL - SDL_GLView = NULL; + SDL_GLView = NULL; #endif - SDL_View = NULL; - Unlock(); - shown = false; - inhibit_resize = false; - } - - virtual ~SDL_BWin() { - Lock(); - if ( the_view ) { + SDL_View = NULL; + Unlock(); + shown = false; + inhibit_resize = false; + } + + virtual ~ SDL_BWin() + { + Lock(); + if (the_view) { #if SDL_VIDEO_OPENGL - if ( the_view == SDL_GLView ) { - SDL_GLView->UnlockGL(); - } + if (the_view == SDL_GLView) { + SDL_GLView->UnlockGL(); + } #endif - RemoveChild(the_view); - the_view = NULL; - } - Unlock(); + RemoveChild(the_view); + the_view = NULL; + } + Unlock(); #if SDL_VIDEO_OPENGL - if ( SDL_GLView ) { - delete SDL_GLView; - } + if (SDL_GLView) { + delete SDL_GLView; + } #endif - if ( SDL_View ) { - delete SDL_View; - } - } - - virtual void InitKeyboard(void) { - for ( uint i=0; iLockGL(); - the_view = SDL_GLView; - } + if (SDL_GLView == NULL) { + SDL_GLView = new BGLView(Bounds(), "SDL GLView", + B_FOLLOW_ALL_SIDES, + (B_WILL_DRAW | B_FRAME_EVENTS), + gl_flags); + } + if (the_view != SDL_GLView) { + if (the_view) { + RemoveChild(the_view); + } + AddChild(SDL_GLView); + SDL_GLView->LockGL(); + the_view = SDL_GLView; + } #else - SDL_SetError("OpenGL support not enabled"); - retval = -1; + SDL_SetError("OpenGL support not enabled"); + retval = -1; #endif - } else { - if ( SDL_View == NULL ) { - SDL_View = new SDL_BView(Bounds()); - } - if ( the_view != SDL_View ) { - if ( the_view ) { + } else { + if (SDL_View == NULL) { + SDL_View = new SDL_BView(Bounds()); + } + if (the_view != SDL_View) { + if (the_view) { #if SDL_VIDEO_OPENGL - if ( the_view == SDL_GLView ) { - SDL_GLView->UnlockGL(); - } + if (the_view == SDL_GLView) { + SDL_GLView->UnlockGL(); + } #endif - RemoveChild(the_view); - } - AddChild(SDL_View); - the_view = SDL_View; - } - } - Unlock(); - return(retval); - } - virtual void SetBitmap(BBitmap *bitmap) { - SDL_View->SetBitmap(bitmap); - } - virtual void SetXYOffset(int x, int y) { + RemoveChild(the_view); + } + AddChild(SDL_View); + the_view = SDL_View; + } + } + Unlock(); + return (retval); + } + virtual void SetBitmap(BBitmap * bitmap) + { + SDL_View->SetBitmap(bitmap); + } + virtual void SetXYOffset(int x, int y) + { #if SDL_VIDEO_OPENGL - if ( the_view == SDL_GLView ) { - return; - } + if (the_view == SDL_GLView) { + return; + } #endif - SDL_View->SetXYOffset(x, y); - } - virtual void GetXYOffset(int &x, int &y) { + SDL_View->SetXYOffset(x, y); + } + virtual void GetXYOffset(int &x, int &y) + { #if SDL_VIDEO_OPENGL - if ( the_view == SDL_GLView ) { - x = 0; - y = 0; - return; - } + if (the_view == SDL_GLView) { + x = 0; + y = 0; + return; + } #endif - SDL_View->GetXYOffset(x, y); - } - virtual bool BeginDraw(void) { - return(Lock()); - } - virtual void DrawAsync(BRect updateRect) { - SDL_View->DrawAsync(updateRect); - } - virtual void EndDraw(void) { - SDL_View->Sync(); - Unlock(); - } + SDL_View->GetXYOffset(x, y); + } + virtual bool BeginDraw(void) + { + return (Lock()); + } + virtual void DrawAsync(BRect updateRect) + { + SDL_View->DrawAsync(updateRect); + } + virtual void EndDraw(void) + { + SDL_View->Sync(); + Unlock(); + } #if SDL_VIDEO_OPENGL - virtual void SwapBuffers(void) { - SDL_GLView->UnlockGL(); - SDL_GLView->LockGL(); - SDL_GLView->SwapBuffers(); - } + virtual void SwapBuffers(void) + { + SDL_GLView->UnlockGL(); + SDL_GLView->LockGL(); + SDL_GLView->SwapBuffers(); + } #endif - virtual BView *View(void) { - return(the_view); - } - - /* Hook functions -- overridden */ - virtual void Minimize(bool minimize) { - /* This is only called when mimimized, not when restored */ - //SDL_PrivateAppActive(minimize, SDL_APPACTIVE); - BWindow::Minimize(minimize); - } - virtual void WindowActivated(bool active) { - SDL_PrivateAppActive(active, SDL_APPINPUTFOCUS); - } - virtual bool QuitRequested(void) { - if ( SDL_BeAppActive > 0 ) { - SDL_PrivateQuit(); - /* We don't ever actually close the window here because - the application should respond to the quit request, - or ignore it as desired. - */ - return(false); - } - return(true); /* Close the app window */ - } - virtual void Quit() { - if (!IsLocked()) - Lock(); - BDirectWindow::Quit(); - } - - virtual int16 Translate2Unicode(const char *buf) { - int32 state, srclen, dstlen; - unsigned char destbuf[2]; - Uint16 unicode = 0; - - if ((uchar)buf[0] > 127) { - state = 0; - srclen = SDL_strlen(buf); - dstlen = sizeof(destbuf); - convert_from_utf8(B_UNICODE_CONVERSION, buf, &srclen, (char *)destbuf, &dstlen, &state); - unicode = destbuf[0]; - unicode <<= 8; - unicode |= destbuf[1]; - } else - unicode = buf[0]; - - /* For some reason function keys map to control characters */ + virtual BView *View(void) + { + return (the_view); + } + + /* Hook functions -- overridden */ + virtual void Minimize(bool minimize) + { + /* This is only called when mimimized, not when restored */ + //SDL_PrivateAppActive(minimize, SDL_APPACTIVE); + BWindow::Minimize(minimize); + } + virtual void WindowActivated(bool active) + { + SDL_PrivateAppActive(active, SDL_APPINPUTFOCUS); + } + virtual bool QuitRequested(void) + { + if (SDL_BeAppActive > 0) { + SDL_PrivateQuit(); + /* We don't ever actually close the window here because + the application should respond to the quit request, + or ignore it as desired. + */ + return (false); + } + return (true); /* Close the app window */ + } + virtual void Quit() + { + if (!IsLocked()) + Lock(); + BDirectWindow::Quit(); + } + + virtual int16 Translate2Unicode(const char *buf) + { + int32 state, srclen, dstlen; + unsigned char destbuf[2]; + Uint16 unicode = 0; + + if ((uchar) buf[0] > 127) { + state = 0; + srclen = SDL_strlen(buf); + dstlen = sizeof(destbuf); + convert_from_utf8(B_UNICODE_CONVERSION, buf, &srclen, + (char *) destbuf, &dstlen, &state); + unicode = destbuf[0]; + unicode <<= 8; + unicode |= destbuf[1]; + } else + unicode = buf[0]; + + /* For some reason function keys map to control characters */ # define CTRL(X) ((X)-'@') - switch (unicode) { - case CTRL('A'): - case CTRL('B'): - case CTRL('C'): - case CTRL('D'): - case CTRL('E'): - case CTRL('K'): - case CTRL('L'): - case CTRL('P'): - if ( ! (SDL_GetModState() & KMOD_CTRL) ) - unicode = 0; - break; - /* Keyboard input maps newline to carriage return */ - case '\n': - unicode = '\r'; - break; - default: - break; - } - - return unicode; - } - - virtual void DispatchMessage(BMessage *msg, BHandler *target) { - switch (msg->what) { - case B_MOUSE_MOVED: - { - BPoint where; - int32 transit; - if (msg->FindPoint("where", &where) == B_OK && msg->FindInt32("be:transit", &transit) == B_OK) { - if (transit == B_EXITED_VIEW) { - if ( SDL_GetAppState() & SDL_APPMOUSEFOCUS ) { - SDL_PrivateAppActive(0, SDL_APPMOUSEFOCUS); - be_app->SetCursor(B_HAND_CURSOR); - } - } else { - int x, y; - if ( ! (SDL_GetAppState() & SDL_APPMOUSEFOCUS) ) { - SDL_PrivateAppActive(1, SDL_APPMOUSEFOCUS); - SDL_SetCursor(NULL); - } - GetXYOffset(x, y); - x = (int)where.x - x; - y = (int)where.y - y; - SDL_PrivateMouseMotion(0, 0, x, y); - } - } - break; - } - - case B_MOUSE_DOWN: - { - /* it looks like mouse down is send only for first clicked - button, each next is not send while last one is holded */ - int32 buttons; - int sdl_buttons = 0; - if (msg->FindInt32("buttons", &buttons) == B_OK) { - /* Add any mouse button events */ - if (buttons & B_PRIMARY_MOUSE_BUTTON) { - sdl_buttons |= SDL_BUTTON_LEFT; - } - if (buttons & B_SECONDARY_MOUSE_BUTTON) { - sdl_buttons |= SDL_BUTTON_RIGHT; - } - if (buttons & B_TERTIARY_MOUSE_BUTTON) { - sdl_buttons |= SDL_BUTTON_MIDDLE; - } - SDL_PrivateMouseButton(SDL_PRESSED, sdl_buttons, 0, 0); - - last_buttons = buttons; - } - break; - } - - case B_MOUSE_UP: - { - /* mouse up doesn't give which button was released, - only state of buttons (after release, so it's always = 0), - which is not what we need ;] - So we need to store button in mouse down, and restore - in mouse up :( - mouse up is (similarly to mouse down) send only for - first button down (ie. it's no send if we click another button - without releasing previous one first) - but that's probably - because of how drivers are written?, not BeOS itself. */ - int32 buttons; - int sdl_buttons = 0; - if (msg->FindInt32("buttons", &buttons) == B_OK) { - /* Add any mouse button events */ - if ((buttons ^ B_PRIMARY_MOUSE_BUTTON) & last_buttons) { - sdl_buttons |= SDL_BUTTON_LEFT; - } - if ((buttons ^ B_SECONDARY_MOUSE_BUTTON) & last_buttons) { - sdl_buttons |= SDL_BUTTON_RIGHT; - } - if ((buttons ^ B_TERTIARY_MOUSE_BUTTON) & last_buttons) { - sdl_buttons |= SDL_BUTTON_MIDDLE; - } - SDL_PrivateMouseButton(SDL_RELEASED, sdl_buttons, 0, 0); - - last_buttons = buttons; - } - break; - } - - case B_MOUSE_WHEEL_CHANGED: - { - float x, y; - x = y = 0; - if (msg->FindFloat("be:wheel_delta_x", &x) == B_OK && msg->FindFloat("be:wheel_delta_y", &y) == B_OK) { - if (x < 0 || y < 0) { - SDL_PrivateMouseButton(SDL_PRESSED, SDL_BUTTON_WHEELDOWN, 0, 0); - SDL_PrivateMouseButton(SDL_RELEASED, SDL_BUTTON_WHEELDOWN, 0, 0); - } else if (x > 0 || y > 0) { - SDL_PrivateMouseButton(SDL_PRESSED, SDL_BUTTON_WHEELUP, 0, 0); - SDL_PrivateMouseButton(SDL_RELEASED, SDL_BUTTON_WHEELUP, 0, 0); - } - } - break; - } - - case B_KEY_DOWN: - case B_UNMAPPED_KEY_DOWN: /* modifier keys are unmapped */ - { - int32 key; - int32 modifiers; - int32 key_repeat; - /* Workaround for SDL message queue being filled too fast because of BeOS own key-repeat mechanism */ - if (msg->FindInt32("be:key_repeat", &key_repeat) == B_OK && key_repeat > 0) - break; - - if (msg->FindInt32("key", &key) == B_OK && msg->FindInt32("modifiers", &modifiers) == B_OK) { - SDL_keysym keysym; - keysym.scancode = key; - if ((key > 0) && (key < 128)) { - keysym.sym = keymap[key]; - } else { - keysym.sym = SDLK_UNKNOWN; - } - /* FIX THIS? - it seems SDL_PrivateKeyboard() changes mod value - anyway, and doesn't care about what we setup here */ - keysym.mod = KMOD_NONE; - keysym.unicode = 0; - if (SDL_TranslateUNICODE) { - const char *bytes; - if (msg->FindString("bytes", &bytes) == B_OK) { - /* FIX THIS? - this cares only about first "letter", - so if someone maps some key to print - "BeOS rulez!" only "B" will be used. */ - keysym.unicode = Translate2Unicode(bytes); - } - } - SDL_PrivateKeyboard(SDL_PRESSED, &keysym); - } - break; - } - - case B_KEY_UP: - case B_UNMAPPED_KEY_UP: /* modifier keys are unmapped */ - { - int32 key; - int32 modifiers; - if (msg->FindInt32("key", &key) == B_OK && msg->FindInt32("modifiers", &modifiers) == B_OK) { - SDL_keysym keysym; - keysym.scancode = key; - if ((key > 0) && (key < 128)) { - keysym.sym = keymap[key]; - } else { - keysym.sym = SDLK_UNKNOWN; - } - keysym.mod = KMOD_NONE; /* FIX THIS? */ - keysym.unicode = 0; - if (SDL_TranslateUNICODE) { - const char *bytes; - if (msg->FindString("bytes", &bytes) == B_OK) { - keysym.unicode = Translate2Unicode(bytes); - } - } - SDL_PrivateKeyboard(SDL_RELEASED, &keysym); - } - break; - } - - default: - /* move it after switch{} so it's always handled - that way we keep BeOS feautures like: - - CTRL+Q to close window (and other shortcuts) - - PrintScreen to make screenshot into /boot/home - - etc.. */ - //BDirectWindow::DispatchMessage(msg, target); - break; - } - BDirectWindow::DispatchMessage(msg, target); - } - -private: + switch (unicode) { + case CTRL('A'): + case CTRL('B'): + case CTRL('C'): + case CTRL('D'): + case CTRL('E'): + case CTRL('K'): + case CTRL('L'): + case CTRL('P'): + if (!(SDL_GetModState() & KMOD_CTRL)) + unicode = 0; + break; + /* Keyboard input maps newline to carriage return */ + case '\n': + unicode = '\r'; + break; + default: + break; + } + + return unicode; + } + + virtual void DispatchMessage(BMessage * msg, BHandler * target) + { + switch (msg->what) { + case B_MOUSE_MOVED: + { + BPoint where; + int32 transit; + if (msg->FindPoint("where", &where) == B_OK + && msg->FindInt32("be:transit", &transit) == B_OK) { + if (transit == B_EXITED_VIEW) { + if (SDL_GetAppState() & SDL_APPMOUSEFOCUS) { + SDL_PrivateAppActive(0, SDL_APPMOUSEFOCUS); + be_app->SetCursor(B_HAND_CURSOR); + } + } else { + int x, y; + if (!(SDL_GetAppState() & SDL_APPMOUSEFOCUS)) { + SDL_PrivateAppActive(1, SDL_APPMOUSEFOCUS); + SDL_SetCursor(NULL); + } + GetXYOffset(x, y); + x = (int) where.x - x; + y = (int) where.y - y; + SDL_PrivateMouseMotion(0, 0, x, y); + } + } + break; + } + + case B_MOUSE_DOWN: + { + /* it looks like mouse down is send only for first clicked + button, each next is not send while last one is holded */ + int32 buttons; + int sdl_buttons = 0; + if (msg->FindInt32("buttons", &buttons) == B_OK) { + /* Add any mouse button events */ + if (buttons & B_PRIMARY_MOUSE_BUTTON) { + sdl_buttons |= SDL_BUTTON_LEFT; + } + if (buttons & B_SECONDARY_MOUSE_BUTTON) { + sdl_buttons |= SDL_BUTTON_RIGHT; + } + if (buttons & B_TERTIARY_MOUSE_BUTTON) { + sdl_buttons |= SDL_BUTTON_MIDDLE; + } + SDL_PrivateMouseButton(SDL_PRESSED, sdl_buttons, 0, 0); + + last_buttons = buttons; + } + break; + } + + case B_MOUSE_UP: + { + /* mouse up doesn't give which button was released, + only state of buttons (after release, so it's always = 0), + which is not what we need ;] + So we need to store button in mouse down, and restore + in mouse up :( + mouse up is (similarly to mouse down) send only for + first button down (ie. it's no send if we click another button + without releasing previous one first) - but that's probably + because of how drivers are written?, not BeOS itself. */ + int32 buttons; + int sdl_buttons = 0; + if (msg->FindInt32("buttons", &buttons) == B_OK) { + /* Add any mouse button events */ + if ((buttons ^ B_PRIMARY_MOUSE_BUTTON) & last_buttons) { + sdl_buttons |= SDL_BUTTON_LEFT; + } + if ((buttons ^ B_SECONDARY_MOUSE_BUTTON) & last_buttons) { + sdl_buttons |= SDL_BUTTON_RIGHT; + } + if ((buttons ^ B_TERTIARY_MOUSE_BUTTON) & last_buttons) { + sdl_buttons |= SDL_BUTTON_MIDDLE; + } + SDL_PrivateMouseButton(SDL_RELEASED, sdl_buttons, 0, 0); + + last_buttons = buttons; + } + break; + } + + case B_MOUSE_WHEEL_CHANGED: + { + float x, y; + x = y = 0; + if (msg->FindFloat("be:wheel_delta_x", &x) == B_OK + && msg->FindFloat("be:wheel_delta_y", &y) == B_OK) { + if (x < 0 || y < 0) { + SDL_PrivateMouseButton(SDL_PRESSED, + SDL_BUTTON_WHEELDOWN, 0, 0); + SDL_PrivateMouseButton(SDL_RELEASED, + SDL_BUTTON_WHEELDOWN, 0, 0); + } else if (x > 0 || y > 0) { + SDL_PrivateMouseButton(SDL_PRESSED, + SDL_BUTTON_WHEELUP, 0, 0); + SDL_PrivateMouseButton(SDL_RELEASED, + SDL_BUTTON_WHEELUP, 0, 0); + } + } + break; + } + + case B_KEY_DOWN: + case B_UNMAPPED_KEY_DOWN: /* modifier keys are unmapped */ + { + int32 key; + int32 modifiers; + int32 key_repeat; + /* Workaround for SDL message queue being filled too fast because of BeOS own key-repeat mechanism */ + if (msg->FindInt32("be:key_repeat", &key_repeat) == B_OK + && key_repeat > 0) + break; + + if (msg->FindInt32("key", &key) == B_OK + && msg->FindInt32("modifiers", &modifiers) == B_OK) { + SDL_keysym keysym; + keysym.scancode = key; + if ((key > 0) && (key < 128)) { + keysym.sym = keymap[key]; + } else { + keysym.sym = SDLK_UNKNOWN; + } + /* FIX THIS? + it seems SDL_PrivateKeyboard() changes mod value + anyway, and doesn't care about what we setup here */ + keysym.mod = KMOD_NONE; + keysym.unicode = 0; + if (SDL_TranslateUNICODE) { + const char *bytes; + if (msg->FindString("bytes", &bytes) == B_OK) { + /* FIX THIS? + this cares only about first "letter", + so if someone maps some key to print + "BeOS rulez!" only "B" will be used. */ + keysym.unicode = Translate2Unicode(bytes); + } + } + SDL_PrivateKeyboard(SDL_PRESSED, &keysym); + } + break; + } + + case B_KEY_UP: + case B_UNMAPPED_KEY_UP: /* modifier keys are unmapped */ + { + int32 key; + int32 modifiers; + if (msg->FindInt32("key", &key) == B_OK + && msg->FindInt32("modifiers", &modifiers) == B_OK) { + SDL_keysym keysym; + keysym.scancode = key; + if ((key > 0) && (key < 128)) { + keysym.sym = keymap[key]; + } else { + keysym.sym = SDLK_UNKNOWN; + } + keysym.mod = KMOD_NONE; /* FIX THIS? */ + keysym.unicode = 0; + if (SDL_TranslateUNICODE) { + const char *bytes; + if (msg->FindString("bytes", &bytes) == B_OK) { + keysym.unicode = Translate2Unicode(bytes); + } + } + SDL_PrivateKeyboard(SDL_RELEASED, &keysym); + } + break; + } + + default: + /* move it after switch{} so it's always handled + that way we keep BeOS feautures like: + - CTRL+Q to close window (and other shortcuts) + - PrintScreen to make screenshot into /boot/home + - etc.. */ + //BDirectWindow::DispatchMessage(msg, target); + break; + } + BDirectWindow::DispatchMessage(msg, target); + } + + private: #if SDL_VIDEO_OPENGL - BGLView *SDL_GLView; + BGLView * SDL_GLView; #endif - SDL_BView *SDL_View; - BView *the_view; + SDL_BView *SDL_View; + BView *the_view; - bool shown; - bool inhibit_resize; + bool shown; + bool inhibit_resize; - int32 last_buttons; - SDLKey keymap[128]; + int32 last_buttons; + SDLKey keymap[128]; }; #endif /* _SDL_BWin_h */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/bwindow/SDL_lowvideo.h b/src/video/bwindow/SDL_lowvideo.h index 7af004b9c..06f375146 100644 --- a/src/video/bwindow/SDL_lowvideo.h +++ b/src/video/bwindow/SDL_lowvideo.h @@ -32,20 +32,21 @@ #define _THIS SDL_VideoDevice *_this /* Private display data */ -struct SDL_PrivateVideoData { - /* The main window */ - SDL_BWin *SDL_Win; +struct SDL_PrivateVideoData +{ + /* The main window */ + SDL_BWin *SDL_Win; - /* The fullscreen mode list */ - display_mode saved_mode; -#define NUM_MODELISTS 4 /* 8, 16, 24, and 32 bits-per-pixel */ - int SDL_nummodes[NUM_MODELISTS]; - SDL_Rect **SDL_modelist[NUM_MODELISTS]; + /* The fullscreen mode list */ + display_mode saved_mode; +#define NUM_MODELISTS 4 /* 8, 16, 24, and 32 bits-per-pixel */ + int SDL_nummodes[NUM_MODELISTS]; + SDL_Rect **SDL_modelist[NUM_MODELISTS]; - /* A completely clear cursor */ - WMcursor *BlankCursor; + /* A completely clear cursor */ + WMcursor *BlankCursor; - SDL_Overlay *overlay; + SDL_Overlay *overlay; }; /* Old variable names */ #define SDL_Win (_this->hidden->SDL_Win) @@ -56,3 +57,4 @@ struct SDL_PrivateVideoData { #define current_overlay (_this->hidden->overlay) #endif /* _SDL_lowvideo_h */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/bwindow/SDL_sysevents.cc b/src/video/bwindow/SDL_sysevents.cc index dee2f97d2..fb18f7ddc 100644 --- a/src/video/bwindow/SDL_sysevents.cc +++ b/src/video/bwindow/SDL_sysevents.cc @@ -29,18 +29,21 @@ #include "SDL_BWin.h" #include "SDL_lowvideo.h" -extern "C" { +extern "C" +{ #include "../../events/SDL_sysevents.h" #include "../../events/SDL_events_c.h" #include "SDL_sysevents_c.h" -void BE_PumpEvents(_THIS) -{ -} + void BE_PumpEvents(_THIS) + { + } -void BE_InitOSKeymap(_THIS) -{ -} + void BE_InitOSKeymap(_THIS) + { + } + +}; /* Extern C */ -}; /* Extern C */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/bwindow/SDL_sysevents_c.h b/src/video/bwindow/SDL_sysevents_c.h index e2ef3f563..358b2de05 100644 --- a/src/video/bwindow/SDL_sysevents_c.h +++ b/src/video/bwindow/SDL_sysevents_c.h @@ -29,3 +29,4 @@ extern void BE_InitOSKeymap(_THIS); extern void BE_PumpEvents(_THIS); +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/bwindow/SDL_sysmouse.cc b/src/video/bwindow/SDL_sysmouse.cc index 34644f6de..3f7c10198 100644 --- a/src/video/bwindow/SDL_sysmouse.cc +++ b/src/video/bwindow/SDL_sysmouse.cc @@ -26,7 +26,8 @@ #include "SDL_BWin.h" -extern "C" { +extern "C" +{ #include "SDL_sysmouse_c.h" @@ -34,105 +35,111 @@ extern "C" { #define PADDED_BITS(bits) ((bits+7)/8) /* The implementation dependent data for the window manager cursor */ -struct WMcursor { - char *bits; -}; + struct WMcursor + { + char *bits; + }; /* Can this be done in the BeOS? */ -WMcursor *BE_CreateWMCursor(_THIS, - Uint8 *data, Uint8 *mask, int w, int h, int hot_x, int hot_y) -{ - WMcursor *cursor; - int allowed_x; - int allowed_y; - int run, pad, i; - char *cptr; - - allowed_x = 16; /* BeOS limitation */ - allowed_y = 16; /* BeOS limitation */ - if ( (w > allowed_x) || (h > allowed_y) ) { - SDL_SetError("Only cursors of dimension (%dx%d) are allowed", - allowed_x, allowed_y); - return(NULL); - } - - /* Allocate the cursor */ - cursor = (WMcursor *)SDL_malloc(sizeof(WMcursor)); - if ( cursor == NULL ) { - SDL_OutOfMemory(); - return(NULL); - } - cursor->bits = (char *)SDL_malloc(4+2*((allowed_x/8)*allowed_y)); - if ( cursor->bits == NULL ) { - SDL_free(cursor); - SDL_OutOfMemory(); - return(NULL); - } - cursor->bits[0] = allowed_y; /* Size of the cursor */ - cursor->bits[1] = 1; /* Bit depth of cursor */ - cursor->bits[2] = hot_y; - cursor->bits[3] = hot_x; - cptr = &cursor->bits[4]; - - /* Pad out to the normal cursor size */ - run = PADDED_BITS(w); - pad = PADDED_BITS(allowed_x)-run; - for ( i=0; iLock() ) { - if ( cursor == NULL ) { - if ( SDL_BlankCursor != NULL ) { - be_app->SetCursor(SDL_BlankCursor->bits); - } - } else { - be_app->SetCursor(cursor->bits); - } - be_app->Unlock(); - } - return(1); -} - -void BE_FreeWMCursor(_THIS, WMcursor *cursor) -{ - SDL_free(cursor->bits); - SDL_free(cursor); -} + WMcursor *BE_CreateWMCursor(_THIS, + Uint8 * data, Uint8 * mask, int w, int h, + int hot_x, int hot_y) + { + WMcursor *cursor; + int allowed_x; + int allowed_y; + int run, pad, i; + char *cptr; + + allowed_x = 16; /* BeOS limitation */ + allowed_y = 16; /* BeOS limitation */ + if ((w > allowed_x) || (h > allowed_y)) + { + SDL_SetError("Only cursors of dimension (%dx%d) are allowed", + allowed_x, allowed_y); + return (NULL); + } + + /* Allocate the cursor */ + cursor = (WMcursor *) SDL_malloc(sizeof(WMcursor)); + if (cursor == NULL) { + SDL_OutOfMemory(); + return (NULL); + } + cursor->bits = + (char *) SDL_malloc(4 + 2 * ((allowed_x / 8) * allowed_y)); + if (cursor->bits == NULL) { + SDL_free(cursor); + SDL_OutOfMemory(); + return (NULL); + } + cursor->bits[0] = allowed_y; /* Size of the cursor */ + cursor->bits[1] = 1; /* Bit depth of cursor */ + cursor->bits[2] = hot_y; + cursor->bits[3] = hot_x; + cptr = &cursor->bits[4]; + + /* Pad out to the normal cursor size */ + run = PADDED_BITS(w); + pad = PADDED_BITS(allowed_x) - run; + for (i = 0; i < h; ++i) { + SDL_memcpy(cptr, data, run); + SDL_memset(cptr + run, 0, pad); + data += run; + cptr += (run + pad); + } + for (; i < allowed_y; ++i) { + SDL_memset(cptr, 0, run + pad); + cptr += (run + pad); + } + for (i = 0; i < h; ++i) { + /* FIXME: The mask should be OR'd with the data to turn + inverted color pixels black, since inverted color pixels + aren't supported under BeOS. + */ + SDL_memcpy(cptr, mask, run); + SDL_memset(cptr + run, 0, pad); + mask += run; + cptr += (run + pad); + } + for (; i < allowed_y; ++i) { + SDL_memset(cptr, 0, run + pad); + cptr += (run + pad); + } + return (cursor); + } + + int BE_ShowWMCursor(_THIS, WMcursor * cursor) + { + if (be_app->Lock()) { + if (cursor == NULL) { + if (SDL_BlankCursor != NULL) { + be_app->SetCursor(SDL_BlankCursor->bits); + } + } else { + be_app->SetCursor(cursor->bits); + } + be_app->Unlock(); + } + return (1); + } + + void BE_FreeWMCursor(_THIS, WMcursor * cursor) + { + SDL_free(cursor->bits); + SDL_free(cursor); + } /* Implementation by Christian Bauer */ -void BE_WarpWMCursor(_THIS, Uint16 x, Uint16 y) -{ - BPoint pt(x, y); - SDL_Win->Lock(); - SDL_Win->ConvertToScreen(&pt); - SDL_Win->Unlock(); - set_mouse_position((int32)pt.x, (int32)pt.y); -} - -}; /* Extern C */ + void BE_WarpWMCursor(_THIS, Uint16 x, Uint16 y) + { + BPoint pt(x, y); + SDL_Win->Lock(); + SDL_Win->ConvertToScreen(&pt); + SDL_Win->Unlock(); + set_mouse_position((int32) pt.x, (int32) pt.y); + } + +}; /* Extern C */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/bwindow/SDL_sysmouse_c.h b/src/video/bwindow/SDL_sysmouse_c.h index e4ee25534..b58f892ef 100644 --- a/src/video/bwindow/SDL_sysmouse_c.h +++ b/src/video/bwindow/SDL_sysmouse_c.h @@ -24,9 +24,10 @@ #include "SDL_lowvideo.h" /* Functions to be exported */ -extern void BE_FreeWMCursor(_THIS, WMcursor *cursor); +extern void BE_FreeWMCursor(_THIS, WMcursor * cursor); extern WMcursor *BE_CreateWMCursor(_THIS, - Uint8 *data, Uint8 *mask, int w, int h, int hot_x, int hot_y); -extern int BE_ShowWMCursor(_THIS, WMcursor *cursor); + Uint8 * data, Uint8 * mask, int w, int h, + int hot_x, int hot_y); +extern int BE_ShowWMCursor(_THIS, WMcursor * cursor); extern void BE_WarpWMCursor(_THIS, Uint16 x, Uint16 y); - +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/bwindow/SDL_sysvideo.cc b/src/video/bwindow/SDL_sysvideo.cc index 18e305ad4..c42477828 100644 --- a/src/video/bwindow/SDL_sysvideo.cc +++ b/src/video/bwindow/SDL_sysvideo.cc @@ -28,7 +28,8 @@ #include "SDL_BWin.h" #include "SDL_timer.h" -extern "C" { +extern "C" +{ #include "../SDL_sysvideo.h" #include "../../events/SDL_events_c.h" @@ -40,789 +41,811 @@ extern "C" { #include "SDL_sysyuv.h" #include "../blank_cursor.h" -#define BEOS_HIDDEN_SIZE 32 /* starting hidden window size */ +#define BEOS_HIDDEN_SIZE 32 /* starting hidden window size */ /* Initialization/Query functions */ -static int BE_VideoInit(_THIS, SDL_PixelFormat *vformat); -static SDL_Rect **BE_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags); -static SDL_Surface *BE_SetVideoMode(_THIS, SDL_Surface *current, int width, int height, int bpp, Uint32 flags); -static void BE_UpdateMouse(_THIS); -static int BE_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color *colors); -static void BE_VideoQuit(_THIS); + static int BE_VideoInit(_THIS, SDL_PixelFormat * vformat); + static SDL_Rect **BE_ListModes(_THIS, SDL_PixelFormat * format, + Uint32 flags); + static SDL_Surface *BE_SetVideoMode(_THIS, SDL_Surface * current, + int width, int height, int bpp, + Uint32 flags); + static void BE_UpdateMouse(_THIS); + static int BE_SetColors(_THIS, int firstcolor, int ncolors, + SDL_Color * colors); + static void BE_VideoQuit(_THIS); /* Hardware surface functions */ -static int BE_AllocHWSurface(_THIS, SDL_Surface *surface); -static int BE_LockHWSurface(_THIS, SDL_Surface *surface); -static void BE_UnlockHWSurface(_THIS, SDL_Surface *surface); -static void BE_FreeHWSurface(_THIS, SDL_Surface *surface); + static int BE_AllocHWSurface(_THIS, SDL_Surface * surface); + static int BE_LockHWSurface(_THIS, SDL_Surface * surface); + static void BE_UnlockHWSurface(_THIS, SDL_Surface * surface); + static void BE_FreeHWSurface(_THIS, SDL_Surface * surface); -static int BE_ToggleFullScreen(_THIS, int fullscreen); -static SDL_Overlay *BE_CreateYUVOverlay(_THIS, int width, int height, Uint32 format, SDL_Surface *display); + static int BE_ToggleFullScreen(_THIS, int fullscreen); + static SDL_Overlay *BE_CreateYUVOverlay(_THIS, int width, int height, + Uint32 format, + SDL_Surface * display); /* OpenGL functions */ #if SDL_VIDEO_OPENGL -static int BE_GL_LoadLibrary(_THIS, const char *path); -static void* BE_GL_GetProcAddress(_THIS, const char *proc); -static int BE_GL_GetAttribute(_THIS, SDL_GLattr attrib, int* value); -static int BE_GL_MakeCurrent(_THIS); -static void BE_GL_SwapBuffers(_THIS); + static int BE_GL_LoadLibrary(_THIS, const char *path); + static void *BE_GL_GetProcAddress(_THIS, const char *proc); + static int BE_GL_GetAttribute(_THIS, SDL_GLattr attrib, int *value); + static int BE_GL_MakeCurrent(_THIS); + static void BE_GL_SwapBuffers(_THIS); #endif /* FB driver bootstrap functions */ -static int BE_Available(void) -{ - return(1); -} + static int BE_Available(void) + { + return (1); + } -static void BE_DeleteDevice(SDL_VideoDevice *device) -{ - SDL_free(device->hidden); - SDL_free(device); -} + static void BE_DeleteDevice(SDL_VideoDevice * device) + { + SDL_free(device->hidden); + SDL_free(device); + } -static SDL_VideoDevice *BE_CreateDevice(int devindex) -{ - SDL_VideoDevice *device; - - /* Initialize all variables that we clean on shutdown */ - device = (SDL_VideoDevice *)SDL_malloc(sizeof(SDL_VideoDevice)); - if ( device ) { - SDL_memset(device, 0, (sizeof *device)); - device->hidden = (struct SDL_PrivateVideoData *) - SDL_malloc((sizeof *device->hidden)); - } - if ( (device == NULL) || (device->hidden == NULL) ) { - SDL_OutOfMemory(); - if ( device ) { - SDL_free(device); - } - return(0); - } - SDL_memset(device->hidden, 0, (sizeof *device->hidden)); - - /* Set the function pointers */ - /* Initialization/Query functions */ - device->VideoInit = BE_VideoInit; - device->ListModes = BE_ListModes; - device->SetVideoMode = BE_SetVideoMode; - device->ToggleFullScreen = BE_ToggleFullScreen; - device->UpdateMouse = BE_UpdateMouse; - device->CreateYUVOverlay = BE_CreateYUVOverlay; - device->SetColors = BE_SetColors; - device->UpdateRects = NULL; - device->VideoQuit = BE_VideoQuit; - /* Hardware acceleration functions */ - device->AllocHWSurface = BE_AllocHWSurface; - device->CheckHWBlit = NULL; - device->FillHWRect = NULL; - device->SetHWColorKey = NULL; - device->SetHWAlpha = NULL; - device->LockHWSurface = BE_LockHWSurface; - device->UnlockHWSurface = BE_UnlockHWSurface; - device->FlipHWSurface = NULL; - device->FreeHWSurface = BE_FreeHWSurface; - /* Gamma support */ + static SDL_VideoDevice *BE_CreateDevice(int devindex) + { + SDL_VideoDevice *device; + + /* Initialize all variables that we clean on shutdown */ + device = (SDL_VideoDevice *) SDL_malloc(sizeof(SDL_VideoDevice)); + if (device) { + SDL_memset(device, 0, (sizeof *device)); + device->hidden = (struct SDL_PrivateVideoData *) + SDL_malloc((sizeof *device->hidden)); + } + if ((device == NULL) || (device->hidden == NULL)) { + SDL_OutOfMemory(); + if (device) { + SDL_free(device); + } + return (0); + } + SDL_memset(device->hidden, 0, (sizeof *device->hidden)); + + /* Set the function pointers */ + /* Initialization/Query functions */ + device->VideoInit = BE_VideoInit; + device->ListModes = BE_ListModes; + device->SetVideoMode = BE_SetVideoMode; + device->ToggleFullScreen = BE_ToggleFullScreen; + device->UpdateMouse = BE_UpdateMouse; + device->CreateYUVOverlay = BE_CreateYUVOverlay; + device->SetColors = BE_SetColors; + device->UpdateRects = NULL; + device->VideoQuit = BE_VideoQuit; + /* Hardware acceleration functions */ + device->AllocHWSurface = BE_AllocHWSurface; + device->CheckHWBlit = NULL; + device->FillHWRect = NULL; + device->SetHWColorKey = NULL; + device->SetHWAlpha = NULL; + device->LockHWSurface = BE_LockHWSurface; + device->UnlockHWSurface = BE_UnlockHWSurface; + device->FlipHWSurface = NULL; + device->FreeHWSurface = BE_FreeHWSurface; + /* Gamma support */ #if SDL_VIDEO_OPENGL - /* OpenGL support */ - device->GL_LoadLibrary = BE_GL_LoadLibrary; - device->GL_GetProcAddress = BE_GL_GetProcAddress; - device->GL_GetAttribute = BE_GL_GetAttribute; - device->GL_MakeCurrent = BE_GL_MakeCurrent; - device->GL_SwapBuffers = BE_GL_SwapBuffers; + /* OpenGL support */ + device->GL_LoadLibrary = BE_GL_LoadLibrary; + device->GL_GetProcAddress = BE_GL_GetProcAddress; + device->GL_GetAttribute = BE_GL_GetAttribute; + device->GL_MakeCurrent = BE_GL_MakeCurrent; + device->GL_SwapBuffers = BE_GL_SwapBuffers; #endif - /* Window manager functions */ - device->SetCaption = BE_SetWMCaption; - device->SetIcon = NULL; - device->IconifyWindow = BE_IconifyWindow; - device->GrabInput = NULL; - device->GetWMInfo = BE_GetWMInfo; - /* Cursor manager functions */ - device->FreeWMCursor = BE_FreeWMCursor; - device->CreateWMCursor = BE_CreateWMCursor; - device->ShowWMCursor = BE_ShowWMCursor; - device->WarpWMCursor = BE_WarpWMCursor; - device->MoveWMCursor = NULL; - device->CheckMouseMode = NULL; - /* Event manager functions */ - device->InitOSKeymap = BE_InitOSKeymap; - device->PumpEvents = BE_PumpEvents; - - device->free = BE_DeleteDevice; - - /* Set the driver flags */ - device->handles_any_size = 1; - - return device; -} - -VideoBootStrap BWINDOW_bootstrap = { - "bwindow", "BDirectWindow graphics", - BE_Available, BE_CreateDevice -}; - -static inline int ColorSpaceToBitsPerPixel(uint32 colorspace) -{ - int bitsperpixel; - - bitsperpixel = 0; - switch (colorspace) { - case B_CMAP8: - bitsperpixel = 8; - break; - case B_RGB15: - case B_RGBA15: - case B_RGB15_BIG: - case B_RGBA15_BIG: - bitsperpixel = 15; - break; - case B_RGB16: - case B_RGB16_BIG: - bitsperpixel = 16; - break; - case B_RGB32: - case B_RGBA32: - case B_RGB32_BIG: - case B_RGBA32_BIG: - bitsperpixel = 32; - break; - default: - break; - } - return(bitsperpixel); -} + /* Window manager functions */ + device->SetCaption = BE_SetWMCaption; + device->SetIcon = NULL; + device->IconifyWindow = BE_IconifyWindow; + device->GrabInput = NULL; + device->GetWMInfo = BE_GetWMInfo; + /* Cursor manager functions */ + device->FreeWMCursor = BE_FreeWMCursor; + device->CreateWMCursor = BE_CreateWMCursor; + device->ShowWMCursor = BE_ShowWMCursor; + device->WarpWMCursor = BE_WarpWMCursor; + device->MoveWMCursor = NULL; + device->CheckMouseMode = NULL; + /* Event manager functions */ + device->InitOSKeymap = BE_InitOSKeymap; + device->PumpEvents = BE_PumpEvents; + + device->free = BE_DeleteDevice; + + /* Set the driver flags */ + device->handles_any_size = 1; + + return device; + } + + VideoBootStrap BWINDOW_bootstrap = { + "bwindow", "BDirectWindow graphics", + BE_Available, BE_CreateDevice + }; + + static inline int ColorSpaceToBitsPerPixel(uint32 colorspace) + { + int bitsperpixel; + + bitsperpixel = 0; + switch (colorspace) { + case B_CMAP8: + bitsperpixel = 8; + break; + case B_RGB15: + case B_RGBA15: + case B_RGB15_BIG: + case B_RGBA15_BIG: + bitsperpixel = 15; + break; + case B_RGB16: + case B_RGB16_BIG: + bitsperpixel = 16; + break; + case B_RGB32: + case B_RGBA32: + case B_RGB32_BIG: + case B_RGBA32_BIG: + bitsperpixel = 32; + break; + default: + break; + } + return (bitsperpixel); + } /* Function to sort the display_list in bscreen */ -static int CompareModes(const void *A, const void *B) -{ - const display_mode *a = (display_mode *)A; - const display_mode *b = (display_mode *)B; - - if ( a->space == b->space ) { - return((b->virtual_width*b->virtual_height)- - (a->virtual_width*a->virtual_height)); - } else { - return(ColorSpaceToBitsPerPixel(b->space)- - ColorSpaceToBitsPerPixel(a->space)); - } -} + static int CompareModes(const void *A, const void *B) + { + const display_mode *a = (display_mode *) A; + const display_mode *b = (display_mode *) B; + + if (a->space == b->space) { + return ((b->virtual_width * b->virtual_height) - + (a->virtual_width * a->virtual_height)); + } else { + return (ColorSpaceToBitsPerPixel(b->space) - + ColorSpaceToBitsPerPixel(a->space)); + } + } /* Yes, this isn't the fastest it could be, but it works nicely */ -static int BE_AddMode(_THIS, int index, unsigned int w, unsigned int h) -{ - SDL_Rect *mode; - int i; - int next_mode; - - /* Check to see if we already have this mode */ - if ( SDL_nummodes[index] > 0 ) { - for ( i=SDL_nummodes[index]-1; i >= 0; --i ) { - mode = SDL_modelist[index][i]; - if ( (mode->w == w) && (mode->h == h) ) { + static int BE_AddMode(_THIS, int index, unsigned int w, unsigned int h) + { + SDL_Rect *mode; + int i; + int next_mode; + + /* Check to see if we already have this mode */ + if (SDL_nummodes[index] > 0) { + for (i = SDL_nummodes[index] - 1; i >= 0; --i) { + mode = SDL_modelist[index][i]; + if ((mode->w == w) && (mode->h == h)) { #ifdef BWINDOW_DEBUG - fprintf(stderr, "We already have mode %dx%d at %d bytes per pixel\n", w, h, index+1); + fprintf(stderr, + "We already have mode %dx%d at %d bytes per pixel\n", + w, h, index + 1); #endif - return(0); - } - } - } - - /* Set up the new video mode rectangle */ - mode = (SDL_Rect *)SDL_malloc(sizeof *mode); - if ( mode == NULL ) { - SDL_OutOfMemory(); - return(-1); - } - mode->x = 0; - mode->y = 0; - mode->w = w; - mode->h = h; + return (0); + } + } + } + + /* Set up the new video mode rectangle */ + mode = (SDL_Rect *) SDL_malloc(sizeof *mode); + if (mode == NULL) { + SDL_OutOfMemory(); + return (-1); + } + mode->x = 0; + mode->y = 0; + mode->w = w; + mode->h = h; #ifdef BWINDOW_DEBUG - fprintf(stderr, "Adding mode %dx%d at %d bytes per pixel\n", w, h, index+1); + fprintf(stderr, "Adding mode %dx%d at %d bytes per pixel\n", w, h, + index + 1); #endif - /* Allocate the new list of modes, and fill in the new mode */ - next_mode = SDL_nummodes[index]; - SDL_modelist[index] = (SDL_Rect **) - SDL_realloc(SDL_modelist[index], (1+next_mode+1)*sizeof(SDL_Rect *)); - if ( SDL_modelist[index] == NULL ) { - SDL_OutOfMemory(); - SDL_nummodes[index] = 0; - SDL_free(mode); - return(-1); - } - SDL_modelist[index][next_mode] = mode; - SDL_modelist[index][next_mode+1] = NULL; - SDL_nummodes[index]++; - - return(0); -} - -int BE_VideoInit(_THIS, SDL_PixelFormat *vformat) -{ - display_mode *modes; - uint32 i, nmodes; - int bpp; - BRect bounds; - - /* Initialize the Be Application for appserver interaction */ - if ( SDL_InitBeApp() < 0 ) { - return(-1); - } - - /* It is important that this be created after SDL_InitBeApp() */ - BScreen bscreen; - - /* Save the current display mode */ - bscreen.GetMode(&saved_mode); - _this->info.current_w = saved_mode.virtual_width; - _this->info.current_h = saved_mode.virtual_height; - - /* Determine the screen depth */ - vformat->BitsPerPixel = ColorSpaceToBitsPerPixel(bscreen.ColorSpace()); - if ( vformat->BitsPerPixel == 0 ) { - SDL_SetError("Unknown BScreen colorspace: 0x%x", - bscreen.ColorSpace()); - return(-1); - } - - /* Get the video modes we can switch to in fullscreen mode */ - bscreen.GetModeList(&modes, &nmodes); - SDL_qsort(modes, nmodes, sizeof *modes, CompareModes); - for ( i=0; iinfo.current_w = saved_mode.virtual_width; + _this->info.current_h = saved_mode.virtual_height; + + /* Determine the screen depth */ + vformat->BitsPerPixel = + ColorSpaceToBitsPerPixel(bscreen.ColorSpace()); + if (vformat->BitsPerPixel == 0) { + SDL_SetError("Unknown BScreen colorspace: 0x%x", + bscreen.ColorSpace()); + return (-1); + } + + /* Get the video modes we can switch to in fullscreen mode */ + bscreen.GetModeList(&modes, &nmodes); + SDL_qsort(modes, nmodes, sizeof *modes, CompareModes); + for (i = 0; i < nmodes; ++i) { + bpp = ColorSpaceToBitsPerPixel(modes[i].space); + //if ( bpp != 0 ) { // There are bugs in changing colorspace + if (modes[i].space == saved_mode.space) { + BE_AddMode(_this, ((bpp + 7) / 8) - 1, + modes[i].virtual_width, modes[i].virtual_height); + } + } + + /* Create the window and view */ + bounds.top = 0; + bounds.left = 0; + bounds.right = BEOS_HIDDEN_SIZE; + bounds.bottom = BEOS_HIDDEN_SIZE; + SDL_Win = new SDL_BWin(bounds); #if SDL_VIDEO_OPENGL - /* testgl application doesn't load library, just tries to load symbols */ - /* is it correct? if so we have to load library here */ - BE_GL_LoadLibrary(_this, NULL); + /* testgl application doesn't load library, just tries to load symbols */ + /* is it correct? if so we have to load library here */ + BE_GL_LoadLibrary(_this, NULL); #endif - /* Create the clear cursor */ - SDL_BlankCursor = BE_CreateWMCursor(_this, blank_cdata, blank_cmask, - BLANK_CWIDTH, BLANK_CHEIGHT, BLANK_CHOTX, BLANK_CHOTY); + /* Create the clear cursor */ + SDL_BlankCursor = BE_CreateWMCursor(_this, blank_cdata, blank_cmask, + BLANK_CWIDTH, BLANK_CHEIGHT, + BLANK_CHOTX, BLANK_CHOTY); - /* Fill in some window manager capabilities */ - _this->info.wm_available = 1; + /* Fill in some window manager capabilities */ + _this->info.wm_available = 1; - /* We're done! */ - return(0); -} + /* We're done! */ + return (0); + } /* We support any dimension at our bit-depth */ -SDL_Rect **BE_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags) -{ - SDL_Rect **modes; - - modes = ((SDL_Rect **)0); - if ( (flags & SDL_FULLSCREEN) == SDL_FULLSCREEN ) { - modes = SDL_modelist[((format->BitsPerPixel+7)/8)-1]; - } else { - if ( format->BitsPerPixel == - _this->screen->format->BitsPerPixel ) { - modes = ((SDL_Rect **)-1); - } - } - return(modes); -} + SDL_Rect **BE_ListModes(_THIS, SDL_PixelFormat * format, Uint32 flags) + { + SDL_Rect **modes; + + modes = ((SDL_Rect **) 0); + if ((flags & SDL_FULLSCREEN) == SDL_FULLSCREEN) { + modes = SDL_modelist[((format->BitsPerPixel + 7) / 8) - 1]; + } else { + if (format->BitsPerPixel == _this->screen->format->BitsPerPixel) { + modes = ((SDL_Rect **) - 1); + } + } + return (modes); + } /* Various screen update functions available */ -static void BE_NormalUpdate(_THIS, int numrects, SDL_Rect *rects); + static void BE_NormalUpdate(_THIS, int numrects, SDL_Rect * rects); /* Find the closest display mode for fullscreen */ -static bool BE_FindClosestFSMode(_THIS, int width, int height, int bpp, - display_mode *mode) -{ - BScreen bscreen; - uint32 i, nmodes; - SDL_Rect **modes; - display_mode *dmodes; - display_mode current; - float current_refresh; - bscreen.GetMode(¤t); - current_refresh = (1000 * current.timing.pixel_clock) / - (current.timing.h_total * current.timing.v_total); - - modes = SDL_modelist[((bpp+7)/8)-1]; - for ( i=0; modes[i] && (modes[i]->w > width) && - (modes[i]->h > height); ++i ) { - /* still looking */ - } - if ( ! modes[i] || (modes[i]->w < width) || (modes[i]->h < width) ) { - --i; /* We went too far */ - } - width = modes[i]->w; - height = modes[i]->h; - bscreen.GetModeList(&dmodes, &nmodes); - for ( i = 0; i < nmodes; ++i ) { - if ( (bpp == ColorSpaceToBitsPerPixel(dmodes[i].space)) && - (width == dmodes[i].virtual_width) && - (height == dmodes[i].virtual_height) ) { - break; - } - } - if ( i != nmodes ) { - *mode = dmodes[i]; - if ((mode->virtual_width <= current.virtual_width) && - (mode->virtual_height <= current.virtual_height)) { - float new_refresh = (1000 * mode->timing.pixel_clock) / - (mode->timing.h_total * mode->timing.v_total); - if (new_refresh < current_refresh) { - mode->timing.pixel_clock = (uint32)((mode->timing.h_total * mode->timing.v_total) - * current_refresh / 1000); - } - } - return true; - } else { - return false; - } -} - -static int BE_SetFullScreen(_THIS, SDL_Surface *screen, int fullscreen) -{ - int was_fullscreen; - bool needs_unlock; - BScreen bscreen; - BRect bounds; - display_mode mode; - int width, height, bpp; - - /* Set the fullscreen mode */ - was_fullscreen = SDL_Win->IsFullScreen(); - SDL_Win->SetFullScreen(fullscreen); - fullscreen = SDL_Win->IsFullScreen(); - - width = screen->w; - height = screen->h; - - /* Set the appropriate video mode */ - if ( fullscreen ) { - bpp = screen->format->BitsPerPixel; - bscreen.GetMode(&mode); - if ( (bpp != ColorSpaceToBitsPerPixel(mode.space)) || - (width != mode.virtual_width) || - (height != mode.virtual_height)) { - if(BE_FindClosestFSMode(_this, width, height, bpp, &mode)) { - bscreen.SetMode(&mode); - /* This simply stops the next resize event from being - * sent to the SDL handler. - */ - SDL_Win->InhibitResize(); - } else { - fullscreen = 0; - SDL_Win->SetFullScreen(fullscreen); - } - } - } - if ( was_fullscreen && ! fullscreen ) { - bscreen.SetMode(&saved_mode); - } - - if ( SDL_Win->Lock() ) { - int xoff, yoff; - if ( SDL_Win->Shown() ) { - needs_unlock = 1; - SDL_Win->Hide(); - } else { - needs_unlock = 0; - } - /* This resizes the window and view area, but inhibits resizing - * of the BBitmap due to the InhibitResize call above. Thus the - * bitmap (pixel data) never changes. - */ - SDL_Win->ResizeTo(width, height); - bounds = bscreen.Frame(); - /* Calculate offsets - used either to center window - * (windowed mode) or to set drawing offsets (fullscreen mode) - */ - xoff = (bounds.IntegerWidth() - width)/2; - yoff = (bounds.IntegerHeight() - height)/2; - if ( fullscreen ) { - /* Set offset for drawing */ - SDL_Win->SetXYOffset(xoff, yoff); - } else { - /* Center window and reset the drawing offset */ - SDL_Win->SetXYOffset(0, 0); - } - if ( ! needs_unlock || was_fullscreen ) { - /* Center the window the first time */ - SDL_Win->MoveTo(xoff > 0 ? (float)xoff : 0.0f, - yoff > 0 ? (float)yoff : 0.0f); - } - SDL_Win->Show(); - - /* Unlock the window manually after the first Show() */ - if ( needs_unlock ) { - SDL_Win->Unlock(); - } - } - - /* Set the fullscreen flag in the screen surface */ - if ( fullscreen ) { - screen->flags |= SDL_FULLSCREEN; - } else { - screen->flags &= ~SDL_FULLSCREEN; - } - return(1); -} - -static int BE_ToggleFullScreen(_THIS, int fullscreen) -{ - return BE_SetFullScreen(_this, _this->screen, fullscreen); -} + static bool BE_FindClosestFSMode(_THIS, int width, int height, int bpp, + display_mode * mode) + { + BScreen bscreen; + uint32 i, nmodes; + SDL_Rect **modes; + display_mode *dmodes; + display_mode current; + float current_refresh; + bscreen.GetMode(¤t); + current_refresh = (1000 * current.timing.pixel_clock) / + (current.timing.h_total * current.timing.v_total); + + modes = SDL_modelist[((bpp + 7) / 8) - 1]; + for (i = 0; modes[i] && (modes[i]->w > width) && + (modes[i]->h > height); ++i) { + /* still looking */ + } + if (!modes[i] || (modes[i]->w < width) || (modes[i]->h < width)) { + --i; /* We went too far */ + } + width = modes[i]->w; + height = modes[i]->h; + bscreen.GetModeList(&dmodes, &nmodes); + for (i = 0; i < nmodes; ++i) { + if ((bpp == ColorSpaceToBitsPerPixel(dmodes[i].space)) && + (width == dmodes[i].virtual_width) && + (height == dmodes[i].virtual_height)) { + break; + } + } + if (i != nmodes) { + *mode = dmodes[i]; + if ((mode->virtual_width <= current.virtual_width) && + (mode->virtual_height <= current.virtual_height)) { + float new_refresh = (1000 * mode->timing.pixel_clock) / + (mode->timing.h_total * mode->timing.v_total); + if (new_refresh < current_refresh) { + mode->timing.pixel_clock = + (uint32) ((mode->timing.h_total * + mode->timing.v_total) * + current_refresh / 1000); + } + } + return true; + } else { + return false; + } + } + + static int BE_SetFullScreen(_THIS, SDL_Surface * screen, int fullscreen) + { + int was_fullscreen; + bool needs_unlock; + BScreen bscreen; + BRect bounds; + display_mode mode; + int width, height, bpp; + + /* Set the fullscreen mode */ + was_fullscreen = SDL_Win->IsFullScreen(); + SDL_Win->SetFullScreen(fullscreen); + fullscreen = SDL_Win->IsFullScreen(); + + width = screen->w; + height = screen->h; + + /* Set the appropriate video mode */ + if (fullscreen) { + bpp = screen->format->BitsPerPixel; + bscreen.GetMode(&mode); + if ((bpp != ColorSpaceToBitsPerPixel(mode.space)) || + (width != mode.virtual_width) || + (height != mode.virtual_height)) { + if (BE_FindClosestFSMode(_this, width, height, bpp, &mode)) { + bscreen.SetMode(&mode); + /* This simply stops the next resize event from being + * sent to the SDL handler. + */ + SDL_Win->InhibitResize(); + } else { + fullscreen = 0; + SDL_Win->SetFullScreen(fullscreen); + } + } + } + if (was_fullscreen && !fullscreen) { + bscreen.SetMode(&saved_mode); + } + + if (SDL_Win->Lock()) { + int xoff, yoff; + if (SDL_Win->Shown()) { + needs_unlock = 1; + SDL_Win->Hide(); + } else { + needs_unlock = 0; + } + /* This resizes the window and view area, but inhibits resizing + * of the BBitmap due to the InhibitResize call above. Thus the + * bitmap (pixel data) never changes. + */ + SDL_Win->ResizeTo(width, height); + bounds = bscreen.Frame(); + /* Calculate offsets - used either to center window + * (windowed mode) or to set drawing offsets (fullscreen mode) + */ + xoff = (bounds.IntegerWidth() - width) / 2; + yoff = (bounds.IntegerHeight() - height) / 2; + if (fullscreen) { + /* Set offset for drawing */ + SDL_Win->SetXYOffset(xoff, yoff); + } else { + /* Center window and reset the drawing offset */ + SDL_Win->SetXYOffset(0, 0); + } + if (!needs_unlock || was_fullscreen) { + /* Center the window the first time */ + SDL_Win->MoveTo(xoff > 0 ? (float) xoff : 0.0f, + yoff > 0 ? (float) yoff : 0.0f); + } + SDL_Win->Show(); + + /* Unlock the window manually after the first Show() */ + if (needs_unlock) { + SDL_Win->Unlock(); + } + } + + /* Set the fullscreen flag in the screen surface */ + if (fullscreen) { + screen->flags |= SDL_FULLSCREEN; + } else { + screen->flags &= ~SDL_FULLSCREEN; + } + return (1); + } + + static int BE_ToggleFullScreen(_THIS, int fullscreen) + { + return BE_SetFullScreen(_this, _this->screen, fullscreen); + } /* FIXME: check return values and cleanup here */ -SDL_Surface *BE_SetVideoMode(_THIS, SDL_Surface *current, - int width, int height, int bpp, Uint32 flags) -{ - BScreen bscreen; - BBitmap *bbitmap; - BRect bounds; - Uint32 gl_flags = 0; - - /* Only RGB works on r5 currently */ - gl_flags = BGL_RGB; - if (_this->gl_config.double_buffer) - gl_flags |= BGL_DOUBLE; - else - gl_flags |= BGL_SINGLE; - if (_this->gl_config.alpha_size > 0 || bpp == 32) - gl_flags |= BGL_ALPHA; - if (_this->gl_config.depth_size > 0) - gl_flags |= BGL_DEPTH; - if (_this->gl_config.stencil_size > 0) - gl_flags |= BGL_STENCIL; - if (_this->gl_config.accum_red_size > 0 - || _this->gl_config.accum_green_size > 0 - || _this->gl_config.accum_blue_size > 0 - || _this->gl_config.accum_alpha_size > 0) - gl_flags |= BGL_ACCUM; - - /* Create the view for this window, using found flags */ - if ( SDL_Win->CreateView(flags, gl_flags) < 0 ) { - return(NULL); - } - - current->flags = 0; /* Clear flags */ - current->w = width; - current->h = height; - SDL_Win->SetType(B_TITLED_WINDOW); - if ( flags & SDL_NOFRAME ) { - current->flags |= SDL_NOFRAME; - SDL_Win->SetLook(B_NO_BORDER_WINDOW_LOOK); - } else { - if ( (flags & SDL_RESIZABLE) && !(flags & SDL_OPENGL) ) { - current->flags |= SDL_RESIZABLE; - /* We don't want opaque resizing (TM). :-) */ - SDL_Win->SetFlags(B_OUTLINE_RESIZE); - } else { - SDL_Win->SetFlags(B_NOT_RESIZABLE|B_NOT_ZOOMABLE); - } - } - - if ( flags & SDL_OPENGL ) { - current->flags |= SDL_OPENGL; - current->pitch = 0; - current->pixels = NULL; - _this->UpdateRects = NULL; - } else { - /* Create the BBitmap framebuffer */ - bounds.top = 0; bounds.left = 0; - bounds.right = width-1; - bounds.bottom = height-1; - bbitmap = new BBitmap(bounds, bscreen.ColorSpace()); - if ( ! bbitmap->IsValid() ) { - SDL_SetError("Couldn't create screen bitmap"); - delete bbitmap; - return(NULL); - } - current->pitch = bbitmap->BytesPerRow(); - current->pixels = (void *)bbitmap->Bits(); - SDL_Win->SetBitmap(bbitmap); - _this->UpdateRects = BE_NormalUpdate; - } - - /* Set the correct fullscreen mode */ - BE_SetFullScreen(_this, current, flags & SDL_FULLSCREEN ? 1 : 0); - - /* We're done */ - return(current); -} + SDL_Surface *BE_SetVideoMode(_THIS, SDL_Surface * current, + int width, int height, int bpp, Uint32 flags) + { + BScreen bscreen; + BBitmap *bbitmap; + BRect bounds; + Uint32 gl_flags = 0; + + /* Only RGB works on r5 currently */ + gl_flags = BGL_RGB; + if (_this->gl_config.double_buffer) + gl_flags |= BGL_DOUBLE; + else + gl_flags |= BGL_SINGLE; + if (_this->gl_config.alpha_size > 0 || bpp == 32) + gl_flags |= BGL_ALPHA; + if (_this->gl_config.depth_size > 0) + gl_flags |= BGL_DEPTH; + if (_this->gl_config.stencil_size > 0) + gl_flags |= BGL_STENCIL; + if (_this->gl_config.accum_red_size > 0 + || _this->gl_config.accum_green_size > 0 + || _this->gl_config.accum_blue_size > 0 + || _this->gl_config.accum_alpha_size > 0) + gl_flags |= BGL_ACCUM; + + /* Create the view for this window, using found flags */ + if (SDL_Win->CreateView(flags, gl_flags) < 0) { + return (NULL); + } + + current->flags = 0; /* Clear flags */ + current->w = width; + current->h = height; + SDL_Win->SetType(B_TITLED_WINDOW); + if (flags & SDL_NOFRAME) { + current->flags |= SDL_NOFRAME; + SDL_Win->SetLook(B_NO_BORDER_WINDOW_LOOK); + } else { + if ((flags & SDL_RESIZABLE) && !(flags & SDL_INTERNALOPENGL)) { + current->flags |= SDL_RESIZABLE; + /* We don't want opaque resizing (TM). :-) */ + SDL_Win->SetFlags(B_OUTLINE_RESIZE); + } else { + SDL_Win->SetFlags(B_NOT_RESIZABLE | B_NOT_ZOOMABLE); + } + } + + if (flags & SDL_INTERNALOPENGL) { + current->flags |= SDL_INTERNALOPENGL; + current->pitch = 0; + current->pixels = NULL; + _this->UpdateRects = NULL; + } else { + /* Create the BBitmap framebuffer */ + bounds.top = 0; + bounds.left = 0; + bounds.right = width - 1; + bounds.bottom = height - 1; + bbitmap = new BBitmap(bounds, bscreen.ColorSpace()); + if (!bbitmap->IsValid()) { + SDL_SetError("Couldn't create screen bitmap"); + delete bbitmap; + return (NULL); + } + current->pitch = bbitmap->BytesPerRow(); + current->pixels = (void *) bbitmap->Bits(); + SDL_Win->SetBitmap(bbitmap); + _this->UpdateRects = BE_NormalUpdate; + } + + /* Set the correct fullscreen mode */ + BE_SetFullScreen(_this, current, flags & SDL_FULLSCREEN ? 1 : 0); + + /* We're done */ + return (current); + } /* Update the current mouse state and position */ -void BE_UpdateMouse(_THIS) -{ - BPoint point; - uint32 buttons; - - if ( SDL_Win->Lock() ) { - /* Get new input state, if still active */ - if ( SDL_Win->IsActive() ) { - (SDL_Win->View())->GetMouse(&point, &buttons, true); - } else { - point.x = -1; - point.y = -1; - } - SDL_Win->Unlock(); - - if ( (point.x >= 0) && (point.x < SDL_VideoSurface->w) && - (point.y >= 0) && (point.y < SDL_VideoSurface->h) ) { - SDL_PrivateAppActive(1, SDL_APPMOUSEFOCUS); - SDL_PrivateMouseMotion(0, 0, - (Sint16)point.x, (Sint16)point.y); - } else { - SDL_PrivateAppActive(0, SDL_APPMOUSEFOCUS); - } - } -} + void BE_UpdateMouse(_THIS) + { + BPoint point; + uint32 buttons; + + if (SDL_Win->Lock()) { + /* Get new input state, if still active */ + if (SDL_Win->IsActive()) { + (SDL_Win->View())->GetMouse(&point, &buttons, true); + } else { + point.x = -1; + point.y = -1; + } + SDL_Win->Unlock(); + + if ((point.x >= 0) && (point.x < SDL_VideoSurface->w) && + (point.y >= 0) && (point.y < SDL_VideoSurface->h)) { + SDL_PrivateAppActive(1, SDL_APPMOUSEFOCUS); + SDL_PrivateMouseMotion(0, 0, + (Sint16) point.x, (Sint16) point.y); + } else { + SDL_PrivateAppActive(0, SDL_APPMOUSEFOCUS); + } + } + } /* We don't actually allow hardware surfaces other than the main one */ -static int BE_AllocHWSurface(_THIS, SDL_Surface *surface) -{ - return(-1); -} -static void BE_FreeHWSurface(_THIS, SDL_Surface *surface) -{ - return; -} -static int BE_LockHWSurface(_THIS, SDL_Surface *surface) -{ - return(0); -} -static void BE_UnlockHWSurface(_THIS, SDL_Surface *surface) -{ - return; -} + static int BE_AllocHWSurface(_THIS, SDL_Surface * surface) + { + return (-1); + } + static void BE_FreeHWSurface(_THIS, SDL_Surface * surface) + { + return; + } + static int BE_LockHWSurface(_THIS, SDL_Surface * surface) + { + return (0); + } + static void BE_UnlockHWSurface(_THIS, SDL_Surface * surface) + { + return; + } -static void BE_NormalUpdate(_THIS, int numrects, SDL_Rect *rects) -{ - if ( SDL_Win->BeginDraw() ) { - int i; - - for ( i=0; iDrawAsync(rect); - } - SDL_Win->EndDraw(); - } -} + static void BE_NormalUpdate(_THIS, int numrects, SDL_Rect * rects) + { + if (SDL_Win->BeginDraw()) { + int i; + + for (i = 0; i < numrects; ++i) { + BRect rect; + + rect.top = rects[i].y; + rect.left = rects[i].x; + rect.bottom = rect.top + rects[i].h - 1; + rect.right = rect.left + rects[i].w - 1; + SDL_Win->DrawAsync(rect); + } + SDL_Win->EndDraw(); + } + } #if SDL_VIDEO_OPENGL /* Passing a NULL path means load pointers from the application */ -int BE_GL_LoadLibrary(_THIS, const char *path) -{ - if (path == NULL) { - if (_this->gl_config.dll_handle == NULL) { - image_info info; - int32 cookie = 0; - while (get_next_image_info(0,&cookie,&info) == B_OK) { - void *location = NULL; - if (get_image_symbol((image_id)cookie,"glBegin",B_SYMBOL_TYPE_ANY,&location) == B_OK) { - _this->gl_config.dll_handle = (void*)cookie; - _this->gl_config.driver_loaded = 1; - SDL_strlcpy(_this->gl_config.driver_path, "libGL.so", SDL_arraysize(_this->gl_config.driver_path)); - } - } - } - } else { - /* - FIXME None of BeOS libGL.so implementations have exported functions - to load BGLView, which should be reloaded from new lib. - So for now just "load" linked libGL.so :( - */ - if (_this->gl_config.dll_handle == NULL) { - return BE_GL_LoadLibrary(_this, NULL); - } - - /* Unload old first */ - /*if (_this->gl_config.dll_handle != NULL) {*/ - /* Do not try to unload application itself (if LoadLibrary was called before with NULL ;) */ - /* image_info info; - if (get_image_info((image_id)_this->gl_config.dll_handle, &info) == B_OK) { - if (info.type != B_APP_IMAGE) { - unload_add_on((image_id)_this->gl_config.dll_handle); - } - } - - } - - if ((_this->gl_config.dll_handle = (void*)load_add_on(path)) != (void*)B_ERROR) { - _this->gl_config.driver_loaded = 1; - SDL_strlcpy(_this->gl_config.driver_path, path, SDL_arraysize(_this->gl_config.driver_path)); - }*/ - } - - if (_this->gl_config.dll_handle != NULL) { - return 0; - } else { - _this->gl_config.dll_handle = NULL; - _this->gl_config.driver_loaded = 0; - *_this->gl_config.driver_path = '\0'; - return -1; - } -} - -void* BE_GL_GetProcAddress(_THIS, const char *proc) -{ - if (_this->gl_config.dll_handle != NULL) { - void *location = NULL; - status_t err; - if ((err = get_image_symbol((image_id)_this->gl_config.dll_handle, proc, B_SYMBOL_TYPE_ANY, &location)) == B_OK) { - return location; - } else { - SDL_SetError("Couldn't find OpenGL symbol"); - return NULL; - } - } else { - SDL_SetError("OpenGL library not loaded"); - return NULL; - } -} - -int BE_GL_GetAttribute(_THIS, SDL_GLattr attrib, int* value) -{ - /* - FIXME? Right now BE_GL_GetAttribute shouldn't be called between glBegin() and glEnd() - it doesn't use "cached" values - */ - switch (attrib) + int BE_GL_LoadLibrary(_THIS, const char *path) { - case SDL_GL_RED_SIZE: - glGetIntegerv(GL_RED_BITS, (GLint*)value); - break; - case SDL_GL_GREEN_SIZE: - glGetIntegerv(GL_GREEN_BITS, (GLint*)value); - break; - case SDL_GL_BLUE_SIZE: - glGetIntegerv(GL_BLUE_BITS, (GLint*)value); - break; - case SDL_GL_ALPHA_SIZE: - glGetIntegerv(GL_ALPHA_BITS, (GLint*)value); - break; - case SDL_GL_DOUBLEBUFFER: - glGetBooleanv(GL_DOUBLEBUFFER, (GLboolean*)value); - break; - case SDL_GL_BUFFER_SIZE: - int v; - glGetIntegerv(GL_RED_BITS, (GLint*)&v); - *value = v; - glGetIntegerv(GL_GREEN_BITS, (GLint*)&v); - *value += v; - glGetIntegerv(GL_BLUE_BITS, (GLint*)&v); - *value += v; - glGetIntegerv(GL_ALPHA_BITS, (GLint*)&v); - *value += v; - break; - case SDL_GL_DEPTH_SIZE: - glGetIntegerv(GL_DEPTH_BITS, (GLint*)value); /* Mesa creates 16 only? r5 always 32 */ - break; - case SDL_GL_STENCIL_SIZE: - glGetIntegerv(GL_STENCIL_BITS, (GLint*)value); - break; - case SDL_GL_ACCUM_RED_SIZE: - glGetIntegerv(GL_ACCUM_RED_BITS, (GLint*)value); - break; - case SDL_GL_ACCUM_GREEN_SIZE: - glGetIntegerv(GL_ACCUM_GREEN_BITS, (GLint*)value); - break; - case SDL_GL_ACCUM_BLUE_SIZE: - glGetIntegerv(GL_ACCUM_BLUE_BITS, (GLint*)value); - break; - case SDL_GL_ACCUM_ALPHA_SIZE: - glGetIntegerv(GL_ACCUM_ALPHA_BITS, (GLint*)value); - break; - case SDL_GL_STEREO: - case SDL_GL_MULTISAMPLEBUFFERS: - case SDL_GL_MULTISAMPLESAMPLES: - default: - *value=0; - return(-1); - } - return 0; -} - -int BE_GL_MakeCurrent(_THIS) -{ - /* FIXME: should we glview->unlock and then glview->lock()? */ - return 0; -} + if (path == NULL) { + if (_this->gl_config.dll_handle == NULL) { + image_info info; + int32 cookie = 0; + while (get_next_image_info(0, &cookie, &info) == B_OK) { + void *location = NULL; + if (get_image_symbol + ((image_id) cookie, "glBegin", + B_SYMBOL_TYPE_ANY, &location) == B_OK) { + _this->gl_config.dll_handle = (void *) cookie; + _this->gl_config.driver_loaded = 1; + SDL_strlcpy(_this->gl_config.driver_path, + "libGL.so", + SDL_arraysize(_this->gl_config. + driver_path)); + } + } + } + } else { + /* + FIXME None of BeOS libGL.so implementations have exported functions + to load BGLView, which should be reloaded from new lib. + So for now just "load" linked libGL.so :( + */ + if (_this->gl_config.dll_handle == NULL) { + return BE_GL_LoadLibrary(_this, NULL); + } + + /* Unload old first */ + /*if (_this->gl_config.dll_handle != NULL) { */ + /* Do not try to unload application itself (if LoadLibrary was called before with NULL ;) */ + /* image_info info; + if (get_image_info((image_id)_this->gl_config.dll_handle, &info) == B_OK) { + if (info.type != B_APP_IMAGE) { + unload_add_on((image_id)_this->gl_config.dll_handle); + } + } + + } + + if ((_this->gl_config.dll_handle = (void*)load_add_on(path)) != (void*)B_ERROR) { + _this->gl_config.driver_loaded = 1; + SDL_strlcpy(_this->gl_config.driver_path, path, SDL_arraysize(_this->gl_config.driver_path)); + } */ + } + + if (_this->gl_config.dll_handle != NULL) { + return 0; + } else { + _this->gl_config.dll_handle = NULL; + _this->gl_config.driver_loaded = 0; + *_this->gl_config.driver_path = '\0'; + return -1; + } + } + + void *BE_GL_GetProcAddress(_THIS, const char *proc) + { + if (_this->gl_config.dll_handle != NULL) { + void *location = NULL; + status_t err; + if ((err = + get_image_symbol((image_id) _this->gl_config.dll_handle, + proc, B_SYMBOL_TYPE_ANY, + &location)) == B_OK) { + return location; + } else { + SDL_SetError("Couldn't find OpenGL symbol"); + return NULL; + } + } else { + SDL_SetError("OpenGL library not loaded"); + return NULL; + } + } + + int BE_GL_GetAttribute(_THIS, SDL_GLattr attrib, int *value) + { + /* + FIXME? Right now BE_GL_GetAttribute shouldn't be called between glBegin() and glEnd() - it doesn't use "cached" values + */ + switch (attrib) { + case SDL_GL_RED_SIZE: + glGetIntegerv(GL_RED_BITS, (GLint *) value); + break; + case SDL_GL_GREEN_SIZE: + glGetIntegerv(GL_GREEN_BITS, (GLint *) value); + break; + case SDL_GL_BLUE_SIZE: + glGetIntegerv(GL_BLUE_BITS, (GLint *) value); + break; + case SDL_GL_ALPHA_SIZE: + glGetIntegerv(GL_ALPHA_BITS, (GLint *) value); + break; + case SDL_GL_DOUBLEBUFFER: + glGetBooleanv(GL_DOUBLEBUFFER, (GLboolean *) value); + break; + case SDL_GL_BUFFER_SIZE: + int v; + glGetIntegerv(GL_RED_BITS, (GLint *) & v); + *value = v; + glGetIntegerv(GL_GREEN_BITS, (GLint *) & v); + *value += v; + glGetIntegerv(GL_BLUE_BITS, (GLint *) & v); + *value += v; + glGetIntegerv(GL_ALPHA_BITS, (GLint *) & v); + *value += v; + break; + case SDL_GL_DEPTH_SIZE: + glGetIntegerv(GL_DEPTH_BITS, (GLint *) value); /* Mesa creates 16 only? r5 always 32 */ + break; + case SDL_GL_STENCIL_SIZE: + glGetIntegerv(GL_STENCIL_BITS, (GLint *) value); + break; + case SDL_GL_ACCUM_RED_SIZE: + glGetIntegerv(GL_ACCUM_RED_BITS, (GLint *) value); + break; + case SDL_GL_ACCUM_GREEN_SIZE: + glGetIntegerv(GL_ACCUM_GREEN_BITS, (GLint *) value); + break; + case SDL_GL_ACCUM_BLUE_SIZE: + glGetIntegerv(GL_ACCUM_BLUE_BITS, (GLint *) value); + break; + case SDL_GL_ACCUM_ALPHA_SIZE: + glGetIntegerv(GL_ACCUM_ALPHA_BITS, (GLint *) value); + break; + case SDL_GL_STEREO: + case SDL_GL_MULTISAMPLEBUFFERS: + case SDL_GL_MULTISAMPLESAMPLES: + default: + *value = 0; + return (-1); + } + return 0; + } + + int BE_GL_MakeCurrent(_THIS) + { + /* FIXME: should we glview->unlock and then glview->lock()? */ + return 0; + } -void BE_GL_SwapBuffers(_THIS) -{ - SDL_Win->SwapBuffers(); -} + void BE_GL_SwapBuffers(_THIS) + { + SDL_Win->SwapBuffers(); + } #endif /* Is the system palette settable? */ -int BE_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color *colors) -{ - int i; - SDL_Palette *palette; - const color_map *cmap = BScreen().ColorMap(); - - /* Get the screen colormap */ - palette = _this->screen->format->palette; - for ( i=0; i<256; ++i ) { - palette->colors[i].r = cmap->color_list[i].red; - palette->colors[i].g = cmap->color_list[i].green; - palette->colors[i].b = cmap->color_list[i].blue; - } - return(0); -} - -void BE_VideoQuit(_THIS) -{ - int i, j; - - SDL_Win->Quit(); - SDL_Win = NULL; - - if ( SDL_BlankCursor != NULL ) { - BE_FreeWMCursor(_this, SDL_BlankCursor); - SDL_BlankCursor = NULL; - } - for ( i=0; iscreen ) { - if ( (_this->screen->flags&SDL_FULLSCREEN) == SDL_FULLSCREEN ) { - BScreen bscreen; - bscreen.SetMode(&saved_mode); - } - _this->screen->pixels = NULL; - } - + int BE_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color * colors) + { + int i; + SDL_Palette *palette; + const color_map *cmap = BScreen().ColorMap(); + + /* Get the screen colormap */ + palette = _this->screen->format->palette; + for (i = 0; i < 256; ++i) { + palette->colors[i].r = cmap->color_list[i].red; + palette->colors[i].g = cmap->color_list[i].green; + palette->colors[i].b = cmap->color_list[i].blue; + } + return (0); + } + + void BE_VideoQuit(_THIS) + { + int i, j; + + SDL_Win->Quit(); + SDL_Win = NULL; + + if (SDL_BlankCursor != NULL) { + BE_FreeWMCursor(_this, SDL_BlankCursor); + SDL_BlankCursor = NULL; + } + for (i = 0; i < NUM_MODELISTS; ++i) { + if (SDL_modelist[i]) { + for (j = 0; SDL_modelist[i][j]; ++j) { + SDL_free(SDL_modelist[i][j]); + } + SDL_free(SDL_modelist[i]); + SDL_modelist[i] = NULL; + } + } + /* Restore the original video mode */ + if (_this->screen) { + if ((_this->screen->flags & SDL_FULLSCREEN) == SDL_FULLSCREEN) { + BScreen bscreen; + bscreen.SetMode(&saved_mode); + } + _this->screen->pixels = NULL; + } #if SDL_VIDEO_OPENGL - if (_this->gl_config.dll_handle != NULL) - unload_add_on((image_id)_this->gl_config.dll_handle); + if (_this->gl_config.dll_handle != NULL) + unload_add_on((image_id) _this->gl_config.dll_handle); #endif - SDL_QuitBeApp(); -} + SDL_QuitBeApp(); + } + +}; /* Extern C */ -}; /* Extern C */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/bwindow/SDL_syswm.cc b/src/video/bwindow/SDL_syswm.cc index 81bda1a81..91b92d63b 100644 --- a/src/video/bwindow/SDL_syswm.cc +++ b/src/video/bwindow/SDL_syswm.cc @@ -23,33 +23,33 @@ #include "SDL_BWin.h" -extern "C" { +extern "C" +{ #include "SDL_syswm_c.h" #include "SDL_error.h" -void BE_SetWMCaption(_THIS, const char *title, const char *icon) -{ - SDL_Win->SetTitle(title); -} - -int BE_IconifyWindow(_THIS) -{ - SDL_Win->Minimize(true); -} + void BE_SetWMCaption(_THIS, const char *title, const char *icon) + { + SDL_Win->SetTitle(title); + } -int BE_GetWMInfo(_THIS, SDL_SysWMinfo *info) -{ - if (info->version.major <= SDL_MAJOR_VERSION) + int BE_IconifyWindow(_THIS) { - return 1; + SDL_Win->Minimize(true); } - else + + int BE_GetWMInfo(_THIS, SDL_SysWMinfo * info) { - SDL_SetError("Application not compiled with SDL %d.%d\n", - SDL_MAJOR_VERSION, SDL_MINOR_VERSION); - return -1; + if (info->version.major <= SDL_MAJOR_VERSION) { + return 1; + } else { + SDL_SetError("Application not compiled with SDL %d.%d\n", + SDL_MAJOR_VERSION, SDL_MINOR_VERSION); + return -1; + } } -} -}; /* Extern C */ +}; /* Extern C */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/bwindow/SDL_syswm_c.h b/src/video/bwindow/SDL_syswm_c.h index 44892a8f6..e6de8b712 100644 --- a/src/video/bwindow/SDL_syswm_c.h +++ b/src/video/bwindow/SDL_syswm_c.h @@ -28,4 +28,5 @@ /* Functions to be exported */ extern void BE_SetWMCaption(_THIS, const char *title, const char *icon); extern int BE_IconifyWindow(_THIS); -extern int BE_GetWMInfo(_THIS, SDL_SysWMinfo *info); +extern int BE_GetWMInfo(_THIS, SDL_SysWMinfo * info); +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/bwindow/SDL_sysyuv.cc b/src/video/bwindow/SDL_sysyuv.cc index 557a120ed..c31fcb9ff 100644 --- a/src/video/bwindow/SDL_sysyuv.cc +++ b/src/video/bwindow/SDL_sysyuv.cc @@ -27,288 +27,296 @@ #include "SDL_sysyuv.h" #include "../SDL_yuvfuncs.h" -extern "C" { +extern "C" +{ /* The functions used to manipulate software video overlays */ -static struct private_yuvhwfuncs be_yuvfuncs = -{ - BE_LockYUVOverlay, - BE_UnlockYUVOverlay, - BE_DisplayYUVOverlay, - BE_FreeYUVOverlay -}; - -BBitmap * BE_GetOverlayBitmap(BRect bounds, color_space cs) { - BBitmap *bbitmap; - bbitmap = new BBitmap(bounds,B_BITMAP_WILL_OVERLAY,cs); - if (!bbitmap || bbitmap->InitCheck() != B_OK) { - delete bbitmap; - return 0; - } - overlay_restrictions r; - bbitmap->GetOverlayRestrictions(&r); - uint32 width = bounds.IntegerWidth() + 1; - uint32 height = bounds.IntegerHeight() + 1; - uint32 width_padding = 0; - uint32 height_padding = 0; - if ((r.source.horizontal_alignment != 0) || - (r.source.vertical_alignment != 0)) { - delete bbitmap; - return 0; - } - if (r.source.width_alignment != 0) { - uint32 aligned_width = r.source.width_alignment + 1; - if (width % aligned_width > 0) { - width_padding = aligned_width - width % aligned_width; - } - } - if (r.source.height_alignment != 0) { - uint32 aligned_height = r.source.height_alignment + 1; - if (height % aligned_height > 0) { - fprintf(stderr,"GetOverlayBitmap failed height alignment\n"); - fprintf(stderr,"- height = %lu, aligned_height = %lu\n",height,aligned_height); - delete bbitmap; - return 0; - } - } - if ((r.source.min_width > width) || - (r.source.min_height > height) || - (r.source.max_width < width) || - (r.source.max_height < height)) { - fprintf(stderr,"GetOverlayBitmap failed bounds tests\n"); - delete bbitmap; - return 0; - } - if ((width_padding != 0) || (height_padding != 0)) { - delete bbitmap; - bounds.Set(bounds.left,bounds.top,bounds.right+width_padding,bounds.bottom+height_padding); - bbitmap = new BBitmap(bounds,B_BITMAP_WILL_OVERLAY,cs); - if (!bbitmap || bbitmap->InitCheck() != B_OK) { - fprintf(stderr,"GetOverlayBitmap failed late\n"); - delete bbitmap; - return 0; - } - } - return bbitmap; -} + static struct private_yuvhwfuncs be_yuvfuncs = { + BE_LockYUVOverlay, + BE_UnlockYUVOverlay, + BE_DisplayYUVOverlay, + BE_FreeYUVOverlay + }; + + BBitmap *BE_GetOverlayBitmap(BRect bounds, color_space cs) + { + BBitmap *bbitmap; + bbitmap = new BBitmap(bounds, B_BITMAP_WILL_OVERLAY, cs); + if (!bbitmap || bbitmap->InitCheck() != B_OK) { + delete bbitmap; + return 0; + } + overlay_restrictions r; + bbitmap->GetOverlayRestrictions(&r); + uint32 width = bounds.IntegerWidth() + 1; + uint32 height = bounds.IntegerHeight() + 1; + uint32 width_padding = 0; + uint32 height_padding = 0; + if ((r.source.horizontal_alignment != 0) || + (r.source.vertical_alignment != 0)) { + delete bbitmap; + return 0; + } + if (r.source.width_alignment != 0) { + uint32 aligned_width = r.source.width_alignment + 1; + if (width % aligned_width > 0) { + width_padding = aligned_width - width % aligned_width; + } + } + if (r.source.height_alignment != 0) { + uint32 aligned_height = r.source.height_alignment + 1; + if (height % aligned_height > 0) { + fprintf(stderr, "GetOverlayBitmap failed height alignment\n"); + fprintf(stderr, "- height = %lu, aligned_height = %lu\n", + height, aligned_height); + delete bbitmap; + return 0; + } + } + if ((r.source.min_width > width) || + (r.source.min_height > height) || + (r.source.max_width < width) || (r.source.max_height < height)) { + fprintf(stderr, "GetOverlayBitmap failed bounds tests\n"); + delete bbitmap; + return 0; + } + if ((width_padding != 0) || (height_padding != 0)) { + delete bbitmap; + bounds.Set(bounds.left, bounds.top, + bounds.right + width_padding, + bounds.bottom + height_padding); + bbitmap = new BBitmap(bounds, B_BITMAP_WILL_OVERLAY, cs); + if (!bbitmap || bbitmap->InitCheck() != B_OK) { + fprintf(stderr, "GetOverlayBitmap failed late\n"); + delete bbitmap; + return 0; + } + } + return bbitmap; + } // See [btw: Cb=U, Cr=V] // See also http://www.fourcc.org/indexyuv.htm -enum color_space convert_color_space(Uint32 format) { - switch (format) { - case SDL_YV12_OVERLAY: - return B_YUV9; - case SDL_IYUV_OVERLAY: - return B_YUV12; - case SDL_YUY2_OVERLAY: - return B_YCbCr422; - case SDL_UYVY_OVERLAY: - return B_YUV422; - case SDL_YVYU_OVERLAY: // not supported on beos? - return B_NO_COLOR_SPACE; - default: - return B_NO_COLOR_SPACE; - } -} + enum color_space convert_color_space(Uint32 format) + { + switch (format) { + case SDL_YV12_OVERLAY: + return B_YUV9; + case SDL_IYUV_OVERLAY: + return B_YUV12; + case SDL_YUY2_OVERLAY: + return B_YCbCr422; + case SDL_UYVY_OVERLAY: + return B_YUV422; + case SDL_YVYU_OVERLAY: // not supported on beos? + return B_NO_COLOR_SPACE; + default: + return B_NO_COLOR_SPACE; + } + } // See SDL_video.h -int count_planes(Uint32 format) { - switch (format) { - case SDL_YV12_OVERLAY: - case SDL_IYUV_OVERLAY: - return 3; - case SDL_YUY2_OVERLAY: - case SDL_UYVY_OVERLAY: - case SDL_YVYU_OVERLAY: - return 1; - default: - return 0; - } -} - -SDL_Overlay *BE_CreateYUVOverlay(_THIS, int width, int height, Uint32 format, SDL_Surface *display) { - SDL_Overlay* overlay; - struct private_yuvhwdata* hwdata; - BBitmap *bbitmap; - int planes; - BRect bounds; - color_space cs; - - /* find the appropriate BeOS colorspace descriptor */ - cs = convert_color_space(format); - if (cs == B_NO_COLOR_SPACE) - { - return NULL; - } - - /* count planes */ - planes = count_planes(format); - if (planes == 0) - { - return NULL; - } - /* TODO: figure out planar modes, if anyone cares */ - if (planes == 3) - { - return NULL; - } - - /* Create the overlay structure */ - overlay = (SDL_Overlay*)SDL_calloc(1, sizeof(SDL_Overlay)); - - if (overlay == NULL) + int count_planes(Uint32 format) { - SDL_OutOfMemory(); - return NULL; + switch (format) { + case SDL_YV12_OVERLAY: + case SDL_IYUV_OVERLAY: + return 3; + case SDL_YUY2_OVERLAY: + case SDL_UYVY_OVERLAY: + case SDL_YVYU_OVERLAY: + return 1; + default: + return 0; + } } - /* Fill in the basic members */ - overlay->format = format; - overlay->w = width; - overlay->h = height; - overlay->hwdata = NULL; - - /* Set up the YUV surface function structure */ - overlay->hwfuncs = &be_yuvfuncs; + SDL_Overlay *BE_CreateYUVOverlay(_THIS, int width, int height, + Uint32 format, SDL_Surface * display) + { + SDL_Overlay *overlay; + struct private_yuvhwdata *hwdata; + BBitmap *bbitmap; + int planes; + BRect bounds; + color_space cs; - /* Create the pixel data and lookup tables */ - hwdata = (struct private_yuvhwdata*)SDL_calloc(1, sizeof(struct private_yuvhwdata)); + /* find the appropriate BeOS colorspace descriptor */ + cs = convert_color_space(format); + if (cs == B_NO_COLOR_SPACE) { + return NULL; + } - if (hwdata == NULL) - { - SDL_OutOfMemory(); - SDL_FreeYUVOverlay(overlay); - return NULL; - } + /* count planes */ + planes = count_planes(format); + if (planes == 0) { + return NULL; + } + /* TODO: figure out planar modes, if anyone cares */ + if (planes == 3) { + return NULL; + } - overlay->hwdata = hwdata; - overlay->hwdata->display = display; - overlay->hwdata->bview = NULL; - overlay->hwdata->bbitmap = NULL; - overlay->hwdata->locked = 0; - - /* Create the BBitmap framebuffer */ - bounds.top = 0; bounds.left = 0; - bounds.right = width-1; - bounds.bottom = height-1; - - BView * bview = new BView(bounds,"overlay",B_FOLLOW_NONE,B_WILL_DRAW); - if (!bview) { - SDL_OutOfMemory(); - SDL_FreeYUVOverlay(overlay); - return NULL; - } - overlay->hwdata->bview = bview; - overlay->hwdata->first_display = true; - bview->Hide(); - - bbitmap = BE_GetOverlayBitmap(bounds,cs); - if (!bbitmap) { - overlay->hwdata->bbitmap = NULL; - SDL_FreeYUVOverlay(overlay); - return NULL; - } - overlay->hwdata->bbitmap = bbitmap; - - overlay->planes = planes; - overlay->pitches = (Uint16*)SDL_calloc(overlay->planes, sizeof(Uint16)); - overlay->pixels = (Uint8**)SDL_calloc(overlay->planes, sizeof(Uint8*)); - if (!overlay->pitches || !overlay->pixels) - { - SDL_OutOfMemory(); - SDL_FreeYUVOverlay(overlay); - return(NULL); - } + /* Create the overlay structure */ + overlay = (SDL_Overlay *) SDL_calloc(1, sizeof(SDL_Overlay)); + + if (overlay == NULL) { + SDL_OutOfMemory(); + return NULL; + } + + /* Fill in the basic members */ + overlay->format = format; + overlay->w = width; + overlay->h = height; + overlay->hwdata = NULL; + + /* Set up the YUV surface function structure */ + overlay->hwfuncs = &be_yuvfuncs; + + /* Create the pixel data and lookup tables */ + hwdata = + (struct private_yuvhwdata *) SDL_calloc(1, + sizeof(struct + private_yuvhwdata)); + + if (hwdata == NULL) { + SDL_OutOfMemory(); + SDL_FreeYUVOverlay(overlay); + return NULL; + } + + overlay->hwdata = hwdata; + overlay->hwdata->display = display; + overlay->hwdata->bview = NULL; + overlay->hwdata->bbitmap = NULL; + overlay->hwdata->locked = 0; + + /* Create the BBitmap framebuffer */ + bounds.top = 0; + bounds.left = 0; + bounds.right = width - 1; + bounds.bottom = height - 1; + + BView *bview = + new BView(bounds, "overlay", B_FOLLOW_NONE, B_WILL_DRAW); + if (!bview) { + SDL_OutOfMemory(); + SDL_FreeYUVOverlay(overlay); + return NULL; + } + overlay->hwdata->bview = bview; + overlay->hwdata->first_display = true; + bview->Hide(); + + bbitmap = BE_GetOverlayBitmap(bounds, cs); + if (!bbitmap) { + overlay->hwdata->bbitmap = NULL; + SDL_FreeYUVOverlay(overlay); + return NULL; + } + overlay->hwdata->bbitmap = bbitmap; + + overlay->planes = planes; + overlay->pitches = + (Uint16 *) SDL_calloc(overlay->planes, sizeof(Uint16)); + overlay->pixels = + (Uint8 **) SDL_calloc(overlay->planes, sizeof(Uint8 *)); + if (!overlay->pitches || !overlay->pixels) { + SDL_OutOfMemory(); + SDL_FreeYUVOverlay(overlay); + return (NULL); + } - overlay->pitches[0] = bbitmap->BytesPerRow(); - overlay->pixels[0] = (Uint8 *)bbitmap->Bits(); - overlay->hw_overlay = 1; - - if (SDL_Win->LockWithTimeout(1000000) != B_OK) { - SDL_FreeYUVOverlay(overlay); - return(NULL); + overlay->pitches[0] = bbitmap->BytesPerRow(); + overlay->pixels[0] = (Uint8 *) bbitmap->Bits(); + overlay->hw_overlay = 1; + + if (SDL_Win->LockWithTimeout(1000000) != B_OK) { + SDL_FreeYUVOverlay(overlay); + return (NULL); + } + BView *view = SDL_Win->View(); + view->AddChild(bview); + rgb_color key; + bview->SetViewOverlay(bbitmap, bounds, bview->Bounds(), &key, + B_FOLLOW_ALL, + B_OVERLAY_FILTER_HORIZONTAL | + B_OVERLAY_FILTER_VERTICAL); + bview->SetViewColor(key); + bview->Flush(); + SDL_Win->Unlock(); + + current_overlay = overlay; + + return overlay; } - BView * view = SDL_Win->View(); - view->AddChild(bview); - rgb_color key; - bview->SetViewOverlay(bbitmap,bounds,bview->Bounds(),&key,B_FOLLOW_ALL, - B_OVERLAY_FILTER_HORIZONTAL|B_OVERLAY_FILTER_VERTICAL); - bview->SetViewColor(key); - bview->Flush(); - SDL_Win->Unlock(); - - current_overlay=overlay; - - return overlay; -} - -int BE_LockYUVOverlay(_THIS, SDL_Overlay* overlay) -{ - if (overlay == NULL) + + int BE_LockYUVOverlay(_THIS, SDL_Overlay * overlay) { + if (overlay == NULL) { + return 0; + } + + overlay->hwdata->locked = 1; return 0; } - overlay->hwdata->locked = 1; - return 0; -} - -void BE_UnlockYUVOverlay(_THIS, SDL_Overlay* overlay) -{ - if (overlay == NULL) + void BE_UnlockYUVOverlay(_THIS, SDL_Overlay * overlay) { - return; - } + if (overlay == NULL) { + return; + } - overlay->hwdata->locked = 0; -} + overlay->hwdata->locked = 0; + } -int BE_DisplayYUVOverlay(_THIS, SDL_Overlay* overlay, SDL_Rect* src, SDL_Rect *dst) -{ - if ((overlay == NULL) || (overlay->hwdata==NULL) - || (overlay->hwdata->bview==NULL) || (SDL_Win->View() == NULL)) + int BE_DisplayYUVOverlay(_THIS, SDL_Overlay * overlay, SDL_Rect * src, + SDL_Rect * dst) { - return -1; - } - if (SDL_Win->LockWithTimeout(50000) != B_OK) { + if ((overlay == NULL) || (overlay->hwdata == NULL) + || (overlay->hwdata->bview == NULL) || (SDL_Win->View() == NULL)) { + return -1; + } + if (SDL_Win->LockWithTimeout(50000) != B_OK) { + return 0; + } + BView *bview = overlay->hwdata->bview; + if (SDL_Win->IsFullScreen()) { + int left, top; + SDL_Win->GetXYOffset(left, top); + bview->MoveTo(left + dst->x, top + dst->y); + } else { + bview->MoveTo(dst->x, dst->y); + } + bview->ResizeTo(dst->w, dst->h); + bview->Flush(); + if (overlay->hwdata->first_display) { + bview->Show(); + overlay->hwdata->first_display = false; + } + SDL_Win->Unlock(); + return 0; } - BView * bview = overlay->hwdata->bview; - if (SDL_Win->IsFullScreen()) { - int left,top; - SDL_Win->GetXYOffset(left,top); - bview->MoveTo(left+dst->x,top+dst->y); - } else { - bview->MoveTo(dst->x,dst->y); - } - bview->ResizeTo(dst->w,dst->h); - bview->Flush(); - if (overlay->hwdata->first_display) { - bview->Show(); - overlay->hwdata->first_display = false; - } - SDL_Win->Unlock(); - - return 0; -} - -void BE_FreeYUVOverlay(_THIS, SDL_Overlay *overlay) -{ - if (overlay == NULL) - { - return; - } - if (overlay->hwdata == NULL) + void BE_FreeYUVOverlay(_THIS, SDL_Overlay * overlay) { - return; - } + if (overlay == NULL) { + return; + } + + if (overlay->hwdata == NULL) { + return; + } - current_overlay=NULL; + current_overlay = NULL; - delete overlay->hwdata->bbitmap; + delete overlay->hwdata->bbitmap; + + SDL_free(overlay->hwdata); + } - SDL_free(overlay->hwdata); -} +}; // extern "C" -}; // extern "C" +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/bwindow/SDL_sysyuv.h b/src/video/bwindow/SDL_sysyuv.h index 64859f2fe..90f62cd36 100644 --- a/src/video/bwindow/SDL_sysyuv.h +++ b/src/video/bwindow/SDL_sysyuv.h @@ -30,10 +30,11 @@ #include "SDL_video.h" #include "SDL_lowvideo.h" -extern "C" { - -struct private_yuvhwdata +extern "C" { + + struct private_yuvhwdata + { /* FRAMEDATA* CurrentFrameData; FRAMEDATA* FrameData0; FRAMEDATA* FrameData1; @@ -54,20 +55,24 @@ struct private_yuvhwdata unsigned long State; long flags; */ - SDL_Surface *display; - BView *bview; - bool first_display; - BBitmap *bbitmap; - int locked; -}; + SDL_Surface *display; + BView *bview; + bool first_display; + BBitmap *bbitmap; + int locked; + }; -extern BBitmap * BE_GetOverlayBitmap(BRect bounds, color_space cs); -extern SDL_Overlay* BE_CreateYUVOverlay(_THIS, int width, int height, Uint32 format, SDL_Surface* display); -extern int BE_LockYUVOverlay(_THIS, SDL_Overlay* overlay); -extern void BE_UnlockYUVOverlay(_THIS, SDL_Overlay* overlay); -extern int BE_DisplayYUVOverlay(_THIS, SDL_Overlay* overlay, SDL_Rect* src, SDL_Rect* dst); -extern void BE_FreeYUVOverlay(_THIS, SDL_Overlay* overlay); + extern BBitmap *BE_GetOverlayBitmap(BRect bounds, color_space cs); + extern SDL_Overlay *BE_CreateYUVOverlay(_THIS, int width, int height, + Uint32 format, + SDL_Surface * display); + extern int BE_LockYUVOverlay(_THIS, SDL_Overlay * overlay); + extern void BE_UnlockYUVOverlay(_THIS, SDL_Overlay * overlay); + extern int BE_DisplayYUVOverlay(_THIS, SDL_Overlay * overlay, + SDL_Rect * src, SDL_Rect * dst); + extern void BE_FreeYUVOverlay(_THIS, SDL_Overlay * overlay); }; #endif /* __SDL_PH_YUV_H__ */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/cybergfx/SDL_amigaevents.c b/src/video/cybergfx/SDL_amigaevents.c index 333d0fa38..8481411bc 100644 --- a/src/video/cybergfx/SDL_amigaevents.c +++ b/src/video/cybergfx/SDL_amigaevents.c @@ -37,9 +37,9 @@ /* The translation tables from an Amiga keysym to a SDL keysym */ static SDLKey MISC_keymap[256]; -SDL_keysym *amiga_TranslateKey(int code, SDL_keysym *keysym); -struct IOStdReq *ConReq=NULL; -struct MsgPort *ConPort=NULL; +SDL_keysym *amiga_TranslateKey(int code, SDL_keysym * keysym); +struct IOStdReq *ConReq = NULL; +struct MsgPort *ConPort = NULL; /* Note: The X server buffers and accumulates mouse motion events, so the motion event generated by the warp may not appear exactly as we @@ -50,270 +50,276 @@ struct MsgPort *ConPort=NULL; #if 0 -static inline int amiga_WarpedMotion(_THIS, struct IntuiMessage *m) +static inline int +amiga_WarpedMotion(_THIS, struct IntuiMessage *m) { - int w, h, i; - int deltax, deltay; - int posted; - - w = SDL_VideoSurface->w; - h = SDL_VideoSurface->h; - deltax = xevent->xmotion.x - mouse_last.x; - deltay = xevent->xmotion.y - mouse_last.y; + int w, h, i; + int deltax, deltay; + int posted; + + w = SDL_VideoSurface->w; + h = SDL_VideoSurface->h; + deltax = xevent->xmotion.x - mouse_last.x; + deltay = xevent->xmotion.y - mouse_last.y; #ifdef DEBUG_MOTION - printf("Warped mouse motion: %d,%d\n", deltax, deltay); + printf("Warped mouse motion: %d,%d\n", deltax, deltay); #endif - mouse_last.x = xevent->xmotion.x; - mouse_last.y = xevent->xmotion.y; - posted = SDL_PrivateMouseMotion(0, 1, deltax, deltay); - - if ( (xevent->xmotion.x < MOUSE_FUDGE_FACTOR) || - (xevent->xmotion.x > (w-MOUSE_FUDGE_FACTOR)) || - (xevent->xmotion.y < MOUSE_FUDGE_FACTOR) || - (xevent->xmotion.y > (h-MOUSE_FUDGE_FACTOR)) ) { - /* Get the events that have accumulated */ - while ( XCheckTypedEvent(SDL_Display, MotionNotify, xevent) ) { - deltax = xevent->xmotion.x - mouse_last.x; - deltay = xevent->xmotion.y - mouse_last.y; + mouse_last.x = xevent->xmotion.x; + mouse_last.y = xevent->xmotion.y; + posted = SDL_PrivateMouseMotion(0, 1, deltax, deltay); + + if ((xevent->xmotion.x < MOUSE_FUDGE_FACTOR) || + (xevent->xmotion.x > (w - MOUSE_FUDGE_FACTOR)) || + (xevent->xmotion.y < MOUSE_FUDGE_FACTOR) || + (xevent->xmotion.y > (h - MOUSE_FUDGE_FACTOR))) { + /* Get the events that have accumulated */ + while (XCheckTypedEvent(SDL_Display, MotionNotify, xevent)) { + deltax = xevent->xmotion.x - mouse_last.x; + deltay = xevent->xmotion.y - mouse_last.y; #ifdef DEBUG_MOTION - printf("Extra mouse motion: %d,%d\n", deltax, deltay); + printf("Extra mouse motion: %d,%d\n", deltax, deltay); #endif - mouse_last.x = xevent->xmotion.x; - mouse_last.y = xevent->xmotion.y; - posted += SDL_PrivateMouseMotion(0, 1, deltax, deltay); - } - mouse_last.x = w/2; - mouse_last.y = h/2; - XWarpPointer(SDL_Display, None, SDL_Window, 0, 0, 0, 0, - mouse_last.x, mouse_last.y); - for ( i=0; i<10; ++i ) { - XMaskEvent(SDL_Display, PointerMotionMask, xevent); - if ( (xevent->xmotion.x > - (mouse_last.x-MOUSE_FUDGE_FACTOR)) && - (xevent->xmotion.x < - (mouse_last.x+MOUSE_FUDGE_FACTOR)) && - (xevent->xmotion.y > - (mouse_last.y-MOUSE_FUDGE_FACTOR)) && - (xevent->xmotion.y < - (mouse_last.y+MOUSE_FUDGE_FACTOR)) ) { - break; - } + mouse_last.x = xevent->xmotion.x; + mouse_last.y = xevent->xmotion.y; + posted += SDL_PrivateMouseMotion(0, 1, deltax, deltay); + } + mouse_last.x = w / 2; + mouse_last.y = h / 2; + XWarpPointer(SDL_Display, None, SDL_Window, 0, 0, 0, 0, + mouse_last.x, mouse_last.y); + for (i = 0; i < 10; ++i) { + XMaskEvent(SDL_Display, PointerMotionMask, xevent); + if ((xevent->xmotion.x > + (mouse_last.x - MOUSE_FUDGE_FACTOR)) && + (xevent->xmotion.x < + (mouse_last.x + MOUSE_FUDGE_FACTOR)) && + (xevent->xmotion.y > + (mouse_last.y - MOUSE_FUDGE_FACTOR)) && + (xevent->xmotion.y < (mouse_last.y + MOUSE_FUDGE_FACTOR))) { + break; + } #ifdef DEBUG_XEVENTS - printf("Lost mouse motion: %d,%d\n", xevent->xmotion.x, xevent->xmotion.y); + printf("Lost mouse motion: %d,%d\n", xevent->xmotion.x, + xevent->xmotion.y); #endif - } + } #ifdef DEBUG_XEVENTS - if ( i == 10 ) { - printf("Warning: didn't detect mouse warp motion\n"); - } + if (i == 10) { + printf("Warning: didn't detect mouse warp motion\n"); + } #endif - } - return(posted); + } + return (posted); } #endif -static int amiga_GetButton(int code) +static int +amiga_GetButton(int code) { - switch(code) - { - case IECODE_MBUTTON: - return SDL_BUTTON_MIDDLE; - case IECODE_RBUTTON: - return SDL_BUTTON_RIGHT; - default: - return SDL_BUTTON_LEFT; - } + switch (code) { + case IECODE_MBUTTON: + return SDL_BUTTON_MIDDLE; + case IECODE_RBUTTON: + return SDL_BUTTON_RIGHT; + default: + return SDL_BUTTON_LEFT; + } } -static int amiga_DispatchEvent(_THIS,struct IntuiMessage *msg) +static int +amiga_DispatchEvent(_THIS, struct IntuiMessage *msg) { - int class=msg->Class,code=msg->Code; - int posted; - - posted = 0; - switch (class) { - /* Gaining mouse coverage? */ - case IDCMP_ACTIVEWINDOW: - posted = SDL_PrivateAppActive(1, SDL_APPMOUSEFOCUS); - break; - - /* Losing mouse coverage? */ - case IDCMP_INACTIVEWINDOW: - posted = SDL_PrivateAppActive(0, SDL_APPMOUSEFOCUS); - break; + int class = msg->Class, code = msg->Code; + int posted; + + posted = 0; + switch (class) { + /* Gaining mouse coverage? */ + case IDCMP_ACTIVEWINDOW: + posted = SDL_PrivateAppActive(1, SDL_APPMOUSEFOCUS); + break; + + /* Losing mouse coverage? */ + case IDCMP_INACTIVEWINDOW: + posted = SDL_PrivateAppActive(0, SDL_APPMOUSEFOCUS); + break; #if 0 - /* Gaining input focus? */ - case IDCMP_ACTIVEWINDOW: - posted = SDL_PrivateAppActive(1, SDL_APPINPUTFOCUS); - - /* Queue entry into fullscreen mode */ - switch_waiting = 0x01 | SDL_FULLSCREEN; - switch_time = SDL_GetTicks() + 1500; - break; - - /* Losing input focus? */ - case IDCMP_INACTIVEWINDOW: - posted = SDL_PrivateAppActive(0, SDL_APPINPUTFOCUS); - - /* Queue leaving fullscreen mode */ - switch_waiting = 0x01; - switch_time = SDL_GetTicks() + 200; - break; + /* Gaining input focus? */ + case IDCMP_ACTIVEWINDOW: + posted = SDL_PrivateAppActive(1, SDL_APPINPUTFOCUS); + + /* Queue entry into fullscreen mode */ + switch_waiting = 0x01 | SDL_FULLSCREEN; + switch_time = SDL_GetTicks() + 1500; + break; + + /* Losing input focus? */ + case IDCMP_INACTIVEWINDOW: + posted = SDL_PrivateAppActive(0, SDL_APPINPUTFOCUS); + + /* Queue leaving fullscreen mode */ + switch_waiting = 0x01; + switch_time = SDL_GetTicks() + 200; + break; #endif - /* Mouse motion? */ - case IDCMP_MOUSEMOVE: - if ( SDL_VideoSurface ) { - posted = SDL_PrivateMouseMotion(0, 0, - msg->MouseX-SDL_Window->BorderLeft, - msg->MouseY-SDL_Window->BorderTop); - } - break; - - /* Mouse button press? */ - case IDCMP_MOUSEBUTTONS: - - if(!(code&IECODE_UP_PREFIX)) - { - posted = SDL_PrivateMouseButton(SDL_PRESSED, - amiga_GetButton(code), 0, 0); - } - /* Mouse button release? */ - else - { - code&=~IECODE_UP_PREFIX; - posted = SDL_PrivateMouseButton(SDL_RELEASED, - amiga_GetButton(code), 0, 0); - } - break; - - case IDCMP_RAWKEY: - - /* Key press? */ - - if( !(code&IECODE_UP_PREFIX) ) - { - SDL_keysym keysym; - posted = SDL_PrivateKeyboard(SDL_PRESSED, - amiga_TranslateKey(code, &keysym)); - } - else - { - /* Key release? */ - - SDL_keysym keysym; - code&=~IECODE_UP_PREFIX; - - /* Check to see if this is a repeated key */ + /* Mouse motion? */ + case IDCMP_MOUSEMOVE: + if (SDL_VideoSurface) { + posted = SDL_PrivateMouseMotion(0, 0, + msg->MouseX - + SDL_Window->BorderLeft, + msg->MouseY - + SDL_Window->BorderTop); + } + break; + + /* Mouse button press? */ + case IDCMP_MOUSEBUTTONS: + + if (!(code & IECODE_UP_PREFIX)) { + posted = SDL_PrivateMouseButton(SDL_PRESSED, + amiga_GetButton(code), 0, 0); + } + /* Mouse button release? */ + else { + code &= ~IECODE_UP_PREFIX; + posted = SDL_PrivateMouseButton(SDL_RELEASED, + amiga_GetButton(code), 0, 0); + } + break; + + case IDCMP_RAWKEY: + + /* Key press? */ + + if (!(code & IECODE_UP_PREFIX)) { + SDL_keysym keysym; + posted = SDL_PrivateKeyboard(SDL_PRESSED, + amiga_TranslateKey(code, &keysym)); + } else { + /* Key release? */ + + SDL_keysym keysym; + code &= ~IECODE_UP_PREFIX; + + /* Check to see if this is a repeated key */ /* if ( ! X11_KeyRepeat(SDL_Display, &xevent) ) */ - posted = SDL_PrivateKeyboard(SDL_RELEASED, - amiga_TranslateKey(code, &keysym)); - } - break; - /* Have we been iconified? */ + posted = SDL_PrivateKeyboard(SDL_RELEASED, + amiga_TranslateKey(code, &keysym)); + } + break; + /* Have we been iconified? */ #if 0 - case UnmapNotify: { + case UnmapNotify: + { #ifdef DEBUG_XEVENTS -printf("UnmapNotify!\n"); + printf("UnmapNotify!\n"); #endif - posted=SDL_PrivateAppActive(0, SDL_APPACTIVE|SDL_APPINPUTFOCUS); - } - break; + posted = + SDL_PrivateAppActive(0, SDL_APPACTIVE | SDL_APPINPUTFOCUS); + } + break; - /* Have we been restored? */ + /* Have we been restored? */ - case MapNotify: { + case MapNotify: + { #ifdef DEBUG_XEVENTS -printf("MapNotify!\n"); + printf("MapNotify!\n"); #endif - posted = SDL_PrivateAppActive(1, SDL_APPACTIVE); - - if ( SDL_VideoSurface && - (SDL_VideoSurface->flags & SDL_FULLSCREEN) ) - { - CGX_EnterFullScreen(this); - } else { - X11_GrabInputNoLock(this, this->input_grab); - } - if ( SDL_VideoSurface ) { - CGX_RefreshDisplay(this); - } - } - break; - case Expose: - if ( SDL_VideoSurface && (xevent.xexpose.count == 0) ) { - CGX_RefreshDisplay(this); - } - break; + posted = SDL_PrivateAppActive(1, SDL_APPACTIVE); + + if (SDL_VideoSurface && + (SDL_VideoSurface->flags & SDL_FULLSCREEN)) { + CGX_EnterFullScreen(this); + } else { + X11_GrabInputNoLock(this, this->input_grab); + } + if (SDL_VideoSurface) { + CGX_RefreshDisplay(this); + } + } + break; + case Expose: + if (SDL_VideoSurface && (xevent.xexpose.count == 0)) { + CGX_RefreshDisplay(this); + } + break; #endif - /* Have we been resized? */ - case IDCMP_NEWSIZE: - SDL_PrivateResize(SDL_Window->Width-SDL_Window->BorderLeft-SDL_Window->BorderRight, - SDL_Window->Height-SDL_Window->BorderTop-SDL_Window->BorderBottom); + /* Have we been resized? */ + case IDCMP_NEWSIZE: + SDL_PrivateResize(SDL_Window->Width - SDL_Window->BorderLeft - + SDL_Window->BorderRight, + SDL_Window->Height - SDL_Window->BorderTop - + SDL_Window->BorderBottom); - break; + break; - /* Have we been requested to quit? */ - case IDCMP_CLOSEWINDOW: - posted = SDL_PrivateQuit(); - break; + /* Have we been requested to quit? */ + case IDCMP_CLOSEWINDOW: + posted = SDL_PrivateQuit(); + break; - /* Do we need to refresh ourselves? */ + /* Do we need to refresh ourselves? */ - default: { - /* Only post the event if we're watching for it */ - if ( SDL_ProcessEvents[SDL_SYSWMEVENT] == SDL_ENABLE ) { - SDL_SysWMmsg wmmsg; + default: + { + /* Only post the event if we're watching for it */ + if (SDL_ProcessEvents[SDL_SYSWMEVENT] == SDL_ENABLE) { + SDL_SysWMmsg wmmsg; - SDL_VERSION(&wmmsg.version); + SDL_VERSION(&wmmsg.version); #if 0 - wmmsg.subsystem = SDL_SYSWM_CGX; - wmmsg.event.xevent = xevent; + wmmsg.subsystem = SDL_SYSWM_CGX; + wmmsg.event.xevent = xevent; #endif - posted = SDL_PrivateSysWMEvent(&wmmsg); - } - } - break; - } - ReplyMsg((struct Message *)msg); + posted = SDL_PrivateSysWMEvent(&wmmsg); + } + } + break; + } + ReplyMsg((struct Message *) msg); - return(posted); + return (posted); } -void amiga_PumpEvents(_THIS) +void +amiga_PumpEvents(_THIS) { - int pending; - struct IntuiMessage *m; - - /* Keep processing pending events */ - pending = 0; - while ( m=(struct IntuiMessage *)GetMsg(SDL_Window->UserPort) ) { - amiga_DispatchEvent(this,m); - ++pending; - } + int pending; + struct IntuiMessage *m; + + /* Keep processing pending events */ + pending = 0; + while (m = (struct IntuiMessage *) GetMsg(SDL_Window->UserPort)) { + amiga_DispatchEvent(this, m); + ++pending; + } } -void amiga_InitKeymap(void) +void +amiga_InitKeymap(void) { - int i; - - /* Map the miscellaneous keys */ - for ( i=0; iscancode = code; - keysym->sym = MISC_keymap[code]; + /* Get the raw keyboard scancode */ + keysym->scancode = code; + keysym->sym = MISC_keymap[code]; #ifdef DEBUG_KEYS - fprintf(stderr, "Translating key 0x%.4x (%d)\n", xsym, xkey->keycode); + fprintf(stderr, "Translating key 0x%.4x (%d)\n", xsym, xkey->keycode); +#endif + /* Get the translated SDL virtual keysym */ + if (keysym->sym == SDLK_UNKNOWN) { +#ifdef STORMC4_WOS + if (!KeymapBase) +#else + if (!ConsoleDevice) +#endif + { +#ifdef STORMC4_WOS + KeymapBase = OpenLibrary("keymap.library", 0L); +#else + if (ConPort = CreateMsgPort()) { + if (ConReq = + CreateIORequest(ConPort, sizeof(struct IOStdReq))) { + if (!OpenDevice + ("console.device", -1, + (struct IORequest *) ConReq, 0)) + ConsoleDevice = (struct Library *) ConReq->io_Device; + else { + DeleteIORequest(ConReq); + ConReq = NULL; + } + } else { + DeleteMsgPort(ConPort); + ConPort = NULL; + } + } #endif - /* Get the translated SDL virtual keysym */ - if ( keysym->sym==SDLK_UNKNOWN ) - { - #ifdef STORMC4_WOS - if(!KeymapBase) - #else - if(!ConsoleDevice) - #endif - { - #ifdef STORMC4_WOS - KeymapBase=OpenLibrary("keymap.library", 0L); - #else - if(ConPort=CreateMsgPort()) - { - if(ConReq=CreateIORequest(ConPort,sizeof(struct IOStdReq))) - { - if(!OpenDevice("console.device",-1,(struct IORequest *)ConReq,0)) - ConsoleDevice=(struct Library *)ConReq->io_Device; - else - { - DeleteIORequest(ConReq); - ConReq=NULL; - } - } - else - { - DeleteMsgPort(ConPort); - ConPort=NULL; - } - } - #endif - } - - #ifdef STORMC4_WOS - if(KeymapBase) - #else - if(ConsoleDevice) - #endif - { - struct InputEvent event; - long actual; - char buffer[5]; - - event.ie_Qualifier=0; - event.ie_Class=IECLASS_RAWKEY; - event.ie_SubClass=0L; - event.ie_Code=code; - event.ie_X=event.ie_Y=0; - event.ie_EventAddress=NULL; - event.ie_NextEvent=NULL; - event.ie_Prev1DownCode=event.ie_Prev1DownQual=event.ie_Prev2DownCode=event.ie_Prev2DownQual=0; - - #ifdef STORMC4_WOS - if( (actual=MapRawKey(&event,buffer,5,NULL))>=0) - #else - if( (actual=RawKeyConvert(&event,buffer,5,NULL))>=0) - #endif - { - if(actual>1) - { - D(bug("Warning (%ld) character conversion!\n",actual)); - } - else if(actual==1) - { - keysym->sym=*buffer; - D(bug("Converted rawcode %ld to <%lc>\n",code,*buffer)); + } +#ifdef STORMC4_WOS + if (KeymapBase) +#else + if (ConsoleDevice) +#endif + { + struct InputEvent event; + long actual; + char buffer[5]; + + event.ie_Qualifier = 0; + event.ie_Class = IECLASS_RAWKEY; + event.ie_SubClass = 0L; + event.ie_Code = code; + event.ie_X = event.ie_Y = 0; + event.ie_EventAddress = NULL; + event.ie_NextEvent = NULL; + event.ie_Prev1DownCode = event.ie_Prev1DownQual = + event.ie_Prev2DownCode = event.ie_Prev2DownQual = 0; + +#ifdef STORMC4_WOS + if ((actual = MapRawKey(&event, buffer, 5, NULL)) >= 0) +#else + if ((actual = RawKeyConvert(&event, buffer, 5, NULL)) >= 0) +#endif + { + if (actual > 1) { + D(bug("Warning (%ld) character conversion!\n", actual)); + } else if (actual == 1) { + keysym->sym = *buffer; + D(bug("Converted rawcode %ld to <%lc>\n", code, *buffer)); // Bufferizzo x le successive chiamate! - MISC_keymap[code]=*buffer; - } - } - } + MISC_keymap[code] = *buffer; + } + } + } - } - keysym->mod = KMOD_NONE; + } + keysym->mod = KMOD_NONE; - /* If UNICODE is on, get the UNICODE value for the key */ - keysym->unicode = 0; - if ( SDL_TranslateUNICODE ) { + /* If UNICODE is on, get the UNICODE value for the key */ + keysym->unicode = 0; + if (SDL_TranslateUNICODE) { #if 0 - static XComposeStatus state; - /* Until we handle the IM protocol, use XLookupString() */ - unsigned char keybuf[32]; - if ( XLookupString(xkey, (char *)keybuf, sizeof(keybuf), - NULL, &state) ) { - keysym->unicode = keybuf[0]; - } + static XComposeStatus state; + /* Until we handle the IM protocol, use XLookupString() */ + unsigned char keybuf[32]; + if (XLookupString(xkey, (char *) keybuf, sizeof(keybuf), + NULL, &state)) { + keysym->unicode = keybuf[0]; + } #endif - } - return(keysym); + } + return (keysym); } -void amiga_InitOSKeymap(_THIS) +void +amiga_InitOSKeymap(_THIS) { - amiga_InitKeymap(); + amiga_InitKeymap(); } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/cybergfx/SDL_amigaevents_c.h b/src/video/cybergfx/SDL_amigaevents_c.h index 11b86b5e5..a3a2e197c 100644 --- a/src/video/cybergfx/SDL_amigaevents_c.h +++ b/src/video/cybergfx/SDL_amigaevents_c.h @@ -26,4 +26,4 @@ /* Functions to be exported */ extern void amiga_InitOSKeymap(_THIS); extern void amiga_PumpEvents(_THIS); - +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/cybergfx/SDL_amigamouse.c b/src/video/cybergfx/SDL_amigamouse.c index 64940a82d..786714812 100644 --- a/src/video/cybergfx/SDL_amigamouse.c +++ b/src/video/cybergfx/SDL_amigamouse.c @@ -29,49 +29,57 @@ /* The implementation dependent data for the window manager cursor */ -typedef void * WMCursor; +typedef void *WMCursor; -void amiga_FreeWMCursor(_THIS, WMcursor *cursor) +void +amiga_FreeWMCursor(_THIS, WMcursor * cursor) { } -WMcursor *amiga_CreateWMCursor(_THIS, - Uint8 *data, Uint8 *mask, int w, int h, int hot_x, int hot_y) +WMcursor * +amiga_CreateWMCursor(_THIS, + Uint8 * data, Uint8 * mask, int w, int h, int hot_x, + int hot_y) { - return (WMcursor *)1; // Amiga has an Hardware cursor, so it's ok to return something unuseful but true + return (WMcursor *) 1; // Amiga has an Hardware cursor, so it's ok to return something unuseful but true } -int amiga_ShowWMCursor(_THIS, WMcursor *cursor) +int +amiga_ShowWMCursor(_THIS, WMcursor * cursor) { - /* Don't do anything if the display is gone */ - if ( SDL_Display == NULL) { - return(0); - } + /* Don't do anything if the display is gone */ + if (SDL_Display == NULL) { + return (0); + } - /* Set the Amiga prefs cursor cursor, or blank if cursor is NULL */ + /* Set the Amiga prefs cursor cursor, or blank if cursor is NULL */ - if ( SDL_Window ) { - SDL_Lock_EventThread(); - if ( cursor == NULL ) { - if ( SDL_BlankCursor != NULL ) { + if (SDL_Window) { + SDL_Lock_EventThread(); + if (cursor == NULL) { + if (SDL_BlankCursor != NULL) { // Hide cursor HERE - SetPointer(SDL_Window,(UWORD *)SDL_BlankCursor,1,1,0,0); - } - } else { + SetPointer(SDL_Window, (UWORD *) SDL_BlankCursor, 1, 1, 0, 0); + } + } else { // Show cursor - ClearPointer(SDL_Window); - } - SDL_Unlock_EventThread(); - } - return(1); + ClearPointer(SDL_Window); + } + SDL_Unlock_EventThread(); + } + return (1); } -void amiga_WarpWMCursor(_THIS, Uint16 x, Uint16 y) +void +amiga_WarpWMCursor(_THIS, Uint16 x, Uint16 y) { /* FIXME: Not implemented */ } /* Check to see if we need to enter or leave mouse relative mode */ -void amiga_CheckMouseMode(_THIS) +void +amiga_CheckMouseMode(_THIS) { } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/cybergfx/SDL_amigamouse_c.h b/src/video/cybergfx/SDL_amigamouse_c.h index aad19b627..f2356bf09 100644 --- a/src/video/cybergfx/SDL_amigamouse_c.h +++ b/src/video/cybergfx/SDL_amigamouse_c.h @@ -24,9 +24,11 @@ #include "SDL_cgxvideo.h" /* Functions to be exported */ -extern void amiga_FreeWMCursor(_THIS, WMcursor *cursor); +extern void amiga_FreeWMCursor(_THIS, WMcursor * cursor); extern WMcursor *amiga_CreateWMCursor(_THIS, - Uint8 *data, Uint8 *mask, int w, int h, int hot_x, int hot_y); -extern int amiga_ShowWMCursor(_THIS, WMcursor *cursor); + Uint8 * data, Uint8 * mask, int w, + int h, int hot_x, int hot_y); +extern int amiga_ShowWMCursor(_THIS, WMcursor * cursor); extern void amiga_WarpWMCursor(_THIS, Uint16 x, Uint16 y); extern void amiga_CheckMouseMode(_THIS); +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/cybergfx/SDL_cgxaccel.c b/src/video/cybergfx/SDL_cgxaccel.c index 24605e355..c0f73660c 100644 --- a/src/video/cybergfx/SDL_cgxaccel.c +++ b/src/video/cybergfx/SDL_cgxaccel.c @@ -27,8 +27,8 @@ #include "../SDL_blit.h" #include "SDL_cgxvideo.h" -static int CGX_HWAccelBlit(SDL_Surface *src, SDL_Rect *srcrect, - SDL_Surface *dst, SDL_Rect *dstrect); +static int CGX_HWAccelBlit(SDL_Surface * src, SDL_Rect * srcrect, + SDL_Surface * dst, SDL_Rect * dstrect); // These are needed to avoid register troubles with gcc -O2! @@ -37,226 +37,236 @@ static int CGX_HWAccelBlit(SDL_Surface *src, SDL_Rect *srcrect, #define BBRP(a,b,c,d,e,f,g,h,i) BltBitMapRastPort(a,b,c,d,e,f,g,h,i) #define BBB(a,b,c,d,e,f,g,h,i,j,k) BltBitMap(a,b,c,d,e,f,g,h,i,j,k) #else -void BMKBRP(struct BitMap *a,WORD b, WORD c,struct RastPort *d,WORD e,WORD f,WORD g,WORD h,UBYTE i,APTR j) -{BltMaskBitMapRastPort(a,b,c,d,e,f,g,h,i,j);} +void +BMKBRP(struct BitMap *a, WORD b, WORD c, struct RastPort *d, WORD e, WORD f, + WORD g, WORD h, UBYTE i, APTR j) +{ + BltMaskBitMapRastPort(a, b, c, d, e, f, g, h, i, j); +} -void BBRP(struct BitMap *a,WORD b, WORD c,struct RastPort *d,WORD e,WORD f,WORD g,WORD h,UBYTE i) -{BltBitMapRastPort(a,b,c,d,e,f,g,h,i);} +void +BBRP(struct BitMap *a, WORD b, WORD c, struct RastPort *d, WORD e, WORD f, + WORD g, WORD h, UBYTE i) +{ + BltBitMapRastPort(a, b, c, d, e, f, g, h, i); +} -void BBB(struct BitMap *a,WORD b, WORD c,struct BitMap *d,WORD e,WORD f,WORD g,WORD h,UBYTE i,UBYTE j,UWORD *k) -{BltBitMap(a,b,c,d,e,f,g,h,i,j,k);} +void +BBB(struct BitMap *a, WORD b, WORD c, struct BitMap *d, WORD e, WORD f, + WORD g, WORD h, UBYTE i, UBYTE j, UWORD * k) +{ + BltBitMap(a, b, c, d, e, f, g, h, i, j, k); +} #endif -int CGX_SetHWColorKey(_THIS,SDL_Surface *surface, Uint32 key) +int +CGX_SetHWColorKey(_THIS, SDL_Surface * surface, Uint32 key) { - if(surface->hwdata) - { - if(surface->hwdata->mask) - SDL_free(surface->hwdata->mask); - - if(surface->hwdata->mask=SDL_malloc(RASSIZE(surface->w,surface->h))) - { - Uint32 pitch,ok=0; - APTR lock; - - SDL_memset(surface->hwdata->mask,255,RASSIZE(surface->w,surface->h)); - - D(bug("Building colorkey mask: color: %ld, size: %ld x %ld, %ld bytes...Bpp:%ld\n",key,surface->w,surface->h,RASSIZE(surface->w,surface->h),surface->format->BytesPerPixel)); - - if(lock=LockBitMapTags(surface->hwdata->bmap,LBMI_BASEADDRESS,(ULONG)&surface->pixels, - LBMI_BYTESPERROW,(ULONG)&pitch,TAG_DONE)) - { - switch(surface->format->BytesPerPixel) - { - case 1: - { - unsigned char k=key; - register int i,j,t; - register unsigned char *dest=surface->hwdata->mask,*map=surface->pixels; - - pitch-=surface->w; - - for(i=0;ih;i++) - { - for(t=128,j=0;jw;j++) - { - if(*map==k) - *dest&=~t; - - t>>=1; - - if(t==0) - { - dest++; - t=128; - } - map++; - } - map+=pitch; - } - } - break; - case 2: - { - Uint16 k=key,*mapw; - register int i,j,t; - register unsigned char *dest=surface->hwdata->mask,*map=surface->pixels; - - for(i=surface->h;i;--i) - { - mapw=(Uint16 *)map; - - for(t=128,j=surface->w;j;--j) - { - if(*mapw==k) - *dest&=~t; - - t>>=1; - - if(t==0) - { - dest++; - t=128; - } - mapw++; - } - map+=pitch; - } - } - break; - case 4: - { - Uint32 *mapl; - register int i,j,t; - register unsigned char *dest=surface->hwdata->mask,*map=surface->pixels; - - for(i=surface->h;i;--i) - { - mapl=(Uint32 *)map; - - for(t=128,j=surface->w;j;--j) - { - if(*mapl==key) - *dest&=~t; - - t>>=1; - - if(t==0) - { - dest++; - t=128; - } - mapl++; - } - map+=pitch; - } - - } - break; - default: - D(bug("Pixel mode non supported for color key...")); - SDL_free(surface->hwdata->mask); - surface->hwdata->mask=NULL; - ok=-1; - } - UnLockBitMap(lock); - D(bug("...Colorkey built!\n")); - return ok; - } - } - } - D(bug("HW colorkey not supported for this depth\n")); - - return -1; + if (surface->hwdata) { + if (surface->hwdata->mask) + SDL_free(surface->hwdata->mask); + + if (surface->hwdata->mask = + SDL_malloc(RASSIZE(surface->w, surface->h))) { + Uint32 pitch, ok = 0; + APTR lock; + + SDL_memset(surface->hwdata->mask, 255, + RASSIZE(surface->w, surface->h)); + + D(bug + ("Building colorkey mask: color: %ld, size: %ld x %ld, %ld bytes...Bpp:%ld\n", + key, surface->w, surface->h, RASSIZE(surface->w, + surface->h), + surface->format->BytesPerPixel)); + + if (lock = + LockBitMapTags(surface->hwdata->bmap, LBMI_BASEADDRESS, + (ULONG) & surface->pixels, + LBMI_BYTESPERROW, (ULONG) & pitch, TAG_DONE)) { + switch (surface->format->BytesPerPixel) { + case 1: + { + unsigned char k = key; + register int i, j, t; + register unsigned char *dest = + surface->hwdata->mask, *map = surface->pixels; + + pitch -= surface->w; + + for (i = 0; i < surface->h; i++) { + for (t = 128, j = 0; j < surface->w; j++) { + if (*map == k) + *dest &= ~t; + + t >>= 1; + + if (t == 0) { + dest++; + t = 128; + } + map++; + } + map += pitch; + } + } + break; + case 2: + { + Uint16 k = key, *mapw; + register int i, j, t; + register unsigned char *dest = + surface->hwdata->mask, *map = surface->pixels; + + for (i = surface->h; i; --i) { + mapw = (Uint16 *) map; + + for (t = 128, j = surface->w; j; --j) { + if (*mapw == k) + *dest &= ~t; + + t >>= 1; + + if (t == 0) { + dest++; + t = 128; + } + mapw++; + } + map += pitch; + } + } + break; + case 4: + { + Uint32 *mapl; + register int i, j, t; + register unsigned char *dest = + surface->hwdata->mask, *map = surface->pixels; + + for (i = surface->h; i; --i) { + mapl = (Uint32 *) map; + + for (t = 128, j = surface->w; j; --j) { + if (*mapl == key) + *dest &= ~t; + + t >>= 1; + + if (t == 0) { + dest++; + t = 128; + } + mapl++; + } + map += pitch; + } + + } + break; + default: + D(bug("Pixel mode non supported for color key...")); + SDL_free(surface->hwdata->mask); + surface->hwdata->mask = NULL; + ok = -1; + } + UnLockBitMap(lock); + D(bug("...Colorkey built!\n")); + return ok; + } + } + } + D(bug("HW colorkey not supported for this depth\n")); + + return -1; } -int CGX_CheckHWBlit(_THIS,SDL_Surface *src,SDL_Surface *dst) +int +CGX_CheckHWBlit(_THIS, SDL_Surface * src, SDL_Surface * dst) { // Doesn't support yet alpha blitting - if(src->hwdata&& !(src->flags & (SDL_SRCALPHA))) - { - D(bug("CheckHW blit... OK!\n")); + if (src->hwdata && !(src->flags & (SDL_SRCALPHA))) { + D(bug("CheckHW blit... OK!\n")); - if ( (src->flags & SDL_SRCCOLORKEY) == SDL_SRCCOLORKEY ) { - if ( CGX_SetHWColorKey(this, src, src->format->colorkey) < 0 ) { - src->flags &= ~SDL_HWACCEL; - return -1; - } - } + if ((src->flags & SDL_SRCCOLORKEY) == SDL_SRCCOLORKEY) { + if (CGX_SetHWColorKey(this, src, src->format->colorkey) < 0) { + src->flags &= ~SDL_HWACCEL; + return -1; + } + } - src->flags|=SDL_HWACCEL; - src->map->hw_blit = CGX_HWAccelBlit; - return 1; - } - else - src->flags &= ~SDL_HWACCEL; + src->flags |= SDL_HWACCEL; + src->map->hw_blit = CGX_HWAccelBlit; + return 1; + } else + src->flags &= ~SDL_HWACCEL; - D(bug("CheckHW blit... NO!\n")); + D(bug("CheckHW blit... NO!\n")); - return 0; + return 0; } -static int temprp_init=0; +static int temprp_init = 0; static struct RastPort temprp; -static int CGX_HWAccelBlit(SDL_Surface *src, SDL_Rect *srcrect, - SDL_Surface *dst, SDL_Rect *dstrect) +static int +CGX_HWAccelBlit(SDL_Surface * src, SDL_Rect * srcrect, + SDL_Surface * dst, SDL_Rect * dstrect) { - struct SDL_VideoDevice *this=src->hwdata->videodata; - -// D(bug("Accel blit!\n")); - - if(src->flags&SDL_SRCCOLORKEY && src->hwdata->mask) - { - if(dst==SDL_VideoSurface) - { - BMKBRP(src->hwdata->bmap,srcrect->x,srcrect->y, - SDL_RastPort,dstrect->x+SDL_Window->BorderLeft,dstrect->y+SDL_Window->BorderTop, - srcrect->w,srcrect->h,0xc0,src->hwdata->mask); - } - else if(dst->hwdata) - { - if(!temprp_init) - { - InitRastPort(&temprp); - temprp_init=1; - } - temprp.BitMap=(struct BitMap *)dst->hwdata->bmap; - - BMKBRP(src->hwdata->bmap,srcrect->x,srcrect->y, - &temprp,dstrect->x,dstrect->y, - srcrect->w,srcrect->h,0xc0,src->hwdata->mask); - - } - } - else if(dst==SDL_VideoSurface) - { - BBRP(src->hwdata->bmap,srcrect->x,srcrect->y,SDL_RastPort,dstrect->x+SDL_Window->BorderLeft,dstrect->y+SDL_Window->BorderTop,srcrect->w,srcrect->h,0xc0); - } - else if(dst->hwdata) - BBB(src->hwdata->bmap,srcrect->x,srcrect->y,dst->hwdata->bmap,dstrect->x,dstrect->y,srcrect->w,srcrect->h,0xc0,0xff,NULL); - - return 0; + struct SDL_VideoDevice *this = src->hwdata->videodata; + +// D(bug("Accel blit!\n")); + + if (src->flags & SDL_SRCCOLORKEY && src->hwdata->mask) { + if (dst == SDL_VideoSurface) { + BMKBRP(src->hwdata->bmap, srcrect->x, srcrect->y, + SDL_RastPort, dstrect->x + SDL_Window->BorderLeft, + dstrect->y + SDL_Window->BorderTop, srcrect->w, + srcrect->h, 0xc0, src->hwdata->mask); + } else if (dst->hwdata) { + if (!temprp_init) { + InitRastPort(&temprp); + temprp_init = 1; + } + temprp.BitMap = (struct BitMap *) dst->hwdata->bmap; + + BMKBRP(src->hwdata->bmap, srcrect->x, srcrect->y, + &temprp, dstrect->x, dstrect->y, + srcrect->w, srcrect->h, 0xc0, src->hwdata->mask); + + } + } else if (dst == SDL_VideoSurface) { + BBRP(src->hwdata->bmap, srcrect->x, srcrect->y, SDL_RastPort, + dstrect->x + SDL_Window->BorderLeft, + dstrect->y + SDL_Window->BorderTop, srcrect->w, srcrect->h, + 0xc0); + } else if (dst->hwdata) + BBB(src->hwdata->bmap, srcrect->x, srcrect->y, dst->hwdata->bmap, + dstrect->x, dstrect->y, srcrect->w, srcrect->h, 0xc0, 0xff, NULL); + + return 0; } -int CGX_FillHWRect(_THIS,SDL_Surface *dst,SDL_Rect *dstrect,Uint32 color) +int +CGX_FillHWRect(_THIS, SDL_Surface * dst, SDL_Rect * dstrect, Uint32 color) { - if(dst==SDL_VideoSurface) - { - FillPixelArray(SDL_RastPort,dstrect->x+SDL_Window->BorderLeft,dstrect->y+SDL_Window->BorderTop,dstrect->w,dstrect->h,color); - } - else if(dst->hwdata) - { - if(!temprp_init) - { - InitRastPort(&temprp); - temprp_init=1; - } - - temprp.BitMap=(struct BitMap *)dst->hwdata->bmap; - - FillPixelArray(&temprp,dstrect->x,dstrect->y,dstrect->w,dstrect->h,color); - } - return 0; + if (dst == SDL_VideoSurface) { + FillPixelArray(SDL_RastPort, dstrect->x + SDL_Window->BorderLeft, + dstrect->y + SDL_Window->BorderTop, dstrect->w, + dstrect->h, color); + } else if (dst->hwdata) { + if (!temprp_init) { + InitRastPort(&temprp); + temprp_init = 1; + } + + temprp.BitMap = (struct BitMap *) dst->hwdata->bmap; + + FillPixelArray(&temprp, dstrect->x, dstrect->y, dstrect->w, + dstrect->h, color); + } + return 0; } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/cybergfx/SDL_cgxgl.c b/src/video/cybergfx/SDL_cgxgl.c index e19614b9d..d892ec40e 100644 --- a/src/video/cybergfx/SDL_cgxgl.c +++ b/src/video/cybergfx/SDL_cgxgl.c @@ -27,186 +27,201 @@ #include "SDL_cgxvideo.h" #if SDL_VIDEO_OPENGL -AmigaMesaContext glcont=NULL; +AmigaMesaContext glcont = NULL; #endif /* Init OpenGL */ -int CGX_GL_Init(_THIS) +int +CGX_GL_Init(_THIS) { #if SDL_VIDEO_OPENGL - int i = 0; - struct TagItem attributes [ 14 ]; /* 14 should be more than enough :) */ - struct Window *win = (struct Window *)SDL_Window; - - // default config. Always used... - attributes[i].ti_Tag = AMA_Window; attributes[i++].ti_Data = (unsigned long)win; - attributes[i].ti_Tag = AMA_Left; attributes[i++].ti_Data = 0; - attributes[i].ti_Tag = AMA_Bottom; attributes[i++].ti_Data = 0; - attributes[i].ti_Tag = AMA_Width; attributes[i++].ti_Data = win->Width-win->BorderLeft-win->BorderRight; - attributes[i].ti_Tag = AMA_Height; attributes[i++].ti_Data = win->Height-win->BorderBottom-win->BorderTop; - attributes[i].ti_Tag = AMA_DirectRender; attributes[i++].ti_Data = GL_TRUE; - - // double buffer ? - attributes[i].ti_Tag = AMA_DoubleBuf; - if ( this->gl_config.double_buffer ) { - attributes[i++].ti_Data = GL_TRUE; - } - else { - attributes[i++].ti_Data = GL_FALSE; - } - // RGB(A) Mode ? - attributes[i].ti_Tag = AMA_RGBMode; - if ( this->gl_config.red_size != 0 && - this->gl_config.blue_size != 0 && - this->gl_config.green_size != 0 ) { - attributes[i++].ti_Data = GL_TRUE; - } - else { - attributes[i++].ti_Data = GL_FALSE; - } - // no depth buffer ? - if ( this->gl_config.depth_size == 0 ) { - attributes[i].ti_Tag = AMA_NoDepth; - attributes[i++].ti_Data = GL_TRUE; - } - // no stencil buffer ? - if ( this->gl_config.stencil_size == 0 ) { - attributes[i].ti_Tag = AMA_NoStencil; - attributes[i++].ti_Data = GL_TRUE; - } - // no accum buffer ? - if ( this->gl_config.accum_red_size != 0 && - this->gl_config.accum_blue_size != 0 && - this->gl_config.accum_green_size != 0 ) { - attributes[i].ti_Tag = AMA_NoAccum; - attributes[i++].ti_Data = GL_TRUE; - } - // done... - attributes[i].ti_Tag = TAG_DONE; - - glcont = AmigaMesaCreateContext(attributes); - if ( glcont == NULL ) { - SDL_SetError("Couldn't create OpenGL context"); - return(-1); - } - this->gl_data->gl_active = 1; - this->gl_config.driver_loaded = 1; - - return(0); + int i = 0; + struct TagItem attributes[14]; /* 14 should be more than enough :) */ + struct Window *win = (struct Window *) SDL_Window; + + // default config. Always used... + attributes[i].ti_Tag = AMA_Window; + attributes[i++].ti_Data = (unsigned long) win; + attributes[i].ti_Tag = AMA_Left; + attributes[i++].ti_Data = 0; + attributes[i].ti_Tag = AMA_Bottom; + attributes[i++].ti_Data = 0; + attributes[i].ti_Tag = AMA_Width; + attributes[i++].ti_Data = win->Width - win->BorderLeft - win->BorderRight; + attributes[i].ti_Tag = AMA_Height; + attributes[i++].ti_Data = + win->Height - win->BorderBottom - win->BorderTop; + attributes[i].ti_Tag = AMA_DirectRender; + attributes[i++].ti_Data = GL_TRUE; + + // double buffer ? + attributes[i].ti_Tag = AMA_DoubleBuf; + if (this->gl_config.double_buffer) { + attributes[i++].ti_Data = GL_TRUE; + } else { + attributes[i++].ti_Data = GL_FALSE; + } + // RGB(A) Mode ? + attributes[i].ti_Tag = AMA_RGBMode; + if (this->gl_config.red_size != 0 && + this->gl_config.blue_size != 0 && this->gl_config.green_size != 0) { + attributes[i++].ti_Data = GL_TRUE; + } else { + attributes[i++].ti_Data = GL_FALSE; + } + // no depth buffer ? + if (this->gl_config.depth_size == 0) { + attributes[i].ti_Tag = AMA_NoDepth; + attributes[i++].ti_Data = GL_TRUE; + } + // no stencil buffer ? + if (this->gl_config.stencil_size == 0) { + attributes[i].ti_Tag = AMA_NoStencil; + attributes[i++].ti_Data = GL_TRUE; + } + // no accum buffer ? + if (this->gl_config.accum_red_size != 0 && + this->gl_config.accum_blue_size != 0 && + this->gl_config.accum_green_size != 0) { + attributes[i].ti_Tag = AMA_NoAccum; + attributes[i++].ti_Data = GL_TRUE; + } + // done... + attributes[i].ti_Tag = TAG_DONE; + + glcont = AmigaMesaCreateContext(attributes); + if (glcont == NULL) { + SDL_SetError("Couldn't create OpenGL context"); + return (-1); + } + this->gl_data->gl_active = 1; + this->gl_config.driver_loaded = 1; + + return (0); #else - SDL_SetError("OpenGL support not configured"); - return(-1); + SDL_SetError("OpenGL support not configured"); + return (-1); #endif } /* Quit OpenGL */ -void CGX_GL_Quit(_THIS) +void +CGX_GL_Quit(_THIS) { #if SDL_VIDEO_OPENGL - if ( glcont != NULL ) { - AmigaMesaDestroyContext(glcont); - glcont = NULL; - this->gl_data->gl_active = 0; - this->gl_config.driver_loaded = 0; - } + if (glcont != NULL) { + AmigaMesaDestroyContext(glcont); + glcont = NULL; + this->gl_data->gl_active = 0; + this->gl_config.driver_loaded = 0; + } #endif } /* Attach context to another window */ -int CGX_GL_Update(_THIS) +int +CGX_GL_Update(_THIS) { #if SDL_VIDEO_OPENGL - struct TagItem tags[2]; - struct Window *win = (struct Window*)SDL_Window; - if(glcont == NULL) { - return -1; //should never happen - } - tags[0].ti_Tag = AMA_Window; - tags[0].ti_Data = (unsigned long)win; - tags[1].ti_Tag = TAG_DONE; - AmigaMesaSetRast(glcont, tags); - - return 0; + struct TagItem tags[2]; + struct Window *win = (struct Window *) SDL_Window; + if (glcont == NULL) { + return -1; //should never happen + } + tags[0].ti_Tag = AMA_Window; + tags[0].ti_Data = (unsigned long) win; + tags[1].ti_Tag = TAG_DONE; + AmigaMesaSetRast(glcont, tags); + + return 0; #else - SDL_SetError("OpenGL support not configured"); - return -1; + SDL_SetError("OpenGL support not configured"); + return -1; #endif } #if SDL_VIDEO_OPENGL /* Make the current context active */ -int CGX_GL_MakeCurrent(_THIS) +int +CGX_GL_MakeCurrent(_THIS) { - if(glcont == NULL) - return -1; + if (glcont == NULL) + return -1; - AmigaMesaMakeCurrent(glcont, glcont->buffer); - return 0; + AmigaMesaMakeCurrent(glcont, glcont->buffer); + return 0; } -void CGX_GL_SwapBuffers(_THIS) +void +CGX_GL_SwapBuffers(_THIS) { - AmigaMesaSwapBuffers(glcont); + AmigaMesaSwapBuffers(glcont); } -int CGX_GL_GetAttribute(_THIS, SDL_GLattr attrib, int* value) { - GLenum mesa_attrib; - - switch(attrib) { - case SDL_GL_RED_SIZE: - mesa_attrib = GL_RED_BITS; - break; - case SDL_GL_GREEN_SIZE: - mesa_attrib = GL_GREEN_BITS; - break; - case SDL_GL_BLUE_SIZE: - mesa_attrib = GL_BLUE_BITS; - break; - case SDL_GL_ALPHA_SIZE: - mesa_attrib = GL_ALPHA_BITS; - break; - case SDL_GL_DOUBLEBUFFER: - mesa_attrib = GL_DOUBLEBUFFER; - break; - case SDL_GL_DEPTH_SIZE: - mesa_attrib = GL_DEPTH_BITS; - break; - case SDL_GL_STENCIL_SIZE: - mesa_attrib = GL_STENCIL_BITS; - break; - case SDL_GL_ACCUM_RED_SIZE: - mesa_attrib = GL_ACCUM_RED_BITS; - break; - case SDL_GL_ACCUM_GREEN_SIZE: - mesa_attrib = GL_ACCUM_GREEN_BITS; - break; - case SDL_GL_ACCUM_BLUE_SIZE: - mesa_attrib = GL_ACCUM_BLUE_BITS; - break; - case SDL_GL_ACCUM_ALPHA_SIZE: - mesa_attrib = GL_ACCUM_ALPHA_BITS; - break; - default : - return -1; - } - - AmigaMesaGetConfig(glcont->visual, mesa_attrib, value); - return 0; +int +CGX_GL_GetAttribute(_THIS, SDL_GLattr attrib, int *value) +{ + GLenum mesa_attrib; + + switch (attrib) { + case SDL_GL_RED_SIZE: + mesa_attrib = GL_RED_BITS; + break; + case SDL_GL_GREEN_SIZE: + mesa_attrib = GL_GREEN_BITS; + break; + case SDL_GL_BLUE_SIZE: + mesa_attrib = GL_BLUE_BITS; + break; + case SDL_GL_ALPHA_SIZE: + mesa_attrib = GL_ALPHA_BITS; + break; + case SDL_GL_DOUBLEBUFFER: + mesa_attrib = GL_DOUBLEBUFFER; + break; + case SDL_GL_DEPTH_SIZE: + mesa_attrib = GL_DEPTH_BITS; + break; + case SDL_GL_STENCIL_SIZE: + mesa_attrib = GL_STENCIL_BITS; + break; + case SDL_GL_ACCUM_RED_SIZE: + mesa_attrib = GL_ACCUM_RED_BITS; + break; + case SDL_GL_ACCUM_GREEN_SIZE: + mesa_attrib = GL_ACCUM_GREEN_BITS; + break; + case SDL_GL_ACCUM_BLUE_SIZE: + mesa_attrib = GL_ACCUM_BLUE_BITS; + break; + case SDL_GL_ACCUM_ALPHA_SIZE: + mesa_attrib = GL_ACCUM_ALPHA_BITS; + break; + default: + return -1; + } + + AmigaMesaGetConfig(glcont->visual, mesa_attrib, value); + return 0; } -void *CGX_GL_GetProcAddress(_THIS, const char *proc) { - void *func = NULL; - func = AmiGetGLProc(proc); - return func; +void * +CGX_GL_GetProcAddress(_THIS, const char *proc) +{ + void *func = NULL; + func = AmiGetGLProc(proc); + return func; } -int CGX_GL_LoadLibrary(_THIS, const char *path) { - /* Library is always open */ - this->gl_config.driver_loaded = 1; +int +CGX_GL_LoadLibrary(_THIS, const char *path) +{ + /* Library is always open */ + this->gl_config.driver_loaded = 1; - return 0; + return 0; } #endif /* SDL_VIDEO_OPENGL */ - +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/cybergfx/SDL_cgxgl_c.h b/src/video/cybergfx/SDL_cgxgl_c.h index 4c04f59a5..2130d90cb 100644 --- a/src/video/cybergfx/SDL_cgxgl_c.h +++ b/src/video/cybergfx/SDL_cgxgl_c.h @@ -32,8 +32,9 @@ extern void *AmiGetGLProc(const char *proc); #endif /* SDL_VIDEO_OPENGL */ -struct SDL_PrivateGLData { - int gl_active; +struct SDL_PrivateGLData +{ + int gl_active; }; /* OpenGL functions */ @@ -42,10 +43,11 @@ extern void CGX_GL_Quit(_THIS); extern int CGX_GL_Update(_THIS); #if SDL_VIDEO_OPENGL extern int CGX_GL_MakeCurrent(_THIS); -extern int CGX_GL_GetAttribute(_THIS, SDL_GLattr attrib, int* value); +extern int CGX_GL_GetAttribute(_THIS, SDL_GLattr attrib, int *value); extern void CGX_GL_SwapBuffers(_THIS); extern void *CGX_GL_GetProcAddress(_THIS, const char *proc); extern int CGX_GL_LoadLibrary(_THIS, const char *path); #endif #undef _THIS +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/cybergfx/SDL_cgximage.c b/src/video/cybergfx/SDL_cgximage.c index 3e8938efe..95bd61c06 100644 --- a/src/video/cybergfx/SDL_cgximage.c +++ b/src/video/cybergfx/SDL_cgximage.c @@ -30,335 +30,358 @@ #ifdef USE_CGX_WRITELUTPIXEL #if defined(__SASC) || defined(__PPC__) - #define WLUT WriteLUTPixelArray +#define WLUT WriteLUTPixelArray #else -void WLUT(APTR a,UWORD b,UWORD c,UWORD d,struct RastPort *e,APTR f,UWORD g,UWORD h,UWORD i,UWORD l,UBYTE m) -{ WriteLUTPixelArray(a,b,c,d,e,f,g,h,i,l,m); } +void +WLUT(APTR a, UWORD b, UWORD c, UWORD d, struct RastPort *e, APTR f, UWORD g, + UWORD h, UWORD i, UWORD l, UBYTE m) +{ + WriteLUTPixelArray(a, b, c, d, e, f, g, h, i, l, m); +} #endif #endif /* Various screen update functions available */ -static void CGX_NormalUpdate(_THIS, int numrects, SDL_Rect *rects); -static void CGX_FakeUpdate(_THIS, int numrects, SDL_Rect *rects); +static void CGX_NormalUpdate(_THIS, int numrects, SDL_Rect * rects); +static void CGX_FakeUpdate(_THIS, int numrects, SDL_Rect * rects); -BOOL SafeDisp=TRUE,SafeChange=TRUE; -struct MsgPort *safeport=NULL,*dispport=NULL; -ULONG safe_sigbit,disp_sigbit; -int use_picasso96=1; +BOOL SafeDisp = TRUE, SafeChange = TRUE; +struct MsgPort *safeport = NULL, *dispport = NULL; +ULONG safe_sigbit, disp_sigbit; +int use_picasso96 = 1; -int CGX_SetupImage(_THIS, SDL_Surface *screen) +int +CGX_SetupImage(_THIS, SDL_Surface * screen) { - SDL_Ximage=NULL; - - if(screen->flags&SDL_HWSURFACE) { - ULONG pitch; - - if(!screen->hwdata) { - if(!(screen->hwdata=SDL_malloc(sizeof(struct private_hwdata)))) - return -1; - - D(bug("Creating system accel struct\n")); - } - screen->hwdata->lock=NULL; - screen->hwdata->allocated=0; - screen->hwdata->mask=NULL; - screen->hwdata->bmap=SDL_RastPort->BitMap; - screen->hwdata->videodata=this; - - if(!(screen->hwdata->lock=LockBitMapTags(screen->hwdata->bmap, - LBMI_BASEADDRESS,(ULONG)&screen->pixels, - LBMI_BYTESPERROW,(ULONG)&pitch,TAG_DONE))) { - SDL_free(screen->hwdata); - screen->hwdata=NULL; - return -1; - } - else { - UnLockBitMap(screen->hwdata->lock); - screen->hwdata->lock=NULL; - } - - screen->pitch=pitch; - - this->UpdateRects = CGX_FakeUpdate; - - D(bug("Accel video image configured (%lx, pitch %ld).\n",screen->pixels,screen->pitch)); - return 0; - } - - screen->pixels = SDL_malloc(screen->h*screen->pitch); - - if ( screen->pixels == NULL ) { - SDL_OutOfMemory(); - return(-1); - } - - SDL_Ximage=screen->pixels; - - if ( SDL_Ximage == NULL ) { - SDL_SetError("Couldn't create XImage"); - return(-1); - } - - this->UpdateRects = CGX_NormalUpdate; - - return(0); + SDL_Ximage = NULL; + + if (screen->flags & SDL_HWSURFACE) { + ULONG pitch; + + if (!screen->hwdata) { + if (!(screen->hwdata = SDL_malloc(sizeof(struct private_hwdata)))) + return -1; + + D(bug("Creating system accel struct\n")); + } + screen->hwdata->lock = NULL; + screen->hwdata->allocated = 0; + screen->hwdata->mask = NULL; + screen->hwdata->bmap = SDL_RastPort->BitMap; + screen->hwdata->videodata = this; + + if (!(screen->hwdata->lock = LockBitMapTags(screen->hwdata->bmap, + LBMI_BASEADDRESS, + (ULONG) & screen-> + pixels, + LBMI_BYTESPERROW, + (ULONG) & pitch, + TAG_DONE))) { + SDL_free(screen->hwdata); + screen->hwdata = NULL; + return -1; + } else { + UnLockBitMap(screen->hwdata->lock); + screen->hwdata->lock = NULL; + } + + screen->pitch = pitch; + + this->UpdateRects = CGX_FakeUpdate; + + D(bug + ("Accel video image configured (%lx, pitch %ld).\n", + screen->pixels, screen->pitch)); + return 0; + } + + screen->pixels = SDL_malloc(screen->h * screen->pitch); + + if (screen->pixels == NULL) { + SDL_OutOfMemory(); + return (-1); + } + + SDL_Ximage = screen->pixels; + + if (SDL_Ximage == NULL) { + SDL_SetError("Couldn't create XImage"); + return (-1); + } + + this->UpdateRects = CGX_NormalUpdate; + + return (0); } -void CGX_DestroyImage(_THIS, SDL_Surface *screen) +void +CGX_DestroyImage(_THIS, SDL_Surface * screen) { - if ( SDL_Ximage ) { - SDL_free(SDL_Ximage); - SDL_Ximage = NULL; - } - if ( screen ) { - screen->pixels = NULL; - - if(screen->hwdata) { - SDL_free(screen->hwdata); - screen->hwdata=NULL; - } - } + if (SDL_Ximage) { + SDL_free(SDL_Ximage); + SDL_Ximage = NULL; + } + if (screen) { + screen->pixels = NULL; + + if (screen->hwdata) { + SDL_free(screen->hwdata); + screen->hwdata = NULL; + } + } } /* This is a hack to see whether this system has more than 1 CPU */ -static int num_CPU(void) +static int +num_CPU(void) { - return 1; + return 1; } -int CGX_ResizeImage(_THIS, SDL_Surface *screen, Uint32 flags) +int +CGX_ResizeImage(_THIS, SDL_Surface * screen, Uint32 flags) { - int retval; - - D(bug("Calling ResizeImage()\n")); - - CGX_DestroyImage(this, screen); - - if ( flags & SDL_OPENGL ) { /* No image when using GL */ - retval = 0; - } else { - retval = CGX_SetupImage(this, screen); - /* We support asynchronous blitting on the display */ - if ( flags & SDL_ASYNCBLIT ) { - if ( num_CPU() > 1 ) { - screen->flags |= SDL_ASYNCBLIT; - } - } - } - return(retval); + int retval; + + D(bug("Calling ResizeImage()\n")); + + CGX_DestroyImage(this, screen); + + if (flags & SDL_INTERNALOPENGL) { /* No image when using GL */ + retval = 0; + } else { + retval = CGX_SetupImage(this, screen); + /* We support asynchronous blitting on the display */ + if (flags & SDL_ASYNCBLIT) { + if (num_CPU() > 1) { + screen->flags |= SDL_ASYNCBLIT; + } + } + } + return (retval); } -int CGX_AllocHWSurface(_THIS, SDL_Surface *surface) +int +CGX_AllocHWSurface(_THIS, SDL_Surface * surface) { - D(bug("Alloc HW surface...%ld x %ld x %ld!\n",surface->w,surface->h,this->hidden->depth)); - - if(surface==SDL_VideoSurface) - { - D(bug("Allocation skipped, it's system one!\n")); - return 0; - } - - if(!surface->hwdata) - { - if(!(surface->hwdata=SDL_malloc(sizeof(struct private_hwdata)))) - return -1; - } - - surface->hwdata->mask=NULL; - surface->hwdata->lock=NULL; - surface->hwdata->videodata=this; - surface->hwdata->allocated=0; - - if(surface->hwdata->bmap=AllocBitMap(surface->w,surface->h,this->hidden->depth,BMF_MINPLANES,SDL_Display->RastPort.BitMap)) - { - surface->hwdata->allocated=1; - surface->flags|=SDL_HWSURFACE; - D(bug("...OK\n")); - return 0; - } - else - { - SDL_free(surface->hwdata); - surface->hwdata=NULL; - } - - return(-1); + D(bug + ("Alloc HW surface...%ld x %ld x %ld!\n", surface->w, surface->h, + this->hidden->depth)); + + if (surface == SDL_VideoSurface) { + D(bug("Allocation skipped, it's system one!\n")); + return 0; + } + + if (!surface->hwdata) { + if (!(surface->hwdata = SDL_malloc(sizeof(struct private_hwdata)))) + return -1; + } + + surface->hwdata->mask = NULL; + surface->hwdata->lock = NULL; + surface->hwdata->videodata = this; + surface->hwdata->allocated = 0; + + if (surface->hwdata->bmap = + AllocBitMap(surface->w, surface->h, this->hidden->depth, + BMF_MINPLANES, SDL_Display->RastPort.BitMap)) { + surface->hwdata->allocated = 1; + surface->flags |= SDL_HWSURFACE; + D(bug("...OK\n")); + return 0; + } else { + SDL_free(surface->hwdata); + surface->hwdata = NULL; + } + + return (-1); } -void CGX_FreeHWSurface(_THIS, SDL_Surface *surface) + +void +CGX_FreeHWSurface(_THIS, SDL_Surface * surface) { - if(surface && surface!=SDL_VideoSurface && surface->hwdata) - { - D(bug("Free hw surface.\n")); - - if(surface->hwdata->mask) - SDL_free(surface->hwdata->mask); - - if(surface->hwdata->bmap&&surface->hwdata->allocated) - FreeBitMap(surface->hwdata->bmap); - - SDL_free(surface->hwdata); - surface->hwdata=NULL; - surface->pixels=NULL; - D(bug("end of free hw surface\n")); - } - return; + if (surface && surface != SDL_VideoSurface && surface->hwdata) { + D(bug("Free hw surface.\n")); + + if (surface->hwdata->mask) + SDL_free(surface->hwdata->mask); + + if (surface->hwdata->bmap && surface->hwdata->allocated) + FreeBitMap(surface->hwdata->bmap); + + SDL_free(surface->hwdata); + surface->hwdata = NULL; + surface->pixels = NULL; + D(bug("end of free hw surface\n")); + } + return; } -int CGX_LockHWSurface(_THIS, SDL_Surface *surface) +int +CGX_LockHWSurface(_THIS, SDL_Surface * surface) { - if (surface->hwdata) - { -// D(bug("Locking a bitmap...\n")); - if(!surface->hwdata->lock) - { - Uint32 pitch; - - if(!(surface->hwdata->lock=LockBitMapTags(surface->hwdata->bmap, - LBMI_BASEADDRESS,(ULONG)&surface->pixels, - LBMI_BYTESPERROW,(ULONG)&pitch,TAG_DONE))) - return -1; + if (surface->hwdata) { +// D(bug("Locking a bitmap...\n")); + if (!surface->hwdata->lock) { + Uint32 pitch; + + if (! + (surface->hwdata->lock = + LockBitMapTags(surface->hwdata->bmap, LBMI_BASEADDRESS, + (ULONG) & surface->pixels, + LBMI_BYTESPERROW, (ULONG) & pitch, TAG_DONE))) + return -1; // surface->pitch e' a 16bit! - surface->pitch=pitch; - - if(!currently_fullscreen&&surface==SDL_VideoSurface) - surface->pixels=((char *)surface->pixels)+(surface->pitch*(SDL_Window->BorderTop+SDL_Window->TopEdge)+ - surface->format->BytesPerPixel*(SDL_Window->BorderLeft+SDL_Window->LeftEdge)); - } - D(else bug("Already locked!!!\n")); - } - return(0); + surface->pitch = pitch; + + if (!currently_fullscreen && surface == SDL_VideoSurface) + surface->pixels = + ((char *) surface->pixels) + + (surface->pitch * + (SDL_Window->BorderTop + SDL_Window->TopEdge) + + surface->format->BytesPerPixel * + (SDL_Window->BorderLeft + SDL_Window->LeftEdge)); + } + D( + else + bug("Already locked!!!\n")); + } + return (0); } -void CGX_UnlockHWSurface(_THIS, SDL_Surface *surface) +void +CGX_UnlockHWSurface(_THIS, SDL_Surface * surface) { - if(surface->hwdata && surface->hwdata->lock) - { - UnLockBitMap(surface->hwdata->lock); - surface->hwdata->lock=NULL; -// surface->pixels=NULL; - } + if (surface->hwdata && surface->hwdata->lock) { + UnLockBitMap(surface->hwdata->lock); + surface->hwdata->lock = NULL; +// surface->pixels=NULL; + } } -int CGX_FlipHWSurface(_THIS, SDL_Surface *surface) +int +CGX_FlipHWSurface(_THIS, SDL_Surface * surface) { - static int current=0; + static int current = 0; - if(this->hidden->dbuffer) - { - if(!SafeChange) - { - Wait(disp_sigbit); + if (this->hidden->dbuffer) { + if (!SafeChange) { + Wait(disp_sigbit); // Non faccio nulla, vuoto solo la porta - while(GetMsg(dispport)!=NULL) - ; - SafeChange=TRUE; - } - - if(ChangeScreenBuffer(SDL_Display,this->hidden->SB[current^1])) - { - surface->hwdata->bmap=SDL_RastPort->BitMap=this->hidden->SB[current]->sb_BitMap; - SafeChange=FALSE; - SafeDisp=FALSE; - current^=1; - } - - if(!SafeDisp) - { - Wait(safe_sigbit); - while(GetMsg(safeport)!=NULL) - ; - SafeDisp=TRUE; - } - - } - return(0); + while (GetMsg(dispport) != NULL); + SafeChange = TRUE; + } + + if (ChangeScreenBuffer(SDL_Display, this->hidden->SB[current ^ 1])) { + surface->hwdata->bmap = SDL_RastPort->BitMap = + this->hidden->SB[current]->sb_BitMap; + SafeChange = FALSE; + SafeDisp = FALSE; + current ^= 1; + } + + if (!SafeDisp) { + Wait(safe_sigbit); + while (GetMsg(safeport) != NULL); + SafeDisp = TRUE; + } + + } + return (0); } /* Byte-swap the pixels in the display image */ -static void CGX_SwapAllPixels(SDL_Surface *screen) +static void +CGX_SwapAllPixels(SDL_Surface * screen) { - int x, y; - - switch (screen->format->BytesPerPixel) { - case 2: { - Uint16 *spot; - for ( y=0; yh; ++y ) { - spot = (Uint16 *) ((Uint8 *)screen->pixels + - y * screen->pitch); - for ( x=0; xw; ++x, ++spot ) { - *spot = SDL_Swap16(*spot); - } - } - } - break; - - case 4: { - Uint32 *spot; - for ( y=0; yh; ++y ) { - spot = (Uint32 *) ((Uint8 *)screen->pixels + - y * screen->pitch); - for ( x=0; xw; ++x, ++spot ) { - *spot = SDL_Swap32(*spot); - } - } - } - break; - - default: - /* should never get here */ - break; - } + int x, y; + + switch (screen->format->BytesPerPixel) { + case 2: + { + Uint16 *spot; + for (y = 0; y < screen->h; ++y) { + spot = (Uint16 *) ((Uint8 *) screen->pixels + + y * screen->pitch); + for (x = 0; x < screen->w; ++x, ++spot) { + *spot = SDL_Swap16(*spot); + } + } + } + break; + + case 4: + { + Uint32 *spot; + for (y = 0; y < screen->h; ++y) { + spot = (Uint32 *) ((Uint8 *) screen->pixels + + y * screen->pitch); + for (x = 0; x < screen->w; ++x, ++spot) { + *spot = SDL_Swap32(*spot); + } + } + } + break; + + default: + /* should never get here */ + break; + } } -static void CGX_SwapPixels(SDL_Surface *screen, int numrects, SDL_Rect *rects) +static void +CGX_SwapPixels(SDL_Surface * screen, int numrects, SDL_Rect * rects) { - int i; - int x, minx, maxx; - int y, miny, maxy; - - switch (screen->format->BytesPerPixel) { - case 2: { - Uint16 *spot; - for ( i=0; ipixels + - y * screen->pitch + minx * 2); - for ( x=minx; xpixels + - y * screen->pitch + minx * 4); - for ( x=minx; xformat->BytesPerPixel) { + case 2: + { + Uint16 *spot; + for (i = 0; i < numrects; ++i) { + minx = rects[i].x; + maxx = rects[i].x + rects[i].w; + miny = rects[i].y; + maxy = rects[i].y + rects[i].h; + for (y = miny; y < maxy; ++y) { + spot = (Uint16 *) ((Uint8 *) screen->pixels + + y * screen->pitch + minx * 2); + for (x = minx; x < maxx; ++x, ++spot) { + *spot = SDL_Swap16(*spot); + } + } + } + } + break; + + case 4: + { + Uint32 *spot; + for (i = 0; i < numrects; ++i) { + minx = rects[i].x; + maxx = rects[i].x + rects[i].w; + miny = rects[i].y; + maxy = rects[i].y + rects[i].h; + for (y = miny; y < maxy; ++y) { + spot = (Uint32 *) ((Uint8 *) screen->pixels + + y * screen->pitch + minx * 4); + for (x = minx; x < maxx; ++x, ++spot) { + *spot = SDL_Swap32(*spot); + } + } + } + } + break; + + default: + /* should never get here */ + break; + } } #ifdef __SASC @@ -366,541 +389,545 @@ static void CGX_SwapPixels(SDL_Surface *screen, int numrects, SDL_Rect *rects) #define USE_WPA WritePixelArray #else -void USE_WPA(char *a,int b,int c,int d, struct RastPort *e,int f,int g, int h, int i, Uint32 l) +void +USE_WPA(char *a, int b, int c, int d, struct RastPort *e, int f, int g, + int h, int i, Uint32 l) { - WritePixelArray(a,b,c,d,e,f,g,h,i,l); + WritePixelArray(a, b, c, d, e, f, g, h, i, l); } #endif -static void CGX_FakeUpdate(_THIS, int numrects, SDL_Rect *rects) +static void +CGX_FakeUpdate(_THIS, int numrects, SDL_Rect * rects) { } -static void CGX_NormalUpdate(_THIS, int numrects, SDL_Rect *rects) +static void +CGX_NormalUpdate(_THIS, int numrects, SDL_Rect * rects) { - int i,format,customroutine=0; + int i, format, customroutine = 0; #ifndef USE_CGX_WRITELUTPIXEL - int bpp; + int bpp; #endif - if(this->hidden->same_format && !use_picasso96) - { - format=RECTFMT_RAW; - } - else switch(this->screen->format->BytesPerPixel) - { - case 4: - format=RECTFMT_RGBA; - break; - case 3: - format=RECTFMT_RGB; - break; - case 2: - customroutine=1; - break; - case 1: -// D(bug("soft depth: 8 hardbpp: %ld\n",this->hidden->depth)); - if(this->hidden->depth>8) - { + if (this->hidden->same_format && !use_picasso96) { + format = RECTFMT_RAW; + } else + switch (this->screen->format->BytesPerPixel) { + case 4: + format = RECTFMT_RGBA; + break; + case 3: + format = RECTFMT_RGB; + break; + case 2: + customroutine = 1; + break; + case 1: +// D(bug("soft depth: 8 hardbpp: %ld\n",this->hidden->depth)); + if (this->hidden->depth > 8) { #ifndef USE_CGX_WRITELUTPIXEL - if(this->hidden->depth>32) - customroutine=4; - else if(this->hidden->depth>16) - { - bpp=this->hidden->BytesPerPixel; // That one is the only one that needs bpp - customroutine=2; // The slow one! - } - else - customroutine=3; + if (this->hidden->depth > 32) + customroutine = 4; + else if (this->hidden->depth > 16) { + bpp = this->hidden->BytesPerPixel; // That one is the only one that needs bpp + customroutine = 2; // The slow one! + } else + customroutine = 3; #else - customroutine=2; + customroutine = 2; #endif - -// format=RECTFMT_LUT8; Vecchia funzione x usare la WritePixelArray. - } - else - customroutine=1; - break; - default: - D(bug("Unable to blit this surface!\n")); - return; - } - - /* Check for endian-swapped X server, swap if necessary (VERY slow!) */ - if ( swap_pixels && - ((this->screen->format->BytesPerPixel%2) == 0) ) { - D(bug("Software Swapping! SLOOOW!\n")); - CGX_SwapPixels(this->screen, numrects, rects); - for ( i=0; iscreen->pixels,rects[i].x, rects[i].y,this->screen->pitch, - SDL_RastPort,SDL_Window->BorderLeft+rects[i].x,SDL_Window->BorderTop+rects[i].y, - rects[i].w,rects[i].h,format); - } - CGX_SwapPixels(this->screen, numrects, rects); - } - else if (customroutine==2) - { + +// format=RECTFMT_LUT8; Vecchia funzione x usare la WritePixelArray. + } else + customroutine = 1; + break; + default: + D(bug("Unable to blit this surface!\n")); + return; + } + + /* Check for endian-swapped X server, swap if necessary (VERY slow!) */ + if (swap_pixels && ((this->screen->format->BytesPerPixel % 2) == 0)) { + D(bug("Software Swapping! SLOOOW!\n")); + CGX_SwapPixels(this->screen, numrects, rects); + for (i = 0; i < numrects; ++i) { + if (!rects[i].w) { /* Clipped? */ + continue; + } + USE_WPA(this->screen->pixels, rects[i].x, rects[i].y, + this->screen->pitch, SDL_RastPort, + SDL_Window->BorderLeft + rects[i].x, + SDL_Window->BorderTop + rects[i].y, rects[i].w, + rects[i].h, format); + } + CGX_SwapPixels(this->screen, numrects, rects); + } else if (customroutine == 2) { #ifdef USE_CGX_WRITELUTPIXEL - for ( i=0; iscreen->pixels,rects[i].x, rects[i].y,this->screen->pitch, - SDL_RastPort,SDL_XPixels,SDL_Window->BorderLeft+rects[i].x,SDL_Window->BorderTop+rects[i].y, - rects[i].w,rects[i].h,CTABFMT_XRGB8); - } + for (i = 0; i < numrects; ++i) { + if (!rects[i].w) { /* Clipped? */ + continue; + } + + WLUT(this->screen->pixels, rects[i].x, rects[i].y, + this->screen->pitch, SDL_RastPort, SDL_XPixels, + SDL_Window->BorderLeft + rects[i].x, + SDL_Window->BorderTop + rects[i].y, rects[i].w, + rects[i].h, CTABFMT_XRGB8); + } #else - unsigned char *bm_address; - Uint32 destpitch; - APTR handle; - - if(handle=LockBitMapTags(SDL_RastPort->BitMap,LBMI_BASEADDRESS,&bm_address, - LBMI_BYTESPERROW,&destpitch,TAG_DONE)) - { - int srcwidth; - unsigned char *destbase; - register int j,k,t; - register unsigned char *mask,*dst; - register unsigned char *src,*dest; + unsigned char *bm_address; + Uint32 destpitch; + APTR handle; + + if (handle = + LockBitMapTags(SDL_RastPort->BitMap, LBMI_BASEADDRESS, + &bm_address, LBMI_BYTESPERROW, &destpitch, + TAG_DONE)) { + int srcwidth; + unsigned char *destbase; + register int j, k, t; + register unsigned char *mask, *dst; + register unsigned char *src, *dest; // Aggiungo il bordo della finestra se sono fullscreen. - if(currently_fullscreen) - destbase=bm_address; - else - destbase=bm_address+(SDL_Window->TopEdge+SDL_Window->BorderTop)*destpitch+(SDL_Window->BorderLeft+SDL_Window->LeftEdge)*this->hidden->BytesPerPixel; - - for ( i=0; ihidden->BytesPerPixel; - dest+=(rects[i].y*destpitch); - src=((char *)(this->screen->pixels))+rects[i].x; - src+=(rects[i].y*this->screen->pitch); - - for(j=rects[i].h;j;--j) - { - dst=dest; + if (currently_fullscreen) + destbase = bm_address; + else + destbase = + bm_address + (SDL_Window->TopEdge + + SDL_Window->BorderTop) * destpitch + + (SDL_Window->BorderLeft + + SDL_Window->LeftEdge) * this->hidden->BytesPerPixel; + + for (i = 0; i < numrects; ++i) { + srcwidth = rects[i].w; + + if (!srcwidth) { /* Clipped? */ + continue; + } + + dest = destbase + rects[i].x * this->hidden->BytesPerPixel; + dest += (rects[i].y * destpitch); + src = ((char *) (this->screen->pixels)) + rects[i].x; + src += (rects[i].y * this->screen->pitch); + + for (j = rects[i].h; j; --j) { + dst = dest; // SLOW routine, used for 8->24 bit mapping - for(k=0;kscreen->pitch; - dest+=destpitch; - } - } - UnLockBitMap(handle); - } - } - else if (customroutine==3) - { - unsigned char *bm_address; - Uint32 destpitch; - APTR handle; - - if(handle=LockBitMapTags(SDL_RastPort->BitMap,LBMI_BASEADDRESS,&bm_address, - LBMI_BYTESPERROW,&destpitch,TAG_DONE)) - { - int srcwidth; - unsigned char *destbase; - register int j,k; - register unsigned char *src,*dest; - register Uint16 *destl,*srcl; - - if(currently_fullscreen) - destbase=bm_address; - else - destbase=bm_address+(SDL_Window->TopEdge+SDL_Window->BorderTop)*destpitch+(SDL_Window->BorderLeft+SDL_Window->LeftEdge)*this->hidden->BytesPerPixel; - - for ( i=0; ihidden->BytesPerPixel; - dest+=(rects[i].y*destpitch); - src=((char *)(this->screen->pixels))+rects[i].x; - src+=(rects[i].y*this->screen->pitch); - + for (k = 0; k < srcwidth; k++) { + mask = (unsigned char *) (&SDL_XPixels[src[k]]); + for (t = 0; t < bpp; t++) { + dst[t] = mask[t]; + } + dst += bpp; + } + src += this->screen->pitch; + dest += destpitch; + } + } + UnLockBitMap(handle); + } + } else if (customroutine == 3) { + unsigned char *bm_address; + Uint32 destpitch; + APTR handle; + + if (handle = + LockBitMapTags(SDL_RastPort->BitMap, LBMI_BASEADDRESS, + &bm_address, LBMI_BYTESPERROW, &destpitch, + TAG_DONE)) { + int srcwidth; + unsigned char *destbase; + register int j, k; + register unsigned char *src, *dest; + register Uint16 *destl, *srcl; + + if (currently_fullscreen) + destbase = bm_address; + else + destbase = + bm_address + (SDL_Window->TopEdge + + SDL_Window->BorderTop) * destpitch + + (SDL_Window->BorderLeft + + SDL_Window->LeftEdge) * this->hidden->BytesPerPixel; + + for (i = 0; i < numrects; ++i) { + srcwidth = rects[i].w; + + if (!srcwidth) { /* Clipped? */ + continue; + } + + dest = destbase + rects[i].x * this->hidden->BytesPerPixel; + dest += (rects[i].y * destpitch); + src = ((char *) (this->screen->pixels)) + rects[i].x; + src += (rects[i].y * this->screen->pitch); + // This is the fast, well not too slow, remapping code for 16bit displays - for(j=rects[i].h;j;--j) - { - destl=(Uint16 *)dest; - - for(k=0;kscreen->pitch; - dest+=destpitch; - } - } - UnLockBitMap(handle); - } - } - else if (customroutine==4) - { - unsigned char *bm_address; - Uint32 destpitch; - APTR handle; - - if(handle=LockBitMapTags(SDL_RastPort->BitMap,LBMI_BASEADDRESS,&bm_address, - LBMI_BYTESPERROW,&destpitch,TAG_DONE)) - { - int srcwidth; - unsigned char *destbase; - register int j,k; - register unsigned char *src,*dest; - register Uint32 *destl,*srcl; - - if(currently_fullscreen) - destbase=bm_address; - else - destbase=bm_address+(SDL_Window->TopEdge+SDL_Window->BorderTop)*destpitch+(SDL_Window->BorderLeft+SDL_Window->LeftEdge)*this->hidden->BytesPerPixel; - - for ( i=0; ihidden->BytesPerPixel; - dest+=(rects[i].y*destpitch); - src=((char *)(this->screen->pixels))+rects[i].x; - src+=(rects[i].y*this->screen->pitch); - + for (j = rects[i].h; j; --j) { + destl = (Uint16 *) dest; + + for (k = 0; k < srcwidth; k++) { + srcl = (Uint16 *) & SDL_XPixels[src[k]]; + *destl = *srcl; + destl++; + } + src += this->screen->pitch; + dest += destpitch; + } + } + UnLockBitMap(handle); + } + } else if (customroutine == 4) { + unsigned char *bm_address; + Uint32 destpitch; + APTR handle; + + if (handle = + LockBitMapTags(SDL_RastPort->BitMap, LBMI_BASEADDRESS, + &bm_address, LBMI_BYTESPERROW, &destpitch, + TAG_DONE)) { + int srcwidth; + unsigned char *destbase; + register int j, k; + register unsigned char *src, *dest; + register Uint32 *destl, *srcl; + + if (currently_fullscreen) + destbase = bm_address; + else + destbase = + bm_address + (SDL_Window->TopEdge + + SDL_Window->BorderTop) * destpitch + + (SDL_Window->BorderLeft + + SDL_Window->LeftEdge) * this->hidden->BytesPerPixel; + + for (i = 0; i < numrects; ++i) { + srcwidth = rects[i].w; + + if (!srcwidth) { /* Clipped? */ + continue; + } + + dest = destbase + rects[i].x * this->hidden->BytesPerPixel; + dest += (rects[i].y * destpitch); + src = ((char *) (this->screen->pixels)) + rects[i].x; + src += (rects[i].y * this->screen->pitch); + // This is the fast, well not too slow, remapping code for 32bit displays - for(j=rects[i].h;j;--j) - { - destl=(Uint32 *)dest; - - for(k=0;kscreen->pitch; - dest+=destpitch; - } - } - UnLockBitMap(handle); - } + for (j = rects[i].h; j; --j) { + destl = (Uint32 *) dest; + + for (k = 0; k < srcwidth; k++) { + srcl = (Uint32 *) & SDL_XPixels[src[k]]; + *destl = *srcl; + destl++; + } + src += this->screen->pitch; + dest += destpitch; + } + } + UnLockBitMap(handle); + } #endif - } - else if(customroutine) - { - unsigned char *bm_address; - Uint32 destpitch; - APTR handle; - -// D(bug("Using customroutine!\n")); - - if(handle=LockBitMapTags(SDL_RastPort->BitMap,LBMI_BASEADDRESS,(ULONG)&bm_address, - LBMI_BYTESPERROW,(ULONG)&destpitch,TAG_DONE)) - { - unsigned char *destbase; - register int j,srcwidth; - register unsigned char *src,*dest; + } else if (customroutine) { + unsigned char *bm_address; + Uint32 destpitch; + APTR handle; + +// D(bug("Using customroutine!\n")); + + if (handle = + LockBitMapTags(SDL_RastPort->BitMap, LBMI_BASEADDRESS, + (ULONG) & bm_address, LBMI_BYTESPERROW, + (ULONG) & destpitch, TAG_DONE)) { + unsigned char *destbase; + register int j, srcwidth; + register unsigned char *src, *dest; // Aggiungo il bordo della finestra se sono fullscreen. - if(currently_fullscreen) - destbase=bm_address; - else - destbase=bm_address+(SDL_Window->TopEdge+SDL_Window->BorderTop)*destpitch+(SDL_Window->BorderLeft+SDL_Window->LeftEdge)*this->screen->format->BytesPerPixel; - - for ( i=0; iscreen->format->BytesPerPixel; - dest+=(rects[i].y*destpitch); - src=((char *)(this->screen->pixels))+rects[i].x*this->screen->format->BytesPerPixel; - src+=(rects[i].y*this->screen->pitch); - - srcwidth*=this->screen->format->BytesPerPixel; - -// D(bug("Rects: %ld,%ld %ld,%ld Src:%lx Dest:%lx\n",rects[i].x,rects[i].y,rects[i].w,rects[i].h,src,dest)); - - for(j=rects[i].h;j;--j) - { - SDL_memcpy(dest,src,srcwidth); - src+=this->screen->pitch; - dest+=destpitch; - } - } - UnLockBitMap(handle); -// D(bug("Rectblit addr: %lx pitch: %ld rects:%ld srcptr: %lx srcpitch: %ld\n",bm_address,destpitch,numrects,this->screen->pixels,this->screen->pitch)); - } - } - else - { - for ( i=0; iscreen->pixels,rects[i].x, rects[i].y,this->screen->pitch, - SDL_RastPort,SDL_Window->BorderLeft+rects[i].x,SDL_Window->BorderTop+rects[i].y, - rects[i].w,rects[i].h,format); - } - } + if (currently_fullscreen) + destbase = bm_address; + else + destbase = + bm_address + (SDL_Window->TopEdge + + SDL_Window->BorderTop) * destpitch + + (SDL_Window->BorderLeft + + SDL_Window->LeftEdge) * + this->screen->format->BytesPerPixel; + + for (i = 0; i < numrects; ++i) { + srcwidth = rects[i].w; + + if (!srcwidth) { /* Clipped? */ + continue; + } + + dest = + destbase + + rects[i].x * this->screen->format->BytesPerPixel; + dest += (rects[i].y * destpitch); + src = + ((char *) (this->screen->pixels)) + + rects[i].x * this->screen->format->BytesPerPixel; + src += (rects[i].y * this->screen->pitch); + + srcwidth *= this->screen->format->BytesPerPixel; + +// D(bug("Rects: %ld,%ld %ld,%ld Src:%lx Dest:%lx\n",rects[i].x,rects[i].y,rects[i].w,rects[i].h,src,dest)); + + for (j = rects[i].h; j; --j) { + SDL_memcpy(dest, src, srcwidth); + src += this->screen->pitch; + dest += destpitch; + } + } + UnLockBitMap(handle); +// D(bug("Rectblit addr: %lx pitch: %ld rects:%ld srcptr: %lx srcpitch: %ld\n",bm_address,destpitch,numrects,this->screen->pixels,this->screen->pitch)); + } + } else { + for (i = 0; i < numrects; ++i) { + if (!rects[i].w) { /* Clipped? */ + continue; + } + USE_WPA(this->screen->pixels, rects[i].x, rects[i].y, + this->screen->pitch, SDL_RastPort, + SDL_Window->BorderLeft + rects[i].x, + SDL_Window->BorderTop + rects[i].y, rects[i].w, + rects[i].h, format); + } + } } -void CGX_RefreshDisplay(_THIS) +void +CGX_RefreshDisplay(_THIS) { - int format,customroutine=0; + int format, customroutine = 0; #ifndef USE_CGX_WRITELUTPIXEL - int bpp; + int bpp; #endif - /* Don't refresh a display that doesn't have an image (like GL) */ - if ( ! SDL_Ximage ) { - return; - } - - if(this->hidden->same_format && !use_picasso96) - { - format=RECTFMT_RAW; - } - else switch(this->screen->format->BytesPerPixel) - { - case 4: - format=RECTFMT_RGBA; - break; - case 3: - format=RECTFMT_RGB; - break; - case 2: - customroutine=1; - break; - case 1: -// D(bug("soft depth: 8 hardbpp: %ld\n",this->hidden->depth)); - if(this->hidden->depth>8) - { + /* Don't refresh a display that doesn't have an image (like GL) */ + if (!SDL_Ximage) { + return; + } + + if (this->hidden->same_format && !use_picasso96) { + format = RECTFMT_RAW; + } else + switch (this->screen->format->BytesPerPixel) { + case 4: + format = RECTFMT_RGBA; + break; + case 3: + format = RECTFMT_RGB; + break; + case 2: + customroutine = 1; + break; + case 1: +// D(bug("soft depth: 8 hardbpp: %ld\n",this->hidden->depth)); + if (this->hidden->depth > 8) { #ifndef USE_CGX_WRITELUTPIXEL - if(this->hidden->depth>32) - customroutine=4; - else if(this->hidden->depth>16) - { - bpp=this->hidden->BytesPerPixel; // That one is the only one that needs bpp - customroutine=2; // The slow one! - } - else - customroutine=3; + if (this->hidden->depth > 32) + customroutine = 4; + else if (this->hidden->depth > 16) { + bpp = this->hidden->BytesPerPixel; // That one is the only one that needs bpp + customroutine = 2; // The slow one! + } else + customroutine = 3; #else - customroutine=2; + customroutine = 2; #endif -// format=RECTFMT_LUT8; - } - else - customroutine=1; - break; - - } - - /* Check for endian-swapped X server, swap if necessary */ - if ( swap_pixels && - ((this->screen->format->BytesPerPixel%2) == 0) ) { - CGX_SwapAllPixels(this->screen); - USE_WPA(this->screen->pixels,0,0,this->screen->pitch, - SDL_RastPort,SDL_Window->BorderLeft,SDL_Window->BorderTop, - this->screen->w,this->screen->h,format); - CGX_SwapAllPixels(this->screen); - } - else if (customroutine==2) - { +// format=RECTFMT_LUT8; + } else + customroutine = 1; + break; + + } + + /* Check for endian-swapped X server, swap if necessary */ + if (swap_pixels && ((this->screen->format->BytesPerPixel % 2) == 0)) { + CGX_SwapAllPixels(this->screen); + USE_WPA(this->screen->pixels, 0, 0, this->screen->pitch, + SDL_RastPort, SDL_Window->BorderLeft, + SDL_Window->BorderTop, this->screen->w, this->screen->h, + format); + CGX_SwapAllPixels(this->screen); + } else if (customroutine == 2) { #ifdef USE_CGX_WRITELUTPIXEL - WLUT(this->screen->pixels,0,0,this->screen->pitch, - SDL_RastPort,SDL_XPixels,SDL_Window->BorderLeft,SDL_Window->BorderTop, - this->screen->w,this->screen->h,CTABFMT_XRGB8); + WLUT(this->screen->pixels, 0, 0, this->screen->pitch, + SDL_RastPort, SDL_XPixels, SDL_Window->BorderLeft, + SDL_Window->BorderTop, this->screen->w, this->screen->h, + CTABFMT_XRGB8); #else - unsigned char *bm_address; - Uint32 destpitch; - APTR handle; - - if(handle=LockBitMapTags(SDL_RastPort->BitMap,LBMI_BASEADDRESS,(ULONG)&bm_address, - LBMI_BYTESPERROW,(ULONG)&destpitch,TAG_DONE)) - { - register int j,k,t; - register unsigned char *mask,*dst; - register unsigned char *src,*dest; + unsigned char *bm_address; + Uint32 destpitch; + APTR handle; + + if (handle = + LockBitMapTags(SDL_RastPort->BitMap, LBMI_BASEADDRESS, + (ULONG) & bm_address, LBMI_BYTESPERROW, + (ULONG) & destpitch, TAG_DONE)) { + register int j, k, t; + register unsigned char *mask, *dst; + register unsigned char *src, *dest; // Aggiungo il bordo della finestra se sono fullscreen. - if(!currently_fullscreen) - dest=bm_address+(SDL_Window->TopEdge+SDL_Window->BorderTop)*destpitch+(SDL_Window->BorderLeft+SDL_Window->LeftEdge)*this->hidden->BytesPerPixel; - else - dest=bm_address; - - src=this->screen->pixels; - - for(j=this->screen->h;j;--j) - { - dst=dest; + if (!currently_fullscreen) + dest = + bm_address + (SDL_Window->TopEdge + + SDL_Window->BorderTop) * destpitch + + (SDL_Window->BorderLeft + + SDL_Window->LeftEdge) * this->hidden->BytesPerPixel; + else + dest = bm_address; + + src = this->screen->pixels; + + for (j = this->screen->h; j; --j) { + dst = dest; // SLOW routine, used for 8->24 bit mapping - for(k=0;kscreen->w;k++) - { - mask=(unsigned char *)(&SDL_XPixels[src[k]]); - for(t=0;tscreen->pitch; - dest+=destpitch; - } - UnLockBitMap(handle); - } - } - else if (customroutine==3) - { - unsigned char *bm_address; - Uint32 destpitch; - APTR handle; - - if(handle=LockBitMapTags(SDL_RastPort->BitMap,LBMI_BASEADDRESS,(ULONG)&bm_address, - LBMI_BYTESPERROW,(ULONG)&destpitch,TAG_DONE)) - { - register int j,k; - register unsigned char *src,*dest; - register Uint16 *destl,*srcl; - - if(!currently_fullscreen) - dest=bm_address+(SDL_Window->TopEdge+SDL_Window->BorderTop)*destpitch+(SDL_Window->BorderLeft+SDL_Window->LeftEdge)*this->hidden->BytesPerPixel; - else - dest=bm_address; - - src=this->screen->pixels; - + for (k = 0; k < this->screen->w; k++) { + mask = (unsigned char *) (&SDL_XPixels[src[k]]); + for (t = 0; t < bpp; t++) { + dst[t] = mask[t]; + } + dst += bpp; + } + src += this->screen->pitch; + dest += destpitch; + } + UnLockBitMap(handle); + } + } else if (customroutine == 3) { + unsigned char *bm_address; + Uint32 destpitch; + APTR handle; + + if (handle = + LockBitMapTags(SDL_RastPort->BitMap, LBMI_BASEADDRESS, + (ULONG) & bm_address, LBMI_BYTESPERROW, + (ULONG) & destpitch, TAG_DONE)) { + register int j, k; + register unsigned char *src, *dest; + register Uint16 *destl, *srcl; + + if (!currently_fullscreen) + dest = + bm_address + (SDL_Window->TopEdge + + SDL_Window->BorderTop) * destpitch + + (SDL_Window->BorderLeft + + SDL_Window->LeftEdge) * this->hidden->BytesPerPixel; + else + dest = bm_address; + + src = this->screen->pixels; + // This is the fast, well not too slow, remapping code for 16bit displays - for(j=this->screen->h;j;--j) - { - destl=(Uint16 *)dest; - - for(k=0;kscreen->w;k++) - { - srcl=(Uint16 *)&SDL_XPixels[src[k]]; - *destl=*srcl; - destl++; - } - src+=this->screen->pitch; - dest+=destpitch; - } - UnLockBitMap(handle); - } - } - else if (customroutine==4) - { - unsigned char *bm_address; - Uint32 destpitch; - APTR handle; - - if(handle=LockBitMapTags(SDL_RastPort->BitMap,LBMI_BASEADDRESS,(ULONG)&bm_address, - LBMI_BYTESPERROW,(ULONG)&destpitch,TAG_DONE)) - { - register int j,k; - register unsigned char *src,*dest; - register Uint32 *destl,*srcl; - - if(!currently_fullscreen) - dest=bm_address+(SDL_Window->TopEdge+SDL_Window->BorderTop)*destpitch+(SDL_Window->BorderLeft+SDL_Window->LeftEdge)*this->hidden->BytesPerPixel; - else - dest=bm_address; - - src=this->screen->pixels; - + for (j = this->screen->h; j; --j) { + destl = (Uint16 *) dest; + + for (k = 0; k < this->screen->w; k++) { + srcl = (Uint16 *) & SDL_XPixels[src[k]]; + *destl = *srcl; + destl++; + } + src += this->screen->pitch; + dest += destpitch; + } + UnLockBitMap(handle); + } + } else if (customroutine == 4) { + unsigned char *bm_address; + Uint32 destpitch; + APTR handle; + + if (handle = + LockBitMapTags(SDL_RastPort->BitMap, LBMI_BASEADDRESS, + (ULONG) & bm_address, LBMI_BYTESPERROW, + (ULONG) & destpitch, TAG_DONE)) { + register int j, k; + register unsigned char *src, *dest; + register Uint32 *destl, *srcl; + + if (!currently_fullscreen) + dest = + bm_address + (SDL_Window->TopEdge + + SDL_Window->BorderTop) * destpitch + + (SDL_Window->BorderLeft + + SDL_Window->LeftEdge) * this->hidden->BytesPerPixel; + else + dest = bm_address; + + src = this->screen->pixels; + // This is the fast, well not too slow, remapping code for 32bit displays - for(j=this->screen->h;j;--j) - { - destl=(Uint32 *)dest; - - for(k=0;kscreen->w;k++) - { - srcl=(Uint32 *)&SDL_XPixels[src[k]]; - *destl=*srcl; - destl++; - } - src+=this->screen->pitch; - dest+=destpitch; - } - UnLockBitMap(handle); - } + for (j = this->screen->h; j; --j) { + destl = (Uint32 *) dest; + + for (k = 0; k < this->screen->w; k++) { + srcl = (Uint32 *) & SDL_XPixels[src[k]]; + *destl = *srcl; + destl++; + } + src += this->screen->pitch; + dest += destpitch; + } + UnLockBitMap(handle); + } #endif - } - else if(customroutine) - { - unsigned char *bm_address; - Uint32 destpitch; - APTR handle; - - if(handle=LockBitMapTags(SDL_RastPort->BitMap, - LBMI_BASEADDRESS,(ULONG)&bm_address, - LBMI_BYTESPERROW,(ULONG)&destpitch,TAG_DONE)) - { - register int j; - register unsigned char *src,*dest; - - if(!currently_fullscreen) - dest=bm_address+(SDL_Window->TopEdge+SDL_Window->BorderTop)*destpitch+(SDL_Window->BorderLeft+SDL_Window->LeftEdge)*this->screen->format->BytesPerPixel; - else - dest=bm_address; - - src=this->screen->pixels; - -// D(bug("addr: %lx pitch: %ld src:%lx srcpitch: %ld\n",dest,destpitch,this->screen->pixels,this->screen->pitch)); - - if(this->screen->pitch==destpitch) - { - SDL_memcpy(dest,src,this->screen->pitch*this->screen->h); - } - else - { - for(j=this->screen->h;j;--j) - { - SDL_memcpy(dest,src,this->screen->pitch); - src+=this->screen->pitch; - dest+=destpitch; - } - } - - UnLockBitMap(handle); - } - } - else - { - USE_WPA(this->screen->pixels,0,0,this->screen->pitch, - SDL_RastPort,SDL_Window->BorderLeft,SDL_Window->BorderTop, - this->screen->w,this->screen->h,format); - } + } else if (customroutine) { + unsigned char *bm_address; + Uint32 destpitch; + APTR handle; + + if (handle = LockBitMapTags(SDL_RastPort->BitMap, + LBMI_BASEADDRESS, (ULONG) & bm_address, + LBMI_BYTESPERROW, (ULONG) & destpitch, + TAG_DONE)) { + register int j; + register unsigned char *src, *dest; + + if (!currently_fullscreen) + dest = + bm_address + (SDL_Window->TopEdge + + SDL_Window->BorderTop) * destpitch + + (SDL_Window->BorderLeft + + SDL_Window->LeftEdge) * + this->screen->format->BytesPerPixel; + else + dest = bm_address; + + src = this->screen->pixels; + +// D(bug("addr: %lx pitch: %ld src:%lx srcpitch: %ld\n",dest,destpitch,this->screen->pixels,this->screen->pitch)); + + if (this->screen->pitch == destpitch) { + SDL_memcpy(dest, src, this->screen->pitch * this->screen->h); + } else { + for (j = this->screen->h; j; --j) { + SDL_memcpy(dest, src, this->screen->pitch); + src += this->screen->pitch; + dest += destpitch; + } + } + + UnLockBitMap(handle); + } + } else { + USE_WPA(this->screen->pixels, 0, 0, this->screen->pitch, + SDL_RastPort, SDL_Window->BorderLeft, + SDL_Window->BorderTop, this->screen->w, this->screen->h, + format); + } } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/cybergfx/SDL_cgximage_c.h b/src/video/cybergfx/SDL_cgximage_c.h index 30dc7a413..739284a68 100644 --- a/src/video/cybergfx/SDL_cgximage_c.h +++ b/src/video/cybergfx/SDL_cgximage_c.h @@ -23,14 +23,15 @@ #include "SDL_cgxvideo.h" -extern int CGX_SetupImage(_THIS, SDL_Surface *screen); -extern void CGX_DestroyImage(_THIS, SDL_Surface *screen); -extern int CGX_ResizeImage(_THIS, SDL_Surface *screen, Uint32 flags); +extern int CGX_SetupImage(_THIS, SDL_Surface * screen); +extern void CGX_DestroyImage(_THIS, SDL_Surface * screen); +extern int CGX_ResizeImage(_THIS, SDL_Surface * screen, Uint32 flags); -extern int CGX_AllocHWSurface(_THIS, SDL_Surface *surface); -extern void CGX_FreeHWSurface(_THIS, SDL_Surface *surface); -extern int CGX_LockHWSurface(_THIS, SDL_Surface *surface); -extern void CGX_UnlockHWSurface(_THIS, SDL_Surface *surface); -extern int CGX_FlipHWSurface(_THIS, SDL_Surface *surface); +extern int CGX_AllocHWSurface(_THIS, SDL_Surface * surface); +extern void CGX_FreeHWSurface(_THIS, SDL_Surface * surface); +extern int CGX_LockHWSurface(_THIS, SDL_Surface * surface); +extern void CGX_UnlockHWSurface(_THIS, SDL_Surface * surface); +extern int CGX_FlipHWSurface(_THIS, SDL_Surface * surface); extern void CGX_RefreshDisplay(_THIS); +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/cybergfx/SDL_cgxmodes.c b/src/video/cybergfx/SDL_cgxmodes.c index fdf7dbd29..5dec18a42 100644 --- a/src/video/cybergfx/SDL_cgxmodes.c +++ b/src/video/cybergfx/SDL_cgxmodes.c @@ -32,149 +32,154 @@ #define CGX_DEBUG -static void set_best_resolution(_THIS, int width, int height) +static void +set_best_resolution(_THIS, int width, int height) { - Uint32 idok; - int depth=8; - - if(SDL_Display) - depth=GetCyberMapAttr(SDL_Display->RastPort.BitMap,CYBRMATTR_DEPTH); - - idok=BestCModeIDTags(CYBRBIDTG_NominalWidth,width, - CYBRBIDTG_NominalHeight,height, - CYBRBIDTG_Depth,depth, - TAG_DONE); - - if(idok!=INVALID_ID) - { - if(SDL_Display) - { - if(currently_fullscreen) - CloseScreen(SDL_Display); - else - UnlockPubScreen(NULL,SDL_Display); - } - SDL_Display=GFX_Display=OpenScreenTags(NULL,SA_Width,width,SA_Height,height, - SA_Depth,depth,SA_DisplayID,idok, - SA_ShowTitle,FALSE, - TAG_DONE); - } + Uint32 idok; + int depth = 8; + + if (SDL_Display) + depth = + GetCyberMapAttr(SDL_Display->RastPort.BitMap, CYBRMATTR_DEPTH); + + idok = BestCModeIDTags(CYBRBIDTG_NominalWidth, width, + CYBRBIDTG_NominalHeight, height, + CYBRBIDTG_Depth, depth, TAG_DONE); + + if (idok != INVALID_ID) { + if (SDL_Display) { + if (currently_fullscreen) + CloseScreen(SDL_Display); + else + UnlockPubScreen(NULL, SDL_Display); + } + SDL_Display = GFX_Display = + OpenScreenTags(NULL, SA_Width, width, SA_Height, height, + SA_Depth, depth, SA_DisplayID, idok, + SA_ShowTitle, FALSE, TAG_DONE); + } } -static void get_real_resolution(_THIS, int* w, int* h) +static void +get_real_resolution(_THIS, int *w, int *h) { - *w = /*SDL_Display->Width*/ SDL_Window->Width-SDL_Window->BorderLeft-SDL_Window->BorderRight; - *h = /*SDL_Display->Height*/ SDL_Window->Height-SDL_Window->BorderBottom-SDL_Window->BorderTop; + *w = /*SDL_Display->Width */ SDL_Window->Width - SDL_Window->BorderLeft - + SDL_Window->BorderRight; + *h = /*SDL_Display->Height */ SDL_Window->Height - + SDL_Window->BorderBottom - SDL_Window->BorderTop; } -static void move_cursor_to(_THIS, int x, int y) +static void +move_cursor_to(_THIS, int x, int y) { /* XWarpPointer(SDL_Display, None, SDL_Root, 0, 0, 0, 0, x, y); */ /* DA FARE! */ } -static void add_visual(_THIS, int depth, int class) +static void +add_visual(_THIS, int depth, int class) { - Uint32 tID; - - tID=BestCModeIDTags(CYBRBIDTG_Depth,depth, - CYBRBIDTG_NominalWidth,640, - CYBRBIDTG_NominalHeight,480, - TAG_DONE); - - if(tID!=INVALID_ID) - { - int n = this->hidden->nvisuals; - - this->hidden->visuals[n].depth = depth; - this->hidden->visuals[n].visual = tID; - this->hidden->visuals[n].bpp = GetCyberIDAttr(CYBRIDATTR_BPPIX,tID); - this->hidden->nvisuals++; - } + Uint32 tID; + + tID = BestCModeIDTags(CYBRBIDTG_Depth, depth, + CYBRBIDTG_NominalWidth, 640, + CYBRBIDTG_NominalHeight, 480, TAG_DONE); + + if (tID != INVALID_ID) { + int n = this->hidden->nvisuals; + + this->hidden->visuals[n].depth = depth; + this->hidden->visuals[n].visual = tID; + this->hidden->visuals[n].bpp = GetCyberIDAttr(CYBRIDATTR_BPPIX, tID); + this->hidden->nvisuals++; + } } #define TrueColor 1 #define PseudoColor 2 -int CGX_GetVideoModes(_THIS) +int +CGX_GetVideoModes(_THIS) { int i; - ULONG nextid; - int nmodes=0; - - SDL_modelist=NULL; - - nextid=NextDisplayInfo(INVALID_ID); - - while(nextid!=INVALID_ID) - { - if(IsCyberModeID(nextid)) - { - DisplayInfoHandle h; - - if(h=FindDisplayInfo(nextid)) - { - struct DimensionInfo info; - - if(GetDisplayInfoData(h,(char *)&info,sizeof(struct DimensionInfo),DTAG_DIMS,NULL)) - { - int ok=0; - - for(i=0;iw == (info.Nominal.MaxX+1) && - SDL_modelist[i]->h == (info.Nominal.MaxY+1) ) - ok=1; - } - - if(!ok) - { - nmodes++; - - SDL_modelist = (SDL_Rect **)SDL_realloc(SDL_modelist,(nmodes+1)*sizeof(SDL_Rect *)); - SDL_modelist[nmodes]=NULL; - - if ( SDL_modelist ) - { - SDL_modelist[nmodes-1] = (SDL_Rect *)SDL_malloc(sizeof(SDL_Rect)); - - if ( SDL_modelist[nmodes-1] == NULL ) - break; - - SDL_modelist[nmodes-1]->x = 0; - SDL_modelist[nmodes-1]->y = 0; - SDL_modelist[nmodes-1]->w = info.Nominal.MaxX+1; - SDL_modelist[nmodes-1]->h = info.Nominal.MaxY+1; - } - } - } - } - } - nextid=NextDisplayInfo(nextid); - } - - - this->hidden->nvisuals = 0; - /* Search for the visuals in deepest-first order, so that the first - will be the richest one */ - add_visual(this, 32, TrueColor); - add_visual(this, 24, TrueColor); - add_visual(this, 16, TrueColor); - add_visual(this, 15, TrueColor); - add_visual(this, 8, PseudoColor); - - if(this->hidden->nvisuals == 0) { - SDL_SetError("Found no sufficiently capable CGX visuals"); - return -1; - } - - if ( SDL_modelist == NULL ) { - SDL_modelist = (SDL_Rect **)SDL_malloc((1+1)*sizeof(SDL_Rect *)); + ULONG nextid; + int nmodes = 0; + + SDL_modelist = NULL; + + nextid = NextDisplayInfo(INVALID_ID); + + while (nextid != INVALID_ID) { + if (IsCyberModeID(nextid)) { + DisplayInfoHandle h; + + if (h = FindDisplayInfo(nextid)) { + struct DimensionInfo info; + + if (GetDisplayInfoData + (h, (char *) &info, sizeof(struct DimensionInfo), + DTAG_DIMS, NULL)) { + int ok = 0; + + for (i = 0; i < nmodes; i++) { + if (SDL_modelist[i]->w == (info.Nominal.MaxX + 1) + && SDL_modelist[i]->h == (info.Nominal.MaxY + 1)) + ok = 1; + } + + if (!ok) { + nmodes++; + + SDL_modelist = + (SDL_Rect **) SDL_realloc(SDL_modelist, + (nmodes + + 1) * + sizeof(SDL_Rect *)); + SDL_modelist[nmodes] = NULL; + + if (SDL_modelist) { + SDL_modelist[nmodes - 1] = (SDL_Rect *) + SDL_malloc(sizeof(SDL_Rect)); + + if (SDL_modelist[nmodes - 1] == NULL) + break; + + SDL_modelist[nmodes - 1]->x = 0; + SDL_modelist[nmodes - 1]->y = 0; + SDL_modelist[nmodes - 1]->w = + info.Nominal.MaxX + 1; + SDL_modelist[nmodes - 1]->h = + info.Nominal.MaxY + 1; + } + } + } + } + } + nextid = NextDisplayInfo(nextid); + } + + + this->hidden->nvisuals = 0; + /* Search for the visuals in deepest-first order, so that the first + will be the richest one */ + add_visual(this, 32, TrueColor); + add_visual(this, 24, TrueColor); + add_visual(this, 16, TrueColor); + add_visual(this, 15, TrueColor); + add_visual(this, 8, PseudoColor); + + if (this->hidden->nvisuals == 0) { + SDL_SetError("Found no sufficiently capable CGX visuals"); + return -1; + } + + if (SDL_modelist == NULL) { + SDL_modelist = (SDL_Rect **) SDL_malloc((1 + 1) * sizeof(SDL_Rect *)); i = 0; - if ( SDL_modelist ) { - SDL_modelist[i] = (SDL_Rect *)SDL_malloc(sizeof(SDL_Rect)); - if ( SDL_modelist[i] ) { + if (SDL_modelist) { + SDL_modelist[i] = (SDL_Rect *) SDL_malloc(sizeof(SDL_Rect)); + if (SDL_modelist[i]) { SDL_modelist[i]->x = 0; SDL_modelist[i]->y = 0; SDL_modelist[i]->w = SDL_Display->Width; @@ -185,54 +190,55 @@ int CGX_GetVideoModes(_THIS) } } - D( if ( SDL_modelist ) { - bug("CGX video mode list: (%ld)\n",nmodes); - for ( i=0; SDL_modelist[i]; ++i ) { - bug( "\t%ld x %ld\n", - SDL_modelist[i]->w, SDL_modelist[i]->h); - } - } + D(if (SDL_modelist) { + bug("CGX video mode list: (%ld)\n", nmodes); + for (i = 0; SDL_modelist[i]; ++i) { + bug("\t%ld x %ld\n", SDL_modelist[i]->w, SDL_modelist[i]->h);} + } ); - D( { bug("CGX visuals list: (%ld)\n",this->hidden->nvisuals); - - for(i=0;ihidden->nvisuals;i++) - bug("\t%lx - depth: %ld bpp: %ld\n",this->hidden->visuals[i].visual,this->hidden->visuals[i].depth,this->hidden->visuals[i].bpp); - } + D( { + bug("CGX visuals list: (%ld)\n", this->hidden->nvisuals); + for (i = 0; i < this->hidden->nvisuals; i++) + bug("\t%lx - depth: %ld bpp: %ld\n", + this->hidden->visuals[i].visual, + this->hidden->visuals[i].depth, this->hidden->visuals[i].bpp);} ); return 0; } -int CGX_SupportedVisual(_THIS, SDL_PixelFormat *format) +int +CGX_SupportedVisual(_THIS, SDL_PixelFormat * format) { int i; - for(i = 0; i < this->hidden->nvisuals; i++) - { - if(this->hidden->visuals[i].depth == format->BitsPerPixel) // Era bpp - return 1; - } + for (i = 0; i < this->hidden->nvisuals; i++) { + if (this->hidden->visuals[i].depth == format->BitsPerPixel) // Era bpp + return 1; + } return 0; } -SDL_Rect **CGX_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags) +SDL_Rect ** +CGX_ListModes(_THIS, SDL_PixelFormat * format, Uint32 flags) { - if ( CGX_SupportedVisual(this, format) ) { - if ( flags & SDL_FULLSCREEN ) { - return(SDL_modelist); + if (CGX_SupportedVisual(this, format)) { + if (flags & SDL_FULLSCREEN) { + return (SDL_modelist); } else { - return((SDL_Rect **)-1); + return ((SDL_Rect **) - 1); } } else { - return((SDL_Rect **)0); + return ((SDL_Rect **) 0); } } -void CGX_FreeVideoModes(_THIS) +void +CGX_FreeVideoModes(_THIS) { int i; - if ( SDL_modelist ) { - for ( i=0; SDL_modelist[i]; ++i ) { + if (SDL_modelist) { + for (i = 0; SDL_modelist[i]; ++i) { SDL_free(SDL_modelist[i]); } SDL_free(SDL_modelist); @@ -240,50 +246,55 @@ void CGX_FreeVideoModes(_THIS) } } -int CGX_ResizeFullScreen(_THIS) +int +CGX_ResizeFullScreen(_THIS) { int x, y; int real_w, real_h; - if ( currently_fullscreen ) { + if (currently_fullscreen) { /* Per ora non faccio nulla qui */ } - return(1); + return (1); } -void _QueueEnterFullScreen(_THIS) +void +_QueueEnterFullScreen(_THIS) { } -int CGX_EnterFullScreen(_THIS) +int +CGX_EnterFullScreen(_THIS) { int okay; - Uint32 saved_flags; + Uint32 saved_flags; okay = 1; saved_flags = this->screen->flags; - if ( ! currently_fullscreen ) - { + if (!currently_fullscreen) { int real_w, real_h; /* Map the fullscreen window to blank the screen */ get_real_resolution(this, &real_w, &real_h); - CGX_DestroyWindow(this,this->screen); - set_best_resolution(this, real_w,real_h); + CGX_DestroyWindow(this, this->screen); + set_best_resolution(this, real_w, real_h); currently_fullscreen = 1; - this->screen->flags = saved_flags; + this->screen->flags = saved_flags; - CGX_CreateWindow(this,this->screen,real_w,real_h,GetCyberMapAttr(SDL_Display->RastPort.BitMap,CYBRMATTR_DEPTH),this->screen->flags); + CGX_CreateWindow(this, this->screen, real_w, real_h, + GetCyberMapAttr(SDL_Display->RastPort.BitMap, + CYBRMATTR_DEPTH), + this->screen->flags); /* Set the new resolution */ okay = CGX_ResizeFullScreen(this); - if ( ! okay ) { + if (!okay) { CGX_LeaveFullScreen(this); } - /* Set the colormap */ + /* Set the colormap */ /* if ( SDL_XColorMap ) { XInstallColormap(SDL_Display, SDL_XColorMap); @@ -291,26 +302,33 @@ int CGX_EnterFullScreen(_THIS) */ } // CGX_GrabInputNoLock(this, this->input_grab | SDL_GRAB_FULLSCREEN); - return(okay); + return (okay); } -int CGX_LeaveFullScreen(_THIS) +int +CGX_LeaveFullScreen(_THIS) { - if ( currently_fullscreen ) { - int width,height; - if ( SDL_Window ) { - CloseWindow(SDL_Window); - SDL_Window=NULL; - } - CloseScreen(SDL_Display); + if (currently_fullscreen) { + int width, height; + if (SDL_Window) { + CloseWindow(SDL_Window); + SDL_Window = NULL; + } + CloseScreen(SDL_Display); - GFX_Display=SDL_Display=LockPubScreen(NULL); + GFX_Display = SDL_Display = LockPubScreen(NULL); - currently_fullscreen = 0; + currently_fullscreen = 0; - CGX_CreateWindow(this,this->screen,this->screen->w,this->screen->h,GetCyberMapAttr(SDL_Display->RastPort.BitMap,CYBRMATTR_DEPTH),this->screen->flags); - CGX_ResizeImage(this,this->screen,0L); + CGX_CreateWindow(this, this->screen, this->screen->w, + this->screen->h, + GetCyberMapAttr(SDL_Display->RastPort.BitMap, + CYBRMATTR_DEPTH), + this->screen->flags); + CGX_ResizeImage(this, this->screen, 0L); } - return(0); + return (0); } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/cybergfx/SDL_cgxmodes_c.h b/src/video/cybergfx/SDL_cgxmodes_c.h index 6c6f4856e..20562f275 100644 --- a/src/video/cybergfx/SDL_cgxmodes_c.h +++ b/src/video/cybergfx/SDL_cgxmodes_c.h @@ -33,7 +33,8 @@ #define GRAB_FULLSCREEN extern int CGX_GetVideoModes(_THIS); -extern SDL_Rect **CGX_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags); +extern SDL_Rect **CGX_ListModes(_THIS, SDL_PixelFormat * format, + Uint32 flags); extern void CGX_FreeVideoModes(_THIS); extern int CGX_ResizeFullScreen(_THIS); /* @@ -43,3 +44,4 @@ extern void CGX_QueueEnterFullScreen(_THIS); */ extern int CGX_EnterFullScreen(_THIS); extern int CGX_LeaveFullScreen(_THIS); +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/cybergfx/SDL_cgxvideo.c b/src/video/cybergfx/SDL_cgxvideo.c index e3067464d..f37b67efb 100644 --- a/src/video/cybergfx/SDL_cgxvideo.c +++ b/src/video/cybergfx/SDL_cgxvideo.c @@ -43,1333 +43,1402 @@ #include "SDL_cgximage_c.h" /* Initialization/Query functions */ -static int CGX_VideoInit(_THIS, SDL_PixelFormat *vformat); -static SDL_Surface *CGX_SetVideoMode(_THIS, SDL_Surface *current, int width, int height, int bpp, Uint32 flags); +static int CGX_VideoInit(_THIS, SDL_PixelFormat * vformat); +static SDL_Surface *CGX_SetVideoMode(_THIS, SDL_Surface * current, int width, + int height, int bpp, Uint32 flags); static int CGX_ToggleFullScreen(_THIS, int on); static void CGX_UpdateMouse(_THIS); -static int CGX_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color *colors); +static int CGX_SetColors(_THIS, int firstcolor, int ncolors, + SDL_Color * colors); static void CGX_VideoQuit(_THIS); /* CGX driver bootstrap functions */ -struct Library *CyberGfxBase=NULL; -struct IntuitionBase *IntuitionBase=NULL; -struct GfxBase *GfxBase=NULL; +struct Library *CyberGfxBase = NULL; +struct IntuitionBase *IntuitionBase = NULL; +struct GfxBase *GfxBase = NULL; -int CGX_SetGamma(_THIS, float red, float green, float blue) +int +CGX_SetGamma(_THIS, float red, float green, float blue) { SDL_SetError("Gamma correction not supported"); return -1; } -int CGX_GetGamma(_THIS, float red, float green, float blue) +int +CGX_GetGamma(_THIS, float red, float green, float blue) { SDL_SetError("Gamma correction not supported"); return -1; } -int CGX_SetGammaRamp(_THIS, Uint16 *ramp) +int +CGX_SetGammaRamp(_THIS, Uint16 * ramp) { #if 0 - Int i, ncolors; - XColor xcmap[256]; - - /* See if actually setting the gamma is supported */ - if ( SDL_Visual->class != DirectColor ) { - SDL_SetError("Gamma correction not supported on this visual"); - return(-1); - } - - /* Calculate the appropriate palette for the given gamma ramp */ - ncolors = SDL_Visual->map_entries; - for ( i=0; iscreen->format, c, c, c); - xcmap[i].red = ramp[0*256+c]; - xcmap[i].green = ramp[1*256+c]; - xcmap[i].blue = ramp[2*256+c]; - xcmap[i].flags = (DoRed|DoGreen|DoBlue); - } - XStoreColors(GFX_Display, SDL_XColorMap, xcmap, ncolors); - XSync(GFX_Display, False); - - return(0); + Int i, ncolors; + XColor xcmap[256]; + + /* See if actually setting the gamma is supported */ + if (SDL_Visual->class != DirectColor) { + SDL_SetError("Gamma correction not supported on this visual"); + return (-1); + } + + /* Calculate the appropriate palette for the given gamma ramp */ + ncolors = SDL_Visual->map_entries; + for (i = 0; i < ncolors; ++i) { + Uint8 c = (256 * i / ncolors); + xcmap[i].pixel = SDL_MapRGB(this->screen->format, c, c, c); + xcmap[i].red = ramp[0 * 256 + c]; + xcmap[i].green = ramp[1 * 256 + c]; + xcmap[i].blue = ramp[2 * 256 + c]; + xcmap[i].flags = (DoRed | DoGreen | DoBlue); + } + XStoreColors(GFX_Display, SDL_XColorMap, xcmap, ncolors); + XSync(GFX_Display, False); + + return (0); #else SDL_SetError("Gamma correction not supported on this visual"); - return(-1); + return (-1); #endif } -static void DestroyScreen(_THIS) +static void +DestroyScreen(_THIS) { - if(currently_fullscreen) - { - if(this->hidden->dbuffer) - { - extern struct MsgPort *safeport,*dispport; - - this->hidden->dbuffer=0; - - if(safeport) - { - while(GetMsg(safeport)!=NULL); - DeleteMsgPort(safeport); - } - if(dispport) - { - while(GetMsg(dispport)!=NULL); - DeleteMsgPort(dispport); - } - - this->hidden->SB[0]->sb_DBufInfo->dbi_SafeMessage.mn_ReplyPort=this->hidden->SB[0]->sb_DBufInfo->dbi_DispMessage.mn_ReplyPort=NULL; - this->hidden->SB[1]->sb_DBufInfo->dbi_SafeMessage.mn_ReplyPort=this->hidden->SB[1]->sb_DBufInfo->dbi_DispMessage.mn_ReplyPort=NULL; - - if(this->hidden->SB[1]) - FreeScreenBuffer(SDL_Display,this->hidden->SB[1]); - if(this->hidden->SB[0]) - FreeScreenBuffer(SDL_Display,this->hidden->SB[0]); - - - this->hidden->SB[0]=this->hidden->SB[1]=NULL; - - if(SDL_RastPort && SDL_RastPort != &SDL_Display->RastPort) - SDL_free(SDL_RastPort); - - SDL_RastPort=NULL; - } - CloseScreen(GFX_Display); - currently_fullscreen=0; - } - else if(GFX_Display) - UnlockPubScreen(NULL,GFX_Display); - - GFX_Display = NULL; + if (currently_fullscreen) { + if (this->hidden->dbuffer) { + extern struct MsgPort *safeport, *dispport; + + this->hidden->dbuffer = 0; + + if (safeport) { + while (GetMsg(safeport) != NULL); + DeleteMsgPort(safeport); + } + if (dispport) { + while (GetMsg(dispport) != NULL); + DeleteMsgPort(dispport); + } + + this->hidden->SB[0]->sb_DBufInfo->dbi_SafeMessage. + mn_ReplyPort = + this->hidden->SB[0]->sb_DBufInfo->dbi_DispMessage. + mn_ReplyPort = NULL; + this->hidden->SB[1]->sb_DBufInfo->dbi_SafeMessage. + mn_ReplyPort = + this->hidden->SB[1]->sb_DBufInfo->dbi_DispMessage. + mn_ReplyPort = NULL; + + if (this->hidden->SB[1]) + FreeScreenBuffer(SDL_Display, this->hidden->SB[1]); + if (this->hidden->SB[0]) + FreeScreenBuffer(SDL_Display, this->hidden->SB[0]); + + + this->hidden->SB[0] = this->hidden->SB[1] = NULL; + + if (SDL_RastPort && SDL_RastPort != &SDL_Display->RastPort) + SDL_free(SDL_RastPort); + + SDL_RastPort = NULL; + } + CloseScreen(GFX_Display); + currently_fullscreen = 0; + } else if (GFX_Display) + UnlockPubScreen(NULL, GFX_Display); + + GFX_Display = NULL; } -static int CGX_Available(void) +static int +CGX_Available(void) { - struct Library *l; + struct Library *l; - l = OpenLibrary("cybergraphics.library",0L); + l = OpenLibrary("cybergraphics.library", 0L); - if ( l != NULL ) { - D(bug("CGX video device AVAILABLE\n")); - CloseLibrary(l); - } - D(else bug("**CGX video device UNAVAILABLE\n")); + if (l != NULL) { + D(bug("CGX video device AVAILABLE\n")); + CloseLibrary(l); + } + D( + else + bug("**CGX video device UNAVAILABLE\n")); - return(l != NULL); + return (l != NULL); } -static void CGX_DeleteDevice(SDL_VideoDevice *device) +static void +CGX_DeleteDevice(SDL_VideoDevice * device) { - if ( device ) { - if ( device->hidden ) { - SDL_free(device->hidden); - } - if ( device->gl_data ) { - SDL_free(device->gl_data); - } - SDL_free(device); - } + if (device) { + if (device->hidden) { + SDL_free(device->hidden); + } + if (device->gl_data) { + SDL_free(device->gl_data); + } + SDL_free(device); + } } -static SDL_VideoDevice *CGX_CreateDevice(int devindex) +static SDL_VideoDevice * +CGX_CreateDevice(int devindex) { - SDL_VideoDevice *device; - - /* Initialize all variables that we clean on shutdown */ - device = (SDL_VideoDevice *)SDL_malloc(sizeof(SDL_VideoDevice)); - if ( device ) { - SDL_memset(device, 0, (sizeof *device)); - device->hidden = (struct SDL_PrivateVideoData *) - SDL_malloc((sizeof *device->hidden)); - device->gl_data = (struct SDL_PrivateGLData *) - SDL_malloc((sizeof *device->gl_data)); - } - if ( (device == NULL) || (device->hidden == NULL) || - (device->gl_data == NULL) ) { - D(bug("Unable to create video device!\n")); - SDL_OutOfMemory(); - CGX_DeleteDevice(device); - return(0); - } - SDL_memset(device->hidden, 0, sizeof(*device->hidden)); - SDL_memset(device->gl_data, 0, sizeof(*device->gl_data)); - - /* Set the driver flags */ - device->handles_any_size = 1; - - /* Set the function pointers */ - device->VideoInit = CGX_VideoInit; - device->ListModes = CGX_ListModes; - device->SetVideoMode = CGX_SetVideoMode; - device->ToggleFullScreen = CGX_ToggleFullScreen; - device->UpdateMouse = CGX_UpdateMouse; - device->SetColors = CGX_SetColors; - device->UpdateRects = NULL; - device->VideoQuit = CGX_VideoQuit; - device->AllocHWSurface = CGX_AllocHWSurface; - device->CheckHWBlit = CGX_CheckHWBlit; - device->FillHWRect = CGX_FillHWRect; - device->SetHWColorKey = CGX_SetHWColorKey; - device->SetHWAlpha = NULL; - device->LockHWSurface = CGX_LockHWSurface; - device->UnlockHWSurface = CGX_UnlockHWSurface; - device->FlipHWSurface = CGX_FlipHWSurface; - device->FreeHWSurface = CGX_FreeHWSurface; - device->SetGamma = CGX_SetGamma; - device->GetGamma = CGX_GetGamma; - device->SetGammaRamp = CGX_SetGammaRamp; - device->GetGammaRamp = NULL; + SDL_VideoDevice *device; + + /* Initialize all variables that we clean on shutdown */ + device = (SDL_VideoDevice *) SDL_malloc(sizeof(SDL_VideoDevice)); + if (device) { + SDL_memset(device, 0, (sizeof *device)); + device->hidden = (struct SDL_PrivateVideoData *) + SDL_malloc((sizeof *device->hidden)); + device->gl_data = (struct SDL_PrivateGLData *) + SDL_malloc((sizeof *device->gl_data)); + } + if ((device == NULL) || (device->hidden == NULL) || + (device->gl_data == NULL)) { + D(bug("Unable to create video device!\n")); + SDL_OutOfMemory(); + CGX_DeleteDevice(device); + return (0); + } + SDL_memset(device->hidden, 0, sizeof(*device->hidden)); + SDL_memset(device->gl_data, 0, sizeof(*device->gl_data)); + + /* Set the driver flags */ + device->handles_any_size = 1; + + /* Set the function pointers */ + device->VideoInit = CGX_VideoInit; + device->ListModes = CGX_ListModes; + device->SetVideoMode = CGX_SetVideoMode; + device->ToggleFullScreen = CGX_ToggleFullScreen; + device->UpdateMouse = CGX_UpdateMouse; + device->SetColors = CGX_SetColors; + device->UpdateRects = NULL; + device->VideoQuit = CGX_VideoQuit; + device->AllocHWSurface = CGX_AllocHWSurface; + device->CheckHWBlit = CGX_CheckHWBlit; + device->FillHWRect = CGX_FillHWRect; + device->SetHWColorKey = CGX_SetHWColorKey; + device->SetHWAlpha = NULL; + device->LockHWSurface = CGX_LockHWSurface; + device->UnlockHWSurface = CGX_UnlockHWSurface; + device->FlipHWSurface = CGX_FlipHWSurface; + device->FreeHWSurface = CGX_FreeHWSurface; + device->SetGamma = CGX_SetGamma; + device->GetGamma = CGX_GetGamma; + device->SetGammaRamp = CGX_SetGammaRamp; + device->GetGammaRamp = NULL; #if SDL_VIDEO_OPENGL - device->GL_LoadLibrary = CGX_GL_LoadLibrary; - device->GL_GetProcAddress = CGX_GL_GetProcAddress; - device->GL_GetAttribute = CGX_GL_GetAttribute; - device->GL_MakeCurrent = CGX_GL_MakeCurrent; - device->GL_SwapBuffers = CGX_GL_SwapBuffers; + device->GL_LoadLibrary = CGX_GL_LoadLibrary; + device->GL_GetProcAddress = CGX_GL_GetProcAddress; + device->GL_GetAttribute = CGX_GL_GetAttribute; + device->GL_MakeCurrent = CGX_GL_MakeCurrent; + device->GL_SwapBuffers = CGX_GL_SwapBuffers; #endif - device->SetIcon = CGX_SetIcon; - device->SetCaption = CGX_SetCaption; - device->IconifyWindow = NULL; /* CGX_IconifyWindow; */ - device->GrabInput = NULL /* CGX_GrabInput*/; - device->GetWMInfo = CGX_GetWMInfo; - device->FreeWMCursor = amiga_FreeWMCursor; - device->CreateWMCursor = amiga_CreateWMCursor; - device->ShowWMCursor = amiga_ShowWMCursor; - device->WarpWMCursor = amiga_WarpWMCursor; - device->CheckMouseMode = amiga_CheckMouseMode; - device->InitOSKeymap = amiga_InitOSKeymap; - device->PumpEvents = amiga_PumpEvents; - - device->free = CGX_DeleteDevice; - - return device; + device->SetIcon = CGX_SetIcon; + device->SetCaption = CGX_SetCaption; + device->IconifyWindow = NULL; /* CGX_IconifyWindow; */ + device->GrabInput = NULL /* CGX_GrabInput */ ; + device->GetWMInfo = CGX_GetWMInfo; + device->FreeWMCursor = amiga_FreeWMCursor; + device->CreateWMCursor = amiga_CreateWMCursor; + device->ShowWMCursor = amiga_ShowWMCursor; + device->WarpWMCursor = amiga_WarpWMCursor; + device->CheckMouseMode = amiga_CheckMouseMode; + device->InitOSKeymap = amiga_InitOSKeymap; + device->PumpEvents = amiga_PumpEvents; + + device->free = CGX_DeleteDevice; + + return device; } VideoBootStrap CGX_bootstrap = { - "CGX", "AmigaOS CyberGraphics", CGX_Available, CGX_CreateDevice + "CGX", "AmigaOS CyberGraphics", CGX_Available, CGX_CreateDevice }; -Uint32 MakeBitMask(_THIS,int type,int format,int *bpp) +Uint32 +MakeBitMask(_THIS, int type, int format, int *bpp) { - D(if(type==0)bug("REAL pixel format: ")); - - if(this->hidden->depth==*bpp) - { - - switch(format) - { - case PIXFMT_LUT8: - D(if(type==0)bug("LUT8\n")); - return 0; - case PIXFMT_BGR15: - case PIXFMT_RGB15PC: - switch(type) - { - case 0: - D(bug("RGB15PC/BGR15\n")); - return 31; - case 1: - return 992; - case 2: - return 31744; - } - case PIXFMT_RGB15: - case PIXFMT_BGR15PC: - switch(type) - { - case 0: - D(bug("RGB15/BGR15PC\n")); - return 31744; - case 1: - return 992; - case 2: - return 31; - } - case PIXFMT_BGR16PC: - case PIXFMT_RGB16: - switch(type) - { - case 0: - D(bug("RGB16PC\n")); - return 63488; - case 1: - return 2016; - case 2: - return 31; - } - case PIXFMT_BGR16: - case PIXFMT_RGB16PC: - switch(type) - { - case 0: - D(bug("RGB16PC/BGR16\n")); - return 31; - case 1: - return 2016; - case 2: - return 63488; - } - - case PIXFMT_RGB24: - switch(type) - { - case 0: - D(bug("RGB24/BGR24\n")); - return 0xff0000; - case 1: - return 0xff00; - case 2: - return 0xff; - } - case PIXFMT_BGR24: - switch(type) - { - case 0: - D(bug("BGR24\n")); - return 0xff; - case 1: - return 0xff00; - case 2: - return 0xff0000; - } - case PIXFMT_ARGB32: - switch(type) - { - case 0: - D(bug("ARGB32\n")); - return 0xff0000; - case 1: - return 0xff00; - case 2: - return 0xff; - } - case PIXFMT_BGRA32: - switch(type) - { - case 0: - D(bug("BGRA32\n")); - return 0xff00; - case 1: - return 0xff0000; - case 2: - return 0xff000000; - } - case PIXFMT_RGBA32: - switch(type) - { - case 0: - D(bug("RGBA32\n")); - return 0xff000000; - case 1: - return 0xff0000; - case 2: - return 0xff00; - } - default: - D(bug("Unknown pixel format! Default to 24bit\n")); - return (Uint32) (255<<(type*8)); - } - } - else - { - D(if(type==0)bug("DIFFERENT from screen.\nAllocated screen format: ")); - - switch(*bpp) - { - case 32: - D(if(type==0) bug("RGBA32\n")); - switch(type) - { - case 0: - return 0xff000000; - case 1: - return 0xff0000; - case 2: - return 0xff00; - } - break; - case 24: -use_truecolor: - switch(type) - { - case 0: - D(bug("RGB24\n")); - return 0xff0000; - case 1: - return 0xff00; - case 2: - return 0xff; - } - case 16: - case 15: - D(if(type==0) bug("Not supported, switching to 24bit!\n")); - *bpp=24; - goto use_truecolor; - break; - default: - D(if(type==0)bug("This is a chunky display\n")); + D(if (type == 0) bug("REAL pixel format: ")); + + if (this->hidden->depth == *bpp) { + + switch (format) { + case PIXFMT_LUT8: + D(if (type == 0) bug("LUT8\n")); + return 0; + case PIXFMT_BGR15: + case PIXFMT_RGB15PC: + switch (type) { + case 0: + D(bug("RGB15PC/BGR15\n")); + return 31; + case 1: + return 992; + case 2: + return 31744; + } + case PIXFMT_RGB15: + case PIXFMT_BGR15PC: + switch (type) { + case 0: + D(bug("RGB15/BGR15PC\n")); + return 31744; + case 1: + return 992; + case 2: + return 31; + } + case PIXFMT_BGR16PC: + case PIXFMT_RGB16: + switch (type) { + case 0: + D(bug("RGB16PC\n")); + return 63488; + case 1: + return 2016; + case 2: + return 31; + } + case PIXFMT_BGR16: + case PIXFMT_RGB16PC: + switch (type) { + case 0: + D(bug("RGB16PC/BGR16\n")); + return 31; + case 1: + return 2016; + case 2: + return 63488; + } + + case PIXFMT_RGB24: + switch (type) { + case 0: + D(bug("RGB24/BGR24\n")); + return 0xff0000; + case 1: + return 0xff00; + case 2: + return 0xff; + } + case PIXFMT_BGR24: + switch (type) { + case 0: + D(bug("BGR24\n")); + return 0xff; + case 1: + return 0xff00; + case 2: + return 0xff0000; + } + case PIXFMT_ARGB32: + switch (type) { + case 0: + D(bug("ARGB32\n")); + return 0xff0000; + case 1: + return 0xff00; + case 2: + return 0xff; + } + case PIXFMT_BGRA32: + switch (type) { + case 0: + D(bug("BGRA32\n")); + return 0xff00; + case 1: + return 0xff0000; + case 2: + return 0xff000000; + } + case PIXFMT_RGBA32: + switch (type) { + case 0: + D(bug("RGBA32\n")); + return 0xff000000; + case 1: + return 0xff0000; + case 2: + return 0xff00; + } + default: + D(bug("Unknown pixel format! Default to 24bit\n")); + return (Uint32) (255 << (type * 8)); + } + } else { + D(if (type == 0) + bug("DIFFERENT from screen.\nAllocated screen format: ")); + + switch (*bpp) { + case 32: + D(if (type == 0) bug("RGBA32\n")); + switch (type) { + case 0: + return 0xff000000; + case 1: + return 0xff0000; + case 2: + return 0xff00; + } + break; + case 24: + use_truecolor: + switch (type) { + case 0: + D(bug("RGB24\n")); + return 0xff0000; + case 1: + return 0xff00; + case 2: + return 0xff; + } + case 16: + case 15: + D(if (type == 0) + bug("Not supported, switching to 24bit!\n")); + *bpp = 24; + goto use_truecolor; + break; + default: + D(if (type == 0) bug("This is a chunky display\n")); // For chunky display mask is always 0; - return 0; - } - } - return 0; + return 0; + } + } + return 0; } -static int CGX_VideoInit(_THIS, SDL_PixelFormat *vformat) +static int +CGX_VideoInit(_THIS, SDL_PixelFormat * vformat) { - int i; - struct Library *RTGBase; - - D(bug("VideoInit... Opening libraries\n")); - - if(!IntuitionBase) { - if( !(IntuitionBase=(struct IntuitionBase *)OpenLibrary("intuition.library",39L))) { - SDL_SetError("Couldn't open intuition V39+"); - return -1; - } - } - - if(!GfxBase) { - if( !(GfxBase=(struct GfxBase *)OpenLibrary("graphics.library",39L))) { - SDL_SetError("Couldn't open graphics V39+"); - return -1; - } - } - - if(!CyberGfxBase) { - if( !(CyberGfxBase=OpenLibrary("cybergraphics.library",40L))) { - SDL_SetError("Couldn't open cybergraphics."); - return(-1); - } - } - - if(RTGBase=OpenLibrary("libs:picasso96/rtg.library",0L)) { - extern int use_picasso96; - - CloseLibrary(RTGBase); - use_picasso96=1; - } - - D(bug("Library intialized, locking screen...\n")); - - SDL_Display = LockPubScreen(NULL); - - if ( SDL_Display == NULL ) { - D(bug("Cannot lock display...\n")); - SDL_SetError("Couldn't lock the display"); - return(-1); - } - this->info.current_w = SDL_Display->Width; - this->info.current_h = SDL_Display->Height; - - D(bug("Checking if we are using a CGX native display...\n")); - - if(!IsCyberModeID(GetVPModeID(&SDL_Display->ViewPort))) - { - Uint32 okid=BestCModeIDTags(CYBRBIDTG_NominalWidth,SDL_Display->Width, - CYBRBIDTG_NominalHeight,SDL_Display->Height, - CYBRBIDTG_Depth,8, - TAG_DONE); - - D(bug("Default visual is not CGX native!\n")); - - UnlockPubScreen(NULL,SDL_Display); - - GFX_Display=NULL; - - if(okid!=INVALID_ID) - { - GFX_Display=OpenScreenTags(NULL, - SA_Width,SDL_Display->Width, - SA_Height,SDL_Display->Height, - SA_Depth,8,SA_Quiet,TRUE, - SA_ShowTitle,FALSE, - SA_DisplayID,okid, - TAG_DONE); - } - - if(!GFX_Display) - { - SDL_SetError("Unable to open a suited CGX display"); - return -1; - } - else SDL_Display=GFX_Display; - - } - else GFX_Display = SDL_Display; - - - /* See whether or not we need to swap pixels */ - - swap_pixels = 0; + int i; + struct Library *RTGBase; + + D(bug("VideoInit... Opening libraries\n")); + + if (!IntuitionBase) { + if (! + (IntuitionBase = + (struct IntuitionBase *) OpenLibrary("intuition.library", + 39L))) { + SDL_SetError("Couldn't open intuition V39+"); + return -1; + } + } + + if (!GfxBase) { + if (! + (GfxBase = + (struct GfxBase *) OpenLibrary("graphics.library", 39L))) { + SDL_SetError("Couldn't open graphics V39+"); + return -1; + } + } + + if (!CyberGfxBase) { + if (!(CyberGfxBase = OpenLibrary("cybergraphics.library", 40L))) { + SDL_SetError("Couldn't open cybergraphics."); + return (-1); + } + } + + if (RTGBase = OpenLibrary("libs:picasso96/rtg.library", 0L)) { + extern int use_picasso96; + + CloseLibrary(RTGBase); + use_picasso96 = 1; + } + + D(bug("Library intialized, locking screen...\n")); + + SDL_Display = LockPubScreen(NULL); + + if (SDL_Display == NULL) { + D(bug("Cannot lock display...\n")); + SDL_SetError("Couldn't lock the display"); + return (-1); + } + this->info.current_w = SDL_Display->Width; + this->info.current_h = SDL_Display->Height; + + D(bug("Checking if we are using a CGX native display...\n")); + + if (!IsCyberModeID(GetVPModeID(&SDL_Display->ViewPort))) { + Uint32 okid = + BestCModeIDTags(CYBRBIDTG_NominalWidth, SDL_Display->Width, + CYBRBIDTG_NominalHeight, SDL_Display->Height, + CYBRBIDTG_Depth, 8, + TAG_DONE); + + D(bug("Default visual is not CGX native!\n")); + + UnlockPubScreen(NULL, SDL_Display); + + GFX_Display = NULL; + + if (okid != INVALID_ID) { + GFX_Display = OpenScreenTags(NULL, + SA_Width, SDL_Display->Width, + SA_Height, SDL_Display->Height, + SA_Depth, 8, SA_Quiet, TRUE, + SA_ShowTitle, FALSE, + SA_DisplayID, okid, TAG_DONE); + } + + if (!GFX_Display) { + SDL_SetError("Unable to open a suited CGX display"); + return -1; + } else + SDL_Display = GFX_Display; + + } else + GFX_Display = SDL_Display; + + + /* See whether or not we need to swap pixels */ + + swap_pixels = 0; // Non e' detto che sia cosi' pero', alcune schede potrebbero gestire i modi in modo differente - if ( SDL_BYTEORDER == SDL_LIL_ENDIAN ) { - swap_pixels = 1; - } + if (SDL_BYTEORDER == SDL_LIL_ENDIAN) { + swap_pixels = 1; + } - D(bug("Before GetVideoModes....\n")); + D(bug("Before GetVideoModes....\n")); - /* Get the available video modes */ - if(CGX_GetVideoModes(this) < 0) - return -1; + /* Get the available video modes */ + if (CGX_GetVideoModes(this) < 0) + return -1; - /* Determine the default screen depth: - Use the default visual (or at least one with the same depth) */ + /* Determine the default screen depth: + Use the default visual (or at least one with the same depth) */ - for(i = 0; i < this->hidden->nvisuals; i++) - if(this->hidden->visuals[i].depth == GetCyberMapAttr(SDL_Display->RastPort.BitMap,CYBRMATTR_DEPTH)) - break; - if(i == this->hidden->nvisuals) { - /* default visual was useless, take the deepest one instead */ - i = 0; - } - SDL_Visual = this->hidden->visuals[i].visual; + for (i = 0; i < this->hidden->nvisuals; i++) + if (this->hidden->visuals[i].depth == + GetCyberMapAttr(SDL_Display->RastPort.BitMap, CYBRMATTR_DEPTH)) + break; + if (i == this->hidden->nvisuals) { + /* default visual was useless, take the deepest one instead */ + i = 0; + } + SDL_Visual = this->hidden->visuals[i].visual; -// SDL_XColorMap = SDL_DisplayColormap; +// SDL_XColorMap = SDL_DisplayColormap; - this->hidden->depth = this->hidden->visuals[i].depth; - D(bug("Init: Setting screen depth to: %ld\n",this->hidden->depth)); - vformat->BitsPerPixel = this->hidden->visuals[i].depth; /* this->hidden->visuals[i].bpp; */ + this->hidden->depth = this->hidden->visuals[i].depth; + D(bug("Init: Setting screen depth to: %ld\n", this->hidden->depth)); + vformat->BitsPerPixel = this->hidden->visuals[i].depth; /* this->hidden->visuals[i].bpp; */ - { - int form; - APTR handle; - struct DisplayInfo info; + { + int form; + APTR handle; + struct DisplayInfo info; - if(!(handle=FindDisplayInfo(this->hidden->visuals[i].visual))) - { - D(bug("Unable to get visual info...\n")); - return -1; - } + if (!(handle = FindDisplayInfo(this->hidden->visuals[i].visual))) { + D(bug("Unable to get visual info...\n")); + return -1; + } - if(!GetDisplayInfoData(handle,(char *)&info,sizeof(struct DisplayInfo),DTAG_DISP,NULL)) { - D(bug("Unable to get visual info data...\n")); - return -1; - } + if (!GetDisplayInfoData + (handle, (char *) &info, sizeof(struct DisplayInfo), DTAG_DISP, + NULL)) { + D(bug("Unable to get visual info data...\n")); + return -1; + } - form=GetCyberIDAttr(CYBRIDATTR_PIXFMT,SDL_Visual); + form = GetCyberIDAttr(CYBRIDATTR_PIXFMT, SDL_Visual); // In this case I use makebitmask in a way that I'm sure I'll get PIXFMT pixel mask - if ( vformat->BitsPerPixel > 8 ) - { - vformat->Rmask = MakeBitMask(this,0,form,&this->hidden->depth); - vformat->Gmask = MakeBitMask(this,1,form,&this->hidden->depth); - vformat->Bmask = MakeBitMask(this,2,form,&this->hidden->depth); - } - } + if (vformat->BitsPerPixel > 8) { + vformat->Rmask = MakeBitMask(this, 0, form, &this->hidden->depth); + vformat->Gmask = MakeBitMask(this, 1, form, &this->hidden->depth); + vformat->Bmask = MakeBitMask(this, 2, form, &this->hidden->depth); + } + } - /* See if we have been passed a window to use */ + /* See if we have been passed a window to use */ /* SDL_windowid = SDL_getenv("SDL_WINDOWID"); */ - SDL_windowid=NULL; + SDL_windowid = NULL; - /* Create the blank cursor */ - SDL_BlankCursor = AllocMem(16,MEMF_CHIP|MEMF_CLEAR); + /* Create the blank cursor */ + SDL_BlankCursor = AllocMem(16, MEMF_CHIP | MEMF_CLEAR); - /* Fill in some window manager capabilities */ - this->info.wm_available = 1; - this->info.blit_hw = 1; - this->info.blit_hw_CC = 1; - this->info.blit_sw = 1; - this->info.blit_fill = 1; - this->info.video_mem=2000000; // Not always true but almost any Amiga card has this memory! + /* Fill in some window manager capabilities */ + this->info.wm_available = 1; + this->info.blit_hw = 1; + this->info.blit_hw_CC = 1; + this->info.blit_sw = 1; + this->info.blit_fill = 1; + this->info.video_mem = 2000000; // Not always true but almost any Amiga card has this memory! - this->hidden->same_format=0; - SDL_RastPort=&SDL_Display->RastPort; - /* We're done! */ - D(bug("End of CGX_VideoInit\n")); + this->hidden->same_format = 0; + SDL_RastPort = &SDL_Display->RastPort; + /* We're done! */ + D(bug("End of CGX_VideoInit\n")); - return(0); + return (0); } -void CGX_DestroyWindow(_THIS, SDL_Surface *screen) +void +CGX_DestroyWindow(_THIS, SDL_Surface * screen) { - D(bug("Destroy Window...\n")); - - if ( ! SDL_windowid ) { - /* Hide the managed window */ - int was_fullscreen=0; - - /* Clean up OpenGL */ - if ( screen ) { - screen->flags &= ~(SDL_OPENGL|SDL_OPENGLBLIT); - } - - if ( screen && (screen->flags & SDL_FULLSCREEN) ) { - was_fullscreen=1; - screen->flags &= ~SDL_FULLSCREEN; -// CGX_LeaveFullScreen(this); tolto x crash - } - - /* Destroy the output window */ - if ( SDL_Window ) { - CloseWindow(SDL_Window); - SDL_Window=NULL; - } - - /* Free the colormap entries */ - if ( SDL_XPixels ) { - int numcolors; - unsigned long pixel; - - if(this->screen->format&&this->hidden->depth==8&&!was_fullscreen) - { - numcolors = 1<screen->format->BitsPerPixel; - - if(numcolors>256) - numcolors=256; - - if(!was_fullscreen&&this->hidden->depth==8) - { - for ( pixel=0; pixel=0) - ReleasePen(GFX_Display->ViewPort.ColorMap,SDL_XPixels[pixel]); - } - } - } - SDL_free(SDL_XPixels); - SDL_XPixels = NULL; - } - } + D(bug("Destroy Window...\n")); + + if (!SDL_windowid) { + /* Hide the managed window */ + int was_fullscreen = 0; + + /* Clean up OpenGL */ + if (screen) { + screen->flags &= ~SDL_INTERNALOPENGL; + } + + if (screen && (screen->flags & SDL_FULLSCREEN)) { + was_fullscreen = 1; + screen->flags &= ~SDL_FULLSCREEN; +// CGX_LeaveFullScreen(this); tolto x crash + } + + /* Destroy the output window */ + if (SDL_Window) { + CloseWindow(SDL_Window); + SDL_Window = NULL; + } + + /* Free the colormap entries */ + if (SDL_XPixels) { + int numcolors; + unsigned long pixel; + + if (this->screen->format && this->hidden->depth == 8 + && !was_fullscreen) { + numcolors = 1 << this->screen->format->BitsPerPixel; + + if (numcolors > 256) + numcolors = 256; + + if (!was_fullscreen && this->hidden->depth == 8) { + for (pixel = 0; pixel < numcolors; pixel++) { + if (SDL_XPixels[pixel] >= 0) + ReleasePen(GFX_Display->ViewPort. + ColorMap, SDL_XPixels[pixel]); + } + } + } + SDL_free(SDL_XPixels); + SDL_XPixels = NULL; + } + } } -static void CGX_SetSizeHints(_THIS, int w, int h, Uint32 flags) +static void +CGX_SetSizeHints(_THIS, int w, int h, Uint32 flags) { - if ( flags & SDL_RESIZABLE ) { - WindowLimits(SDL_Window, 32, 32,4096,4096); - } else { - WindowLimits(SDL_Window, w,h,w,h); - } - if ( flags & SDL_FULLSCREEN ) { - flags&=~SDL_RESIZABLE; - } else if ( SDL_getenv("SDL_VIDEO_CENTERED") ) { - int display_w, display_h; - - display_w = SDL_Display->Width; - display_h = SDL_Display->Height; - ChangeWindowBox(SDL_Window,(display_w - w - SDL_Window->BorderLeft-SDL_Window->BorderRight)/2, - (display_h - h - SDL_Window->BorderTop-SDL_Window->BorderBottom)/2, - w+SDL_Window->BorderLeft+SDL_Window->BorderRight, - h+SDL_Window->BorderTop+SDL_Window->BorderBottom); - } + if (flags & SDL_RESIZABLE) { + WindowLimits(SDL_Window, 32, 32, 4096, 4096); + } else { + WindowLimits(SDL_Window, w, h, w, h); + } + if (flags & SDL_FULLSCREEN) { + flags &= ~SDL_RESIZABLE; + } else if (SDL_getenv("SDL_VIDEO_CENTERED")) { + int display_w, display_h; + + display_w = SDL_Display->Width; + display_h = SDL_Display->Height; + ChangeWindowBox(SDL_Window, + (display_w - w - SDL_Window->BorderLeft - + SDL_Window->BorderRight) / 2, + (display_h - h - SDL_Window->BorderTop - + SDL_Window->BorderBottom) / 2, + w + SDL_Window->BorderLeft + + SDL_Window->BorderRight, + h + SDL_Window->BorderTop + SDL_Window->BorderBottom); + } } -int CGX_CreateWindow(_THIS, SDL_Surface *screen, - int w, int h, int bpp, Uint32 flags) +int +CGX_CreateWindow(_THIS, SDL_Surface * screen, + int w, int h, int bpp, Uint32 flags) { #if 0 - int i, depth; - Uint32 vis; + int i, depth; + Uint32 vis; #endif - D(bug("CGX_CreateWindow\n")); + D(bug("CGX_CreateWindow\n")); - /* If a window is already present, destroy it and start fresh */ - if ( SDL_Window ) { - CGX_DestroyWindow(this, screen); - } + /* If a window is already present, destroy it and start fresh */ + if (SDL_Window) { + CGX_DestroyWindow(this, screen); + } - /* See if we have been given a window id */ - if ( SDL_windowid ) { - SDL_Window = (struct Window *)atol(SDL_windowid); - } else { - SDL_Window = 0; - } + /* See if we have been given a window id */ + if (SDL_windowid) { + SDL_Window = (struct Window *) atol(SDL_windowid); + } else { + SDL_Window = 0; + } - /* find out which visual we are going to use */ + /* find out which visual we are going to use */ #if 0 /* questo l'ho spostato nell'apertura dello schermo, in quanto su Amiga le finestre hanno il pixel mode degli schermi. */ - /*if ( flags & SDL_OPENGL ) { - SDL_SetError("OpenGL not supported by the Amiga SDL!"); - return -1; - } - else {*/ - for ( i = 0; i < this->hidden->nvisuals; i++ ) { - if ( this->hidden->visuals[i].depth == bpp ) /* era .depth */ - break; - } - if ( i == this->hidden->nvisuals ) { - SDL_SetError("No matching visual for requested depth"); - return -1; /* should never happen */ - } - vis = this->hidden->visuals[i].visual; - depth = this->hidden->visuals[i].depth; -// } - SDL_Visual = vis; - this->hidden->depth = depth; - D(bug("Setting screen depth to: %ld\n",this->hidden->depth)); + /*if ( flags & SDL_INTERNALOPENGL ) { + SDL_SetError("OpenGL not supported by the Amiga SDL!"); + return -1; + } + else { */ + for (i = 0; i < this->hidden->nvisuals; i++) { + if (this->hidden->visuals[i].depth == bpp) /* era .depth */ + break; + } + if (i == this->hidden->nvisuals) { + SDL_SetError("No matching visual for requested depth"); + return -1; /* should never happen */ + } + vis = this->hidden->visuals[i].visual; + depth = this->hidden->visuals[i].depth; +// } + SDL_Visual = vis; + this->hidden->depth = depth; + D(bug("Setting screen depth to: %ld\n", this->hidden->depth)); #endif - /* Allocate the new pixel format for this video mode */ - { - Uint32 form; - APTR handle; - struct DisplayInfo info; + /* Allocate the new pixel format for this video mode */ + { + Uint32 form; + APTR handle; + struct DisplayInfo info; - if(!(handle=FindDisplayInfo(SDL_Visual))) - return -1; + if (!(handle = FindDisplayInfo(SDL_Visual))) + return -1; - if(!GetDisplayInfoData(handle,(char *)&info,sizeof(struct DisplayInfo),DTAG_DISP,NULL)) - return -1; + if (!GetDisplayInfoData + (handle, (char *) &info, sizeof(struct DisplayInfo), DTAG_DISP, + NULL)) + return -1; - form=GetCyberIDAttr(CYBRIDATTR_PIXFMT,SDL_Visual); + form = GetCyberIDAttr(CYBRIDATTR_PIXFMT, SDL_Visual); - if(flags&SDL_HWSURFACE) - { - if(bpp!=this->hidden->depth) - { - bpp=this->hidden->depth; - D(bug("Accel forces bpp to be equal (%ld)\n",bpp)); - } - } + if (flags & SDL_HWSURFACE) { + if (bpp != this->hidden->depth) { + bpp = this->hidden->depth; + D(bug("Accel forces bpp to be equal (%ld)\n", bpp)); + } + } - D(bug("BEFORE screen allocation: bpp:%ld (real:%ld)\n",bpp,this->hidden->depth)); + D(bug + ("BEFORE screen allocation: bpp:%ld (real:%ld)\n", bpp, + this->hidden->depth)); /* With this call if needed I'll revert the wanted bpp to a bpp best suited for the display, actually occurs only with requested format 15/16bit and display format != 15/16bit */ - if ( ! SDL_ReallocFormat(screen, bpp, - MakeBitMask(this,0,form,&bpp), MakeBitMask(this,1,form,&bpp), MakeBitMask(this,2,form,&bpp), 0) ) - return -1; + if (!SDL_ReallocFormat(screen, bpp, + MakeBitMask(this, 0, form, &bpp), + MakeBitMask(this, 1, form, &bpp), + MakeBitMask(this, 2, form, &bpp), 0)) + return -1; - D(bug("AFTER screen allocation: bpp:%ld (real:%ld)\n",bpp,this->hidden->depth)); + D(bug + ("AFTER screen allocation: bpp:%ld (real:%ld)\n", bpp, + this->hidden->depth)); - } + } - /* Create the appropriate colormap */ + /* Create the appropriate colormap */ /* if ( SDL_XColorMap != SDL_DisplayColormap ) { XFreeColormap(SDL_Display, SDL_XColorMap); } */ - if ( GetCyberMapAttr(SDL_Display->RastPort.BitMap,CYBRMATTR_PIXFMT)==PIXFMT_LUT8 || bpp==8 ) { - int ncolors,i; - D(bug("XPixels palette allocation...\n")); - - /* Allocate the pixel flags */ - - if(bpp==8) - ncolors=256; - else - ncolors = 1 << screen->format->BitsPerPixel; - - SDL_XPixels = (Sint32 *)SDL_malloc(ncolors * sizeof(Sint32)); - - if(SDL_XPixels == NULL) { - SDL_OutOfMemory(); - return -1; - } - - - for(i=0;iflags |= SDL_HWPALETTE; - } - - /* resize the (possibly new) window manager window */ - - /* Create (or use) the X11 display window */ - - if ( !SDL_windowid ) { - if( flags & SDL_FULLSCREEN ) - { - SDL_Window = OpenWindowTags(NULL,WA_Width,w,WA_Height,h, - WA_Flags,WFLG_ACTIVATE|WFLG_RMBTRAP|WFLG_BORDERLESS|WFLG_BACKDROP|WFLG_REPORTMOUSE, - WA_IDCMP,IDCMP_RAWKEY|IDCMP_MOUSEBUTTONS|IDCMP_MOUSEMOVE, - WA_CustomScreen,(ULONG)SDL_Display, - TAG_DONE); - - D(bug("Opening backdrop window %ldx%ld on display %lx!\n",w,h,SDL_Display)); - } - else - { - /* Create GimmeZeroZero window when OpenGL is used */ - unsigned long gzz = FALSE; - if( flags & SDL_OPENGL ) { - gzz = TRUE; - } - - SDL_Window = OpenWindowTags(NULL,WA_InnerWidth,w,WA_InnerHeight,h, - WA_Flags,WFLG_REPORTMOUSE|WFLG_ACTIVATE|WFLG_RMBTRAP | ((flags&SDL_NOFRAME) ? 0 : (WFLG_DEPTHGADGET|WFLG_CLOSEGADGET|WFLG_DRAGBAR | ((flags&SDL_RESIZABLE) ? WFLG_SIZEGADGET|WFLG_SIZEBBOTTOM : 0))), - WA_IDCMP,IDCMP_RAWKEY|IDCMP_CLOSEWINDOW|IDCMP_MOUSEBUTTONS|IDCMP_NEWSIZE|IDCMP_MOUSEMOVE, - WA_PubScreen,(ULONG)SDL_Display, - WA_GimmeZeroZero, gzz, - TAG_DONE); - D(bug("Opening WB window of size: %ldx%ld!\n",w,h)); - } - - if(!SDL_Window) - return -1; - } - - this->hidden->BytesPerPixel=GetCyberMapAttr(SDL_Window->RPort->BitMap,CYBRMATTR_BPPIX); - - if(screen->flags & SDL_DOUBLEBUF) - { - if(SDL_RastPort=SDL_malloc(sizeof(struct RastPort))) - { - InitRastPort(SDL_RastPort); - SDL_RastPort->BitMap=this->hidden->SB[1]->sb_BitMap; - } - else - return -1; - } - else SDL_RastPort=SDL_Window->RPort; - - if(flags&SDL_HWSURFACE) - screen->flags|=SDL_HWSURFACE; - - if( !SDL_windowid ) { - CGX_SetSizeHints(this, w, h, flags); - } - - /* Set our colormaps when not setting a GL mode */ + if (GetCyberMapAttr(SDL_Display->RastPort.BitMap, CYBRMATTR_PIXFMT) == + PIXFMT_LUT8 || bpp == 8) { + int ncolors, i; + D(bug("XPixels palette allocation...\n")); + + /* Allocate the pixel flags */ + + if (bpp == 8) + ncolors = 256; + else + ncolors = 1 << screen->format->BitsPerPixel; + + SDL_XPixels = (Sint32 *) SDL_malloc(ncolors * sizeof(Sint32)); + + if (SDL_XPixels == NULL) { + SDL_OutOfMemory(); + return -1; + } + + + for (i = 0; i < ncolors; i++) + SDL_XPixels[i] = -1; + + /* always allocate a private colormap on non-default visuals */ + if (bpp == 8) + flags |= SDL_HWPALETTE; + + if (flags & SDL_HWPALETTE) + screen->flags |= SDL_HWPALETTE; + } + + /* resize the (possibly new) window manager window */ + + /* Create (or use) the X11 display window */ + + if (!SDL_windowid) { + if (flags & SDL_FULLSCREEN) { + SDL_Window = OpenWindowTags(NULL, WA_Width, w, WA_Height, h, + WA_Flags, + WFLG_ACTIVATE | WFLG_RMBTRAP | + WFLG_BORDERLESS | WFLG_BACKDROP | + WFLG_REPORTMOUSE, WA_IDCMP, + IDCMP_RAWKEY | IDCMP_MOUSEBUTTONS + | IDCMP_MOUSEMOVE, + WA_CustomScreen, + (ULONG) SDL_Display, TAG_DONE); + + D(bug + ("Opening backdrop window %ldx%ld on display %lx!\n", w, h, + SDL_Display)); + } else { + /* Create GimmeZeroZero window when OpenGL is used */ + unsigned long gzz = FALSE; + if (flags & SDL_INTERNALOPENGL) { + gzz = TRUE; + } + + SDL_Window = + OpenWindowTags(NULL, WA_InnerWidth, w, WA_InnerHeight, h, + WA_Flags, + WFLG_REPORTMOUSE | WFLG_ACTIVATE | + WFLG_RMBTRAP | ((flags & SDL_NOFRAME) ? 0 + : (WFLG_DEPTHGADGET | + WFLG_CLOSEGADGET | + WFLG_DRAGBAR | + ((flags & + SDL_RESIZABLE) ? + WFLG_SIZEGADGET | + WFLG_SIZEBBOTTOM : + 0))), WA_IDCMP, + IDCMP_RAWKEY | IDCMP_CLOSEWINDOW | + IDCMP_MOUSEBUTTONS | IDCMP_NEWSIZE | + IDCMP_MOUSEMOVE, WA_PubScreen, + (ULONG) SDL_Display, WA_GimmeZeroZero, + gzz, TAG_DONE); + D(bug("Opening WB window of size: %ldx%ld!\n", w, h)); + } + + if (!SDL_Window) + return -1; + } + + this->hidden->BytesPerPixel = + GetCyberMapAttr(SDL_Window->RPort->BitMap, CYBRMATTR_BPPIX); + + if (screen->flags & SDL_DOUBLEBUF) { + if (SDL_RastPort = SDL_malloc(sizeof(struct RastPort))) { + InitRastPort(SDL_RastPort); + SDL_RastPort->BitMap = this->hidden->SB[1]->sb_BitMap; + } else + return -1; + } else + SDL_RastPort = SDL_Window->RPort; + + if (flags & SDL_HWSURFACE) + screen->flags |= SDL_HWSURFACE; + + if (!SDL_windowid) { + CGX_SetSizeHints(this, w, h, flags); + } + + /* Set our colormaps when not setting a GL mode */ /* - if ( ! (flags & SDL_OPENGL) ) { + if ( ! (flags & SDL_INTERNALOPENGL) ) { XSetWindowColormap(SDL_Display, SDL_Window, SDL_XColorMap); } */ - /* Map them both and go fullscreen, if requested */ - if ( ! SDL_windowid ) { - if ( flags & SDL_FULLSCREEN ) { - screen->flags |= SDL_FULLSCREEN; - currently_fullscreen=1; -// CGX_EnterFullScreen(this); Ci siamo gia'! - } else { - screen->flags &= ~SDL_FULLSCREEN; - } - } - screen->w = w; - screen->h = h; - screen->pitch = SDL_CalculatePitch(screen); - CGX_ResizeImage(this, screen, flags); - - /* Make OpenGL Context if needed*/ - if(flags & SDL_OPENGL) { - if(this->gl_data->gl_active == 0) { - if(CGX_GL_Init(this) < 0) - return -1; - else - screen->flags |= SDL_OPENGL; - } - else { - if(CGX_GL_Update(this) < 0) - return -1; - else - screen->flags |= SDL_OPENGL; - } - } + /* Map them both and go fullscreen, if requested */ + if (!SDL_windowid) { + if (flags & SDL_FULLSCREEN) { + screen->flags |= SDL_FULLSCREEN; + currently_fullscreen = 1; +// CGX_EnterFullScreen(this); Ci siamo gia'! + } else { + screen->flags &= ~SDL_FULLSCREEN; + } + } + screen->w = w; + screen->h = h; + screen->pitch = SDL_CalculatePitch(screen); + CGX_ResizeImage(this, screen, flags); + + /* Make OpenGL Context if needed */ + if (flags & SDL_INTERNALOPENGL) { + if (this->gl_data->gl_active == 0) { + if (CGX_GL_Init(this) < 0) + return -1; + else + screen->flags |= SDL_INTERNALOPENGL; + } else { + if (CGX_GL_Update(this) < 0) + return -1; + else + screen->flags |= SDL_INTERNALOPENGL; + } + } } -int CGX_ResizeWindow(_THIS, - SDL_Surface *screen, int w, int h, Uint32 flags) +int +CGX_ResizeWindow(_THIS, SDL_Surface * screen, int w, int h, Uint32 flags) { - D(bug("CGX_ResizeWindow\n")); - - if ( ! SDL_windowid ) { - /* Resize the window manager window */ - CGX_SetSizeHints(this, w, h, flags); - - ChangeWindowBox(SDL_Window,SDL_Window->LeftEdge,SDL_Window->TopEdge, w+SDL_Window->BorderLeft+SDL_Window->BorderRight, - h+SDL_Window->BorderTop+SDL_Window->BorderBottom); - - screen->w = w; - screen->h = h; - screen->pitch = SDL_CalculatePitch(screen); - CGX_ResizeImage(this, screen, flags); - } - return(0); + D(bug("CGX_ResizeWindow\n")); + + if (!SDL_windowid) { + /* Resize the window manager window */ + CGX_SetSizeHints(this, w, h, flags); + + ChangeWindowBox(SDL_Window, SDL_Window->LeftEdge, + SDL_Window->TopEdge, + w + SDL_Window->BorderLeft + + SDL_Window->BorderRight, + h + SDL_Window->BorderTop + SDL_Window->BorderBottom); + + screen->w = w; + screen->h = h; + screen->pitch = SDL_CalculatePitch(screen); + CGX_ResizeImage(this, screen, flags); + } + return (0); } -static SDL_Surface *CGX_SetVideoMode(_THIS, SDL_Surface *current, - int width, int height, int bpp, Uint32 flags) +static SDL_Surface * +CGX_SetVideoMode(_THIS, SDL_Surface * current, + int width, int height, int bpp, Uint32 flags) { - Uint32 saved_flags; - int needcreate=0; + Uint32 saved_flags; + int needcreate = 0; - D(bug("CGX_SetVideoMode current:%lx\n",current)); + D(bug("CGX_SetVideoMode current:%lx\n", current)); - /* Lock the event thread, in multi-threading environments */ - SDL_Lock_EventThread(); + /* Lock the event thread, in multi-threading environments */ + SDL_Lock_EventThread(); // Check if the window needs to be closed or can be resized - if( (flags&SDL_FULLSCREEN) || (current && current->flags&SDL_FULLSCREEN && !(flags&SDL_FULLSCREEN))) - needcreate=1; + if ((flags & SDL_FULLSCREEN) + || (current && current->flags & SDL_FULLSCREEN + && !(flags & SDL_FULLSCREEN))) + needcreate = 1; // Check if we need to close an already existing videomode... - if(current && current->flags&SDL_FULLSCREEN && !(flags&SDL_FULLSCREEN)) { - unsigned long i; - D(bug("Destroying image, window & screen!\n")); - - CGX_DestroyImage(this,current); - CGX_DestroyWindow(this,current); - DestroyScreen(this); - GFX_Display=SDL_Display=LockPubScreen(NULL); - - bpp=this->hidden->depth=GetCyberMapAttr(SDL_Display->RastPort.BitMap,CYBRMATTR_DEPTH); - - for ( i = 0; i < this->hidden->nvisuals; i++ ) { - if ( this->hidden->visuals[i].depth == bpp ) /* era .depth */ - break; - } - if ( i == this->hidden->nvisuals ) { - SDL_SetError("No matching visual for requested depth"); - return NULL; /* should never happen */ - } - SDL_Visual = this->hidden->visuals[i].visual; - - D(bug("Setting screen depth to: %ld\n",this->hidden->depth)); - - } - /* Check the combination of flags we were passed */ - if ( flags & SDL_FULLSCREEN ) { - int i; - - /* Clear fullscreen flag if not supported */ - if ( SDL_windowid ) { - flags &= ~SDL_FULLSCREEN; - } - else if(current && current->flags&SDL_FULLSCREEN ) { - if(current->w!=width || - current->h!=height || - (this->hidden && this->hidden->depth!=bpp)) - { - D(bug("Deleting previous window...\n")); - CGX_DestroyImage(this,current); - CGX_DestroyWindow(this,current); - DestroyScreen(this); - goto buildnewscreen; - } - } - else -buildnewscreen: - { - Uint32 okid=BestCModeIDTags(CYBRBIDTG_NominalWidth,width, - CYBRBIDTG_NominalHeight,height, - CYBRBIDTG_Depth,bpp, - TAG_DONE); - - GFX_Display=NULL; - - D(bug("Opening screen...\n")); - - if(okid!=INVALID_ID) - GFX_Display=OpenScreenTags(NULL, - SA_Width,width, - SA_Height,height, - SA_Quiet,TRUE,SA_ShowTitle,FALSE, - SA_Depth,bpp, - SA_DisplayID,okid, - TAG_DONE); - - if(!GFX_Display) { - GFX_Display=SDL_Display; - flags &= ~SDL_FULLSCREEN; - flags &= ~SDL_DOUBLEBUF; - } - else { - UnlockPubScreen(NULL,SDL_Display); - SDL_Display=GFX_Display; - - D(bug("Screen opened.\n")); - - if(flags&SDL_DOUBLEBUF) { - int ok=0; - D(bug("Start of DBuffering allocations...\n")); - - if(this->hidden->SB[0]=AllocScreenBuffer(SDL_Display,NULL,SB_SCREEN_BITMAP)) { - - if(this->hidden->SB[1]=AllocScreenBuffer(SDL_Display,NULL,0L)) { - extern struct MsgPort *safeport,*dispport; - - safeport=CreateMsgPort(); - dispport=CreateMsgPort(); - - if(!safeport || !dispport) { - if(safeport) { - DeleteMsgPort(safeport); - safeport=NULL; - } - if(dispport) { - DeleteMsgPort(dispport); - dispport=NULL; - } - FreeScreenBuffer(SDL_Display,this->hidden->SB[0]); - FreeScreenBuffer(SDL_Display,this->hidden->SB[1]); - } - else { - extern ULONG safe_sigbit,disp_sigbit; - int i; - - safe_sigbit=1L<< safeport->mp_SigBit; - disp_sigbit=1L<< dispport->mp_SigBit; - - for(i=0;i<2;i++) { - this->hidden->SB[i]->sb_DBufInfo->dbi_SafeMessage.mn_ReplyPort=safeport; - this->hidden->SB[i]->sb_DBufInfo->dbi_DispMessage.mn_ReplyPort=dispport; - } - - ok=1; - D(bug("Dbuffering enabled!\n")); - this->hidden->dbuffer=1; - current->flags|=SDL_DOUBLEBUF; - } - } - else { - FreeScreenBuffer(SDL_Display,this->hidden->SB[1]); - this->hidden->SB[0]=NULL; - } - } - - if(!ok) - flags&=~SDL_DOUBLEBUF; - } - } - - if(GetCyberMapAttr(SDL_Display->RastPort.BitMap,CYBRMATTR_DEPTH)==bpp) - this->hidden->same_format=1; - } - - bpp=this->hidden->depth=GetCyberMapAttr(SDL_Display->RastPort.BitMap,CYBRMATTR_DEPTH); - D(bug("Setting screen depth to: %ld\n",this->hidden->depth)); - - for ( i = 0; i < this->hidden->nvisuals; i++ ) - if ( this->hidden->visuals[i].depth == bpp ) /* era .depth */ - break; - - if ( i == this->hidden->nvisuals ) { - SDL_SetError("No matching visual for requested depth"); - return NULL; /* should never happen */ - } - SDL_Visual = this->hidden->visuals[i].visual; - - } - - /* Set up the X11 window */ - saved_flags = current->flags; - - if (SDL_Window && (saved_flags&SDL_OPENGL) == (flags&SDL_OPENGL) - && bpp == current->format->BitsPerPixel && !needcreate) { - if (CGX_ResizeWindow(this, current, width, height, flags) < 0) { - current = NULL; - goto done; - } - } else { - if (CGX_CreateWindow(this,current,width,height,bpp,flags) < 0) { - current = NULL; - goto done; - } - } + if (current && current->flags & SDL_FULLSCREEN + && !(flags & SDL_FULLSCREEN)) { + unsigned long i; + D(bug("Destroying image, window & screen!\n")); + + CGX_DestroyImage(this, current); + CGX_DestroyWindow(this, current); + DestroyScreen(this); + GFX_Display = SDL_Display = LockPubScreen(NULL); + + bpp = this->hidden->depth = + GetCyberMapAttr(SDL_Display->RastPort.BitMap, CYBRMATTR_DEPTH); + + for (i = 0; i < this->hidden->nvisuals; i++) { + if (this->hidden->visuals[i].depth == bpp) /* era .depth */ + break; + } + if (i == this->hidden->nvisuals) { + SDL_SetError("No matching visual for requested depth"); + return NULL; /* should never happen */ + } + SDL_Visual = this->hidden->visuals[i].visual; + + D(bug("Setting screen depth to: %ld\n", this->hidden->depth)); + + } + /* Check the combination of flags we were passed */ + if (flags & SDL_FULLSCREEN) { + int i; + + /* Clear fullscreen flag if not supported */ + if (SDL_windowid) { + flags &= ~SDL_FULLSCREEN; + } else if (current && current->flags & SDL_FULLSCREEN) { + if (current->w != width || + current->h != height || + (this->hidden && this->hidden->depth != bpp)) { + D(bug("Deleting previous window...\n")); + CGX_DestroyImage(this, current); + CGX_DestroyWindow(this, current); + DestroyScreen(this); + goto buildnewscreen; + } + } else + buildnewscreen: + { + Uint32 okid = BestCModeIDTags(CYBRBIDTG_NominalWidth, width, + CYBRBIDTG_NominalHeight, + height, + CYBRBIDTG_Depth, bpp, + TAG_DONE); + + GFX_Display = NULL; + + D(bug("Opening screen...\n")); + + if (okid != INVALID_ID) + GFX_Display = OpenScreenTags(NULL, + SA_Width, width, + SA_Height, height, + SA_Quiet, TRUE, + SA_ShowTitle, FALSE, + SA_Depth, bpp, SA_DisplayID, + okid, TAG_DONE); + + if (!GFX_Display) { + GFX_Display = SDL_Display; + flags &= ~SDL_FULLSCREEN; + flags &= ~SDL_DOUBLEBUF; + } else { + UnlockPubScreen(NULL, SDL_Display); + SDL_Display = GFX_Display; + + D(bug("Screen opened.\n")); + + if (flags & SDL_DOUBLEBUF) { + int ok = 0; + D(bug("Start of DBuffering allocations...\n")); + + if (this->hidden->SB[0] = + AllocScreenBuffer(SDL_Display, NULL, + SB_SCREEN_BITMAP)) { + + if (this->hidden->SB[1] = + AllocScreenBuffer(SDL_Display, NULL, 0L)) { + extern struct MsgPort *safeport, *dispport; + + safeport = CreateMsgPort(); + dispport = CreateMsgPort(); + + if (!safeport || !dispport) { + if (safeport) { + DeleteMsgPort(safeport); + safeport = NULL; + } + if (dispport) { + DeleteMsgPort(dispport); + dispport = NULL; + } + FreeScreenBuffer(SDL_Display, + this->hidden->SB[0]); + FreeScreenBuffer(SDL_Display, + this->hidden->SB[1]); + } else { + extern ULONG safe_sigbit, disp_sigbit; + int i; + + safe_sigbit = 1L << safeport->mp_SigBit; + disp_sigbit = 1L << dispport->mp_SigBit; + + for (i = 0; i < 2; i++) { + this->hidden->SB[i]-> + sb_DBufInfo-> + dbi_SafeMessage. + mn_ReplyPort = safeport; + this->hidden->SB[i]-> + sb_DBufInfo-> + dbi_DispMessage. + mn_ReplyPort = dispport; + } + + ok = 1; + D(bug("Dbuffering enabled!\n")); + this->hidden->dbuffer = 1; + current->flags |= SDL_DOUBLEBUF; + } + } else { + FreeScreenBuffer(SDL_Display, + this->hidden->SB[1]); + this->hidden->SB[0] = NULL; + } + } + + if (!ok) + flags &= ~SDL_DOUBLEBUF; + } + } + + if (GetCyberMapAttr + (SDL_Display->RastPort.BitMap, CYBRMATTR_DEPTH) == bpp) + this->hidden->same_format = 1; + } + + bpp = this->hidden->depth = + GetCyberMapAttr(SDL_Display->RastPort.BitMap, CYBRMATTR_DEPTH); + D(bug("Setting screen depth to: %ld\n", this->hidden->depth)); + + for (i = 0; i < this->hidden->nvisuals; i++) + if (this->hidden->visuals[i].depth == bpp) /* era .depth */ + break; + + if (i == this->hidden->nvisuals) { + SDL_SetError("No matching visual for requested depth"); + return NULL; /* should never happen */ + } + SDL_Visual = this->hidden->visuals[i].visual; + + } + + /* Set up the X11 window */ + saved_flags = current->flags; + + if (SDL_Window + && (saved_flags & SDL_INTERNALOPENGL) == (flags & SDL_INTERNALOPENGL) + && bpp == current->format->BitsPerPixel && !needcreate) { + if (CGX_ResizeWindow(this, current, width, height, flags) < 0) { + current = NULL; + goto done; + } + } else { + if (CGX_CreateWindow(this, current, width, height, bpp, flags) < 0) { + current = NULL; + goto done; + } + } #if 0 - /* Set up the new mode framebuffer */ - if ( ((current->w != width) || (current->h != height)) || - ((saved_flags&SDL_OPENGL) != (flags&SDL_OPENGL)) ) { - current->w = width; - current->h = height; - current->pitch = SDL_CalculatePitch(current); - CGX_ResizeImage(this, current, flags); - } + /* Set up the new mode framebuffer */ + if (((current->w != width) || (current->h != height)) || + ((saved_flags & SDL_INTERNALOPENGL) != (flags & SDL_INTERNALOPENGL))) + { + current->w = width; + current->h = height; + current->pitch = SDL_CalculatePitch(current); + CGX_ResizeImage(this, current, flags); + } #endif - current->flags |= (flags&SDL_RESIZABLE); // Resizable only if the user asked it + current->flags |= (flags & SDL_RESIZABLE); // Resizable only if the user asked it done: - /* Release the event thread */ - SDL_Unlock_EventThread(); + /* Release the event thread */ + SDL_Unlock_EventThread(); - /* We're done! */ - return(current); + /* We're done! */ + return (current); } -static int CGX_ToggleFullScreen(_THIS, int on) +static int +CGX_ToggleFullScreen(_THIS, int on) { - Uint32 event_thread; - - /* Don't switch if we don't own the window */ - if ( SDL_windowid ) { - return(0); - } - - /* Don't lock if we are the event thread */ - event_thread = SDL_EventThreadID(); - if ( event_thread && (SDL_ThreadID() == event_thread) ) { - event_thread = 0; - } - if ( event_thread ) { - SDL_Lock_EventThread(); - } - if ( on ) { - this->screen->flags |= SDL_FULLSCREEN; - CGX_EnterFullScreen(this); - } else { - this->screen->flags &= ~SDL_FULLSCREEN; - CGX_LeaveFullScreen(this); - } - - CGX_RefreshDisplay(this); - if ( event_thread ) { - SDL_Unlock_EventThread(); - } - - SDL_ResetKeyboard(); - - return(1); + Uint32 event_thread; + + /* Don't switch if we don't own the window */ + if (SDL_windowid) { + return (0); + } + + /* Don't lock if we are the event thread */ + event_thread = SDL_EventThreadID(); + if (event_thread && (SDL_ThreadID() == event_thread)) { + event_thread = 0; + } + if (event_thread) { + SDL_Lock_EventThread(); + } + if (on) { + this->screen->flags |= SDL_FULLSCREEN; + CGX_EnterFullScreen(this); + } else { + this->screen->flags &= ~SDL_FULLSCREEN; + CGX_LeaveFullScreen(this); + } + + CGX_RefreshDisplay(this); + if (event_thread) { + SDL_Unlock_EventThread(); + } + + SDL_ResetKeyboard(); + + return (1); } -static void SetSingleColor(Uint32 fmt, unsigned char r, unsigned char g, unsigned char b, unsigned char *c) +static void +SetSingleColor(Uint32 fmt, unsigned char r, unsigned char g, unsigned char b, + unsigned char *c) { - switch(fmt) - { - case PIXFMT_BGR15: - case PIXFMT_RGB15PC: - { - Uint16 *t=(Uint16 *)c; - *t=(r>>3) | ((g>>3)<<5) | ((b>>3)<<10) ; - } - break; - case PIXFMT_RGB15: - case PIXFMT_BGR15PC: - { - Uint16 *t=(Uint16 *)c; - *t=(b>>3) | ((g>>3)<<5) | ((r>>3)<<10) ; - } - break; - case PIXFMT_BGR16PC: - case PIXFMT_RGB16: - { - Uint16 *t=(Uint16 *)c; - *t=(b>>3) | ((g>>2)<<5) | ((r>>3)<<11) ; - } - break; - case PIXFMT_BGR16: - case PIXFMT_RGB16PC: - { - Uint16 *t=(Uint16 *)c; - *t=(r>>3) | ((g>>2)<<5) | ((b>>3)<<11) ; - } - break; - case PIXFMT_RGB24: - c[0]=r; - c[1]=g; - c[2]=b; - c[3]=0; - break; - case PIXFMT_BGR24: - c[0]=b; - c[1]=g; - c[2]=r; - c[3]=0; - break; - case PIXFMT_ARGB32: - c[0]=0; - c[1]=r; - c[2]=g; - c[3]=b; - break; - case PIXFMT_BGRA32: - c[0]=b; - c[1]=g; - c[2]=r; - c[3]=0; - break; - case PIXFMT_RGBA32: - c[0]=r; - c[1]=g; - c[2]=b; - c[3]=0; - break; - - default: - D(bug("Error, SetSingleColor with PIXFMT %ld!\n",fmt)); - } + switch (fmt) { + case PIXFMT_BGR15: + case PIXFMT_RGB15PC: + { + Uint16 *t = (Uint16 *) c; + *t = (r >> 3) | ((g >> 3) << 5) | ((b >> 3) << 10); + } + break; + case PIXFMT_RGB15: + case PIXFMT_BGR15PC: + { + Uint16 *t = (Uint16 *) c; + *t = (b >> 3) | ((g >> 3) << 5) | ((r >> 3) << 10); + } + break; + case PIXFMT_BGR16PC: + case PIXFMT_RGB16: + { + Uint16 *t = (Uint16 *) c; + *t = (b >> 3) | ((g >> 2) << 5) | ((r >> 3) << 11); + } + break; + case PIXFMT_BGR16: + case PIXFMT_RGB16PC: + { + Uint16 *t = (Uint16 *) c; + *t = (r >> 3) | ((g >> 2) << 5) | ((b >> 3) << 11); + } + break; + case PIXFMT_RGB24: + c[0] = r; + c[1] = g; + c[2] = b; + c[3] = 0; + break; + case PIXFMT_BGR24: + c[0] = b; + c[1] = g; + c[2] = r; + c[3] = 0; + break; + case PIXFMT_ARGB32: + c[0] = 0; + c[1] = r; + c[2] = g; + c[3] = b; + break; + case PIXFMT_BGRA32: + c[0] = b; + c[1] = g; + c[2] = r; + c[3] = 0; + break; + case PIXFMT_RGBA32: + c[0] = r; + c[1] = g; + c[2] = b; + c[3] = 0; + break; + + default: + D(bug("Error, SetSingleColor with PIXFMT %ld!\n", fmt)); + } } /* Update the current mouse state and position */ -static void CGX_UpdateMouse(_THIS) +static void +CGX_UpdateMouse(_THIS) { - /* Lock the event thread, in multi-threading environments */ - SDL_Lock_EventThread(); - - if(currently_fullscreen) - { - SDL_PrivateAppActive(1, SDL_APPMOUSEFOCUS); - SDL_PrivateMouseMotion(0, 0, SDL_Display->MouseX, SDL_Display->MouseY); - } - else - { - if( SDL_Display->MouseX>=(SDL_Window->LeftEdge+SDL_Window->BorderLeft) && SDL_Display->MouseX<(SDL_Window->LeftEdge+SDL_Window->Width-SDL_Window->BorderRight) && - SDL_Display->MouseY>=(SDL_Window->TopEdge+SDL_Window->BorderLeft) && SDL_Display->MouseY<(SDL_Window->TopEdge+SDL_Window->Height-SDL_Window->BorderBottom) - ) - { - SDL_PrivateAppActive(1, SDL_APPMOUSEFOCUS); - SDL_PrivateMouseMotion(0, 0, SDL_Display->MouseX-SDL_Window->LeftEdge-SDL_Window->BorderLeft, - SDL_Display->MouseY-SDL_Window->TopEdge-SDL_Window->BorderTop); - } - else - { - SDL_PrivateAppActive(0, SDL_APPMOUSEFOCUS); - } - } - SDL_Unlock_EventThread(); + /* Lock the event thread, in multi-threading environments */ + SDL_Lock_EventThread(); + + if (currently_fullscreen) { + SDL_PrivateAppActive(1, SDL_APPMOUSEFOCUS); + SDL_PrivateMouseMotion(0, 0, SDL_Display->MouseX, + SDL_Display->MouseY); + } else { + if (SDL_Display->MouseX >= + (SDL_Window->LeftEdge + SDL_Window->BorderLeft) + && SDL_Display->MouseX < + (SDL_Window->LeftEdge + SDL_Window->Width - + SDL_Window->BorderRight) + && SDL_Display->MouseY >= + (SDL_Window->TopEdge + SDL_Window->BorderLeft) + && SDL_Display->MouseY < + (SDL_Window->TopEdge + SDL_Window->Height - + SDL_Window->BorderBottom)) { + SDL_PrivateAppActive(1, SDL_APPMOUSEFOCUS); + SDL_PrivateMouseMotion(0, 0, + SDL_Display->MouseX - + SDL_Window->LeftEdge - + SDL_Window->BorderLeft, + SDL_Display->MouseY - + SDL_Window->TopEdge - + SDL_Window->BorderTop); + } else { + SDL_PrivateAppActive(0, SDL_APPMOUSEFOCUS); + } + } + SDL_Unlock_EventThread(); } -static int CGX_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color *colors) +static int +CGX_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color * colors) { - int i; + int i; - /* Check to make sure we have a colormap allocated */ + /* Check to make sure we have a colormap allocated */ - /* It's easy if we have a hidden colormap */ - if ( (this->screen->flags & SDL_HWPALETTE) && currently_fullscreen ) - { - ULONG xcmap[256*3+2]; + /* It's easy if we have a hidden colormap */ + if ((this->screen->flags & SDL_HWPALETTE) && currently_fullscreen) { + ULONG xcmap[256 * 3 + 2]; - xcmap[0]=(ncolors<<16); - xcmap[0]+=firstcolor; + xcmap[0] = (ncolors << 16); + xcmap[0] += firstcolor; -// D(bug("Setting %ld colors on an HWPALETTE screen\n",ncolors)); +// D(bug("Setting %ld colors on an HWPALETTE screen\n",ncolors)); - for ( i=0; iViewPort,xcmap); - } else { + for (i = 0; i < ncolors; i++) { + xcmap[i * 3 + 1] = colors[i + firstcolor].r << 24; + xcmap[i * 3 + 2] = colors[i + firstcolor].g << 24; + xcmap[i * 3 + 3] = colors[i + firstcolor].b << 24; + } + xcmap[ncolors * 3 + 1] = 0; + LoadRGB32(&GFX_Display->ViewPort, xcmap); + } else { // XPixels are not needed on 8bit screen with hwpalette - unsigned long pixel; + unsigned long pixel; - if ( SDL_XPixels == NULL ) { - D(bug("SetColors without colormap!")); - return(0); - } + if (SDL_XPixels == NULL) { + D(bug("SetColors without colormap!")); + return (0); + } - if(this->hidden->depth==8) - { + if (this->hidden->depth == 8) { // In this case I have to unalloc and realloc the full palette - D(bug("Obtaining %ld colors on the screen\n",ncolors)); - - /* Free existing allocated colors */ - for ( pixel=0; pixelscreen->format->palette->ncolors; ++pixel ) { - if(SDL_XPixels[pixel]>=0) - ReleasePen(GFX_Display->ViewPort.ColorMap,SDL_XPixels[pixel]); - } - - /* Try to allocate all the colors */ - for ( i=0; iscreen->format->palette->ncolors; ++i ) { - SDL_XPixels[i]=ObtainBestPenA(GFX_Display->ViewPort.ColorMap,colors[i].r<<24,colors[i].g<<24,colors[i].b<<24,NULL); - } - } - else - { + D(bug("Obtaining %ld colors on the screen\n", ncolors)); + + /* Free existing allocated colors */ + for (pixel = 0; + pixel < this->screen->format->palette->ncolors; ++pixel) { + if (SDL_XPixels[pixel] >= 0) + ReleasePen(GFX_Display->ViewPort.ColorMap, + SDL_XPixels[pixel]); + } + + /* Try to allocate all the colors */ + for (i = 0; i < this->screen->format->palette->ncolors; ++i) { + SDL_XPixels[i] = + ObtainBestPenA(GFX_Display->ViewPort.ColorMap, + colors[i].r << 24, + colors[i].g << 24, + colors[i].b << 24, NULL); + } + } else { #ifndef USE_CGX_WRITELUTPIXEL - Uint32 fmt; - D(bug("Preparing a conversion pixel table...\n")); - - fmt=GetCyberMapAttr(SDL_Display->RastPort.BitMap,CYBRMATTR_PIXFMT); - - for(i=0;iRastPort.BitMap, + CYBRMATTR_PIXFMT); + + for (i = 0; i < ncolors; i++) { + SetSingleColor(fmt, colors[firstcolor + i].r, + colors[firstcolor + i].g, + colors[firstcolor + i].b, (unsigned char *) + &SDL_XPixels[firstcolor + i]); + } #else -// D(bug("Executing XPixel(%lx) remapping: (from %ld, %ld colors) first: r%ld g%ld b%ld\n",SDL_XPixels,firstcolor,ncolors,colors[firstcolor].r,colors[firstcolor].g,colors[firstcolor].b)); - for(i=0;igl_data->gl_active == 1) { - CGX_GL_Quit(this); - } - /* Start shutting down the windows */ - D(bug("Destroying image...\n")); - CGX_DestroyImage(this, this->screen); - D(bug("Destroying window...\n")); - CGX_DestroyWindow(this, this->screen); + /* Shutdown everything that's still up */ + /* The event thread should be done, so we can touch SDL_Display */ + D(bug("CGX_VideoQuit\n")); + + if (SDL_Display != NULL) { + /* Clean up OpenGL */ + if (this->gl_data->gl_active == 1) { + CGX_GL_Quit(this); + } + /* Start shutting down the windows */ + D(bug("Destroying image...\n")); + CGX_DestroyImage(this, this->screen); + D(bug("Destroying window...\n")); + CGX_DestroyWindow(this, this->screen); // Otherwise SDL_VideoQuit will try to free it! - SDL_VideoSurface=NULL; + SDL_VideoSurface = NULL; - CGX_FreeVideoModes(this); + CGX_FreeVideoModes(this); - /* Free that blank cursor */ - if ( SDL_BlankCursor != NULL ) { - FreeMem(SDL_BlankCursor,16); - SDL_BlankCursor = NULL; - } + /* Free that blank cursor */ + if (SDL_BlankCursor != NULL) { + FreeMem(SDL_BlankCursor, 16); + SDL_BlankCursor = NULL; + } - /* Close the X11 graphics connection */ - this->hidden->same_format=0; + /* Close the X11 graphics connection */ + this->hidden->same_format = 0; - D(bug("Destroying screen...\n")); + D(bug("Destroying screen...\n")); - if ( GFX_Display != NULL ) - DestroyScreen(this); + if (GFX_Display != NULL) + DestroyScreen(this); - /* Close the X11 display connection */ - SDL_Display = NULL; + /* Close the X11 display connection */ + SDL_Display = NULL; - /* Unload GL library after X11 shuts down */ - } + /* Unload GL library after X11 shuts down */ + } - D(bug("Closing libraries...\n")); + D(bug("Closing libraries...\n")); - if( CyberGfxBase) { - CloseLibrary(CyberGfxBase); - CyberGfxBase=NULL; - } + if (CyberGfxBase) { + CloseLibrary(CyberGfxBase); + CyberGfxBase = NULL; + } - if (IntuitionBase) { - CloseLibrary((struct Library *)IntuitionBase); - IntuitionBase=NULL; - } - if (GfxBase) { - CloseLibrary((struct Library *)GfxBase); - GfxBase=NULL; - } + if (IntuitionBase) { + CloseLibrary((struct Library *) IntuitionBase); + IntuitionBase = NULL; + } + if (GfxBase) { + CloseLibrary((struct Library *) GfxBase); + GfxBase = NULL; + } - if ( this->screen && (this->screen->flags & SDL_HWSURFACE) ) { - /* Direct screen access, no memory buffer */ - this->screen->pixels = NULL; - } - D(bug("End of CGX_VideoQuit.\n")); + if (this->screen && (this->screen->flags & SDL_HWSURFACE)) { + /* Direct screen access, no memory buffer */ + this->screen->pixels = NULL; + } + D(bug("End of CGX_VideoQuit.\n")); } +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/cybergfx/SDL_cgxvideo.h b/src/video/cybergfx/SDL_cgxvideo.h index 9ef76ea55..0957263cc 100644 --- a/src/video/cybergfx/SDL_cgxvideo.h +++ b/src/video/cybergfx/SDL_cgxvideo.h @@ -54,25 +54,28 @@ #define _THIS SDL_VideoDevice *this /* Private display data */ -struct SDL_PrivateVideoData { - struct Screen *Public_Display; /* Used for events and window management */ - struct Screen *GFX_Display; /* Used for graphics and colormap stuff */ - Uint32 SDL_VisualUnused; /* The visual used by our window */ - struct Window *SDL_Window; /* Shared by both displays (no X security?) */ - unsigned char *BlankCursor; /* The invisible cursor */ +struct SDL_PrivateVideoData +{ + struct Screen *Public_Display; /* Used for events and window management */ + struct Screen *GFX_Display; /* Used for graphics and colormap stuff */ + Uint32 SDL_VisualUnused; /* The visual used by our window */ + struct Window *SDL_Window; /* Shared by both displays (no X security?) */ + unsigned char *BlankCursor; /* The invisible cursor */ - char *SDL_windowid; /* Flag: true if we have been passed a window */ + char *SDL_windowid; /* Flag: true if we have been passed a window */ /* The variables used for displaying graphics */ - Uint8 *Ximage; /* The X image for our window */ - int swap_pixels; /* Flag: true if display is swapped endian */ + Uint8 *Ximage; /* The X image for our window */ + int swap_pixels; /* Flag: true if display is swapped endian */ /* Support for internal mouse warping */ - struct { + struct + { int x; int y; } mouse_last; - struct { + struct + { int numerator; int denominator; int threshold; @@ -83,17 +86,18 @@ struct SDL_PrivateVideoData { SDL_Rect **modelist; /* available visuals of interest to us, sorted deepest first */ - struct { - Uint32 visual; - int depth; /* number of significant bits/pixel */ - int bpp; /* pixel quantum in bits */ - } visuals[5]; /* at most entries for 8, 15, 16, 24 */ + struct + { + Uint32 visual; + int depth; /* number of significant bits/pixel */ + int bpp; /* pixel quantum in bits */ + } visuals[5]; /* at most entries for 8, 15, 16, 24 */ int nvisuals; - Uint32 vis; /* current visual in use */ - int depth; /* current visual depth (not bpp) */ + Uint32 vis; /* current visual in use */ + int depth; /* current visual depth (not bpp) */ int BytesPerPixel; - int currently_fullscreen,same_format,dbuffer; + int currently_fullscreen, same_format, dbuffer; /* Automatic mode switching support (entering/leaving fullscreen) */ Uint32 switch_waiting; @@ -104,10 +108,10 @@ struct SDL_PrivateVideoData { /* Colormap handling */ LONG Pens; - Sint32 *XPixels; /* A list of pixels that have been allocated, the size depends on the screen format */ - struct ScreenBuffer *SB[2]; - struct RastPort *RP; - short *iconcolors; /* List of colors used by the icon */ + Sint32 *XPixels; /* A list of pixels that have been allocated, the size depends on the screen format */ + struct ScreenBuffer *SB[2]; + struct RastPort *RP; + short *iconcolors; /* List of colors used by the icon */ }; /* Old variable names */ @@ -144,12 +148,12 @@ struct SDL_PrivateVideoData { /* Used to get the X cursor from a window-manager specific cursor */ // extern Cursor SDL_GetWMXCursor(WMcursor *cursor); -extern int CGX_CreateWindow(_THIS, SDL_Surface *screen, - int w, int h, int bpp, Uint32 flags); +extern int CGX_CreateWindow(_THIS, SDL_Surface * screen, + int w, int h, int bpp, Uint32 flags); extern int CGX_ResizeWindow(_THIS, - SDL_Surface *screen, int w, int h, Uint32 flags); + SDL_Surface * screen, int w, int h, Uint32 flags); -extern void CGX_DestroyWindow(_THIS, SDL_Surface *screen); +extern void CGX_DestroyWindow(_THIS, SDL_Surface * screen); extern struct Library *CyberGfxBase; extern struct IntuitionBase *IntuitionBase; @@ -159,14 +163,16 @@ extern struct DosLibrary *DOSBase; struct private_hwdata { - struct BitMap *bmap; - APTR lock; - struct SDL_VideoDevice *videodata; - APTR mask; - int allocated; + struct BitMap *bmap; + APTR lock; + struct SDL_VideoDevice *videodata; + APTR mask; + int allocated; }; -int CGX_CheckHWBlit(_THIS,SDL_Surface *src,SDL_Surface *dst); -int CGX_FillHWRect(_THIS,SDL_Surface *dst,SDL_Rect *dstrect,Uint32 color); -int CGX_SetHWColorKey(_THIS,SDL_Surface *surface, Uint32 key); +int CGX_CheckHWBlit(_THIS, SDL_Surface * src, SDL_Surface * dst); +int CGX_FillHWRect(_THIS, SDL_Surface * dst, SDL_Rect * dstrect, + Uint32 color); +int CGX_SetHWColorKey(_THIS, SDL_Surface * surface, Uint32 key); #endif /* _SDL_x11video_h */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/cybergfx/SDL_cgxwm.c b/src/video/cybergfx/SDL_cgxwm.c index 47a7d6002..255421d8a 100644 --- a/src/video/cybergfx/SDL_cgxwm.c +++ b/src/video/cybergfx/SDL_cgxwm.c @@ -33,31 +33,37 @@ /* This is necessary for working properly with Enlightenment, etc. */ #define USE_ICON_WINDOW -void CGX_SetIcon(_THIS, SDL_Surface *icon, Uint8 *mask) +void +CGX_SetIcon(_THIS, SDL_Surface * icon, Uint8 * mask) { /* Not yet implemented */ } -void CGX_SetCaption(_THIS, const char *title, const char *icon) +void +CGX_SetCaption(_THIS, const char *title, const char *icon) { - if(SDL_Window) - SetWindowTitles(SDL_Window,(char *)title,NULL); + if (SDL_Window) + SetWindowTitles(SDL_Window, (char *) title, NULL); } /* Iconify the window */ -int CGX_IconifyWindow(_THIS) +int +CGX_IconifyWindow(_THIS) { /* Not yet implemented */ - return 0; + return 0; } -int CGX_GetWMInfo(_THIS, SDL_SysWMinfo *info) +int +CGX_GetWMInfo(_THIS, SDL_SysWMinfo * info) { - if ( info->version.major <= SDL_MAJOR_VERSION ) { - return(1); - } else { - SDL_SetError("Application not compiled with SDL %d.%d\n", - SDL_MAJOR_VERSION, SDL_MINOR_VERSION); - return(-1); - } + if (info->version.major <= SDL_MAJOR_VERSION) { + return (1); + } else { + SDL_SetError("Application not compiled with SDL %d.%d\n", + SDL_MAJOR_VERSION, SDL_MINOR_VERSION); + return (-1); + } } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/cybergfx/SDL_cgxwm_c.h b/src/video/cybergfx/SDL_cgxwm_c.h index 35d1a616e..beca3aa15 100644 --- a/src/video/cybergfx/SDL_cgxwm_c.h +++ b/src/video/cybergfx/SDL_cgxwm_c.h @@ -25,9 +25,9 @@ /* Functions to be exported */ extern void CGX_SetCaption(_THIS, const char *title, const char *icon); -extern void CGX_SetIcon(_THIS, SDL_Surface *icon, Uint8 *mask); +extern void CGX_SetIcon(_THIS, SDL_Surface * icon, Uint8 * mask); extern int CGX_IconifyWindow(_THIS); extern SDL_GrabMode CGX_GrabInputNoLock(_THIS, SDL_GrabMode mode); extern SDL_GrabMode CGX_GrabInput(_THIS, SDL_GrabMode mode); -extern int CGX_GetWMInfo(_THIS, SDL_SysWMinfo *info); - +extern int CGX_GetWMInfo(_THIS, SDL_SysWMinfo * info); +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/dc/SDL_dcevents.c b/src/video/dc/SDL_dcevents.c index 1e8e2b5d8..e39b538e5 100644 --- a/src/video/dc/SDL_dcevents.c +++ b/src/video/dc/SDL_dcevents.c @@ -31,122 +31,143 @@ #include #include -const static unsigned short sdl_key[]= { - /*0*/ 0, 0, 0, 0, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', - 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', - 'u', 'v', 'w', 'x', 'y', 'z', - /*1e*/ '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', - /*28*/ SDLK_RETURN, SDLK_ESCAPE, SDLK_BACKSPACE, SDLK_TAB, SDLK_SPACE, SDLK_MINUS, SDLK_PLUS, SDLK_LEFTBRACKET, - SDLK_RIGHTBRACKET, SDLK_BACKSLASH , 0, SDLK_SEMICOLON, SDLK_QUOTE, - /*35*/ '~', SDLK_COMMA, SDLK_PERIOD, SDLK_SLASH, SDLK_CAPSLOCK, - SDLK_F1, SDLK_F2, SDLK_F3, SDLK_F4, SDLK_F5, SDLK_F6, SDLK_F7, SDLK_F8, SDLK_F9, SDLK_F10, SDLK_F11, SDLK_F12, - /*46*/ SDLK_PRINT, SDLK_SCROLLOCK, SDLK_PAUSE, SDLK_INSERT, SDLK_HOME, SDLK_PAGEUP, SDLK_DELETE, SDLK_END, SDLK_PAGEDOWN, SDLK_RIGHT, SDLK_LEFT, SDLK_DOWN, SDLK_UP, - /*53*/ SDLK_NUMLOCK, SDLK_KP_DIVIDE, SDLK_KP_MULTIPLY, SDLK_KP_MINUS, SDLK_KP_PLUS, SDLK_KP_ENTER, - SDLK_KP1, SDLK_KP2, SDLK_KP3, SDLK_KP4, SDLK_KP5, SDLK_KP6, - /*5f*/ SDLK_KP7, SDLK_KP8, SDLK_KP9, SDLK_KP0, SDLK_KP_PERIOD, 0 /* S3 */ +const static unsigned short sdl_key[] = { + /*0 */ 0, 0, 0, 0, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', + 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', + 'u', 'v', 'w', 'x', 'y', 'z', + /*1e */ '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', + /*28 */ SDLK_RETURN, SDLK_ESCAPE, SDLK_BACKSPACE, SDLK_TAB, SDLK_SPACE, + SDLK_MINUS, SDLK_PLUS, SDLK_LEFTBRACKET, + SDLK_RIGHTBRACKET, SDLK_BACKSLASH, 0, SDLK_SEMICOLON, SDLK_QUOTE, + /*35 */ '~', SDLK_COMMA, SDLK_PERIOD, SDLK_SLASH, SDLK_CAPSLOCK, + SDLK_F1, SDLK_F2, SDLK_F3, SDLK_F4, SDLK_F5, SDLK_F6, SDLK_F7, SDLK_F8, + SDLK_F9, SDLK_F10, SDLK_F11, SDLK_F12, + /*46 */ SDLK_PRINT, SDLK_SCROLLOCK, SDLK_PAUSE, SDLK_INSERT, SDLK_HOME, + SDLK_PAGEUP, SDLK_DELETE, SDLK_END, SDLK_PAGEDOWN, SDLK_RIGHT, + SDLK_LEFT, SDLK_DOWN, SDLK_UP, + /*53 */ SDLK_NUMLOCK, SDLK_KP_DIVIDE, SDLK_KP_MULTIPLY, SDLK_KP_MINUS, + SDLK_KP_PLUS, SDLK_KP_ENTER, + SDLK_KP1, SDLK_KP2, SDLK_KP3, SDLK_KP4, SDLK_KP5, SDLK_KP6, + /*5f */ SDLK_KP7, SDLK_KP8, SDLK_KP9, SDLK_KP0, SDLK_KP_PERIOD, 0 + /* S3 */ }; const static unsigned short sdl_shift[] = { - SDLK_LCTRL,SDLK_LSHIFT,SDLK_LALT,0 /* S1 */, - SDLK_RCTRL,SDLK_RSHIFT,SDLK_RALT,0 /* S2 */, + SDLK_LCTRL, SDLK_LSHIFT, SDLK_LALT, 0 /* S1 */ , + SDLK_RCTRL, SDLK_RSHIFT, SDLK_RALT, 0 /* S2 */ , }; #define MOUSE_WHEELUP (1<<4) #define MOUSE_WHEELDOWN (1<<5) -static void mouse_update(void) +static void +mouse_update(void) { -const static char sdl_mousebtn[] = { - MOUSE_LEFTBUTTON, - MOUSE_RIGHTBUTTON, - MOUSE_SIDEBUTTON, - MOUSE_WHEELUP, - MOUSE_WHEELDOWN -}; - - uint8 addr; - mouse_cond_t cond; - - static int prev_buttons; - int buttons,changed; - int i; - - if ((addr = maple_first_mouse())==0 || mouse_get_cond(addr, &cond)<0) return; - - buttons = cond.buttons^0xff; - if (cond.dz<0) buttons|=MOUSE_WHEELUP; - if (cond.dz>0) buttons|=MOUSE_WHEELDOWN; - - if (cond.dx||cond.dy) SDL_PrivateMouseMotion(0,1,cond.dx,cond.dy); - - changed = buttons^prev_buttons; - for(i=0;i 0) + buttons |= MOUSE_WHEELDOWN; + + if (cond.dx || cond.dy) + SDL_PrivateMouseMotion(0, 1, cond.dx, cond.dy); + + changed = buttons ^ prev_buttons; + for (i = 0; i < sizeof(sdl_mousebtn); i++) { + if (changed & sdl_mousebtn[i]) { + SDL_PrivateMouseButton((buttons & sdl_mousebtn[i]) ? + SDL_PRESSED : SDL_RELEASED, i, 0, 0); + } + } + prev_buttons = buttons; } -static void keyboard_update(void) +static void +keyboard_update(void) { - static kbd_state_t old_state; - static uint8 old_addr; - - kbd_state_t *state; - uint8 addr; - int port,unit; - - int shiftkeys; - SDL_keysym keysym; - - int i; - - addr = maple_first_kb(); - - if (addr==0) return; - - if (addr!=old_addr) { - old_addr = addr; - SDL_memset(&old_state,0,sizeof(old_state)); - } - - maple_raddr(addr,&port,&unit); - - state = maple_dev_state(port,unit); - if (!state) return; - - shiftkeys = state->shift_keys ^ old_state.shift_keys; - for(i=0;i>i)&1) { - keysym.sym = sdl_shift[i]; - SDL_PrivateKeyboard(((state->shift_keys>>i)&1)?SDL_PRESSED:SDL_RELEASED,&keysym); - } - } - - for(i=0;imatrix[i]!=old_state.matrix[i]) { - int key = sdl_key[i]; - if (key) { - keysym.sym = key; - SDL_PrivateKeyboard(state->matrix[i]?SDL_PRESSED:SDL_RELEASED,&keysym); - } - } - } - - old_state = *state; + static kbd_state_t old_state; + static uint8 old_addr; + + kbd_state_t *state; + uint8 addr; + int port, unit; + + int shiftkeys; + SDL_keysym keysym; + + int i; + + addr = maple_first_kb(); + + if (addr == 0) + return; + + if (addr != old_addr) { + old_addr = addr; + SDL_memset(&old_state, 0, sizeof(old_state)); + } + + maple_raddr(addr, &port, &unit); + + state = maple_dev_state(port, unit); + if (!state) + return; + + shiftkeys = state->shift_keys ^ old_state.shift_keys; + for (i = 0; i < sizeof(sdl_shift); i++) { + if ((shiftkeys >> i) & 1) { + keysym.sym = sdl_shift[i]; + SDL_PrivateKeyboard(((state-> + shift_keys >> i) & 1) ? SDL_PRESSED : + SDL_RELEASED, &keysym); + } + } + + for (i = 0; i < sizeof(sdl_key); i++) { + if (state->matrix[i] != old_state.matrix[i]) { + int key = sdl_key[i]; + if (key) { + keysym.sym = key; + SDL_PrivateKeyboard(state-> + matrix[i] ? SDL_PRESSED : + SDL_RELEASED, &keysym); + } + } + } + + old_state = *state; } -void DC_PumpEvents(_THIS) +void +DC_PumpEvents(_THIS) { - keyboard_update(); - mouse_update(); + keyboard_update(); + mouse_update(); } -void DC_InitOSKeymap(_THIS) +void +DC_InitOSKeymap(_THIS) { - /* do nothing. */ + /* do nothing. */ } /* end of SDL_dcevents.c ... */ - +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/dc/SDL_dcevents_c.h b/src/video/dc/SDL_dcevents_c.h index 57dc6d603..874f0b771 100644 --- a/src/video/dc/SDL_dcevents_c.h +++ b/src/video/dc/SDL_dcevents_c.h @@ -30,4 +30,4 @@ extern void DC_InitOSKeymap(_THIS); extern void DC_PumpEvents(_THIS); /* end of SDL_dcevents_c.h ... */ - +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/dc/SDL_dcmouse.c b/src/video/dc/SDL_dcmouse.c index ccb969d79..f0a16b668 100644 --- a/src/video/dc/SDL_dcmouse.c +++ b/src/video/dc/SDL_dcmouse.c @@ -30,6 +30,8 @@ /* The implementation dependent data for the window manager cursor */ -struct WMcursor { - int unused; +struct WMcursor +{ + int unused; }; +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/dc/SDL_dcmouse_c.h b/src/video/dc/SDL_dcmouse_c.h index e985c7593..0337fd607 100644 --- a/src/video/dc/SDL_dcmouse_c.h +++ b/src/video/dc/SDL_dcmouse_c.h @@ -24,3 +24,4 @@ #include "SDL_dcvideo.h" /* Functions to be exported */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/dc/SDL_dcvideo.c b/src/video/dc/SDL_dcvideo.c index 3d884c339..7a4d4d993 100644 --- a/src/video/dc/SDL_dcvideo.c +++ b/src/video/dc/SDL_dcvideo.c @@ -36,410 +36,442 @@ /* Initialization/Query functions */ -static int DC_VideoInit(_THIS, SDL_PixelFormat *vformat); -static SDL_Rect **DC_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags); -static SDL_Surface *DC_SetVideoMode(_THIS, SDL_Surface *current, int width, int height, int bpp, Uint32 flags); -static int DC_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color *colors); +static int DC_VideoInit(_THIS, SDL_PixelFormat * vformat); +static SDL_Rect **DC_ListModes(_THIS, SDL_PixelFormat * format, Uint32 flags); +static SDL_Surface *DC_SetVideoMode(_THIS, SDL_Surface * current, int width, + int height, int bpp, Uint32 flags); +static int DC_SetColors(_THIS, int firstcolor, int ncolors, + SDL_Color * colors); static void DC_VideoQuit(_THIS); /* Hardware surface functions */ -static int DC_AllocHWSurface(_THIS, SDL_Surface *surface); -static int DC_LockHWSurface(_THIS, SDL_Surface *surface); -static void DC_UnlockHWSurface(_THIS, SDL_Surface *surface); -static void DC_FreeHWSurface(_THIS, SDL_Surface *surface); -static int DC_FlipHWSurface(_THIS, SDL_Surface *surface); +static int DC_AllocHWSurface(_THIS, SDL_Surface * surface); +static int DC_LockHWSurface(_THIS, SDL_Surface * surface); +static void DC_UnlockHWSurface(_THIS, SDL_Surface * surface); +static void DC_FreeHWSurface(_THIS, SDL_Surface * surface); +static int DC_FlipHWSurface(_THIS, SDL_Surface * surface); /* etc. */ -static void DC_UpdateRects(_THIS, int numrects, SDL_Rect *rects); +static void DC_UpdateRects(_THIS, int numrects, SDL_Rect * rects); /* OpenGL */ #if SDL_VIDEO_OPENGL static void *DC_GL_GetProcAddress(_THIS, const char *proc); static int DC_GL_LoadLibrary(_THIS, const char *path); -static int DC_GL_GetAttribute(_THIS, SDL_GLattr attrib, int* value); +static int DC_GL_GetAttribute(_THIS, SDL_GLattr attrib, int *value); static void DC_GL_SwapBuffers(_THIS); #endif /* DC driver bootstrap functions */ -static int DC_Available(void) +static int +DC_Available(void) { - return 1; + return 1; } -static void DC_DeleteDevice(SDL_VideoDevice *device) +static void +DC_DeleteDevice(SDL_VideoDevice * device) { - SDL_free(device->hidden); - SDL_free(device); + SDL_free(device->hidden); + SDL_free(device); } -static SDL_VideoDevice *DC_CreateDevice(int devindex) +static SDL_VideoDevice * +DC_CreateDevice(int devindex) { - SDL_VideoDevice *device; - - /* Initialize all variables that we clean on shutdown */ - device = (SDL_VideoDevice *)SDL_malloc(sizeof(SDL_VideoDevice)); - if ( device ) { - SDL_memset(device, 0, (sizeof *device)); - device->hidden = (struct SDL_PrivateVideoData *) - SDL_malloc((sizeof *device->hidden)); - } - if ( (device == NULL) || (device->hidden == NULL) ) { - SDL_OutOfMemory(); - if ( device ) { - SDL_free(device); - } - return(0); - } - SDL_memset(device->hidden, 0, (sizeof *device->hidden)); - - /* Set the function pointers */ - device->VideoInit = DC_VideoInit; - device->ListModes = DC_ListModes; - device->SetVideoMode = DC_SetVideoMode; - device->CreateYUVOverlay = NULL; - device->SetColors = DC_SetColors; - device->UpdateRects = DC_UpdateRects; - device->VideoQuit = DC_VideoQuit; - device->AllocHWSurface = DC_AllocHWSurface; - device->CheckHWBlit = NULL; - device->FillHWRect = NULL; - device->SetHWColorKey = NULL; - device->SetHWAlpha = NULL; - device->LockHWSurface = DC_LockHWSurface; - device->UnlockHWSurface = DC_UnlockHWSurface; - device->FlipHWSurface = DC_FlipHWSurface; - device->FreeHWSurface = DC_FreeHWSurface; + SDL_VideoDevice *device; + + /* Initialize all variables that we clean on shutdown */ + device = (SDL_VideoDevice *) SDL_malloc(sizeof(SDL_VideoDevice)); + if (device) { + SDL_memset(device, 0, (sizeof *device)); + device->hidden = (struct SDL_PrivateVideoData *) + SDL_malloc((sizeof *device->hidden)); + } + if ((device == NULL) || (device->hidden == NULL)) { + SDL_OutOfMemory(); + if (device) { + SDL_free(device); + } + return (0); + } + SDL_memset(device->hidden, 0, (sizeof *device->hidden)); + + /* Set the function pointers */ + device->VideoInit = DC_VideoInit; + device->ListModes = DC_ListModes; + device->SetVideoMode = DC_SetVideoMode; + device->CreateYUVOverlay = NULL; + device->SetColors = DC_SetColors; + device->UpdateRects = DC_UpdateRects; + device->VideoQuit = DC_VideoQuit; + device->AllocHWSurface = DC_AllocHWSurface; + device->CheckHWBlit = NULL; + device->FillHWRect = NULL; + device->SetHWColorKey = NULL; + device->SetHWAlpha = NULL; + device->LockHWSurface = DC_LockHWSurface; + device->UnlockHWSurface = DC_UnlockHWSurface; + device->FlipHWSurface = DC_FlipHWSurface; + device->FreeHWSurface = DC_FreeHWSurface; #if SDL_VIDEO_OPENGL - device->GL_LoadLibrary = DC_GL_LoadLibrary; - device->GL_GetProcAddress = DC_GL_GetProcAddress; - device->GL_GetAttribute = DC_GL_GetAttribute; - device->GL_MakeCurrent = NULL; - device->GL_SwapBuffers = DC_GL_SwapBuffers; + device->GL_LoadLibrary = DC_GL_LoadLibrary; + device->GL_GetProcAddress = DC_GL_GetProcAddress; + device->GL_GetAttribute = DC_GL_GetAttribute; + device->GL_MakeCurrent = NULL; + device->GL_SwapBuffers = DC_GL_SwapBuffers; #endif - device->SetCaption = NULL; - device->SetIcon = NULL; - device->IconifyWindow = NULL; - device->GrabInput = NULL; - device->GetWMInfo = NULL; - device->InitOSKeymap = DC_InitOSKeymap; - device->PumpEvents = DC_PumpEvents; + device->SetCaption = NULL; + device->SetIcon = NULL; + device->IconifyWindow = NULL; + device->GrabInput = NULL; + device->GetWMInfo = NULL; + device->InitOSKeymap = DC_InitOSKeymap; + device->PumpEvents = DC_PumpEvents; - device->free = DC_DeleteDevice; + device->free = DC_DeleteDevice; - return device; + return device; } VideoBootStrap DC_bootstrap = { - "dcvideo", "Dreamcast Video", - DC_Available, DC_CreateDevice + "dcvideo", "Dreamcast Video", + DC_Available, DC_CreateDevice }; -int DC_VideoInit(_THIS, SDL_PixelFormat *vformat) +int +DC_VideoInit(_THIS, SDL_PixelFormat * vformat) { - /* Determine the screen depth (use default 16-bit depth) */ - /* we change this during the SDL_SetVideoMode implementation... */ - vformat->BitsPerPixel = 16; - vformat->Rmask = 0x0000f800; - vformat->Gmask = 0x000007e0; - vformat->Bmask = 0x0000001f; - - /* We're done! */ - return(0); + /* Determine the screen depth (use default 16-bit depth) */ + /* we change this during the SDL_SetVideoMode implementation... */ + vformat->BitsPerPixel = 16; + vformat->Rmask = 0x0000f800; + vformat->Gmask = 0x000007e0; + vformat->Bmask = 0x0000001f; + + /* We're done! */ + return (0); } -const static SDL_Rect - RECT_800x600 = {0,0,800,600}, - RECT_640x480 = {0,0,640,480}, - RECT_320x240 = {0,0,320,240}; +const static SDL_Rect RECT_800x600 = { 0, 0, 800, 600 }, RECT_640x480 = { +0, 0, 640, 480}, RECT_320x240 = { +0, 0, 320, 240}; const static SDL_Rect *vid_modes[] = { - &RECT_800x600, - &RECT_640x480, - &RECT_320x240, - NULL + &RECT_800x600, + &RECT_640x480, + &RECT_320x240, + NULL }; -SDL_Rect **DC_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags) +SDL_Rect ** +DC_ListModes(_THIS, SDL_PixelFormat * format, Uint32 flags) { - switch(format->BitsPerPixel) { - case 15: - case 16: - return &vid_modes; - case 32: - if (!(flags & SDL_OPENGL)) - return &vid_modes; - default: - return NULL; - } -// return (SDL_Rect **) -1; + switch (format->BitsPerPixel) { + case 15: + case 16: + return &vid_modes; + case 32: + if (!(flags & SDL_INTERNALOPENGL)) + return &vid_modes; + default: + return NULL; + } +// return (SDL_Rect **) -1; } pvr_init_params_t params = { - /* Enable opaque and translucent polygons with size 16 */ - { PVR_BINSIZE_16, PVR_BINSIZE_0, PVR_BINSIZE_16, PVR_BINSIZE_0, PVR_BINSIZE_16 }, + /* Enable opaque and translucent polygons with size 16 */ + {PVR_BINSIZE_16, PVR_BINSIZE_0, PVR_BINSIZE_16, PVR_BINSIZE_0, + PVR_BINSIZE_16} + , - /* Vertex buffer size */ - 512*1024 + /* Vertex buffer size */ + 512 * 1024 }; #if SDL_VIDEO_OPENGL static int pvr_inited; #endif -SDL_Surface *DC_SetVideoMode(_THIS, SDL_Surface *current, - int width, int height, int bpp, Uint32 flags) +SDL_Surface * +DC_SetVideoMode(_THIS, SDL_Surface * current, + int width, int height, int bpp, Uint32 flags) { - int disp_mode,pixel_mode,pitch; - Uint32 Rmask, Gmask, Bmask; - - if (width==320 && height==240) disp_mode=DM_320x240; - else if (width==640 && height==480) disp_mode=DM_640x480; - else if (width==800 && height==600) disp_mode=DM_800x608; - else { - SDL_SetError("Couldn't find requested mode in list"); - return(NULL); - } - - switch(bpp) { - case 15: pixel_mode = PM_RGB555; pitch = width*2; - /* 5-5-5 */ - Rmask = 0x00007c00; - Gmask = 0x000003e0; - Bmask = 0x0000001f; - break; - case 16: pixel_mode = PM_RGB565; pitch = width*2; - /* 5-6-5 */ - Rmask = 0x0000f800; - Gmask = 0x000007e0; - Bmask = 0x0000001f; - break; - case 24: bpp = 32; - case 32: pixel_mode = PM_RGB888; pitch = width*4; - Rmask = 0x00ff0000; - Gmask = 0x0000ff00; - Bmask = 0x000000ff; + int disp_mode, pixel_mode, pitch; + Uint32 Rmask, Gmask, Bmask; + + if (width == 320 && height == 240) + disp_mode = DM_320x240; + else if (width == 640 && height == 480) + disp_mode = DM_640x480; + else if (width == 800 && height == 600) + disp_mode = DM_800x608; + else { + SDL_SetError("Couldn't find requested mode in list"); + return (NULL); + } + + switch (bpp) { + case 15: + pixel_mode = PM_RGB555; + pitch = width * 2; + /* 5-5-5 */ + Rmask = 0x00007c00; + Gmask = 0x000003e0; + Bmask = 0x0000001f; + break; + case 16: + pixel_mode = PM_RGB565; + pitch = width * 2; + /* 5-6-5 */ + Rmask = 0x0000f800; + Gmask = 0x000007e0; + Bmask = 0x0000001f; + break; + case 24: + bpp = 32; + case 32: + pixel_mode = PM_RGB888; + pitch = width * 4; + Rmask = 0x00ff0000; + Gmask = 0x0000ff00; + Bmask = 0x000000ff; #if SDL_VIDEO_OPENGL - if (!(flags & SDL_OPENGL)) + if (!(flags & SDL_INTERNALOPENGL)) #endif - break; - default: - SDL_SetError("Couldn't find requested mode in list"); - return(NULL); - } + break; + default: + SDL_SetError("Couldn't find requested mode in list"); + return (NULL); + } // if ( bpp != current->format->BitsPerPixel ) { - if ( ! SDL_ReallocFormat(current, bpp, Rmask, Gmask, Bmask, 0) ) { - return(NULL); - } + if (!SDL_ReallocFormat(current, bpp, Rmask, Gmask, Bmask, 0)) { + return (NULL); + } // } - /* Set up the new mode framebuffer */ - current->flags = (SDL_FULLSCREEN|SDL_HWSURFACE); - current->w = width; - current->h = height; - current->pitch = pitch; + /* Set up the new mode framebuffer */ + current->flags = (SDL_FULLSCREEN | SDL_HWSURFACE); + current->w = width; + current->h = height; + current->pitch = pitch; #if SDL_VIDEO_OPENGL - if (pvr_inited) { - pvr_inited = 0; - pvr_shutdown(); - } + if (pvr_inited) { + pvr_inited = 0; + pvr_shutdown(); + } #endif - vid_set_mode(disp_mode,pixel_mode); + vid_set_mode(disp_mode, pixel_mode); - current->pixels = vram_s; + current->pixels = vram_s; #if SDL_VIDEO_OPENGL - if (flags & SDL_OPENGL) { - this->gl_config.driver_loaded = 1; - current->flags = SDL_FULLSCREEN | SDL_OPENGL; - current->pixels = NULL; - pvr_inited = 1; - pvr_init(¶ms); - glKosInit(); - glKosBeginFrame(); - } else + if (flags & SDL_INTERNALOPENGL) { + this->gl_config.driver_loaded = 1; + current->flags = SDL_FULLSCREEN | SDL_INTERNALOPENGL; + current->pixels = NULL; + pvr_inited = 1; + pvr_init(¶ms); + glKosInit(); + glKosBeginFrame(); + } else #endif - if (flags | SDL_DOUBLEBUF) { - current->flags |= SDL_DOUBLEBUF; - current->pixels = (void*)((int)current->pixels | 0x400000); - } + if (flags | SDL_DOUBLEBUF) { + current->flags |= SDL_DOUBLEBUF; + current->pixels = (void *) ((int) current->pixels | 0x400000); + } - /* We're done */ - return(current); + /* We're done */ + return (current); } /* We don't actually allow hardware surfaces other than the main one */ -static int DC_AllocHWSurface(_THIS, SDL_Surface *surface) +static int +DC_AllocHWSurface(_THIS, SDL_Surface * surface) { - return(-1); + return (-1); } -static void DC_FreeHWSurface(_THIS, SDL_Surface *surface) +static void +DC_FreeHWSurface(_THIS, SDL_Surface * surface) { - return; + return; } /* We need to wait for vertical retrace on page flipped displays */ -static int DC_LockHWSurface(_THIS, SDL_Surface *surface) +static int +DC_LockHWSurface(_THIS, SDL_Surface * surface) { - return(0); + return (0); } -static void DC_UnlockHWSurface(_THIS, SDL_Surface *surface) +static void +DC_UnlockHWSurface(_THIS, SDL_Surface * surface) { - return; + return; } -static int DC_FlipHWSurface(_THIS, SDL_Surface *surface) +static int +DC_FlipHWSurface(_THIS, SDL_Surface * surface) { - if (surface->flags & SDL_DOUBLEBUF) { - vid_set_start((int)surface->pixels & 0xffffff); - surface->pixels = (void*)((int)surface->pixels ^ 0x400000); - } - return(0); + if (surface->flags & SDL_DOUBLEBUF) { + vid_set_start((int) surface->pixels & 0xffffff); + surface->pixels = (void *) ((int) surface->pixels ^ 0x400000); + } + return (0); } -static void DC_UpdateRects(_THIS, int numrects, SDL_Rect *rects) +static void +DC_UpdateRects(_THIS, int numrects, SDL_Rect * rects) { - /* do nothing. */ + /* do nothing. */ } -static int DC_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color *colors) +static int +DC_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color * colors) { - /* do nothing of note. */ - return(1); + /* do nothing of note. */ + return (1); } /* Note: If we are terminated, this could be called in the middle of another SDL video routine -- notably UpdateRects. */ -static void DC_VideoQuit(_THIS) +static void +DC_VideoQuit(_THIS) { #if SDL_VIDEO_OPENGL - if (pvr_inited) { - pvr_inited = 0; - pvr_shutdown(); - } + if (pvr_inited) { + pvr_inited = 0; + pvr_shutdown(); + } #endif } #if SDL_VIDEO_OPENGL -void dmyfunc(void) {} +void +dmyfunc(void) +{ +} -typedef void (*funcptr)(); -const static struct { - char *name; - funcptr addr; +typedef void (*funcptr) (); +const static struct +{ + char *name; + funcptr addr; } glfuncs[] = { #define DEF(func) {#func,&func} - DEF(glBegin), - DEF(glBindTexture), - DEF(glBlendFunc), - DEF(glColor4f), -// DEF(glCopyImageID), - DEF(glDisable), - DEF(glEnable), - DEF(glEnd), - DEF(glFlush), - DEF(glGenTextures), - DEF(glGetString), - DEF(glLoadIdentity), - DEF(glMatrixMode), - DEF(glOrtho), - DEF(glPixelStorei), -// DEF(glPopAttrib), -// DEF(glPopClientAttrib), - {"glPopAttrib",&dmyfunc}, - {"glPopClientAttrib",&dmyfunc}, - DEF(glPopMatrix), -// DEF(glPushAttrib), -// DEF(glPushClientAttrib), - {"glPushAttrib",&dmyfunc}, - {"glPushClientAttrib",&dmyfunc}, - DEF(glPushMatrix), - DEF(glTexCoord2f), - DEF(glTexEnvf), - DEF(glTexImage2D), - DEF(glTexParameteri), - DEF(glTexSubImage2D), - DEF(glVertex2i), - DEF(glViewport), + DEF(glBegin), DEF(glBindTexture), DEF(glBlendFunc), DEF(glColor4f), +// DEF(glCopyImageID), + DEF(glDisable), + DEF(glEnable), + DEF(glEnd), + DEF(glFlush), + DEF(glGenTextures), + DEF(glGetString), + DEF(glLoadIdentity), + DEF(glMatrixMode), DEF(glOrtho), DEF(glPixelStorei), +// DEF(glPopAttrib), +// DEF(glPopClientAttrib), + { + "glPopAttrib", &dmyfunc}, { + "glPopClientAttrib", &dmyfunc}, DEF(glPopMatrix), +// DEF(glPushAttrib), +// DEF(glPushClientAttrib), + { + "glPushAttrib", &dmyfunc}, { + "glPushClientAttrib", &dmyfunc}, + DEF(glPushMatrix), + DEF(glTexCoord2f), + DEF(glTexEnvf), + DEF(glTexImage2D), + DEF(glTexParameteri), + DEF(glTexSubImage2D), DEF(glVertex2i), DEF(glViewport), #undef DEF }; -static void *DC_GL_GetProcAddress(_THIS, const char *proc) +static void * +DC_GL_GetProcAddress(_THIS, const char *proc) { - void *ret; - int i; + void *ret; + int i; - ret = glKosGetProcAddress(proc); - if (ret) return ret; + ret = glKosGetProcAddress(proc); + if (ret) + return ret; - for(i=0;igl_config.driver_loaded = 1; + this->gl_config.driver_loaded = 1; - return 0; + return 0; } -static int DC_GL_GetAttribute(_THIS, SDL_GLattr attrib, int* value) +static int +DC_GL_GetAttribute(_THIS, SDL_GLattr attrib, int *value) { - GLenum mesa_attrib; - int val; - - switch(attrib) { - case SDL_GL_RED_SIZE: - val = 5; - break; - case SDL_GL_GREEN_SIZE: - val = 6; - break; - case SDL_GL_BLUE_SIZE: - val = 5; - break; - case SDL_GL_ALPHA_SIZE: - val = 0; - break; - case SDL_GL_DOUBLEBUFFER: - val = 1; - break; - case SDL_GL_DEPTH_SIZE: - val = 16; /* or 32? */ - break; - case SDL_GL_STENCIL_SIZE: - val = 0; - break; - case SDL_GL_ACCUM_RED_SIZE: - val = 0; - break; - case SDL_GL_ACCUM_GREEN_SIZE: - val = 0; - case SDL_GL_ACCUM_BLUE_SIZE: - val = 0; - break; - case SDL_GL_ACCUM_ALPHA_SIZE: - val = 0; - break; - default : - return -1; - } - *value = val; - return 0; + GLenum mesa_attrib; + int val; + + switch (attrib) { + case SDL_GL_RED_SIZE: + val = 5; + break; + case SDL_GL_GREEN_SIZE: + val = 6; + break; + case SDL_GL_BLUE_SIZE: + val = 5; + break; + case SDL_GL_ALPHA_SIZE: + val = 0; + break; + case SDL_GL_DOUBLEBUFFER: + val = 1; + break; + case SDL_GL_DEPTH_SIZE: + val = 16; /* or 32? */ + break; + case SDL_GL_STENCIL_SIZE: + val = 0; + break; + case SDL_GL_ACCUM_RED_SIZE: + val = 0; + break; + case SDL_GL_ACCUM_GREEN_SIZE: + val = 0; + case SDL_GL_ACCUM_BLUE_SIZE: + val = 0; + break; + case SDL_GL_ACCUM_ALPHA_SIZE: + val = 0; + break; + default: + return -1; + } + *value = val; + return 0; } -static void DC_GL_SwapBuffers(_THIS) +static void +DC_GL_SwapBuffers(_THIS) { - glKosFinishFrame(); - glKosBeginFrame(); + glKosFinishFrame(); + glKosBeginFrame(); } #endif +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/dc/SDL_dcvideo.h b/src/video/dc/SDL_dcvideo.h index 2c7bf2553..474ffb23a 100644 --- a/src/video/dc/SDL_dcvideo.h +++ b/src/video/dc/SDL_dcvideo.h @@ -34,9 +34,11 @@ /* Private display data */ -struct SDL_PrivateVideoData { +struct SDL_PrivateVideoData +{ int w, h; void *buffer; }; #endif /* _SDL_dcvideo_h */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/dga/SDL_dgaevents.c b/src/video/dga/SDL_dgaevents.c index eaf2c230e..59001ec1e 100644 --- a/src/video/dga/SDL_dgaevents.c +++ b/src/video/dga/SDL_dgaevents.c @@ -36,118 +36,129 @@ #include "../x11/SDL_x11dyn.h" /* Heheh we're using X11 event code */ -extern int X11_Pending(Display *display); +extern int X11_Pending(Display * display); extern void X11_InitKeymap(void); -extern SDLKey X11_TranslateKeycode(Display *display, KeyCode kc); +extern SDLKey X11_TranslateKeycode(Display * display, KeyCode kc); -static int DGA_DispatchEvent(_THIS) +static int +DGA_DispatchEvent(_THIS) { - int posted; - SDL_NAME(XDGAEvent) xevent; - - XNextEvent(DGA_Display, (XEvent *)&xevent); - - posted = 0; - xevent.type -= DGA_event_base; - switch (xevent.type) { - - /* Mouse motion? */ - case MotionNotify: { - if ( SDL_VideoSurface ) { - posted = SDL_PrivateMouseMotion(0, 1, - xevent.xmotion.dx, xevent.xmotion.dy); - } - } - break; - - /* Mouse button press? */ - case ButtonPress: { - posted = SDL_PrivateMouseButton(SDL_PRESSED, - xevent.xbutton.button, 0, 0); - } - break; - - /* Mouse button release? */ - case ButtonRelease: { - posted = SDL_PrivateMouseButton(SDL_RELEASED, - xevent.xbutton.button, 0, 0); - } - break; - - /* Key press? */ - case KeyPress: { - SDL_keysym keysym; - KeyCode keycode; - XKeyEvent xkey; - - SDL_NAME(XDGAKeyEventToXKeyEvent)(&xevent.xkey, &xkey); - keycode = xkey.keycode; + int posted; + SDL_NAME(XDGAEvent) xevent; + + XNextEvent(DGA_Display, (XEvent *) & xevent); + + posted = 0; + xevent.type -= DGA_event_base; + switch (xevent.type) { + + /* Mouse motion? */ + case MotionNotify: + { + if (SDL_VideoSurface) { + posted = SDL_PrivateMouseMotion(0, 1, + xevent.xmotion.dx, + xevent.xmotion.dy); + } + } + break; + + /* Mouse button press? */ + case ButtonPress: + { + posted = SDL_PrivateMouseButton(SDL_PRESSED, + xevent.xbutton.button, 0, 0); + } + break; + + /* Mouse button release? */ + case ButtonRelease: + { + posted = SDL_PrivateMouseButton(SDL_RELEASED, + xevent.xbutton.button, 0, 0); + } + break; + + /* Key press? */ + case KeyPress: + { + SDL_keysym keysym; + KeyCode keycode; + XKeyEvent xkey; + + SDL_NAME(XDGAKeyEventToXKeyEvent) (&xevent.xkey, &xkey); + keycode = xkey.keycode; #ifdef DEBUG_XEVENTS -printf("KeyPress (X11 keycode = 0x%X)\n", xkey.keycode); + printf("KeyPress (X11 keycode = 0x%X)\n", xkey.keycode); #endif - /* Get the translated SDL virtual keysym */ - keysym.scancode = keycode; - keysym.sym = X11_TranslateKeycode(DGA_Display, keycode); - keysym.mod = KMOD_NONE; - keysym.unicode = 0; - - /* Look up the translated value for the key event */ - if ( SDL_TranslateUNICODE ) { - static XComposeStatus state; - char keybuf[32]; - - if ( XLookupString(&xkey, keybuf, sizeof(keybuf), NULL, &state) ) { - /* - * FIXME: XLookupString() may yield more than one - * character, so we need a mechanism to allow for - * this (perhaps null keypress events with a - * unicode value) - */ - keysym.unicode = (Uint8)keybuf[0]; - } - } - posted = SDL_PrivateKeyboard(SDL_PRESSED, &keysym); - } - break; - - /* Key release? */ - case KeyRelease: { - SDL_keysym keysym; - KeyCode keycode; - XKeyEvent xkey; - - SDL_NAME(XDGAKeyEventToXKeyEvent)(&xevent.xkey, &xkey); - keycode = xkey.keycode; + /* Get the translated SDL virtual keysym */ + keysym.scancode = keycode; + keysym.sym = X11_TranslateKeycode(DGA_Display, keycode); + keysym.mod = KMOD_NONE; + keysym.unicode = 0; + + /* Look up the translated value for the key event */ + if (SDL_TranslateUNICODE) { + static XComposeStatus state; + char keybuf[32]; + + if (XLookupString + (&xkey, keybuf, sizeof(keybuf), NULL, &state)) { + /* + * FIXME: XLookupString() may yield more than one + * character, so we need a mechanism to allow for + * this (perhaps null keypress events with a + * unicode value) + */ + keysym.unicode = (Uint8) keybuf[0]; + } + } + posted = SDL_PrivateKeyboard(SDL_PRESSED, &keysym); + } + break; + + /* Key release? */ + case KeyRelease: + { + SDL_keysym keysym; + KeyCode keycode; + XKeyEvent xkey; + + SDL_NAME(XDGAKeyEventToXKeyEvent) (&xevent.xkey, &xkey); + keycode = xkey.keycode; #ifdef DEBUG_XEVENTS -printf("KeyRelease (X11 keycode = 0x%X)\n", xkey.keycode); + printf("KeyRelease (X11 keycode = 0x%X)\n", xkey.keycode); #endif - /* Get the translated SDL virtual keysym */ - keysym.scancode = keycode; - keysym.sym = X11_TranslateKeycode(DGA_Display, keycode); - keysym.mod = KMOD_NONE; - keysym.unicode = 0; - posted = SDL_PrivateKeyboard(SDL_RELEASED, &keysym); - } - break; - - break; - - } - return(posted); + /* Get the translated SDL virtual keysym */ + keysym.scancode = keycode; + keysym.sym = X11_TranslateKeycode(DGA_Display, keycode); + keysym.mod = KMOD_NONE; + keysym.unicode = 0; + posted = SDL_PrivateKeyboard(SDL_RELEASED, &keysym); + } + break; + + break; + + } + return (posted); } -void DGA_PumpEvents(_THIS) +void +DGA_PumpEvents(_THIS) { - /* Keep processing pending events */ - LOCK_DISPLAY(); - while ( X11_Pending(DGA_Display) ) { - DGA_DispatchEvent(this); - } - UNLOCK_DISPLAY(); + /* Keep processing pending events */ + LOCK_DISPLAY(); + while (X11_Pending(DGA_Display)) { + DGA_DispatchEvent(this); + } + UNLOCK_DISPLAY(); } -void DGA_InitOSKeymap(_THIS) +void +DGA_InitOSKeymap(_THIS) { - X11_InitKeymap(); + X11_InitKeymap(); } +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/dga/SDL_dgaevents_c.h b/src/video/dga/SDL_dgaevents_c.h index 15e47f73e..31876eaa0 100644 --- a/src/video/dga/SDL_dgaevents_c.h +++ b/src/video/dga/SDL_dgaevents_c.h @@ -26,3 +26,4 @@ /* Functions to be exported */ extern void DGA_PumpEvents(_THIS); extern void DGA_InitOSKeymap(_THIS); +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/dga/SDL_dgamouse.c b/src/video/dga/SDL_dgamouse.c index fb995633a..b791b4e05 100644 --- a/src/video/dga/SDL_dgamouse.c +++ b/src/video/dga/SDL_dgamouse.c @@ -30,6 +30,8 @@ /* The implementation dependent data for the window manager cursor */ -struct WMcursor { - int unused; +struct WMcursor +{ + int unused; }; +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/dga/SDL_dgamouse_c.h b/src/video/dga/SDL_dgamouse_c.h index e863f6a4a..6663e42a2 100644 --- a/src/video/dga/SDL_dgamouse_c.h +++ b/src/video/dga/SDL_dgamouse_c.h @@ -24,3 +24,4 @@ #include "SDL_dgavideo.h" /* Functions to be exported */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/dga/SDL_dgavideo.c b/src/video/dga/SDL_dgavideo.c index 331fcd260..6ee493cf7 100644 --- a/src/video/dga/SDL_dgavideo.c +++ b/src/video/dga/SDL_dgavideo.c @@ -44,1057 +44,1107 @@ /*#define DGA_DEBUG*/ /* Heheh we're using X11 event code */ -extern void X11_SaveScreenSaver(Display *display, int *saved_timeout, BOOL *dpms); -extern void X11_DisableScreenSaver(Display *display); -extern void X11_RestoreScreenSaver(Display *display, int saved_timeout, BOOL dpms); +extern void X11_SaveScreenSaver(Display * display, int *saved_timeout, + BOOL * dpms); +extern void X11_DisableScreenSaver(Display * display); +extern void X11_RestoreScreenSaver(Display * display, int saved_timeout, + BOOL dpms); /* Initialization/Query functions */ -static int DGA_VideoInit(_THIS, SDL_PixelFormat *vformat); -static SDL_Rect **DGA_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags); -static SDL_Surface *DGA_SetVideoMode(_THIS, SDL_Surface *current, int width, int height, int bpp, Uint32 flags); +static int DGA_VideoInit(_THIS, SDL_PixelFormat * vformat); +static SDL_Rect **DGA_ListModes(_THIS, SDL_PixelFormat * format, + Uint32 flags); +static SDL_Surface *DGA_SetVideoMode(_THIS, SDL_Surface * current, int width, + int height, int bpp, Uint32 flags); static int DGA_SetColors(_THIS, int firstcolor, int ncolors, - SDL_Color *colors); -static int DGA_SetGammaRamp(_THIS, Uint16 *ramp); + SDL_Color * colors); +static int DGA_SetGammaRamp(_THIS, Uint16 * ramp); static void DGA_VideoQuit(_THIS); /* Hardware surface functions */ -static int DGA_InitHWSurfaces(_THIS, SDL_Surface *screen, Uint8 *base, int size); +static int DGA_InitHWSurfaces(_THIS, SDL_Surface * screen, Uint8 * base, + int size); static void DGA_FreeHWSurfaces(_THIS); -static int DGA_AllocHWSurface(_THIS, SDL_Surface *surface); -static int DGA_FillHWRect(_THIS, SDL_Surface *dst, SDL_Rect *rect, Uint32 color); -static int DGA_CheckHWBlit(_THIS, SDL_Surface *src, SDL_Surface *dst); -static int DGA_LockHWSurface(_THIS, SDL_Surface *surface); -static void DGA_UnlockHWSurface(_THIS, SDL_Surface *surface); -static void DGA_FreeHWSurface(_THIS, SDL_Surface *surface); -static int DGA_FlipHWSurface(_THIS, SDL_Surface *surface); +static int DGA_AllocHWSurface(_THIS, SDL_Surface * surface); +static int DGA_FillHWRect(_THIS, SDL_Surface * dst, SDL_Rect * rect, + Uint32 color); +static int DGA_CheckHWBlit(_THIS, SDL_Surface * src, SDL_Surface * dst); +static int DGA_LockHWSurface(_THIS, SDL_Surface * surface); +static void DGA_UnlockHWSurface(_THIS, SDL_Surface * surface); +static void DGA_FreeHWSurface(_THIS, SDL_Surface * surface); +static int DGA_FlipHWSurface(_THIS, SDL_Surface * surface); /* DGA driver bootstrap functions */ -static int DGA_Available(void) +static int +DGA_Available(void) { - const char *display = NULL; - Display *dpy = NULL; - int available = 0; - - /* The driver is available is available if the display is local - and the DGA 2.0+ extension is available, and we can map mem. - */ - if ( SDL_X11_LoadSymbols() ) { - if ( (SDL_strncmp(XDisplayName(display), ":", 1) == 0) || - (SDL_strncmp(XDisplayName(display), "unix:", 5) == 0) ) { - dpy = XOpenDisplay(display); - if ( dpy ) { - int events, errors, major, minor; - - if ( SDL_NAME(XDGAQueryExtension)(dpy, &events, &errors) && - SDL_NAME(XDGAQueryVersion)(dpy, &major, &minor) ) { - int screen; - - screen = DefaultScreen(dpy); - if ( (major >= 2) && - SDL_NAME(XDGAOpenFramebuffer)(dpy, screen) ) { - available = 1; - SDL_NAME(XDGACloseFramebuffer)(dpy, screen); - } - } - XCloseDisplay(dpy); - } - } - SDL_X11_UnloadSymbols(); - } - return(available); + const char *display = NULL; + Display *dpy = NULL; + int available = 0; + + /* The driver is available is available if the display is local + and the DGA 2.0+ extension is available, and we can map mem. + */ + if (SDL_X11_LoadSymbols()) { + if ((SDL_strncmp(XDisplayName(display), ":", 1) == 0) || + (SDL_strncmp(XDisplayName(display), "unix:", 5) == 0)) { + dpy = XOpenDisplay(display); + if (dpy) { + int events, errors, major, minor; + + if (SDL_NAME(XDGAQueryExtension) + (dpy, &events, &errors) + && SDL_NAME(XDGAQueryVersion) (dpy, &major, &minor)) { + int screen; + + screen = DefaultScreen(dpy); + if ((major >= 2) && + SDL_NAME(XDGAOpenFramebuffer) (dpy, screen)) { + available = 1; + SDL_NAME(XDGACloseFramebuffer) (dpy, screen); + } + } + XCloseDisplay(dpy); + } + } + SDL_X11_UnloadSymbols(); + } + return (available); } -static void DGA_DeleteDevice(SDL_VideoDevice *device) +static void +DGA_DeleteDevice(SDL_VideoDevice * device) { - if (device != NULL) { - SDL_free(device->hidden); - SDL_free(device); - SDL_X11_UnloadSymbols(); - } + if (device != NULL) { + SDL_free(device->hidden); + SDL_free(device); + SDL_X11_UnloadSymbols(); + } } -static SDL_VideoDevice *DGA_CreateDevice(int devindex) +static SDL_VideoDevice * +DGA_CreateDevice(int devindex) { - SDL_VideoDevice *device = NULL; - - /* Initialize all variables that we clean on shutdown */ - if (SDL_X11_LoadSymbols()) { - device = (SDL_VideoDevice *)SDL_malloc(sizeof(SDL_VideoDevice)); - if ( device ) { - SDL_memset(device, 0, (sizeof *device)); - device->hidden = (struct SDL_PrivateVideoData *) - SDL_malloc((sizeof *device->hidden)); - } - if ( (device == NULL) || (device->hidden == NULL) ) { - SDL_OutOfMemory(); - if ( device ) { - SDL_free(device); - } - SDL_X11_UnloadSymbols(); - return(0); - } - SDL_memset(device->hidden, 0, (sizeof *device->hidden)); - - /* Set the function pointers */ - device->VideoInit = DGA_VideoInit; - device->ListModes = DGA_ListModes; - device->SetVideoMode = DGA_SetVideoMode; - device->SetColors = DGA_SetColors; - device->UpdateRects = NULL; - device->VideoQuit = DGA_VideoQuit; - device->AllocHWSurface = DGA_AllocHWSurface; - device->CheckHWBlit = DGA_CheckHWBlit; - device->FillHWRect = DGA_FillHWRect; - device->SetHWColorKey = NULL; - device->SetHWAlpha = NULL; - device->LockHWSurface = DGA_LockHWSurface; - device->UnlockHWSurface = DGA_UnlockHWSurface; - device->FlipHWSurface = DGA_FlipHWSurface; - device->FreeHWSurface = DGA_FreeHWSurface; - device->SetGammaRamp = DGA_SetGammaRamp; - device->GetGammaRamp = NULL; - device->SetCaption = NULL; - device->SetIcon = NULL; - device->IconifyWindow = NULL; - device->GrabInput = NULL; - device->GetWMInfo = NULL; - device->InitOSKeymap = DGA_InitOSKeymap; - device->PumpEvents = DGA_PumpEvents; - - device->free = DGA_DeleteDevice; - } - - return device; + SDL_VideoDevice *device = NULL; + + /* Initialize all variables that we clean on shutdown */ + if (SDL_X11_LoadSymbols()) { + device = (SDL_VideoDevice *) SDL_malloc(sizeof(SDL_VideoDevice)); + if (device) { + SDL_memset(device, 0, (sizeof *device)); + device->hidden = (struct SDL_PrivateVideoData *) + SDL_malloc((sizeof *device->hidden)); + } + if ((device == NULL) || (device->hidden == NULL)) { + SDL_OutOfMemory(); + if (device) { + SDL_free(device); + } + SDL_X11_UnloadSymbols(); + return (0); + } + SDL_memset(device->hidden, 0, (sizeof *device->hidden)); + + /* Set the function pointers */ + device->VideoInit = DGA_VideoInit; + device->ListModes = DGA_ListModes; + device->SetVideoMode = DGA_SetVideoMode; + device->SetColors = DGA_SetColors; + device->UpdateRects = NULL; + device->VideoQuit = DGA_VideoQuit; + device->AllocHWSurface = DGA_AllocHWSurface; + device->CheckHWBlit = DGA_CheckHWBlit; + device->FillHWRect = DGA_FillHWRect; + device->SetHWColorKey = NULL; + device->SetHWAlpha = NULL; + device->LockHWSurface = DGA_LockHWSurface; + device->UnlockHWSurface = DGA_UnlockHWSurface; + device->FlipHWSurface = DGA_FlipHWSurface; + device->FreeHWSurface = DGA_FreeHWSurface; + device->SetGammaRamp = DGA_SetGammaRamp; + device->GetGammaRamp = NULL; + device->SetCaption = NULL; + device->SetIcon = NULL; + device->IconifyWindow = NULL; + device->GrabInput = NULL; + device->GetWMInfo = NULL; + device->InitOSKeymap = DGA_InitOSKeymap; + device->PumpEvents = DGA_PumpEvents; + + device->free = DGA_DeleteDevice; + } + + return device; } VideoBootStrap DGA_bootstrap = { - "dga", "XFree86 DGA 2.0", - DGA_Available, DGA_CreateDevice + "dga", "XFree86 DGA 2.0", + DGA_Available, DGA_CreateDevice }; -static int DGA_AddMode(_THIS, int bpp, int w, int h) +static int +DGA_AddMode(_THIS, int bpp, int w, int h) { - SDL_Rect *mode; - int index; - int next_mode; - - /* Check to see if we already have this mode */ - if ( bpp < 8 ) { /* Not supported */ - return(0); - } - index = ((bpp+7)/8)-1; - if ( SDL_nummodes[index] > 0 ) { - mode = SDL_modelist[index][SDL_nummodes[index]-1]; - if ( (mode->w == w) && (mode->h == h) ) { - return(0); - } - } - - /* Set up the new video mode rectangle */ - mode = (SDL_Rect *)SDL_malloc(sizeof *mode); - if ( mode == NULL ) { - SDL_OutOfMemory(); - return(-1); - } - mode->x = 0; - mode->y = 0; - mode->w = w; - mode->h = h; - - /* Allocate the new list of modes, and fill in the new mode */ - next_mode = SDL_nummodes[index]; - SDL_modelist[index] = (SDL_Rect **) - SDL_realloc(SDL_modelist[index], (1+next_mode+1)*sizeof(SDL_Rect *)); - if ( SDL_modelist[index] == NULL ) { - SDL_OutOfMemory(); - SDL_nummodes[index] = 0; - SDL_free(mode); - return(-1); - } - SDL_modelist[index][next_mode] = mode; - SDL_modelist[index][next_mode+1] = NULL; - SDL_nummodes[index]++; - - return(0); + SDL_Rect *mode; + int index; + int next_mode; + + /* Check to see if we already have this mode */ + if (bpp < 8) { /* Not supported */ + return (0); + } + index = ((bpp + 7) / 8) - 1; + if (SDL_nummodes[index] > 0) { + mode = SDL_modelist[index][SDL_nummodes[index] - 1]; + if ((mode->w == w) && (mode->h == h)) { + return (0); + } + } + + /* Set up the new video mode rectangle */ + mode = (SDL_Rect *) SDL_malloc(sizeof *mode); + if (mode == NULL) { + SDL_OutOfMemory(); + return (-1); + } + mode->x = 0; + mode->y = 0; + mode->w = w; + mode->h = h; + + /* Allocate the new list of modes, and fill in the new mode */ + next_mode = SDL_nummodes[index]; + SDL_modelist[index] = (SDL_Rect **) + SDL_realloc(SDL_modelist[index], + (1 + next_mode + 1) * sizeof(SDL_Rect *)); + if (SDL_modelist[index] == NULL) { + SDL_OutOfMemory(); + SDL_nummodes[index] = 0; + SDL_free(mode); + return (-1); + } + SDL_modelist[index][next_mode] = mode; + SDL_modelist[index][next_mode + 1] = NULL; + SDL_nummodes[index]++; + + return (0); } /* This whole function is a hack. :) */ -static Uint32 get_video_size(_THIS) +static Uint32 +get_video_size(_THIS) { - /* This is a non-exported function from libXxf86dga.a */ - extern unsigned char *SDL_NAME(XDGAGetMappedMemory)(int screen); - FILE *proc; - unsigned long mem; - unsigned start, stop; - char line[BUFSIZ]; - Uint32 size; - - mem = (unsigned long)SDL_NAME(XDGAGetMappedMemory)(DGA_Screen); - size = 0; - proc = fopen("/proc/self/maps", "r"); - if ( proc ) { - while ( fgets(line, sizeof(line)-1, proc) ) { - SDL_sscanf(line, "%x-%x", &start, &stop); - if ( start == mem ) { - size = (Uint32)((stop-start)/1024); - break; - } - } - fclose(proc); - } - return(size); + /* This is a non-exported function from libXxf86dga.a */ + extern unsigned char *SDL_NAME(XDGAGetMappedMemory) (int screen); + FILE *proc; + unsigned long mem; + unsigned start, stop; + char line[BUFSIZ]; + Uint32 size; + + mem = (unsigned long) SDL_NAME(XDGAGetMappedMemory) (DGA_Screen); + size = 0; + proc = fopen("/proc/self/maps", "r"); + if (proc) { + while (fgets(line, sizeof(line) - 1, proc)) { + SDL_sscanf(line, "%x-%x", &start, &stop); + if (start == mem) { + size = (Uint32) ((stop - start) / 1024); + break; + } + } + fclose(proc); + } + return (size); } #ifdef DGA_DEBUG -static void PrintMode(SDL_NAME(XDGAMode) *mode) +static void +PrintMode(SDL_NAME(XDGAMode) * mode) { - printf("Mode: %s (%dx%d) at %d bpp (%f refresh, %d pitch) num: %d\n", - mode->name, - mode->viewportWidth, mode->viewportHeight, - mode->depth == 24 ? mode->bitsPerPixel : mode->depth, - mode->verticalRefresh, mode->bytesPerScanline, mode->num); - printf("\tRGB: 0x%8.8x 0x%8.8x 0x%8.8x (%d - %s)\n", - mode->redMask, mode->greenMask, mode->blueMask, - mode->visualClass, - mode->visualClass == TrueColor ? "truecolor" : - mode->visualClass == DirectColor ? "directcolor" : - mode->visualClass == PseudoColor ? "pseudocolor" : "unknown"); - printf("\tFlags: "); - if ( mode->flags & XDGAConcurrentAccess ) - printf(" XDGAConcurrentAccess"); - if ( mode->flags & XDGASolidFillRect ) - printf(" XDGASolidFillRect"); - if ( mode->flags & XDGABlitRect ) - printf(" XDGABlitRect"); - if ( mode->flags & XDGABlitTransRect ) - printf(" XDGABlitTransRect"); - if ( mode->flags & XDGAPixmap ) - printf(" XDGAPixmap"); - if ( mode->flags & XDGAInterlaced ) - printf(" XDGAInterlaced"); - if ( mode->flags & XDGADoublescan ) - printf(" XDGADoublescan"); - if ( mode->viewportFlags & XDGAFlipRetrace ) - printf(" XDGAFlipRetrace"); - if ( mode->viewportFlags & XDGAFlipImmediate ) - printf(" XDGAFlipImmediate"); - printf("\n"); + printf("Mode: %s (%dx%d) at %d bpp (%f refresh, %d pitch) num: %d\n", + mode->name, + mode->viewportWidth, mode->viewportHeight, + mode->depth == 24 ? mode->bitsPerPixel : mode->depth, + mode->verticalRefresh, mode->bytesPerScanline, mode->num); + printf("\tRGB: 0x%8.8x 0x%8.8x 0x%8.8x (%d - %s)\n", + mode->redMask, mode->greenMask, mode->blueMask, + mode->visualClass, + mode->visualClass == TrueColor ? "truecolor" : + mode->visualClass == DirectColor ? "directcolor" : + mode->visualClass == PseudoColor ? "pseudocolor" : "unknown"); + printf("\tFlags: "); + if (mode->flags & XDGAConcurrentAccess) + printf(" XDGAConcurrentAccess"); + if (mode->flags & XDGASolidFillRect) + printf(" XDGASolidFillRect"); + if (mode->flags & XDGABlitRect) + printf(" XDGABlitRect"); + if (mode->flags & XDGABlitTransRect) + printf(" XDGABlitTransRect"); + if (mode->flags & XDGAPixmap) + printf(" XDGAPixmap"); + if (mode->flags & XDGAInterlaced) + printf(" XDGAInterlaced"); + if (mode->flags & XDGADoublescan) + printf(" XDGADoublescan"); + if (mode->viewportFlags & XDGAFlipRetrace) + printf(" XDGAFlipRetrace"); + if (mode->viewportFlags & XDGAFlipImmediate) + printf(" XDGAFlipImmediate"); + printf("\n"); } #endif /* DGA_DEBUG */ -static int cmpmodes(const void *va, const void *vb) +static int +cmpmodes(const void *va, const void *vb) { - const SDL_NAME(XDGAMode) *a = (const SDL_NAME(XDGAMode) *)va; - const SDL_NAME(XDGAMode) *b = (const SDL_NAME(XDGAMode) *)vb; + const SDL_NAME(XDGAMode) * a = (const SDL_NAME(XDGAMode) *) va; + const SDL_NAME(XDGAMode) * b = (const SDL_NAME(XDGAMode) *) vb; - if ( (a->viewportWidth == b->viewportWidth) && - (b->viewportHeight == a->viewportHeight) ) { + if ((a->viewportWidth == b->viewportWidth) && + (b->viewportHeight == a->viewportHeight)) { /* Prefer 32 bpp over 24 bpp, 16 bpp over 15 bpp */ int a_bpp = a->depth == 24 ? a->bitsPerPixel : a->depth; int b_bpp = b->depth == 24 ? b->bitsPerPixel : b->depth; - if ( a_bpp != b_bpp ) { + if (a_bpp != b_bpp) { return b_bpp - a_bpp; } /* Prefer DirectColor visuals, for gamma support */ - if ( a->visualClass == DirectColor && b->visualClass != DirectColor ) + if (a->visualClass == DirectColor && b->visualClass != DirectColor) return -1; - if ( b->visualClass == DirectColor && a->visualClass != DirectColor ) + if (b->visualClass == DirectColor && a->visualClass != DirectColor) return 1; /* Maintain server refresh rate sorting */ return a->num - b->num; - } else if ( a->viewportWidth == b->viewportWidth ) { + } else if (a->viewportWidth == b->viewportWidth) { return b->viewportHeight - a->viewportHeight; } else { return b->viewportWidth - a->viewportWidth; } } -static void UpdateHWInfo(_THIS, SDL_NAME(XDGAMode) *mode) +static void +UpdateHWInfo(_THIS, SDL_NAME(XDGAMode) * mode) { - this->info.wm_available = 0; - this->info.hw_available = 1; - if ( mode->flags & XDGABlitRect ) { - this->info.blit_hw = 1; - } else { - this->info.blit_hw = 0; - } - if ( mode->flags & XDGABlitTransRect ) { - this->info.blit_hw_CC = 1; - } else { - this->info.blit_hw_CC = 0; - } - if ( mode->flags & XDGASolidFillRect ) { - this->info.blit_fill = 1; - } else { - this->info.blit_fill = 0; - } - this->info.video_mem = get_video_size(this); + this->info.wm_available = 0; + this->info.hw_available = 1; + if (mode->flags & XDGABlitRect) { + this->info.blit_hw = 1; + } else { + this->info.blit_hw = 0; + } + if (mode->flags & XDGABlitTransRect) { + this->info.blit_hw_CC = 1; + } else { + this->info.blit_hw_CC = 0; + } + if (mode->flags & XDGASolidFillRect) { + this->info.blit_fill = 1; + } else { + this->info.blit_fill = 0; + } + this->info.video_mem = get_video_size(this); } -static int DGA_VideoInit(_THIS, SDL_PixelFormat *vformat) +static int +DGA_VideoInit(_THIS, SDL_PixelFormat * vformat) { - const char *display; - int event_base, error_base; - int major_version, minor_version; - Visual *visual; - SDL_NAME(XDGAMode) *modes; - int i, num_modes; - - /* Open the X11 display */ - display = NULL; /* Get it from DISPLAY environment variable */ - - DGA_Display = XOpenDisplay(display); - if ( DGA_Display == NULL ) { - SDL_SetError("Couldn't open X11 display"); - return(-1); - } - - /* Check for the DGA extension */ - if ( ! SDL_NAME(XDGAQueryExtension)(DGA_Display, &event_base, &error_base) || - ! SDL_NAME(XDGAQueryVersion)(DGA_Display, &major_version, &minor_version) ) { - SDL_SetError("DGA extension not available"); - XCloseDisplay(DGA_Display); - return(-1); - } - if ( major_version < 2 ) { - SDL_SetError("DGA driver requires DGA 2.0 or newer"); - XCloseDisplay(DGA_Display); - return(-1); - } - DGA_event_base = event_base; - - /* Determine the current screen size */ - this->info.current_w = DisplayWidth(DGA_Display, DGA_Screen); - this->info.current_h = DisplayHeight(DGA_Display, DGA_Screen); - - /* Determine the current screen depth */ - visual = DefaultVisual(DGA_Display, DGA_Screen); - { - XPixmapFormatValues *pix_format; - int i, num_formats; - - vformat->BitsPerPixel = DefaultDepth(DGA_Display, DGA_Screen); - pix_format = XListPixmapFormats(DGA_Display, &num_formats); - if ( pix_format == NULL ) { - SDL_SetError("Couldn't determine screen formats"); - XCloseDisplay(DGA_Display); - return(-1); - } - for ( i=0; iBitsPerPixel == pix_format[i].depth ) - break; - } - if ( i != num_formats ) - vformat->BitsPerPixel = pix_format[i].bits_per_pixel; - XFree((char *)pix_format); - } - if ( vformat->BitsPerPixel > 8 ) { - vformat->Rmask = visual->red_mask; - vformat->Gmask = visual->green_mask; - vformat->Bmask = visual->blue_mask; - } - - /* Open access to the framebuffer */ - if ( ! SDL_NAME(XDGAOpenFramebuffer)(DGA_Display, DGA_Screen) ) { - SDL_SetError("Unable to map the video memory"); - XCloseDisplay(DGA_Display); - return(-1); - } - - /* Save DPMS and screensaver settings */ - X11_SaveScreenSaver(DGA_Display, &screensaver_timeout, &dpms_enabled); - X11_DisableScreenSaver(DGA_Display); - - /* Query for the list of available video modes */ - modes = SDL_NAME(XDGAQueryModes)(DGA_Display, DGA_Screen, &num_modes); - SDL_qsort(modes, num_modes, sizeof *modes, cmpmodes); - for ( i=0; iinfo.current_w = DisplayWidth(DGA_Display, DGA_Screen); + this->info.current_h = DisplayHeight(DGA_Display, DGA_Screen); + + /* Determine the current screen depth */ + visual = DefaultVisual(DGA_Display, DGA_Screen); + { + XPixmapFormatValues *pix_format; + int i, num_formats; + + vformat->BitsPerPixel = DefaultDepth(DGA_Display, DGA_Screen); + pix_format = XListPixmapFormats(DGA_Display, &num_formats); + if (pix_format == NULL) { + SDL_SetError("Couldn't determine screen formats"); + XCloseDisplay(DGA_Display); + return (-1); + } + for (i = 0; i < num_formats; ++i) { + if (vformat->BitsPerPixel == pix_format[i].depth) + break; + } + if (i != num_formats) + vformat->BitsPerPixel = pix_format[i].bits_per_pixel; + XFree((char *) pix_format); + } + if (vformat->BitsPerPixel > 8) { + vformat->Rmask = visual->red_mask; + vformat->Gmask = visual->green_mask; + vformat->Bmask = visual->blue_mask; + } + + /* Open access to the framebuffer */ + if (!SDL_NAME(XDGAOpenFramebuffer) (DGA_Display, DGA_Screen)) { + SDL_SetError("Unable to map the video memory"); + XCloseDisplay(DGA_Display); + return (-1); + } + + /* Save DPMS and screensaver settings */ + X11_SaveScreenSaver(DGA_Display, &screensaver_timeout, &dpms_enabled); + X11_DisableScreenSaver(DGA_Display); + + /* Query for the list of available video modes */ + modes = SDL_NAME(XDGAQueryModes) (DGA_Display, DGA_Screen, &num_modes); + SDL_qsort(modes, num_modes, sizeof *modes, cmpmodes); + for (i = 0; i < num_modes; ++i) { + if (((modes[i].visualClass == PseudoColor) || + (modes[i].visualClass == DirectColor) || + (modes[i].visualClass == TrueColor)) && + !(modes[i].flags & (XDGAInterlaced | XDGADoublescan))) { #ifdef DGA_DEBUG - PrintMode(&modes[i]); + PrintMode(&modes[i]); #endif - DGA_AddMode(this, modes[i].bitsPerPixel, - modes[i].viewportWidth, - modes[i].viewportHeight); - } - } - UpdateHWInfo(this, modes); - XFree(modes); - - /* Create the hardware surface lock mutex */ - hw_lock = SDL_CreateMutex(); - if ( hw_lock == NULL ) { - SDL_SetError("Unable to create lock mutex"); - DGA_VideoQuit(this); - return(-1); - } - + DGA_AddMode(this, modes[i].bitsPerPixel, + modes[i].viewportWidth, modes[i].viewportHeight); + } + } + UpdateHWInfo(this, modes); + XFree(modes); + + /* Create the hardware surface lock mutex */ + hw_lock = SDL_CreateMutex(); + if (hw_lock == NULL) { + SDL_SetError("Unable to create lock mutex"); + DGA_VideoQuit(this); + return (-1); + } #ifdef LOCK_DGA_DISPLAY - /* Create the event lock so we're thread-safe.. :-/ */ - event_lock = SDL_CreateMutex(); + /* Create the event lock so we're thread-safe.. :-/ */ + event_lock = SDL_CreateMutex(); #endif /* LOCK_DGA_DISPLAY */ - /* We're done! */ - return(0); + /* We're done! */ + return (0); } -SDL_Rect **DGA_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags) +SDL_Rect ** +DGA_ListModes(_THIS, SDL_PixelFormat * format, Uint32 flags) { - return(SDL_modelist[((format->BitsPerPixel+7)/8)-1]); + return (SDL_modelist[((format->BitsPerPixel + 7) / 8) - 1]); } /* Various screen update functions available */ -static void DGA_DirectUpdate(_THIS, int numrects, SDL_Rect *rects); +static void DGA_DirectUpdate(_THIS, int numrects, SDL_Rect * rects); -SDL_Surface *DGA_SetVideoMode(_THIS, SDL_Surface *current, - int width, int height, int bpp, Uint32 flags) +SDL_Surface * +DGA_SetVideoMode(_THIS, SDL_Surface * current, + int width, int height, int bpp, Uint32 flags) { - SDL_NAME(XDGAMode) *modes; - int i, num_modes; - SDL_NAME(XDGADevice) *mode; - int screen_len; - Uint8 *surfaces_mem; - int surfaces_len; - - /* Free any previous colormap */ - if ( DGA_colormap ) { - XFreeColormap(DGA_Display, DGA_colormap); - DGA_colormap = 0; - } - - /* Search for a matching video mode */ - modes = SDL_NAME(XDGAQueryModes)(DGA_Display, DGA_Screen, &num_modes); - SDL_qsort(modes, num_modes, sizeof *modes, cmpmodes); - for ( i=0; imode.visualClass; - memory_base = (Uint8 *)mode->data; - memory_pitch = mode->mode.bytesPerScanline; - - /* Set up the new mode framebuffer */ - current->flags = (SDL_FULLSCREEN|SDL_HWSURFACE); - current->w = mode->mode.viewportWidth; - current->h = mode->mode.viewportHeight; - current->pitch = memory_pitch; - current->pixels = memory_base; - if ( ! SDL_ReallocFormat(current, mode->mode.bitsPerPixel, - mode->mode.redMask, - mode->mode.greenMask, - mode->mode.blueMask, 0) ) { - return(NULL); - } - screen_len = current->h*current->pitch; - - /* Create a colormap if necessary */ - if ( (DGA_visualClass == PseudoColor) || - (DGA_visualClass == DirectColor) ) { - DGA_colormap = SDL_NAME(XDGACreateColormap)(DGA_Display, DGA_Screen, - mode, AllocAll); - if ( DGA_visualClass == PseudoColor ) { - current->flags |= SDL_HWPALETTE; - } else { - /* Initialize the colormap to the identity mapping */ - SDL_GetGammaRamp(0, 0, 0); - this->screen = current; - DGA_SetGammaRamp(this, this->gamma); - this->screen = NULL; - } - } else { - DGA_colormap = SDL_NAME(XDGACreateColormap)(DGA_Display, DGA_Screen, - mode, AllocNone); - } - SDL_NAME(XDGAInstallColormap)(DGA_Display, DGA_Screen, DGA_colormap); - - /* Update the hardware capabilities */ - UpdateHWInfo(this, &mode->mode); - - /* Set up the information for hardware surfaces */ - surfaces_mem = (Uint8 *)current->pixels + screen_len; - surfaces_len = (mode->mode.imageHeight*current->pitch - screen_len); - - /* Update for double-buffering, if we can */ - SDL_NAME(XDGASetViewport)(DGA_Display, DGA_Screen, 0, 0, XDGAFlipRetrace); - if ( flags & SDL_DOUBLEBUF ) { - if ( mode->mode.imageHeight >= (current->h*2) ) { - current->flags |= SDL_DOUBLEBUF; - flip_page = 0; - flip_yoffset[0] = 0; - flip_yoffset[1] = current->h; - flip_address[0] = memory_base; - flip_address[1] = memory_base+screen_len; - surfaces_mem += screen_len; - surfaces_len -= screen_len; - } - } - - /* Allocate memory tracking for hardware surfaces */ - DGA_FreeHWSurfaces(this); - if ( surfaces_len < 0 ) { - surfaces_len = 0; - } - DGA_InitHWSurfaces(this, current, surfaces_mem, surfaces_len); - - /* Expose the back buffer as surface memory */ - if ( current->flags & SDL_DOUBLEBUF ) { - this->screen = current; - DGA_FlipHWSurface(this, current); - this->screen = NULL; - } - - /* Set the update rectangle function */ - this->UpdateRects = DGA_DirectUpdate; - - /* Enable mouse and keyboard support */ - { long input_mask; - input_mask = (KeyPressMask | KeyReleaseMask); - input_mask |= (ButtonPressMask | ButtonReleaseMask); - input_mask |= PointerMotionMask; - SDL_NAME(XDGASelectInput)(DGA_Display, DGA_Screen, input_mask); - } - - /* We're done */ - return(current); + /* Set the video mode */ + mode = SDL_NAME(XDGASetMode) (DGA_Display, DGA_Screen, modes[i].num); + XFree(modes); + if (mode == NULL) { + SDL_SetError("Unable to switch to requested mode"); + return (NULL); + } + DGA_visualClass = mode->mode.visualClass; + memory_base = (Uint8 *) mode->data; + memory_pitch = mode->mode.bytesPerScanline; + + /* Set up the new mode framebuffer */ + current->flags = (SDL_FULLSCREEN | SDL_HWSURFACE); + current->w = mode->mode.viewportWidth; + current->h = mode->mode.viewportHeight; + current->pitch = memory_pitch; + current->pixels = memory_base; + if (!SDL_ReallocFormat(current, mode->mode.bitsPerPixel, + mode->mode.redMask, + mode->mode.greenMask, mode->mode.blueMask, 0)) { + return (NULL); + } + screen_len = current->h * current->pitch; + + /* Create a colormap if necessary */ + if ((DGA_visualClass == PseudoColor) || (DGA_visualClass == DirectColor)) { + DGA_colormap = + SDL_NAME(XDGACreateColormap) (DGA_Display, DGA_Screen, mode, + AllocAll); + if (DGA_visualClass == PseudoColor) { + current->flags |= SDL_HWPALETTE; + } else { + /* Initialize the colormap to the identity mapping */ + SDL_GetGammaRamp(0, 0, 0); + this->screen = current; + DGA_SetGammaRamp(this, this->gamma); + this->screen = NULL; + } + } else { + DGA_colormap = + SDL_NAME(XDGACreateColormap) (DGA_Display, DGA_Screen, mode, + AllocNone); + } + SDL_NAME(XDGAInstallColormap) (DGA_Display, DGA_Screen, DGA_colormap); + + /* Update the hardware capabilities */ + UpdateHWInfo(this, &mode->mode); + + /* Set up the information for hardware surfaces */ + surfaces_mem = (Uint8 *) current->pixels + screen_len; + surfaces_len = (mode->mode.imageHeight * current->pitch - screen_len); + + /* Update for double-buffering, if we can */ + SDL_NAME(XDGASetViewport) (DGA_Display, DGA_Screen, 0, 0, + XDGAFlipRetrace); + if (flags & SDL_DOUBLEBUF) { + if (mode->mode.imageHeight >= (current->h * 2)) { + current->flags |= SDL_DOUBLEBUF; + flip_page = 0; + flip_yoffset[0] = 0; + flip_yoffset[1] = current->h; + flip_address[0] = memory_base; + flip_address[1] = memory_base + screen_len; + surfaces_mem += screen_len; + surfaces_len -= screen_len; + } + } + + /* Allocate memory tracking for hardware surfaces */ + DGA_FreeHWSurfaces(this); + if (surfaces_len < 0) { + surfaces_len = 0; + } + DGA_InitHWSurfaces(this, current, surfaces_mem, surfaces_len); + + /* Expose the back buffer as surface memory */ + if (current->flags & SDL_DOUBLEBUF) { + this->screen = current; + DGA_FlipHWSurface(this, current); + this->screen = NULL; + } + + /* Set the update rectangle function */ + this->UpdateRects = DGA_DirectUpdate; + + /* Enable mouse and keyboard support */ + { + long input_mask; + input_mask = (KeyPressMask | KeyReleaseMask); + input_mask |= (ButtonPressMask | ButtonReleaseMask); + input_mask |= PointerMotionMask; + SDL_NAME(XDGASelectInput) (DGA_Display, DGA_Screen, input_mask); + } + + /* We're done */ + return (current); } #ifdef DGA_DEBUG -static void DGA_DumpHWSurfaces(_THIS) +static void +DGA_DumpHWSurfaces(_THIS) { - vidmem_bucket *bucket; - - printf("Memory left: %d (%d total)\n", surfaces_memleft, surfaces_memtotal); - printf("\n"); - printf(" Base Size\n"); - for ( bucket=&surfaces; bucket; bucket=bucket->next ) { - printf("Bucket: %p, %d (%s)\n", bucket->base, bucket->size, bucket->used ? "used" : "free"); - if ( bucket->prev ) { - if ( bucket->base != bucket->prev->base+bucket->prev->size ) { - printf("Warning, corrupt bucket list! (prev)\n"); - } - } else { - if ( bucket != &surfaces ) { - printf("Warning, corrupt bucket list! (!prev)\n"); - } - } - if ( bucket->next ) { - if ( bucket->next->base != bucket->base+bucket->size ) { - printf("Warning, corrupt bucket list! (next)\n"); - } - } - } - printf("\n"); + vidmem_bucket *bucket; + + printf("Memory left: %d (%d total)\n", surfaces_memleft, + surfaces_memtotal); + printf("\n"); + printf(" Base Size\n"); + for (bucket = &surfaces; bucket; bucket = bucket->next) { + printf("Bucket: %p, %d (%s)\n", bucket->base, bucket->size, + bucket->used ? "used" : "free"); + if (bucket->prev) { + if (bucket->base != bucket->prev->base + bucket->prev->size) { + printf("Warning, corrupt bucket list! (prev)\n"); + } + } else { + if (bucket != &surfaces) { + printf("Warning, corrupt bucket list! (!prev)\n"); + } + } + if (bucket->next) { + if (bucket->next->base != bucket->base + bucket->size) { + printf("Warning, corrupt bucket list! (next)\n"); + } + } + } + printf("\n"); } #endif -static int DGA_InitHWSurfaces(_THIS, SDL_Surface *screen, Uint8 *base, int size) +static int +DGA_InitHWSurfaces(_THIS, SDL_Surface * screen, Uint8 * base, int size) { - vidmem_bucket *bucket; - - surfaces_memtotal = size; - surfaces_memleft = size; - - if ( surfaces_memleft > 0 ) { - bucket = (vidmem_bucket *)SDL_malloc(sizeof(*bucket)); - if ( bucket == NULL ) { - SDL_OutOfMemory(); - return(-1); - } - bucket->prev = &surfaces; - bucket->used = 0; - bucket->dirty = 0; - bucket->base = base; - bucket->size = size; - bucket->next = NULL; - } else { - bucket = NULL; - } - - surfaces.prev = NULL; - surfaces.used = 1; - surfaces.dirty = 0; - surfaces.base = screen->pixels; - surfaces.size = (unsigned int)((long)base - (long)surfaces.base); - surfaces.next = bucket; - screen->hwdata = (struct private_hwdata *)&surfaces; - return(0); + vidmem_bucket *bucket; + + surfaces_memtotal = size; + surfaces_memleft = size; + + if (surfaces_memleft > 0) { + bucket = (vidmem_bucket *) SDL_malloc(sizeof(*bucket)); + if (bucket == NULL) { + SDL_OutOfMemory(); + return (-1); + } + bucket->prev = &surfaces; + bucket->used = 0; + bucket->dirty = 0; + bucket->base = base; + bucket->size = size; + bucket->next = NULL; + } else { + bucket = NULL; + } + + surfaces.prev = NULL; + surfaces.used = 1; + surfaces.dirty = 0; + surfaces.base = screen->pixels; + surfaces.size = (unsigned int) ((long) base - (long) surfaces.base); + surfaces.next = bucket; + screen->hwdata = (struct private_hwdata *) &surfaces; + return (0); } -static void DGA_FreeHWSurfaces(_THIS) +static void +DGA_FreeHWSurfaces(_THIS) { - vidmem_bucket *bucket, *freeable; - - bucket = surfaces.next; - while ( bucket ) { - freeable = bucket; - bucket = bucket->next; - SDL_free(freeable); - } - surfaces.next = NULL; + vidmem_bucket *bucket, *freeable; + + bucket = surfaces.next; + while (bucket) { + freeable = bucket; + bucket = bucket->next; + SDL_free(freeable); + } + surfaces.next = NULL; } -static __inline__ void DGA_AddBusySurface(SDL_Surface *surface) +static __inline__ void +DGA_AddBusySurface(SDL_Surface * surface) { - ((vidmem_bucket *)surface->hwdata)->dirty = 1; + ((vidmem_bucket *) surface->hwdata)->dirty = 1; } -static __inline__ int DGA_IsSurfaceBusy(SDL_Surface *surface) +static __inline__ int +DGA_IsSurfaceBusy(SDL_Surface * surface) { - return ((vidmem_bucket *)surface->hwdata)->dirty; + return ((vidmem_bucket *) surface->hwdata)->dirty; } -static __inline__ void DGA_WaitBusySurfaces(_THIS) +static __inline__ void +DGA_WaitBusySurfaces(_THIS) { - vidmem_bucket *bucket; + vidmem_bucket *bucket; - /* Wait for graphic operations to complete */ - SDL_NAME(XDGASync)(DGA_Display, DGA_Screen); + /* Wait for graphic operations to complete */ + SDL_NAME(XDGASync) (DGA_Display, DGA_Screen); - /* Clear all surface dirty bits */ - for ( bucket=&surfaces; bucket; bucket=bucket->next ) { - bucket->dirty = 0; - } + /* Clear all surface dirty bits */ + for (bucket = &surfaces; bucket; bucket = bucket->next) { + bucket->dirty = 0; + } } -static int DGA_AllocHWSurface(_THIS, SDL_Surface *surface) +static int +DGA_AllocHWSurface(_THIS, SDL_Surface * surface) { - vidmem_bucket *bucket; - int size; - int extra; - int retval = 0; + vidmem_bucket *bucket; + int size; + int extra; + int retval = 0; /* Temporarily, we only allow surfaces the same width as display. Some blitters require the pitch between two hardware surfaces to be the same. Others have interesting alignment restrictions. */ -if ( surface->pitch > SDL_VideoSurface->pitch ) { - SDL_SetError("Surface requested wider than screen"); - return(-1); -} -surface->pitch = SDL_VideoSurface->pitch; - size = surface->h * surface->pitch; + if (surface->pitch > SDL_VideoSurface->pitch) { + SDL_SetError("Surface requested wider than screen"); + return (-1); + } + surface->pitch = SDL_VideoSurface->pitch; + size = surface->h * surface->pitch; #ifdef DGA_DEBUG - fprintf(stderr, "Allocating bucket of %d bytes\n", size); + fprintf(stderr, "Allocating bucket of %d bytes\n", size); #endif - LOCK_DISPLAY(); - - /* Quick check for available mem */ - if ( size > surfaces_memleft ) { - SDL_SetError("Not enough video memory"); - retval = -1; - goto done; - } - - /* Search for an empty bucket big enough */ - for ( bucket=&surfaces; bucket; bucket=bucket->next ) { - if ( ! bucket->used && (size <= bucket->size) ) { - break; - } - } - if ( bucket == NULL ) { - SDL_SetError("Video memory too fragmented"); - retval = -1; - goto done; - } - - /* Create a new bucket for left-over memory */ - extra = (bucket->size - size); - if ( extra ) { - vidmem_bucket *newbucket; + LOCK_DISPLAY(); + + /* Quick check for available mem */ + if (size > surfaces_memleft) { + SDL_SetError("Not enough video memory"); + retval = -1; + goto done; + } + + /* Search for an empty bucket big enough */ + for (bucket = &surfaces; bucket; bucket = bucket->next) { + if (!bucket->used && (size <= bucket->size)) { + break; + } + } + if (bucket == NULL) { + SDL_SetError("Video memory too fragmented"); + retval = -1; + goto done; + } + + /* Create a new bucket for left-over memory */ + extra = (bucket->size - size); + if (extra) { + vidmem_bucket *newbucket; #ifdef DGA_DEBUG - fprintf(stderr, "Adding new free bucket of %d bytes\n", extra); + fprintf(stderr, "Adding new free bucket of %d bytes\n", extra); #endif - newbucket = (vidmem_bucket *)SDL_malloc(sizeof(*newbucket)); - if ( newbucket == NULL ) { - SDL_OutOfMemory(); - retval = -1; - goto done; - } - newbucket->prev = bucket; - newbucket->used = 0; - newbucket->base = bucket->base+size; - newbucket->size = extra; - newbucket->next = bucket->next; - if ( bucket->next ) { - bucket->next->prev = newbucket; - } - bucket->next = newbucket; - } - - /* Set the current bucket values and return it! */ - bucket->used = 1; - bucket->size = size; - bucket->dirty = 0; + newbucket = (vidmem_bucket *) SDL_malloc(sizeof(*newbucket)); + if (newbucket == NULL) { + SDL_OutOfMemory(); + retval = -1; + goto done; + } + newbucket->prev = bucket; + newbucket->used = 0; + newbucket->base = bucket->base + size; + newbucket->size = extra; + newbucket->next = bucket->next; + if (bucket->next) { + bucket->next->prev = newbucket; + } + bucket->next = newbucket; + } + + /* Set the current bucket values and return it! */ + bucket->used = 1; + bucket->size = size; + bucket->dirty = 0; #ifdef DGA_DEBUG - fprintf(stderr, "Allocated %d bytes at %p\n", bucket->size, bucket->base); + fprintf(stderr, "Allocated %d bytes at %p\n", bucket->size, bucket->base); #endif - surfaces_memleft -= size; - surface->flags |= SDL_HWSURFACE; - surface->pixels = bucket->base; - surface->hwdata = (struct private_hwdata *)bucket; -done: - UNLOCK_DISPLAY(); - return(retval); + surfaces_memleft -= size; + surface->flags |= SDL_HWSURFACE; + surface->pixels = bucket->base; + surface->hwdata = (struct private_hwdata *) bucket; + done: + UNLOCK_DISPLAY(); + return (retval); } -static void DGA_FreeHWSurface(_THIS, SDL_Surface *surface) +static void +DGA_FreeHWSurface(_THIS, SDL_Surface * surface) { - vidmem_bucket *bucket, *freeable; - - /* Wait for any pending operations involving this surface */ - if ( DGA_IsSurfaceBusy(surface) ) { - LOCK_DISPLAY(); - DGA_WaitBusySurfaces(this); - UNLOCK_DISPLAY(); - } - - /* Look for the bucket in the current list */ - for ( bucket=&surfaces; bucket; bucket=bucket->next ) { - if ( bucket == (vidmem_bucket *)surface->hwdata ) { - break; - } - } - if ( bucket && bucket->used ) { - /* Add the memory back to the total */ + vidmem_bucket *bucket, *freeable; + + /* Wait for any pending operations involving this surface */ + if (DGA_IsSurfaceBusy(surface)) { + LOCK_DISPLAY(); + DGA_WaitBusySurfaces(this); + UNLOCK_DISPLAY(); + } + + /* Look for the bucket in the current list */ + for (bucket = &surfaces; bucket; bucket = bucket->next) { + if (bucket == (vidmem_bucket *) surface->hwdata) { + break; + } + } + if (bucket && bucket->used) { + /* Add the memory back to the total */ #ifdef DGA_DEBUG - printf("Freeing bucket of %d bytes\n", bucket->size); + printf("Freeing bucket of %d bytes\n", bucket->size); #endif - surfaces_memleft += bucket->size; + surfaces_memleft += bucket->size; - /* Can we merge the space with surrounding buckets? */ - bucket->used = 0; - if ( bucket->next && ! bucket->next->used ) { + /* Can we merge the space with surrounding buckets? */ + bucket->used = 0; + if (bucket->next && !bucket->next->used) { #ifdef DGA_DEBUG - printf("Merging with next bucket, for %d total bytes\n", bucket->size+bucket->next->size); + printf("Merging with next bucket, for %d total bytes\n", + bucket->size + bucket->next->size); #endif - freeable = bucket->next; - bucket->size += bucket->next->size; - bucket->next = bucket->next->next; - if ( bucket->next ) { - bucket->next->prev = bucket; - } - SDL_free(freeable); - } - if ( bucket->prev && ! bucket->prev->used ) { + freeable = bucket->next; + bucket->size += bucket->next->size; + bucket->next = bucket->next->next; + if (bucket->next) { + bucket->next->prev = bucket; + } + SDL_free(freeable); + } + if (bucket->prev && !bucket->prev->used) { #ifdef DGA_DEBUG - printf("Merging with previous bucket, for %d total bytes\n", bucket->prev->size+bucket->size); + printf("Merging with previous bucket, for %d total bytes\n", + bucket->prev->size + bucket->size); #endif - freeable = bucket; - bucket->prev->size += bucket->size; - bucket->prev->next = bucket->next; - if ( bucket->next ) { - bucket->next->prev = bucket->prev; - } - SDL_free(freeable); - } - } - surface->pixels = NULL; - surface->hwdata = NULL; + freeable = bucket; + bucket->prev->size += bucket->size; + bucket->prev->next = bucket->next; + if (bucket->next) { + bucket->next->prev = bucket->prev; + } + SDL_free(freeable); + } + } + surface->pixels = NULL; + surface->hwdata = NULL; } -static __inline__ void DGA_dst_to_xy(_THIS, SDL_Surface *dst, int *x, int *y) +static __inline__ void +DGA_dst_to_xy(_THIS, SDL_Surface * dst, int *x, int *y) { - *x = (long)((Uint8 *)dst->pixels - memory_base)%memory_pitch; - *y = (long)((Uint8 *)dst->pixels - memory_base)/memory_pitch; + *x = (long) ((Uint8 *) dst->pixels - memory_base) % memory_pitch; + *y = (long) ((Uint8 *) dst->pixels - memory_base) / memory_pitch; } -static int DGA_FillHWRect(_THIS, SDL_Surface *dst, SDL_Rect *rect, Uint32 color) +static int +DGA_FillHWRect(_THIS, SDL_Surface * dst, SDL_Rect * rect, Uint32 color) { - int x, y; - unsigned int w, h; - - /* Don't fill the visible part of the screen, wait until flipped */ - LOCK_DISPLAY(); - if ( was_flipped && (dst == this->screen) ) { - while ( SDL_NAME(XDGAGetViewportStatus)(DGA_Display, DGA_Screen) ) - /* Keep waiting for the hardware ... */ ; - was_flipped = 0; - } - DGA_dst_to_xy(this, dst, &x, &y); - x += rect->x; - y += rect->y; - w = rect->w; - h = rect->h; + int x, y; + unsigned int w, h; + + /* Don't fill the visible part of the screen, wait until flipped */ + LOCK_DISPLAY(); + if (was_flipped && (dst == this->screen)) { + while (SDL_NAME(XDGAGetViewportStatus) (DGA_Display, DGA_Screen)) + /* Keep waiting for the hardware ... */ ; + was_flipped = 0; + } + DGA_dst_to_xy(this, dst, &x, &y); + x += rect->x; + y += rect->y; + w = rect->w; + h = rect->h; #if 0 - printf("Hardware accelerated rectangle fill: %dx%d at %d,%d\n", w, h, x, y); + printf("Hardware accelerated rectangle fill: %dx%d at %d,%d\n", w, h, x, + y); #endif - SDL_NAME(XDGAFillRectangle)(DGA_Display, DGA_Screen, x, y, w, h, color); - if ( !(this->screen->flags & SDL_DOUBLEBUF) ) { - XFlush(DGA_Display); - } - DGA_AddBusySurface(dst); - UNLOCK_DISPLAY(); - return(0); + SDL_NAME(XDGAFillRectangle) (DGA_Display, DGA_Screen, x, y, w, h, color); + if (!(this->screen->flags & SDL_DOUBLEBUF)) { + XFlush(DGA_Display); + } + DGA_AddBusySurface(dst); + UNLOCK_DISPLAY(); + return (0); } -static int HWAccelBlit(SDL_Surface *src, SDL_Rect *srcrect, - SDL_Surface *dst, SDL_Rect *dstrect) +static int +HWAccelBlit(SDL_Surface * src, SDL_Rect * srcrect, + SDL_Surface * dst, SDL_Rect * dstrect) { - SDL_VideoDevice *this; - int srcx, srcy; - int dstx, dsty; - unsigned int w, h; - - this = current_video; - /* Don't blit to the visible part of the screen, wait until flipped */ - LOCK_DISPLAY(); - if ( was_flipped && (dst == this->screen) ) { - while ( SDL_NAME(XDGAGetViewportStatus)(DGA_Display, DGA_Screen) ) - /* Keep waiting for the hardware ... */ ; - was_flipped = 0; - } - DGA_dst_to_xy(this, src, &srcx, &srcy); - srcx += srcrect->x; - srcy += srcrect->y; - DGA_dst_to_xy(this, dst, &dstx, &dsty); - dstx += dstrect->x; - dsty += dstrect->y; - w = srcrect->w; - h = srcrect->h; + SDL_VideoDevice *this; + int srcx, srcy; + int dstx, dsty; + unsigned int w, h; + + this = current_video; + /* Don't blit to the visible part of the screen, wait until flipped */ + LOCK_DISPLAY(); + if (was_flipped && (dst == this->screen)) { + while (SDL_NAME(XDGAGetViewportStatus) (DGA_Display, DGA_Screen)) + /* Keep waiting for the hardware ... */ ; + was_flipped = 0; + } + DGA_dst_to_xy(this, src, &srcx, &srcy); + srcx += srcrect->x; + srcy += srcrect->y; + DGA_dst_to_xy(this, dst, &dstx, &dsty); + dstx += dstrect->x; + dsty += dstrect->y; + w = srcrect->w; + h = srcrect->h; #if 0 - printf("Blitting %dx%d from %d,%d to %d,%d\n", w, h, srcx, srcy, dstx, dsty); + printf("Blitting %dx%d from %d,%d to %d,%d\n", w, h, srcx, srcy, dstx, + dsty); #endif - if ( (src->flags & SDL_SRCCOLORKEY) == SDL_SRCCOLORKEY ) { - SDL_NAME(XDGACopyTransparentArea)(DGA_Display, DGA_Screen, - srcx, srcy, w, h, dstx, dsty, src->format->colorkey); - } else { - SDL_NAME(XDGACopyArea)(DGA_Display, DGA_Screen, - srcx, srcy, w, h, dstx, dsty); - } - if ( !(this->screen->flags & SDL_DOUBLEBUF) ) { - XFlush(DGA_Display); - } - DGA_AddBusySurface(src); - DGA_AddBusySurface(dst); - UNLOCK_DISPLAY(); - return(0); + if ((src->flags & SDL_SRCCOLORKEY) == SDL_SRCCOLORKEY) { + SDL_NAME(XDGACopyTransparentArea) (DGA_Display, DGA_Screen, + srcx, srcy, w, h, dstx, dsty, + src->format->colorkey); + } else { + SDL_NAME(XDGACopyArea) (DGA_Display, DGA_Screen, + srcx, srcy, w, h, dstx, dsty); + } + if (!(this->screen->flags & SDL_DOUBLEBUF)) { + XFlush(DGA_Display); + } + DGA_AddBusySurface(src); + DGA_AddBusySurface(dst); + UNLOCK_DISPLAY(); + return (0); } -static int DGA_CheckHWBlit(_THIS, SDL_Surface *src, SDL_Surface *dst) +static int +DGA_CheckHWBlit(_THIS, SDL_Surface * src, SDL_Surface * dst) { - int accelerated; - - /* Set initial acceleration on */ - src->flags |= SDL_HWACCEL; - - /* Set the surface attributes */ - if ( (src->flags & SDL_SRCALPHA) == SDL_SRCALPHA ) { - if ( ! this->info.blit_hw_A ) { - src->flags &= ~SDL_HWACCEL; - } - } - if ( (src->flags & SDL_SRCCOLORKEY) == SDL_SRCCOLORKEY ) { - if ( ! this->info.blit_hw_CC ) { - src->flags &= ~SDL_HWACCEL; - } - } - - /* Check to see if final surface blit is accelerated */ - accelerated = !!(src->flags & SDL_HWACCEL); - if ( accelerated ) { - src->map->hw_blit = HWAccelBlit; - } - return(accelerated); + int accelerated; + + /* Set initial acceleration on */ + src->flags |= SDL_HWACCEL; + + /* Set the surface attributes */ + if ((src->flags & SDL_SRCALPHA) == SDL_SRCALPHA) { + if (!this->info.blit_hw_A) { + src->flags &= ~SDL_HWACCEL; + } + } + if ((src->flags & SDL_SRCCOLORKEY) == SDL_SRCCOLORKEY) { + if (!this->info.blit_hw_CC) { + src->flags &= ~SDL_HWACCEL; + } + } + + /* Check to see if final surface blit is accelerated */ + accelerated = !!(src->flags & SDL_HWACCEL); + if (accelerated) { + src->map->hw_blit = HWAccelBlit; + } + return (accelerated); } -static __inline__ void DGA_WaitFlip(_THIS) +static __inline__ void +DGA_WaitFlip(_THIS) { - if ( was_flipped ) { - while ( SDL_NAME(XDGAGetViewportStatus)(DGA_Display, DGA_Screen) ) - /* Keep waiting for the hardware ... */ ; - was_flipped = 0; - } + if (was_flipped) { + while (SDL_NAME(XDGAGetViewportStatus) (DGA_Display, DGA_Screen)) + /* Keep waiting for the hardware ... */ ; + was_flipped = 0; + } } -static int DGA_LockHWSurface(_THIS, SDL_Surface *surface) +static int +DGA_LockHWSurface(_THIS, SDL_Surface * surface) { - if ( surface == this->screen ) { - SDL_mutexP(hw_lock); - LOCK_DISPLAY(); - if ( DGA_IsSurfaceBusy(surface) ) { - DGA_WaitBusySurfaces(this); - } - DGA_WaitFlip(this); - UNLOCK_DISPLAY(); - } else { - if ( DGA_IsSurfaceBusy(surface) ) { - LOCK_DISPLAY(); - DGA_WaitBusySurfaces(this); - UNLOCK_DISPLAY(); - } - } - return(0); + if (surface == this->screen) { + SDL_mutexP(hw_lock); + LOCK_DISPLAY(); + if (DGA_IsSurfaceBusy(surface)) { + DGA_WaitBusySurfaces(this); + } + DGA_WaitFlip(this); + UNLOCK_DISPLAY(); + } else { + if (DGA_IsSurfaceBusy(surface)) { + LOCK_DISPLAY(); + DGA_WaitBusySurfaces(this); + UNLOCK_DISPLAY(); + } + } + return (0); } -static void DGA_UnlockHWSurface(_THIS, SDL_Surface *surface) +static void +DGA_UnlockHWSurface(_THIS, SDL_Surface * surface) { - if ( surface == this->screen ) { - SDL_mutexV(hw_lock); - } + if (surface == this->screen) { + SDL_mutexV(hw_lock); + } } -static int DGA_FlipHWSurface(_THIS, SDL_Surface *surface) +static int +DGA_FlipHWSurface(_THIS, SDL_Surface * surface) { - /* Wait for vertical retrace and then flip display */ - LOCK_DISPLAY(); - if ( DGA_IsSurfaceBusy(this->screen) ) { - DGA_WaitBusySurfaces(this); - } - DGA_WaitFlip(this); - SDL_NAME(XDGASetViewport)(DGA_Display, DGA_Screen, - 0, flip_yoffset[flip_page], XDGAFlipRetrace); - XFlush(DGA_Display); - UNLOCK_DISPLAY(); - was_flipped = 1; - flip_page = !flip_page; - - surface->pixels = flip_address[flip_page]; - return(0); + /* Wait for vertical retrace and then flip display */ + LOCK_DISPLAY(); + if (DGA_IsSurfaceBusy(this->screen)) { + DGA_WaitBusySurfaces(this); + } + DGA_WaitFlip(this); + SDL_NAME(XDGASetViewport) (DGA_Display, DGA_Screen, + 0, flip_yoffset[flip_page], XDGAFlipRetrace); + XFlush(DGA_Display); + UNLOCK_DISPLAY(); + was_flipped = 1; + flip_page = !flip_page; + + surface->pixels = flip_address[flip_page]; + return (0); } -static void DGA_DirectUpdate(_THIS, int numrects, SDL_Rect *rects) +static void +DGA_DirectUpdate(_THIS, int numrects, SDL_Rect * rects) { - /* The application is already updating the visible video memory */ - return; + /* The application is already updating the visible video memory */ + return; } -static int DGA_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color *colors) +static int +DGA_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color * colors) { - int i; - XColor *xcmap; - - /* This happens on initialization */ - if ( ! DGA_colormap ) { - return(0); - } - xcmap = SDL_stack_alloc(XColor, ncolors); - for ( i=0; iscreen->format->BitsPerPixel <= 16 ) { - ncolors = 64; /* Is this right? */ - } else { - ncolors = 256; - } - for ( i=0; iscreen->format, c, c, c); - xcmap[i].red = ramp[0*256+c]; - xcmap[i].green = ramp[1*256+c]; - xcmap[i].blue = ramp[2*256+c]; - xcmap[i].flags = (DoRed|DoGreen|DoBlue); - } - LOCK_DISPLAY(); - XStoreColors(DGA_Display, DGA_colormap, xcmap, ncolors); - XSync(DGA_Display, False); - UNLOCK_DISPLAY(); - return(0); + int i, ncolors; + XColor xcmap[256]; + + /* See if actually setting the gamma is supported */ + if (DGA_visualClass != DirectColor) { + SDL_SetError("Gamma correction not supported on this visual"); + return (-1); + } + + /* Calculate the appropriate palette for the given gamma ramp */ + if (this->screen->format->BitsPerPixel <= 16) { + ncolors = 64; /* Is this right? */ + } else { + ncolors = 256; + } + for (i = 0; i < ncolors; ++i) { + Uint8 c = (256 * i / ncolors); + xcmap[i].pixel = SDL_MapRGB(this->screen->format, c, c, c); + xcmap[i].red = ramp[0 * 256 + c]; + xcmap[i].green = ramp[1 * 256 + c]; + xcmap[i].blue = ramp[2 * 256 + c]; + xcmap[i].flags = (DoRed | DoGreen | DoBlue); + } + LOCK_DISPLAY(); + XStoreColors(DGA_Display, DGA_colormap, xcmap, ncolors); + XSync(DGA_Display, False); + UNLOCK_DISPLAY(); + return (0); } -void DGA_VideoQuit(_THIS) +void +DGA_VideoQuit(_THIS) { - int i, j; - - if ( DGA_Display ) { - /* Free colormap, if necessary */ - if ( DGA_colormap ) { - XFreeColormap(DGA_Display, DGA_colormap); - DGA_colormap = 0; - } - - /* Unmap memory and reset video mode */ - SDL_NAME(XDGACloseFramebuffer)(DGA_Display, DGA_Screen); - if ( this->screen ) { - /* Tell SDL not to free the pixels */ - DGA_FreeHWSurface(this, this->screen); - } - SDL_NAME(XDGASetMode)(DGA_Display, DGA_Screen, 0); - - /* Clear the lock mutex */ - if ( hw_lock != NULL ) { - SDL_DestroyMutex(hw_lock); - hw_lock = NULL; - } + int i, j; + + if (DGA_Display) { + /* Free colormap, if necessary */ + if (DGA_colormap) { + XFreeColormap(DGA_Display, DGA_colormap); + DGA_colormap = 0; + } + + /* Unmap memory and reset video mode */ + SDL_NAME(XDGACloseFramebuffer) (DGA_Display, DGA_Screen); + if (this->screen) { + /* Tell SDL not to free the pixels */ + DGA_FreeHWSurface(this, this->screen); + } + SDL_NAME(XDGASetMode) (DGA_Display, DGA_Screen, 0); + + /* Clear the lock mutex */ + if (hw_lock != NULL) { + SDL_DestroyMutex(hw_lock); + hw_lock = NULL; + } #ifdef LOCK_DGA_DISPLAY - if ( event_lock != NULL ) { - SDL_DestroyMutex(event_lock); - event_lock = NULL; - } + if (event_lock != NULL) { + SDL_DestroyMutex(event_lock); + event_lock = NULL; + } #endif /* LOCK_DGA_DISPLAY */ - /* Clean up defined video modes */ - for ( i=0; ihidden->DGA_Display) @@ -120,3 +122,4 @@ struct SDL_PrivateVideoData { #define dpms_enabled (this->hidden->dpms_enabled) #endif /* _SDL_dgavideo_h */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/directfb/SDL_DirectFB_events.c b/src/video/directfb/SDL_DirectFB_events.c index 0864d9ac5..e5d7b7553 100644 --- a/src/video/directfb/SDL_DirectFB_events.c +++ b/src/video/directfb/SDL_DirectFB_events.c @@ -40,171 +40,181 @@ /* The translation tables from a DirectFB keycode to a SDL keysym */ static SDLKey keymap[256]; -static SDL_keysym *DirectFB_TranslateKey (DFBInputEvent *ev, SDL_keysym *keysym); -static int DirectFB_TranslateButton (DFBInputEvent *ev); +static SDL_keysym *DirectFB_TranslateKey(DFBInputEvent * ev, + SDL_keysym * keysym); +static int DirectFB_TranslateButton(DFBInputEvent * ev); static int posted = 0; -void DirectFB_PumpEvents (_THIS) +void +DirectFB_PumpEvents(_THIS) { - DFBInputEvent evt; + DFBInputEvent evt; - while (HIDDEN->eventbuffer->GetEvent (HIDDEN->eventbuffer, - DFB_EVENT (&evt)) == DFB_OK) - { - SDL_keysym keysym; + while (HIDDEN->eventbuffer->GetEvent(HIDDEN->eventbuffer, + DFB_EVENT(&evt)) == DFB_OK) { + SDL_keysym keysym; - switch (evt.type) - { + switch (evt.type) { case DIET_BUTTONPRESS: - posted += SDL_PrivateMouseButton(SDL_PRESSED, - DirectFB_TranslateButton (&evt), 0, 0); - break; + posted += SDL_PrivateMouseButton(SDL_PRESSED, + DirectFB_TranslateButton + (&evt), 0, 0); + break; case DIET_BUTTONRELEASE: - posted += SDL_PrivateMouseButton(SDL_RELEASED, - DirectFB_TranslateButton (&evt), 0, 0); - break; + posted += SDL_PrivateMouseButton(SDL_RELEASED, + DirectFB_TranslateButton + (&evt), 0, 0); + break; case DIET_KEYPRESS: - posted += SDL_PrivateKeyboard(SDL_PRESSED, DirectFB_TranslateKey(&evt, &keysym)); - break; + posted += + SDL_PrivateKeyboard(SDL_PRESSED, + DirectFB_TranslateKey(&evt, &keysym)); + break; case DIET_KEYRELEASE: - posted += SDL_PrivateKeyboard(SDL_RELEASED, DirectFB_TranslateKey(&evt, &keysym)); - break; + posted += + SDL_PrivateKeyboard(SDL_RELEASED, + DirectFB_TranslateKey(&evt, &keysym)); + break; case DIET_AXISMOTION: - if (evt.flags & DIEF_AXISREL) - { - if (evt.axis == DIAI_X) - posted += SDL_PrivateMouseMotion(0, 1, evt.axisrel, 0); - else if (evt.axis == DIAI_Y) - posted += SDL_PrivateMouseMotion(0, 1, 0, evt.axisrel); + if (evt.flags & DIEF_AXISREL) { + if (evt.axis == DIAI_X) + posted += SDL_PrivateMouseMotion(0, 1, evt.axisrel, 0); + else if (evt.axis == DIAI_Y) + posted += SDL_PrivateMouseMotion(0, 1, 0, evt.axisrel); } - break; + break; default: - ; + ; } } } -void DirectFB_InitOSKeymap (_THIS) +void +DirectFB_InitOSKeymap(_THIS) { - int i; - - /* Initialize the DirectFB key translation table */ - for (i=0; iscancode = ev->key_id; - keysym->mod = KMOD_NONE; /* FIXME */ - keysym->unicode = (DFB_KEY_TYPE (ev->key_symbol) == DIKT_UNICODE) ? ev->key_symbol : 0; - - if (ev->key_symbol > 0 && ev->key_symbol < 128) - keysym->sym = ev->key_symbol; - else - keysym->sym = keymap[ev->key_id - DIKI_UNKNOWN]; - - return keysym; + /* Set the keysym information */ + keysym->scancode = ev->key_id; + keysym->mod = KMOD_NONE; /* FIXME */ + keysym->unicode = + (DFB_KEY_TYPE(ev->key_symbol) == DIKT_UNICODE) ? ev->key_symbol : 0; + + if (ev->key_symbol > 0 && ev->key_symbol < 128) + keysym->sym = ev->key_symbol; + else + keysym->sym = keymap[ev->key_id - DIKI_UNKNOWN]; + + return keysym; } -static int DirectFB_TranslateButton (DFBInputEvent *ev) +static int +DirectFB_TranslateButton(DFBInputEvent * ev) { - switch (ev->button) - { + switch (ev->button) { case DIBI_LEFT: - return 1; + return 1; case DIBI_MIDDLE: - return 2; + return 2; case DIBI_RIGHT: - return 3; + return 3; default: - return 0; + return 0; } } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/directfb/SDL_DirectFB_events.h b/src/video/directfb/SDL_DirectFB_events.h index b4b4370b8..7385db078 100644 --- a/src/video/directfb/SDL_DirectFB_events.h +++ b/src/video/directfb/SDL_DirectFB_events.h @@ -26,4 +26,4 @@ /* Functions to be exported */ extern void DirectFB_InitOSKeymap(_THIS); extern void DirectFB_PumpEvents(_THIS); - +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/directfb/SDL_DirectFB_keys.h b/src/video/directfb/SDL_DirectFB_keys.h index 2868ee6ff..0137cd743 100644 --- a/src/video/directfb/SDL_DirectFB_keys.h +++ b/src/video/directfb/SDL_DirectFB_keys.h @@ -116,20 +116,20 @@ #define SCANCODE_KEYPADDIVIDE 98 #define SCANCODE_PRINTSCREEN 99 #define SCANCODE_RIGHTALT 100 -#define SCANCODE_BREAK 101 /* Beware: is 119 */ -#define SCANCODE_BREAK_ALTERNATIVE 119 /* on some keyboards! */ +#define SCANCODE_BREAK 101 /* Beware: is 119 */ +#define SCANCODE_BREAK_ALTERNATIVE 119 /* on some keyboards! */ #define SCANCODE_HOME 102 -#define SCANCODE_CURSORBLOCKUP 90 /* Cursor key block */ +#define SCANCODE_CURSORBLOCKUP 90 /* Cursor key block */ #define SCANCODE_PAGEUP 104 -#define SCANCODE_CURSORBLOCKLEFT 92 /* Cursor key block */ -#define SCANCODE_CURSORBLOCKRIGHT 94 /* Cursor key block */ +#define SCANCODE_CURSORBLOCKLEFT 92 /* Cursor key block */ +#define SCANCODE_CURSORBLOCKRIGHT 94 /* Cursor key block */ #define SCANCODE_END 107 -#define SCANCODE_CURSORBLOCKDOWN 108 /* Cursor key block */ +#define SCANCODE_CURSORBLOCKDOWN 108 /* Cursor key block */ #define SCANCODE_PAGEDOWN 109 #define SCANCODE_INSERT 110 #define SCANCODE_REMOVE 111 #define SCANCODE_RIGHTWIN 126 #define SCANCODE_LEFTWIN 125 - +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/directfb/SDL_DirectFB_video.c b/src/video/directfb/SDL_DirectFB_video.c index 696b5c3b1..2c350dc64 100644 --- a/src/video/directfb/SDL_DirectFB_video.c +++ b/src/video/directfb/SDL_DirectFB_video.c @@ -45,41 +45,47 @@ #include "SDL_DirectFB_yuv.h" /* The implementation dependent data for the window manager cursor */ -struct WMcursor { - int unused; +struct WMcursor +{ + int unused; }; /* Initialization/Query functions */ -static int DirectFB_VideoInit(_THIS, SDL_PixelFormat *vformat); -static SDL_Rect **DirectFB_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags); -static SDL_Surface *DirectFB_SetVideoMode(_THIS, SDL_Surface *current, int width, int height, int bpp, Uint32 flags); +static int DirectFB_VideoInit(_THIS, SDL_PixelFormat * vformat); +static SDL_Rect **DirectFB_ListModes(_THIS, SDL_PixelFormat * format, + Uint32 flags); +static SDL_Surface *DirectFB_SetVideoMode(_THIS, SDL_Surface * current, + int width, int height, int bpp, + Uint32 flags); static int DirectFB_SetColors(_THIS, int firstcolor, int ncolors, - SDL_Color *colors); + SDL_Color * colors); static void DirectFB_VideoQuit(_THIS); /* Hardware surface functions */ -static int DirectFB_AllocHWSurface(_THIS, SDL_Surface *surface); -static int DirectFB_FillHWRect(_THIS, SDL_Surface *dst, SDL_Rect *dstrect, Uint32 color); -static int DirectFB_LockHWSurface(_THIS, SDL_Surface *surface); -static void DirectFB_UnlockHWSurface(_THIS, SDL_Surface *surface); -static void DirectFB_FreeHWSurface(_THIS, SDL_Surface *surface); -static int DirectFB_CheckHWBlit(_THIS, SDL_Surface *src, SDL_Surface *dst); -static int DirectFB_HWAccelBlit(SDL_Surface *src, SDL_Rect *srcrect, - SDL_Surface *dst, SDL_Rect *dstrect); -static int DirectFB_SetHWColorKey(_THIS, SDL_Surface *surface, Uint32 key); -static int DirectFB_SetHWAlpha(_THIS, SDL_Surface *surface, Uint8 alpha); -static int DirectFB_FlipHWSurface(_THIS, SDL_Surface *surface); -static int DirectFB_ShowWMCursor(_THIS, WMcursor *cursor); +static int DirectFB_AllocHWSurface(_THIS, SDL_Surface * surface); +static int DirectFB_FillHWRect(_THIS, SDL_Surface * dst, SDL_Rect * dstrect, + Uint32 color); +static int DirectFB_LockHWSurface(_THIS, SDL_Surface * surface); +static void DirectFB_UnlockHWSurface(_THIS, SDL_Surface * surface); +static void DirectFB_FreeHWSurface(_THIS, SDL_Surface * surface); +static int DirectFB_CheckHWBlit(_THIS, SDL_Surface * src, SDL_Surface * dst); +static int DirectFB_HWAccelBlit(SDL_Surface * src, SDL_Rect * srcrect, + SDL_Surface * dst, SDL_Rect * dstrect); +static int DirectFB_SetHWColorKey(_THIS, SDL_Surface * surface, Uint32 key); +static int DirectFB_SetHWAlpha(_THIS, SDL_Surface * surface, Uint8 alpha); +static int DirectFB_FlipHWSurface(_THIS, SDL_Surface * surface); +static int DirectFB_ShowWMCursor(_THIS, WMcursor * cursor); /* Various screen update functions available */ -static void DirectFB_DirectUpdate(_THIS, int numrects, SDL_Rect *rects); -static void DirectFB_WindowedUpdate(_THIS, int numrects, SDL_Rect *rects); +static void DirectFB_DirectUpdate(_THIS, int numrects, SDL_Rect * rects); +static void DirectFB_WindowedUpdate(_THIS, int numrects, SDL_Rect * rects); /* This is the rect EnumModes2 uses */ -struct DirectFBEnumRect { - SDL_Rect r; - struct DirectFBEnumRect* next; +struct DirectFBEnumRect +{ + SDL_Rect r; + struct DirectFBEnumRect *next; }; static struct DirectFBEnumRect *enumlist = NULL; @@ -87,943 +93,953 @@ static struct DirectFBEnumRect *enumlist = NULL; /* DirectFB driver bootstrap functions */ -static int DirectFB_Available(void) +static int +DirectFB_Available(void) { - return 1; + return 1; } -static void DirectFB_DeleteDevice(SDL_VideoDevice *device) +static void +DirectFB_DeleteDevice(SDL_VideoDevice * device) { - SDL_free(device->hidden); - SDL_free(device); + SDL_free(device->hidden); + SDL_free(device); } -static SDL_VideoDevice *DirectFB_CreateDevice(int devindex) +static SDL_VideoDevice * +DirectFB_CreateDevice(int devindex) { - SDL_VideoDevice *device; - - /* Initialize all variables that we clean on shutdown */ - device = (SDL_VideoDevice *)SDL_malloc(sizeof(SDL_VideoDevice)); - if (device) - { - SDL_memset (device, 0, (sizeof *device)); - device->hidden = (struct SDL_PrivateVideoData *) malloc (sizeof (*device->hidden)); + SDL_VideoDevice *device; + + /* Initialize all variables that we clean on shutdown */ + device = (SDL_VideoDevice *) SDL_malloc(sizeof(SDL_VideoDevice)); + if (device) { + SDL_memset(device, 0, (sizeof *device)); + device->hidden = (struct SDL_PrivateVideoData *) + malloc(sizeof(*device->hidden)); } - if (device == NULL || device->hidden == NULL) - { - SDL_OutOfMemory(); - if (device) - { - free (device); + if (device == NULL || device->hidden == NULL) { + SDL_OutOfMemory(); + if (device) { + free(device); } - return(0); + return (0); } - SDL_memset (device->hidden, 0, sizeof (*device->hidden)); - - /* Set the function pointers */ - device->VideoInit = DirectFB_VideoInit; - device->ListModes = DirectFB_ListModes; - device->SetVideoMode = DirectFB_SetVideoMode; - device->SetColors = DirectFB_SetColors; - device->UpdateRects = NULL; - device->CreateYUVOverlay = DirectFB_CreateYUVOverlay; - device->VideoQuit = DirectFB_VideoQuit; - device->AllocHWSurface = DirectFB_AllocHWSurface; - device->CheckHWBlit = DirectFB_CheckHWBlit; - device->FillHWRect = DirectFB_FillHWRect; - device->SetHWColorKey = DirectFB_SetHWColorKey; - device->SetHWAlpha = DirectFB_SetHWAlpha; - device->LockHWSurface = DirectFB_LockHWSurface; - device->UnlockHWSurface = DirectFB_UnlockHWSurface; - device->FlipHWSurface = DirectFB_FlipHWSurface; - device->FreeHWSurface = DirectFB_FreeHWSurface; - device->ShowWMCursor = DirectFB_ShowWMCursor; - device->SetCaption = NULL; - device->SetIcon = NULL; - device->IconifyWindow = NULL; - device->GrabInput = NULL; - device->GetWMInfo = NULL; - device->InitOSKeymap = DirectFB_InitOSKeymap; - device->PumpEvents = DirectFB_PumpEvents; - - device->free = DirectFB_DeleteDevice; - - return device; + SDL_memset(device->hidden, 0, sizeof(*device->hidden)); + + /* Set the function pointers */ + device->VideoInit = DirectFB_VideoInit; + device->ListModes = DirectFB_ListModes; + device->SetVideoMode = DirectFB_SetVideoMode; + device->SetColors = DirectFB_SetColors; + device->UpdateRects = NULL; + device->CreateYUVOverlay = DirectFB_CreateYUVOverlay; + device->VideoQuit = DirectFB_VideoQuit; + device->AllocHWSurface = DirectFB_AllocHWSurface; + device->CheckHWBlit = DirectFB_CheckHWBlit; + device->FillHWRect = DirectFB_FillHWRect; + device->SetHWColorKey = DirectFB_SetHWColorKey; + device->SetHWAlpha = DirectFB_SetHWAlpha; + device->LockHWSurface = DirectFB_LockHWSurface; + device->UnlockHWSurface = DirectFB_UnlockHWSurface; + device->FlipHWSurface = DirectFB_FlipHWSurface; + device->FreeHWSurface = DirectFB_FreeHWSurface; + device->ShowWMCursor = DirectFB_ShowWMCursor; + device->SetCaption = NULL; + device->SetIcon = NULL; + device->IconifyWindow = NULL; + device->GrabInput = NULL; + device->GetWMInfo = NULL; + device->InitOSKeymap = DirectFB_InitOSKeymap; + device->PumpEvents = DirectFB_PumpEvents; + + device->free = DirectFB_DeleteDevice; + + return device; } VideoBootStrap DirectFB_bootstrap = { - "directfb", "DirectFB", - DirectFB_Available, DirectFB_CreateDevice + "directfb", "DirectFB", + DirectFB_Available, DirectFB_CreateDevice }; -static DFBSurfacePixelFormat GetFormatForBpp (int bpp, IDirectFBDisplayLayer *layer) +static DFBSurfacePixelFormat +GetFormatForBpp(int bpp, IDirectFBDisplayLayer * layer) { - DFBDisplayLayerConfig dlc; - int bytes = (bpp + 7) / 8; + DFBDisplayLayerConfig dlc; + int bytes = (bpp + 7) / 8; - layer->GetConfiguration (layer, &dlc); + layer->GetConfiguration(layer, &dlc); - if (bytes == DFB_BYTES_PER_PIXEL(dlc.pixelformat) && bytes > 1) - return dlc.pixelformat; + if (bytes == DFB_BYTES_PER_PIXEL(dlc.pixelformat) && bytes > 1) + return dlc.pixelformat; - switch (bytes) - { + switch (bytes) { case 1: - return DSPF_LUT8; + return DSPF_LUT8; case 2: - return DSPF_RGB16; + return DSPF_RGB16; case 3: - return DSPF_RGB24; + return DSPF_RGB24; case 4: - return DSPF_RGB32; + return DSPF_RGB32; } - return DSPF_UNKNOWN; + return DSPF_UNKNOWN; } -static DFBEnumerationResult EnumModesCallback (int width, - int height, - int bpp, - void *data) +static DFBEnumerationResult +EnumModesCallback(int width, int height, int bpp, void *data) { - SDL_VideoDevice *this = (SDL_VideoDevice *)data; - struct DirectFBEnumRect *enumrect; + SDL_VideoDevice *this = (SDL_VideoDevice *) data; + struct DirectFBEnumRect *enumrect; - HIDDEN->nummodes++; + HIDDEN->nummodes++; - if (enumlist && enumlist->r.w == width && enumlist->r.h == height) - return DFENUM_OK; + if (enumlist && enumlist->r.w == width && enumlist->r.h == height) + return DFENUM_OK; - enumrect = SDL_calloc(1, sizeof(struct DirectFBEnumRect)); - if (!enumrect) - { - SDL_OutOfMemory(); - return DFENUM_CANCEL; + enumrect = SDL_calloc(1, sizeof(struct DirectFBEnumRect)); + if (!enumrect) { + SDL_OutOfMemory(); + return DFENUM_CANCEL; } - enumrect->r.w = (Uint16)width; - enumrect->r.h = (Uint16)height; - enumrect->next = enumlist; + enumrect->r.w = (Uint16) width; + enumrect->r.h = (Uint16) height; + enumrect->next = enumlist; - enumlist = enumrect; + enumlist = enumrect; - return DFENUM_OK; + return DFENUM_OK; } -struct private_hwdata { - IDirectFBSurface *surface; - IDirectFBPalette *palette; +struct private_hwdata +{ + IDirectFBSurface *surface; + IDirectFBPalette *palette; }; -void SetDirectFBerror (const char *function, DFBResult code) +void +SetDirectFBerror(const char *function, DFBResult code) { - const char *error = DirectFBErrorString (code); + const char *error = DirectFBErrorString(code); - if (error) - SDL_SetError("%s: %s", function, error); - else - SDL_SetError("Unknown error code from %s", function); + if (error) + SDL_SetError("%s: %s", function, error); + else + SDL_SetError("Unknown error code from %s", function); } -static DFBSurfacePixelFormat SDLToDFBPixelFormat (SDL_PixelFormat *format) +static DFBSurfacePixelFormat +SDLToDFBPixelFormat(SDL_PixelFormat * format) { - if (format->Rmask && format->Gmask && format->Bmask) - { - switch (format->BitsPerPixel) - { + if (format->Rmask && format->Gmask && format->Bmask) { + switch (format->BitsPerPixel) { case 8: - return DSPF_LUT8; - + return DSPF_LUT8; + case 16: - if (format->Rmask == 0xF800 && - format->Gmask == 0x07E0 && - format->Bmask == 0x001F) - return DSPF_RGB16; - /* fall through */ - + if (format->Rmask == 0xF800 && + format->Gmask == 0x07E0 && format->Bmask == 0x001F) + return DSPF_RGB16; + /* fall through */ + case 15: - if (format->Rmask == 0x7C00 && - format->Gmask == 0x03E0 && - format->Bmask == 0x001F) - return DSPF_ARGB1555; - break; - + if (format->Rmask == 0x7C00 && + format->Gmask == 0x03E0 && format->Bmask == 0x001F) + return DSPF_ARGB1555; + break; + case 24: - if (format->Rmask == 0xFF0000 && - format->Gmask == 0x00FF00 && - format->Bmask == 0x0000FF) - return DSPF_RGB24; - break; + if (format->Rmask == 0xFF0000 && + format->Gmask == 0x00FF00 && format->Bmask == 0x0000FF) + return DSPF_RGB24; + break; case 32: - if (format->Rmask == 0xFF0000 && - format->Gmask == 0x00FF00 && - format->Bmask == 0x0000FF) - { - if (format->Amask == 0xFF000000) - return DSPF_ARGB; - else - return DSPF_RGB32; + if (format->Rmask == 0xFF0000 && + format->Gmask == 0x00FF00 && format->Bmask == 0x0000FF) { + if (format->Amask == 0xFF000000) + return DSPF_ARGB; + else + return DSPF_RGB32; } - break; + break; } - } - else - { - switch (format->BitsPerPixel) - { + } else { + switch (format->BitsPerPixel) { case 8: - return DSPF_LUT8; - case 15: - return DSPF_ARGB1555; - case 16: - return DSPF_RGB16; - case 24: - return DSPF_RGB24; - case 32: - return DSPF_RGB32; - } + return DSPF_LUT8; + case 15: + return DSPF_ARGB1555; + case 16: + return DSPF_RGB16; + case 24: + return DSPF_RGB24; + case 32: + return DSPF_RGB32; + } } - return DSPF_UNKNOWN; + return DSPF_UNKNOWN; } -static SDL_Palette *AllocatePalette(int size) +static SDL_Palette * +AllocatePalette(int size) { - SDL_Palette *palette; - SDL_Color *colors; - - palette = SDL_calloc (1, sizeof(SDL_Palette)); - if (!palette) - { - SDL_OutOfMemory(); - return NULL; + SDL_Palette *palette; + SDL_Color *colors; + + palette = SDL_calloc(1, sizeof(SDL_Palette)); + if (!palette) { + SDL_OutOfMemory(); + return NULL; } - colors = SDL_calloc (size, sizeof(SDL_Color)); - if (!colors) - { - SDL_OutOfMemory(); - return NULL; + colors = SDL_calloc(size, sizeof(SDL_Color)); + if (!colors) { + SDL_OutOfMemory(); + return NULL; } - palette->ncolors = size; - palette->colors = colors; + palette->ncolors = size; + palette->colors = colors; - return palette; + return palette; } -static int DFBToSDLPixelFormat (DFBSurfacePixelFormat pixelformat, SDL_PixelFormat *format) +static int +DFBToSDLPixelFormat(DFBSurfacePixelFormat pixelformat, + SDL_PixelFormat * format) { - format->Amask = format->Rmask = format->Gmask = format->Bmask = 0; - format->BitsPerPixel = format->BytesPerPixel = 0; + format->Amask = format->Rmask = format->Gmask = format->Bmask = 0; + format->BitsPerPixel = format->BytesPerPixel = 0; - switch (pixelformat) - { + switch (pixelformat) { case DSPF_A8: - format->Amask = 0x000000FF; - break; + format->Amask = 0x000000FF; + break; case DSPF_ARGB1555: - format->Rmask = 0x00007C00; - format->Gmask = 0x000003E0; - format->Bmask = 0x0000001F; - break; + format->Rmask = 0x00007C00; + format->Gmask = 0x000003E0; + format->Bmask = 0x0000001F; + break; case DSPF_RGB16: - format->Rmask = 0x0000F800; - format->Gmask = 0x000007E0; - format->Bmask = 0x0000001F; - break; + format->Rmask = 0x0000F800; + format->Gmask = 0x000007E0; + format->Bmask = 0x0000001F; + break; case DSPF_ARGB: - format->Amask = 0; /* apps don't seem to like that: 0xFF000000; */ - /* fall through */ + format->Amask = 0; /* apps don't seem to like that: 0xFF000000; */ + /* fall through */ case DSPF_RGB24: case DSPF_RGB32: - format->Rmask = 0x00FF0000; - format->Gmask = 0x0000FF00; - format->Bmask = 0x000000FF; - break; + format->Rmask = 0x00FF0000; + format->Gmask = 0x0000FF00; + format->Bmask = 0x000000FF; + break; case DSPF_LUT8: - format->Rmask = 0x000000FF; - format->Gmask = 0x000000FF; - format->Bmask = 0x000000FF; + format->Rmask = 0x000000FF; + format->Gmask = 0x000000FF; + format->Bmask = 0x000000FF; - if (!format->palette) - format->palette = AllocatePalette(256); - break; + if (!format->palette) + format->palette = AllocatePalette(256); + break; default: - fprintf (stderr, "SDL_DirectFB: Unsupported pixelformat (0x%08x)!\n", pixelformat); - return -1; + fprintf(stderr, + "SDL_DirectFB: Unsupported pixelformat (0x%08x)!\n", + pixelformat); + return -1; } - format->BitsPerPixel = DFB_BYTES_PER_PIXEL(pixelformat) * 8; - format->BytesPerPixel = DFB_BYTES_PER_PIXEL(pixelformat); + format->BitsPerPixel = DFB_BYTES_PER_PIXEL(pixelformat) * 8; + format->BytesPerPixel = DFB_BYTES_PER_PIXEL(pixelformat); - return 0; + return 0; } -int DirectFB_VideoInit(_THIS, SDL_PixelFormat *vformat) +int +DirectFB_VideoInit(_THIS, SDL_PixelFormat * vformat) { - int i; - DFBResult ret; + int i; + DFBResult ret; #if (DIRECTFB_MAJOR_VERSION == 0) && (DIRECTFB_MINOR_VERSION == 9) && (DIRECTFB_MICRO_VERSION < 23) - DFBCardCapabilities caps; + DFBCardCapabilities caps; #else - DFBGraphicsDeviceDescription caps; + DFBGraphicsDeviceDescription caps; #endif - DFBDisplayLayerConfig dlc; - struct DirectFBEnumRect *rect; - IDirectFB *dfb = NULL; - IDirectFBDisplayLayer *layer = NULL; - IDirectFBEventBuffer *events = NULL; - - HIDDEN->c2layer = NULL, HIDDEN->c2frame = NULL; - HIDDEN->enable_mga_crtc2 = 0; - HIDDEN->mga_crtc2_stretch_overscan = 1; - - ret = DirectFBInit (NULL, NULL); - if (ret) - { - SetDirectFBerror ("DirectFBInit", ret); - goto error; + DFBDisplayLayerConfig dlc; + struct DirectFBEnumRect *rect; + IDirectFB *dfb = NULL; + IDirectFBDisplayLayer *layer = NULL; + IDirectFBEventBuffer *events = NULL; + + HIDDEN->c2layer = NULL, HIDDEN->c2frame = NULL; + HIDDEN->enable_mga_crtc2 = 0; + HIDDEN->mga_crtc2_stretch_overscan = 1; + + ret = DirectFBInit(NULL, NULL); + if (ret) { + SetDirectFBerror("DirectFBInit", ret); + goto error; } - ret = DirectFBCreate (&dfb); - if (ret) - { - SetDirectFBerror ("DirectFBCreate", ret); - goto error; + ret = DirectFBCreate(&dfb); + if (ret) { + SetDirectFBerror("DirectFBCreate", ret); + goto error; } - ret = dfb->GetDisplayLayer (dfb, DLID_PRIMARY, &layer); - if (ret) - { - SetDirectFBerror ("dfb->GetDisplayLayer", ret); - goto error; + ret = dfb->GetDisplayLayer(dfb, DLID_PRIMARY, &layer); + if (ret) { + SetDirectFBerror("dfb->GetDisplayLayer", ret); + goto error; } - ret = dfb->CreateInputEventBuffer (dfb, DICAPS_ALL, DFB_FALSE, &events); - if (ret) - { - SetDirectFBerror ("dfb->CreateEventBuffer", ret); - goto error; + ret = dfb->CreateInputEventBuffer(dfb, DICAPS_ALL, DFB_FALSE, &events); + if (ret) { + SetDirectFBerror("dfb->CreateEventBuffer", ret); + goto error; } - - layer->EnableCursor (layer, 1); - - /* Query layer configuration to determine the current mode and pixelformat */ - layer->GetConfiguration (layer, &dlc); - - /* If current format is not supported use LUT8 as the default */ - if (DFBToSDLPixelFormat (dlc.pixelformat, vformat)) - DFBToSDLPixelFormat (DSPF_LUT8, vformat); - - /* Enumerate the available fullscreen modes */ - ret = dfb->EnumVideoModes (dfb, EnumModesCallback, this); - if (ret) - { - SetDirectFBerror ("dfb->EnumVideoModes", ret); - goto error; + + layer->EnableCursor(layer, 1); + + /* Query layer configuration to determine the current mode and pixelformat */ + layer->GetConfiguration(layer, &dlc); + + /* If current format is not supported use LUT8 as the default */ + if (DFBToSDLPixelFormat(dlc.pixelformat, vformat)) + DFBToSDLPixelFormat(DSPF_LUT8, vformat); + + /* Enumerate the available fullscreen modes */ + ret = dfb->EnumVideoModes(dfb, EnumModesCallback, this); + if (ret) { + SetDirectFBerror("dfb->EnumVideoModes", ret); + goto error; } - HIDDEN->modelist = SDL_calloc (HIDDEN->nummodes + 1, sizeof(SDL_Rect *)); - if (!HIDDEN->modelist) - { - SDL_OutOfMemory(); - goto error; + HIDDEN->modelist = SDL_calloc(HIDDEN->nummodes + 1, sizeof(SDL_Rect *)); + if (!HIDDEN->modelist) { + SDL_OutOfMemory(); + goto error; } - for (i = 0, rect = enumlist; rect; ++i, rect = rect->next ) - { - HIDDEN->modelist[i] = &rect->r; + for (i = 0, rect = enumlist; rect; ++i, rect = rect->next) { + HIDDEN->modelist[i] = &rect->r; } - HIDDEN->modelist[i] = NULL; + HIDDEN->modelist[i] = NULL; - /* Query card capabilities to get the video memory size */ + /* Query card capabilities to get the video memory size */ #if (DIRECTFB_MAJOR_VERSION == 0) && (DIRECTFB_MINOR_VERSION == 9) && (DIRECTFB_MICRO_VERSION < 23) - dfb->GetCardCapabilities (dfb, &caps); + dfb->GetCardCapabilities(dfb, &caps); #else - dfb->GetDeviceDescription (dfb, &caps); + dfb->GetDeviceDescription(dfb, &caps); #endif - this->info.wm_available = 1; - this->info.hw_available = 1; - this->info.blit_hw = 1; - this->info.blit_hw_CC = 1; - this->info.blit_hw_A = 1; - this->info.blit_fill = 1; - this->info.video_mem = caps.video_memory / 1024; - - HIDDEN->initialized = 1; - HIDDEN->dfb = dfb; - HIDDEN->layer = layer; - HIDDEN->eventbuffer = events; - - if (SDL_getenv("SDL_DIRECTFB_MGA_CRTC2") != NULL) - HIDDEN->enable_mga_crtc2 = 1; - - if (HIDDEN->enable_mga_crtc2) - { - DFBDisplayLayerConfig dlc; - DFBDisplayLayerConfigFlags failed; - - ret = dfb->GetDisplayLayer (dfb, 2, &HIDDEN->c2layer); - if (ret) - { - SetDirectFBerror ("dfb->GetDisplayLayer(CRTC2)", ret); - goto error; + this->info.wm_available = 1; + this->info.hw_available = 1; + this->info.blit_hw = 1; + this->info.blit_hw_CC = 1; + this->info.blit_hw_A = 1; + this->info.blit_fill = 1; + this->info.video_mem = caps.video_memory / 1024; + + HIDDEN->initialized = 1; + HIDDEN->dfb = dfb; + HIDDEN->layer = layer; + HIDDEN->eventbuffer = events; + + if (SDL_getenv("SDL_DIRECTFB_MGA_CRTC2") != NULL) + HIDDEN->enable_mga_crtc2 = 1; + + if (HIDDEN->enable_mga_crtc2) { + DFBDisplayLayerConfig dlc; + DFBDisplayLayerConfigFlags failed; + + ret = dfb->GetDisplayLayer(dfb, 2, &HIDDEN->c2layer); + if (ret) { + SetDirectFBerror("dfb->GetDisplayLayer(CRTC2)", ret); + goto error; } - ret = HIDDEN->layer->SetCooperativeLevel(HIDDEN->layer, DLSCL_EXCLUSIVE); - if (ret) - { - SetDirectFBerror ("layer->SetCooperativeLevel(CRTC2, EXCLUSIVE)", ret); - goto error; + ret = + HIDDEN->layer->SetCooperativeLevel(HIDDEN->layer, + DLSCL_EXCLUSIVE); + if (ret) { + SetDirectFBerror + ("layer->SetCooperativeLevel(CRTC2, EXCLUSIVE)", ret); + goto error; } - - ret = HIDDEN->c2layer->SetCooperativeLevel(HIDDEN->c2layer, DLSCL_EXCLUSIVE); - if (ret) - { - SetDirectFBerror ("c2layer->SetCooperativeLevel(CRTC2, EXCLUSIVE)", ret); - goto error; + + ret = + HIDDEN->c2layer->SetCooperativeLevel(HIDDEN->c2layer, + DLSCL_EXCLUSIVE); + if (ret) { + SetDirectFBerror + ("c2layer->SetCooperativeLevel(CRTC2, EXCLUSIVE)", ret); + goto error; } - HIDDEN->c2layer->SetOpacity(HIDDEN->c2layer, 0x0); - - /* Init the surface here as it got a fixed size */ - dlc.flags = DLCONF_PIXELFORMAT | DLCONF_BUFFERMODE; - dlc.buffermode = DLBM_BACKVIDEO; - dlc.pixelformat = DSPF_RGB32; - - ret = HIDDEN->c2layer->TestConfiguration( HIDDEN->c2layer, &dlc, &failed ); - if (ret) - { - SetDirectFBerror ("c2layer->TestConfiguration", ret); - goto error; + HIDDEN->c2layer->SetOpacity(HIDDEN->c2layer, 0x0); + + /* Init the surface here as it got a fixed size */ + dlc.flags = DLCONF_PIXELFORMAT | DLCONF_BUFFERMODE; + dlc.buffermode = DLBM_BACKVIDEO; + dlc.pixelformat = DSPF_RGB32; + + ret = + HIDDEN->c2layer->TestConfiguration(HIDDEN->c2layer, &dlc, + &failed); + if (ret) { + SetDirectFBerror("c2layer->TestConfiguration", ret); + goto error; } - - ret = HIDDEN->c2layer->SetConfiguration( HIDDEN->c2layer, &dlc ); - if (ret) - { - SetDirectFBerror ("c2layer->SetConfiguration", ret); - goto error; + + ret = HIDDEN->c2layer->SetConfiguration(HIDDEN->c2layer, &dlc); + if (ret) { + SetDirectFBerror("c2layer->SetConfiguration", ret); + goto error; } - - ret = HIDDEN->c2layer->GetSurface( HIDDEN->c2layer, &HIDDEN->c2frame ); - if (ret) - { - SetDirectFBerror ("c2layer->GetSurface", ret); - goto error; + + ret = HIDDEN->c2layer->GetSurface(HIDDEN->c2layer, &HIDDEN->c2frame); + if (ret) { + SetDirectFBerror("c2layer->GetSurface", ret); + goto error; } - HIDDEN->c2framesize.x = 0; - HIDDEN->c2framesize.y = 0; - HIDDEN->c2frame->GetSize( HIDDEN->c2frame, &HIDDEN->c2framesize.w, &HIDDEN->c2framesize.h); - - HIDDEN->c2frame->SetBlittingFlags( HIDDEN->c2frame, DSBLIT_NOFX ); - HIDDEN->c2frame->SetColor( HIDDEN->c2frame, 0, 0, 0, 0xff ); - - /* Clear CRTC2 */ - HIDDEN->c2frame->Clear(HIDDEN->c2frame, 0, 0, 0, 0xff ); - HIDDEN->c2frame->Flip(HIDDEN->c2frame, NULL, 0 ); - HIDDEN->c2frame->Clear(HIDDEN->c2frame, 0, 0, 0, 0xff ); - HIDDEN->c2frame->Flip(HIDDEN->c2frame, NULL, 0 ); - HIDDEN->c2frame->Clear(HIDDEN->c2frame, 0, 0, 0, 0xff ); - - HIDDEN->c2layer->SetOpacity(HIDDEN->c2layer, 0xFF ); - - /* Check if overscan is possibly set */ - if (SDL_getenv("SDL_DIRECTFB_MGA_OVERSCAN") != NULL) - { - float overscan = 0; - if (SDL_sscanf(SDL_getenv("SDL_DIRECTFB_MGA_OVERSCAN"), "%f", &overscan) == 1) - if (overscan > 0 && overscan < 2) - HIDDEN->mga_crtc2_stretch_overscan = overscan; - } - - #ifdef DIRECTFB_CRTC2_DEBUG - printf("CRTC2 overscan: %f\n", HIDDEN->mga_crtc2_stretch_overscan); - #endif + HIDDEN->c2framesize.x = 0; + HIDDEN->c2framesize.y = 0; + HIDDEN->c2frame->GetSize(HIDDEN->c2frame, &HIDDEN->c2framesize.w, + &HIDDEN->c2framesize.h); + + HIDDEN->c2frame->SetBlittingFlags(HIDDEN->c2frame, DSBLIT_NOFX); + HIDDEN->c2frame->SetColor(HIDDEN->c2frame, 0, 0, 0, 0xff); + + /* Clear CRTC2 */ + HIDDEN->c2frame->Clear(HIDDEN->c2frame, 0, 0, 0, 0xff); + HIDDEN->c2frame->Flip(HIDDEN->c2frame, NULL, 0); + HIDDEN->c2frame->Clear(HIDDEN->c2frame, 0, 0, 0, 0xff); + HIDDEN->c2frame->Flip(HIDDEN->c2frame, NULL, 0); + HIDDEN->c2frame->Clear(HIDDEN->c2frame, 0, 0, 0, 0xff); + + HIDDEN->c2layer->SetOpacity(HIDDEN->c2layer, 0xFF); + + /* Check if overscan is possibly set */ + if (SDL_getenv("SDL_DIRECTFB_MGA_OVERSCAN") != NULL) { + float overscan = 0; + if (SDL_sscanf + (SDL_getenv("SDL_DIRECTFB_MGA_OVERSCAN"), "%f", + &overscan) == 1) + if (overscan > 0 && overscan < 2) + HIDDEN->mga_crtc2_stretch_overscan = overscan; + } +#ifdef DIRECTFB_CRTC2_DEBUG + printf("CRTC2 overscan: %f\n", HIDDEN->mga_crtc2_stretch_overscan); +#endif } - return 0; + return 0; - error: - if (events) - events->Release (events); - - if (HIDDEN->c2frame) - HIDDEN->c2frame->Release (HIDDEN->c2frame); + error: + if (events) + events->Release(events); - if (HIDDEN->c2layer) - HIDDEN->c2layer->Release (HIDDEN->c2layer); + if (HIDDEN->c2frame) + HIDDEN->c2frame->Release(HIDDEN->c2frame); - if (layer) - layer->Release (layer); + if (HIDDEN->c2layer) + HIDDEN->c2layer->Release(HIDDEN->c2layer); - if (dfb) - dfb->Release (dfb); + if (layer) + layer->Release(layer); - return -1; + if (dfb) + dfb->Release(dfb); + + return -1; } -static SDL_Rect **DirectFB_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags) +static SDL_Rect ** +DirectFB_ListModes(_THIS, SDL_PixelFormat * format, Uint32 flags) { - if (flags & SDL_FULLSCREEN) - return HIDDEN->modelist; - else - if (SDLToDFBPixelFormat (format) != DSPF_UNKNOWN) - return (SDL_Rect**) -1; + if (flags & SDL_FULLSCREEN) + return HIDDEN->modelist; + else if (SDLToDFBPixelFormat(format) != DSPF_UNKNOWN) + return (SDL_Rect **) - 1; - return NULL; + return NULL; } -static SDL_Surface *DirectFB_SetVideoMode(_THIS, SDL_Surface *current, int width, int height, int bpp, Uint32 flags) +static SDL_Surface * +DirectFB_SetVideoMode(_THIS, SDL_Surface * current, int width, int height, + int bpp, Uint32 flags) { - DFBResult ret; - DFBSurfaceDescription dsc; - DFBSurfacePixelFormat pixelformat; - IDirectFBSurface *surface; - - fprintf (stderr, "SDL DirectFB_SetVideoMode: %dx%d@%d, flags: 0x%08x\n", - width, height, bpp, flags); - - flags |= SDL_FULLSCREEN; - - /* Release previous primary surface */ - if (current->hwdata && current->hwdata->surface) - { - current->hwdata->surface->Release (current->hwdata->surface); - current->hwdata->surface = NULL; - - /* And its palette if present */ - if (current->hwdata->palette) - { - current->hwdata->palette->Release (current->hwdata->palette); - current->hwdata->palette = NULL; + DFBResult ret; + DFBSurfaceDescription dsc; + DFBSurfacePixelFormat pixelformat; + IDirectFBSurface *surface; + + fprintf(stderr, "SDL DirectFB_SetVideoMode: %dx%d@%d, flags: 0x%08x\n", + width, height, bpp, flags); + + flags |= SDL_FULLSCREEN; + + /* Release previous primary surface */ + if (current->hwdata && current->hwdata->surface) { + current->hwdata->surface->Release(current->hwdata->surface); + current->hwdata->surface = NULL; + + /* And its palette if present */ + if (current->hwdata->palette) { + current->hwdata->palette->Release(current->hwdata->palette); + current->hwdata->palette = NULL; + } + } else if (!current->hwdata) { + /* Allocate the hardware acceleration data */ + current->hwdata = + (struct private_hwdata *) SDL_calloc(1, sizeof(*current->hwdata)); + if (!current->hwdata) { + SDL_OutOfMemory(); + return NULL; } - } - else if (!current->hwdata) - { - /* Allocate the hardware acceleration data */ - current->hwdata = (struct private_hwdata *) SDL_calloc (1, sizeof(*current->hwdata)); - if (!current->hwdata) - { - SDL_OutOfMemory(); - return NULL; - } } - /* Set cooperative level depending on flag SDL_FULLSCREEN */ - if (flags & SDL_FULLSCREEN) - { - ret = HIDDEN->dfb->SetCooperativeLevel (HIDDEN->dfb, DFSCL_FULLSCREEN); - if (ret && !HIDDEN->enable_mga_crtc2) - { - DirectFBError ("dfb->SetCooperativeLevel", ret); - flags &= ~SDL_FULLSCREEN; + /* Set cooperative level depending on flag SDL_FULLSCREEN */ + if (flags & SDL_FULLSCREEN) { + ret = HIDDEN->dfb->SetCooperativeLevel(HIDDEN->dfb, DFSCL_FULLSCREEN); + if (ret && !HIDDEN->enable_mga_crtc2) { + DirectFBError("dfb->SetCooperativeLevel", ret); + flags &= ~SDL_FULLSCREEN; } - } - else - HIDDEN->dfb->SetCooperativeLevel (HIDDEN->dfb, DFSCL_NORMAL); - - /* Set video mode */ - ret = HIDDEN->dfb->SetVideoMode (HIDDEN->dfb, width, height, bpp); - if (ret) - { - if (flags & SDL_FULLSCREEN) - { - flags &= ~SDL_FULLSCREEN; - HIDDEN->dfb->SetCooperativeLevel (HIDDEN->dfb, DFSCL_NORMAL); - ret = HIDDEN->dfb->SetVideoMode (HIDDEN->dfb, width, height, bpp); + } else + HIDDEN->dfb->SetCooperativeLevel(HIDDEN->dfb, DFSCL_NORMAL); + + /* Set video mode */ + ret = HIDDEN->dfb->SetVideoMode(HIDDEN->dfb, width, height, bpp); + if (ret) { + if (flags & SDL_FULLSCREEN) { + flags &= ~SDL_FULLSCREEN; + HIDDEN->dfb->SetCooperativeLevel(HIDDEN->dfb, DFSCL_NORMAL); + ret = HIDDEN->dfb->SetVideoMode(HIDDEN->dfb, width, height, bpp); } - if (ret) - { - SetDirectFBerror ("dfb->SetVideoMode", ret); - return NULL; + if (ret) { + SetDirectFBerror("dfb->SetVideoMode", ret); + return NULL; } } - /* Create primary surface */ - dsc.flags = DSDESC_CAPS | DSDESC_PIXELFORMAT; - dsc.caps = DSCAPS_PRIMARY | ((flags & SDL_DOUBLEBUF) ? DSCAPS_FLIPPING : 0); - dsc.pixelformat = GetFormatForBpp (bpp, HIDDEN->layer); - - ret = HIDDEN->dfb->CreateSurface (HIDDEN->dfb, &dsc, &surface); - if (ret && (flags & SDL_DOUBLEBUF)) - { - /* Try without double buffering */ - dsc.caps &= ~DSCAPS_FLIPPING; - ret = HIDDEN->dfb->CreateSurface (HIDDEN->dfb, &dsc, &surface); + /* Create primary surface */ + dsc.flags = DSDESC_CAPS | DSDESC_PIXELFORMAT; + dsc.caps = + DSCAPS_PRIMARY | ((flags & SDL_DOUBLEBUF) ? DSCAPS_FLIPPING : 0); + dsc.pixelformat = GetFormatForBpp(bpp, HIDDEN->layer); + + ret = HIDDEN->dfb->CreateSurface(HIDDEN->dfb, &dsc, &surface); + if (ret && (flags & SDL_DOUBLEBUF)) { + /* Try without double buffering */ + dsc.caps &= ~DSCAPS_FLIPPING; + ret = HIDDEN->dfb->CreateSurface(HIDDEN->dfb, &dsc, &surface); } - if (ret) - { - SetDirectFBerror ("dfb->CreateSurface", ret); - return NULL; + if (ret) { + SetDirectFBerror("dfb->CreateSurface", ret); + return NULL; } - current->w = width; - current->h = height; - current->flags = SDL_HWSURFACE | SDL_PREALLOC; + current->w = width; + current->h = height; + current->flags = SDL_HWSURFACE | SDL_PREALLOC; - if (flags & SDL_FULLSCREEN) - { - current->flags |= SDL_FULLSCREEN; - this->UpdateRects = DirectFB_DirectUpdate; - } - else - this->UpdateRects = DirectFB_WindowedUpdate; + if (flags & SDL_FULLSCREEN) { + current->flags |= SDL_FULLSCREEN; + this->UpdateRects = DirectFB_DirectUpdate; + } else + this->UpdateRects = DirectFB_WindowedUpdate; - if (dsc.caps & DSCAPS_FLIPPING) - current->flags |= SDL_DOUBLEBUF; + if (dsc.caps & DSCAPS_FLIPPING) + current->flags |= SDL_DOUBLEBUF; - surface->GetPixelFormat (surface, &pixelformat); + surface->GetPixelFormat(surface, &pixelformat); - DFBToSDLPixelFormat (pixelformat, current->format); + DFBToSDLPixelFormat(pixelformat, current->format); - /* Get the surface palette (if supported) */ - if (DFB_PIXELFORMAT_IS_INDEXED( pixelformat )) - { - surface->GetPalette (surface, ¤t->hwdata->palette); + /* Get the surface palette (if supported) */ + if (DFB_PIXELFORMAT_IS_INDEXED(pixelformat)) { + surface->GetPalette(surface, ¤t->hwdata->palette); - current->flags |= SDL_HWPALETTE; + current->flags |= SDL_HWPALETTE; } - current->hwdata->surface = surface; - - /* MGA CRTC2 stuff */ - if (HIDDEN->enable_mga_crtc2) - { - /* no stretching if c2ssize == c2framesize */ - HIDDEN->c2ssize.x = 0, HIDDEN->c2ssize.y = 0; - HIDDEN->c2ssize.w = width; - HIDDEN->c2ssize.h = height; - - HIDDEN->c2dsize.x = 0, HIDDEN->c2dsize.y = 0; - HIDDEN->c2dsize.w = width; - HIDDEN->c2dsize.h = height; - - HIDDEN->mga_crtc2_stretch = 0; - - if (SDL_getenv("SDL_DIRECTFB_MGA_STRETCH") != NULL) - { - /* Normally assume a picture aspect ratio of 4:3 */ - int zoom_aspect_x = 4, zoom_aspect_y = 3, i, j; - - for (i = 1; i < 20; i++) - { - for (j = 1; j < 10; j++) - { - if ((float)width/(float)i*(float)j == height) - { - zoom_aspect_x = i; - zoom_aspect_y = j; - - /* break the loop */ - i = 21; - break; - } - } - } - - #ifdef DIRECTFB_CRTC2_DEBUG - printf("Source resolution: X: %d, Y: %d, Aspect ratio: %d:%d\n", width, height, zoom_aspect_x, zoom_aspect_y); - printf("CRTC2 resolution: X: %d, Y: %d\n", HIDDEN->c2framesize.w, HIDDEN->c2framesize.h); - #endif - - /* don't stretch only slightly smaller/larger images */ - if ((float)width < (float)HIDDEN->c2framesize.w*0.95 || (float)height < (float)HIDDEN->c2framesize.h*0.95) - { - while ((float)HIDDEN->c2dsize.w < (float)HIDDEN->c2framesize.w*HIDDEN->mga_crtc2_stretch_overscan && (float)HIDDEN->c2dsize.h < (float)HIDDEN->c2framesize.h*HIDDEN->mga_crtc2_stretch_overscan) - { - HIDDEN->c2dsize.w+=zoom_aspect_x; - HIDDEN->c2dsize.h+=zoom_aspect_y; - } + current->hwdata->surface = surface; - /* one step down */ - HIDDEN->c2dsize.w-=zoom_aspect_x; - HIDDEN->c2dsize.h-=zoom_aspect_y; - - #ifdef DIRECTFB_CRTC2_DEBUG - printf("Stretched resolution: X: %d, Y: %d\n", HIDDEN->c2dsize.w, HIDDEN->c2dsize.h); - #endif - - HIDDEN->mga_crtc2_stretch = 1; - } - else if ((float)width > (float)HIDDEN->c2framesize.w*0.95 || (float)height > (float)HIDDEN->c2framesize.h*0.95) - { - while ((float)HIDDEN->c2dsize.w > (float)HIDDEN->c2framesize.w*HIDDEN->mga_crtc2_stretch_overscan || (float)HIDDEN->c2dsize.h > (float)HIDDEN->c2framesize.h*HIDDEN->mga_crtc2_stretch_overscan) - { - HIDDEN->c2dsize.w-=zoom_aspect_x; - HIDDEN->c2dsize.h-=zoom_aspect_y; + /* MGA CRTC2 stuff */ + if (HIDDEN->enable_mga_crtc2) { + /* no stretching if c2ssize == c2framesize */ + HIDDEN->c2ssize.x = 0, HIDDEN->c2ssize.y = 0; + HIDDEN->c2ssize.w = width; + HIDDEN->c2ssize.h = height; + + HIDDEN->c2dsize.x = 0, HIDDEN->c2dsize.y = 0; + HIDDEN->c2dsize.w = width; + HIDDEN->c2dsize.h = height; + + HIDDEN->mga_crtc2_stretch = 0; + + if (SDL_getenv("SDL_DIRECTFB_MGA_STRETCH") != NULL) { + /* Normally assume a picture aspect ratio of 4:3 */ + int zoom_aspect_x = 4, zoom_aspect_y = 3, i, j; + + for (i = 1; i < 20; i++) { + for (j = 1; j < 10; j++) { + if ((float) width / (float) i * (float) j == height) { + zoom_aspect_x = i; + zoom_aspect_y = j; + + /* break the loop */ + i = 21; + break; + } } - - #ifdef DIRECTFB_CRTC2_DEBUG - printf("Down-Stretched resolution: X: %d, Y: %d\n", HIDDEN->c2dsize.w, HIDDEN->c2dsize.h); - #endif - - HIDDEN->mga_crtc2_stretch = 1; - } else { - #ifdef DIRECTFB_CRTC2_DEBUG - printf("Not stretching image\n"); - #endif - } + } - /* Panning */ - if (HIDDEN->c2framesize.w > HIDDEN->c2dsize.w) - HIDDEN->c2dsize.x = (HIDDEN->c2framesize.w - HIDDEN->c2dsize.w) / 2; - else - HIDDEN->c2dsize.x = (HIDDEN->c2dsize.w - HIDDEN->c2framesize.w) / 2; +#ifdef DIRECTFB_CRTC2_DEBUG + printf + ("Source resolution: X: %d, Y: %d, Aspect ratio: %d:%d\n", + width, height, zoom_aspect_x, zoom_aspect_y); + printf("CRTC2 resolution: X: %d, Y: %d\n", + HIDDEN->c2framesize.w, HIDDEN->c2framesize.h); +#endif - if (HIDDEN->c2framesize.h > HIDDEN->c2dsize.h) - HIDDEN->c2dsize.y = (HIDDEN->c2framesize.h - HIDDEN->c2dsize.h) / 2; - else - HIDDEN->c2dsize.y = (HIDDEN->c2dsize.h - HIDDEN->c2framesize.h) / 2; + /* don't stretch only slightly smaller/larger images */ + if ((float) width < (float) HIDDEN->c2framesize.w * 0.95 + || (float) height < (float) HIDDEN->c2framesize.h * 0.95) { + while ((float) HIDDEN->c2dsize.w < + (float) HIDDEN->c2framesize.w * + HIDDEN->mga_crtc2_stretch_overscan + && (float) HIDDEN->c2dsize.h < + (float) HIDDEN->c2framesize.h * + HIDDEN->mga_crtc2_stretch_overscan) { + HIDDEN->c2dsize.w += zoom_aspect_x; + HIDDEN->c2dsize.h += zoom_aspect_y; + } - #ifdef DIRECTFB_CRTC2_DEBUG - printf("CRTC2 position X: %d, Y: %d\n", HIDDEN->c2dsize.x, HIDDEN->c2dsize.y); - #endif - } - } + /* one step down */ + HIDDEN->c2dsize.w -= zoom_aspect_x; + HIDDEN->c2dsize.h -= zoom_aspect_y; - return current; -} +#ifdef DIRECTFB_CRTC2_DEBUG + printf("Stretched resolution: X: %d, Y: %d\n", + HIDDEN->c2dsize.w, HIDDEN->c2dsize.h); +#endif -static int DirectFB_AllocHWSurface(_THIS, SDL_Surface *surface) -{ - DFBResult ret; - DFBSurfaceDescription dsc; + HIDDEN->mga_crtc2_stretch = 1; + } else if ((float) width > (float) HIDDEN->c2framesize.w * 0.95 + || (float) height > + (float) HIDDEN->c2framesize.h * 0.95) { + while ((float) HIDDEN->c2dsize.w > + (float) HIDDEN->c2framesize.w * + HIDDEN->mga_crtc2_stretch_overscan + || (float) HIDDEN->c2dsize.h > + (float) HIDDEN->c2framesize.h * + HIDDEN->mga_crtc2_stretch_overscan) { + HIDDEN->c2dsize.w -= zoom_aspect_x; + HIDDEN->c2dsize.h -= zoom_aspect_y; + } - /* fprintf(stderr, "SDL: DirectFB_AllocHWSurface (%dx%d@%d, flags: 0x%08x)\n", - surface->w, surface->h, surface->format->BitsPerPixel, surface->flags);*/ +#ifdef DIRECTFB_CRTC2_DEBUG + printf("Down-Stretched resolution: X: %d, Y: %d\n", + HIDDEN->c2dsize.w, HIDDEN->c2dsize.h); +#endif - if (surface->w < 8 || surface->h < 8) - return -1; + HIDDEN->mga_crtc2_stretch = 1; + } else { +#ifdef DIRECTFB_CRTC2_DEBUG + printf("Not stretching image\n"); +#endif + } - /* fill surface description */ - dsc.flags = DSDESC_WIDTH | DSDESC_HEIGHT | DSDESC_PIXELFORMAT | DSDESC_CAPS; - dsc.width = surface->w; - dsc.height = surface->h; - dsc.caps = (surface->flags & SDL_DOUBLEBUF) ? DSCAPS_FLIPPING : 0; + /* Panning */ + if (HIDDEN->c2framesize.w > HIDDEN->c2dsize.w) + HIDDEN->c2dsize.x = + (HIDDEN->c2framesize.w - HIDDEN->c2dsize.w) / 2; + else + HIDDEN->c2dsize.x = + (HIDDEN->c2dsize.w - HIDDEN->c2framesize.w) / 2; + + if (HIDDEN->c2framesize.h > HIDDEN->c2dsize.h) + HIDDEN->c2dsize.y = + (HIDDEN->c2framesize.h - HIDDEN->c2dsize.h) / 2; + else + HIDDEN->c2dsize.y = + (HIDDEN->c2dsize.h - HIDDEN->c2framesize.h) / 2; + +#ifdef DIRECTFB_CRTC2_DEBUG + printf("CRTC2 position X: %d, Y: %d\n", HIDDEN->c2dsize.x, + HIDDEN->c2dsize.y); +#endif + } + } - /* find the right pixelformat */ - dsc.pixelformat = SDLToDFBPixelFormat (surface->format); - if (dsc.pixelformat == DSPF_UNKNOWN) - return -1; + return current; +} - /* Allocate the hardware acceleration data */ - surface->hwdata = (struct private_hwdata *) SDL_calloc (1, sizeof(*surface->hwdata)); - if (surface->hwdata == NULL) - { - SDL_OutOfMemory(); - return -1; +static int +DirectFB_AllocHWSurface(_THIS, SDL_Surface * surface) +{ + DFBResult ret; + DFBSurfaceDescription dsc; + + /* fprintf(stderr, "SDL: DirectFB_AllocHWSurface (%dx%d@%d, flags: 0x%08x)\n", + surface->w, surface->h, surface->format->BitsPerPixel, surface->flags); */ + + if (surface->w < 8 || surface->h < 8) + return -1; + + /* fill surface description */ + dsc.flags = + DSDESC_WIDTH | DSDESC_HEIGHT | DSDESC_PIXELFORMAT | DSDESC_CAPS; + dsc.width = surface->w; + dsc.height = surface->h; + dsc.caps = (surface->flags & SDL_DOUBLEBUF) ? DSCAPS_FLIPPING : 0; + + /* find the right pixelformat */ + dsc.pixelformat = SDLToDFBPixelFormat(surface->format); + if (dsc.pixelformat == DSPF_UNKNOWN) + return -1; + + /* Allocate the hardware acceleration data */ + surface->hwdata = + (struct private_hwdata *) SDL_calloc(1, sizeof(*surface->hwdata)); + if (surface->hwdata == NULL) { + SDL_OutOfMemory(); + return -1; } - /* Create the surface */ - ret = HIDDEN->dfb->CreateSurface (HIDDEN->dfb, &dsc, &surface->hwdata->surface); - if (ret) - { - SetDirectFBerror ("dfb->CreateSurface", ret); - free (surface->hwdata); - surface->hwdata = NULL; - return -1; + /* Create the surface */ + ret = + HIDDEN->dfb->CreateSurface(HIDDEN->dfb, &dsc, + &surface->hwdata->surface); + if (ret) { + SetDirectFBerror("dfb->CreateSurface", ret); + free(surface->hwdata); + surface->hwdata = NULL; + return -1; } - surface->flags |= SDL_HWSURFACE | SDL_PREALLOC; + surface->flags |= SDL_HWSURFACE | SDL_PREALLOC; - return 0; + return 0; } -static void DirectFB_FreeHWSurface(_THIS, SDL_Surface *surface) +static void +DirectFB_FreeHWSurface(_THIS, SDL_Surface * surface) { - if (surface->hwdata && HIDDEN->initialized) - { - surface->hwdata->surface->Release (surface->hwdata->surface); - free (surface->hwdata); - surface->hwdata = NULL; + if (surface->hwdata && HIDDEN->initialized) { + surface->hwdata->surface->Release(surface->hwdata->surface); + free(surface->hwdata); + surface->hwdata = NULL; } } -static int DirectFB_CheckHWBlit(_THIS, SDL_Surface *src, SDL_Surface *dst) +static int +DirectFB_CheckHWBlit(_THIS, SDL_Surface * src, SDL_Surface * dst) { - /* fprintf(stderr, "SDL: DirectFB_CheckHWBlit (src->hwdata: %p, dst->hwdata: %p)\n", - src->hwdata, dst->hwdata);*/ + /* fprintf(stderr, "SDL: DirectFB_CheckHWBlit (src->hwdata: %p, dst->hwdata: %p)\n", + src->hwdata, dst->hwdata); */ - if (!src->hwdata || !dst->hwdata) - return 0; + if (!src->hwdata || !dst->hwdata) + return 0; - src->flags |= SDL_HWACCEL; - src->map->hw_blit = DirectFB_HWAccelBlit; + src->flags |= SDL_HWACCEL; + src->map->hw_blit = DirectFB_HWAccelBlit; - return 1; + return 1; } -static int DirectFB_HWAccelBlit(SDL_Surface *src, SDL_Rect *srcrect, - SDL_Surface *dst, SDL_Rect *dstrect) +static int +DirectFB_HWAccelBlit(SDL_Surface * src, SDL_Rect * srcrect, + SDL_Surface * dst, SDL_Rect * dstrect) { - DFBSurfaceBlittingFlags flags = DSBLIT_NOFX; + DFBSurfaceBlittingFlags flags = DSBLIT_NOFX; - DFBRectangle sr = { srcrect->x, srcrect->y, srcrect->w, srcrect->h }; - DFBRectangle dr = { dstrect->x, dstrect->y, dstrect->w, dstrect->h }; + DFBRectangle sr = { srcrect->x, srcrect->y, srcrect->w, srcrect->h }; + DFBRectangle dr = { dstrect->x, dstrect->y, dstrect->w, dstrect->h }; - IDirectFBSurface *surface = dst->hwdata->surface; + IDirectFBSurface *surface = dst->hwdata->surface; - if (src->flags & SDL_SRCCOLORKEY) - { - flags |= DSBLIT_SRC_COLORKEY; - DirectFB_SetHWColorKey (NULL, src, src->format->colorkey); + if (src->flags & SDL_SRCCOLORKEY) { + flags |= DSBLIT_SRC_COLORKEY; + DirectFB_SetHWColorKey(NULL, src, src->format->colorkey); } - if (src->flags & SDL_SRCALPHA) - { - flags |= DSBLIT_BLEND_COLORALPHA; - surface->SetColor (surface, 0xff, 0xff, 0xff, src->format->alpha); + if (src->flags & SDL_SRCALPHA) { + flags |= DSBLIT_BLEND_COLORALPHA; + surface->SetColor(surface, 0xff, 0xff, 0xff, src->format->alpha); } - surface->SetBlittingFlags (surface, flags); + surface->SetBlittingFlags(surface, flags); - if (sr.w == dr.w && sr.h == dr.h) - surface->Blit (surface, src->hwdata->surface, &sr, dr.x, dr.y); - else - surface->StretchBlit (surface, src->hwdata->surface, &sr, &dr); + if (sr.w == dr.w && sr.h == dr.h) + surface->Blit(surface, src->hwdata->surface, &sr, dr.x, dr.y); + else + surface->StretchBlit(surface, src->hwdata->surface, &sr, &dr); - return 0; + return 0; } -static int DirectFB_FillHWRect(_THIS, SDL_Surface *dst, SDL_Rect *dstrect, Uint32 color) +static int +DirectFB_FillHWRect(_THIS, SDL_Surface * dst, SDL_Rect * dstrect, + Uint32 color) { - SDL_PixelFormat *fmt = dst->format; - IDirectFBSurface *surface = dst->hwdata->surface; + SDL_PixelFormat *fmt = dst->format; + IDirectFBSurface *surface = dst->hwdata->surface; - /* ugly */ - surface->SetColor (surface, - (color & fmt->Rmask) >> (fmt->Rshift - fmt->Rloss), - (color & fmt->Gmask) >> (fmt->Gshift - fmt->Gloss), - (color & fmt->Bmask) << (fmt->Bloss - fmt->Bshift), 0xFF); - surface->FillRectangle (surface, dstrect->x, dstrect->y, dstrect->w, dstrect->h); + /* ugly */ + surface->SetColor(surface, + (color & fmt->Rmask) >> (fmt->Rshift - fmt->Rloss), + (color & fmt->Gmask) >> (fmt->Gshift - fmt->Gloss), + (color & fmt->Bmask) << (fmt->Bloss - fmt->Bshift), + 0xFF); + surface->FillRectangle(surface, dstrect->x, dstrect->y, dstrect->w, + dstrect->h); - return 0; + return 0; } -static int DirectFB_SetHWColorKey(_THIS, SDL_Surface *src, Uint32 key) +static int +DirectFB_SetHWColorKey(_THIS, SDL_Surface * src, Uint32 key) { - SDL_PixelFormat *fmt = src->format; - IDirectFBSurface *surface = src->hwdata->surface; + SDL_PixelFormat *fmt = src->format; + IDirectFBSurface *surface = src->hwdata->surface; - if (fmt->BitsPerPixel == 8) - surface->SetSrcColorKeyIndex (surface, key); - else - /* ugly */ - surface->SetSrcColorKey (surface, - (key & fmt->Rmask) >> (fmt->Rshift - fmt->Rloss), - (key & fmt->Gmask) >> (fmt->Gshift - fmt->Gloss), - (key & fmt->Bmask) << (fmt->Bloss - fmt->Bshift)); + if (fmt->BitsPerPixel == 8) + surface->SetSrcColorKeyIndex(surface, key); + else + /* ugly */ + surface->SetSrcColorKey(surface, + (key & fmt->Rmask) >> (fmt->Rshift - + fmt->Rloss), + (key & fmt->Gmask) >> (fmt->Gshift - + fmt->Gloss), + (key & fmt->Bmask) << (fmt->Bloss - + fmt->Bshift)); - return 0; + return 0; } -static int DirectFB_SetHWAlpha(_THIS, SDL_Surface *surface, Uint8 alpha) +static int +DirectFB_SetHWAlpha(_THIS, SDL_Surface * surface, Uint8 alpha) { - return 0; + return 0; } -static int DirectFB_FlipHWSurface(_THIS, SDL_Surface *surface) +static int +DirectFB_FlipHWSurface(_THIS, SDL_Surface * surface) { - if (HIDDEN->enable_mga_crtc2) - { - int rtn = surface->hwdata->surface->Flip (surface->hwdata->surface, NULL, 0); - if (HIDDEN->mga_crtc2_stretch) - HIDDEN->c2frame->StretchBlit(HIDDEN->c2frame, surface->hwdata->surface, &HIDDEN->c2ssize, &HIDDEN->c2dsize); - else - HIDDEN->c2frame->Blit(HIDDEN->c2frame, surface->hwdata->surface, NULL, HIDDEN->c2dsize.x, HIDDEN->c2dsize.y); - - HIDDEN->c2frame->Flip(HIDDEN->c2frame, NULL, DSFLIP_WAITFORSYNC); - return rtn; - } - else - return surface->hwdata->surface->Flip (surface->hwdata->surface, NULL, DSFLIP_WAITFORSYNC); + if (HIDDEN->enable_mga_crtc2) { + int rtn = + surface->hwdata->surface->Flip(surface->hwdata->surface, NULL, + 0); + if (HIDDEN->mga_crtc2_stretch) + HIDDEN->c2frame->StretchBlit(HIDDEN->c2frame, + surface->hwdata->surface, + &HIDDEN->c2ssize, &HIDDEN->c2dsize); + else + HIDDEN->c2frame->Blit(HIDDEN->c2frame, + surface->hwdata->surface, NULL, + HIDDEN->c2dsize.x, HIDDEN->c2dsize.y); + + HIDDEN->c2frame->Flip(HIDDEN->c2frame, NULL, DSFLIP_WAITFORSYNC); + return rtn; + } else + return surface->hwdata->surface->Flip(surface->hwdata->surface, NULL, + DSFLIP_WAITFORSYNC); } -static int DirectFB_LockHWSurface(_THIS, SDL_Surface *surface) +static int +DirectFB_LockHWSurface(_THIS, SDL_Surface * surface) { - DFBResult ret; - void *data; - int pitch; - - ret = surface->hwdata->surface->Lock (surface->hwdata->surface, - DSLF_WRITE, &data, &pitch); - if (ret) - { - SetDirectFBerror ("surface->Lock", ret); - return -1; + DFBResult ret; + void *data; + int pitch; + + ret = surface->hwdata->surface->Lock(surface->hwdata->surface, + DSLF_WRITE, &data, &pitch); + if (ret) { + SetDirectFBerror("surface->Lock", ret); + return -1; } - surface->pixels = data; - surface->pitch = pitch; + surface->pixels = data; + surface->pitch = pitch; - return 0; + return 0; } -static void DirectFB_UnlockHWSurface(_THIS, SDL_Surface *surface) +static void +DirectFB_UnlockHWSurface(_THIS, SDL_Surface * surface) { - surface->hwdata->surface->Unlock (surface->hwdata->surface); - surface->pixels = NULL; + surface->hwdata->surface->Unlock(surface->hwdata->surface); + surface->pixels = NULL; } -static void DirectFB_DirectUpdate(_THIS, int numrects, SDL_Rect *rects) +static void +DirectFB_DirectUpdate(_THIS, int numrects, SDL_Rect * rects) { - if (HIDDEN->enable_mga_crtc2) - { - if (HIDDEN->mga_crtc2_stretch) - HIDDEN->c2frame->StretchBlit(HIDDEN->c2frame, this->screen->hwdata->surface, &HIDDEN->c2ssize, &HIDDEN->c2dsize); - else - HIDDEN->c2frame->Blit(HIDDEN->c2frame, this->screen->hwdata->surface, NULL, HIDDEN->c2dsize.x, HIDDEN->c2dsize.y); - - HIDDEN->c2frame->Flip(HIDDEN->c2frame, NULL, DSFLIP_WAITFORSYNC); + if (HIDDEN->enable_mga_crtc2) { + if (HIDDEN->mga_crtc2_stretch) + HIDDEN->c2frame->StretchBlit(HIDDEN->c2frame, + this->screen->hwdata->surface, + &HIDDEN->c2ssize, &HIDDEN->c2dsize); + else + HIDDEN->c2frame->Blit(HIDDEN->c2frame, + this->screen->hwdata->surface, NULL, + HIDDEN->c2dsize.x, HIDDEN->c2dsize.y); + + HIDDEN->c2frame->Flip(HIDDEN->c2frame, NULL, DSFLIP_WAITFORSYNC); } } -static void DirectFB_WindowedUpdate(_THIS, int numrects, SDL_Rect *rects) +static void +DirectFB_WindowedUpdate(_THIS, int numrects, SDL_Rect * rects) { - DFBRegion region; - int i; - int region_valid = 0; - IDirectFBSurface *surface = this->screen->hwdata->surface; + DFBRegion region; + int i; + int region_valid = 0; + IDirectFBSurface *surface = this->screen->hwdata->surface; - for (i=0; i region.x2) - region.x2 = x2; + if (x2 > region.x2) + region.x2 = x2; - if (y2 > region.y2) - region.y2 = y2; - } - else - { + if (y2 > region.y2) + region.y2 = y2; + } else { region.x1 = rects[i].x; region.y1 = rects[i].y; region.x2 = x2; @@ -1033,137 +1049,130 @@ static void DirectFB_WindowedUpdate(_THIS, int numrects, SDL_Rect *rects) } } - if (region_valid) - { - if (HIDDEN->enable_mga_crtc2) - { - if (HIDDEN->mga_crtc2_stretch) - HIDDEN->c2frame->StretchBlit(HIDDEN->c2frame, surface, &HIDDEN->c2ssize, &HIDDEN->c2dsize); - else - HIDDEN->c2frame->Blit(HIDDEN->c2frame, surface, NULL, HIDDEN->c2dsize.x, HIDDEN->c2dsize.y); - - HIDDEN->c2frame->Flip(HIDDEN->c2frame, NULL, DSFLIP_WAITFORSYNC); - } - else - surface->Flip (surface, ®ion, DSFLIP_WAITFORSYNC); + if (region_valid) { + if (HIDDEN->enable_mga_crtc2) { + if (HIDDEN->mga_crtc2_stretch) + HIDDEN->c2frame->StretchBlit(HIDDEN->c2frame, surface, + &HIDDEN->c2ssize, + &HIDDEN->c2dsize); + else + HIDDEN->c2frame->Blit(HIDDEN->c2frame, surface, NULL, + HIDDEN->c2dsize.x, HIDDEN->c2dsize.y); + + HIDDEN->c2frame->Flip(HIDDEN->c2frame, NULL, DSFLIP_WAITFORSYNC); + } else + surface->Flip(surface, ®ion, DSFLIP_WAITFORSYNC); } } -int DirectFB_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color *colors) +int +DirectFB_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color * colors) { - IDirectFBPalette *palette = this->screen->hwdata->palette; + IDirectFBPalette *palette = this->screen->hwdata->palette; - if (!palette) - return 0; + if (!palette) + return 0; - if (firstcolor > 255) - return 0; + if (firstcolor > 255) + return 0; - if (firstcolor + ncolors > 256) - ncolors = 256 - firstcolor; + if (firstcolor + ncolors > 256) + ncolors = 256 - firstcolor; - if (ncolors > 0) - { - int i; - DFBColor entries[ncolors]; + if (ncolors > 0) { + int i; + DFBColor entries[ncolors]; - for (i=0; iSetEntries (palette, entries, ncolors, firstcolor); + palette->SetEntries(palette, entries, ncolors, firstcolor); } - return 1; + return 1; } - -void DirectFB_VideoQuit(_THIS) + +void +DirectFB_VideoQuit(_THIS) { - struct DirectFBEnumRect *rect = enumlist; + struct DirectFBEnumRect *rect = enumlist; - if (this->screen && this->screen->hwdata) - { - IDirectFBSurface *surface = this->screen->hwdata->surface; - IDirectFBPalette *palette = this->screen->hwdata->palette; + if (this->screen && this->screen->hwdata) { + IDirectFBSurface *surface = this->screen->hwdata->surface; + IDirectFBPalette *palette = this->screen->hwdata->palette; - if (palette) - palette->Release (palette); + if (palette) + palette->Release(palette); - if (surface) - surface->Release (surface); + if (surface) + surface->Release(surface); - this->screen->hwdata->surface = NULL; - this->screen->hwdata->palette = NULL; + this->screen->hwdata->surface = NULL; + this->screen->hwdata->palette = NULL; } - if (HIDDEN->c2frame) - { - HIDDEN->c2frame->Release (HIDDEN->c2frame); - HIDDEN->c2frame = NULL; + if (HIDDEN->c2frame) { + HIDDEN->c2frame->Release(HIDDEN->c2frame); + HIDDEN->c2frame = NULL; } - if (HIDDEN->eventbuffer) - { - HIDDEN->eventbuffer->Release (HIDDEN->eventbuffer); - HIDDEN->eventbuffer = NULL; + if (HIDDEN->eventbuffer) { + HIDDEN->eventbuffer->Release(HIDDEN->eventbuffer); + HIDDEN->eventbuffer = NULL; } - if (HIDDEN->c2layer) - { - HIDDEN->c2layer->Release (HIDDEN->c2layer); - HIDDEN->c2layer = NULL; + if (HIDDEN->c2layer) { + HIDDEN->c2layer->Release(HIDDEN->c2layer); + HIDDEN->c2layer = NULL; } - if (HIDDEN->layer) - { - HIDDEN->layer->Release (HIDDEN->layer); - HIDDEN->layer = NULL; + if (HIDDEN->layer) { + HIDDEN->layer->Release(HIDDEN->layer); + HIDDEN->layer = NULL; } - if (HIDDEN->dfb) - { - HIDDEN->dfb->Release (HIDDEN->dfb); - HIDDEN->dfb = NULL; + if (HIDDEN->dfb) { + HIDDEN->dfb->Release(HIDDEN->dfb); + HIDDEN->dfb = NULL; } - /* Free video mode list */ - if (HIDDEN->modelist) - { - free (HIDDEN->modelist); - HIDDEN->modelist = NULL; + /* Free video mode list */ + if (HIDDEN->modelist) { + free(HIDDEN->modelist); + HIDDEN->modelist = NULL; } - /* Free mode enumeration list */ - while (rect) - { - struct DirectFBEnumRect *next = rect->next; - free (rect); - rect = next; + /* Free mode enumeration list */ + while (rect) { + struct DirectFBEnumRect *next = rect->next; + free(rect); + rect = next; } - enumlist = NULL; + enumlist = NULL; - HIDDEN->initialized = 0; + HIDDEN->initialized = 0; } -int DirectFB_ShowWMCursor(_THIS, WMcursor *cursor) +int +DirectFB_ShowWMCursor(_THIS, WMcursor * cursor) { - /* We can only hide or show the default cursor */ - if ( cursor == NULL ) - { - HIDDEN->layer->SetCursorOpacity(HIDDEN->layer, 0x00); + /* We can only hide or show the default cursor */ + if (cursor == NULL) { + HIDDEN->layer->SetCursorOpacity(HIDDEN->layer, 0x00); + } else { + HIDDEN->layer->SetCursorOpacity(HIDDEN->layer, 0xFF); } - else - { - HIDDEN->layer->SetCursorOpacity(HIDDEN->layer, 0xFF); - } - return 1; + return 1; } -void DirectFB_FinalQuit(void) +void +DirectFB_FinalQuit(void) { } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/directfb/SDL_DirectFB_video.h b/src/video/directfb/SDL_DirectFB_video.h index fd92b288e..1a3607d19 100644 --- a/src/video/directfb/SDL_DirectFB_video.h +++ b/src/video/directfb/SDL_DirectFB_video.h @@ -35,28 +35,29 @@ struct SDL_PrivateVideoData { - int initialized; - - IDirectFB *dfb; - IDirectFBDisplayLayer *layer; - IDirectFBEventBuffer *eventbuffer; - - int nummodes; - SDL_Rect **modelist; - - /* MGA CRTC2 support */ - int enable_mga_crtc2; - int mga_crtc2_stretch; - float mga_crtc2_stretch_overscan; - IDirectFBDisplayLayer *c2layer; - IDirectFBSurface *c2frame; - DFBRectangle c2ssize; /* Real screen size */ - DFBRectangle c2dsize; /* Stretched screen size */ - DFBRectangle c2framesize; /* CRTC2 screen size */ + int initialized; + + IDirectFB *dfb; + IDirectFBDisplayLayer *layer; + IDirectFBEventBuffer *eventbuffer; + + int nummodes; + SDL_Rect **modelist; + + /* MGA CRTC2 support */ + int enable_mga_crtc2; + int mga_crtc2_stretch; + float mga_crtc2_stretch_overscan; + IDirectFBDisplayLayer *c2layer; + IDirectFBSurface *c2frame; + DFBRectangle c2ssize; /* Real screen size */ + DFBRectangle c2dsize; /* Stretched screen size */ + DFBRectangle c2framesize; /* CRTC2 screen size */ }; #define HIDDEN (this->hidden) -void SetDirectFBerror (const char *function, DFBResult code); +void SetDirectFBerror(const char *function, DFBResult code); #endif /* _SDL_DirectFB_video_h */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/directfb/SDL_DirectFB_yuv.c b/src/video/directfb/SDL_DirectFB_yuv.c index 583b8274e..931a3acfb 100644 --- a/src/video/directfb/SDL_DirectFB_yuv.c +++ b/src/video/directfb/SDL_DirectFB_yuv.c @@ -30,252 +30,252 @@ /* The functions used to manipulate software video overlays */ static struct private_yuvhwfuncs directfb_yuvfuncs = { - DirectFB_LockYUVOverlay, - DirectFB_UnlockYUVOverlay, - DirectFB_DisplayYUVOverlay, - DirectFB_FreeYUVOverlay + DirectFB_LockYUVOverlay, + DirectFB_UnlockYUVOverlay, + DirectFB_DisplayYUVOverlay, + DirectFB_FreeYUVOverlay }; -struct private_yuvhwdata { - DFBDisplayLayerID layer_id; +struct private_yuvhwdata +{ + DFBDisplayLayerID layer_id; - IDirectFBDisplayLayer *layer; - IDirectFBSurface *surface; + IDirectFBDisplayLayer *layer; + IDirectFBSurface *surface; - /* These are just so we don't have to allocate them separately */ - Uint16 pitches[3]; - Uint8 *planes[3]; + /* These are just so we don't have to allocate them separately */ + Uint16 pitches[3]; + Uint8 *planes[3]; }; static DFBEnumerationResult -enum_layers_callback( DFBDisplayLayerID id, - DFBDisplayLayerDescription desc, - void *data ) +enum_layers_callback(DFBDisplayLayerID id, + DFBDisplayLayerDescription desc, void *data) { - struct private_yuvhwdata *hwdata = (struct private_yuvhwdata *) data; + struct private_yuvhwdata *hwdata = (struct private_yuvhwdata *) data; - /* we don't want the primary */ - if (id == DLID_PRIMARY) - return DFENUM_OK; + /* we don't want the primary */ + if (id == DLID_PRIMARY) + return DFENUM_OK; - /* take the one with a surface for video */ - if ((desc.caps & DLCAPS_SURFACE) && (desc.type & DLTF_VIDEO)) - { - hwdata->layer_id = id; + /* take the one with a surface for video */ + if ((desc.caps & DLCAPS_SURFACE) && (desc.type & DLTF_VIDEO)) { + hwdata->layer_id = id; - return DFENUM_CANCEL; + return DFENUM_CANCEL; } - return DFENUM_OK; + return DFENUM_OK; } -static DFBResult CreateYUVSurface(_THIS, struct private_yuvhwdata *hwdata, - int width, int height, Uint32 format) +static DFBResult +CreateYUVSurface(_THIS, struct private_yuvhwdata *hwdata, + int width, int height, Uint32 format) { - DFBResult ret; - IDirectFB *dfb = HIDDEN->dfb; - IDirectFBDisplayLayer *layer; - DFBDisplayLayerConfig conf; - - ret = dfb->EnumDisplayLayers (dfb, enum_layers_callback, hwdata); - if (ret) - { - SetDirectFBerror("IDirectFB::EnumDisplayLayers", ret); - return ret; + DFBResult ret; + IDirectFB *dfb = HIDDEN->dfb; + IDirectFBDisplayLayer *layer; + DFBDisplayLayerConfig conf; + + ret = dfb->EnumDisplayLayers(dfb, enum_layers_callback, hwdata); + if (ret) { + SetDirectFBerror("IDirectFB::EnumDisplayLayers", ret); + return ret; } - if (!hwdata->layer_id) - return DFB_UNSUPPORTED; + if (!hwdata->layer_id) + return DFB_UNSUPPORTED; - ret = dfb->GetDisplayLayer (dfb, hwdata->layer_id, &layer); - if (ret) - { - SetDirectFBerror("IDirectFB::GetDisplayLayer", ret); - return ret; + ret = dfb->GetDisplayLayer(dfb, hwdata->layer_id, &layer); + if (ret) { + SetDirectFBerror("IDirectFB::GetDisplayLayer", ret); + return ret; } - conf.flags = DLCONF_WIDTH | DLCONF_HEIGHT | DLCONF_PIXELFORMAT; - conf.width = width; - conf.height = height; + conf.flags = DLCONF_WIDTH | DLCONF_HEIGHT | DLCONF_PIXELFORMAT; + conf.width = width; + conf.height = height; - switch (format) - { + switch (format) { case SDL_YV12_OVERLAY: - conf.pixelformat = DSPF_YV12; - break; + conf.pixelformat = DSPF_YV12; + break; case SDL_IYUV_OVERLAY: - conf.pixelformat = DSPF_I420; - break; + conf.pixelformat = DSPF_I420; + break; case SDL_YUY2_OVERLAY: - conf.pixelformat = DSPF_YUY2; - break; + conf.pixelformat = DSPF_YUY2; + break; case SDL_UYVY_OVERLAY: - conf.pixelformat = DSPF_UYVY; - break; + conf.pixelformat = DSPF_UYVY; + break; default: - fprintf (stderr, "SDL_DirectFB: Unsupported YUV format (0x%08x)!\n", format); - break; + fprintf(stderr, "SDL_DirectFB: Unsupported YUV format (0x%08x)!\n", + format); + break; } - ret = layer->SetConfiguration (layer, &conf); - if (ret) - { - SetDirectFBerror("IDirectFBDisplayLayer::SetConfiguration", ret); - layer->Release (layer); - return ret; + ret = layer->SetConfiguration(layer, &conf); + if (ret) { + SetDirectFBerror("IDirectFBDisplayLayer::SetConfiguration", ret); + layer->Release(layer); + return ret; } - ret = layer->GetSurface (layer, &hwdata->surface); - if (ret) - { - SetDirectFBerror("IDirectFBDisplayLayer::GetSurface", ret); - layer->Release (layer); - return ret; + ret = layer->GetSurface(layer, &hwdata->surface); + if (ret) { + SetDirectFBerror("IDirectFBDisplayLayer::GetSurface", ret); + layer->Release(layer); + return ret; } - hwdata->layer = layer; + hwdata->layer = layer; - return DFB_OK; + return DFB_OK; } -SDL_Overlay *DirectFB_CreateYUVOverlay(_THIS, int width, int height, Uint32 format, SDL_Surface *display) +SDL_Overlay * +DirectFB_CreateYUVOverlay(_THIS, int width, int height, Uint32 format, + SDL_Surface * display) { - SDL_Overlay *overlay; - struct private_yuvhwdata *hwdata; - - /* Create the overlay structure */ - overlay = SDL_calloc (1, sizeof(SDL_Overlay)); - if (!overlay) - { - SDL_OutOfMemory(); - return NULL; + SDL_Overlay *overlay; + struct private_yuvhwdata *hwdata; + + /* Create the overlay structure */ + overlay = SDL_calloc(1, sizeof(SDL_Overlay)); + if (!overlay) { + SDL_OutOfMemory(); + return NULL; } - - /* Fill in the basic members */ - overlay->format = format; - overlay->w = width; - overlay->h = height; - - /* Set up the YUV surface function structure */ - overlay->hwfuncs = &directfb_yuvfuncs; - - /* Create the pixel data and lookup tables */ - hwdata = SDL_calloc(1, sizeof(struct private_yuvhwdata)); - overlay->hwdata = hwdata; - if (!hwdata) - { - SDL_OutOfMemory(); - SDL_FreeYUVOverlay (overlay); - return NULL; + + /* Fill in the basic members */ + overlay->format = format; + overlay->w = width; + overlay->h = height; + + /* Set up the YUV surface function structure */ + overlay->hwfuncs = &directfb_yuvfuncs; + + /* Create the pixel data and lookup tables */ + hwdata = SDL_calloc(1, sizeof(struct private_yuvhwdata)); + overlay->hwdata = hwdata; + if (!hwdata) { + SDL_OutOfMemory(); + SDL_FreeYUVOverlay(overlay); + return NULL; } - if (CreateYUVSurface (this, hwdata, width, height, format)) - { - SDL_FreeYUVOverlay (overlay); - return NULL; + if (CreateYUVSurface(this, hwdata, width, height, format)) { + SDL_FreeYUVOverlay(overlay); + return NULL; } - overlay->hw_overlay = 1; + overlay->hw_overlay = 1; - /* Set up the plane pointers */ - overlay->pitches = hwdata->pitches; - overlay->pixels = hwdata->planes; - switch (format) - { + /* Set up the plane pointers */ + overlay->pitches = hwdata->pitches; + overlay->pixels = hwdata->planes; + switch (format) { case SDL_YV12_OVERLAY: case SDL_IYUV_OVERLAY: - overlay->planes = 3; - break; + overlay->planes = 3; + break; default: - overlay->planes = 1; - break; + overlay->planes = 1; + break; } - /* We're all done.. */ - return overlay; + /* We're all done.. */ + return overlay; } -int DirectFB_LockYUVOverlay(_THIS, SDL_Overlay *overlay) +int +DirectFB_LockYUVOverlay(_THIS, SDL_Overlay * overlay) { - DFBResult ret; - void *data; - int pitch; - IDirectFBSurface *surface = overlay->hwdata->surface; - - ret = surface->Lock (surface, DSLF_READ | DSLF_WRITE, &data, &pitch); - if (ret) - { - SetDirectFBerror("IDirectFBSurface::Lock", ret); - return -1; + DFBResult ret; + void *data; + int pitch; + IDirectFBSurface *surface = overlay->hwdata->surface; + + ret = surface->Lock(surface, DSLF_READ | DSLF_WRITE, &data, &pitch); + if (ret) { + SetDirectFBerror("IDirectFBSurface::Lock", ret); + return -1; } - /* Find the pitch and offset values for the overlay */ - overlay->pitches[0] = (Uint16) pitch; - overlay->pixels[0] = (Uint8*) data; + /* Find the pitch and offset values for the overlay */ + overlay->pitches[0] = (Uint16) pitch; + overlay->pixels[0] = (Uint8 *) data; - switch (overlay->format) - { + switch (overlay->format) { case SDL_YV12_OVERLAY: case SDL_IYUV_OVERLAY: - /* Add the two extra planes */ - overlay->pitches[1] = overlay->pitches[0] / 2; - overlay->pitches[2] = overlay->pitches[0] / 2; - overlay->pixels[1] = overlay->pixels[0] + overlay->pitches[0] * overlay->h; - overlay->pixels[2] = overlay->pixels[1] + overlay->pitches[1] * overlay->h / 2; - break; + /* Add the two extra planes */ + overlay->pitches[1] = overlay->pitches[0] / 2; + overlay->pitches[2] = overlay->pitches[0] / 2; + overlay->pixels[1] = + overlay->pixels[0] + overlay->pitches[0] * overlay->h; + overlay->pixels[2] = + overlay->pixels[1] + overlay->pitches[1] * overlay->h / 2; + break; default: - /* Only one plane, no worries */ - break; + /* Only one plane, no worries */ + break; } - return 0; + return 0; } -void DirectFB_UnlockYUVOverlay(_THIS, SDL_Overlay *overlay) +void +DirectFB_UnlockYUVOverlay(_THIS, SDL_Overlay * overlay) { - IDirectFBSurface *surface = overlay->hwdata->surface; + IDirectFBSurface *surface = overlay->hwdata->surface; - overlay->pixels[0] = overlay->pixels[1] = overlay->pixels[2] = NULL; + overlay->pixels[0] = overlay->pixels[1] = overlay->pixels[2] = NULL; - surface->Unlock (surface); + surface->Unlock(surface); } -int DirectFB_DisplayYUVOverlay(_THIS, SDL_Overlay *overlay, SDL_Rect *src, SDL_Rect *dst) +int +DirectFB_DisplayYUVOverlay(_THIS, SDL_Overlay * overlay, SDL_Rect * src, + SDL_Rect * dst) { - DFBResult ret; - DFBDisplayLayerConfig conf; - IDirectFBDisplayLayer *primary = HIDDEN->layer; - IDirectFBDisplayLayer *layer = overlay->hwdata->layer; - - primary->GetConfiguration (primary, &conf); - - ret = layer->SetScreenLocation (layer, - dst->x / (float) conf.width, dst->y / (float) conf.height, - dst->w / (float) conf.width, dst->h / (float) conf.height ); - if (ret) - { - SetDirectFBerror("IDirectFBDisplayLayer::SetScreenLocation", ret); - return -1; + DFBResult ret; + DFBDisplayLayerConfig conf; + IDirectFBDisplayLayer *primary = HIDDEN->layer; + IDirectFBDisplayLayer *layer = overlay->hwdata->layer; + + primary->GetConfiguration(primary, &conf); + + ret = layer->SetScreenLocation(layer, + dst->x / (float) conf.width, + dst->y / (float) conf.height, + dst->w / (float) conf.width, + dst->h / (float) conf.height); + if (ret) { + SetDirectFBerror("IDirectFBDisplayLayer::SetScreenLocation", ret); + return -1; } - return 0; + return 0; } -void DirectFB_FreeYUVOverlay(_THIS, SDL_Overlay *overlay) +void +DirectFB_FreeYUVOverlay(_THIS, SDL_Overlay * overlay) { - struct private_yuvhwdata *hwdata; + struct private_yuvhwdata *hwdata; - hwdata = overlay->hwdata; - if (hwdata) - { - if (hwdata->surface) - hwdata->surface->Release (hwdata->surface); + hwdata = overlay->hwdata; + if (hwdata) { + if (hwdata->surface) + hwdata->surface->Release(hwdata->surface); - if (hwdata->layer) - hwdata->layer->Release (hwdata->layer); + if (hwdata->layer) + hwdata->layer->Release(hwdata->layer); - free (hwdata); + free(hwdata); } } +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/directfb/SDL_DirectFB_yuv.h b/src/video/directfb/SDL_DirectFB_yuv.h index 23a42dc2b..a2098a07d 100644 --- a/src/video/directfb/SDL_DirectFB_yuv.h +++ b/src/video/directfb/SDL_DirectFB_yuv.h @@ -26,13 +26,16 @@ #include "SDL_video.h" #include "SDL_DirectFB_video.h" -extern SDL_Overlay *DirectFB_CreateYUVOverlay(_THIS, int width, int height, Uint32 format, SDL_Surface *display); +extern SDL_Overlay *DirectFB_CreateYUVOverlay(_THIS, int width, int height, + Uint32 format, + SDL_Surface * display); -extern int DirectFB_LockYUVOverlay(_THIS, SDL_Overlay *overlay); +extern int DirectFB_LockYUVOverlay(_THIS, SDL_Overlay * overlay); -extern void DirectFB_UnlockYUVOverlay(_THIS, SDL_Overlay *overlay); +extern void DirectFB_UnlockYUVOverlay(_THIS, SDL_Overlay * overlay); -extern int DirectFB_DisplayYUVOverlay(_THIS, SDL_Overlay *overlay, SDL_Rect *src, SDL_Rect *dst); - -extern void DirectFB_FreeYUVOverlay(_THIS, SDL_Overlay *overlay); +extern int DirectFB_DisplayYUVOverlay(_THIS, SDL_Overlay * overlay, + SDL_Rect * src, SDL_Rect * dst); +extern void DirectFB_FreeYUVOverlay(_THIS, SDL_Overlay * overlay); +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/dummy/SDL_nullevents.c b/src/video/dummy/SDL_nullevents.c index 099475f60..bfb8f28d6 100644 --- a/src/video/dummy/SDL_nullevents.c +++ b/src/video/dummy/SDL_nullevents.c @@ -31,15 +31,10 @@ #include "SDL_nullvideo.h" #include "SDL_nullevents_c.h" -void DUMMY_PumpEvents(_THIS) +void +DUMMY_PumpEvents(_THIS) { - /* do nothing. */ + /* do nothing. */ } -void DUMMY_InitOSKeymap(_THIS) -{ - /* do nothing. */ -} - -/* end of SDL_nullevents.c ... */ - +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/dummy/SDL_nullevents_c.h b/src/video/dummy/SDL_nullevents_c.h index 674c336fa..c53fcddb1 100644 --- a/src/video/dummy/SDL_nullevents_c.h +++ b/src/video/dummy/SDL_nullevents_c.h @@ -23,11 +23,6 @@ #include "SDL_nullvideo.h" -/* Variables and functions exported by SDL_sysevents.c to other parts - of the native video subsystem (SDL_sysvideo.c) -*/ -extern void DUMMY_InitOSKeymap(_THIS); extern void DUMMY_PumpEvents(_THIS); -/* end of SDL_nullevents_c.h ... */ - +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/dummy/SDL_nullrender.c b/src/video/dummy/SDL_nullrender.c new file mode 100644 index 000000000..fb8d0592d --- /dev/null +++ b/src/video/dummy/SDL_nullrender.c @@ -0,0 +1,194 @@ +/* + SDL - Simple DirectMedia Layer + Copyright (C) 1997-2006 Sam Lantinga + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + Sam Lantinga + slouken@libsdl.org +*/ +#include "SDL_config.h" + +#include "SDL_video.h" +#include "../SDL_sysvideo.h" + + +/* SDL surface based renderer implementation */ + +static SDL_Renderer *SDL_DUMMY_CreateRenderer(SDL_Window * window, + Uint32 flags); +static int SDL_DUMMY_CreateTexture(SDL_Renderer * renderer, + SDL_Texture * texture); +static int SDL_DUMMY_RenderReadPixels(SDL_Renderer * renderer, + const SDL_Rect * rect, void *pixels, + int pitch); +static int SDL_DUMMY_RenderWritePixels(SDL_Renderer * renderer, + const SDL_Rect * rect, + const void *pixels, int pitch); +static void SDL_DUMMY_RenderPresent(SDL_Renderer * renderer); +static void SDL_DUMMY_DestroyRenderer(SDL_Renderer * renderer); + + +SDL_RenderDriver SDL_DUMMY_RenderDriver = { + SDL_DUMMY_CreateRenderer, + { + "minimal", + (SDL_Renderer_Minimal | SDL_Renderer_PresentDiscard | + SDL_Renderer_PresentCopy), + SDL_TextureBlendMode_None, + SDL_TextureScaleMode_None, + 0, + {0}, + 0, + 0} +}; + +typedef struct +{ + SDL_Surface *surface; +} SDL_DUMMY_RenderData; + +SDL_Renderer * +SDL_DUMMY_CreateRenderer(SDL_Window * window, Uint32 flags) +{ + SDL_VideoDisplay *display = SDL_GetDisplayFromWindow(window); + SDL_DisplayMode *displayMode = &display->current_mode; + SDL_Renderer *renderer; + SDL_DUMMY_RenderData *data; + int bpp; + Uint32 Rmask, Gmask, Bmask, Amask; + + if (!SDL_PixelFormatEnumToMasks + (displayMode->format, &bpp, &Rmask, &Gmask, &Bmask, &Amask)) { + SDL_SetError("Unknown display format"); + return NULL; + } + + renderer = (SDL_Renderer *) SDL_malloc(sizeof(*renderer)); + if (!renderer) { + SDL_OutOfMemory(); + return NULL; + } + SDL_zerop(renderer); + + data = (SDL_DUMMY_RenderData *) SDL_malloc(sizeof(*data)); + if (!data) { + SDL_DUMMY_DestroyRenderer(renderer); + SDL_OutOfMemory(); + return NULL; + } + SDL_zerop(data); + + renderer->RenderReadPixels = SDL_DUMMY_RenderReadPixels; + renderer->RenderWritePixels = SDL_DUMMY_RenderWritePixels; + renderer->RenderPresent = SDL_DUMMY_RenderPresent; + renderer->DestroyRenderer = SDL_DUMMY_DestroyRenderer; + renderer->info = SDL_DUMMY_RenderDriver.info; + renderer->window = window->id; + renderer->driverdata = data; + + data->surface = + SDL_CreateRGBSurface(0, window->w, window->h, bpp, Rmask, Gmask, + Bmask, Amask); + if (!data->surface) { + SDL_DUMMY_DestroyRenderer(renderer); + return NULL; + } + SDL_SetSurfacePalette(data->surface, display->palette); + + return renderer; +} + +int +SDL_DUMMY_RenderReadPixels(SDL_Renderer * renderer, const SDL_Rect * rect, + void *pixels, int pitch) +{ + SDL_DUMMY_RenderData *data = + (SDL_DUMMY_RenderData *) renderer->driverdata; + SDL_Surface *surface = data->surface; + Uint8 *src, *dst; + int row; + size_t length; + + src = + (Uint8 *) surface->pixels + rect->y * surface->pitch + + rect->x * surface->format->BytesPerPixel; + dst = (Uint8 *) pixels; + length = rect->w * surface->format->BytesPerPixel; + for (row = 0; row < rect->h; ++row) { + SDL_memcpy(dst, src, length); + src += surface->pitch; + dst += pitch; + } + return 0; +} + +int +SDL_DUMMY_RenderWritePixels(SDL_Renderer * renderer, const SDL_Rect * rect, + const void *pixels, int pitch) +{ + SDL_DUMMY_RenderData *data = + (SDL_DUMMY_RenderData *) renderer->driverdata; + SDL_Surface *surface = data->surface; + Uint8 *src, *dst; + int row; + size_t length; + + src = (Uint8 *) pixels; + dst = + (Uint8 *) surface->pixels + rect->y * surface->pitch + + rect->x * surface->format->BytesPerPixel; + length = rect->w * surface->format->BytesPerPixel; + for (row = 0; row < rect->h; ++row) { + SDL_memcpy(dst, src, length); + src += pitch; + dst += surface->pitch; + } + return 0; +} + +void +SDL_DUMMY_RenderPresent(SDL_Renderer * renderer) +{ + static int frame_number; + SDL_DUMMY_RenderData *data = + (SDL_DUMMY_RenderData *) renderer->driverdata; + SDL_Surface *surface = data->surface; + + if (SDL_getenv("SDL_VIDEO_DUMMY_SAVE_FRAMES")) { + char file[128]; + SDL_snprintf(file, sizeof(file), "SDL_window%d-%8.8d.bmp", + renderer->window, ++frame_number); + SDL_SaveBMP(surface, file); + } +} + +void +SDL_DUMMY_DestroyRenderer(SDL_Renderer * renderer) +{ + SDL_DUMMY_RenderData *data = + (SDL_DUMMY_RenderData *) renderer->driverdata; + + if (data) { + if (data->surface) { + data->surface->format->palette = NULL; + SDL_FreeSurface(data->surface); + } + SDL_free(data); + } + SDL_free(renderer); +} + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/include/SDL_getenv.h b/src/video/dummy/SDL_nullrender_c.h similarity index 84% rename from include/SDL_getenv.h rename to src/video/dummy/SDL_nullrender_c.h index 853b9ce45..ef6d3a919 100644 --- a/include/SDL_getenv.h +++ b/src/video/dummy/SDL_nullrender_c.h @@ -19,6 +19,10 @@ Sam Lantinga slouken@libsdl.org */ +#include "SDL_config.h" -/* DEPRECATED */ -#include "SDL_stdinc.h" +/* SDL surface based renderer implementation */ + +extern SDL_RenderDriver SDL_DUMMY_RenderDriver; + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/dummy/SDL_nullvideo.c b/src/video/dummy/SDL_nullvideo.c index fe6fab6cc..36b986800 100644 --- a/src/video/dummy/SDL_nullvideo.c +++ b/src/video/dummy/SDL_nullvideo.c @@ -44,196 +44,90 @@ #include "SDL_nullvideo.h" #include "SDL_nullevents_c.h" -#include "SDL_nullmouse_c.h" +#include "SDL_nullrender_c.h" #define DUMMYVID_DRIVER_NAME "dummy" /* Initialization/Query functions */ -static int DUMMY_VideoInit(_THIS, SDL_PixelFormat *vformat); -static SDL_Rect **DUMMY_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags); -static SDL_Surface *DUMMY_SetVideoMode(_THIS, SDL_Surface *current, int width, int height, int bpp, Uint32 flags); -static int DUMMY_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color *colors); +static int DUMMY_VideoInit(_THIS); +static int DUMMY_SetDisplayMode(_THIS, SDL_DisplayMode * mode); static void DUMMY_VideoQuit(_THIS); -/* Hardware surface functions */ -static int DUMMY_AllocHWSurface(_THIS, SDL_Surface *surface); -static int DUMMY_LockHWSurface(_THIS, SDL_Surface *surface); -static void DUMMY_UnlockHWSurface(_THIS, SDL_Surface *surface); -static void DUMMY_FreeHWSurface(_THIS, SDL_Surface *surface); - -/* etc. */ -static void DUMMY_UpdateRects(_THIS, int numrects, SDL_Rect *rects); - /* DUMMY driver bootstrap functions */ -static int DUMMY_Available(void) +static int +DUMMY_Available(void) { - const char *envr = SDL_getenv("SDL_VIDEODRIVER"); - if ((envr) && (SDL_strcmp(envr, DUMMYVID_DRIVER_NAME) == 0)) { - return(1); - } + const char *envr = SDL_getenv("SDL_VIDEODRIVER"); + if ((envr) && (SDL_strcmp(envr, DUMMYVID_DRIVER_NAME) == 0)) { + return (1); + } - return(0); + return (0); } -static void DUMMY_DeleteDevice(SDL_VideoDevice *device) +static void +DUMMY_DeleteDevice(SDL_VideoDevice * device) { - SDL_free(device->hidden); - SDL_free(device); + SDL_free(device); } -static SDL_VideoDevice *DUMMY_CreateDevice(int devindex) +static SDL_VideoDevice * +DUMMY_CreateDevice(int devindex) { - SDL_VideoDevice *device; - - /* Initialize all variables that we clean on shutdown */ - device = (SDL_VideoDevice *)SDL_malloc(sizeof(SDL_VideoDevice)); - if ( device ) { - SDL_memset(device, 0, (sizeof *device)); - device->hidden = (struct SDL_PrivateVideoData *) - SDL_malloc((sizeof *device->hidden)); - } - if ( (device == NULL) || (device->hidden == NULL) ) { - SDL_OutOfMemory(); - if ( device ) { - SDL_free(device); - } - return(0); - } - SDL_memset(device->hidden, 0, (sizeof *device->hidden)); - - /* Set the function pointers */ - device->VideoInit = DUMMY_VideoInit; - device->ListModes = DUMMY_ListModes; - device->SetVideoMode = DUMMY_SetVideoMode; - device->CreateYUVOverlay = NULL; - device->SetColors = DUMMY_SetColors; - device->UpdateRects = DUMMY_UpdateRects; - device->VideoQuit = DUMMY_VideoQuit; - device->AllocHWSurface = DUMMY_AllocHWSurface; - device->CheckHWBlit = NULL; - device->FillHWRect = NULL; - device->SetHWColorKey = NULL; - device->SetHWAlpha = NULL; - device->LockHWSurface = DUMMY_LockHWSurface; - device->UnlockHWSurface = DUMMY_UnlockHWSurface; - device->FlipHWSurface = NULL; - device->FreeHWSurface = DUMMY_FreeHWSurface; - device->SetCaption = NULL; - device->SetIcon = NULL; - device->IconifyWindow = NULL; - device->GrabInput = NULL; - device->GetWMInfo = NULL; - device->InitOSKeymap = DUMMY_InitOSKeymap; - device->PumpEvents = DUMMY_PumpEvents; - - device->free = DUMMY_DeleteDevice; - - return device; + SDL_VideoDevice *device; + + /* Initialize all variables that we clean on shutdown */ + device = (SDL_VideoDevice *) SDL_calloc(1, sizeof(SDL_VideoDevice)); + if (!device) { + SDL_OutOfMemory(); + if (device) { + SDL_free(device); + } + return (0); + } + + /* Set the function pointers */ + device->VideoInit = DUMMY_VideoInit; + device->SetDisplayMode = DUMMY_SetDisplayMode; + device->VideoQuit = DUMMY_VideoQuit; + device->PumpEvents = DUMMY_PumpEvents; + + device->free = DUMMY_DeleteDevice; + + return device; } VideoBootStrap DUMMY_bootstrap = { - DUMMYVID_DRIVER_NAME, "SDL dummy video driver", - DUMMY_Available, DUMMY_CreateDevice + DUMMYVID_DRIVER_NAME, "SDL dummy video driver", + DUMMY_Available, DUMMY_CreateDevice }; -int DUMMY_VideoInit(_THIS, SDL_PixelFormat *vformat) +int +DUMMY_VideoInit(_THIS) { - /* - fprintf(stderr, "WARNING: You are using the SDL dummy video driver!\n"); - */ + SDL_DisplayMode mode; - /* Determine the screen depth (use default 8-bit depth) */ - /* we change this during the SDL_SetVideoMode implementation... */ - vformat->BitsPerPixel = 8; - vformat->BytesPerPixel = 1; + SDL_AddBasicVideoDisplay(NULL); + SDL_AddRenderDriver(0, &SDL_DUMMY_RenderDriver); - /* We're done! */ - return(0); -} + SDL_zero(mode); + SDL_AddDisplayMode(0, &mode); -SDL_Rect **DUMMY_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags) -{ - return (SDL_Rect **) -1; + /* We're done! */ + return 0; } -SDL_Surface *DUMMY_SetVideoMode(_THIS, SDL_Surface *current, - int width, int height, int bpp, Uint32 flags) +static int +DUMMY_SetDisplayMode(_THIS, SDL_DisplayMode * mode) { - if ( this->hidden->buffer ) { - SDL_free( this->hidden->buffer ); - } - - this->hidden->buffer = SDL_malloc(width * height * (bpp / 8)); - if ( ! this->hidden->buffer ) { - SDL_SetError("Couldn't allocate buffer for requested mode"); - return(NULL); - } - -/* printf("Setting mode %dx%d\n", width, height); */ - - SDL_memset(this->hidden->buffer, 0, width * height * (bpp / 8)); - - /* Allocate the new pixel format for the screen */ - if ( ! SDL_ReallocFormat(current, bpp, 0, 0, 0, 0) ) { - SDL_free(this->hidden->buffer); - this->hidden->buffer = NULL; - SDL_SetError("Couldn't allocate new pixel format for requested mode"); - return(NULL); - } - - /* Set up the new mode framebuffer */ - current->flags = flags & SDL_FULLSCREEN; - this->hidden->w = current->w = width; - this->hidden->h = current->h = height; - current->pitch = current->w * (bpp / 8); - current->pixels = this->hidden->buffer; - - /* We're done */ - return(current); + return 0; } -/* We don't actually allow hardware surfaces other than the main one */ -static int DUMMY_AllocHWSurface(_THIS, SDL_Surface *surface) -{ - return(-1); -} -static void DUMMY_FreeHWSurface(_THIS, SDL_Surface *surface) +void +DUMMY_VideoQuit(_THIS) { - return; } -/* We need to wait for vertical retrace on page flipped displays */ -static int DUMMY_LockHWSurface(_THIS, SDL_Surface *surface) -{ - return(0); -} - -static void DUMMY_UnlockHWSurface(_THIS, SDL_Surface *surface) -{ - return; -} - -static void DUMMY_UpdateRects(_THIS, int numrects, SDL_Rect *rects) -{ - /* do nothing. */ -} - -int DUMMY_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color *colors) -{ - /* do nothing of note. */ - return(1); -} - -/* Note: If we are terminated, this could be called in the middle of - another SDL video routine -- notably UpdateRects. -*/ -void DUMMY_VideoQuit(_THIS) -{ - if (this->screen->pixels != NULL) - { - SDL_free(this->screen->pixels); - this->screen->pixels = NULL; - } -} +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/dummy/SDL_nullvideo.h b/src/video/dummy/SDL_nullvideo.h index a615ff454..378ad29f6 100644 --- a/src/video/dummy/SDL_nullvideo.h +++ b/src/video/dummy/SDL_nullvideo.h @@ -26,15 +26,6 @@ #include "../SDL_sysvideo.h" -/* Hidden "this" pointer for the video functions */ -#define _THIS SDL_VideoDevice *this - - -/* Private display data */ - -struct SDL_PrivateVideoData { - int w, h; - void *buffer; -}; - #endif /* _SDL_nullvideo_h */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/e_log.h b/src/video/e_log.h index 7f8bf7161..44321e716 100644 --- a/src/video/e_log.h +++ b/src/video/e_log.h @@ -73,68 +73,89 @@ static const double #else static double #endif -ln2_hi = 6.93147180369123816490e-01, /* 3fe62e42 fee00000 */ -ln2_lo = 1.90821492927058770002e-10, /* 3dea39ef 35793c76 */ -Lg1 = 6.666666666666735130e-01, /* 3FE55555 55555593 */ -Lg2 = 3.999999999940941908e-01, /* 3FD99999 9997FA04 */ -Lg3 = 2.857142874366239149e-01, /* 3FD24924 94229359 */ -Lg4 = 2.222219843214978396e-01, /* 3FCC71C5 1D8E78AF */ -Lg5 = 1.818357216161805012e-01, /* 3FC74664 96CB03DE */ -Lg6 = 1.531383769920937332e-01, /* 3FC39A09 D078C69F */ -Lg7 = 1.479819860511658591e-01; /* 3FC2F112 DF3E5244 */ + ln2_hi = 6.93147180369123816490e-01, /* 3fe62e42 fee00000 */ + ln2_lo = 1.90821492927058770002e-10, /* 3dea39ef 35793c76 */ + Lg1 = 6.666666666666735130e-01, /* 3FE55555 55555593 */ + Lg2 = 3.999999999940941908e-01, /* 3FD99999 9997FA04 */ + Lg3 = 2.857142874366239149e-01, /* 3FD24924 94229359 */ + Lg4 = 2.222219843214978396e-01, /* 3FCC71C5 1D8E78AF */ + Lg5 = 1.818357216161805012e-01, /* 3FC74664 96CB03DE */ + Lg6 = 1.531383769920937332e-01, /* 3FC39A09 D078C69F */ + Lg7 = 1.479819860511658591e-01; /* 3FC2F112 DF3E5244 */ #ifdef __STDC__ - double __ieee754_log(double x) +double +__ieee754_log(double x) #else - double __ieee754_log(x) - double x; +double +__ieee754_log(x) + double x; #endif { - double hfsq,f,s,z,R,w,t1,t2,dk; - int32_t k,hx,i,j; - u_int32_t lx; + double hfsq, f, s, z, R, w, t1, t2, dk; + int32_t k, hx, i, j; + u_int32_t lx; - EXTRACT_WORDS(hx,lx,x); + EXTRACT_WORDS(hx, lx, x); - k=0; - if (hx < 0x00100000) { /* x < 2**-1022 */ - if (((hx&0x7fffffff)|lx)==0) - return -two54/zero; /* log(+-0)=-inf */ - if (hx<0) return (x-x)/zero; /* log(-#) = NaN */ - k -= 54; x *= two54; /* subnormal number, scale up x */ - GET_HIGH_WORD(hx,x); - } - if (hx >= 0x7ff00000) return x+x; - k += (hx>>20)-1023; - hx &= 0x000fffff; - i = (hx+0x95f64)&0x100000; - SET_HIGH_WORD(x,hx|(i^0x3ff00000)); /* normalize x or x/2 */ - k += (i>>20); - f = x-1.0; - if((0x000fffff&(2+hx))<3) { /* |f| < 2**-20 */ - if(f==zero) {if(k==0) return zero; else {dk=(double)k; - return dk*ln2_hi+dk*ln2_lo;} - } - R = f*f*(0.5-0.33333333333333333*f); - if(k==0) return f-R; else {dk=(double)k; - return dk*ln2_hi-((R-dk*ln2_lo)-f);} - } - s = f/(2.0+f); - dk = (double)k; - z = s*s; - i = hx-0x6147a; - w = z*z; - j = 0x6b851-hx; - t1= w*(Lg2+w*(Lg4+w*Lg6)); - t2= z*(Lg1+w*(Lg3+w*(Lg5+w*Lg7))); - i |= j; - R = t2+t1; - if(i>0) { - hfsq=0.5*f*f; - if(k==0) return f-(hfsq-s*(hfsq+R)); else - return dk*ln2_hi-((hfsq-(s*(hfsq+R)+dk*ln2_lo))-f); - } else { - if(k==0) return f-s*(f-R); else - return dk*ln2_hi-((s*(f-R)-dk*ln2_lo)-f); - } + k = 0; + if (hx < 0x00100000) { /* x < 2**-1022 */ + if (((hx & 0x7fffffff) | lx) == 0) + return -two54 / zero; /* log(+-0)=-inf */ + if (hx < 0) + return (x - x) / zero; /* log(-#) = NaN */ + k -= 54; + x *= two54; /* subnormal number, scale up x */ + GET_HIGH_WORD(hx, x); + } + if (hx >= 0x7ff00000) + return x + x; + k += (hx >> 20) - 1023; + hx &= 0x000fffff; + i = (hx + 0x95f64) & 0x100000; + SET_HIGH_WORD(x, hx | (i ^ 0x3ff00000)); /* normalize x or x/2 */ + k += (i >> 20); + f = x - 1.0; + if ((0x000fffff & (2 + hx)) < 3) { /* |f| < 2**-20 */ + if (f == zero) { + if (k == 0) + return zero; + else { + dk = (double) k; + return dk * ln2_hi + dk * ln2_lo; + } + } + R = f * f * (0.5 - 0.33333333333333333 * f); + if (k == 0) + return f - R; + else { + dk = (double) k; + return dk * ln2_hi - ((R - dk * ln2_lo) - f); + } + } + s = f / (2.0 + f); + dk = (double) k; + z = s * s; + i = hx - 0x6147a; + w = z * z; + j = 0x6b851 - hx; + t1 = w * (Lg2 + w * (Lg4 + w * Lg6)); + t2 = z * (Lg1 + w * (Lg3 + w * (Lg5 + w * Lg7))); + i |= j; + R = t2 + t1; + if (i > 0) { + hfsq = 0.5 * f * f; + if (k == 0) + return f - (hfsq - s * (hfsq + R)); + else + return dk * ln2_hi - ((hfsq - (s * (hfsq + R) + dk * ln2_lo)) - + f); + } else { + if (k == 0) + return f - s * (f - R); + else + return dk * ln2_hi - ((s * (f - R) - dk * ln2_lo) - f); + } } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/e_pow.h b/src/video/e_pow.h index 0aa372a68..d87348d72 100644 --- a/src/video/e_pow.h +++ b/src/video/e_pow.h @@ -67,236 +67,274 @@ static const double #else static double #endif -bp[] = {1.0, 1.5,}, -dp_h[] = { 0.0, 5.84962487220764160156e-01,}, /* 0x3FE2B803, 0x40000000 */ -dp_l[] = { 0.0, 1.35003920212974897128e-08,}, /* 0x3E4CFDEB, 0x43CFD006 */ - /* poly coefs for (3/2)*(log(x)-2s-2/3*s**3 */ -L1 = 5.99999999999994648725e-01, /* 0x3FE33333, 0x33333303 */ -L2 = 4.28571428578550184252e-01, /* 0x3FDB6DB6, 0xDB6FABFF */ -L3 = 3.33333329818377432918e-01, /* 0x3FD55555, 0x518F264D */ -L4 = 2.72728123808534006489e-01, /* 0x3FD17460, 0xA91D4101 */ -L5 = 2.30660745775561754067e-01, /* 0x3FCD864A, 0x93C9DB65 */ -L6 = 2.06975017800338417784e-01, /* 0x3FCA7E28, 0x4A454EEF */ -P1 = 1.66666666666666019037e-01, /* 0x3FC55555, 0x5555553E */ -P2 = -2.77777777770155933842e-03, /* 0xBF66C16C, 0x16BEBD93 */ -P3 = 6.61375632143793436117e-05, /* 0x3F11566A, 0xAF25DE2C */ -P4 = -1.65339022054652515390e-06, /* 0xBEBBBD41, 0xC5D26BF1 */ -P5 = 4.13813679705723846039e-08, /* 0x3E663769, 0x72BEA4D0 */ -lg2 = 6.93147180559945286227e-01, /* 0x3FE62E42, 0xFEFA39EF */ -lg2_h = 6.93147182464599609375e-01, /* 0x3FE62E43, 0x00000000 */ -lg2_l = -1.90465429995776804525e-09, /* 0xBE205C61, 0x0CA86C39 */ -ovt = 8.0085662595372944372e-0017, /* -(1024-log2(ovfl+.5ulp)) */ -cp = 9.61796693925975554329e-01, /* 0x3FEEC709, 0xDC3A03FD =2/(3ln2) */ -cp_h = 9.61796700954437255859e-01, /* 0x3FEEC709, 0xE0000000 =(float)cp */ -cp_l = -7.02846165095275826516e-09, /* 0xBE3E2FE0, 0x145B01F5 =tail of cp_h*/ -ivln2 = 1.44269504088896338700e+00, /* 0x3FF71547, 0x652B82FE =1/ln2 */ -ivln2_h = 1.44269502162933349609e+00, /* 0x3FF71547, 0x60000000 =24b 1/ln2*/ -ivln2_l = 1.92596299112661746887e-08; /* 0x3E54AE0B, 0xF85DDF44 =1/ln2 tail*/ + bp[] = { 1.0, 1.5, }, dp_h[] = { +0.0, 5.84962487220764160156e-01,}, /* 0x3FE2B803, 0x40000000 */ + + dp_l[] = { +0.0, 1.35003920212974897128e-08,}, /* 0x3E4CFDEB, 0x43CFD006 */ + + /* poly coefs for (3/2)*(log(x)-2s-2/3*s**3 */ + L1 = 5.99999999999994648725e-01, /* 0x3FE33333, 0x33333303 */ + L2 = 4.28571428578550184252e-01, /* 0x3FDB6DB6, 0xDB6FABFF */ + L3 = 3.33333329818377432918e-01, /* 0x3FD55555, 0x518F264D */ + L4 = 2.72728123808534006489e-01, /* 0x3FD17460, 0xA91D4101 */ + L5 = 2.30660745775561754067e-01, /* 0x3FCD864A, 0x93C9DB65 */ + L6 = 2.06975017800338417784e-01, /* 0x3FCA7E28, 0x4A454EEF */ + P1 = 1.66666666666666019037e-01, /* 0x3FC55555, 0x5555553E */ + P2 = -2.77777777770155933842e-03, /* 0xBF66C16C, 0x16BEBD93 */ + P3 = 6.61375632143793436117e-05, /* 0x3F11566A, 0xAF25DE2C */ + P4 = -1.65339022054652515390e-06, /* 0xBEBBBD41, 0xC5D26BF1 */ + P5 = 4.13813679705723846039e-08, /* 0x3E663769, 0x72BEA4D0 */ + lg2 = 6.93147180559945286227e-01, /* 0x3FE62E42, 0xFEFA39EF */ + lg2_h = 6.93147182464599609375e-01, /* 0x3FE62E43, 0x00000000 */ + lg2_l = -1.90465429995776804525e-09, /* 0xBE205C61, 0x0CA86C39 */ + ovt = 8.0085662595372944372e-0017, /* -(1024-log2(ovfl+.5ulp)) */ + cp = 9.61796693925975554329e-01, /* 0x3FEEC709, 0xDC3A03FD =2/(3ln2) */ + cp_h = 9.61796700954437255859e-01, /* 0x3FEEC709, 0xE0000000 =(float)cp */ + cp_l = -7.02846165095275826516e-09, /* 0xBE3E2FE0, 0x145B01F5 =tail of cp_h */ + ivln2 = 1.44269504088896338700e+00, /* 0x3FF71547, 0x652B82FE =1/ln2 */ + ivln2_h = 1.44269502162933349609e+00, /* 0x3FF71547, 0x60000000 =24b 1/ln2 */ + ivln2_l = 1.92596299112661746887e-08; /* 0x3E54AE0B, 0xF85DDF44 =1/ln2 tail */ #ifdef __STDC__ - double __ieee754_pow(double x, double y) +double +__ieee754_pow(double x, double y) #else - double __ieee754_pow(x,y) - double x, y; +double +__ieee754_pow(x, y) + double x, y; #endif { - double z,ax,z_h,z_l,p_h,p_l; - double y1,t1,t2,r,s,t,u,v,w; - int32_t i,j,k,yisint,n; - int32_t hx,hy,ix,iy; - u_int32_t lx,ly; + double z, ax, z_h, z_l, p_h, p_l; + double y1, t1, t2, r, s, t, u, v, w; + int32_t i, j, k, yisint, n; + int32_t hx, hy, ix, iy; + u_int32_t lx, ly; - EXTRACT_WORDS(hx,lx,x); - EXTRACT_WORDS(hy,ly,y); - ix = hx&0x7fffffff; iy = hy&0x7fffffff; + EXTRACT_WORDS(hx, lx, x); + EXTRACT_WORDS(hy, ly, y); + ix = hx & 0x7fffffff; + iy = hy & 0x7fffffff; /* y==zero: x**0 = 1 */ - if((iy|ly)==0) return one; + if ((iy | ly) == 0) + return one; /* +-NaN return x+y */ - if(ix > 0x7ff00000 || ((ix==0x7ff00000)&&(lx!=0)) || - iy > 0x7ff00000 || ((iy==0x7ff00000)&&(ly!=0))) - return x+y; + if (ix > 0x7ff00000 || ((ix == 0x7ff00000) && (lx != 0)) || + iy > 0x7ff00000 || ((iy == 0x7ff00000) && (ly != 0))) + return x + y; /* determine if y is an odd int when x < 0 - * yisint = 0 ... y is not an integer - * yisint = 1 ... y is an odd int - * yisint = 2 ... y is an even int + * yisint = 0 ... y is not an integer + * yisint = 1 ... y is an odd int + * yisint = 2 ... y is an even int */ - yisint = 0; - if(hx<0) { - if(iy>=0x43400000) yisint = 2; /* even integer y */ - else if(iy>=0x3ff00000) { - k = (iy>>20)-0x3ff; /* exponent */ - if(k>20) { - j = ly>>(52-k); - if((u_int32_t)(j<<(52-k))==ly) yisint = 2-(j&1); - } else if(ly==0) { - j = iy>>(20-k); - if((j<<(20-k))==iy) yisint = 2-(j&1); - } - } - } + yisint = 0; + if (hx < 0) { + if (iy >= 0x43400000) + yisint = 2; /* even integer y */ + else if (iy >= 0x3ff00000) { + k = (iy >> 20) - 0x3ff; /* exponent */ + if (k > 20) { + j = ly >> (52 - k); + if ((u_int32_t) (j << (52 - k)) == ly) + yisint = 2 - (j & 1); + } else if (ly == 0) { + j = iy >> (20 - k); + if ((j << (20 - k)) == iy) + yisint = 2 - (j & 1); + } + } + } /* special value of y */ - if(ly==0) { - if (iy==0x7ff00000) { /* y is +-inf */ - if(((ix-0x3ff00000)|lx)==0) - return y - y; /* inf**+-1 is NaN */ - else if (ix >= 0x3ff00000)/* (|x|>1)**+-inf = inf,0 */ - return (hy>=0)? y: zero; - else /* (|x|<1)**-,+inf = inf,0 */ - return (hy<0)?-y: zero; - } - if(iy==0x3ff00000) { /* y is +-1 */ - if(hy<0) return one/x; else return x; - } - if(hy==0x40000000) return x*x; /* y is 2 */ - if(hy==0x3fe00000) { /* y is 0.5 */ - if(hx>=0) /* x >= +0 */ - return __ieee754_sqrt(x); - } - } + if (ly == 0) { + if (iy == 0x7ff00000) { /* y is +-inf */ + if (((ix - 0x3ff00000) | lx) == 0) + return y - y; /* inf**+-1 is NaN */ + else if (ix >= 0x3ff00000) /* (|x|>1)**+-inf = inf,0 */ + return (hy >= 0) ? y : zero; + else /* (|x|<1)**-,+inf = inf,0 */ + return (hy < 0) ? -y : zero; + } + if (iy == 0x3ff00000) { /* y is +-1 */ + if (hy < 0) + return one / x; + else + return x; + } + if (hy == 0x40000000) + return x * x; /* y is 2 */ + if (hy == 0x3fe00000) { /* y is 0.5 */ + if (hx >= 0) /* x >= +0 */ + return __ieee754_sqrt(x); + } + } - ax = x < 0 ? -x : x; /*fabs(x);*/ + ax = x < 0 ? -x : x; /*fabs(x); */ /* special value of x */ - if(lx==0) { - if(ix==0x7ff00000||ix==0||ix==0x3ff00000){ - z = ax; /*x is +-0,+-inf,+-1*/ - if(hy<0) z = one/z; /* z = (1/|x|) */ - if(hx<0) { - if(((ix-0x3ff00000)|yisint)==0) { - z = (z-z)/(z-z); /* (-1)**non-int is NaN */ - } else if(yisint==1) - z = -z; /* (x<0)**odd = -(|x|**odd) */ - } - return z; - } - } + if (lx == 0) { + if (ix == 0x7ff00000 || ix == 0 || ix == 0x3ff00000) { + z = ax; /*x is +-0,+-inf,+-1 */ + if (hy < 0) + z = one / z; /* z = (1/|x|) */ + if (hx < 0) { + if (((ix - 0x3ff00000) | yisint) == 0) { + z = (z - z) / (z - z); /* (-1)**non-int is NaN */ + } else if (yisint == 1) + z = -z; /* (x<0)**odd = -(|x|**odd) */ + } + return z; + } + } /* (x<0)**(non-int) is NaN */ - if(((((u_int32_t)hx>>31)-1)|yisint)==0) return (x-x)/(x-x); + if (((((u_int32_t) hx >> 31) - 1) | yisint) == 0) + return (x - x) / (x - x); /* |y| is huge */ - if(iy>0x41e00000) { /* if |y| > 2**31 */ - if(iy>0x43f00000){ /* if |y| > 2**64, must o/uflow */ - if(ix<=0x3fefffff) return (hy<0)? huge*huge:tiny*tiny; - if(ix>=0x3ff00000) return (hy>0)? huge*huge:tiny*tiny; - } - /* over/underflow if x is not close to one */ - if(ix<0x3fefffff) return (hy<0)? huge*huge:tiny*tiny; - if(ix>0x3ff00000) return (hy>0)? huge*huge:tiny*tiny; - /* now |1-x| is tiny <= 2**-20, suffice to compute - log(x) by x-x^2/2+x^3/3-x^4/4 */ - t = x-1; /* t has 20 trailing zeros */ - w = (t*t)*(0.5-t*(0.3333333333333333333333-t*0.25)); - u = ivln2_h*t; /* ivln2_h has 21 sig. bits */ - v = t*ivln2_l-w*ivln2; - t1 = u+v; - SET_LOW_WORD(t1,0); - t2 = v-(t1-u); - } else { - double s2,s_h,s_l,t_h,t_l; - n = 0; - /* take care subnormal number */ - if(ix<0x00100000) - {ax *= two53; n -= 53; GET_HIGH_WORD(ix,ax); } - n += ((ix)>>20)-0x3ff; - j = ix&0x000fffff; - /* determine interval */ - ix = j|0x3ff00000; /* normalize ix */ - if(j<=0x3988E) k=0; /* |x| 0x41e00000) { /* if |y| > 2**31 */ + if (iy > 0x43f00000) { /* if |y| > 2**64, must o/uflow */ + if (ix <= 0x3fefffff) + return (hy < 0) ? huge * huge : tiny * tiny; + if (ix >= 0x3ff00000) + return (hy > 0) ? huge * huge : tiny * tiny; + } + /* over/underflow if x is not close to one */ + if (ix < 0x3fefffff) + return (hy < 0) ? huge * huge : tiny * tiny; + if (ix > 0x3ff00000) + return (hy > 0) ? huge * huge : tiny * tiny; + /* now |1-x| is tiny <= 2**-20, suffice to compute + log(x) by x-x^2/2+x^3/3-x^4/4 */ + t = x - 1; /* t has 20 trailing zeros */ + w = (t * t) * (0.5 - t * (0.3333333333333333333333 - t * 0.25)); + u = ivln2_h * t; /* ivln2_h has 21 sig. bits */ + v = t * ivln2_l - w * ivln2; + t1 = u + v; + SET_LOW_WORD(t1, 0); + t2 = v - (t1 - u); + } else { + double s2, s_h, s_l, t_h, t_l; + n = 0; + /* take care subnormal number */ + if (ix < 0x00100000) { + ax *= two53; + n -= 53; + GET_HIGH_WORD(ix, ax); + } + n += ((ix) >> 20) - 0x3ff; + j = ix & 0x000fffff; + /* determine interval */ + ix = j | 0x3ff00000; /* normalize ix */ + if (j <= 0x3988E) + k = 0; /* |x|>1)|0x20000000)+0x00080000+(k<<18)); - t_l = ax - (t_h-bp[k]); - s_l = v*((u-s_h*t_h)-s_h*t_l); - /* compute log(ax) */ - s2 = s*s; - r = s2*s2*(L1+s2*(L2+s2*(L3+s2*(L4+s2*(L5+s2*L6))))); - r += s_l*(s_h+s); - s2 = s_h*s_h; - t_h = 3.0+s2+r; - SET_LOW_WORD(t_h,0); - t_l = r-((t_h-3.0)-s2); - /* u+v = s*(1+...) */ - u = s_h*t_h; - v = s_l*t_h+t_l*s; - /* 2/(3log2)*(s+...) */ - p_h = u+v; - SET_LOW_WORD(p_h,0); - p_l = v-(p_h-u); - z_h = cp_h*p_h; /* cp_h+cp_l = 2/(3*log2) */ - z_l = cp_l*p_h+p_l*cp+dp_l[k]; - /* log2(ax) = (s+..)*2/(3*log2) = n + dp_h + z_h + z_l */ - t = (double)n; - t1 = (((z_h+z_l)+dp_h[k])+t); - SET_LOW_WORD(t1,0); - t2 = z_l-(((t1-t)-dp_h[k])-z_h); - } + /* compute s = s_h+s_l = (x-1)/(x+1) or (x-1.5)/(x+1.5) */ + u = ax - bp[k]; /* bp[0]=1.0, bp[1]=1.5 */ + v = one / (ax + bp[k]); + s = u * v; + s_h = s; + SET_LOW_WORD(s_h, 0); + /* t_h=ax+bp[k] High */ + t_h = zero; + SET_HIGH_WORD(t_h, ((ix >> 1) | 0x20000000) + 0x00080000 + (k << 18)); + t_l = ax - (t_h - bp[k]); + s_l = v * ((u - s_h * t_h) - s_h * t_l); + /* compute log(ax) */ + s2 = s * s; + r = s2 * s2 * (L1 + + s2 * (L2 + + s2 * (L3 + s2 * (L4 + s2 * (L5 + s2 * L6))))); + r += s_l * (s_h + s); + s2 = s_h * s_h; + t_h = 3.0 + s2 + r; + SET_LOW_WORD(t_h, 0); + t_l = r - ((t_h - 3.0) - s2); + /* u+v = s*(1+...) */ + u = s_h * t_h; + v = s_l * t_h + t_l * s; + /* 2/(3log2)*(s+...) */ + p_h = u + v; + SET_LOW_WORD(p_h, 0); + p_l = v - (p_h - u); + z_h = cp_h * p_h; /* cp_h+cp_l = 2/(3*log2) */ + z_l = cp_l * p_h + p_l * cp + dp_l[k]; + /* log2(ax) = (s+..)*2/(3*log2) = n + dp_h + z_h + z_l */ + t = (double) n; + t1 = (((z_h + z_l) + dp_h[k]) + t); + SET_LOW_WORD(t1, 0); + t2 = z_l - (((t1 - t) - dp_h[k]) - z_h); + } - s = one; /* s (sign of result -ve**odd) = -1 else = 1 */ - if(((((u_int32_t)hx>>31)-1)|(yisint-1))==0) - s = -one;/* (-ve)**(odd int) */ + s = one; /* s (sign of result -ve**odd) = -1 else = 1 */ + if (((((u_int32_t) hx >> 31) - 1) | (yisint - 1)) == 0) + s = -one; /* (-ve)**(odd int) */ /* split up y into y1+y2 and compute (y1+y2)*(t1+t2) */ - y1 = y; - SET_LOW_WORD(y1,0); - p_l = (y-y1)*t1+y*t2; - p_h = y1*t1; - z = p_l+p_h; - EXTRACT_WORDS(j,i,z); - if (j>=0x40900000) { /* z >= 1024 */ - if(((j-0x40900000)|i)!=0) /* if z > 1024 */ - return s*huge*huge; /* overflow */ - else { - if(p_l+ovt>z-p_h) return s*huge*huge; /* overflow */ - } - } else if((j&0x7fffffff)>=0x4090cc00 ) { /* z <= -1075 */ - if(((j-0xc090cc00)|i)!=0) /* z < -1075 */ - return s*tiny*tiny; /* underflow */ - else { - if(p_l<=z-p_h) return s*tiny*tiny; /* underflow */ - } - } + y1 = y; + SET_LOW_WORD(y1, 0); + p_l = (y - y1) * t1 + y * t2; + p_h = y1 * t1; + z = p_l + p_h; + EXTRACT_WORDS(j, i, z); + if (j >= 0x40900000) { /* z >= 1024 */ + if (((j - 0x40900000) | i) != 0) /* if z > 1024 */ + return s * huge * huge; /* overflow */ + else { + if (p_l + ovt > z - p_h) + return s * huge * huge; /* overflow */ + } + } else if ((j & 0x7fffffff) >= 0x4090cc00) { /* z <= -1075 */ + if (((j - 0xc090cc00) | i) != 0) /* z < -1075 */ + return s * tiny * tiny; /* underflow */ + else { + if (p_l <= z - p_h) + return s * tiny * tiny; /* underflow */ + } + } /* * compute 2**(p_h+p_l) */ - i = j&0x7fffffff; - k = (i>>20)-0x3ff; - n = 0; - if(i>0x3fe00000) { /* if |z| > 0.5, set n = [z+0.5] */ - n = j+(0x00100000>>(k+1)); - k = ((n&0x7fffffff)>>20)-0x3ff; /* new k for n */ - t = zero; - SET_HIGH_WORD(t,n&~(0x000fffff>>k)); - n = ((n&0x000fffff)|0x00100000)>>(20-k); - if(j<0) n = -n; - p_h -= t; - } - t = p_l+p_h; - SET_LOW_WORD(t,0); - u = t*lg2_h; - v = (p_l-(t-p_h))*lg2+t*lg2_l; - z = u+v; - w = v-(z-u); - t = z*z; - t1 = z - t*(P1+t*(P2+t*(P3+t*(P4+t*P5)))); - r = (z*t1)/(t1-two)-(w+z*w); - z = one-(r-z); - GET_HIGH_WORD(j,z); - j += (n<<20); - if((j>>20)<=0) z = SDL_NAME(scalbn)(z,n); /* subnormal output */ - else SET_HIGH_WORD(z,j); - return s*z; + i = j & 0x7fffffff; + k = (i >> 20) - 0x3ff; + n = 0; + if (i > 0x3fe00000) { /* if |z| > 0.5, set n = [z+0.5] */ + n = j + (0x00100000 >> (k + 1)); + k = ((n & 0x7fffffff) >> 20) - 0x3ff; /* new k for n */ + t = zero; + SET_HIGH_WORD(t, n & ~(0x000fffff >> k)); + n = ((n & 0x000fffff) | 0x00100000) >> (20 - k); + if (j < 0) + n = -n; + p_h -= t; + } + t = p_l + p_h; + SET_LOW_WORD(t, 0); + u = t * lg2_h; + v = (p_l - (t - p_h)) * lg2 + t * lg2_l; + z = u + v; + w = v - (z - u); + t = z * z; + t1 = z - t * (P1 + t * (P2 + t * (P3 + t * (P4 + t * P5)))); + r = (z * t1) / (t1 - two) - (w + z * w); + z = one - (r - z); + GET_HIGH_WORD(j, z); + j += (n << 20); + if ((j >> 20) <= 0) + z = SDL_NAME(scalbn) (z, n); /* subnormal output */ + else + SET_HIGH_WORD(z, j); + return s * z; } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/e_sqrt.h b/src/video/e_sqrt.h index 657380ea4..2fadaf7f3 100644 --- a/src/video/e_sqrt.h +++ b/src/video/e_sqrt.h @@ -88,150 +88,173 @@ static char rcsid[] = "$NetBSD: e_sqrt.c,v 1.8 1995/05/10 20:46:17 jtc Exp $"; #include "math_private.h" #ifdef __STDC__ - double SDL_NAME(copysign)(double x, double y) +double SDL_NAME(copysign) (double x, double y) #else - double SDL_NAME(copysign)(x,y) - double x,y; +double SDL_NAME(copysign) (x, y) + double + x, + y; #endif { - u_int32_t hx,hy; - GET_HIGH_WORD(hx,x); - GET_HIGH_WORD(hy,y); - SET_HIGH_WORD(x,(hx&0x7fffffff)|(hy&0x80000000)); - return x; + u_int32_t hx, hy; + GET_HIGH_WORD(hx, x); + GET_HIGH_WORD(hy, y); + SET_HIGH_WORD(x, (hx & 0x7fffffff) | (hy & 0x80000000)); + return x; } #ifdef __STDC__ - double SDL_NAME(scalbn) (double x, int n) +double SDL_NAME(scalbn) (double x, int n) #else - double SDL_NAME(scalbn) (x,n) - double x; int n; +double SDL_NAME(scalbn) (x, n) + double + x; + int + n; #endif { - int32_t k,hx,lx; - EXTRACT_WORDS(hx,lx,x); - k = (hx&0x7ff00000)>>20; /* extract exponent */ - if (k==0) { /* 0 or subnormal x */ - if ((lx|(hx&0x7fffffff))==0) return x; /* +-0 */ - x *= two54; - GET_HIGH_WORD(hx,x); - k = ((hx&0x7ff00000)>>20) - 54; - if (n< -50000) return tiny*x; /*underflow*/ - } - if (k==0x7ff) return x+x; /* NaN or Inf */ - k = k+n; - if (k > 0x7fe) return huge*SDL_NAME(copysign)(huge,x); /* overflow */ - if (k > 0) /* normal result */ - {SET_HIGH_WORD(x,(hx&0x800fffff)|(k<<20)); return x;} - if (k <= -54) { - if (n > 50000) /* in case integer overflow in n+k */ - return huge*SDL_NAME(copysign)(huge,x); /*overflow*/ - else return tiny*SDL_NAME(copysign)(tiny,x); /*underflow*/ - } - k += 54; /* subnormal result */ - SET_HIGH_WORD(x,(hx&0x800fffff)|(k<<20)); - return x*twom54; + int32_t k, hx, lx; + EXTRACT_WORDS(hx, lx, x); + k = (hx & 0x7ff00000) >> 20; /* extract exponent */ + if (k == 0) { /* 0 or subnormal x */ + if ((lx | (hx & 0x7fffffff)) == 0) + return x; /* +-0 */ + x *= two54; + GET_HIGH_WORD(hx, x); + k = ((hx & 0x7ff00000) >> 20) - 54; + if (n < -50000) + return tiny * x; /*underflow */ + } + if (k == 0x7ff) + return x + x; /* NaN or Inf */ + k = k + n; + if (k > 0x7fe) + return huge * SDL_NAME(copysign) (huge, x); /* overflow */ + if (k > 0) { /* normal result */ + SET_HIGH_WORD(x, (hx & 0x800fffff) | (k << 20)); + return x; + } + if (k <= -54) { + if (n > 50000) /* in case integer overflow in n+k */ + return huge * SDL_NAME(copysign) (huge, x); /*overflow */ + else + return tiny * SDL_NAME(copysign) (tiny, x); /*underflow */ + } + k += 54; /* subnormal result */ + SET_HIGH_WORD(x, (hx & 0x800fffff) | (k << 20)); + return x * twom54; } #ifdef __STDC__ - double __ieee754_sqrt(double x) +double +__ieee754_sqrt(double x) #else - double __ieee754_sqrt(x) - double x; +double +__ieee754_sqrt(x) + double x; #endif { - double z; - int32_t sign = (int)0x80000000; - int32_t ix0,s0,q,m,t,i; - u_int32_t r,t1,s1,ix1,q1; + double z; + int32_t sign = (int) 0x80000000; + int32_t ix0, s0, q, m, t, i; + u_int32_t r, t1, s1, ix1, q1; - EXTRACT_WORDS(ix0,ix1,x); + EXTRACT_WORDS(ix0, ix1, x); /* take care of Inf and NaN */ - if((ix0&0x7ff00000)==0x7ff00000) { - return x*x+x; /* sqrt(NaN)=NaN, sqrt(+inf)=+inf - sqrt(-inf)=sNaN */ - } + if ((ix0 & 0x7ff00000) == 0x7ff00000) { + return x * x + x; /* sqrt(NaN)=NaN, sqrt(+inf)=+inf + sqrt(-inf)=sNaN */ + } /* take care of zero */ - if(ix0<=0) { - if(((ix0&(~sign))|ix1)==0) return x;/* sqrt(+-0) = +-0 */ - else if(ix0<0) - return (x-x)/(x-x); /* sqrt(-ve) = sNaN */ - } + if (ix0 <= 0) { + if (((ix0 & (~sign)) | ix1) == 0) + return x; /* sqrt(+-0) = +-0 */ + else if (ix0 < 0) + return (x - x) / (x - x); /* sqrt(-ve) = sNaN */ + } /* normalize x */ - m = (ix0>>20); - if(m==0) { /* subnormal x */ - while(ix0==0) { - m -= 21; - ix0 |= (ix1>>11); ix1 <<= 21; - } - for(i=0;(ix0&0x00100000)==0;i++) ix0<<=1; - m -= i-1; - ix0 |= (ix1>>(32-i)); - ix1 <<= i; - } - m -= 1023; /* unbias exponent */ - ix0 = (ix0&0x000fffff)|0x00100000; - if(m&1){ /* odd m, double x to make it even */ - ix0 += ix0 + ((ix1&sign)>>31); - ix1 += ix1; - } - m >>= 1; /* m = [m/2] */ + m = (ix0 >> 20); + if (m == 0) { /* subnormal x */ + while (ix0 == 0) { + m -= 21; + ix0 |= (ix1 >> 11); + ix1 <<= 21; + } + for (i = 0; (ix0 & 0x00100000) == 0; i++) + ix0 <<= 1; + m -= i - 1; + ix0 |= (ix1 >> (32 - i)); + ix1 <<= i; + } + m -= 1023; /* unbias exponent */ + ix0 = (ix0 & 0x000fffff) | 0x00100000; + if (m & 1) { /* odd m, double x to make it even */ + ix0 += ix0 + ((ix1 & sign) >> 31); + ix1 += ix1; + } + m >>= 1; /* m = [m/2] */ /* generate sqrt(x) bit by bit */ - ix0 += ix0 + ((ix1&sign)>>31); - ix1 += ix1; - q = q1 = s0 = s1 = 0; /* [q,q1] = sqrt(x) */ - r = 0x00200000; /* r = moving bit from right to left */ - - while(r!=0) { - t = s0+r; - if(t<=ix0) { - s0 = t+r; - ix0 -= t; - q += r; - } - ix0 += ix0 + ((ix1&sign)>>31); - ix1 += ix1; - r>>=1; - } - - r = sign; - while(r!=0) { - t1 = s1+r; - t = s0; - if((t>31); - ix1 += ix1; - r>>=1; - } + ix0 += ix0 + ((ix1 & sign) >> 31); + ix1 += ix1; + q = q1 = s0 = s1 = 0; /* [q,q1] = sqrt(x) */ + r = 0x00200000; /* r = moving bit from right to left */ + + while (r != 0) { + t = s0 + r; + if (t <= ix0) { + s0 = t + r; + ix0 -= t; + q += r; + } + ix0 += ix0 + ((ix1 & sign) >> 31); + ix1 += ix1; + r >>= 1; + } + + r = sign; + while (r != 0) { + t1 = s1 + r; + t = s0; + if ((t < ix0) || ((t == ix0) && (t1 <= ix1))) { + s1 = t1 + r; + if (((int32_t) (t1 & sign) == sign) && (s1 & sign) == 0) + s0 += 1; + ix0 -= t; + if (ix1 < t1) + ix0 -= 1; + ix1 -= t1; + q1 += r; + } + ix0 += ix0 + ((ix1 & sign) >> 31); + ix1 += ix1; + r >>= 1; + } /* use floating add to find out rounding direction */ - if((ix0|ix1)!=0) { - z = one-tiny; /* trigger inexact flag */ - if (z>=one) { - z = one+tiny; - if (q1==(u_int32_t)0xffffffff) { q1=0; q += 1;} - else if (z>one) { - if (q1==(u_int32_t)0xfffffffe) q+=1; - q1+=2; - } else - q1 += (q1&1); - } - } - ix0 = (q>>1)+0x3fe00000; - ix1 = q1>>1; - if ((q&1)==1) ix1 |= sign; - ix0 += (m <<20); - INSERT_WORDS(z,ix0,ix1); - return z; + if ((ix0 | ix1) != 0) { + z = one - tiny; /* trigger inexact flag */ + if (z >= one) { + z = one + tiny; + if (q1 == (u_int32_t) 0xffffffff) { + q1 = 0; + q += 1; + } else if (z > one) { + if (q1 == (u_int32_t) 0xfffffffe) + q += 1; + q1 += 2; + } else + q1 += (q1 & 1); + } + } + ix0 = (q >> 1) + 0x3fe00000; + ix1 = q1 >> 1; + if ((q & 1) == 1) + ix1 |= sign; + ix0 += (m << 20); + INSERT_WORDS(z, ix0, ix1); + return z; } /* @@ -490,4 +513,4 @@ B. sqrt(x) by Reciproot Iteration (4) Special cases (see (4) of Section A). */ - +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/epoc/SDL_epocevents_c.h b/src/video/epoc/SDL_epocevents_c.h index 8455c153b..9c5db0262 100644 --- a/src/video/epoc/SDL_epocevents_c.h +++ b/src/video/epoc/SDL_epocevents_c.h @@ -29,7 +29,8 @@ */ -extern "C" { +extern "C" +{ #include "../SDL_sysvideo.h" }; @@ -39,8 +40,9 @@ extern "C" { of the native video subsystem (SDL_sysvideo.c) */ -extern "C" { -extern void EPOC_InitOSKeymap(_THIS); -extern void EPOC_PumpEvents(_THIS); +extern "C" +{ + extern void EPOC_InitOSKeymap(_THIS); + extern void EPOC_PumpEvents(_THIS); }; - +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/epoc/SDL_epocvideo.h b/src/video/epoc/SDL_epocvideo.h index efff50a98..365f3e30b 100644 --- a/src/video/epoc/SDL_epocvideo.h +++ b/src/video/epoc/SDL_epocvideo.h @@ -31,13 +31,14 @@ #ifndef _SDL_epocvideo_h #define _SDL_epocvideo_h -extern "C" { +extern "C" +{ #include "SDL_mouse.h" #include "../SDL_sysvideo.h" }; #include -#include +#include #include /* Hidden "this" pointer for the video functions */ @@ -47,44 +48,47 @@ extern "C" { #define SDL_NUMMODES 4 /* Private display data */ -struct SDL_PrivateVideoData { - - SDL_Rect *SDL_modelist[SDL_NUMMODES+1]; - - /* Epoc window server info */ - - RWsSession EPOC_WsSession; - RWindowGroup EPOC_WsWindowGroup; - TInt EPOC_WsWindowGroupID; - RWindow EPOC_WsWindow; - CWsScreenDevice* EPOC_WsScreen; - CWindowGc* EPOC_WindowGc; - TRequestStatus EPOC_WsEventStatus; - TRequestStatus EPOC_RedrawEventStatus; - TWsEvent EPOC_WsEvent; - TWsRedrawEvent EPOC_RedrawEvent; - #ifdef __WINS__ - CWsBitmap* EPOC_Bitmap; - #endif - TBool EPOC_IsWindowFocused; //!!Not used for anything yet! +struct SDL_PrivateVideoData +{ + + SDL_Rect *SDL_modelist[SDL_NUMMODES + 1]; + + /* Epoc window server info */ + + RWsSession EPOC_WsSession; + RWindowGroup EPOC_WsWindowGroup; + TInt EPOC_WsWindowGroupID; + RWindow EPOC_WsWindow; + CWsScreenDevice *EPOC_WsScreen; + CWindowGc *EPOC_WindowGc; + TRequestStatus EPOC_WsEventStatus; + TRequestStatus EPOC_RedrawEventStatus; + TWsEvent EPOC_WsEvent; + TWsRedrawEvent EPOC_RedrawEvent; +#ifdef __WINS__ + CWsBitmap *EPOC_Bitmap; +#endif + TBool EPOC_IsWindowFocused; //!!Not used for anything yet! /* Screen hardware frame buffer info */ - TBool EPOC_HasFrameBuffer; - TInt EPOC_BytesPerPixel; - TInt EPOC_BytesPerScanLine; - TDisplayMode EPOC_DisplayMode; - TSize EPOC_ScreenSize; - TUint8* EPOC_FrameBuffer; /* if NULL in HW we can't do direct screen access */ - TInt EPOC_ScreenOffset; + TBool EPOC_HasFrameBuffer; + TInt EPOC_BytesPerPixel; + TInt EPOC_BytesPerScanLine; + TDisplayMode EPOC_DisplayMode; + TSize EPOC_ScreenSize; + TUint8 *EPOC_FrameBuffer; /* if NULL in HW we can't do direct screen access */ + TInt EPOC_ScreenOffset; /* Simulate double screen height */ - TBool EPOC_ShrinkedHeight; + TBool EPOC_ShrinkedHeight; }; -extern "C" { -extern void RedrawWindowL(_THIS); +extern "C" +{ + extern void RedrawWindowL(_THIS); }; #endif /* _SDL_epocvideo_h */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/fbcon/3dfx_mmio.h b/src/video/fbcon/3dfx_mmio.h index 5a4acb96b..d6028b896 100644 --- a/src/video/fbcon/3dfx_mmio.h +++ b/src/video/fbcon/3dfx_mmio.h @@ -53,4 +53,4 @@ i = (tdfx_in32(TDFX_STATUS) & STATUS_BUSY) ? 0 : i + 1; \ } while ( i != 3 ); \ } - +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/fbcon/3dfx_regs.h b/src/video/fbcon/3dfx_regs.h index 1180c8244..58cc4dfd8 100644 --- a/src/video/fbcon/3dfx_regs.h +++ b/src/video/fbcon/3dfx_regs.h @@ -80,4 +80,4 @@ #define STATUS_BUSY BIT(9) #endif /* _3DFX_REGS_H */ - +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/fbcon/SDL_fb3dfx.c b/src/video/fbcon/SDL_fb3dfx.c index dca9f7339..a40cf2534 100644 --- a/src/video/fbcon/SDL_fb3dfx.c +++ b/src/video/fbcon/SDL_fb3dfx.c @@ -28,190 +28,197 @@ /* Wait for vertical retrace */ -static void WaitVBL(_THIS) +static void +WaitVBL(_THIS) { - /* find start of retrace */ - tdfx_waitidle(); - while( (tdfx_in32(TDFX_STATUS) & STATUS_RETRACE) == STATUS_RETRACE ) - ; - /* wait until we're past the start */ - while( (tdfx_in32(TDFX_STATUS) & STATUS_RETRACE) == 0 ) - ; + /* find start of retrace */ + tdfx_waitidle(); + while ((tdfx_in32(TDFX_STATUS) & STATUS_RETRACE) == STATUS_RETRACE); + /* wait until we're past the start */ + while ((tdfx_in32(TDFX_STATUS) & STATUS_RETRACE) == 0); } -static void WaitIdle(_THIS) +static void +WaitIdle(_THIS) { - tdfx_waitidle(); + tdfx_waitidle(); } /* Sets video mem colorkey and accelerated blit function */ -static int SetHWColorKey(_THIS, SDL_Surface *surface, Uint32 key) +static int +SetHWColorKey(_THIS, SDL_Surface * surface, Uint32 key) { - return(0); + return (0); } -static int FillHWRect(_THIS, SDL_Surface *dst, SDL_Rect *rect, Uint32 color) +static int +FillHWRect(_THIS, SDL_Surface * dst, SDL_Rect * rect, Uint32 color) { - int bpp; - char *dst_base; - Uint32 format; - int dstX, dstY; - - /* Don't blit to the display surface when switched away */ - if ( switched_away ) { - return -2; /* no hardware access */ - } - if ( dst == this->screen ) { - SDL_mutexP(hw_lock); - } - - /* Set the destination pixel format */ - dst_base = (char *)((char *)dst->pixels - mapped_mem); - bpp = dst->format->BitsPerPixel; - format = dst->pitch | ((bpp+((bpp==8) ? 0 : 8)) << 13); - - /* Calculate source and destination base coordinates */ - dstX = rect->x; - dstY = rect->y; - - /* Execute the fill command */ - tdfx_wait(6); - tdfx_out32(DSTBASE, (Uint32)dst_base); - tdfx_out32(DSTFORMAT, format); - tdfx_out32(COLORFORE, color); - tdfx_out32(COMMAND_2D, COMMAND_2D_FILLRECT); - tdfx_out32(DSTSIZE, rect->w | (rect->h << 16)); - tdfx_out32(LAUNCH_2D, dstX | (dstY << 16)); - - FB_AddBusySurface(dst); - - if ( dst == this->screen ) { - SDL_mutexV(hw_lock); - } - return(0); + int bpp; + char *dst_base; + Uint32 format; + int dstX, dstY; + + /* Don't blit to the display surface when switched away */ + if (switched_away) { + return -2; /* no hardware access */ + } + if (dst == this->screen) { + SDL_mutexP(hw_lock); + } + + /* Set the destination pixel format */ + dst_base = (char *) ((char *) dst->pixels - mapped_mem); + bpp = dst->format->BitsPerPixel; + format = dst->pitch | ((bpp + ((bpp == 8) ? 0 : 8)) << 13); + + /* Calculate source and destination base coordinates */ + dstX = rect->x; + dstY = rect->y; + + /* Execute the fill command */ + tdfx_wait(6); + tdfx_out32(DSTBASE, (Uint32) dst_base); + tdfx_out32(DSTFORMAT, format); + tdfx_out32(COLORFORE, color); + tdfx_out32(COMMAND_2D, COMMAND_2D_FILLRECT); + tdfx_out32(DSTSIZE, rect->w | (rect->h << 16)); + tdfx_out32(LAUNCH_2D, dstX | (dstY << 16)); + + FB_AddBusySurface(dst); + + if (dst == this->screen) { + SDL_mutexV(hw_lock); + } + return (0); } -static int HWAccelBlit(SDL_Surface *src, SDL_Rect *srcrect, - SDL_Surface *dst, SDL_Rect *dstrect) +static int +HWAccelBlit(SDL_Surface * src, SDL_Rect * srcrect, + SDL_Surface * dst, SDL_Rect * dstrect) { - SDL_VideoDevice *this = current_video; - int bpp; - Uint32 src_format; - Uint32 dst_format; - char *src_base; - char *dst_base; - int srcX, srcY; - int dstX, dstY; - Uint32 blitop; - Uint32 use_colorkey; - - /* Don't blit to the display surface when switched away */ - if ( switched_away ) { - return -2; /* no hardware access */ - } - if ( dst == this->screen ) { - SDL_mutexP(hw_lock); - } - - /* Set the source and destination pixel format */ - src_base = (char *)((char *)src->pixels - mapped_mem); - bpp = src->format->BitsPerPixel; - src_format = src->pitch | ((bpp+((bpp==8) ? 0 : 8)) << 13); - dst_base = (char *)((char *)dst->pixels - mapped_mem); - bpp = dst->format->BitsPerPixel; - dst_format = dst->pitch | ((bpp+((bpp==8) ? 0 : 8)) << 13); - - srcX = srcrect->x; - srcY = srcrect->y; - dstX = dstrect->x; - dstY = dstrect->y; - - /* Assemble the blit operation */ - blitop = COMMAND_2D_BITBLT | (0xCC << 24); - if ( srcX <= dstX ) { - blitop |= BIT(14); - srcX += (dstrect->w - 1); - dstX += (dstrect->w - 1); - } - if ( srcY <= dstY ) { - blitop |= BIT(15); - srcY += (dstrect->h - 1); - dstY += (dstrect->h - 1); - } - - /* Perform the blit! */ - if ( (src->flags & SDL_SRCCOLORKEY) == SDL_SRCCOLORKEY ) { - tdfx_wait(3); - tdfx_out32(SRCCOLORKEYMIN, src->format->colorkey); - tdfx_out32(SRCCOLORKEYMAX, src->format->colorkey); - tdfx_out32(ROP_2D, 0xAA00); - use_colorkey = 1; - } else { - use_colorkey = 0; - } - tdfx_wait(9); - tdfx_out32(SRCBASE, (Uint32)src_base); - tdfx_out32(SRCFORMAT, src_format); - tdfx_out32(DSTBASE, (Uint32)dst_base); - tdfx_out32(DSTFORMAT, src_format); - tdfx_out32(COMMAND_2D, blitop); - tdfx_out32(COMMANDEXTRA_2D, use_colorkey); - tdfx_out32(DSTSIZE, dstrect->w | (dstrect->h << 16)); - tdfx_out32(DSTXY, dstX | (dstY << 16)); - tdfx_out32(LAUNCH_2D, srcX | (srcY << 16)); - - FB_AddBusySurface(src); - FB_AddBusySurface(dst); - - if ( dst == this->screen ) { - SDL_mutexV(hw_lock); - } - return(0); + SDL_VideoDevice *this = current_video; + int bpp; + Uint32 src_format; + Uint32 dst_format; + char *src_base; + char *dst_base; + int srcX, srcY; + int dstX, dstY; + Uint32 blitop; + Uint32 use_colorkey; + + /* Don't blit to the display surface when switched away */ + if (switched_away) { + return -2; /* no hardware access */ + } + if (dst == this->screen) { + SDL_mutexP(hw_lock); + } + + /* Set the source and destination pixel format */ + src_base = (char *) ((char *) src->pixels - mapped_mem); + bpp = src->format->BitsPerPixel; + src_format = src->pitch | ((bpp + ((bpp == 8) ? 0 : 8)) << 13); + dst_base = (char *) ((char *) dst->pixels - mapped_mem); + bpp = dst->format->BitsPerPixel; + dst_format = dst->pitch | ((bpp + ((bpp == 8) ? 0 : 8)) << 13); + + srcX = srcrect->x; + srcY = srcrect->y; + dstX = dstrect->x; + dstY = dstrect->y; + + /* Assemble the blit operation */ + blitop = COMMAND_2D_BITBLT | (0xCC << 24); + if (srcX <= dstX) { + blitop |= BIT(14); + srcX += (dstrect->w - 1); + dstX += (dstrect->w - 1); + } + if (srcY <= dstY) { + blitop |= BIT(15); + srcY += (dstrect->h - 1); + dstY += (dstrect->h - 1); + } + + /* Perform the blit! */ + if ((src->flags & SDL_SRCCOLORKEY) == SDL_SRCCOLORKEY) { + tdfx_wait(3); + tdfx_out32(SRCCOLORKEYMIN, src->format->colorkey); + tdfx_out32(SRCCOLORKEYMAX, src->format->colorkey); + tdfx_out32(ROP_2D, 0xAA00); + use_colorkey = 1; + } else { + use_colorkey = 0; + } + tdfx_wait(9); + tdfx_out32(SRCBASE, (Uint32) src_base); + tdfx_out32(SRCFORMAT, src_format); + tdfx_out32(DSTBASE, (Uint32) dst_base); + tdfx_out32(DSTFORMAT, src_format); + tdfx_out32(COMMAND_2D, blitop); + tdfx_out32(COMMANDEXTRA_2D, use_colorkey); + tdfx_out32(DSTSIZE, dstrect->w | (dstrect->h << 16)); + tdfx_out32(DSTXY, dstX | (dstY << 16)); + tdfx_out32(LAUNCH_2D, srcX | (srcY << 16)); + + FB_AddBusySurface(src); + FB_AddBusySurface(dst); + + if (dst == this->screen) { + SDL_mutexV(hw_lock); + } + return (0); } -static int CheckHWBlit(_THIS, SDL_Surface *src, SDL_Surface *dst) +static int +CheckHWBlit(_THIS, SDL_Surface * src, SDL_Surface * dst) { - int accelerated; - - /* Set initial acceleration on */ - src->flags |= SDL_HWACCEL; - - /* Set the surface attributes */ - if ( (src->flags & SDL_SRCALPHA) == SDL_SRCALPHA ) { - if ( ! this->info.blit_hw_A ) { - src->flags &= ~SDL_HWACCEL; - } - } - if ( (src->flags & SDL_SRCCOLORKEY) == SDL_SRCCOLORKEY ) { - if ( ! this->info.blit_hw_CC ) { - src->flags &= ~SDL_HWACCEL; - } - } - - /* Check to see if final surface blit is accelerated */ - accelerated = !!(src->flags & SDL_HWACCEL); - if ( accelerated ) { - src->map->hw_blit = HWAccelBlit; - } - return(accelerated); + int accelerated; + + /* Set initial acceleration on */ + src->flags |= SDL_HWACCEL; + + /* Set the surface attributes */ + if ((src->flags & SDL_SRCALPHA) == SDL_SRCALPHA) { + if (!this->info.blit_hw_A) { + src->flags &= ~SDL_HWACCEL; + } + } + if ((src->flags & SDL_SRCCOLORKEY) == SDL_SRCCOLORKEY) { + if (!this->info.blit_hw_CC) { + src->flags &= ~SDL_HWACCEL; + } + } + + /* Check to see if final surface blit is accelerated */ + accelerated = !!(src->flags & SDL_HWACCEL); + if (accelerated) { + src->map->hw_blit = HWAccelBlit; + } + return (accelerated); } -void FB_3DfxAccel(_THIS, __u32 card) +void +FB_3DfxAccel(_THIS, __u32 card) { - /* We have hardware accelerated surface functions */ - this->CheckHWBlit = CheckHWBlit; - wait_vbl = WaitVBL; - wait_idle = WaitIdle; - - /* Reset the 3Dfx controller */ - tdfx_out32(BRESERROR0, 0); - tdfx_out32(BRESERROR1, 0); - - /* The 3Dfx has an accelerated color fill */ - this->info.blit_fill = 1; - this->FillHWRect = FillHWRect; - - /* The 3Dfx has accelerated normal and colorkey blits */ - this->info.blit_hw = 1; - this->info.blit_hw_CC = 1; - this->SetHWColorKey = SetHWColorKey; + /* We have hardware accelerated surface functions */ + this->CheckHWBlit = CheckHWBlit; + wait_vbl = WaitVBL; + wait_idle = WaitIdle; + + /* Reset the 3Dfx controller */ + tdfx_out32(BRESERROR0, 0); + tdfx_out32(BRESERROR1, 0); + + /* The 3Dfx has an accelerated color fill */ + this->info.blit_fill = 1; + this->FillHWRect = FillHWRect; + + /* The 3Dfx has accelerated normal and colorkey blits */ + this->info.blit_hw = 1; + this->info.blit_hw_CC = 1; + this->SetHWColorKey = SetHWColorKey; } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/fbcon/SDL_fb3dfx.h b/src/video/fbcon/SDL_fb3dfx.h index b8b4aace5..c86f19229 100644 --- a/src/video/fbcon/SDL_fb3dfx.h +++ b/src/video/fbcon/SDL_fb3dfx.h @@ -27,3 +27,4 @@ /* Set up the driver for 3Dfx acceleration */ extern void FB_3DfxAccel(_THIS, __u32 card); +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/fbcon/SDL_fbelo.c b/src/video/fbcon/SDL_fbelo.c index 1142923d2..d85aebdb6 100644 --- a/src/video/fbcon/SDL_fbelo.c +++ b/src/video/fbcon/SDL_fbelo.c @@ -45,16 +45,16 @@ static int ELO_MIN_Y = 500; static int ELO_MAX_Y = 3540; #define ELO_SNAP_SIZE 6 -#define ELO_TOUCH_BYTE 'T' +#define ELO_TOUCH_BYTE 'T' #define ELO_ID 'I' #define ELO_MODE 'M' #define ELO_PARAMETER 'P' #define ELO_REPORT 'B' -#define ELO_ACK 'A' +#define ELO_ACK 'A' #define ELO_INIT_CHECKSUM 0xAA -#define ELO_BTN_PRESS 0x01 +#define ELO_BTN_PRESS 0x01 #define ELO_STREAM 0x02 #define ELO_BTN_RELEASE 0x04 @@ -78,365 +78,386 @@ static int ELO_MAX_Y = 3540; /* eloParsePacket */ -int eloParsePacket(unsigned char* mousebuf, int* dx, int* dy, int* button_state) { - static int elo_button = 0; - static int last_x = 0; - static int last_y = 0; - int x,y; - - /* Check if we have a touch packet */ - if (mousebuf[1] != ELO_TOUCH_BYTE) { - return 0; - } - - x = ((mousebuf[4] << 8) | mousebuf[3]); - y = ((mousebuf[6] << 8) | mousebuf[5]); - - if((SDL_abs(x - last_x) > ELO_SNAP_SIZE) || (SDL_abs(y - last_y) > ELO_SNAP_SIZE)) { - *dx = ((mousebuf[4] << 8) | mousebuf[3]); - *dy = ((mousebuf[6] << 8) | mousebuf[5]); - } - else { - *dx = last_x; - *dy = last_y; - } - - last_x = *dx; - last_y = *dy; - - if ( (mousebuf[2] & 0x07) == ELO_BTN_PRESS ) { - elo_button = 1; - } - if ( (mousebuf[2] & 0x07) == ELO_BTN_RELEASE ) { - elo_button = 0; - } - - *button_state = elo_button; - return 1; +int +eloParsePacket(unsigned char *mousebuf, int *dx, int *dy, int *button_state) +{ + static int elo_button = 0; + static int last_x = 0; + static int last_y = 0; + int x, y; + + /* Check if we have a touch packet */ + if (mousebuf[1] != ELO_TOUCH_BYTE) { + return 0; + } + + x = ((mousebuf[4] << 8) | mousebuf[3]); + y = ((mousebuf[6] << 8) | mousebuf[5]); + + if ((SDL_abs(x - last_x) > ELO_SNAP_SIZE) + || (SDL_abs(y - last_y) > ELO_SNAP_SIZE)) { + *dx = ((mousebuf[4] << 8) | mousebuf[3]); + *dy = ((mousebuf[6] << 8) | mousebuf[5]); + } else { + *dx = last_x; + *dy = last_y; + } + + last_x = *dx; + last_y = *dy; + + if ((mousebuf[2] & 0x07) == ELO_BTN_PRESS) { + elo_button = 1; + } + if ((mousebuf[2] & 0x07) == ELO_BTN_RELEASE) { + elo_button = 0; + } + + *button_state = elo_button; + return 1; } /* Convert the raw coordinates from the ELO controller to a screen position. */ -void eloConvertXY(_THIS, int *dx, int *dy) { - int input_x = *dx; - int input_y = *dy; - int width = ELO_MAX_X - ELO_MIN_X; - int height = ELO_MAX_Y - ELO_MIN_Y; - - *dx = ((int)cache_vinfo.xres - ((int)cache_vinfo.xres * (input_x - ELO_MIN_X)) / width); - *dy = (cache_vinfo.yres * (input_y - ELO_MIN_Y)) / height; +void +eloConvertXY(_THIS, int *dx, int *dy) +{ + int input_x = *dx; + int input_y = *dy; + int width = ELO_MAX_X - ELO_MIN_X; + int height = ELO_MAX_Y - ELO_MIN_Y; + + *dx = + ((int) cache_vinfo.xres - + ((int) cache_vinfo.xres * (input_x - ELO_MIN_X)) / width); + *dy = (cache_vinfo.yres * (input_y - ELO_MIN_Y)) / height; } /* eloGetPacket */ -int eloGetPacket(unsigned char* buffer, int* buffer_p, int* checksum, int fd) { - int num_bytes; - int ok; - - if(fd == 0) { - num_bytes = ELO_PACKET_SIZE; - } - else { - num_bytes = read(fd, - (char *) (buffer + *buffer_p), - ELO_PACKET_SIZE - *buffer_p); - } - - if (num_bytes < 0) { +int +eloGetPacket(unsigned char *buffer, int *buffer_p, int *checksum, int fd) +{ + int num_bytes; + int ok; + + if (fd == 0) { + num_bytes = ELO_PACKET_SIZE; + } else { + num_bytes = read(fd, + (char *) (buffer + *buffer_p), + ELO_PACKET_SIZE - *buffer_p); + } + + if (num_bytes < 0) { #ifdef DEBUG_MOUSE - fprintf(stderr, "System error while reading from Elographics touchscreen.\n"); + fprintf(stderr, + "System error while reading from Elographics touchscreen.\n"); #endif - return 0; - } - - while (num_bytes) { - if ((*buffer_p == 0) && (buffer[0] != ELO_START_BYTE)) { - SDL_memcpy(&buffer[0], &buffer[1], num_bytes-1); - } - else { - if (*buffer_p < ELO_PACKET_SIZE-1) { - *checksum = *checksum + buffer[*buffer_p]; - *checksum = *checksum % 256; - } - (*buffer_p)++; - } - num_bytes--; - } - - if (*buffer_p == ELO_PACKET_SIZE) { - ok = (*checksum == buffer[ELO_PACKET_SIZE-1]); - *checksum = ELO_INIT_CHECKSUM; - *buffer_p = 0; - - if (!ok) { - return 0; - } - - return 1; - } - else { - return 0; - } + return 0; + } + + while (num_bytes) { + if ((*buffer_p == 0) && (buffer[0] != ELO_START_BYTE)) { + SDL_memcpy(&buffer[0], &buffer[1], num_bytes - 1); + } else { + if (*buffer_p < ELO_PACKET_SIZE - 1) { + *checksum = *checksum + buffer[*buffer_p]; + *checksum = *checksum % 256; + } + (*buffer_p)++; + } + num_bytes--; + } + + if (*buffer_p == ELO_PACKET_SIZE) { + ok = (*checksum == buffer[ELO_PACKET_SIZE - 1]); + *checksum = ELO_INIT_CHECKSUM; + *buffer_p = 0; + + if (!ok) { + return 0; + } + + return 1; + } else { + return 0; + } } /* eloSendPacket */ -int eloSendPacket(unsigned char* packet, int fd) +int +eloSendPacket(unsigned char *packet, int fd) { - int i, result; - int sum = ELO_INIT_CHECKSUM; + int i, result; + int sum = ELO_INIT_CHECKSUM; - packet[0] = ELO_START_BYTE; - for (i = 0; i < ELO_PACKET_SIZE-1; i++) { - sum += packet[i]; - sum &= 0xFF; - } - packet[ELO_PACKET_SIZE-1] = sum; + packet[0] = ELO_START_BYTE; + for (i = 0; i < ELO_PACKET_SIZE - 1; i++) { + sum += packet[i]; + sum &= 0xFF; + } + packet[ELO_PACKET_SIZE - 1] = sum; - result = write(fd, packet, ELO_PACKET_SIZE); + result = write(fd, packet, ELO_PACKET_SIZE); - if (result != ELO_PACKET_SIZE) { + if (result != ELO_PACKET_SIZE) { #ifdef DEBUG_MOUSE - printf("System error while sending to Elographics touchscreen.\n"); + printf("System error while sending to Elographics touchscreen.\n"); #endif - return 0; - } - else { - return 1; - } + return 0; + } else { + return 1; + } } /* eloWaitForInput */ -int eloWaitForInput(int fd, int timeout) +int +eloWaitForInput(int fd, int timeout) { - fd_set readfds; - struct timeval to; - int r; + fd_set readfds; + struct timeval to; + int r; - FD_ZERO(&readfds); - FD_SET(fd, &readfds); - to.tv_sec = 0; - to.tv_usec = timeout; + FD_ZERO(&readfds); + FD_SET(fd, &readfds); + to.tv_sec = 0; + to.tv_usec = timeout; - r = select(FD_SETSIZE, &readfds, NULL, NULL, &to); - return r; + r = select(FD_SETSIZE, &readfds, NULL, NULL, &to); + return r; } /* eloWaitReply */ -int eloWaitReply(unsigned char type, unsigned char *reply, int fd) { - int ok; - int i, result; - int reply_p = 0; - int sum = ELO_INIT_CHECKSUM; +int +eloWaitReply(unsigned char type, unsigned char *reply, int fd) +{ + int ok; + int i, result; + int reply_p = 0; + int sum = ELO_INIT_CHECKSUM; - i = ELO_MAX_TRIALS; - do { - ok = 0; + i = ELO_MAX_TRIALS; + do { + ok = 0; - result = eloWaitForInput(fd, ELO_MAX_WAIT); + result = eloWaitForInput(fd, ELO_MAX_WAIT); - if (result > 0) { - ok = eloGetPacket(reply, &reply_p, &sum, fd); + if (result > 0) { + ok = eloGetPacket(reply, &reply_p, &sum, fd); - if (ok && reply[1] != type && type != ELO_PARAMETER) { + if (ok && reply[1] != type && type != ELO_PARAMETER) { #ifdef DEBUG_MOUSE - fprintf(stderr, "Wrong reply received\n"); + fprintf(stderr, "Wrong reply received\n"); #endif - ok = 0; - } - } - else { + ok = 0; + } + } else { #ifdef DEBUG_MOUSE - fprintf(stderr, "No input!\n"); + fprintf(stderr, "No input!\n"); #endif - } + } - if (result == 0) { - i--; - } - } while(!ok && (i>0)); + if (result == 0) { + i--; + } + } + while (!ok && (i > 0)); - return ok; + return ok; } /* eloWaitAck */ -int eloWaitAck(int fd) { - unsigned char packet[ELO_PACKET_SIZE]; - int i, nb_errors; - - if (eloWaitReply(ELO_ACK, packet, fd)) { - for (i = 0, nb_errors = 0; i < 4; i++) { - if (packet[2 + i] != '0') { - nb_errors++; - } - } +int +eloWaitAck(int fd) +{ + unsigned char packet[ELO_PACKET_SIZE]; + int i, nb_errors; + + if (eloWaitReply(ELO_ACK, packet, fd)) { + for (i = 0, nb_errors = 0; i < 4; i++) { + if (packet[2 + i] != '0') { + nb_errors++; + } + } - if (nb_errors != 0) { + if (nb_errors != 0) { #ifdef DEBUG_MOUSE - fprintf(stderr, "Elographics acknowledge packet reports %d errors\n", nb_errors); + fprintf(stderr, + "Elographics acknowledge packet reports %d errors\n", + nb_errors); #endif - } - return 1; - } - else { - return 0; - } + } + return 1; + } else { + return 0; + } } /* eloSendQuery -- */ -int eloSendQuery(unsigned char *request, unsigned char* reply, int fd) { - int ok; - - if (eloSendPacket(request, fd)) { - ok = eloWaitReply(toupper(request[1]), reply, fd); - if (ok) { - ok = eloWaitAck(fd); - } - return ok; - } - else { - return 0; - } +int +eloSendQuery(unsigned char *request, unsigned char *reply, int fd) +{ + int ok; + + if (eloSendPacket(request, fd)) { + ok = eloWaitReply(toupper(request[1]), reply, fd); + if (ok) { + ok = eloWaitAck(fd); + } + return ok; + } else { + return 0; + } } /* eloSendControl */ -int eloSendControl(unsigned char* control, int fd) { - if (eloSendPacket(control, fd)) { - return eloWaitAck(fd); - } - else { - return 0; - } +int +eloSendControl(unsigned char *control, int fd) +{ + if (eloSendPacket(control, fd)) { + return eloWaitAck(fd); + } else { + return 0; + } } /* eloInitController */ -int eloInitController(int fd) { - unsigned char req[ELO_PACKET_SIZE]; - unsigned char reply[ELO_PACKET_SIZE]; - const char *buffer = NULL; - int result = 0; - - struct termios mouse_termios; - - /* try to read the calibration values */ - buffer = SDL_getenv("SDL_ELO_MIN_X"); - if(buffer) { - ELO_MIN_X = SDL_atoi(buffer); - } - buffer = SDL_getenv("SDL_ELO_MAX_X"); - if(buffer) { - ELO_MAX_X = SDL_atoi(buffer); - } - buffer = SDL_getenv("SDL_ELO_MIN_Y"); - if(buffer) { - ELO_MIN_Y = SDL_atoi(buffer); - } - buffer = SDL_getenv("SDL_ELO_MAX_Y"); - if(buffer) { - ELO_MAX_Y = SDL_atoi(buffer); - } - +int +eloInitController(int fd) +{ + unsigned char req[ELO_PACKET_SIZE]; + unsigned char reply[ELO_PACKET_SIZE]; + const char *buffer = NULL; + int result = 0; + + struct termios mouse_termios; + + /* try to read the calibration values */ + buffer = SDL_getenv("SDL_ELO_MIN_X"); + if (buffer) { + ELO_MIN_X = SDL_atoi(buffer); + } + buffer = SDL_getenv("SDL_ELO_MAX_X"); + if (buffer) { + ELO_MAX_X = SDL_atoi(buffer); + } + buffer = SDL_getenv("SDL_ELO_MIN_Y"); + if (buffer) { + ELO_MIN_Y = SDL_atoi(buffer); + } + buffer = SDL_getenv("SDL_ELO_MAX_Y"); + if (buffer) { + ELO_MAX_Y = SDL_atoi(buffer); + } #ifdef DEBUG_MOUSE - fprintf( stderr, "ELO calibration values:\nmin_x: %i\nmax_x: %i\nmin_y: %i\nmax_y: %i\n", - ELO_MIN_X, - ELO_MAX_X, - ELO_MIN_Y, - ELO_MAX_Y); + fprintf(stderr, + "ELO calibration values:\nmin_x: %i\nmax_x: %i\nmin_y: %i\nmax_y: %i\n", + ELO_MIN_X, ELO_MAX_X, ELO_MIN_Y, ELO_MAX_Y); #endif - /* set comm params */ - SDL_memset(&mouse_termios, 0, sizeof(mouse_termios)); - mouse_termios.c_cflag = B9600 | CS8 | CREAD | CLOCAL; - mouse_termios.c_cc[VMIN] = 1; - result = tcsetattr(fd, TCSANOW, &mouse_termios); + /* set comm params */ + SDL_memset(&mouse_termios, 0, sizeof(mouse_termios)); + mouse_termios.c_cflag = B9600 | CS8 | CREAD | CLOCAL; + mouse_termios.c_cc[VMIN] = 1; + result = tcsetattr(fd, TCSANOW, &mouse_termios); - if (result < 0) { + if (result < 0) { #ifdef DEBUG_MOUSE - fprintf( stderr, "Unable to configure Elographics touchscreen port\n"); + fprintf(stderr, "Unable to configure Elographics touchscreen port\n"); #endif - return 0; - } + return 0; + } - SDL_memset(req, 0, ELO_PACKET_SIZE); - req[1] = tolower(ELO_PARAMETER); - if (!eloSendQuery(req, reply, fd)) { + SDL_memset(req, 0, ELO_PACKET_SIZE); + req[1] = tolower(ELO_PARAMETER); + if (!eloSendQuery(req, reply, fd)) { #ifdef DEBUG_MOUSE - fprintf( stderr, "Not at the specified rate or model 2310, will continue\n"); + fprintf(stderr, + "Not at the specified rate or model 2310, will continue\n"); #endif - } + } - SDL_memset(req, 0, ELO_PACKET_SIZE); - req[1] = tolower(ELO_ID); - if (eloSendQuery(req, reply, fd)) { + SDL_memset(req, 0, ELO_PACKET_SIZE); + req[1] = tolower(ELO_ID); + if (eloSendQuery(req, reply, fd)) { #ifdef DEBUG_MOUSE - fprintf(stderr, "Ok, controller configured!\n"); + fprintf(stderr, "Ok, controller configured!\n"); #endif - } - else { + } else { #ifdef DEBUG_MOUSE - fprintf( stderr, "Unable to ask Elographics touchscreen identification\n"); + fprintf(stderr, + "Unable to ask Elographics touchscreen identification\n"); #endif - return 0; - } - - SDL_memset(req, 0, ELO_PACKET_SIZE); - req[1] = ELO_MODE; - req[3] = ELO_TOUCH_MODE | ELO_STREAM_MODE | ELO_UNTOUCH_MODE; - req[4] = ELO_TRACKING_MODE; - if (!eloSendControl(req, fd)) { + return 0; + } + + SDL_memset(req, 0, ELO_PACKET_SIZE); + req[1] = ELO_MODE; + req[3] = ELO_TOUCH_MODE | ELO_STREAM_MODE | ELO_UNTOUCH_MODE; + req[4] = ELO_TRACKING_MODE; + if (!eloSendControl(req, fd)) { #ifdef DEBUG_MOUSE - fprintf( stderr, "Unable to change Elographics touchscreen operating mode\n"); + fprintf(stderr, + "Unable to change Elographics touchscreen operating mode\n"); #endif - return 0; - } - - SDL_memset(req, 0, ELO_PACKET_SIZE); - req[1] = ELO_REPORT; - req[2] = ELO_UNTOUCH_DELAY; - req[3] = ELO_REPORT_DELAY; - if (!eloSendControl(req, fd)) { + return 0; + } + + SDL_memset(req, 0, ELO_PACKET_SIZE); + req[1] = ELO_REPORT; + req[2] = ELO_UNTOUCH_DELAY; + req[3] = ELO_REPORT_DELAY; + if (!eloSendControl(req, fd)) { #ifdef DEBUG_MOUSE - fprintf( stderr, "Unable to change Elographics touchscreen reports timings\n"); + fprintf(stderr, + "Unable to change Elographics touchscreen reports timings\n"); #endif - return 0; - } + return 0; + } - return 1; + return 1; } -int eloReadPosition(_THIS, int fd, int* x, int* y, int* button_state, int* realx, int* realy) { - unsigned char buffer[ELO_PACKET_SIZE]; - int pointer = 0; - int checksum = ELO_INIT_CHECKSUM; +int +eloReadPosition(_THIS, int fd, int *x, int *y, int *button_state, int *realx, + int *realy) +{ + unsigned char buffer[ELO_PACKET_SIZE]; + int pointer = 0; + int checksum = ELO_INIT_CHECKSUM; - while(pointer < ELO_PACKET_SIZE) { - if(eloGetPacket(buffer, &pointer, &checksum, fd)) { - break; - } + while (pointer < ELO_PACKET_SIZE) { + if (eloGetPacket(buffer, &pointer, &checksum, fd)) { + break; } + } - if(!eloParsePacket(buffer, realx, realy, button_state)) { - return 0; - } + if (!eloParsePacket(buffer, realx, realy, button_state)) { + return 0; + } + + *x = *realx; + *y = *realy; - *x = *realx; - *y = *realy; + eloConvertXY(this, x, y); - eloConvertXY(this, x, y); - - return 1; + return 1; } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/fbcon/SDL_fbelo.h b/src/video/fbcon/SDL_fbelo.h index 004664520..fcc1c2403 100644 --- a/src/video/fbcon/SDL_fbelo.h +++ b/src/video/fbcon/SDL_fbelo.h @@ -34,7 +34,7 @@ Convert the raw coordinates from the ELO controller to a screen position. */ -void eloConvertXY(_THIS, int *dx, int *dy); +void eloConvertXY(_THIS, int *dx, int *dy); /* eloInitController(int fd) Initialize the ELO serial touchscreen controller @@ -44,12 +44,15 @@ int eloInitController(int fd); /* eloParsePacket extract position and button state from a packet */ -int eloParsePacket(unsigned char* mousebuf, int* dx, int* dy, int* button_state); +int eloParsePacket(unsigned char *mousebuf, int *dx, int *dy, + int *button_state); /* eloReadPosition read a packet and get the cursor position */ -int eloReadPosition(_THIS, int fd, int* x, int* y, int* button_state, int* realx, int* realy); +int eloReadPosition(_THIS, int fd, int *x, int *y, int *button_state, + int *realx, int *realy); -#endif /* SDL_fbelo_h */ +#endif /* SDL_fbelo_h */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/fbcon/SDL_fbevents.c b/src/video/fbcon/SDL_fbevents.c index b2e84b373..2bf6ad452 100644 --- a/src/video/fbcon/SDL_fbevents.c +++ b/src/video/fbcon/SDL_fbevents.c @@ -63,385 +63,404 @@ static Uint16 vga_keymap[NUM_VGAKEYMAPS][NR_KEYS]; static SDLKey keymap[128]; static Uint16 keymap_temp[128]; /* only used at startup */ -static SDL_keysym *TranslateKey(int scancode, SDL_keysym *keysym); +static SDL_keysym *TranslateKey(int scancode, SDL_keysym * keysym); /* Ugh, we have to duplicate the kernel's keysym mapping code... Oh, it's not so bad. :-) FIXME: Add keyboard LED handling code */ -static void FB_vgainitkeymaps(int fd) +static void +FB_vgainitkeymaps(int fd) { - struct kbentry entry; - int map, i; - - /* Don't do anything if we are passed a closed keyboard */ - if ( fd < 0 ) { - return; - } - - /* Load all the keysym mappings */ - for ( map=0; map= 0) && (saved_kbd_mode >= 0)); + return ((keyboard_fd >= 0) && (saved_kbd_mode >= 0)); } -int FB_EnterGraphicsMode(_THIS) +int +FB_EnterGraphicsMode(_THIS) { - struct termios keyboard_termios; - - /* Set medium-raw keyboard mode */ - if ( (keyboard_fd >= 0) && !FB_InGraphicsMode(this) ) { - - /* Switch to the correct virtual terminal */ - if ( current_vt > 0 ) { - struct vt_stat vtstate; - - if ( ioctl(keyboard_fd, VT_GETSTATE, &vtstate) == 0 ) { - saved_vt = vtstate.v_active; - } - if ( ioctl(keyboard_fd, VT_ACTIVATE, current_vt) == 0 ) { - ioctl(keyboard_fd, VT_WAITACTIVE, current_vt); - } - } - - /* Set the terminal input mode */ - if ( tcgetattr(keyboard_fd, &saved_kbd_termios) < 0 ) { - SDL_SetError("Unable to get terminal attributes"); - if ( keyboard_fd > 0 ) { - close(keyboard_fd); - } - keyboard_fd = -1; - return(-1); - } - if ( ioctl(keyboard_fd, KDGKBMODE, &saved_kbd_mode) < 0 ) { - SDL_SetError("Unable to get current keyboard mode"); - if ( keyboard_fd > 0 ) { - close(keyboard_fd); - } - keyboard_fd = -1; - return(-1); - } - keyboard_termios = saved_kbd_termios; - keyboard_termios.c_lflag &= ~(ICANON | ECHO | ISIG); - keyboard_termios.c_iflag &= ~(ISTRIP | IGNCR | ICRNL | INLCR | IXOFF | IXON); - keyboard_termios.c_cc[VMIN] = 0; - keyboard_termios.c_cc[VTIME] = 0; - if (tcsetattr(keyboard_fd, TCSAFLUSH, &keyboard_termios) < 0) { - FB_CloseKeyboard(this); - SDL_SetError("Unable to set terminal attributes"); - return(-1); - } - /* This will fail if we aren't root or this isn't our tty */ - if ( ioctl(keyboard_fd, KDSKBMODE, K_MEDIUMRAW) < 0 ) { - FB_CloseKeyboard(this); - SDL_SetError("Unable to set keyboard in raw mode"); - return(-1); - } - if ( ioctl(keyboard_fd, KDSETMODE, KD_GRAPHICS) < 0 ) { - FB_CloseKeyboard(this); - SDL_SetError("Unable to set keyboard in graphics mode"); - return(-1); - } - /* Prevent switching the virtual terminal */ - ioctl(keyboard_fd, VT_LOCKSWITCH, 1); - } - return(keyboard_fd); + struct termios keyboard_termios; + + /* Set medium-raw keyboard mode */ + if ((keyboard_fd >= 0) && !FB_InGraphicsMode(this)) { + + /* Switch to the correct virtual terminal */ + if (current_vt > 0) { + struct vt_stat vtstate; + + if (ioctl(keyboard_fd, VT_GETSTATE, &vtstate) == 0) { + saved_vt = vtstate.v_active; + } + if (ioctl(keyboard_fd, VT_ACTIVATE, current_vt) == 0) { + ioctl(keyboard_fd, VT_WAITACTIVE, current_vt); + } + } + + /* Set the terminal input mode */ + if (tcgetattr(keyboard_fd, &saved_kbd_termios) < 0) { + SDL_SetError("Unable to get terminal attributes"); + if (keyboard_fd > 0) { + close(keyboard_fd); + } + keyboard_fd = -1; + return (-1); + } + if (ioctl(keyboard_fd, KDGKBMODE, &saved_kbd_mode) < 0) { + SDL_SetError("Unable to get current keyboard mode"); + if (keyboard_fd > 0) { + close(keyboard_fd); + } + keyboard_fd = -1; + return (-1); + } + keyboard_termios = saved_kbd_termios; + keyboard_termios.c_lflag &= ~(ICANON | ECHO | ISIG); + keyboard_termios.c_iflag &= + ~(ISTRIP | IGNCR | ICRNL | INLCR | IXOFF | IXON); + keyboard_termios.c_cc[VMIN] = 0; + keyboard_termios.c_cc[VTIME] = 0; + if (tcsetattr(keyboard_fd, TCSAFLUSH, &keyboard_termios) < 0) { + FB_CloseKeyboard(this); + SDL_SetError("Unable to set terminal attributes"); + return (-1); + } + /* This will fail if we aren't root or this isn't our tty */ + if (ioctl(keyboard_fd, KDSKBMODE, K_MEDIUMRAW) < 0) { + FB_CloseKeyboard(this); + SDL_SetError("Unable to set keyboard in raw mode"); + return (-1); + } + if (ioctl(keyboard_fd, KDSETMODE, KD_GRAPHICS) < 0) { + FB_CloseKeyboard(this); + SDL_SetError("Unable to set keyboard in graphics mode"); + return (-1); + } + /* Prevent switching the virtual terminal */ + ioctl(keyboard_fd, VT_LOCKSWITCH, 1); + } + return (keyboard_fd); } -void FB_LeaveGraphicsMode(_THIS) +void +FB_LeaveGraphicsMode(_THIS) { - if ( FB_InGraphicsMode(this) ) { - ioctl(keyboard_fd, KDSETMODE, KD_TEXT); - ioctl(keyboard_fd, KDSKBMODE, saved_kbd_mode); - tcsetattr(keyboard_fd, TCSAFLUSH, &saved_kbd_termios); - saved_kbd_mode = -1; - - /* Head back over to the original virtual terminal */ - ioctl(keyboard_fd, VT_UNLOCKSWITCH, 1); - if ( saved_vt > 0 ) { - ioctl(keyboard_fd, VT_ACTIVATE, saved_vt); - } - } + if (FB_InGraphicsMode(this)) { + ioctl(keyboard_fd, KDSETMODE, KD_TEXT); + ioctl(keyboard_fd, KDSKBMODE, saved_kbd_mode); + tcsetattr(keyboard_fd, TCSAFLUSH, &saved_kbd_termios); + saved_kbd_mode = -1; + + /* Head back over to the original virtual terminal */ + ioctl(keyboard_fd, VT_UNLOCKSWITCH, 1); + if (saved_vt > 0) { + ioctl(keyboard_fd, VT_ACTIVATE, saved_vt); + } + } } -void FB_CloseKeyboard(_THIS) +void +FB_CloseKeyboard(_THIS) { - if ( keyboard_fd >= 0 ) { - FB_LeaveGraphicsMode(this); - if ( keyboard_fd > 0 ) { - close(keyboard_fd); - } - } - keyboard_fd = -1; + if (keyboard_fd >= 0) { + FB_LeaveGraphicsMode(this); + if (keyboard_fd > 0) { + close(keyboard_fd); + } + } + keyboard_fd = -1; } -int FB_OpenKeyboard(_THIS) +int +FB_OpenKeyboard(_THIS) { - /* Open only if not already opened */ - if ( keyboard_fd < 0 ) { - static const char * const tty0[] = { "/dev/tty0", "/dev/vc/0", NULL }; - static const char * const vcs[] = { "/dev/vc/%d", "/dev/tty%d", NULL }; - int i, tty0_fd; - - /* Try to query for a free virtual terminal */ - tty0_fd = -1; - for ( i=0; tty0[i] && (tty0_fd < 0); ++i ) { - tty0_fd = open(tty0[i], O_WRONLY, 0); - } - if ( tty0_fd < 0 ) { - tty0_fd = dup(0); /* Maybe stdin is a VT? */ - } - ioctl(tty0_fd, VT_OPENQRY, ¤t_vt); - close(tty0_fd); - if ( (geteuid() == 0) && (current_vt > 0) ) { - for ( i=0; vcs[i] && (keyboard_fd < 0); ++i ) { - char vtpath[12]; - - SDL_snprintf(vtpath, SDL_arraysize(vtpath), vcs[i], current_vt); - keyboard_fd = open(vtpath, O_RDWR, 0); + /* Open only if not already opened */ + if (keyboard_fd < 0) { + static const char *const tty0[] = { "/dev/tty0", "/dev/vc/0", NULL }; + static const char *const vcs[] = { "/dev/vc/%d", "/dev/tty%d", NULL }; + int i, tty0_fd; + + /* Try to query for a free virtual terminal */ + tty0_fd = -1; + for (i = 0; tty0[i] && (tty0_fd < 0); ++i) { + tty0_fd = open(tty0[i], O_WRONLY, 0); + } + if (tty0_fd < 0) { + tty0_fd = dup(0); /* Maybe stdin is a VT? */ + } + ioctl(tty0_fd, VT_OPENQRY, ¤t_vt); + close(tty0_fd); + if ((geteuid() == 0) && (current_vt > 0)) { + for (i = 0; vcs[i] && (keyboard_fd < 0); ++i) { + char vtpath[12]; + + SDL_snprintf(vtpath, SDL_arraysize(vtpath), vcs[i], + current_vt); + keyboard_fd = open(vtpath, O_RDWR, 0); #ifdef DEBUG_KEYBOARD - fprintf(stderr, "vtpath = %s, fd = %d\n", - vtpath, keyboard_fd); + fprintf(stderr, "vtpath = %s, fd = %d\n", + vtpath, keyboard_fd); #endif /* DEBUG_KEYBOARD */ - /* This needs to be our controlling tty - so that the kernel ioctl() calls work - */ - if ( keyboard_fd >= 0 ) { - tty0_fd = open("/dev/tty", O_RDWR, 0); - if ( tty0_fd >= 0 ) { - ioctl(tty0_fd, TIOCNOTTY, 0); - close(tty0_fd); - } - } - } - } - if ( keyboard_fd < 0 ) { - /* Last resort, maybe our tty is a usable VT */ - struct vt_stat vtstate; - - keyboard_fd = open("/dev/tty", O_RDWR); - - if ( ioctl(keyboard_fd, VT_GETSTATE, &vtstate) == 0 ) { - current_vt = vtstate.v_active; - } else { - current_vt = 0; - } - } + /* This needs to be our controlling tty + so that the kernel ioctl() calls work + */ + if (keyboard_fd >= 0) { + tty0_fd = open("/dev/tty", O_RDWR, 0); + if (tty0_fd >= 0) { + ioctl(tty0_fd, TIOCNOTTY, 0); + close(tty0_fd); + } + } + } + } + if (keyboard_fd < 0) { + /* Last resort, maybe our tty is a usable VT */ + struct vt_stat vtstate; + + keyboard_fd = open("/dev/tty", O_RDWR); + + if (ioctl(keyboard_fd, VT_GETSTATE, &vtstate) == 0) { + current_vt = vtstate.v_active; + } else { + current_vt = 0; + } + } #ifdef DEBUG_KEYBOARD - fprintf(stderr, "Current VT: %d\n", current_vt); + fprintf(stderr, "Current VT: %d\n", current_vt); #endif - saved_kbd_mode = -1; - - /* Make sure that our input is a console terminal */ - { int dummy; - if ( ioctl(keyboard_fd, KDGKBMODE, &dummy) < 0 ) { - close(keyboard_fd); - keyboard_fd = -1; - SDL_SetError("Unable to open a console terminal"); - } - } - - /* Set up keymap */ - FB_vgainitkeymaps(keyboard_fd); - } - return(keyboard_fd); + saved_kbd_mode = -1; + + /* Make sure that our input is a console terminal */ + { + int dummy; + if (ioctl(keyboard_fd, KDGKBMODE, &dummy) < 0) { + close(keyboard_fd); + keyboard_fd = -1; + SDL_SetError("Unable to open a console terminal"); + } + } + + /* Set up keymap */ + FB_vgainitkeymaps(keyboard_fd); + } + return (keyboard_fd); } -static enum { - MOUSE_NONE = -1, - MOUSE_MSC, /* Note: GPM uses the MSC protocol */ - MOUSE_PS2, - MOUSE_IMPS2, - MOUSE_MS, - MOUSE_BM, - MOUSE_ELO, - MOUSE_TSLIB, - NUM_MOUSE_DRVS +static enum +{ + MOUSE_NONE = -1, + MOUSE_MSC, /* Note: GPM uses the MSC protocol */ + MOUSE_PS2, + MOUSE_IMPS2, + MOUSE_MS, + MOUSE_BM, + MOUSE_ELO, + MOUSE_TSLIB, + NUM_MOUSE_DRVS } mouse_drv = MOUSE_NONE; -void FB_CloseMouse(_THIS) +void +FB_CloseMouse(_THIS) { #if SDL_INPUT_TSLIB - if (ts_dev != NULL) { - ts_close(ts_dev); - ts_dev = NULL; - mouse_fd = -1; - } + if (ts_dev != NULL) { + ts_close(ts_dev); + ts_dev = NULL; + mouse_fd = -1; + } #endif /* SDL_INPUT_TSLIB */ - if ( mouse_fd > 0 ) { - close(mouse_fd); - } - mouse_fd = -1; + if (mouse_fd > 0) { + close(mouse_fd); + } + mouse_fd = -1; } /* Returns processes listed in /proc with the desired name */ -static int find_pid(DIR *proc, const char *wanted_name) +static int +find_pid(DIR * proc, const char *wanted_name) { - struct dirent *entry; - int pid; - - /* First scan proc for the gpm process */ - pid = 0; - while ( (pid == 0) && ((entry=readdir(proc)) != NULL) ) { - if ( isdigit(entry->d_name[0]) ) { - FILE *status; - char path[PATH_MAX]; - char name[PATH_MAX]; - - SDL_snprintf(path, SDL_arraysize(path), "/proc/%s/status", entry->d_name); - status=fopen(path, "r"); - if ( status ) { - name[0] = '\0'; - fscanf(status, "Name: %s", name); - if ( SDL_strcmp(name, wanted_name) == 0 ) { - pid = SDL_atoi(entry->d_name); - } - fclose(status); - } - } - } - return pid; + struct dirent *entry; + int pid; + + /* First scan proc for the gpm process */ + pid = 0; + while ((pid == 0) && ((entry = readdir(proc)) != NULL)) { + if (isdigit(entry->d_name[0])) { + FILE *status; + char path[PATH_MAX]; + char name[PATH_MAX]; + + SDL_snprintf(path, SDL_arraysize(path), "/proc/%s/status", + entry->d_name); + status = fopen(path, "r"); + if (status) { + name[0] = '\0'; + fscanf(status, "Name: %s", name); + if (SDL_strcmp(name, wanted_name) == 0) { + pid = SDL_atoi(entry->d_name); + } + fclose(status); + } + } + } + return pid; } /* Returns true if /dev/gpmdata is being written to by gpm */ -static int gpm_available(char *proto, size_t protolen) +static int +gpm_available(char *proto, size_t protolen) { - int available; - DIR *proc; - int pid; - int cmdline, len, arglen; - char path[PATH_MAX]; - char args[PATH_MAX], *arg; - - /* Don't bother looking if the fifo isn't there */ -#ifdef DEBUG_MOUSE - fprintf(stderr,"testing gpm\n"); + int available; + DIR *proc; + int pid; + int cmdline, len, arglen; + char path[PATH_MAX]; + char args[PATH_MAX], *arg; + + /* Don't bother looking if the fifo isn't there */ +#ifdef DEBUG_MOUSE + fprintf(stderr, "testing gpm\n"); #endif - if ( access(GPM_NODE_FIFO, F_OK) < 0 ) { - return(0); - } - - available = 0; - proc = opendir("/proc"); - if ( proc ) { - char raw_proto[10] = { '\0' }; - char repeat_proto[10] = { '\0' }; - while ( !available && (pid=find_pid(proc, "gpm")) > 0 ) { - SDL_snprintf(path, SDL_arraysize(path), "/proc/%d/cmdline", pid); - cmdline = open(path, O_RDONLY, 0); - if ( cmdline >= 0 ) { - len = read(cmdline, args, sizeof(args)); - arg = args; - while ( len > 0 ) { - arglen = SDL_strlen(arg)+1; -#ifdef DEBUG_MOUSE - fprintf(stderr,"gpm arg %s len %d\n",arg,arglen); + if (access(GPM_NODE_FIFO, F_OK) < 0) { + return (0); + } + + available = 0; + proc = opendir("/proc"); + if (proc) { + char raw_proto[10] = { '\0' }; + char repeat_proto[10] = { '\0' }; + while (!available && (pid = find_pid(proc, "gpm")) > 0) { + SDL_snprintf(path, SDL_arraysize(path), "/proc/%d/cmdline", pid); + cmdline = open(path, O_RDONLY, 0); + if (cmdline >= 0) { + len = read(cmdline, args, sizeof(args)); + arg = args; + while (len > 0) { + arglen = SDL_strlen(arg) + 1; +#ifdef DEBUG_MOUSE + fprintf(stderr, "gpm arg %s len %d\n", arg, arglen); #endif - if ( SDL_strcmp(arg, "-t") == 0) { - /* protocol string, keep it for later */ - char *t, *s; - t = arg + arglen; - s = SDL_strchr(t, ' '); - if (s) *s = 0; - SDL_strlcpy(raw_proto, t, SDL_arraysize(raw_proto)); - if (s) *s = ' '; - } - if ( SDL_strncmp(arg, "-R", 2) == 0 ) { - char *t, *s; - available = 1; - t = arg + 2; - s = SDL_strchr(t, ' '); - if (s) *s = 0; - SDL_strlcpy(repeat_proto, t, SDL_arraysize(repeat_proto)); - if (s) *s = ' '; - } - len -= arglen; - arg += arglen; - } - close(cmdline); - } - } - closedir(proc); - - if ( available ) { - if ( SDL_strcmp(repeat_proto, "raw") == 0 ) { - SDL_strlcpy(proto, raw_proto, protolen); - } else if ( *repeat_proto ) { - SDL_strlcpy(proto, repeat_proto, protolen); - } else { - SDL_strlcpy(proto, "msc", protolen); - } - } - } - return available; + if (SDL_strcmp(arg, "-t") == 0) { + /* protocol string, keep it for later */ + char *t, *s; + t = arg + arglen; + s = SDL_strchr(t, ' '); + if (s) + *s = 0; + SDL_strlcpy(raw_proto, t, SDL_arraysize(raw_proto)); + if (s) + *s = ' '; + } + if (SDL_strncmp(arg, "-R", 2) == 0) { + char *t, *s; + available = 1; + t = arg + 2; + s = SDL_strchr(t, ' '); + if (s) + *s = 0; + SDL_strlcpy(repeat_proto, t, + SDL_arraysize(repeat_proto)); + if (s) + *s = ' '; + } + len -= arglen; + arg += arglen; + } + close(cmdline); + } + } + closedir(proc); + + if (available) { + if (SDL_strcmp(repeat_proto, "raw") == 0) { + SDL_strlcpy(proto, raw_proto, protolen); + } else if (*repeat_proto) { + SDL_strlcpy(proto, repeat_proto, protolen); + } else { + SDL_strlcpy(proto, "msc", protolen); + } + } + } + return available; } @@ -450,796 +469,923 @@ static int gpm_available(char *proto, size_t protolen) * writes to device failed, but you still need to query the * device to see which mode it's actually in. */ -static int set_imps2_mode(int fd) +static int +set_imps2_mode(int fd) { - /* If you wanted to control the mouse mode (and we do :) ) ... - Set IMPS/2 protocol: - {0xf3,200,0xf3,100,0xf3,80} - Reset mouse device: - {0xFF} - */ - Uint8 set_imps2[] = {0xf3, 200, 0xf3, 100, 0xf3, 80}; - /*Uint8 reset = 0xff;*/ - fd_set fdset; - struct timeval tv; - int retval = 0; - - if ( write(fd, &set_imps2, sizeof(set_imps2)) == sizeof(set_imps2) ) { - /* Don't reset it, that'll clear IMPS/2 mode on some mice - if (write(fd, &reset, sizeof (reset)) == sizeof (reset) ) { - retval = 1; - } - */ - } - - /* Get rid of any chatter from the above */ - FD_ZERO(&fdset); - FD_SET(fd, &fdset); - tv.tv_sec = 0; - tv.tv_usec = 0; - while ( select(fd+1, &fdset, 0, 0, &tv) > 0 ) { - char temp[32]; - read(fd, temp, sizeof(temp)); - } - - return retval; + /* If you wanted to control the mouse mode (and we do :) ) ... + Set IMPS/2 protocol: + {0xf3,200,0xf3,100,0xf3,80} + Reset mouse device: + {0xFF} + */ + Uint8 set_imps2[] = { 0xf3, 200, 0xf3, 100, 0xf3, 80 }; + /*Uint8 reset = 0xff; */ + fd_set fdset; + struct timeval tv; + int retval = 0; + + if (write(fd, &set_imps2, sizeof(set_imps2)) == sizeof(set_imps2)) { + /* Don't reset it, that'll clear IMPS/2 mode on some mice + if (write(fd, &reset, sizeof (reset)) == sizeof (reset) ) { + retval = 1; + } + */ + } + + /* Get rid of any chatter from the above */ + FD_ZERO(&fdset); + FD_SET(fd, &fdset); + tv.tv_sec = 0; + tv.tv_usec = 0; + while (select(fd + 1, &fdset, 0, 0, &tv) > 0) { + char temp[32]; + read(fd, temp, sizeof(temp)); + } + + return retval; } /* Returns true if the mouse uses the IMPS/2 protocol */ -static int detect_imps2(int fd) +static int +detect_imps2(int fd) { - int imps2; - - imps2 = 0; - - if ( SDL_getenv("SDL_MOUSEDEV_IMPS2") ) { - imps2 = 1; - } - if ( ! imps2 ) { - Uint8 query_ps2 = 0xF2; - fd_set fdset; - struct timeval tv; - - /* Get rid of any mouse motion noise */ - FD_ZERO(&fdset); - FD_SET(fd, &fdset); - tv.tv_sec = 0; - tv.tv_usec = 0; - while ( select(fd+1, &fdset, 0, 0, &tv) > 0 ) { - char temp[32]; - read(fd, temp, sizeof(temp)); - } - - /* Query for the type of mouse protocol */ - if ( write(fd, &query_ps2, sizeof (query_ps2)) == sizeof (query_ps2)) { - Uint8 ch = 0; - - /* Get the mouse protocol response */ - do { - FD_ZERO(&fdset); - FD_SET(fd, &fdset); - tv.tv_sec = 1; - tv.tv_usec = 0; - if ( select(fd+1, &fdset, 0, 0, &tv) < 1 ) { - break; - } - } while ( (read(fd, &ch, sizeof (ch)) == sizeof (ch)) && - ((ch == 0xFA) || (ch == 0xAA)) ); - - /* Experimental values (Logitech wheelmouse) */ + int imps2; + + imps2 = 0; + + if (SDL_getenv("SDL_MOUSEDEV_IMPS2")) { + imps2 = 1; + } + if (!imps2) { + Uint8 query_ps2 = 0xF2; + fd_set fdset; + struct timeval tv; + + /* Get rid of any mouse motion noise */ + FD_ZERO(&fdset); + FD_SET(fd, &fdset); + tv.tv_sec = 0; + tv.tv_usec = 0; + while (select(fd + 1, &fdset, 0, 0, &tv) > 0) { + char temp[32]; + read(fd, temp, sizeof(temp)); + } + + /* Query for the type of mouse protocol */ + if (write(fd, &query_ps2, sizeof(query_ps2)) == sizeof(query_ps2)) { + Uint8 ch = 0; + + /* Get the mouse protocol response */ + do { + FD_ZERO(&fdset); + FD_SET(fd, &fdset); + tv.tv_sec = 1; + tv.tv_usec = 0; + if (select(fd + 1, &fdset, 0, 0, &tv) < 1) { + break; + } + } + while ((read(fd, &ch, sizeof(ch)) == sizeof(ch)) && + ((ch == 0xFA) || (ch == 0xAA))); + + /* Experimental values (Logitech wheelmouse) */ #ifdef DEBUG_MOUSE -fprintf(stderr, "Last mouse mode: 0x%x\n", ch); + fprintf(stderr, "Last mouse mode: 0x%x\n", ch); #endif - if ( (ch == 3) || (ch == 4) ) { - imps2 = 1; - } - } - } - return imps2; + if ((ch == 3) || (ch == 4)) { + imps2 = 1; + } + } + } + return imps2; } -int FB_OpenMouse(_THIS) +int +FB_OpenMouse(_THIS) { - int i; - const char *mousedev; - const char *mousedrv; + int i; + const char *mousedev; + const char *mousedrv; - mousedrv = SDL_getenv("SDL_MOUSEDRV"); - mousedev = SDL_getenv("SDL_MOUSEDEV"); - mouse_fd = -1; + mousedrv = SDL_getenv("SDL_MOUSEDRV"); + mousedev = SDL_getenv("SDL_MOUSEDEV"); + mouse_fd = -1; #if SDL_INPUT_TSLIB - if ( mousedrv && (SDL_strcmp(mousedrv, "TSLIB") == 0) ) { - if (mousedev == NULL) mousedev = SDL_getenv("TSLIB_TSDEVICE"); - if (mousedev != NULL) { - ts_dev = ts_open(mousedev, 1); - if ((ts_dev != NULL) && (ts_config(ts_dev) >= 0)) { + if (mousedrv && (SDL_strcmp(mousedrv, "TSLIB") == 0)) { + if (mousedev == NULL) + mousedev = SDL_getenv("TSLIB_TSDEVICE"); + if (mousedev != NULL) { + ts_dev = ts_open(mousedev, 1); + if ((ts_dev != NULL) && (ts_config(ts_dev) >= 0)) { #ifdef DEBUG_MOUSE - fprintf(stderr, "Using tslib touchscreen\n"); + fprintf(stderr, "Using tslib touchscreen\n"); #endif - mouse_drv = MOUSE_TSLIB; - mouse_fd = ts_fd(ts_dev); - return mouse_fd; - } - } - mouse_drv = MOUSE_NONE; - return mouse_fd; - } + mouse_drv = MOUSE_TSLIB; + mouse_fd = ts_fd(ts_dev); + return mouse_fd; + } + } + mouse_drv = MOUSE_NONE; + return mouse_fd; + } #endif /* SDL_INPUT_TSLIB */ - /* ELO TOUCHSCREEN SUPPORT */ + /* ELO TOUCHSCREEN SUPPORT */ - if ( mousedrv && (SDL_strcmp(mousedrv, "ELO") == 0) ) { - mouse_fd = open(mousedev, O_RDWR); - if ( mouse_fd >= 0 ) { - if(eloInitController(mouse_fd)) { + if (mousedrv && (SDL_strcmp(mousedrv, "ELO") == 0)) { + mouse_fd = open(mousedev, O_RDWR); + if (mouse_fd >= 0) { + if (eloInitController(mouse_fd)) { #ifdef DEBUG_MOUSE -fprintf(stderr, "Using ELO touchscreen\n"); + fprintf(stderr, "Using ELO touchscreen\n"); #endif - mouse_drv = MOUSE_ELO; - } - - } - else if ( mouse_fd < 0 ) { - mouse_drv = MOUSE_NONE; - } - - return(mouse_fd); - } - - /* STD MICE */ - - if ( mousedev == NULL ) { - /* FIXME someday... allow multiple mice in this driver */ - static const char *ps2mice[] = { - "/dev/input/mice", "/dev/usbmouse", "/dev/psaux", NULL - }; - /* First try to use GPM in repeater mode */ - if ( mouse_fd < 0 ) { - char proto[10]; - if ( gpm_available(proto, SDL_arraysize(proto)) ) { - mouse_fd = open(GPM_NODE_FIFO, O_RDONLY, 0); - if ( mouse_fd >= 0 ) { - if ( SDL_strcmp(proto, "msc") == 0 ) { - mouse_drv = MOUSE_MSC; - } else if ( SDL_strcmp(proto, "ps2") == 0 ) { - mouse_drv = MOUSE_PS2; - } else if ( SDL_strcmp(proto, "imps2") == 0 ) { - mouse_drv = MOUSE_IMPS2; - } else if ( SDL_strcmp(proto, "ms") == 0 || - SDL_strcmp(proto, "bare") == 0 ) { - mouse_drv = MOUSE_MS; - } else if ( SDL_strcmp(proto, "bm") == 0 ) { - mouse_drv = MOUSE_BM; - } else { - /* Unknown protocol... */ + mouse_drv = MOUSE_ELO; + } + + } else if (mouse_fd < 0) { + mouse_drv = MOUSE_NONE; + } + + return (mouse_fd); + } + + /* STD MICE */ + + if (mousedev == NULL) { + /* FIXME someday... allow multiple mice in this driver */ + static const char *ps2mice[] = { + "/dev/input/mice", "/dev/usbmouse", "/dev/psaux", NULL + }; + /* First try to use GPM in repeater mode */ + if (mouse_fd < 0) { + char proto[10]; + if (gpm_available(proto, SDL_arraysize(proto))) { + mouse_fd = open(GPM_NODE_FIFO, O_RDONLY, 0); + if (mouse_fd >= 0) { + if (SDL_strcmp(proto, "msc") == 0) { + mouse_drv = MOUSE_MSC; + } else if (SDL_strcmp(proto, "ps2") == 0) { + mouse_drv = MOUSE_PS2; + } else if (SDL_strcmp(proto, "imps2") == 0) { + mouse_drv = MOUSE_IMPS2; + } else if (SDL_strcmp(proto, "ms") == 0 || + SDL_strcmp(proto, "bare") == 0) { + mouse_drv = MOUSE_MS; + } else if (SDL_strcmp(proto, "bm") == 0) { + mouse_drv = MOUSE_BM; + } else { + /* Unknown protocol... */ #ifdef DEBUG_MOUSE - fprintf(stderr, "GPM mouse using unknown protocol = %s\n", proto); + fprintf(stderr, + "GPM mouse using unknown protocol = %s\n", + proto); #endif - close(mouse_fd); - mouse_fd = -1; - } - } + close(mouse_fd); + mouse_fd = -1; + } + } #ifdef DEBUG_MOUSE - if ( mouse_fd >= 0 ) { - fprintf(stderr, "Using GPM mouse, protocol = %s\n", proto); - } + if (mouse_fd >= 0) { + fprintf(stderr, + "Using GPM mouse, protocol = %s\n", proto); + } #endif /* DEBUG_MOUSE */ - } - } - /* Now try to use a modern PS/2 mouse */ - for ( i=0; (mouse_fd < 0) && ps2mice[i]; ++i ) { - mouse_fd = open(ps2mice[i], O_RDWR, 0); - if (mouse_fd < 0) { - mouse_fd = open(ps2mice[i], O_RDONLY, 0); - } - if (mouse_fd >= 0) { - /* rcg06112001 Attempt to set IMPS/2 mode */ - set_imps2_mode(mouse_fd); - if (detect_imps2(mouse_fd)) { + } + } + /* Now try to use a modern PS/2 mouse */ + for (i = 0; (mouse_fd < 0) && ps2mice[i]; ++i) { + mouse_fd = open(ps2mice[i], O_RDWR, 0); + if (mouse_fd < 0) { + mouse_fd = open(ps2mice[i], O_RDONLY, 0); + } + if (mouse_fd >= 0) { + /* rcg06112001 Attempt to set IMPS/2 mode */ + set_imps2_mode(mouse_fd); + if (detect_imps2(mouse_fd)) { #ifdef DEBUG_MOUSE -fprintf(stderr, "Using IMPS2 mouse\n"); + fprintf(stderr, "Using IMPS2 mouse\n"); #endif - mouse_drv = MOUSE_IMPS2; - } else { + mouse_drv = MOUSE_IMPS2; + } else { #ifdef DEBUG_MOUSE -fprintf(stderr, "Using PS2 mouse\n"); + fprintf(stderr, "Using PS2 mouse\n"); #endif - mouse_drv = MOUSE_PS2; - } - } - } - /* Next try to use a PPC ADB port mouse */ - if ( mouse_fd < 0 ) { - mouse_fd = open("/dev/adbmouse", O_RDONLY, 0); - if ( mouse_fd >= 0 ) { + mouse_drv = MOUSE_PS2; + } + } + } + /* Next try to use a PPC ADB port mouse */ + if (mouse_fd < 0) { + mouse_fd = open("/dev/adbmouse", O_RDONLY, 0); + if (mouse_fd >= 0) { #ifdef DEBUG_MOUSE -fprintf(stderr, "Using ADB mouse\n"); + fprintf(stderr, "Using ADB mouse\n"); #endif - mouse_drv = MOUSE_BM; - } - } - } - /* Default to a serial Microsoft mouse */ - if ( mouse_fd < 0 ) { - if ( mousedev == NULL ) { - mousedev = "/dev/mouse"; - } - mouse_fd = open(mousedev, O_RDONLY, 0); - if ( mouse_fd >= 0 ) { - struct termios mouse_termios; - - /* Set the sampling speed to 1200 baud */ - tcgetattr(mouse_fd, &mouse_termios); - mouse_termios.c_iflag = IGNBRK | IGNPAR; - mouse_termios.c_oflag = 0; - mouse_termios.c_lflag = 0; - mouse_termios.c_line = 0; - mouse_termios.c_cc[VTIME] = 0; - mouse_termios.c_cc[VMIN] = 1; - mouse_termios.c_cflag = CREAD | CLOCAL | HUPCL; - mouse_termios.c_cflag |= CS8; - mouse_termios.c_cflag |= B1200; - tcsetattr(mouse_fd, TCSAFLUSH, &mouse_termios); - if ( mousedrv && (SDL_strcmp(mousedrv, "PS2") == 0) ) { + mouse_drv = MOUSE_BM; + } + } + } + /* Default to a serial Microsoft mouse */ + if (mouse_fd < 0) { + if (mousedev == NULL) { + mousedev = "/dev/mouse"; + } + mouse_fd = open(mousedev, O_RDONLY, 0); + if (mouse_fd >= 0) { + struct termios mouse_termios; + + /* Set the sampling speed to 1200 baud */ + tcgetattr(mouse_fd, &mouse_termios); + mouse_termios.c_iflag = IGNBRK | IGNPAR; + mouse_termios.c_oflag = 0; + mouse_termios.c_lflag = 0; + mouse_termios.c_line = 0; + mouse_termios.c_cc[VTIME] = 0; + mouse_termios.c_cc[VMIN] = 1; + mouse_termios.c_cflag = CREAD | CLOCAL | HUPCL; + mouse_termios.c_cflag |= CS8; + mouse_termios.c_cflag |= B1200; + tcsetattr(mouse_fd, TCSAFLUSH, &mouse_termios); + if (mousedrv && (SDL_strcmp(mousedrv, "PS2") == 0)) { #ifdef DEBUG_MOUSE -fprintf(stderr, "Using (user specified) PS2 mouse on %s\n", mousedev); + fprintf(stderr, + "Using (user specified) PS2 mouse on %s\n", mousedev); #endif - mouse_drv = MOUSE_PS2; - } else { + mouse_drv = MOUSE_PS2; + } else { #ifdef DEBUG_MOUSE -fprintf(stderr, "Using (default) MS mouse on %s\n", mousedev); + fprintf(stderr, "Using (default) MS mouse on %s\n", mousedev); #endif - mouse_drv = MOUSE_MS; - } - } - } - if ( mouse_fd < 0 ) { - mouse_drv = MOUSE_NONE; - } - return(mouse_fd); + mouse_drv = MOUSE_MS; + } + } + } + if (mouse_fd < 0) { + mouse_drv = MOUSE_NONE; + } + return (mouse_fd); } static int posted = 0; -void FB_vgamousecallback(int button, int relative, int dx, int dy) +void +FB_vgamousecallback(int button, int relative, int dx, int dy) { - int button_1, button_3; - int button_state; - int state_changed; - int i; - Uint8 state; - - if ( dx || dy ) { - posted += SDL_PrivateMouseMotion(0, relative, dx, dy); - } - - /* Swap button 1 and 3 */ - button_1 = (button & 0x04) >> 2; - button_3 = (button & 0x01) << 2; - button &= ~0x05; - button |= (button_1|button_3); - - /* See what changed */ - button_state = SDL_GetMouseState(NULL, NULL); - state_changed = button_state ^ button; - for ( i=0; i<8; ++i ) { - if ( state_changed & (1<> 2; + button_3 = (button & 0x01) << 2; + button &= ~0x05; + button |= (button_1 | button_3); + + /* See what changed */ + button_state = SDL_GetMouseState(NULL, NULL); + state_changed = button_state ^ button; + for (i = 0; i < 8; ++i) { + if (state_changed & (1 << i)) { + if (button & (1 << i)) { + state = SDL_PRESSED; + } else { + state = SDL_RELEASED; + } + posted += SDL_PrivateMouseButton(state, i + 1, 0, 0); + } + } } /* Handle input from tslib */ #if SDL_INPUT_TSLIB -static void handle_tslib(_THIS) +static void +handle_tslib(_THIS) { - struct ts_sample sample; - int button; - - while (ts_read(ts_dev, &sample, 1) > 0) { - button = (sample.pressure > 0) ? 1 : 0; - button <<= 2; /* must report it as button 3 */ - FB_vgamousecallback(button, 0, sample.x, sample.y); - } - return; + struct ts_sample sample; + int button; + + while (ts_read(ts_dev, &sample, 1) > 0) { + button = (sample.pressure > 0) ? 1 : 0; + button <<= 2; /* must report it as button 3 */ + FB_vgamousecallback(button, 0, sample.x, sample.y); + } + return; } #endif /* SDL_INPUT_TSLIB */ /* For now, use MSC, PS/2, and MS protocols Driver adapted from the SVGAlib mouse driver code (taken from gpm, etc.) */ -static void handle_mouse(_THIS) +static void +handle_mouse(_THIS) { - static int start = 0; - static unsigned char mousebuf[BUFSIZ]; - static int relative = 1; - - int i, nread; - int button = 0; - int dx = 0, dy = 0; - int packetsize = 0; - int realx, realy; - - /* Figure out the mouse packet size */ - switch (mouse_drv) { - case MOUSE_NONE: - /* Ack! */ - read(mouse_fd, mousebuf, BUFSIZ); - return; - case MOUSE_MSC: - packetsize = 5; - break; - case MOUSE_IMPS2: - packetsize = 4; - break; - case MOUSE_PS2: - case MOUSE_MS: - case MOUSE_BM: - packetsize = 3; - break; - case MOUSE_ELO: - /* try to read the next packet */ - if(eloReadPosition(this, mouse_fd, &dx, &dy, &button, &realx, &realy)) { - button = (button & 0x01) << 2; - FB_vgamousecallback(button, 0, dx, dy); - } - return; /* nothing left to do */ - case MOUSE_TSLIB: + static int start = 0; + static unsigned char mousebuf[BUFSIZ]; + static int relative = 1; + + int i, nread; + int button = 0; + int dx = 0, dy = 0; + int packetsize = 0; + int realx, realy; + + /* Figure out the mouse packet size */ + switch (mouse_drv) { + case MOUSE_NONE: + /* Ack! */ + read(mouse_fd, mousebuf, BUFSIZ); + return; + case MOUSE_MSC: + packetsize = 5; + break; + case MOUSE_IMPS2: + packetsize = 4; + break; + case MOUSE_PS2: + case MOUSE_MS: + case MOUSE_BM: + packetsize = 3; + break; + case MOUSE_ELO: + /* try to read the next packet */ + if (eloReadPosition + (this, mouse_fd, &dx, &dy, &button, &realx, &realy)) { + button = (button & 0x01) << 2; + FB_vgamousecallback(button, 0, dx, dy); + } + return; /* nothing left to do */ + case MOUSE_TSLIB: #if SDL_INPUT_TSLIB - handle_tslib(this); + handle_tslib(this); #endif - return; /* nothing left to do */ - default: - /* Uh oh.. */ - packetsize = 0; - break; - } - - /* Special handling for the quite sensitive ELO controller */ - if (mouse_drv == MOUSE_ELO) { - - } - - /* Read as many packets as possible */ - nread = read(mouse_fd, &mousebuf[start], BUFSIZ-start); - if ( nread < 0 ) { - return; - } - nread += start; + return; /* nothing left to do */ + default: + /* Uh oh.. */ + packetsize = 0; + break; + } + + /* Special handling for the quite sensitive ELO controller */ + if (mouse_drv == MOUSE_ELO) { + + } + + /* Read as many packets as possible */ + nread = read(mouse_fd, &mousebuf[start], BUFSIZ - start); + if (nread < 0) { + return; + } + nread += start; #ifdef DEBUG_MOUSE - fprintf(stderr, "Read %d bytes from mouse, start = %d\n", nread, start); + fprintf(stderr, "Read %d bytes from mouse, start = %d\n", nread, start); #endif - for ( i=0; i<(nread-(packetsize-1)); i += packetsize ) { - switch (mouse_drv) { - case MOUSE_NONE: - break; - case MOUSE_MSC: - /* MSC protocol has 0x80 in high byte */ - if ( (mousebuf[i] & 0xF8) != 0x80 ) { - /* Go to next byte */ - i -= (packetsize-1); - continue; - } - /* Get current mouse state */ - button = (~mousebuf[i]) & 0x07; - dx = (signed char)(mousebuf[i+1]) + - (signed char)(mousebuf[i+3]); - dy = -((signed char)(mousebuf[i+2]) + - (signed char)(mousebuf[i+4])); - break; - case MOUSE_PS2: - /* PS/2 protocol has nothing in high byte */ - if ( (mousebuf[i] & 0xC0) != 0 ) { - /* Go to next byte */ - i -= (packetsize-1); - continue; - } - /* Get current mouse state */ - button = (mousebuf[i] & 0x04) >> 1 | /*Middle*/ - (mousebuf[i] & 0x02) >> 1 | /*Right*/ - (mousebuf[i] & 0x01) << 2; /*Left*/ - dx = (mousebuf[i] & 0x10) ? - mousebuf[i+1] - 256 : mousebuf[i+1]; - dy = (mousebuf[i] & 0x20) ? - -(mousebuf[i+2] - 256) : -mousebuf[i+2]; - break; - case MOUSE_IMPS2: - /* Get current mouse state */ - button = (mousebuf[i] & 0x04) >> 1 | /*Middle*/ - (mousebuf[i] & 0x02) >> 1 | /*Right*/ - (mousebuf[i] & 0x01) << 2 | /*Left*/ - (mousebuf[i] & 0x40) >> 3 | /* 4 */ - (mousebuf[i] & 0x80) >> 3; /* 5 */ - dx = (mousebuf[i] & 0x10) ? - mousebuf[i+1] - 256 : mousebuf[i+1]; - dy = (mousebuf[i] & 0x20) ? - -(mousebuf[i+2] - 256) : -mousebuf[i+2]; - switch (mousebuf[i+3]&0x0F) { - case 0x0E: /* DX = +1 */ - case 0x02: /* DX = -1 */ - break; - case 0x0F: /* DY = +1 (map button 4) */ - FB_vgamousecallback(button | (1<<3), - 1, 0, 0); - break; - case 0x01: /* DY = -1 (map button 5) */ - FB_vgamousecallback(button | (1<<4), - 1, 0, 0); - break; - } - break; - case MOUSE_MS: - /* Microsoft protocol has 0x40 in high byte */ - if ( (mousebuf[i] & 0x40) != 0x40 ) { - /* Go to next byte */ - i -= (packetsize-1); - continue; - } - /* Get current mouse state */ - button = ((mousebuf[i] & 0x20) >> 3) | - ((mousebuf[i] & 0x10) >> 4); - dx = (signed char)(((mousebuf[i] & 0x03) << 6) | - (mousebuf[i + 1] & 0x3F)); - dy = (signed char)(((mousebuf[i] & 0x0C) << 4) | - (mousebuf[i + 2] & 0x3F)); - break; - case MOUSE_BM: - /* BusMouse protocol has 0xF8 in high byte */ - if ( (mousebuf[i] & 0xF8) != 0x80 ) { - /* Go to next byte */ - i -= (packetsize-1); - continue; - } - /* Get current mouse state */ - button = (~mousebuf[i]) & 0x07; - dx = (signed char)mousebuf[i+1]; - dy = -(signed char)mousebuf[i+2]; - break; - default: - /* Uh oh.. */ - dx = 0; - dy = 0; - break; - } - FB_vgamousecallback(button, relative, dx, dy); - } - if ( i < nread ) { - SDL_memcpy(mousebuf, &mousebuf[i], (nread-i)); - start = (nread-i); - } else { - start = 0; - } - return; + for (i = 0; i < (nread - (packetsize - 1)); i += packetsize) { + switch (mouse_drv) { + case MOUSE_NONE: + break; + case MOUSE_MSC: + /* MSC protocol has 0x80 in high byte */ + if ((mousebuf[i] & 0xF8) != 0x80) { + /* Go to next byte */ + i -= (packetsize - 1); + continue; + } + /* Get current mouse state */ + button = (~mousebuf[i]) & 0x07; + dx = (signed char) (mousebuf[i + 1]) + + (signed char) (mousebuf[i + 3]); + dy = -((signed char) (mousebuf[i + 2]) + + (signed char) (mousebuf[i + 4])); + break; + case MOUSE_PS2: + /* PS/2 protocol has nothing in high byte */ + if ((mousebuf[i] & 0xC0) != 0) { + /* Go to next byte */ + i -= (packetsize - 1); + continue; + } + /* Get current mouse state */ + button = (mousebuf[i] & 0x04) >> 1 | /*Middle */ + (mousebuf[i] & 0x02) >> 1 | /*Right */ + (mousebuf[i] & 0x01) << 2; /*Left */ + dx = (mousebuf[i] & 0x10) ? + mousebuf[i + 1] - 256 : mousebuf[i + 1]; + dy = (mousebuf[i] & 0x20) ? + -(mousebuf[i + 2] - 256) : -mousebuf[i + 2]; + break; + case MOUSE_IMPS2: + /* Get current mouse state */ + button = (mousebuf[i] & 0x04) >> 1 | /*Middle */ + (mousebuf[i] & 0x02) >> 1 | /*Right */ + (mousebuf[i] & 0x01) << 2 | /*Left */ + (mousebuf[i] & 0x40) >> 3 | /* 4 */ + (mousebuf[i] & 0x80) >> 3; /* 5 */ + dx = (mousebuf[i] & 0x10) ? + mousebuf[i + 1] - 256 : mousebuf[i + 1]; + dy = (mousebuf[i] & 0x20) ? + -(mousebuf[i + 2] - 256) : -mousebuf[i + 2]; + switch (mousebuf[i + 3] & 0x0F) { + case 0x0E: /* DX = +1 */ + case 0x02: /* DX = -1 */ + break; + case 0x0F: /* DY = +1 (map button 4) */ + FB_vgamousecallback(button | (1 << 3), 1, 0, 0); + break; + case 0x01: /* DY = -1 (map button 5) */ + FB_vgamousecallback(button | (1 << 4), 1, 0, 0); + break; + } + break; + case MOUSE_MS: + /* Microsoft protocol has 0x40 in high byte */ + if ((mousebuf[i] & 0x40) != 0x40) { + /* Go to next byte */ + i -= (packetsize - 1); + continue; + } + /* Get current mouse state */ + button = ((mousebuf[i] & 0x20) >> 3) | + ((mousebuf[i] & 0x10) >> 4); + dx = (signed char) (((mousebuf[i] & 0x03) << 6) | + (mousebuf[i + 1] & 0x3F)); + dy = (signed char) (((mousebuf[i] & 0x0C) << 4) | + (mousebuf[i + 2] & 0x3F)); + break; + case MOUSE_BM: + /* BusMouse protocol has 0xF8 in high byte */ + if ((mousebuf[i] & 0xF8) != 0x80) { + /* Go to next byte */ + i -= (packetsize - 1); + continue; + } + /* Get current mouse state */ + button = (~mousebuf[i]) & 0x07; + dx = (signed char) mousebuf[i + 1]; + dy = -(signed char) mousebuf[i + 2]; + break; + default: + /* Uh oh.. */ + dx = 0; + dy = 0; + break; + } + FB_vgamousecallback(button, relative, dx, dy); + } + if (i < nread) { + SDL_memcpy(mousebuf, &mousebuf[i], (nread - i)); + start = (nread - i); + } else { + start = 0; + } + return; } /* Handle switching to another VC, returns when our VC is back */ -static void switch_vt_prep(_THIS) +static void +switch_vt_prep(_THIS) { - SDL_Surface *screen = SDL_VideoSurface; - - SDL_PrivateAppActive(0, (SDL_APPACTIVE|SDL_APPINPUTFOCUS|SDL_APPMOUSEFOCUS)); - - /* Save the contents of the screen, and go to text mode */ - wait_idle(this); - screen_arealen = ((screen->h + (2*this->offset_y)) * screen->pitch); - screen_contents = (Uint8 *)SDL_malloc(screen_arealen); - if ( screen_contents ) { - SDL_memcpy(screen_contents, screen->pixels, screen_arealen); - } - FB_SavePaletteTo(this, 256, screen_palette); - ioctl(console_fd, FBIOGET_VSCREENINFO, &screen_vinfo); - ioctl(keyboard_fd, KDSETMODE, KD_TEXT); - ioctl(keyboard_fd, VT_UNLOCKSWITCH, 1); + SDL_Surface *screen = SDL_VideoSurface; + + SDL_PrivateAppActive(0, + (SDL_APPACTIVE | SDL_APPINPUTFOCUS | + SDL_APPMOUSEFOCUS)); + + /* Save the contents of the screen, and go to text mode */ + wait_idle(this); + screen_arealen = ((screen->h + (2 * this->offset_y)) * screen->pitch); + screen_contents = (Uint8 *) SDL_malloc(screen_arealen); + if (screen_contents) { + SDL_memcpy(screen_contents, screen->pixels, screen_arealen); + } + FB_SavePaletteTo(this, 256, screen_palette); + ioctl(console_fd, FBIOGET_VSCREENINFO, &screen_vinfo); + ioctl(keyboard_fd, KDSETMODE, KD_TEXT); + ioctl(keyboard_fd, VT_UNLOCKSWITCH, 1); } -static void switch_vt_done(_THIS) +static void +switch_vt_done(_THIS) { - SDL_Surface *screen = SDL_VideoSurface; - - /* Restore graphics mode and the contents of the screen */ - ioctl(keyboard_fd, VT_LOCKSWITCH, 1); - ioctl(keyboard_fd, KDSETMODE, KD_GRAPHICS); - ioctl(console_fd, FBIOPUT_VSCREENINFO, &screen_vinfo); - FB_RestorePaletteFrom(this, 256, screen_palette); - if ( screen_contents ) { - SDL_memcpy(screen->pixels, screen_contents, screen_arealen); - SDL_free(screen_contents); - screen_contents = NULL; - } - - /* Get updates to the shadow surface while switched away */ - if ( SDL_ShadowSurface ) { - SDL_UpdateRect(SDL_ShadowSurface, 0, 0, 0, 0); - } - - SDL_PrivateAppActive(1, (SDL_APPACTIVE|SDL_APPINPUTFOCUS|SDL_APPMOUSEFOCUS)); + SDL_Surface *screen = SDL_VideoSurface; + + /* Restore graphics mode and the contents of the screen */ + ioctl(keyboard_fd, VT_LOCKSWITCH, 1); + ioctl(keyboard_fd, KDSETMODE, KD_GRAPHICS); + ioctl(console_fd, FBIOPUT_VSCREENINFO, &screen_vinfo); + FB_RestorePaletteFrom(this, 256, screen_palette); + if (screen_contents) { + SDL_memcpy(screen->pixels, screen_contents, screen_arealen); + SDL_free(screen_contents); + screen_contents = NULL; + } + + /* Get updates to the shadow surface while switched away */ + if (SDL_ShadowSurface) { + SDL_UpdateRect(SDL_ShadowSurface, 0, 0, 0, 0); + } + + SDL_PrivateAppActive(1, + (SDL_APPACTIVE | SDL_APPINPUTFOCUS | + SDL_APPMOUSEFOCUS)); } -static void switch_vt(_THIS, unsigned short which) +static void +switch_vt(_THIS, unsigned short which) { - struct vt_stat vtstate; - - /* Figure out whether or not we're switching to a new console */ - if ( (ioctl(keyboard_fd, VT_GETSTATE, &vtstate) < 0) || - (which == vtstate.v_active) ) { - return; - } - - /* New console, switch to it */ - SDL_mutexP(hw_lock); - switch_vt_prep(this); - if ( ioctl(keyboard_fd, VT_ACTIVATE, which) == 0 ) { - ioctl(keyboard_fd, VT_WAITACTIVE, which); - switched_away = 1; - } else { - switch_vt_done(this); - } - SDL_mutexV(hw_lock); + struct vt_stat vtstate; + + /* Figure out whether or not we're switching to a new console */ + if ((ioctl(keyboard_fd, VT_GETSTATE, &vtstate) < 0) || + (which == vtstate.v_active)) { + return; + } + + /* New console, switch to it */ + SDL_mutexP(hw_lock); + switch_vt_prep(this); + if (ioctl(keyboard_fd, VT_ACTIVATE, which) == 0) { + ioctl(keyboard_fd, VT_WAITACTIVE, which); + switched_away = 1; + } else { + switch_vt_done(this); + } + SDL_mutexV(hw_lock); } -static void handle_keyboard(_THIS) +static void +handle_keyboard(_THIS) { - unsigned char keybuf[BUFSIZ]; - int i, nread; - int pressed; - int scancode; - SDL_keysym keysym; - - nread = read(keyboard_fd, keybuf, BUFSIZ); - for ( i=0; i= 0 ) { - FD_SET(keyboard_fd, &fdset); - if ( max_fd < keyboard_fd ) { - max_fd = keyboard_fd; - } - } - if ( mouse_fd >= 0 ) { - FD_SET(mouse_fd, &fdset); - if ( max_fd < mouse_fd ) { - max_fd = mouse_fd; - } - } - if ( select(max_fd+1, &fdset, NULL, NULL, &zero) > 0 ) { - if ( keyboard_fd >= 0 ) { - if ( FD_ISSET(keyboard_fd, &fdset) ) { - handle_keyboard(this); - } - } - if ( mouse_fd >= 0 ) { - if ( FD_ISSET(mouse_fd, &fdset) ) { - handle_mouse(this); - } - } - } - } while ( posted ); + fd_set fdset; + int max_fd; + static struct timeval zero; + + do { + if (switched_away) { + struct vt_stat vtstate; + + SDL_mutexP(hw_lock); + if ((ioctl(keyboard_fd, VT_GETSTATE, &vtstate) == 0) && + vtstate.v_active == current_vt) { + switched_away = 0; + switch_vt_done(this); + } + SDL_mutexV(hw_lock); + } + + posted = 0; + + FD_ZERO(&fdset); + max_fd = 0; + if (keyboard_fd >= 0) { + FD_SET(keyboard_fd, &fdset); + if (max_fd < keyboard_fd) { + max_fd = keyboard_fd; + } + } + if (mouse_fd >= 0) { + FD_SET(mouse_fd, &fdset); + if (max_fd < mouse_fd) { + max_fd = mouse_fd; + } + } + if (select(max_fd + 1, &fdset, NULL, NULL, &zero) > 0) { + if (keyboard_fd >= 0) { + if (FD_ISSET(keyboard_fd, &fdset)) { + handle_keyboard(this); + } + } + if (mouse_fd >= 0) { + if (FD_ISSET(mouse_fd, &fdset)) { + handle_mouse(this); + } + } + } + } + while (posted); } -void FB_InitOSKeymap(_THIS) +void +FB_InitOSKeymap(_THIS) { - int i; - - /* Initialize the Linux key translation table */ - - /* First get the ascii keys and others not well handled */ - for (i=0; iscancode = scancode; - keysym->sym = keymap[scancode]; - keysym->mod = KMOD_NONE; - - /* If UNICODE is on, get the UNICODE value for the key */ - keysym->unicode = 0; - if ( SDL_TranslateUNICODE ) { - int map; - SDLMod modstate; - - modstate = SDL_GetModState(); - map = 0; - if ( modstate & KMOD_SHIFT ) { - map |= (1<unicode=KVAL(vga_keymap[map][scancode]); - } - } else { - keysym->unicode = KVAL(vga_keymap[map][scancode]); - } - } - return(keysym); + /* Set the keysym information */ + keysym->scancode = scancode; + keysym->sym = keymap[scancode]; + keysym->mod = KMOD_NONE; + + /* If UNICODE is on, get the UNICODE value for the key */ + keysym->unicode = 0; + if (SDL_TranslateUNICODE) { + int map; + SDLMod modstate; + + modstate = SDL_GetModState(); + map = 0; + if (modstate & KMOD_SHIFT) { + map |= (1 << KG_SHIFT); + } + if (modstate & KMOD_CTRL) { + map |= (1 << KG_CTRL); + } + if (modstate & KMOD_LALT) { + map |= (1 << KG_ALT); + } + if (modstate & KMOD_RALT) { + map |= (1 << KG_ALTGR); + } + if (KTYP(vga_keymap[map][scancode]) == KT_LETTER) { + if (modstate & KMOD_CAPS) { + map ^= (1 << KG_SHIFT); + } + } + if (KTYP(vga_keymap[map][scancode]) == KT_PAD) { + if (modstate & KMOD_NUM) { + keysym->unicode = KVAL(vga_keymap[map][scancode]); + } + } else { + keysym->unicode = KVAL(vga_keymap[map][scancode]); + } + } + return (keysym); } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/fbcon/SDL_fbevents_c.h b/src/video/fbcon/SDL_fbevents_c.h index 99166bda2..22ffb6800 100644 --- a/src/video/fbcon/SDL_fbevents_c.h +++ b/src/video/fbcon/SDL_fbevents_c.h @@ -36,3 +36,4 @@ extern void FB_LeaveGraphicsMode(_THIS); extern void FB_InitOSKeymap(_THIS); extern void FB_PumpEvents(_THIS); +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/fbcon/SDL_fbkeys.h b/src/video/fbcon/SDL_fbkeys.h index 2b01b6b2e..1f5117c32 100644 --- a/src/video/fbcon/SDL_fbkeys.h +++ b/src/video/fbcon/SDL_fbkeys.h @@ -120,20 +120,20 @@ #define SCANCODE_KEYPADDIVIDE 98 #define SCANCODE_PRINTSCREEN 99 #define SCANCODE_RIGHTALT 100 -#define SCANCODE_BREAK 101 /* Beware: is 119 */ -#define SCANCODE_BREAK_ALTERNATIVE 119 /* on some keyboards! */ +#define SCANCODE_BREAK 101 /* Beware: is 119 */ +#define SCANCODE_BREAK_ALTERNATIVE 119 /* on some keyboards! */ #define SCANCODE_HOME 102 -#define SCANCODE_CURSORBLOCKUP 103 /* Cursor key block */ +#define SCANCODE_CURSORBLOCKUP 103 /* Cursor key block */ #define SCANCODE_PAGEUP 104 -#define SCANCODE_CURSORBLOCKLEFT 105 /* Cursor key block */ -#define SCANCODE_CURSORBLOCKRIGHT 106 /* Cursor key block */ +#define SCANCODE_CURSORBLOCKLEFT 105 /* Cursor key block */ +#define SCANCODE_CURSORBLOCKRIGHT 106 /* Cursor key block */ #define SCANCODE_END 107 -#define SCANCODE_CURSORBLOCKDOWN 108 /* Cursor key block */ +#define SCANCODE_CURSORBLOCKDOWN 108 /* Cursor key block */ #define SCANCODE_PAGEDOWN 109 #define SCANCODE_INSERT 110 #define SCANCODE_REMOVE 111 #define SCANCODE_RIGHTWIN 126 #define SCANCODE_LEFTWIN 125 - +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/fbcon/SDL_fbmatrox.c b/src/video/fbcon/SDL_fbmatrox.c index 177131a71..bcf774602 100644 --- a/src/video/fbcon/SDL_fbmatrox.c +++ b/src/video/fbcon/SDL_fbmatrox.c @@ -28,253 +28,257 @@ /* Wait for vertical retrace - taken from the XFree86 Matrox driver */ -static void WaitVBL(_THIS) +static void +WaitVBL(_THIS) { - int count; - - /* find start of retrace */ - mga_waitidle(); - while ( (mga_in8(0x1FDA) & 0x08) ) - ; - while ( !(mga_in8(0x1FDA) & 0x08) ) - ; - /* wait until we're past the start */ - count = mga_in32(0x1E20) + 2; - while ( mga_in32(0x1E20) < count ) - ; + int count; + + /* find start of retrace */ + mga_waitidle(); + while ((mga_in8(0x1FDA) & 0x08)); + while (!(mga_in8(0x1FDA) & 0x08)); + /* wait until we're past the start */ + count = mga_in32(0x1E20) + 2; + while (mga_in32(0x1E20) < count); } -static void WaitIdle(_THIS) +static void +WaitIdle(_THIS) { - mga_waitidle(); + mga_waitidle(); } /* Sets video mem colorkey and accelerated blit function */ -static int SetHWColorKey(_THIS, SDL_Surface *surface, Uint32 key) +static int +SetHWColorKey(_THIS, SDL_Surface * surface, Uint32 key) { - return(0); + return (0); } /* Sets per surface hardware alpha value */ #if 0 -static int SetHWAlpha(_THIS, SDL_Surface *surface, Uint8 value) +static int +SetHWAlpha(_THIS, SDL_Surface * surface, Uint8 value) { - return(0); + return (0); } #endif -static int FillHWRect(_THIS, SDL_Surface *dst, SDL_Rect *rect, Uint32 color) +static int +FillHWRect(_THIS, SDL_Surface * dst, SDL_Rect * rect, Uint32 color) { - int dstX, dstY; - Uint32 fxbndry; - Uint32 ydstlen; - Uint32 fillop; - - /* Don't blit to the display surface when switched away */ - if ( switched_away ) { - return -2; /* no hardware access */ - } - if ( dst == this->screen ) { - SDL_mutexP(hw_lock); - } - - switch (dst->format->BytesPerPixel) { - case 1: - color |= (color<<8); - case 2: - color |= (color<<16); - break; - } - - /* Set up the X/Y base coordinates */ - FB_dst_to_xy(this, dst, &dstX, &dstY); - - /* Adjust for the current rectangle */ - dstX += rect->x; - dstY += rect->y; - - /* Set up the X boundaries */ - fxbndry = (dstX | ((dstX+rect->w) << 16)); - - /* Set up the Y boundaries */ - ydstlen = (rect->h | (dstY << 16)); - - /* Set up for color fill operation */ - fillop = MGADWG_TRAP | MGADWG_SOLID | - MGADWG_ARZERO | MGADWG_SGNZERO | MGADWG_SHIFTZERO; - - /* Execute the operations! */ - mga_wait(5); - mga_out32(MGAREG_DWGCTL, fillop | MGADWG_REPLACE); - mga_out32(MGAREG_FCOL, color); - mga_out32(MGAREG_FXBNDRY, fxbndry); - mga_out32(MGAREG_YDSTLEN + MGAREG_EXEC, ydstlen); - - FB_AddBusySurface(dst); - - if ( dst == this->screen ) { - SDL_mutexV(hw_lock); - } - return(0); + int dstX, dstY; + Uint32 fxbndry; + Uint32 ydstlen; + Uint32 fillop; + + /* Don't blit to the display surface when switched away */ + if (switched_away) { + return -2; /* no hardware access */ + } + if (dst == this->screen) { + SDL_mutexP(hw_lock); + } + + switch (dst->format->BytesPerPixel) { + case 1: + color |= (color << 8); + case 2: + color |= (color << 16); + break; + } + + /* Set up the X/Y base coordinates */ + FB_dst_to_xy(this, dst, &dstX, &dstY); + + /* Adjust for the current rectangle */ + dstX += rect->x; + dstY += rect->y; + + /* Set up the X boundaries */ + fxbndry = (dstX | ((dstX + rect->w) << 16)); + + /* Set up the Y boundaries */ + ydstlen = (rect->h | (dstY << 16)); + + /* Set up for color fill operation */ + fillop = MGADWG_TRAP | MGADWG_SOLID | + MGADWG_ARZERO | MGADWG_SGNZERO | MGADWG_SHIFTZERO; + + /* Execute the operations! */ + mga_wait(5); + mga_out32(MGAREG_DWGCTL, fillop | MGADWG_REPLACE); + mga_out32(MGAREG_FCOL, color); + mga_out32(MGAREG_FXBNDRY, fxbndry); + mga_out32(MGAREG_YDSTLEN + MGAREG_EXEC, ydstlen); + + FB_AddBusySurface(dst); + + if (dst == this->screen) { + SDL_mutexV(hw_lock); + } + return (0); } -static int HWAccelBlit(SDL_Surface *src, SDL_Rect *srcrect, - SDL_Surface *dst, SDL_Rect *dstrect) +static int +HWAccelBlit(SDL_Surface * src, SDL_Rect * srcrect, + SDL_Surface * dst, SDL_Rect * dstrect) { - SDL_VideoDevice *this = current_video; - int pitch, w, h; - int srcX, srcY; - int dstX, dstY; - Uint32 sign; - Uint32 start, stop; - int skip; - Uint32 blitop; - - /* FIXME: For now, only blit to display surface */ - if ( dst->pitch != SDL_VideoSurface->pitch ) { - return(src->map->sw_blit(src, srcrect, dst, dstrect)); - } - - /* Don't blit to the display surface when switched away */ - if ( switched_away ) { - return -2; /* no hardware access */ - } - if ( dst == this->screen ) { - SDL_mutexP(hw_lock); - } - - /* Calculate source and destination base coordinates (in pixels) */ - w = dstrect->w; - h = dstrect->h; - FB_dst_to_xy(this, src, &srcX, &srcY); - FB_dst_to_xy(this, dst, &dstX, &dstY); - - /* Adjust for the current blit rectangles */ - srcX += srcrect->x; - srcY += srcrect->y; - dstX += dstrect->x; - dstY += dstrect->y; - pitch = dst->pitch/dst->format->BytesPerPixel; - - /* Set up the blit direction (sign) flags */ - sign = 0; - if ( srcX < dstX ) { - sign |= 1; - } - if ( srcY < dstY ) { - sign |= 4; - srcY += (h - 1); - dstY += (h - 1); - } - - /* Set up the blit source row start, end, and skip (in pixels) */ - stop = start = (srcY * pitch) + srcX; - if ( srcX < dstX ) { - start += (w - 1); - } else { - stop += (w - 1); - } - if ( srcY < dstY ) { - skip = -pitch; - } else { - skip = pitch; - } - - /* Set up the blit operation */ - if ( (src->flags & SDL_SRCCOLORKEY) == SDL_SRCCOLORKEY ) { - Uint32 colorkey; - - blitop = MGADWG_BFCOL | MGADWG_BITBLT | - MGADWG_SHIFTZERO | MGADWG_RSTR | (0x0C << 16) | - MGADWG_TRANSC; - - colorkey = src->format->colorkey; - switch (dst->format->BytesPerPixel) { - case 1: - colorkey |= (colorkey<<8); - case 2: - colorkey |= (colorkey<<16); - break; - } - mga_wait(2); - mga_out32(MGAREG_FCOL, colorkey); - mga_out32(MGAREG_BCOL, 0xFFFFFFFF); - } else { - blitop = MGADWG_BFCOL | MGADWG_BITBLT | - MGADWG_SHIFTZERO | MGADWG_RSTR | (0x0C << 16); - } - mga_wait(7); - mga_out32(MGAREG_SGN, sign); - mga_out32(MGAREG_AR3, start); - mga_out32(MGAREG_AR0, stop); - mga_out32(MGAREG_AR5, skip); - mga_out32(MGAREG_FXBNDRY, (dstX | ((dstX + w-1) << 16))); - mga_out32(MGAREG_YDSTLEN, (dstY << 16) | h); - mga_out32(MGAREG_DWGCTL + MGAREG_EXEC, blitop); - - FB_AddBusySurface(src); - FB_AddBusySurface(dst); - - if ( dst == this->screen ) { - SDL_mutexV(hw_lock); - } - return(0); + SDL_VideoDevice *this = current_video; + int pitch, w, h; + int srcX, srcY; + int dstX, dstY; + Uint32 sign; + Uint32 start, stop; + int skip; + Uint32 blitop; + + /* FIXME: For now, only blit to display surface */ + if (dst->pitch != SDL_VideoSurface->pitch) { + return (src->map->sw_blit(src, srcrect, dst, dstrect)); + } + + /* Don't blit to the display surface when switched away */ + if (switched_away) { + return -2; /* no hardware access */ + } + if (dst == this->screen) { + SDL_mutexP(hw_lock); + } + + /* Calculate source and destination base coordinates (in pixels) */ + w = dstrect->w; + h = dstrect->h; + FB_dst_to_xy(this, src, &srcX, &srcY); + FB_dst_to_xy(this, dst, &dstX, &dstY); + + /* Adjust for the current blit rectangles */ + srcX += srcrect->x; + srcY += srcrect->y; + dstX += dstrect->x; + dstY += dstrect->y; + pitch = dst->pitch / dst->format->BytesPerPixel; + + /* Set up the blit direction (sign) flags */ + sign = 0; + if (srcX < dstX) { + sign |= 1; + } + if (srcY < dstY) { + sign |= 4; + srcY += (h - 1); + dstY += (h - 1); + } + + /* Set up the blit source row start, end, and skip (in pixels) */ + stop = start = (srcY * pitch) + srcX; + if (srcX < dstX) { + start += (w - 1); + } else { + stop += (w - 1); + } + if (srcY < dstY) { + skip = -pitch; + } else { + skip = pitch; + } + + /* Set up the blit operation */ + if ((src->flags & SDL_SRCCOLORKEY) == SDL_SRCCOLORKEY) { + Uint32 colorkey; + + blitop = MGADWG_BFCOL | MGADWG_BITBLT | + MGADWG_SHIFTZERO | MGADWG_RSTR | (0x0C << 16) | MGADWG_TRANSC; + + colorkey = src->format->colorkey; + switch (dst->format->BytesPerPixel) { + case 1: + colorkey |= (colorkey << 8); + case 2: + colorkey |= (colorkey << 16); + break; + } + mga_wait(2); + mga_out32(MGAREG_FCOL, colorkey); + mga_out32(MGAREG_BCOL, 0xFFFFFFFF); + } else { + blitop = MGADWG_BFCOL | MGADWG_BITBLT | + MGADWG_SHIFTZERO | MGADWG_RSTR | (0x0C << 16); + } + mga_wait(7); + mga_out32(MGAREG_SGN, sign); + mga_out32(MGAREG_AR3, start); + mga_out32(MGAREG_AR0, stop); + mga_out32(MGAREG_AR5, skip); + mga_out32(MGAREG_FXBNDRY, (dstX | ((dstX + w - 1) << 16))); + mga_out32(MGAREG_YDSTLEN, (dstY << 16) | h); + mga_out32(MGAREG_DWGCTL + MGAREG_EXEC, blitop); + + FB_AddBusySurface(src); + FB_AddBusySurface(dst); + + if (dst == this->screen) { + SDL_mutexV(hw_lock); + } + return (0); } -static int CheckHWBlit(_THIS, SDL_Surface *src, SDL_Surface *dst) +static int +CheckHWBlit(_THIS, SDL_Surface * src, SDL_Surface * dst) { - int accelerated; - - /* Set initial acceleration on */ - src->flags |= SDL_HWACCEL; - - /* Set the surface attributes */ - if ( (src->flags & SDL_SRCALPHA) == SDL_SRCALPHA ) { - if ( ! this->info.blit_hw_A ) { - src->flags &= ~SDL_HWACCEL; - } - } - if ( (src->flags & SDL_SRCCOLORKEY) == SDL_SRCCOLORKEY ) { - if ( ! this->info.blit_hw_CC ) { - src->flags &= ~SDL_HWACCEL; - } - } - - /* Check to see if final surface blit is accelerated */ - accelerated = !!(src->flags & SDL_HWACCEL); - if ( accelerated ) { - src->map->hw_blit = HWAccelBlit; - } - return(accelerated); + int accelerated; + + /* Set initial acceleration on */ + src->flags |= SDL_HWACCEL; + + /* Set the surface attributes */ + if ((src->flags & SDL_SRCALPHA) == SDL_SRCALPHA) { + if (!this->info.blit_hw_A) { + src->flags &= ~SDL_HWACCEL; + } + } + if ((src->flags & SDL_SRCCOLORKEY) == SDL_SRCCOLORKEY) { + if (!this->info.blit_hw_CC) { + src->flags &= ~SDL_HWACCEL; + } + } + + /* Check to see if final surface blit is accelerated */ + accelerated = !!(src->flags & SDL_HWACCEL); + if (accelerated) { + src->map->hw_blit = HWAccelBlit; + } + return (accelerated); } -void FB_MatroxAccel(_THIS, __u32 card) +void +FB_MatroxAccel(_THIS, __u32 card) { - /* We have hardware accelerated surface functions */ - this->CheckHWBlit = CheckHWBlit; - wait_vbl = WaitVBL; - wait_idle = WaitIdle; - - /* The Matrox has an accelerated color fill */ - this->info.blit_fill = 1; - this->FillHWRect = FillHWRect; - - /* The Matrox has accelerated normal and colorkey blits. */ - this->info.blit_hw = 1; - /* The Millenium I appears to do the colorkey test a word - at a time, and the transparency is intverted. (?) - */ - if ( card != FB_ACCEL_MATROX_MGA2064W ) { - this->info.blit_hw_CC = 1; - this->SetHWColorKey = SetHWColorKey; - } - -#if 0 /* Not yet implemented? */ - /* The Matrox G200/G400 has an accelerated alpha blit */ - if ( (card == FB_ACCEL_MATROX_MGAG200) - || (card == FB_ACCEL_MATROX_MGAG400) - ) { - this->info.blit_hw_A = 1; - this->SetHWAlpha = SetHWAlpha; - } + /* We have hardware accelerated surface functions */ + this->CheckHWBlit = CheckHWBlit; + wait_vbl = WaitVBL; + wait_idle = WaitIdle; + + /* The Matrox has an accelerated color fill */ + this->info.blit_fill = 1; + this->FillHWRect = FillHWRect; + + /* The Matrox has accelerated normal and colorkey blits. */ + this->info.blit_hw = 1; + /* The Millenium I appears to do the colorkey test a word + at a time, and the transparency is intverted. (?) + */ + if (card != FB_ACCEL_MATROX_MGA2064W) { + this->info.blit_hw_CC = 1; + this->SetHWColorKey = SetHWColorKey; + } +#if 0 /* Not yet implemented? */ + /* The Matrox G200/G400 has an accelerated alpha blit */ + if ((card == FB_ACCEL_MATROX_MGAG200) + || (card == FB_ACCEL_MATROX_MGAG400)) { + this->info.blit_hw_A = 1; + this->SetHWAlpha = SetHWAlpha; + } #endif } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/fbcon/SDL_fbmatrox.h b/src/video/fbcon/SDL_fbmatrox.h index 1721785a6..d7b116168 100644 --- a/src/video/fbcon/SDL_fbmatrox.h +++ b/src/video/fbcon/SDL_fbmatrox.h @@ -27,3 +27,4 @@ /* Set up the driver for Matrox acceleration */ extern void FB_MatroxAccel(_THIS, __u32 card); +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/fbcon/SDL_fbmouse.c b/src/video/fbcon/SDL_fbmouse.c index d2d30cdb8..b42efff7e 100644 --- a/src/video/fbcon/SDL_fbmouse.c +++ b/src/video/fbcon/SDL_fbmouse.c @@ -28,6 +28,8 @@ /* The implementation dependent data for the window manager cursor */ -struct WMcursor { - int unused; +struct WMcursor +{ + int unused; }; +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/fbcon/SDL_fbmouse_c.h b/src/video/fbcon/SDL_fbmouse_c.h index 4950f56f2..a015499f5 100644 --- a/src/video/fbcon/SDL_fbmouse_c.h +++ b/src/video/fbcon/SDL_fbmouse_c.h @@ -24,3 +24,4 @@ #include "SDL_fbvideo.h" /* Functions to be exported */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/fbcon/SDL_fbriva.c b/src/video/fbcon/SDL_fbriva.c index 1a712dce0..6c1044832 100644 --- a/src/video/fbcon/SDL_fbriva.c +++ b/src/video/fbcon/SDL_fbriva.c @@ -32,191 +32,198 @@ static int FifoEmptyCount = 0; static int FifoFreeCount = 0; /* Wait for vertical retrace */ -static void WaitVBL(_THIS) +static void +WaitVBL(_THIS) { - volatile Uint8 *port = (Uint8 *)(mapped_io + PCIO_OFFSET + 0x3DA); + volatile Uint8 *port = (Uint8 *) (mapped_io + PCIO_OFFSET + 0x3DA); - while ( (*port & 0x08) ) - ; - while ( !(*port & 0x08) ) - ; + while ((*port & 0x08)); + while (!(*port & 0x08)); } -static void NV3WaitIdle(_THIS) +static void +NV3WaitIdle(_THIS) { - RivaRop *Rop = (RivaRop *)(mapped_io + ROP_OFFSET); - while ( (Rop->FifoFree < FifoEmptyCount) || - (*(mapped_io + PGRAPH_OFFSET + 0x000006B0) & 0x01) ) - ; + RivaRop *Rop = (RivaRop *) (mapped_io + ROP_OFFSET); + while ((Rop->FifoFree < FifoEmptyCount) || + (*(mapped_io + PGRAPH_OFFSET + 0x000006B0) & 0x01)); } -static void NV4WaitIdle(_THIS) +static void +NV4WaitIdle(_THIS) { - RivaRop *Rop = (RivaRop *)(mapped_io + ROP_OFFSET); - while ( (Rop->FifoFree < FifoEmptyCount) || - (*(mapped_io + PGRAPH_OFFSET + 0x00000700) & 0x01) ) - ; + RivaRop *Rop = (RivaRop *) (mapped_io + ROP_OFFSET); + while ((Rop->FifoFree < FifoEmptyCount) || + (*(mapped_io + PGRAPH_OFFSET + 0x00000700) & 0x01)); } -#if 0 /* Not yet implemented? */ +#if 0 /* Not yet implemented? */ /* Sets video mem colorkey and accelerated blit function */ -static int SetHWColorKey(_THIS, SDL_Surface *surface, Uint32 key) +static int +SetHWColorKey(_THIS, SDL_Surface * surface, Uint32 key) { - return(0); + return (0); } /* Sets per surface hardware alpha value */ -static int SetHWAlpha(_THIS, SDL_Surface *surface, Uint8 value) +static int +SetHWAlpha(_THIS, SDL_Surface * surface, Uint8 value) { - return(0); + return (0); } #endif /* Not yet implemented */ -static int FillHWRect(_THIS, SDL_Surface *dst, SDL_Rect *rect, Uint32 color) +static int +FillHWRect(_THIS, SDL_Surface * dst, SDL_Rect * rect, Uint32 color) { - int dstX, dstY; - int dstW, dstH; - RivaBitmap *Bitmap = (RivaBitmap *)(mapped_io + BITMAP_OFFSET); - - /* Don't blit to the display surface when switched away */ - if ( switched_away ) { - return -2; /* no hardware access */ - } - if ( dst == this->screen ) { - SDL_mutexP(hw_lock); - } - - /* Set up the X/Y base coordinates */ - dstW = rect->w; - dstH = rect->h; - FB_dst_to_xy(this, dst, &dstX, &dstY); - - /* Adjust for the current rectangle */ - dstX += rect->x; - dstY += rect->y; - - RIVA_FIFO_FREE(Bitmap, 1); - Bitmap->Color1A = color; - - RIVA_FIFO_FREE(Bitmap, 2); - Bitmap->UnclippedRectangle[0].TopLeft = (dstX << 16) | dstY; - Bitmap->UnclippedRectangle[0].WidthHeight = (dstW << 16) | dstH; - - FB_AddBusySurface(dst); - - if ( dst == this->screen ) { - SDL_mutexV(hw_lock); - } - return(0); + int dstX, dstY; + int dstW, dstH; + RivaBitmap *Bitmap = (RivaBitmap *) (mapped_io + BITMAP_OFFSET); + + /* Don't blit to the display surface when switched away */ + if (switched_away) { + return -2; /* no hardware access */ + } + if (dst == this->screen) { + SDL_mutexP(hw_lock); + } + + /* Set up the X/Y base coordinates */ + dstW = rect->w; + dstH = rect->h; + FB_dst_to_xy(this, dst, &dstX, &dstY); + + /* Adjust for the current rectangle */ + dstX += rect->x; + dstY += rect->y; + + RIVA_FIFO_FREE(Bitmap, 1); + Bitmap->Color1A = color; + + RIVA_FIFO_FREE(Bitmap, 2); + Bitmap->UnclippedRectangle[0].TopLeft = (dstX << 16) | dstY; + Bitmap->UnclippedRectangle[0].WidthHeight = (dstW << 16) | dstH; + + FB_AddBusySurface(dst); + + if (dst == this->screen) { + SDL_mutexV(hw_lock); + } + return (0); } -static int HWAccelBlit(SDL_Surface *src, SDL_Rect *srcrect, - SDL_Surface *dst, SDL_Rect *dstrect) +static int +HWAccelBlit(SDL_Surface * src, SDL_Rect * srcrect, + SDL_Surface * dst, SDL_Rect * dstrect) { - SDL_VideoDevice *this = current_video; - int srcX, srcY; - int dstX, dstY; - int dstW, dstH; - RivaScreenBlt *Blt = (RivaScreenBlt *)(mapped_io + BLT_OFFSET); - - /* FIXME: For now, only blit to display surface */ - if ( dst->pitch != SDL_VideoSurface->pitch ) { - return(src->map->sw_blit(src, srcrect, dst, dstrect)); - } - - /* Don't blit to the display surface when switched away */ - if ( switched_away ) { - return -2; /* no hardware access */ - } - if ( dst == this->screen ) { - SDL_mutexP(hw_lock); - } - - /* Calculate source and destination base coordinates (in pixels) */ - dstW = dstrect->w; - dstH = dstrect->h; - FB_dst_to_xy(this, src, &srcX, &srcY); - FB_dst_to_xy(this, dst, &dstX, &dstY); - - /* Adjust for the current blit rectangles */ - srcX += srcrect->x; - srcY += srcrect->y; - dstX += dstrect->x; - dstY += dstrect->y; - - RIVA_FIFO_FREE(Blt, 3); - Blt->TopLeftSrc = (srcY << 16) | srcX; - Blt->TopLeftDst = (dstY << 16) | dstX; - Blt->WidthHeight = (dstH << 16) | dstW; - - FB_AddBusySurface(src); - FB_AddBusySurface(dst); - - if ( dst == this->screen ) { - SDL_mutexV(hw_lock); - } - return(0); + SDL_VideoDevice *this = current_video; + int srcX, srcY; + int dstX, dstY; + int dstW, dstH; + RivaScreenBlt *Blt = (RivaScreenBlt *) (mapped_io + BLT_OFFSET); + + /* FIXME: For now, only blit to display surface */ + if (dst->pitch != SDL_VideoSurface->pitch) { + return (src->map->sw_blit(src, srcrect, dst, dstrect)); + } + + /* Don't blit to the display surface when switched away */ + if (switched_away) { + return -2; /* no hardware access */ + } + if (dst == this->screen) { + SDL_mutexP(hw_lock); + } + + /* Calculate source and destination base coordinates (in pixels) */ + dstW = dstrect->w; + dstH = dstrect->h; + FB_dst_to_xy(this, src, &srcX, &srcY); + FB_dst_to_xy(this, dst, &dstX, &dstY); + + /* Adjust for the current blit rectangles */ + srcX += srcrect->x; + srcY += srcrect->y; + dstX += dstrect->x; + dstY += dstrect->y; + + RIVA_FIFO_FREE(Blt, 3); + Blt->TopLeftSrc = (srcY << 16) | srcX; + Blt->TopLeftDst = (dstY << 16) | dstX; + Blt->WidthHeight = (dstH << 16) | dstW; + + FB_AddBusySurface(src); + FB_AddBusySurface(dst); + + if (dst == this->screen) { + SDL_mutexV(hw_lock); + } + return (0); } -static int CheckHWBlit(_THIS, SDL_Surface *src, SDL_Surface *dst) +static int +CheckHWBlit(_THIS, SDL_Surface * src, SDL_Surface * dst) { - int accelerated; - - /* Set initial acceleration on */ - src->flags |= SDL_HWACCEL; - - /* Set the surface attributes */ - if ( (src->flags & SDL_SRCALPHA) == SDL_SRCALPHA ) { - if ( ! this->info.blit_hw_A ) { - src->flags &= ~SDL_HWACCEL; - } - } - if ( (src->flags & SDL_SRCCOLORKEY) == SDL_SRCCOLORKEY ) { - if ( ! this->info.blit_hw_CC ) { - src->flags &= ~SDL_HWACCEL; - } - } - - /* Check to see if final surface blit is accelerated */ - accelerated = !!(src->flags & SDL_HWACCEL); - if ( accelerated ) { - src->map->hw_blit = HWAccelBlit; - } - return(accelerated); + int accelerated; + + /* Set initial acceleration on */ + src->flags |= SDL_HWACCEL; + + /* Set the surface attributes */ + if ((src->flags & SDL_SRCALPHA) == SDL_SRCALPHA) { + if (!this->info.blit_hw_A) { + src->flags &= ~SDL_HWACCEL; + } + } + if ((src->flags & SDL_SRCCOLORKEY) == SDL_SRCCOLORKEY) { + if (!this->info.blit_hw_CC) { + src->flags &= ~SDL_HWACCEL; + } + } + + /* Check to see if final surface blit is accelerated */ + accelerated = !!(src->flags & SDL_HWACCEL); + if (accelerated) { + src->map->hw_blit = HWAccelBlit; + } + return (accelerated); } -void FB_RivaAccel(_THIS, __u32 card) +void +FB_RivaAccel(_THIS, __u32 card) { - RivaRop *Rop = (RivaRop *)(mapped_io + ROP_OFFSET); - - /* We have hardware accelerated surface functions */ - this->CheckHWBlit = CheckHWBlit; - wait_vbl = WaitVBL; - switch (card) { - case FB_ACCEL_NV3: - wait_idle = NV3WaitIdle; - break; - case FB_ACCEL_NV4: - wait_idle = NV4WaitIdle; - break; - default: - /* Hmm... FIXME */ - break; - } - FifoEmptyCount = Rop->FifoFree; - - /* The Riva has an accelerated color fill */ - this->info.blit_fill = 1; - this->FillHWRect = FillHWRect; - - /* The Riva has accelerated normal and colorkey blits. */ - this->info.blit_hw = 1; -#if 0 /* Not yet implemented? */ - this->info.blit_hw_CC = 1; - this->SetHWColorKey = SetHWColorKey; + RivaRop *Rop = (RivaRop *) (mapped_io + ROP_OFFSET); + + /* We have hardware accelerated surface functions */ + this->CheckHWBlit = CheckHWBlit; + wait_vbl = WaitVBL; + switch (card) { + case FB_ACCEL_NV3: + wait_idle = NV3WaitIdle; + break; + case FB_ACCEL_NV4: + wait_idle = NV4WaitIdle; + break; + default: + /* Hmm... FIXME */ + break; + } + FifoEmptyCount = Rop->FifoFree; + + /* The Riva has an accelerated color fill */ + this->info.blit_fill = 1; + this->FillHWRect = FillHWRect; + + /* The Riva has accelerated normal and colorkey blits. */ + this->info.blit_hw = 1; +#if 0 /* Not yet implemented? */ + this->info.blit_hw_CC = 1; + this->SetHWColorKey = SetHWColorKey; #endif -#if 0 /* Not yet implemented? */ - /* The Riva has an accelerated alpha blit */ - this->info.blit_hw_A = 1; - this->SetHWAlpha = SetHWAlpha; +#if 0 /* Not yet implemented? */ + /* The Riva has an accelerated alpha blit */ + this->info.blit_hw_A = 1; + this->SetHWAlpha = SetHWAlpha; #endif } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/fbcon/SDL_fbriva.h b/src/video/fbcon/SDL_fbriva.h index 9ccc4707e..5068371c0 100644 --- a/src/video/fbcon/SDL_fbriva.h +++ b/src/video/fbcon/SDL_fbriva.h @@ -34,3 +34,4 @@ /* Set up the driver for Riva acceleration */ extern void FB_RivaAccel(_THIS, __u32 card); +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/fbcon/SDL_fbvideo.c b/src/video/fbcon/SDL_fbvideo.c index 2d97bcbeb..46930d6cc 100644 --- a/src/video/fbcon/SDL_fbvideo.c +++ b/src/video/fbcon/SDL_fbvideo.c @@ -29,7 +29,7 @@ #include #include #include -#include /* For definition of PAGE_SIZE */ +#include /* For definition of PAGE_SIZE */ #include #include "SDL_video.h" @@ -48,7 +48,7 @@ #if defined(i386) && defined(FB_TYPE_VGA_PLANES) #define VGA16_FBCON_SUPPORT -#include /* For ioperm() */ +#include /* For ioperm() */ #ifndef FB_AUX_VGA_PLANES_VGA4 #define FB_AUX_VGA_PLANES_VGA4 0 #endif @@ -62,1259 +62,1327 @@ static inline void outb (unsigned char value, unsigned short port) /* A list of video resolutions that we query for (sorted largest to smallest) */ static const SDL_Rect checkres[] = { - { 0, 0, 1600, 1200 }, /* 16 bpp: 0x11E, or 286 */ - { 0, 0, 1408, 1056 }, /* 16 bpp: 0x19A, or 410 */ - { 0, 0, 1280, 1024 }, /* 16 bpp: 0x11A, or 282 */ - { 0, 0, 1152, 864 }, /* 16 bpp: 0x192, or 402 */ - { 0, 0, 1024, 768 }, /* 16 bpp: 0x117, or 279 */ - { 0, 0, 960, 720 }, /* 16 bpp: 0x18A, or 394 */ - { 0, 0, 800, 600 }, /* 16 bpp: 0x114, or 276 */ - { 0, 0, 768, 576 }, /* 16 bpp: 0x182, or 386 */ - { 0, 0, 720, 576 }, /* PAL */ - { 0, 0, 720, 480 }, /* NTSC */ - { 0, 0, 640, 480 }, /* 16 bpp: 0x111, or 273 */ - { 0, 0, 640, 400 }, /* 8 bpp: 0x100, or 256 */ - { 0, 0, 512, 384 }, - { 0, 0, 320, 240 }, - { 0, 0, 320, 200 } + {0, 0, 1600, 1200}, /* 16 bpp: 0x11E, or 286 */ + {0, 0, 1408, 1056}, /* 16 bpp: 0x19A, or 410 */ + {0, 0, 1280, 1024}, /* 16 bpp: 0x11A, or 282 */ + {0, 0, 1152, 864}, /* 16 bpp: 0x192, or 402 */ + {0, 0, 1024, 768}, /* 16 bpp: 0x117, or 279 */ + {0, 0, 960, 720}, /* 16 bpp: 0x18A, or 394 */ + {0, 0, 800, 600}, /* 16 bpp: 0x114, or 276 */ + {0, 0, 768, 576}, /* 16 bpp: 0x182, or 386 */ + {0, 0, 720, 576}, /* PAL */ + {0, 0, 720, 480}, /* NTSC */ + {0, 0, 640, 480}, /* 16 bpp: 0x111, or 273 */ + {0, 0, 640, 400}, /* 8 bpp: 0x100, or 256 */ + {0, 0, 512, 384}, + {0, 0, 320, 240}, + {0, 0, 320, 200} }; -static const struct { - int xres; - int yres; - int pixclock; - int left; - int right; - int upper; - int lower; - int hslen; - int vslen; - int sync; - int vmode; +static const struct +{ + int xres; + int yres; + int pixclock; + int left; + int right; + int upper; + int lower; + int hslen; + int vslen; + int sync; + int vmode; } vesa_timings[] = { -#ifdef USE_VESA_TIMINGS /* Only tested on Matrox Millenium I */ - { 640, 400, 39771, 48, 16, 39, 8, 96, 2, 2, 0 }, /* 70 Hz */ - { 640, 480, 39683, 48, 16, 33, 10, 96, 2, 0, 0 }, /* 60 Hz */ - { 768, 576, 26101, 144, 16, 28, 6, 112, 4, 0, 0 }, /* 60 Hz */ - { 800, 600, 24038, 144, 24, 28, 8, 112, 6, 0, 0 }, /* 60 Hz */ - { 960, 720, 17686, 144, 24, 28, 8, 112, 4, 0, 0 }, /* 60 Hz */ - { 1024, 768, 15386, 160, 32, 30, 4, 128, 4, 0, 0 }, /* 60 Hz */ - { 1152, 864, 12286, 192, 32, 30, 4, 128, 4, 0, 0 }, /* 60 Hz */ - { 1280, 1024, 9369, 224, 32, 32, 4, 136, 4, 0, 0 }, /* 60 Hz */ - { 1408, 1056, 8214, 256, 40, 32, 5, 144, 5, 0, 0 }, /* 60 Hz */ - { 1600, 1200,/*?*/0, 272, 48, 32, 5, 152, 5, 0, 0 }, /* 60 Hz */ +#ifdef USE_VESA_TIMINGS /* Only tested on Matrox Millenium I */ + { + 640, 400, 39771, 48, 16, 39, 8, 96, 2, 2, 0}, /* 70 Hz */ + { + 640, 480, 39683, 48, 16, 33, 10, 96, 2, 0, 0}, /* 60 Hz */ + { + 768, 576, 26101, 144, 16, 28, 6, 112, 4, 0, 0}, /* 60 Hz */ + { + 800, 600, 24038, 144, 24, 28, 8, 112, 6, 0, 0}, /* 60 Hz */ + { + 960, 720, 17686, 144, 24, 28, 8, 112, 4, 0, 0}, /* 60 Hz */ + { + 1024, 768, 15386, 160, 32, 30, 4, 128, 4, 0, 0}, /* 60 Hz */ + { + 1152, 864, 12286, 192, 32, 30, 4, 128, 4, 0, 0}, /* 60 Hz */ + { + 1280, 1024, 9369, 224, 32, 32, 4, 136, 4, 0, 0}, /* 60 Hz */ + { + 1408, 1056, 8214, 256, 40, 32, 5, 144, 5, 0, 0}, /* 60 Hz */ + { + 1600, 1200, /*? */ 0, 272, 48, 32, 5, 152, 5, 0, 0}, /* 60 Hz */ #else - /* You can generate these timings from your XF86Config file using - the 'modeline2fb' perl script included with the fbset package. - These timings were generated for Matrox Millenium I, 15" monitor. - */ - { 320, 200, 79440, 16, 16, 20, 4, 48, 1, 0, 2 }, /* 70 Hz */ - { 320, 240, 63492, 16, 16, 16, 4, 48, 2, 0, 2 }, /* 72 Hz */ - { 512, 384, 49603, 48, 16, 16, 1, 64, 3, 0, 0 }, /* 78 Hz */ - { 640, 400, 31746, 96, 32, 41, 1, 64, 3, 2, 0 }, /* 85 Hz */ - { 640, 480, 31746, 120, 16, 16, 1, 64, 3, 0, 0 }, /* 75 Hz */ - { 768, 576, 26101, 144, 16, 28, 6, 112, 4, 0, 0 }, /* 60 Hz */ - { 800, 600, 20000, 64, 56, 23, 37, 120, 6, 3, 0 }, /* 72 Hz */ - { 960, 720, 17686, 144, 24, 28, 8, 112, 4, 0, 0 }, /* 60 Hz */ - { 1024, 768, 13333, 144, 24, 29, 3, 136, 6, 0, 0 }, /* 70 Hz */ - { 1152, 864, 12286, 192, 32, 30, 4, 128, 4, 0, 0 }, /* 60 Hz */ - { 1280, 1024, 9369, 224, 32, 32, 4, 136, 4, 0, 0 }, /* 60 Hz */ - { 1408, 1056, 8214, 256, 40, 32, 5, 144, 5, 0, 0 }, /* 60 Hz */ - { 1600, 1200,/*?*/0, 272, 48, 32, 5, 152, 5, 0, 0 }, /* 60 Hz */ + /* You can generate these timings from your XF86Config file using + the 'modeline2fb' perl script included with the fbset package. + These timings were generated for Matrox Millenium I, 15" monitor. + */ + { + 320, 200, 79440, 16, 16, 20, 4, 48, 1, 0, 2}, /* 70 Hz */ + { + 320, 240, 63492, 16, 16, 16, 4, 48, 2, 0, 2}, /* 72 Hz */ + { + 512, 384, 49603, 48, 16, 16, 1, 64, 3, 0, 0}, /* 78 Hz */ + { + 640, 400, 31746, 96, 32, 41, 1, 64, 3, 2, 0}, /* 85 Hz */ + { + 640, 480, 31746, 120, 16, 16, 1, 64, 3, 0, 0}, /* 75 Hz */ + { + 768, 576, 26101, 144, 16, 28, 6, 112, 4, 0, 0}, /* 60 Hz */ + { + 800, 600, 20000, 64, 56, 23, 37, 120, 6, 3, 0}, /* 72 Hz */ + { + 960, 720, 17686, 144, 24, 28, 8, 112, 4, 0, 0}, /* 60 Hz */ + { + 1024, 768, 13333, 144, 24, 29, 3, 136, 6, 0, 0}, /* 70 Hz */ + { + 1152, 864, 12286, 192, 32, 30, 4, 128, 4, 0, 0}, /* 60 Hz */ + { + 1280, 1024, 9369, 224, 32, 32, 4, 136, 4, 0, 0}, /* 60 Hz */ + { + 1408, 1056, 8214, 256, 40, 32, 5, 144, 5, 0, 0}, /* 60 Hz */ + { + 1600, 1200, /*? */ 0, 272, 48, 32, 5, 152, 5, 0, 0}, /* 60 Hz */ #endif }; /* Initialization/Query functions */ -static int FB_VideoInit(_THIS, SDL_PixelFormat *vformat); -static SDL_Rect **FB_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags); -static SDL_Surface *FB_SetVideoMode(_THIS, SDL_Surface *current, int width, int height, int bpp, Uint32 flags); +static int FB_VideoInit(_THIS, SDL_PixelFormat * vformat); +static SDL_Rect **FB_ListModes(_THIS, SDL_PixelFormat * format, Uint32 flags); +static SDL_Surface *FB_SetVideoMode(_THIS, SDL_Surface * current, int width, + int height, int bpp, Uint32 flags); #ifdef VGA16_FBCON_SUPPORT -static SDL_Surface *FB_SetVGA16Mode(_THIS, SDL_Surface *current, int width, int height, int bpp, Uint32 flags); +static SDL_Surface *FB_SetVGA16Mode(_THIS, SDL_Surface * current, int width, + int height, int bpp, Uint32 flags); #endif -static int FB_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color *colors); +static int FB_SetColors(_THIS, int firstcolor, int ncolors, + SDL_Color * colors); static void FB_VideoQuit(_THIS); /* Hardware surface functions */ -static int FB_InitHWSurfaces(_THIS, SDL_Surface *screen, char *base, int size); +static int FB_InitHWSurfaces(_THIS, SDL_Surface * screen, char *base, + int size); static void FB_FreeHWSurfaces(_THIS); -static int FB_AllocHWSurface(_THIS, SDL_Surface *surface); -static int FB_LockHWSurface(_THIS, SDL_Surface *surface); -static void FB_UnlockHWSurface(_THIS, SDL_Surface *surface); -static void FB_FreeHWSurface(_THIS, SDL_Surface *surface); +static int FB_AllocHWSurface(_THIS, SDL_Surface * surface); +static int FB_LockHWSurface(_THIS, SDL_Surface * surface); +static void FB_UnlockHWSurface(_THIS, SDL_Surface * surface); +static void FB_FreeHWSurface(_THIS, SDL_Surface * surface); static void FB_WaitVBL(_THIS); static void FB_WaitIdle(_THIS); -static int FB_FlipHWSurface(_THIS, SDL_Surface *surface); +static int FB_FlipHWSurface(_THIS, SDL_Surface * surface); /* Internal palette functions */ static void FB_SavePalette(_THIS, struct fb_fix_screeninfo *finfo, - struct fb_var_screeninfo *vinfo); + struct fb_var_screeninfo *vinfo); static void FB_RestorePalette(_THIS); /* Small wrapper for mmap() so we can play nicely with no-mmu hosts * (non-mmu hosts disallow the MAP_SHARED flag) */ -static void *do_mmap(void *start, size_t length, int prot, int flags, int fd, off_t offset) +static void * +do_mmap(void *start, size_t length, int prot, int flags, int fd, off_t offset) { - void *ret; - ret = mmap(start, length, prot, flags, fd, offset); - if ( ret == (char *)-1 && (flags & MAP_SHARED) ) { - ret = mmap(start, length, prot, - (flags & ~MAP_SHARED) | MAP_PRIVATE, fd, offset); - } - return ret; + void *ret; + ret = mmap(start, length, prot, flags, fd, offset); + if (ret == (char *) -1 && (flags & MAP_SHARED)) { + ret = mmap(start, length, prot, + (flags & ~MAP_SHARED) | MAP_PRIVATE, fd, offset); + } + return ret; } /* FB driver bootstrap functions */ -static int FB_Available(void) +static int +FB_Available(void) { - int console = -1; - /* Added check for /fb/0 (devfs) */ - /* but - use environment variable first... if it fails, still check defaults */ - int idx = 0; - const char *SDL_fbdevs[4] = { NULL, "/dev/fb0", "/dev/fb/0", NULL }; - - SDL_fbdevs[0] = SDL_getenv("SDL_FBDEV"); - if( !SDL_fbdevs[0] ) - idx++; - for( ; SDL_fbdevs[idx]; idx++ ) - { - console = open(SDL_fbdevs[idx], O_RDWR, 0); - if ( console >= 0 ) { - close(console); - break; - } - } - return(console >= 0); + int console = -1; + /* Added check for /fb/0 (devfs) */ + /* but - use environment variable first... if it fails, still check defaults */ + int idx = 0; + const char *SDL_fbdevs[4] = { NULL, "/dev/fb0", "/dev/fb/0", NULL }; + + SDL_fbdevs[0] = SDL_getenv("SDL_FBDEV"); + if (!SDL_fbdevs[0]) + idx++; + for (; SDL_fbdevs[idx]; idx++) { + console = open(SDL_fbdevs[idx], O_RDWR, 0); + if (console >= 0) { + close(console); + break; + } + } + return (console >= 0); } -static void FB_DeleteDevice(SDL_VideoDevice *device) +static void +FB_DeleteDevice(SDL_VideoDevice * device) { - SDL_free(device->hidden); - SDL_free(device); + SDL_free(device->hidden); + SDL_free(device); } -static SDL_VideoDevice *FB_CreateDevice(int devindex) +static SDL_VideoDevice * +FB_CreateDevice(int devindex) { - SDL_VideoDevice *this; - - /* Initialize all variables that we clean on shutdown */ - this = (SDL_VideoDevice *)SDL_malloc(sizeof(SDL_VideoDevice)); - if ( this ) { - SDL_memset(this, 0, (sizeof *this)); - this->hidden = (struct SDL_PrivateVideoData *) - SDL_malloc((sizeof *this->hidden)); - } - if ( (this == NULL) || (this->hidden == NULL) ) { - SDL_OutOfMemory(); - if ( this ) { - SDL_free(this); - } - return(0); - } - SDL_memset(this->hidden, 0, (sizeof *this->hidden)); - wait_vbl = FB_WaitVBL; - wait_idle = FB_WaitIdle; - mouse_fd = -1; - keyboard_fd = -1; - - /* Set the function pointers */ - this->VideoInit = FB_VideoInit; - this->ListModes = FB_ListModes; - this->SetVideoMode = FB_SetVideoMode; - this->SetColors = FB_SetColors; - this->UpdateRects = NULL; - this->VideoQuit = FB_VideoQuit; - this->AllocHWSurface = FB_AllocHWSurface; - this->CheckHWBlit = NULL; - this->FillHWRect = NULL; - this->SetHWColorKey = NULL; - this->SetHWAlpha = NULL; - this->LockHWSurface = FB_LockHWSurface; - this->UnlockHWSurface = FB_UnlockHWSurface; - this->FlipHWSurface = FB_FlipHWSurface; - this->FreeHWSurface = FB_FreeHWSurface; - this->SetCaption = NULL; - this->SetIcon = NULL; - this->IconifyWindow = NULL; - this->GrabInput = NULL; - this->GetWMInfo = NULL; - this->InitOSKeymap = FB_InitOSKeymap; - this->PumpEvents = FB_PumpEvents; - - this->free = FB_DeleteDevice; - - return this; + SDL_VideoDevice *this; + + /* Initialize all variables that we clean on shutdown */ + this = (SDL_VideoDevice *) SDL_malloc(sizeof(SDL_VideoDevice)); + if (this) { + SDL_memset(this, 0, (sizeof *this)); + this->hidden = (struct SDL_PrivateVideoData *) + SDL_malloc((sizeof *this->hidden)); + } + if ((this == NULL) || (this->hidden == NULL)) { + SDL_OutOfMemory(); + if (this) { + SDL_free(this); + } + return (0); + } + SDL_memset(this->hidden, 0, (sizeof *this->hidden)); + wait_vbl = FB_WaitVBL; + wait_idle = FB_WaitIdle; + mouse_fd = -1; + keyboard_fd = -1; + + /* Set the function pointers */ + this->VideoInit = FB_VideoInit; + this->ListModes = FB_ListModes; + this->SetVideoMode = FB_SetVideoMode; + this->SetColors = FB_SetColors; + this->UpdateRects = NULL; + this->VideoQuit = FB_VideoQuit; + this->AllocHWSurface = FB_AllocHWSurface; + this->CheckHWBlit = NULL; + this->FillHWRect = NULL; + this->SetHWColorKey = NULL; + this->SetHWAlpha = NULL; + this->LockHWSurface = FB_LockHWSurface; + this->UnlockHWSurface = FB_UnlockHWSurface; + this->FlipHWSurface = FB_FlipHWSurface; + this->FreeHWSurface = FB_FreeHWSurface; + this->SetCaption = NULL; + this->SetIcon = NULL; + this->IconifyWindow = NULL; + this->GrabInput = NULL; + this->GetWMInfo = NULL; + this->InitOSKeymap = FB_InitOSKeymap; + this->PumpEvents = FB_PumpEvents; + + this->free = FB_DeleteDevice; + + return this; } VideoBootStrap FBCON_bootstrap = { - "fbcon", "Linux Framebuffer Console", - FB_Available, FB_CreateDevice + "fbcon", "Linux Framebuffer Console", + FB_Available, FB_CreateDevice }; #define FB_MODES_DB "/etc/fb.modes" -static int read_fbmodes_line(FILE*f, char* line, int length) +static int +read_fbmodes_line(FILE * f, char *line, int length) { - int blank; - char* c; - int i; - - blank=0; - /* find a relevant line */ - do - { - if (fgets(line,length,f)<=0) - return 0; - c=line; - while(((*c=='\t')||(*c==' '))&&(*c!=0)) - c++; - - if ((*c=='\n')||(*c=='#')||(*c==0)) - blank=1; - else - blank=0; - } - while(blank); - /* remove whitespace at the begining of the string */ - i=0; - do - { - line[i]=c[i]; - i++; - } - while(c[i]!=0); - return 1; + int blank; + char *c; + int i; + + blank = 0; + /* find a relevant line */ + do { + if (fgets(line, length, f) <= 0) + return 0; + c = line; + while (((*c == '\t') || (*c == ' ')) && (*c != 0)) + c++; + + if ((*c == '\n') || (*c == '#') || (*c == 0)) + blank = 1; + else + blank = 0; + } + while (blank); + /* remove whitespace at the begining of the string */ + i = 0; + do { + line[i] = c[i]; + i++; + } + while (c[i] != 0); + return 1; } -static int read_fbmodes_mode(FILE *f, struct fb_var_screeninfo *vinfo) +static int +read_fbmodes_mode(FILE * f, struct fb_var_screeninfo *vinfo) { - char line[1024]; - char option[256]; - - /* Find a "geometry" */ - do { - if (read_fbmodes_line(f, line, sizeof(line))==0) - return 0; - if (SDL_strncmp(line,"geometry",8)==0) - break; - } - while(1); - - SDL_sscanf(line, "geometry %d %d %d %d %d", &vinfo->xres, &vinfo->yres, - &vinfo->xres_virtual, &vinfo->yres_virtual, &vinfo->bits_per_pixel); - if (read_fbmodes_line(f, line, sizeof(line))==0) - return 0; - - SDL_sscanf(line, "timings %d %d %d %d %d %d %d", &vinfo->pixclock, - &vinfo->left_margin, &vinfo->right_margin, &vinfo->upper_margin, - &vinfo->lower_margin, &vinfo->hsync_len, &vinfo->vsync_len); - - vinfo->sync=0; - vinfo->vmode=FB_VMODE_NONINTERLACED; - - /* Parse misc options */ - do { - if (read_fbmodes_line(f, line, sizeof(line))==0) - return 0; - - if (SDL_strncmp(line,"hsync",5)==0) { - SDL_sscanf(line,"hsync %s",option); - if (SDL_strncmp(option,"high",4)==0) - vinfo->sync |= FB_SYNC_HOR_HIGH_ACT; - } - else if (SDL_strncmp(line,"vsync",5)==0) { - SDL_sscanf(line,"vsync %s",option); - if (SDL_strncmp(option,"high",4)==0) - vinfo->sync |= FB_SYNC_VERT_HIGH_ACT; - } - else if (SDL_strncmp(line,"csync",5)==0) { - SDL_sscanf(line,"csync %s",option); - if (SDL_strncmp(option,"high",4)==0) - vinfo->sync |= FB_SYNC_COMP_HIGH_ACT; - } - else if (SDL_strncmp(line,"extsync",5)==0) { - SDL_sscanf(line,"extsync %s",option); - if (SDL_strncmp(option,"true",4)==0) - vinfo->sync |= FB_SYNC_EXT; - } - else if (SDL_strncmp(line,"laced",5)==0) { - SDL_sscanf(line,"laced %s",option); - if (SDL_strncmp(option,"true",4)==0) - vinfo->vmode |= FB_VMODE_INTERLACED; - } - else if (SDL_strncmp(line,"double",6)==0) { - SDL_sscanf(line,"double %s",option); - if (SDL_strncmp(option,"true",4)==0) - vinfo->vmode |= FB_VMODE_DOUBLE; - } - } - while(SDL_strncmp(line,"endmode",7)!=0); - - return 1; + char line[1024]; + char option[256]; + + /* Find a "geometry" */ + do { + if (read_fbmodes_line(f, line, sizeof(line)) == 0) + return 0; + if (SDL_strncmp(line, "geometry", 8) == 0) + break; + } + while (1); + + SDL_sscanf(line, "geometry %d %d %d %d %d", &vinfo->xres, &vinfo->yres, + &vinfo->xres_virtual, &vinfo->yres_virtual, + &vinfo->bits_per_pixel); + if (read_fbmodes_line(f, line, sizeof(line)) == 0) + return 0; + + SDL_sscanf(line, "timings %d %d %d %d %d %d %d", &vinfo->pixclock, + &vinfo->left_margin, &vinfo->right_margin, + &vinfo->upper_margin, &vinfo->lower_margin, &vinfo->hsync_len, + &vinfo->vsync_len); + + vinfo->sync = 0; + vinfo->vmode = FB_VMODE_NONINTERLACED; + + /* Parse misc options */ + do { + if (read_fbmodes_line(f, line, sizeof(line)) == 0) + return 0; + + if (SDL_strncmp(line, "hsync", 5) == 0) { + SDL_sscanf(line, "hsync %s", option); + if (SDL_strncmp(option, "high", 4) == 0) + vinfo->sync |= FB_SYNC_HOR_HIGH_ACT; + } else if (SDL_strncmp(line, "vsync", 5) == 0) { + SDL_sscanf(line, "vsync %s", option); + if (SDL_strncmp(option, "high", 4) == 0) + vinfo->sync |= FB_SYNC_VERT_HIGH_ACT; + } else if (SDL_strncmp(line, "csync", 5) == 0) { + SDL_sscanf(line, "csync %s", option); + if (SDL_strncmp(option, "high", 4) == 0) + vinfo->sync |= FB_SYNC_COMP_HIGH_ACT; + } else if (SDL_strncmp(line, "extsync", 5) == 0) { + SDL_sscanf(line, "extsync %s", option); + if (SDL_strncmp(option, "true", 4) == 0) + vinfo->sync |= FB_SYNC_EXT; + } else if (SDL_strncmp(line, "laced", 5) == 0) { + SDL_sscanf(line, "laced %s", option); + if (SDL_strncmp(option, "true", 4) == 0) + vinfo->vmode |= FB_VMODE_INTERLACED; + } else if (SDL_strncmp(line, "double", 6) == 0) { + SDL_sscanf(line, "double %s", option); + if (SDL_strncmp(option, "true", 4) == 0) + vinfo->vmode |= FB_VMODE_DOUBLE; + } + } + while (SDL_strncmp(line, "endmode", 7) != 0); + + return 1; } -static int FB_CheckMode(_THIS, struct fb_var_screeninfo *vinfo, - int index, unsigned int *w, unsigned int *h) +static int +FB_CheckMode(_THIS, struct fb_var_screeninfo *vinfo, + int index, unsigned int *w, unsigned int *h) { - int mode_okay; - - mode_okay = 0; - vinfo->bits_per_pixel = (index+1)*8; - vinfo->xres = *w; - vinfo->xres_virtual = *w; - vinfo->yres = *h; - vinfo->yres_virtual = *h; - vinfo->activate = FB_ACTIVATE_TEST; - if ( ioctl(console_fd, FBIOPUT_VSCREENINFO, vinfo) == 0 ) { + int mode_okay; + + mode_okay = 0; + vinfo->bits_per_pixel = (index + 1) * 8; + vinfo->xres = *w; + vinfo->xres_virtual = *w; + vinfo->yres = *h; + vinfo->yres_virtual = *h; + vinfo->activate = FB_ACTIVATE_TEST; + if (ioctl(console_fd, FBIOPUT_VSCREENINFO, vinfo) == 0) { #ifdef FBCON_DEBUG - fprintf(stderr, "Checked mode %dx%d at %d bpp, got mode %dx%d at %d bpp\n", *w, *h, (index+1)*8, vinfo->xres, vinfo->yres, vinfo->bits_per_pixel); + fprintf(stderr, + "Checked mode %dx%d at %d bpp, got mode %dx%d at %d bpp\n", + *w, *h, (index + 1) * 8, vinfo->xres, vinfo->yres, + vinfo->bits_per_pixel); #endif - if ( (((vinfo->bits_per_pixel+7)/8)-1) == index ) { - *w = vinfo->xres; - *h = vinfo->yres; - mode_okay = 1; - } - } - return mode_okay; + if ((((vinfo->bits_per_pixel + 7) / 8) - 1) == index) { + *w = vinfo->xres; + *h = vinfo->yres; + mode_okay = 1; + } + } + return mode_okay; } -static int FB_AddMode(_THIS, int index, unsigned int w, unsigned int h, int check_timings) +static int +FB_AddMode(_THIS, int index, unsigned int w, unsigned int h, + int check_timings) { - SDL_Rect *mode; - int i; - int next_mode; - - /* Check to see if we already have this mode */ - if ( SDL_nummodes[index] > 0 ) { - mode = SDL_modelist[index][SDL_nummodes[index]-1]; - if ( (mode->w == w) && (mode->h == h) ) { + SDL_Rect *mode; + int i; + int next_mode; + + /* Check to see if we already have this mode */ + if (SDL_nummodes[index] > 0) { + mode = SDL_modelist[index][SDL_nummodes[index] - 1]; + if ((mode->w == w) && (mode->h == h)) { #ifdef FBCON_DEBUG - fprintf(stderr, "We already have mode %dx%d at %d bytes per pixel\n", w, h, index+1); + fprintf(stderr, + "We already have mode %dx%d at %d bytes per pixel\n", + w, h, index + 1); #endif - return(0); - } - } - - /* Only allow a mode if we have a valid timing for it */ - if ( check_timings ) { - int found_timing = 0; - for ( i=0; i<(sizeof(vesa_timings)/sizeof(vesa_timings[0])); ++i ) { - if ( (w == vesa_timings[i].xres) && - (h == vesa_timings[i].yres) && vesa_timings[i].pixclock ) { - found_timing = 1; - break; - } - } - if ( !found_timing ) { + return (0); + } + } + + /* Only allow a mode if we have a valid timing for it */ + if (check_timings) { + int found_timing = 0; + for (i = 0; i < (sizeof(vesa_timings) / sizeof(vesa_timings[0])); ++i) { + if ((w == vesa_timings[i].xres) && + (h == vesa_timings[i].yres) && vesa_timings[i].pixclock) { + found_timing = 1; + break; + } + } + if (!found_timing) { #ifdef FBCON_DEBUG - fprintf(stderr, "No valid timing line for mode %dx%d\n", w, h); + fprintf(stderr, "No valid timing line for mode %dx%d\n", w, h); #endif - return(0); - } - } - - /* Set up the new video mode rectangle */ - mode = (SDL_Rect *)SDL_malloc(sizeof *mode); - if ( mode == NULL ) { - SDL_OutOfMemory(); - return(-1); - } - mode->x = 0; - mode->y = 0; - mode->w = w; - mode->h = h; + return (0); + } + } + + /* Set up the new video mode rectangle */ + mode = (SDL_Rect *) SDL_malloc(sizeof *mode); + if (mode == NULL) { + SDL_OutOfMemory(); + return (-1); + } + mode->x = 0; + mode->y = 0; + mode->w = w; + mode->h = h; #ifdef FBCON_DEBUG - fprintf(stderr, "Adding mode %dx%d at %d bytes per pixel\n", w, h, index+1); + fprintf(stderr, "Adding mode %dx%d at %d bytes per pixel\n", w, h, + index + 1); #endif - /* Allocate the new list of modes, and fill in the new mode */ - next_mode = SDL_nummodes[index]; - SDL_modelist[index] = (SDL_Rect **) - SDL_realloc(SDL_modelist[index], (1+next_mode+1)*sizeof(SDL_Rect *)); - if ( SDL_modelist[index] == NULL ) { - SDL_OutOfMemory(); - SDL_nummodes[index] = 0; - SDL_free(mode); - return(-1); - } - SDL_modelist[index][next_mode] = mode; - SDL_modelist[index][next_mode+1] = NULL; - SDL_nummodes[index]++; - - return(0); + /* Allocate the new list of modes, and fill in the new mode */ + next_mode = SDL_nummodes[index]; + SDL_modelist[index] = (SDL_Rect **) + SDL_realloc(SDL_modelist[index], + (1 + next_mode + 1) * sizeof(SDL_Rect *)); + if (SDL_modelist[index] == NULL) { + SDL_OutOfMemory(); + SDL_nummodes[index] = 0; + SDL_free(mode); + return (-1); + } + SDL_modelist[index][next_mode] = mode; + SDL_modelist[index][next_mode + 1] = NULL; + SDL_nummodes[index]++; + + return (0); } -static int cmpmodes(const void *va, const void *vb) +static int +cmpmodes(const void *va, const void *vb) { - const SDL_Rect *a = *(const SDL_Rect**)va; - const SDL_Rect *b = *(const SDL_Rect**)vb; - if ( a->h == b->h ) + const SDL_Rect *a = *(const SDL_Rect **) va; + const SDL_Rect *b = *(const SDL_Rect **) vb; + if (a->h == b->h) return b->w - a->w; else return b->h - a->h; } -static void FB_SortModes(_THIS) +static void +FB_SortModes(_THIS) { - int i; - for ( i=0; i 0 ) { - SDL_qsort(SDL_modelist[i], SDL_nummodes[i], sizeof *SDL_modelist[i], cmpmodes); - } - } + int i; + for (i = 0; i < NUM_MODELISTS; ++i) { + if (SDL_nummodes[i] > 0) { + SDL_qsort(SDL_modelist[i], SDL_nummodes[i], + sizeof *SDL_modelist[i], cmpmodes); + } + } } -static int FB_VideoInit(_THIS, SDL_PixelFormat *vformat) +static int +FB_VideoInit(_THIS, SDL_PixelFormat * vformat) { - struct fb_fix_screeninfo finfo; - struct fb_var_screeninfo vinfo; - int i, j; - int current_index; - unsigned int current_w; - unsigned int current_h; - const char *SDL_fbdev; - FILE *modesdb; - - /* Initialize the library */ - SDL_fbdev = SDL_getenv("SDL_FBDEV"); - if ( SDL_fbdev == NULL ) { - SDL_fbdev = "/dev/fb0"; - } - console_fd = open(SDL_fbdev, O_RDWR, 0); - if ( console_fd < 0 ) { - SDL_SetError("Unable to open %s", SDL_fbdev); - return(-1); - } - + struct fb_fix_screeninfo finfo; + struct fb_var_screeninfo vinfo; + int i, j; + int current_index; + unsigned int current_w; + unsigned int current_h; + const char *SDL_fbdev; + FILE *modesdb; + + /* Initialize the library */ + SDL_fbdev = SDL_getenv("SDL_FBDEV"); + if (SDL_fbdev == NULL) { + SDL_fbdev = "/dev/fb0"; + } + console_fd = open(SDL_fbdev, O_RDWR, 0); + if (console_fd < 0) { + SDL_SetError("Unable to open %s", SDL_fbdev); + return (-1); + } #if !SDL_THREADS_DISABLED - /* Create the hardware surface lock mutex */ - hw_lock = SDL_CreateMutex(); - if ( hw_lock == NULL ) { - SDL_SetError("Unable to create lock mutex"); - FB_VideoQuit(this); - return(-1); - } + /* Create the hardware surface lock mutex */ + hw_lock = SDL_CreateMutex(); + if (hw_lock == NULL) { + SDL_SetError("Unable to create lock mutex"); + FB_VideoQuit(this); + return (-1); + } #endif - /* Get the type of video hardware */ - if ( ioctl(console_fd, FBIOGET_FSCREENINFO, &finfo) < 0 ) { - SDL_SetError("Couldn't get console hardware info"); - FB_VideoQuit(this); - return(-1); - } - switch (finfo.type) { - case FB_TYPE_PACKED_PIXELS: - /* Supported, no worries.. */ - break; + /* Get the type of video hardware */ + if (ioctl(console_fd, FBIOGET_FSCREENINFO, &finfo) < 0) { + SDL_SetError("Couldn't get console hardware info"); + FB_VideoQuit(this); + return (-1); + } + switch (finfo.type) { + case FB_TYPE_PACKED_PIXELS: + /* Supported, no worries.. */ + break; #ifdef VGA16_FBCON_SUPPORT - case FB_TYPE_VGA_PLANES: - /* VGA16 is supported, but that's it */ - if ( finfo.type_aux == FB_AUX_VGA_PLANES_VGA4 ) { - if ( ioperm(0x3b4, 0x3df - 0x3b4 + 1, 1) < 0 ) { - SDL_SetError("No I/O port permissions"); - FB_VideoQuit(this); - return(-1); - } - this->SetVideoMode = FB_SetVGA16Mode; - break; - } - /* Fall through to unsupported case */ + case FB_TYPE_VGA_PLANES: + /* VGA16 is supported, but that's it */ + if (finfo.type_aux == FB_AUX_VGA_PLANES_VGA4) { + if (ioperm(0x3b4, 0x3df - 0x3b4 + 1, 1) < 0) { + SDL_SetError("No I/O port permissions"); + FB_VideoQuit(this); + return (-1); + } + this->SetVideoMode = FB_SetVGA16Mode; + break; + } + /* Fall through to unsupported case */ #endif /* VGA16_FBCON_SUPPORT */ - default: - SDL_SetError("Unsupported console hardware"); - FB_VideoQuit(this); - return(-1); - } - switch (finfo.visual) { - case FB_VISUAL_TRUECOLOR: - case FB_VISUAL_PSEUDOCOLOR: - case FB_VISUAL_STATIC_PSEUDOCOLOR: - case FB_VISUAL_DIRECTCOLOR: - break; - default: - SDL_SetError("Unsupported console hardware"); - FB_VideoQuit(this); - return(-1); - } - - /* Check if the user wants to disable hardware acceleration */ - { const char *fb_accel; - fb_accel = SDL_getenv("SDL_FBACCEL"); - if ( fb_accel ) { - finfo.accel = SDL_atoi(fb_accel); - } - } - - /* Memory map the device, compensating for buggy PPC mmap() */ - mapped_offset = (((long)finfo.smem_start) - - (((long)finfo.smem_start)&~(PAGE_SIZE-1))); - mapped_memlen = finfo.smem_len+mapped_offset; - mapped_mem = do_mmap(NULL, mapped_memlen, - PROT_READ|PROT_WRITE, MAP_SHARED, console_fd, 0); - if ( mapped_mem == (char *)-1 ) { - SDL_SetError("Unable to memory map the video hardware"); - mapped_mem = NULL; - FB_VideoQuit(this); - return(-1); - } - - /* Determine the current screen depth */ - if ( ioctl(console_fd, FBIOGET_VSCREENINFO, &vinfo) < 0 ) { - SDL_SetError("Couldn't get console pixel format"); - FB_VideoQuit(this); - return(-1); - } - vformat->BitsPerPixel = vinfo.bits_per_pixel; - if ( vformat->BitsPerPixel < 8 ) { - /* Assuming VGA16, we handle this via a shadow framebuffer */ - vformat->BitsPerPixel = 8; - } - for ( i=0; iRmask <<= 1; - vformat->Rmask |= (0x00000001<Gmask <<= 1; - vformat->Gmask |= (0x00000001<Bmask <<= 1; - vformat->Bmask |= (0x00000001< w) || (current_h > h) ) { - /* Only check once */ - FB_AddMode(this, i, current_w, current_h, 0); - current_index = -1; - } - } - if ( FB_CheckMode(this, &vinfo, i, &w, &h) ) { - FB_AddMode(this, i, w, h, 0); - } - } - } - fclose(modesdb); - FB_SortModes(this); - } else { - for ( i=0; i w) || (current_h > h) ) { - /* Only check once */ - FB_AddMode(this, i, current_w, current_h, 0); - current_index = -1; - } - } - if ( FB_CheckMode(this, &vinfo, i, &w, &h) ) { - FB_AddMode(this, i, w, h, 1); - } - } - } - } - - /* Fill in our hardware acceleration capabilities */ - this->info.current_w = current_w; - this->info.current_h = current_h; - this->info.wm_available = 0; - this->info.hw_available = 1; - this->info.video_mem = finfo.smem_len/1024; - if ( mapped_io ) { - switch (finfo.accel) { - case FB_ACCEL_MATROX_MGA2064W: - case FB_ACCEL_MATROX_MGA1064SG: - case FB_ACCEL_MATROX_MGA2164W: - case FB_ACCEL_MATROX_MGA2164W_AGP: - case FB_ACCEL_MATROX_MGAG100: - /*case FB_ACCEL_MATROX_MGAG200: G200 acceleration broken! */ - case FB_ACCEL_MATROX_MGAG400: + default: + SDL_SetError("Unsupported console hardware"); + FB_VideoQuit(this); + return (-1); + } + switch (finfo.visual) { + case FB_VISUAL_TRUECOLOR: + case FB_VISUAL_PSEUDOCOLOR: + case FB_VISUAL_STATIC_PSEUDOCOLOR: + case FB_VISUAL_DIRECTCOLOR: + break; + default: + SDL_SetError("Unsupported console hardware"); + FB_VideoQuit(this); + return (-1); + } + + /* Check if the user wants to disable hardware acceleration */ + { + const char *fb_accel; + fb_accel = SDL_getenv("SDL_FBACCEL"); + if (fb_accel) { + finfo.accel = SDL_atoi(fb_accel); + } + } + + /* Memory map the device, compensating for buggy PPC mmap() */ + mapped_offset = (((long) finfo.smem_start) - + (((long) finfo.smem_start) & ~(PAGE_SIZE - 1))); + mapped_memlen = finfo.smem_len + mapped_offset; + mapped_mem = do_mmap(NULL, mapped_memlen, + PROT_READ | PROT_WRITE, MAP_SHARED, console_fd, 0); + if (mapped_mem == (char *) -1) { + SDL_SetError("Unable to memory map the video hardware"); + mapped_mem = NULL; + FB_VideoQuit(this); + return (-1); + } + + /* Determine the current screen depth */ + if (ioctl(console_fd, FBIOGET_VSCREENINFO, &vinfo) < 0) { + SDL_SetError("Couldn't get console pixel format"); + FB_VideoQuit(this); + return (-1); + } + vformat->BitsPerPixel = vinfo.bits_per_pixel; + if (vformat->BitsPerPixel < 8) { + /* Assuming VGA16, we handle this via a shadow framebuffer */ + vformat->BitsPerPixel = 8; + } + for (i = 0; i < vinfo.red.length; ++i) { + vformat->Rmask <<= 1; + vformat->Rmask |= (0x00000001 << vinfo.red.offset); + } + for (i = 0; i < vinfo.green.length; ++i) { + vformat->Gmask <<= 1; + vformat->Gmask |= (0x00000001 << vinfo.green.offset); + } + for (i = 0; i < vinfo.blue.length; ++i) { + vformat->Bmask <<= 1; + vformat->Bmask |= (0x00000001 << vinfo.blue.offset); + } + saved_vinfo = vinfo; + + /* Save hardware palette, if needed */ + FB_SavePalette(this, &finfo, &vinfo); + + /* If the I/O registers are available, memory map them so we + can take advantage of any supported hardware acceleration. + */ + vinfo.accel_flags = 0; /* Temporarily reserve registers */ + ioctl(console_fd, FBIOPUT_VSCREENINFO, &vinfo); + if (finfo.accel && finfo.mmio_len) { + mapped_iolen = finfo.mmio_len; + mapped_io = do_mmap(NULL, mapped_iolen, PROT_READ | PROT_WRITE, + MAP_SHARED, console_fd, mapped_memlen); + if (mapped_io == (char *) -1) { + /* Hmm, failed to memory map I/O registers */ + mapped_io = NULL; + } + } + + /* Query for the list of available video modes */ + current_w = vinfo.xres; + current_h = vinfo.yres; + current_index = ((vinfo.bits_per_pixel + 7) / 8) - 1; + modesdb = fopen(FB_MODES_DB, "r"); + for (i = 0; i < NUM_MODELISTS; ++i) { + SDL_nummodes[i] = 0; + SDL_modelist[i] = NULL; + } + if (SDL_getenv("SDL_FB_BROKEN_MODES") != NULL) { + FB_AddMode(this, current_index, current_w, current_h, 0); + } else if (modesdb) { + while (read_fbmodes_mode(modesdb, &vinfo)) { + for (i = 0; i < NUM_MODELISTS; ++i) { + unsigned int w, h; + + /* See if we are querying for the current mode */ + w = vinfo.xres; + h = vinfo.yres; + if (i == current_index) { + if ((current_w > w) || (current_h > h)) { + /* Only check once */ + FB_AddMode(this, i, current_w, current_h, 0); + current_index = -1; + } + } + if (FB_CheckMode(this, &vinfo, i, &w, &h)) { + FB_AddMode(this, i, w, h, 0); + } + } + } + fclose(modesdb); + FB_SortModes(this); + } else { + for (i = 0; i < NUM_MODELISTS; ++i) { + for (j = 0; j < (sizeof(checkres) / sizeof(checkres[0])); ++j) { + unsigned int w, h; + + /* See if we are querying for the current mode */ + w = checkres[j].w; + h = checkres[j].h; + if (i == current_index) { + if ((current_w > w) || (current_h > h)) { + /* Only check once */ + FB_AddMode(this, i, current_w, current_h, 0); + current_index = -1; + } + } + if (FB_CheckMode(this, &vinfo, i, &w, &h)) { + FB_AddMode(this, i, w, h, 1); + } + } + } + } + + /* Fill in our hardware acceleration capabilities */ + this->info.current_w = current_w; + this->info.current_h = current_h; + this->info.wm_available = 0; + this->info.hw_available = 1; + this->info.video_mem = finfo.smem_len / 1024; + if (mapped_io) { + switch (finfo.accel) { + case FB_ACCEL_MATROX_MGA2064W: + case FB_ACCEL_MATROX_MGA1064SG: + case FB_ACCEL_MATROX_MGA2164W: + case FB_ACCEL_MATROX_MGA2164W_AGP: + case FB_ACCEL_MATROX_MGAG100: + /*case FB_ACCEL_MATROX_MGAG200: G200 acceleration broken! */ + case FB_ACCEL_MATROX_MGAG400: #ifdef FBACCEL_DEBUG - printf("Matrox hardware accelerator!\n"); + printf("Matrox hardware accelerator!\n"); #endif - FB_MatroxAccel(this, finfo.accel); - break; - case FB_ACCEL_3DFX_BANSHEE: + FB_MatroxAccel(this, finfo.accel); + break; + case FB_ACCEL_3DFX_BANSHEE: #ifdef FBACCEL_DEBUG - printf("3DFX hardware accelerator!\n"); + printf("3DFX hardware accelerator!\n"); #endif - FB_3DfxAccel(this, finfo.accel); - break; - case FB_ACCEL_NV3: - case FB_ACCEL_NV4: + FB_3DfxAccel(this, finfo.accel); + break; + case FB_ACCEL_NV3: + case FB_ACCEL_NV4: #ifdef FBACCEL_DEBUG - printf("NVidia hardware accelerator!\n"); + printf("NVidia hardware accelerator!\n"); #endif - FB_RivaAccel(this, finfo.accel); - break; - default: + FB_RivaAccel(this, finfo.accel); + break; + default: #ifdef FBACCEL_DEBUG - printf("Unknown hardware accelerator.\n"); + printf("Unknown hardware accelerator.\n"); #endif - break; - } - } - - /* Enable mouse and keyboard support */ - if ( FB_OpenKeyboard(this) < 0 ) { - FB_VideoQuit(this); - return(-1); - } - if ( FB_OpenMouse(this) < 0 ) { - const char *sdl_nomouse; - - sdl_nomouse = SDL_getenv("SDL_NOMOUSE"); - if ( ! sdl_nomouse ) { - SDL_SetError("Unable to open mouse"); - FB_VideoQuit(this); - return(-1); - } - } - - /* We're done! */ - return(0); + break; + } + } + + /* Enable mouse and keyboard support */ + if (FB_OpenKeyboard(this) < 0) { + FB_VideoQuit(this); + return (-1); + } + if (FB_OpenMouse(this) < 0) { + const char *sdl_nomouse; + + sdl_nomouse = SDL_getenv("SDL_NOMOUSE"); + if (!sdl_nomouse) { + SDL_SetError("Unable to open mouse"); + FB_VideoQuit(this); + return (-1); + } + } + + /* We're done! */ + return (0); } -static SDL_Rect **FB_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags) +static SDL_Rect ** +FB_ListModes(_THIS, SDL_PixelFormat * format, Uint32 flags) { - return(SDL_modelist[((format->BitsPerPixel+7)/8)-1]); + return (SDL_modelist[((format->BitsPerPixel + 7) / 8) - 1]); } /* Various screen update functions available */ -static void FB_DirectUpdate(_THIS, int numrects, SDL_Rect *rects); +static void FB_DirectUpdate(_THIS, int numrects, SDL_Rect * rects); #ifdef VGA16_FBCON_SUPPORT -static void FB_VGA16Update(_THIS, int numrects, SDL_Rect *rects); +static void FB_VGA16Update(_THIS, int numrects, SDL_Rect * rects); #endif #ifdef FBCON_DEBUG -static void print_vinfo(struct fb_var_screeninfo *vinfo) +static void +print_vinfo(struct fb_var_screeninfo *vinfo) { - fprintf(stderr, "Printing vinfo:\n"); - fprintf(stderr, "\txres: %d\n", vinfo->xres); - fprintf(stderr, "\tyres: %d\n", vinfo->yres); - fprintf(stderr, "\txres_virtual: %d\n", vinfo->xres_virtual); - fprintf(stderr, "\tyres_virtual: %d\n", vinfo->yres_virtual); - fprintf(stderr, "\txoffset: %d\n", vinfo->xoffset); - fprintf(stderr, "\tyoffset: %d\n", vinfo->yoffset); - fprintf(stderr, "\tbits_per_pixel: %d\n", vinfo->bits_per_pixel); - fprintf(stderr, "\tgrayscale: %d\n", vinfo->grayscale); - fprintf(stderr, "\tnonstd: %d\n", vinfo->nonstd); - fprintf(stderr, "\tactivate: %d\n", vinfo->activate); - fprintf(stderr, "\theight: %d\n", vinfo->height); - fprintf(stderr, "\twidth: %d\n", vinfo->width); - fprintf(stderr, "\taccel_flags: %d\n", vinfo->accel_flags); - fprintf(stderr, "\tpixclock: %d\n", vinfo->pixclock); - fprintf(stderr, "\tleft_margin: %d\n", vinfo->left_margin); - fprintf(stderr, "\tright_margin: %d\n", vinfo->right_margin); - fprintf(stderr, "\tupper_margin: %d\n", vinfo->upper_margin); - fprintf(stderr, "\tlower_margin: %d\n", vinfo->lower_margin); - fprintf(stderr, "\thsync_len: %d\n", vinfo->hsync_len); - fprintf(stderr, "\tvsync_len: %d\n", vinfo->vsync_len); - fprintf(stderr, "\tsync: %d\n", vinfo->sync); - fprintf(stderr, "\tvmode: %d\n", vinfo->vmode); - fprintf(stderr, "\tred: %d/%d\n", vinfo->red.length, vinfo->red.offset); - fprintf(stderr, "\tgreen: %d/%d\n", vinfo->green.length, vinfo->green.offset); - fprintf(stderr, "\tblue: %d/%d\n", vinfo->blue.length, vinfo->blue.offset); - fprintf(stderr, "\talpha: %d/%d\n", vinfo->transp.length, vinfo->transp.offset); + fprintf(stderr, "Printing vinfo:\n"); + fprintf(stderr, "\txres: %d\n", vinfo->xres); + fprintf(stderr, "\tyres: %d\n", vinfo->yres); + fprintf(stderr, "\txres_virtual: %d\n", vinfo->xres_virtual); + fprintf(stderr, "\tyres_virtual: %d\n", vinfo->yres_virtual); + fprintf(stderr, "\txoffset: %d\n", vinfo->xoffset); + fprintf(stderr, "\tyoffset: %d\n", vinfo->yoffset); + fprintf(stderr, "\tbits_per_pixel: %d\n", vinfo->bits_per_pixel); + fprintf(stderr, "\tgrayscale: %d\n", vinfo->grayscale); + fprintf(stderr, "\tnonstd: %d\n", vinfo->nonstd); + fprintf(stderr, "\tactivate: %d\n", vinfo->activate); + fprintf(stderr, "\theight: %d\n", vinfo->height); + fprintf(stderr, "\twidth: %d\n", vinfo->width); + fprintf(stderr, "\taccel_flags: %d\n", vinfo->accel_flags); + fprintf(stderr, "\tpixclock: %d\n", vinfo->pixclock); + fprintf(stderr, "\tleft_margin: %d\n", vinfo->left_margin); + fprintf(stderr, "\tright_margin: %d\n", vinfo->right_margin); + fprintf(stderr, "\tupper_margin: %d\n", vinfo->upper_margin); + fprintf(stderr, "\tlower_margin: %d\n", vinfo->lower_margin); + fprintf(stderr, "\thsync_len: %d\n", vinfo->hsync_len); + fprintf(stderr, "\tvsync_len: %d\n", vinfo->vsync_len); + fprintf(stderr, "\tsync: %d\n", vinfo->sync); + fprintf(stderr, "\tvmode: %d\n", vinfo->vmode); + fprintf(stderr, "\tred: %d/%d\n", vinfo->red.length, vinfo->red.offset); + fprintf(stderr, "\tgreen: %d/%d\n", vinfo->green.length, + vinfo->green.offset); + fprintf(stderr, "\tblue: %d/%d\n", vinfo->blue.length, + vinfo->blue.offset); + fprintf(stderr, "\talpha: %d/%d\n", vinfo->transp.length, + vinfo->transp.offset); } -static void print_finfo(struct fb_fix_screeninfo *finfo) +static void +print_finfo(struct fb_fix_screeninfo *finfo) { - fprintf(stderr, "Printing finfo:\n"); - fprintf(stderr, "\tsmem_start = %p\n", (char *)finfo->smem_start); - fprintf(stderr, "\tsmem_len = %d\n", finfo->smem_len); - fprintf(stderr, "\ttype = %d\n", finfo->type); - fprintf(stderr, "\ttype_aux = %d\n", finfo->type_aux); - fprintf(stderr, "\tvisual = %d\n", finfo->visual); - fprintf(stderr, "\txpanstep = %d\n", finfo->xpanstep); - fprintf(stderr, "\typanstep = %d\n", finfo->ypanstep); - fprintf(stderr, "\tywrapstep = %d\n", finfo->ywrapstep); - fprintf(stderr, "\tline_length = %d\n", finfo->line_length); - fprintf(stderr, "\tmmio_start = %p\n", (char *)finfo->mmio_start); - fprintf(stderr, "\tmmio_len = %d\n", finfo->mmio_len); - fprintf(stderr, "\taccel = %d\n", finfo->accel); + fprintf(stderr, "Printing finfo:\n"); + fprintf(stderr, "\tsmem_start = %p\n", (char *) finfo->smem_start); + fprintf(stderr, "\tsmem_len = %d\n", finfo->smem_len); + fprintf(stderr, "\ttype = %d\n", finfo->type); + fprintf(stderr, "\ttype_aux = %d\n", finfo->type_aux); + fprintf(stderr, "\tvisual = %d\n", finfo->visual); + fprintf(stderr, "\txpanstep = %d\n", finfo->xpanstep); + fprintf(stderr, "\typanstep = %d\n", finfo->ypanstep); + fprintf(stderr, "\tywrapstep = %d\n", finfo->ywrapstep); + fprintf(stderr, "\tline_length = %d\n", finfo->line_length); + fprintf(stderr, "\tmmio_start = %p\n", (char *) finfo->mmio_start); + fprintf(stderr, "\tmmio_len = %d\n", finfo->mmio_len); + fprintf(stderr, "\taccel = %d\n", finfo->accel); } #endif -static int choose_fbmodes_mode(struct fb_var_screeninfo *vinfo) +static int +choose_fbmodes_mode(struct fb_var_screeninfo *vinfo) { - int matched; - FILE *modesdb; - struct fb_var_screeninfo cinfo; - - matched = 0; - modesdb = fopen(FB_MODES_DB, "r"); - if ( modesdb ) { - /* Parse the mode definition file */ - while ( read_fbmodes_mode(modesdb, &cinfo) ) { - if ( (vinfo->xres == cinfo.xres && vinfo->yres == cinfo.yres) && - (!matched || (vinfo->bits_per_pixel == cinfo.bits_per_pixel)) ) { - vinfo->pixclock = cinfo.pixclock; - vinfo->left_margin = cinfo.left_margin; - vinfo->right_margin = cinfo.right_margin; - vinfo->upper_margin = cinfo.upper_margin; - vinfo->lower_margin = cinfo.lower_margin; - vinfo->hsync_len = cinfo.hsync_len; - vinfo->vsync_len = cinfo.vsync_len; - if ( matched ) { - break; - } - matched = 1; - } - } - fclose(modesdb); - } - return(matched); + int matched; + FILE *modesdb; + struct fb_var_screeninfo cinfo; + + matched = 0; + modesdb = fopen(FB_MODES_DB, "r"); + if (modesdb) { + /* Parse the mode definition file */ + while (read_fbmodes_mode(modesdb, &cinfo)) { + if ((vinfo->xres == cinfo.xres && vinfo->yres == cinfo.yres) + && (!matched + || (vinfo->bits_per_pixel == cinfo.bits_per_pixel))) { + vinfo->pixclock = cinfo.pixclock; + vinfo->left_margin = cinfo.left_margin; + vinfo->right_margin = cinfo.right_margin; + vinfo->upper_margin = cinfo.upper_margin; + vinfo->lower_margin = cinfo.lower_margin; + vinfo->hsync_len = cinfo.hsync_len; + vinfo->vsync_len = cinfo.vsync_len; + if (matched) { + break; + } + matched = 1; + } + } + fclose(modesdb); + } + return (matched); } -static int choose_vesa_mode(struct fb_var_screeninfo *vinfo) +static int +choose_vesa_mode(struct fb_var_screeninfo *vinfo) { - int matched; - int i; - - /* Check for VESA timings */ - matched = 0; - for ( i=0; i<(sizeof(vesa_timings)/sizeof(vesa_timings[0])); ++i ) { - if ( (vinfo->xres == vesa_timings[i].xres) && - (vinfo->yres == vesa_timings[i].yres) ) { + int matched; + int i; + + /* Check for VESA timings */ + matched = 0; + for (i = 0; i < (sizeof(vesa_timings) / sizeof(vesa_timings[0])); ++i) { + if ((vinfo->xres == vesa_timings[i].xres) && + (vinfo->yres == vesa_timings[i].yres)) { #ifdef FBCON_DEBUG - fprintf(stderr, "Using VESA timings for %dx%d\n", - vinfo->xres, vinfo->yres); + fprintf(stderr, "Using VESA timings for %dx%d\n", + vinfo->xres, vinfo->yres); #endif - if ( vesa_timings[i].pixclock ) { - vinfo->pixclock = vesa_timings[i].pixclock; - } - vinfo->left_margin = vesa_timings[i].left; - vinfo->right_margin = vesa_timings[i].right; - vinfo->upper_margin = vesa_timings[i].upper; - vinfo->lower_margin = vesa_timings[i].lower; - vinfo->hsync_len = vesa_timings[i].hslen; - vinfo->vsync_len = vesa_timings[i].vslen; - vinfo->sync = vesa_timings[i].sync; - vinfo->vmode = vesa_timings[i].vmode; - matched = 1; - break; - } - } - return(matched); + if (vesa_timings[i].pixclock) { + vinfo->pixclock = vesa_timings[i].pixclock; + } + vinfo->left_margin = vesa_timings[i].left; + vinfo->right_margin = vesa_timings[i].right; + vinfo->upper_margin = vesa_timings[i].upper; + vinfo->lower_margin = vesa_timings[i].lower; + vinfo->hsync_len = vesa_timings[i].hslen; + vinfo->vsync_len = vesa_timings[i].vslen; + vinfo->sync = vesa_timings[i].sync; + vinfo->vmode = vesa_timings[i].vmode; + matched = 1; + break; + } + } + return (matched); } #ifdef VGA16_FBCON_SUPPORT -static SDL_Surface *FB_SetVGA16Mode(_THIS, SDL_Surface *current, - int width, int height, int bpp, Uint32 flags) +static SDL_Surface * +FB_SetVGA16Mode(_THIS, SDL_Surface * current, + int width, int height, int bpp, Uint32 flags) { - struct fb_fix_screeninfo finfo; - struct fb_var_screeninfo vinfo; - - /* Set the terminal into graphics mode */ - if ( FB_EnterGraphicsMode(this) < 0 ) { - return(NULL); - } - - /* Restore the original palette */ - FB_RestorePalette(this); - - /* Set the video mode and get the final screen format */ - if ( ioctl(console_fd, FBIOGET_VSCREENINFO, &vinfo) < 0 ) { - SDL_SetError("Couldn't get console screen info"); - return(NULL); - } - cache_vinfo = vinfo; + struct fb_fix_screeninfo finfo; + struct fb_var_screeninfo vinfo; + + /* Set the terminal into graphics mode */ + if (FB_EnterGraphicsMode(this) < 0) { + return (NULL); + } + + /* Restore the original palette */ + FB_RestorePalette(this); + + /* Set the video mode and get the final screen format */ + if (ioctl(console_fd, FBIOGET_VSCREENINFO, &vinfo) < 0) { + SDL_SetError("Couldn't get console screen info"); + return (NULL); + } + cache_vinfo = vinfo; #ifdef FBCON_DEBUG - fprintf(stderr, "Printing actual vinfo:\n"); - print_vinfo(&vinfo); + fprintf(stderr, "Printing actual vinfo:\n"); + print_vinfo(&vinfo); #endif - if ( ! SDL_ReallocFormat(current, bpp, 0, 0, 0, 0) ) { - return(NULL); - } - current->format->palette->ncolors = 16; - - /* Get the fixed information about the console hardware. - This is necessary since finfo.line_length changes. - */ - if ( ioctl(console_fd, FBIOGET_FSCREENINFO, &finfo) < 0 ) { - SDL_SetError("Couldn't get console hardware info"); - return(NULL); - } + if (!SDL_ReallocFormat(current, bpp, 0, 0, 0, 0)) { + return (NULL); + } + current->format->palette->ncolors = 16; + + /* Get the fixed information about the console hardware. + This is necessary since finfo.line_length changes. + */ + if (ioctl(console_fd, FBIOGET_FSCREENINFO, &finfo) < 0) { + SDL_SetError("Couldn't get console hardware info"); + return (NULL); + } #ifdef FBCON_DEBUG - fprintf(stderr, "Printing actual finfo:\n"); - print_finfo(&finfo); + fprintf(stderr, "Printing actual finfo:\n"); + print_finfo(&finfo); #endif - /* Save hardware palette, if needed */ - FB_SavePalette(this, &finfo, &vinfo); + /* Save hardware palette, if needed */ + FB_SavePalette(this, &finfo, &vinfo); - /* Set up the new mode framebuffer */ - current->flags = SDL_FULLSCREEN; - current->w = vinfo.xres; - current->h = vinfo.yres; - current->pitch = current->w; - current->pixels = SDL_malloc(current->h*current->pitch); + /* Set up the new mode framebuffer */ + current->flags = SDL_FULLSCREEN; + current->w = vinfo.xres; + current->h = vinfo.yres; + current->pitch = current->w; + current->pixels = SDL_malloc(current->h * current->pitch); - /* Set the update rectangle function */ - this->UpdateRects = FB_VGA16Update; + /* Set the update rectangle function */ + this->UpdateRects = FB_VGA16Update; - /* We're done */ - return(current); + /* We're done */ + return (current); } #endif /* VGA16_FBCON_SUPPORT */ -static SDL_Surface *FB_SetVideoMode(_THIS, SDL_Surface *current, - int width, int height, int bpp, Uint32 flags) +static SDL_Surface * +FB_SetVideoMode(_THIS, SDL_Surface * current, + int width, int height, int bpp, Uint32 flags) { - struct fb_fix_screeninfo finfo; - struct fb_var_screeninfo vinfo; - int i; - Uint32 Rmask; - Uint32 Gmask; - Uint32 Bmask; - char *surfaces_mem; - int surfaces_len; - - /* Set the terminal into graphics mode */ - if ( FB_EnterGraphicsMode(this) < 0 ) { - return(NULL); - } - - /* Restore the original palette */ - FB_RestorePalette(this); - - /* Set the video mode and get the final screen format */ - if ( ioctl(console_fd, FBIOGET_VSCREENINFO, &vinfo) < 0 ) { - SDL_SetError("Couldn't get console screen info"); - return(NULL); - } + struct fb_fix_screeninfo finfo; + struct fb_var_screeninfo vinfo; + int i; + Uint32 Rmask; + Uint32 Gmask; + Uint32 Bmask; + char *surfaces_mem; + int surfaces_len; + + /* Set the terminal into graphics mode */ + if (FB_EnterGraphicsMode(this) < 0) { + return (NULL); + } + + /* Restore the original palette */ + FB_RestorePalette(this); + + /* Set the video mode and get the final screen format */ + if (ioctl(console_fd, FBIOGET_VSCREENINFO, &vinfo) < 0) { + SDL_SetError("Couldn't get console screen info"); + return (NULL); + } #ifdef FBCON_DEBUG - fprintf(stderr, "Printing original vinfo:\n"); - print_vinfo(&vinfo); + fprintf(stderr, "Printing original vinfo:\n"); + print_vinfo(&vinfo); #endif - if ( (vinfo.xres != width) || (vinfo.yres != height) || - (vinfo.bits_per_pixel != bpp) || (flags & SDL_DOUBLEBUF) ) { - vinfo.activate = FB_ACTIVATE_NOW; - vinfo.accel_flags = 0; - vinfo.bits_per_pixel = bpp; - vinfo.xres = width; - vinfo.xres_virtual = width; - vinfo.yres = height; - if ( flags & SDL_DOUBLEBUF ) { - vinfo.yres_virtual = height*2; - } else { - vinfo.yres_virtual = height; - } - vinfo.xoffset = 0; - vinfo.yoffset = 0; - vinfo.red.length = vinfo.red.offset = 0; - vinfo.green.length = vinfo.green.offset = 0; - vinfo.blue.length = vinfo.blue.offset = 0; - vinfo.transp.length = vinfo.transp.offset = 0; - if ( ! choose_fbmodes_mode(&vinfo) ) { - choose_vesa_mode(&vinfo); - } + if ((vinfo.xres != width) || (vinfo.yres != height) || + (vinfo.bits_per_pixel != bpp) || (flags & SDL_DOUBLEBUF)) { + vinfo.activate = FB_ACTIVATE_NOW; + vinfo.accel_flags = 0; + vinfo.bits_per_pixel = bpp; + vinfo.xres = width; + vinfo.xres_virtual = width; + vinfo.yres = height; + if (flags & SDL_DOUBLEBUF) { + vinfo.yres_virtual = height * 2; + } else { + vinfo.yres_virtual = height; + } + vinfo.xoffset = 0; + vinfo.yoffset = 0; + vinfo.red.length = vinfo.red.offset = 0; + vinfo.green.length = vinfo.green.offset = 0; + vinfo.blue.length = vinfo.blue.offset = 0; + vinfo.transp.length = vinfo.transp.offset = 0; + if (!choose_fbmodes_mode(&vinfo)) { + choose_vesa_mode(&vinfo); + } #ifdef FBCON_DEBUG - fprintf(stderr, "Printing wanted vinfo:\n"); - print_vinfo(&vinfo); + fprintf(stderr, "Printing wanted vinfo:\n"); + print_vinfo(&vinfo); #endif - if ( ioctl(console_fd, FBIOPUT_VSCREENINFO, &vinfo) < 0 ) { - vinfo.yres_virtual = height; - if ( ioctl(console_fd, FBIOPUT_VSCREENINFO, &vinfo) < 0 ) { - SDL_SetError("Couldn't set console screen info"); - return(NULL); - } - } - } else { - int maxheight; - - /* Figure out how much video memory is available */ - if ( flags & SDL_DOUBLEBUF ) { - maxheight = height*2; - } else { - maxheight = height; - } - if ( vinfo.yres_virtual > maxheight ) { - vinfo.yres_virtual = maxheight; - } - } - cache_vinfo = vinfo; + if (ioctl(console_fd, FBIOPUT_VSCREENINFO, &vinfo) < 0) { + vinfo.yres_virtual = height; + if (ioctl(console_fd, FBIOPUT_VSCREENINFO, &vinfo) < 0) { + SDL_SetError("Couldn't set console screen info"); + return (NULL); + } + } + } else { + int maxheight; + + /* Figure out how much video memory is available */ + if (flags & SDL_DOUBLEBUF) { + maxheight = height * 2; + } else { + maxheight = height; + } + if (vinfo.yres_virtual > maxheight) { + vinfo.yres_virtual = maxheight; + } + } + cache_vinfo = vinfo; #ifdef FBCON_DEBUG - fprintf(stderr, "Printing actual vinfo:\n"); - print_vinfo(&vinfo); + fprintf(stderr, "Printing actual vinfo:\n"); + print_vinfo(&vinfo); #endif - Rmask = 0; - for ( i=0; iflags = (SDL_FULLSCREEN|SDL_HWSURFACE); - current->w = vinfo.xres; - current->h = vinfo.yres; - current->pitch = finfo.line_length; - current->pixels = mapped_mem+mapped_offset; - - /* Set up the information for hardware surfaces */ - surfaces_mem = (char *)current->pixels + - vinfo.yres_virtual*current->pitch; - surfaces_len = (mapped_memlen-(surfaces_mem-mapped_mem)); - FB_FreeHWSurfaces(this); - FB_InitHWSurfaces(this, current, surfaces_mem, surfaces_len); - - /* Let the application know we have a hardware palette */ - switch (finfo.visual) { - case FB_VISUAL_PSEUDOCOLOR: - current->flags |= SDL_HWPALETTE; - break; - default: - break; - } - - /* Update for double-buffering, if we can */ - if ( flags & SDL_DOUBLEBUF ) { - if ( vinfo.yres_virtual == (height*2) ) { - current->flags |= SDL_DOUBLEBUF; - flip_page = 0; - flip_address[0] = (char *)current->pixels; - flip_address[1] = (char *)current->pixels+ - current->h*current->pitch; - this->screen = current; - FB_FlipHWSurface(this, current); - this->screen = NULL; - } - } - - /* Set the update rectangle function */ - this->UpdateRects = FB_DirectUpdate; - - /* We're done */ - return(current); + Rmask = 0; + for (i = 0; i < vinfo.red.length; ++i) { + Rmask <<= 1; + Rmask |= (0x00000001 << vinfo.red.offset); + } + Gmask = 0; + for (i = 0; i < vinfo.green.length; ++i) { + Gmask <<= 1; + Gmask |= (0x00000001 << vinfo.green.offset); + } + Bmask = 0; + for (i = 0; i < vinfo.blue.length; ++i) { + Bmask <<= 1; + Bmask |= (0x00000001 << vinfo.blue.offset); + } + if (!SDL_ReallocFormat(current, vinfo.bits_per_pixel, + Rmask, Gmask, Bmask, 0)) { + return (NULL); + } + + /* Get the fixed information about the console hardware. + This is necessary since finfo.line_length changes. + */ + if (ioctl(console_fd, FBIOGET_FSCREENINFO, &finfo) < 0) { + SDL_SetError("Couldn't get console hardware info"); + return (NULL); + } + + /* Save hardware palette, if needed */ + FB_SavePalette(this, &finfo, &vinfo); + + /* Set up the new mode framebuffer */ + current->flags = (SDL_FULLSCREEN | SDL_HWSURFACE); + current->w = vinfo.xres; + current->h = vinfo.yres; + current->pitch = finfo.line_length; + current->pixels = mapped_mem + mapped_offset; + + /* Set up the information for hardware surfaces */ + surfaces_mem = (char *) current->pixels + + vinfo.yres_virtual * current->pitch; + surfaces_len = (mapped_memlen - (surfaces_mem - mapped_mem)); + FB_FreeHWSurfaces(this); + FB_InitHWSurfaces(this, current, surfaces_mem, surfaces_len); + + /* Let the application know we have a hardware palette */ + switch (finfo.visual) { + case FB_VISUAL_PSEUDOCOLOR: + current->flags |= SDL_HWPALETTE; + break; + default: + break; + } + + /* Update for double-buffering, if we can */ + if (flags & SDL_DOUBLEBUF) { + if (vinfo.yres_virtual == (height * 2)) { + current->flags |= SDL_DOUBLEBUF; + flip_page = 0; + flip_address[0] = (char *) current->pixels; + flip_address[1] = (char *) current->pixels + + current->h * current->pitch; + this->screen = current; + FB_FlipHWSurface(this, current); + this->screen = NULL; + } + } + + /* Set the update rectangle function */ + this->UpdateRects = FB_DirectUpdate; + + /* We're done */ + return (current); } #ifdef FBCON_DEBUG -void FB_DumpHWSurfaces(_THIS) +void +FB_DumpHWSurfaces(_THIS) { - vidmem_bucket *bucket; - - printf("Memory left: %d (%d total)\n", surfaces_memleft, surfaces_memtotal); - printf("\n"); - printf(" Base Size\n"); - for ( bucket=&surfaces; bucket; bucket=bucket->next ) { - printf("Bucket: %p, %d (%s)\n", bucket->base, bucket->size, bucket->used ? "used" : "free"); - if ( bucket->prev ) { - if ( bucket->base != bucket->prev->base+bucket->prev->size ) { - printf("Warning, corrupt bucket list! (prev)\n"); - } - } else { - if ( bucket != &surfaces ) { - printf("Warning, corrupt bucket list! (!prev)\n"); - } - } - if ( bucket->next ) { - if ( bucket->next->base != bucket->base+bucket->size ) { - printf("Warning, corrupt bucket list! (next)\n"); - } - } - } - printf("\n"); + vidmem_bucket *bucket; + + printf("Memory left: %d (%d total)\n", surfaces_memleft, + surfaces_memtotal); + printf("\n"); + printf(" Base Size\n"); + for (bucket = &surfaces; bucket; bucket = bucket->next) { + printf("Bucket: %p, %d (%s)\n", bucket->base, bucket->size, + bucket->used ? "used" : "free"); + if (bucket->prev) { + if (bucket->base != bucket->prev->base + bucket->prev->size) { + printf("Warning, corrupt bucket list! (prev)\n"); + } + } else { + if (bucket != &surfaces) { + printf("Warning, corrupt bucket list! (!prev)\n"); + } + } + if (bucket->next) { + if (bucket->next->base != bucket->base + bucket->size) { + printf("Warning, corrupt bucket list! (next)\n"); + } + } + } + printf("\n"); } #endif -static int FB_InitHWSurfaces(_THIS, SDL_Surface *screen, char *base, int size) +static int +FB_InitHWSurfaces(_THIS, SDL_Surface * screen, char *base, int size) { - vidmem_bucket *bucket; - - surfaces_memtotal = size; - surfaces_memleft = size; - - if ( surfaces_memleft > 0 ) { - bucket = (vidmem_bucket *)SDL_malloc(sizeof(*bucket)); - if ( bucket == NULL ) { - SDL_OutOfMemory(); - return(-1); - } - bucket->prev = &surfaces; - bucket->used = 0; - bucket->dirty = 0; - bucket->base = base; - bucket->size = size; - bucket->next = NULL; - } else { - bucket = NULL; - } - - surfaces.prev = NULL; - surfaces.used = 1; - surfaces.dirty = 0; - surfaces.base = screen->pixels; - surfaces.size = (unsigned int)((long)base - (long)surfaces.base); - surfaces.next = bucket; - screen->hwdata = (struct private_hwdata *)&surfaces; - return(0); + vidmem_bucket *bucket; + + surfaces_memtotal = size; + surfaces_memleft = size; + + if (surfaces_memleft > 0) { + bucket = (vidmem_bucket *) SDL_malloc(sizeof(*bucket)); + if (bucket == NULL) { + SDL_OutOfMemory(); + return (-1); + } + bucket->prev = &surfaces; + bucket->used = 0; + bucket->dirty = 0; + bucket->base = base; + bucket->size = size; + bucket->next = NULL; + } else { + bucket = NULL; + } + + surfaces.prev = NULL; + surfaces.used = 1; + surfaces.dirty = 0; + surfaces.base = screen->pixels; + surfaces.size = (unsigned int) ((long) base - (long) surfaces.base); + surfaces.next = bucket; + screen->hwdata = (struct private_hwdata *) &surfaces; + return (0); } -static void FB_FreeHWSurfaces(_THIS) +static void +FB_FreeHWSurfaces(_THIS) { - vidmem_bucket *bucket, *freeable; - - bucket = surfaces.next; - while ( bucket ) { - freeable = bucket; - bucket = bucket->next; - SDL_free(freeable); - } - surfaces.next = NULL; + vidmem_bucket *bucket, *freeable; + + bucket = surfaces.next; + while (bucket) { + freeable = bucket; + bucket = bucket->next; + SDL_free(freeable); + } + surfaces.next = NULL; } -static int FB_AllocHWSurface(_THIS, SDL_Surface *surface) +static int +FB_AllocHWSurface(_THIS, SDL_Surface * surface) { - vidmem_bucket *bucket; - int size; - int extra; + vidmem_bucket *bucket; + int size; + int extra; /* Temporarily, we only allow surfaces the same width as display. Some blitters require the pitch between two hardware surfaces to be the same. Others have interesting alignment restrictions. Until someone who knows these details looks at the code... */ -if ( surface->pitch > SDL_VideoSurface->pitch ) { - SDL_SetError("Surface requested wider than screen"); - return(-1); -} -surface->pitch = SDL_VideoSurface->pitch; - size = surface->h * surface->pitch; + if (surface->pitch > SDL_VideoSurface->pitch) { + SDL_SetError("Surface requested wider than screen"); + return (-1); + } + surface->pitch = SDL_VideoSurface->pitch; + size = surface->h * surface->pitch; #ifdef FBCON_DEBUG - fprintf(stderr, "Allocating bucket of %d bytes\n", size); + fprintf(stderr, "Allocating bucket of %d bytes\n", size); #endif - /* Quick check for available mem */ - if ( size > surfaces_memleft ) { - SDL_SetError("Not enough video memory"); - return(-1); - } - - /* Search for an empty bucket big enough */ - for ( bucket=&surfaces; bucket; bucket=bucket->next ) { - if ( ! bucket->used && (size <= bucket->size) ) { - break; - } - } - if ( bucket == NULL ) { - SDL_SetError("Video memory too fragmented"); - return(-1); - } - - /* Create a new bucket for left-over memory */ - extra = (bucket->size - size); - if ( extra ) { - vidmem_bucket *newbucket; + /* Quick check for available mem */ + if (size > surfaces_memleft) { + SDL_SetError("Not enough video memory"); + return (-1); + } + + /* Search for an empty bucket big enough */ + for (bucket = &surfaces; bucket; bucket = bucket->next) { + if (!bucket->used && (size <= bucket->size)) { + break; + } + } + if (bucket == NULL) { + SDL_SetError("Video memory too fragmented"); + return (-1); + } + + /* Create a new bucket for left-over memory */ + extra = (bucket->size - size); + if (extra) { + vidmem_bucket *newbucket; #ifdef FBCON_DEBUG - fprintf(stderr, "Adding new free bucket of %d bytes\n", extra); + fprintf(stderr, "Adding new free bucket of %d bytes\n", extra); #endif - newbucket = (vidmem_bucket *)SDL_malloc(sizeof(*newbucket)); - if ( newbucket == NULL ) { - SDL_OutOfMemory(); - return(-1); - } - newbucket->prev = bucket; - newbucket->used = 0; - newbucket->base = bucket->base+size; - newbucket->size = extra; - newbucket->next = bucket->next; - if ( bucket->next ) { - bucket->next->prev = newbucket; - } - bucket->next = newbucket; - } - - /* Set the current bucket values and return it! */ - bucket->used = 1; - bucket->size = size; - bucket->dirty = 0; + newbucket = (vidmem_bucket *) SDL_malloc(sizeof(*newbucket)); + if (newbucket == NULL) { + SDL_OutOfMemory(); + return (-1); + } + newbucket->prev = bucket; + newbucket->used = 0; + newbucket->base = bucket->base + size; + newbucket->size = extra; + newbucket->next = bucket->next; + if (bucket->next) { + bucket->next->prev = newbucket; + } + bucket->next = newbucket; + } + + /* Set the current bucket values and return it! */ + bucket->used = 1; + bucket->size = size; + bucket->dirty = 0; #ifdef FBCON_DEBUG - fprintf(stderr, "Allocated %d bytes at %p\n", bucket->size, bucket->base); + fprintf(stderr, "Allocated %d bytes at %p\n", bucket->size, bucket->base); #endif - surfaces_memleft -= size; - surface->flags |= SDL_HWSURFACE; - surface->pixels = bucket->base; - surface->hwdata = (struct private_hwdata *)bucket; - return(0); + surfaces_memleft -= size; + surface->flags |= SDL_HWSURFACE; + surface->pixels = bucket->base; + surface->hwdata = (struct private_hwdata *) bucket; + return (0); } -static void FB_FreeHWSurface(_THIS, SDL_Surface *surface) +static void +FB_FreeHWSurface(_THIS, SDL_Surface * surface) { - vidmem_bucket *bucket, *freeable; - - /* Look for the bucket in the current list */ - for ( bucket=&surfaces; bucket; bucket=bucket->next ) { - if ( bucket == (vidmem_bucket *)surface->hwdata ) { - break; - } - } - if ( bucket && bucket->used ) { - /* Add the memory back to the total */ + vidmem_bucket *bucket, *freeable; + + /* Look for the bucket in the current list */ + for (bucket = &surfaces; bucket; bucket = bucket->next) { + if (bucket == (vidmem_bucket *) surface->hwdata) { + break; + } + } + if (bucket && bucket->used) { + /* Add the memory back to the total */ #ifdef DGA_DEBUG - printf("Freeing bucket of %d bytes\n", bucket->size); + printf("Freeing bucket of %d bytes\n", bucket->size); #endif - surfaces_memleft += bucket->size; + surfaces_memleft += bucket->size; - /* Can we merge the space with surrounding buckets? */ - bucket->used = 0; - if ( bucket->next && ! bucket->next->used ) { + /* Can we merge the space with surrounding buckets? */ + bucket->used = 0; + if (bucket->next && !bucket->next->used) { #ifdef DGA_DEBUG - printf("Merging with next bucket, for %d total bytes\n", bucket->size+bucket->next->size); + printf("Merging with next bucket, for %d total bytes\n", + bucket->size + bucket->next->size); #endif - freeable = bucket->next; - bucket->size += bucket->next->size; - bucket->next = bucket->next->next; - if ( bucket->next ) { - bucket->next->prev = bucket; - } - SDL_free(freeable); - } - if ( bucket->prev && ! bucket->prev->used ) { + freeable = bucket->next; + bucket->size += bucket->next->size; + bucket->next = bucket->next->next; + if (bucket->next) { + bucket->next->prev = bucket; + } + SDL_free(freeable); + } + if (bucket->prev && !bucket->prev->used) { #ifdef DGA_DEBUG - printf("Merging with previous bucket, for %d total bytes\n", bucket->prev->size+bucket->size); + printf("Merging with previous bucket, for %d total bytes\n", + bucket->prev->size + bucket->size); #endif - freeable = bucket; - bucket->prev->size += bucket->size; - bucket->prev->next = bucket->next; - if ( bucket->next ) { - bucket->next->prev = bucket->prev; - } - SDL_free(freeable); - } - } - surface->pixels = NULL; - surface->hwdata = NULL; + freeable = bucket; + bucket->prev->size += bucket->size; + bucket->prev->next = bucket->next; + if (bucket->next) { + bucket->next->prev = bucket->prev; + } + SDL_free(freeable); + } + } + surface->pixels = NULL; + surface->hwdata = NULL; } -static int FB_LockHWSurface(_THIS, SDL_Surface *surface) +static int +FB_LockHWSurface(_THIS, SDL_Surface * surface) { - if ( switched_away ) { - return -2; /* no hardware access */ - } - if ( surface == this->screen ) { - SDL_mutexP(hw_lock); - if ( FB_IsSurfaceBusy(surface) ) { - FB_WaitBusySurfaces(this); - } - } else { - if ( FB_IsSurfaceBusy(surface) ) { - FB_WaitBusySurfaces(this); - } - } - return(0); + if (switched_away) { + return -2; /* no hardware access */ + } + if (surface == this->screen) { + SDL_mutexP(hw_lock); + if (FB_IsSurfaceBusy(surface)) { + FB_WaitBusySurfaces(this); + } + } else { + if (FB_IsSurfaceBusy(surface)) { + FB_WaitBusySurfaces(this); + } + } + return (0); } -static void FB_UnlockHWSurface(_THIS, SDL_Surface *surface) +static void +FB_UnlockHWSurface(_THIS, SDL_Surface * surface) { - if ( surface == this->screen ) { - SDL_mutexV(hw_lock); - } + if (surface == this->screen) { + SDL_mutexV(hw_lock); + } } -static void FB_WaitVBL(_THIS) +static void +FB_WaitVBL(_THIS) { -#ifdef FBIOWAITRETRACE /* Heheh, this didn't make it into the main kernel */ - ioctl(console_fd, FBIOWAITRETRACE, 0); +#ifdef FBIOWAITRETRACE /* Heheh, this didn't make it into the main kernel */ + ioctl(console_fd, FBIOWAITRETRACE, 0); #endif - return; + return; } -static void FB_WaitIdle(_THIS) +static void +FB_WaitIdle(_THIS) { - return; + return; } -static int FB_FlipHWSurface(_THIS, SDL_Surface *surface) +static int +FB_FlipHWSurface(_THIS, SDL_Surface * surface) { - if ( switched_away ) { - return -2; /* no hardware access */ - } - - /* Wait for vertical retrace and then flip display */ - cache_vinfo.yoffset = flip_page*surface->h; - if ( FB_IsSurfaceBusy(this->screen) ) { - FB_WaitBusySurfaces(this); - } - wait_vbl(this); - if ( ioctl(console_fd, FBIOPAN_DISPLAY, &cache_vinfo) < 0 ) { - SDL_SetError("ioctl(FBIOPAN_DISPLAY) failed"); - return(-1); - } - flip_page = !flip_page; - - surface->pixels = flip_address[flip_page]; - return(0); + if (switched_away) { + return -2; /* no hardware access */ + } + + /* Wait for vertical retrace and then flip display */ + cache_vinfo.yoffset = flip_page * surface->h; + if (FB_IsSurfaceBusy(this->screen)) { + FB_WaitBusySurfaces(this); + } + wait_vbl(this); + if (ioctl(console_fd, FBIOPAN_DISPLAY, &cache_vinfo) < 0) { + SDL_SetError("ioctl(FBIOPAN_DISPLAY) failed"); + return (-1); + } + flip_page = !flip_page; + + surface->pixels = flip_address[flip_page]; + return (0); } -static void FB_DirectUpdate(_THIS, int numrects, SDL_Rect *rects) +static void +FB_DirectUpdate(_THIS, int numrects, SDL_Rect * rects) { - /* The application is already updating the visible video memory */ - return; + /* The application is already updating the visible video memory */ + return; } #ifdef VGA16_FBCON_SUPPORT @@ -1326,17 +1394,18 @@ outb(value, 0x3CF); outb(index, 0x3C4); \ outb(value, 0x3C5); -static void FB_VGA16Update(_THIS, int numrects, SDL_Rect *rects) +static void +FB_VGA16Update(_THIS, int numrects, SDL_Rect * rects) { SDL_Surface *screen; int width, height, FBPitch, left, i, j, SRCPitch, phase; register Uint32 m; - Uint8 s1, s2, s3, s4; + Uint8 s1, s2, s3, s4; Uint32 *src, *srcPtr; - Uint8 *dst, *dstPtr; + Uint8 *dst, *dstPtr; - if ( switched_away ) { - return; /* no hardware access */ + if (switched_away) { + return; /* no hardware access */ } screen = this->screen; @@ -1348,139 +1417,168 @@ static void FB_VGA16Update(_THIS, int numrects, SDL_Rect *rects) writeGr(0x01, 0x00); writeGr(0x08, 0xFF); - while(numrects--) { - left = rects->x & ~7; + while (numrects--) { + left = rects->x & ~7; width = (rects->w + 7) >> 3; height = rects->h; - src = (Uint32*)screen->pixels + (rects->y * SRCPitch) + (left >> 2); - dst = (Uint8*)mapped_mem + (rects->y * FBPitch) + (left >> 3); - - if((phase = (long)dst & 3L)) { - phase = 4 - phase; - if(phase > width) phase = width; - width -= phase; - } - - while(height--) { - writeSeq(0x02, 1 << 0); - dstPtr = dst; - srcPtr = src; - i = width; - j = phase; - while(j--) { - m = (srcPtr[1] & 0x01010101) | ((srcPtr[0] & 0x01010101) << 4); - *dstPtr++ = (m >> 24) | (m >> 15) | (m >> 6) | (m << 3); - srcPtr += 2; - } - while(i >= 4) { - m = (srcPtr[1] & 0x01010101) | ((srcPtr[0] & 0x01010101) << 4); - s1 = (m >> 24) | (m >> 15) | (m >> 6) | (m << 3); - m = (srcPtr[3] & 0x01010101) | ((srcPtr[2] & 0x01010101) << 4); - s2 = (m >> 24) | (m >> 15) | (m >> 6) | (m << 3); - m = (srcPtr[5] & 0x01010101) | ((srcPtr[4] & 0x01010101) << 4); - s3 = (m >> 24) | (m >> 15) | (m >> 6) | (m << 3); - m = (srcPtr[7] & 0x01010101) | ((srcPtr[6] & 0x01010101) << 4); - s4 = (m >> 24) | (m >> 15) | (m >> 6) | (m << 3); - *((Uint32*)dstPtr) = s1 | (s2 << 8) | (s3 << 16) | (s4 << 24); - srcPtr += 8; - dstPtr += 4; - i -= 4; - } - while(i--) { - m = (srcPtr[1] & 0x01010101) | ((srcPtr[0] & 0x01010101) << 4); - *dstPtr++ = (m >> 24) | (m >> 15) | (m >> 6) | (m << 3); - srcPtr += 2; - } - - writeSeq(0x02, 1 << 1); - dstPtr = dst; - srcPtr = src; - i = width; - j = phase; - while(j--) { - m = (srcPtr[1] & 0x02020202) | ((srcPtr[0] & 0x02020202) << 4); - *dstPtr++ = (m >> 25) | (m >> 16) | (m >> 7) | (m << 2); - srcPtr += 2; - } - while(i >= 4) { - m = (srcPtr[1] & 0x02020202) | ((srcPtr[0] & 0x02020202) << 4); - s1 = (m >> 25) | (m >> 16) | (m >> 7) | (m << 2); - m = (srcPtr[3] & 0x02020202) | ((srcPtr[2] & 0x02020202) << 4); - s2 = (m >> 25) | (m >> 16) | (m >> 7) | (m << 2); - m = (srcPtr[5] & 0x02020202) | ((srcPtr[4] & 0x02020202) << 4); - s3 = (m >> 25) | (m >> 16) | (m >> 7) | (m << 2); - m = (srcPtr[7] & 0x02020202) | ((srcPtr[6] & 0x02020202) << 4); - s4 = (m >> 25) | (m >> 16) | (m >> 7) | (m << 2); - *((Uint32*)dstPtr) = s1 | (s2 << 8) | (s3 << 16) | (s4 << 24); - srcPtr += 8; - dstPtr += 4; - i -= 4; - } - while(i--) { - m = (srcPtr[1] & 0x02020202) | ((srcPtr[0] & 0x02020202) << 4); - *dstPtr++ = (m >> 25) | (m >> 16) | (m >> 7) | (m << 2); - srcPtr += 2; - } - - writeSeq(0x02, 1 << 2); - dstPtr = dst; - srcPtr = src; - i = width; - j = phase; - while(j--) { - m = (srcPtr[1] & 0x04040404) | ((srcPtr[0] & 0x04040404) << 4); - *dstPtr++ = (m >> 26) | (m >> 17) | (m >> 8) | (m << 1); - srcPtr += 2; - } - while(i >= 4) { - m = (srcPtr[1] & 0x04040404) | ((srcPtr[0] & 0x04040404) << 4); - s1 = (m >> 26) | (m >> 17) | (m >> 8) | (m << 1); - m = (srcPtr[3] & 0x04040404) | ((srcPtr[2] & 0x04040404) << 4); - s2 = (m >> 26) | (m >> 17) | (m >> 8) | (m << 1); - m = (srcPtr[5] & 0x04040404) | ((srcPtr[4] & 0x04040404) << 4); - s3 = (m >> 26) | (m >> 17) | (m >> 8) | (m << 1); - m = (srcPtr[7] & 0x04040404) | ((srcPtr[6] & 0x04040404) << 4); - s4 = (m >> 26) | (m >> 17) | (m >> 8) | (m << 1); - *((Uint32*)dstPtr) = s1 | (s2 << 8) | (s3 << 16) | (s4 << 24); - srcPtr += 8; - dstPtr += 4; - i -= 4; - } - while(i--) { - m = (srcPtr[1] & 0x04040404) | ((srcPtr[0] & 0x04040404) << 4); - *dstPtr++ = (m >> 26) | (m >> 17) | (m >> 8) | (m << 1); - srcPtr += 2; - } - - writeSeq(0x02, 1 << 3); - dstPtr = dst; - srcPtr = src; - i = width; - j = phase; - while(j--) { - m = (srcPtr[1] & 0x08080808) | ((srcPtr[0] & 0x08080808) << 4); - *dstPtr++ = (m >> 27) | (m >> 18) | (m >> 9) | m; - srcPtr += 2; - } - while(i >= 4) { - m = (srcPtr[1] & 0x08080808) | ((srcPtr[0] & 0x08080808) << 4); - s1 = (m >> 27) | (m >> 18) | (m >> 9) | m; - m = (srcPtr[3] & 0x08080808) | ((srcPtr[2] & 0x08080808) << 4); - s2 = (m >> 27) | (m >> 18) | (m >> 9) | m; - m = (srcPtr[5] & 0x08080808) | ((srcPtr[4] & 0x08080808) << 4); - s3 = (m >> 27) | (m >> 18) | (m >> 9) | m; - m = (srcPtr[7] & 0x08080808) | ((srcPtr[6] & 0x08080808) << 4); - s4 = (m >> 27) | (m >> 18) | (m >> 9) | m; - *((Uint32*)dstPtr) = s1 | (s2 << 8) | (s3 << 16) | (s4 << 24); - srcPtr += 8; - dstPtr += 4; - i -= 4; - } - while(i--) { - m = (srcPtr[1] & 0x08080808) | ((srcPtr[0] & 0x08080808) << 4); - *dstPtr++ = (m >> 27) | (m >> 18) | (m >> 9) | m; - srcPtr += 2; - } + src = (Uint32 *) screen->pixels + (rects->y * SRCPitch) + (left >> 2); + dst = (Uint8 *) mapped_mem + (rects->y * FBPitch) + (left >> 3); + + if ((phase = (long) dst & 3L)) { + phase = 4 - phase; + if (phase > width) + phase = width; + width -= phase; + } + + while (height--) { + writeSeq(0x02, 1 << 0); + dstPtr = dst; + srcPtr = src; + i = width; + j = phase; + while (j--) { + m = (srcPtr[1] & 0x01010101) | ((srcPtr[0] & 0x01010101) + << 4); + *dstPtr++ = (m >> 24) | (m >> 15) | (m >> 6) | (m << 3); + srcPtr += 2; + } + while (i >= 4) { + m = (srcPtr[1] & 0x01010101) | ((srcPtr[0] & 0x01010101) + << 4); + s1 = (m >> 24) | (m >> 15) | (m >> 6) | (m << 3); + m = (srcPtr[3] & 0x01010101) | ((srcPtr[2] & 0x01010101) + << 4); + s2 = (m >> 24) | (m >> 15) | (m >> 6) | (m << 3); + m = (srcPtr[5] & 0x01010101) | ((srcPtr[4] & 0x01010101) + << 4); + s3 = (m >> 24) | (m >> 15) | (m >> 6) | (m << 3); + m = (srcPtr[7] & 0x01010101) | ((srcPtr[6] & 0x01010101) + << 4); + s4 = (m >> 24) | (m >> 15) | (m >> 6) | (m << 3); + *((Uint32 *) dstPtr) = + s1 | (s2 << 8) | (s3 << 16) | (s4 << 24); + srcPtr += 8; + dstPtr += 4; + i -= 4; + } + while (i--) { + m = (srcPtr[1] & 0x01010101) | ((srcPtr[0] & 0x01010101) + << 4); + *dstPtr++ = (m >> 24) | (m >> 15) | (m >> 6) | (m << 3); + srcPtr += 2; + } + + writeSeq(0x02, 1 << 1); + dstPtr = dst; + srcPtr = src; + i = width; + j = phase; + while (j--) { + m = (srcPtr[1] & 0x02020202) | ((srcPtr[0] & 0x02020202) + << 4); + *dstPtr++ = (m >> 25) | (m >> 16) | (m >> 7) | (m << 2); + srcPtr += 2; + } + while (i >= 4) { + m = (srcPtr[1] & 0x02020202) | ((srcPtr[0] & 0x02020202) + << 4); + s1 = (m >> 25) | (m >> 16) | (m >> 7) | (m << 2); + m = (srcPtr[3] & 0x02020202) | ((srcPtr[2] & 0x02020202) + << 4); + s2 = (m >> 25) | (m >> 16) | (m >> 7) | (m << 2); + m = (srcPtr[5] & 0x02020202) | ((srcPtr[4] & 0x02020202) + << 4); + s3 = (m >> 25) | (m >> 16) | (m >> 7) | (m << 2); + m = (srcPtr[7] & 0x02020202) | ((srcPtr[6] & 0x02020202) + << 4); + s4 = (m >> 25) | (m >> 16) | (m >> 7) | (m << 2); + *((Uint32 *) dstPtr) = + s1 | (s2 << 8) | (s3 << 16) | (s4 << 24); + srcPtr += 8; + dstPtr += 4; + i -= 4; + } + while (i--) { + m = (srcPtr[1] & 0x02020202) | ((srcPtr[0] & 0x02020202) + << 4); + *dstPtr++ = (m >> 25) | (m >> 16) | (m >> 7) | (m << 2); + srcPtr += 2; + } + + writeSeq(0x02, 1 << 2); + dstPtr = dst; + srcPtr = src; + i = width; + j = phase; + while (j--) { + m = (srcPtr[1] & 0x04040404) | ((srcPtr[0] & 0x04040404) + << 4); + *dstPtr++ = (m >> 26) | (m >> 17) | (m >> 8) | (m << 1); + srcPtr += 2; + } + while (i >= 4) { + m = (srcPtr[1] & 0x04040404) | ((srcPtr[0] & 0x04040404) + << 4); + s1 = (m >> 26) | (m >> 17) | (m >> 8) | (m << 1); + m = (srcPtr[3] & 0x04040404) | ((srcPtr[2] & 0x04040404) + << 4); + s2 = (m >> 26) | (m >> 17) | (m >> 8) | (m << 1); + m = (srcPtr[5] & 0x04040404) | ((srcPtr[4] & 0x04040404) + << 4); + s3 = (m >> 26) | (m >> 17) | (m >> 8) | (m << 1); + m = (srcPtr[7] & 0x04040404) | ((srcPtr[6] & 0x04040404) + << 4); + s4 = (m >> 26) | (m >> 17) | (m >> 8) | (m << 1); + *((Uint32 *) dstPtr) = + s1 | (s2 << 8) | (s3 << 16) | (s4 << 24); + srcPtr += 8; + dstPtr += 4; + i -= 4; + } + while (i--) { + m = (srcPtr[1] & 0x04040404) | ((srcPtr[0] & 0x04040404) + << 4); + *dstPtr++ = (m >> 26) | (m >> 17) | (m >> 8) | (m << 1); + srcPtr += 2; + } + + writeSeq(0x02, 1 << 3); + dstPtr = dst; + srcPtr = src; + i = width; + j = phase; + while (j--) { + m = (srcPtr[1] & 0x08080808) | ((srcPtr[0] & 0x08080808) + << 4); + *dstPtr++ = (m >> 27) | (m >> 18) | (m >> 9) | m; + srcPtr += 2; + } + while (i >= 4) { + m = (srcPtr[1] & 0x08080808) | ((srcPtr[0] & 0x08080808) + << 4); + s1 = (m >> 27) | (m >> 18) | (m >> 9) | m; + m = (srcPtr[3] & 0x08080808) | ((srcPtr[2] & 0x08080808) + << 4); + s2 = (m >> 27) | (m >> 18) | (m >> 9) | m; + m = (srcPtr[5] & 0x08080808) | ((srcPtr[4] & 0x08080808) + << 4); + s3 = (m >> 27) | (m >> 18) | (m >> 9) | m; + m = (srcPtr[7] & 0x08080808) | ((srcPtr[6] & 0x08080808) + << 4); + s4 = (m >> 27) | (m >> 18) | (m >> 9) | m; + *((Uint32 *) dstPtr) = + s1 | (s2 << 8) | (s3 << 16) | (s4 << 24); + srcPtr += 8; + dstPtr += 4; + i -= 4; + } + while (i--) { + m = (srcPtr[1] & 0x08080808) | ((srcPtr[0] & 0x08080808) + << 4); + *dstPtr++ = (m >> 27) | (m >> 18) | (m >> 9) | m; + srcPtr += 2; + } dst += FBPitch; src += SRCPitch; @@ -1490,194 +1588,207 @@ static void FB_VGA16Update(_THIS, int numrects, SDL_Rect *rects) } #endif /* VGA16_FBCON_SUPPORT */ -void FB_SavePaletteTo(_THIS, int palette_len, __u16 *area) +void +FB_SavePaletteTo(_THIS, int palette_len, __u16 * area) { - struct fb_cmap cmap; - - cmap.start = 0; - cmap.len = palette_len; - cmap.red = &area[0*palette_len]; - cmap.green = &area[1*palette_len]; - cmap.blue = &area[2*palette_len]; - cmap.transp = NULL; - ioctl(console_fd, FBIOGETCMAP, &cmap); + struct fb_cmap cmap; + + cmap.start = 0; + cmap.len = palette_len; + cmap.red = &area[0 * palette_len]; + cmap.green = &area[1 * palette_len]; + cmap.blue = &area[2 * palette_len]; + cmap.transp = NULL; + ioctl(console_fd, FBIOGETCMAP, &cmap); } -void FB_RestorePaletteFrom(_THIS, int palette_len, __u16 *area) +void +FB_RestorePaletteFrom(_THIS, int palette_len, __u16 * area) { - struct fb_cmap cmap; - - cmap.start = 0; - cmap.len = palette_len; - cmap.red = &area[0*palette_len]; - cmap.green = &area[1*palette_len]; - cmap.blue = &area[2*palette_len]; - cmap.transp = NULL; - ioctl(console_fd, FBIOPUTCMAP, &cmap); + struct fb_cmap cmap; + + cmap.start = 0; + cmap.len = palette_len; + cmap.red = &area[0 * palette_len]; + cmap.green = &area[1 * palette_len]; + cmap.blue = &area[2 * palette_len]; + cmap.transp = NULL; + ioctl(console_fd, FBIOPUTCMAP, &cmap); } -static void FB_SavePalette(_THIS, struct fb_fix_screeninfo *finfo, - struct fb_var_screeninfo *vinfo) +static void +FB_SavePalette(_THIS, struct fb_fix_screeninfo *finfo, + struct fb_var_screeninfo *vinfo) { - int i; - - /* Save hardware palette, if needed */ - if ( finfo->visual == FB_VISUAL_PSEUDOCOLOR ) { - saved_cmaplen = 1<bits_per_pixel; - saved_cmap=(__u16 *)SDL_malloc(3*saved_cmaplen*sizeof(*saved_cmap)); - if ( saved_cmap != NULL ) { - FB_SavePaletteTo(this, saved_cmaplen, saved_cmap); - } - } - - /* Added support for FB_VISUAL_DIRECTCOLOR. - With this mode pixel information is passed through the palette... - Neat fading and gamma correction effects can be had by simply - fooling around with the palette instead of changing the pixel - values themselves... Very neat! - - Adam Meyerowitz 1/19/2000 - ameyerow@optonline.com - */ - if ( finfo->visual == FB_VISUAL_DIRECTCOLOR ) { - __u16 new_entries[3*256]; - - /* Save the colormap */ - saved_cmaplen = 256; - saved_cmap=(__u16 *)SDL_malloc(3*saved_cmaplen*sizeof(*saved_cmap)); - if ( saved_cmap != NULL ) { - FB_SavePaletteTo(this, saved_cmaplen, saved_cmap); - } - - /* Allocate new identity colormap */ - for ( i=0; i<256; ++i ) { - new_entries[(0*256)+i] = - new_entries[(1*256)+i] = - new_entries[(2*256)+i] = (i<<8)|i; - } - FB_RestorePaletteFrom(this, 256, new_entries); - } + int i; + + /* Save hardware palette, if needed */ + if (finfo->visual == FB_VISUAL_PSEUDOCOLOR) { + saved_cmaplen = 1 << vinfo->bits_per_pixel; + saved_cmap = + (__u16 *) SDL_malloc(3 * saved_cmaplen * sizeof(*saved_cmap)); + if (saved_cmap != NULL) { + FB_SavePaletteTo(this, saved_cmaplen, saved_cmap); + } + } + + /* Added support for FB_VISUAL_DIRECTCOLOR. + With this mode pixel information is passed through the palette... + Neat fading and gamma correction effects can be had by simply + fooling around with the palette instead of changing the pixel + values themselves... Very neat! + + Adam Meyerowitz 1/19/2000 + ameyerow@optonline.com + */ + if (finfo->visual == FB_VISUAL_DIRECTCOLOR) { + __u16 new_entries[3 * 256]; + + /* Save the colormap */ + saved_cmaplen = 256; + saved_cmap = + (__u16 *) SDL_malloc(3 * saved_cmaplen * sizeof(*saved_cmap)); + if (saved_cmap != NULL) { + FB_SavePaletteTo(this, saved_cmaplen, saved_cmap); + } + + /* Allocate new identity colormap */ + for (i = 0; i < 256; ++i) { + new_entries[(0 * 256) + i] = + new_entries[(1 * 256) + i] = + new_entries[(2 * 256) + i] = (i << 8) | i; + } + FB_RestorePaletteFrom(this, 256, new_entries); + } } -static void FB_RestorePalette(_THIS) +static void +FB_RestorePalette(_THIS) { - /* Restore the original palette */ - if ( saved_cmap ) { - FB_RestorePaletteFrom(this, saved_cmaplen, saved_cmap); - SDL_free(saved_cmap); - saved_cmap = NULL; - } + /* Restore the original palette */ + if (saved_cmap) { + FB_RestorePaletteFrom(this, saved_cmaplen, saved_cmap); + SDL_free(saved_cmap); + saved_cmap = NULL; + } } -static int FB_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color *colors) +static int +FB_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color * colors) { - int i; - __u16 r[256]; - __u16 g[256]; - __u16 b[256]; - struct fb_cmap cmap; - - /* Set up the colormap */ - for (i = 0; i < ncolors; i++) { - r[i] = colors[i].r << 8; - g[i] = colors[i].g << 8; - b[i] = colors[i].b << 8; - } - cmap.start = firstcolor; - cmap.len = ncolors; - cmap.red = r; - cmap.green = g; - cmap.blue = b; - cmap.transp = NULL; - - if( (ioctl(console_fd, FBIOPUTCMAP, &cmap) < 0) || - !(this->screen->flags & SDL_HWPALETTE) ) { - colors = this->screen->format->palette->colors; - ncolors = this->screen->format->palette->ncolors; - cmap.start = 0; - cmap.len = ncolors; - SDL_memset(r, 0, sizeof(r)); - SDL_memset(g, 0, sizeof(g)); - SDL_memset(b, 0, sizeof(b)); - if ( ioctl(console_fd, FBIOGETCMAP, &cmap) == 0 ) { - for ( i=ncolors-1; i>=0; --i ) { - colors[i].r = (r[i]>>8); - colors[i].g = (g[i]>>8); - colors[i].b = (b[i]>>8); - } - } - return(0); - } - return(1); + int i; + __u16 r[256]; + __u16 g[256]; + __u16 b[256]; + struct fb_cmap cmap; + + /* Set up the colormap */ + for (i = 0; i < ncolors; i++) { + r[i] = colors[i].r << 8; + g[i] = colors[i].g << 8; + b[i] = colors[i].b << 8; + } + cmap.start = firstcolor; + cmap.len = ncolors; + cmap.red = r; + cmap.green = g; + cmap.blue = b; + cmap.transp = NULL; + + if ((ioctl(console_fd, FBIOPUTCMAP, &cmap) < 0) || + !(this->screen->flags & SDL_HWPALETTE)) { + colors = this->screen->format->palette->colors; + ncolors = this->screen->format->palette->ncolors; + cmap.start = 0; + cmap.len = ncolors; + SDL_memset(r, 0, sizeof(r)); + SDL_memset(g, 0, sizeof(g)); + SDL_memset(b, 0, sizeof(b)); + if (ioctl(console_fd, FBIOGETCMAP, &cmap) == 0) { + for (i = ncolors - 1; i >= 0; --i) { + colors[i].r = (r[i] >> 8); + colors[i].g = (g[i] >> 8); + colors[i].b = (b[i] >> 8); + } + } + return (0); + } + return (1); } /* Note: If we are terminated, this could be called in the middle of another SDL video routine -- notably UpdateRects. */ -static void FB_VideoQuit(_THIS) +static void +FB_VideoQuit(_THIS) { - int i, j; - - if ( this->screen ) { - /* Clear screen and tell SDL not to free the pixels */ - if ( this->screen->pixels && FB_InGraphicsMode(this) ) { -#if defined(__powerpc__) || defined(__ia64__) /* SIGBUS when using SDL_memset() ?? */ - Uint8 *rowp = (Uint8 *)this->screen->pixels; - int left = this->screen->pitch*this->screen->h; - while ( left-- ) { *rowp++ = 0; } + int i, j; + + if (this->screen) { + /* Clear screen and tell SDL not to free the pixels */ + if (this->screen->pixels && FB_InGraphicsMode(this)) { +#if defined(__powerpc__) || defined(__ia64__) /* SIGBUS when using SDL_memset() ?? */ + Uint8 *rowp = (Uint8 *) this->screen->pixels; + int left = this->screen->pitch * this->screen->h; + while (left--) { + *rowp++ = 0; + } #else - SDL_memset(this->screen->pixels,0,this->screen->h*this->screen->pitch); + SDL_memset(this->screen->pixels, 0, + this->screen->h * this->screen->pitch); #endif - } - /* This test fails when using the VGA16 shadow memory */ - if ( ((char *)this->screen->pixels >= mapped_mem) && - ((char *)this->screen->pixels < (mapped_mem+mapped_memlen)) ) { - this->screen->pixels = NULL; - } - } - - /* Clear the lock mutex */ - if ( hw_lock ) { - SDL_DestroyMutex(hw_lock); - hw_lock = NULL; - } - - /* Clean up defined video modes */ - for ( i=0; i 0 ) { - /* Unmap the video framebuffer and I/O registers */ - if ( mapped_mem ) { - munmap(mapped_mem, mapped_memlen); - mapped_mem = NULL; - } - if ( mapped_io ) { - munmap(mapped_io, mapped_iolen); - mapped_io = NULL; - } - - /* Restore the original video mode and palette */ - if ( FB_InGraphicsMode(this) ) { - FB_RestorePalette(this); - ioctl(console_fd, FBIOPUT_VSCREENINFO, &saved_vinfo); - } - - /* We're all done with the framebuffer */ - close(console_fd); - console_fd = -1; - } - FB_CloseMouse(this); - FB_CloseKeyboard(this); + } + /* This test fails when using the VGA16 shadow memory */ + if (((char *) this->screen->pixels >= mapped_mem) && + ((char *) this->screen->pixels < (mapped_mem + mapped_memlen))) { + this->screen->pixels = NULL; + } + } + + /* Clear the lock mutex */ + if (hw_lock) { + SDL_DestroyMutex(hw_lock); + hw_lock = NULL; + } + + /* Clean up defined video modes */ + for (i = 0; i < NUM_MODELISTS; ++i) { + if (SDL_modelist[i] != NULL) { + for (j = 0; SDL_modelist[i][j]; ++j) { + SDL_free(SDL_modelist[i][j]); + } + SDL_free(SDL_modelist[i]); + SDL_modelist[i] = NULL; + } + } + + /* Clean up the memory bucket list */ + FB_FreeHWSurfaces(this); + + /* Close console and input file descriptors */ + if (console_fd > 0) { + /* Unmap the video framebuffer and I/O registers */ + if (mapped_mem) { + munmap(mapped_mem, mapped_memlen); + mapped_mem = NULL; + } + if (mapped_io) { + munmap(mapped_io, mapped_iolen); + mapped_io = NULL; + } + + /* Restore the original video mode and palette */ + if (FB_InGraphicsMode(this)) { + FB_RestorePalette(this); + ioctl(console_fd, FBIOPUT_VSCREENINFO, &saved_vinfo); + } + + /* We're all done with the framebuffer */ + close(console_fd); + console_fd = -1; + } + FB_CloseMouse(this); + FB_CloseKeyboard(this); } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/fbcon/SDL_fbvideo.h b/src/video/fbcon/SDL_fbvideo.h index 8a8fa10f0..cadf05605 100644 --- a/src/video/fbcon/SDL_fbvideo.h +++ b/src/video/fbcon/SDL_fbvideo.h @@ -40,59 +40,61 @@ /* This is the structure we use to keep track of video memory */ -typedef struct vidmem_bucket { - struct vidmem_bucket *prev; - int used; - int dirty; - char *base; - unsigned int size; - struct vidmem_bucket *next; +typedef struct vidmem_bucket +{ + struct vidmem_bucket *prev; + int used; + int dirty; + char *base; + unsigned int size; + struct vidmem_bucket *next; } vidmem_bucket; /* Private display data */ -struct SDL_PrivateVideoData { - int console_fd; - struct fb_var_screeninfo cache_vinfo; - struct fb_var_screeninfo saved_vinfo; - int saved_cmaplen; - __u16 *saved_cmap; - - int current_vt; - int saved_vt; - int keyboard_fd; - int saved_kbd_mode; - struct termios saved_kbd_termios; - - int mouse_fd; +struct SDL_PrivateVideoData +{ + int console_fd; + struct fb_var_screeninfo cache_vinfo; + struct fb_var_screeninfo saved_vinfo; + int saved_cmaplen; + __u16 *saved_cmap; + + int current_vt; + int saved_vt; + int keyboard_fd; + int saved_kbd_mode; + struct termios saved_kbd_termios; + + int mouse_fd; #if SDL_INPUT_TSLIB - struct tsdev *ts_dev; + struct tsdev *ts_dev; #endif - char *mapped_mem; - int mapped_memlen; - int mapped_offset; - char *mapped_io; - long mapped_iolen; - int flip_page; - char *flip_address[2]; - -#define NUM_MODELISTS 4 /* 8, 16, 24, and 32 bits-per-pixel */ - int SDL_nummodes[NUM_MODELISTS]; - SDL_Rect **SDL_modelist[NUM_MODELISTS]; - - vidmem_bucket surfaces; - int surfaces_memtotal; - int surfaces_memleft; - - SDL_mutex *hw_lock; - int switched_away; - struct fb_var_screeninfo screen_vinfo; - Uint32 screen_arealen; - Uint8 *screen_contents; - __u16 screen_palette[3*256]; - - void (*wait_vbl)(_THIS); - void (*wait_idle)(_THIS); + char *mapped_mem; + int mapped_memlen; + int mapped_offset; + char *mapped_io; + long mapped_iolen; + int flip_page; + char *flip_address[2]; + +#define NUM_MODELISTS 4 /* 8, 16, 24, and 32 bits-per-pixel */ + int SDL_nummodes[NUM_MODELISTS]; + SDL_Rect **SDL_modelist[NUM_MODELISTS]; + + vidmem_bucket surfaces; + int surfaces_memtotal; + int surfaces_memleft; + + SDL_mutex *hw_lock; + int switched_away; + struct fb_var_screeninfo screen_vinfo; + Uint32 screen_arealen; + Uint8 *screen_contents; + __u16 screen_palette[3 * 256]; + + void (*wait_vbl) (_THIS); + void (*wait_idle) (_THIS); }; /* Old variable names */ #define console_fd (this->hidden->console_fd) @@ -134,49 +136,54 @@ struct SDL_PrivateVideoData { necessarily in the kernel headers on the system we compile on. */ #ifndef FB_ACCEL_MATROX_MGAG400 -#define FB_ACCEL_MATROX_MGAG400 26 /* Matrox G400 */ +#define FB_ACCEL_MATROX_MGAG400 26 /* Matrox G400 */ #endif #ifndef FB_ACCEL_3DFX_BANSHEE -#define FB_ACCEL_3DFX_BANSHEE 31 /* 3Dfx Banshee */ +#define FB_ACCEL_3DFX_BANSHEE 31 /* 3Dfx Banshee */ #endif /* These functions are defined in SDL_fbvideo.c */ -extern void FB_SavePaletteTo(_THIS, int palette_len, __u16 *area); -extern void FB_RestorePaletteFrom(_THIS, int palette_len, __u16 *area); +extern void FB_SavePaletteTo(_THIS, int palette_len, __u16 * area); +extern void FB_RestorePaletteFrom(_THIS, int palette_len, __u16 * area); /* These are utility functions for working with video surfaces */ -static __inline__ void FB_AddBusySurface(SDL_Surface *surface) +static __inline__ void +FB_AddBusySurface(SDL_Surface * surface) { - ((vidmem_bucket *)surface->hwdata)->dirty = 1; + ((vidmem_bucket *) surface->hwdata)->dirty = 1; } -static __inline__ int FB_IsSurfaceBusy(SDL_Surface *surface) +static __inline__ int +FB_IsSurfaceBusy(SDL_Surface * surface) { - return ((vidmem_bucket *)surface->hwdata)->dirty; + return ((vidmem_bucket *) surface->hwdata)->dirty; } -static __inline__ void FB_WaitBusySurfaces(_THIS) +static __inline__ void +FB_WaitBusySurfaces(_THIS) { - vidmem_bucket *bucket; + vidmem_bucket *bucket; - /* Wait for graphic operations to complete */ - wait_idle(this); + /* Wait for graphic operations to complete */ + wait_idle(this); - /* Clear all surface dirty bits */ - for ( bucket=&surfaces; bucket; bucket=bucket->next ) { - bucket->dirty = 0; - } + /* Clear all surface dirty bits */ + for (bucket = &surfaces; bucket; bucket = bucket->next) { + bucket->dirty = 0; + } } -static __inline__ void FB_dst_to_xy(_THIS, SDL_Surface *dst, int *x, int *y) +static __inline__ void +FB_dst_to_xy(_THIS, SDL_Surface * dst, int *x, int *y) { - *x = (long)((char *)dst->pixels - mapped_mem)%this->screen->pitch; - *y = (long)((char *)dst->pixels - mapped_mem)/this->screen->pitch; - if ( dst == this->screen ) { - *x += this->offset_x; - *y += this->offset_y; - } + *x = (long) ((char *) dst->pixels - mapped_mem) % this->screen->pitch; + *y = (long) ((char *) dst->pixels - mapped_mem) / this->screen->pitch; + if (dst == this->screen) { + *x += this->offset_x; + *y += this->offset_y; + } } #endif /* _SDL_fbvideo_h */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/fbcon/matrox_mmio.h b/src/video/fbcon/matrox_mmio.h index 99c766135..29a8aee52 100644 --- a/src/video/fbcon/matrox_mmio.h +++ b/src/video/fbcon/matrox_mmio.h @@ -48,4 +48,4 @@ while ( mga_in32(MGAREG_STATUS) & 0x10000 ) \ ; \ } - +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/fbcon/matrox_regs.h b/src/video/fbcon/matrox_regs.h index d570b0c9b..f05bae731 100644 --- a/src/video/fbcon/matrox_regs.h +++ b/src/video/fbcon/matrox_regs.h @@ -15,7 +15,7 @@ * g.desbief@aix.pacwan.net * MGA1064SG Mystique register file */ - + #ifndef _MGA_REG_H_ #define _MGA_REG_H_ @@ -153,7 +153,7 @@ /* z drawing mode. use MGADWG_NOZCMP for always */ #define MGADWG_NOZCMP ( 0x00 << 8 ) -#define MGADWG_ZE ( 0x02 << 8 ) +#define MGADWG_ZE ( 0x02 << 8 ) #define MGADWG_ZNE ( 0x03 << 8 ) #define MGADWG_ZLT ( 0x04 << 8 ) #define MGADWG_ZLTE ( 0x05 << 8 ) @@ -190,7 +190,7 @@ #define MGADWG_BU24BGR ( 0x0b << 25 ) #define MGADWG_BU24RGB ( 0x0f << 25 ) -#define MGADWG_REPLACE 0x000C0000 /* From Linux kernel sources */ +#define MGADWG_REPLACE 0x000C0000 /* From Linux kernel sources */ #define MGADWG_PATTERN ( 0x01 << 29 ) #define MGADWG_TRANSC ( 0x01 << 30 ) #define MGADWG_NOCLIP ( 0x01 << 31 ) @@ -204,7 +204,7 @@ #define MGAREG_MISC_CLK_SEL_MGA_MSK (0x3 << 2) #define MGAREG_MISC_VIDEO_DIS (0x1 << 4) #define MGAREG_MISC_HIGH_PG_SEL (0x1 << 5) - + /* MMIO VGA registers */ #define MGAREG_CRTC_INDEX 0x1fd4 #define MGAREG_CRTC_DATA 0x1fd5 @@ -373,4 +373,4 @@ #define MGA1064_PIX_PLL_STAT 0x4f #endif - +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/fbcon/riva_mmio.h b/src/video/fbcon/riva_mmio.h index e9261677b..da1d26b68 100644 --- a/src/video/fbcon/riva_mmio.h +++ b/src/video/fbcon/riva_mmio.h @@ -44,7 +44,7 @@ /* * Typedefs to force certain sized values. */ -typedef Uint8 U008; +typedef Uint8 U008; typedef Uint16 U016; typedef Uint32 U032; @@ -161,14 +161,14 @@ typedef volatile struct U016 FifoFree; U016 Nop; U032 reserved01[0x0BB]; - U032 reserved03[(0x040)-1]; + U032 reserved03[(0x040) - 1]; U032 Color1A; struct { U032 TopLeft; U032 WidthHeight; } UnclippedRectangle[64]; - U032 reserved04[(0x080)-3]; + U032 reserved04[(0x080) - 3]; struct { U032 TopLeft; @@ -180,7 +180,7 @@ typedef volatile struct U032 TopLeft; U032 BottomRight; } ClippedRectangle[64]; - U032 reserved05[(0x080)-5]; + U032 reserved05[(0x080) - 5]; struct { U032 TopLeft; @@ -190,7 +190,7 @@ typedef volatile struct U032 WidthHeightC; U032 PointC; U032 MonochromeData1C; - U032 reserved06[(0x080)+121]; + U032 reserved06[(0x080) + 121]; struct { U032 TopLeft; @@ -201,7 +201,7 @@ typedef volatile struct U032 WidthHeightOutD; U032 PointD; U032 MonochromeData1D; - U032 reserved07[(0x080)+120]; + U032 reserved07[(0x080) + 120]; struct { U032 TopLeft; @@ -283,27 +283,31 @@ typedef volatile struct U016 FifoFree; U016 Nop[1]; U032 reserved01[0x0BC]; - U032 Color; /* source color 0304-0307*/ + U032 Color; /* source color 0304-0307 */ U032 Reserved02[0x03e]; - struct { /* start aliased methods in array 0400- */ - U032 point0; /* y_x S16_S16 in pixels 0- 3*/ - U032 point1; /* y_x S16_S16 in pixels 4- 7*/ - } Lin[16]; /* end of aliased methods in array -047f*/ - struct { /* start aliased methods in array 0480- */ - U032 point0X; /* in pixels, 0 at left 0- 3*/ - U032 point0Y; /* in pixels, 0 at top 4- 7*/ - U032 point1X; /* in pixels, 0 at left 8- b*/ - U032 point1Y; /* in pixels, 0 at top c- f*/ - } Lin32[8]; /* end of aliased methods in array -04ff*/ - U032 PolyLin[32]; /* y_x S16_S16 in pixels 0500-057f*/ - struct { /* start aliased methods in array 0580- */ - U032 x; /* in pixels, 0 at left 0- 3*/ - U032 y; /* in pixels, 0 at top 4- 7*/ - } PolyLin32[16]; /* end of aliased methods in array -05ff*/ - struct { /* start aliased methods in array 0600- */ - U032 color; /* source color 0- 3*/ - U032 point; /* y_x S16_S16 in pixels 4- 7*/ - } ColorPolyLin[16]; /* end of aliased methods in array -067f*/ + struct + { /* start aliased methods in array 0400- */ + U032 point0; /* y_x S16_S16 in pixels 0- 3 */ + U032 point1; /* y_x S16_S16 in pixels 4- 7 */ + } Lin[16]; /* end of aliased methods in array -047f */ + struct + { /* start aliased methods in array 0480- */ + U032 point0X; /* in pixels, 0 at left 0- 3 */ + U032 point0Y; /* in pixels, 0 at top 4- 7 */ + U032 point1X; /* in pixels, 0 at left 8- b */ + U032 point1Y; /* in pixels, 0 at top c- f */ + } Lin32[8]; /* end of aliased methods in array -04ff */ + U032 PolyLin[32]; /* y_x S16_S16 in pixels 0500-057f */ + struct + { /* start aliased methods in array 0580- */ + U032 x; /* in pixels, 0 at left 0- 3 */ + U032 y; /* in pixels, 0 at top 4- 7 */ + } PolyLin32[16]; /* end of aliased methods in array -05ff */ + struct + { /* start aliased methods in array 0600- */ + U032 color; /* source color 0- 3 */ + U032 point; /* y_x S16_S16 in pixels 4- 7 */ + } ColorPolyLin[16]; /* end of aliased methods in array -067f */ } RivaLine; /* * 2D/3D surfaces @@ -326,7 +330,7 @@ typedef volatile struct U032 RenderBufferOffset; U032 ZBufferOffset; } RivaSurface3D; - + /***************************************************************************\ * * * Virtualized RIVA H/W interface. * @@ -377,15 +381,17 @@ typedef struct _riva_hw_inst /* * Common chip functions. */ - int (*Busy)(struct _riva_hw_inst *); - void (*CalcStateExt)(struct _riva_hw_inst *,struct _riva_hw_state *,int,int,int,int,int,int,int,int,int,int,int,int,int); - void (*LoadStateExt)(struct _riva_hw_inst *,struct _riva_hw_state *); - void (*UnloadStateExt)(struct _riva_hw_inst *,struct _riva_hw_state *); - void (*SetStartAddress)(struct _riva_hw_inst *,U032); - void (*SetSurfaces2D)(struct _riva_hw_inst *,U032,U032); - void (*SetSurfaces3D)(struct _riva_hw_inst *,U032,U032); - int (*ShowHideCursor)(struct _riva_hw_inst *,int); - void (*LockUnlock)(struct _riva_hw_inst *, int); + int (*Busy) (struct _riva_hw_inst *); + void (*CalcStateExt) (struct _riva_hw_inst *, struct _riva_hw_state *, + int, int, int, int, int, int, int, int, int, int, + int, int, int); + void (*LoadStateExt) (struct _riva_hw_inst *, struct _riva_hw_state *); + void (*UnloadStateExt) (struct _riva_hw_inst *, struct _riva_hw_state *); + void (*SetStartAddress) (struct _riva_hw_inst *, U032); + void (*SetSurfaces2D) (struct _riva_hw_inst *, U032, U032); + void (*SetSurfaces3D) (struct _riva_hw_inst *, U032, U032); + int (*ShowHideCursor) (struct _riva_hw_inst *, int); + void (*LockUnlock) (struct _riva_hw_inst *, int); /* * Current extended mode settings. */ @@ -393,15 +399,15 @@ typedef struct _riva_hw_inst /* * FIFO registers. */ - RivaRop *Rop; - RivaPattern *Patt; - RivaClip *Clip; - RivaPixmap *Pixmap; - RivaScreenBlt *Blt; - RivaBitmap *Bitmap; - RivaLine *Line; - RivaTexturedTriangle03 *Tri03; - RivaTexturedTriangle05 *Tri05; + RivaRop *Rop; + RivaPattern *Patt; + RivaClip *Clip; + RivaPixmap *Pixmap; + RivaScreenBlt *Blt; + RivaBitmap *Bitmap; + RivaLine *Line; + RivaTexturedTriangle03 *Tri03; + RivaTexturedTriangle05 *Tri05; } RIVA_HW_INST; /* * Extended mode state information. @@ -446,4 +452,4 @@ typedef struct _riva_hw_state FifoFreeCount -= (cnt); \ } #endif /* __RIVA_HW_H__ */ - +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/fbcon/riva_regs.h b/src/video/fbcon/riva_regs.h index 4a21c0711..a6f313cab 100644 --- a/src/video/fbcon/riva_regs.h +++ b/src/video/fbcon/riva_regs.h @@ -40,4 +40,4 @@ #define PCIO_OFFSET 0x00601000 #endif /* _RIVA_REGS_H */ - +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/gapi/SDL_gapivideo.c b/src/video/gapi/SDL_gapivideo.c index 93648f983..40da2afef 100644 --- a/src/video/gapi/SDL_gapivideo.c +++ b/src/video/gapi/SDL_gapivideo.c @@ -50,7 +50,7 @@ Inspired by http://arisme.free.fr/ports/SDL.php #include "../../events/SDL_events_c.h" #include "../wincommon/SDL_syswm_c.h" #include "../wincommon/SDL_sysmouse_c.h" -#include "../windib/SDL_dibevents_c.h" +#include "../windib/SDL_dibevents_c.h" #include "SDL_gapivideo.h" @@ -77,30 +77,34 @@ extern void SDL_UnregisterApp(); extern int DIB_AddMode(_THIS, int bpp, int w, int h); /* Initialization/Query functions */ -static int GAPI_VideoInit(_THIS, SDL_PixelFormat *vformat); -static SDL_Rect **GAPI_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags); -static SDL_Surface *GAPI_SetVideoMode(_THIS, SDL_Surface *current, int width, int height, int bpp, Uint32 flags); -static int GAPI_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color *colors); +static int GAPI_VideoInit(_THIS, SDL_PixelFormat * vformat); +static SDL_Rect **GAPI_ListModes(_THIS, SDL_PixelFormat * format, + Uint32 flags); +static SDL_Surface *GAPI_SetVideoMode(_THIS, SDL_Surface * current, + int width, int height, int bpp, + Uint32 flags); +static int GAPI_SetColors(_THIS, int firstcolor, int ncolors, + SDL_Color * colors); static void GAPI_VideoQuit(_THIS); /* Hardware surface functions */ -static int GAPI_AllocHWSurface(_THIS, SDL_Surface *surface); -static int GAPI_LockHWSurface(_THIS, SDL_Surface *surface); -static void GAPI_UnlockHWSurface(_THIS, SDL_Surface *surface); -static void GAPI_FreeHWSurface(_THIS, SDL_Surface *surface); +static int GAPI_AllocHWSurface(_THIS, SDL_Surface * surface); +static int GAPI_LockHWSurface(_THIS, SDL_Surface * surface); +static void GAPI_UnlockHWSurface(_THIS, SDL_Surface * surface); +static void GAPI_FreeHWSurface(_THIS, SDL_Surface * surface); /* Windows message handling functions, will not be processed */ static void GAPI_RealizePalette(_THIS); static void GAPI_PaletteChanged(_THIS, HWND window); -static void GAPI_WinPAINT(_THIS, HDC hdc); +static void GAPI_WinPAINT(_THIS, HDC hdc); /* etc. */ -static void GAPI_UpdateRects(_THIS, int numrects, SDL_Rect *rects); +static void GAPI_UpdateRects(_THIS, int numrects, SDL_Rect * rects); static HMODULE g_hGapiLib = 0; #define LINK(type,name,import) \ if( g_hGapiLib ) \ - name = (PFN##type)GetProcAddress( g_hGapiLib, _T(import) ); + name = (PFN##type)GetProcAddress( g_hGapiLib, _T(import) ); static char g_bRawBufferAvailable = 0; @@ -109,16 +113,16 @@ static char g_bRawBufferAvailable = 0; /* hi res definitions */ typedef struct _RawFrameBufferInfo { - WORD wFormat; - WORD wBPP; - VOID *pFramePointer; - int cxStride; - int cyStride; - int cxPixels; - int cyPixels; -} RawFrameBufferInfo; + WORD wFormat; + WORD wBPP; + VOID *pFramePointer; + int cxStride; + int cyStride; + int cxPixels; + int cyPixels; +} RawFrameBufferInfo; -static struct _RawFrameBufferInfo g_RawFrameBufferInfo = {0}; +static struct _RawFrameBufferInfo g_RawFrameBufferInfo = { 0 }; #define GETRAWFRAMEBUFFER 0x00020001 @@ -134,806 +138,809 @@ static struct _RawFrameBufferInfo g_RawFrameBufferInfo = {0}; typedef struct GXDeviceInfo { -long Version; //00 (should filled with 100 before calling ExtEscape) -void * pvFrameBuffer; //04 -unsigned long cbStride; //08 -unsigned long cxWidth; //0c -unsigned long cyHeight; //10 -unsigned long cBPP; //14 -unsigned long ffFormat; //18 -char Unused[0x84-7*4]; -} GXDeviceInfo; - -static int GAPI_Available(void) + long Version; //00 (should filled with 100 before calling ExtEscape) + void *pvFrameBuffer; //04 + unsigned long cbStride; //08 + unsigned long cxWidth; //0c + unsigned long cyHeight; //10 + unsigned long cBPP; //14 + unsigned long ffFormat; //18 + char Unused[0x84 - 7 * 4]; +} GXDeviceInfo; + +static int +GAPI_Available(void) { - // try to use VGA display, even on emulator - HDC hdc = GetDC(NULL); - int result = ExtEscape(hdc, GETRAWFRAMEBUFFER, 0, NULL, sizeof(RawFrameBufferInfo), (char *)&g_RawFrameBufferInfo); - ReleaseDC(NULL, hdc); - g_bRawBufferAvailable = result > 0; + // try to use VGA display, even on emulator + HDC hdc = GetDC(NULL); + int result = ExtEscape(hdc, GETRAWFRAMEBUFFER, 0, NULL, + sizeof(RawFrameBufferInfo), + (char *) &g_RawFrameBufferInfo); + ReleaseDC(NULL, hdc); + g_bRawBufferAvailable = result > 0; #if WITHOUT_GAPI - return g_bRawBufferAvailable; + return g_bRawBufferAvailable; #endif #if USE_GAPI_EMU - g_hGapiLib = LoadLibrary(_T("GAPI_Emu.dll")); - if( !g_hGapiLib ) - { - SDL_SetError("Gapi Emu not found!"); - } - return g_hGapiLib != 0; + g_hGapiLib = LoadLibrary(_T("GAPI_Emu.dll")); + if (!g_hGapiLib) { + SDL_SetError("Gapi Emu not found!"); + } + return g_hGapiLib != 0; #endif - // try to find gx.dll - g_hGapiLib = LoadLibrary(_T("\\Windows\\gx.dll")); - if( !g_hGapiLib ) - { - g_hGapiLib = LoadLibrary(_T("gx.dll")); - if( !g_hGapiLib ) return g_bRawBufferAvailable; - } + // try to find gx.dll + g_hGapiLib = LoadLibrary(_T("\\Windows\\gx.dll")); + if (!g_hGapiLib) { + g_hGapiLib = LoadLibrary(_T("gx.dll")); + if (!g_hGapiLib) + return g_bRawBufferAvailable; + } - return(1); + return (1); } -static int cmpmodes(const void *va, const void *vb) +static int +cmpmodes(const void *va, const void *vb) { - SDL_Rect *a = *(SDL_Rect **)va; - SDL_Rect *b = *(SDL_Rect **)vb; - if ( a->w == b->w ) + SDL_Rect *a = *(SDL_Rect **) va; + SDL_Rect *b = *(SDL_Rect **) vb; + if (a->w == b->w) return b->h - a->h; else return b->w - a->w; } -static int GAPI_AddMode(_THIS, int bpp, int w, int h) +static int +GAPI_AddMode(_THIS, int bpp, int w, int h) { - SDL_Rect *mode; - int i, index; - int next_mode; - - /* Check to see if we already have this mode */ - if ( bpp < 8 ) { /* Not supported */ - return(0); - } - index = ((bpp+7)/8)-1; - for ( i=0; iSDL_nummodes[index]; ++i ) { - mode = gapi->SDL_modelist[index][i]; - if ( (mode->w == w) && (mode->h == h) ) { - return(0); - } - } - - /* Set up the new video mode rectangle */ - mode = (SDL_Rect *)SDL_malloc(sizeof *mode); - if ( mode == NULL ) { - SDL_OutOfMemory(); - return(-1); - } - mode->x = 0; - mode->y = 0; - mode->w = w; - mode->h = h; - - /* Allocate the new list of modes, and fill in the new mode */ - next_mode = gapi->SDL_nummodes[index]; - gapi->SDL_modelist[index] = (SDL_Rect **) - SDL_realloc(gapi->SDL_modelist[index], (1+next_mode+1)*sizeof(SDL_Rect *)); - if ( gapi->SDL_modelist[index] == NULL ) { - SDL_OutOfMemory(); - gapi->SDL_nummodes[index] = 0; - SDL_free(mode); - return(-1); - } - gapi->SDL_modelist[index][next_mode] = mode; - gapi->SDL_modelist[index][next_mode+1] = NULL; - gapi->SDL_nummodes[index]++; - - return(0); + SDL_Rect *mode; + int i, index; + int next_mode; + + /* Check to see if we already have this mode */ + if (bpp < 8) { /* Not supported */ + return (0); + } + index = ((bpp + 7) / 8) - 1; + for (i = 0; i < gapi->SDL_nummodes[index]; ++i) { + mode = gapi->SDL_modelist[index][i]; + if ((mode->w == w) && (mode->h == h)) { + return (0); + } + } + + /* Set up the new video mode rectangle */ + mode = (SDL_Rect *) SDL_malloc(sizeof *mode); + if (mode == NULL) { + SDL_OutOfMemory(); + return (-1); + } + mode->x = 0; + mode->y = 0; + mode->w = w; + mode->h = h; + + /* Allocate the new list of modes, and fill in the new mode */ + next_mode = gapi->SDL_nummodes[index]; + gapi->SDL_modelist[index] = (SDL_Rect **) + SDL_realloc(gapi->SDL_modelist[index], + (1 + next_mode + 1) * sizeof(SDL_Rect *)); + if (gapi->SDL_modelist[index] == NULL) { + SDL_OutOfMemory(); + gapi->SDL_nummodes[index] = 0; + SDL_free(mode); + return (-1); + } + gapi->SDL_modelist[index][next_mode] = mode; + gapi->SDL_modelist[index][next_mode + 1] = NULL; + gapi->SDL_nummodes[index]++; + + return (0); } -static void GAPI_DeleteDevice(SDL_VideoDevice *device) +static void +GAPI_DeleteDevice(SDL_VideoDevice * device) { - if( g_hGapiLib ) - { - FreeLibrary(g_hGapiLib); - g_hGapiLib = 0; - } - SDL_free(device->hidden); - SDL_free(device); + if (g_hGapiLib) { + FreeLibrary(g_hGapiLib); + g_hGapiLib = 0; + } + SDL_free(device->hidden); + SDL_free(device); } -static SDL_VideoDevice *GAPI_CreateDevice(int devindex) +static SDL_VideoDevice * +GAPI_CreateDevice(int devindex) { - SDL_VideoDevice *device; - - if( !g_hGapiLib && !g_bRawBufferAvailable) - { - if( !GAPI_Available() ) - { - SDL_SetError("GAPI dll is not found and VGA mode is not available!"); - return 0; - } - } - - /* Initialize all variables that we clean on shutdown */ - device = (SDL_VideoDevice *)SDL_malloc(sizeof(SDL_VideoDevice)); - if ( device ) { - SDL_memset(device, 0, (sizeof *device)); - device->hidden = (struct SDL_PrivateVideoData *) - SDL_malloc((sizeof *device->hidden)); - } - if ( (device == NULL) || (device->hidden == NULL) ) { - SDL_OutOfMemory(); - if ( device ) { - SDL_free(device); - } - return(0); - } - SDL_memset(device->hidden, 0, (sizeof *device->hidden)); - - /* Set the function pointers */ - device->VideoInit = GAPI_VideoInit; - device->ListModes = GAPI_ListModes; - device->SetVideoMode = GAPI_SetVideoMode; - device->UpdateMouse = WIN_UpdateMouse; - device->CreateYUVOverlay = NULL; - device->SetColors = GAPI_SetColors; - device->UpdateRects = GAPI_UpdateRects; - device->VideoQuit = GAPI_VideoQuit; - device->AllocHWSurface = GAPI_AllocHWSurface; - device->CheckHWBlit = NULL; - device->FillHWRect = NULL; - device->SetHWColorKey = NULL; - device->SetHWAlpha = NULL; - device->LockHWSurface = GAPI_LockHWSurface; - device->UnlockHWSurface = GAPI_UnlockHWSurface; - device->FlipHWSurface = NULL; - device->FreeHWSurface = GAPI_FreeHWSurface; - device->SetCaption = WIN_SetWMCaption; - device->SetIcon = WIN_SetWMIcon; - device->IconifyWindow = WIN_IconifyWindow; - device->GrabInput = WIN_GrabInput; - device->GetWMInfo = WIN_GetWMInfo; - device->FreeWMCursor = WIN_FreeWMCursor; - device->CreateWMCursor = WIN_CreateWMCursor; - device->ShowWMCursor = WIN_ShowWMCursor; - device->WarpWMCursor = WIN_WarpWMCursor; + SDL_VideoDevice *device; + + if (!g_hGapiLib && !g_bRawBufferAvailable) { + if (!GAPI_Available()) { + SDL_SetError + ("GAPI dll is not found and VGA mode is not available!"); + return 0; + } + } + + /* Initialize all variables that we clean on shutdown */ + device = (SDL_VideoDevice *) SDL_malloc(sizeof(SDL_VideoDevice)); + if (device) { + SDL_memset(device, 0, (sizeof *device)); + device->hidden = (struct SDL_PrivateVideoData *) + SDL_malloc((sizeof *device->hidden)); + } + if ((device == NULL) || (device->hidden == NULL)) { + SDL_OutOfMemory(); + if (device) { + SDL_free(device); + } + return (0); + } + SDL_memset(device->hidden, 0, (sizeof *device->hidden)); + + /* Set the function pointers */ + device->VideoInit = GAPI_VideoInit; + device->ListModes = GAPI_ListModes; + device->SetVideoMode = GAPI_SetVideoMode; + device->UpdateMouse = WIN_UpdateMouse; + device->CreateYUVOverlay = NULL; + device->SetColors = GAPI_SetColors; + device->UpdateRects = GAPI_UpdateRects; + device->VideoQuit = GAPI_VideoQuit; + device->AllocHWSurface = GAPI_AllocHWSurface; + device->CheckHWBlit = NULL; + device->FillHWRect = NULL; + device->SetHWColorKey = NULL; + device->SetHWAlpha = NULL; + device->LockHWSurface = GAPI_LockHWSurface; + device->UnlockHWSurface = GAPI_UnlockHWSurface; + device->FlipHWSurface = NULL; + device->FreeHWSurface = GAPI_FreeHWSurface; + device->SetCaption = WIN_SetWMCaption; + device->SetIcon = WIN_SetWMIcon; + device->IconifyWindow = WIN_IconifyWindow; + device->GrabInput = WIN_GrabInput; + device->GetWMInfo = WIN_GetWMInfo; + device->FreeWMCursor = WIN_FreeWMCursor; + device->CreateWMCursor = WIN_CreateWMCursor; + device->ShowWMCursor = WIN_ShowWMCursor; + device->WarpWMCursor = WIN_WarpWMCursor; device->CheckMouseMode = WIN_CheckMouseMode; - device->InitOSKeymap = DIB_InitOSKeymap; - device->PumpEvents = DIB_PumpEvents; + device->InitOSKeymap = DIB_InitOSKeymap; + device->PumpEvents = DIB_PumpEvents; - /* Set up the windows message handling functions */ - WIN_RealizePalette = GAPI_RealizePalette; - WIN_PaletteChanged = GAPI_PaletteChanged; - WIN_WinPAINT = GAPI_WinPAINT; - HandleMessage = DIB_HandleMessage; + /* Set up the windows message handling functions */ + WIN_RealizePalette = GAPI_RealizePalette; + WIN_PaletteChanged = GAPI_PaletteChanged; + WIN_WinPAINT = GAPI_WinPAINT; + HandleMessage = DIB_HandleMessage; - device->free = GAPI_DeleteDevice; + device->free = GAPI_DeleteDevice; - /* Load gapi library */ + /* Load gapi library */ #define gx device->hidden->gxFunc - LINK( GXOpenDisplay, gx.GXOpenDisplay, "?GXOpenDisplay@@YAHPAUHWND__@@K@Z" ) - LINK( GXCloseDisplay, gx.GXCloseDisplay, "?GXCloseDisplay@@YAHXZ" ) - LINK( GXBeginDraw, gx.GXBeginDraw, "?GXBeginDraw@@YAPAXXZ" ) - LINK( GXEndDraw, gx.GXEndDraw, "?GXEndDraw@@YAHXZ" ) - LINK( GXOpenInput, gx.GXOpenInput, "?GXOpenInput@@YAHXZ" ) - LINK( GXCloseInput, gx.GXCloseInput, "?GXCloseInput@@YAHXZ" ) - LINK( GXGetDisplayProperties, gx.GXGetDisplayProperties,"?GXGetDisplayProperties@@YA?AUGXDisplayProperties@@XZ" ) - LINK( GXGetDefaultKeys, gx.GXGetDefaultKeys, "?GXGetDefaultKeys@@YA?AUGXKeyList@@H@Z" ) - LINK( GXSuspend, gx.GXSuspend, "?GXSuspend@@YAHXZ" ) - LINK( GXResume, gx.GXResume, "?GXResume@@YAHXZ" ) - LINK( GXSetViewport, gx.GXSetViewport, "?GXSetViewport@@YAHKKKK@Z" ) - LINK( GXIsDisplayDRAMBuffer, gx.GXIsDisplayDRAMBuffer, "?GXIsDisplayDRAMBuffer@@YAHXZ" ) - - /* wrong gapi.dll */ - if( !gx.GXOpenDisplay ) - { - if( g_hGapiLib ) - { - FreeLibrary(g_hGapiLib); - g_hGapiLib = 0; - } - } - - if( !gx.GXOpenDisplay && !g_bRawBufferAvailable) - { - SDL_SetError("Error: damaged or unknown gapi.dll!\n"); - GAPI_DeleteDevice(device); - return 0; - } - - return device; + LINK(GXOpenDisplay, gx.GXOpenDisplay, + "?GXOpenDisplay@@YAHPAUHWND__@@K@Z") LINK(GXCloseDisplay, + gx.GXCloseDisplay, + "?GXCloseDisplay@@YAHXZ") + LINK(GXBeginDraw, gx.GXBeginDraw, + "?GXBeginDraw@@YAPAXXZ") LINK(GXEndDraw, gx.GXEndDraw, + "?GXEndDraw@@YAHXZ") + LINK(GXOpenInput, gx.GXOpenInput, + "?GXOpenInput@@YAHXZ") LINK(GXCloseInput, gx.GXCloseInput, + "?GXCloseInput@@YAHXZ") + LINK(GXGetDisplayProperties, gx.GXGetDisplayProperties, + "?GXGetDisplayProperties@@YA?AUGXDisplayProperties@@XZ") + LINK(GXGetDefaultKeys, gx.GXGetDefaultKeys, + "?GXGetDefaultKeys@@YA?AUGXKeyList@@H@Z") LINK(GXSuspend, + gx.GXSuspend, + "?GXSuspend@@YAHXZ") + LINK(GXResume, gx.GXResume, "?GXResume@@YAHXZ") LINK(GXSetViewport, + gx. + GXSetViewport, + "?GXSetViewport@@YAHKKKK@Z") + LINK(GXIsDisplayDRAMBuffer, gx.GXIsDisplayDRAMBuffer, + "?GXIsDisplayDRAMBuffer@@YAHXZ") + /* wrong gapi.dll */ + if (!gx.GXOpenDisplay) { + if (g_hGapiLib) { + FreeLibrary(g_hGapiLib); + g_hGapiLib = 0; + } + } + + if (!gx.GXOpenDisplay && !g_bRawBufferAvailable) { + SDL_SetError("Error: damaged or unknown gapi.dll!\n"); + GAPI_DeleteDevice(device); + return 0; + } + + return device; } VideoBootStrap GAPI_bootstrap = { - GAPIVID_DRIVER_NAME, "WinCE GAPI video driver", - GAPI_Available, GAPI_CreateDevice + GAPIVID_DRIVER_NAME, "WinCE GAPI video driver", + GAPI_Available, GAPI_CreateDevice }; -static void FillStructs(_THIS, BOOL useVga) +static void +FillStructs(_THIS, BOOL useVga) { #ifdef _ARM_ - WCHAR oemstr[100]; + WCHAR oemstr[100]; #endif - /* fill a device properties */ + /* fill a device properties */ - if( !useVga ) - { - this->hidden->gxProperties = this->hidden->gxFunc.GXGetDisplayProperties(); - this->hidden->needUpdate = 1; - this->hidden->hiresFix = 0; - this->hidden->useVga = 0; - this->hidden->useGXOpenDisplay = 1; + if (!useVga) { + this->hidden->gxProperties = + this->hidden->gxFunc.GXGetDisplayProperties(); + this->hidden->needUpdate = 1; + this->hidden->hiresFix = 0; + this->hidden->useVga = 0; + this->hidden->useGXOpenDisplay = 1; #ifdef _ARM_ - /* check some devices and extract addition info */ - SystemParametersInfo( SPI_GETOEMINFO, sizeof( oemstr ), oemstr, 0 ); - - // buggy iPaq38xx - if ((oemstr[12] == 'H') && (oemstr[13] == '3') && (oemstr[14] == '8') && (this->hidden->gxProperties.cbxPitch > 0)) - { - this->hidden->videoMem = (PIXEL*)0xac0755a0; - this->hidden->gxProperties.cbxPitch = -640; - this->hidden->gxProperties.cbyPitch = 2; - this->hidden->needUpdate = 0; - } + /* check some devices and extract addition info */ + SystemParametersInfo(SPI_GETOEMINFO, sizeof(oemstr), oemstr, 0); + + // buggy iPaq38xx + if ((oemstr[12] == 'H') && (oemstr[13] == '3') + && (oemstr[14] == '8') + && (this->hidden->gxProperties.cbxPitch > 0)) { + this->hidden->videoMem = (PIXEL *) 0xac0755a0; + this->hidden->gxProperties.cbxPitch = -640; + this->hidden->gxProperties.cbyPitch = 2; + this->hidden->needUpdate = 0; + } #if (EMULATE_AXIM_X30 == 0) - // buggy Dell Axim X30 - if( _tcsncmp(oemstr, L"Dell Axim X30", 13) == 0 ) + // buggy Dell Axim X30 + if (_tcsncmp(oemstr, L"Dell Axim X30", 13) == 0) #endif - { - GXDeviceInfo gxInfo = {0}; - HDC hdc = GetDC(NULL); - int result; - - gxInfo.Version = 100; - result = ExtEscape(hdc, GETGXINFO, 0, NULL, sizeof(gxInfo), (char *)&gxInfo); - if( result > 0 ) - { - this->hidden->useGXOpenDisplay = 0; - this->hidden->videoMem = gxInfo.pvFrameBuffer; - this->hidden->needUpdate = 0; - this->hidden->gxProperties.cbxPitch = 2; - this->hidden->gxProperties.cbyPitch = 480; - this->hidden->gxProperties.cxWidth = gxInfo.cxWidth; - this->hidden->gxProperties.cyHeight = gxInfo.cyHeight; - this->hidden->gxProperties.ffFormat = gxInfo.ffFormat; - } - } + { + GXDeviceInfo gxInfo = { 0 }; + HDC hdc = GetDC(NULL); + int result; + + gxInfo.Version = 100; + result = + ExtEscape(hdc, GETGXINFO, 0, NULL, sizeof(gxInfo), + (char *) &gxInfo); + if (result > 0) { + this->hidden->useGXOpenDisplay = 0; + this->hidden->videoMem = gxInfo.pvFrameBuffer; + this->hidden->needUpdate = 0; + this->hidden->gxProperties.cbxPitch = 2; + this->hidden->gxProperties.cbyPitch = 480; + this->hidden->gxProperties.cxWidth = gxInfo.cxWidth; + this->hidden->gxProperties.cyHeight = gxInfo.cyHeight; + this->hidden->gxProperties.ffFormat = gxInfo.ffFormat; + } + } #endif - } else - { - this->hidden->needUpdate = 0; - this->hidden->hiresFix = 0; - this->hidden->gxProperties.cBPP = g_RawFrameBufferInfo.wBPP; - this->hidden->gxProperties.cbxPitch = g_RawFrameBufferInfo.cxStride; - this->hidden->gxProperties.cbyPitch = g_RawFrameBufferInfo.cyStride; - this->hidden->gxProperties.cxWidth = g_RawFrameBufferInfo.cxPixels; - this->hidden->gxProperties.cyHeight = g_RawFrameBufferInfo.cyPixels; - this->hidden->videoMem = g_RawFrameBufferInfo.pFramePointer; - this->hidden->useVga = 1; - - switch( g_RawFrameBufferInfo.wFormat ) - { - case FORMAT_565: - this->hidden->gxProperties.ffFormat = kfDirect565; - break; - case FORMAT_555: - this->hidden->gxProperties.ffFormat = kfDirect555; - break; - default: - /* unknown pixel format, try define by BPP! */ - switch( g_RawFrameBufferInfo.wBPP ) - { - case 4: - case 8: - this->hidden->gxProperties.ffFormat = kfDirect; - case 16: - this->hidden->gxProperties.ffFormat = kfDirect565; - default: - this->hidden->gxProperties.ffFormat = kfDirect; - break; - } - } - } - - if( this->hidden->gxProperties.cBPP != 16 ) - { - this->hidden->gapiOrientation = SDL_ORIENTATION_UP; - } else - if( (this->hidden->gxProperties.cbxPitch > 0) && (this->hidden->gxProperties.cbyPitch > 0 )) - { - this->hidden->gapiOrientation = SDL_ORIENTATION_UP; - } else - if( (this->hidden->gxProperties.cbxPitch > 0) && (this->hidden->gxProperties.cbyPitch < 0 )) - { - this->hidden->gapiOrientation = SDL_ORIENTATION_RIGHT; // ipaq 3660 - } else - if( (this->hidden->gxProperties.cbxPitch < 0) && (this->hidden->gxProperties.cbyPitch > 0 )) - { - this->hidden->gapiOrientation = SDL_ORIENTATION_LEFT; // ipaq 3800 - } + } else { + this->hidden->needUpdate = 0; + this->hidden->hiresFix = 0; + this->hidden->gxProperties.cBPP = g_RawFrameBufferInfo.wBPP; + this->hidden->gxProperties.cbxPitch = g_RawFrameBufferInfo.cxStride; + this->hidden->gxProperties.cbyPitch = g_RawFrameBufferInfo.cyStride; + this->hidden->gxProperties.cxWidth = g_RawFrameBufferInfo.cxPixels; + this->hidden->gxProperties.cyHeight = g_RawFrameBufferInfo.cyPixels; + this->hidden->videoMem = g_RawFrameBufferInfo.pFramePointer; + this->hidden->useVga = 1; + + switch (g_RawFrameBufferInfo.wFormat) { + case FORMAT_565: + this->hidden->gxProperties.ffFormat = kfDirect565; + break; + case FORMAT_555: + this->hidden->gxProperties.ffFormat = kfDirect555; + break; + default: + /* unknown pixel format, try define by BPP! */ + switch (g_RawFrameBufferInfo.wBPP) { + case 4: + case 8: + this->hidden->gxProperties.ffFormat = kfDirect; + case 16: + this->hidden->gxProperties.ffFormat = kfDirect565; + default: + this->hidden->gxProperties.ffFormat = kfDirect; + break; + } + } + } + + if (this->hidden->gxProperties.cBPP != 16) { + this->hidden->gapiOrientation = SDL_ORIENTATION_UP; + } else if ((this->hidden->gxProperties.cbxPitch > 0) + && (this->hidden->gxProperties.cbyPitch > 0)) { + this->hidden->gapiOrientation = SDL_ORIENTATION_UP; + } else if ((this->hidden->gxProperties.cbxPitch > 0) + && (this->hidden->gxProperties.cbyPitch < 0)) { + this->hidden->gapiOrientation = SDL_ORIENTATION_RIGHT; // ipaq 3660 + } else if ((this->hidden->gxProperties.cbxPitch < 0) + && (this->hidden->gxProperties.cbyPitch > 0)) { + this->hidden->gapiOrientation = SDL_ORIENTATION_LEFT; // ipaq 3800 + } } -static void GAPI_CreatePalette(int ncolors, SDL_Color *colors) +static void +GAPI_CreatePalette(int ncolors, SDL_Color * colors) { - // Setup a custom color palette - BYTE buffer[ sizeof(LOGPALETTE) + 255 * sizeof(PALETTEENTRY) ]; - int i; - LOGPALETTE* pLogical = (LOGPALETTE*)buffer; - PALETTEENTRY* entries = pLogical->palPalEntry; - HPALETTE hPalette; - HDC hdc; - - for (i = 0; i < ncolors; ++i) - { - // Find intensity by replicating the bit patterns over a byte - entries[i].peRed = colors[i].r; - entries[i].peGreen = colors[i].g; - entries[i].peBlue = colors[i].b; - entries[i].peFlags = 0; - } - - // Create the GDI palette object - pLogical->palVersion = 0x0300; - pLogical->palNumEntries = ncolors; - - hPalette = CreatePalette( pLogical ); - ASSERT(hPalette); - - - // Realize the palette - hdc = GetDC(0); - - SelectPalette( hdc, hPalette, FALSE ); - RealizePalette( hdc ); - - ReleaseDC( 0, hdc ); - DeleteObject( hPalette ); + // Setup a custom color palette + BYTE buffer[sizeof(LOGPALETTE) + 255 * sizeof(PALETTEENTRY)]; + int i; + LOGPALETTE *pLogical = (LOGPALETTE *) buffer; + PALETTEENTRY *entries = pLogical->palPalEntry; + HPALETTE hPalette; + HDC hdc; + + for (i = 0; i < ncolors; ++i) { + // Find intensity by replicating the bit patterns over a byte + entries[i].peRed = colors[i].r; + entries[i].peGreen = colors[i].g; + entries[i].peBlue = colors[i].b; + entries[i].peFlags = 0; + } + + // Create the GDI palette object + pLogical->palVersion = 0x0300; + pLogical->palNumEntries = ncolors; + + hPalette = CreatePalette(pLogical); + ASSERT(hPalette); + + + // Realize the palette + hdc = GetDC(0); + + SelectPalette(hdc, hPalette, FALSE); + RealizePalette(hdc); + + ReleaseDC(0, hdc); + DeleteObject(hPalette); } -int GAPI_VideoInit(_THIS, SDL_PixelFormat *vformat) +int +GAPI_VideoInit(_THIS, SDL_PixelFormat * vformat) { - int i,bpp; - - /* Create the window */ - if ( DIB_CreateWindow(this) < 0 ) { - return(-1); - } - - if( g_hGapiLib ) - { - FillStructs(this, 0); - - // SDL does not supports 2/4bpp mode, so use 16 bpp - bpp = gapi->gxProperties.cBPP < 8 ? 16 : gapi->gxProperties.cBPP; - - /* set up normal and landscape mode */ - GAPI_AddMode(this, bpp, gapi->gxProperties.cyHeight, gapi->gxProperties.cxWidth); - GAPI_AddMode(this, bpp, gapi->gxProperties.cxWidth, gapi->gxProperties.cyHeight); - } - - /* add hi-res mode */ - if( g_bRawBufferAvailable && - !((gapi->gxProperties.cxWidth == (unsigned)g_RawFrameBufferInfo.cxPixels) && (gapi->gxProperties.cyHeight == (unsigned)g_RawFrameBufferInfo.cyPixels))) - { - FillStructs(this, 1); - - // SDL does not supports 2/4bpp mode, so use 16 bpp - bpp = gapi->gxProperties.cBPP < 8 ? 16 : gapi->gxProperties.cBPP; - - /* set up normal and landscape mode */ - GAPI_AddMode(this, bpp, gapi->gxProperties.cyHeight, gapi->gxProperties.cxWidth); - GAPI_AddMode(this, bpp, gapi->gxProperties.cxWidth, gapi->gxProperties.cyHeight); - } - - /* Determine the current screen size */ - this->info.current_w = gapi->gxProperties.cxWidth; - this->info.current_h = gapi->gxProperties.cyHeight; - - /* Sort the mode lists */ - for ( i=0; iSDL_nummodes[i] > 0 ) { - SDL_qsort(gapi->SDL_modelist[i], gapi->SDL_nummodes[i], sizeof *gapi->SDL_modelist[i], cmpmodes); - } - } - - vformat->BitsPerPixel = this->hidden->gxProperties.cBPP < 8 ? 16 : (unsigned char)this->hidden->gxProperties.cBPP; - - // Get color mask - if (this->hidden->gxProperties.ffFormat & kfDirect565) { - vformat->BitsPerPixel = 16; - vformat->Rmask = 0x0000f800; - vformat->Gmask = 0x000007e0; - vformat->Bmask = 0x0000001f; - this->hidden->videoMode = GAPI_DIRECT_565; - } - else - if (this->hidden->gxProperties.ffFormat & kfDirect555) { - vformat->BitsPerPixel = 16; - vformat->Rmask = 0x00007c00; - vformat->Gmask = 0x000003e0; - vformat->Bmask = 0x0000001f; - this->hidden->videoMode = GAPI_DIRECT_555; - } - else - if ((this->hidden->gxProperties.ffFormat & kfDirect) && (this->hidden->gxProperties.cBPP < 8)) { - // We'll perform the conversion - vformat->BitsPerPixel = 16; - vformat->Rmask = 0x0000f800; // 16 bit 565 - vformat->Gmask = 0x000007e0; - vformat->Bmask = 0x0000001f; - if (this->hidden->gxProperties.ffFormat & kfDirectInverted) - this->hidden->invert = (1 << this->hidden->gxProperties.cBPP) - 1; - this->hidden->colorscale = this->hidden->gxProperties.cBPP < 8 ? 8 - this->hidden->gxProperties.cBPP : 0; - this->hidden->videoMode = GAPI_MONO; - } - else - if (this->hidden->gxProperties.ffFormat & kfPalette) { - this->hidden->videoMode = GAPI_PALETTE; - } - - /* We're done! */ - return(0); + int i, bpp; + + /* Create the window */ + if (DIB_CreateWindow(this) < 0) { + return (-1); + } + + if (g_hGapiLib) { + FillStructs(this, 0); + + // SDL does not supports 2/4bpp mode, so use 16 bpp + bpp = gapi->gxProperties.cBPP < 8 ? 16 : gapi->gxProperties.cBPP; + + /* set up normal and landscape mode */ + GAPI_AddMode(this, bpp, gapi->gxProperties.cyHeight, + gapi->gxProperties.cxWidth); + GAPI_AddMode(this, bpp, gapi->gxProperties.cxWidth, + gapi->gxProperties.cyHeight); + } + + /* add hi-res mode */ + if (g_bRawBufferAvailable && + !((gapi->gxProperties.cxWidth == + (unsigned) g_RawFrameBufferInfo.cxPixels) + && (gapi->gxProperties.cyHeight == + (unsigned) g_RawFrameBufferInfo.cyPixels))) { + FillStructs(this, 1); + + // SDL does not supports 2/4bpp mode, so use 16 bpp + bpp = gapi->gxProperties.cBPP < 8 ? 16 : gapi->gxProperties.cBPP; + + /* set up normal and landscape mode */ + GAPI_AddMode(this, bpp, gapi->gxProperties.cyHeight, + gapi->gxProperties.cxWidth); + GAPI_AddMode(this, bpp, gapi->gxProperties.cxWidth, + gapi->gxProperties.cyHeight); + } + + /* Determine the current screen size */ + this->info.current_w = gapi->gxProperties.cxWidth; + this->info.current_h = gapi->gxProperties.cyHeight; + + /* Sort the mode lists */ + for (i = 0; i < NUM_MODELISTS; ++i) { + if (gapi->SDL_nummodes[i] > 0) { + SDL_qsort(gapi->SDL_modelist[i], gapi->SDL_nummodes[i], + sizeof *gapi->SDL_modelist[i], cmpmodes); + } + } + + vformat->BitsPerPixel = + this->hidden->gxProperties.cBPP < + 8 ? 16 : (unsigned char) this->hidden->gxProperties.cBPP; + + // Get color mask + if (this->hidden->gxProperties.ffFormat & kfDirect565) { + vformat->BitsPerPixel = 16; + vformat->Rmask = 0x0000f800; + vformat->Gmask = 0x000007e0; + vformat->Bmask = 0x0000001f; + this->hidden->videoMode = GAPI_DIRECT_565; + } else if (this->hidden->gxProperties.ffFormat & kfDirect555) { + vformat->BitsPerPixel = 16; + vformat->Rmask = 0x00007c00; + vformat->Gmask = 0x000003e0; + vformat->Bmask = 0x0000001f; + this->hidden->videoMode = GAPI_DIRECT_555; + } else if ((this->hidden->gxProperties.ffFormat & kfDirect) + && (this->hidden->gxProperties.cBPP < 8)) { + // We'll perform the conversion + vformat->BitsPerPixel = 16; + vformat->Rmask = 0x0000f800; // 16 bit 565 + vformat->Gmask = 0x000007e0; + vformat->Bmask = 0x0000001f; + if (this->hidden->gxProperties.ffFormat & kfDirectInverted) + this->hidden->invert = (1 << this->hidden->gxProperties.cBPP) - 1; + this->hidden->colorscale = + this->hidden->gxProperties.cBPP < + 8 ? 8 - this->hidden->gxProperties.cBPP : 0; + this->hidden->videoMode = GAPI_MONO; + } else if (this->hidden->gxProperties.ffFormat & kfPalette) { + this->hidden->videoMode = GAPI_PALETTE; + } + + /* We're done! */ + return (0); } -SDL_Rect **GAPI_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags) +SDL_Rect ** +GAPI_ListModes(_THIS, SDL_PixelFormat * format, Uint32 flags) { - return(this->hidden->SDL_modelist[((format->BitsPerPixel+7)/8)-1]); -// return (SDL_Rect **) -1; + return (this->hidden->SDL_modelist[((format->BitsPerPixel + 7) / 8) - 1]); +// return (SDL_Rect **) -1; } -SDL_Surface *GAPI_SetVideoMode(_THIS, SDL_Surface *current, - int width, int height, int bpp, Uint32 flags) +SDL_Surface * +GAPI_SetVideoMode(_THIS, SDL_Surface * current, + int width, int height, int bpp, Uint32 flags) { - SDL_Surface *video; - Uint32 Rmask, Gmask, Bmask; - DWORD style; - SDL_Rect allScreen; - - if( bpp < 4 ) - { - SDL_SetError("1 bpp and 2 bpp modes is not implemented yet!"); - return 0; - } - - /* Recalculate bitmasks if necessary */ - if (bpp == current->format->BitsPerPixel) { - video = current; - } - else { - switch(bpp) { - case 8: - Rmask = 0; - Gmask = 0; - Bmask = 0; - break; - case 15: - case 16: - /* Default is 565 unless the display is specifically 555 */ - if (this->hidden->gxProperties.ffFormat & kfDirect555) { - Rmask = 0x00007c00; - Gmask = 0x000003e0; - Bmask = 0x0000001f; - } - else { - Rmask = 0x0000f800; - Gmask = 0x000007e0; - Bmask = 0x0000001f; - } - break; - case 24: - case 32: - Rmask = 0x00ff0000; - Gmask = 0x0000ff00; - Bmask = 0x000000ff; - break; - default: - SDL_SetError("Unsupported Bits Per Pixel format requested"); - return NULL; - } - video = SDL_CreateRGBSurface(SDL_SWSURFACE, - 0, 0, bpp, Rmask, Gmask, Bmask, 0); - if ( video == NULL ) { - SDL_OutOfMemory(); - return(NULL); - } - } - - gapi->userOrientation = SDL_ORIENTATION_UP; - video->flags = SDL_FULLSCREEN; /* Clear flags, GAPI supports fullscreen only */ - - /* GAPI or VGA? */ - if( g_hGapiLib ) - { - FillStructs(this, 0); - if( (((unsigned)width != gapi->gxProperties.cxWidth) || ((unsigned)height != gapi->gxProperties.cyHeight)) - && (((unsigned)width != gapi->gxProperties.cyHeight) || ((unsigned)height != gapi->gxProperties.cxWidth))) - FillStructs(this, 1); // gapi is found but we use VGA resolution - } else - FillStructs(this, 1); - - if ( !this->hidden->needUpdate && !this->hidden->videoMem) { - SDL_SetError("Couldn't get address of video memory, may be unsupported device or bug"); - return(NULL); - } - - /* detect user landscape mode */ - if( (width > height) && (GetSystemMetrics(SM_CXSCREEN) < GetSystemMetrics(SM_CYSCREEN))) - gapi->userOrientation = SDL_ORIENTATION_RIGHT; - - /* shall we apply hires fix? for example when we do not use hires resource */ - gapi->hiresFix = 0; - if( gapi->userOrientation == SDL_ORIENTATION_RIGHT ) - { - if( (width > GetSystemMetrics(SM_CYSCREEN)) || (height > GetSystemMetrics(SM_CXSCREEN))) - gapi->hiresFix = 1; - } else - if( (width > GetSystemMetrics(SM_CXSCREEN)) || (height > GetSystemMetrics(SM_CYSCREEN))) - if( !((width == GetSystemMetrics(SM_CYSCREEN)) && (height == GetSystemMetrics(SM_CXSCREEN)))) // user portrait, device landscape - gapi->hiresFix = 1; - - switch( gapi->userOrientation ) - { - case SDL_ORIENTATION_UP: - gapi->startOffset = 0; - gapi->dstLineStep = gapi->gxProperties.cbyPitch; - gapi->dstPixelStep = gapi->gxProperties.cbxPitch; - break; - case SDL_ORIENTATION_RIGHT: - switch( gapi->gapiOrientation ) - { - case SDL_ORIENTATION_UP: - case SDL_ORIENTATION_RIGHT: - case SDL_ORIENTATION_LEFT: - if( (this->hidden->videoMode == GAPI_MONO) ) - gapi->startOffset = -gapi->gxProperties.cbxPitch + 1; // monochrome mode - else - gapi->startOffset = gapi->gxProperties.cbyPitch * (gapi->gxProperties.cyHeight - 1); - - gapi->dstLineStep = gapi->gxProperties.cbxPitch; - gapi->dstPixelStep = -gapi->gxProperties.cbyPitch; - break; - } - } - - video->w = this->hidden->w = width; - video->h = this->hidden->h = height; - video->pitch = SDL_CalculatePitch(video); - - /* Small fix for WinCE/Win32 - when activating window - SDL_VideoSurface is equal to zero, so activating code - is not called properly for fullscreen windows because - macros WINDIB_FULLSCREEN uses SDL_VideoSurface - */ - SDL_VideoSurface = video; - - /* GAPI is always fullscreen, title bar is useless */ - style = 0; - - if (!SDL_windowid) - SetWindowLong(SDL_Window, GWL_STYLE, style); - - /* Allocate bitmap */ - if(gapiBuffer) - { - SDL_free(gapiBuffer); - gapiBuffer = NULL; - } - gapiBuffer = SDL_malloc(video->h * video->pitch); - video->pixels = gapiBuffer; - - if ( ! this->hidden->buffer ) { - SDL_SetError("Couldn't allocate buffer for requested mode"); - return(NULL); - } - - SDL_memset(gapiBuffer, 255, video->h * video->pitch); - MoveWindow(SDL_Window, 0, 0, GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN), FALSE); - ShowWindow(SDL_Window, SW_SHOW); - SetForegroundWindow(SDL_Window); - - /* JC 14 Mar 2006 - Flush the message loop or this can cause big problems later - Especially if the user decides to use dialog boxes or assert()! - */ - WIN_FlushMessageQueue(); - - /* Open GAPI display */ - if( !gapi->useVga && this->hidden->useGXOpenDisplay ) - if( !gapi->gxFunc.GXOpenDisplay(SDL_Window, GX_FULLSCREEN) ) - { - SDL_SetError("Couldn't initialize GAPI"); - return(NULL); - } - + SDL_Surface *video; + Uint32 Rmask, Gmask, Bmask; + DWORD style; + SDL_Rect allScreen; + + if (bpp < 4) { + SDL_SetError("1 bpp and 2 bpp modes is not implemented yet!"); + return 0; + } + + /* Recalculate bitmasks if necessary */ + if (bpp == current->format->BitsPerPixel) { + video = current; + } else { + switch (bpp) { + case 8: + Rmask = 0; + Gmask = 0; + Bmask = 0; + break; + case 15: + case 16: + /* Default is 565 unless the display is specifically 555 */ + if (this->hidden->gxProperties.ffFormat & kfDirect555) { + Rmask = 0x00007c00; + Gmask = 0x000003e0; + Bmask = 0x0000001f; + } else { + Rmask = 0x0000f800; + Gmask = 0x000007e0; + Bmask = 0x0000001f; + } + break; + case 24: + case 32: + Rmask = 0x00ff0000; + Gmask = 0x0000ff00; + Bmask = 0x000000ff; + break; + default: + SDL_SetError("Unsupported Bits Per Pixel format requested"); + return NULL; + } + video = SDL_CreateRGBSurface(SDL_SWSURFACE, + 0, 0, bpp, Rmask, Gmask, Bmask, 0); + if (video == NULL) { + SDL_OutOfMemory(); + return (NULL); + } + } + + gapi->userOrientation = SDL_ORIENTATION_UP; + video->flags = SDL_FULLSCREEN; /* Clear flags, GAPI supports fullscreen only */ + + /* GAPI or VGA? */ + if (g_hGapiLib) { + FillStructs(this, 0); + if ((((unsigned) width != gapi->gxProperties.cxWidth) + || ((unsigned) height != gapi->gxProperties.cyHeight)) + && (((unsigned) width != gapi->gxProperties.cyHeight) + || ((unsigned) height != gapi->gxProperties.cxWidth))) + FillStructs(this, 1); // gapi is found but we use VGA resolution + } else + FillStructs(this, 1); + + if (!this->hidden->needUpdate && !this->hidden->videoMem) { + SDL_SetError + ("Couldn't get address of video memory, may be unsupported device or bug"); + return (NULL); + } + + /* detect user landscape mode */ + if ((width > height) + && (GetSystemMetrics(SM_CXSCREEN) < GetSystemMetrics(SM_CYSCREEN))) + gapi->userOrientation = SDL_ORIENTATION_RIGHT; + + /* shall we apply hires fix? for example when we do not use hires resource */ + gapi->hiresFix = 0; + if (gapi->userOrientation == SDL_ORIENTATION_RIGHT) { + if ((width > GetSystemMetrics(SM_CYSCREEN)) + || (height > GetSystemMetrics(SM_CXSCREEN))) + gapi->hiresFix = 1; + } else if ((width > GetSystemMetrics(SM_CXSCREEN)) + || (height > GetSystemMetrics(SM_CYSCREEN))) + if (!((width == GetSystemMetrics(SM_CYSCREEN)) && (height == GetSystemMetrics(SM_CXSCREEN)))) // user portrait, device landscape + gapi->hiresFix = 1; + + switch (gapi->userOrientation) { + case SDL_ORIENTATION_UP: + gapi->startOffset = 0; + gapi->dstLineStep = gapi->gxProperties.cbyPitch; + gapi->dstPixelStep = gapi->gxProperties.cbxPitch; + break; + case SDL_ORIENTATION_RIGHT: + switch (gapi->gapiOrientation) { + case SDL_ORIENTATION_UP: + case SDL_ORIENTATION_RIGHT: + case SDL_ORIENTATION_LEFT: + if ((this->hidden->videoMode == GAPI_MONO)) + gapi->startOffset = -gapi->gxProperties.cbxPitch + 1; // monochrome mode + else + gapi->startOffset = + gapi->gxProperties.cbyPitch * + (gapi->gxProperties.cyHeight - 1); + + gapi->dstLineStep = gapi->gxProperties.cbxPitch; + gapi->dstPixelStep = -gapi->gxProperties.cbyPitch; + break; + } + } + + video->w = this->hidden->w = width; + video->h = this->hidden->h = height; + video->pitch = SDL_CalculatePitch(video); + + /* Small fix for WinCE/Win32 - when activating window + SDL_VideoSurface is equal to zero, so activating code + is not called properly for fullscreen windows because + macros WINDIB_FULLSCREEN uses SDL_VideoSurface + */ + SDL_VideoSurface = video; + + /* GAPI is always fullscreen, title bar is useless */ + style = 0; + + if (!SDL_windowid) + SetWindowLong(SDL_Window, GWL_STYLE, style); + + /* Allocate bitmap */ + if (gapiBuffer) { + SDL_free(gapiBuffer); + gapiBuffer = NULL; + } + gapiBuffer = SDL_malloc(video->h * video->pitch); + video->pixels = gapiBuffer; + + if (!this->hidden->buffer) { + SDL_SetError("Couldn't allocate buffer for requested mode"); + return (NULL); + } + + SDL_memset(gapiBuffer, 255, video->h * video->pitch); + MoveWindow(SDL_Window, 0, 0, GetSystemMetrics(SM_CXSCREEN), + GetSystemMetrics(SM_CYSCREEN), FALSE); + ShowWindow(SDL_Window, SW_SHOW); + SetForegroundWindow(SDL_Window); + + /* JC 14 Mar 2006 + Flush the message loop or this can cause big problems later + Especially if the user decides to use dialog boxes or assert()! + */ + WIN_FlushMessageQueue(); + + /* Open GAPI display */ + if (!gapi->useVga && this->hidden->useGXOpenDisplay) + if (!gapi->gxFunc.GXOpenDisplay(SDL_Window, GX_FULLSCREEN)) { + SDL_SetError("Couldn't initialize GAPI"); + return (NULL); + } #if REPORT_VIDEO_INFO - printf("Video properties:\n"); - printf("display bpp: %d\n", gapi->gxProperties.cBPP); - printf("display width: %d\n", gapi->gxProperties.cxWidth); - printf("display height: %d\n", gapi->gxProperties.cyHeight); - printf("x pitch: %d\n", gapi->gxProperties.cbxPitch); - printf("y pitch: %d\n", gapi->gxProperties.cbyPitch); - printf("gapi flags: 0x%x\n", gapi->gxProperties.ffFormat); - - if( !gapi->useVga && this->hidden->useGXOpenDisplay && gapi->needUpdate) - { - gapi->videoMem = gapi->gxFunc.GXBeginDraw(); - gapi->gxFunc.GXEndDraw(); - } - - printf("video memory: 0x%x\n", gapi->videoMem); - printf("need update: %d\n", gapi->needUpdate); - printf("hi-res fix: %d\n", gapi->hiresFix); - printf("VGA is available on the device: %d\n", g_bRawBufferAvailable); - printf("use raw framebuffer: %d\n", gapi->useVga); - printf("video surface bpp: %d\n", video->format->BitsPerPixel); - printf("video surface width: %d\n", video->w); - printf("video surface height: %d\n", video->h); + printf("Video properties:\n"); + printf("display bpp: %d\n", gapi->gxProperties.cBPP); + printf("display width: %d\n", gapi->gxProperties.cxWidth); + printf("display height: %d\n", gapi->gxProperties.cyHeight); + printf("x pitch: %d\n", gapi->gxProperties.cbxPitch); + printf("y pitch: %d\n", gapi->gxProperties.cbyPitch); + printf("gapi flags: 0x%x\n", gapi->gxProperties.ffFormat); + + if (!gapi->useVga && this->hidden->useGXOpenDisplay && gapi->needUpdate) { + gapi->videoMem = gapi->gxFunc.GXBeginDraw(); + gapi->gxFunc.GXEndDraw(); + } + + printf("video memory: 0x%x\n", gapi->videoMem); + printf("need update: %d\n", gapi->needUpdate); + printf("hi-res fix: %d\n", gapi->hiresFix); + printf("VGA is available on the device: %d\n", g_bRawBufferAvailable); + printf("use raw framebuffer: %d\n", gapi->useVga); + printf("video surface bpp: %d\n", video->format->BitsPerPixel); + printf("video surface width: %d\n", video->w); + printf("video surface height: %d\n", video->h); #endif - /* Blank screen */ - allScreen.x = allScreen.y = 0; - allScreen.w = video->w - 1; - allScreen.h = video->h - 1; - GAPI_UpdateRects(this, 1, &allScreen); + /* Blank screen */ + allScreen.x = allScreen.y = 0; + allScreen.w = video->w - 1; + allScreen.h = video->h - 1; + GAPI_UpdateRects(this, 1, &allScreen); - /* We're done */ - return(video); + /* We're done */ + return (video); } /* We don't actually allow hardware surfaces other than the main one */ -static int GAPI_AllocHWSurface(_THIS, SDL_Surface *surface) +static int +GAPI_AllocHWSurface(_THIS, SDL_Surface * surface) { - return(-1); + return (-1); } -static void GAPI_FreeHWSurface(_THIS, SDL_Surface *surface) +static void +GAPI_FreeHWSurface(_THIS, SDL_Surface * surface) { - return; + return; } /* We need to wait for vertical retrace on page flipped displays */ -static int GAPI_LockHWSurface(_THIS, SDL_Surface *surface) +static int +GAPI_LockHWSurface(_THIS, SDL_Surface * surface) { - return(0); + return (0); } -static void GAPI_UnlockHWSurface(_THIS, SDL_Surface *surface) +static void +GAPI_UnlockHWSurface(_THIS, SDL_Surface * surface) { - return; + return; } -static int updateLine8to8(_THIS, unsigned char *srcPointer, unsigned char *destPointer, int width, int height, int lines) +static int +updateLine8to8(_THIS, unsigned char *srcPointer, unsigned char *destPointer, + int width, int height, int lines) { - if( gapi->dstPixelStep == 1) /* optimized blitting on most devices */ - { - SDL_memcpy(destPointer, srcPointer, width); - return 1; - } else - { - // TODO: read 4 pixels, write DWORD - int step = gapi->dstPixelStep; - while(width--) - { - *destPointer = *srcPointer++; - destPointer += step; - } - } - return 1; + if (gapi->dstPixelStep == 1) { /* optimized blitting on most devices */ + SDL_memcpy(destPointer, srcPointer, width); + return 1; + } else { + // TODO: read 4 pixels, write DWORD + int step = gapi->dstPixelStep; + while (width--) { + *destPointer = *srcPointer++; + destPointer += step; + } + } + return 1; } /* Video memory is very slow so lets optimize as much as possible */ -static int updateLine16to16(_THIS, PIXEL *srcPointer, PIXEL *destPointer, int width, int height, int lines) +static int +updateLine16to16(_THIS, PIXEL * srcPointer, PIXEL * destPointer, int width, + int height, int lines) { - PIXEL *line1, *line2; - int step = gapi->dstPixelStep / 2; - - if( step == 1 ) /* optimized blitting on most devices */ - { - SDL_memcpy(destPointer, srcPointer, width * sizeof(PIXEL)); - return 1; - } - else - { - if( (gapi->gapiOrientation != SDL_ORIENTATION_UP) && - (gapi->userOrientation == SDL_ORIENTATION_UP )) // iPaq 3660/3800 and user orientation up - { - // to prevent data misalignment copy only one line - if( ((((unsigned)destPointer & 3) != 0) && (gapi->gapiOrientation == SDL_ORIENTATION_LEFT)) - || ((((unsigned)destPointer & 3) == 0) && (gapi->gapiOrientation != SDL_ORIENTATION_LEFT)) - || (lines == 1) ) - { - while(width--) - { - *destPointer = *srcPointer++; - destPointer += step; - } - return 1; - } - - /* read two lines at the same time, write DWORD */ - line1 = srcPointer; - line2 = srcPointer + SDL_VideoSurface->pitch / 2; - - if( gapi->gapiOrientation == SDL_ORIENTATION_LEFT ) - while(width--) // iPaq 3800 - { - *(DWORD*)destPointer =(*line2++ << 16) | *line1++; - destPointer += step; - } - else - { - destPointer += gapi->gxProperties.cbyPitch / 2; - - while(width--) // iPaq 3660 - { - *(DWORD*)destPointer =(*line1++ << 16) | *line2++; - destPointer += step; - } - } - return 2; - } else - { - // iPaq 3800 and user orientation landscape - if( gapi->gapiOrientation == SDL_ORIENTATION_LEFT ) - { - int w1; - - // to prevent data misalignment copy only one pixel - if( (((unsigned)destPointer & 3) == 0) && (width > 0)) - { - *destPointer-- = *srcPointer++; - width--; - } - - destPointer--; - - w1 = width / 2; - - while(w1--) - { - DWORD p = *(DWORD*)srcPointer; - *((DWORD*)destPointer) = (p << 16) | (p >> 16); - destPointer -= 2; - srcPointer += 2; - } - - if( width & 1 ) // copy the last pixel - { - destPointer++; - *destPointer = *srcPointer; - } - - return 1; - } - - // modern iPaqs and user orientation landscape - // read two pixels, write DWORD - - line1 = srcPointer; - line2 = srcPointer + SDL_VideoSurface->pitch / 2; - - if( (((unsigned)destPointer & 3) != 0) || (lines == 1) ) - { - while(width--) - { - *destPointer = *srcPointer++; - destPointer += step; - } - return 1; - } - - while(width--) - { - *(DWORD*)destPointer =(*line2++ << 16) | *line1++; - destPointer -= gapi->gxProperties.cbyPitch / 2; - } - return 2; - } - } + PIXEL *line1, *line2; + int step = gapi->dstPixelStep / 2; + + if (step == 1) { /* optimized blitting on most devices */ + SDL_memcpy(destPointer, srcPointer, width * sizeof(PIXEL)); + return 1; + } else { + if ((gapi->gapiOrientation != SDL_ORIENTATION_UP) && (gapi->userOrientation == SDL_ORIENTATION_UP)) // iPaq 3660/3800 and user orientation up + { + // to prevent data misalignment copy only one line + if (((((unsigned) destPointer & 3) != 0) + && (gapi->gapiOrientation == SDL_ORIENTATION_LEFT)) + || ((((unsigned) destPointer & 3) == 0) + && (gapi->gapiOrientation != SDL_ORIENTATION_LEFT)) + || (lines == 1)) { + while (width--) { + *destPointer = *srcPointer++; + destPointer += step; + } + return 1; + } + + /* read two lines at the same time, write DWORD */ + line1 = srcPointer; + line2 = srcPointer + SDL_VideoSurface->pitch / 2; + + if (gapi->gapiOrientation == SDL_ORIENTATION_LEFT) + while (width--) // iPaq 3800 + { + *(DWORD *) destPointer = (*line2++ << 16) | *line1++; + destPointer += step; + } else { + destPointer += gapi->gxProperties.cbyPitch / 2; + + while (width--) // iPaq 3660 + { + *(DWORD *) destPointer = (*line1++ << 16) | *line2++; + destPointer += step; + } + } + return 2; + } else { + // iPaq 3800 and user orientation landscape + if (gapi->gapiOrientation == SDL_ORIENTATION_LEFT) { + int w1; + + // to prevent data misalignment copy only one pixel + if ((((unsigned) destPointer & 3) == 0) && (width > 0)) { + *destPointer-- = *srcPointer++; + width--; + } + + destPointer--; + + w1 = width / 2; + + while (w1--) { + DWORD p = *(DWORD *) srcPointer; + *((DWORD *) destPointer) = (p << 16) | (p >> 16); + destPointer -= 2; + srcPointer += 2; + } + + if (width & 1) // copy the last pixel + { + destPointer++; + *destPointer = *srcPointer; + } + + return 1; + } + // modern iPaqs and user orientation landscape + // read two pixels, write DWORD + + line1 = srcPointer; + line2 = srcPointer + SDL_VideoSurface->pitch / 2; + + if ((((unsigned) destPointer & 3) != 0) || (lines == 1)) { + while (width--) { + *destPointer = *srcPointer++; + destPointer += step; + } + return 1; + } + + while (width--) { + *(DWORD *) destPointer = (*line2++ << 16) | *line1++; + destPointer -= gapi->gxProperties.cbyPitch / 2; + } + return 2; + } + } } // Color component masks for 565 @@ -942,290 +949,318 @@ static int updateLine16to16(_THIS, PIXEL *srcPointer, PIXEL *destPointer, int wi #define BLUEMASK (31) -static int updateLine16to4(_THIS, PIXEL *srcPointer, unsigned char *destPointer, int width, int height, int lines, int yNibble, int xNibble) +static int +updateLine16to4(_THIS, PIXEL * srcPointer, unsigned char *destPointer, + int width, int height, int lines, int yNibble, int xNibble) { - PIXEL *line1, *line2; - int step = gapi->dstPixelStep; - - if( gapi->userOrientation == SDL_ORIENTATION_UP ) - { - if( yNibble ) // copy bottom half of a line - { - while(width--) - { - PIXEL c1 = *srcPointer++; - c1 = ((c1 & REDMASK) >> 11) + ((c1 & GREENMASK) >> 5) + (c1 & BLUEMASK); - *destPointer = (*destPointer & 0x0F) | ((~(c1 >> 3) << 4)); - destPointer += step; - } - return 1; - } - - // either 1 pixel picture or tail, anyway this is the last line - if( lines == 1 ) - { - while(width--) - { - PIXEL c1 = *srcPointer++; - c1 = ((c1 & REDMASK) >> 11) + ((c1 & GREENMASK) >> 5) + (c1 & BLUEMASK); - *destPointer = (*destPointer & 0xF0) | ((~(c1 >> 3) & 0xF)); - destPointer += step; - } - return 1; - } - - line1 = srcPointer; - line2 = srcPointer + SDL_VideoSurface->pitch / 2; - - while(width--) - { - PIXEL c1 = *line1++; - PIXEL c2 = *line2++; - c1 = ((c1 & REDMASK) >> 11) + ((c1 & GREENMASK) >> 5) + (c1 & BLUEMASK); - c2 = ((c2 & REDMASK) >> 11) + ((c2 & GREENMASK) >> 5) + (c2 & BLUEMASK); - *destPointer = ~((c1 >> 3) + ((c2 >> 3) << 4)); - destPointer += step; - } - return 2; - } else - { - int w1; - w1 = width / 2; - - if( xNibble ) - { - // copy one pixel - PIXEL c1 = *srcPointer++; - c1 = ((c1 & REDMASK) >> 11) + ((c1 & GREENMASK) >> 5) + (c1 & BLUEMASK); - *destPointer = (*destPointer & 0xF0) | ((~(c1 >> 3) & 0xF)); - destPointer++; - } - - while(w1--) - { - PIXEL c1 = *srcPointer; - PIXEL c2 = *(srcPointer + 1); - c1 = ((c1 & REDMASK) >> 11) + ((c1 & GREENMASK) >> 5) + (c1 & BLUEMASK); - c2 = ((c2 & REDMASK) >> 11) + ((c2 & GREENMASK) >> 5) + (c2 & BLUEMASK); - *destPointer++ = ~((c2 >> 3) + ((c1 >> 3) << 4)); - srcPointer += 2; - } - - // copy tail - if( (width & 1) && !xNibble ) - { - PIXEL c1 = *srcPointer; - c1 = ((c1 & REDMASK) >> 11) + ((c1 & GREENMASK) >> 5) + (c1 & BLUEMASK); - *destPointer = (*destPointer & 0x0F) | ((~(c1 >> 3) << 4)); - } - - return 1; - } + PIXEL *line1, *line2; + int step = gapi->dstPixelStep; + + if (gapi->userOrientation == SDL_ORIENTATION_UP) { + if (yNibble) // copy bottom half of a line + { + while (width--) { + PIXEL c1 = *srcPointer++; + c1 = ((c1 & REDMASK) >> 11) + ((c1 & GREENMASK) >> 5) + + (c1 & BLUEMASK); + *destPointer = (*destPointer & 0x0F) | ((~(c1 >> 3) << 4)); + destPointer += step; + } + return 1; + } + // either 1 pixel picture or tail, anyway this is the last line + if (lines == 1) { + while (width--) { + PIXEL c1 = *srcPointer++; + c1 = ((c1 & REDMASK) >> 11) + ((c1 & GREENMASK) >> 5) + + (c1 & BLUEMASK); + *destPointer = (*destPointer & 0xF0) | ((~(c1 >> 3) & 0xF)); + destPointer += step; + } + return 1; + } + + line1 = srcPointer; + line2 = srcPointer + SDL_VideoSurface->pitch / 2; + + while (width--) { + PIXEL c1 = *line1++; + PIXEL c2 = *line2++; + c1 = ((c1 & REDMASK) >> 11) + ((c1 & GREENMASK) >> 5) + + (c1 & BLUEMASK); + c2 = ((c2 & REDMASK) >> 11) + ((c2 & GREENMASK) >> 5) + + (c2 & BLUEMASK); + *destPointer = ~((c1 >> 3) + ((c2 >> 3) << 4)); + destPointer += step; + } + return 2; + } else { + int w1; + w1 = width / 2; + + if (xNibble) { + // copy one pixel + PIXEL c1 = *srcPointer++; + c1 = ((c1 & REDMASK) >> 11) + ((c1 & GREENMASK) >> 5) + + (c1 & BLUEMASK); + *destPointer = (*destPointer & 0xF0) | ((~(c1 >> 3) & 0xF)); + destPointer++; + } + + while (w1--) { + PIXEL c1 = *srcPointer; + PIXEL c2 = *(srcPointer + 1); + c1 = ((c1 & REDMASK) >> 11) + ((c1 & GREENMASK) >> 5) + + (c1 & BLUEMASK); + c2 = ((c2 & REDMASK) >> 11) + ((c2 & GREENMASK) >> 5) + + (c2 & BLUEMASK); + *destPointer++ = ~((c2 >> 3) + ((c1 >> 3) << 4)); + srcPointer += 2; + } + + // copy tail + if ((width & 1) && !xNibble) { + PIXEL c1 = *srcPointer; + c1 = ((c1 & REDMASK) >> 11) + ((c1 & GREENMASK) >> 5) + + (c1 & BLUEMASK); + *destPointer = (*destPointer & 0x0F) | ((~(c1 >> 3) << 4)); + } + + return 1; + } } -static void GAPI_UpdateRectsMono(_THIS, int numrects, SDL_Rect *rects) +static void +GAPI_UpdateRectsMono(_THIS, int numrects, SDL_Rect * rects) { - int i, height; - int linesProcessed; - int xNibble, yNibble; - - for (i=0; iuserOrientation == SDL_ORIENTATION_UP ) - destPointer = (unsigned char*) gapi->videoMem + gapi->startOffset - rects[i].y * gapi->gxProperties.cBPP / 8 + rects[i].x * gapi->dstPixelStep; - else - destPointer = (unsigned char*) gapi->videoMem + gapi->startOffset + rects[i].x * gapi->gxProperties.cBPP / 8 + rects[i].y * gapi->dstLineStep; - - srcPointer = ((unsigned char*) SDL_VideoSurface->pixels) + rects[i].y * SDL_VideoSurface->pitch + rects[i].x * 2; - yNibble = rects[i].y & 1; // TODO: only for 4 bpp - xNibble = rects[i].x & 1; - height = rects[i].h; - while (height > 0) - { - switch(gapi->gxProperties.cBPP) - { - case 2: // TODO - case 4: - linesProcessed = updateLine16to4(this, (PIXEL*) srcPointer, destPointer, rects[i].w, rects[i].h, height, yNibble, xNibble); - yNibble = 0; - } - height -= linesProcessed; - if( gapi->userOrientation == SDL_ORIENTATION_UP ) - destPointer--; // always fill 1 byte - else destPointer += gapi->dstLineStep; - srcPointer += SDL_VideoSurface->pitch * linesProcessed; // pitch in bytes - } - } + int i, height; + int linesProcessed; + int xNibble, yNibble; + + for (i = 0; i < numrects; i++) { + unsigned char *destPointer; + unsigned char *srcPointer; + + if (gapi->userOrientation == SDL_ORIENTATION_UP) + destPointer = + (unsigned char *) gapi->videoMem + gapi->startOffset - + rects[i].y * gapi->gxProperties.cBPP / 8 + + rects[i].x * gapi->dstPixelStep; + else + destPointer = + (unsigned char *) gapi->videoMem + gapi->startOffset + + rects[i].x * gapi->gxProperties.cBPP / 8 + + rects[i].y * gapi->dstLineStep; + + srcPointer = + ((unsigned char *) SDL_VideoSurface->pixels) + + rects[i].y * SDL_VideoSurface->pitch + rects[i].x * 2; + yNibble = rects[i].y & 1; // TODO: only for 4 bpp + xNibble = rects[i].x & 1; + height = rects[i].h; + while (height > 0) { + switch (gapi->gxProperties.cBPP) { + case 2: // TODO + case 4: + linesProcessed = + updateLine16to4(this, (PIXEL *) srcPointer, + destPointer, rects[i].w, + rects[i].h, height, yNibble, xNibble); + yNibble = 0; + } + height -= linesProcessed; + if (gapi->userOrientation == SDL_ORIENTATION_UP) + destPointer--; // always fill 1 byte + else + destPointer += gapi->dstLineStep; + srcPointer += SDL_VideoSurface->pitch * linesProcessed; // pitch in bytes + } + } } -static void GAPI_UpdateRectsColor(_THIS, int numrects, SDL_Rect *rects) +static void +GAPI_UpdateRectsColor(_THIS, int numrects, SDL_Rect * rects) { - int i, height; - int bytesPerPixel = (gapi->gxProperties.cBPP + 1) / 8; - int linesProcessed; - for (i=0; ivideoMem + gapi->startOffset + rects[i].y * gapi->dstLineStep + rects[i].x * gapi->dstPixelStep; - unsigned char *srcPointer = ((unsigned char*) SDL_VideoSurface->pixels) + rects[i].y * SDL_VideoSurface->pitch + rects[i].x * bytesPerPixel; - height = rects[i].h; - -// fprintf(stderr, "Starting rect %dx%d, dst=0x%x, w = %d, h = %d\n", rects[i].w, rects[i].h,destPointer,rects[i].w,rects[i].h); -// fflush(stderr); - linesProcessed = height; - - while (height > 0) { - switch(bytesPerPixel) - { - case 1: - linesProcessed = updateLine8to8(this, srcPointer, (unsigned char *) destPointer, rects[i].w, rects[i].h, height); - break; - case 2: + int i, height; + int bytesPerPixel = (gapi->gxProperties.cBPP + 1) / 8; + int linesProcessed; + for (i = 0; i < numrects; i++) { + unsigned char *destPointer = + (unsigned char *) gapi->videoMem + gapi->startOffset + + rects[i].y * gapi->dstLineStep + rects[i].x * gapi->dstPixelStep; + unsigned char *srcPointer = + ((unsigned char *) SDL_VideoSurface->pixels) + + rects[i].y * SDL_VideoSurface->pitch + rects[i].x * bytesPerPixel; + height = rects[i].h; + +// fprintf(stderr, "Starting rect %dx%d, dst=0x%x, w = %d, h = %d\n", rects[i].w, rects[i].h,destPointer,rects[i].w,rects[i].h); +// fflush(stderr); + linesProcessed = height; + + while (height > 0) { + switch (bytesPerPixel) { + case 1: + linesProcessed = + updateLine8to8(this, srcPointer, + (unsigned char *) destPointer, + rects[i].w, rects[i].h, height); + break; + case 2: #pragma warning(disable: 4133) - linesProcessed = updateLine16to16(this, (PIXEL*) srcPointer, destPointer, rects[i].w, rects[i].h, height); - break; - } - height -= linesProcessed; - destPointer += gapi->dstLineStep * linesProcessed; - srcPointer += SDL_VideoSurface->pitch * linesProcessed; // pitch in bytes - } -// fprintf(stderr, "End of rect\n"); -// fflush(stderr); - } + linesProcessed = + updateLine16to16(this, (PIXEL *) srcPointer, + destPointer, rects[i].w, + rects[i].h, height); + break; + } + height -= linesProcessed; + destPointer += gapi->dstLineStep * linesProcessed; + srcPointer += SDL_VideoSurface->pitch * linesProcessed; // pitch in bytes + } +// fprintf(stderr, "End of rect\n"); +// fflush(stderr); + } } -static void GAPI_UpdateRects(_THIS, int numrects, SDL_Rect *rects) +static void +GAPI_UpdateRects(_THIS, int numrects, SDL_Rect * rects) { - // we do not want to corrupt video memory - if( gapi->suspended ) return; + // we do not want to corrupt video memory + if (gapi->suspended) + return; - if( gapi->needUpdate ) - gapi->videoMem = gapi->gxFunc.GXBeginDraw(); + if (gapi->needUpdate) + gapi->videoMem = gapi->gxFunc.GXBeginDraw(); - if( gapi->gxProperties.cBPP < 8 ) - GAPI_UpdateRectsMono(this, numrects, rects); - else - GAPI_UpdateRectsColor(this, numrects, rects); + if (gapi->gxProperties.cBPP < 8) + GAPI_UpdateRectsMono(this, numrects, rects); + else + GAPI_UpdateRectsColor(this, numrects, rects); - if( gapi->needUpdate ) - gapi->gxFunc.GXEndDraw(); + if (gapi->needUpdate) + gapi->gxFunc.GXEndDraw(); } /* Note: If we are terminated, this could be called in the middle of another SDL video routine -- notably UpdateRects. */ -void GAPI_VideoQuit(_THIS) +void +GAPI_VideoQuit(_THIS) { - int i, j; - /* Destroy the window and everything associated with it */ - if ( SDL_Window ) - { - if ((g_hGapiLib != 0) && this && this->hidden && this->hidden->gxFunc.GXCloseDisplay && !this->hidden->useVga) - this->hidden->gxFunc.GXCloseDisplay(); - - if (this->screen->pixels != NULL) - { - SDL_free(this->screen->pixels); - this->screen->pixels = NULL; - } - if ( screen_icn ) { - DestroyIcon(screen_icn); - screen_icn = NULL; - } - - DIB_DestroyWindow(this); - SDL_UnregisterApp(); - - SDL_Window = NULL; + int i, j; + /* Destroy the window and everything associated with it */ + if (SDL_Window) { + if ((g_hGapiLib != 0) && this && this->hidden + && this->hidden->gxFunc.GXCloseDisplay && !this->hidden->useVga) + this->hidden->gxFunc.GXCloseDisplay(); + + if (this->screen->pixels != NULL) { + SDL_free(this->screen->pixels); + this->screen->pixels = NULL; + } + if (screen_icn) { + DestroyIcon(screen_icn); + screen_icn = NULL; + } + + DIB_DestroyWindow(this); + SDL_UnregisterApp(); + + SDL_Window = NULL; #if defined(_WIN32_WCE) // Unload wince aygshell library to prevent leak - if( aygshell ) - { - FreeLibrary(aygshell); - aygshell = NULL; - } + if (aygshell) { + FreeLibrary(aygshell); + aygshell = NULL; + } #endif - /* Free video mode lists */ - for ( i=0; iSDL_modelist[i] != NULL ) { - for ( j=0; gapi->SDL_modelist[i][j]; ++j ) - SDL_free(gapi->SDL_modelist[i][j]); - SDL_free(gapi->SDL_modelist[i]); - gapi->SDL_modelist[i] = NULL; - } - } + /* Free video mode lists */ + for (i = 0; i < NUM_MODELISTS; ++i) { + if (gapi->SDL_modelist[i] != NULL) { + for (j = 0; gapi->SDL_modelist[i][j]; ++j) + SDL_free(gapi->SDL_modelist[i][j]); + SDL_free(gapi->SDL_modelist[i]); + gapi->SDL_modelist[i] = NULL; + } + } - } + } } -static void GAPI_RealizePalette(_THIS) +static void +GAPI_RealizePalette(_THIS) { - OutputDebugString(TEXT("GAPI_RealizePalette NOT IMPLEMENTED !\r\n")); + OutputDebugString(TEXT("GAPI_RealizePalette NOT IMPLEMENTED !\r\n")); } -static void GAPI_PaletteChanged(_THIS, HWND window) +static void +GAPI_PaletteChanged(_THIS, HWND window) { - OutputDebugString(TEXT("GAPI_PaletteChanged NOT IMPLEMENTED !\r\n")); + OutputDebugString(TEXT("GAPI_PaletteChanged NOT IMPLEMENTED !\r\n")); } -static void GAPI_WinPAINT(_THIS, HDC hdc) +static void +GAPI_WinPAINT(_THIS, HDC hdc) { - // draw current offscreen buffer on hdc + // draw current offscreen buffer on hdc - int bpp = 16; // we always use either 8 or 16 bpp internally + int bpp = 16; // we always use either 8 or 16 bpp internally - unsigned short *bitmapData; - HBITMAP hb; - HDC srcDC; + unsigned short *bitmapData; + HBITMAP hb; + HDC srcDC; // Create a DIB - BYTE buffer[sizeof(BITMAPINFOHEADER) + 3 * sizeof(RGBQUAD)] = {0}; - BITMAPINFO* pBMI = (BITMAPINFO*)buffer; - BITMAPINFOHEADER* pHeader = &pBMI->bmiHeader; - DWORD* pColors = (DWORD*)&pBMI->bmiColors; + BYTE buffer[sizeof(BITMAPINFOHEADER) + 3 * sizeof(RGBQUAD)] = { 0 }; + BITMAPINFO *pBMI = (BITMAPINFO *) buffer; + BITMAPINFOHEADER *pHeader = &pBMI->bmiHeader; + DWORD *pColors = (DWORD *) & pBMI->bmiColors; - // CreateDIBSection does not support 332 pixel format on wce - if( gapi->gxProperties.cBPP == 8 ) return; + // CreateDIBSection does not support 332 pixel format on wce + if (gapi->gxProperties.cBPP == 8) + return; // DIB Header - pHeader->biSize = sizeof(BITMAPINFOHEADER); - pHeader->biWidth = this->hidden->w; - pHeader->biHeight = -this->hidden->h; - pHeader->biPlanes = 1; - pHeader->biBitCount = bpp; - pHeader->biCompression = BI_RGB; - pHeader->biSizeImage = (this->hidden->w * this->hidden->h * bpp) / 8; - + pHeader->biSize = sizeof(BITMAPINFOHEADER); + pHeader->biWidth = this->hidden->w; + pHeader->biHeight = -this->hidden->h; + pHeader->biPlanes = 1; + pHeader->biBitCount = bpp; + pHeader->biCompression = BI_RGB; + pHeader->biSizeImage = (this->hidden->w * this->hidden->h * bpp) / 8; + // Color masks - if( bpp == 16 ) - { - pColors[0] = REDMASK; - pColors[1] = GREENMASK; - pColors[2] = BLUEMASK; - pHeader->biCompression = BI_BITFIELDS; - } + if (bpp == 16) { + pColors[0] = REDMASK; + pColors[1] = GREENMASK; + pColors[2] = BLUEMASK; + pHeader->biCompression = BI_BITFIELDS; + } // Create the DIB - hb = CreateDIBSection( 0, pBMI, DIB_RGB_COLORS, (void**)&bitmapData, 0, 0 ); + hb = CreateDIBSection(0, pBMI, DIB_RGB_COLORS, (void **) &bitmapData, 0, + 0); - // copy data - // FIXME: prevent misalignment, but I've never seen non aligned width of screen - memcpy(bitmapData, this->hidden->buffer, pHeader->biSizeImage); - srcDC = CreateCompatibleDC(hdc); - SelectObject(srcDC, hb); + // copy data + // FIXME: prevent misalignment, but I've never seen non aligned width of screen + memcpy(bitmapData, this->hidden->buffer, pHeader->biSizeImage); + srcDC = CreateCompatibleDC(hdc); + SelectObject(srcDC, hb); - BitBlt(hdc, 0, 0, this->hidden->w, this->hidden->h, srcDC, 0, 0, SRCCOPY); + BitBlt(hdc, 0, 0, this->hidden->w, this->hidden->h, srcDC, 0, 0, SRCCOPY); - DeleteObject(hb); - DeleteDC(srcDC); + DeleteObject(hb); + DeleteDC(srcDC); } -int GAPI_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color *colors) +int +GAPI_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color * colors) { - GAPI_CreatePalette(ncolors, colors); - return 1; + GAPI_CreatePalette(ncolors, colors); + return 1; } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/gapi/SDL_gapivideo.h b/src/video/gapi/SDL_gapivideo.h index 99a1d0009..0740ff27e 100644 --- a/src/video/gapi/SDL_gapivideo.h +++ b/src/video/gapi/SDL_gapivideo.h @@ -30,18 +30,20 @@ /* From gx.h, since it's not really C compliant */ -struct GXDisplayProperties { +struct GXDisplayProperties +{ DWORD cxWidth; - DWORD cyHeight; // notice lack of 'th' in the word height. - long cbxPitch; // number of bytes to move right one x pixel - can be negative. - long cbyPitch; // number of bytes to move down one y pixel - can be negative. - long cBPP; // # of bits in each pixel - DWORD ffFormat; // format flags. + DWORD cyHeight; // notice lack of 'th' in the word height. + long cbxPitch; // number of bytes to move right one x pixel - can be negative. + long cbyPitch; // number of bytes to move down one y pixel - can be negative. + long cBPP; // # of bits in each pixel + DWORD ffFormat; // format flags. }; -struct GXKeyList { - short vkUp; // key for up - POINT ptUp; // x,y position of key/button. Not on screen but in screen coordinates. +struct GXKeyList +{ + short vkUp; // key for up + POINT ptUp; // x,y position of key/button. Not on screen but in screen coordinates. short vkDown; POINT ptDown; short vkLeft; @@ -58,64 +60,66 @@ struct GXKeyList { POINT ptStart; }; -typedef int (*PFNGXOpenDisplay)(HWND hWnd, DWORD dwFlags); -typedef int (*PFNGXCloseDisplay)(); -typedef void* (*PFNGXBeginDraw)(); -typedef int (*PFNGXEndDraw)(); -typedef int (*PFNGXOpenInput)(); -typedef int (*PFNGXCloseInput)(); -typedef struct GXDisplayProperties (*PFNGXGetDisplayProperties)(); -typedef struct GXKeyList (*PFNGXGetDefaultKeys)(int iOptions); -typedef int (*PFNGXSuspend)(); -typedef int (*PFNGXResume)(); -typedef int (*PFNGXSetViewport)( DWORD dwTop, DWORD dwHeight, DWORD dwReserved1, DWORD dwReserved2 ); -typedef BOOL (*PFNGXIsDisplayDRAMBuffer)(); +typedef int (*PFNGXOpenDisplay) (HWND hWnd, DWORD dwFlags); +typedef int (*PFNGXCloseDisplay) (); +typedef void *(*PFNGXBeginDraw) (); +typedef int (*PFNGXEndDraw) (); +typedef int (*PFNGXOpenInput) (); +typedef int (*PFNGXCloseInput) (); +typedef struct GXDisplayProperties (*PFNGXGetDisplayProperties) (); +typedef struct GXKeyList (*PFNGXGetDefaultKeys) (int iOptions); +typedef int (*PFNGXSuspend) (); +typedef int (*PFNGXResume) (); +typedef int (*PFNGXSetViewport) (DWORD dwTop, DWORD dwHeight, + DWORD dwReserved1, DWORD dwReserved2); +typedef BOOL(*PFNGXIsDisplayDRAMBuffer) (); struct GapiFunc { - PFNGXOpenDisplay GXOpenDisplay; - PFNGXCloseDisplay GXCloseDisplay; - PFNGXBeginDraw GXBeginDraw; - PFNGXEndDraw GXEndDraw; - PFNGXOpenInput GXOpenInput; - PFNGXCloseInput GXCloseInput; + PFNGXOpenDisplay GXOpenDisplay; + PFNGXCloseDisplay GXCloseDisplay; + PFNGXBeginDraw GXBeginDraw; + PFNGXEndDraw GXEndDraw; + PFNGXOpenInput GXOpenInput; + PFNGXCloseInput GXCloseInput; PFNGXGetDisplayProperties GXGetDisplayProperties; - PFNGXGetDefaultKeys GXGetDefaultKeys; - PFNGXSuspend GXSuspend; - PFNGXResume GXResume; - PFNGXSetViewport GXSetViewport; - PFNGXIsDisplayDRAMBuffer GXIsDisplayDRAMBuffer; + PFNGXGetDefaultKeys GXGetDefaultKeys; + PFNGXSuspend GXSuspend; + PFNGXResume GXResume; + PFNGXSetViewport GXSetViewport; + PFNGXIsDisplayDRAMBuffer GXIsDisplayDRAMBuffer; }; -#define kfLandscape 0x8 // Screen is rotated 270 degrees -#define kfPalette 0x10 // Pixel values are indexes into a palette -#define kfDirect 0x20 // Pixel values contain actual level information -#define kfDirect555 0x40 // 5 bits each for red, green and blue values in a pixel. -#define kfDirect565 0x80 // 5 red bits, 6 green bits and 5 blue bits per pixel -#define kfDirect888 0x100 // 8 bits each for red, green and blue values in a pixel. -#define kfDirect444 0x200 // 4 red, 4 green, 4 blue +#define kfLandscape 0x8 // Screen is rotated 270 degrees +#define kfPalette 0x10 // Pixel values are indexes into a palette +#define kfDirect 0x20 // Pixel values contain actual level information +#define kfDirect555 0x40 // 5 bits each for red, green and blue values in a pixel. +#define kfDirect565 0x80 // 5 red bits, 6 green bits and 5 blue bits per pixel +#define kfDirect888 0x100 // 8 bits each for red, green and blue values in a pixel. +#define kfDirect444 0x200 // 4 red, 4 green, 4 blue #define kfDirectInverted 0x400 -#define GX_FULLSCREEN 0x01 // for OpenDisplay() +#define GX_FULLSCREEN 0x01 // for OpenDisplay() #define GX_NORMALKEYS 0x02 #define GX_LANDSCAPEKEYS 0x03 typedef enum { - SDL_ORIENTATION_UP, - SDL_ORIENTATION_DOWN, - SDL_ORIENTATION_LEFT, - SDL_ORIENTATION_RIGHT + SDL_ORIENTATION_UP, + SDL_ORIENTATION_DOWN, + SDL_ORIENTATION_LEFT, + SDL_ORIENTATION_RIGHT } SDL_ScreenOrientation; /* GAPI video mode */ -typedef enum { - GAPI_NONE = 0, - GAPI_DIRECT_565, - GAPI_DIRECT_555, - GAPI_MONO, - GAPI_PALETTE -} GAPIVideoMode; +typedef enum +{ + GAPI_NONE = 0, + GAPI_DIRECT_565, + GAPI_DIRECT_555, + GAPI_MONO, + GAPI_PALETTE +} GAPIVideoMode; /* Hidden "this" pointer for the video functions */ #define _THIS SDL_VideoDevice *this @@ -125,34 +129,35 @@ typedef unsigned short PIXEL; /* Private display data begin with DIB private structure to allow DIB events code sharing */ -struct SDL_PrivateVideoData { +struct SDL_PrivateVideoData +{ HBITMAP screen_bmp; HPALETTE screen_pal; -#define NUM_MODELISTS 4 /* 8, 16, 24, and 32 bits-per-pixel */ +#define NUM_MODELISTS 4 /* 8, 16, 24, and 32 bits-per-pixel */ int SDL_nummodes[NUM_MODELISTS]; SDL_Rect **SDL_modelist[NUM_MODELISTS]; - enum SDL_ScreenOrientation userOrientation; - int invert; - char hiresFix; // using hires mode without defining hires resource + enum SDL_ScreenOrientation userOrientation; + int invert; + char hiresFix; // using hires mode without defining hires resource // -------------- - int useGXOpenDisplay; /* use GXOpenDispplay */ + int useGXOpenDisplay; /* use GXOpenDispplay */ int w, h; - enum SDL_ScreenOrientation gapiOrientation; - - void *buffer; // may be 8, 16, 24, 32 bpp - PIXEL *videoMem; - BOOL needUpdate; - struct GXKeyList keyList; - struct GapiFunc gxFunc; - struct GXDisplayProperties gxProperties; - enum GAPIVideoMode videoMode; - int colorscale; - int dstLineStep; // in bytes - int dstPixelStep; // in bytes - int startOffset; // in bytes - int useVga; - int suspended; // do not pu anything into video memory + enum SDL_ScreenOrientation gapiOrientation; + + void *buffer; // may be 8, 16, 24, 32 bpp + PIXEL *videoMem; + BOOL needUpdate; + struct GXKeyList keyList; + struct GapiFunc gxFunc; + struct GXDisplayProperties gxProperties; + enum GAPIVideoMode videoMode; + int colorscale; + int dstLineStep; // in bytes + int dstPixelStep; // in bytes + int startOffset; // in bytes + int useVga; + int suspended; // do not pu anything into video memory }; @@ -160,3 +165,4 @@ struct SDL_PrivateVideoData { #define gapi this->hidden #endif /* _SDL_gapivideo_h */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/gem/SDL_gemevents.c b/src/video/gem/SDL_gemevents.c index 09d6fa85b..dcf205ecc 100644 --- a/src/video/gem/SDL_gemevents.c +++ b/src/video/gem/SDL_gemevents.c @@ -36,7 +36,7 @@ #include "../../events/SDL_events_c.h" #include "SDL_gemvideo.h" #include "SDL_gemevents_c.h" -#include "../ataricommon/SDL_atarikeys.h" /* for keyboard scancodes */ +#include "../ataricommon/SDL_atarikeys.h" /* for keyboard scancodes */ #include "../ataricommon/SDL_atarievents_c.h" #include "../ataricommon/SDL_xbiosevents_c.h" #include "../ataricommon/SDL_ataridevmouse_c.h" @@ -56,387 +56,405 @@ static SDLKey keymap[ATARIBIOS_MAXKEYS]; /* Functions prototypes */ -static SDL_keysym *TranslateKey(int scancode, int asciicode, SDL_keysym *keysym, - SDL_bool pressed); +static SDL_keysym *TranslateKey(int scancode, int asciicode, + SDL_keysym * keysym, SDL_bool pressed); static int do_messages(_THIS, short *message); static void do_keyboard(short kc, short ks); static void do_mouse(_THIS, short mx, short my, short mb, short ks); /* Functions */ -static SDL_keysym *TranslateKey(int scancode, int asciicode, SDL_keysym *keysym, - SDL_bool pressed) +static SDL_keysym * +TranslateKey(int scancode, int asciicode, SDL_keysym * keysym, + SDL_bool pressed) { - /* Set the keysym information */ - keysym->scancode = scancode; + /* Set the keysym information */ + keysym->scancode = scancode; - if (asciicode) - keysym->sym = asciicode; - else - keysym->sym = keymap[scancode]; + if (asciicode) + keysym->sym = asciicode; + else + keysym->sym = keymap[scancode]; - keysym->mod = KMOD_NONE; - keysym->unicode = 0; - if (SDL_TranslateUNICODE && pressed) { - keysym->unicode = SDL_AtariToUnicodeTable[asciicode]; - } + keysym->mod = KMOD_NONE; + keysym->unicode = 0; + if (SDL_TranslateUNICODE && pressed) { + keysym->unicode = SDL_AtariToUnicodeTable[asciicode]; + } - return(keysym); + return (keysym); } -void GEM_InitOSKeymap(_THIS) +void +GEM_InitOSKeymap(_THIS) { - int i; - - SDL_memset(gem_currentkeyboard, 0, sizeof(gem_currentkeyboard)); - SDL_memset(gem_previouskeyboard, 0, sizeof(gem_previouskeyboard)); - SDL_memset(gem_currentascii, 0, sizeof(gem_currentascii)); - - /* Initialize keymap */ - for ( i=0; i=0)) { - wind_get (GEM_handle, WF_WORKXYWH, &x2, &y2, &w2, &h2); - event_mask |= MU_M1; - if ( (SDL_GetAppState() & SDL_APPMOUSEFOCUS) ) { - mouse_event = MO_LEAVE; - } else { - mouse_event = MO_ENTER; - } - } - - resultat = evnt_multi( - event_mask, - 0,0,0, - mouse_event,x2,y2,w2,h2, - 0,0,0,0,0, - buffer, - 10, - &dummy,&dummy,&dummy,&kstate,&kc,&dummy - ); - - /* Message event ? */ - if (resultat & MU_MESAG) - quit = do_messages(this, buffer); - - /* Keyboard event ? */ - if (resultat & MU_KEYBD) { - if ((prevkc != kc) || (prevks != kstate)) { - do_keyboard(kc,kstate); - } else { - /* Avoid looping, if repeating same key */ - break; - } - } - - /* Mouse entering/leaving window */ - if (resultat & MU_M1) { - if (this->input_grab == SDL_GRAB_OFF) { - if (SDL_GetAppState() & SDL_APPMOUSEFOCUS) { - SDL_PrivateAppActive(0, SDL_APPMOUSEFOCUS); - if (SDL_GetAppState() & SDL_APPINPUTFOCUS) { - graf_mouse(ARROW, NULL); - } - } else { - SDL_PrivateAppActive(1, SDL_APPMOUSEFOCUS); - if (SDL_GetAppState() & SDL_APPINPUTFOCUS) { - if (GEM_cursor == (void *) -1) { - graf_mouse(M_OFF, NULL); - } else if (GEM_cursor) { - graf_mouse(USER_DEF, GEM_cursor->mform_p); - } - } - } - } - } - - /* Timer event ? */ - if ((resultat & MU_TIMER) || quit) - break; - } - - /* Update mouse */ - graf_mkstate(&mousex, &mousey, &mouseb, &kstate); - do_mouse(this, mousex, mousey, mouseb, kstate); - - /* Now generate keyboard events */ - for (i=0; i>16),(short)(((unsigned long)GEM_title_name) & 0xffff),0,0); - } - } else { - /* Iconified */ - if (GEM_icon_name) { - wind_set(GEM_handle,WF_NAME,(short)(((unsigned long)GEM_icon_name)>>16),(short)(((unsigned long)GEM_icon_name) & 0xffff),0,0); - } - } - GEM_refresh_name = SDL_FALSE; - } + short mousex, mousey, mouseb, dummy; + short kstate, prevkc, prevks; + int i; + SDL_keysym keysym; + + SDL_memset(gem_currentkeyboard, 0, sizeof(gem_currentkeyboard)); + prevkc = prevks = 0; + + for (;;) { + int quit, resultat, event_mask, mouse_event; + short buffer[8], kc; + short x2, y2, w2, h2; + + quit = mouse_event = x2 = y2 = w2 = h2 = 0; + + event_mask = MU_MESAG | MU_TIMER | MU_KEYBD; + if (!GEM_fullscreen && (GEM_handle >= 0)) { + wind_get(GEM_handle, WF_WORKXYWH, &x2, &y2, &w2, &h2); + event_mask |= MU_M1; + if ((SDL_GetAppState() & SDL_APPMOUSEFOCUS)) { + mouse_event = MO_LEAVE; + } else { + mouse_event = MO_ENTER; + } + } + + resultat = evnt_multi(event_mask, + 0, 0, 0, + mouse_event, x2, y2, w2, h2, + 0, 0, 0, 0, 0, + buffer, + 10, + &dummy, &dummy, &dummy, &kstate, &kc, &dummy); + + /* Message event ? */ + if (resultat & MU_MESAG) + quit = do_messages(this, buffer); + + /* Keyboard event ? */ + if (resultat & MU_KEYBD) { + if ((prevkc != kc) || (prevks != kstate)) { + do_keyboard(kc, kstate); + } else { + /* Avoid looping, if repeating same key */ + break; + } + } + + /* Mouse entering/leaving window */ + if (resultat & MU_M1) { + if (this->input_grab == SDL_GRAB_OFF) { + if (SDL_GetAppState() & SDL_APPMOUSEFOCUS) { + SDL_PrivateAppActive(0, SDL_APPMOUSEFOCUS); + } else { + SDL_PrivateAppActive(1, SDL_APPMOUSEFOCUS); + } + } + } + + /* Timer event ? */ + if ((resultat & MU_TIMER) || quit) + break; + } + + /* Update mouse */ + graf_mkstate(&mousex, &mousey, &mouseb, &kstate); + do_mouse(this, mousex, mousey, mouseb, kstate); + + /* Now generate keyboard events */ + for (i = 0; i < ATARIBIOS_MAXKEYS; i++) { + /* Key pressed ? */ + if (gem_currentkeyboard[i] && !gem_previouskeyboard[i]) + SDL_PrivateKeyboard(SDL_PRESSED, + TranslateKey(i, gem_currentascii[i], + &keysym, SDL_TRUE)); + + /* Key unpressed ? */ + if (gem_previouskeyboard[i] && !gem_currentkeyboard[i]) + SDL_PrivateKeyboard(SDL_RELEASED, + TranslateKey(i, gem_currentascii[i], + &keysym, SDL_FALSE)); + } + + SDL_memcpy(gem_previouskeyboard, gem_currentkeyboard, + sizeof(gem_previouskeyboard)); + + /* Refresh window name ? */ + if (GEM_refresh_name) { + if (SDL_GetAppState() & SDL_APPACTIVE) { + /* Fullscreen/windowed */ + if (GEM_title_name) { + wind_set(GEM_handle, WF_NAME, + (short) (((unsigned long) GEM_title_name) >> + 16), + (short) (((unsigned long) GEM_title_name) & + 0xffff), 0, 0); + } + } else { + /* Iconified */ + if (GEM_icon_name) { + wind_set(GEM_handle, WF_NAME, + (short) (((unsigned long) GEM_icon_name) >> + 16), + (short) (((unsigned long) GEM_icon_name) & + 0xffff), 0, 0); + } + } + GEM_refresh_name = SDL_FALSE; + } } -static int do_messages(_THIS, short *message) +static int +do_messages(_THIS, short *message) { - int quit, posted; - short x2,y2,w2,h2; - - quit=0; - switch (message[0]) { - case WM_CLOSED: - case AP_TERM: - posted = SDL_PrivateQuit(); - quit=1; - break; - case WM_MOVED: - wind_set(message[3],WF_CURRXYWH,message[4],message[5],message[6],message[7]); - break; - case WM_TOPPED: - wind_set(message[3],WF_TOP,message[4],0,0,0); - /* Continue with TOP event processing */ - case WM_ONTOP: - SDL_PrivateAppActive(1, SDL_APPINPUTFOCUS); - if (VDI_setpalette) { - VDI_setpalette(this, VDI_curpalette); - } - break; - case WM_REDRAW: - if (!GEM_lock_redraw) { - GEM_wind_redraw(this, message[3],&message[4]); - } - break; - case WM_ICONIFY: - case WM_ALLICONIFY: - wind_set(message[3],WF_ICONIFY,message[4],message[5],message[6],message[7]); - /* If we're active, make ourselves inactive */ - if ( SDL_GetAppState() & SDL_APPACTIVE ) { - /* Send an internal deactivate event */ - SDL_PrivateAppActive(0, SDL_APPACTIVE); - } - /* Update window title */ - if (GEM_refresh_name && GEM_icon_name) { - wind_set(GEM_handle,WF_NAME,(short)(((unsigned long)GEM_icon_name)>>16),(short)(((unsigned long)GEM_icon_name) & 0xffff),0,0); - GEM_refresh_name = SDL_FALSE; - } - break; - case WM_UNICONIFY: - wind_set(message[3],WF_UNICONIFY,message[4],message[5],message[6],message[7]); - /* If we're not active, make ourselves active */ - if ( !(SDL_GetAppState() & SDL_APPACTIVE) ) { - /* Send an internal activate event */ - SDL_PrivateAppActive(1, SDL_APPACTIVE); - } - if (GEM_refresh_name && GEM_title_name) { - wind_set(GEM_handle,WF_NAME,(short)(((unsigned long)GEM_title_name)>>16),(short)(((unsigned long)GEM_title_name) & 0xffff),0,0); - GEM_refresh_name = SDL_FALSE; - } - break; - case WM_SIZED: - wind_set (message[3], WF_CURRXYWH, message[4], message[5], message[6], message[7]); - wind_get (message[3], WF_WORKXYWH, &x2, &y2, &w2, &h2); - GEM_win_fulled = SDL_FALSE; /* Cancel maximized flag */ - GEM_lock_redraw = SDL_TRUE; /* Prevent redraw till buffers resized */ - SDL_PrivateResize(w2, h2); - break; - case WM_FULLED: - { - short x,y,w,h; - - if (GEM_win_fulled) { - wind_get (message[3], WF_PREVXYWH, &x, &y, &w, &h); - GEM_win_fulled = SDL_FALSE; - } else { - x = GEM_desk_x; - y = GEM_desk_y; - w = GEM_desk_w; - h = GEM_desk_h; - GEM_win_fulled = SDL_TRUE; - } - wind_set (message[3], WF_CURRXYWH, x, y, w, h); - wind_get (message[3], WF_WORKXYWH, &x2, &y2, &w2, &h2); - GEM_lock_redraw = SDL_TRUE; /* Prevent redraw till buffers resized */ - SDL_PrivateResize(w2, h2); - } - break; - case WM_BOTTOMED: - wind_set(message[3],WF_BOTTOM,0,0,0,0); - /* Continue with BOTTOM event processing */ - case WM_UNTOPPED: - SDL_PrivateAppActive(0, SDL_APPINPUTFOCUS); - if (VDI_setpalette) { - VDI_setpalette(this, VDI_oldpalette); - } - break; - } - - return quit; + int quit, posted; + short x2, y2, w2, h2; + + quit = 0; + switch (message[0]) { + case WM_CLOSED: + case AP_TERM: + posted = SDL_PrivateQuit(); + quit = 1; + break; + case WM_MOVED: + wind_set(message[3], WF_CURRXYWH, message[4], message[5], + message[6], message[7]); + break; + case WM_TOPPED: + wind_set(message[3], WF_TOP, message[4], 0, 0, 0); + /* Continue with TOP event processing */ + case WM_ONTOP: + SDL_PrivateAppActive(1, SDL_APPINPUTFOCUS); + if (VDI_setpalette) { + VDI_setpalette(this, VDI_curpalette); + } + break; + case WM_REDRAW: + if (!GEM_lock_redraw) { + GEM_wind_redraw(this, message[3], &message[4]); + } + break; + case WM_ICONIFY: + case WM_ALLICONIFY: + wind_set(message[3], WF_ICONIFY, message[4], message[5], + message[6], message[7]); + /* If we're active, make ourselves inactive */ + if (SDL_GetAppState() & SDL_APPACTIVE) { + /* Send an internal deactivate event */ + SDL_PrivateAppActive(0, SDL_APPACTIVE); + } + /* Update window title */ + if (GEM_refresh_name && GEM_icon_name) { + wind_set(GEM_handle, WF_NAME, + (short) (((unsigned long) GEM_icon_name) >> 16), + (short) (((unsigned long) GEM_icon_name) & 0xffff), + 0, 0); + GEM_refresh_name = SDL_FALSE; + } + break; + case WM_UNICONIFY: + wind_set(message[3], WF_UNICONIFY, message[4], message[5], + message[6], message[7]); + /* If we're not active, make ourselves active */ + if (!(SDL_GetAppState() & SDL_APPACTIVE)) { + /* Send an internal activate event */ + SDL_PrivateAppActive(1, SDL_APPACTIVE); + } + if (GEM_refresh_name && GEM_title_name) { + wind_set(GEM_handle, WF_NAME, + (short) (((unsigned long) GEM_title_name) >> 16), + (short) (((unsigned long) GEM_title_name) & 0xffff), + 0, 0); + GEM_refresh_name = SDL_FALSE; + } + break; + case WM_SIZED: + wind_set(message[3], WF_CURRXYWH, message[4], message[5], + message[6], message[7]); + wind_get(message[3], WF_WORKXYWH, &x2, &y2, &w2, &h2); + GEM_win_fulled = SDL_FALSE; /* Cancel maximized flag */ + GEM_lock_redraw = SDL_TRUE; /* Prevent redraw till buffers resized */ + SDL_PrivateResize(w2, h2); + break; + case WM_FULLED: + { + short x, y, w, h; + + if (GEM_win_fulled) { + wind_get(message[3], WF_PREVXYWH, &x, &y, &w, &h); + GEM_win_fulled = SDL_FALSE; + } else { + x = GEM_desk_x; + y = GEM_desk_y; + w = GEM_desk_w; + h = GEM_desk_h; + GEM_win_fulled = SDL_TRUE; + } + wind_set(message[3], WF_CURRXYWH, x, y, w, h); + wind_get(message[3], WF_WORKXYWH, &x2, &y2, &w2, &h2); + GEM_lock_redraw = SDL_TRUE; /* Prevent redraw till buffers resized */ + SDL_PrivateResize(w2, h2); + } + break; + case WM_BOTTOMED: + wind_set(message[3], WF_BOTTOM, 0, 0, 0, 0); + /* Continue with BOTTOM event processing */ + case WM_UNTOPPED: + SDL_PrivateAppActive(0, SDL_APPINPUTFOCUS); + if (VDI_setpalette) { + VDI_setpalette(this, VDI_oldpalette); + } + break; + } + + return quit; } -static void do_keyboard(short kc, short ks) +static void +do_keyboard(short kc, short ks) { - int scancode, asciicode; - - if (kc) { - scancode=(kc>>8) & 127; - asciicode=kc & 255; - - gem_currentkeyboard[scancode]=0xFF; - gem_currentascii[scancode]=asciicode; - } - - /* Read special keys */ - if (ks & K_RSHIFT) - gem_currentkeyboard[SCANCODE_RIGHTSHIFT]=0xFF; - if (ks & K_LSHIFT) - gem_currentkeyboard[SCANCODE_LEFTSHIFT]=0xFF; - if (ks & K_CTRL) - gem_currentkeyboard[SCANCODE_LEFTCONTROL]=0xFF; - if (ks & K_ALT) - gem_currentkeyboard[SCANCODE_LEFTALT]=0xFF; + int scancode, asciicode; + + if (kc) { + scancode = (kc >> 8) & 127; + asciicode = kc & 255; + + gem_currentkeyboard[scancode] = 0xFF; + gem_currentascii[scancode] = asciicode; + } + + /* Read special keys */ + if (ks & K_RSHIFT) + gem_currentkeyboard[SCANCODE_RIGHTSHIFT] = 0xFF; + if (ks & K_LSHIFT) + gem_currentkeyboard[SCANCODE_LEFTSHIFT] = 0xFF; + if (ks & K_CTRL) + gem_currentkeyboard[SCANCODE_LEFTCONTROL] = 0xFF; + if (ks & K_ALT) + gem_currentkeyboard[SCANCODE_LEFTALT] = 0xFF; } -static void do_mouse(_THIS, short mx, short my, short mb, short ks) +static void +do_mouse(_THIS, short mx, short my, short mb, short ks) { - static short prevmousex=0, prevmousey=0, prevmouseb=0; - short x2, y2, w2, h2; - - /* Don't return mouse events if out of window */ - if ((SDL_GetAppState() & SDL_APPMOUSEFOCUS)==0) { - return; - } - - /* Retrieve window coords, and generate mouse events accordingly */ - x2 = y2 = 0; - w2 = VDI_w; - h2 = VDI_h; - if ((!GEM_fullscreen) && (GEM_handle>=0)) { - wind_get (GEM_handle, WF_WORKXYWH, &x2, &y2, &w2, &h2); - - /* Do not generate mouse button event if out of window working area */ - if ((mx=x2+w2) || (my=y2+h2)) { - mb=prevmouseb; - } - } - - /* Mouse motion ? */ - if (GEM_mouse_relative) { - if (GEM_usedevmouse) { - SDL_AtariDevMouse_PostMouseEvents(this, SDL_FALSE); - } else { - SDL_AtariXbios_PostMouseEvents(this, SDL_FALSE); - } - } else { - if ((prevmousex!=mx) || (prevmousey!=my)) { - int posx, posy; - - /* Give mouse position relative to window position */ - posx = mx - x2; - if (posx<0) posx = 0; - if (posx>w2) posx = w2-1; - posy = my - y2; - if (posy<0) posy = 0; - if (posy>h2) posy = h2-1; - - SDL_PrivateMouseMotion(0, 0, posx, posy); - } - prevmousex = mx; - prevmousey = my; - } - - /* Mouse button ? */ - if (prevmouseb!=mb) { - int i; - - for (i=0;i<2;i++) { - int curbutton, prevbutton; - - curbutton = mb & (1<= 0)) { + wind_get(GEM_handle, WF_WORKXYWH, &x2, &y2, &w2, &h2); + + /* Do not generate mouse button event if out of window working area */ + if ((mx < x2) || (mx >= x2 + w2) || (my < y2) || (my >= y2 + h2)) { + mb = prevmouseb; + } + } + + /* Mouse motion ? */ + if (GEM_mouse_relative) { + if (GEM_usedevmouse) { + SDL_AtariDevMouse_PostMouseEvents(this, SDL_FALSE); + } else { + SDL_AtariXbios_PostMouseEvents(this, SDL_FALSE); + } + } else { + if ((prevmousex != mx) || (prevmousey != my)) { + int posx, posy; + + /* Give mouse position relative to window position */ + posx = mx - x2; + if (posx < 0) + posx = 0; + if (posx > w2) + posx = w2 - 1; + posy = my - y2; + if (posy < 0) + posy = 0; + if (posy > h2) + posy = h2 - 1; + + SDL_PrivateMouseMotion(0, 0, posx, posy); + } + prevmousex = mx; + prevmousey = my; + } + + /* Mouse button ? */ + if (prevmouseb != mb) { + int i; + + for (i = 0; i < 2; i++) { + int curbutton, prevbutton; + + curbutton = mb & (1 << i); + prevbutton = prevmouseb & (1 << i); + + if (curbutton && !prevbutton) { + SDL_PrivateMouseButton(SDL_PRESSED, i + 1, 0, 0); + } + if (!curbutton && prevbutton) { + SDL_PrivateMouseButton(SDL_RELEASED, i + 1, 0, 0); + } + } + prevmouseb = mb; + } + + /* Read special keys */ + if (ks & K_RSHIFT) + gem_currentkeyboard[SCANCODE_RIGHTSHIFT] = 0xFF; + if (ks & K_LSHIFT) + gem_currentkeyboard[SCANCODE_LEFTSHIFT] = 0xFF; + if (ks & K_CTRL) + gem_currentkeyboard[SCANCODE_LEFTCONTROL] = 0xFF; + if (ks & K_ALT) + gem_currentkeyboard[SCANCODE_LEFTALT] = 0xFF; } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/gem/SDL_gemevents_c.h b/src/video/gem/SDL_gemevents_c.h index 919f86fe9..329180230 100644 --- a/src/video/gem/SDL_gemevents_c.h +++ b/src/video/gem/SDL_gemevents_c.h @@ -30,4 +30,4 @@ extern void GEM_InitOSKeymap(_THIS); extern void GEM_PumpEvents(_THIS); /* end of SDL_gemevents_c.h */ - +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/gem/SDL_gemmouse.c b/src/video/gem/SDL_gemmouse.c index cc41bc5c3..4e640681d 100644 --- a/src/video/gem/SDL_gemmouse.c +++ b/src/video/gem/SDL_gemmouse.c @@ -33,7 +33,6 @@ #include "../../events/SDL_events_c.h" #include "../SDL_cursor_c.h" #include "SDL_gemmouse_c.h" -#include "SDL_gemvideo.h" /* Defines */ @@ -42,144 +41,138 @@ #define MAXCURWIDTH 16 #define MAXCURHEIGHT 16 -void GEM_FreeWMCursor(_THIS, WMcursor *cursor) +/* The implementation dependent data for the window manager cursor */ +struct WMcursor { -#ifdef DEBUG_VIDEO_GEM - printf("sdl:video:gem: free cursor\n"); -#endif - - if (cursor == NULL) - return; - - graf_mouse(ARROW, NULL); - - if (cursor->mform_p != NULL) - SDL_free(cursor->mform_p); + MFORM *mform_p; +}; - SDL_free(cursor); -} -WMcursor *GEM_CreateWMCursor(_THIS, - Uint8 *data, Uint8 *mask, int w, int h, int hot_x, int hot_y) +void +GEM_FreeWMCursor(_THIS, WMcursor * cursor) { - WMcursor *cursor; - MFORM *new_mform; - int i; - -#ifdef DEBUG_VIDEO_GEM - Uint16 *data1, *mask1; - - printf("sdl:video:gem: create cursor\n"); -#endif - - /* Check the size */ - if ( (w > MAXCURWIDTH) || (h > MAXCURHEIGHT) ) { - SDL_SetError("Only cursors of dimension (%dx%d) are allowed", - MAXCURWIDTH, MAXCURHEIGHT); - return(NULL); - } - - /* Allocate the cursor memory */ - cursor = (WMcursor *)SDL_malloc(sizeof(WMcursor)); - if ( cursor == NULL ) { - SDL_OutOfMemory(); - return(NULL); - } - - /* Allocate mform */ - new_mform = (MFORM *)SDL_malloc(sizeof(MFORM)); - if (new_mform == NULL) { - SDL_free(cursor); - SDL_OutOfMemory(); - return(NULL); - } + if (cursor == NULL) + return; - cursor->mform_p = new_mform; + graf_mouse(ARROW, NULL); - new_mform->mf_xhot = hot_x; - new_mform->mf_yhot = hot_y; - new_mform->mf_nplanes = 1; - new_mform->mf_fg = 0; - new_mform->mf_bg = 1; + if (cursor->mform_p != NULL) + SDL_free(cursor->mform_p); - for (i=0;imf_mask[i]=0; - new_mform->mf_data[i]=0; -#ifdef DEBUG_VIDEO_GEM - data1 = (Uint16 *) &data[i<<1]; - mask1 = (Uint16 *) &mask[i<<1]; - printf("sdl:video:gem: source: line %d: data=0x%04x, mask=0x%04x\n", - i, data1[i], mask1[i]); -#endif - } + SDL_free(cursor); +} - if (w<=8) { - for (i=0;imf_mask[i]= mask[i]<<8; - new_mform->mf_data[i]= data[i]<<8; - } - } else { - for (i=0;imf_mask[i]= (mask[i<<1]<<8) | mask[(i<<1)+1]; - new_mform->mf_data[i]= (data[i<<1]<<8) | data[(i<<1)+1]; - } - } +WMcursor * +GEM_CreateWMCursor(_THIS, + Uint8 * data, Uint8 * mask, int w, int h, int hot_x, + int hot_y) +{ + WMcursor *cursor; + MFORM *new_mform; + int i; + + /* Check the size */ + if ((w > MAXCURWIDTH) || (h > MAXCURHEIGHT)) { + SDL_SetError("Only cursors of dimension (%dx%d) are allowed", + MAXCURWIDTH, MAXCURHEIGHT); + return (NULL); + } + + /* Allocate the cursor memory */ + cursor = (WMcursor *) SDL_malloc(sizeof(WMcursor)); + if (cursor == NULL) { + SDL_OutOfMemory(); + return (NULL); + } + + /* Allocate mform */ + new_mform = (MFORM *) SDL_malloc(sizeof(MFORM)); + if (new_mform == NULL) { + SDL_free(cursor); + SDL_OutOfMemory(); + return (NULL); + } + + cursor->mform_p = new_mform; + + new_mform->mf_xhot = hot_x; + new_mform->mf_yhot = hot_y; + new_mform->mf_nplanes = 1; + new_mform->mf_fg = 0; + new_mform->mf_bg = 1; + + for (i = 0; i < MAXCURHEIGHT; i++) { + new_mform->mf_mask[i] = 0; + new_mform->mf_data[i] = 0; + } + + if (w <= 8) { + for (i = 0; i < h; i++) { + new_mform->mf_mask[i] = mask[i] << 8; + new_mform->mf_data[i] = data[i] << 8; + } + } else { + for (i = 0; i < h; i++) { + new_mform->mf_mask[i] = mask[i << 1] << 8 | mask[(i << 1) + 1]; + new_mform->mf_data[i] = data[i << 1] << 8 | data[(i << 1) + 1]; + } + } #ifdef DEBUG_VIDEO_GEM - for (i=0; imf_data[i], new_mform->mf_mask[i]); - } + for (i = 0; i < h; i++) { + printf("sdl:video:gem: cursor, line %d = 0x%04x\n", i, + new_mform->mf_mask[i]); + } - printf("sdl:video:gem: CreateWMCursor(): done\n"); + printf("sdl:video:gem: CreateWMCursor(): done\n"); #endif - return cursor; + return cursor; } -int GEM_ShowWMCursor(_THIS, WMcursor *cursor) +int +GEM_ShowWMCursor(_THIS, WMcursor * cursor) { - GEM_cursor = cursor; +/* if (cursor == NULL) { graf_mouse(M_OFF, NULL); - GEM_cursor = (void *) -1; } else if (cursor->mform_p) { graf_mouse(USER_DEF, cursor->mform_p); } - +*/ #ifdef DEBUG_VIDEO_GEM - printf("sdl:video:gem: ShowWMCursor(0x%08x)\n", (long) cursor); + printf("sdl:video:gem: ShowWMCursor(0x%08x)\n", (long) cursor); #endif - return 1; + return 1; } #if 0 -void GEM_WarpWMCursor(_THIS, Uint16 x, Uint16 y) +void +GEM_WarpWMCursor(_THIS, Uint16 x, Uint16 y) { - /* This seems to work only on AES 3.4 (Falcon) */ + /* This seems to work only on AES 3.4 (Falcon) */ + + EVNTREC warpevent; - EVNTREC warpevent; - - warpevent.ap_event = APPEVNT_MOUSE; - warpevent.ap_value = (x << 16) | y; + warpevent.ap_event = APPEVNT_MOUSE; + warpevent.ap_value = (x << 16) | y; - appl_tplay(&warpevent, 1, 1000); + appl_tplay(&warpevent, 1, 1000); } #endif -void GEM_CheckMouseMode(_THIS) +void +GEM_CheckMouseMode(_THIS) { -#ifdef DEBUG_VIDEO_GEM - printf("sdl:video:gem: check mouse mode\n"); -#endif - - /* If the mouse is hidden and input is grabbed, we use relative mode */ - if ( (!(SDL_cursorstate & CURSOR_VISIBLE)) && - /*(this->input_grab != SDL_GRAB_OFF) && */ /* Damn GEM can not grab */ - (SDL_GetAppState() & SDL_APPACTIVE) ) { - GEM_mouse_relative = SDL_TRUE; - } else { - GEM_mouse_relative = SDL_FALSE; - } + /* If the mouse is hidden and input is grabbed, we use relative mode */ + if ((!(SDL_cursorstate & CURSOR_VISIBLE)) && + /*(this->input_grab != SDL_GRAB_OFF) && *//* Damn GEM can not grab */ + (SDL_GetAppState() & SDL_APPACTIVE)) { + GEM_mouse_relative = SDL_TRUE; + } else { + GEM_mouse_relative = SDL_FALSE; + } } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/gem/SDL_gemmouse_c.h b/src/video/gem/SDL_gemmouse_c.h index 88028f432..fbc2e84a5 100644 --- a/src/video/gem/SDL_gemmouse_c.h +++ b/src/video/gem/SDL_gemmouse_c.h @@ -24,11 +24,13 @@ #include "SDL_gemvideo.h" /* Functions to be exported */ -extern void GEM_FreeWMCursor(_THIS, WMcursor *cursor); +extern void GEM_FreeWMCursor(_THIS, WMcursor * cursor); extern WMcursor *GEM_CreateWMCursor(_THIS, - Uint8 *data, Uint8 *mask, int w, int h, int hot_x, int hot_y); -extern int GEM_ShowWMCursor(_THIS, WMcursor *cursor); + Uint8 * data, Uint8 * mask, int w, int h, + int hot_x, int hot_y); +extern int GEM_ShowWMCursor(_THIS, WMcursor * cursor); #if 0 extern void GEM_WarpWMCursor(_THIS, Uint16 x, Uint16 y); #endif extern void GEM_CheckMouseMode(_THIS); +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/gem/SDL_gemvideo.c b/src/video/gem/SDL_gemvideo.c index fea61dbd0..e32a1b423 100644 --- a/src/video/gem/SDL_gemvideo.c +++ b/src/video/gem/SDL_gemvideo.c @@ -69,26 +69,29 @@ /* Variables */ static unsigned char vdi_index[256] = { - 0, 2, 3, 6, 4, 7, 5, 8, - 9, 10, 11, 14, 12, 15, 13, 255 + 0, 2, 3, 6, 4, 7, 5, 8, + 9, 10, 11, 14, 12, 15, 13, 255 }; -static const unsigned char empty_name[]=""; +static const unsigned char empty_name[] = ""; /* Initialization/Query functions */ -static int GEM_VideoInit(_THIS, SDL_PixelFormat *vformat); -static SDL_Rect **GEM_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags); -static SDL_Surface *GEM_SetVideoMode(_THIS, SDL_Surface *current, int width, int height, int bpp, Uint32 flags); -static int GEM_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color *colors); +static int GEM_VideoInit(_THIS, SDL_PixelFormat * vformat); +static SDL_Rect **GEM_ListModes(_THIS, SDL_PixelFormat * format, + Uint32 flags); +static SDL_Surface *GEM_SetVideoMode(_THIS, SDL_Surface * current, int width, + int height, int bpp, Uint32 flags); +static int GEM_SetColors(_THIS, int firstcolor, int ncolors, + SDL_Color * colors); static void GEM_VideoQuit(_THIS); /* Hardware surface functions */ -static int GEM_AllocHWSurface(_THIS, SDL_Surface *surface); -static int GEM_LockHWSurface(_THIS, SDL_Surface *surface); -static int GEM_FlipHWSurface(_THIS, SDL_Surface *surface); -static void GEM_UnlockHWSurface(_THIS, SDL_Surface *surface); -static void GEM_FreeHWSurface(_THIS, SDL_Surface *surface); -static void GEM_UpdateRects(_THIS, int numrects, SDL_Rect *rects); +static int GEM_AllocHWSurface(_THIS, SDL_Surface * surface); +static int GEM_LockHWSurface(_THIS, SDL_Surface * surface); +static int GEM_FlipHWSurface(_THIS, SDL_Surface * surface); +static void GEM_UnlockHWSurface(_THIS, SDL_Surface * surface); +static void GEM_FreeHWSurface(_THIS, SDL_Surface * surface); +static void GEM_UpdateRects(_THIS, int numrects, SDL_Rect * rects); #if 0 static int GEM_ToggleFullScreen(_THIS, int on); #endif @@ -109,1232 +112,1267 @@ static void GEM_GL_SwapBuffers(_THIS); /* GEM driver bootstrap functions */ -static int GEM_Available(void) +static int +GEM_Available(void) { - /* Test if AES available */ - if (appl_init() == -1) - return 0; + /* Test if AES available */ + if (appl_init() == -1) + return 0; - appl_exit(); - return 1; + appl_exit(); + return 1; } -static void GEM_DeleteDevice(SDL_VideoDevice *device) +static void +GEM_DeleteDevice(SDL_VideoDevice * device) { - SDL_free(device->hidden); - SDL_free(device); + SDL_free(device->hidden); + SDL_free(device); } -static SDL_VideoDevice *GEM_CreateDevice(int devindex) +static SDL_VideoDevice * +GEM_CreateDevice(int devindex) { - SDL_VideoDevice *device; - int vectors_mask; - unsigned long dummy; - - /* Initialize all variables that we clean on shutdown */ - device = (SDL_VideoDevice *)SDL_malloc(sizeof(SDL_VideoDevice)); - if ( device ) { - SDL_memset(device, 0, (sizeof *device)); - device->hidden = (struct SDL_PrivateVideoData *) - SDL_malloc((sizeof *device->hidden)); - device->gl_data = (struct SDL_PrivateGLData *) - SDL_malloc((sizeof *device->gl_data)); - } - if ( (device == NULL) || (device->hidden == NULL) ) { - SDL_OutOfMemory(); - if ( device ) { - SDL_free(device); - } - return(0); - } - SDL_memset(device->hidden, 0, (sizeof *device->hidden)); - SDL_memset(device->gl_data, 0, sizeof(*device->gl_data)); - - /* Set the function pointers */ - device->VideoInit = GEM_VideoInit; - device->ListModes = GEM_ListModes; - device->SetVideoMode = GEM_SetVideoMode; - device->SetColors = GEM_SetColors; - device->UpdateRects = NULL /*GEM_UpdateRects*/; - device->VideoQuit = GEM_VideoQuit; - device->AllocHWSurface = GEM_AllocHWSurface; - device->LockHWSurface = GEM_LockHWSurface; - device->UnlockHWSurface = GEM_UnlockHWSurface; - device->FlipHWSurface = GEM_FlipHWSurface; - device->FreeHWSurface = GEM_FreeHWSurface; - device->ToggleFullScreen = NULL /*GEM_ToggleFullScreen*/; - - /* Window manager */ - device->SetCaption = GEM_SetCaption; - device->SetIcon = GEM_SetIcon; - device->IconifyWindow = GEM_IconifyWindow; - device->GrabInput = GEM_GrabInput; - - /* Events */ - device->InitOSKeymap = GEM_InitOSKeymap; - device->PumpEvents = GEM_PumpEvents; - - /* Mouse */ - device->FreeWMCursor = GEM_FreeWMCursor; - device->CreateWMCursor = GEM_CreateWMCursor; - device->ShowWMCursor = GEM_ShowWMCursor; - device->WarpWMCursor = NULL /*GEM_WarpWMCursor*/; - device->CheckMouseMode = GEM_CheckMouseMode; + SDL_VideoDevice *device; + int vectors_mask; + unsigned long dummy; + + /* Initialize all variables that we clean on shutdown */ + device = (SDL_VideoDevice *) SDL_malloc(sizeof(SDL_VideoDevice)); + if (device) { + SDL_memset(device, 0, (sizeof *device)); + device->hidden = (struct SDL_PrivateVideoData *) + SDL_malloc((sizeof *device->hidden)); + device->gl_data = (struct SDL_PrivateGLData *) + SDL_malloc((sizeof *device->gl_data)); + } + if ((device == NULL) || (device->hidden == NULL)) { + SDL_OutOfMemory(); + if (device) { + SDL_free(device); + } + return (0); + } + SDL_memset(device->hidden, 0, (sizeof *device->hidden)); + SDL_memset(device->gl_data, 0, sizeof(*device->gl_data)); + + /* Set the function pointers */ + device->VideoInit = GEM_VideoInit; + device->ListModes = GEM_ListModes; + device->SetVideoMode = GEM_SetVideoMode; + device->SetColors = GEM_SetColors; + device->UpdateRects = NULL /*GEM_UpdateRects */ ; + device->VideoQuit = GEM_VideoQuit; + device->AllocHWSurface = GEM_AllocHWSurface; + device->LockHWSurface = GEM_LockHWSurface; + device->UnlockHWSurface = GEM_UnlockHWSurface; + device->FlipHWSurface = GEM_FlipHWSurface; + device->FreeHWSurface = GEM_FreeHWSurface; + device->ToggleFullScreen = NULL /*GEM_ToggleFullScreen */ ; + + /* Window manager */ + device->SetCaption = GEM_SetCaption; + device->SetIcon = GEM_SetIcon; + device->IconifyWindow = GEM_IconifyWindow; + device->GrabInput = GEM_GrabInput; + + /* Events */ + device->InitOSKeymap = GEM_InitOSKeymap; + device->PumpEvents = GEM_PumpEvents; + + /* Mouse */ + device->FreeWMCursor = GEM_FreeWMCursor; + device->CreateWMCursor = GEM_CreateWMCursor; + device->ShowWMCursor = GEM_ShowWMCursor; + device->WarpWMCursor = NULL /*GEM_WarpWMCursor */ ; + device->CheckMouseMode = GEM_CheckMouseMode; #if SDL_VIDEO_OPENGL - /* OpenGL functions */ - device->GL_LoadLibrary = SDL_AtariGL_LoadLibrary; - device->GL_GetProcAddress = SDL_AtariGL_GetProcAddress; - device->GL_GetAttribute = SDL_AtariGL_GetAttribute; - device->GL_MakeCurrent = SDL_AtariGL_MakeCurrent; - device->GL_SwapBuffers = GEM_GL_SwapBuffers; + /* OpenGL functions */ + device->GL_LoadLibrary = SDL_AtariGL_LoadLibrary; + device->GL_GetProcAddress = SDL_AtariGL_GetProcAddress; + device->GL_GetAttribute = SDL_AtariGL_GetAttribute; + device->GL_MakeCurrent = SDL_AtariGL_MakeCurrent; + device->GL_SwapBuffers = GEM_GL_SwapBuffers; #endif - device->hidden->use_dev_mouse = - (SDL_AtariDevMouse_Open()!=0) ? SDL_TRUE : SDL_FALSE; + device->hidden->use_dev_mouse = + (SDL_AtariDevMouse_Open() != 0) ? SDL_TRUE : SDL_FALSE; - vectors_mask = ATARI_XBIOS_JOYSTICKEVENTS; /* XBIOS joystick events */ - if (!(device->hidden->use_dev_mouse)) { - vectors_mask |= ATARI_XBIOS_MOUSEEVENTS; /* XBIOS mouse events */ - } - if (Getcookie(C_MiNT, &dummy)==C_FOUND) { - vectors_mask = 0; - } + vectors_mask = ATARI_XBIOS_JOYSTICKEVENTS; /* XBIOS joystick events */ + if (!(device->hidden->use_dev_mouse)) { + vectors_mask |= ATARI_XBIOS_MOUSEEVENTS; /* XBIOS mouse events */ + } + if (Getcookie(C_MiNT, &dummy) == C_FOUND) { + vectors_mask = 0; + } - SDL_AtariXbios_InstallVectors(vectors_mask); + SDL_AtariXbios_InstallVectors(vectors_mask); - device->free = GEM_DeleteDevice; + device->free = GEM_DeleteDevice; - return device; + return device; } VideoBootStrap GEM_bootstrap = { - GEM_VID_DRIVER_NAME, "Atari GEM video driver", - GEM_Available, GEM_CreateDevice + GEM_VID_DRIVER_NAME, "Atari GEM video driver", + GEM_Available, GEM_CreateDevice }; -static void VDI_ReadExtInfo(_THIS, short *work_out) +static void +VDI_ReadExtInfo(_THIS, short *work_out) { - unsigned long EdDI_version; - unsigned long cookie_EdDI; - Uint32 num_colours; - Uint16 clut_type, num_bits; - - /* Read EdDI informations */ - if (Getcookie(C_EdDI, &cookie_EdDI) == C_NOTFOUND) { - return; - } - - EdDI_version = Atari_get_EdDI_version( (void *)cookie_EdDI); - - vq_scrninfo(VDI_handle, work_out); - - VDI_format = work_out[0]; - clut_type = work_out[1]; - num_bits = work_out[2]; - num_colours = *((Uint32 *) &work_out[3]); - - /* With EdDI>=1.1, we can have screen pitch, address and format - * so we can directly write to screen without using vro_cpyfm - */ - if (EdDI_version >= EDDI_11) { - VDI_pitch = work_out[5]; - VDI_screen = (void *) *((unsigned long *) &work_out[6]); - } - - switch(clut_type) { - case VDI_CLUT_HARDWARE: - { - int i; - Uint16 *tmp_p; - - tmp_p = (Uint16 *)&work_out[16]; - - for (i=0;i<256;i++) { - vdi_index[*tmp_p++] = i; - } - } - break; - case VDI_CLUT_SOFTWARE: - { - int component; /* red, green, blue, alpha, overlay */ - int num_bit; - unsigned short *tmp_p; - - /* We can build masks with info here */ - tmp_p = (unsigned short *) &work_out[16]; - for (component=0;component<5;component++) { - for (num_bit=0;num_bit<16;num_bit++) { - unsigned short valeur; - - valeur = *tmp_p++; - - if (valeur == 0xffff) { - continue; - } - - switch(component) { - case 0: - VDI_redmask |= 1<< valeur; - break; - case 1: - VDI_greenmask |= 1<< valeur; - break; - case 2: - VDI_bluemask |= 1<< valeur; - break; - case 3: - VDI_alphamask |= 1<< valeur; - break; - } - } - } - } - - /* Remove lower green bits for Intel endian screen */ - if ((VDI_greenmask == ((7<<13)|3)) || (VDI_greenmask == ((7<<13)|7))) { - VDI_greenmask &= ~(7<<13); - } - break; - case VDI_CLUT_NONE: - break; - } + unsigned long EdDI_version; + unsigned long cookie_EdDI; + Uint32 num_colours; + Uint16 clut_type, num_bits; + + /* Read EdDI informations */ + if (Getcookie(C_EdDI, &cookie_EdDI) == C_NOTFOUND) { + return; + } + + EdDI_version = Atari_get_EdDI_version((void *) cookie_EdDI); + + vq_scrninfo(VDI_handle, work_out); + + VDI_format = work_out[0]; + clut_type = work_out[1]; + num_bits = work_out[2]; + num_colours = *((Uint32 *) & work_out[3]); + + /* With EdDI>=1.1, we can have screen pitch, address and format + * so we can directly write to screen without using vro_cpyfm + */ + if (EdDI_version >= EDDI_11) { + VDI_pitch = work_out[5]; + VDI_screen = (void *) *((unsigned long *) &work_out[6]); + } + + switch (clut_type) { + case VDI_CLUT_HARDWARE: + { + int i; + Uint16 *tmp_p; + + tmp_p = (Uint16 *) & work_out[16]; + + for (i = 0; i < 256; i++) { + vdi_index[*tmp_p++] = i; + } + } + break; + case VDI_CLUT_SOFTWARE: + { + int component; /* red, green, blue, alpha, overlay */ + int num_bit; + unsigned short *tmp_p; + + /* We can build masks with info here */ + tmp_p = (unsigned short *) &work_out[16]; + for (component = 0; component < 5; component++) { + for (num_bit = 0; num_bit < 16; num_bit++) { + unsigned short valeur; + + valeur = *tmp_p++; + + if (valeur == 0xffff) { + continue; + } + + switch (component) { + case 0: + VDI_redmask |= 1 << valeur; + break; + case 1: + VDI_greenmask |= 1 << valeur; + break; + case 2: + VDI_bluemask |= 1 << valeur; + break; + case 3: + VDI_alphamask |= 1 << valeur; + break; + } + } + } + } + + /* Remove lower green bits for Intel endian screen */ + if ((VDI_greenmask == ((7 << 13) | 3)) + || (VDI_greenmask == ((7 << 13) | 7))) { + VDI_greenmask &= ~(7 << 13); + } + break; + case VDI_CLUT_NONE: + break; + } } -int GEM_VideoInit(_THIS, SDL_PixelFormat *vformat) +int +GEM_VideoInit(_THIS, SDL_PixelFormat * vformat) { - int i, menubar_size; - short work_in[12], work_out[272], dummy; - - /* Open AES (Application Environment Services) */ - if (appl_init() == -1) { - fprintf(stderr,"Can not open AES\n"); - return 1; - } - - /* Read version and features */ - GEM_version = aes_global[0]; - if (GEM_version >= 0x0410) { - short ap_gout[4], errorcode; - - GEM_wfeatures=0; - errorcode=appl_getinfo(AES_WINDOW, &ap_gout[0], &ap_gout[1], &ap_gout[2], &ap_gout[3]); - - if (errorcode==0) { - GEM_wfeatures=ap_gout[0]; - } - } - - /* Ask VDI physical workstation handle opened by AES */ - VDI_handle = graf_handle(&dummy, &dummy, &dummy, &dummy); - if (VDI_handle<1) { - fprintf(stderr,"Wrong VDI handle %d returned by AES\n",VDI_handle); - return 1; - } - - /* Open virtual VDI workstation */ - work_in[0]=Getrez()+2; - for(i = 1; i < 10; i++) - work_in[i] = 1; - work_in[10] = 2; - - v_opnvwk(work_in, &VDI_handle, work_out); - if (VDI_handle == 0) { - fprintf(stderr,"Can not open VDI virtual workstation\n"); - return 1; - } - - /* Read fullscreen size */ - VDI_w = work_out[0] + 1; - VDI_h = work_out[1] + 1; - - /* Read desktop size and position */ - if (!wind_get(DESKTOP_HANDLE, WF_WORKXYWH, &GEM_desk_x, &GEM_desk_y, &GEM_desk_w, &GEM_desk_h)) { - fprintf(stderr,"Can not read desktop properties\n"); - return 1; - } - - /* Read bit depth */ - vq_extnd(VDI_handle, 1, work_out); - VDI_bpp = work_out[4]; - VDI_oldnumcolors=0; - - switch(VDI_bpp) { - case 8: - VDI_pixelsize=1; - break; - case 15: - case 16: - VDI_pixelsize=2; - break; - case 24: - VDI_pixelsize=3; - break; - case 32: - VDI_pixelsize=4; - break; - default: - fprintf(stderr,"%d bits colour depth not supported\n",VDI_bpp); - return 1; - } - - /* Setup hardware -> VDI palette mapping */ - for(i = 16; i < 255; i++) { - vdi_index[i] = i; - } - vdi_index[255] = 1; - - /* Save current palette */ - if (VDI_bpp>8) { - VDI_oldnumcolors=1<<8; - } else { - VDI_oldnumcolors=1<= 0x0410) { + short ap_gout[4], errorcode; + + GEM_wfeatures = 0; + errorcode = + appl_getinfo(AES_WINDOW, &ap_gout[0], &ap_gout[1], &ap_gout[2], + &ap_gout[3]); + + if (errorcode == 0) { + GEM_wfeatures = ap_gout[0]; + } + } + + /* Ask VDI physical workstation handle opened by AES */ + VDI_handle = graf_handle(&dummy, &dummy, &dummy, &dummy); + if (VDI_handle < 1) { + fprintf(stderr, "Wrong VDI handle %d returned by AES\n", VDI_handle); + return 1; + } + + /* Open virtual VDI workstation */ + work_in[0] = Getrez() + 2; + for (i = 1; i < 10; i++) + work_in[i] = 1; + work_in[10] = 2; + + v_opnvwk(work_in, &VDI_handle, work_out); + if (VDI_handle == 0) { + fprintf(stderr, "Can not open VDI virtual workstation\n"); + return 1; + } + + /* Read fullscreen size */ + VDI_w = work_out[0] + 1; + VDI_h = work_out[1] + 1; + + /* Read desktop size and position */ + if (!wind_get + (DESKTOP_HANDLE, WF_WORKXYWH, &GEM_desk_x, &GEM_desk_y, &GEM_desk_w, + &GEM_desk_h)) { + fprintf(stderr, "Can not read desktop properties\n"); + return 1; + } + + /* Read bit depth */ + vq_extnd(VDI_handle, 1, work_out); + VDI_bpp = work_out[4]; + VDI_oldnumcolors = 0; + + switch (VDI_bpp) { + case 8: + VDI_pixelsize = 1; + break; + case 15: + case 16: + VDI_pixelsize = 2; + break; + case 24: + VDI_pixelsize = 3; + break; + case 32: + VDI_pixelsize = 4; + break; + default: + fprintf(stderr, "%d bits colour depth not supported\n", VDI_bpp); + return 1; + } + + /* Setup hardware -> VDI palette mapping */ + for (i = 16; i < 255; i++) { + vdi_index[i] = i; + } + vdi_index[255] = 1; + + /* Save current palette */ + if (VDI_bpp > 8) { + VDI_oldnumcolors = 1 << 8; + } else { + VDI_oldnumcolors = 1 << VDI_bpp; + } + + for (i = 0; i < VDI_oldnumcolors; i++) { + short rgb[3]; + + vq_color(VDI_handle, i, 0, rgb); + + VDI_oldpalette[i][0] = rgb[0]; + VDI_oldpalette[i][1] = rgb[1]; + VDI_oldpalette[i][2] = rgb[2]; + } + VDI_setpalette = GEM_SetNewPalette; + SDL_memcpy(VDI_curpalette, VDI_oldpalette, sizeof(VDI_curpalette)); + + /* Setup screen info */ + GEM_title_name = empty_name; + GEM_icon_name = empty_name; + + GEM_handle = -1; + GEM_locked = SDL_FALSE; + GEM_win_fulled = SDL_FALSE; + GEM_fullscreen = SDL_FALSE; + GEM_lock_redraw = SDL_TRUE; /* Prevent redraw till buffers are setup */ + + VDI_screen = NULL; + VDI_pitch = VDI_w * VDI_pixelsize; + VDI_format = ((VDI_bpp <= 8) ? VDI_FORMAT_INTER : VDI_FORMAT_PACK); + VDI_redmask = VDI_greenmask = VDI_bluemask = VDI_alphamask = 0; + VDI_ReadExtInfo(this, work_out); #ifdef DEBUG_VIDEO_GEM - printf("sdl:video:gem: screen: address=0x%08x, pitch=%d\n", VDI_screen, VDI_pitch); - printf("sdl:video:gem: format=%d\n", VDI_format); - printf("sdl:video:gem: masks: 0x%08x, 0x%08x, 0x%08x, 0x%08x\n", - VDI_alphamask, VDI_redmask, VDI_greenmask, VDI_bluemask - ); + printf("sdl:video:gem: screen: address=0x%08x, pitch=%d\n", VDI_screen, + VDI_pitch); + printf("sdl:video:gem: format=%d\n", VDI_format); + printf("sdl:video:gem: masks: 0x%08x, 0x%08x, 0x%08x, 0x%08x\n", + VDI_alphamask, VDI_redmask, VDI_greenmask, VDI_bluemask); #endif - /* Setup destination mfdb */ - VDI_dst_mfdb.fd_addr = NULL; + /* Setup destination mfdb */ + VDI_dst_mfdb.fd_addr = NULL; - /* Determine the current screen size */ - this->info.current_w = VDI_w; - this->info.current_h = VDI_h; + /* Determine the current screen size */ + this->info.current_w = VDI_w; + this->info.current_h = VDI_h; - /* Determine the screen depth */ - /* we change this during the SDL_SetVideoMode implementation... */ - vformat->BitsPerPixel = VDI_bpp; + /* Determine the screen depth */ + /* we change this during the SDL_SetVideoMode implementation... */ + vformat->BitsPerPixel = VDI_bpp; - /* Set mouse cursor to arrow */ - graf_mouse(ARROW, NULL); - GEM_cursor = NULL; + /* Set mouse cursor to arrow */ + graf_mouse(ARROW, NULL); - /* Init chunky to planar routine */ - SDL_Atari_C2pConvert = SDL_Atari_C2pConvert8; + /* Init chunky to planar routine */ + SDL_Atari_C2pConvert = SDL_Atari_C2pConvert8; - /* Setup VDI fill functions */ - vsf_color(VDI_handle,0); - vsf_interior(VDI_handle,1); - vsf_perimeter(VDI_handle,0); + /* Setup VDI fill functions */ + vsf_color(VDI_handle, 0); + vsf_interior(VDI_handle, 1); + vsf_perimeter(VDI_handle, 0); - /* Menu bar save buffer */ - menubar_size = GEM_desk_w * GEM_desk_y * VDI_pixelsize; - GEM_menubar=Atari_SysMalloc(menubar_size,MX_PREFTTRAM); + /* Menu bar save buffer */ + menubar_size = GEM_desk_w * GEM_desk_y * VDI_pixelsize; + GEM_menubar = Atari_SysMalloc(menubar_size, MX_PREFTTRAM); - /* Fill video modes list */ - SDL_modelist[0] = SDL_malloc(sizeof(SDL_Rect)); - SDL_modelist[0]->x = 0; - SDL_modelist[0]->y = 0; - SDL_modelist[0]->w = VDI_w; - SDL_modelist[0]->h = VDI_h; + /* Fill video modes list */ + SDL_modelist[0] = SDL_malloc(sizeof(SDL_Rect)); + SDL_modelist[0]->x = 0; + SDL_modelist[0]->y = 0; + SDL_modelist[0]->w = VDI_w; + SDL_modelist[0]->h = VDI_h; - SDL_modelist[1] = NULL; + SDL_modelist[1] = NULL; #if SDL_VIDEO_OPENGL - SDL_AtariGL_InitPointers(this); + SDL_AtariGL_InitPointers(this); #endif - /* We're done! */ - return(0); + /* We're done! */ + return (0); } -SDL_Rect **GEM_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags) +SDL_Rect ** +GEM_ListModes(_THIS, SDL_PixelFormat * format, Uint32 flags) { - if (format->BitsPerPixel != VDI_bpp) { - return ((SDL_Rect **)NULL); - } + if (format->BitsPerPixel != VDI_bpp) { + return ((SDL_Rect **) NULL); + } - if (flags & SDL_FULLSCREEN) { - return (SDL_modelist); - } + if (flags & SDL_FULLSCREEN) { + return (SDL_modelist); + } - return((SDL_Rect **)-1); + return ((SDL_Rect **) - 1); } -static void GEM_FreeBuffers(_THIS) +static void +GEM_FreeBuffers(_THIS) { - /* Release buffer */ - if ( GEM_buffer2 ) { - Mfree( GEM_buffer2 ); - GEM_buffer2=NULL; - } - - if ( GEM_buffer1 ) { - Mfree( GEM_buffer1 ); - GEM_buffer1=NULL; - } + /* Release buffer */ + if (GEM_buffer2) { + Mfree(GEM_buffer2); + GEM_buffer2 = NULL; + } + + if (GEM_buffer1) { + Mfree(GEM_buffer1); + GEM_buffer1 = NULL; + } } -static void GEM_ClearRect(_THIS, short *rect) +static void +GEM_ClearRect(_THIS, short *rect) { - short oldrgb[3], rgb[3]={0,0,0}; + short oldrgb[3], rgb[3] = { 0, 0, 0 }; - vq_color(VDI_handle, vdi_index[0], 0, oldrgb); - vs_color(VDI_handle, vdi_index[0], rgb); + vq_color(VDI_handle, vdi_index[0], 0, oldrgb); + vs_color(VDI_handle, vdi_index[0], rgb); - vsf_color(VDI_handle,0); - vsf_interior(VDI_handle,1); - vsf_perimeter(VDI_handle,0); - v_bar(VDI_handle, rect); + vsf_color(VDI_handle, 0); + vsf_interior(VDI_handle, 1); + vsf_perimeter(VDI_handle, 0); + v_bar(VDI_handle, rect); - vs_color(VDI_handle, vdi_index[0], oldrgb); + vs_color(VDI_handle, vdi_index[0], oldrgb); } -static void GEM_ClearScreen(_THIS) +static void +GEM_ClearScreen(_THIS) { - short pxy[4]; + short pxy[4]; - v_hide_c(VDI_handle); + v_hide_c(VDI_handle); - pxy[0] = pxy[1] = 0; - pxy[2] = VDI_w - 1; - pxy[3] = VDI_h - 1; - GEM_ClearRect(this, pxy); + pxy[0] = pxy[1] = 0; + pxy[2] = VDI_w - 1; + pxy[3] = VDI_h - 1; + GEM_ClearRect(this, pxy); - v_show_c(VDI_handle, 1); + v_show_c(VDI_handle, 1); } -static void GEM_SetNewPalette(_THIS, Uint16 newpal[256][3]) +static void +GEM_SetNewPalette(_THIS, Uint16 newpal[256][3]) { - int i; - short rgb[3]; + int i; + short rgb[3]; - if (VDI_oldnumcolors==0) - return; + if (VDI_oldnumcolors == 0) + return; - for(i = 0; i < VDI_oldnumcolors; i++) { - rgb[0] = newpal[i][0]; - rgb[1] = newpal[i][1]; - rgb[2] = newpal[i][2]; + for (i = 0; i < VDI_oldnumcolors; i++) { + rgb[0] = newpal[i][0]; + rgb[1] = newpal[i][1]; + rgb[2] = newpal[i][2]; - vs_color(VDI_handle, i, rgb); - } + vs_color(VDI_handle, i, rgb); + } } -static void GEM_LockScreen(_THIS) +static void +GEM_LockScreen(_THIS) { - if (!GEM_locked) { - /* Lock AES */ - wind_update(BEG_UPDATE); - wind_update(BEG_MCTRL); - /* Reserve memory space, used to be sure of compatibility */ - form_dial( FMD_START, 0,0,0,0, 0,0,VDI_w,VDI_h); - - /* Save menu bar */ - if (GEM_menubar) { - MFDB mfdb_src; - short blitcoords[8]; - - mfdb_src.fd_addr=GEM_menubar; - mfdb_src.fd_w=GEM_desk_w; - mfdb_src.fd_h=GEM_desk_y; - mfdb_src.fd_wdwidth=GEM_desk_w>>4; - mfdb_src.fd_nplanes=VDI_bpp; - mfdb_src.fd_stand= - mfdb_src.fd_r1= - mfdb_src.fd_r2= - mfdb_src.fd_r3= 0; - - blitcoords[0] = blitcoords[4] = 0; - blitcoords[1] = blitcoords[5] = 0; - blitcoords[2] = blitcoords[6] = GEM_desk_w-1; - blitcoords[3] = blitcoords[7] = GEM_desk_y-1; - - vro_cpyfm(VDI_handle, S_ONLY, blitcoords, &VDI_dst_mfdb, &mfdb_src); - } - - GEM_locked=SDL_TRUE; - } + if (!GEM_locked) { + /* Lock AES */ + wind_update(BEG_UPDATE); + wind_update(BEG_MCTRL); + /* Reserve memory space, used to be sure of compatibility */ + form_dial(FMD_START, 0, 0, 0, 0, 0, 0, VDI_w, VDI_h); + + /* Save menu bar */ + if (GEM_menubar) { + MFDB mfdb_src; + short blitcoords[8]; + + mfdb_src.fd_addr = GEM_menubar; + mfdb_src.fd_w = GEM_desk_w; + mfdb_src.fd_h = GEM_desk_y; + mfdb_src.fd_wdwidth = GEM_desk_w >> 4; + mfdb_src.fd_nplanes = VDI_bpp; + mfdb_src.fd_stand = + mfdb_src.fd_r1 = mfdb_src.fd_r2 = mfdb_src.fd_r3 = 0; + + blitcoords[0] = blitcoords[4] = 0; + blitcoords[1] = blitcoords[5] = 0; + blitcoords[2] = blitcoords[6] = GEM_desk_w - 1; + blitcoords[3] = blitcoords[7] = GEM_desk_y - 1; + + vro_cpyfm(VDI_handle, S_ONLY, blitcoords, &VDI_dst_mfdb, + &mfdb_src); + } + + GEM_locked = SDL_TRUE; + } } -static void GEM_UnlockScreen(_THIS) +static void +GEM_UnlockScreen(_THIS) { - if (GEM_locked) { - /* Restore menu bar */ - if (GEM_menubar) { - MFDB mfdb_src; - short blitcoords[8]; - - mfdb_src.fd_addr=GEM_menubar; - mfdb_src.fd_w=GEM_desk_w; - mfdb_src.fd_h=GEM_desk_y; - mfdb_src.fd_wdwidth=GEM_desk_w>>4; - mfdb_src.fd_nplanes=VDI_bpp; - mfdb_src.fd_stand= - mfdb_src.fd_r1= - mfdb_src.fd_r2= - mfdb_src.fd_r3= 0; - - blitcoords[0] = blitcoords[4] = 0; - blitcoords[1] = blitcoords[5] = 0; - blitcoords[2] = blitcoords[6] = GEM_desk_w-1; - blitcoords[3] = blitcoords[7] = GEM_desk_y-1; - - vro_cpyfm(VDI_handle, S_ONLY, blitcoords, &mfdb_src, &VDI_dst_mfdb); - } - - /* Restore screen memory, and send REDRAW to all apps */ - form_dial( FMD_FINISH, 0,0,0,0, 0,0,VDI_w,VDI_h); - /* Unlock AES */ - wind_update(END_MCTRL); - wind_update(END_UPDATE); - - GEM_locked=SDL_FALSE; - } + if (GEM_locked) { + /* Restore menu bar */ + if (GEM_menubar) { + MFDB mfdb_src; + short blitcoords[8]; + + mfdb_src.fd_addr = GEM_menubar; + mfdb_src.fd_w = GEM_desk_w; + mfdb_src.fd_h = GEM_desk_y; + mfdb_src.fd_wdwidth = GEM_desk_w >> 4; + mfdb_src.fd_nplanes = VDI_bpp; + mfdb_src.fd_stand = + mfdb_src.fd_r1 = mfdb_src.fd_r2 = mfdb_src.fd_r3 = 0; + + blitcoords[0] = blitcoords[4] = 0; + blitcoords[1] = blitcoords[5] = 0; + blitcoords[2] = blitcoords[6] = GEM_desk_w - 1; + blitcoords[3] = blitcoords[7] = GEM_desk_y - 1; + + vro_cpyfm(VDI_handle, S_ONLY, blitcoords, &mfdb_src, + &VDI_dst_mfdb); + } + + /* Restore screen memory, and send REDRAW to all apps */ + form_dial(FMD_FINISH, 0, 0, 0, 0, 0, 0, VDI_w, VDI_h); + /* Unlock AES */ + wind_update(END_MCTRL); + wind_update(END_UPDATE); + + GEM_locked = SDL_FALSE; + } } -SDL_Surface *GEM_SetVideoMode(_THIS, SDL_Surface *current, - int width, int height, int bpp, Uint32 flags) +SDL_Surface * +GEM_SetVideoMode(_THIS, SDL_Surface * current, + int width, int height, int bpp, Uint32 flags) { - int maxwidth, maxheight; - Uint32 modeflags, screensize; - SDL_bool use_shadow1, use_shadow2; - - /*--- Verify if asked mode can be used ---*/ - if (flags & SDL_FULLSCREEN) { - maxwidth=VDI_w; - maxheight=VDI_h; - } else { - /* Windowed mode */ - maxwidth=GEM_desk_w; - maxheight=GEM_desk_h; - } - - /* width must be multiple of 16, for vro_cpyfm() and c2p_convert() */ - if ((width & 15) != 0) { - width = (width | 15) +1; - } - - if ((maxwidth < width) || (maxheight < height) || (VDI_bpp != bpp)) { - SDL_SetError("Couldn't find requested mode in list"); - return(NULL); - } - - /*--- Allocate the new pixel format for the screen ---*/ - if ( ! SDL_ReallocFormat(current, VDI_bpp, VDI_redmask, VDI_greenmask, VDI_bluemask, VDI_alphamask) ) { - SDL_SetError("Couldn't allocate new pixel format for requested mode"); - return(NULL); - } - - screensize = width * height * VDI_pixelsize; + int maxwidth, maxheight; + Uint32 modeflags, screensize; + SDL_bool use_shadow1, use_shadow2; + + /*--- Verify if asked mode can be used ---*/ + if (flags & SDL_FULLSCREEN) { + maxwidth = VDI_w; + maxheight = VDI_h; + } else { + /* Windowed mode */ + maxwidth = GEM_desk_w; + maxheight = GEM_desk_h; + } + + /* width must be multiple of 16, for vro_cpyfm() and c2p_convert() */ + if ((width & 15) != 0) { + width = (width | 15) + 1; + } + + if ((maxwidth < width) || (maxheight < height) || (VDI_bpp != bpp)) { + SDL_SetError("Couldn't find requested mode in list"); + return (NULL); + } + + /*--- Allocate the new pixel format for the screen ---*/ + if (!SDL_ReallocFormat + (current, VDI_bpp, VDI_redmask, VDI_greenmask, VDI_bluemask, + VDI_alphamask)) { + SDL_SetError("Couldn't allocate new pixel format for requested mode"); + return (NULL); + } + + screensize = width * height * VDI_pixelsize; #ifdef DEBUG_VIDEO_GEM - printf("sdl:video:gem: setvideomode(): %dx%dx%d = %d\n", width, height, bpp, screensize); + printf("sdl:video:gem: setvideomode(): %dx%dx%d = %d\n", width, height, + bpp, screensize); #endif - /*--- Allocate shadow buffers if needed, and conversion operations ---*/ - GEM_FreeBuffers(this); - - GEM_bufops=0; - use_shadow1=use_shadow2=SDL_FALSE; - if (VDI_screen && (flags & SDL_FULLSCREEN)) { - if (VDI_format==VDI_FORMAT_INTER) { - use_shadow1=SDL_TRUE; - GEM_bufops = B2S_C2P_1TOS; - } - } else { - use_shadow1=SDL_TRUE; - if (VDI_format==VDI_FORMAT_PACK) { - GEM_bufops = B2S_VROCPYFM_1TOS; - } else { - use_shadow2=SDL_TRUE; - GEM_bufops = B2S_C2P_1TO2|B2S_VROCPYFM_2TOS; - } - } - - if (use_shadow1) { - GEM_buffer1 = Atari_SysMalloc(screensize, MX_PREFTTRAM); - if (GEM_buffer1==NULL) { - SDL_SetError("Can not allocate %d KB for frame buffer", screensize>>10); - return NULL; - } - SDL_memset(GEM_buffer1, 0, screensize); + /*--- Allocate shadow buffers if needed, and conversion operations ---*/ + GEM_FreeBuffers(this); + + GEM_bufops = 0; + use_shadow1 = use_shadow2 = SDL_FALSE; + if (VDI_screen && (flags & SDL_FULLSCREEN)) { + if (VDI_format == VDI_FORMAT_INTER) { + use_shadow1 = SDL_TRUE; + GEM_bufops = B2S_C2P_1TOS; + } + } else { + use_shadow1 = SDL_TRUE; + if (VDI_format == VDI_FORMAT_PACK) { + GEM_bufops = B2S_VROCPYFM_1TOS; + } else { + use_shadow2 = SDL_TRUE; + GEM_bufops = B2S_C2P_1TO2 | B2S_VROCPYFM_2TOS; + } + } + + if (use_shadow1) { + GEM_buffer1 = Atari_SysMalloc(screensize, MX_PREFTTRAM); + if (GEM_buffer1 == NULL) { + SDL_SetError("Can not allocate %d KB for frame buffer", + screensize >> 10); + return NULL; + } + SDL_memset(GEM_buffer1, 0, screensize); #ifdef DEBUG_VIDEO_GEM - printf("sdl:video:gem: setvideomode(): allocated buffer 1\n"); + printf("sdl:video:gem: setvideomode(): allocated buffer 1\n"); #endif - } - - if (use_shadow2) { - GEM_buffer2 = Atari_SysMalloc(screensize, MX_PREFTTRAM); - if (GEM_buffer2==NULL) { - SDL_SetError("Can not allocate %d KB for shadow buffer", screensize>>10); - return NULL; - } - SDL_memset(GEM_buffer2, 0, screensize); + } + + if (use_shadow2) { + GEM_buffer2 = Atari_SysMalloc(screensize, MX_PREFTTRAM); + if (GEM_buffer2 == NULL) { + SDL_SetError("Can not allocate %d KB for shadow buffer", + screensize >> 10); + return NULL; + } + SDL_memset(GEM_buffer2, 0, screensize); #ifdef DEBUG_VIDEO_GEM - printf("sdl:video:gem: setvideomode(): allocated buffer 2\n"); + printf("sdl:video:gem: setvideomode(): allocated buffer 2\n"); #endif - } - - /*--- Initialize screen ---*/ - modeflags = SDL_PREALLOC; - if (VDI_bpp == 8) { - modeflags |= SDL_HWPALETTE; - } - - if (flags & SDL_FULLSCREEN) { - GEM_LockScreen(this); - - GEM_ClearScreen(this); - - modeflags |= SDL_FULLSCREEN; - if (VDI_screen && (VDI_format==VDI_FORMAT_PACK) && !use_shadow1) { - modeflags |= SDL_HWSURFACE; - } else { - modeflags |= SDL_SWSURFACE; - } - - GEM_fullscreen = SDL_TRUE; - } else { - int old_win_type; - short x2,y2,w2,h2; - - GEM_UnlockScreen(this); - - /* Set window gadgets */ - old_win_type = GEM_win_type; - if (!(flags & SDL_NOFRAME)) { - GEM_win_type=NAME|MOVER|CLOSER|SMALLER; - if (flags & SDL_RESIZABLE) { - GEM_win_type |= FULLER|SIZER; - modeflags |= SDL_RESIZABLE; - } - } else { - GEM_win_type=0; - modeflags |= SDL_NOFRAME; - } - modeflags |= SDL_SWSURFACE; - - /* Recreate window ? only for different widget or non-created window */ - if ((old_win_type != GEM_win_type) || (GEM_handle < 0)) { - /* Calculate window size */ - if (!wind_calc(WC_BORDER, GEM_win_type, 0,0,width,height, &x2,&y2,&w2,&h2)) { - GEM_FreeBuffers(this); - SDL_SetError("Can not calculate window attributes"); - return NULL; - } - - /* Center window */ - x2 = GEM_desk_x+((GEM_desk_w-w2)>>1); - y2 = GEM_desk_y+((GEM_desk_h-h2)>>1); - - /* Destroy existing window */ - if (GEM_handle >= 0) { - wind_close(GEM_handle); - wind_delete(GEM_handle); - } - - /* Create window */ - GEM_handle=wind_create(GEM_win_type, x2,y2,w2,h2); - if (GEM_handle<0) { - GEM_FreeBuffers(this); - SDL_SetError("Can not create window"); - return NULL; - } - + } + + /*--- Initialize screen ---*/ + modeflags = SDL_PREALLOC; + if (VDI_bpp == 8) { + modeflags |= SDL_HWPALETTE; + } + + if (flags & SDL_FULLSCREEN) { + GEM_LockScreen(this); + + GEM_ClearScreen(this); + + modeflags |= SDL_FULLSCREEN; + if (VDI_screen && (VDI_format == VDI_FORMAT_PACK) && !use_shadow1) { + modeflags |= SDL_HWSURFACE; + } else { + modeflags |= SDL_SWSURFACE; + } + + GEM_fullscreen = SDL_TRUE; + } else { + int old_win_type; + short x2, y2, w2, h2; + + GEM_UnlockScreen(this); + + /* Set window gadgets */ + old_win_type = GEM_win_type; + if (!(flags & SDL_NOFRAME)) { + GEM_win_type = NAME | MOVER | CLOSER | SMALLER; + if (flags & SDL_RESIZABLE) { + GEM_win_type |= FULLER | SIZER; + modeflags |= SDL_RESIZABLE; + } + } else { + GEM_win_type = 0; + modeflags |= SDL_NOFRAME; + } + modeflags |= SDL_SWSURFACE; + + /* Recreate window ? only for different widget or non-created window */ + if ((old_win_type != GEM_win_type) || (GEM_handle < 0)) { + /* Calculate window size */ + if (!wind_calc + (WC_BORDER, GEM_win_type, 0, 0, width, height, &x2, &y2, + &w2, &h2)) { + GEM_FreeBuffers(this); + SDL_SetError("Can not calculate window attributes"); + return NULL; + } + + /* Center window */ + x2 = GEM_desk_x + ((GEM_desk_w - w2) >> 1); + y2 = GEM_desk_y + ((GEM_desk_h - h2) >> 1); + + /* Destroy existing window */ + if (GEM_handle >= 0) { + wind_close(GEM_handle); + wind_delete(GEM_handle); + } + + /* Create window */ + GEM_handle = wind_create(GEM_win_type, x2, y2, w2, h2); + if (GEM_handle < 0) { + GEM_FreeBuffers(this); + SDL_SetError("Can not create window"); + return NULL; + } #ifdef DEBUG_VIDEO_GEM - printf("sdl:video:gem: handle=%d\n", GEM_handle); + printf("sdl:video:gem: handle=%d\n", GEM_handle); #endif - /* Setup window name */ - wind_set(GEM_handle,WF_NAME,(short)(((unsigned long)GEM_title_name)>>16),(short)(((unsigned long)GEM_title_name) & 0xffff),0,0); - GEM_refresh_name = SDL_FALSE; - - /* Open the window */ - wind_open(GEM_handle,x2,y2,w2,h2); - } else { - /* Resize window if needed, to fit asked video mode */ - if (modeflags & SDL_RESIZABLE) { - wind_get (GEM_handle, WF_WORKXYWH, &x2,&y2,&w2,&h2); - if ((w2&15)!=0) { - w2=(w2|15)+1; - } - if ((w2!=width) || (h2!=height)) { - if (wind_calc(WC_BORDER, GEM_win_type, x2,y2,width,height, &x2,&y2,&w2,&h2)) { - wind_set (GEM_handle, WF_CURRXYWH, x2,y2,w2,h2); - } - } - } - } - - GEM_fullscreen = SDL_FALSE; - } - - /* Set up the new mode framebuffer */ - current->w = width; - current->h = height; - if (use_shadow1) { - current->pixels = GEM_buffer1; - current->pitch = width * VDI_pixelsize; - } else { - current->pixels = VDI_screen; - current->pitch = VDI_pitch; - } + /* Setup window name */ + wind_set(GEM_handle, WF_NAME, + (short) (((unsigned long) GEM_title_name) >> 16), + (short) (((unsigned long) GEM_title_name) & 0xffff), + 0, 0); + GEM_refresh_name = SDL_FALSE; + + /* Open the window */ + wind_open(GEM_handle, x2, y2, w2, h2); + } else { + /* Resize window if needed, to fit asked video mode */ + if (modeflags & SDL_RESIZABLE) { + wind_get(GEM_handle, WF_WORKXYWH, &x2, &y2, &w2, &h2); + if ((w2 & 15) != 0) { + w2 = (w2 | 15) + 1; + } + if ((w2 != width) || (h2 != height)) { + if (wind_calc + (WC_BORDER, GEM_win_type, x2, y2, width, + height, &x2, &y2, &w2, &h2)) { + wind_set(GEM_handle, WF_CURRXYWH, x2, y2, w2, h2); + } + } + } + } + + GEM_fullscreen = SDL_FALSE; + } + + /* Set up the new mode framebuffer */ + current->w = width; + current->h = height; + if (use_shadow1) { + current->pixels = GEM_buffer1; + current->pitch = width * VDI_pixelsize; + } else { + current->pixels = VDI_screen; + current->pitch = VDI_pitch; + } #if SDL_VIDEO_OPENGL - if (flags & SDL_OPENGL) { - if (!SDL_AtariGL_Init(this, current)) { - GEM_FreeBuffers(this); - SDL_SetError("Can not create OpenGL context"); - return NULL; - } - - modeflags |= SDL_OPENGL; - } + if (flags & SDL_INTERNALOPENGL) { + if (!SDL_AtariGL_Init(this, current)) { + GEM_FreeBuffers(this); + SDL_SetError("Can not create OpenGL context"); + return NULL; + } + + modeflags |= SDL_INTERNALOPENGL; + } #endif - current->flags = modeflags; + current->flags = modeflags; #ifdef DEBUG_VIDEO_GEM - printf("sdl:video:gem: surface: %dx%d\n", current->w, current->h); + printf("sdl:video:gem: surface: %dx%d\n", current->w, current->h); #endif - this->UpdateRects = GEM_UpdateRects; - GEM_lock_redraw = SDL_FALSE; /* Enable redraw */ + this->UpdateRects = GEM_UpdateRects; + GEM_lock_redraw = SDL_FALSE; /* Enable redraw */ - /* We're done */ - return(current); + /* We're done */ + return (current); } -static int GEM_AllocHWSurface(_THIS, SDL_Surface *surface) +static int +GEM_AllocHWSurface(_THIS, SDL_Surface * surface) { - return -1; + return -1; } -static void GEM_FreeHWSurface(_THIS, SDL_Surface *surface) +static void +GEM_FreeHWSurface(_THIS, SDL_Surface * surface) { - return; + return; } -static int GEM_LockHWSurface(_THIS, SDL_Surface *surface) +static int +GEM_LockHWSurface(_THIS, SDL_Surface * surface) { - return(0); + return (0); } -static void GEM_UnlockHWSurface(_THIS, SDL_Surface *surface) +static void +GEM_UnlockHWSurface(_THIS, SDL_Surface * surface) { - return; + return; } -static void GEM_UpdateRectsFullscreen(_THIS, int numrects, SDL_Rect *rects) +static void +GEM_UpdateRectsFullscreen(_THIS, int numrects, SDL_Rect * rects) { - SDL_Surface *surface; - int i, surf_width; - - surface = this->screen; - /* Need to be a multiple of 16 pixels */ - surf_width=surface->w; - if ((surf_width & 15) != 0) { - surf_width = (surf_width | 15) + 1; - } - - if (GEM_bufops & (B2S_C2P_1TO2|B2S_C2P_1TOS)) { - void *destscr; - int destpitch; - - if (GEM_bufops & B2S_C2P_1TOS) { - destscr = VDI_screen; - destpitch = VDI_pitch; - } else { - destscr = GEM_buffer2; - destpitch = surface->pitch; - } - - for (i=0;ipixels; - source += surface->pitch * rects[i].y; - source += x1; - - destination = destscr; - destination += destpitch * rects[i].y; - destination += x1; - - SDL_Atari_C2pConvert( - source, destination, - x2-x1, rects[i].h, - SDL_FALSE, - surface->pitch, destpitch - ); - } - } - - if (GEM_bufops & (B2S_VROCPYFM_1TOS|B2S_VROCPYFM_2TOS)) { - MFDB mfdb_src; - short blitcoords[8]; - - mfdb_src.fd_addr=surface->pixels; - mfdb_src.fd_w=surf_width; - mfdb_src.fd_h=surface->h; - mfdb_src.fd_wdwidth= (surface->pitch/VDI_pixelsize) >> 4; - mfdb_src.fd_nplanes=surface->format->BitsPerPixel; - mfdb_src.fd_stand= - mfdb_src.fd_r1= - mfdb_src.fd_r2= - mfdb_src.fd_r3= 0; - if (GEM_bufops & B2S_VROCPYFM_2TOS) { - mfdb_src.fd_addr=GEM_buffer2; - } - - for ( i=0; iscreen; + /* Need to be a multiple of 16 pixels */ + surf_width = surface->w; + if ((surf_width & 15) != 0) { + surf_width = (surf_width | 15) + 1; + } + + if (GEM_bufops & (B2S_C2P_1TO2 | B2S_C2P_1TOS)) { + void *destscr; + int destpitch; + + if (GEM_bufops & B2S_C2P_1TOS) { + destscr = VDI_screen; + destpitch = VDI_pitch; + } else { + destscr = GEM_buffer2; + destpitch = surface->pitch; + } + + for (i = 0; i < numrects; i++) { + void *source, *destination; + int x1, x2; + + x1 = rects[i].x & ~15; + x2 = rects[i].x + rects[i].w; + if (x2 & 15) { + x2 = (x2 | 15) + 1; + } + + source = surface->pixels; + source += surface->pitch * rects[i].y; + source += x1; + + destination = destscr; + destination += destpitch * rects[i].y; + destination += x1; + + SDL_Atari_C2pConvert(source, destination, + x2 - x1, rects[i].h, + SDL_FALSE, surface->pitch, destpitch); + } + } + + if (GEM_bufops & (B2S_VROCPYFM_1TOS | B2S_VROCPYFM_2TOS)) { + MFDB mfdb_src; + short blitcoords[8]; + + mfdb_src.fd_addr = surface->pixels; + mfdb_src.fd_w = surf_width; + mfdb_src.fd_h = surface->h; + mfdb_src.fd_wdwidth = (surface->pitch / VDI_pixelsize) >> 4; + mfdb_src.fd_nplanes = surface->format->BitsPerPixel; + mfdb_src.fd_stand = + mfdb_src.fd_r1 = mfdb_src.fd_r2 = mfdb_src.fd_r3 = 0; + if (GEM_bufops & B2S_VROCPYFM_2TOS) { + mfdb_src.fd_addr = GEM_buffer2; + } + + for (i = 0; i < numrects; ++i) { + blitcoords[0] = blitcoords[4] = rects[i].x; + blitcoords[1] = blitcoords[5] = rects[i].y; + blitcoords[2] = blitcoords[6] = rects[i].x + rects[i].w - 1; + blitcoords[3] = blitcoords[7] = rects[i].y + rects[i].h - 1; + + vro_cpyfm(VDI_handle, S_ONLY, blitcoords, &mfdb_src, + &VDI_dst_mfdb); + } + } } -static void GEM_UpdateRectsWindowed(_THIS, int numrects, SDL_Rect *rects) +static void +GEM_UpdateRectsWindowed(_THIS, int numrects, SDL_Rect * rects) { - short pxy[4], wind_pxy[4]; - int i; - - if (wind_get(GEM_handle, WF_WORKXYWH, &wind_pxy[0], &wind_pxy[1], &wind_pxy[2], &wind_pxy[3])==0) { - return; - } - - for ( i=0; iscreen; + surface = this->screen; - if (surface->flags & SDL_FULLSCREEN) { - GEM_UpdateRectsFullscreen(this, numrects, rects); - } else { - GEM_UpdateRectsWindowed(this, numrects, rects); - } + if (surface->flags & SDL_FULLSCREEN) { + GEM_UpdateRectsFullscreen(this, numrects, rects); + } else { + GEM_UpdateRectsWindowed(this, numrects, rects); + } } -static int GEM_FlipHWSurfaceFullscreen(_THIS, SDL_Surface *surface) +static int +GEM_FlipHWSurfaceFullscreen(_THIS, SDL_Surface * surface) { - int surf_width; - - /* Need to be a multiple of 16 pixels */ - surf_width=surface->w; - if ((surf_width & 15) != 0) { - surf_width = (surf_width | 15) + 1; - } - - if (GEM_bufops & (B2S_C2P_1TO2|B2S_C2P_1TOS)) { - void *destscr; - int destpitch; - - if (GEM_bufops & B2S_C2P_1TOS) { - destscr = VDI_screen; - destpitch = VDI_pitch; - } else { - destscr = GEM_buffer2; - destpitch = surface->pitch; - } - - SDL_Atari_C2pConvert( - surface->pixels, destscr, - surf_width, surface->h, - SDL_FALSE, - surface->pitch, destpitch - ); - } - - if (GEM_bufops & (B2S_VROCPYFM_1TOS|B2S_VROCPYFM_2TOS)) { - MFDB mfdb_src; - short blitcoords[8]; - - mfdb_src.fd_w=surf_width; - mfdb_src.fd_h=surface->h; - mfdb_src.fd_wdwidth=mfdb_src.fd_w >> 4; - mfdb_src.fd_nplanes=surface->format->BitsPerPixel; - mfdb_src.fd_stand= - mfdb_src.fd_r1= - mfdb_src.fd_r2= - mfdb_src.fd_r3= 0; - if (GEM_bufops & B2S_VROCPYFM_1TOS) { - mfdb_src.fd_addr=surface->pixels; - } else { - mfdb_src.fd_addr=GEM_buffer2; - } - - blitcoords[0] = blitcoords[4] = 0; - blitcoords[1] = blitcoords[5] = 0; - blitcoords[2] = blitcoords[6] = surface->w - 1; - blitcoords[3] = blitcoords[7] = surface->h - 1; - - vro_cpyfm(VDI_handle, S_ONLY, blitcoords, &mfdb_src, &VDI_dst_mfdb); - } - - return(0); + int surf_width; + + /* Need to be a multiple of 16 pixels */ + surf_width = surface->w; + if ((surf_width & 15) != 0) { + surf_width = (surf_width | 15) + 1; + } + + if (GEM_bufops & (B2S_C2P_1TO2 | B2S_C2P_1TOS)) { + void *destscr; + int destpitch; + + if (GEM_bufops & B2S_C2P_1TOS) { + destscr = VDI_screen; + destpitch = VDI_pitch; + } else { + destscr = GEM_buffer2; + destpitch = surface->pitch; + } + + SDL_Atari_C2pConvert(surface->pixels, destscr, + surf_width, surface->h, + SDL_FALSE, surface->pitch, destpitch); + } + + if (GEM_bufops & (B2S_VROCPYFM_1TOS | B2S_VROCPYFM_2TOS)) { + MFDB mfdb_src; + short blitcoords[8]; + + mfdb_src.fd_w = surf_width; + mfdb_src.fd_h = surface->h; + mfdb_src.fd_wdwidth = mfdb_src.fd_w >> 4; + mfdb_src.fd_nplanes = surface->format->BitsPerPixel; + mfdb_src.fd_stand = + mfdb_src.fd_r1 = mfdb_src.fd_r2 = mfdb_src.fd_r3 = 0; + if (GEM_bufops & B2S_VROCPYFM_1TOS) { + mfdb_src.fd_addr = surface->pixels; + } else { + mfdb_src.fd_addr = GEM_buffer2; + } + + blitcoords[0] = blitcoords[4] = 0; + blitcoords[1] = blitcoords[5] = 0; + blitcoords[2] = blitcoords[6] = surface->w - 1; + blitcoords[3] = blitcoords[7] = surface->h - 1; + + vro_cpyfm(VDI_handle, S_ONLY, blitcoords, &mfdb_src, &VDI_dst_mfdb); + } + + return (0); } -static int GEM_FlipHWSurfaceWindowed(_THIS, SDL_Surface *surface) +static int +GEM_FlipHWSurfaceWindowed(_THIS, SDL_Surface * surface) { - short pxy[8]; + short pxy[8]; - /* Update the whole window */ - wind_get(GEM_handle, WF_WORKXYWH, &pxy[0], &pxy[1], &pxy[2], &pxy[3]); + /* Update the whole window */ + wind_get(GEM_handle, WF_WORKXYWH, &pxy[0], &pxy[1], &pxy[2], &pxy[3]); - GEM_wind_redraw(this, GEM_handle, pxy); + GEM_wind_redraw(this, GEM_handle, pxy); - return(0); + return (0); } -static int GEM_FlipHWSurface(_THIS, SDL_Surface *surface) +static int +GEM_FlipHWSurface(_THIS, SDL_Surface * surface) { - if (GEM_lock_redraw) { - return(0); - } - - if (surface->flags & SDL_FULLSCREEN) { - return GEM_FlipHWSurfaceFullscreen(this, surface); - } else { - return GEM_FlipHWSurfaceWindowed(this, surface); - } + if (GEM_lock_redraw) { + return (0); + } + + if (surface->flags & SDL_FULLSCREEN) { + return GEM_FlipHWSurfaceFullscreen(this, surface); + } else { + return GEM_FlipHWSurfaceWindowed(this, surface); + } } -static int GEM_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color *colors) +static int +GEM_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color * colors) { - int i; - SDL_Surface *surface; + int i; + SDL_Surface *surface; #ifdef DEBUG_VIDEO_GEM - printf("sdl:video:gem: setcolors()\n"); + printf("sdl:video:gem: setcolors()\n"); #endif - /* Do not change palette in True Colour */ - surface = this->screen; - if (surface->format->BitsPerPixel > 8) { - return 1; - } + /* Do not change palette in True Colour */ + surface = this->screen; + if (surface->format->BitsPerPixel > 8) { + return 1; + } - for(i = 0; i < ncolors; i++) - { - int r, g, b; - short rgb[3]; + for (i = 0; i < ncolors; i++) { + int r, g, b; + short rgb[3]; - r = colors[i].r; - g = colors[i].g; - b = colors[i].b; + r = colors[i].r; + g = colors[i].g; + b = colors[i].b; - rgb[0] = VDI_curpalette[i][0] = (1000 * r) / 255; - rgb[1] = VDI_curpalette[i][1] =(1000 * g) / 255; - rgb[2] = VDI_curpalette[i][2] =(1000 * b) / 255; + rgb[0] = VDI_curpalette[i][0] = (1000 * r) / 255; + rgb[1] = VDI_curpalette[i][1] = (1000 * g) / 255; + rgb[2] = VDI_curpalette[i][2] = (1000 * b) / 255; - vs_color(VDI_handle, vdi_index[firstcolor+i], rgb); - } + vs_color(VDI_handle, vdi_index[firstcolor + i], rgb); + } - return(1); + return (1); } #if 0 -static int GEM_ToggleFullScreen(_THIS, int on) +static int +GEM_ToggleFullScreen(_THIS, int on) { - if (on) { - GEM_LockScreen(this); - } else { - GEM_UnlockScreen(this); - } + if (on) { + GEM_LockScreen(this); + } else { + GEM_UnlockScreen(this); + } - return(1); + return (1); } #endif /* Note: If we are terminated, this could be called in the middle of another SDL video routine -- notably UpdateRects. */ -void GEM_VideoQuit(_THIS) +void +GEM_VideoQuit(_THIS) { - SDL_AtariXbios_RestoreVectors(); - if (GEM_usedevmouse) { - SDL_AtariDevMouse_Close(); - } + SDL_AtariXbios_RestoreVectors(); + if (GEM_usedevmouse) { + SDL_AtariDevMouse_Close(); + } - GEM_FreeBuffers(this); + GEM_FreeBuffers(this); #if SDL_VIDEO_OPENGL - if (gl_active) { - SDL_AtariGL_Quit(this, SDL_TRUE); - } + if (gl_active) { + SDL_AtariGL_Quit(this, SDL_TRUE); + } #endif - /* Destroy window */ - if (GEM_handle>=0) { - wind_close(GEM_handle); - wind_delete(GEM_handle); - GEM_handle=-1; - } + /* Destroy window */ + if (GEM_handle >= 0) { + wind_close(GEM_handle); + wind_delete(GEM_handle); + GEM_handle = -1; + } - GEM_UnlockScreen(this); - if (GEM_menubar) { - Mfree(GEM_menubar); - GEM_menubar=NULL; - } + GEM_UnlockScreen(this); + if (GEM_menubar) { + Mfree(GEM_menubar); + GEM_menubar = NULL; + } - appl_exit(); + appl_exit(); - GEM_SetNewPalette(this, VDI_oldpalette); + GEM_SetNewPalette(this, VDI_oldpalette); - /* Close VDI workstation */ - if (VDI_handle) { - v_clsvwk(VDI_handle); - } + /* Close VDI workstation */ + if (VDI_handle) { + v_clsvwk(VDI_handle); + } - /* Free mode list */ - if (SDL_modelist[0]) { - SDL_free(SDL_modelist[0]); - SDL_modelist[0]=NULL; - } + /* Free mode list */ + if (SDL_modelist[0]) { + SDL_free(SDL_modelist[0]); + SDL_modelist[0] = NULL; + } - this->screen->pixels = NULL; + this->screen->pixels = NULL; } -void GEM_wind_redraw(_THIS, int winhandle, short *inside) +void +GEM_wind_redraw(_THIS, int winhandle, short *inside) { - short todo[4]; + short todo[4]; - /* Tell AES we are going to update */ - wind_update(BEG_UPDATE); + /* Tell AES we are going to update */ + wind_update(BEG_UPDATE); - v_hide_c(VDI_handle); + v_hide_c(VDI_handle); - /* Browse the rectangle list to redraw */ - if (wind_get(winhandle, WF_FIRSTXYWH, &todo[0], &todo[1], &todo[2], &todo[3])!=0) { + /* Browse the rectangle list to redraw */ + if (wind_get + (winhandle, WF_FIRSTXYWH, &todo[0], &todo[1], &todo[2], + &todo[3]) != 0) { - while (todo[2] && todo[3]) { + while (todo[2] && todo[3]) { - if (rc_intersect((GRECT *)inside,(GRECT *)todo)) { - todo[2] += todo[0]-1; - todo[3] += todo[1]-1; - refresh_window(this, winhandle, todo); - } + if (rc_intersect((GRECT *) inside, (GRECT *) todo)) { + todo[2] += todo[0] - 1; + todo[3] += todo[1] - 1; + refresh_window(this, winhandle, todo); + } - if (wind_get(winhandle, WF_NEXTXYWH, &todo[0], &todo[1], &todo[2], &todo[3])==0) { - break; - } - } + if (wind_get + (winhandle, WF_NEXTXYWH, &todo[0], &todo[1], &todo[2], + &todo[3]) == 0) { + break; + } + } - } + } - /* Update finished */ - wind_update(END_UPDATE); + /* Update finished */ + wind_update(END_UPDATE); - v_show_c(VDI_handle,1); + v_show_c(VDI_handle, 1); } -static void refresh_window(_THIS, int winhandle, short *rect) +static void +refresh_window(_THIS, int winhandle, short *rect) { - MFDB mfdb_src; - short pxy[8],wind_pxy[8]; - SDL_Surface *surface; - int iconified; - - /* Is window iconified ? */ - iconified = 0; -/* if (GEM_wfeatures & (1<w)>>1; - icony = (wind_pxy[3]-surface->h)>>1; - - icon_rect[0] = iconx; - icon_rect[1] = icony; - icon_rect[2] = surface->w; - icon_rect[3] = surface->h; - - /* Calculate redraw rectangle(x,y,w,h) relative to window */ - dst_rect[0] = rect[0]-wind_pxy[0]; - dst_rect[1] = rect[1]-wind_pxy[1]; - dst_rect[2] = rect[2]-rect[0]+1; - dst_rect[3] = rect[3]-rect[1]+1; - - /* Does the icon rectangle must be redrawn ? */ - if (!rc_intersect((GRECT *)icon_rect, (GRECT *)dst_rect)) { - return; - } - + MFDB mfdb_src; + short pxy[8], wind_pxy[8]; + SDL_Surface *surface; + int iconified; + + /* Is window iconified ? */ + iconified = 0; +/* if (GEM_wfeatures & (1<w) >> 1; + icony = (wind_pxy[3] - surface->h) >> 1; + + icon_rect[0] = iconx; + icon_rect[1] = icony; + icon_rect[2] = surface->w; + icon_rect[3] = surface->h; + + /* Calculate redraw rectangle(x,y,w,h) relative to window */ + dst_rect[0] = rect[0] - wind_pxy[0]; + dst_rect[1] = rect[1] - wind_pxy[1]; + dst_rect[2] = rect[2] - rect[0] + 1; + dst_rect[3] = rect[3] - rect[1] + 1; + + /* Does the icon rectangle must be redrawn ? */ + if (!rc_intersect((GRECT *) icon_rect, (GRECT *) dst_rect)) { + return; + } #if DEBUG_VIDEO_GEM - printf("sdl:video:gem: clip(0,0,%d,%d) to (%d,%d,%d,%d)\n", - surface->w-1,surface->h-1, dst_rect[0],dst_rect[1],dst_rect[2],dst_rect[3]); - printf("sdl:video:gem: icon(%d,%d,%d,%d)\n", - icon_rect[0], icon_rect[1], icon_rect[2], icon_rect[3]); - printf("sdl:video:gem: refresh_window(): draw icon\n"); + printf("sdl:video:gem: clip(0,0,%d,%d) to (%d,%d,%d,%d)\n", + surface->w - 1, surface->h - 1, dst_rect[0], dst_rect[1], + dst_rect[2], dst_rect[3]); + printf("sdl:video:gem: icon(%d,%d,%d,%d)\n", icon_rect[0], + icon_rect[1], icon_rect[2], icon_rect[3]); + printf("sdl:video:gem: refresh_window(): draw icon\n"); #endif - /* Calculate icon(x1,y1,x2,y2) relative to screen */ - icon_rect[0] += wind_pxy[0]; - icon_rect[1] += wind_pxy[1]; - icon_rect[2] += icon_rect[0]-1; - icon_rect[3] += icon_rect[1]-1; + /* Calculate icon(x1,y1,x2,y2) relative to screen */ + icon_rect[0] += wind_pxy[0]; + icon_rect[1] += wind_pxy[1]; + icon_rect[2] += icon_rect[0] - 1; + icon_rect[3] += icon_rect[1] - 1; - /* Calculate intersection rectangle to redraw */ - pxy[4]=pxy[0]=MAX(icon_rect[0],rect[0]); - pxy[5]=pxy[1]=MAX(icon_rect[1],rect[1]); - pxy[6]=pxy[2]=MIN(icon_rect[2],rect[2]); - pxy[7]=pxy[3]=MIN(icon_rect[3],rect[3]); + /* Calculate intersection rectangle to redraw */ + pxy[4] = pxy[0] = MAX(icon_rect[0], rect[0]); + pxy[5] = pxy[1] = MAX(icon_rect[1], rect[1]); + pxy[6] = pxy[2] = MIN(icon_rect[2], rect[2]); + pxy[7] = pxy[3] = MIN(icon_rect[3], rect[3]); - /* Calculate icon source image pos relative to window */ - pxy[0] -= wind_pxy[0]+iconx; - pxy[1] -= wind_pxy[1]+icony; - pxy[2] -= wind_pxy[0]+iconx; - pxy[3] -= wind_pxy[1]+icony; + /* Calculate icon source image pos relative to window */ + pxy[0] -= wind_pxy[0] + iconx; + pxy[1] -= wind_pxy[1] + icony; + pxy[2] -= wind_pxy[0] + iconx; + pxy[3] -= wind_pxy[1] + icony; - } else { - surface = this->screen; + } else { + surface = this->screen; #if DEBUG_VIDEO_GEM - printf("sdl:video:gem: refresh_window(): draw frame buffer\n"); + printf("sdl:video:gem: refresh_window(): draw frame buffer\n"); #endif - /* Redraw all window content */ - pxy[0] = rect[0]-wind_pxy[0]; - pxy[1] = rect[1]-wind_pxy[1]; - pxy[2] = rect[2]-wind_pxy[0]; - pxy[3] = rect[3]-wind_pxy[1]; - - pxy[4] = rect[0]; - pxy[5] = rect[1]; - pxy[6] = rect[2]; - pxy[7] = rect[3]; - } - - if (GEM_bufops & B2S_C2P_1TO2) { - void *src, *dest; - int x1,x2; - - x1 = (rect[0]-wind_pxy[0]) & ~15; - x2 = rect[2]-wind_pxy[0]; - if (x2 & 15) { - x2 = (x2 | 15) +1; - } - - src = surface->pixels; - src += surface->pitch * (rect[1]-wind_pxy[1]); - src += x1; - - dest = GEM_buffer2; - dest += surface->pitch * (rect[1]-wind_pxy[1]); - dest += x1; - - SDL_Atari_C2pConvert( - src, dest, - x2-x1, rect[3]-rect[1]+1, - SDL_FALSE, - surface->pitch, surface->pitch - ); - } - - mfdb_src.fd_addr=surface->pixels; - { - int width; - - /* Need to be a multiple of 16 pixels */ - width=surface->w; - if ((width & 15) != 0) { - width = (width | 15) + 1; - } - mfdb_src.fd_w=width; - } - mfdb_src.fd_h=surface->h; - mfdb_src.fd_nplanes=surface->format->BitsPerPixel; - mfdb_src.fd_wdwidth=mfdb_src.fd_w>>4; - mfdb_src.fd_stand= - mfdb_src.fd_r1= - mfdb_src.fd_r2= - mfdb_src.fd_r3= 0; - - if (GEM_bufops & B2S_VROCPYFM_2TOS) { - mfdb_src.fd_addr=GEM_buffer2; - } - + /* Redraw all window content */ + pxy[0] = rect[0] - wind_pxy[0]; + pxy[1] = rect[1] - wind_pxy[1]; + pxy[2] = rect[2] - wind_pxy[0]; + pxy[3] = rect[3] - wind_pxy[1]; + + pxy[4] = rect[0]; + pxy[5] = rect[1]; + pxy[6] = rect[2]; + pxy[7] = rect[3]; + } + + if (GEM_bufops & B2S_C2P_1TO2) { + void *src, *dest; + int x1, x2; + + x1 = (rect[0] - wind_pxy[0]) & ~15; + x2 = rect[2] - wind_pxy[0]; + if (x2 & 15) { + x2 = (x2 | 15) + 1; + } + + src = surface->pixels; + src += surface->pitch * (rect[1] - wind_pxy[1]); + src += x1; + + dest = GEM_buffer2; + dest += surface->pitch * (rect[1] - wind_pxy[1]); + dest += x1; + + SDL_Atari_C2pConvert(src, dest, + x2 - x1, rect[3] - rect[1] + 1, + SDL_FALSE, surface->pitch, surface->pitch); + } + + mfdb_src.fd_addr = surface->pixels; + { + int width; + + /* Need to be a multiple of 16 pixels */ + width = surface->w; + if ((width & 15) != 0) { + width = (width | 15) + 1; + } + mfdb_src.fd_w = width; + } + mfdb_src.fd_h = surface->h; + mfdb_src.fd_nplanes = surface->format->BitsPerPixel; + mfdb_src.fd_wdwidth = mfdb_src.fd_w >> 4; + mfdb_src.fd_stand = mfdb_src.fd_r1 = mfdb_src.fd_r2 = mfdb_src.fd_r3 = 0; + + if (GEM_bufops & B2S_VROCPYFM_2TOS) { + mfdb_src.fd_addr = GEM_buffer2; + } #if DEBUG_VIDEO_GEM - printf("sdl:video:gem: redraw %dx%d: (%d,%d,%d,%d) to (%d,%d,%d,%d)\n", - surface->w, surface->h, - pxy[0],pxy[1],pxy[2],pxy[3], - pxy[4],pxy[5],pxy[6],pxy[7] - ); + printf("sdl:video:gem: redraw %dx%d: (%d,%d,%d,%d) to (%d,%d,%d,%d)\n", + surface->w, surface->h, + pxy[0], pxy[1], pxy[2], pxy[3], pxy[4], pxy[5], pxy[6], pxy[7]); #endif - vro_cpyfm( VDI_handle, S_ONLY, pxy, &mfdb_src, &VDI_dst_mfdb); + vro_cpyfm(VDI_handle, S_ONLY, pxy, &mfdb_src, &VDI_dst_mfdb); } #if SDL_VIDEO_OPENGL -static void GEM_GL_SwapBuffers(_THIS) +static void +GEM_GL_SwapBuffers(_THIS) { - SDL_AtariGL_SwapBuffers(this); - GEM_FlipHWSurface(this, this->screen); + SDL_AtariGL_SwapBuffers(this); + GEM_FlipHWSurface(this, this->screen); } #endif +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/gem/SDL_gemvideo.h b/src/video/gem/SDL_gemvideo.h index 844607825..48748e8f3 100644 --- a/src/video/gem/SDL_gemvideo.h +++ b/src/video/gem/SDL_gemvideo.h @@ -27,11 +27,6 @@ #include "SDL_mutex.h" #include "../SDL_sysvideo.h" -/* The implementation dependent data for the window manager cursor */ -struct WMcursor { - MFORM *mform_p; -}; - /* Hidden "this" pointer for the video functions */ #define _THIS SDL_VideoDevice *this @@ -40,58 +35,58 @@ void GEM_wind_redraw(_THIS, int winhandle, short *inside); /* Private display data */ -#define B2S_C2P_1TO2 (1<<0) /* C2P convert buffer 1 to buffer 2 */ -#define B2S_C2P_1TOS (1<<1) /* C2P convert buffer 1 to screen */ -#define B2S_VROCPYFM_1TOS (1<<2) /* vro_cpyfm() buffer 1 to screen */ -#define B2S_VROCPYFM_2TOS (1<<3) /* vro_cpyfm() buffer 2 to screen */ - -#define SDL_NUMMODES 1 /* Fullscreen */ - -struct SDL_PrivateVideoData { - Uint16 buf2scr_ops; /* Operations to get buffer to screen */ - void *buffer1; /* Our shadow buffers */ - void *buffer2; - - /* VDI infos */ - short vdi_handle; /* VDI handle */ - short full_w, full_h; /* Fullscreen size */ - short bpp; /* Colour depth */ - short pixelsize; /* Bytes per pixel */ - short old_numcolors; /* Number of colors in saved palette */ - Uint16 pitch; /* Line length */ - Uint16 format; /* Screen format */ - void *screen; /* Screen address */ - Uint32 red, green, blue, alpha; /* Screen components */ - Uint32 screensize; - short blit_coords[8]; /* Coordinates for bitblt */ - MFDB src_mfdb, dst_mfdb; /* VDI MFDB for bitblt */ - Uint16 old_palette[256][3]; /* Saved current palette */ - Uint16 cur_palette[256][3]; /* SDL application palette */ - /* Function to set/restore palette */ - void (*setpalette)(_THIS, Uint16 newpal[256][3]); - - /* GEM infos */ - short desk_x, desk_y; /* Desktop properties */ - short desk_w, desk_h; - short win_handle; /* Our window handle */ - int window_type; /* Window type */ - const char *title_name; /* Window title */ - const char *icon_name; /* Icon title */ - short version; /* AES version */ - short wfeatures; /* AES window features */ - SDL_bool refresh_name; /* Change window title ? */ - SDL_bool window_fulled; /* Window maximized ? */ - SDL_bool mouse_relative; /* Report relative mouse movement */ - SDL_bool locked; /* AES locked for fullscreen ? */ - SDL_bool lock_redraw; /* Prevent redraw till buffers are setup */ - short message[8]; /* To self-send an AES message */ - void *menubar; /* Menu bar save buffer when going fullscreen */ - SDL_bool use_dev_mouse; /* Use /dev/mouse ? */ - WMcursor *cursor; /* To restore cursor when leaving/entering window */ - - SDL_bool fullscreen; /* Fullscreen or windowed mode ? */ - SDL_Rect *SDL_modelist[SDL_NUMMODES+1]; /* Mode list */ - SDL_Surface *icon; /* The icon */ +#define B2S_C2P_1TO2 (1<<0) /* C2P convert buffer 1 to buffer 2 */ +#define B2S_C2P_1TOS (1<<1) /* C2P convert buffer 1 to screen */ +#define B2S_VROCPYFM_1TOS (1<<2) /* vro_cpyfm() buffer 1 to screen */ +#define B2S_VROCPYFM_2TOS (1<<3) /* vro_cpyfm() buffer 2 to screen */ + +#define SDL_NUMMODES 1 /* Fullscreen */ + +struct SDL_PrivateVideoData +{ + Uint16 buf2scr_ops; /* Operations to get buffer to screen */ + void *buffer1; /* Our shadow buffers */ + void *buffer2; + + /* VDI infos */ + short vdi_handle; /* VDI handle */ + short full_w, full_h; /* Fullscreen size */ + short bpp; /* Colour depth */ + short pixelsize; /* Bytes per pixel */ + short old_numcolors; /* Number of colors in saved palette */ + Uint16 pitch; /* Line length */ + Uint16 format; /* Screen format */ + void *screen; /* Screen address */ + Uint32 red, green, blue, alpha; /* Screen components */ + Uint32 screensize; + short blit_coords[8]; /* Coordinates for bitblt */ + MFDB src_mfdb, dst_mfdb; /* VDI MFDB for bitblt */ + Uint16 old_palette[256][3]; /* Saved current palette */ + Uint16 cur_palette[256][3]; /* SDL application palette */ + /* Function to set/restore palette */ + void (*setpalette) (_THIS, Uint16 newpal[256][3]); + + /* GEM infos */ + short desk_x, desk_y; /* Desktop properties */ + short desk_w, desk_h; + short win_handle; /* Our window handle */ + int window_type; /* Window type */ + const char *title_name; /* Window title */ + const char *icon_name; /* Icon title */ + short version; /* AES version */ + short wfeatures; /* AES window features */ + SDL_bool refresh_name; /* Change window title ? */ + SDL_bool window_fulled; /* Window maximized ? */ + SDL_bool mouse_relative; /* Report relative mouse movement */ + SDL_bool locked; /* AES locked for fullscreen ? */ + SDL_bool lock_redraw; /* Prevent redraw till buffers are setup */ + short message[8]; /* To self-send an AES message */ + void *menubar; /* Menu bar save buffer when going fullscreen */ + SDL_bool use_dev_mouse; /* Use /dev/mouse ? */ + + SDL_bool fullscreen; /* Fullscreen or windowed mode ? */ + SDL_Rect *SDL_modelist[SDL_NUMMODES + 1]; /* Mode list */ + SDL_Surface *icon; /* The icon */ }; /* Hidden structure -> variables names */ @@ -137,7 +132,6 @@ struct SDL_PrivateVideoData { #define GEM_fullscreen (this->hidden->fullscreen) #define GEM_menubar (this->hidden->menubar) #define GEM_usedevmouse (this->hidden->use_dev_mouse) -#define GEM_cursor (this->hidden->cursor) #define GEM_buffer1 (this->hidden->buffer1) #define GEM_buffer2 (this->hidden->buffer2) @@ -189,3 +183,4 @@ struct SDL_PrivateVideoData { */ #endif /* _SDL_gemvideo_h */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/gem/SDL_gemwm.c b/src/video/gem/SDL_gemwm.c index 28d26443b..0df9a5cdf 100644 --- a/src/video/gem/SDL_gemwm.c +++ b/src/video/gem/SDL_gemwm.c @@ -40,73 +40,80 @@ /* Functions */ -void GEM_SetCaption(_THIS, const char *title, const char *icon) +void +GEM_SetCaption(_THIS, const char *title, const char *icon) { - if (title) { - GEM_title_name = title; - GEM_refresh_name = SDL_TRUE; - } - - if (icon) { - GEM_icon_name = icon; - GEM_refresh_name = SDL_TRUE; - } + if (title) { + GEM_title_name = title; + GEM_refresh_name = SDL_TRUE; + } + + if (icon) { + GEM_icon_name = icon; + GEM_refresh_name = SDL_TRUE; + } } -void GEM_SetIcon(_THIS, SDL_Surface *icon, Uint8 *mask) +void +GEM_SetIcon(_THIS, SDL_Surface * icon, Uint8 * mask) { - SDL_Surface *sicon; - SDL_Rect bounds; + SDL_Surface *sicon; + SDL_Rect bounds; #if 0 - if ((GEM_wfeatures & (1<w, icon->h, - VDI_bpp, VDI_redmask, VDI_greenmask, VDI_bluemask, 0); - if ( sicon == NULL ) { - return; - } - - bounds.x = 0; - bounds.y = 0; - bounds.w = icon->w; - bounds.h = icon->h; - if ( SDL_LowerBlit(icon, &bounds, sicon, &bounds) < 0 ) { - SDL_FreeSurface(sicon); - return; - } - - GEM_icon = sicon; + if (icon == NULL) { + return; + } + + /* Convert icon to the screen format */ + sicon = SDL_CreateRGBSurface(SDL_SWSURFACE, icon->w, icon->h, + VDI_bpp, VDI_redmask, VDI_greenmask, + VDI_bluemask, 0); + if (sicon == NULL) { + return; + } + + bounds.x = 0; + bounds.y = 0; + bounds.w = icon->w; + bounds.h = icon->h; + if (SDL_LowerBlit(icon, &bounds, sicon, &bounds) < 0) { + SDL_FreeSurface(sicon); + return; + } + + GEM_icon = sicon; } -int GEM_IconifyWindow(_THIS) +int +GEM_IconifyWindow(_THIS) { - if ((GEM_wfeatures & (1<scancode = ev->key.button; - keysym->sym = keymap[ev->key.button]; - keysym->mod = KMOD_NONE; + /* Set the keysym information */ + keysym->scancode = ev->key.button; + keysym->sym = keymap[ev->key.button]; + keysym->mod = KMOD_NONE; - /* If UNICODE is on, get the UNICODE value for the key */ - keysym->unicode = 0; - if (SDL_TranslateUNICODE) - { - keysym->unicode = GII_UNICODE(ev->key.sym); - } + /* If UNICODE is on, get the UNICODE value for the key */ + keysym->unicode = 0; + if (SDL_TranslateUNICODE) { + keysym->unicode = GII_UNICODE(ev->key.sym); + } - return keysym; + return keysym; } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/ggi/SDL_ggievents_c.h b/src/video/ggi/SDL_ggievents_c.h index 114b6925a..94d6dae9c 100755 --- a/src/video/ggi/SDL_ggievents_c.h +++ b/src/video/ggi/SDL_ggievents_c.h @@ -26,4 +26,4 @@ /* Functions to be exported */ extern void GGI_InitOSKeymap(_THIS); extern void GGI_PumpEvents(_THIS); - +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/ggi/SDL_ggikeys.h b/src/video/ggi/SDL_ggikeys.h index 2868ee6ff..0137cd743 100644 --- a/src/video/ggi/SDL_ggikeys.h +++ b/src/video/ggi/SDL_ggikeys.h @@ -116,20 +116,20 @@ #define SCANCODE_KEYPADDIVIDE 98 #define SCANCODE_PRINTSCREEN 99 #define SCANCODE_RIGHTALT 100 -#define SCANCODE_BREAK 101 /* Beware: is 119 */ -#define SCANCODE_BREAK_ALTERNATIVE 119 /* on some keyboards! */ +#define SCANCODE_BREAK 101 /* Beware: is 119 */ +#define SCANCODE_BREAK_ALTERNATIVE 119 /* on some keyboards! */ #define SCANCODE_HOME 102 -#define SCANCODE_CURSORBLOCKUP 90 /* Cursor key block */ +#define SCANCODE_CURSORBLOCKUP 90 /* Cursor key block */ #define SCANCODE_PAGEUP 104 -#define SCANCODE_CURSORBLOCKLEFT 92 /* Cursor key block */ -#define SCANCODE_CURSORBLOCKRIGHT 94 /* Cursor key block */ +#define SCANCODE_CURSORBLOCKLEFT 92 /* Cursor key block */ +#define SCANCODE_CURSORBLOCKRIGHT 94 /* Cursor key block */ #define SCANCODE_END 107 -#define SCANCODE_CURSORBLOCKDOWN 108 /* Cursor key block */ +#define SCANCODE_CURSORBLOCKDOWN 108 /* Cursor key block */ #define SCANCODE_PAGEDOWN 109 #define SCANCODE_INSERT 110 #define SCANCODE_REMOVE 111 #define SCANCODE_RIGHTWIN 126 #define SCANCODE_LEFTWIN 125 - +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/ggi/SDL_ggimouse.c b/src/video/ggi/SDL_ggimouse.c index f9f1a04ca..81ba1a340 100644 --- a/src/video/ggi/SDL_ggimouse.c +++ b/src/video/ggi/SDL_ggimouse.c @@ -27,6 +27,8 @@ /* The implementation dependent data for the window manager cursor */ -struct WMcursor { - int unused; +struct WMcursor +{ + int unused; }; +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/ggi/SDL_ggimouse_c.h b/src/video/ggi/SDL_ggimouse_c.h index a679d0579..6489b952e 100755 --- a/src/video/ggi/SDL_ggimouse_c.h +++ b/src/video/ggi/SDL_ggimouse_c.h @@ -24,3 +24,4 @@ #include "SDL_ggivideo.h" /* Functions to be exported */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/ggi/SDL_ggivideo.c b/src/video/ggi/SDL_ggivideo.c index a55154a83..b08563571 100644 --- a/src/video/ggi/SDL_ggivideo.c +++ b/src/video/ggi/SDL_ggivideo.c @@ -43,336 +43,358 @@ struct private_hwdata { - ggi_visual_t vis; + ggi_visual_t vis; }; ggi_visual_t VIS; /* Initialization/Query functions */ -static int GGI_VideoInit(_THIS, SDL_PixelFormat *vformat); -static SDL_Rect **GGI_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags); -static SDL_Surface *GGI_SetVideoMode(_THIS, SDL_Surface *current, int width, int height, int bpp, Uint32 flags); +static int GGI_VideoInit(_THIS, SDL_PixelFormat * vformat); +static SDL_Rect **GGI_ListModes(_THIS, SDL_PixelFormat * format, + Uint32 flags); +static SDL_Surface *GGI_SetVideoMode(_THIS, SDL_Surface * current, int width, + int height, int bpp, Uint32 flags); static int GGI_SetColors(_THIS, int firstcolor, int ncolors, - SDL_Color *colors); + SDL_Color * colors); static void GGI_VideoQuit(_THIS); /* Hardware surface functions */ -static int GGI_AllocHWSurface(_THIS, SDL_Surface *surface); -static int GGI_LockHWSurface(_THIS, SDL_Surface *surface); -static void GGI_UnlockHWSurface(_THIS, SDL_Surface *surface); -static void GGI_FreeHWSurface(_THIS, SDL_Surface *surface); +static int GGI_AllocHWSurface(_THIS, SDL_Surface * surface); +static int GGI_LockHWSurface(_THIS, SDL_Surface * surface); +static void GGI_UnlockHWSurface(_THIS, SDL_Surface * surface); +static void GGI_FreeHWSurface(_THIS, SDL_Surface * surface); /* GGI driver bootstrap functions */ -static int GGI_Available(void) +static int +GGI_Available(void) { - ggi_visual_t *vis; - - vis = NULL; - if (ggiInit() == 0) { - vis = ggiOpen(NULL); - if (vis != NULL) { - ggiClose(vis); - } - } - return (vis != NULL); + ggi_visual_t *vis; + + vis = NULL; + if (ggiInit() == 0) { + vis = ggiOpen(NULL); + if (vis != NULL) { + ggiClose(vis); + } + } + return (vis != NULL); } -static void GGI_DeleteDevice(SDL_VideoDevice *device) +static void +GGI_DeleteDevice(SDL_VideoDevice * device) { - SDL_free(device->hidden); - SDL_free(device); + SDL_free(device->hidden); + SDL_free(device); } -static SDL_VideoDevice *GGI_CreateDevice(int devindex) +static SDL_VideoDevice * +GGI_CreateDevice(int devindex) { - SDL_VideoDevice *device; - - /* Initialize all variables that we clean on shutdown */ - device = (SDL_VideoDevice *)SDL_malloc(sizeof(SDL_VideoDevice)); - if ( device ) { - SDL_memset(device, 0, (sizeof *device)); - device->hidden = (struct SDL_PrivateVideoData *) - SDL_malloc((sizeof *device->hidden)); - } - if ( (device == NULL) || (device->hidden == NULL) ) { - SDL_OutOfMemory(); - if ( device ) { - SDL_free(device); - } - return(0); - } - SDL_memset(device->hidden, 0, (sizeof *device->hidden)); - - /* Set the function pointers */ - device->VideoInit = GGI_VideoInit; - device->ListModes = GGI_ListModes; - device->SetVideoMode = GGI_SetVideoMode; - device->SetColors = GGI_SetColors; - device->UpdateRects = NULL; - device->VideoQuit = GGI_VideoQuit; - device->AllocHWSurface = GGI_AllocHWSurface; - device->CheckHWBlit = NULL; - device->FillHWRect = NULL; - device->SetHWColorKey = NULL; - device->SetHWAlpha = NULL; - device->LockHWSurface = GGI_LockHWSurface; - device->UnlockHWSurface = GGI_UnlockHWSurface; - device->FlipHWSurface = NULL; - device->FreeHWSurface = GGI_FreeHWSurface; - device->SetCaption = NULL; - device->SetIcon = NULL; - device->IconifyWindow = NULL; - device->GrabInput = NULL; - device->GetWMInfo = NULL; - device->InitOSKeymap = GGI_InitOSKeymap; - device->PumpEvents = GGI_PumpEvents; - - device->free = GGI_DeleteDevice; - - return device; + SDL_VideoDevice *device; + + /* Initialize all variables that we clean on shutdown */ + device = (SDL_VideoDevice *) SDL_malloc(sizeof(SDL_VideoDevice)); + if (device) { + SDL_memset(device, 0, (sizeof *device)); + device->hidden = (struct SDL_PrivateVideoData *) + SDL_malloc((sizeof *device->hidden)); + } + if ((device == NULL) || (device->hidden == NULL)) { + SDL_OutOfMemory(); + if (device) { + SDL_free(device); + } + return (0); + } + SDL_memset(device->hidden, 0, (sizeof *device->hidden)); + + /* Set the function pointers */ + device->VideoInit = GGI_VideoInit; + device->ListModes = GGI_ListModes; + device->SetVideoMode = GGI_SetVideoMode; + device->SetColors = GGI_SetColors; + device->UpdateRects = NULL; + device->VideoQuit = GGI_VideoQuit; + device->AllocHWSurface = GGI_AllocHWSurface; + device->CheckHWBlit = NULL; + device->FillHWRect = NULL; + device->SetHWColorKey = NULL; + device->SetHWAlpha = NULL; + device->LockHWSurface = GGI_LockHWSurface; + device->UnlockHWSurface = GGI_UnlockHWSurface; + device->FlipHWSurface = NULL; + device->FreeHWSurface = GGI_FreeHWSurface; + device->SetCaption = NULL; + device->SetIcon = NULL; + device->IconifyWindow = NULL; + device->GrabInput = NULL; + device->GetWMInfo = NULL; + device->InitOSKeymap = GGI_InitOSKeymap; + device->PumpEvents = GGI_PumpEvents; + + device->free = GGI_DeleteDevice; + + return device; } VideoBootStrap GGI_bootstrap = { - "ggi", "General Graphics Interface (GGI)", - GGI_Available, GGI_CreateDevice + "ggi", "General Graphics Interface (GGI)", + GGI_Available, GGI_CreateDevice }; static SDL_Rect video_mode; static SDL_Rect *SDL_modelist[4] = { NULL, NULL, NULL, NULL }; -int GGI_VideoInit(_THIS, SDL_PixelFormat *vformat) +int +GGI_VideoInit(_THIS, SDL_PixelFormat * vformat) { - ggi_mode mode = - { - 1, - { GGI_AUTO, GGI_AUTO }, - { GGI_AUTO, GGI_AUTO }, - { 0, 0 }, - GT_AUTO, - { GGI_AUTO, GGI_AUTO } - }; - struct private_hwdata *priv; - ggi_color pal[256], map[256]; - const ggi_directbuffer *db; - int err, num_bufs; - ggi_pixel white, black; - - priv = SDL_malloc(sizeof(struct private_hwdata)); - if (priv == NULL) - { - SDL_SetError("Unhandled GGI mode type!\n"); - GGI_VideoQuit(NULL); - } - - if (ggiInit() != 0) - { - SDL_SetError("Unable to initialize GGI!\n"); - GGI_VideoQuit(NULL); - } - - VIS = ggiOpen(NULL); - if (VIS == NULL) - { - SDL_SetError("Unable to open default GGI visual!\n"); - ggiExit(); - GGI_VideoQuit(NULL); - } - - ggiSetFlags(VIS, GGIFLAG_ASYNC); - - /* Validate mode, autodetecting any GGI_AUTO or GT_AUTO fields */ - ggiCheckMode(VIS, &mode); - - /* At this point we should have a valid mode - try to set it */ - err = ggiSetMode(VIS, &mode); - - /* If we couldn't set _any_ modes, something is very wrong */ - if (err) - { - SDL_SetError("Can't set a mode!\n"); - ggiClose(VIS); - ggiExit(); - GGI_VideoQuit(NULL); - } - - /* Determine the current screen size */ - this->info.current_w = mode.virt.x; - this->info.current_h = mode.virt.y; - - /* Set a palette for palletized modes */ - if (GT_SCHEME(mode.graphtype) == GT_PALETTE) - { - ggiSetColorfulPalette(VIS); - ggiGetPalette(VIS, 0, 1 << vformat->BitsPerPixel, pal); - } - - /* Now we try to get the DirectBuffer info, which determines whether - * SDL can access hardware surfaces directly. */ - - num_bufs = ggiDBGetNumBuffers(VIS); - - if (num_bufs > 0) - { - db = ggiDBGetBuffer(VIS, 0); /* Only handle one DB for now */ - - vformat->BitsPerPixel = db->buffer.plb.pixelformat->depth; - - vformat->Rmask = db->buffer.plb.pixelformat->red_mask; - vformat->Gmask = db->buffer.plb.pixelformat->green_mask; - vformat->Bmask = db->buffer.plb.pixelformat->blue_mask; - - /* Fill in our hardware acceleration capabilities */ - - this->info.wm_available = 0; - this->info.hw_available = 1; - this->info.video_mem = db->buffer.plb.stride * mode.virt.y; - } - - video_mode.x = 0; - video_mode.y = 0; - video_mode.w = mode.virt.x; - video_mode.h = mode.virt.y; - SDL_modelist[((vformat->BitsPerPixel + 7) / 8) - 1] = &video_mode; - - /* We're done! */ - return(0); + ggi_mode mode = { + 1, + {GGI_AUTO, GGI_AUTO}, + {GGI_AUTO, GGI_AUTO}, + {0, 0}, + GT_AUTO, + {GGI_AUTO, GGI_AUTO} + }; + struct private_hwdata *priv; + ggi_color pal[256], map[256]; + const ggi_directbuffer *db; + int err, num_bufs; + ggi_pixel white, black; + + priv = SDL_malloc(sizeof(struct private_hwdata)); + if (priv == NULL) { + SDL_SetError("Unhandled GGI mode type!\n"); + GGI_VideoQuit(NULL); + } + + if (ggiInit() != 0) { + SDL_SetError("Unable to initialize GGI!\n"); + GGI_VideoQuit(NULL); + } + + VIS = ggiOpen(NULL); + if (VIS == NULL) { + SDL_SetError("Unable to open default GGI visual!\n"); + ggiExit(); + GGI_VideoQuit(NULL); + } + + ggiSetFlags(VIS, GGIFLAG_ASYNC); + + /* Validate mode, autodetecting any GGI_AUTO or GT_AUTO fields */ + ggiCheckMode(VIS, &mode); + + /* At this point we should have a valid mode - try to set it */ + err = ggiSetMode(VIS, &mode); + + /* If we couldn't set _any_ modes, something is very wrong */ + if (err) { + SDL_SetError("Can't set a mode!\n"); + ggiClose(VIS); + ggiExit(); + GGI_VideoQuit(NULL); + } + + /* Determine the current screen size */ + this->info.current_w = mode.virt.x; + this->info.current_h = mode.virt.y; + + /* Set a palette for palletized modes */ + if (GT_SCHEME(mode.graphtype) == GT_PALETTE) { + ggiSetColorfulPalette(VIS); + ggiGetPalette(VIS, 0, 1 << vformat->BitsPerPixel, pal); + } + + /* Now we try to get the DirectBuffer info, which determines whether + * SDL can access hardware surfaces directly. */ + + num_bufs = ggiDBGetNumBuffers(VIS); + + if (num_bufs > 0) { + db = ggiDBGetBuffer(VIS, 0); /* Only handle one DB for now */ + + vformat->BitsPerPixel = db->buffer.plb.pixelformat->depth; + + vformat->Rmask = db->buffer.plb.pixelformat->red_mask; + vformat->Gmask = db->buffer.plb.pixelformat->green_mask; + vformat->Bmask = db->buffer.plb.pixelformat->blue_mask; + + /* Fill in our hardware acceleration capabilities */ + + this->info.wm_available = 0; + this->info.hw_available = 1; + this->info.video_mem = db->buffer.plb.stride * mode.virt.y; + } + + video_mode.x = 0; + video_mode.y = 0; + video_mode.w = mode.virt.x; + video_mode.h = mode.virt.y; + SDL_modelist[((vformat->BitsPerPixel + 7) / 8) - 1] = &video_mode; + + /* We're done! */ + return (0); } -static SDL_Rect **GGI_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags) +static SDL_Rect ** +GGI_ListModes(_THIS, SDL_PixelFormat * format, Uint32 flags) { - return(&SDL_modelist[((format->BitsPerPixel + 7) / 8) - 1]); + return (&SDL_modelist[((format->BitsPerPixel + 7) / 8) - 1]); } /* Various screen update functions available */ -static void GGI_DirectUpdate(_THIS, int numrects, SDL_Rect *rects); +static void GGI_DirectUpdate(_THIS, int numrects, SDL_Rect * rects); -SDL_Surface *GGI_SetVideoMode(_THIS, SDL_Surface *current, int width, int height, int bpp, Uint32 flags) +SDL_Surface * +GGI_SetVideoMode(_THIS, SDL_Surface * current, int width, int height, + int bpp, Uint32 flags) { - ggi_mode mode = - { - 1, - { GGI_AUTO, GGI_AUTO }, - { GGI_AUTO, GGI_AUTO }, - { 0, 0 }, - GT_AUTO, - { GGI_AUTO, GGI_AUTO } - }; - const ggi_directbuffer *db; - ggi_color pal[256]; - int err; - - fprintf(stderr, "GGI_SetVideoMode()\n"); - - mode.visible.x = mode.virt.x = width; - mode.visible.y = mode.virt.y = height; - - /* Translate requested SDL bit depth into a GGI mode */ - switch (bpp) - { - case 1: mode.graphtype = GT_1BIT; break; - case 2: mode.graphtype = GT_2BIT; break; - case 4: mode.graphtype = GT_4BIT; break; - case 8: mode.graphtype = GT_8BIT; break; - case 15: mode.graphtype = GT_15BIT; break; - case 16: mode.graphtype = GT_16BIT; break; - case 24: mode.graphtype = GT_24BIT; break; - case 32: mode.graphtype = GT_32BIT; break; - default: - SDL_SetError("Unknown SDL bit depth, using GT_AUTO....\n"); - mode.graphtype = GT_AUTO; - } - - /* Validate mode, autodetecting any GGI_AUTO or GT_AUTO fields */ - ggiCheckMode(VIS, &mode); - - /* At this point we should have a valid mode - try to set it */ - err = ggiSetMode(VIS, &mode); - - /* If we couldn't set _any_ modes, something is very wrong */ - if (err) - { - SDL_SetError("Can't set a mode!\n"); - ggiClose(VIS); - ggiExit(); - GGI_VideoQuit(NULL); - } - - /* Set a palette for palletized modes */ - if (GT_SCHEME(mode.graphtype) == GT_PALETTE) - { - ggiSetColorfulPalette(VIS); - ggiGetPalette(VIS, 0, 1 << bpp, pal); - } - - db = ggiDBGetBuffer(VIS, 0); - - /* Set up the new mode framebuffer */ - current->flags = (SDL_FULLSCREEN | SDL_HWSURFACE); - current->w = mode.virt.x; - current->h = mode.virt.y; - current->pitch = db->buffer.plb.stride; - current->pixels = db->read; - - /* Set the blit function */ - this->UpdateRects = GGI_DirectUpdate; - - /* We're done */ - return(current); + ggi_mode mode = { + 1, + {GGI_AUTO, GGI_AUTO}, + {GGI_AUTO, GGI_AUTO}, + {0, 0}, + GT_AUTO, + {GGI_AUTO, GGI_AUTO} + }; + const ggi_directbuffer *db; + ggi_color pal[256]; + int err; + + fprintf(stderr, "GGI_SetVideoMode()\n"); + + mode.visible.x = mode.virt.x = width; + mode.visible.y = mode.virt.y = height; + + /* Translate requested SDL bit depth into a GGI mode */ + switch (bpp) { + case 1: + mode.graphtype = GT_1BIT; + break; + case 2: + mode.graphtype = GT_2BIT; + break; + case 4: + mode.graphtype = GT_4BIT; + break; + case 8: + mode.graphtype = GT_8BIT; + break; + case 15: + mode.graphtype = GT_15BIT; + break; + case 16: + mode.graphtype = GT_16BIT; + break; + case 24: + mode.graphtype = GT_24BIT; + break; + case 32: + mode.graphtype = GT_32BIT; + break; + default: + SDL_SetError("Unknown SDL bit depth, using GT_AUTO....\n"); + mode.graphtype = GT_AUTO; + } + + /* Validate mode, autodetecting any GGI_AUTO or GT_AUTO fields */ + ggiCheckMode(VIS, &mode); + + /* At this point we should have a valid mode - try to set it */ + err = ggiSetMode(VIS, &mode); + + /* If we couldn't set _any_ modes, something is very wrong */ + if (err) { + SDL_SetError("Can't set a mode!\n"); + ggiClose(VIS); + ggiExit(); + GGI_VideoQuit(NULL); + } + + /* Set a palette for palletized modes */ + if (GT_SCHEME(mode.graphtype) == GT_PALETTE) { + ggiSetColorfulPalette(VIS); + ggiGetPalette(VIS, 0, 1 << bpp, pal); + } + + db = ggiDBGetBuffer(VIS, 0); + + /* Set up the new mode framebuffer */ + current->flags = (SDL_FULLSCREEN | SDL_HWSURFACE); + current->w = mode.virt.x; + current->h = mode.virt.y; + current->pitch = db->buffer.plb.stride; + current->pixels = db->read; + + /* Set the blit function */ + this->UpdateRects = GGI_DirectUpdate; + + /* We're done */ + return (current); } -static int GGI_AllocHWSurface(_THIS, SDL_Surface *surface) +static int +GGI_AllocHWSurface(_THIS, SDL_Surface * surface) { - return(-1); + return (-1); } -static void GGI_FreeHWSurface(_THIS, SDL_Surface *surface) +static void +GGI_FreeHWSurface(_THIS, SDL_Surface * surface) { - return; + return; } -static int GGI_LockHWSurface(_THIS, SDL_Surface *surface) +static int +GGI_LockHWSurface(_THIS, SDL_Surface * surface) { - return(0); + return (0); } -static void GGI_UnlockHWSurface(_THIS, SDL_Surface *surface) +static void +GGI_UnlockHWSurface(_THIS, SDL_Surface * surface) { - return; + return; } -static void GGI_DirectUpdate(_THIS, int numrects, SDL_Rect *rects) +static void +GGI_DirectUpdate(_THIS, int numrects, SDL_Rect * rects) { - int i; - + int i; + /* ggiFlush(VIS); */ - - for (i = 0; i < numrects; i++) - { - ggiFlushRegion(VIS, rects[i].x, rects[i].y, rects[i].w, rects[i].h); - } - return; + + for (i = 0; i < numrects; i++) { + ggiFlushRegion(VIS, rects[i].x, rects[i].y, rects[i].w, rects[i].h); + } + return; } -int GGI_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color *colors) +int +GGI_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color * colors) { - int i; - ggi_color pal[256]; - - /* Set up the colormap */ - for (i = 0; i < ncolors; i++) - { - pal[i].r = (colors[i].r << 8) | colors[i].r; - pal[i].g = (colors[i].g << 8) | colors[i].g; - pal[i].b = (colors[i].b << 8) | colors[i].b; - } - - ggiSetPalette(VIS, firstcolor, ncolors, pal); - - return 1; + int i; + ggi_color pal[256]; + + /* Set up the colormap */ + for (i = 0; i < ncolors; i++) { + pal[i].r = (colors[i].r << 8) | colors[i].r; + pal[i].g = (colors[i].g << 8) | colors[i].g; + pal[i].b = (colors[i].b << 8) | colors[i].b; + } + + ggiSetPalette(VIS, firstcolor, ncolors, pal); + + return 1; } - -void GGI_VideoQuit(_THIS) + +void +GGI_VideoQuit(_THIS) { } -void GGI_FinalQuit(void) +void +GGI_FinalQuit(void) { } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/ggi/SDL_ggivideo.h b/src/video/ggi/SDL_ggivideo.h index 9d687041a..844455469 100644 --- a/src/video/ggi/SDL_ggivideo.h +++ b/src/video/ggi/SDL_ggivideo.h @@ -35,10 +35,10 @@ struct SDL_PrivateVideoData { - ggi_visual_t *ggivis; + ggi_visual_t *ggivis; }; -extern ggi_visual_t VIS; /* FIXME: use the private data struct */ +extern ggi_visual_t VIS; /* FIXME: use the private data struct */ extern int SDL_OpenKeyboard(void); extern void SDL_CloseKeyboard(void); @@ -46,3 +46,4 @@ extern int SDL_OpenMouse(void); extern void SDL_CloseMouse(void); #endif /* _SDL_ggivideo_h */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/glsdl/SDL_glsdl.c b/src/video/glsdl/SDL_glsdl.c new file mode 100644 index 000000000..8662e5cb7 --- /dev/null +++ b/src/video/glsdl/SDL_glsdl.c @@ -0,0 +1,2465 @@ +/* + SDL - Simple DirectMedia Layer + Copyright (C) 1997-2006 Sam Lantinga + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + Sam Lantinga + slouken@libsdl.org +*/ +#include "SDL_config.h" + +/* + * glSDL "SDL-over-OpenGL" video driver implemented by + * David Olofson and + * Stephane Marchesin + */ +#include + +#include "SDL.h" +#include "SDL_error.h" +#include "SDL_video.h" +#include "SDL_mouse.h" +#include "../SDL_sysvideo.h" +#include "../SDL_pixels_c.h" + +#include "SDL_glsdl.h" + +#undef DEBUG_GLSDL +#undef DEBUG_GLSDL_CHOP +#define FAKE_MAXTEXSIZE 256 +#undef GLSDL_GRAPHICAL_DEBUG + +/* Initialization/Query functions */ + +/* Hardware surface functions */ +static int glSDL_SetColors(_THIS, int firstcolor, int ncolors, + SDL_Color * colors); +static int glSDL_AllocHWSurface(_THIS, SDL_Surface * surface); +static int glSDL_LockHWSurface(_THIS, SDL_Surface * surface); +static int glSDL_FlipHWSurface(_THIS, SDL_Surface * surface); +static void glSDL_UnlockHWSurface(_THIS, SDL_Surface * surface); +static void glSDL_FreeHWSurface(_THIS, SDL_Surface * surface); +static int glSDL_FillHWRect(_THIS, SDL_Surface * dst, SDL_Rect * rect, + Uint32 color); +static int glSDL_CheckHWBlit(_THIS, SDL_Surface * src, SDL_Surface * dst); +static int glSDL_SetHWColorKey(_THIS, SDL_Surface * surface, Uint32 key); +static int glSDL_SetHWAlpha(_THIS, SDL_Surface * surface, Uint8 alpha); +static int glSDL_VideoInit(_THIS, SDL_PixelFormat * vformat); +static SDL_Rect **glSDL_ListModes(_THIS, SDL_PixelFormat * format, + Uint32 flags); +static void glSDL_VideoQuit(_THIS); +static void glSDL_UpdateRects(_THIS, int numrects, SDL_Rect * rects); +static SDL_Surface *glSDL_SetVideoMode(_THIS, SDL_Surface * current, + int width, int height, int bpp, + Uint32 flags); + +#define IS_GLSDL_SURFACE(s) ((s) && glSDL_GetTexInfo(s)) + +#define LOGIC_W(s) ( IS_GLSDL_SURFACE(this,s) ? TEXINFO(s)->lw : (s)->w ) +#define LOGIC_H(s) ( IS_GLSDL_SURFACE(this,s) ? TEXINFO(s)->lh : (s)->h ) + +#define GLSDL_NOTEX (~0) + +/* + * Special version for glSDL, which ignores the fake SDL_HWSURFACE + * flags, so we don't have SDL calling us back whenever we want to + * do some internal blitting... + */ +static void +glSDL_SoftBlit(SDL_Surface * src, SDL_Rect * srcrect, + SDL_Surface * dst, SDL_Rect * dstrect) +{ + SDL_BlitInfo info; + + if (srcrect) + if (!srcrect->w || !srcrect->h) + return; + + /* Check to make sure the blit mapping is valid */ + if ((src->map->dst != dst) || + (src->map->dst->format_version != src->map->format_version)) + if (SDL_MapSurface(src, dst) < 0) + return; + + /* Set up the blit information */ + if (srcrect) { + info.s_pixels = (Uint8 *) src->pixels + + (Uint16) srcrect->y * src->pitch + + (Uint16) srcrect->x * src->format->BytesPerPixel; + info.s_width = srcrect->w; + info.s_height = srcrect->h; + } else { + info.s_pixels = (Uint8 *) src->pixels; + info.s_width = src->w; + info.s_height = src->h; + } + info.s_skip = src->pitch - info.s_width * src->format->BytesPerPixel; + if (dstrect) { + info.d_pixels = (Uint8 *) dst->pixels + + (Uint16) dstrect->y * dst->pitch + + (Uint16) dstrect->x * dst->format->BytesPerPixel; + /* + * NOTE: SDL_SoftBlit() uses the 'dstrect' for this! + * This version is more like SDL_BlitSurface(). + */ + info.d_width = srcrect->w; + info.d_height = srcrect->h; + } else { + info.d_pixels = (Uint8 *) dst->pixels; + info.d_width = dst->w; + info.d_height = dst->h; + } + info.d_skip = dst->pitch - info.d_width * dst->format->BytesPerPixel; + info.aux_data = src->map->sw_data->aux_data; + info.src = src->format; + info.table = src->map->table; + info.dst = dst->format; + + src->map->sw_data->blit(&info); +} + + +/* + * Another special version. Doesn't lock/unlock, and doesn't mess + * with flags and stuff. It just converts the surface, period. + * Does not convert into palletized formats. + */ +static SDL_Surface * +glSDL_ConvertSurface(SDL_Surface * surface, + SDL_PixelFormat * format, Uint32 flags) +{ + SDL_Surface *convert; + Uint32 colorkey = 0; + Uint8 alpha = 0; + Uint32 surface_flags; + SDL_Rect bounds; + + /* Create a new surface with the desired format */ + convert = SDL_CreateRGBSurface(flags, + surface->w, surface->h, + format->BitsPerPixel, format->Rmask, + format->Gmask, format->Bmask, + format->Amask); + if (convert == NULL) { + return (NULL); + } + + /* Save the original surface color key and alpha */ + surface_flags = surface->flags; + if ((surface_flags & SDL_SRCCOLORKEY) == SDL_SRCCOLORKEY) { + /* Convert colourkeyed surfaces to RGBA if requested */ + if ((flags & SDL_SRCCOLORKEY) != SDL_SRCCOLORKEY && format->Amask) { + surface_flags &= ~SDL_SRCCOLORKEY; + } else { + colorkey = surface->format->colorkey; + SDL_SetColorKey(surface, 0, 0); + } + } + if ((surface_flags & SDL_SRCALPHA) == SDL_SRCALPHA) { + /* Copy over the alpha channel to RGBA if requested */ + if (format->Amask) { + surface->flags &= ~SDL_SRCALPHA; + } else { + alpha = surface->format->alpha; + SDL_SetAlpha(surface, 0, 0); + } + } + + /* Copy over the image data */ + bounds.x = 0; + bounds.y = 0; + bounds.w = surface->w; + bounds.h = surface->h; + glSDL_SoftBlit(surface, &bounds, convert, &bounds); + + /* Clean up the original surface, and update converted surface */ + if (convert != NULL) { + SDL_SetClipRect(convert, &surface->clip_rect); + } + if ((surface_flags & SDL_SRCCOLORKEY) == SDL_SRCCOLORKEY) { + Uint32 cflags = surface_flags & (SDL_SRCCOLORKEY | SDL_RLEACCELOK); + if (convert != NULL) { + Uint8 keyR, keyG, keyB; + + SDL_GetRGB(colorkey, surface->format, &keyR, &keyG, &keyB); + SDL_SetColorKey(convert, cflags | (flags & SDL_RLEACCELOK), + SDL_MapRGB(convert->format, keyR, keyG, keyB)); + } + SDL_SetColorKey(surface, cflags, colorkey); + } + if ((surface_flags & SDL_SRCALPHA) == SDL_SRCALPHA) { + Uint32 aflags = surface_flags & (SDL_SRCALPHA | SDL_RLEACCELOK); + if (convert != NULL) { + SDL_SetAlpha(convert, aflags | (flags & SDL_RLEACCELOK), alpha); + } + if (format->Amask) { + surface->flags |= SDL_SRCALPHA; + } else { + SDL_SetAlpha(surface, aflags, alpha); + } + } + + /* We're ready to go! */ + return (convert); +} + + +/*---------------------------------------------------------- + Some OpenGL function wrappers + ----------------------------------------------------------*/ + +static struct +{ + int do_blend; + int do_texture; + GLuint texture; + GLenum sfactor, dfactor; +} glstate; + +static void +glSDL_reset(void) +{ + glstate.do_blend = -1; + glstate.do_blend = -1; + glstate.texture = GLSDL_NOTEX; + glstate.sfactor = 0xffffffff; + glstate.dfactor = 0xffffffff; +} + +static __inline__ void +glSDL_do_blend(_THIS, int on) +{ + if (glstate.do_blend == on) + return; + + if (on) + this->glEnable(GL_BLEND); + else + this->glDisable(GL_BLEND); + glstate.do_blend = on; +} + +static __inline__ void +glSDL_do_texture(_THIS, int on) +{ + if (glstate.do_texture == on) + return; + + if (on) + this->glEnable(GL_TEXTURE_2D); + else + this->glDisable(GL_TEXTURE_2D); + glstate.do_texture = on; +} + +static __inline__ void +glSDL_blendfunc(_THIS, GLenum sfactor, GLenum dfactor) +{ + if ((sfactor == glstate.sfactor) && (dfactor == glstate.dfactor)) + return; + + this->glBlendFunc(sfactor, dfactor); + + glstate.sfactor = sfactor; + glstate.dfactor = dfactor; +} + +static __inline__ void +glSDL_texture(_THIS, GLuint tx) +{ + if (tx == glstate.texture) + return; + + this->glBindTexture(GL_TEXTURE_2D, tx); + glstate.texture = tx; +} + + + + +/*---------------------------------------------------------- + glSDL specific data types + ----------------------------------------------------------*/ + +typedef enum +{ + GLSDL_TM_SINGLE, + GLSDL_TM_HORIZONTAL, + GLSDL_TM_VERTICAL, + GLSDL_TM_HUGE +} GLSDL_TileModes; + + +typedef struct private_hwdata +{ + /* Size of surface in logic screen pixels */ + int lw, lh; + + int textures; + GLuint *texture; + int texsize; /* width/height of OpenGL texture */ + GLSDL_TileModes tilemode; + int tilew, tileh; /* At least one must equal texsize! */ + int tilespertex; + SDL_Rect virt; /* Total size of assembled surface */ + + /* Area of surface to upload when/after unlocking */ + SDL_Rect invalid_area; + + int temporary; /* Throw away after one use. */ + + SDL_Surface *next; /* The next Surface in our linked list of hardware surfaces ; == NULL if first surface */ + SDL_Surface *prev; /* The prev Surface in our linked list of hardware surfaces ; == NULL if last surface */ +} private_hwdata; + +/* some function prototypes */ +static void glSDL_Invalidate(SDL_Surface * surface, SDL_Rect * area); +static void glSDL_SetLogicSize(_THIS, SDL_Surface * surface, int w, int h); +static private_hwdata *glSDL_UploadSurface(_THIS, SDL_Surface * surface); +static private_hwdata *glSDL_GetTexInfo(SDL_Surface * surface); +static void glSDL_init_formats(_THIS); +static private_hwdata *glSDL_AddTexInfo(_THIS, SDL_Surface * surface); +static void glSDL_RemoveTexInfo(_THIS, SDL_Surface * surface); +static void glSDL_UnloadTexture(_THIS, private_hwdata * txi); +static int glSDL_BlitGL(_THIS, SDL_Surface * src, + SDL_Rect * srcrect, SDL_Rect * dstrect); + +/* some variables */ +static GLint maxtexsize = -1; +static SDL_PixelFormat *RGBfmt = NULL; +static SDL_PixelFormat *RGBAfmt = NULL; +static void *mirrorbuf = NULL; +/* the raw 888 opengl surface, hidden from the application */ +SDL_Surface *OpenGL_Surface; + +/* pointer to the beggining of the list used for memory allocation */ +SDL_Surface *first = NULL; + +#ifdef DEBUG_GLSDL +static __inline__ int +GLERET(const char *txt) +{ + fprintf(stderr, "glSDL ERROR: '%s'\n", txt); + return -1; +} +static __inline__ void +GLERR(const char *txt) +{ + fprintf(stderr, "glSDL ERROR: '%s'\n", txt); +} +#else +#define GLERET(x) (-1) +#define GLERR(x) +#endif + +static SDL_VideoDevice underlying_device; +static int old_screen_flags; + +/* + * List of video drivers known to support OpenGL + * The purpose of this is to make glSDL "portable" across + * all video backends that support OpenGL + */ +static VideoBootStrap *opengl_bootstrap = +#if SDL_VIDEO_DRIVER_QUARTZ + &QZ_bootstrap; +#elif SDL_VIDEO_DRIVER_X11 + &X11_bootstrap; +#elif SDL_VIDEO_DRIVER_WINDIB + &WINDIB_bootstrap; +#elif SDL_VIDEO_DRIVER_BWINDOW + &BWINDOW_bootstrap; +#elif SDL_VIDEO_DRIVER_TOOLBOX + &TOOLBOX_bootstrap; +#elif SDL_VIDEO_DRIVER_CYBERGRAPHICS + &CGX_bootstrap; +#elif SDL_VIDEO_DRIVER_PHOTON + &ph_bootstrap; +#elif SDL_VIDEO_DRIVER_DC + &DC_bootstrap; +#else + NULL; +#endif + +static int +glSDL_Available(void) +{ +#ifdef DEBUG_GLSDL + fprintf(stderr, "available\n"); +#endif + if (opengl_bootstrap == NULL) + return 0; + return (opengl_bootstrap->available()); +} + +static void +glSDL_DeleteDevice(SDL_VideoDevice * device) +{ + SDL_free(device->hidden); + SDL_free(device); +} + +/* Create a glSDL device */ +static SDL_VideoDevice * +glSDL_CreateDevice(int devindex) +{ + SDL_VideoDevice *device; +#ifdef DEBUG_GLSDL + fprintf(stderr, "entering createdevice\n"); +#endif + + /* Create the device with the underlying driver */ + device = opengl_bootstrap->create(devindex); + + /* Save the video device contents for future use */ + SDL_memcpy(&underlying_device, device, sizeof(SDL_VideoDevice)); + + /* Hook glSDL on the video device */ + device->VideoInit = glSDL_VideoInit; + device->ListModes = glSDL_ListModes; + device->VideoQuit = glSDL_VideoQuit; + device->UpdateRects = glSDL_UpdateRects; + device->FillHWRect = glSDL_FillHWRect; + device->SetHWColorKey = glSDL_SetHWColorKey; + device->SetHWAlpha = glSDL_SetHWAlpha; + device->AllocHWSurface = glSDL_AllocHWSurface; + device->LockHWSurface = glSDL_LockHWSurface; + device->UnlockHWSurface = glSDL_UnlockHWSurface; + device->FlipHWSurface = glSDL_FlipHWSurface; + device->FreeHWSurface = glSDL_FreeHWSurface; + device->CheckHWBlit = glSDL_CheckHWBlit; + device->SetColors = glSDL_SetColors; + device->SetVideoMode = glSDL_SetVideoMode; + device->info.hw_available = 1; + device->info.blit_hw = 1; + device->info.blit_hw_CC = 1; + device->info.blit_hw_A = 1; + device->info.blit_sw = 1; + device->info.blit_sw_CC = 1; + device->info.blit_sw_A = 1; + device->info.blit_fill = 1; + + /* These functions are not supported by glSDL, so we NULLify them */ + device->SetGamma = NULL; + device->GetGamma = NULL; + device->SetGammaRamp = NULL; + device->GetGammaRamp = NULL; + device->ToggleFullScreen = NULL; + + device->free = glSDL_DeleteDevice; + +#ifdef DEBUG_GLSDL + fprintf(stderr, "leaving createdevice\n"); +#endif + + return device; +} + +/* Our bootstraping structure */ +VideoBootStrap glSDL_bootstrap = { + "glSDL", "glSDL - SDL over OpenGL", + glSDL_Available, glSDL_CreateDevice +}; + +static int +glSDL_VideoInit(_THIS, SDL_PixelFormat * vformat) +{ + int r; + printf("glSDL videoinit\n"); +#ifdef DEBUG_GLSDL + fprintf(stderr, "videoinit\n"); +#endif + r = underlying_device.VideoInit(this, vformat); + this->info.hw_available = 1; + this->info.blit_hw = 1; + this->info.blit_hw_CC = 1; + this->info.blit_hw_A = 1; + this->info.blit_sw = 1; + this->info.blit_sw_CC = 1; + this->info.blit_sw_A = 1; + this->info.blit_fill = 1; + + return r; +} + +SDL_Rect ** +glSDL_ListModes(_THIS, SDL_PixelFormat * format, Uint32 flags) +{ + return ((SDL_Rect **) - 1); +} + +static void +glSDL_VideoQuit(_THIS) +{ + SDL_Surface *scr; + + /* free all hwdata structures */ + while (first != NULL) + glSDL_RemoveTexInfo(this, first); + + SDL_free(mirrorbuf); + mirrorbuf = NULL; + + SDL_FreeFormat(RGBfmt); + SDL_FreeFormat(RGBAfmt); + RGBfmt = RGBAfmt = NULL; + + SDL_FreeFormat(this->displayformatalphapixel); + this->displayformatalphapixel = NULL; + + SDL_FreeSurface(OpenGL_Surface); + OpenGL_Surface = NULL; + + /* restore the flags to gracefully exit from fullscreen */ + this->screen->flags = old_screen_flags; + + /* keep the screen */ + scr = this->screen; + + /* we cleaned up our stuff, now restore the underlying video driver */ + SDL_memcpy(this, &underlying_device, sizeof(SDL_VideoDevice)); + + this->screen = scr; + + /* call the underlying video driver's VideoQuit function */ + this->VideoQuit(this); +} + +static SDL_Surface * +glSDL_SetVideoMode(_THIS, SDL_Surface * current, int width, int height, + int bpp, Uint32 flags) +{ + SDL_Surface *hooked_screen; + int i; + int flag_doublebuf = 0; + + if (opengl_bootstrap == NULL) { + GLERR("No bootstrap for glSDL compiled in !\n"); + return NULL; + } + + /* we don't have OpenGL */ + if ((flags & SDL_INTERNALOPENGL) == SDL_INTERNALOPENGL) { + GLERR("OpenGL video modes are not supported by glSDL !\n"); + return (NULL); + } + + /* + * Adjust the flags + */ + flags &= ~SDL_HWPALETTE; + flags |= SDL_INTERNALOPENGL; + + /* remember whether the user requested DOUBLEBUF */ + + if (flags & SDL_DOUBLEBUF) { + SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); + flag_doublebuf = 1; + } else { + SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 0); + flag_doublebuf = 0; + } + + hooked_screen = + underlying_device.SetVideoMode(this, current, width, height, 0, + flags); + + if (!hooked_screen) { + GLERR("Unable to open an OpenGL window !\n"); + return (NULL); + } + + /* save the screen flags for restore time */ + old_screen_flags = hooked_screen->flags; + +#ifdef DEBUG_GLSDL + fprintf(stderr, "got %d bpp\n", bpp); +#endif + + /* setup the public surface format + * glSDL always returns the bpp its asked + */ + switch (bpp) { + case 32: + this->is_32bit = 1; + this->screen = SDL_CreateRGBSurface(flags, width, height, bpp, +#if SDL_BYTEORDER == SDL_LIL_ENDIAN + 0x00FF0000, + 0x0000FF00, 0x000000FF, 0x00000000 +#else + 0x0000FF00, + 0x00FF0000, 0xFF000000, 0x00000000 +#endif + ); + break; + case 24: + this->is_32bit = 0; + this->screen = SDL_CreateRGBSurface(flags, width, height, bpp, +#if SDL_BYTEORDER == SDL_LIL_ENDIAN + 0x00FF0000, + 0x0000FF00, 0x000000FF, 0x00000000 +#else + 0x0000FF00, + 0x00FF0000, 0xFF000000, 0x00000000 +#endif + ); + break; + case 16: + this->is_32bit = 0; + this->screen = SDL_CreateRGBSurface(flags, width, height, bpp, +#if SDL_BYTEORDER == SDL_LIL_ENDIAN + 0x0000F800, + 0x000007E0, 0x0000001F, 0x00000000 +#else + 0x0000001F, + 0x000007E0, 0x0000F800, 0x00000000 +#endif + ); + break; + case 15: + this->is_32bit = 0; + this->screen = SDL_CreateRGBSurface(flags, width, height, bpp, +#if SDL_BYTEORDER == SDL_LIL_ENDIAN + 0x00007C00, + 0x000003E0, 0x0000001F, 0x00000000 +#else + 0x0000001F, + 0x000003E0, 0x00007C00, 0x00000000 +#endif + ); + break; + case 8: + default: + this->is_32bit = 0; + this->screen = + SDL_CreateRGBSurface(flags, width, height, bpp, 0, 0, 0, 0); + /* give it a default palette if 8 bpp + * note : SDL already takes care of the palette for 4 bits & 1 bit surfaces + */ +/* if (bpp==8) + { + this->screen->format->palette->ncolors=255; + SDL_DitherColors(this->screen->format->palette->colors,bpp); + }*/ + break; + } + + /* also, we add SDL_HWSURFACE all the time, and let SDL create a shadow surface accordingly */ + this->screen->flags = + hooked_screen->flags | SDL_HWSURFACE | SDL_INTERNALOPENGL; + /* add SDL_DOUBLEBUF if it was requested */ + if (flag_doublebuf) + this->screen->flags |= SDL_DOUBLEBUF; + + /* Tell SDL the alpha pixel format we'd like to have */ + this->displayformatalphapixel = SDL_AllocFormat(32, +#if SDL_BYTEORDER == SDL_BIG_ENDIAN + 0xFF000000, + 0x00FF0000, + 0x0000FF00, 0x000000FF +#else + 0x000000FF, + 0x0000FF00, + 0x00FF0000, 0xFF000000 +#endif + ); + + /* Now create the raw OpenGL surface */ + OpenGL_Surface = SDL_CreateRGBSurface(flags, width, height, 24, +#if SDL_BYTEORDER == SDL_LIL_ENDIAN + 0x000000FF, + 0x0000FF00, 0x00FF0000, 0x00000000 +#else + 0xFF000000, + 0x00FF0000, 0x0000FF00, 0x00000000 +#endif + ); + + /* Here we have to setup OpenGL funcs ourselves */ +#ifndef __QNXNTO__ +#define SDL_PROC(ret,func,params) \ + do { \ + this->func = SDL_GL_GetProcAddress(#func); \ + if ( ! this->func ) { \ + SDL_SetError("Couldn't load GL function: %s\n", #func); \ + return(NULL); \ + } \ + } while ( 0 ); +#else +#define SDL_PROC(ret,func,params) this->func=func; +#endif /* __QNXNTO__ */ +#include "../SDL_glfuncs.h" +#undef SDL_PROC + + if (this->GL_MakeCurrent(this) < 0) + return (NULL); +#define SDL_PROC(ret,func,params) \ + do { \ + this->func = SDL_GL_GetProcAddress(#func); \ + if ( ! this->func ) { \ + SDL_SetError("Couldn't load GL function: %s\n", #func); \ + return(NULL); \ + } \ + } while ( 0 ); +#include "../SDL_glfuncs.h" +#undef SDL_PROC + + +#ifdef FAKE_MAXTEXSIZE + maxtexsize = FAKE_MAXTEXSIZE; +#else + this->glGetIntegerv(GL_MAX_TEXTURE_SIZE, &maxtexsize); +#endif +#ifdef DEBUG_GLSDL + fprintf(stderr, "glSDL: Max texture size: %d\n", maxtexsize); +#endif + + glSDL_init_formats(this); + + if (flag_doublebuf) + this->glDrawBuffer(GL_BACK); + else + this->glDrawBuffer(GL_FRONT); + + this->glDisable(GL_DITHER); + + if (glSDL_AddTexInfo(this, this->screen) < 0) { + GLERR("HookDevice() failed to add info to screen surface!"); + return NULL; + } + + glSDL_SetLogicSize(this, this->screen, this->screen->w, this->screen->h); + + glSDL_do_texture(this, 0); + glSDL_do_blend(this, 0); + + for (i = 0; i < 1 + flag_doublebuf; ++i) { + this->glBegin(GL_TRIANGLE_FAN); + this->glColor3ub(0, 0, 0); + this->glVertex2i(0, 0); + this->glVertex2i(this->screen->w, 0); + this->glVertex2i(this->screen->w, this->screen->h); + this->glVertex2i(0, this->screen->h); + this->glEnd(); + if (!i) + this->GL_SwapBuffers(this); + } + + mirrorbuf = SDL_malloc(this->screen->h * this->screen->pitch); + if (!mirrorbuf) { + GLERR("HookDevice() failed to allocate temp buffer for mirroring!"); + return NULL; + } + + return this->screen; +} + +static int +glSDL_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color * colors) +{ + /* We don't need to fill this one */ + return 0; +} + + +#ifdef DEBUG_GLSDL +static void +glSDL_print_glerror(_THIS, int point) +{ + const char *err = ""; + switch (this->glGetError()) { + case GL_NO_ERROR: + return; + case GL_INVALID_ENUM: + err = "GL_INVALID_ENUM"; + break; + case GL_INVALID_VALUE: + err = "GL_INVALID_VALUE"; + break; + case GL_INVALID_OPERATION: + err = "GL_INVALID_OPERATION"; + break; + case GL_STACK_OVERFLOW: + err = "GL_STACK_OVERFLOW"; + break; + case GL_STACK_UNDERFLOW: + err = "GL_STACK_UNDERFLOW"; + break; + case GL_OUT_OF_MEMORY: + err = "GL_OUT_OF_MEMORY"; + default: + break; + } + fprintf(stderr, "OpenGL error \"%s\" at point %d.\n", err, point); +} +#endif + +/* Get texinfo for a surface. */ +static __inline__ private_hwdata * +glSDL_GetTexInfo(SDL_Surface * surface) +{ + if (!surface) + return NULL; + return surface->hwdata; +} + + +/* Allocate a "blank" texinfo for a suface. */ +static private_hwdata * +glSDL_AllocTexInfo(SDL_Surface * surface) +{ + private_hwdata *txi; + if (!surface) + return NULL; + + txi = glSDL_GetTexInfo(surface); + if (txi) + return txi; /* There already is one! --> */ + + /* ...and hook a new texinfo struct up to it. */ + txi = (private_hwdata *) SDL_calloc(1, sizeof(private_hwdata)); + if (!txi) { + GLERR("AllocTexInfo(): Failed allocating TexInfo struct!"); + return NULL; + } + txi->temporary = 1; +#ifdef DEBUG_GLSDL + fprintf(stderr, "glSDL: Allocated TexInfo %p.\n", txi); +#endif + return txi; +} + + +static void +glSDL_FreeTexInfo(_THIS, private_hwdata * txi) +{ + if (!txi) + return; + + glSDL_UnloadTexture(this, txi); + SDL_free(txi->texture); + SDL_free(txi); +#ifdef DEBUG_GLSDL + fprintf(stderr, "glSDL: Freed TexInfo %p.\n", txi); +#endif +} + + +/* Detach and free the texinfo of a surface. */ +static void +glSDL_RemoveTexInfo(_THIS, SDL_Surface * surface) +{ + SDL_Surface *next, *prev; + if (!glSDL_GetTexInfo(surface)) + return; + + /* maintain our doubly linked list */ + next = surface->hwdata->next; + prev = surface->hwdata->prev; + if (prev != NULL) { + prev->hwdata->next = next; + } else { + first = next; + } + if (next != NULL) { + next->hwdata->prev = prev; + } + + glSDL_FreeTexInfo(this, surface->hwdata); + surface->hwdata = NULL; +} + + +/* + * Calculate chopping/tiling of a surface to + * fit it into the smallest possible OpenGL + * texture. + */ +static int +glSDL_CalcChop(private_hwdata * txi) +{ + int rows, vw, vh; + int vertical = 0; + int texsize; + int lastw, lasth, minsize; + + vw = txi->virt.w; + vh = txi->virt.h; + +#ifdef DEBUG_GLSDL_CHOP + fprintf(stderr, "w=%d, h=%d ", vw, vh); +#endif + if (vh > vw) { + int t = vw; + vw = vh; + vh = t; + vertical = 1; +#ifdef DEBUG_GLSDL_CHOP + fprintf(stderr, "(vertical) \t"); +#endif + } + + /* + * Check whether this is a "huge" surface - at least one dimension + * must be <= than the maximum texture size, or we'll have to chop + * in both directions. + */ +#ifdef DEBUG_GLSDL + if (maxtexsize < 0) + return GLERET("glSDL_CalcChop() called before OpenGL init!"); +#endif + if (vh > maxtexsize) { + /* + * Very simple hack for now; we just tile + * both ways with maximum size textures. + */ + texsize = maxtexsize; + + txi->tilemode = GLSDL_TM_HUGE; + txi->texsize = texsize; + txi->tilew = texsize; + txi->tileh = texsize; + txi->tilespertex = 1; + + /* Calculate number of textures needed */ + txi->textures = (vw + texsize - 1) / texsize; + txi->textures *= (vh + texsize - 1) / texsize; + txi->texture = SDL_malloc(txi->textures * sizeof(int)); + SDL_memset(txi->texture, -1, txi->textures * sizeof(int)); +#ifdef DEBUG_GLSDL + fprintf(stderr, "two-way tiling; textures=%d\n", txi->textures); +#endif + if (!txi->texture) { + fprintf(stderr, "glSDL: INTERNAL ERROR: Failed to allocate" + " texture name table!\n"); + return -3; + } + return 0; + } + + /* Calculate minimum size */ + rows = 1; + lastw = vw; + lasth = vh; + minsize = lastw > lasth ? lastw : lasth; + while (1) { + int w, h, size; + ++rows; + w = vw / rows; + h = rows * vh; + size = w > h ? w : h; + if (size >= minsize) { + --rows; + break; + } + lastw = w; + lasth = h; + minsize = size; + } + if (minsize > maxtexsize) { + /* Handle multiple textures for very wide/tall surfaces. */ + minsize = maxtexsize; + rows = (vw + minsize - 1) / minsize; + } +#ifdef DEBUG_GLSDL_CHOP + fprintf(stderr, "==> minsize=%d ", minsize); + fprintf(stderr, "(rows=%d) \t", rows); +#endif + + /* Recalculate with nearest higher power-of-2 width. */ + for (texsize = 1; texsize < minsize; texsize <<= 1); + txi->texsize = texsize; + rows = (vw + texsize - 1) / texsize; +#ifdef DEBUG_GLSDL_CHOP + fprintf(stderr, "==> texsize=%d (rows=%d) \t", texsize, rows); +#endif + + /* Calculate number of tiles per texture */ + txi->tilespertex = txi->texsize / vh; +#ifdef DEBUG_GLSDL_CHOP + fprintf(stderr, "tilespertex=%d \t", txi->tilespertex); +#endif + + /* Calculate number of textures needed */ + txi->textures = (rows + txi->tilespertex - 1) / txi->tilespertex; + txi->texture = (GLuint *) SDL_malloc(txi->textures * sizeof(GLuint)); + SDL_memset(txi->texture, GLSDL_NOTEX, txi->textures * sizeof(GLuint)); +#ifdef DEBUG_GLSDL_CHOP + fprintf(stderr, "textures=%d, ", txi->textures); +#endif + if (!txi->texture) + return GLERET("Failed to allocate texture name table!"); + + /* Set up tile size. (Only one axis supported here!) */ + if (1 == rows) { + txi->tilemode = GLSDL_TM_SINGLE; + if (vertical) { + txi->tilew = vh; + txi->tileh = vw; + } else { + txi->tilew = vw; + txi->tileh = vh; + } + } else if (vertical) { + txi->tilemode = GLSDL_TM_VERTICAL; + txi->tilew = vh; + txi->tileh = texsize; + } else { + txi->tilemode = GLSDL_TM_HORIZONTAL; + txi->tilew = texsize; + txi->tileh = vh; + } + +#ifdef DEBUG_GLSDL_CHOP + fprintf(stderr, "tilew=%d, tileh=%d\n", txi->tilew, txi->tileh); +#endif + return 0; +} + + +/* Create a temporary TexInfo struct for an SDL_Surface */ +static private_hwdata * +glSDL_CreateTempTexInfo(_THIS, SDL_Surface * surface) +{ + private_hwdata *txi; + if (!surface) { + GLERR("CreateTempTexInfo(); no surface!"); + return NULL; + } + if (IS_GLSDL_SURFACE(surface)) + return glSDL_GetTexInfo(surface); /* Do nothing */ + + txi = glSDL_AllocTexInfo(surface); + if (!txi) { + GLERR("CreateTempTexInfo(); Could not alloc TexInfo!"); + return NULL; + } + txi->virt.w = txi->lw = surface->w; + txi->virt.h = txi->lh = surface->h; + + if (glSDL_CalcChop(txi) < 0) { + glSDL_FreeTexInfo(this, txi); + GLERR("CreateTempTexInfo(); CalcChop() failed!"); + return NULL; + } + + return txi; +} + +/* Add a glSDL_TexInfo struct to an SDL_Surface */ +static private_hwdata * +glSDL_AddTexInfo(_THIS, SDL_Surface * surface) +{ + private_hwdata *txi = glSDL_CreateTempTexInfo(this, surface); + if (!txi) + return NULL; + + /* Connect the surface to the new TexInfo. */ + txi->temporary = 0; + surface->hwdata = txi; + + /* add this new surface in front of the list of hw surfaces */ + txi->next = first; + txi->prev = NULL; + first = surface; + if (txi->next != NULL) { + txi->next->hwdata->prev = surface; + } + + SDL_SetClipRect(surface, &txi->virt); + return txi; +} + + +/* Create a surface of the prefered OpenGL RGB texture format */ +/*static SDL_Surface *glSDL_CreateRGBSurface(int w, int h) +{ + SDL_Surface *s; + Uint32 rmask, gmask, bmask; + int bits = 24; +#if SDL_BYTEORDER == SDL_LIL_ENDIAN + rmask = 0x000000FF; + gmask = 0x0000FF00; + bmask = 0x00FF0000; +#else + rmask = 0x00FF0000; + gmask = 0x0000FF00; + bmask = 0x000000FF; +#endif + s = SDL_CreateRGBSurface(SDL_SWSURFACE, w, h, + bits, rmask, gmask, bmask, 0); + if(s) + s->flags |= SDL_HWACCEL; + + return s; +} +*/ + +/* Create a surface of the prefered OpenGL RGBA texture format */ +static SDL_Surface * +glSDL_CreateRGBASurface(int w, int h) +{ + SDL_Surface *s; + Uint32 rmask, gmask, bmask, amask; + int bits = 32; +#if SDL_BYTEORDER == SDL_LIL_ENDIAN + rmask = 0x000000FF; + gmask = 0x0000FF00; + bmask = 0x00FF0000; + amask = 0xFF000000; +#else + rmask = 0xFF000000; + gmask = 0x00FF0000; + bmask = 0x0000FF00; + amask = 0x000000FF; +#endif + s = SDL_CreateRGBSurface(SDL_SWSURFACE, w, h, + bits, rmask, gmask, bmask, amask); + if (s) + s->flags |= SDL_HWACCEL; + + return s; +} + + +static void +glSDL_init_formats(_THIS) +{ + RGBfmt = SDL_AllocFormat(24, +#if SDL_BYTEORDER == SDL_LIL_ENDIAN + 0x000000FF, 0x0000FF00, 0x00FF0000, 0); +#else + 0x00FF0000, 0x0000FF00, 0x000000FF, 0); +#endif + RGBAfmt = SDL_AllocFormat(32, +#if SDL_BYTEORDER == SDL_LIL_ENDIAN + 0x000000FF, 0x0000FF00, 0x00FF0000, 0xFF000000); +#else + 0xFF000000, 0x00FF0000, 0x0000FF00, 0x000000FF); +#endif +} + + +static int +glSDL_FormatIsOk(SDL_Surface * surface) +{ + SDL_PixelFormat *pf; + if (!surface) + return 1; /* Well, there ain't much we can do anyway... */ + + pf = surface->format; + + /* Colorkeying requires an alpha channel! */ + if (surface->flags & SDL_SRCCOLORKEY) + if (!pf->Amask) + return 0; + + /* We need pitch == (width * BytesPerPixel) for glTex[Sub]Image2D() */ + if (surface->pitch != (surface->w * pf->BytesPerPixel)) + return 0; + + if (pf->Amask) { + if (pf->BytesPerPixel != RGBAfmt->BytesPerPixel) + return 0; + if (pf->Rmask != RGBAfmt->Rmask) + return 0; + if (pf->Gmask != RGBAfmt->Gmask) + return 0; + if (pf->Bmask != RGBAfmt->Bmask) + return 0; + if (pf->Amask != RGBAfmt->Amask) + return 0; + } else { + if (pf->BytesPerPixel != RGBfmt->BytesPerPixel) + return 0; + if (pf->Rmask != RGBfmt->Rmask) + return 0; + if (pf->Gmask != RGBfmt->Gmask) + return 0; + if (pf->Bmask != RGBfmt->Bmask) + return 0; + } + return 1; +} + +static void +glSDL_key2alpha(SDL_Surface * surface) +{ + int x, y; + Uint32 ckey = surface->format->colorkey; + +#ifdef DEBUG_GLSDL + fprintf(stderr, "glSDL_key2alpha()\n"); +#endif + for (y = 0; y < surface->h; ++y) { + Uint32 *px = + (Uint32 *) ((char *) surface->pixels + y * surface->pitch); + for (x = 0; x < surface->w; ++x) + if (px[x] == ckey) + px[x] = 0; + } +} + + + +/*---------------------------------------------------------- + SDL style API + ----------------------------------------------------------*/ + +static int +glSDL_FlipHWSurface(_THIS, SDL_Surface * surface) +{ +#ifdef GLSDL_GRAPHICAL_DEBUG + this->glDisable(GL_TEXTURE_2D); + this->glBegin(GL_LINE_LOOP); + this->glColor4ub(0, 0, 255, 128); + this->glVertex2i(0, 0); + this->glVertex2i(surface->w, 0); + this->glVertex2i(surface->w, surface->h); + this->glVertex2i(0, surface->h); + this->glEnd(); + this->glEnable(GL_TEXTURE_2D); +#endif + if (this->screen->flags & SDL_DOUBLEBUF) + this->GL_SwapBuffers(this); + else + this->glFinish(); + return 0; +} + + +static void +glSDL_UpdateRects(_THIS, int numrects, SDL_Rect * rects) +{ +#ifdef GLSDL_GRAPHICAL_DEBUG + int i; + this->glDisable(GL_TEXTURE_2D); + for (i = 0; i < numrects; i++) { + this->glColor4ub(255, 0, 0, 128); + this->glBegin(GL_LINE_LOOP); + this->glVertex2i(rects[i].x, rects[i].y); + this->glVertex2i(rects[i].x + rects[i].w, rects[i].y); + this->glVertex2i(rects[i].x + rects[i].w, rects[i].y + rects[i].h); + this->glVertex2i(rects[i].x, rects[i].y + rects[i].h); + this->glEnd(); + } + this->glEnable(GL_TEXTURE_2D); +#endif + if (this->screen->flags & SDL_DOUBLEBUF) + this->GL_SwapBuffers(this); + else + this->glFinish(); +} + + +static int +glSDL_AllocHWSurface(_THIS, SDL_Surface * surface) +{ + surface->flags |= (SDL_HWSURFACE | SDL_HWACCEL); + + surface->pixels = SDL_malloc(surface->h * surface->pitch); + if (surface->pixels == NULL) { + SDL_FreeSurface(surface); + SDL_OutOfMemory(); + return (-1); + } + SDL_memset(surface->pixels, 0, surface->h * surface->pitch); + return 0; +} + + +static void +glSDL_FreeHWSurface(_THIS, SDL_Surface * surface) +{ + if (!surface) + return; + glSDL_RemoveTexInfo(this, surface); +} + + +static int +glSDL_LockHWSurface(_THIS, SDL_Surface * surface) +{ + int y; + + if (!surface) + return -1; + +#ifdef DEBUG_GLSDL + fprintf(stderr, "glSDL: Lock Surface.\n"); +#endif + + if (SDL_VideoSurface == surface) { + glSDL_Invalidate(surface, NULL); + this->glPixelStorei(GL_UNPACK_ROW_LENGTH, + surface->pitch / surface->format->BytesPerPixel); + this->glReadPixels(0, 0, OpenGL_Surface->w, OpenGL_Surface->h, + GL_RGB, GL_UNSIGNED_BYTE, OpenGL_Surface->pixels); + for (y = 0; y < OpenGL_Surface->h / 2; ++y) { + void *upper = (Uint8 *) OpenGL_Surface->pixels + + OpenGL_Surface->pitch * y; + void *lower = (Uint8 *) OpenGL_Surface->pixels + + OpenGL_Surface->pitch * (OpenGL_Surface->h - y - 1); + SDL_memcpy(mirrorbuf, upper, OpenGL_Surface->pitch); + SDL_memcpy(upper, lower, OpenGL_Surface->pitch); + SDL_memcpy(lower, mirrorbuf, OpenGL_Surface->pitch); + } + /* the mapping has to be invalidated on 8bpp video surfaces in case of a hw palette change. + * Now if someone could tell me why this is not handled by SDL... */ + if (SDL_VideoSurface->format->BitsPerPixel == 8) + SDL_InvalidateMap(OpenGL_Surface->map); + + /* convert this raw surface to the application-requested format + * FIXME this is sometimes overkill, we could use glPixelStore smartly + * But this would be slow anyway :) */ + + glSDL_SoftBlit(OpenGL_Surface, NULL, SDL_VideoSurface, NULL); + } else + glSDL_Invalidate(surface, NULL); + + return 0; +} + + +static void +glSDL_UnlockHWSurface(_THIS, SDL_Surface * surface) +{ + private_hwdata *txi; + + if (!surface) + return; + + /* upload this surface ONLY if this is a glSDL surface + * because sometimes (during displayformating for ex.) surfaces are unlocked that aren't glSDL + */ + if (!IS_GLSDL_SURFACE(surface)) + return; + +#ifdef DEBUG_GLSDL + fprintf(stderr, "glSDL: Unlock Surface.\n"); +#endif + + txi = glSDL_UploadSurface(this, surface); + + if (!txi) { + GLERR("glSDL_UnlockHWSurface() failed to upload surface!"); + return; + } + if (txi->temporary) { + GLERR + ("Weirdness... glSDL_UnlockHWSurface() got a temporary TexInfo."); + return; + } + if (surface == SDL_VideoSurface) + glSDL_BlitGL(this, SDL_VideoSurface, NULL, NULL); +} + + +static int +glSDL_SetHWColorKey(_THIS, SDL_Surface * surface, Uint32 key) +{ + /* + * If an application does this *after* SDL_DisplayFormat, + * we're basically screwed, unless we want to do an + * in-place surface conversion hack here. + * + * What we do is just kill the glSDL texinfo... No big + * deal in most cases, as glSDL only converts once anyway, + * *unless* you keep modifying the surface. + */ + if (IS_GLSDL_SURFACE(surface)) + glSDL_RemoveTexInfo(this, surface); + return 0; +} + + +static int +glSDL_SetHWAlpha(_THIS, SDL_Surface * surface, Uint8 alpha) +{ + /* + * If an application does this *after* SDL_DisplayFormat, + * we're basically screwed, unless we want to do an + * in-place surface conversion hack here. + * + * What we do is just kill the glSDL texinfo... No big + * deal in most cases, as glSDL only converts once anyway, + * *unless* you keep modifying the surface. + */ + if (IS_GLSDL_SURFACE(surface)) + glSDL_RemoveTexInfo(this, surface); + return 0; +} + +static SDL_bool +glSDL_SetClipRect(_THIS, SDL_Surface * surface, SDL_Rect * rect) +{ + SDL_bool res; + if (!surface) + return SDL_FALSE; + + res = SDL_SetClipRect(surface, rect); + if (!res) + return SDL_FALSE; + + rect = &surface->clip_rect; + + if (surface == SDL_VideoSurface) { + SDL_Rect r; + float xscale, yscale; + private_hwdata *txi; + + r.x = rect->x; + r.y = rect->y; + r.w = rect->w; + r.h = rect->h; + SDL_SetClipRect(surface, rect); + + txi = glSDL_GetTexInfo(surface); + if (!txi) + return GLERET("SetClipRect(): Could not get TexInfo!"); + + this->glViewport(rect->x, + surface->h - (rect->y + rect->h), rect->w, rect->h); + /* + * Note that this projection is upside down in + * relation to the OpenGL coordinate system. + */ + this->glMatrixMode(GL_PROJECTION); + this->glLoadIdentity(); + xscale = (float) txi->lw / (float) surface->w; + yscale = (float) txi->lh / (float) surface->h; + this->glOrtho(xscale * (float) rect->x, + xscale * (float) (rect->w + rect->x), + yscale * (float) (rect->h + rect->y), + yscale * (float) rect->y, -1.0, 1.0); + return SDL_TRUE; + } + return res; +} + +static int +glSDL_BlitFromGL(_THIS, SDL_Rect * srcrect, + SDL_Surface * dst, SDL_Rect * dstrect) +{ + SDL_Rect sr, dr; + + /* In case the destination has an OpenGL texture... */ + glSDL_Invalidate(dst, dstrect); + + /* Abuse the fake screen buffer a little. */ + this->glPixelStorei(GL_UNPACK_ROW_LENGTH, SDL_VideoSurface->pitch / + SDL_VideoSurface->format->BytesPerPixel); + if (srcrect) + this->glReadPixels(srcrect->x, + OpenGL_Surface->h - (srcrect->y + srcrect->h - 1), + srcrect->w, srcrect->h, GL_RGB, GL_UNSIGNED_BYTE, + OpenGL_Surface->pixels); + else + this->glReadPixels(0, 0, OpenGL_Surface->w, OpenGL_Surface->h, + GL_RGB, GL_UNSIGNED_BYTE, OpenGL_Surface->pixels); + sr = *srcrect; + dr = *dstrect; + glSDL_SoftBlit(OpenGL_Surface, &sr, dst, &dr); + return 0; +} + +static __inline__ void +glSDL_BlitGL_single(_THIS, private_hwdata * txi, + float sx1, float sy1, SDL_Rect * dst, unsigned char alpha) +{ + float sx2, sy2, texscale; + if (!txi->textures) + return; + if (-1 == txi->texture[0]) + return; + glSDL_texture(this, txi->texture[0]); + + texscale = 1.0 / (float) txi->texsize; + sx2 = (sx1 + (float) dst->w) * texscale; + sy2 = (sy1 + (float) dst->h) * texscale; + sx1 *= texscale; + sy1 *= texscale; + +#ifdef GLSDL_GRAPHICAL_DEBUG + this->glDisable(GL_TEXTURE_2D); + this->glBegin(GL_LINE_LOOP); + this->glColor4ub(0, 255, 0, 128); + this->glVertex2i(dst->x, dst->y); + this->glVertex2i(dst->x + dst->w, dst->y); + this->glVertex2i(dst->x + dst->w, dst->y + dst->h); + this->glVertex2i(dst->x, dst->y + dst->h); + this->glEnd(); + this->glEnable(GL_TEXTURE_2D); +#endif + + this->glBegin(GL_TRIANGLE_FAN); + this->glColor4ub(255, 255, 255, alpha); + this->glTexCoord2f(sx1, sy1); + this->glVertex2i(dst->x, dst->y); + this->glTexCoord2f(sx2, sy1); + this->glVertex2i(dst->x + dst->w, dst->y); + this->glTexCoord2f(sx2, sy2); + this->glVertex2i(dst->x + dst->w, dst->y + dst->h); + this->glTexCoord2f(sx1, sy2); + this->glVertex2i(dst->x, dst->y + dst->h); + this->glEnd(); +} + + +static void +glSDL_BlitGL_htile(_THIS, private_hwdata * txi, + float sx1, float sy1, SDL_Rect * dst, unsigned char alpha) +{ + int tex; + float tile, sx2, sy2, yo; + float texscale = 1.0 / (float) txi->texsize; + float tileh = (float) txi->tileh * texscale; + sx2 = (sx1 + (float) dst->w) * texscale; + sy2 = (sy1 + (float) dst->h) * texscale; + sx1 *= texscale; + sy1 *= texscale; + tile = floor(sx1); + tex = (int) tile / txi->tilespertex; + yo = ((int) tile % txi->tilespertex) * tileh; + + if (tex >= txi->textures) + return; + if (-1 == txi->texture[tex]) + return; + glSDL_texture(this, txi->texture[tex]); + + while (tile < sx2) { + int tdx1 = dst->x; + int tdx2 = dst->x + dst->w; + float tsx1 = sx1 - tile; + float tsx2 = sx2 - tile; + + /* Clip to current tile */ + if (tsx1 < 0.0) { + tdx1 -= tsx1 * txi->texsize; + tsx1 = 0.0; + } + if (tsx2 > 1.0) { + tdx2 -= (tsx2 - 1.0) * txi->texsize; + tsx2 = 1.0; + } + + /* Maybe select next texture? */ + if (yo + tileh > 1.0) { + ++tex; + if (tex >= txi->textures) + return; + if (-1 == txi->texture[tex]) + return; + glSDL_texture(this, txi->texture[tex]); + yo = 0.0; + } +#ifdef GLSDL_GRAPHICAL_DEBUG + this->glDisable(GL_TEXTURE_2D); + this->glBegin(GL_LINE_LOOP); + this->glColor4ub(0, 255, 0, 128); + this->glVertex2i(tdx1, dst->y); + this->glVertex2i(tdx2, dst->y); + this->glVertex2i(tdx2, dst->y + dst->h); + this->glVertex2i(tdx1, dst->y + dst->h); + this->glEnd(); + this->glEnable(GL_TEXTURE_2D); +#endif + + this->glBegin(GL_TRIANGLE_FAN); + this->glColor4ub(255, 255, 255, alpha); + this->glTexCoord2f(tsx1, yo + sy1); + this->glVertex2i(tdx1, dst->y); + this->glTexCoord2f(tsx2, yo + sy1); + this->glVertex2i(tdx2, dst->y); + this->glTexCoord2f(tsx2, yo + sy2); + this->glVertex2i(tdx2, dst->y + dst->h); + this->glTexCoord2f(tsx1, yo + sy2); + this->glVertex2i(tdx1, dst->y + dst->h); + this->glEnd(); + tile += 1.0; + yo += tileh; + } +} + + +static void +glSDL_BlitGL_vtile(_THIS, private_hwdata * txi, + float sx1, float sy1, SDL_Rect * dst, unsigned char alpha) +{ + int tex; + float tile, sx2, sy2, xo; + float texscale = 1.0 / (float) txi->texsize; + float tilew = (float) txi->tilew * texscale; + sx2 = (sx1 + (float) dst->w) * texscale; + sy2 = (sy1 + (float) dst->h) * texscale; + sx1 *= texscale; + sy1 *= texscale; + tile = floor(sy1); + tex = (int) tile / txi->tilespertex; + xo = ((int) tile % txi->tilespertex) * tilew; + + if (tex >= txi->textures) + return; + if (-1 == txi->texture[tex]) + return; + glSDL_texture(this, txi->texture[tex]); + + while (tile < sy2) { + int tdy1 = dst->y; + int tdy2 = dst->y + dst->h; + float tsy1 = sy1 - tile; + float tsy2 = sy2 - tile; + + /* Clip to current tile */ + if (tsy1 < 0.0) { + tdy1 -= tsy1 * txi->texsize; + tsy1 = 0.0; + } + if (tsy2 > 1.0) { + tdy2 -= (tsy2 - 1.0) * txi->texsize; + tsy2 = 1.0; + } + + /* Maybe select next texture? */ + if (xo + tilew > 1.0) { + ++tex; + if (tex >= txi->textures) + return; + if (-1 == txi->texture[tex]) + return; + glSDL_texture(this, txi->texture[tex]); + xo = 0.0; + } +#ifdef GLSDL_GRAPHICAL_DEBUG + this->glDisable(GL_TEXTURE_2D); + this->glBegin(GL_LINE_LOOP); + this->glColor4ub(0, 255, 0, 128); + this->glVertex2i(dst->x, tdy1); + this->glVertex2i(dst->x + dst->w, tdy1); + this->glVertex2i(dst->x + dst->w, tdy2); + this->glVertex2i(dst->x, tdy2); + this->glEnd(); + this->glEnable(GL_TEXTURE_2D); +#endif + + this->glBegin(GL_TRIANGLE_FAN); + this->glColor4ub(255, 255, 255, alpha); + this->glTexCoord2f(xo + sx1, tsy1); + this->glVertex2i(dst->x, tdy1); + this->glTexCoord2f(xo + sx2, tsy1); + this->glVertex2i(dst->x + dst->w, tdy1); + this->glTexCoord2f(xo + sx2, tsy2); + this->glVertex2i(dst->x + dst->w, tdy2); + this->glTexCoord2f(xo + sx1, tsy2); + this->glVertex2i(dst->x, tdy2); + this->glEnd(); + + tile += 1.0; + xo += tilew; + } +} + + +static void +glSDL_BlitGL_hvtile(_THIS, SDL_Surface * src, private_hwdata * txi, + float sx1, float sy1, SDL_Rect * dst, unsigned char alpha) +{ + int x, y, last_tex, tex; + float sx2, sy2; + float texscale = 1.0 / (float) txi->texsize; + int tilesperrow = (src->w + txi->tilew - 1) / txi->tilew; + sx2 = (sx1 + (float) dst->w) * texscale; + sy2 = (sy1 + (float) dst->h) * texscale; + sx1 *= texscale; + sy1 *= texscale; + + last_tex = tex = floor(sy1) * tilesperrow + floor(sx1); + if (tex >= txi->textures) + return; + if (-1 == txi->texture[tex]) + return; + glSDL_texture(this, txi->texture[tex]); + + for (y = floor(sy1); y < sy2; ++y) { + int tdy1 = dst->y; + int tdy2 = dst->y + dst->h; + float tsy1 = sy1 - y; + float tsy2 = sy2 - y; + + /* Clip to current tile */ + if (tsy1 < 0.0) { + tdy1 -= tsy1 * txi->texsize; + tsy1 = 0.0; + } + if (tsy2 > 1.0) { + tdy2 -= (tsy2 - 1.0) * txi->texsize; + tsy2 = 1.0; + } + for (x = floor(sx1); x < sx2; ++x) { + int tdx1 = dst->x; + int tdx2 = dst->x + dst->w; + float tsx1 = sx1 - x; + float tsx2 = sx2 - x; + + /* Clip to current tile */ + if (tsx1 < 0.0) { + tdx1 -= tsx1 * txi->texsize; + tsx1 = 0.0; + } + if (tsx2 > 1.0) { + tdx2 -= (tsx2 - 1.0) * txi->texsize; + tsx2 = 1.0; + } + + /* Select texture */ + tex = y * tilesperrow + x; + if (tex != last_tex) { + if (tex >= txi->textures) + return; + if (-1 == txi->texture[tex]) + return; + glSDL_texture(this, txi->texture[tex]); + last_tex = tex; + } +#ifdef GLSDL_GRAPHICAL_DEBUG + this->glDisable(GL_TEXTURE_2D); + this->glBegin(GL_LINE_LOOP); + this->glColor4ub(0, 255, 0, 128); + this->glVertex2i(tdx1, tdy1); + this->glVertex2i(tdx2, tdy1); + this->glVertex2i(tdx2, tdy2); + this->glVertex2i(tdx1, tdy2); + this->glEnd(); + this->glEnable(GL_TEXTURE_2D); +#endif + + this->glBegin(GL_TRIANGLE_FAN); + this->glColor4ub(255, 255, 255, alpha); + this->glTexCoord2f(tsx1, tsy1); + this->glVertex2i(tdx1, tdy1); + this->glTexCoord2f(tsx2, tsy1); + this->glVertex2i(tdx2, tdy1); + this->glTexCoord2f(tsx2, tsy2); + this->glVertex2i(tdx2, tdy2); + this->glTexCoord2f(tsx1, tsy2); + this->glVertex2i(tdx1, tdy2); + this->glEnd(); + } + } +} + +/* + * Calculate the actual blit rectangle and source offset + * for a blit from a rectangle in a surface with specified + * size to a surface with a cliprect. + * + * In: rect source rectangle + * w, h source surface size + * (x, y) destination coordinate + * clip destination clip rectangle + * + * Out: (x, y) source top-left offset + * rect destination rectangle + * + * Returns 1 if the result is visible, otherwise 0. + */ +static __inline__ int +blitclip(SDL_Rect * rect, int w, int h, int *x, int *y, SDL_Rect * clip) +{ + int sx1, sy1, sx2, sy2; + int dx1, dy1, dx2, dy2; + + /* Get source and destination coordinates */ + sx1 = rect->x; + sy1 = rect->y; + sx2 = sx1 + rect->w; + sy2 = sy1 + rect->h; + dx1 = *x; + dy1 = *y; + + /* Keep source rect inside source surface */ + if (sx1 < 0) { + dx1 -= sx1; + sx1 = 0; + } + if (sy1 < 0) { + dy1 -= sy1; + sy1 = 0; + } + if (sx2 > w) + sx2 = w; + if (sy2 > h) + sy2 = h; + + /* Cull blits from void space */ + if (sx1 >= sx2 || sy1 >= sy2) + return 0; + + /* Calculate destination lower-right */ + dx2 = dx1 + (sx2 - sx1); + dy2 = dy1 + (sy2 - sy1); + + /* Clip to destination cliprect */ + if (dx1 < clip->x) { + sx1 += clip->x - dx1; + dx1 = clip->x; + } + if (dy1 < clip->y) { + sy1 += clip->y - dy1; + dy1 = clip->y; + } + if (dx2 > clip->x + clip->w) + dx2 = clip->x + clip->w; + if (dy2 > clip->y + clip->h) + dy2 = clip->y + clip->h; + + /* Cull nop/off-screen blits */ + if (dx1 >= dx2 || dy1 >= dy2) + return 0; + + *x = sx1; + *y = sy1; + rect->x = dx1; + rect->y = dy1; + rect->w = dx2 - dx1; + rect->h = dy2 - dy1; + return 1; +} + +static int +glSDL_BlitGL(_THIS, SDL_Surface * src, SDL_Rect * srcrect, SDL_Rect * dstrect) +{ + private_hwdata *txi; + float x1, y1; + unsigned char alpha; + SDL_Rect d; + int x, y; + SDL_Rect r; + + if (!src) + return GLERET("BlitGL(): No src surface!"); + + /* Get source and destination coordinates */ + if (srcrect) + r = *srcrect; + else { + r.x = r.y = 0; + r.w = src->w; + r.h = src->h; + } + if (dstrect) { + x = dstrect->x; + y = dstrect->y; + } else + x = y = 0; + + /* Clip! */ + if (!blitclip(&r, src->w, src->h, &x, &y, &this->screen->clip_rect)) { + if (dstrect) + dstrect->w = dstrect->h = 0; + return 0; + } + + /* Write back the resulting cliprect */ + if (dstrect) + *dstrect = r; + + /* Make sure we have a source with a valid texture */ + txi = glSDL_UploadSurface(this, src); + if (!txi) + return GLERET("BlitGL(): Could not get a TexInfo!"); + + /* Set up blending */ + if (src->flags & (SDL_SRCALPHA | SDL_SRCCOLORKEY)) { + glSDL_blendfunc(this, GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + glSDL_do_blend(this, 1); + } else + glSDL_do_blend(this, 0); + + /* Enable texturing */ + glSDL_do_texture(this, 1); + + /* Calculate texcoords */ + if (!srcrect) + srcrect = &txi->virt; + x1 = (float) srcrect->x; + y1 = (float) srcrect->y; + + /* Calculate screen coords. */ + if (dstrect) { + d.x = dstrect->x; + d.y = dstrect->y; + d.w = (int) (srcrect->w * (float) txi->lw / (float) txi->virt.w); + d.h = (int) (srcrect->h * (float) txi->lh / (float) txi->virt.h); + } else { + d.x = 0; + d.y = 0; + d.w = (int) (srcrect->w * (float) txi->lw / (float) txi->virt.w); + d.h = (int) (srcrect->h * (float) txi->lh / (float) txi->virt.h); + } + + /* + * Note that we actually *prevent* the use of "full surface alpha" + * and alpha channel in combination - to stay SDL 2D compatible. + */ + if ((src->flags & SDL_SRCALPHA) && (src->format->Amask)) + alpha = 255; + else + alpha = src->format->alpha; + + /* Render! */ + switch (txi->tilemode) { + case GLSDL_TM_SINGLE: + glSDL_BlitGL_single(this, txi, x1, y1, &d, alpha); + break; + case GLSDL_TM_HORIZONTAL: + glSDL_BlitGL_htile(this, txi, x1, y1, &d, alpha); + break; + case GLSDL_TM_VERTICAL: + glSDL_BlitGL_vtile(this, txi, x1, y1, &d, alpha); + break; + case GLSDL_TM_HUGE: + glSDL_BlitGL_hvtile(this, src, txi, x1, y1, &d, alpha); + break; + } + + if (txi->temporary) + glSDL_FreeTexInfo(this, txi); + + return 0; +} + + +static int +glSDL_HWAccelBlit(SDL_Surface * src, SDL_Rect * srcrect, + SDL_Surface * dst, SDL_Rect * dstrect) +{ + SDL_Surface *vs; + + if (!src) + return GLERET("HWAccelBlit(): No src surface!"); + if (!dst) + return GLERET("HWAccelBlit(): No dst surface!"); + + /* + * Figure out what to do: + * screen->screen: glSDL_BlitFromGL() + glSDL_BlitGL() + * surface->screen: glSDL_BlitGL() + * screen->surface: glSDL_BlitFromGL() + * surface->surface: glSDL_SoftBlit() + */ + vs = SDL_VideoSurface; + if (src == vs) { + if (dst == vs) { + /* + FIXME: Try glCopyPixels() instead... + */ + glSDL_BlitFromGL(current_video, srcrect, vs, dstrect); + return glSDL_BlitGL(current_video, vs, srcrect, dstrect); + } else { + return glSDL_BlitFromGL(current_video, srcrect, dst, dstrect); + } + } else { + if (dst == vs) { + return glSDL_BlitGL(current_video, src, srcrect, dstrect); + } else { + glSDL_Invalidate(dst, dstrect); + glSDL_SoftBlit(src, srcrect, dst, dstrect); + return 0; + } + } +} + + +static int +glSDL_FillHWRect(_THIS, SDL_Surface * dst, SDL_Rect * dstrect, Uint32 color) +{ + SDL_Surface *vs = SDL_VideoSurface; + int dx1, dy1, dx2, dy2; + Uint32 r, g, b; + Uint8 br, bg, bb; + + /* + * Some ugly reverse conversion for compatibility... + * (We must do this before losing the dst pointer, + * as the pixel formats of the screen and + * SDL_VideoSurface may differ!) + */ + + if (dst->format->palette) { + /* this a paletted color */ + SDL_GetRGB(color, dst->format, &br, &bg, &bb); + } else { + /* this a RGB color */ + r = color & dst->format->Rmask; + r = r >> dst->format->Rshift; + r = r << dst->format->Rloss; + br = r; + + g = color & dst->format->Gmask; + g = g >> dst->format->Gshift; + g = g << dst->format->Gloss; + bg = g; + + b = color & dst->format->Bmask; + b = b >> dst->format->Bshift; + b = b << dst->format->Bloss; + bb = b; + } + + if (vs != dst) { + /* draw a rect offscreen */ + glSDL_Invalidate(dst, dstrect); + /* software-fill the surface by faking it as a SW_SURFACE */ + dst->flags &= ~SDL_HWSURFACE; + SDL_FillRect(dst, dstrect, color); + dst->flags |= SDL_HWSURFACE; + } else { + /* draw a rect onscreen */ + glSDL_do_texture(this, 0); + glSDL_do_blend(this, 0); + + dx1 = dstrect->x; + dy1 = dstrect->y; + dx2 = dx1 + dstrect->w; + dy2 = dy1 + dstrect->h; + + this->glBegin(GL_TRIANGLE_FAN); + this->glColor3ub(br, bg, bb); + this->glVertex2i(dx1, dy1); + this->glVertex2i(dx2, dy1); + this->glVertex2i(dx2, dy2); + this->glVertex2i(dx1, dy2); + this->glEnd(); + } + return 0; +} + +static int +glSDL_CheckHWBlit(_THIS, SDL_Surface * src, SDL_Surface * dst) +{ + src->flags |= SDL_HWACCEL; + src->map->hw_blit = glSDL_HWAccelBlit; + return 1; +} + + +static SDL_Surface * +glSDL_DisplayFormat(SDL_Surface * surface) +{ + SDL_Surface *tmp; + int use_rgba = (surface->flags & SDL_SRCCOLORKEY) || + ((surface->flags & SDL_SRCALPHA) && surface->format->Amask); +#ifdef DEBUG_GLSDL + fprintf(stderr, "#### glSDL_DisplayFormat()\n"); +#endif + if (use_rgba) + tmp = glSDL_ConvertSurface(surface, RGBAfmt, SDL_SWSURFACE); + else + tmp = glSDL_ConvertSurface(surface, RGBfmt, SDL_SWSURFACE); + if (!tmp) { + GLERR("glSDL_DisplayFormat() could not convert surface!"); + return NULL; + } + SDL_SetAlpha(tmp, 0, 0); + + if (surface->flags & SDL_SRCCOLORKEY) { + /* + * We drop colorkey data here, but we have to, + * or we'll run into trouble when converting, + * in particular from indexed color formats. + */ + SDL_SetColorKey(tmp, SDL_SRCCOLORKEY, surface->format->colorkey); + glSDL_key2alpha(tmp); + SDL_SetColorKey(tmp, 0, 0); + } + + return tmp; +} + + +static SDL_Surface * +glSDL_DisplayFormatAlpha(SDL_Surface * surface) +{ + SDL_Surface *s, *tmp; + tmp = glSDL_ConvertSurface(surface, RGBAfmt, SDL_SWSURFACE); +#ifdef DEBUG_GLSDL + fprintf(stderr, "#### glSDL_DisplayFormatAlpha()\n"); +#endif + if (!tmp) + return NULL; + + SDL_SetAlpha(tmp, 0, 0); + SDL_SetColorKey(tmp, 0, 0); + s = glSDL_CreateRGBASurface(surface->w, surface->h); + if (!s) { + SDL_FreeSurface(tmp); + return NULL; + } + glSDL_SoftBlit(tmp, NULL, s, NULL); + SDL_FreeSurface(tmp); + + if (surface->flags & SDL_SRCCOLORKEY) { + SDL_SetColorKey(s, SDL_SRCCOLORKEY, surface->format->colorkey); + glSDL_key2alpha(s); + SDL_SetColorKey(s, 0, 0); + } + + if (surface->flags & SDL_SRCALPHA) + SDL_SetAlpha(s, SDL_SRCALPHA, surface->format->alpha); + return s; +} + + +/*---------------------------------------------------------- + glSDL specific API extensions + ----------------------------------------------------------*/ + +static void +glSDL_Invalidate(SDL_Surface * surface, SDL_Rect * area) +{ + private_hwdata *txi; + if (!surface) + return; + txi = glSDL_GetTexInfo(surface); + if (!txi) + return; + if (!area) { + txi->invalid_area.x = 0; + txi->invalid_area.y = 0; + txi->invalid_area.w = surface->w; + txi->invalid_area.h = surface->h; + return; + } + txi->invalid_area = *area; +} + + +static void +glSDL_SetLogicSize(_THIS, SDL_Surface * surface, int w, int h) +{ + SDL_Rect r; + private_hwdata *txi; + if (!IS_GLSDL_SURFACE(surface)) + return; + + txi = glSDL_GetTexInfo(surface); + + txi->lw = w; + txi->lh = h; + + if (SDL_VideoSurface != surface) + return; + + r.x = r.y = 0; + r.w = w; + r.h = h; + glSDL_SetClipRect(this, surface, &r); + + this->glMatrixMode(GL_MODELVIEW); + this->glLoadIdentity(); + this->glTranslated(0.0f, 0.0f, 0.0f); + + this->glDisable(GL_DEPTH_TEST); + this->glDisable(GL_CULL_FACE); + + glSDL_reset(); +} + +static int +glSDL_InitTexture(_THIS, SDL_Surface * datasurf, private_hwdata * txi, + int tex) +{ + this->glGenTextures(1, (GLuint *) & txi->texture[tex]); + this->glBindTexture(GL_TEXTURE_2D, txi->texture[tex]); + glstate.texture = txi->texture[tex]; + this->glPixelStorei(GL_UNPACK_ROW_LENGTH, datasurf->pitch / + datasurf->format->BytesPerPixel); + this->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + this->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + this->glTexImage2D(GL_TEXTURE_2D, 0, + datasurf->format->Amask ? GL_RGBA8 : GL_RGB8, + txi->texsize, txi->texsize, 0, + datasurf->format->Amask ? GL_RGBA : GL_RGB, + GL_UNSIGNED_BYTE, NULL); +#ifdef DEBUG_GLSDL + glSDL_print_glerror(this, 1); +#endif + return 0; +} + + +/* Image tiled horizontally (wide surface), or not at all */ +static int +glSDL_UploadHoriz(_THIS, SDL_Surface * datasurf, private_hwdata * txi) +{ + int bpp = datasurf->format->BytesPerPixel; + int res; + int tex = 0; + int fromx = 0; + int toy = txi->texsize; /* To init first texture */ + while (1) { + int thistw = datasurf->w - fromx; + if (thistw > txi->tilew) + thistw = txi->tilew; + else if (thistw <= 0) + break; + if (toy + txi->tileh > txi->texsize) { + toy = 0; + res = glSDL_InitTexture(this, datasurf, txi, tex); + if (res < 0) + return res; + ++tex; + } + this->glTexSubImage2D(GL_TEXTURE_2D, 0, 0, toy, + thistw, txi->tileh, + datasurf->format->Amask ? GL_RGBA : GL_RGB, + GL_UNSIGNED_BYTE, + (char *) datasurf->pixels + bpp * fromx); +#ifdef DEBUG_GLSDL + glSDL_print_glerror(this, 2); +#endif + fromx += txi->tilew; + toy += txi->tileh; + } + return 0; +} + + +/* Image tiled vertically (tall surface) */ +static int +glSDL_UploadVert(_THIS, SDL_Surface * datasurf, private_hwdata * txi) +{ + int res; + int tex = 0; + int fromy = 0; + int tox = txi->texsize; /* To init first texture */ + while (1) { + int thisth = datasurf->h - fromy; + if (thisth > txi->tileh) + thisth = txi->tileh; + else if (thisth <= 0) + break; + if (tox + txi->tilew > txi->texsize) { + tox = 0; + res = glSDL_InitTexture(this, datasurf, txi, tex); + if (res < 0) + return res; + ++tex; + } + this->glTexSubImage2D(GL_TEXTURE_2D, 0, tox, 0, + txi->tilew, thisth, + datasurf->format->Amask ? GL_RGBA : GL_RGB, + GL_UNSIGNED_BYTE, + (char *) datasurf->pixels + + datasurf->pitch * fromy); +#ifdef DEBUG_GLSDL + glSDL_print_glerror(this, 3); +#endif + fromy += txi->tileh; + tox += txi->tilew; + } + return 0; +} + + +/* Image tiled two-way (huge surface) */ +static int +glSDL_UploadHuge(_THIS, SDL_Surface * datasurf, private_hwdata * txi) +{ + int bpp = datasurf->format->BytesPerPixel; + int res; + int tex = 0; + int y = 0; + while (y < datasurf->h) { + int x; + int thisth = datasurf->h - y; + if (thisth > txi->tileh) + thisth = txi->tileh; + x = 0; + while (x < datasurf->w) { + int thistw = datasurf->w - x; + if (thistw > txi->tilew) + thistw = txi->tilew; + res = glSDL_InitTexture(this, datasurf, txi, tex++); + if (res < 0) + return res; + this->glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, + thistw, thisth, + datasurf->format-> + Amask ? GL_RGBA : GL_RGB, + GL_UNSIGNED_BYTE, + (char *) datasurf->pixels + + datasurf->pitch * y + bpp * x); +#ifdef DEBUG_GLSDL + fprintf(stderr, + "glTexSubImage(x = %d, y = %d, w = %d, h = %d)\n", x, + y, thistw, thisth); + glSDL_print_glerror(this, 4); +#endif + x += txi->tilew; + } + y += txi->tileh; + } + return 0; +} + + +/* Upload all textures for a surface. */ +static int +glSDL_UploadTextures(_THIS, SDL_Surface * datasurf, private_hwdata * txi) +{ + switch (txi->tilemode) { + case GLSDL_TM_SINGLE: + case GLSDL_TM_HORIZONTAL: + glSDL_UploadHoriz(this, datasurf, txi); + break; + case GLSDL_TM_VERTICAL: + glSDL_UploadVert(this, datasurf, txi); + break; + case GLSDL_TM_HUGE: + glSDL_UploadHuge(this, datasurf, txi); + break; + } + return 0; +} + + +/* + * IMPORTANT: + * This function will try various ways of giving you + * a TexInfo, and will succeed most of the time. + * + * However, the TexInfo returned may be temporary, + * (as opposed to connected to 'surface'). A temporary + * TexInfo must be used only once and then thrown away, + * since it means that glSDL cannot track changes in + * the pixel data of 'texture'. + */ +static private_hwdata * +glSDL_UploadSurface(_THIS, SDL_Surface * surface) +{ + int i; + int converted = 0; + private_hwdata *txi = glSDL_GetTexInfo(surface); + + if (IS_GLSDL_SURFACE(surface)) { + /* + * Ok, this is a glSDL surface, and it *might* be + * in texture memory already. If so, it may need + * an update. + */ + if (txi->invalid_area.w) { + glSDL_UnloadTexture(this, txi); + } else { + int missing = 0; + if (txi->textures) { + for (i = 0; i < txi->textures; ++i) + if (GLSDL_NOTEX == txi->texture[i]) { + missing = 1; + break; + } + if (!missing) + return txi; /* They're already there! */ + } + } + } else { + /* + * Nope, this isn't (yet) a glSDL surface. Let's + * try to either make it one, or set up a temporary + * TexInfo for it, valid for only one blit. + */ + if ((surface->flags & SDL_HWSURFACE) == SDL_HWSURFACE) { + txi = glSDL_AddTexInfo(this, surface); + if (!txi) { + GLERR("UploadSurface(): Could not add TexInfo!"); + return NULL; + } + surface->flags |= SDL_HWSURFACE; + surface->flags |= SDL_HWACCEL; + } else { + /* + * FIXME + * here if the surface is small enough, it's a good + * candidate for a blit using glDrawPixels instead + * of a texture blit + */ + txi = glSDL_CreateTempTexInfo(this, surface); + if (!txi) { + GLERR("UploadSurface(): Could not create temp TexInfo!"); + return NULL; + } + } + } + + if (txi->texsize > maxtexsize) { + /* This surface wasn't tiled properly... */ + if (txi->temporary) + glSDL_FreeTexInfo(this, txi); + GLERR("UploadSurface(): Too large texture!"); + return NULL; + } + + /* + * Kludge: Convert if not of preferred RGB or RGBA format. + * + * Conversion should only be done when *really* needed. + * That is, it should rarely have to be done with OpenGL + * 1.2+. + * + * Besides, any surface that's been SDL_DisplayFormat()ed + * should already be in the best known OpenGL format - + * preferably one that makes DMA w/o conversion possible. + */ + if (!glSDL_FormatIsOk(surface)) { +#ifdef DEBUG_GLSDL + fprintf(stderr, "glSDL: WARNING: On-the-fly conversion performed!\n"); +#endif + converted = 1; + /* NOTE: We forget about the original surface here. */ + if (surface->format->Amask) + surface = glSDL_DisplayFormatAlpha(surface); + else + surface = glSDL_DisplayFormat(surface); + if (!surface) { + GLERR("UploadSurface(): Could not convert surface!"); + if (txi->temporary) + glSDL_FreeTexInfo(this, txi); + return NULL; + } + } + + glSDL_UploadTextures(this, surface, txi); + + if (converted) + SDL_FreeSurface(surface); + + return txi; +} + + +static void +glSDL_UnloadTexture(_THIS, private_hwdata * txi) +{ + int i; + for (i = 0; i < txi->textures; ++i) + if (txi->texture[i] != GLSDL_NOTEX) + this->glDeleteTextures(1, &txi->texture[i]); + SDL_memset(&txi->invalid_area, 0, sizeof(txi->invalid_area)); +} + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/glsdl/SDL_glsdl.h b/src/video/glsdl/SDL_glsdl.h new file mode 100644 index 000000000..8c12442a8 --- /dev/null +++ b/src/video/glsdl/SDL_glsdl.h @@ -0,0 +1,39 @@ +/* + SDL - Simple DirectMedia Layer + Copyright (C) 1997-2006 Sam Lantinga + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + Sam Lantinga + slouken@libsdl.org +*/ +#include "SDL_config.h" + +/* + * glSDL "SDL-over-OpenGL" video driver implemented by + * David Olofson and + * Stephane Marchesin + */ + +#ifndef _SDL_gl_h +#define _SDL_gl_h + +#include "../SDL_sysvideo.h" + +/* Hidden "this" pointer for the video functions */ +#define _THIS SDL_VideoDevice *this + +#endif /* _SDL_gl_h */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/ipod/SDL_ipodvideo.c b/src/video/ipod/SDL_ipodvideo.c index cac476602..b338e6fc0 100644 --- a/src/video/ipod/SDL_ipodvideo.c +++ b/src/video/ipod/SDL_ipodvideo.c @@ -45,13 +45,17 @@ #define _THIS SDL_VideoDevice *this -static int iPod_VideoInit (_THIS, SDL_PixelFormat *vformat); -static SDL_Rect **iPod_ListModes (_THIS, SDL_PixelFormat *format, Uint32 flags); -static SDL_Surface *iPod_SetVideoMode (_THIS, SDL_Surface *current, int width, int height, int bpp, Uint32 flags); -static int iPod_SetColors (_THIS, int firstcolor, int ncolors, SDL_Color *colors); -static void iPod_UpdateRects (_THIS, int nrects, SDL_Rect *rects); -static void iPod_VideoQuit (_THIS); -static void iPod_PumpEvents (_THIS); +static int iPod_VideoInit(_THIS, SDL_PixelFormat * vformat); +static SDL_Rect **iPod_ListModes(_THIS, SDL_PixelFormat * format, + Uint32 flags); +static SDL_Surface *iPod_SetVideoMode(_THIS, SDL_Surface * current, + int width, int height, int bpp, + Uint32 flags); +static int iPod_SetColors(_THIS, int firstcolor, int ncolors, + SDL_Color * colors); +static void iPod_UpdateRects(_THIS, int nrects, SDL_Rect * rects); +static void iPod_VideoQuit(_THIS); +static void iPod_PumpEvents(_THIS); static long iPod_GetGeneration(); @@ -75,56 +79,64 @@ FILE *dbgout; static unsigned long lcd_base, lcd_rtc, lcd_width, lcd_height; -static long iPod_GetGeneration() +static long +iPod_GetGeneration() { int i; char cpuinfo[256]; char *ptr; FILE *file; - + if ((file = fopen("/proc/cpuinfo", "r")) != NULL) { - while (fgets(cpuinfo, sizeof(cpuinfo), file) != NULL) - if (SDL_strncmp(cpuinfo, "Revision", 8) == 0) - break; - fclose(file); + while (fgets(cpuinfo, sizeof(cpuinfo), file) != NULL) + if (SDL_strncmp(cpuinfo, "Revision", 8) == 0) + break; + fclose(file); } for (i = 0; !isspace(cpuinfo[i]); i++); for (; isspace(cpuinfo[i]); i++); ptr = cpuinfo + i + 2; - + return SDL_strtol(ptr, NULL, 10); } -static int iPod_Available() +static int +iPod_Available() { return 1; } -static void iPod_DeleteDevice (SDL_VideoDevice *device) +static void +iPod_DeleteDevice(SDL_VideoDevice * device) { - free (device->hidden); - free (device); + free(device->hidden); + free(device); } -void iPod_InitOSKeymap (_THIS) {} +void +iPod_InitOSKeymap(_THIS) +{ +} -static SDL_VideoDevice *iPod_CreateDevice (int devindex) +static SDL_VideoDevice * +iPod_CreateDevice(int devindex) { SDL_VideoDevice *this; - - this = (SDL_VideoDevice *)SDL_malloc (sizeof(SDL_VideoDevice)); + + this = (SDL_VideoDevice *) SDL_malloc(sizeof(SDL_VideoDevice)); if (this) { - memset (this, 0, sizeof *this); - this->hidden = (struct SDL_PrivateVideoData *) SDL_malloc (sizeof(struct SDL_PrivateVideoData)); + memset(this, 0, sizeof *this); + this->hidden = (struct SDL_PrivateVideoData *) + SDL_malloc(sizeof(struct SDL_PrivateVideoData)); } if (!this || !this->hidden) { - SDL_OutOfMemory(); - if (this) - SDL_free (this); - return 0; + SDL_OutOfMemory(); + if (this) + SDL_free(this); + return 0; } - memset (this->hidden, 0, sizeof(struct SDL_PrivateVideoData)); - + memset(this->hidden, 0, sizeof(struct SDL_PrivateVideoData)); + generation = iPod_GetGeneration(); this->VideoInit = iPod_VideoInit; @@ -161,168 +173,182 @@ VideoBootStrap iPod_bootstrap = { //--// -static int iPod_VideoInit (_THIS, SDL_PixelFormat *vformat) +static int +iPod_VideoInit(_THIS, SDL_PixelFormat * vformat) { if (!initd) { - /*** Code adapted/copied from SDL fbcon driver. ***/ - - static const char * const tty0[] = { "/dev/tty0", "/dev/vc/0", 0 }; - static const char * const vcs[] = { "/dev/vc/%d", "/dev/tty%d", 0 }; - int i, tty0_fd; - - dbgout = fdopen (open ("/etc/sdlpod.log", O_WRONLY | O_SYNC | O_APPEND), "a"); - if (dbgout) { - setbuf (dbgout, 0); - fprintf (dbgout, "--> Started SDL <--\n"); - } - - // Try to query for a free VT - tty0_fd = -1; - for ( i=0; tty0[i] && (tty0_fd < 0); ++i ) { - tty0_fd = open(tty0[i], O_WRONLY, 0); - } - if ( tty0_fd < 0 ) { - tty0_fd = dup(0); /* Maybe stdin is a VT? */ - } - ioctl(tty0_fd, VT_OPENQRY, &curvt); - close(tty0_fd); - - tty0_fd = open("/dev/tty", O_RDWR, 0); - if ( tty0_fd >= 0 ) { - ioctl(tty0_fd, TIOCNOTTY, 0); - close(tty0_fd); - } - - if ( (geteuid() == 0) && (curvt > 0) ) { - for ( i=0; vcs[i] && (kbfd < 0); ++i ) { - char vtpath[12]; - - SDL_snprintf(vtpath, SDL_arraysize(vtpath), vcs[i], curvt); - kbfd = open(vtpath, O_RDWR); - } - } - if ( kbfd < 0 ) { - if (dbgout) fprintf (dbgout, "Couldn't open any VC\n"); - return -1; - } - if (dbgout) fprintf (stderr, "Current VT: %d\n", curvt); - - if (kbfd >= 0) { - /* Switch to the correct virtual terminal */ - if ( curvt > 0 ) { - struct vt_stat vtstate; - - if ( ioctl(kbfd, VT_GETSTATE, &vtstate) == 0 ) { - oldvt = vtstate.v_active; - } - if ( ioctl(kbfd, VT_ACTIVATE, curvt) == 0 ) { - if (dbgout) fprintf (dbgout, "Waiting for switch to this VT... "); - ioctl(kbfd, VT_WAITACTIVE, curvt); - if (dbgout) fprintf (dbgout, "done!\n"); - } - } - - // Set terminal input mode - if (tcgetattr (kbfd, &old_termios) < 0) { - if (dbgout) fprintf (dbgout, "Can't get termios\n"); - return -1; - } - cur_termios = old_termios; - // cur_termios.c_iflag &= ~(ICRNL | INPCK | ISTRIP | IXON); - // cur_termios.c_iflag |= (BRKINT); - // cur_termios.c_lflag &= ~(ICANON | ECHO | ISIG | IEXTEN); - // cur_termios.c_oflag &= ~(OPOST); - // cur_termios.c_oflag |= (ONOCR | ONLRET); - cur_termios.c_lflag &= ~(ICANON | ECHO | ISIG); - cur_termios.c_iflag &= ~(ISTRIP | IGNCR | ICRNL | INLCR | IXOFF | IXON); - cur_termios.c_cc[VMIN] = 0; - cur_termios.c_cc[VTIME] = 0; - - if (tcsetattr (kbfd, TCSAFLUSH, &cur_termios) < 0) { - if (dbgout) fprintf (dbgout, "Can't set termios\n"); - return -1; - } - if (ioctl (kbfd, KDSKBMODE, K_MEDIUMRAW) < 0) { - if (dbgout) fprintf (dbgout, "Can't set medium-raw mode\n"); - return -1; - } - if (ioctl (kbfd, KDSETMODE, KD_GRAPHICS) < 0) { - if (dbgout) fprintf (dbgout, "Can't set graphics\n"); - return -1; - } - } - - // Open the framebuffer - if ((fbfd = open ("/dev/fb0", O_RDWR)) < 0) { - if (dbgout) fprintf (dbgout, "Can't open framebuffer\n"); - return -1; - } else { - struct fb_var_screeninfo vinfo; - - if (dbgout) fprintf (dbgout, "Generation: %ld\n", generation); - - if (generation >= 40000) { - lcd_base = IPOD_NEW_LCD_BASE; - } else { - lcd_base = IPOD_OLD_LCD_BASE; - } - - ioctl (fbfd, FBIOGET_VSCREENINFO, &vinfo); - close (fbfd); - - if (lcd_base == IPOD_OLD_LCD_BASE) - lcd_rtc = IPOD_OLD_LCD_RTC; - else if (lcd_base == IPOD_NEW_LCD_BASE) - lcd_rtc = IPOD_NEW_LCD_RTC; - else { - SDL_SetError ("Unknown iPod version"); - return -1; - } - - lcd_width = vinfo.xres; - lcd_height = vinfo.yres; - - if (dbgout) fprintf (dbgout, "LCD is %dx%d\n", lcd_width, lcd_height); - } - - fcntl (kbfd, F_SETFL, O_RDWR | O_NONBLOCK); - - /* Determine the current screen size */ - this->info.current_w = lcd_width; - this->info.current_h = lcd_height; - - if ((generation >= 60000) && (generation < 70000)) { - vformat->BitsPerPixel = 16; - vformat->Rmask = 0xF800; - vformat->Gmask = 0x07E0; - vformat->Bmask = 0x001F; - } else { - vformat->BitsPerPixel = 8; - vformat->Rmask = vformat->Gmask = vformat->Bmask = 0; - } - - initd = 1; - if (dbgout) fprintf (dbgout, "Initialized.\n\n"); + /*** Code adapted/copied from SDL fbcon driver. ***/ + + static const char *const tty0[] = { "/dev/tty0", "/dev/vc/0", 0 }; + static const char *const vcs[] = { "/dev/vc/%d", "/dev/tty%d", 0 }; + int i, tty0_fd; + + dbgout = + fdopen(open("/etc/sdlpod.log", O_WRONLY | O_SYNC | O_APPEND), + "a"); + if (dbgout) { + setbuf(dbgout, 0); + fprintf(dbgout, "--> Started SDL <--\n"); + } + // Try to query for a free VT + tty0_fd = -1; + for (i = 0; tty0[i] && (tty0_fd < 0); ++i) { + tty0_fd = open(tty0[i], O_WRONLY, 0); + } + if (tty0_fd < 0) { + tty0_fd = dup(0); /* Maybe stdin is a VT? */ + } + ioctl(tty0_fd, VT_OPENQRY, &curvt); + close(tty0_fd); + + tty0_fd = open("/dev/tty", O_RDWR, 0); + if (tty0_fd >= 0) { + ioctl(tty0_fd, TIOCNOTTY, 0); + close(tty0_fd); + } + + if ((geteuid() == 0) && (curvt > 0)) { + for (i = 0; vcs[i] && (kbfd < 0); ++i) { + char vtpath[12]; + + SDL_snprintf(vtpath, SDL_arraysize(vtpath), vcs[i], curvt); + kbfd = open(vtpath, O_RDWR); + } + } + if (kbfd < 0) { + if (dbgout) + fprintf(dbgout, "Couldn't open any VC\n"); + return -1; + } + if (dbgout) + fprintf(stderr, "Current VT: %d\n", curvt); + + if (kbfd >= 0) { + /* Switch to the correct virtual terminal */ + if (curvt > 0) { + struct vt_stat vtstate; + + if (ioctl(kbfd, VT_GETSTATE, &vtstate) == 0) { + oldvt = vtstate.v_active; + } + if (ioctl(kbfd, VT_ACTIVATE, curvt) == 0) { + if (dbgout) + fprintf(dbgout, "Waiting for switch to this VT... "); + ioctl(kbfd, VT_WAITACTIVE, curvt); + if (dbgout) + fprintf(dbgout, "done!\n"); + } + } + // Set terminal input mode + if (tcgetattr(kbfd, &old_termios) < 0) { + if (dbgout) + fprintf(dbgout, "Can't get termios\n"); + return -1; + } + cur_termios = old_termios; + // cur_termios.c_iflag &= ~(ICRNL | INPCK | ISTRIP | IXON); + // cur_termios.c_iflag |= (BRKINT); + // cur_termios.c_lflag &= ~(ICANON | ECHO | ISIG | IEXTEN); + // cur_termios.c_oflag &= ~(OPOST); + // cur_termios.c_oflag |= (ONOCR | ONLRET); + cur_termios.c_lflag &= ~(ICANON | ECHO | ISIG); + cur_termios.c_iflag &= + ~(ISTRIP | IGNCR | ICRNL | INLCR | IXOFF | IXON); + cur_termios.c_cc[VMIN] = 0; + cur_termios.c_cc[VTIME] = 0; + + if (tcsetattr(kbfd, TCSAFLUSH, &cur_termios) < 0) { + if (dbgout) + fprintf(dbgout, "Can't set termios\n"); + return -1; + } + if (ioctl(kbfd, KDSKBMODE, K_MEDIUMRAW) < 0) { + if (dbgout) + fprintf(dbgout, "Can't set medium-raw mode\n"); + return -1; + } + if (ioctl(kbfd, KDSETMODE, KD_GRAPHICS) < 0) { + if (dbgout) + fprintf(dbgout, "Can't set graphics\n"); + return -1; + } + } + // Open the framebuffer + if ((fbfd = open("/dev/fb0", O_RDWR)) < 0) { + if (dbgout) + fprintf(dbgout, "Can't open framebuffer\n"); + return -1; + } else { + struct fb_var_screeninfo vinfo; + + if (dbgout) + fprintf(dbgout, "Generation: %ld\n", generation); + + if (generation >= 40000) { + lcd_base = IPOD_NEW_LCD_BASE; + } else { + lcd_base = IPOD_OLD_LCD_BASE; + } + + ioctl(fbfd, FBIOGET_VSCREENINFO, &vinfo); + close(fbfd); + + if (lcd_base == IPOD_OLD_LCD_BASE) + lcd_rtc = IPOD_OLD_LCD_RTC; + else if (lcd_base == IPOD_NEW_LCD_BASE) + lcd_rtc = IPOD_NEW_LCD_RTC; + else { + SDL_SetError("Unknown iPod version"); + return -1; + } + + lcd_width = vinfo.xres; + lcd_height = vinfo.yres; + + if (dbgout) + fprintf(dbgout, "LCD is %dx%d\n", lcd_width, lcd_height); + } + + fcntl(kbfd, F_SETFL, O_RDWR | O_NONBLOCK); + + /* Determine the current screen size */ + this->info.current_w = lcd_width; + this->info.current_h = lcd_height; + + if ((generation >= 60000) && (generation < 70000)) { + vformat->BitsPerPixel = 16; + vformat->Rmask = 0xF800; + vformat->Gmask = 0x07E0; + vformat->Bmask = 0x001F; + } else { + vformat->BitsPerPixel = 8; + vformat->Rmask = vformat->Gmask = vformat->Bmask = 0; + } + + initd = 1; + if (dbgout) + fprintf(dbgout, "Initialized.\n\n"); } return 0; } -static SDL_Rect **iPod_ListModes (_THIS, SDL_PixelFormat *format, Uint32 flags) +static SDL_Rect ** +iPod_ListModes(_THIS, SDL_PixelFormat * format, Uint32 flags) { int width, height, fd; static SDL_Rect r; static SDL_Rect *rs[2] = { &r, 0 }; - if ((fd = open ("/dev/fb0", O_RDWR)) < 0) { - return 0; + if ((fd = open("/dev/fb0", O_RDWR)) < 0) { + return 0; } else { - struct fb_var_screeninfo vinfo; - - ioctl (fbfd, FBIOGET_VSCREENINFO, &vinfo); - close (fbfd); - - width = vinfo.xres; - height = vinfo.yres; + struct fb_var_screeninfo vinfo; + + ioctl(fbfd, FBIOGET_VSCREENINFO, &vinfo); + close(fbfd); + + width = vinfo.xres; + height = vinfo.yres; } r.x = r.y = 0; r.w = width; @@ -331,43 +357,45 @@ static SDL_Rect **iPod_ListModes (_THIS, SDL_PixelFormat *format, Uint32 flags) } -static SDL_Surface *iPod_SetVideoMode (_THIS, SDL_Surface *current, int width, int height, int bpp, - Uint32 flags) +static SDL_Surface * +iPod_SetVideoMode(_THIS, SDL_Surface * current, int width, int height, + int bpp, Uint32 flags) { Uint32 Rmask, Gmask, Bmask; if (bpp > 8) { - Rmask = 0xF800; - Gmask = 0x07E0; - Bmask = 0x001F; + Rmask = 0xF800; + Gmask = 0x07E0; + Bmask = 0x001F; } else { - Rmask = Gmask = Bmask = 0; + Rmask = Gmask = Bmask = 0; } - if (this->hidden->buffer) SDL_free (this->hidden->buffer); - this->hidden->buffer = SDL_malloc (width * height * (bpp / 8)); + if (this->hidden->buffer) + SDL_free(this->hidden->buffer); + this->hidden->buffer = SDL_malloc(width * height * (bpp / 8)); if (!this->hidden->buffer) { - SDL_SetError ("Couldn't allocate buffer for requested mode"); - return 0; + SDL_SetError("Couldn't allocate buffer for requested mode"); + return 0; } - memset (this->hidden->buffer, 0, width * height * (bpp / 8)); + memset(this->hidden->buffer, 0, width * height * (bpp / 8)); - if (!SDL_ReallocFormat (current, bpp, Rmask, Gmask, Bmask, 0)) { - SDL_SetError ("Couldn't allocate new pixel format"); - SDL_free (this->hidden->buffer); - this->hidden->buffer = 0; - return 0; + if (!SDL_ReallocFormat(current, bpp, Rmask, Gmask, Bmask, 0)) { + SDL_SetError("Couldn't allocate new pixel format"); + SDL_free(this->hidden->buffer); + this->hidden->buffer = 0; + return 0; } if (bpp <= 8) { - int i, j; - for (i = 0; i < 256; i += 4) { - for (j = 0; j < 4; j++) { - current->format->palette->colors[i+j].r = 85 * j; - current->format->palette->colors[i+j].g = 85 * j; - current->format->palette->colors[i+j].b = 85 * j; - } - } + int i, j; + for (i = 0; i < 256; i += 4) { + for (j = 0; j < 4; j++) { + current->format->palette->colors[i + j].r = 85 * j; + current->format->palette->colors[i + j].g = 85 * j; + current->format->palette->colors[i + j].b = 85 * j; + } + } } current->flags = flags & SDL_FULLSCREEN; @@ -379,69 +407,73 @@ static SDL_Surface *iPod_SetVideoMode (_THIS, SDL_Surface *current, int width, i return current; } -static int iPod_SetColors (_THIS, int firstcolor, int ncolors, SDL_Color *colors) +static int +iPod_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color * colors) { - if (SDL_VideoSurface && SDL_VideoSurface->format && SDL_VideoSurface->format->palette) { - int i, j; - for (i = 0; i < 256; i += 4) { - for (j = 0; j < 4; j++) { - SDL_VideoSurface->format->palette->colors[i+j].r = 85 * j; - SDL_VideoSurface->format->palette->colors[i+j].g = 85 * j; - SDL_VideoSurface->format->palette->colors[i+j].b = 85 * j; - } - } + if (SDL_VideoSurface && SDL_VideoSurface->format + && SDL_VideoSurface->format->palette) { + int i, j; + for (i = 0; i < 256; i += 4) { + for (j = 0; j < 4; j++) { + SDL_VideoSurface->format->palette->colors[i + j].r = 85 * j; + SDL_VideoSurface->format->palette->colors[i + j].g = 85 * j; + SDL_VideoSurface->format->palette->colors[i + j].b = 85 * j; + } + } } return 0; } -static void iPod_VideoQuit (_THIS) +static void +iPod_VideoQuit(_THIS) { - ioctl (kbfd, KDSETMODE, KD_TEXT); - tcsetattr (kbfd, TCSAFLUSH, &old_termios); + ioctl(kbfd, KDSETMODE, KD_TEXT); + tcsetattr(kbfd, TCSAFLUSH, &old_termios); old_kbmode = -1; if (oldvt > 0) - ioctl (kbfd, VT_ACTIVATE, oldvt); - + ioctl(kbfd, VT_ACTIVATE, oldvt); + if (kbfd > 0) - close (kbfd); + close(kbfd); if (dbgout) { - fprintf (dbgout, "<-- Ended SDL -->\n"); - fclose (dbgout); + fprintf(dbgout, "<-- Ended SDL -->\n"); + fclose(dbgout); } - + kbfd = -1; } static char iPod_SC_keymap[] = { - 0, /* 0 - no key */ - '[' - 0x40, /* ESC (Ctrl+[) */ + 0, /* 0 - no key */ + '[' - 0x40, /* ESC (Ctrl+[) */ '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '=', - '\b', '\t', /* Backspace, Tab (Ctrl+H,Ctrl+I) */ + '\b', '\t', /* Backspace, Tab (Ctrl+H,Ctrl+I) */ 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p', '[', ']', - '\n', 0, /* Enter, Left CTRL */ + '\n', 0, /* Enter, Left CTRL */ 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', ';', '\'', '`', - 0, '\\', /* left shift, backslash */ + 0, '\\', /* left shift, backslash */ 'z', 'x', 'c', 'v', 'b', 'n', 'm', ',', '.', '/', - 0, '*', 0, ' ', 0, /* right shift, KP mul, left alt, space, capslock */ - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* F1-10 */ - 0, 0, /* numlock, scrollock */ - '7', '8', '9', '-', '4', '5', '6', '+', '1', '2', '3', '0', '.', /* numeric keypad */ - 0, 0, /* padding */ - 0, 0, 0, /* "less" (?), F11, F12 */ - 0, 0, 0, 0, 0, 0, 0, /* padding */ - '\n', 0, '/', 0, 0, /* KP enter, Rctrl, Ctrl, KP div, PrtSc, RAlt */ - 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Break, Home, Up, PgUp, Left, Right, End, Down, PgDn */ - 0, 0, /* Ins, Del */ - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* padding */ - 0, 0, /* RWin, LWin */ - 0 /* no key */ + 0, '*', 0, ' ', 0, /* right shift, KP mul, left alt, space, capslock */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* F1-10 */ + 0, 0, /* numlock, scrollock */ + '7', '8', '9', '-', '4', '5', '6', '+', '1', '2', '3', '0', '.', /* numeric keypad */ + 0, 0, /* padding */ + 0, 0, 0, /* "less" (?), F11, F12 */ + 0, 0, 0, 0, 0, 0, 0, /* padding */ + '\n', 0, '/', 0, 0, /* KP enter, Rctrl, Ctrl, KP div, PrtSc, RAlt */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Break, Home, Up, PgUp, Left, Right, End, Down, PgDn */ + 0, 0, /* Ins, Del */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* padding */ + 0, 0, /* RWin, LWin */ + 0 /* no key */ }; - -static void iPod_keyboard() + +static void +iPod_keyboard() { unsigned char keybuf[128]; int i, nread; @@ -450,23 +482,26 @@ static void iPod_keyboard() keysym.mod = 0; keysym.scancode = 0xff; - memset (&ev, 0, sizeof(SDL_Event)); + memset(&ev, 0, sizeof(SDL_Event)); - nread = read (kbfd, keybuf, 128); + nread = read(kbfd, keybuf, 128); for (i = 0; i < nread; i++) { - char ascii = iPod_SC_keymap[keybuf[i] & 0x7f]; + char ascii = iPod_SC_keymap[keybuf[i] & 0x7f]; - if (dbgout) fprintf (dbgout, "Key! %02x is %c %s", keybuf[i], ascii, (keybuf[i] & 0x80)? "up" : "down"); + if (dbgout) + fprintf(dbgout, "Key! %02x is %c %s", keybuf[i], ascii, + (keybuf[i] & 0x80) ? "up" : "down"); - keysym.sym = keysym.unicode = ascii; - ev.type = (keybuf[i] & 0x80)? SDL_KEYUP : SDL_KEYDOWN; - ev.key.state = 0; - ev.key.keysym = keysym; - SDL_PushEvent (&ev); + keysym.sym = keysym.unicode = ascii; + ev.type = (keybuf[i] & 0x80) ? SDL_KEYUP : SDL_KEYDOWN; + ev.key.state = 0; + ev.key.keysym = keysym; + SDL_PushEvent(&ev); } } -static void iPod_PumpEvents (_THIS) +static void +iPod_PumpEvents(_THIS) { fd_set fdset; int max_fd = 0; @@ -474,25 +509,29 @@ static void iPod_PumpEvents (_THIS) int posted; do { - posted = 0; - - FD_ZERO (&fdset); - if (kbfd >= 0) { - FD_SET (kbfd, &fdset); - max_fd = kbfd; - } - if (dbgout) fprintf (dbgout, "Selecting"); - if (select (max_fd + 1, &fdset, 0, 0, &zero) > 0) { - if (dbgout) fprintf (dbgout, " -> match!\n"); - iPod_keyboard(); - posted++; - } - if (dbgout) fprintf (dbgout, "\n"); - } while (posted); + posted = 0; + + FD_ZERO(&fdset); + if (kbfd >= 0) { + FD_SET(kbfd, &fdset); + max_fd = kbfd; + } + if (dbgout) + fprintf(dbgout, "Selecting"); + if (select(max_fd + 1, &fdset, 0, 0, &zero) > 0) { + if (dbgout) + fprintf(dbgout, " -> match!\n"); + iPod_keyboard(); + posted++; + } + if (dbgout) + fprintf(dbgout, "\n"); + } + while (posted); } // enough space for 160x128x2 -static char ipod_scr[160 * (128/4)]; +static char ipod_scr[160 * (128 / 4)]; #define outl(datum,addr) (*(volatile unsigned long *)(addr) = (datum)) #define inl(addr) (*(volatile unsigned long *)(addr)) @@ -501,48 +540,53 @@ static char ipod_scr[160 * (128/4)]; file arch/armnommu/mach-ipod/fb.c. A few modifications have been made. ***/ /* get current usec counter */ -static int M_timer_get_current(void) +static int +M_timer_get_current(void) { - return inl(lcd_rtc); + return inl(lcd_rtc); } /* check if number of useconds has past */ -static int M_timer_check(int clock_start, int usecs) +static int +M_timer_check(int clock_start, int usecs) { - unsigned long clock; - clock = inl(lcd_rtc); - - if ( (clock - clock_start) >= usecs ) { - return 1; - } else { - return 0; - } + unsigned long clock; + clock = inl(lcd_rtc); + + if ((clock - clock_start) >= usecs) { + return 1; + } else { + return 0; + } } /* wait for LCD with timeout */ -static void M_lcd_wait_write(void) +static void +M_lcd_wait_write(void) { - if ( (inl(lcd_base) & 0x8000) != 0 ) { - int start = M_timer_get_current(); - - do { - if ( (inl(lcd_base) & (unsigned int)0x8000) == 0 ) - break; - } while ( M_timer_check(start, 1000) == 0 ); - } + if ((inl(lcd_base) & 0x8000) != 0) { + int start = M_timer_get_current(); + + do { + if ((inl(lcd_base) & (unsigned int) 0x8000) == 0) + break; + } + while (M_timer_check(start, 1000) == 0); + } } /* send LCD data */ -static void M_lcd_send_data(int data_lo, int data_hi) +static void +M_lcd_send_data(int data_lo, int data_hi) { - M_lcd_wait_write(); - - outl(data_lo, lcd_base + LCD_DATA); - - M_lcd_wait_write(); - - outl(data_hi, lcd_base + LCD_DATA); + M_lcd_wait_write(); + + outl(data_lo, lcd_base + LCD_DATA); + + M_lcd_wait_write(); + + outl(data_hi, lcd_base + LCD_DATA); } @@ -550,184 +594,202 @@ static void M_lcd_send_data(int data_lo, int data_hi) static void M_lcd_prepare_cmd(int cmd) { - M_lcd_wait_write(); + M_lcd_wait_write(); - outl(0x0, lcd_base + LCD_CMD); + outl(0x0, lcd_base + LCD_CMD); + + M_lcd_wait_write(); + + outl(cmd, lcd_base + LCD_CMD); - M_lcd_wait_write(); - - outl(cmd, lcd_base + LCD_CMD); - } /* send LCD command and data */ -static void M_lcd_cmd_and_data(int cmd, int data_lo, int data_hi) +static void +M_lcd_cmd_and_data(int cmd, int data_lo, int data_hi) { - M_lcd_prepare_cmd(cmd); + M_lcd_prepare_cmd(cmd); - M_lcd_send_data(data_lo, data_hi); + M_lcd_send_data(data_lo, data_hi); } // Copied from uW -static void M_update_display(int sx, int sy, int mx, int my) +static void +M_update_display(int sx, int sy, int mx, int my) { - int y; - unsigned short cursor_pos; + int y; + unsigned short cursor_pos; - sx >>= 3; - mx >>= 3; + sx >>= 3; + mx >>= 3; - cursor_pos = sx + (sy << 5); + cursor_pos = sx + (sy << 5); - for ( y = sy; y <= my; y++ ) { - unsigned char *img_data; - int x; + for (y = sy; y <= my; y++) { + unsigned char *img_data; + int x; - /* move the cursor */ - M_lcd_cmd_and_data(0x11, cursor_pos >> 8, cursor_pos & 0xff); + /* move the cursor */ + M_lcd_cmd_and_data(0x11, cursor_pos >> 8, cursor_pos & 0xff); - /* setup for printing */ - M_lcd_prepare_cmd(0x12); + /* setup for printing */ + M_lcd_prepare_cmd(0x12); - img_data = ipod_scr + (sx << 1) + (y * (lcd_width/4)); + img_data = ipod_scr + (sx << 1) + (y * (lcd_width / 4)); - /* loops up to 160 times */ - for ( x = sx; x <= mx; x++ ) { - /* display eight pixels */ - M_lcd_send_data(*(img_data + 1), *img_data); + /* loops up to 160 times */ + for (x = sx; x <= mx; x++) { + /* display eight pixels */ + M_lcd_send_data(*(img_data + 1), *img_data); - img_data += 2; - } + img_data += 2; + } - /* update cursor pos counter */ - cursor_pos += 0x20; - } + /* update cursor pos counter */ + cursor_pos += 0x20; + } } /* get current usec counter */ -static int C_timer_get_current(void) +static int +C_timer_get_current(void) { - return inl(0x60005010); + return inl(0x60005010); } /* check if number of useconds has past */ -static int C_timer_check(int clock_start, int usecs) +static int +C_timer_check(int clock_start, int usecs) { - unsigned long clock; - clock = inl(0x60005010); - - if ( (clock - clock_start) >= usecs ) { - return 1; - } else { - return 0; - } + unsigned long clock; + clock = inl(0x60005010); + + if ((clock - clock_start) >= usecs) { + return 1; + } else { + return 0; + } } /* wait for LCD with timeout */ -static void C_lcd_wait_write(void) +static void +C_lcd_wait_write(void) { - if ((inl(0x70008A0C) & 0x80000000) != 0) { - int start = C_timer_get_current(); - - do { - if ((inl(0x70008A0C) & 0x80000000) == 0) - break; - } while (C_timer_check(start, 1000) == 0); - } + if ((inl(0x70008A0C) & 0x80000000) != 0) { + int start = C_timer_get_current(); + + do { + if ((inl(0x70008A0C) & 0x80000000) == 0) + break; + } + while (C_timer_check(start, 1000) == 0); + } } -static void C_lcd_cmd_data(int cmd, int data) +static void +C_lcd_cmd_data(int cmd, int data) { - C_lcd_wait_write(); - outl(cmd | 0x80000000, 0x70008A0C); + C_lcd_wait_write(); + outl(cmd | 0x80000000, 0x70008A0C); - C_lcd_wait_write(); - outl(data | 0x80000000, 0x70008A0C); + C_lcd_wait_write(); + outl(data | 0x80000000, 0x70008A0C); } -static void C_update_display(int sx, int sy, int mx, int my) +static void +C_update_display(int sx, int sy, int mx, int my) { - int height = (my - sy) + 1; - int width = (mx - sx) + 1; + int height = (my - sy) + 1; + int width = (mx - sx) + 1; - char *addr = SDL_VideoSurface->pixels; + char *addr = SDL_VideoSurface->pixels; - if (width & 1) width++; + if (width & 1) + width++; - /* start X and Y */ - C_lcd_cmd_data(0x12, (sy & 0xff)); - C_lcd_cmd_data(0x13, (((SDL_VideoSurface->w - 1) - sx) & 0xff)); + /* start X and Y */ + C_lcd_cmd_data(0x12, (sy & 0xff)); + C_lcd_cmd_data(0x13, (((SDL_VideoSurface->w - 1) - sx) & 0xff)); - /* max X and Y */ - C_lcd_cmd_data(0x15, (((sy + height) - 1) & 0xff)); - C_lcd_cmd_data(0x16, (((((SDL_VideoSurface->w - 1) - sx) - width) + 1) & 0xff)); + /* max X and Y */ + C_lcd_cmd_data(0x15, (((sy + height) - 1) & 0xff)); + C_lcd_cmd_data(0x16, + (((((SDL_VideoSurface->w - 1) - sx) - width) + 1) & 0xff)); - addr += sx + sy * SDL_VideoSurface->pitch; + addr += sx + sy * SDL_VideoSurface->pitch; - while (height > 0) { - int h, x, y, pixels_to_write; + while (height > 0) { + int h, x, y, pixels_to_write; - pixels_to_write = (width * height) * 2; + pixels_to_write = (width * height) * 2; - /* calculate how much we can do in one go */ - h = height; - if (pixels_to_write > 64000) { - h = (64000/2) / width; - pixels_to_write = (width * h) * 2; - } + /* calculate how much we can do in one go */ + h = height; + if (pixels_to_write > 64000) { + h = (64000 / 2) / width; + pixels_to_write = (width * h) * 2; + } - outl(0x10000080, 0x70008A20); - outl((pixels_to_write - 1) | 0xC0010000, 0x70008A24); - outl(0x34000000, 0x70008A20); + outl(0x10000080, 0x70008A20); + outl((pixels_to_write - 1) | 0xC0010000, 0x70008A24); + outl(0x34000000, 0x70008A20); - /* for each row */ - for (x = 0; x < h; x++) - { - /* for each column */ - for (y = 0; y < width; y += 2) { - unsigned two_pixels; + /* for each row */ + for (x = 0; x < h; x++) { + /* for each column */ + for (y = 0; y < width; y += 2) { + unsigned two_pixels; - two_pixels = addr[0] | (addr[1] << 16); - addr += 2; + two_pixels = addr[0] | (addr[1] << 16); + addr += 2; - while ((inl(0x70008A20) & 0x1000000) == 0); + while ((inl(0x70008A20) & 0x1000000) == 0); - /* output 2 pixels */ - outl(two_pixels, 0x70008B00); - } + /* output 2 pixels */ + outl(two_pixels, 0x70008B00); + } - addr += SDL_VideoSurface->w - width; - } + addr += SDL_VideoSurface->w - width; + } - while ((inl(0x70008A20) & 0x4000000) == 0); + while ((inl(0x70008A20) & 0x4000000) == 0); - outl(0x0, 0x70008A24); + outl(0x0, 0x70008A24); - height = height - h; - } + height = height - h; + } } // Should work with photo. However, I don't have one, so I'm not sure. -static void iPod_UpdateRects (_THIS, int nrects, SDL_Rect *rects) +static void +iPod_UpdateRects(_THIS, int nrects, SDL_Rect * rects) { if (SDL_VideoSurface->format->BitsPerPixel == 16) { - C_update_display (0, 0, lcd_width, lcd_height); + C_update_display(0, 0, lcd_width, lcd_height); } else { - int i, y, x; - for (i = 0; i < nrects; i++) { - SDL_Rect *r = rects + i; - if (!r) { - continue; - } - - for (y = r->y; (y < r->y + r->h) && y < lcd_height; y++) { - for (x = r->x; (x < r->x + r->w) && x < lcd_width; x++) { - ipod_scr[y*(lcd_width/4) + x/4] &= ~(3 << (2 * (x%4))); - ipod_scr[y*(lcd_width/4) + x/4] |= - (((Uint8*)(SDL_VideoSurface->pixels))[ y*SDL_VideoSurface->pitch + x ] & 3) << (2 * (x%4)); - } - } - } - - M_update_display (0, 0, lcd_width, lcd_height); + int i, y, x; + for (i = 0; i < nrects; i++) { + SDL_Rect *r = rects + i; + if (!r) { + continue; + } + + for (y = r->y; (y < r->y + r->h) && y < lcd_height; y++) { + for (x = r->x; (x < r->x + r->w) && x < lcd_width; x++) { + ipod_scr[y * (lcd_width / 4) + x / 4] &= + ~(3 << (2 * (x % 4))); + ipod_scr[y * (lcd_width / 4) + x / 4] |= + (((Uint8 *) (SDL_VideoSurface->pixels))[y * + SDL_VideoSurface-> + pitch + + + x] & + 3) << (2 * (x % 4)); + } + } + } + + M_update_display(0, 0, lcd_width, lcd_height); } } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/ipod/SDL_ipodvideo.h b/src/video/ipod/SDL_ipodvideo.h index a704f411c..c72b5c3d3 100644 --- a/src/video/ipod/SDL_ipodvideo.h +++ b/src/video/ipod/SDL_ipodvideo.h @@ -29,10 +29,12 @@ #ifndef _SDL_ipodvideo_h #define _SDL_ipodvideo_h -struct SDL_PrivateVideoData { +struct SDL_PrivateVideoData +{ char *buffer; int w, h; }; #endif +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/maccommon/SDL_lowvideo.h b/src/video/maccommon/SDL_lowvideo.h index 1f7316c4a..cf5bd50c1 100644 --- a/src/video/maccommon/SDL_lowvideo.h +++ b/src/video/maccommon/SDL_lowvideo.h @@ -45,44 +45,45 @@ typedef struct __AGLContextRec *AGLContext; /* Hidden "this" pointer for the video functions */ #define _THIS SDL_VideoDevice *this -#if !TARGET_API_MAC_CARBON /* not available in OS X (or more accurately, Carbon) */ +#if !TARGET_API_MAC_CARBON /* not available in OS X (or more accurately, Carbon) */ /* Global QuickDraw data */ extern QDGlobals *theQD; #endif /* Private display data */ -struct SDL_PrivateVideoData { - GDevice **SDL_Display; - WindowRef SDL_Window; - SDL_Rect **SDL_modelist; - CTabHandle SDL_CTab; - PaletteHandle SDL_CPal; +struct SDL_PrivateVideoData +{ + GDevice **SDL_Display; + WindowRef SDL_Window; + SDL_Rect **SDL_modelist; + CTabHandle SDL_CTab; + PaletteHandle SDL_CPal; #if TARGET_API_MAC_CARBON - /* For entering and leaving fullscreen mode */ - Ptr fullscreen_ctx; + /* For entering and leaving fullscreen mode */ + Ptr fullscreen_ctx; #endif - /* The current window document style */ - int current_style; + /* The current window document style */ + int current_style; - /* Information about the last cursor position */ - Point last_where; + /* Information about the last cursor position */ + Point last_where; - /* Information about the last keys down */ - EventModifiers last_mods; - KeyMap last_keys; + /* Information about the last keys down */ + EventModifiers last_mods; + KeyMap last_keys; - /* A handle to the Apple Menu */ - MenuRef apple_menu; + /* A handle to the Apple Menu */ + MenuRef apple_menu; - /* Information used by DrawSprocket driver */ - struct DSpInfo *dspinfo; + /* Information used by DrawSprocket driver */ + struct DSpInfo *dspinfo; #if SDL_VIDEO_OPENGL - AGLContext appleGLContext; + AGLContext appleGLContext; - void *libraryHandle; + void *libraryHandle; #endif }; /* Old variable names */ @@ -100,3 +101,4 @@ struct SDL_PrivateVideoData { #define glContext (this->hidden->appleGLContext) #endif /* _SDL_lowvideo_h */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/maccommon/SDL_macevents.c b/src/video/maccommon/SDL_macevents.c index 0e4f813e2..144f64bba 100644 --- a/src/video/maccommon/SDL_macevents.c +++ b/src/video/maccommon/SDL_macevents.c @@ -50,8 +50,8 @@ */ /* Macintosh resource constants */ -#define mApple 128 /* Apple menu resource */ -#define iAbout 1 /* About menu item */ +#define mApple 128 /* Apple menu resource */ +#define iAbout 1 /* About menu item */ /* Functions to handle the About menu */ static void Mac_DoAppleMenu(_THIS, long item); @@ -59,672 +59,705 @@ static void Mac_DoAppleMenu(_THIS, long item); /* The translation table from a macintosh key scancode to a SDL keysym */ static SDLKey MAC_keymap[256]; static SDL_keysym *TranslateKey(int scancode, int modifiers, - SDL_keysym *keysym, int pressed); + SDL_keysym * keysym, int pressed); /* Handle activation and deactivation -- returns whether an event was posted */ -static int Mac_HandleActivate(int activate) +static int +Mac_HandleActivate(int activate) { - if ( activate ) { - /* Show the current SDL application cursor */ - SDL_SetCursor(NULL); + if (activate) { + /* Show the current SDL application cursor */ + SDL_SetCursor(NULL); - /* put our mask back case it changed during context switch */ - SetEventMask(everyEvent & ~autoKeyMask); - } else { + /* put our mask back case it changed during context switch */ + SetEventMask(everyEvent & ~autoKeyMask); + } else { #if TARGET_API_MAC_CARBON - { Cursor cursor; - SetCursor(GetQDGlobalsArrow(&cursor)); - } + { + Cursor cursor; + SetCursor(GetQDGlobalsArrow(&cursor)); + } #else - SetCursor(&theQD->arrow); + SetCursor(&theQD->arrow); #endif - if ( ! Mac_cursor_showing ) { - ShowCursor(); - Mac_cursor_showing = 1; - } - } - return(SDL_PrivateAppActive(activate, SDL_APPINPUTFOCUS)); + if (!Mac_cursor_showing) { + ShowCursor(); + Mac_cursor_showing = 1; + } + } + return (SDL_PrivateAppActive(activate, SDL_APPINPUTFOCUS)); } -static void myGlobalToLocal(_THIS, Point *pt) +static void +myGlobalToLocal(_THIS, Point * pt) { - if ( SDL_VideoSurface && !(SDL_VideoSurface->flags&SDL_FULLSCREEN) ) { - GrafPtr saveport; - GetPort(&saveport); + if (SDL_VideoSurface && !(SDL_VideoSurface->flags & SDL_FULLSCREEN)) { + GrafPtr saveport; + GetPort(&saveport); #if TARGET_API_MAC_CARBON - SetPort(GetWindowPort(SDL_Window)); + SetPort(GetWindowPort(SDL_Window)); #else - SetPort(SDL_Window); + SetPort(SDL_Window); #endif - GlobalToLocal(pt); - SetPort(saveport); - } + GlobalToLocal(pt); + SetPort(saveport); + } } /* The main MacOS event handler */ -static int Mac_HandleEvents(_THIS, int wait4it) +static int +Mac_HandleEvents(_THIS, int wait4it) { - static int mouse_button = 1; - int i; - EventRecord event; + static int mouse_button = 1; + int i; + EventRecord event; #if TARGET_API_MAC_CARBON - /* There's no GetOSEvent() in the Carbon API. *sigh* */ + /* There's no GetOSEvent() in the Carbon API. *sigh* */ #define cooperative_multitasking 1 #else - int cooperative_multitasking; - /* If we're running fullscreen, we can hog the MacOS events, - otherwise we had better play nicely with the other apps. - */ - if ( this->screen && (this->screen->flags & SDL_FULLSCREEN) ) { - cooperative_multitasking = 0; - } else { - cooperative_multitasking = 1; - } + int cooperative_multitasking; + /* If we're running fullscreen, we can hog the MacOS events, + otherwise we had better play nicely with the other apps. + */ + if (this->screen && (this->screen->flags & SDL_FULLSCREEN)) { + cooperative_multitasking = 0; + } else { + cooperative_multitasking = 1; + } #endif - /* If we call WaitNextEvent(), MacOS will check other processes - * and allow them to run, and perform other high-level processing. - */ - if ( cooperative_multitasking || wait4it ) { - UInt32 wait_time; - - /* Are we polling or not? */ - if ( wait4it ) { - wait_time = 2147483647; - } else { - wait_time = 0; - } - WaitNextEvent(everyEvent, &event, wait_time, nil); - } else { + /* If we call WaitNextEvent(), MacOS will check other processes + * and allow them to run, and perform other high-level processing. + */ + if (cooperative_multitasking || wait4it) { + UInt32 wait_time; + + /* Are we polling or not? */ + if (wait4it) { + wait_time = 2147483647; + } else { + wait_time = 0; + } + WaitNextEvent(everyEvent, &event, wait_time, nil); + } else { #if ! TARGET_API_MAC_CARBON - GetOSEvent(everyEvent, &event); + GetOSEvent(everyEvent, &event); #endif - } + } #if TARGET_API_MAC_CARBON - /* for some reason, event.where isn't set ? */ - GetGlobalMouse ( &event.where ); + /* for some reason, event.where isn't set ? */ + GetGlobalMouse(&event.where); #endif - /* Check for mouse motion */ - if ( (event.where.h != last_where.h) || - (event.where.v != last_where.v) ) { - Point pt; - pt = last_where = event.where; - myGlobalToLocal(this, &pt); - SDL_PrivateMouseMotion(0, 0, pt.h, pt.v); - } - - /* Check the current state of the keyboard */ - if ( SDL_GetAppState() & SDL_APPINPUTFOCUS ) { - KeyMap keys; - - /* Check for special non-event keys */ - if ( event.modifiers != last_mods ) { - static struct { - EventModifiers mask; - SDLKey key; - } mods[] = { - { alphaLock, SDLK_CAPSLOCK }, -#if 0 /* These are handled below in the GetKeys() code */ - { cmdKey, SDLK_LMETA }, - { shiftKey, SDLK_LSHIFT }, - { rightShiftKey, SDLK_RSHIFT }, - { optionKey, SDLK_LALT }, - { rightOptionKey, SDLK_RALT }, - { controlKey, SDLK_LCTRL }, - { rightControlKey, SDLK_RCTRL }, + /* Check for mouse motion */ + if ((event.where.h != last_where.h) || (event.where.v != last_where.v)) { + Point pt; + pt = last_where = event.where; + myGlobalToLocal(this, &pt); + SDL_PrivateMouseMotion(0, 0, pt.h, pt.v); + } + + /* Check the current state of the keyboard */ + if (SDL_GetAppState() & SDL_APPINPUTFOCUS) { + KeyMap keys; + + /* Check for special non-event keys */ + if (event.modifiers != last_mods) { + static struct + { + EventModifiers mask; + SDLKey key; + } mods[] = { + { + alphaLock, SDLK_CAPSLOCK}, +#if 0 /* These are handled below in the GetKeys() code */ + { + cmdKey, SDLK_LMETA}, { + shiftKey, SDLK_LSHIFT}, { + rightShiftKey, SDLK_RSHIFT}, { + optionKey, SDLK_LALT}, { + rightOptionKey, SDLK_RALT}, { + controlKey, SDLK_LCTRL}, { + rightControlKey, SDLK_RCTRL}, #endif /* 0 */ - { 0, 0 } - }; - SDL_keysym keysym; - Uint8 mode; - EventModifiers mod, mask; - - - /* Set up the keyboard event */ - keysym.scancode = 0; - keysym.sym = SDLK_UNKNOWN; - keysym.mod = KMOD_NONE; - keysym.unicode = 0; - - /* See what has changed, and generate events */ - mod = event.modifiers; - for ( i=0; mods[i].mask; ++i ) { - mask = mods[i].mask; - if ( (mod&mask) != (last_mods&mask) ) { - keysym.sym = mods[i].key; - if ( (mod&mask) || - (mods[i].key == SDLK_CAPSLOCK) ) { - mode = SDL_PRESSED; - } else { - mode = SDL_RELEASED; - } - SDL_PrivateKeyboard(mode, &keysym); - } - } - - /* Save state for next time */ - last_mods = mod; - } - - /* Check for normal event keys, but we have to scan the - actual keyboard state because on Mac OS X a keydown event - is immediately followed by a keyup event. - */ - GetKeys(keys); - if ( (keys[0] != last_keys[0]) || (keys[1] != last_keys[1]) || - (keys[2] != last_keys[2]) || (keys[3] != last_keys[3]) ) { - SDL_keysym keysym; - int old_bit, new_bit; + { + 0, 0} + }; + SDL_keysym keysym; + Uint8 mode; + EventModifiers mod, mask; + + + /* Set up the keyboard event */ + keysym.scancode = 0; + keysym.sym = SDLK_UNKNOWN; + keysym.mod = KMOD_NONE; + keysym.unicode = 0; + + /* See what has changed, and generate events */ + mod = event.modifiers; + for (i = 0; mods[i].mask; ++i) { + mask = mods[i].mask; + if ((mod & mask) != (last_mods & mask)) { + keysym.sym = mods[i].key; + if ((mod & mask) || (mods[i].key == SDLK_CAPSLOCK)) { + mode = SDL_PRESSED; + } else { + mode = SDL_RELEASED; + } + SDL_PrivateKeyboard(mode, &keysym); + } + } + + /* Save state for next time */ + last_mods = mod; + } + + /* Check for normal event keys, but we have to scan the + actual keyboard state because on Mac OS X a keydown event + is immediately followed by a keyup event. + */ + GetKeys(keys); + if ((keys[0] != last_keys[0]) || (keys[1] != last_keys[1]) || + (keys[2] != last_keys[2]) || (keys[3] != last_keys[3])) { + SDL_keysym keysym; + int old_bit, new_bit; #ifdef DEBUG_KEYBOARD - fprintf(sterr, "New keys: 0x%x 0x%x 0x%x 0x%x\n", - new_keys[0], new_keys[1], - new_keys[2], new_keys[3]); + fprintf(sterr, "New keys: 0x%x 0x%x 0x%x 0x%x\n", + new_keys[0], new_keys[1], new_keys[2], new_keys[3]); #endif - for ( i=0; i<128; ++i ) { - old_bit = (((Uint8 *)last_keys)[i/8]>>(i%8)) & 0x01; - new_bit = (((Uint8 *)keys)[i/8]>>(i%8)) & 0x01; - if ( old_bit != new_bit ) { - /* Post the keyboard event */ + for (i = 0; i < 128; ++i) { + old_bit = (((Uint8 *) last_keys)[i / 8] >> (i % 8)) & 0x01; + new_bit = (((Uint8 *) keys)[i / 8] >> (i % 8)) & 0x01; + if (old_bit != new_bit) { + /* Post the keyboard event */ #ifdef DEBUG_KEYBOARD - fprintf(stderr,"Scancode: 0x%2.2X\n",i); + fprintf(stderr, "Scancode: 0x%2.2X\n", i); #endif - SDL_PrivateKeyboard(new_bit, - TranslateKey(i, event.modifiers, - &keysym, new_bit)); - } - } - - /* Save state for next time */ - last_keys[0] = keys[0]; - last_keys[1] = keys[1]; - last_keys[2] = keys[2]; - last_keys[3] = keys[3]; - } - } - - /* Handle normal events */ - switch (event.what) { - case mouseDown: { - WindowRef win; - short area; - - area = FindWindow(event.where, &win); - /* Support switching between the SIOUX console - and SDL_Window by clicking in the window. - */ - if ( win && (win != FrontWindow()) ) { - SelectWindow(win); - } - switch (area) { - case inMenuBar: /* Only the apple menu exists */ - Mac_DoAppleMenu(this, MenuSelect(event.where)); - HiliteMenu(0); - break; - case inDrag: + SDL_PrivateKeyboard(new_bit, + TranslateKey(i, + event. + modifiers, + &keysym, new_bit)); + } + } + + /* Save state for next time */ + last_keys[0] = keys[0]; + last_keys[1] = keys[1]; + last_keys[2] = keys[2]; + last_keys[3] = keys[3]; + } + } + + /* Handle normal events */ + switch (event.what) { + case mouseDown: + { + WindowRef win; + short area; + + area = FindWindow(event.where, &win); + /* Support switching between the SIOUX console + and SDL_Window by clicking in the window. + */ + if (win && (win != FrontWindow())) { + SelectWindow(win); + } + switch (area) { + case inMenuBar: /* Only the apple menu exists */ + Mac_DoAppleMenu(this, MenuSelect(event.where)); + HiliteMenu(0); + break; + case inDrag: #if TARGET_API_MAC_CARBON - DragWindow(win, event.where, NULL); + DragWindow(win, event.where, NULL); #else - DragWindow(win, event.where, &theQD->screenBits.bounds); + DragWindow(win, event.where, &theQD->screenBits.bounds); #endif - break; - case inGoAway: - if ( TrackGoAway(win, event.where) ) { - SDL_PrivateQuit(); - } - break; - case inContent: - myGlobalToLocal(this, &event.where); - /* Treat command-click as right mouse button */ - if ( event.modifiers & optionKey ) { - mouse_button = 2; - } else if ( event.modifiers & cmdKey ) { - mouse_button = 3; - } else { - mouse_button = 1; - } - SDL_PrivateMouseButton(SDL_PRESSED, - mouse_button, event.where.h, event.where.v); - break; - case inGrow: { - int newSize; - - /* Don't allow resize if video mode isn't resizable */ - if ( ! SDL_PublicSurface || - ! (SDL_PublicSurface->flags & SDL_RESIZABLE) ) { - break; - } + break; + case inGoAway: + if (TrackGoAway(win, event.where)) { + SDL_PrivateQuit(); + } + break; + case inContent: + myGlobalToLocal(this, &event.where); + /* Treat command-click as right mouse button */ + if (event.modifiers & optionKey) { + mouse_button = 2; + } else if (event.modifiers & cmdKey) { + mouse_button = 3; + } else { + mouse_button = 1; + } + SDL_PrivateMouseButton(SDL_PRESSED, + mouse_button, event.where.h, + event.where.v); + break; + case inGrow: + { + int newSize; + + /* Don't allow resize if video mode isn't resizable */ + if (!SDL_PublicSurface || + !(SDL_PublicSurface->flags & SDL_RESIZABLE)) { + break; + } #if TARGET_API_MAC_CARBON - newSize = GrowWindow(win, event.where, NULL); + newSize = GrowWindow(win, event.where, NULL); #else - newSize = GrowWindow(win, event.where, &theQD->screenBits.bounds); + newSize = + GrowWindow(win, event.where, + &theQD->screenBits.bounds); #endif - if ( newSize ) { + if (newSize) { #if !TARGET_API_MAC_CARBON - EraseRect ( &theQD->screenBits.bounds ); + EraseRect(&theQD->screenBits.bounds); #endif - SizeWindow ( win, LoWord (newSize), HiWord (newSize), 1 ); - SDL_PrivateResize ( LoWord (newSize), HiWord (newSize) ); - } - } break; - case inZoomIn: - case inZoomOut: - if ( TrackBox (win, event.where, area )) { - Rect rect; + SizeWindow(win, LoWord(newSize), HiWord(newSize), 1); + SDL_PrivateResize(LoWord(newSize), HiWord(newSize)); + } + } + break; + case inZoomIn: + case inZoomOut: + if (TrackBox(win, event.where, area)) { + Rect rect; #if !TARGET_API_MAC_CARBON - EraseRect ( &theQD->screenBits.bounds ); + EraseRect(&theQD->screenBits.bounds); #endif - ZoomWindow ( win, area, 0); - if ( area == inZoomIn ) { - GetWindowUserState(SDL_Window, &rect); - } else { - GetWindowStandardState(SDL_Window, &rect); - } - SDL_PrivateResize (rect.right-rect.left, - rect.bottom-rect.top); - } - break; + ZoomWindow(win, area, 0); + if (area == inZoomIn) { + GetWindowUserState(SDL_Window, &rect); + } else { + GetWindowStandardState(SDL_Window, &rect); + } + SDL_PrivateResize(rect.right - rect.left, + rect.bottom - rect.top); + } + break; #if TARGET_API_MAC_CARBON - case inCollapseBox: - if ( TrackBox (win, event.where, area )) { - if ( IsWindowCollapsable(win) ) { - CollapseWindow (win, !IsWindowCollapsed(win)); - /* There should be something done like in inGrow case, but... */ - } - } - break; + case inCollapseBox: + if (TrackBox(win, event.where, area)) { + if (IsWindowCollapsable(win)) { + CollapseWindow(win, !IsWindowCollapsed(win)); + /* There should be something done like in inGrow case, but... */ + } + } + break; #endif /* TARGET_API_MAC_CARBON */ - case inSysWindow: + case inSysWindow: #if TARGET_API_MAC_CARBON - /* Never happens in Carbon? */ + /* Never happens in Carbon? */ #else - SystemClick(&event, win); + SystemClick(&event, win); #endif - break; - default: - break; - } - } - break; - case mouseUp: { - myGlobalToLocal(this, &event.where); - /* Release the mouse button we simulated in the last press. - The drawback of this methos is we cannot press more than - one button. However, this doesn't matter, since there is - only a single logical mouse button, even if you have a - multi-button mouse, this doesn't matter at all. - */ - SDL_PrivateMouseButton(SDL_RELEASED, - mouse_button, event.where.h, event.where.v); - } - break; -#if 0 /* Handled above the switch statement */ - case keyDown: { - SDL_keysym keysym; - - SDL_PrivateKeyboard(SDL_PRESSED, - TranslateKey((event.message&keyCodeMask)>>8 - event.modifiers, &keysym, 1)); - } - break; - case keyUp: { - SDL_keysym keysym; - - SDL_PrivateKeyboard(SDL_RELEASED, - TranslateKey((event.message&keyCodeMask)>>8 - event.modifiers, &keysym, 0)); - } - break; + break; + default: + break; + } + } + break; + case mouseUp: + { + myGlobalToLocal(this, &event.where); + /* Release the mouse button we simulated in the last press. + The drawback of this methos is we cannot press more than + one button. However, this doesn't matter, since there is + only a single logical mouse button, even if you have a + multi-button mouse, this doesn't matter at all. + */ + SDL_PrivateMouseButton(SDL_RELEASED, + mouse_button, event.where.h, + event.where.v); + } + break; +#if 0 /* Handled above the switch statement */ + case keyDown: + { + SDL_keysym keysym; + + SDL_PrivateKeyboard(SDL_PRESSED, + TranslateKey((event. + message & keyCodeMask) >> 8 + event.modifiers, &keysym, 1)); + } + break; + case keyUp: + { + SDL_keysym keysym; + + SDL_PrivateKeyboard(SDL_RELEASED, + TranslateKey((event. + message & keyCodeMask) >> 8 + event.modifiers, &keysym, 0)); + } + break; #endif - case updateEvt: { - BeginUpdate(SDL_Window); - #if SDL_VIDEO_OPENGL - if (SDL_VideoSurface->flags & SDL_OPENGL) - SDL_GL_SwapBuffers(); - else - #endif - if ( (SDL_VideoSurface->flags & SDL_HWSURFACE) == - SDL_SWSURFACE ) { - SDL_UpdateRect(SDL_VideoSurface, 0, 0, 0, 0); - } - EndUpdate(SDL_Window); - } - /* If this was an update event for the SIOUX console, we return 0 - in order to stop an endless series of updates being triggered. - */ - if ( (WindowRef) event.message != SDL_Window ) { - return 0; - } - break; - case activateEvt: { - Mac_HandleActivate(!!(event.modifiers & activeFlag)); - } - break; - case diskEvt: { + case updateEvt: + { + BeginUpdate(SDL_Window); +#if SDL_VIDEO_OPENGL + if (SDL_VideoSurface->flags & SDL_INTERNALOPENGL) + SDL_GL_SwapBuffers(); + else +#endif + if ((SDL_VideoSurface->flags & SDL_HWSURFACE) == SDL_SWSURFACE) { + SDL_UpdateRect(SDL_VideoSurface, 0, 0, 0, 0); + } + EndUpdate(SDL_Window); + } + /* If this was an update event for the SIOUX console, we return 0 + in order to stop an endless series of updates being triggered. + */ + if ((WindowRef) event.message != SDL_Window) { + return 0; + } + break; + case activateEvt: + { + Mac_HandleActivate(!!(event.modifiers & activeFlag)); + } + break; + case diskEvt: + { #if TARGET_API_MAC_CARBON - /* What are we supposed to do? */; + /* What are we supposed to do? */ ; #else - if ( ((event.message>>16)&0xFFFF) != noErr ) { - Point spot; - SetPt(&spot, 0x0070, 0x0050); - DIBadMount(spot, event.message); - } + if (((event.message >> 16) & 0xFFFF) != noErr) { + Point spot; + SetPt(&spot, 0x0070, 0x0050); + DIBadMount(spot, event.message); + } #endif - } - break; - case osEvt: { - switch ((event.message>>24) & 0xFF) { -#if 0 /* Handled above the switch statement */ - case mouseMovedMessage: { - myGlobalToLocal(this, &event.where); - SDL_PrivateMouseMotion(0, 0, - event.where.h, event.where.v); - } - break; + } + break; + case osEvt: + { + switch ((event.message >> 24) & 0xFF) { +#if 0 /* Handled above the switch statement */ + case mouseMovedMessage: + { + myGlobalToLocal(this, &event.where); + SDL_PrivateMouseMotion(0, 0, + event.where.h, event.where.v); + } + break; #endif /* 0 */ - case suspendResumeMessage: { - Mac_HandleActivate(!!(event.message & resumeFlag)); - } - break; - } - } - break; - default: { - ; - } - break; - } - return (event.what != nullEvent); + case suspendResumeMessage: + { + Mac_HandleActivate(!!(event.message & resumeFlag)); + } + break; + } + } + break; + default: + { + ; + } + break; + } + return (event.what != nullEvent); } -void Mac_PumpEvents(_THIS) +void +Mac_PumpEvents(_THIS) { - /* Process pending MacOS events */ - while ( Mac_HandleEvents(this, 0) ) { - /* Loop and check again */; - } + /* Process pending MacOS events */ + while (Mac_HandleEvents(this, 0)) { + /* Loop and check again */ ; + } } -void Mac_InitOSKeymap(_THIS) +void +Mac_InitOSKeymap(_THIS) { - const void *KCHRPtr; - UInt32 state; - UInt32 value; - int i; - int world = SDLK_WORLD_0; - - /* Map the MAC keysyms */ - for ( i=0; ikeysym map. However, it will not - * work very well on international keyboard. Hence we now query MacOS - * for its own keymap to adjust our own mapping table. However, this is - * bascially only useful for ascii char keys. This is also the reason - * why we keep the static table, too. - */ - - /* Get a pointer to the systems cached KCHR */ - KCHRPtr = (void *)GetScriptManagerVariable(smKCHRCache); - if (KCHRPtr) - { - /* Loop over all 127 possible scan codes */ - for (i = 0; i < 0x7F; i++) - { - /* We pretend a clean start to begin with (i.e. no dead keys active */ - state = 0; - - /* Now translate the key code to a key value */ - value = KeyTranslate(KCHRPtr, i, &state) & 0xff; - - /* If the state become 0, it was a dead key. We need to translate again, - passing in the new state, to get the actual key value */ - if (state != 0) - value = KeyTranslate(KCHRPtr, i, &state) & 0xff; - - /* Now we should have an ascii value, or 0. Try to figure out to which SDL symbol it maps */ - if (value >= 128) /* Some non-ASCII char, map it to SDLK_WORLD_* */ - MAC_keymap[i] = world++; - else if (value >= 32) /* non-control ASCII char */ - MAC_keymap[i] = value; - } - } - - /* The keypad codes are re-setup here, because the loop above cannot - * distinguish between a key on the keypad and a regular key. We maybe - * could get around this problem in another fashion: NSEvent's flags - * include a "NSNumericPadKeyMask" bit; we could check that and modify - * the symbol we return on the fly. However, this flag seems to exhibit - * some weird behaviour related to the num lock key - */ - MAC_keymap[MK_KP0] = SDLK_KP0; - MAC_keymap[MK_KP1] = SDLK_KP1; - MAC_keymap[MK_KP2] = SDLK_KP2; - MAC_keymap[MK_KP3] = SDLK_KP3; - MAC_keymap[MK_KP4] = SDLK_KP4; - MAC_keymap[MK_KP5] = SDLK_KP5; - MAC_keymap[MK_KP6] = SDLK_KP6; - MAC_keymap[MK_KP7] = SDLK_KP7; - MAC_keymap[MK_KP8] = SDLK_KP8; - MAC_keymap[MK_KP9] = SDLK_KP9; - MAC_keymap[MK_KP_MINUS] = SDLK_KP_MINUS; - MAC_keymap[MK_KP_PLUS] = SDLK_KP_PLUS; - MAC_keymap[MK_KP_PERIOD] = SDLK_KP_PERIOD; - MAC_keymap[MK_KP_EQUALS] = SDLK_KP_EQUALS; - MAC_keymap[MK_KP_DIVIDE] = SDLK_KP_DIVIDE; - MAC_keymap[MK_KP_MULTIPLY] = SDLK_KP_MULTIPLY; - MAC_keymap[MK_KP_ENTER] = SDLK_KP_ENTER; + /* Up there we setup a static scancode->keysym map. However, it will not + * work very well on international keyboard. Hence we now query MacOS + * for its own keymap to adjust our own mapping table. However, this is + * bascially only useful for ascii char keys. This is also the reason + * why we keep the static table, too. + */ + + /* Get a pointer to the systems cached KCHR */ + KCHRPtr = (void *) GetScriptManagerVariable(smKCHRCache); + if (KCHRPtr) { + /* Loop over all 127 possible scan codes */ + for (i = 0; i < 0x7F; i++) { + /* We pretend a clean start to begin with (i.e. no dead keys active */ + state = 0; + + /* Now translate the key code to a key value */ + value = KeyTranslate(KCHRPtr, i, &state) & 0xff; + + /* If the state become 0, it was a dead key. We need to translate again, + passing in the new state, to get the actual key value */ + if (state != 0) + value = KeyTranslate(KCHRPtr, i, &state) & 0xff; + + /* Now we should have an ascii value, or 0. Try to figure out to which SDL symbol it maps */ + if (value >= 128) /* Some non-ASCII char, map it to SDLK_WORLD_* */ + MAC_keymap[i] = world++; + else if (value >= 32) /* non-control ASCII char */ + MAC_keymap[i] = value; + } + } + + /* The keypad codes are re-setup here, because the loop above cannot + * distinguish between a key on the keypad and a regular key. We maybe + * could get around this problem in another fashion: NSEvent's flags + * include a "NSNumericPadKeyMask" bit; we could check that and modify + * the symbol we return on the fly. However, this flag seems to exhibit + * some weird behaviour related to the num lock key + */ + MAC_keymap[MK_KP0] = SDLK_KP0; + MAC_keymap[MK_KP1] = SDLK_KP1; + MAC_keymap[MK_KP2] = SDLK_KP2; + MAC_keymap[MK_KP3] = SDLK_KP3; + MAC_keymap[MK_KP4] = SDLK_KP4; + MAC_keymap[MK_KP5] = SDLK_KP5; + MAC_keymap[MK_KP6] = SDLK_KP6; + MAC_keymap[MK_KP7] = SDLK_KP7; + MAC_keymap[MK_KP8] = SDLK_KP8; + MAC_keymap[MK_KP9] = SDLK_KP9; + MAC_keymap[MK_KP_MINUS] = SDLK_KP_MINUS; + MAC_keymap[MK_KP_PLUS] = SDLK_KP_PLUS; + MAC_keymap[MK_KP_PERIOD] = SDLK_KP_PERIOD; + MAC_keymap[MK_KP_EQUALS] = SDLK_KP_EQUALS; + MAC_keymap[MK_KP_DIVIDE] = SDLK_KP_DIVIDE; + MAC_keymap[MK_KP_MULTIPLY] = SDLK_KP_MULTIPLY; + MAC_keymap[MK_KP_ENTER] = SDLK_KP_ENTER; } -static SDL_keysym *TranslateKey(int scancode, int modifiers, - SDL_keysym *keysym, int pressed) +static SDL_keysym * +TranslateKey(int scancode, int modifiers, SDL_keysym * keysym, int pressed) { - /* Set the keysym information */ - keysym->scancode = scancode; - keysym->sym = MAC_keymap[keysym->scancode]; - keysym->mod = KMOD_NONE; - keysym->unicode = 0; - if ( pressed && SDL_TranslateUNICODE ) { - static unsigned long state = 0; - static Ptr keymap = nil; - Ptr new_keymap; - - /* Get the current keyboard map resource */ - new_keymap = (Ptr)GetScriptManagerVariable(smKCHRCache); - if ( new_keymap != keymap ) { - keymap = new_keymap; - state = 0; - } - keysym->unicode = KeyTranslate(keymap, - keysym->scancode|modifiers, &state) & 0xFFFF; - } - return(keysym); + /* Set the keysym information */ + keysym->scancode = scancode; + keysym->sym = MAC_keymap[keysym->scancode]; + keysym->mod = KMOD_NONE; + keysym->unicode = 0; + if (pressed && SDL_TranslateUNICODE) { + static unsigned long state = 0; + static Ptr keymap = nil; + Ptr new_keymap; + + /* Get the current keyboard map resource */ + new_keymap = (Ptr) GetScriptManagerVariable(smKCHRCache); + if (new_keymap != keymap) { + keymap = new_keymap; + state = 0; + } + keysym->unicode = KeyTranslate(keymap, + keysym->scancode | modifiers, + &state) & 0xFFFF; + } + return (keysym); } -void Mac_InitEvents(_THIS) +void +Mac_InitEvents(_THIS) { - /* Create apple menu bar */ - apple_menu = GetMenu(mApple); - if ( apple_menu != nil ) { - AppendResMenu(apple_menu, 'DRVR'); - InsertMenu(apple_menu, 0); - } - DrawMenuBar(); - - /* Get rid of spurious events at startup */ - FlushEvents(everyEvent, 0); - - /* Allow every event but keyrepeat */ - SetEventMask(everyEvent & ~autoKeyMask); + /* Create apple menu bar */ + apple_menu = GetMenu(mApple); + if (apple_menu != nil) { + AppendResMenu(apple_menu, 'DRVR'); + InsertMenu(apple_menu, 0); + } + DrawMenuBar(); + + /* Get rid of spurious events at startup */ + FlushEvents(everyEvent, 0); + + /* Allow every event but keyrepeat */ + SetEventMask(everyEvent & ~autoKeyMask); } -void Mac_QuitEvents(_THIS) +void +Mac_QuitEvents(_THIS) { - ClearMenuBar(); - if ( apple_menu != nil ) { - ReleaseResource((char **)apple_menu); - } + ClearMenuBar(); + if (apple_menu != nil) { + ReleaseResource((char **) apple_menu); + } - /* Clean up pending events */ - FlushEvents(everyEvent, 0); + /* Clean up pending events */ + FlushEvents(everyEvent, 0); } -static void Mac_DoAppleMenu(_THIS, long choice) +static void +Mac_DoAppleMenu(_THIS, long choice) { -#if !TARGET_API_MAC_CARBON /* No Apple menu in OS X */ - short menu, item; - - item = (choice&0xFFFF); - choice >>= 16; - menu = (choice&0xFFFF); - - switch (menu) { - case mApple: { - switch (item) { - case iAbout: { - /* Run the about box */; - } - break; - default: { - Str255 name; - - GetMenuItemText(apple_menu, item, name); - OpenDeskAcc(name); - } - break; - } - } - break; - default: { - /* Ignore other menus */; - } - } +#if !TARGET_API_MAC_CARBON /* No Apple menu in OS X */ + short menu, item; + + item = (choice & 0xFFFF); + choice >>= 16; + menu = (choice & 0xFFFF); + + switch (menu) { + case mApple: + { + switch (item) { + case iAbout: + { + /* Run the about box */ ; + } + break; + default: + { + Str255 name; + + GetMenuItemText(apple_menu, item, name); + OpenDeskAcc(name); + } + break; + } + } + break; + default: + { + /* Ignore other menus */ ; + } + } #endif /* !TARGET_API_MAC_CARBON */ } @@ -734,9 +767,12 @@ QDGlobals *theQD = NULL; #endif /* Exported to the macmain code */ -void SDL_InitQuickDraw(struct QDGlobals *the_qd) +void +SDL_InitQuickDraw(struct QDGlobals *the_qd) { #if !TARGET_API_MAC_CARBON - theQD = the_qd; + theQD = the_qd; #endif } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/maccommon/SDL_macevents_c.h b/src/video/maccommon/SDL_macevents_c.h index 8ea92ae44..8f7835e92 100644 --- a/src/video/maccommon/SDL_macevents_c.h +++ b/src/video/maccommon/SDL_macevents_c.h @@ -30,3 +30,4 @@ extern void Mac_QuitEvents(_THIS); extern void Mac_InitOSKeymap(_THIS); extern void Mac_PumpEvents(_THIS); +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/maccommon/SDL_macgl.c b/src/video/maccommon/SDL_macgl.c index 76bc52927..8153bbbe8 100644 --- a/src/video/maccommon/SDL_macgl.c +++ b/src/video/maccommon/SDL_macgl.c @@ -29,169 +29,175 @@ /* krat: adding OpenGL support */ -int Mac_GL_Init(_THIS) +int +Mac_GL_Init(_THIS) { #if SDL_VIDEO_OPENGL - AGLPixelFormat format; - int i = 0; - GLint attributes [ 26 ]; /* 26 is max possible in this setup */ - GLboolean noerr; - - /* load the gl driver from a default path */ - if ( ! this->gl_config.driver_loaded ) { - /* no driver has been loaded, use default (ourselves) */ - if ( Mac_GL_LoadLibrary(this, NULL) < 0 ) { - return(-1); - } - } - - attributes[i++] = AGL_RGBA; - if ( this->gl_config.red_size != 0 && - this->gl_config.blue_size != 0 && - this->gl_config.green_size != 0 ) { - attributes[i++] = AGL_RED_SIZE; - attributes[i++] = this->gl_config.red_size; - attributes[i++] = AGL_GREEN_SIZE; - attributes[i++] = this->gl_config.green_size; - attributes[i++] = AGL_BLUE_SIZE; - attributes[i++] = this->gl_config.blue_size; - attributes[i++] = AGL_ALPHA_SIZE; - attributes[i++] = this->gl_config.alpha_size; - } - if ( this->gl_config.double_buffer ) { - attributes[i++] = AGL_DOUBLEBUFFER; - } - if ( this->gl_config.depth_size != 0 ) { - attributes[i++] = AGL_DEPTH_SIZE; - attributes[i++] = this->gl_config.depth_size; - } - if ( this->gl_config.stencil_size != 0 ) { - attributes[i++] = AGL_STENCIL_SIZE; - attributes[i++] = this->gl_config.stencil_size; - } - if ( this->gl_config.accum_red_size != 0 && - this->gl_config.accum_blue_size != 0 && - this->gl_config.accum_green_size != 0 ) { - - attributes[i++] = AGL_ACCUM_RED_SIZE; - attributes[i++] = this->gl_config.accum_red_size; - attributes[i++] = AGL_ACCUM_GREEN_SIZE; - attributes[i++] = this->gl_config.accum_green_size; - attributes[i++] = AGL_ACCUM_BLUE_SIZE; - attributes[i++] = this->gl_config.accum_blue_size; - attributes[i++] = AGL_ACCUM_ALPHA_SIZE; - attributes[i++] = this->gl_config.accum_alpha_size; - } - if ( this->gl_config.stereo ) { - attributes[i++] = AGL_STEREO; - } + AGLPixelFormat format; + int i = 0; + GLint attributes[26]; /* 26 is max possible in this setup */ + GLboolean noerr; + + /* load the gl driver from a default path */ + if (!this->gl_config.driver_loaded) { + /* no driver has been loaded, use default (ourselves) */ + if (Mac_GL_LoadLibrary(this, NULL) < 0) { + return (-1); + } + } + + attributes[i++] = AGL_RGBA; + if (this->gl_config.red_size != 0 && + this->gl_config.blue_size != 0 && this->gl_config.green_size != 0) { + attributes[i++] = AGL_RED_SIZE; + attributes[i++] = this->gl_config.red_size; + attributes[i++] = AGL_GREEN_SIZE; + attributes[i++] = this->gl_config.green_size; + attributes[i++] = AGL_BLUE_SIZE; + attributes[i++] = this->gl_config.blue_size; + attributes[i++] = AGL_ALPHA_SIZE; + attributes[i++] = this->gl_config.alpha_size; + } + if (this->gl_config.double_buffer) { + attributes[i++] = AGL_DOUBLEBUFFER; + } + if (this->gl_config.depth_size != 0) { + attributes[i++] = AGL_DEPTH_SIZE; + attributes[i++] = this->gl_config.depth_size; + } + if (this->gl_config.stencil_size != 0) { + attributes[i++] = AGL_STENCIL_SIZE; + attributes[i++] = this->gl_config.stencil_size; + } + if (this->gl_config.accum_red_size != 0 && + this->gl_config.accum_blue_size != 0 && + this->gl_config.accum_green_size != 0) { + + attributes[i++] = AGL_ACCUM_RED_SIZE; + attributes[i++] = this->gl_config.accum_red_size; + attributes[i++] = AGL_ACCUM_GREEN_SIZE; + attributes[i++] = this->gl_config.accum_green_size; + attributes[i++] = AGL_ACCUM_BLUE_SIZE; + attributes[i++] = this->gl_config.accum_blue_size; + attributes[i++] = AGL_ACCUM_ALPHA_SIZE; + attributes[i++] = this->gl_config.accum_alpha_size; + } + if (this->gl_config.stereo) { + attributes[i++] = AGL_STEREO; + } #if defined(AGL_SAMPLE_BUFFERS_ARB) && defined(AGL_SAMPLES_ARB) - if ( this->gl_config.multisamplebuffers != 0 ) { - attributes[i++] = AGL_SAMPLE_BUFFERS_ARB; - attributes[i++] = this->gl_config.multisamplebuffers; - } - if ( this->gl_config.multisamplesamples != 0 ) { - attributes[i++] = AGL_SAMPLES_ARB; - attributes[i++] = this->gl_config.multisamplesamples; - } + if (this->gl_config.multisamplebuffers != 0) { + attributes[i++] = AGL_SAMPLE_BUFFERS_ARB; + attributes[i++] = this->gl_config.multisamplebuffers; + } + if (this->gl_config.multisamplesamples != 0) { + attributes[i++] = AGL_SAMPLES_ARB; + attributes[i++] = this->gl_config.multisamplesamples; + } #endif - if ( this->gl_config.accelerated > 0 ) { - attributes[i++] = AGL_ACCELERATED; - attributes[i++] = AGL_NO_RECOVERY; - } - - attributes[i++] = AGL_ALL_RENDERERS; - attributes[i] = AGL_NONE; - - format = aglChoosePixelFormat(NULL, 0, attributes); - if ( format == NULL ) { - SDL_SetError("Couldn't match OpenGL desired format"); - return(-1); - } - - glContext = aglCreateContext(format, NULL); - if ( glContext == NULL ) { - SDL_SetError("Couldn't create OpenGL context"); - return(-1); - } - aglDestroyPixelFormat(format); - - #if TARGET_API_MAC_CARBON - noerr = aglSetDrawable(glContext, GetWindowPort(SDL_Window)); - #else - noerr = aglSetDrawable(glContext, (AGLDrawable)SDL_Window); - #endif - - if(!noerr) { - SDL_SetError("Unable to bind GL context to window"); - return(-1); - } - return(0); + if (this->gl_config.accelerated > 0) { + attributes[i++] = AGL_ACCELERATED; + attributes[i++] = AGL_NO_RECOVERY; + } + + attributes[i++] = AGL_ALL_RENDERERS; + attributes[i] = AGL_NONE; + + format = aglChoosePixelFormat(NULL, 0, attributes); + if (format == NULL) { + SDL_SetError("Couldn't match OpenGL desired format"); + return (-1); + } + + glContext = aglCreateContext(format, NULL); + if (glContext == NULL) { + SDL_SetError("Couldn't create OpenGL context"); + return (-1); + } + aglDestroyPixelFormat(format); + +#if TARGET_API_MAC_CARBON + noerr = aglSetDrawable(glContext, GetWindowPort(SDL_Window)); #else - SDL_SetError("OpenGL support not configured"); - return(-1); + noerr = aglSetDrawable(glContext, (AGLDrawable) SDL_Window); +#endif + + if (!noerr) { + SDL_SetError("Unable to bind GL context to window"); + return (-1); + } + return (0); +#else + SDL_SetError("OpenGL support not configured"); + return (-1); #endif } -void Mac_GL_Quit(_THIS) +void +Mac_GL_Quit(_THIS) { #if SDL_VIDEO_OPENGL - if ( glContext != NULL ) { - aglSetCurrentContext(NULL); - aglSetDrawable(glContext, NULL); - aglDestroyContext(glContext); - glContext = NULL; - } + if (glContext != NULL) { + aglSetCurrentContext(NULL); + aglSetDrawable(glContext, NULL); + aglDestroyContext(glContext); + glContext = NULL; + } #endif } #if SDL_VIDEO_OPENGL /* Make the current context active */ -int Mac_GL_MakeCurrent(_THIS) +int +Mac_GL_MakeCurrent(_THIS) { - int retval; - - retval = 0; - if( ! aglSetCurrentContext(glContext) ) { - SDL_SetError("Unable to make GL context current"); - retval = -1; - } - return(retval); + int retval; + + retval = 0; + if (!aglSetCurrentContext(glContext)) { + SDL_SetError("Unable to make GL context current"); + retval = -1; + } + return (retval); } -void Mac_GL_SwapBuffers(_THIS) +void +Mac_GL_SwapBuffers(_THIS) { - aglSwapBuffers(glContext); + aglSwapBuffers(glContext); } -int Mac_GL_LoadLibrary(_THIS, const char *location) +int +Mac_GL_LoadLibrary(_THIS, const char *location) { - if (location == NULL) + if (location == NULL) #if __MACH__ - location = "/System/Library/Frameworks/OpenGL.framework/OpenGL"; + location = "/System/Library/Frameworks/OpenGL.framework/OpenGL"; #else - location = "OpenGLLibrary"; + location = "OpenGLLibrary"; #endif - this->hidden->libraryHandle = SDL_LoadObject(location); + this->hidden->libraryHandle = SDL_LoadObject(location); - this->gl_config.driver_loaded = 1; - return (this->hidden->libraryHandle != NULL) ? 0 : -1; + this->gl_config.driver_loaded = 1; + return (this->hidden->libraryHandle != NULL) ? 0 : -1; } -void Mac_GL_UnloadLibrary(_THIS) +void +Mac_GL_UnloadLibrary(_THIS) { - SDL_UnloadObject(this->hidden->libraryHandle); + SDL_UnloadObject(this->hidden->libraryHandle); - this->hidden->libraryHandle = NULL; - this->gl_config.driver_loaded = 0; + this->hidden->libraryHandle = NULL; + this->gl_config.driver_loaded = 0; } -void* Mac_GL_GetProcAddress(_THIS, const char *proc) +void * +Mac_GL_GetProcAddress(_THIS, const char *proc) { - return SDL_LoadFunction( this->hidden->libraryHandle, proc ); + return SDL_LoadFunction(this->hidden->libraryHandle, proc); } #endif /* SDL_VIDEO_OPENGL */ - +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/maccommon/SDL_macgl_c.h b/src/video/maccommon/SDL_macgl_c.h index df1cbe503..c8d115c4a 100644 --- a/src/video/maccommon/SDL_macgl_c.h +++ b/src/video/maccommon/SDL_macgl_c.h @@ -27,7 +27,7 @@ #if SDL_VIDEO_OPENGL #include "SDL_opengl.h" #if __MACOSX__ -#include /* AGL.framework */ +#include /* AGL.framework */ #else #include #endif @@ -38,10 +38,10 @@ extern int Mac_GL_Init(_THIS); extern void Mac_GL_Quit(_THIS); #if SDL_VIDEO_OPENGL extern int Mac_GL_MakeCurrent(_THIS); -extern int Mac_GL_GetAttribute(_THIS, SDL_GLattr attrib, int* value); +extern int Mac_GL_GetAttribute(_THIS, SDL_GLattr attrib, int *value); extern void Mac_GL_SwapBuffers(_THIS); extern int Mac_GL_LoadLibrary(_THIS, const char *location); extern void Mac_GL_UnloadLibrary(_THIS); -extern void* Mac_GL_GetProcAddress(_THIS, const char *proc); +extern void *Mac_GL_GetProcAddress(_THIS, const char *proc); #endif - +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/maccommon/SDL_mackeys.h b/src/video/maccommon/SDL_mackeys.h index df458ca57..6c00d974a 100644 --- a/src/video/maccommon/SDL_mackeys.h +++ b/src/video/maccommon/SDL_mackeys.h @@ -109,7 +109,7 @@ #define MK_COMMA 0x2B #define MK_PERIOD 0x2F #define MK_SLASH 0x2C -#if 0 /* These are the same as the left versions - use left by default */ +#if 0 /* These are the same as the left versions - use left by default */ #define MK_RSHIFT 0x38 #endif #define MK_UP 0x7E @@ -121,7 +121,7 @@ #define MK_LALT 0x3A #define MK_LMETA 0x37 #define MK_SPACE 0x31 -#if 0 /* These are the same as the left versions - use left by default */ +#if 0 /* These are the same as the left versions - use left by default */ #define MK_RMETA 0x37 #define MK_RALT 0x3A #define MK_RCTRL 0x3B @@ -138,3 +138,4 @@ #define MK_IBOOK_RIGHT 0x3C #define MK_IBOOK_DOWN 0x3D #define MK_IBOOK_UP 0x3E +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/maccommon/SDL_macmouse.c b/src/video/maccommon/SDL_macmouse.c index 85c3a0e7b..6d9a8b758 100644 --- a/src/video/maccommon/SDL_macmouse.c +++ b/src/video/maccommon/SDL_macmouse.c @@ -39,91 +39,98 @@ /* The implementation dependent data for the window manager cursor */ -struct WMcursor { - Cursor curs; +struct WMcursor +{ + Cursor curs; }; -void Mac_FreeWMCursor(_THIS, WMcursor *cursor) +void +Mac_FreeWMCursor(_THIS, WMcursor * cursor) { - SDL_free(cursor); + SDL_free(cursor); } -WMcursor *Mac_CreateWMCursor(_THIS, - Uint8 *data, Uint8 *mask, int w, int h, int hot_x, int hot_y) +WMcursor * +Mac_CreateWMCursor(_THIS, + Uint8 * data, Uint8 * mask, int w, int h, int hot_x, + int hot_y) { - WMcursor *cursor; - int row, bytes; - - /* Allocate the cursor memory */ - cursor = (WMcursor *)SDL_malloc(sizeof(WMcursor)); - if ( cursor == NULL ) { - SDL_OutOfMemory(); - return(NULL); - } - SDL_memset(cursor, 0, sizeof(*cursor)); - + WMcursor *cursor; + int row, bytes; + + /* Allocate the cursor memory */ + cursor = (WMcursor *) SDL_malloc(sizeof(WMcursor)); + if (cursor == NULL) { + SDL_OutOfMemory(); + return (NULL); + } + SDL_memset(cursor, 0, sizeof(*cursor)); + if (w > 16) w = 16; - + if (h > 16) h = 16; - - bytes = (w+7)/8; - - for ( row=0; rowcurs.data[row], data, bytes); - data += bytes; - } - for ( row=0; rowcurs.mask[row], mask, bytes); - mask += bytes; - } - cursor->curs.hotSpot.h = hot_x; - cursor->curs.hotSpot.v = hot_y; - - /* That was easy. :) */ - return(cursor); + + bytes = (w + 7) / 8; + + for (row = 0; row < h; ++row) { + SDL_memcpy(&cursor->curs.data[row], data, bytes); + data += bytes; + } + for (row = 0; row < h; ++row) { + SDL_memcpy(&cursor->curs.mask[row], mask, bytes); + mask += bytes; + } + cursor->curs.hotSpot.h = hot_x; + cursor->curs.hotSpot.v = hot_y; + + /* That was easy. :) */ + return (cursor); } int Mac_cursor_showing = 1; -int Mac_ShowWMCursor(_THIS, WMcursor *cursor) +int +Mac_ShowWMCursor(_THIS, WMcursor * cursor) { - if ( cursor == NULL ) { - if ( Mac_cursor_showing ) { - HideCursor(); - Mac_cursor_showing = 0; - } - } else { - SetCursor(&cursor->curs); - if ( ! Mac_cursor_showing ) { - ShowCursor(); - Mac_cursor_showing = 1; - } - } - return(1); + if (cursor == NULL) { + if (Mac_cursor_showing) { + HideCursor(); + Mac_cursor_showing = 0; + } + } else { + SetCursor(&cursor->curs); + if (!Mac_cursor_showing) { + ShowCursor(); + Mac_cursor_showing = 1; + } + } + return (1); } -void Mac_WarpWMCursor(_THIS, Uint16 x, Uint16 y) +void +Mac_WarpWMCursor(_THIS, Uint16 x, Uint16 y) { #if !TARGET_API_MAC_CARBON - CursorDevice *cursordevice; - - cursordevice = nil; - CursorDeviceNextDevice(&cursordevice); - if ( cursordevice != nil ) { - WindowPtr saveport; - Point where; - - GetPort(&saveport); - SetPort(SDL_Window); - where.h = x; - where.v = y; - LocalToGlobal(&where); - SetPort(saveport); - CursorDeviceMoveTo(cursordevice, where.h, where.v); - } + CursorDevice *cursordevice; + + cursordevice = nil; + CursorDeviceNextDevice(&cursordevice); + if (cursordevice != nil) { + WindowPtr saveport; + Point where; + + GetPort(&saveport); + SetPort(SDL_Window); + where.h = x; + where.v = y; + LocalToGlobal(&where); + SetPort(saveport); + CursorDeviceMoveTo(cursordevice, where.h, where.v); + } #endif /* !TARGET_API_MAC_CARBON */ } +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/maccommon/SDL_macmouse_c.h b/src/video/maccommon/SDL_macmouse_c.h index deba59285..b1f57da22 100644 --- a/src/video/maccommon/SDL_macmouse_c.h +++ b/src/video/maccommon/SDL_macmouse_c.h @@ -24,11 +24,13 @@ #include "../macrom/SDL_romvideo.h" /* Functions to be exported */ -extern void Mac_FreeWMCursor(_THIS, WMcursor *cursor); +extern void Mac_FreeWMCursor(_THIS, WMcursor * cursor); extern WMcursor *Mac_CreateWMCursor(_THIS, - Uint8 *data, Uint8 *mask, int w, int h, int hot_x, int hot_y); -extern int Mac_ShowWMCursor(_THIS, WMcursor *cursor); + Uint8 * data, Uint8 * mask, int w, int h, + int hot_x, int hot_y); +extern int Mac_ShowWMCursor(_THIS, WMcursor * cursor); extern void Mac_WarpWMCursor(_THIS, Uint16 x, Uint16 y); /* Data to be exported */ extern int Mac_cursor_showing; +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/maccommon/SDL_macwm.c b/src/video/maccommon/SDL_macwm.c index 667774467..7d0b33342 100644 --- a/src/video/maccommon/SDL_macwm.c +++ b/src/video/maccommon/SDL_macwm.c @@ -33,12 +33,15 @@ #include "SDL_stdinc.h" #include "SDL_macwm_c.h" -void Mac_SetCaption(_THIS, const char *title, const char *icon) +void +Mac_SetCaption(_THIS, const char *title, const char *icon) { - /* Don't convert C to P string in place, because it may be read-only */ - Str255 ptitle; /* MJS */ - ptitle[0] = strlen (title); - SDL_memcpy(ptitle+1, title, ptitle[0]); /* MJS */ - if (SDL_Window) - SetWTitle(SDL_Window, ptitle); /* MJS */ + /* Don't convert C to P string in place, because it may be read-only */ + Str255 ptitle; /* MJS */ + ptitle[0] = strlen(title); + SDL_memcpy(ptitle + 1, title, ptitle[0]); /* MJS */ + if (SDL_Window) + SetWTitle(SDL_Window, ptitle); /* MJS */ } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/maccommon/SDL_macwm_c.h b/src/video/maccommon/SDL_macwm_c.h index 5f56b699d..acb37535e 100644 --- a/src/video/maccommon/SDL_macwm_c.h +++ b/src/video/maccommon/SDL_macwm_c.h @@ -25,4 +25,4 @@ /* Functions to be exported */ extern void Mac_SetCaption(_THIS, const char *title, const char *icon); - +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/macdsp/SDL_dspvideo.c b/src/video/macdsp/SDL_dspvideo.c index a1150d777..395fef41c 100644 --- a/src/video/macdsp/SDL_dspvideo.c +++ b/src/video/macdsp/SDL_dspvideo.c @@ -150,1265 +150,1331 @@ #include "../maccommon/SDL_macevents_c.h" /* Initialization/Query functions */ -static int DSp_VideoInit(_THIS, SDL_PixelFormat *vformat); -static SDL_Rect **DSp_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags); -static SDL_Surface *DSp_SetVideoMode(_THIS, SDL_Surface *current, int width, int height, int bpp, Uint32 flags); +static int DSp_VideoInit(_THIS, SDL_PixelFormat * vformat); +static SDL_Rect **DSp_ListModes(_THIS, SDL_PixelFormat * format, + Uint32 flags); +static SDL_Surface *DSp_SetVideoMode(_THIS, SDL_Surface * current, int width, + int height, int bpp, Uint32 flags); static int DSp_SetColors(_THIS, int firstcolor, int ncolors, - SDL_Color *colors); + SDL_Color * colors); static int DSp_CreatePalette(_THIS); static int DSp_DestroyPalette(_THIS); static void DSp_VideoQuit(_THIS); -static int DSp_GetMainDevice (_THIS, GDHandle *device); -static void DSp_IsHWAvailable (_THIS, SDL_PixelFormat *vformat); -static void DSp_DSpUpdate(_THIS, int numrects, SDL_Rect *sdl_rects); -static void DSp_DirectUpdate(_THIS, int numrects, SDL_Rect *sdl_rects); +static int DSp_GetMainDevice(_THIS, GDHandle * device); +static void DSp_IsHWAvailable(_THIS, SDL_PixelFormat * vformat); +static void DSp_DSpUpdate(_THIS, int numrects, SDL_Rect * sdl_rects); +static void DSp_DirectUpdate(_THIS, int numrects, SDL_Rect * sdl_rects); /* Hardware surface functions */ -static int DSp_SetHWAlpha(_THIS, SDL_Surface *surface, UInt8 alpha); -static int DSp_SetHWColorKey(_THIS, SDL_Surface *surface, Uint32 key); -static int DSp_NewHWSurface(_THIS, CGrafPtr *port, int depth, int width, int height); -static int DSp_AllocHWSurface(_THIS, SDL_Surface *surface); -static int DSp_LockHWSurface(_THIS, SDL_Surface *surface); -static void DSp_UnlockHWSurface(_THIS, SDL_Surface *surface); -static void DSp_FreeHWSurface(_THIS, SDL_Surface *surface); -static int DSp_FlipHWSurface(_THIS, SDL_Surface *surface); -static int DSp_CheckHWBlit(_THIS, SDL_Surface *src, SDL_Surface *dest); -static int DSp_HWAccelBlit(SDL_Surface *src, SDL_Rect *srcrect, - SDL_Surface *dst, SDL_Rect *dstrect); -static int DSp_FillHWRect(_THIS, SDL_Surface *dst, SDL_Rect *rect, Uint32 color); +static int DSp_SetHWAlpha(_THIS, SDL_Surface * surface, UInt8 alpha); +static int DSp_SetHWColorKey(_THIS, SDL_Surface * surface, Uint32 key); +static int DSp_NewHWSurface(_THIS, CGrafPtr * port, int depth, int width, + int height); +static int DSp_AllocHWSurface(_THIS, SDL_Surface * surface); +static int DSp_LockHWSurface(_THIS, SDL_Surface * surface); +static void DSp_UnlockHWSurface(_THIS, SDL_Surface * surface); +static void DSp_FreeHWSurface(_THIS, SDL_Surface * surface); +static int DSp_FlipHWSurface(_THIS, SDL_Surface * surface); +static int DSp_CheckHWBlit(_THIS, SDL_Surface * src, SDL_Surface * dest); +static int DSp_HWAccelBlit(SDL_Surface * src, SDL_Rect * srcrect, + SDL_Surface * dst, SDL_Rect * dstrect); +static int DSp_FillHWRect(_THIS, SDL_Surface * dst, SDL_Rect * rect, + Uint32 color); #if SDL_VIDEO_OPENGL - static void DSp_GL_SwapBuffers (_THIS); +static void DSp_GL_SwapBuffers(_THIS); #endif #if ! TARGET_API_MAC_CARBON - #define GetPortPixRowBytes(x) ( (*(x->portPixMap))->rowBytes ) - #define GetGDevPixMap(x) ((**(x)).gdPMap) - #define GetPortPixMap(x) ((*(x)).portPixMap) - - #define GetPixDepth(y) ((**(y)).pixelSize) +#define GetPortPixRowBytes(x) ( (*(x->portPixMap))->rowBytes ) +#define GetGDevPixMap(x) ((**(x)).gdPMap) +#define GetPortPixMap(x) ((*(x)).portPixMap) + +#define GetPixDepth(y) ((**(y)).pixelSize) //#define GetPixRowBytes(y) ((**(y)).rowBytes) //#define GetPixBaseAddr(y) ((**(y)).baseAddr) - #define GetPixCTab(y) ((**(y)).pmTable) - #define GetPortBitMapForCopyBits(x) (&(((GrafPtr)(x))->portBits)) - +#define GetPixCTab(y) ((**(y)).pmTable) +#define GetPortBitMapForCopyBits(x) (&(((GrafPtr)(x))->portBits)) + #else - #define GetPortPixRowBytes(x) (GetPixRowBytes(GetPortPixMap(x)) ) - #define GetGDevPixMap(x) ((**(x)).gdPMap) +#define GetPortPixRowBytes(x) (GetPixRowBytes(GetPortPixMap(x)) ) +#define GetGDevPixMap(x) ((**(x)).gdPMap) #endif -typedef struct private_hwdata { +typedef struct private_hwdata +{ + + GWorldPtr offscreen; // offscreen gworld in VRAM or AGP + +#ifdef DSP_TRY_CC_AND_AA + GWorldPtr mask; // transparent mask + RGBColor alpha; // alpha color + RGBColor trans; // transparent color +#endif - GWorldPtr offscreen; // offscreen gworld in VRAM or AGP - - #ifdef DSP_TRY_CC_AND_AA - GWorldPtr mask; // transparent mask - RGBColor alpha; // alpha color - RGBColor trans; // transparent color - #endif - } private_hwdata; -typedef private_hwdata private_swdata ; /* have same fields */ +typedef private_hwdata private_swdata; /* have same fields */ /* Macintosh toolbox driver bootstrap functions */ -static int DSp_Available(void) +static int +DSp_Available(void) { - /* Check for DrawSprocket */ + /* Check for DrawSprocket */ #if ! TARGET_API_MAC_OSX - /* This check is only meaningful if you weak-link DrawSprocketLib */ - return ((Ptr)DSpStartup != (Ptr)kUnresolvedCFragSymbolAddress); + /* This check is only meaningful if you weak-link DrawSprocketLib */ + return ((Ptr) DSpStartup != (Ptr) kUnresolvedCFragSymbolAddress); #else - return 1; // DrawSprocket.framework doesn't have it all, but it's there + return 1; // DrawSprocket.framework doesn't have it all, but it's there #endif } -static void DSp_DeleteDevice(SDL_VideoDevice *device) +static void +DSp_DeleteDevice(SDL_VideoDevice * device) { - /* -dw- taking no chances with null pointers */ - if (device) { - - if (device->hidden) { - - if (device->hidden->dspinfo) - SDL_free(device->hidden->dspinfo); - - SDL_free(device->hidden); - } - SDL_free(device); - } + /* -dw- taking no chances with null pointers */ + if (device) { + + if (device->hidden) { + + if (device->hidden->dspinfo) + SDL_free(device->hidden->dspinfo); + + SDL_free(device->hidden); + } + SDL_free(device); + } } -static SDL_VideoDevice *DSp_CreateDevice(int devindex) +static SDL_VideoDevice * +DSp_CreateDevice(int devindex) { - SDL_VideoDevice *device; - - /* Initialize all variables that we clean on shutdown */ - device = (SDL_VideoDevice *)SDL_malloc(sizeof(SDL_VideoDevice)); - if ( device ) { - SDL_memset(device, 0, sizeof (*device)); - device->hidden = (struct SDL_PrivateVideoData *) - SDL_malloc((sizeof *device->hidden)); - if (device->hidden) - SDL_memset(device->hidden, 0, sizeof ( *(device->hidden) ) ); - } - if ( (device == NULL) || (device->hidden == NULL) ) { - SDL_OutOfMemory(); - - if ( device ) { - - if (device->hidden) - SDL_free(device->hidden); - - SDL_free(device); - } - - return(NULL); - } - - /* Allocate DrawSprocket information */ - device->hidden->dspinfo = (struct DSpInfo *)SDL_malloc( - (sizeof *device->hidden->dspinfo)); - if ( device->hidden->dspinfo == NULL ) { - SDL_OutOfMemory(); - SDL_free(device->hidden); - SDL_free(device); - return(0); - } - SDL_memset(device->hidden->dspinfo, 0, (sizeof *device->hidden->dspinfo)); - - /* Set the function pointers */ - device->VideoInit = DSp_VideoInit; - device->ListModes = DSp_ListModes; - device->SetVideoMode = DSp_SetVideoMode; - device->SetColors = DSp_SetColors; - device->UpdateRects = NULL; - device->VideoQuit = DSp_VideoQuit; - device->AllocHWSurface = DSp_AllocHWSurface; - device->CheckHWBlit = NULL; - device->FillHWRect = NULL; - device->SetHWColorKey = NULL; - device->SetHWAlpha = NULL; - device->LockHWSurface = DSp_LockHWSurface; - device->UnlockHWSurface = DSp_UnlockHWSurface; - device->FlipHWSurface = DSp_FlipHWSurface; - device->FreeHWSurface = DSp_FreeHWSurface; + SDL_VideoDevice *device; + + /* Initialize all variables that we clean on shutdown */ + device = (SDL_VideoDevice *) SDL_malloc(sizeof(SDL_VideoDevice)); + if (device) { + SDL_memset(device, 0, sizeof(*device)); + device->hidden = (struct SDL_PrivateVideoData *) + SDL_malloc((sizeof *device->hidden)); + if (device->hidden) + SDL_memset(device->hidden, 0, sizeof(*(device->hidden))); + } + if ((device == NULL) || (device->hidden == NULL)) { + SDL_OutOfMemory(); + + if (device) { + + if (device->hidden) + SDL_free(device->hidden); + + SDL_free(device); + } + + return (NULL); + } + + /* Allocate DrawSprocket information */ + device->hidden->dspinfo = (struct DSpInfo *) SDL_malloc((sizeof *device-> + hidden-> + dspinfo)); + if (device->hidden->dspinfo == NULL) { + SDL_OutOfMemory(); + SDL_free(device->hidden); + SDL_free(device); + return (0); + } + SDL_memset(device->hidden->dspinfo, 0, (sizeof *device->hidden->dspinfo)); + + /* Set the function pointers */ + device->VideoInit = DSp_VideoInit; + device->ListModes = DSp_ListModes; + device->SetVideoMode = DSp_SetVideoMode; + device->SetColors = DSp_SetColors; + device->UpdateRects = NULL; + device->VideoQuit = DSp_VideoQuit; + device->AllocHWSurface = DSp_AllocHWSurface; + device->CheckHWBlit = NULL; + device->FillHWRect = NULL; + device->SetHWColorKey = NULL; + device->SetHWAlpha = NULL; + device->LockHWSurface = DSp_LockHWSurface; + device->UnlockHWSurface = DSp_UnlockHWSurface; + device->FlipHWSurface = DSp_FlipHWSurface; + device->FreeHWSurface = DSp_FreeHWSurface; #if SDL_VIDEO_OPENGL - device->GL_MakeCurrent = Mac_GL_MakeCurrent; - device->GL_SwapBuffers = DSp_GL_SwapBuffers; - device->GL_LoadLibrary = Mac_GL_LoadLibrary; - device->GL_GetProcAddress = Mac_GL_GetProcAddress; + device->GL_MakeCurrent = Mac_GL_MakeCurrent; + device->GL_SwapBuffers = DSp_GL_SwapBuffers; + device->GL_LoadLibrary = Mac_GL_LoadLibrary; + device->GL_GetProcAddress = Mac_GL_GetProcAddress; #endif - device->SetCaption = NULL; - device->SetIcon = NULL; - device->IconifyWindow = NULL; - device->GrabInput = NULL; - device->GetWMInfo = NULL; - device->FreeWMCursor = Mac_FreeWMCursor; - device->CreateWMCursor = Mac_CreateWMCursor; - device->ShowWMCursor = Mac_ShowWMCursor; - device->WarpWMCursor = Mac_WarpWMCursor; - device->InitOSKeymap = Mac_InitOSKeymap; - device->PumpEvents = Mac_PumpEvents; - - device->GrabInput = NULL; - device->CheckMouseMode = NULL; - - device->free = DSp_DeleteDevice; - - return device; + device->SetCaption = NULL; + device->SetIcon = NULL; + device->IconifyWindow = NULL; + device->GrabInput = NULL; + device->GetWMInfo = NULL; + device->FreeWMCursor = Mac_FreeWMCursor; + device->CreateWMCursor = Mac_CreateWMCursor; + device->ShowWMCursor = Mac_ShowWMCursor; + device->WarpWMCursor = Mac_WarpWMCursor; + device->InitOSKeymap = Mac_InitOSKeymap; + device->PumpEvents = Mac_PumpEvents; + + device->GrabInput = NULL; + device->CheckMouseMode = NULL; + + device->free = DSp_DeleteDevice; + + return device; } VideoBootStrap DSp_bootstrap = { - "DSp", "MacOS DrawSprocket", - DSp_Available, DSp_CreateDevice + "DSp", "MacOS DrawSprocket", + DSp_Available, DSp_CreateDevice }; /* Use DSp/Display Manager to build mode list for given screen */ -static SDL_Rect** DSp_BuildModeList (const GDHandle gDevice, int *displayWidth, int *displayHeight) +static SDL_Rect ** +DSp_BuildModeList(const GDHandle gDevice, int *displayWidth, + int *displayHeight) { - DSpContextAttributes attributes; - DSpContextReference context; - DisplayIDType displayID; - SDL_Rect temp_list [16]; - SDL_Rect **mode_list; - int width, height, i, j; - - #if TARGET_API_MAC_OSX - - displayID = 0; - - #else - /* Ask Display Manager for integer id of screen device */ - if ( DMGetDisplayIDByGDevice (gDevice, &displayID, SDL_TRUE) != noErr ) { - return NULL; - } - #endif - /* Get the first possible DSp context on this device */ - if ( DSpGetFirstContext (displayID, &context) != noErr ) { - return NULL; - } - - if ( DSpContext_GetAttributes (context, &attributes) != noErr ) - return NULL; - - *displayWidth = attributes.displayWidth; - *displayHeight = attributes.displayHeight; - - for ( i = 0; i < SDL_arraysize(temp_list); i++ ) { - width = attributes.displayWidth; - height = attributes.displayHeight; - - temp_list [i].x = 0 | attributes.displayBestDepth; - temp_list [i].y = 0; - temp_list [i].w = width; - temp_list [i].h = height; - - /* DSp will report many different contexts with the same width and height. */ - /* They will differ in bit depth and refresh rate. */ - /* We will ignore them until we reach one with a different width/height */ - /* When there are no more contexts to look at, we will quit building the list*/ - while ( width == attributes.displayWidth && height == attributes.displayHeight ) { - - OSStatus err = DSpGetNextContext (context, &context); - if (err != noErr) - if (err == kDSpContextNotFoundErr) - goto done; - else - return NULL; - - if ( DSpContext_GetAttributes (context, &attributes) != noErr ) - return NULL; - - temp_list [i].x |= attributes.displayBestDepth; - } - } -done: - i++; /* i was not incremented before kicking out of the loop */ - - mode_list = (SDL_Rect**) SDL_malloc (sizeof (SDL_Rect*) * (i+1)); - if (mode_list) { - - /* -dw- new stuff: build in reverse order so largest sizes list first */ - for (j = i-1; j >= 0; j--) { - mode_list [j] = (SDL_Rect*) SDL_malloc (sizeof (SDL_Rect)); - if (mode_list [j]) - SDL_memcpy (mode_list [j], &(temp_list [j]), sizeof (SDL_Rect)); - else { - SDL_OutOfMemory (); - return NULL; - } - } - mode_list [i] = NULL; /* append null to the end */ - } - else { - SDL_OutOfMemory (); - return NULL; - } - - return mode_list; + DSpContextAttributes attributes; + DSpContextReference context; + DisplayIDType displayID; + SDL_Rect temp_list[16]; + SDL_Rect **mode_list; + int width, height, i, j; + +#if TARGET_API_MAC_OSX + + displayID = 0; + +#else + /* Ask Display Manager for integer id of screen device */ + if (DMGetDisplayIDByGDevice(gDevice, &displayID, SDL_TRUE) != noErr) { + return NULL; + } +#endif + /* Get the first possible DSp context on this device */ + if (DSpGetFirstContext(displayID, &context) != noErr) { + return NULL; + } + + if (DSpContext_GetAttributes(context, &attributes) != noErr) + return NULL; + + *displayWidth = attributes.displayWidth; + *displayHeight = attributes.displayHeight; + + for (i = 0; i < SDL_arraysize(temp_list); i++) { + width = attributes.displayWidth; + height = attributes.displayHeight; + + temp_list[i].x = 0 | attributes.displayBestDepth; + temp_list[i].y = 0; + temp_list[i].w = width; + temp_list[i].h = height; + + /* DSp will report many different contexts with the same width and height. */ + /* They will differ in bit depth and refresh rate. */ + /* We will ignore them until we reach one with a different width/height */ + /* When there are no more contexts to look at, we will quit building the list */ + while (width == attributes.displayWidth + && height == attributes.displayHeight) { + + OSStatus err = DSpGetNextContext(context, &context); + if (err != noErr) + if (err == kDSpContextNotFoundErr) + goto done; + else + return NULL; + + if (DSpContext_GetAttributes(context, &attributes) != noErr) + return NULL; + + temp_list[i].x |= attributes.displayBestDepth; + } + } + done: + i++; /* i was not incremented before kicking out of the loop */ + + mode_list = (SDL_Rect **) SDL_malloc(sizeof(SDL_Rect *) * (i + 1)); + if (mode_list) { + + /* -dw- new stuff: build in reverse order so largest sizes list first */ + for (j = i - 1; j >= 0; j--) { + mode_list[j] = (SDL_Rect *) SDL_malloc(sizeof(SDL_Rect)); + if (mode_list[j]) + SDL_memcpy(mode_list[j], &(temp_list[j]), sizeof(SDL_Rect)); + else { + SDL_OutOfMemory(); + return NULL; + } + } + mode_list[i] = NULL; /* append null to the end */ + } else { + SDL_OutOfMemory(); + return NULL; + } + + return mode_list; } -static void DSp_IsHWAvailable (_THIS, SDL_PixelFormat *vformat) +static void +DSp_IsHWAvailable(_THIS, SDL_PixelFormat * vformat) { - /* - VRAM GWorlds are only available on OS 9 or later. - Even with OS 9, some display drivers won't support it, - so we create a test GWorld and check for errors. - */ + /* + VRAM GWorlds are only available on OS 9 or later. + Even with OS 9, some display drivers won't support it, + so we create a test GWorld and check for errors. + */ - long versionSystem; + long versionSystem; + + dsp_vram_available = SDL_FALSE; + dsp_agp_available = SDL_FALSE; + + Gestalt('sysv', &versionSystem); + if (0x00000860 < (versionSystem & 0x0000FFFF)) { + + GWorldPtr offscreen; + OSStatus err; + Rect bounds; + + SetRect(&bounds, 0, 0, 320, 240); - dsp_vram_available = SDL_FALSE; - dsp_agp_available = SDL_FALSE; - - Gestalt ('sysv', &versionSystem); - if (0x00000860 < (versionSystem & 0x0000FFFF)) { - - GWorldPtr offscreen; - OSStatus err; - Rect bounds; - - SetRect (&bounds, 0, 0, 320, 240); - #if useDistantHdwrMem && useLocalHdwrMem - err = NewGWorld (&offscreen, vformat->BitsPerPixel, &bounds, NULL, SDL_Display, useDistantHdwrMem | noNewDevice); - if (err == noErr) { - dsp_vram_available = SDL_TRUE; - DisposeGWorld (offscreen); - } - - err = NewGWorld (&offscreen, vformat->BitsPerPixel, &bounds, NULL, SDL_Display, useLocalHdwrMem | noNewDevice); - if (err == noErr) { - DisposeGWorld (offscreen); - dsp_agp_available = SDL_TRUE; - } + err = + NewGWorld(&offscreen, vformat->BitsPerPixel, &bounds, NULL, + SDL_Display, useDistantHdwrMem | noNewDevice); + if (err == noErr) { + dsp_vram_available = SDL_TRUE; + DisposeGWorld(offscreen); + } + + err = + NewGWorld(&offscreen, vformat->BitsPerPixel, &bounds, NULL, + SDL_Display, useLocalHdwrMem | noNewDevice); + if (err == noErr) { + DisposeGWorld(offscreen); + dsp_agp_available = SDL_TRUE; + } #endif - } + } } -static int DSp_GetMainDevice (_THIS, GDHandle *device) +static int +DSp_GetMainDevice(_THIS, GDHandle * device) { - + #if TARGET_API_MAC_OSX - /* DSpUserSelectContext not available on OS X */ - *device = GetMainDevice(); - return 0; + /* DSpUserSelectContext not available on OS X */ + *device = GetMainDevice(); + return 0; #else - - DSpContextAttributes attrib; - DSpContextReference context; - DisplayIDType display_id; - GDHandle main_device; - GDHandle device_list; - - device_list = GetDeviceList (); - main_device = GetMainDevice (); - - /* Quick check to avoid slower method when only one display exists */ - if ( (**device_list).gdNextGD == NULL ) { - *device = main_device; - return 0; - } - - SDL_memset (&attrib, 0, sizeof (DSpContextAttributes)); - - /* These attributes are hopefully supported on all devices...*/ - attrib.displayWidth = 640; - attrib.displayHeight = 480; - attrib.displayBestDepth = 8; - attrib.backBufferBestDepth = 8; - attrib.displayDepthMask = kDSpDepthMask_All; - attrib.backBufferDepthMask = kDSpDepthMask_All; - attrib.colorNeeds = kDSpColorNeeds_Require; - attrib.pageCount = 1; - - if (noErr != DMGetDisplayIDByGDevice (main_device, &display_id, SDL_FALSE)) { - SDL_SetError ("Display Manager couldn't associate GDevice with a Display ID"); - return (-1); - } - - /* Put up dialog on main display to select which display to use */ - if (noErr != DSpUserSelectContext (&attrib, display_id, NULL, &context)) { - SDL_SetError ("DrawSprocket couldn't create a context"); - return (-1); - } - - if (noErr != DSpContext_GetDisplayID (context, &display_id)) { - SDL_SetError ("DrawSprocket couldn't get display ID"); - return (-1); - } - - if (noErr != DMGetGDeviceByDisplayID (display_id, &main_device, SDL_FALSE)) { - SDL_SetError ("Display Manager couldn't associate Display ID with GDevice"); - return (-1); - } - *device = main_device; - return (0); + DSpContextAttributes attrib; + DSpContextReference context; + DisplayIDType display_id; + GDHandle main_device; + GDHandle device_list; + + device_list = GetDeviceList(); + main_device = GetMainDevice(); + + /* Quick check to avoid slower method when only one display exists */ + if ((**device_list).gdNextGD == NULL) { + *device = main_device; + return 0; + } + + SDL_memset(&attrib, 0, sizeof(DSpContextAttributes)); + + /* These attributes are hopefully supported on all devices... */ + attrib.displayWidth = 640; + attrib.displayHeight = 480; + attrib.displayBestDepth = 8; + attrib.backBufferBestDepth = 8; + attrib.displayDepthMask = kDSpDepthMask_All; + attrib.backBufferDepthMask = kDSpDepthMask_All; + attrib.colorNeeds = kDSpColorNeeds_Require; + attrib.pageCount = 1; + + if (noErr != DMGetDisplayIDByGDevice(main_device, &display_id, SDL_FALSE)) { + SDL_SetError + ("Display Manager couldn't associate GDevice with a Display ID"); + return (-1); + } + + /* Put up dialog on main display to select which display to use */ + if (noErr != DSpUserSelectContext(&attrib, display_id, NULL, &context)) { + SDL_SetError("DrawSprocket couldn't create a context"); + return (-1); + } + + if (noErr != DSpContext_GetDisplayID(context, &display_id)) { + SDL_SetError("DrawSprocket couldn't get display ID"); + return (-1); + } + + if (noErr != DMGetGDeviceByDisplayID(display_id, &main_device, SDL_FALSE)) { + SDL_SetError + ("Display Manager couldn't associate Display ID with GDevice"); + return (-1); + } + + *device = main_device; + return (0); #endif } -static int DSp_VideoInit(_THIS, SDL_PixelFormat *vformat) +static int +DSp_VideoInit(_THIS, SDL_PixelFormat * vformat) { - NumVersion dsp_version = { 0x01, 0x00, 0x00, 0x00 }; - + NumVersion dsp_version = { 0x01, 0x00, 0x00, 0x00 }; + #if UNIVERSAL_INTERFACES_VERSION > 0x0320 - dsp_version = DSpGetVersion (); + dsp_version = DSpGetVersion(); #endif - - if ( (dsp_version.majorRev == 1 && dsp_version.minorAndBugRev < 0x73) || - (dsp_version.majorRev < 1) ) { - - /* StandardAlert (kAlertStopAlert, "\pError!", - "\pI need DrawSprocket 1.7.3 or later!\n" - "You can find a newer version at http://www.apple.com/swupdates.", - NULL, NULL); - */ - SDL_SetError ("DrawSprocket version is too old. Need 1.7.3 or later."); - return (-1); - } - - if ( DSpStartup () != noErr ) { - SDL_SetError ("DrawSprocket couldn't startup"); - return(-1); - } - - /* Start DSpintosh events */ - Mac_InitEvents(this); - - /* Get a handle to the main monitor, or choose one on multiple monitor setups */ - if ( DSp_GetMainDevice(this, &SDL_Display) < 0) - return (-1); - - /* Determine pixel format */ - vformat->BitsPerPixel = GetPixDepth ( (**SDL_Display).gdPMap ); - dsp_old_depth = vformat->BitsPerPixel; - - switch (vformat->BitsPerPixel) { - case 16: - vformat->Rmask = 0x00007c00; - vformat->Gmask = 0x000003e0; - vformat->Bmask = 0x0000001f; - break; - default: - break; - } - - if ( DSp_CreatePalette (this) < 0 ) { - SDL_SetError ("Could not create palette"); - return (-1); - } - - /* Get a list of available fullscreen modes */ - SDL_modelist = DSp_BuildModeList (SDL_Display, - &this->info.current_w, &this->info.current_h); - if (SDL_modelist == NULL) { - SDL_SetError ("DrawSprocket could not build a mode list"); - return (-1); - } - - /* Check for VRAM and AGP GWorlds for HW Blitting */ - DSp_IsHWAvailable (this, vformat); - - this->info.wm_available = 0; - - if (dsp_vram_available || dsp_agp_available) { - - this->info.hw_available = SDL_TRUE; - - this->CheckHWBlit = DSp_CheckHWBlit; - this->info.blit_hw = SDL_TRUE; - - this->FillHWRect = DSp_FillHWRect; - this->info.blit_fill = SDL_TRUE; - - #ifdef DSP_TRY_CC_AND_AA - this->SetHWColorKey = DSp_SetHWColorKey; - this->info.blit_hw_CC = SDL_TRUE; - - this->SetHWAlpha = DSp_SetHWAlpha; - this->info.blit_hw_A = SDL_TRUE; - #endif - - } - - return(0); + + if ((dsp_version.majorRev == 1 && dsp_version.minorAndBugRev < 0x73) || + (dsp_version.majorRev < 1)) { + + /* StandardAlert (kAlertStopAlert, "\pError!", + "\pI need DrawSprocket 1.7.3 or later!\n" + "You can find a newer version at http://www.apple.com/swupdates.", + NULL, NULL); + */ + SDL_SetError("DrawSprocket version is too old. Need 1.7.3 or later."); + return (-1); + } + + if (DSpStartup() != noErr) { + SDL_SetError("DrawSprocket couldn't startup"); + return (-1); + } + + /* Start DSpintosh events */ + Mac_InitEvents(this); + + /* Get a handle to the main monitor, or choose one on multiple monitor setups */ + if (DSp_GetMainDevice(this, &SDL_Display) < 0) + return (-1); + + /* Determine pixel format */ + vformat->BitsPerPixel = GetPixDepth((**SDL_Display).gdPMap); + dsp_old_depth = vformat->BitsPerPixel; + + switch (vformat->BitsPerPixel) { + case 16: + vformat->Rmask = 0x00007c00; + vformat->Gmask = 0x000003e0; + vformat->Bmask = 0x0000001f; + break; + default: + break; + } + + if (DSp_CreatePalette(this) < 0) { + SDL_SetError("Could not create palette"); + return (-1); + } + + /* Get a list of available fullscreen modes */ + SDL_modelist = DSp_BuildModeList(SDL_Display, + &this->info.current_w, + &this->info.current_h); + if (SDL_modelist == NULL) { + SDL_SetError("DrawSprocket could not build a mode list"); + return (-1); + } + + /* Check for VRAM and AGP GWorlds for HW Blitting */ + DSp_IsHWAvailable(this, vformat); + + this->info.wm_available = 0; + + if (dsp_vram_available || dsp_agp_available) { + + this->info.hw_available = SDL_TRUE; + + this->CheckHWBlit = DSp_CheckHWBlit; + this->info.blit_hw = SDL_TRUE; + + this->FillHWRect = DSp_FillHWRect; + this->info.blit_fill = SDL_TRUE; + +#ifdef DSP_TRY_CC_AND_AA + this->SetHWColorKey = DSp_SetHWColorKey; + this->info.blit_hw_CC = SDL_TRUE; + + this->SetHWAlpha = DSp_SetHWAlpha; + this->info.blit_hw_A = SDL_TRUE; +#endif + + } + + return (0); } -static SDL_Rect **DSp_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags) +static SDL_Rect ** +DSp_ListModes(_THIS, SDL_PixelFormat * format, Uint32 flags) { - static SDL_Rect *dsp_modes[16]; - int i = 0, j = 0; - - if ( format->BitsPerPixel == 0 ) - return ( (SDL_Rect**) NULL ); - - while (SDL_modelist[i] != NULL) { - - if (SDL_modelist[i]->x & format->BitsPerPixel) { - dsp_modes[j] = SDL_modelist[i]; - j++; - } - i++; - } - - dsp_modes[j] = NULL; - - return dsp_modes; + static SDL_Rect *dsp_modes[16]; + int i = 0, j = 0; + + if (format->BitsPerPixel == 0) + return ((SDL_Rect **) NULL); + + while (SDL_modelist[i] != NULL) { + + if (SDL_modelist[i]->x & format->BitsPerPixel) { + dsp_modes[j] = SDL_modelist[i]; + j++; + } + i++; + } + + dsp_modes[j] = NULL; + + return dsp_modes; } /* Various screen update functions available */ -static void DSp_DirectUpdate(_THIS, int numrects, SDL_Rect *rects); +static void DSp_DirectUpdate(_THIS, int numrects, SDL_Rect * rects); #if ! TARGET_API_MAC_OSX static volatile unsigned int retrace_count = 0; /* -dw- need volatile because it updates asychronously */ -Boolean DSp_VBLProc ( DSpContextReference context, void *ref_con ) +Boolean +DSp_VBLProc(DSpContextReference context, void *ref_con) { - retrace_count++; - - return 1; /* Darrell, is this right? */ + retrace_count++; + + return 1; /* Darrell, is this right? */ } -static void DSp_SetHWError (OSStatus err, int is_agp) +static void +DSp_SetHWError(OSStatus err, int is_agp) { - char message[1024]; - const char *fmt, *mem; - - if ( is_agp ) { - mem = "AGP Memory"; - } else { - mem = "VRAM"; - } - switch(err) { - case memFullErr: - fmt = "Hardware surface possible but not enough %s available"; - break; - case cDepthErr: - fmt = "Hardware surface possible but invalid color depth"; - break; - default: - fmt = "Hardware surface could not be allocated in %s - unknown error"; - break; - } - SDL_snprintf(message, SDL_arraysize(message), fmt, mem); - SDL_SetError(message); + char message[1024]; + const char *fmt, *mem; + + if (is_agp) { + mem = "AGP Memory"; + } else { + mem = "VRAM"; + } + switch (err) { + case memFullErr: + fmt = "Hardware surface possible but not enough %s available"; + break; + case cDepthErr: + fmt = "Hardware surface possible but invalid color depth"; + break; + default: + fmt = "Hardware surface could not be allocated in %s - unknown error"; + break; + } + SDL_snprintf(message, SDL_arraysize(message), fmt, mem); + SDL_SetError(message); } #endif // TARGET_API_MAC_OSX /* put up a dialog to verify display change */ -static int DSp_ConfirmSwitch () { +static int +DSp_ConfirmSwitch() +{ + + /* resource id's for dialog */ + const int rDialog = 1002; + const int bCancel = 1; + const int bOK = 2; + + DialogPtr dialog; + OSStatus err; + SInt32 response; + DialogItemIndex item = 0; + GrafPtr savePort; + + GetPort(&savePort); + + dialog = GetNewDialog(rDialog, NULL, (WindowPtr) - 1); + if (dialog == NULL) + return (0); - /* resource id's for dialog */ - const int rDialog = 1002; - const int bCancel = 1; - const int bOK = 2; - - DialogPtr dialog; - OSStatus err; - SInt32 response; - DialogItemIndex item = 0; - GrafPtr savePort; - - GetPort (&savePort); - - dialog = GetNewDialog (rDialog, NULL, (WindowPtr) -1); - if (dialog == NULL) - return (0); - #if TARGET_API_MAC_CARBON - SetPort (GetDialogPort(dialog)); + SetPort(GetDialogPort(dialog)); #else - SetPort ((WindowPtr) dialog); + SetPort((WindowPtr) dialog); #endif - - SetDialogDefaultItem (dialog, bCancel); - SetDialogCancelItem (dialog, bCancel); - - SetEventMask (everyEvent); - FlushEvents (everyEvent, 0); - - /* On MacOS 8.5 or later, we can make the dialog go away after 15 seconds */ - /* This is good since it's possible user can't even see the dialog! */ - /* Requires linking to DialogsLib */ - err = Gestalt(gestaltSystemVersion,&response); - if (err == noErr && response >= 0x00000850) { - SetDialogTimeout(dialog, bCancel, 15); - } - - do { - - ModalDialog ( NULL, &item ); - } while ( item != bCancel && item != bOK && err != noErr); + SetDialogDefaultItem(dialog, bCancel); + SetDialogCancelItem(dialog, bCancel); + SetEventMask(everyEvent); + FlushEvents(everyEvent, 0); - DisposeDialog (dialog); - SetPort (savePort); - - SetEventMask(everyEvent - autoKeyMask); - FlushEvents(everyEvent, 0); - - return (item - 1); + /* On MacOS 8.5 or later, we can make the dialog go away after 15 seconds */ + /* This is good since it's possible user can't even see the dialog! */ + /* Requires linking to DialogsLib */ + err = Gestalt(gestaltSystemVersion, &response); + if (err == noErr && response >= 0x00000850) { + SetDialogTimeout(dialog, bCancel, 15); + } + + do { + + ModalDialog(NULL, &item); + + } + while (item != bCancel && item != bOK && err != noErr); + + + DisposeDialog(dialog); + SetPort(savePort); + + SetEventMask(everyEvent - autoKeyMask); + FlushEvents(everyEvent, 0); + + return (item - 1); } -static void DSp_UnsetVideoMode(_THIS, SDL_Surface *current) +static void +DSp_UnsetVideoMode(_THIS, SDL_Surface * current) { - - - if ( current->flags & SDL_OPENGL ) { - Mac_GL_Quit (this); - } - - if (dsp_context != NULL) { - - GWorldPtr front; - DSpContext_GetFrontBuffer (dsp_context, &front); - - if (front != dsp_back_buffer) - DisposeGWorld (dsp_back_buffer); - - if (current->hwdata) - SDL_free(current->hwdata); - - DSpContext_SetState (dsp_context, kDSpContextState_Inactive ); - DSpContext_Release (dsp_context); - - dsp_context = NULL; - } - + + + if (current->flags & SDL_INTERNALOPENGL) { + Mac_GL_Quit(this); + } + + if (dsp_context != NULL) { + + GWorldPtr front; + DSpContext_GetFrontBuffer(dsp_context, &front); + + if (front != dsp_back_buffer) + DisposeGWorld(dsp_back_buffer); + + if (current->hwdata) + SDL_free(current->hwdata); + + DSpContext_SetState(dsp_context, kDSpContextState_Inactive); + DSpContext_Release(dsp_context); + + dsp_context = NULL; + } + if (SDL_Window != NULL) { - DisposeWindow (SDL_Window); + DisposeWindow(SDL_Window); SDL_Window = NULL; - } - + } + current->pixels = NULL; - current->flags = 0; + current->flags = 0; } -static SDL_Surface *DSp_SetVideoMode(_THIS, - SDL_Surface *current, int width, int height, int bpp, Uint32 flags) +static SDL_Surface * +DSp_SetVideoMode(_THIS, + SDL_Surface * current, int width, int height, int bpp, + Uint32 flags) { - + #if !TARGET_API_MAC_OSX - DisplayIDType display_id; - Fixed freq; + DisplayIDType display_id; + Fixed freq; #endif - DSpContextAttributes attrib; - OSStatus err; - UInt32 rmask = 0, gmask = 0, bmask = 0; - - int page_count; - int double_buf; - int hw_surface; - int use_dsp_back_buffer; - - DSp_UnsetVideoMode (this, current); - + DSpContextAttributes attrib; + OSStatus err; + UInt32 rmask = 0, gmask = 0, bmask = 0; + + int page_count; + int double_buf; + int hw_surface; + int use_dsp_back_buffer; + + DSp_UnsetVideoMode(this, current); + if (bpp != dsp_old_depth) - DSp_DestroyPalette (this); - - double_buf = (flags & SDL_DOUBLEBUF) != 0; - hw_surface = (flags & SDL_HWSURFACE) != 0; - use_dsp_back_buffer = !dsp_vram_available || !hw_surface ; - - current->flags |= SDL_FULLSCREEN; + DSp_DestroyPalette(this); -rebuild: - - if ( double_buf && use_dsp_back_buffer ) { - page_count = 2; - } else { - page_count = 1; - } - - SDL_memset (&attrib, 0, sizeof (DSpContextAttributes)); - attrib.displayWidth = width; - attrib.displayHeight = height; - attrib.displayBestDepth = bpp; - attrib.backBufferBestDepth = bpp; - attrib.displayDepthMask = kDSpDepthMask_All; - attrib.backBufferDepthMask = kDSpDepthMask_All; - attrib.colorNeeds = kDSpColorNeeds_Require; - attrib.colorTable = 0; - attrib.pageCount = page_count; - #if TARGET_API_MAC_OSX || UNIVERSAL_INTERFACES_VERSION == 0x0320 - - if ( DSpFindBestContext (&attrib, &dsp_context) != noErr ) { - SDL_SetError ("DrawSprocket couldn't find a context"); + double_buf = (flags & SDL_DOUBLEBUF) != 0; + hw_surface = (flags & SDL_HWSURFACE) != 0; + use_dsp_back_buffer = !dsp_vram_available || !hw_surface; + + current->flags |= SDL_FULLSCREEN; + + rebuild: + + if (double_buf && use_dsp_back_buffer) { + page_count = 2; + } else { + page_count = 1; + } + + SDL_memset(&attrib, 0, sizeof(DSpContextAttributes)); + attrib.displayWidth = width; + attrib.displayHeight = height; + attrib.displayBestDepth = bpp; + attrib.backBufferBestDepth = bpp; + attrib.displayDepthMask = kDSpDepthMask_All; + attrib.backBufferDepthMask = kDSpDepthMask_All; + attrib.colorNeeds = kDSpColorNeeds_Require; + attrib.colorTable = 0; + attrib.pageCount = page_count; +#if TARGET_API_MAC_OSX || UNIVERSAL_INTERFACES_VERSION == 0x0320 + + if (DSpFindBestContext(&attrib, &dsp_context) != noErr) { + SDL_SetError("DrawSprocket couldn't find a context"); + return NULL; + } +#else + if (noErr != DMGetDisplayIDByGDevice(SDL_Display, &display_id, SDL_FALSE)) { + SDL_SetError + ("Display Manager couldn't associate GDevice with display_id"); + return NULL; + } + if (DSpFindBestContextOnDisplayID(&attrib, &dsp_context, display_id) != + noErr) { + SDL_SetError + ("DrawSprocket couldn't find a suitable context on given display"); + return NULL; + } +#endif + if (DSpContext_Reserve(dsp_context, &attrib) != noErr) { + SDL_SetError + ("DrawSprocket couldn't get the needed resources to build the display"); + return NULL; + } + + if ((err = + DSpContext_SetState(dsp_context, kDSpContextState_Active)) != noErr) + { + + if (err == kDSpConfirmSwitchWarning) { + + if (!DSp_ConfirmSwitch()) { + + DSpContext_Release(dsp_context); + dsp_context = NULL; + SDL_SetError("User cancelled display switch"); + return NULL; + } else + /* Have to reactivate context. Why? */ + DSpContext_SetState(dsp_context, kDSpContextState_Active); + + } else { + SDL_SetError("DrawSprocket couldn't activate the context"); return NULL; } - - #else - if ( noErr != DMGetDisplayIDByGDevice (SDL_Display, &display_id, SDL_FALSE) ) { - SDL_SetError ("Display Manager couldn't associate GDevice with display_id"); - return NULL; - } - if ( DSpFindBestContextOnDisplayID(&attrib, &dsp_context, display_id) != noErr ) { - SDL_SetError ("DrawSprocket couldn't find a suitable context on given display"); - return NULL; - } - - #endif - if ( DSpContext_Reserve (dsp_context, &attrib) != noErr ) { - SDL_SetError ("DrawSprocket couldn't get the needed resources to build the display"); - return NULL; - } - - if ( (err = DSpContext_SetState (dsp_context, kDSpContextState_Active)) != noErr ) { - - if (err == kDSpConfirmSwitchWarning) { - - if ( ! DSp_ConfirmSwitch () ) { - - DSpContext_Release (dsp_context); - dsp_context = NULL; - SDL_SetError ("User cancelled display switch"); - return NULL; - } - else - /* Have to reactivate context. Why? */ - DSpContext_SetState (dsp_context, kDSpContextState_Active); - - } - else { - SDL_SetError ("DrawSprocket couldn't activate the context"); - return NULL; - } - } - - - if (bpp != dsp_old_depth) { - - DSp_CreatePalette (this); - - /* update format if display depth changed */ - if (bpp == 16) { - - rmask = 0x00007c00; - gmask = 0x000003e0; - bmask = 0x0000001f; - } - if ( ! SDL_ReallocFormat (current, bpp, rmask, gmask, bmask, 0 ) ) { - - SDL_SetError ("Could not reallocate video format."); - return(NULL); - } - } - - if (!double_buf) { - - /* single-buffer context */ - DSpContext_GetFrontBuffer (dsp_context, &dsp_back_buffer); - - current->hwdata = (private_hwdata*) SDL_malloc (sizeof (private_hwdata)); - if (current ->hwdata == NULL) { - SDL_OutOfMemory (); - return NULL; - } - current->hwdata->offscreen = dsp_back_buffer; - current->flags |= SDL_HWSURFACE; - this->UpdateRects = DSp_DirectUpdate; - } - else if ( use_dsp_back_buffer ) { - - DSpContext_GetBackBuffer (dsp_context, kDSpBufferKind_Normal, &dsp_back_buffer); - - current->flags |= SDL_DOUBLEBUF | SDL_SWSURFACE; /* only front buffer is in VRAM */ - this->UpdateRects = DSp_DSpUpdate; - } - else if ( DSp_NewHWSurface(this, &dsp_back_buffer, bpp, width-1, height-1) == 0 ) { - - current->hwdata = (private_hwdata*) SDL_malloc (sizeof (private_hwdata)); - if (current ->hwdata == NULL) { - SDL_OutOfMemory (); - return NULL; - } - - SDL_memset (current->hwdata, 0, sizeof (private_hwdata)); - current->hwdata->offscreen = dsp_back_buffer; - current->flags |= SDL_DOUBLEBUF | SDL_HWSURFACE; - this->UpdateRects = DSp_DirectUpdate; /* hardware doesn't do update rects, must be page-flipped */ - } - else { - - DSpContext_Release (dsp_context); - use_dsp_back_buffer = SDL_TRUE; - goto rebuild; } - - current->pitch = GetPortPixRowBytes(dsp_back_buffer) & 0x3FFF; - current->pixels = GetPixBaseAddr(GetPortPixMap(dsp_back_buffer)); - - current->w = width; - current->h = height; - - #if ! TARGET_API_MAC_OSX - - if (use_dsp_back_buffer) { - - DSpContext_GetMonitorFrequency (dsp_context, &freq); - DSpContext_SetMaxFrameRate (dsp_context, freq >> 16); - } - - - if ( (current->flags & SDL_HWSURFACE) || (current->flags & SDL_OPENGL) ) - DSpContext_SetVBLProc (dsp_context, DSp_VBLProc, NULL); - #endif - - if (bpp == 8) - current->flags |= SDL_HWPALETTE; - - if (flags & SDL_OPENGL) { - - Rect rect; - RGBColor rgb = { 0.0, 0.0, 0.0 }; - GrafPtr save_port; - - SetRect (&rect, 0, 0, width, height); - SDL_Window = NewCWindow(nil, &( (**SDL_Display).gdRect), "\p", SDL_TRUE, plainDBox, (WindowPtr)-1, SDL_FALSE, 0); - - if (SDL_Window == NULL) { - - SDL_SetError ("DSp_SetVideoMode : OpenGL window could not be created."); - return NULL; - } - - /* Set window color to black to avoid white flash*/ - GetPort (&save_port); + + + if (bpp != dsp_old_depth) { + + DSp_CreatePalette(this); + + /* update format if display depth changed */ + if (bpp == 16) { + + rmask = 0x00007c00; + gmask = 0x000003e0; + bmask = 0x0000001f; + } + if (!SDL_ReallocFormat(current, bpp, rmask, gmask, bmask, 0)) { + + SDL_SetError("Could not reallocate video format."); + return (NULL); + } + } + + if (!double_buf) { + + /* single-buffer context */ + DSpContext_GetFrontBuffer(dsp_context, &dsp_back_buffer); + + current->hwdata = + (private_hwdata *) SDL_malloc(sizeof(private_hwdata)); + if (current->hwdata == NULL) { + SDL_OutOfMemory(); + return NULL; + } + current->hwdata->offscreen = dsp_back_buffer; + current->flags |= SDL_HWSURFACE; + this->UpdateRects = DSp_DirectUpdate; + } else if (use_dsp_back_buffer) { + + DSpContext_GetBackBuffer(dsp_context, kDSpBufferKind_Normal, + &dsp_back_buffer); + + current->flags |= SDL_DOUBLEBUF | SDL_SWSURFACE; /* only front buffer is in VRAM */ + this->UpdateRects = DSp_DSpUpdate; + } else if (DSp_NewHWSurface + (this, &dsp_back_buffer, bpp, width - 1, height - 1) == 0) { + + current->hwdata = + (private_hwdata *) SDL_malloc(sizeof(private_hwdata)); + if (current->hwdata == NULL) { + SDL_OutOfMemory(); + return NULL; + } + + SDL_memset(current->hwdata, 0, sizeof(private_hwdata)); + current->hwdata->offscreen = dsp_back_buffer; + current->flags |= SDL_DOUBLEBUF | SDL_HWSURFACE; + this->UpdateRects = DSp_DirectUpdate; /* hardware doesn't do update rects, must be page-flipped */ + } else { + + DSpContext_Release(dsp_context); + use_dsp_back_buffer = SDL_TRUE; + goto rebuild; + } + + current->pitch = GetPortPixRowBytes(dsp_back_buffer) & 0x3FFF; + current->pixels = GetPixBaseAddr(GetPortPixMap(dsp_back_buffer)); + + current->w = width; + current->h = height; + +#if ! TARGET_API_MAC_OSX + + if (use_dsp_back_buffer) { + + DSpContext_GetMonitorFrequency(dsp_context, &freq); + DSpContext_SetMaxFrameRate(dsp_context, freq >> 16); + } + + + if ((current->flags & SDL_HWSURFACE) + || (current->flags & SDL_INTERNALOPENGL)) + DSpContext_SetVBLProc(dsp_context, DSp_VBLProc, NULL); +#endif + + if (bpp == 8) + current->flags |= SDL_HWPALETTE; + + if (flags & SDL_INTERNALOPENGL) { + + Rect rect; + RGBColor rgb = { 0.0, 0.0, 0.0 }; + GrafPtr save_port; + + SetRect(&rect, 0, 0, width, height); + SDL_Window = + NewCWindow(nil, &((**SDL_Display).gdRect), "\p", SDL_TRUE, + plainDBox, (WindowPtr) - 1, SDL_FALSE, 0); + + if (SDL_Window == NULL) { + + SDL_SetError + ("DSp_SetVideoMode : OpenGL window could not be created."); + return NULL; + } + + /* Set window color to black to avoid white flash */ + GetPort(&save_port); #if TARGET_API_MAC_CARBON - SetPort (GetWindowPort(SDL_Window)); + SetPort(GetWindowPort(SDL_Window)); #else - SetPort (SDL_Window); + SetPort(SDL_Window); #endif - RGBForeColor (&rgb); - PaintRect (&rect); - SetPort (save_port); - - SetPortWindowPort (SDL_Window); - SelectWindow (SDL_Window); - - if ( Mac_GL_Init (this) < 0 ) { - - SDL_SetError ("DSp_SetVideoMode : could not create OpenGL context."); - return NULL; - } - - current->flags |= SDL_OPENGL; - } - - return current; + RGBForeColor(&rgb); + PaintRect(&rect); + SetPort(save_port); + + SetPortWindowPort(SDL_Window); + SelectWindow(SDL_Window); + + if (Mac_GL_Init(this) < 0) { + + SDL_SetError + ("DSp_SetVideoMode : could not create OpenGL context."); + return NULL; + } + + current->flags |= SDL_INTERNALOPENGL; + } + + return current; } #ifdef DSP_TRY_CC_AND_AA -static int DSp_MakeHWMask (_THIS, SDL_Surface *surface) +static int +DSp_MakeHWMask(_THIS, SDL_Surface * surface) { GDHandle save_device; CGrafPtr save_port; GWorldPtr temp; RGBColor black = { 0, 0, 0 }; RGBColor white = { 0xFFFF, 0xFFFF, 0xFFFF }; - Rect rect; - - Uint32 depth = GetPixDepth ( GetGDevPixMap (SDL_Display) ); - - SetRect (&rect, 0, 0, surface->w, surface->h); - - if ( noErr != NewGWorld (&(surface->hwdata->mask), depth, &rect, 0, SDL_Display, 0 ) < 0 ) { - - SDL_OutOfMemory (); + Rect rect; + + Uint32 depth = GetPixDepth(GetGDevPixMap(SDL_Display)); + + SetRect(&rect, 0, 0, surface->w, surface->h); + + if (noErr != + NewGWorld(&(surface->hwdata->mask), depth, &rect, 0, SDL_Display, + 0) < 0) { + + SDL_OutOfMemory(); return (-1); - } - - if ( noErr != NewGWorld (&temp, depth, &rect, 0 , SDL_Display, 0 ) ) { - - SDL_OutOfMemory (); + } + + if (noErr != NewGWorld(&temp, depth, &rect, 0, SDL_Display, 0)) { + + SDL_OutOfMemory(); return (-1); - } + } - - GetGWorld (&save_port, &save_device); - SetGWorld (surface->hwdata->mask, SDL_Display); - - RGBForeColor (&white); - PaintRect (&rect); - - RGBBackColor (&(surface->hwdata->trans)); - - CopyBits ( GetPortBitMapForCopyBits(surface->hwdata->offscreen), - GetPortBitMapForCopyBits(surface->hwdata->mask), - &rect, &rect, transparent, NULL ); - - SetGWorld (surface->hwdata->mask, SDL_Display); - SetGWorld (save_port, save_device); + + GetGWorld(&save_port, &save_device); + SetGWorld(surface->hwdata->mask, SDL_Display); + + RGBForeColor(&white); + PaintRect(&rect); + + RGBBackColor(&(surface->hwdata->trans)); + + CopyBits(GetPortBitMapForCopyBits(surface->hwdata->offscreen), + GetPortBitMapForCopyBits(surface->hwdata->mask), + &rect, &rect, transparent, NULL); + + SetGWorld(surface->hwdata->mask, SDL_Display); + SetGWorld(save_port, save_device); return (0); } -static int DSp_SetHWAlpha(_THIS, SDL_Surface *surface, UInt8 alpha) +static int +DSp_SetHWAlpha(_THIS, SDL_Surface * surface, UInt8 alpha) { - surface->hwdata->alpha.red = (alpha / 255.0) * 65535; - surface->hwdata->alpha.blue = (alpha / 255.0) * 65535; + surface->hwdata->alpha.red = (alpha / 255.0) * 65535; + surface->hwdata->alpha.blue = (alpha / 255.0) * 65535; surface->hwdata->alpha.green = (alpha / 255.0) * 65535; surface->flags |= SDL_SRCALPHA; if (surface->flags & SDL_SRCCOLORKEY) { - return(DSp_MakeHWMask (this, surface)); + return (DSp_MakeHWMask(this, surface)); } - return(0); + return (0); } -static int DSp_SetHWColorKey(_THIS, SDL_Surface *surface, Uint32 key) +static int +DSp_SetHWColorKey(_THIS, SDL_Surface * surface, Uint32 key) { CGrafPtr save_port; GDHandle save_device; - - GetGWorld (&save_port, &save_device); - SetGWorld (surface->hwdata->offscreen, NULL); - - Index2Color (key, &(surface->hwdata->trans)); - surface->flags |= SDL_SRCCOLORKEY; - - SetGWorld (save_port, save_device); - - if ( surface->flags & SDL_SRCALPHA ) { - return(DSp_MakeHWMask (this, surface)); - } - return(0); + + GetGWorld(&save_port, &save_device); + SetGWorld(surface->hwdata->offscreen, NULL); + + Index2Color(key, &(surface->hwdata->trans)); + surface->flags |= SDL_SRCCOLORKEY; + + SetGWorld(save_port, save_device); + + if (surface->flags & SDL_SRCALPHA) { + return (DSp_MakeHWMask(this, surface)); + } + return (0); } #endif /* DSP_TRY_CC_AND_AA */ -static int DSp_NewHWSurface(_THIS, CGrafPtr *port, int depth, int width, int height) { - - OSStatus err; - Rect bounds; - - SetRect (&bounds, 0, 0, width, height); - - #if useDistantHdwrMem && useLocalHdwrMem +static int +DSp_NewHWSurface(_THIS, CGrafPtr * port, int depth, int width, int height) +{ + + OSStatus err; + Rect bounds; + + SetRect(&bounds, 0, 0, width, height); + +#if useDistantHdwrMem && useLocalHdwrMem if (dsp_vram_available) { - /* try VRAM */ - err = NewGWorld (port, depth, &bounds, 0 , SDL_Display, useDistantHdwrMem | noNewDevice ); - if (err != noErr) - DSp_SetHWError (err, SDL_FALSE); - else - return (0); + /* try VRAM */ + err = + NewGWorld(port, depth, &bounds, 0, SDL_Display, + useDistantHdwrMem | noNewDevice); + if (err != noErr) + DSp_SetHWError(err, SDL_FALSE); + else + return (0); } - + if (dsp_agp_available) { - /* try AGP */ - err = NewGWorld (port, depth, &bounds, 0 , SDL_Display, useLocalHdwrMem | noNewDevice ); - - if (err != noErr) - DSp_SetHWError (err, SDL_TRUE); - else - return (0); - } + /* try AGP */ + err = + NewGWorld(port, depth, &bounds, 0, SDL_Display, + useLocalHdwrMem | noNewDevice); + + if (err != noErr) + DSp_SetHWError(err, SDL_TRUE); + else + return (0); + } #endif - - return (-1); + + return (-1); } -static int DSp_AllocHWSurface(_THIS, SDL_Surface *surface) +static int +DSp_AllocHWSurface(_THIS, SDL_Surface * surface) { - GWorldPtr temp; - - if ( DSp_NewHWSurface (this, &temp, surface->format->BitsPerPixel, surface->w, surface->h) < 0 ) - return (-1); - - surface->hwdata = (private_hwdata*) SDL_malloc (sizeof (private_hwdata)); - if (surface->hwdata == NULL) { - SDL_OutOfMemory (); - return -1; - } - - SDL_memset (surface->hwdata, 0, sizeof(private_hwdata)); - surface->hwdata->offscreen = temp; - surface->pitch = GetPixRowBytes (GetPortPixMap (temp)) & 0x3FFF; - surface->pixels = GetPixBaseAddr (GetPortPixMap (temp)); - surface->flags |= SDL_HWSURFACE; -#ifdef DSP_TRY_CC_AND_AA - surface->flags |= SDL_HWACCEL; -#endif - return 0; + GWorldPtr temp; + + if (DSp_NewHWSurface + (this, &temp, surface->format->BitsPerPixel, surface->w, + surface->h) < 0) + return (-1); + + surface->hwdata = (private_hwdata *) SDL_malloc(sizeof(private_hwdata)); + if (surface->hwdata == NULL) { + SDL_OutOfMemory(); + return -1; + } + + SDL_memset(surface->hwdata, 0, sizeof(private_hwdata)); + surface->hwdata->offscreen = temp; + surface->pitch = GetPixRowBytes(GetPortPixMap(temp)) & 0x3FFF; + surface->pixels = GetPixBaseAddr(GetPortPixMap(temp)); + surface->flags |= SDL_HWSURFACE; +#ifdef DSP_TRY_CC_AND_AA + surface->flags |= SDL_HWACCEL; +#endif + return 0; } -static void DSp_FreeHWSurface(_THIS, SDL_Surface *surface) -{ - if (surface->hwdata->offscreen != NULL) - DisposeGWorld (surface->hwdata->offscreen); - SDL_free(surface->hwdata); +static void +DSp_FreeHWSurface(_THIS, SDL_Surface * surface) +{ + if (surface->hwdata->offscreen != NULL) + DisposeGWorld(surface->hwdata->offscreen); + SDL_free(surface->hwdata); surface->pixels = NULL; } -static int DSp_CheckHWBlit(_THIS, SDL_Surface *src, SDL_Surface *dest) +static int +DSp_CheckHWBlit(_THIS, SDL_Surface * src, SDL_Surface * dest) { - int accelerated; - - /* Set initial acceleration on */ - src->flags |= SDL_HWACCEL; - - /* Set the surface attributes */ - if ( (src->flags & SDL_SRCALPHA) == SDL_SRCALPHA ) { - if ( ! this->info.blit_hw_A ) { - src->flags &= ~SDL_HWACCEL; - } - } - if ( (src->flags & SDL_SRCCOLORKEY) == SDL_SRCCOLORKEY ) { - if ( ! this->info.blit_hw_CC ) { - src->flags &= ~SDL_HWACCEL; - } - } - - /* Check to see if final surface blit is accelerated */ - accelerated = !!(src->flags & SDL_HWACCEL); - if ( accelerated ) { - src->map->hw_blit = DSp_HWAccelBlit; - } - return(accelerated); + int accelerated; + + /* Set initial acceleration on */ + src->flags |= SDL_HWACCEL; + + /* Set the surface attributes */ + if ((src->flags & SDL_SRCALPHA) == SDL_SRCALPHA) { + if (!this->info.blit_hw_A) { + src->flags &= ~SDL_HWACCEL; + } + } + if ((src->flags & SDL_SRCCOLORKEY) == SDL_SRCCOLORKEY) { + if (!this->info.blit_hw_CC) { + src->flags &= ~SDL_HWACCEL; + } + } + + /* Check to see if final surface blit is accelerated */ + accelerated = !!(src->flags & SDL_HWACCEL); + if (accelerated) { + src->map->hw_blit = DSp_HWAccelBlit; + } + return (accelerated); } -static int DSp_HWAccelBlit(SDL_Surface *src, SDL_Rect *srcrect, - SDL_Surface *dst, SDL_Rect *dstrect) +static int +DSp_HWAccelBlit(SDL_Surface * src, SDL_Rect * srcrect, + SDL_Surface * dst, SDL_Rect * dstrect) { - CGrafPtr save_port; - GDHandle save_device; - Rect src_rect, dst_rect; + CGrafPtr save_port; + GDHandle save_device; + Rect src_rect, dst_rect; RGBColor black = { 0, 0, 0 }; RGBColor white = { 0xFFFF, 0xFFFF, 0xFFFF }; -#ifdef DSP_TRY_CC_AND_AA - UInt32 mode; +#ifdef DSP_TRY_CC_AND_AA + UInt32 mode; #endif - - SetRect (&src_rect, srcrect->x, srcrect->y, srcrect->x + srcrect->w, srcrect->y + srcrect->h); - SetRect (&dst_rect, dstrect->x, dstrect->y, dstrect->x + dstrect->w, dstrect->y + dstrect->h); - - GetGWorld (&save_port, &save_device); - SetGWorld (dst->hwdata->offscreen, NULL); - - RGBForeColor (&black); - RGBBackColor (&white); - + + SetRect(&src_rect, srcrect->x, srcrect->y, srcrect->x + srcrect->w, + srcrect->y + srcrect->h); + SetRect(&dst_rect, dstrect->x, dstrect->y, dstrect->x + dstrect->w, + dstrect->y + dstrect->h); + + GetGWorld(&save_port, &save_device); + SetGWorld(dst->hwdata->offscreen, NULL); + + RGBForeColor(&black); + RGBBackColor(&white); + #ifdef DSP_TRY_CC_AND_AA - - if ( (src->flags & SDL_SRCCOLORKEY) && - (src->flags & SDL_SRCALPHA) ) { - - OpColor (&(src->hwdata->alpha)); - - CopyDeepMask ( GetPortBitMapForCopyBits(src->hwdata->offscreen), - GetPortBitMapForCopyBits(src->hwdata->mask), - GetPortBitMapForCopyBits(dst->hwdata->offscreen), - &src_rect, &src_rect, &dst_rect, - blend, - NULL ); - } - else { - - if ( src->flags & SDL_SRCCOLORKEY) { - RGBBackColor (&(src->hwdata->trans) ); - mode = transparent; - } - else if (src->flags & SDL_SRCALPHA) { - - OpColor (&(src->hwdata->alpha)); - mode = blend; - } - else { - - mode = srcCopy; - } - - CopyBits ( GetPortBitMapForCopyBits(src->hwdata->offscreen), - GetPortBitMapForCopyBits(dst->hwdata->offscreen), - &src_rect, &dst_rect, mode, NULL ); - } + + if ((src->flags & SDL_SRCCOLORKEY) && (src->flags & SDL_SRCALPHA)) { + + OpColor(&(src->hwdata->alpha)); + + CopyDeepMask(GetPortBitMapForCopyBits(src->hwdata->offscreen), + GetPortBitMapForCopyBits(src->hwdata->mask), + GetPortBitMapForCopyBits(dst->hwdata->offscreen), + &src_rect, &src_rect, &dst_rect, blend, NULL); + } else { + + if (src->flags & SDL_SRCCOLORKEY) { + RGBBackColor(&(src->hwdata->trans)); + mode = transparent; + } else if (src->flags & SDL_SRCALPHA) { + + OpColor(&(src->hwdata->alpha)); + mode = blend; + } else { + + mode = srcCopy; + } + + CopyBits(GetPortBitMapForCopyBits(src->hwdata->offscreen), + GetPortBitMapForCopyBits(dst->hwdata->offscreen), + &src_rect, &dst_rect, mode, NULL); + } #else - - CopyBits ( &(((GrafPtr)(src->hwdata->offscreen))->portBits), - &(((GrafPtr)(dst->hwdata->offscreen))->portBits), - &src_rect, &dst_rect, srcCopy, NULL ); -#endif /* DSP_TRY_CC_AND_AA */ - - SetGWorld (save_port, save_device); + CopyBits(&(((GrafPtr) (src->hwdata->offscreen))->portBits), + &(((GrafPtr) (dst->hwdata->offscreen))->portBits), + &src_rect, &dst_rect, srcCopy, NULL); + +#endif /* DSP_TRY_CC_AND_AA */ + + SetGWorld(save_port, save_device); - return(0); + return (0); } -static int DSp_FillHWRect(_THIS, SDL_Surface *dst, SDL_Rect *rect, Uint32 color) +static int +DSp_FillHWRect(_THIS, SDL_Surface * dst, SDL_Rect * rect, Uint32 color) { - CGrafPtr save_port; - GDHandle save_device; - Rect fill_rect; - RGBColor rgb; - - SetRect (&fill_rect, rect->x, rect->y, rect->x + rect->w, rect->y + rect->h); - - GetGWorld (&save_port, &save_device); - SetGWorld (dst->hwdata->offscreen, NULL); - - Index2Color (color, &rgb); - - RGBForeColor (&rgb); - PaintRect (&fill_rect); + CGrafPtr save_port; + GDHandle save_device; + Rect fill_rect; + RGBColor rgb; + + SetRect(&fill_rect, rect->x, rect->y, rect->x + rect->w, + rect->y + rect->h); + + GetGWorld(&save_port, &save_device); + SetGWorld(dst->hwdata->offscreen, NULL); + + Index2Color(color, &rgb); + + RGBForeColor(&rgb); + PaintRect(&fill_rect); - SetGWorld (save_port, save_device); + SetGWorld(save_port, save_device); - return(0); + return (0); } -static int DSp_FlipHWSurface(_THIS, SDL_Surface *surface) +static int +DSp_FlipHWSurface(_THIS, SDL_Surface * surface) { - if ( (surface->flags & SDL_HWSURFACE) ) { - CGrafPtr dsp_front_buffer, save_port; - Rect rect; - - #if ! TARGET_API_MAC_OSX - unsigned int old_count; - #endif - - /* pseudo page flipping for VRAM back buffer*/ - DSpContext_GetFrontBuffer (dsp_context, &dsp_front_buffer); - SetRect (&rect, 0, 0, surface->w-1, surface->h-1); - - GetPort ((GrafPtr *)&save_port); - SetPort ((GrafPtr)dsp_front_buffer); - - /* wait for retrace */ - /* I have tried doing the swap in interrupt routine (VBL Proc) to do */ - /* it asynchronously, but apparently CopyBits isn't interrupt safe */ - - #if ! TARGET_API_MAC_OSX - #ifndef DSP_NO_SYNC_VBL - old_count = retrace_count; - while (old_count == retrace_count) - ; - #endif - #endif - - CopyBits ( GetPortBitMapForCopyBits(dsp_back_buffer), - GetPortBitMapForCopyBits(dsp_front_buffer), - &rect, &rect, srcCopy, NULL ); - - SetPort ((GrafPtr)save_port); - - } else { - /* not really page flipping at all: DSp just blits the dirty rectangles from DSp_UpdateRects */ - Boolean busy_flag; - DSpContext_SwapBuffers (dsp_context, NULL, &busy_flag); /* this waits for VBL */ - DSpContext_GetBackBuffer (dsp_context, kDSpBufferKind_Normal, &dsp_back_buffer); - surface->pixels = GetPixBaseAddr( GetPortPixMap(dsp_back_buffer) ); - } - return(0); + if ((surface->flags & SDL_HWSURFACE)) { + CGrafPtr dsp_front_buffer, save_port; + Rect rect; + +#if ! TARGET_API_MAC_OSX + unsigned int old_count; +#endif + + /* pseudo page flipping for VRAM back buffer */ + DSpContext_GetFrontBuffer(dsp_context, &dsp_front_buffer); + SetRect(&rect, 0, 0, surface->w - 1, surface->h - 1); + + GetPort((GrafPtr *) & save_port); + SetPort((GrafPtr) dsp_front_buffer); + + /* wait for retrace */ + /* I have tried doing the swap in interrupt routine (VBL Proc) to do */ + /* it asynchronously, but apparently CopyBits isn't interrupt safe */ + +#if ! TARGET_API_MAC_OSX +#ifndef DSP_NO_SYNC_VBL + old_count = retrace_count; + while (old_count == retrace_count); +#endif +#endif + + CopyBits(GetPortBitMapForCopyBits(dsp_back_buffer), + GetPortBitMapForCopyBits(dsp_front_buffer), + &rect, &rect, srcCopy, NULL); + + SetPort((GrafPtr) save_port); + + } else { + /* not really page flipping at all: DSp just blits the dirty rectangles from DSp_UpdateRects */ + Boolean busy_flag; + DSpContext_SwapBuffers(dsp_context, NULL, &busy_flag); /* this waits for VBL */ + DSpContext_GetBackBuffer(dsp_context, kDSpBufferKind_Normal, + &dsp_back_buffer); + surface->pixels = GetPixBaseAddr(GetPortPixMap(dsp_back_buffer)); + } + return (0); } -static int DSp_LockHWSurface(_THIS, SDL_Surface *surface) +static int +DSp_LockHWSurface(_THIS, SDL_Surface * surface) { - if ( LockPixels (GetGWorldPixMap (surface->hwdata->offscreen)) ) - return 0; - else - return -1; + if (LockPixels(GetGWorldPixMap(surface->hwdata->offscreen))) + return 0; + else + return -1; } -static void DSp_UnlockHWSurface(_THIS, SDL_Surface *surface) +static void +DSp_UnlockHWSurface(_THIS, SDL_Surface * surface) { - UnlockPixels (GetGWorldPixMap (surface->hwdata->offscreen)); + UnlockPixels(GetGWorldPixMap(surface->hwdata->offscreen)); } -static void DSp_DirectUpdate(_THIS, int numrects, SDL_Rect *sdl_rects) +static void +DSp_DirectUpdate(_THIS, int numrects, SDL_Rect * sdl_rects) { - return; + return; } -static void DSp_DSpUpdate(_THIS, int numrects, SDL_Rect *sdl_rects) +static void +DSp_DSpUpdate(_THIS, int numrects, SDL_Rect * sdl_rects) { -#if ! TARGET_API_MAC_OSX /* Unsupported DSp in here */ - int i; - Rect rect; - - for (i = 0; i < numrects; i++) { - - rect.top = sdl_rects[i].y; - rect.left = sdl_rects[i].x; - rect.bottom = sdl_rects[i].h + sdl_rects[i].y; - rect.right = sdl_rects[i].w + sdl_rects[i].x; - - DSpContext_InvalBackBufferRect (dsp_context, &rect); - } +#if ! TARGET_API_MAC_OSX /* Unsupported DSp in here */ + int i; + Rect rect; + + for (i = 0; i < numrects; i++) { + + rect.top = sdl_rects[i].y; + rect.left = sdl_rects[i].x; + rect.bottom = sdl_rects[i].h + sdl_rects[i].y; + rect.right = sdl_rects[i].w + sdl_rects[i].x; + + DSpContext_InvalBackBufferRect(dsp_context, &rect); + } #endif } -static int DSp_CreatePalette(_THIS) { - - - /* Create our palette */ - SDL_CTab = (CTabHandle)NewHandle(sizeof(ColorSpec)*256 + 8); - if ( SDL_CTab == nil ) { - SDL_OutOfMemory(); - return(-1); - } - (**SDL_CTab).ctSeed = GetCTSeed(); - (**SDL_CTab).ctFlags = 0; - (**SDL_CTab).ctSize = 255; - CTabChanged(SDL_CTab); - SDL_CPal = NewPalette(256, SDL_CTab, pmExplicit+pmTolerant, 0); - - return 0; +static int +DSp_CreatePalette(_THIS) +{ + + + /* Create our palette */ + SDL_CTab = (CTabHandle) NewHandle(sizeof(ColorSpec) * 256 + 8); + if (SDL_CTab == nil) { + SDL_OutOfMemory(); + return (-1); + } + (**SDL_CTab).ctSeed = GetCTSeed(); + (**SDL_CTab).ctFlags = 0; + (**SDL_CTab).ctSize = 255; + CTabChanged(SDL_CTab); + SDL_CPal = NewPalette(256, SDL_CTab, pmExplicit + pmTolerant, 0); + + return 0; } -static int DSp_DestroyPalette(_THIS) { - - /* Free palette and restore original one */ - if ( SDL_CTab != nil ) { - DisposeHandle((Handle)SDL_CTab); - SDL_CTab = nil; - } - if ( SDL_CPal != nil ) { - DisposePalette(SDL_CPal); - SDL_CPal = nil; - } - RestoreDeviceClut(SDL_Display); - - return (0); +static int +DSp_DestroyPalette(_THIS) +{ + + /* Free palette and restore original one */ + if (SDL_CTab != nil) { + DisposeHandle((Handle) SDL_CTab); + SDL_CTab = nil; + } + if (SDL_CPal != nil) { + DisposePalette(SDL_CPal); + SDL_CPal = nil; + } + RestoreDeviceClut(SDL_Display); + + return (0); } -static int DSp_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color *colors) +static int +DSp_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color * colors) { - CTabHandle cTab; - - int i; - - cTab = SDL_CTab; - - /* Verify the range of colors */ - if ( (firstcolor+ncolors) > ((**cTab).ctSize+1) ) { - return(0); - } - - /* Set the screen palette and update the display */ - for(i = 0; i < ncolors; i++) { - int j = firstcolor + i; - (**cTab).ctTable[j].value = j; - (**cTab).ctTable[j].rgb.red = colors[i].r << 8 | colors[i].r; - (**cTab).ctTable[j].rgb.green = colors[i].g << 8 | colors[i].g; - (**cTab).ctTable[j].rgb.blue = colors[i].b << 8 | colors[i].b; - } - - SetGDevice(SDL_Display); - SetEntries(0, (**cTab).ctSize, (ColorSpec *)&(**cTab).ctTable); - - return(1); + CTabHandle cTab; + + int i; + + cTab = SDL_CTab; + + /* Verify the range of colors */ + if ((firstcolor + ncolors) > ((**cTab).ctSize + 1)) { + return (0); + } + + /* Set the screen palette and update the display */ + for (i = 0; i < ncolors; i++) { + int j = firstcolor + i; + (**cTab).ctTable[j].value = j; + (**cTab).ctTable[j].rgb.red = colors[i].r << 8 | colors[i].r; + (**cTab).ctTable[j].rgb.green = colors[i].g << 8 | colors[i].g; + (**cTab).ctTable[j].rgb.blue = colors[i].b << 8 | colors[i].b; + } + + SetGDevice(SDL_Display); + SetEntries(0, (**cTab).ctSize, (ColorSpec *) & (**cTab).ctTable); + + return (1); } -void DSp_VideoQuit(_THIS) +void +DSp_VideoQuit(_THIS) { - int i; - - /* Free current video mode */ - DSp_UnsetVideoMode(this, this->screen); - - /* Free Palette and restore original */ - DSp_DestroyPalette (this); - - /* Free list of video modes */ - if ( SDL_modelist != NULL ) { - for ( i=0; SDL_modelist[i]; i++ ) { - SDL_free(SDL_modelist[i]); - } - SDL_free(SDL_modelist); - SDL_modelist = NULL; - } - - /* Unload DrawSprocket */ - DSpShutdown (); + int i; + + /* Free current video mode */ + DSp_UnsetVideoMode(this, this->screen); + + /* Free Palette and restore original */ + DSp_DestroyPalette(this); + + /* Free list of video modes */ + if (SDL_modelist != NULL) { + for (i = 0; SDL_modelist[i]; i++) { + SDL_free(SDL_modelist[i]); + } + SDL_free(SDL_modelist); + SDL_modelist = NULL; + } + + /* Unload DrawSprocket */ + DSpShutdown(); } #if SDL_VIDEO_OPENGL /* swap buffers with v-sync */ -static void DSp_GL_SwapBuffers (_THIS) { +static void +DSp_GL_SwapBuffers(_THIS) +{ - #ifndef DSP_NO_SYNC_OPENGL - - unsigned int old_count; - - old_count = retrace_count; - while (old_count == retrace_count) - ; - #endif - - aglSwapBuffers (glContext); +#ifndef DSP_NO_SYNC_OPENGL + + unsigned int old_count; + + old_count = retrace_count; + while (old_count == retrace_count); +#endif + + aglSwapBuffers(glContext); } #endif +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/macdsp/SDL_dspvideo.h b/src/video/macdsp/SDL_dspvideo.h index 3b49da608..e2ad17526 100644 --- a/src/video/macdsp/SDL_dspvideo.h +++ b/src/video/macdsp/SDL_dspvideo.h @@ -25,7 +25,7 @@ #define _SDL_dspvideo_h #if TARGET_API_MAC_OSX -# include /* Drawsprocket.framework */ +# include /* Drawsprocket.framework */ #else #include #endif @@ -33,17 +33,18 @@ #include "../maccommon/SDL_lowvideo.h" /* DrawSprocket specific information */ -struct DSpInfo { - DSpContextReference dsp_context; - CGrafPtr dsp_back_buffer; - int dsp_old_depth; - - /* Flags for hw acceleration */ - int dsp_vram_available; - int dsp_agp_available; - - -}; +struct DSpInfo +{ + DSpContextReference dsp_context; + CGrafPtr dsp_back_buffer; + int dsp_old_depth; + + /* Flags for hw acceleration */ + int dsp_vram_available; + int dsp_agp_available; + + +}; /* Old variable names */ #define dsp_context (this->hidden->dspinfo->dsp_context) #define dsp_back_buffer (this->hidden->dspinfo->dsp_back_buffer) @@ -52,3 +53,4 @@ struct DSpInfo { #define dsp_agp_available (this->hidden->dspinfo->dsp_agp_available) #endif /* _SDL_dspvideo_h */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/macrom/SDL_romvideo.c b/src/video/macrom/SDL_romvideo.c index fbe65fd9a..70fb6870d 100644 --- a/src/video/macrom/SDL_romvideo.c +++ b/src/video/macrom/SDL_romvideo.c @@ -53,24 +53,26 @@ #include "../maccommon/SDL_macevents_c.h" /* Initialization/Query functions */ -static int ROM_VideoInit(_THIS, SDL_PixelFormat *vformat); -static SDL_Rect **ROM_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags); -static SDL_Surface *ROM_SetVideoMode(_THIS, SDL_Surface *current, int width, int height, int bpp, Uint32 flags); +static int ROM_VideoInit(_THIS, SDL_PixelFormat * vformat); +static SDL_Rect **ROM_ListModes(_THIS, SDL_PixelFormat * format, + Uint32 flags); +static SDL_Surface *ROM_SetVideoMode(_THIS, SDL_Surface * current, int width, + int height, int bpp, Uint32 flags); static int ROM_SetColors(_THIS, int firstcolor, int ncolors, - SDL_Color *colors); + SDL_Color * colors); static void ROM_VideoQuit(_THIS); /* Hardware surface functions */ -static int ROM_AllocHWSurface(_THIS, SDL_Surface *surface); -static int ROM_LockHWSurface(_THIS, SDL_Surface *surface); -static void ROM_UnlockHWSurface(_THIS, SDL_Surface *surface); -static void ROM_FreeHWSurface(_THIS, SDL_Surface *surface); +static int ROM_AllocHWSurface(_THIS, SDL_Surface * surface); +static int ROM_LockHWSurface(_THIS, SDL_Surface * surface); +static void ROM_UnlockHWSurface(_THIS, SDL_Surface * surface); +static void ROM_FreeHWSurface(_THIS, SDL_Surface * surface); -#if !TARGET_API_MAC_CARBON /* This seems not to be available? -sts Aug 2000 */ +#if !TARGET_API_MAC_CARBON /* This seems not to be available? -sts Aug 2000 */ /* Saved state for the menu bar */ -static RgnHandle gSaveGrayRgn = nil; -static short gSaveMenuBar = 0; -static Boolean gSaveCSVis = true; +static RgnHandle gSaveGrayRgn = nil; +static short gSaveMenuBar = 0; +static Boolean gSaveCSVis = true; #if powerc /* Mixed mode glue to activate the 68K emulator and twiddle a register */ @@ -87,648 +89,674 @@ static Boolean gSaveCSVis = true; 0x0008, 0x2F10, 0x4E75, 0x0000, 0x0000, 0x0000 } /* ControlStrip inline glue for PowerPC */ -static pascal Boolean SBIsControlStripVisible(void) +static pascal Boolean +SBIsControlStripVisible(void) { - static short procData[] = TWOWORDSTUB(0x7000, 0xAAF2); - ProcInfoType procInfo = kD0DispatchedPascalStackBased - | RESULT_SIZE(SIZE_CODE(sizeof(Boolean))) - | DISPATCHED_STACK_ROUTINE_SELECTOR_SIZE(kFourByteCode); - - return((Boolean) CallUniversalProc((UniversalProcPtr) procData, procInfo, 0x00)); + static short procData[] = TWOWORDSTUB(0x7000, 0xAAF2); + ProcInfoType procInfo = kD0DispatchedPascalStackBased + | RESULT_SIZE(SIZE_CODE(sizeof(Boolean))) + | DISPATCHED_STACK_ROUTINE_SELECTOR_SIZE(kFourByteCode); + + return ((Boolean) + CallUniversalProc((UniversalProcPtr) procData, procInfo, 0x00)); } -static pascal void SBShowHideControlStrip(Boolean showIt) +static pascal void +SBShowHideControlStrip(Boolean showIt) { - static short procData[] = THREEWORDSTUB(0x303C, 0x0101, 0xAAF2); - ProcInfoType procInfo = kD0DispatchedPascalStackBased - | DISPATCHED_STACK_ROUTINE_SELECTOR_SIZE(kFourByteCode) - | DISPATCHED_STACK_ROUTINE_PARAMETER(1, SIZE_CODE(sizeof(Boolean))); + static short procData[] = THREEWORDSTUB(0x303C, 0x0101, 0xAAF2); + ProcInfoType procInfo = kD0DispatchedPascalStackBased + | DISPATCHED_STACK_ROUTINE_SELECTOR_SIZE(kFourByteCode) + | DISPATCHED_STACK_ROUTINE_PARAMETER(1, + SIZE_CODE(sizeof(Boolean))); - CallUniversalProc((UniversalProcPtr) procData, procInfo, 0x01, showIt); + CallUniversalProc((UniversalProcPtr) procData, procInfo, 0x01, showIt); } #endif /* powerc */ #endif /* !TARGET_API_MAC_CARBON */ /* Macintosh toolbox driver bootstrap functions */ -static int ROM_Available(void) +static int +ROM_Available(void) { - return(1); + return (1); } -static void ROM_DeleteDevice(SDL_VideoDevice *device) +static void +ROM_DeleteDevice(SDL_VideoDevice * device) { - SDL_free(device->hidden); - SDL_free(device); + SDL_free(device->hidden); + SDL_free(device); } -static SDL_VideoDevice *ROM_CreateDevice(int devindex) +static SDL_VideoDevice * +ROM_CreateDevice(int devindex) { - SDL_VideoDevice *device; - - /* Initialize all variables that we clean on shutdown */ - device = (SDL_VideoDevice *)SDL_malloc(sizeof(SDL_VideoDevice)); - if ( device ) { - SDL_memset(device, 0, (sizeof *device)); - device->hidden = (struct SDL_PrivateVideoData *) - SDL_malloc((sizeof *device->hidden)); - } - if ( (device == NULL) || (device->hidden == NULL) ) { - SDL_OutOfMemory(); - if ( device ) { - SDL_free(device); - } - return(0); - } - SDL_memset(device->hidden, 0, (sizeof *device->hidden)); - - /* Set the function pointers */ - device->VideoInit = ROM_VideoInit; - device->ListModes = ROM_ListModes; - device->SetVideoMode = ROM_SetVideoMode; - device->SetColors = ROM_SetColors; - device->UpdateRects = NULL; - device->VideoQuit = ROM_VideoQuit; - device->AllocHWSurface = ROM_AllocHWSurface; - device->CheckHWBlit = NULL; - device->FillHWRect = NULL; - device->SetHWColorKey = NULL; - device->SetHWAlpha = NULL; - device->LockHWSurface = ROM_LockHWSurface; - device->UnlockHWSurface = ROM_UnlockHWSurface; - device->FlipHWSurface = NULL; - device->FreeHWSurface = ROM_FreeHWSurface; + SDL_VideoDevice *device; + + /* Initialize all variables that we clean on shutdown */ + device = (SDL_VideoDevice *) SDL_malloc(sizeof(SDL_VideoDevice)); + if (device) { + SDL_memset(device, 0, (sizeof *device)); + device->hidden = (struct SDL_PrivateVideoData *) + SDL_malloc((sizeof *device->hidden)); + } + if ((device == NULL) || (device->hidden == NULL)) { + SDL_OutOfMemory(); + if (device) { + SDL_free(device); + } + return (0); + } + SDL_memset(device->hidden, 0, (sizeof *device->hidden)); + + /* Set the function pointers */ + device->VideoInit = ROM_VideoInit; + device->ListModes = ROM_ListModes; + device->SetVideoMode = ROM_SetVideoMode; + device->SetColors = ROM_SetColors; + device->UpdateRects = NULL; + device->VideoQuit = ROM_VideoQuit; + device->AllocHWSurface = ROM_AllocHWSurface; + device->CheckHWBlit = NULL; + device->FillHWRect = NULL; + device->SetHWColorKey = NULL; + device->SetHWAlpha = NULL; + device->LockHWSurface = ROM_LockHWSurface; + device->UnlockHWSurface = ROM_UnlockHWSurface; + device->FlipHWSurface = NULL; + device->FreeHWSurface = ROM_FreeHWSurface; #if SDL_VIDEO_OPENGL - device->GL_MakeCurrent = Mac_GL_MakeCurrent; - device->GL_SwapBuffers = Mac_GL_SwapBuffers; - device->GL_LoadLibrary = Mac_GL_LoadLibrary; - device->GL_GetProcAddress = Mac_GL_GetProcAddress; -#endif // Have OpenGL - device->SetCaption = Mac_SetCaption; - device->SetIcon = NULL; - device->IconifyWindow = NULL; - device->GrabInput = NULL; - device->GetWMInfo = NULL; - device->FreeWMCursor = Mac_FreeWMCursor; - device->CreateWMCursor = Mac_CreateWMCursor; - device->ShowWMCursor = Mac_ShowWMCursor; - device->WarpWMCursor = Mac_WarpWMCursor; - device->InitOSKeymap = Mac_InitOSKeymap; - device->PumpEvents = Mac_PumpEvents; - - device->free = ROM_DeleteDevice; - - return device; + device->GL_MakeCurrent = Mac_GL_MakeCurrent; + device->GL_SwapBuffers = Mac_GL_SwapBuffers; + device->GL_LoadLibrary = Mac_GL_LoadLibrary; + device->GL_GetProcAddress = Mac_GL_GetProcAddress; +#endif // Have OpenGL + device->SetCaption = Mac_SetCaption; + device->SetIcon = NULL; + device->IconifyWindow = NULL; + device->GrabInput = NULL; + device->GetWMInfo = NULL; + device->FreeWMCursor = Mac_FreeWMCursor; + device->CreateWMCursor = Mac_CreateWMCursor; + device->ShowWMCursor = Mac_ShowWMCursor; + device->WarpWMCursor = Mac_WarpWMCursor; + device->InitOSKeymap = Mac_InitOSKeymap; + device->PumpEvents = Mac_PumpEvents; + + device->free = ROM_DeleteDevice; + + return device; } VideoBootStrap TOOLBOX_bootstrap = { - "toolbox", "MacOS ROM Toolbox", - ROM_Available, ROM_CreateDevice + "toolbox", "MacOS ROM Toolbox", + ROM_Available, ROM_CreateDevice }; -static int ROM_VideoInit(_THIS, SDL_PixelFormat *vformat) +static int +ROM_VideoInit(_THIS, SDL_PixelFormat * vformat) { - long info; - - /* Check out some things about the system */ - Gestalt(gestaltQuickdrawVersion, &info); - if ( info == gestaltOriginalQD ) { - SDL_SetError("Color Quickdraw not available"); - return(-1); - } - - /* Start ROMintosh events */ - Mac_InitEvents(this); - - /* Get a handle to the main monitor */ - SDL_Display = GetMainDevice(); - - /* Determine the current screen size */ - this->info.current_w = (**SDL_Display).gdRect.right; - this->info.current_h = (**SDL_Display).gdRect.bottom; - - /* Determine pixel format */ - vformat->BitsPerPixel = (**(**SDL_Display).gdPMap).pixelSize; - switch (vformat->BitsPerPixel) { - case 16: /* 5-5-5 RGB */ - vformat->Rmask = 0x00007c00; - vformat->Gmask = 0x000003e0; - vformat->Bmask = 0x0000001f; - break; - default: - break; - } - - /* Create our palette */ - SDL_CTab = (CTabHandle)NewHandle(sizeof(ColorSpec)*256 + 8); - if ( SDL_CTab == nil ) { - SDL_OutOfMemory(); - return(-1); - } - (**SDL_CTab).ctSeed = GetCTSeed(); - (**SDL_CTab).ctFlags = 0; - (**SDL_CTab).ctSize = 255; - CTabChanged(SDL_CTab); - SDL_CPal = NewPalette(256, SDL_CTab, pmExplicit+pmTolerant, 0); - - /* Get a list of available fullscreen modes */ - SDL_modelist = (SDL_Rect **)SDL_malloc((1+1)*sizeof(SDL_Rect *)); - if ( SDL_modelist ) { - SDL_modelist[0] = (SDL_Rect *)SDL_malloc(sizeof(SDL_Rect)); - if ( SDL_modelist[0] ) { - SDL_modelist[0]->x = 0; - SDL_modelist[0]->y = 0; - SDL_modelist[0]->w = (**SDL_Display).gdRect.right; - SDL_modelist[0]->h = (**SDL_Display).gdRect.bottom; - } - SDL_modelist[1] = NULL; - } - - /* Fill in some window manager capabilities */ - this->info.wm_available = 1; - - /* We're done! */ - return(0); + long info; + + /* Check out some things about the system */ + Gestalt(gestaltQuickdrawVersion, &info); + if (info == gestaltOriginalQD) { + SDL_SetError("Color Quickdraw not available"); + return (-1); + } + + /* Start ROMintosh events */ + Mac_InitEvents(this); + + /* Get a handle to the main monitor */ + SDL_Display = GetMainDevice(); + + /* Determine the current screen size */ + this->info.current_w = (**SDL_Display).gdRect.right; + this->info.current_h = (**SDL_Display).gdRect.bottom; + + /* Determine pixel format */ + vformat->BitsPerPixel = (**(**SDL_Display).gdPMap).pixelSize; + switch (vformat->BitsPerPixel) { + case 16: /* 5-5-5 RGB */ + vformat->Rmask = 0x00007c00; + vformat->Gmask = 0x000003e0; + vformat->Bmask = 0x0000001f; + break; + default: + break; + } + + /* Create our palette */ + SDL_CTab = (CTabHandle) NewHandle(sizeof(ColorSpec) * 256 + 8); + if (SDL_CTab == nil) { + SDL_OutOfMemory(); + return (-1); + } + (**SDL_CTab).ctSeed = GetCTSeed(); + (**SDL_CTab).ctFlags = 0; + (**SDL_CTab).ctSize = 255; + CTabChanged(SDL_CTab); + SDL_CPal = NewPalette(256, SDL_CTab, pmExplicit + pmTolerant, 0); + + /* Get a list of available fullscreen modes */ + SDL_modelist = (SDL_Rect **) SDL_malloc((1 + 1) * sizeof(SDL_Rect *)); + if (SDL_modelist) { + SDL_modelist[0] = (SDL_Rect *) SDL_malloc(sizeof(SDL_Rect)); + if (SDL_modelist[0]) { + SDL_modelist[0]->x = 0; + SDL_modelist[0]->y = 0; + SDL_modelist[0]->w = (**SDL_Display).gdRect.right; + SDL_modelist[0]->h = (**SDL_Display).gdRect.bottom; + } + SDL_modelist[1] = NULL; + } + + /* Fill in some window manager capabilities */ + this->info.wm_available = 1; + + /* We're done! */ + return (0); } -static SDL_Rect **ROM_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags) +static SDL_Rect ** +ROM_ListModes(_THIS, SDL_PixelFormat * format, Uint32 flags) { - if ( this->screen->format->BitsPerPixel == format->BitsPerPixel ) { - if ( (flags & SDL_FULLSCREEN) == SDL_FULLSCREEN ) { - return(SDL_modelist); - } else { - return((SDL_Rect **)-1); - } - } else { - return((SDL_Rect **)0); - } + if (this->screen->format->BitsPerPixel == format->BitsPerPixel) { + if ((flags & SDL_FULLSCREEN) == SDL_FULLSCREEN) { + return (SDL_modelist); + } else { + return ((SDL_Rect **) - 1); + } + } else { + return ((SDL_Rect **) 0); + } } -static void ROM_HideMenuBar(_THIS) +static void +ROM_HideMenuBar(_THIS) { -#if !TARGET_API_MAC_CARBON /* This seems not to be available? -sts Aug 2000 */ - RgnHandle drawRgn = nil; - RgnHandle tempRgn = nil; - RgnHandle grayRgn = nil; - WindowPtr window = nil; - GDHandle gd = nil; - GrafPtr savePort; - long response; - short height; - EventRecord theEvent; - - height = GetMBarHeight(); - - if ( height > 0 ) { - tempRgn = NewRgn(); - drawRgn = NewRgn(); - gSaveGrayRgn = NewRgn(); - if ( ! tempRgn || ! drawRgn || ! gSaveGrayRgn ) { - goto CLEANUP; - } - grayRgn = GetGrayRgn(); /* No need to check for this */ - - GetPort(&savePort); - - /* Hide the control strip if it's present, and record its - previous position into the dirty region for redrawing. - This isn't necessary, but may help catch stray bits. */ - CopyRgn(grayRgn, tempRgn); - if (!Gestalt(gestaltControlStripAttr, &response) && - (response & (1L << gestaltControlStripExists))) { - gSaveCSVis = SBIsControlStripVisible(); - if (gSaveCSVis) - SBShowHideControlStrip(false); - } - DiffRgn(grayRgn, tempRgn, drawRgn); - - /* Save the gray region once the control strip is hidden*/ - CopyRgn(grayRgn, gSaveGrayRgn); - - /* Change the menu height in lowmem */ - gSaveMenuBar = height; - LMSetMBarHeight(0); - - /* Walk the monitor rectangles, and combine any pieces that - aren't in GrayRgn: menubar, round corners, fake floaters. */ - for(gd = GetDeviceList(); gd; gd = GetNextDevice(gd)) - { - if (!TestDeviceAttribute(gd, screenDevice)) continue; - if (!TestDeviceAttribute(gd, screenActive)) continue; - - RectRgn(tempRgn, &(*gd)->gdRect); /* Get the whole screen */ - DiffRgn(tempRgn, grayRgn, tempRgn); /* Subtract out GrayRgn */ - UnionRgn(tempRgn, drawRgn, drawRgn);/* Combine all the bits */ - } - - /* Add the bits into the GrayRgn */ - UnionRgn(drawRgn, grayRgn, grayRgn); - - /* Modify the vis regions of exposed windows */ - window = (FrontWindow()) ? FrontWindow() : (WindowPtr) -1L; - PaintBehind(window, drawRgn); - CalcVisBehind(window, drawRgn); - - SetPort(savePort); - - /* Yield time so that floaters can catch up */ - EventAvail(0, &theEvent); - EventAvail(0, &theEvent); - EventAvail(0, &theEvent); - EventAvail(0, &theEvent); - } - -CLEANUP: - - if (tempRgn) DisposeRgn(tempRgn); - if (drawRgn) DisposeRgn(drawRgn); +#if !TARGET_API_MAC_CARBON /* This seems not to be available? -sts Aug 2000 */ + RgnHandle drawRgn = nil; + RgnHandle tempRgn = nil; + RgnHandle grayRgn = nil; + WindowPtr window = nil; + GDHandle gd = nil; + GrafPtr savePort; + long response; + short height; + EventRecord theEvent; + + height = GetMBarHeight(); + + if (height > 0) { + tempRgn = NewRgn(); + drawRgn = NewRgn(); + gSaveGrayRgn = NewRgn(); + if (!tempRgn || !drawRgn || !gSaveGrayRgn) { + goto CLEANUP; + } + grayRgn = GetGrayRgn(); /* No need to check for this */ + + GetPort(&savePort); + + /* Hide the control strip if it's present, and record its + previous position into the dirty region for redrawing. + This isn't necessary, but may help catch stray bits. */ + CopyRgn(grayRgn, tempRgn); + if (!Gestalt(gestaltControlStripAttr, &response) && + (response & (1L << gestaltControlStripExists))) { + gSaveCSVis = SBIsControlStripVisible(); + if (gSaveCSVis) + SBShowHideControlStrip(false); + } + DiffRgn(grayRgn, tempRgn, drawRgn); + + /* Save the gray region once the control strip is hidden */ + CopyRgn(grayRgn, gSaveGrayRgn); + + /* Change the menu height in lowmem */ + gSaveMenuBar = height; + LMSetMBarHeight(0); + + /* Walk the monitor rectangles, and combine any pieces that + aren't in GrayRgn: menubar, round corners, fake floaters. */ + for (gd = GetDeviceList(); gd; gd = GetNextDevice(gd)) { + if (!TestDeviceAttribute(gd, screenDevice)) + continue; + if (!TestDeviceAttribute(gd, screenActive)) + continue; + + RectRgn(tempRgn, &(*gd)->gdRect); /* Get the whole screen */ + DiffRgn(tempRgn, grayRgn, tempRgn); /* Subtract out GrayRgn */ + UnionRgn(tempRgn, drawRgn, drawRgn); /* Combine all the bits */ + } + + /* Add the bits into the GrayRgn */ + UnionRgn(drawRgn, grayRgn, grayRgn); + + /* Modify the vis regions of exposed windows */ + window = (FrontWindow())? FrontWindow() : (WindowPtr) - 1L; + PaintBehind(window, drawRgn); + CalcVisBehind(window, drawRgn); + + SetPort(savePort); + + /* Yield time so that floaters can catch up */ + EventAvail(0, &theEvent); + EventAvail(0, &theEvent); + EventAvail(0, &theEvent); + EventAvail(0, &theEvent); + } + + CLEANUP: + + if (tempRgn) + DisposeRgn(tempRgn); + if (drawRgn) + DisposeRgn(drawRgn); #endif /* !TARGET_API_MAC_CARBON */ } - -static void ROM_ShowMenuBar(_THIS) + +static void +ROM_ShowMenuBar(_THIS) { -#if !TARGET_API_MAC_CARBON /* This seems not to be available? -sts Aug 2000 */ - RgnHandle drawRgn = nil; - RgnHandle menuRgn = nil; - RgnHandle tempRgn = nil; - RgnHandle grayRgn = nil; - WindowPtr window = nil; - GrafPtr wMgrPort; - GrafPtr savePort; - Rect menuRect; - long response; - short height; - EventRecord theEvent; - RGBColor saveRGB; - RGBColor blackRGB = { 0, 0, 0 }; - - height = GetMBarHeight(); - - if ((height <= 0) && (gSaveMenuBar > 0)) { - drawRgn = NewRgn(); - menuRgn = NewRgn(); - tempRgn = NewRgn(); - if ( ! tempRgn || ! drawRgn || ! gSaveGrayRgn ) { - goto CLEANUP; - } - grayRgn = GetGrayRgn(); /* No need to check for this */ - - GetPort(&savePort); - GetWMgrPort(&wMgrPort); - - /* Set the height properly */ - LMSetMBarHeight(gSaveMenuBar); - - /* Restore the old GrayRgn: rounded corners, etc, but not - the menubar -- subtract that out first! */ - if (gSaveGrayRgn) - { - menuRect = (*GetMainDevice())->gdRect; - menuRect.bottom = menuRect.top + gSaveMenuBar; - RectRgn(menuRgn, &menuRect); - - DiffRgn(grayRgn, gSaveGrayRgn, drawRgn); /* What do we inval? */ - DiffRgn(drawRgn, menuRgn, drawRgn); /* Clip out the menu */ - - /* Now redraw the corners and other bits black */ - SetPort(wMgrPort); - GetClip(tempRgn); - SetClip(drawRgn); - GetForeColor(&saveRGB); - RGBForeColor(&blackRGB); - PaintRgn(drawRgn); - RGBForeColor(&saveRGB); - SetClip(tempRgn); - SetPort(savePort); - - UnionRgn(drawRgn, menuRgn, drawRgn); /* Put back the menu */ - - /* Now actually restore the GrayRgn */ - CopyRgn(gSaveGrayRgn, grayRgn); - DisposeRgn(gSaveGrayRgn); - gSaveGrayRgn = nil; - } - - /* Modify the vis regions of exposed windows and draw menubar */ - window = (FrontWindow()) ? FrontWindow() : (WindowPtr) -1L; - PaintBehind(window, drawRgn); - CalcVisBehind(window, drawRgn); - DrawMenuBar(); - - SetPort(savePort); - gSaveMenuBar = 0; - - /* Now show the control strip if it's present */ - if (!Gestalt(gestaltControlStripAttr, &response) && - (response & (1L << gestaltControlStripExists))) - { - if (gSaveCSVis && !SBIsControlStripVisible()) - SBShowHideControlStrip(true); - gSaveCSVis = true; - } - - /* Yield time so that floaters can catch up */ - EventAvail(0, &theEvent); - EventAvail(0, &theEvent); - EventAvail(0, &theEvent); - EventAvail(0, &theEvent); - } - -CLEANUP: - - if (drawRgn) DisposeRgn(drawRgn); - if (menuRgn) DisposeRgn(menuRgn); - if (tempRgn) DisposeRgn(tempRgn); +#if !TARGET_API_MAC_CARBON /* This seems not to be available? -sts Aug 2000 */ + RgnHandle drawRgn = nil; + RgnHandle menuRgn = nil; + RgnHandle tempRgn = nil; + RgnHandle grayRgn = nil; + WindowPtr window = nil; + GrafPtr wMgrPort; + GrafPtr savePort; + Rect menuRect; + long response; + short height; + EventRecord theEvent; + RGBColor saveRGB; + RGBColor blackRGB = { 0, 0, 0 }; + + height = GetMBarHeight(); + + if ((height <= 0) && (gSaveMenuBar > 0)) { + drawRgn = NewRgn(); + menuRgn = NewRgn(); + tempRgn = NewRgn(); + if (!tempRgn || !drawRgn || !gSaveGrayRgn) { + goto CLEANUP; + } + grayRgn = GetGrayRgn(); /* No need to check for this */ + + GetPort(&savePort); + GetWMgrPort(&wMgrPort); + + /* Set the height properly */ + LMSetMBarHeight(gSaveMenuBar); + + /* Restore the old GrayRgn: rounded corners, etc, but not + the menubar -- subtract that out first! */ + if (gSaveGrayRgn) { + menuRect = (*GetMainDevice())->gdRect; + menuRect.bottom = menuRect.top + gSaveMenuBar; + RectRgn(menuRgn, &menuRect); + + DiffRgn(grayRgn, gSaveGrayRgn, drawRgn); /* What do we inval? */ + DiffRgn(drawRgn, menuRgn, drawRgn); /* Clip out the menu */ + + /* Now redraw the corners and other bits black */ + SetPort(wMgrPort); + GetClip(tempRgn); + SetClip(drawRgn); + GetForeColor(&saveRGB); + RGBForeColor(&blackRGB); + PaintRgn(drawRgn); + RGBForeColor(&saveRGB); + SetClip(tempRgn); + SetPort(savePort); + + UnionRgn(drawRgn, menuRgn, drawRgn); /* Put back the menu */ + + /* Now actually restore the GrayRgn */ + CopyRgn(gSaveGrayRgn, grayRgn); + DisposeRgn(gSaveGrayRgn); + gSaveGrayRgn = nil; + } + + /* Modify the vis regions of exposed windows and draw menubar */ + window = (FrontWindow())? FrontWindow() : (WindowPtr) - 1L; + PaintBehind(window, drawRgn); + CalcVisBehind(window, drawRgn); + DrawMenuBar(); + + SetPort(savePort); + gSaveMenuBar = 0; + + /* Now show the control strip if it's present */ + if (!Gestalt(gestaltControlStripAttr, &response) && + (response & (1L << gestaltControlStripExists))) { + if (gSaveCSVis && !SBIsControlStripVisible()) + SBShowHideControlStrip(true); + gSaveCSVis = true; + } + + /* Yield time so that floaters can catch up */ + EventAvail(0, &theEvent); + EventAvail(0, &theEvent); + EventAvail(0, &theEvent); + EventAvail(0, &theEvent); + } + + CLEANUP: + + if (drawRgn) + DisposeRgn(drawRgn); + if (menuRgn) + DisposeRgn(menuRgn); + if (tempRgn) + DisposeRgn(tempRgn); #endif /* !TARGET_API_MAC_CARBON */ } /* Various screen update functions available */ -static void ROM_DirectUpdate(_THIS, int numrects, SDL_Rect *rects); -static void ROM_WindowUpdate(_THIS, int numrects, SDL_Rect *rects); +static void ROM_DirectUpdate(_THIS, int numrects, SDL_Rect * rects); +static void ROM_WindowUpdate(_THIS, int numrects, SDL_Rect * rects); -static void ROM_UnsetVideoMode(_THIS, SDL_Surface *current) +static void +ROM_UnsetVideoMode(_THIS, SDL_Surface * current) { - /* Free the current window, if any */ - if ( SDL_Window != nil ) { - GWorldPtr memworld; - - /* Handle OpenGL support */ - Mac_GL_Quit(this); - - memworld = (GWorldPtr)GetWRefCon(SDL_Window); - if ( memworld != nil ) { - UnlockPixels(GetGWorldPixMap(memworld)); - DisposeGWorld(memworld); - } - if ( (current->flags & SDL_FULLSCREEN) == SDL_FULLSCREEN ) { + /* Free the current window, if any */ + if (SDL_Window != nil) { + GWorldPtr memworld; + + /* Handle OpenGL support */ + Mac_GL_Quit(this); + + memworld = (GWorldPtr) GetWRefCon(SDL_Window); + if (memworld != nil) { + UnlockPixels(GetGWorldPixMap(memworld)); + DisposeGWorld(memworld); + } + if ((current->flags & SDL_FULLSCREEN) == SDL_FULLSCREEN) { #if USE_QUICKTIME - EndFullScreen(fullscreen_ctx, nil); - SDL_Window = nil; + EndFullScreen(fullscreen_ctx, nil); + SDL_Window = nil; #else - ROM_ShowMenuBar(this); + ROM_ShowMenuBar(this); #endif - } - } - current->pixels = NULL; - current->flags &= ~(SDL_HWSURFACE|SDL_FULLSCREEN); + } + } + current->pixels = NULL; + current->flags &= ~(SDL_HWSURFACE | SDL_FULLSCREEN); } -static SDL_Surface *ROM_SetVideoMode(_THIS, SDL_Surface *current, - int width, int height, int bpp, Uint32 flags) +static SDL_Surface * +ROM_SetVideoMode(_THIS, SDL_Surface * current, + int width, int height, int bpp, Uint32 flags) { - Rect wrect, orect; + Rect wrect, orect; #if TARGET_API_MAC_CARBON - Rect tmprect; + Rect tmprect; #endif - /* Free any previous video mode */ - ROM_UnsetVideoMode(this, current); + /* Free any previous video mode */ + ROM_UnsetVideoMode(this, current); - /* Create the ROM window and SDL video surface */ - current->flags = 0; /* Clear flags */ - current->w = width; - current->h = height; - SetRect(&wrect, 0, 0, width, height); - if ( SDL_Window ) { - /* If we recreate the window, don't move it around */ + /* Create the ROM window and SDL video surface */ + current->flags = 0; /* Clear flags */ + current->w = width; + current->h = height; + SetRect(&wrect, 0, 0, width, height); + if (SDL_Window) { + /* If we recreate the window, don't move it around */ #if TARGET_API_MAC_CARBON - orect = *GetWindowPortBounds(SDL_Window, &tmprect); + orect = *GetWindowPortBounds(SDL_Window, &tmprect); #else - orect = SDL_Window->portRect; + orect = SDL_Window->portRect; #endif - OffsetRect(&wrect, orect.left, orect.top); - } else { - /* Center the window the first time we show it */ - OffsetRect(&wrect, - (SDL_modelist[0]->w-width)/2, (SDL_modelist[0]->h-height)/2); - } + OffsetRect(&wrect, orect.left, orect.top); + } else { + /* Center the window the first time we show it */ + OffsetRect(&wrect, + (SDL_modelist[0]->w - width) / 2, + (SDL_modelist[0]->h - height) / 2); + } #if defined(__MACOSX__) && !USE_QUICKTIME - /* Hum.. fullscreen mode is broken */ - flags &= ~SDL_FULLSCREEN; + /* Hum.. fullscreen mode is broken */ + flags &= ~SDL_FULLSCREEN; #endif - if ( (flags & SDL_FULLSCREEN) == SDL_FULLSCREEN ) { - /* Create the fullscreen window and use screen bits */ - current->flags |= SDL_HWSURFACE|SDL_FULLSCREEN; - if ( SDL_Window ) { - DisposeWindow(SDL_Window); - } + if ((flags & SDL_FULLSCREEN) == SDL_FULLSCREEN) { + /* Create the fullscreen window and use screen bits */ + current->flags |= SDL_HWSURFACE | SDL_FULLSCREEN; + if (SDL_Window) { + DisposeWindow(SDL_Window); + } #if USE_QUICKTIME - BeginFullScreen(&fullscreen_ctx, nil, 0,0, &SDL_Window, nil, 0); + BeginFullScreen(&fullscreen_ctx, nil, 0, 0, &SDL_Window, nil, 0); #else - SDL_Window = NewCWindow(nil, &wrect, "\p", true, plainDBox, - (WindowPtr)-1, false, 0); - ROM_HideMenuBar(this); + SDL_Window = NewCWindow(nil, &wrect, "\p", true, plainDBox, + (WindowPtr) - 1, false, 0); + ROM_HideMenuBar(this); #endif - current->pitch = (**(**SDL_Display).gdPMap).rowBytes & 0x3FFF; - current->pixels = (**(**SDL_Display).gdPMap).baseAddr; - this->UpdateRects = ROM_DirectUpdate; - } else { - GWorldPtr memworld; - PixMapHandle pixmap; - int style; - - style = noGrowDocProc; - if ( flags & SDL_NOFRAME ) { - style = plainDBox; - current->flags |= SDL_NOFRAME; - } else - if ( flags & SDL_RESIZABLE ) { - style = zoomDocProc; - current->flags |= SDL_RESIZABLE; - } - if ( SDL_Window && (style == current_style) ) { - /* Resize existing window, if necessary */ - if ( ((orect.right-orect.left) != width) || - ((orect.bottom-orect.top) != height) ) { - SizeWindow(SDL_Window, width, height, false); - } - } else { - /* Recreate the window in the new style */ - if ( SDL_Window ) { - DisposeWindow(SDL_Window); - } - SDL_Window = NewCWindow(nil, &wrect, "\p", true, - style, (WindowPtr)-1, true, 0); - - /* Set the window title, if any */ - { char *title; - SDL_WM_GetCaption(&title, NULL); - if ( title ) { - Mac_SetCaption(this, title, NULL); - } - } - } - current_style = style; - SetPalette(SDL_Window, SDL_CPal, false); - ActivatePalette(SDL_Window); - if ( NewGWorld(&memworld, 0, + current->pitch = (**(**SDL_Display).gdPMap).rowBytes & 0x3FFF; + current->pixels = (**(**SDL_Display).gdPMap).baseAddr; + this->UpdateRects = ROM_DirectUpdate; + } else { + GWorldPtr memworld; + PixMapHandle pixmap; + int style; + + style = noGrowDocProc; + if (flags & SDL_NOFRAME) { + style = plainDBox; + current->flags |= SDL_NOFRAME; + } else if (flags & SDL_RESIZABLE) { + style = zoomDocProc; + current->flags |= SDL_RESIZABLE; + } + if (SDL_Window && (style == current_style)) { + /* Resize existing window, if necessary */ + if (((orect.right - orect.left) != width) || + ((orect.bottom - orect.top) != height)) { + SizeWindow(SDL_Window, width, height, false); + } + } else { + /* Recreate the window in the new style */ + if (SDL_Window) { + DisposeWindow(SDL_Window); + } + SDL_Window = NewCWindow(nil, &wrect, "\p", true, + style, (WindowPtr) - 1, true, 0); + + /* Set the window title, if any */ + { + char *title; + SDL_WM_GetCaption(&title, NULL); + if (title) { + Mac_SetCaption(this, title, NULL); + } + } + } + current_style = style; + SetPalette(SDL_Window, SDL_CPal, false); + ActivatePalette(SDL_Window); + if (NewGWorld(&memworld, 0, #if TARGET_API_MAC_CARBON - GetWindowPortBounds(SDL_Window, &tmprect), + GetWindowPortBounds(SDL_Window, &tmprect), #else - &SDL_Window->portRect, + &SDL_Window->portRect, #endif - SDL_CTab, nil, 0) != noErr ) { - SDL_SetError("NewGWorld() failed"); - return(NULL); - } - SetWRefCon(SDL_Window, (long)memworld); - pixmap = GetGWorldPixMap(memworld); - LockPixels(pixmap); - current->pitch = (**pixmap).rowBytes & 0x3FFF; - current->pixels = GetPixBaseAddr(pixmap); - this->UpdateRects = ROM_WindowUpdate; - } - SetPortWindowPort(SDL_Window); - SelectWindow(SDL_Window); - - /* Handle OpenGL support */ - if ( flags & SDL_OPENGL ) { - if ( Mac_GL_Init(this) == 0 ) { - current->flags |= SDL_OPENGL; - } else { - current = NULL; - } - } - - if ( (flags & SDL_HWPALETTE) && (flags & SDL_FULLSCREEN) ) - current->flags |= SDL_HWPALETTE; - - /* We're live! */ - return(current); + SDL_CTab, nil, 0) != noErr) { + SDL_SetError("NewGWorld() failed"); + return (NULL); + } + SetWRefCon(SDL_Window, (long) memworld); + pixmap = GetGWorldPixMap(memworld); + LockPixels(pixmap); + current->pitch = (**pixmap).rowBytes & 0x3FFF; + current->pixels = GetPixBaseAddr(pixmap); + this->UpdateRects = ROM_WindowUpdate; + } + SetPortWindowPort(SDL_Window); + SelectWindow(SDL_Window); + + /* Handle OpenGL support */ + if (flags & SDL_INTERNALOPENGL) { + if (Mac_GL_Init(this) == 0) { + current->flags |= SDL_INTERNALOPENGL; + } else { + current = NULL; + } + } + + if ((flags & SDL_HWPALETTE) && (flags & SDL_FULLSCREEN)) + current->flags |= SDL_HWPALETTE; + + /* We're live! */ + return (current); } /* We don't actually allow hardware surfaces other than the main one */ -static int ROM_AllocHWSurface(_THIS, SDL_Surface *surface) +static int +ROM_AllocHWSurface(_THIS, SDL_Surface * surface) { - return(-1); + return (-1); } -static void ROM_FreeHWSurface(_THIS, SDL_Surface *surface) +static void +ROM_FreeHWSurface(_THIS, SDL_Surface * surface) { - return; + return; } -static int ROM_LockHWSurface(_THIS, SDL_Surface *surface) +static int +ROM_LockHWSurface(_THIS, SDL_Surface * surface) { - return(0); + return (0); } -static void ROM_UnlockHWSurface(_THIS, SDL_Surface *surface) +static void +ROM_UnlockHWSurface(_THIS, SDL_Surface * surface) { - return; + return; } -static void ROM_DirectUpdate(_THIS, int numrects, SDL_Rect *rects) +static void +ROM_DirectUpdate(_THIS, int numrects, SDL_Rect * rects) { - /* The application is already updating the visible video memory */ - return; + /* The application is already updating the visible video memory */ + return; } -static void ROM_WindowUpdate(_THIS, int numrects, SDL_Rect *rects) +static void +ROM_WindowUpdate(_THIS, int numrects, SDL_Rect * rects) { - GWorldPtr memworld; - GrafPtr saveport; - CGrafPtr thePort; - const BitMap *memBits; - const BitMap *winBits; - int i; - Rect update; - - /* Copy from the offscreen GWorld to the window port */ - GetPort(&saveport); - SetPortWindowPort(SDL_Window); - thePort = GetWindowPort(SDL_Window); - memworld = (GWorldPtr)GetWRefCon(SDL_Window); + GWorldPtr memworld; + GrafPtr saveport; + CGrafPtr thePort; + const BitMap *memBits; + const BitMap *winBits; + int i; + Rect update; + + /* Copy from the offscreen GWorld to the window port */ + GetPort(&saveport); + SetPortWindowPort(SDL_Window); + thePort = GetWindowPort(SDL_Window); + memworld = (GWorldPtr) GetWRefCon(SDL_Window); #if TARGET_API_MAC_CARBON && ACCESSOR_CALLS_ARE_FUNCTIONS - memBits = GetPortBitMapForCopyBits((CGrafPtr) memworld); + memBits = GetPortBitMapForCopyBits((CGrafPtr) memworld); #else - memBits = &((GrafPtr)memworld)->portBits; + memBits = &((GrafPtr) memworld)->portBits; #endif #if TARGET_API_MAC_CARBON && ACCESSOR_CALLS_ARE_FUNCTIONS - winBits = GetPortBitMapForCopyBits(thePort); + winBits = GetPortBitMapForCopyBits(thePort); #else - winBits = &SDL_Window->portBits; + winBits = &SDL_Window->portBits; #endif - for ( i=0; iscreen->flags & SDL_FULLSCREEN) == SDL_FULLSCREEN ) { - cTab = (**(**SDL_Display).gdPMap).pmTable; - } else { - cTab = SDL_CTab; - } - - /* Verify the range of colors */ - if ( (firstcolor+ncolors) > ((**cTab).ctSize+1) ) { - return(0); - } - - /* Set the screen palette and update the display */ - for ( i=0; i< ncolors; ++i ) { - int j = firstcolor + i; - (**cTab).ctTable[j].value = j; - (**cTab).ctTable[j].rgb.red = colors[i].r << 8 | colors[i].r; - (**cTab).ctTable[j].rgb.green = colors[i].g << 8 | colors[i].g; - (**cTab).ctTable[j].rgb.blue = colors[i].b << 8 | colors[i].b; - } -// if ( (this->screen->flags & SDL_FULLSCREEN) == SDL_FULLSCREEN ) +static int +ROM_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color * colors) { - GDevice **odisplay; - odisplay = GetGDevice(); - SetGDevice(SDL_Display); - SetEntries(0, (**cTab).ctSize, (ColorSpec *)&(**cTab).ctTable); - SetGDevice(odisplay); - } - return(1); + CTabHandle cTab; + int i; + + /* Get the colortable from the either the display or window */ + if ((this->screen->flags & SDL_FULLSCREEN) == SDL_FULLSCREEN) { + cTab = (**(**SDL_Display).gdPMap).pmTable; + } else { + cTab = SDL_CTab; + } + + /* Verify the range of colors */ + if ((firstcolor + ncolors) > ((**cTab).ctSize + 1)) { + return (0); + } + + /* Set the screen palette and update the display */ + for (i = 0; i < ncolors; ++i) { + int j = firstcolor + i; + (**cTab).ctTable[j].value = j; + (**cTab).ctTable[j].rgb.red = colors[i].r << 8 | colors[i].r; + (**cTab).ctTable[j].rgb.green = colors[i].g << 8 | colors[i].g; + (**cTab).ctTable[j].rgb.blue = colors[i].b << 8 | colors[i].b; + } +// if ( (this->screen->flags & SDL_FULLSCREEN) == SDL_FULLSCREEN ) + { + GDevice **odisplay; + odisplay = GetGDevice(); + SetGDevice(SDL_Display); + SetEntries(0, (**cTab).ctSize, (ColorSpec *) & (**cTab).ctTable); + SetGDevice(odisplay); + } + return (1); } -void ROM_VideoQuit(_THIS) +void +ROM_VideoQuit(_THIS) { - int i; - - /* Free current video mode */ - ROM_UnsetVideoMode(this, this->screen); - if ( SDL_Window ) { - DisposeWindow(SDL_Window); - SDL_Window = nil; - } - - /* Free palette and restore original one */ - if ( SDL_CTab != nil ) { - DisposeHandle((Handle)SDL_CTab); - SDL_CTab = nil; - } - if ( SDL_CPal != nil ) { - DisposePalette(SDL_CPal); - SDL_CPal = nil; - } - RestoreDeviceClut(GetMainDevice()); - - /* Free list of video modes */ - if ( SDL_modelist != NULL ) { - for ( i=0; SDL_modelist[i]; ++i ) { - SDL_free(SDL_modelist[i]); - } - SDL_free(SDL_modelist); - SDL_modelist = NULL; - } + int i; + + /* Free current video mode */ + ROM_UnsetVideoMode(this, this->screen); + if (SDL_Window) { + DisposeWindow(SDL_Window); + SDL_Window = nil; + } + + /* Free palette and restore original one */ + if (SDL_CTab != nil) { + DisposeHandle((Handle) SDL_CTab); + SDL_CTab = nil; + } + if (SDL_CPal != nil) { + DisposePalette(SDL_CPal); + SDL_CPal = nil; + } + RestoreDeviceClut(GetMainDevice()); + + /* Free list of video modes */ + if (SDL_modelist != NULL) { + for (i = 0; SDL_modelist[i]; ++i) { + SDL_free(SDL_modelist[i]); + } + SDL_free(SDL_modelist); + SDL_modelist = NULL; + } } +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/macrom/SDL_romvideo.h b/src/video/macrom/SDL_romvideo.h index 96910d41d..76b663c5a 100644 --- a/src/video/macrom/SDL_romvideo.h +++ b/src/video/macrom/SDL_romvideo.h @@ -27,3 +27,4 @@ #include "../maccommon/SDL_lowvideo.h" #endif /* _SDL_romvideo_h */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/math_private.h b/src/video/math_private.h index 1087d7dea..06cb06ac7 100644 --- a/src/video/math_private.h +++ b/src/video/math_private.h @@ -20,7 +20,7 @@ #include "SDL_name.h" #include "SDL_endian.h" -#define huge really_big /* huge is a reserved keyword in VC++ 6.0 */ +#define huge really_big /* huge is a reserved keyword in VC++ 6.0 */ #define u_int32_t uint32_t /* The original fdlibm code used statements like: @@ -48,24 +48,24 @@ typedef union { - double value; - struct - { - u_int32_t msw; - u_int32_t lsw; - } parts; + double value; + struct + { + u_int32_t msw; + u_int32_t lsw; + } parts; } ieee_double_shape_type; #else typedef union { - double value; - struct - { - u_int32_t lsw; - u_int32_t msw; - } parts; + double value; + struct + { + u_int32_t lsw; + u_int32_t msw; + } parts; } ieee_double_shape_type; #endif @@ -133,8 +133,8 @@ do { \ typedef union { - float value; - u_int32_t word; + float value; + u_int32_t word; } ieee_float_shape_type; /* Get a 32 bit int from a float. */ @@ -161,13 +161,10 @@ static const double #else static double #endif -zero = 0.0, -one = 1.0, -two = 2.0, -two53 = 9007199254740992.0, /* 0x43400000, 0x00000000 */ -two54 = 1.80143985094819840000e+16, /* 0x43500000, 0x00000000 */ -twom54 = 5.55111512312578270212e-17, /* 0x3C900000, 0x00000000 */ -huge = 1.0e+300, -tiny = 1.0e-300; + zero = 0.0, one = 1.0, two = 2.0, two53 = 9007199254740992.0, /* 0x43400000, 0x00000000 */ + two54 = 1.80143985094819840000e+16, /* 0x43500000, 0x00000000 */ + twom54 = 5.55111512312578270212e-17, /* 0x3C900000, 0x00000000 */ + huge = 1.0e+300, tiny = 1.0e-300; #endif /* _MATH_PRIVATE_H_ */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/mmx.h b/src/video/mmx.h index 396c4326c..86190d473 100644 --- a/src/video/mmx.h +++ b/src/video/mmx.h @@ -43,17 +43,18 @@ by LL and unsigned long long values by ULL, lest they be truncated by the compiler) */ -typedef union { - long long q; /* Quadword (64-bit) value */ - unsigned long long uq; /* Unsigned Quadword */ - int d[2]; /* 2 Doubleword (32-bit) values */ - unsigned int ud[2]; /* 2 Unsigned Doubleword */ - short w[4]; /* 4 Word (16-bit) values */ - unsigned short uw[4]; /* 4 Unsigned Word */ - char b[8]; /* 8 Byte (8-bit) values */ - unsigned char ub[8]; /* 8 Unsigned Byte */ - float s[2]; /* Single-precision (32-bit) value */ -} __attribute__ ((aligned (8))) mmx_t; /* On an 8-byte (64-bit) boundary */ +typedef union +{ + long long q; /* Quadword (64-bit) value */ + unsigned long long uq; /* Unsigned Quadword */ + int d[2]; /* 2 Doubleword (32-bit) values */ + unsigned int ud[2]; /* 2 Unsigned Doubleword */ + short w[4]; /* 4 Word (16-bit) values */ + unsigned short uw[4]; /* 4 Unsigned Word */ + char b[8]; /* 8 Byte (8-bit) values */ + unsigned char ub[8]; /* 8 Unsigned Byte */ + float s[2]; /* Single-precision (32-bit) value */ +} __attribute__ ((aligned(8))) mmx_t; /* On an 8-byte (64-bit) boundary */ #if 0 @@ -62,158 +63,95 @@ typedef union { inline extern int mm_support(void) { - /* Returns 1 if MMX instructions are supported, - 3 if Cyrix MMX and Extended MMX instructions are supported - 5 if AMD MMX and 3DNow! instructions are supported - 0 if hardware does not support any of these - */ - register int rval = 0; - - __asm__ __volatile__ ( - /* See if CPUID instruction is supported ... */ - /* ... Get copies of EFLAGS into eax and ecx */ - "pushf\n\t" - "popl %%eax\n\t" - "movl %%eax, %%ecx\n\t" - - /* ... Toggle the ID bit in one copy and store */ - /* to the EFLAGS reg */ - "xorl $0x200000, %%eax\n\t" - "push %%eax\n\t" - "popf\n\t" - - /* ... Get the (hopefully modified) EFLAGS */ - "pushf\n\t" - "popl %%eax\n\t" - - /* ... Compare and test result */ - "xorl %%eax, %%ecx\n\t" - "testl $0x200000, %%ecx\n\t" - "jz NotSupported1\n\t" /* CPUID not supported */ - - - /* Get standard CPUID information, and - go to a specific vendor section */ - "movl $0, %%eax\n\t" - "cpuid\n\t" - - /* Check for Intel */ - "cmpl $0x756e6547, %%ebx\n\t" - "jne TryAMD\n\t" - "cmpl $0x49656e69, %%edx\n\t" - "jne TryAMD\n\t" - "cmpl $0x6c65746e, %%ecx\n" - "jne TryAMD\n\t" - "jmp Intel\n\t" - - /* Check for AMD */ - "\nTryAMD:\n\t" - "cmpl $0x68747541, %%ebx\n\t" - "jne TryCyrix\n\t" - "cmpl $0x69746e65, %%edx\n\t" - "jne TryCyrix\n\t" - "cmpl $0x444d4163, %%ecx\n" - "jne TryCyrix\n\t" - "jmp AMD\n\t" - - /* Check for Cyrix */ - "\nTryCyrix:\n\t" - "cmpl $0x69727943, %%ebx\n\t" - "jne NotSupported2\n\t" - "cmpl $0x736e4978, %%edx\n\t" - "jne NotSupported3\n\t" - "cmpl $0x64616574, %%ecx\n\t" - "jne NotSupported4\n\t" - /* Drop through to Cyrix... */ - - - /* Cyrix Section */ - /* See if extended CPUID level 80000001 is supported */ - /* The value of CPUID/80000001 for the 6x86MX is undefined - according to the Cyrix CPU Detection Guide (Preliminary - Rev. 1.01 table 1), so we'll check the value of eax for - CPUID/0 to see if standard CPUID level 2 is supported. - According to the table, the only CPU which supports level - 2 is also the only one which supports extended CPUID levels. - */ - "cmpl $0x2, %%eax\n\t" - "jne MMXtest\n\t" /* Use standard CPUID instead */ - - /* Extended CPUID supported (in theory), so get extended - features */ - "movl $0x80000001, %%eax\n\t" - "cpuid\n\t" - "testl $0x00800000, %%eax\n\t" /* Test for MMX */ - "jz NotSupported5\n\t" /* MMX not supported */ - "testl $0x01000000, %%eax\n\t" /* Test for Ext'd MMX */ - "jnz EMMXSupported\n\t" - "movl $1, %0:\n\n\t" /* MMX Supported */ - "jmp Return\n\n" - "EMMXSupported:\n\t" - "movl $3, %0:\n\n\t" /* EMMX and MMX Supported */ - "jmp Return\n\t" - - - /* AMD Section */ - "AMD:\n\t" - - /* See if extended CPUID is supported */ - "movl $0x80000000, %%eax\n\t" - "cpuid\n\t" - "cmpl $0x80000000, %%eax\n\t" - "jl MMXtest\n\t" /* Use standard CPUID instead */ - - /* Extended CPUID supported, so get extended features */ - "movl $0x80000001, %%eax\n\t" - "cpuid\n\t" - "testl $0x00800000, %%edx\n\t" /* Test for MMX */ - "jz NotSupported6\n\t" /* MMX not supported */ - "testl $0x80000000, %%edx\n\t" /* Test for 3DNow! */ - "jnz ThreeDNowSupported\n\t" - "movl $1, %0:\n\n\t" /* MMX Supported */ - "jmp Return\n\n" - "ThreeDNowSupported:\n\t" - "movl $5, %0:\n\n\t" /* 3DNow! and MMX Supported */ - "jmp Return\n\t" - - - /* Intel Section */ - "Intel:\n\t" - - /* Check for MMX */ - "MMXtest:\n\t" - "movl $1, %%eax\n\t" - "cpuid\n\t" - "testl $0x00800000, %%edx\n\t" /* Test for MMX */ - "jz NotSupported7\n\t" /* MMX Not supported */ - "movl $1, %0:\n\n\t" /* MMX Supported */ - "jmp Return\n\t" - - /* Nothing supported */ - "\nNotSupported1:\n\t" - "#movl $101, %0:\n\n\t" - "\nNotSupported2:\n\t" - "#movl $102, %0:\n\n\t" - "\nNotSupported3:\n\t" - "#movl $103, %0:\n\n\t" - "\nNotSupported4:\n\t" - "#movl $104, %0:\n\n\t" - "\nNotSupported5:\n\t" - "#movl $105, %0:\n\n\t" - "\nNotSupported6:\n\t" - "#movl $106, %0:\n\n\t" - "\nNotSupported7:\n\t" - "#movl $107, %0:\n\n\t" - "movl $0, %0:\n\n\t" - - "Return:\n\t" - : "=a" (rval) - : /* no input */ - : "eax", "ebx", "ecx", "edx" - ); - - /* Return */ - return(rval); + /* Returns 1 if MMX instructions are supported, + 3 if Cyrix MMX and Extended MMX instructions are supported + 5 if AMD MMX and 3DNow! instructions are supported + 0 if hardware does not support any of these + */ + register int rval = 0; + + __asm__ __volatile__( + /* See if CPUID instruction is supported ... */ + /* ... Get copies of EFLAGS into eax and ecx */ + "pushf\n\t" + "popl %%eax\n\t" "movl %%eax, %%ecx\n\t" + /* ... Toggle the ID bit in one copy and store */ + /* to the EFLAGS reg */ + "xorl $0x200000, %%eax\n\t" + "push %%eax\n\t" "popf\n\t" + /* ... Get the (hopefully modified) EFLAGS */ + "pushf\n\t" "popl %%eax\n\t" + /* ... Compare and test result */ + "xorl %%eax, %%ecx\n\t" "testl $0x200000, %%ecx\n\t" "jz NotSupported1\n\t" /* CPUID not supported */ + /* Get standard CPUID information, and + go to a specific vendor section */ + "movl $0, %%eax\n\t" "cpuid\n\t" + /* Check for Intel */ + "cmpl $0x756e6547, %%ebx\n\t" + "jne TryAMD\n\t" + "cmpl $0x49656e69, %%edx\n\t" + "jne TryAMD\n\t" + "cmpl $0x6c65746e, %%ecx\n" + "jne TryAMD\n\t" "jmp Intel\n\t" + /* Check for AMD */ + "\nTryAMD:\n\t" + "cmpl $0x68747541, %%ebx\n\t" + "jne TryCyrix\n\t" + "cmpl $0x69746e65, %%edx\n\t" + "jne TryCyrix\n\t" + "cmpl $0x444d4163, %%ecx\n" + "jne TryCyrix\n\t" "jmp AMD\n\t" + /* Check for Cyrix */ + "\nTryCyrix:\n\t" + "cmpl $0x69727943, %%ebx\n\t" + "jne NotSupported2\n\t" + "cmpl $0x736e4978, %%edx\n\t" + "jne NotSupported3\n\t" + "cmpl $0x64616574, %%ecx\n\t" + "jne NotSupported4\n\t" + /* Drop through to Cyrix... */ + /* Cyrix Section */ + /* See if extended CPUID level 80000001 is supported */ + /* The value of CPUID/80000001 for the 6x86MX is undefined + according to the Cyrix CPU Detection Guide (Preliminary + Rev. 1.01 table 1), so we'll check the value of eax for + CPUID/0 to see if standard CPUID level 2 is supported. + According to the table, the only CPU which supports level + 2 is also the only one which supports extended CPUID levels. + */ + "cmpl $0x2, %%eax\n\t" "jne MMXtest\n\t" /* Use standard CPUID instead */ + /* Extended CPUID supported (in theory), so get extended + features */ + "movl $0x80000001, %%eax\n\t" "cpuid\n\t" "testl $0x00800000, %%eax\n\t" /* Test for MMX */ + "jz NotSupported5\n\t" /* MMX not supported */ + "testl $0x01000000, %%eax\n\t" /* Test for Ext'd MMX */ + "jnz EMMXSupported\n\t" "movl $1, %0:\n\n\t" /* MMX Supported */ + "jmp Return\n\n" "EMMXSupported:\n\t" "movl $3, %0:\n\n\t" /* EMMX and MMX Supported */ + "jmp Return\n\t" + /* AMD Section */ + "AMD:\n\t" + /* See if extended CPUID is supported */ + "movl $0x80000000, %%eax\n\t" "cpuid\n\t" "cmpl $0x80000000, %%eax\n\t" "jl MMXtest\n\t" /* Use standard CPUID instead */ + /* Extended CPUID supported, so get extended features */ + "movl $0x80000001, %%eax\n\t" "cpuid\n\t" "testl $0x00800000, %%edx\n\t" /* Test for MMX */ + "jz NotSupported6\n\t" /* MMX not supported */ + "testl $0x80000000, %%edx\n\t" /* Test for 3DNow! */ + "jnz ThreeDNowSupported\n\t" "movl $1, %0:\n\n\t" /* MMX Supported */ + "jmp Return\n\n" "ThreeDNowSupported:\n\t" "movl $5, %0:\n\n\t" /* 3DNow! and MMX Supported */ + "jmp Return\n\t" + /* Intel Section */ + "Intel:\n\t" + /* Check for MMX */ + "MMXtest:\n\t" "movl $1, %%eax\n\t" "cpuid\n\t" "testl $0x00800000, %%edx\n\t" /* Test for MMX */ + "jz NotSupported7\n\t" /* MMX Not supported */ + "movl $1, %0:\n\n\t" /* MMX Supported */ + "jmp Return\n\t" + /* Nothing supported */ + "\nNotSupported1:\n\t" "#movl $101, %0:\n\n\t" "\nNotSupported2:\n\t" "#movl $102, %0:\n\n\t" "\nNotSupported3:\n\t" "#movl $103, %0:\n\n\t" "\nNotSupported4:\n\t" "#movl $104, %0:\n\n\t" "\nNotSupported5:\n\t" "#movl $105, %0:\n\n\t" "\nNotSupported6:\n\t" "#movl $106, %0:\n\n\t" "\nNotSupported7:\n\t" "#movl $107, %0:\n\n\t" "movl $0, %0:\n\n\t" "Return:\n\t":"=a"(rval): /* no input */ + :"eax", "ebx", "ecx", "edx"); + + /* Return */ + return (rval); } /* Function to test if mmx instructions are supported... @@ -221,8 +159,8 @@ mm_support(void) inline extern int mmx_ok(void) { - /* Returns 1 if MMX instructions are supported, 0 otherwise */ - return ( mm_support() & 0x1 ); + /* Returns 1 if MMX instructions are supported, 0 otherwise */ + return (mm_support() & 0x1); } #endif @@ -701,4 +639,4 @@ mmx_ok(void) #endif #endif - +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/nanox/SDL_nxevents.c b/src/video/nanox/SDL_nxevents.c index fb1980d5d..6192fda5a 100644 --- a/src/video/nanox/SDL_nxevents.c +++ b/src/video/nanox/SDL_nxevents.c @@ -33,350 +33,371 @@ #include "SDL_nximage_c.h" // The translation tables from a nanox keysym to a SDL keysym -static SDLKey NX_NONASCII_keymap [MWKEY_LAST + 1] ; +static SDLKey NX_NONASCII_keymap[MWKEY_LAST + 1]; -void NX_InitOSKeymap (_THIS) +void +NX_InitOSKeymap(_THIS) { - int i ; + int i; - Dprintf ("enter NX_InitOSKeymap\n") ; + Dprintf("enter NX_InitOSKeymap\n"); // Map the nanox scancodes to SDL keysyms - for (i = 0; i < SDL_arraysize (NX_NONASCII_keymap); ++ i) - NX_NONASCII_keymap [i] = SDLK_UNKNOWN ; - - NX_NONASCII_keymap [MWKEY_LEFT & 0xFF] = SDLK_LEFT ; - NX_NONASCII_keymap [MWKEY_RIGHT & 0xFF] = SDLK_RIGHT ; - NX_NONASCII_keymap [MWKEY_UP & 0xFF] = SDLK_UP ; - NX_NONASCII_keymap [MWKEY_DOWN & 0xFF] = SDLK_DOWN ; - NX_NONASCII_keymap [MWKEY_INSERT & 0xFF] = SDLK_INSERT ; - NX_NONASCII_keymap [MWKEY_DELETE & 0xFF] = SDLK_DELETE ; - NX_NONASCII_keymap [MWKEY_HOME & 0xFF] = SDLK_HOME ; - NX_NONASCII_keymap [MWKEY_END & 0xFF] = SDLK_END ; - NX_NONASCII_keymap [MWKEY_PAGEUP & 0xFF] = SDLK_PAGEUP ; - NX_NONASCII_keymap [MWKEY_PAGEDOWN & 0xFF] = SDLK_PAGEDOWN ; - - NX_NONASCII_keymap [MWKEY_KP0 & 0xFF] = SDLK_KP0 ; - NX_NONASCII_keymap [MWKEY_KP1 & 0xFF] = SDLK_KP1 ; - NX_NONASCII_keymap [MWKEY_KP2 & 0xFF] = SDLK_KP2 ; - NX_NONASCII_keymap [MWKEY_KP3 & 0xFF] = SDLK_KP3 ; - NX_NONASCII_keymap [MWKEY_KP4 & 0xFF] = SDLK_KP4 ; - NX_NONASCII_keymap [MWKEY_KP5 & 0xFF] = SDLK_KP5 ; - NX_NONASCII_keymap [MWKEY_KP6 & 0xFF] = SDLK_KP6 ; - NX_NONASCII_keymap [MWKEY_KP7 & 0xFF] = SDLK_KP7 ; - NX_NONASCII_keymap [MWKEY_KP8 & 0xFF] = SDLK_KP8 ; - NX_NONASCII_keymap [MWKEY_KP9 & 0xFF] = SDLK_KP9 ; - NX_NONASCII_keymap [MWKEY_KP_PERIOD & 0xFF] = SDLK_KP_PERIOD ; - NX_NONASCII_keymap [MWKEY_KP_DIVIDE & 0xFF] = SDLK_KP_DIVIDE ; - NX_NONASCII_keymap [MWKEY_KP_MULTIPLY & 0xFF] = SDLK_KP_MULTIPLY ; - NX_NONASCII_keymap [MWKEY_KP_MINUS & 0xFF] = SDLK_KP_MINUS ; - NX_NONASCII_keymap [MWKEY_KP_PLUS & 0xFF] = SDLK_KP_PLUS ; - NX_NONASCII_keymap [MWKEY_KP_ENTER & 0xFF] = SDLK_KP_ENTER ; - NX_NONASCII_keymap [MWKEY_KP_EQUALS & 0xFF] = SDLK_KP_EQUALS ; - - NX_NONASCII_keymap [MWKEY_F1 & 0xFF] = SDLK_F1 ; - NX_NONASCII_keymap [MWKEY_F2 & 0xFF] = SDLK_F2 ; - NX_NONASCII_keymap [MWKEY_F3 & 0xFF] = SDLK_F3 ; - NX_NONASCII_keymap [MWKEY_F4 & 0xFF] = SDLK_F4 ; - NX_NONASCII_keymap [MWKEY_F5 & 0xFF] = SDLK_F5 ; - NX_NONASCII_keymap [MWKEY_F6 & 0xFF] = SDLK_F6 ; - NX_NONASCII_keymap [MWKEY_F7 & 0xFF] = SDLK_F7 ; - NX_NONASCII_keymap [MWKEY_F8 & 0xFF] = SDLK_F8 ; - NX_NONASCII_keymap [MWKEY_F9 & 0xFF] = SDLK_F9 ; - NX_NONASCII_keymap [MWKEY_F10 & 0xFF] = SDLK_F10 ; - NX_NONASCII_keymap [MWKEY_F11 & 0xFF] = SDLK_F11 ; - NX_NONASCII_keymap [MWKEY_F12 & 0xFF] = SDLK_F12 ; - - NX_NONASCII_keymap [MWKEY_NUMLOCK & 0xFF] = SDLK_NUMLOCK ; - NX_NONASCII_keymap [MWKEY_CAPSLOCK & 0xFF] = SDLK_CAPSLOCK ; - NX_NONASCII_keymap [MWKEY_SCROLLOCK & 0xFF] = SDLK_SCROLLOCK ; - NX_NONASCII_keymap [MWKEY_LSHIFT & 0xFF] = SDLK_LSHIFT ; - NX_NONASCII_keymap [MWKEY_RSHIFT & 0xFF] = SDLK_RSHIFT ; - NX_NONASCII_keymap [MWKEY_LCTRL & 0xFF] = SDLK_LCTRL ; - NX_NONASCII_keymap [MWKEY_RCTRL & 0xFF] = SDLK_RCTRL ; - NX_NONASCII_keymap [MWKEY_LALT & 0xFF] = SDLK_LALT ; - NX_NONASCII_keymap [MWKEY_RALT & 0xFF] = SDLK_RALT ; - NX_NONASCII_keymap [MWKEY_LMETA & 0xFF] = SDLK_LMETA ; - NX_NONASCII_keymap [MWKEY_RMETA & 0xFF] = SDLK_RMETA ; - NX_NONASCII_keymap [MWKEY_ALTGR & 0xFF] = SDLK_MODE ; - - NX_NONASCII_keymap [MWKEY_PRINT & 0xFF] = SDLK_PRINT ; - NX_NONASCII_keymap [MWKEY_SYSREQ & 0xFF] = SDLK_SYSREQ ; - NX_NONASCII_keymap [MWKEY_PAUSE & 0xFF] = SDLK_PAUSE ; - NX_NONASCII_keymap [MWKEY_BREAK & 0xFF] = SDLK_BREAK ; - NX_NONASCII_keymap [MWKEY_MENU & 0xFF] = SDLK_MENU ; - - Dprintf ("leave NX_InitOSKeymap\n") ; + for (i = 0; i < SDL_arraysize(NX_NONASCII_keymap); ++i) + NX_NONASCII_keymap[i] = SDLK_UNKNOWN; + + NX_NONASCII_keymap[MWKEY_LEFT & 0xFF] = SDLK_LEFT; + NX_NONASCII_keymap[MWKEY_RIGHT & 0xFF] = SDLK_RIGHT; + NX_NONASCII_keymap[MWKEY_UP & 0xFF] = SDLK_UP; + NX_NONASCII_keymap[MWKEY_DOWN & 0xFF] = SDLK_DOWN; + NX_NONASCII_keymap[MWKEY_INSERT & 0xFF] = SDLK_INSERT; + NX_NONASCII_keymap[MWKEY_DELETE & 0xFF] = SDLK_DELETE; + NX_NONASCII_keymap[MWKEY_HOME & 0xFF] = SDLK_HOME; + NX_NONASCII_keymap[MWKEY_END & 0xFF] = SDLK_END; + NX_NONASCII_keymap[MWKEY_PAGEUP & 0xFF] = SDLK_PAGEUP; + NX_NONASCII_keymap[MWKEY_PAGEDOWN & 0xFF] = SDLK_PAGEDOWN; + + NX_NONASCII_keymap[MWKEY_KP0 & 0xFF] = SDLK_KP0; + NX_NONASCII_keymap[MWKEY_KP1 & 0xFF] = SDLK_KP1; + NX_NONASCII_keymap[MWKEY_KP2 & 0xFF] = SDLK_KP2; + NX_NONASCII_keymap[MWKEY_KP3 & 0xFF] = SDLK_KP3; + NX_NONASCII_keymap[MWKEY_KP4 & 0xFF] = SDLK_KP4; + NX_NONASCII_keymap[MWKEY_KP5 & 0xFF] = SDLK_KP5; + NX_NONASCII_keymap[MWKEY_KP6 & 0xFF] = SDLK_KP6; + NX_NONASCII_keymap[MWKEY_KP7 & 0xFF] = SDLK_KP7; + NX_NONASCII_keymap[MWKEY_KP8 & 0xFF] = SDLK_KP8; + NX_NONASCII_keymap[MWKEY_KP9 & 0xFF] = SDLK_KP9; + NX_NONASCII_keymap[MWKEY_KP_PERIOD & 0xFF] = SDLK_KP_PERIOD; + NX_NONASCII_keymap[MWKEY_KP_DIVIDE & 0xFF] = SDLK_KP_DIVIDE; + NX_NONASCII_keymap[MWKEY_KP_MULTIPLY & 0xFF] = SDLK_KP_MULTIPLY; + NX_NONASCII_keymap[MWKEY_KP_MINUS & 0xFF] = SDLK_KP_MINUS; + NX_NONASCII_keymap[MWKEY_KP_PLUS & 0xFF] = SDLK_KP_PLUS; + NX_NONASCII_keymap[MWKEY_KP_ENTER & 0xFF] = SDLK_KP_ENTER; + NX_NONASCII_keymap[MWKEY_KP_EQUALS & 0xFF] = SDLK_KP_EQUALS; + + NX_NONASCII_keymap[MWKEY_F1 & 0xFF] = SDLK_F1; + NX_NONASCII_keymap[MWKEY_F2 & 0xFF] = SDLK_F2; + NX_NONASCII_keymap[MWKEY_F3 & 0xFF] = SDLK_F3; + NX_NONASCII_keymap[MWKEY_F4 & 0xFF] = SDLK_F4; + NX_NONASCII_keymap[MWKEY_F5 & 0xFF] = SDLK_F5; + NX_NONASCII_keymap[MWKEY_F6 & 0xFF] = SDLK_F6; + NX_NONASCII_keymap[MWKEY_F7 & 0xFF] = SDLK_F7; + NX_NONASCII_keymap[MWKEY_F8 & 0xFF] = SDLK_F8; + NX_NONASCII_keymap[MWKEY_F9 & 0xFF] = SDLK_F9; + NX_NONASCII_keymap[MWKEY_F10 & 0xFF] = SDLK_F10; + NX_NONASCII_keymap[MWKEY_F11 & 0xFF] = SDLK_F11; + NX_NONASCII_keymap[MWKEY_F12 & 0xFF] = SDLK_F12; + + NX_NONASCII_keymap[MWKEY_NUMLOCK & 0xFF] = SDLK_NUMLOCK; + NX_NONASCII_keymap[MWKEY_CAPSLOCK & 0xFF] = SDLK_CAPSLOCK; + NX_NONASCII_keymap[MWKEY_SCROLLOCK & 0xFF] = SDLK_SCROLLOCK; + NX_NONASCII_keymap[MWKEY_LSHIFT & 0xFF] = SDLK_LSHIFT; + NX_NONASCII_keymap[MWKEY_RSHIFT & 0xFF] = SDLK_RSHIFT; + NX_NONASCII_keymap[MWKEY_LCTRL & 0xFF] = SDLK_LCTRL; + NX_NONASCII_keymap[MWKEY_RCTRL & 0xFF] = SDLK_RCTRL; + NX_NONASCII_keymap[MWKEY_LALT & 0xFF] = SDLK_LALT; + NX_NONASCII_keymap[MWKEY_RALT & 0xFF] = SDLK_RALT; + NX_NONASCII_keymap[MWKEY_LMETA & 0xFF] = SDLK_LMETA; + NX_NONASCII_keymap[MWKEY_RMETA & 0xFF] = SDLK_RMETA; + NX_NONASCII_keymap[MWKEY_ALTGR & 0xFF] = SDLK_MODE; + + NX_NONASCII_keymap[MWKEY_PRINT & 0xFF] = SDLK_PRINT; + NX_NONASCII_keymap[MWKEY_SYSREQ & 0xFF] = SDLK_SYSREQ; + NX_NONASCII_keymap[MWKEY_PAUSE & 0xFF] = SDLK_PAUSE; + NX_NONASCII_keymap[MWKEY_BREAK & 0xFF] = SDLK_BREAK; + NX_NONASCII_keymap[MWKEY_MENU & 0xFF] = SDLK_MENU; + + Dprintf("leave NX_InitOSKeymap\n"); } -SDL_keysym * NX_TranslateKey (GR_EVENT_KEYSTROKE * keystroke, SDL_keysym * keysym) +SDL_keysym * +NX_TranslateKey(GR_EVENT_KEYSTROKE * keystroke, SDL_keysym * keysym) { - GR_KEY ch = keystroke -> ch ; + GR_KEY ch = keystroke->ch; - Dprintf ("enter NX_TranslateKey\n") ; + Dprintf("enter NX_TranslateKey\n"); - keysym -> scancode = keystroke -> scancode ; - keysym -> sym = SDLK_UNKNOWN ; + keysym->scancode = keystroke->scancode; + keysym->sym = SDLK_UNKNOWN; if (ch & MWKEY_NONASCII_MASK) { - keysym -> sym = NX_NONASCII_keymap [ch & 0xFF] ; + keysym->sym = NX_NONASCII_keymap[ch & 0xFF]; } else { - keysym -> sym = ch & 0x7F ; + keysym->sym = ch & 0x7F; } - keysym -> mod = KMOD_NONE ; - -#if 1 // Retrieve more mode information + keysym->mod = KMOD_NONE; + +#if 1 // Retrieve more mode information { - GR_KEYMOD mod = keystroke -> modifiers ; + GR_KEYMOD mod = keystroke->modifiers; if (mod & MWKMOD_LSHIFT) - keysym -> mod |= KMOD_LSHIFT ; + keysym->mod |= KMOD_LSHIFT; if (mod & MWKMOD_RSHIFT) - keysym -> mod |= KMOD_RSHIFT ; + keysym->mod |= KMOD_RSHIFT; if (mod & MWKMOD_LCTRL) - keysym -> mod |= KMOD_LCTRL ; + keysym->mod |= KMOD_LCTRL; if (mod & MWKMOD_RCTRL) - keysym -> mod |= KMOD_RCTRL ; + keysym->mod |= KMOD_RCTRL; if (mod & MWKMOD_LALT) - keysym -> mod |= KMOD_LALT ; + keysym->mod |= KMOD_LALT; if (mod & MWKMOD_RALT) - keysym -> mod |= KMOD_RALT ; + keysym->mod |= KMOD_RALT; if (mod & MWKMOD_LMETA) - keysym -> mod |= KMOD_LMETA ; + keysym->mod |= KMOD_LMETA; if (mod & MWKMOD_RMETA) - keysym -> mod |= KMOD_RMETA ; + keysym->mod |= KMOD_RMETA; if (mod & MWKMOD_NUM) - keysym -> mod |= KMOD_NUM ; + keysym->mod |= KMOD_NUM; if (mod & MWKMOD_CAPS) - keysym -> mod |= KMOD_CAPS ; + keysym->mod |= KMOD_CAPS; if (mod & MWKMOD_ALTGR) - keysym -> mod |= KMOD_MODE ; + keysym->mod |= KMOD_MODE; } #endif - keysym -> unicode = ch ; + keysym->unicode = ch; - Dprintf ("leave NX_TranslateKey\n") ; - return keysym ; + Dprintf("leave NX_TranslateKey\n"); + return keysym; } -static int check_boundary (_THIS, int x, int y) +static int +check_boundary(_THIS, int x, int y) { - if (x < OffsetX || y < OffsetY || x > OffsetX + this -> screen -> w || - y > OffsetY + this -> screen -> h) - return 0 ; - - return 1 ; + if (x < OffsetX || y < OffsetY || x > OffsetX + this->screen->w || + y > OffsetY + this->screen->h) + return 0; + + return 1; } -void NX_PumpEvents (_THIS) +void +NX_PumpEvents(_THIS) { - GR_EVENT event ; - static GR_BUTTON last_button_down = 0 ; + GR_EVENT event; + static GR_BUTTON last_button_down = 0; - GrCheckNextEvent (& event) ; + GrCheckNextEvent(&event); while (event.type != GR_EVENT_TYPE_NONE) { // dispatch event switch (event.type) { - case GR_EVENT_TYPE_MOUSE_ENTER : + case GR_EVENT_TYPE_MOUSE_ENTER: { - Dprintf ("mouse enter\n") ; - SDL_PrivateAppActive (1, SDL_APPMOUSEFOCUS) ; - break ; + Dprintf("mouse enter\n"); + SDL_PrivateAppActive(1, SDL_APPMOUSEFOCUS); + break; } - case GR_EVENT_TYPE_MOUSE_EXIT : + case GR_EVENT_TYPE_MOUSE_EXIT: { - Dprintf ("mouse exit\n") ; - SDL_PrivateAppActive (0, SDL_APPMOUSEFOCUS) ; - break ; + Dprintf("mouse exit\n"); + SDL_PrivateAppActive(0, SDL_APPMOUSEFOCUS); + break; } - case GR_EVENT_TYPE_FOCUS_IN : + case GR_EVENT_TYPE_FOCUS_IN: { - Dprintf ("focus in\n") ; - SDL_PrivateAppActive (1, SDL_APPINPUTFOCUS) ; - break ; + Dprintf("focus in\n"); + SDL_PrivateAppActive(1, SDL_APPINPUTFOCUS); + break; } - case GR_EVENT_TYPE_FOCUS_OUT : + case GR_EVENT_TYPE_FOCUS_OUT: { - Dprintf ("focus out\n") ; - SDL_PrivateAppActive (0, SDL_APPINPUTFOCUS) ; - break ; + Dprintf("focus out\n"); + SDL_PrivateAppActive(0, SDL_APPINPUTFOCUS); + break; } - case GR_EVENT_TYPE_MOUSE_MOTION : - { - Dprintf ("mouse motion\n") ; + case GR_EVENT_TYPE_MOUSE_MOTION: + { + Dprintf("mouse motion\n"); if (SDL_VideoSurface) { if (currently_fullscreen) { - if (check_boundary (this, event.button.x, event.button.y)) { - SDL_PrivateMouseMotion (0, 0, event.button.x - OffsetX, - event.button.y - OffsetY) ; + if (check_boundary + (this, event.button.x, event.button.y)) { + SDL_PrivateMouseMotion(0, 0, + event.button.x - + OffsetX, + event.button.y - OffsetY); } } else { - SDL_PrivateMouseMotion (0, 0, event.button.x, event.button.y) ; + SDL_PrivateMouseMotion(0, 0, event.button.x, + event.button.y); } } - break ; + break; } - case GR_EVENT_TYPE_BUTTON_DOWN : + case GR_EVENT_TYPE_BUTTON_DOWN: { - int button = event.button.buttons ; - - Dprintf ("button down\n") ; + int button = event.button.buttons; + + Dprintf("button down\n"); switch (button) { - case MWBUTTON_L : - button = 1 ; - break ; - case MWBUTTON_M : - button = 2 ; - break ; - case MWBUTTON_R : - button = 3 ; - break ; - default : - button = 0 ; + case MWBUTTON_L: + button = 1; + break; + case MWBUTTON_M: + button = 2; + break; + case MWBUTTON_R: + button = 3; + break; + default: + button = 0; } - last_button_down = button ; - + last_button_down = button; + if (currently_fullscreen) { - if (check_boundary (this, event.button.x, event.button.y)) { - SDL_PrivateMouseButton (SDL_PRESSED, button, - event.button.x - OffsetX, event.button.y - OffsetY) ; + if (check_boundary(this, event.button.x, event.button.y)) { + SDL_PrivateMouseButton(SDL_PRESSED, button, + event.button.x - + OffsetX, + event.button.y - OffsetY); } } else { - SDL_PrivateMouseButton (SDL_PRESSED, button, - event.button.x, event.button.y) ; + SDL_PrivateMouseButton(SDL_PRESSED, button, + event.button.x, event.button.y); } - break ; + break; } // do not konw which button is released - case GR_EVENT_TYPE_BUTTON_UP : - { - Dprintf ("button up\n") ; + case GR_EVENT_TYPE_BUTTON_UP: + { + Dprintf("button up\n"); if (currently_fullscreen) { - if (check_boundary (this, event.button.x, event.button.y)) { - SDL_PrivateMouseButton (SDL_RELEASED, last_button_down, - event.button.x - OffsetX, event.button.y - OffsetY) ; + if (check_boundary(this, event.button.x, event.button.y)) { + SDL_PrivateMouseButton(SDL_RELEASED, + last_button_down, + event.button.x - + OffsetX, + event.button.y - OffsetY); } } else { - SDL_PrivateMouseButton (SDL_RELEASED, last_button_down, - event.button.x, event.button.y) ; + SDL_PrivateMouseButton(SDL_RELEASED, + last_button_down, + event.button.x, event.button.y); } - last_button_down = 0 ; - break ; + last_button_down = 0; + break; } - case GR_EVENT_TYPE_KEY_DOWN : + case GR_EVENT_TYPE_KEY_DOWN: { - SDL_keysym keysym ; + SDL_keysym keysym; - Dprintf ("key down\n") ; - SDL_PrivateKeyboard (SDL_PRESSED, - NX_TranslateKey (& event.keystroke, & keysym)) ; - break ; + Dprintf("key down\n"); + SDL_PrivateKeyboard(SDL_PRESSED, + NX_TranslateKey(&event.keystroke, + &keysym)); + break; } - case GR_EVENT_TYPE_KEY_UP : + case GR_EVENT_TYPE_KEY_UP: { - SDL_keysym keysym ; + SDL_keysym keysym; - Dprintf ("key up\n") ; - SDL_PrivateKeyboard (SDL_RELEASED, - NX_TranslateKey (& event.keystroke, & keysym)) ; - break ; + Dprintf("key up\n"); + SDL_PrivateKeyboard(SDL_RELEASED, + NX_TranslateKey(&event.keystroke, + &keysym)); + break; } - case GR_EVENT_TYPE_CLOSE_REQ : + case GR_EVENT_TYPE_CLOSE_REQ: { - Dprintf ("close require\n") ; - SDL_PrivateQuit () ; - break ; + Dprintf("close require\n"); + SDL_PrivateQuit(); + break; } - case GR_EVENT_TYPE_EXPOSURE : + case GR_EVENT_TYPE_EXPOSURE: { - Dprintf ("event_type_exposure\n") ; + Dprintf("event_type_exposure\n"); if (SDL_VideoSurface) { - NX_RefreshDisplay (this) ;//, & event.exposure) ; + NX_RefreshDisplay(this); //, & event.exposure) ; } - break ; + break; } - case GR_EVENT_TYPE_UPDATE : + case GR_EVENT_TYPE_UPDATE: { switch (event.update.utype) { - case GR_UPDATE_MAP : + case GR_UPDATE_MAP: { - Dprintf ("GR_UPDATE_MAP\n") ; + Dprintf("GR_UPDATE_MAP\n"); // If we're not active, make ourselves active - if (!(SDL_GetAppState () & SDL_APPACTIVE)) { + if (!(SDL_GetAppState() & SDL_APPACTIVE)) { // Send an internal activate event - SDL_PrivateAppActive (1, SDL_APPACTIVE) ; + SDL_PrivateAppActive(1, SDL_APPACTIVE); } if (SDL_VideoSurface) { - NX_RefreshDisplay (this) ; + NX_RefreshDisplay(this); } - break ; + break; } - - case GR_UPDATE_UNMAP : - case GR_UPDATE_UNMAPTEMP : + + case GR_UPDATE_UNMAP: + case GR_UPDATE_UNMAPTEMP: { - Dprintf ("GR_UPDATE_UNMAP or GR_UPDATE_UNMAPTEMP\n") ; + Dprintf("GR_UPDATE_UNMAP or GR_UPDATE_UNMAPTEMP\n"); // If we're active, make ourselves inactive - if (SDL_GetAppState () & SDL_APPACTIVE) { + if (SDL_GetAppState() & SDL_APPACTIVE) { // Send an internal deactivate event - SDL_PrivateAppActive (0, SDL_APPACTIVE | SDL_APPINPUTFOCUS) ; + SDL_PrivateAppActive(0, + SDL_APPACTIVE | + SDL_APPINPUTFOCUS); } - break ; + break; } - - case GR_UPDATE_SIZE : + + case GR_UPDATE_SIZE: { - Dprintf ("GR_UPDATE_SIZE\n") ; - SDL_PrivateResize (event.update.width, event.update.height) ; - break ; + Dprintf("GR_UPDATE_SIZE\n"); + SDL_PrivateResize(event.update.width, + event.update.height); + break; } - case GR_UPDATE_MOVE : - case GR_UPDATE_REPARENT : + case GR_UPDATE_MOVE: + case GR_UPDATE_REPARENT: { - Dprintf ("GR_UPDATE_MOVE or GR_UPDATE_REPARENT\n") ; + Dprintf("GR_UPDATE_MOVE or GR_UPDATE_REPARENT\n"); #ifdef ENABLE_NANOX_DIRECT_FB - if (Clientfb) { - /* Get current window position and fb pointer*/ - if (currently_fullscreen) - GrGetWindowFBInfo(FSwindow, &fbinfo); - else - GrGetWindowFBInfo(SDL_Window, &fbinfo); - } + if (Clientfb) { + /* Get current window position and fb pointer */ + if (currently_fullscreen) + GrGetWindowFBInfo(FSwindow, &fbinfo); + else + GrGetWindowFBInfo(SDL_Window, &fbinfo); + } #endif - break ; + break; } - - default : - Dprintf ("unknown GR_EVENT_TYPE_UPDATE\n") ; - break ; + + default: + Dprintf("unknown GR_EVENT_TYPE_UPDATE\n"); + break; } - break ; + break; } - - default : + + default: { - Dprintf ("pump event default\n") ; + Dprintf("pump event default\n"); } } - GrCheckNextEvent (& event) ; + GrCheckNextEvent(&event); } } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/nanox/SDL_nxevents_c.h b/src/video/nanox/SDL_nxevents_c.h index ba12c21c5..ccc23febd 100644 --- a/src/video/nanox/SDL_nxevents_c.h +++ b/src/video/nanox/SDL_nxevents_c.h @@ -28,5 +28,6 @@ #include "SDL_nxvideo.h" // Functions to be exported -extern void NX_InitOSKeymap (_THIS) ; -extern void NX_PumpEvents (_THIS) ; +extern void NX_InitOSKeymap(_THIS); +extern void NX_PumpEvents(_THIS); +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/nanox/SDL_nximage.c b/src/video/nanox/SDL_nximage.c index 6afe3b957..41b9d1c93 100644 --- a/src/video/nanox/SDL_nximage.c +++ b/src/video/nanox/SDL_nximage.c @@ -28,68 +28,73 @@ #include "SDL_nximage_c.h" -void NX_NormalUpdate (_THIS, int numrects, SDL_Rect * rects) +void +NX_NormalUpdate(_THIS, int numrects, SDL_Rect * rects) { - int i, j, xinc, yinc, destinc, rowinc ; - int x, y, w, h ; - unsigned char * src = NULL, * dest = NULL ; + int i, j, xinc, yinc, destinc, rowinc; + int x, y, w, h; + unsigned char *src = NULL, *dest = NULL; + + Dprintf("enter NX_NormalUpdate\n"); - Dprintf ("enter NX_NormalUpdate\n") ; - /* These are the values for the incoming image */ - xinc = this -> screen -> format -> BytesPerPixel ; - yinc = this -> screen -> pitch ; - - for (i = 0; i < numrects; ++ i) { - x = rects [i].x, y = rects [i].y ; - w = rects [i].w, h = rects [i].h ; - src = SDL_Image + y * yinc + x * xinc ; + xinc = this->screen->format->BytesPerPixel; + yinc = this->screen->pitch; + + for (i = 0; i < numrects; ++i) { + x = rects[i].x, y = rects[i].y; + w = rects[i].w, h = rects[i].h; + src = SDL_Image + y * yinc + x * xinc; #ifdef ENABLE_NANOX_DIRECT_FB if (Clientfb) { if (currently_fullscreen) - dest = fbinfo.winpixels + (((y+OffsetY) * fbinfo.pitch) + - ((x+OffsetX) * fbinfo.bytespp)); + dest = + fbinfo.winpixels + (((y + OffsetY) * fbinfo.pitch) + + ((x + OffsetX) * fbinfo.bytespp)); else - dest = fbinfo.winpixels + ((y * fbinfo.pitch) + (x * fbinfo.bytespp)); + dest = + fbinfo.winpixels + ((y * fbinfo.pitch) + + (x * fbinfo.bytespp)); destinc = fbinfo.pitch; - } - else + } else #endif { - dest = Image_buff ; - destinc = w * xinc ; + dest = Image_buff; + destinc = w * xinc; } rowinc = w * xinc; // apply GammaRamp table - if ((pixel_type == MWPF_TRUECOLOR0888 || pixel_type == MWPF_TRUECOLOR888) - && GammaRamp_R && GammaRamp_G && GammaRamp_B) { - Uint8 * ptrsrc ; - Uint8 * ptrdst ; - int k ; - - for (j = h; j > 0; -- j, src += yinc, dest += destinc) { - ptrsrc = src ; - ptrdst = dest ; - for (k = w; k > 0; -- k) { - *ptrdst++ = GammaRamp_B [*ptrsrc++] >> 8; - *ptrdst++ = GammaRamp_G [*ptrsrc++] >> 8; - *ptrdst++ = GammaRamp_R [*ptrsrc++] >> 8; + if ((pixel_type == MWPF_TRUECOLOR0888 + || pixel_type == MWPF_TRUECOLOR888) && GammaRamp_R + && GammaRamp_G && GammaRamp_B) { + Uint8 *ptrsrc; + Uint8 *ptrdst; + int k; + + for (j = h; j > 0; --j, src += yinc, dest += destinc) { + ptrsrc = src; + ptrdst = dest; + for (k = w; k > 0; --k) { + *ptrdst++ = GammaRamp_B[*ptrsrc++] >> 8; + *ptrdst++ = GammaRamp_G[*ptrsrc++] >> 8; + *ptrdst++ = GammaRamp_R[*ptrsrc++] >> 8; *ptrdst++ = 0; ++ptrsrc; } } } -#if 1 /* This is needed for microwindows 0.90 or older */ - else if (pixel_type == MWPF_TRUECOLOR0888 || pixel_type == MWPF_TRUECOLOR888) { - Uint8 * ptrsrc ; - Uint8 * ptrdst ; - int k ; - - for (j = h; j > 0; -- j, src += yinc, dest += destinc) { - ptrsrc = src ; - ptrdst = dest ; - for (k = w; k > 0; -- k) { +#if 1 /* This is needed for microwindows 0.90 or older */ + else if (pixel_type == MWPF_TRUECOLOR0888 + || pixel_type == MWPF_TRUECOLOR888) { + Uint8 *ptrsrc; + Uint8 *ptrdst; + int k; + + for (j = h; j > 0; --j, src += yinc, dest += destinc) { + ptrsrc = src; + ptrdst = dest; + for (k = w; k > 0; --k) { *ptrdst++ = *ptrsrc++; *ptrdst++ = *ptrsrc++; *ptrdst++ = *ptrsrc++; @@ -99,98 +104,104 @@ void NX_NormalUpdate (_THIS, int numrects, SDL_Rect * rects) } } #endif - else - { - for (j = h; j > 0; -- j, src += yinc, dest += destinc) - SDL_memcpy (dest, src, rowinc) ; + else { + for (j = h; j > 0; --j, src += yinc, dest += destinc) + SDL_memcpy(dest, src, rowinc); } if (!Clientfb) { if (currently_fullscreen) { - GrArea (FSwindow, SDL_GC, x + OffsetX, y + OffsetY, w, h, Image_buff, - pixel_type) ; + GrArea(FSwindow, SDL_GC, x + OffsetX, y + OffsetY, w, + h, Image_buff, pixel_type); } else { - GrArea (SDL_Window, SDL_GC, x, y, w, h, Image_buff, pixel_type) ; + GrArea(SDL_Window, SDL_GC, x, y, w, h, Image_buff, + pixel_type); } } } GrFlush(); - Dprintf ("leave NX_NormalUpdate\n") ; + Dprintf("leave NX_NormalUpdate\n"); } -int NX_SetupImage (_THIS, SDL_Surface * screen) +int +NX_SetupImage(_THIS, SDL_Surface * screen) { - int size = screen -> h * screen -> pitch ; - - Dprintf ("enter NX_SetupImage\n") ; + int size = screen->h * screen->pitch; + + Dprintf("enter NX_SetupImage\n"); - screen -> pixels = (void *) SDL_malloc (size) ; + screen->pixels = (void *) SDL_malloc(size); if (!Clientfb) { - Image_buff = (unsigned char *) SDL_malloc (size) ; - if (screen -> pixels == NULL || Image_buff == NULL) { - SDL_free (screen -> pixels) ; - SDL_free (Image_buff) ; - SDL_OutOfMemory () ; - return -1 ; + Image_buff = (unsigned char *) SDL_malloc(size); + if (screen->pixels == NULL || Image_buff == NULL) { + SDL_free(screen->pixels); + SDL_free(Image_buff); + SDL_OutOfMemory(); + return -1; } } - SDL_Image = (unsigned char *) screen -> pixels ; + SDL_Image = (unsigned char *) screen->pixels; - this -> UpdateRects = NX_NormalUpdate ; + this->UpdateRects = NX_NormalUpdate; - Dprintf ("leave NX_SetupImage\n") ; - return 0 ; + Dprintf("leave NX_SetupImage\n"); + return 0; } -void NX_DestroyImage (_THIS, SDL_Surface * screen) +void +NX_DestroyImage(_THIS, SDL_Surface * screen) { - Dprintf ("enter NX_DestroyImage\n") ; - - if (SDL_Image) SDL_free (SDL_Image) ; - if (Image_buff) SDL_free (Image_buff) ; - if (screen) screen -> pixels = NULL ; - - Dprintf ("leave NX_DestroyImage\n") ; + Dprintf("enter NX_DestroyImage\n"); + + if (SDL_Image) + SDL_free(SDL_Image); + if (Image_buff) + SDL_free(Image_buff); + if (screen) + screen->pixels = NULL; + + Dprintf("leave NX_DestroyImage\n"); } -int NX_ResizeImage (_THIS, SDL_Surface * screen, Uint32 flags) +int +NX_ResizeImage(_THIS, SDL_Surface * screen, Uint32 flags) { - int retval ; - GR_SCREEN_INFO si ; + int retval; + GR_SCREEN_INFO si; - Dprintf ("enter NX_ResizeImage\n") ; + Dprintf("enter NX_ResizeImage\n"); - NX_DestroyImage (this, screen) ; - retval = NX_SetupImage (this, screen) ; + NX_DestroyImage(this, screen); + retval = NX_SetupImage(this, screen); - GrGetScreenInfo (& si) ; - OffsetX = (si.cols - screen -> w) / 2 ; - OffsetY = (si.rows - screen -> h) / 2 ; + GrGetScreenInfo(&si); + OffsetX = (si.cols - screen->w) / 2; + OffsetY = (si.rows - screen->h) / 2; #ifdef ENABLE_NANOX_DIRECT_FB if (Clientfb) { - /* Get current window position and fb pointer*/ - if (currently_fullscreen) + /* Get current window position and fb pointer */ + if (currently_fullscreen) GrGetWindowFBInfo(FSwindow, &fbinfo); else GrGetWindowFBInfo(SDL_Window, &fbinfo); } #endif - Dprintf ("leave NX_ResizeImage\n") ; - return retval ; + Dprintf("leave NX_ResizeImage\n"); + return retval; } -void NX_RefreshDisplay (_THIS) +void +NX_RefreshDisplay(_THIS) { - Dprintf ("enter NX_RefreshDisplay\n") ; + Dprintf("enter NX_RefreshDisplay\n"); // Don't refresh a display that doesn't have an image (like GL) - if (! SDL_Image) { + if (!SDL_Image) { return; } - #ifdef ENABLE_NANOX_DIRECT_FB if (Clientfb) { int j; @@ -199,32 +210,34 @@ void NX_RefreshDisplay (_THIS) GrGetWindowFBInfo(SDL_Window, &fbinfo); - xinc = this -> screen -> format -> BytesPerPixel ; - yinc = this -> screen -> pitch ; + xinc = this->screen->format->BytesPerPixel; + yinc = this->screen->pitch; src = SDL_Image; if (currently_fullscreen) dest = fbinfo.winpixels + ((OffsetY * fbinfo.pitch) + - (OffsetX * fbinfo.bytespp)); + (OffsetX * fbinfo.bytespp)); else dest = fbinfo.winpixels; - rowinc = xinc * this -> screen -> w; + rowinc = xinc * this->screen->w; - for (j = this -> screen -> h; j > 0; -- j, src += yinc, dest += fbinfo.pitch) - SDL_memcpy (dest, src, rowinc) ; - } - else + for (j = this->screen->h; j > 0; + --j, src += yinc, dest += fbinfo.pitch) + SDL_memcpy(dest, src, rowinc); + } else #endif { if (currently_fullscreen) { - GrArea (FSwindow, SDL_GC, OffsetX, OffsetY, this -> screen -> w, - this -> screen -> h, SDL_Image, pixel_type) ; + GrArea(FSwindow, SDL_GC, OffsetX, OffsetY, this->screen->w, + this->screen->h, SDL_Image, pixel_type); } else { - GrArea (SDL_Window, SDL_GC, 0, 0, this -> screen -> w, - this -> screen -> h, SDL_Image, pixel_type) ; + GrArea(SDL_Window, SDL_GC, 0, 0, this->screen->w, + this->screen->h, SDL_Image, pixel_type); } } GrFlush(); - Dprintf ("leave NX_RefreshDisplay\n") ; + Dprintf("leave NX_RefreshDisplay\n"); } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/nanox/SDL_nximage_c.h b/src/video/nanox/SDL_nximage_c.h index 2cdc01fac..a454ce700 100644 --- a/src/video/nanox/SDL_nximage_c.h +++ b/src/video/nanox/SDL_nximage_c.h @@ -27,9 +27,10 @@ #include "SDL_nxvideo.h" -extern int NX_SetupImage (_THIS, SDL_Surface * screen) ; -extern void NX_DestroyImage (_THIS, SDL_Surface * screen) ; -extern int NX_ResizeImage (_THIS, SDL_Surface * screen, Uint32 flags) ; +extern int NX_SetupImage(_THIS, SDL_Surface * screen); +extern void NX_DestroyImage(_THIS, SDL_Surface * screen); +extern int NX_ResizeImage(_THIS, SDL_Surface * screen, Uint32 flags); -extern void NX_NormalUpdate (_THIS, int numrects, SDL_Rect * rects) ; -extern void NX_RefreshDisplay (_THIS) ; +extern void NX_NormalUpdate(_THIS, int numrects, SDL_Rect * rects); +extern void NX_RefreshDisplay(_THIS); +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/nanox/SDL_nxmodes.c b/src/video/nanox/SDL_nxmodes.c index bc597e29a..6c8087434 100644 --- a/src/video/nanox/SDL_nxmodes.c +++ b/src/video/nanox/SDL_nxmodes.c @@ -28,57 +28,63 @@ #include "SDL_stdinc.h" #include "SDL_nxmodes_c.h" -SDL_Rect ** NX_ListModes (_THIS, SDL_PixelFormat * format, Uint32 flags) +SDL_Rect ** +NX_ListModes(_THIS, SDL_PixelFormat * format, Uint32 flags) { if (flags & SDL_FULLSCREEN) - return SDL_modelist ; + return SDL_modelist; - if (SDL_Visual.bpp == format -> BitsPerPixel) { - return ((SDL_Rect **) -1) ; + if (SDL_Visual.bpp == format->BitsPerPixel) { + return ((SDL_Rect **) - 1); } else { - return ((SDL_Rect **) 0) ; + return ((SDL_Rect **) 0); } } -void NX_FreeVideoModes (_THIS) +void +NX_FreeVideoModes(_THIS) { - int i ; + int i; if (SDL_modelist) { - for (i = 0; SDL_modelist [i]; ++ i) { - SDL_free (SDL_modelist [i]) ; + for (i = 0; SDL_modelist[i]; ++i) { + SDL_free(SDL_modelist[i]); } - SDL_free (SDL_modelist) ; + SDL_free(SDL_modelist); SDL_modelist = NULL; } } -int NX_EnterFullScreen (_THIS) +int +NX_EnterFullScreen(_THIS) { - if (! currently_fullscreen) { - GR_SCREEN_INFO si ; + if (!currently_fullscreen) { + GR_SCREEN_INFO si; - GrGetScreenInfo (& si) ; - GrResizeWindow (FSwindow, si.cols, si.rows) ; - GrUnmapWindow (SDL_Window) ; - GrMapWindow (FSwindow) ; - GrRaiseWindow (FSwindow) ; - GrSetFocus (FSwindow) ; - currently_fullscreen = 1 ; + GrGetScreenInfo(&si); + GrResizeWindow(FSwindow, si.cols, si.rows); + GrUnmapWindow(SDL_Window); + GrMapWindow(FSwindow); + GrRaiseWindow(FSwindow); + GrSetFocus(FSwindow); + currently_fullscreen = 1; } - return 1 ; + return 1; } -int NX_LeaveFullScreen (_THIS) +int +NX_LeaveFullScreen(_THIS) { if (currently_fullscreen) { - GrUnmapWindow (FSwindow) ; - GrMapWindow (SDL_Window) ; - GrRaiseWindow (SDL_Window) ; - GrSetFocus (SDL_Window) ; - currently_fullscreen = 0 ; + GrUnmapWindow(FSwindow); + GrMapWindow(SDL_Window); + GrRaiseWindow(SDL_Window); + GrSetFocus(SDL_Window); + currently_fullscreen = 0; } - return 0 ; + return 0; } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/nanox/SDL_nxmodes_c.h b/src/video/nanox/SDL_nxmodes_c.h index d643ad701..ae5f5f7e3 100644 --- a/src/video/nanox/SDL_nxmodes_c.h +++ b/src/video/nanox/SDL_nxmodes_c.h @@ -28,7 +28,8 @@ #include "SDL_nxvideo.h" #include -extern SDL_Rect ** NX_ListModes (_THIS, SDL_PixelFormat * format, Uint32 flags) ; -extern void NX_FreeVideoModes (_THIS) ; -extern int NX_EnterFullScreen (_THIS) ; -extern int NX_LeaveFullScreen (_THIS) ; +extern SDL_Rect **NX_ListModes(_THIS, SDL_PixelFormat * format, Uint32 flags); +extern void NX_FreeVideoModes(_THIS); +extern int NX_EnterFullScreen(_THIS); +extern int NX_LeaveFullScreen(_THIS); +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/nanox/SDL_nxmouse.c b/src/video/nanox/SDL_nxmouse.c index 54017b192..fbd0f18ea 100644 --- a/src/video/nanox/SDL_nxmouse.c +++ b/src/video/nanox/SDL_nxmouse.c @@ -30,50 +30,58 @@ #include "SDL_nxmouse_c.h" // The implementation dependent data for the window manager cursor -struct WMcursor { - int unused ; -} ; +struct WMcursor +{ + int unused; +}; -WMcursor * NX_CreateWMCursor (_THIS, - Uint8 * data, Uint8 * mask, int w, int h, int hot_x, int hot_y) +WMcursor * +NX_CreateWMCursor(_THIS, + Uint8 * data, Uint8 * mask, int w, int h, int hot_x, + int hot_y) { - WMcursor * cursor ; + WMcursor *cursor; - Dprintf ("enter NX_CreateWMCursor\n") ; + Dprintf("enter NX_CreateWMCursor\n"); - cursor = (WMcursor *) SDL_malloc (sizeof (WMcursor)) ; + cursor = (WMcursor *) SDL_malloc(sizeof(WMcursor)); if (cursor == NULL) { - SDL_OutOfMemory () ; - return NULL ; + SDL_OutOfMemory(); + return NULL; } - Dprintf ("leave NX_CreateWMCursor\n") ; - return cursor ; + Dprintf("leave NX_CreateWMCursor\n"); + return cursor; } -void NX_FreeWMCursor (_THIS, WMcursor * cursor) +void +NX_FreeWMCursor(_THIS, WMcursor * cursor) { - Dprintf ("NX_FreeWMCursor\n") ; - SDL_free (cursor) ; - return ; + Dprintf("NX_FreeWMCursor\n"); + SDL_free(cursor); + return; } -void NX_WarpWMCursor(_THIS, Uint16 x, Uint16 y) +void +NX_WarpWMCursor(_THIS, Uint16 x, Uint16 y) { - GR_WINDOW_INFO info ; + GR_WINDOW_INFO info; - Dprintf ("enter NX_WarpWMCursor\n") ; - SDL_Lock_EventThread () ; - - GrGetWindowInfo (SDL_Window, & info) ; - GrMoveCursor (info.x + x, info.y + y) ; + Dprintf("enter NX_WarpWMCursor\n"); + SDL_Lock_EventThread(); - SDL_Unlock_EventThread () ; - Dprintf ("leave NX_WarpWMCursor\n") ; + GrGetWindowInfo(SDL_Window, &info); + GrMoveCursor(info.x + x, info.y + y); + + SDL_Unlock_EventThread(); + Dprintf("leave NX_WarpWMCursor\n"); } -int NX_ShowWMCursor (_THIS, WMcursor * cursor) +int +NX_ShowWMCursor(_THIS, WMcursor * cursor) { - Dprintf ("NX_ShowWMCursor\n") ; - return 1 ; + Dprintf("NX_ShowWMCursor\n"); + return 1; } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/nanox/SDL_nxmouse_c.h b/src/video/nanox/SDL_nxmouse_c.h index 819eedbae..2349a5072 100644 --- a/src/video/nanox/SDL_nxmouse_c.h +++ b/src/video/nanox/SDL_nxmouse_c.h @@ -23,7 +23,9 @@ #include "SDL_nxvideo.h" -extern WMcursor * NX_CreateWMCursor (_THIS, Uint8 * data, Uint8 * mask, int w, int h, int hot_x, int hot_y) ; -void NX_FreeWMCursor (_THIS, WMcursor * cursor) ; -extern void NX_WarpWMCursor (_THIS, Uint16 x, Uint16 y) ; -extern int NX_ShowWMCursor (_THIS, WMcursor * cursor) ; +extern WMcursor *NX_CreateWMCursor(_THIS, Uint8 * data, Uint8 * mask, int w, + int h, int hot_x, int hot_y); +void NX_FreeWMCursor(_THIS, WMcursor * cursor); +extern void NX_WarpWMCursor(_THIS, Uint16 x, Uint16 y); +extern int NX_ShowWMCursor(_THIS, WMcursor * cursor); +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/nanox/SDL_nxvideo.c b/src/video/nanox/SDL_nxvideo.c index 12df7e2b6..9580b7693 100644 --- a/src/video/nanox/SDL_nxvideo.c +++ b/src/video/nanox/SDL_nxvideo.c @@ -40,190 +40,203 @@ #include "SDL_nxevents_c.h" // Initialization/Query functions -static int NX_VideoInit (_THIS, SDL_PixelFormat * vformat) ; -static SDL_Surface * NX_SetVideoMode (_THIS, SDL_Surface * current, int width, int height, int bpp, Uint32 flags) ; -static int NX_SetColors (_THIS, int firstcolor, int ncolors, SDL_Color * colors) ; -static void NX_VideoQuit (_THIS) ; -static void NX_DestroyWindow (_THIS, SDL_Surface * screen) ; -static int NX_ToggleFullScreen (_THIS, int on) ; -static void NX_UpdateMouse (_THIS) ; -static int NX_SetGammaRamp (_THIS, Uint16 * ramp) ; -static int NX_GetGammaRamp (_THIS, Uint16 * ramp) ; +static int NX_VideoInit(_THIS, SDL_PixelFormat * vformat); +static SDL_Surface *NX_SetVideoMode(_THIS, SDL_Surface * current, int width, + int height, int bpp, Uint32 flags); +static int NX_SetColors(_THIS, int firstcolor, int ncolors, + SDL_Color * colors); +static void NX_VideoQuit(_THIS); +static void NX_DestroyWindow(_THIS, SDL_Surface * screen); +static int NX_ToggleFullScreen(_THIS, int on); +static void NX_UpdateMouse(_THIS); +static int NX_SetGammaRamp(_THIS, Uint16 * ramp); +static int NX_GetGammaRamp(_THIS, Uint16 * ramp); // Microwin driver bootstrap functions -static int NX_Available () +static int +NX_Available() { - Dprintf ("enter NX_Available\n") ; + Dprintf("enter NX_Available\n"); - if (GrOpen () < 0) return 0 ; - GrClose () ; - - Dprintf ("leave NX_Available\n") ; - return 1 ; + if (GrOpen() < 0) + return 0; + GrClose(); + + Dprintf("leave NX_Available\n"); + return 1; } -static void NX_DeleteDevice (SDL_VideoDevice * device) +static void +NX_DeleteDevice(SDL_VideoDevice * device) { - Dprintf ("enter NX_DeleteDevice\n") ; + Dprintf("enter NX_DeleteDevice\n"); if (device) { - if (device -> hidden) SDL_free (device -> hidden) ; - if (device -> gl_data) SDL_free (device -> gl_data) ; - SDL_free (device) ; + if (device->hidden) + SDL_free(device->hidden); + if (device->gl_data) + SDL_free(device->gl_data); + SDL_free(device); } - Dprintf ("leave NX_DeleteDevice\n") ; + Dprintf("leave NX_DeleteDevice\n"); } - -static SDL_VideoDevice * NX_CreateDevice (int devindex) + +static SDL_VideoDevice * +NX_CreateDevice(int devindex) { - SDL_VideoDevice * device ; + SDL_VideoDevice *device; - Dprintf ("enter NX_CreateDevice\n") ; + Dprintf("enter NX_CreateDevice\n"); // Initialize all variables that we clean on shutdown - device = (SDL_VideoDevice *) SDL_malloc (sizeof (SDL_VideoDevice)) ; + device = (SDL_VideoDevice *) SDL_malloc(sizeof(SDL_VideoDevice)); if (device) { - SDL_memset (device, 0, (sizeof * device)) ; - device -> hidden = (struct SDL_PrivateVideoData *) - SDL_malloc ((sizeof * device -> hidden)) ; - device -> gl_data = NULL ; + SDL_memset(device, 0, (sizeof *device)); + device->hidden = (struct SDL_PrivateVideoData *) + SDL_malloc((sizeof *device->hidden)); + device->gl_data = NULL; } - if ((device == NULL) || (device -> hidden == NULL)) { - SDL_OutOfMemory () ; - NX_DeleteDevice (device) ; - return 0 ; + if ((device == NULL) || (device->hidden == NULL)) { + SDL_OutOfMemory(); + NX_DeleteDevice(device); + return 0; } - SDL_memset (device -> hidden, 0, (sizeof * device -> hidden)) ; + SDL_memset(device->hidden, 0, (sizeof *device->hidden)); // Set the function pointers - device -> VideoInit = NX_VideoInit ; - device -> ListModes = NX_ListModes ; - device -> SetVideoMode = NX_SetVideoMode ; - device -> ToggleFullScreen = NX_ToggleFullScreen ; - device -> UpdateMouse = NX_UpdateMouse ; - device -> CreateYUVOverlay = NULL ; - device -> SetColors = NX_SetColors ; - device -> UpdateRects = NULL ; - device -> VideoQuit = NX_VideoQuit; - device -> AllocHWSurface = NULL ; - device -> CheckHWBlit = NULL ; - device -> FillHWRect = NULL ; - device -> SetHWColorKey = NULL ; - device -> SetHWAlpha = NULL ; - device -> LockHWSurface = NULL ; - device -> UnlockHWSurface = NULL ; - device -> FlipHWSurface = NULL ; - device -> FreeHWSurface = NULL ; - device -> SetGamma = NULL ; - device -> GetGamma = NULL ; - device -> SetGammaRamp = NX_SetGammaRamp ; - device -> GetGammaRamp = NX_GetGammaRamp ; + device->VideoInit = NX_VideoInit; + device->ListModes = NX_ListModes; + device->SetVideoMode = NX_SetVideoMode; + device->ToggleFullScreen = NX_ToggleFullScreen; + device->UpdateMouse = NX_UpdateMouse; + device->CreateYUVOverlay = NULL; + device->SetColors = NX_SetColors; + device->UpdateRects = NULL; + device->VideoQuit = NX_VideoQuit; + device->AllocHWSurface = NULL; + device->CheckHWBlit = NULL; + device->FillHWRect = NULL; + device->SetHWColorKey = NULL; + device->SetHWAlpha = NULL; + device->LockHWSurface = NULL; + device->UnlockHWSurface = NULL; + device->FlipHWSurface = NULL; + device->FreeHWSurface = NULL; + device->SetGamma = NULL; + device->GetGamma = NULL; + device->SetGammaRamp = NX_SetGammaRamp; + device->GetGammaRamp = NX_GetGammaRamp; #if SDL_VIDEO_OPENGL - device -> GL_LoadLibrary = NULL ; - device -> GL_GetProcAddress = NULL ; - device -> GL_GetAttribute = NULL ; - device -> GL_MakeCurrent = NULL ; - device -> GL_SwapBuffers = NULL ; + device->GL_LoadLibrary = NULL; + device->GL_GetProcAddress = NULL; + device->GL_GetAttribute = NULL; + device->GL_MakeCurrent = NULL; + device->GL_SwapBuffers = NULL; #endif - device -> SetIcon = NULL ; - device -> SetCaption = NX_SetCaption; - device -> IconifyWindow = NULL ; - device -> GrabInput = NULL ; - device -> GetWMInfo = NX_GetWMInfo ; - device -> FreeWMCursor = NX_FreeWMCursor ; - device -> CreateWMCursor = NX_CreateWMCursor ; - device -> ShowWMCursor = NX_ShowWMCursor ; - device -> WarpWMCursor = NX_WarpWMCursor ; - device -> CheckMouseMode = NULL ; - device -> InitOSKeymap = NX_InitOSKeymap ; - device -> PumpEvents = NX_PumpEvents ; - - device -> free = NX_DeleteDevice ; - - Dprintf ("leave NX_CreateDevice\n") ; - return device ; + device->SetIcon = NULL; + device->SetCaption = NX_SetCaption; + device->IconifyWindow = NULL; + device->GrabInput = NULL; + device->GetWMInfo = NX_GetWMInfo; + device->FreeWMCursor = NX_FreeWMCursor; + device->CreateWMCursor = NX_CreateWMCursor; + device->ShowWMCursor = NX_ShowWMCursor; + device->WarpWMCursor = NX_WarpWMCursor; + device->CheckMouseMode = NULL; + device->InitOSKeymap = NX_InitOSKeymap; + device->PumpEvents = NX_PumpEvents; + + device->free = NX_DeleteDevice; + + Dprintf("leave NX_CreateDevice\n"); + return device; } VideoBootStrap NX_bootstrap = { "nanox", "nanox", NX_Available, NX_CreateDevice -} ; +}; -static void create_aux_windows (_THIS) +static void +create_aux_windows(_THIS) { - GR_WM_PROPERTIES props ; + GR_WM_PROPERTIES props; - Dprintf ("enter create_aux_windows\n") ; + Dprintf("enter create_aux_windows\n"); // Don't create any extra windows if we are being managed if (SDL_windowid) { - FSwindow = 0 ; - return ; + FSwindow = 0; + return; } - + if (FSwindow && FSwindow != GR_ROOT_WINDOW_ID) { - GrDestroyWindow (FSwindow) ; + GrDestroyWindow(FSwindow); } - - FSwindow = GrNewWindow (GR_ROOT_WINDOW_ID, 0, 0, 1, 1, 0, BLACK, BLACK) ; - props.flags = GR_WM_FLAGS_PROPS ; - props.props = GR_WM_PROPS_NODECORATE ; - GrSetWMProperties (FSwindow, & props) ; - - GrSelectEvents (FSwindow, (GR_EVENT_MASK_EXPOSURE | - GR_EVENT_MASK_BUTTON_DOWN | GR_EVENT_MASK_BUTTON_UP | - GR_EVENT_MASK_FOCUS_IN | GR_EVENT_MASK_FOCUS_OUT | - GR_EVENT_MASK_KEY_DOWN | GR_EVENT_MASK_KEY_UP | - GR_EVENT_MASK_MOUSE_ENTER | GR_EVENT_MASK_MOUSE_EXIT | - GR_EVENT_MASK_MOUSE_MOTION | GR_EVENT_MASK_UPDATE | - GR_EVENT_MASK_CLOSE_REQ)) ; - - Dprintf ("leave create_aux_windows\n") ; + + FSwindow = GrNewWindow(GR_ROOT_WINDOW_ID, 0, 0, 1, 1, 0, BLACK, BLACK); + props.flags = GR_WM_FLAGS_PROPS; + props.props = GR_WM_PROPS_NODECORATE; + GrSetWMProperties(FSwindow, &props); + + GrSelectEvents(FSwindow, (GR_EVENT_MASK_EXPOSURE | + GR_EVENT_MASK_BUTTON_DOWN | + GR_EVENT_MASK_BUTTON_UP | + GR_EVENT_MASK_FOCUS_IN | + GR_EVENT_MASK_FOCUS_OUT | + GR_EVENT_MASK_KEY_DOWN | GR_EVENT_MASK_KEY_UP | + GR_EVENT_MASK_MOUSE_ENTER | + GR_EVENT_MASK_MOUSE_EXIT | + GR_EVENT_MASK_MOUSE_MOTION | + GR_EVENT_MASK_UPDATE | + GR_EVENT_MASK_CLOSE_REQ)); + + Dprintf("leave create_aux_windows\n"); } -int NX_VideoInit (_THIS, SDL_PixelFormat * vformat) +int +NX_VideoInit(_THIS, SDL_PixelFormat * vformat) { - GR_SCREEN_INFO si ; + GR_SCREEN_INFO si; - Dprintf ("enter NX_VideoInit\n") ; - - if (GrOpen () < 0) { - SDL_SetError ("GrOpen() fail") ; - return -1 ; - } + Dprintf("enter NX_VideoInit\n"); + if (GrOpen() < 0) { + SDL_SetError("GrOpen() fail"); + return -1; + } // use share memory to speed up #ifdef NANOX_SHARE_MEMORY - GrReqShmCmds (0xFFFF); + GrReqShmCmds(0xFFFF); #endif - SDL_Window = 0 ; - FSwindow = 0 ; + SDL_Window = 0; + FSwindow = 0; - GammaRamp_R = NULL ; - GammaRamp_G = NULL ; - GammaRamp_B = NULL ; + GammaRamp_R = NULL; + GammaRamp_G = NULL; + GammaRamp_B = NULL; - GrGetScreenInfo (& si) ; - SDL_Visual.bpp = si.bpp ; + GrGetScreenInfo(&si); + SDL_Visual.bpp = si.bpp; /* Determine the current screen size */ - this->info.current_w = si.cols ; - this->info.current_h = si.rows ; + this->info.current_w = si.cols; + this->info.current_h = si.rows; // GetVideoMode - SDL_modelist = (SDL_Rect **) SDL_malloc (sizeof (SDL_Rect *) * 2) ; + SDL_modelist = (SDL_Rect **) SDL_malloc(sizeof(SDL_Rect *) * 2); if (SDL_modelist) { - SDL_modelist [0] = (SDL_Rect *) SDL_malloc (sizeof(SDL_Rect)) ; - if (SDL_modelist [0]) { - SDL_modelist [0] -> x = 0 ; - SDL_modelist [0] -> y = 0 ; - SDL_modelist [0] -> w = si.cols ; - SDL_modelist [0] -> h = si.rows ; + SDL_modelist[0] = (SDL_Rect *) SDL_malloc(sizeof(SDL_Rect)); + if (SDL_modelist[0]) { + SDL_modelist[0]->x = 0; + SDL_modelist[0]->y = 0; + SDL_modelist[0]->w = si.cols; + SDL_modelist[0]->h = si.rows; } - SDL_modelist [1] = NULL ; + SDL_modelist[1] = NULL; } pixel_type = si.pixtype; @@ -231,311 +244,329 @@ int NX_VideoInit (_THIS, SDL_PixelFormat * vformat) SDL_Visual.green_mask = si.gmask; SDL_Visual.blue_mask = si.bmask; - vformat -> BitsPerPixel = SDL_Visual.bpp ; - if (vformat -> BitsPerPixel > 8) { - vformat -> Rmask = SDL_Visual.red_mask ; - vformat -> Gmask = SDL_Visual.green_mask ; - vformat -> Bmask = SDL_Visual.blue_mask ; + vformat->BitsPerPixel = SDL_Visual.bpp; + if (vformat->BitsPerPixel > 8) { + vformat->Rmask = SDL_Visual.red_mask; + vformat->Gmask = SDL_Visual.green_mask; + vformat->Bmask = SDL_Visual.blue_mask; } - // See if we have been passed a window to use - SDL_windowid = getenv ("SDL_WINDOWID") ; - + SDL_windowid = getenv("SDL_WINDOWID"); + // Create the fullscreen (and managed windows : no implement) - create_aux_windows (this) ; + create_aux_windows(this); - Dprintf ("leave NX_VideoInit\n") ; - return 0 ; + Dprintf("leave NX_VideoInit\n"); + return 0; } -void NX_VideoQuit (_THIS) +void +NX_VideoQuit(_THIS) { - Dprintf ("enter NX_VideoQuit\n") ; + Dprintf("enter NX_VideoQuit\n"); // Start shutting down the windows - NX_DestroyImage (this, this -> screen) ; - NX_DestroyWindow (this, this -> screen) ; + NX_DestroyImage(this, this->screen); + NX_DestroyWindow(this, this->screen); if (FSwindow && FSwindow != GR_ROOT_WINDOW_ID) { - GrDestroyWindow (FSwindow) ; + GrDestroyWindow(FSwindow); } - NX_FreeVideoModes (this) ; - SDL_free (GammaRamp_R) ; - SDL_free (GammaRamp_G) ; - SDL_free (GammaRamp_B) ; + NX_FreeVideoModes(this); + SDL_free(GammaRamp_R); + SDL_free(GammaRamp_G); + SDL_free(GammaRamp_B); #ifdef ENABLE_NANOX_DIRECT_FB if (Clientfb) GrCloseClientFramebuffer(); #endif - GrClose () ; + GrClose(); - Dprintf ("leave NX_VideoQuit\n") ; + Dprintf("leave NX_VideoQuit\n"); } -static void NX_DestroyWindow (_THIS, SDL_Surface * screen) +static void +NX_DestroyWindow(_THIS, SDL_Surface * screen) { - Dprintf ("enter NX_DestroyWindow\n") ; + Dprintf("enter NX_DestroyWindow\n"); - if (! SDL_windowid) { - if (screen && (screen -> flags & SDL_FULLSCREEN)) { - screen -> flags &= ~ SDL_FULLSCREEN ; - NX_LeaveFullScreen (this) ; + if (!SDL_windowid) { + if (screen && (screen->flags & SDL_FULLSCREEN)) { + screen->flags &= ~SDL_FULLSCREEN; + NX_LeaveFullScreen(this); } - // Destroy the output window if (SDL_Window && SDL_Window != GR_ROOT_WINDOW_ID) { - GrDestroyWindow (SDL_Window) ; + GrDestroyWindow(SDL_Window); } } - // Free the graphics context - if (! SDL_GC) { - GrDestroyGC (SDL_GC) ; + if (!SDL_GC) { + GrDestroyGC(SDL_GC); SDL_GC = 0; } - Dprintf ("leave NX_DestroyWindow\n") ; + Dprintf("leave NX_DestroyWindow\n"); } -static int NX_CreateWindow (_THIS, SDL_Surface * screen, +static int +NX_CreateWindow(_THIS, SDL_Surface * screen, int w, int h, int bpp, Uint32 flags) { - Dprintf ("enter NX_CreateWindow\n") ; + Dprintf("enter NX_CreateWindow\n"); // If a window is already present, destroy it and start fresh if (SDL_Window && SDL_Window != GR_ROOT_WINDOW_ID) { - NX_DestroyWindow (this, screen) ; + NX_DestroyWindow(this, screen); } - // See if we have been given a window id if (SDL_windowid) { - SDL_Window = SDL_strtol (SDL_windowid, NULL, 0) ; + SDL_Window = SDL_strtol(SDL_windowid, NULL, 0); } else { - SDL_Window = 0 ; + SDL_Window = 0; } - - if ( ! SDL_ReallocFormat (screen, bpp, SDL_Visual.red_mask, - SDL_Visual.green_mask, SDL_Visual.blue_mask, 0)) + + if (!SDL_ReallocFormat(screen, bpp, SDL_Visual.red_mask, + SDL_Visual.green_mask, SDL_Visual.blue_mask, 0)) return -1; // Create (or use) the nanox display window - if (! SDL_windowid) { - - SDL_Window = GrNewWindow (GR_ROOT_WINDOW_ID, 0, 0, w, h, 0, BLACK, WHITE) ; - - GrSelectEvents (SDL_Window, (GR_EVENT_MASK_EXPOSURE | - GR_EVENT_MASK_BUTTON_DOWN | GR_EVENT_MASK_BUTTON_UP | - GR_EVENT_MASK_FOCUS_IN | GR_EVENT_MASK_FOCUS_OUT | - GR_EVENT_MASK_KEY_DOWN | GR_EVENT_MASK_KEY_UP | - GR_EVENT_MASK_MOUSE_ENTER | GR_EVENT_MASK_MOUSE_EXIT | - GR_EVENT_MASK_MOUSE_MOTION | GR_EVENT_MASK_UPDATE | - GR_EVENT_MASK_CLOSE_REQ)) ; + if (!SDL_windowid) { + + SDL_Window = + GrNewWindow(GR_ROOT_WINDOW_ID, 0, 0, w, h, 0, BLACK, WHITE); + + GrSelectEvents(SDL_Window, (GR_EVENT_MASK_EXPOSURE | + GR_EVENT_MASK_BUTTON_DOWN | + GR_EVENT_MASK_BUTTON_UP | + GR_EVENT_MASK_FOCUS_IN | + GR_EVENT_MASK_FOCUS_OUT | + GR_EVENT_MASK_KEY_DOWN | + GR_EVENT_MASK_KEY_UP | + GR_EVENT_MASK_MOUSE_ENTER | + GR_EVENT_MASK_MOUSE_EXIT | + GR_EVENT_MASK_MOUSE_MOTION | + GR_EVENT_MASK_UPDATE | + GR_EVENT_MASK_CLOSE_REQ)); } - + /* Create the graphics context here, once we have a window */ - SDL_GC = GrNewGC () ; + SDL_GC = GrNewGC(); if (SDL_GC == 0) { SDL_SetError("Couldn't create graphics context"); - return(-1); + return (-1); } - // Map them both and go fullscreen, if requested - if (! SDL_windowid) { - GrMapWindow (SDL_Window) ; + if (!SDL_windowid) { + GrMapWindow(SDL_Window); if (flags & SDL_FULLSCREEN) { - screen -> flags |= SDL_FULLSCREEN ; - NX_EnterFullScreen (this) ; + screen->flags |= SDL_FULLSCREEN; + NX_EnterFullScreen(this); } else { - screen -> flags &= ~ SDL_FULLSCREEN ; + screen->flags &= ~SDL_FULLSCREEN; } } - #ifdef ENABLE_NANOX_DIRECT_FB /* attempt allocating the client side framebuffer */ Clientfb = GrOpenClientFramebuffer(); - /* NULL return will default to using GrArea()*/ + /* NULL return will default to using GrArea() */ #endif - Dprintf ("leave NX_CreateWindow\n") ; - return 0 ; + Dprintf("leave NX_CreateWindow\n"); + return 0; } -SDL_Surface * NX_SetVideoMode (_THIS, SDL_Surface * current, +SDL_Surface * +NX_SetVideoMode(_THIS, SDL_Surface * current, int width, int height, int bpp, Uint32 flags) { - Dprintf ("enter NX_SetVideoMode\n") ; + Dprintf("enter NX_SetVideoMode\n"); // Lock the event thread, in multi-threading environments - SDL_Lock_EventThread () ; + SDL_Lock_EventThread(); - bpp = SDL_Visual.bpp ; - if (NX_CreateWindow (this, current, width, height, bpp, flags) < 0) { + bpp = SDL_Visual.bpp; + if (NX_CreateWindow(this, current, width, height, bpp, flags) < 0) { current = NULL; goto done; } - if (current -> w != width || current -> h != height) { - current -> w = width ; - current -> h = height ; - current -> pitch = SDL_CalculatePitch (current) ; - NX_ResizeImage (this, current, flags) ; + if (current->w != width || current->h != height) { + current->w = width; + current->h = height; + current->pitch = SDL_CalculatePitch(current); + NX_ResizeImage(this, current, flags); } - current -> flags |= (flags & (SDL_RESIZABLE | SDL_NOFRAME)) ; + current->flags |= (flags & (SDL_RESIZABLE | SDL_NOFRAME)); done: - SDL_Unlock_EventThread () ; + SDL_Unlock_EventThread(); - Dprintf ("leave NX_SetVideoMode\n") ; + Dprintf("leave NX_SetVideoMode\n"); // We're done! - return current ; + return current; } // ncolors <= 256 -int NX_SetColors (_THIS, int firstcolor, int ncolors, SDL_Color * colors) +int +NX_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color * colors) { - int i ; - GR_PALETTE pal ; + int i; + GR_PALETTE pal; - Dprintf ("enter NX_SetColors\n") ; + Dprintf("enter NX_SetColors\n"); - if (ncolors > 256) return 0 ; - - pal.count = ncolors ; - for (i = 0; i < ncolors; ++ i) { - pal.palette [i].r = colors [i].r ; - pal.palette [i].g = colors [i].g ; - pal.palette [i].b = colors [i].b ; + if (ncolors > 256) + return 0; + + pal.count = ncolors; + for (i = 0; i < ncolors; ++i) { + pal.palette[i].r = colors[i].r; + pal.palette[i].g = colors[i].g; + pal.palette[i].b = colors[i].b; } - GrSetSystemPalette (firstcolor, & pal) ; + GrSetSystemPalette(firstcolor, &pal); - Dprintf ("leave NX_SetColors\n") ; - return 1 ; + Dprintf("leave NX_SetColors\n"); + return 1; } -static int NX_ToggleFullScreen (_THIS, int on) +static int +NX_ToggleFullScreen(_THIS, int on) { - SDL_Rect rect ; - Uint32 event_thread ; - - Dprintf ("enter NX_ToggleFullScreen\n") ; + SDL_Rect rect; + Uint32 event_thread; + + Dprintf("enter NX_ToggleFullScreen\n"); // Don't switch if we don't own the window - if (SDL_windowid) return 0 ; - + if (SDL_windowid) + return 0; + // Don't lock if we are the event thread - event_thread = SDL_EventThreadID () ; - if (event_thread && (SDL_ThreadID () == event_thread)) { - event_thread = 0 ; + event_thread = SDL_EventThreadID(); + if (event_thread && (SDL_ThreadID() == event_thread)) { + event_thread = 0; } if (event_thread) { - SDL_Lock_EventThread() ; + SDL_Lock_EventThread(); } - + if (on) { - NX_EnterFullScreen (this) ; + NX_EnterFullScreen(this); } else { - this -> screen -> flags &= ~ SDL_FULLSCREEN ; - NX_LeaveFullScreen (this) ; + this->screen->flags &= ~SDL_FULLSCREEN; + NX_LeaveFullScreen(this); } - rect.x = rect.y = 0 ; - rect.w = this -> screen -> w, rect.h = this -> screen -> h ; - NX_NormalUpdate (this, 1, & rect) ; + rect.x = rect.y = 0; + rect.w = this->screen->w, rect.h = this->screen->h; + NX_NormalUpdate(this, 1, &rect); if (event_thread) { - SDL_Unlock_EventThread () ; + SDL_Unlock_EventThread(); } - - Dprintf ("leave NX_ToggleFullScreen\n") ; - return 1 ; + + Dprintf("leave NX_ToggleFullScreen\n"); + return 1; } // Update the current mouse state and position -static void NX_UpdateMouse (_THIS) +static void +NX_UpdateMouse(_THIS) { - int x, y ; - GR_WINDOW_INFO info ; - GR_SCREEN_INFO si ; + int x, y; + GR_WINDOW_INFO info; + GR_SCREEN_INFO si; - Dprintf ("enter NX_UpdateMouse\n") ; + Dprintf("enter NX_UpdateMouse\n"); // Lock the event thread, in multi-threading environments - SDL_Lock_EventThread () ; - - GrGetScreenInfo (& si) ; - GrGetWindowInfo (SDL_Window, & info) ; - x = si.xpos - info.x ; - y = si.ypos - info.y ; + SDL_Lock_EventThread(); + + GrGetScreenInfo(&si); + GrGetWindowInfo(SDL_Window, &info); + x = si.xpos - info.x; + y = si.ypos - info.y; if (x >= 0 && x <= info.width && y >= 0 && y <= info.height) { - SDL_PrivateAppActive (1, SDL_APPMOUSEFOCUS) ; - SDL_PrivateMouseMotion (0, 0, x, y); + SDL_PrivateAppActive(1, SDL_APPMOUSEFOCUS); + SDL_PrivateMouseMotion(0, 0, x, y); } else { - SDL_PrivateAppActive (0, SDL_APPMOUSEFOCUS) ; + SDL_PrivateAppActive(0, SDL_APPMOUSEFOCUS); } - SDL_Unlock_EventThread () ; - Dprintf ("leave NX_UpdateMouse\n") ; + SDL_Unlock_EventThread(); + Dprintf("leave NX_UpdateMouse\n"); } -static int NX_SetGammaRamp (_THIS, Uint16 * ramp) +static int +NX_SetGammaRamp(_THIS, Uint16 * ramp) { - int i ; - Uint16 * red, * green, * blue ; - - Dprintf ("enter NX_SetGammaRamp\n") ; - - if (SDL_Visual.bpp != 32 && SDL_Visual.bpp != 24) return -1 ; - - if (! GammaRamp_R) GammaRamp_R = (Uint16 *) SDL_malloc (sizeof (Uint16) * CI_SIZE) ; - if (! GammaRamp_G) GammaRamp_G = (Uint16 *) SDL_malloc (sizeof (Uint16) * CI_SIZE) ; - if (! GammaRamp_B) GammaRamp_B = (Uint16 *) SDL_malloc (sizeof (Uint16) * CI_SIZE) ; - if ((! GammaRamp_R) || (! GammaRamp_G) || (! GammaRamp_B)) { - SDL_OutOfMemory () ; - return -1 ; + int i; + Uint16 *red, *green, *blue; + + Dprintf("enter NX_SetGammaRamp\n"); + + if (SDL_Visual.bpp != 32 && SDL_Visual.bpp != 24) + return -1; + + if (!GammaRamp_R) + GammaRamp_R = (Uint16 *) SDL_malloc(sizeof(Uint16) * CI_SIZE); + if (!GammaRamp_G) + GammaRamp_G = (Uint16 *) SDL_malloc(sizeof(Uint16) * CI_SIZE); + if (!GammaRamp_B) + GammaRamp_B = (Uint16 *) SDL_malloc(sizeof(Uint16) * CI_SIZE); + if ((!GammaRamp_R) || (!GammaRamp_G) || (!GammaRamp_B)) { + SDL_OutOfMemory(); + return -1; } - for (i = 0; i < CI_SIZE; ++ i) - GammaRamp_R [i] = GammaRamp_G [i] = GammaRamp_B [i] = i ; - - red = ramp ; - green = ramp + CI_SIZE ; - blue = green + CI_SIZE ; - - for (i = 0; i < CI_SIZE; ++ i) { - GammaRamp_R [i] = red [i] ; - GammaRamp_G [i] = green [i] ; - GammaRamp_B [i] = blue [i] ; + for (i = 0; i < CI_SIZE; ++i) + GammaRamp_R[i] = GammaRamp_G[i] = GammaRamp_B[i] = i; + + red = ramp; + green = ramp + CI_SIZE; + blue = green + CI_SIZE; + + for (i = 0; i < CI_SIZE; ++i) { + GammaRamp_R[i] = red[i]; + GammaRamp_G[i] = green[i]; + GammaRamp_B[i] = blue[i]; } SDL_UpdateRect(this->screen, 0, 0, 0, 0); - Dprintf ("leave NX_SetGammaRamp\n") ; - return 0 ; + Dprintf("leave NX_SetGammaRamp\n"); + return 0; } -static int NX_GetGammaRamp (_THIS, Uint16 * ramp) +static int +NX_GetGammaRamp(_THIS, Uint16 * ramp) { - int i ; - Uint16 * red, * green, * blue ; + int i; + Uint16 *red, *green, *blue; - Dprintf ("enter NX_GetGammaRamp\n") ; + Dprintf("enter NX_GetGammaRamp\n"); - if (SDL_Visual.bpp != 32 && SDL_Visual.bpp != 24) return -1 ; - red = ramp ; - green = ramp + CI_SIZE ; - blue = green + CI_SIZE ; + if (SDL_Visual.bpp != 32 && SDL_Visual.bpp != 24) + return -1; + red = ramp; + green = ramp + CI_SIZE; + blue = green + CI_SIZE; if (GammaRamp_R && GammaRamp_G && GammaRamp_B) { - for (i = 0; i < CI_SIZE; ++ i) { - red [i] = GammaRamp_R [i] ; - green [i] = GammaRamp_G [i] ; - blue [i] = GammaRamp_B [i] ; + for (i = 0; i < CI_SIZE; ++i) { + red[i] = GammaRamp_R[i]; + green[i] = GammaRamp_G[i]; + blue[i] = GammaRamp_B[i]; } } else { - for (i = 0; i < CI_SIZE; ++ i) - red [i] = green [i] = blue [i] = i ; + for (i = 0; i < CI_SIZE; ++i) + red[i] = green[i] = blue[i] = i; } - Dprintf ("leave NX_GetGammaRamp\n") ; - return 0 ; + Dprintf("leave NX_GetGammaRamp\n"); + return 0; } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/nanox/SDL_nxvideo.h b/src/video/nanox/SDL_nxvideo.h index 4e5fa277f..3a83aca2a 100644 --- a/src/video/nanox/SDL_nxvideo.h +++ b/src/video/nanox/SDL_nxvideo.h @@ -42,36 +42,38 @@ #define _THIS SDL_VideoDevice * this // Private display data -typedef struct NX_SDL_VISUAL { - int bpp ; - Uint32 red_mask ; - Uint32 green_mask ; - Uint32 blue_mask ; -} nx_sdl_visual_t ; +typedef struct NX_SDL_VISUAL +{ + int bpp; + Uint32 red_mask; + Uint32 green_mask; + Uint32 blue_mask; +} nx_sdl_visual_t; -struct SDL_PrivateVideoData { - GR_WINDOW_ID SDL_Window ; - GR_WINDOW_ID FSwindow ; +struct SDL_PrivateVideoData +{ + GR_WINDOW_ID SDL_Window; + GR_WINDOW_ID FSwindow; // Flag: true if we have been passed a window - char * SDL_windowid ; - GR_GC_ID GC ; - unsigned char * Image ; - unsigned char * Image_buff ; /* for GrArea*/ - unsigned char * Clientfb; /* for DirectFB*/ - nx_sdl_visual_t SDL_Visual ; + char *SDL_windowid; + GR_GC_ID GC; + unsigned char *Image; + unsigned char *Image_buff; /* for GrArea */ + unsigned char *Clientfb; /* for DirectFB */ + nx_sdl_visual_t SDL_Visual; // The current list of available video modes - SDL_Rect ** modelist ; - int currently_fullscreen ; + SDL_Rect **modelist; + int currently_fullscreen; // for fullscreen - int OffsetX, OffsetY ; + int OffsetX, OffsetY; // for GammaRamp - Uint16 * GammaRamp_R, * GammaRamp_G, * GammaRamp_B ; + Uint16 *GammaRamp_R, *GammaRamp_G, *GammaRamp_B; // for GrArea, r_mask, g_mask, b_mask - int pixel_type ; + int pixel_type; #ifdef ENABLE_NANOX_DIRECT_FB GR_WINDOW_FB_INFO fbinfo; #endif -} ; +}; #define SDL_Window (this -> hidden -> SDL_Window) #define FSwindow (this -> hidden -> FSwindow) @@ -91,6 +93,7 @@ struct SDL_PrivateVideoData { #define pixel_type (this -> hidden -> pixel_type) #define fbinfo (this -> hidden -> fbinfo) -#define CI_SIZE 256 // color index size +#define CI_SIZE 256 // color index size -#endif // _SDL_nxvideo_h +#endif // _SDL_nxvideo_h +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/nanox/SDL_nxwm.c b/src/video/nanox/SDL_nxwm.c index d0af3bfbd..2950c4560 100644 --- a/src/video/nanox/SDL_nxwm.c +++ b/src/video/nanox/SDL_nxwm.c @@ -30,32 +30,36 @@ #include "SDL_nxwm_c.h" -void NX_SetCaption (_THIS, const char * title, const char * icon) +void +NX_SetCaption(_THIS, const char *title, const char *icon) { - Dprintf ("enter NX_SetCaption\n") ; + Dprintf("enter NX_SetCaption\n"); // Lock the event thread, in multi-threading environments - SDL_Lock_EventThread () ; - - if (SDL_Window) - GrSetWindowTitle (SDL_Window, title) ; - - SDL_Unlock_EventThread () ; - Dprintf ("leave NX_SetCaption\n") ; + SDL_Lock_EventThread(); + + if (SDL_Window) + GrSetWindowTitle(SDL_Window, title); + + SDL_Unlock_EventThread(); + Dprintf("leave NX_SetCaption\n"); } -int NX_GetWMInfo (_THIS, SDL_SysWMinfo * info) +int +NX_GetWMInfo(_THIS, SDL_SysWMinfo * info) { - Dprintf ("enter NX_GetWMInfo\n") ; + Dprintf("enter NX_GetWMInfo\n"); - if (info -> version.major <= SDL_MAJOR_VERSION) { - info -> window = SDL_Window ; - return 1 ; + if (info->version.major <= SDL_MAJOR_VERSION) { + info->window = SDL_Window; + return 1; } else { SDL_SetError("Application not compiled with SDL %d.%d\n", - SDL_MAJOR_VERSION, SDL_MINOR_VERSION) ; - return -1 ; + SDL_MAJOR_VERSION, SDL_MINOR_VERSION); + return -1; } - Dprintf ("leave NX_GetWMInfo\n") ; + Dprintf("leave NX_GetWMInfo\n"); } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/nanox/SDL_nxwm_c.h b/src/video/nanox/SDL_nxwm_c.h index 459cec888..26aa6a1ca 100644 --- a/src/video/nanox/SDL_nxwm_c.h +++ b/src/video/nanox/SDL_nxwm_c.h @@ -28,5 +28,6 @@ #include "SDL_nxvideo.h" // Functions to be exported -extern void NX_SetCaption (_THIS, const char * title, const char * icon) ; -extern int NX_GetWMInfo (_THIS, SDL_SysWMinfo * info) ; +extern void NX_SetCaption(_THIS, const char *title, const char *icon); +extern int NX_GetWMInfo(_THIS, SDL_SysWMinfo * info); +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/os2fslib/SDL_os2fslib.c b/src/video/os2fslib/SDL_os2fslib.c index e05540a27..ab5d3d58b 100644 --- a/src/video/os2fslib/SDL_os2fslib.c +++ b/src/video/os2fslib/SDL_os2fslib.c @@ -23,8 +23,8 @@ #define _ULS_CALLCONV_ #define CALLCONV _System -#include // Unicode API -#include // Unicode API (codepage conversion) +#include // Unicode API +#include // Unicode API (codepage conversion) #include #include @@ -38,15 +38,12 @@ #include "SDL_os2fslib.h" static ULONG ulFCFToUse = - FCF_TITLEBAR | - FCF_SYSMENU | - FCF_MINBUTTON | - FCF_MAXBUTTON | - FCF_NOBYTEALIGN | - FCF_SIZEBORDER | - FCF_TASKLIST; - -static int bMouseCaptured = 0; + FCF_TITLEBAR | + FCF_SYSMENU | + FCF_MINBUTTON | + FCF_MAXBUTTON | FCF_NOBYTEALIGN | FCF_SIZEBORDER | FCF_TASKLIST; + +static int bMouseCaptured = 0; static int bMouseCapturable = 0; static HPOINTER hptrGlobalPointer = NULL; static HPOINTER hptrCurrentIcon = NULL; @@ -57,16 +54,17 @@ static int bWindowResized = 0; #pragma pack(1) typedef struct BMPINFO { - BITMAPINFO; - RGB clr; + BITMAPINFO; + RGB clr; } BMPINFO, *PBMPINFO; #pragma pack() // Backdoors: -DECLSPEC void SDLCALL SDL_OS2FSLIB_SetFCFToUse(ULONG ulFCF) +DECLSPEC void SDLCALL +SDL_OS2FSLIB_SetFCFToUse(ULONG ulFCF) { - ulFCFToUse = ulFCF; + ulFCFToUse = ulFCF; } // Configuration defines: @@ -92,8 +90,9 @@ DECLSPEC void SDLCALL SDL_OS2FSLIB_SetFCFToUse(ULONG ulFCF) /* The translation table from a VK keysym to a SDL keysym */ static SDLKey HWScanKeyMap[256]; -static SDL_keysym *TranslateKey(int vkey, int chcode, int scancode, SDL_keysym *keysym, int iPressed); -static int iShiftIsPressed; +static SDL_keysym *TranslateKey(int vkey, int chcode, int scancode, + SDL_keysym * keysym, int iPressed); +static int iShiftIsPressed; #ifdef BITBLT_IN_WINMESSAGEPROC #define WM_UPDATERECTSREQUEST WM_USER+50 @@ -119,111 +118,101 @@ static int iShiftIsPressed; // always on the screen, the titlebar will be accessable everytime. // ///////////////////////////////////////////////////////////////////// -static BOOL SetAccessableWindowPos(HWND hwnd, HWND hwndInsertBehind, - LONG x, LONG y, - LONG cx, LONG cy, - ULONG fl) +static BOOL +SetAccessableWindowPos(HWND hwnd, HWND hwndInsertBehind, + LONG x, LONG y, LONG cx, LONG cy, ULONG fl) { - SWP swpDesktop, swp; - // Get desktop area - WinQueryWindowPos(HWND_DESKTOP, &swpDesktop); - - if ((fl & SWP_MOVE) && (fl & SWP_SIZE)) - { - // If both moving and sizing, then change size and pos now!! - if (x+cx>swpDesktop.cx) - x = swpDesktop.cx - cx; - if (x<0) - x = 0; - if (y<0) - y = 0; - if (y+cy>swpDesktop.cy) - y = swpDesktop.cy - cy; - return WinSetWindowPos(hwnd, hwndInsertBehind, x, y, cx, cy, fl); - } else - if (fl & SWP_MOVE) - { - // Just moving - WinQueryWindowPos(hwnd, &swp); - if (x+swp.cx>swpDesktop.cx) - x = swpDesktop.cx - swp.cx; - if (x<0) - x = 0; - if (y<0) - y = 0; - if (y+swp.cy>swpDesktop.cy) - y = swpDesktop.cy - swp.cy; - return WinSetWindowPos(hwnd, hwndInsertBehind, x, y, cx, cy, fl); - } else - if (fl & SWP_SIZE) - { - // Just sizing - WinQueryWindowPos(hwnd, &swp); - x = swp.x; - y = swp.y; - if (x+cx>swpDesktop.cx) - x = swpDesktop.cx - cx; - if (x<0) - x = 0; - if (y<0) - y = 0; - if (y+cy>swpDesktop.cy) - y = swpDesktop.cy - cy; - return WinSetWindowPos(hwnd, hwndInsertBehind, x, y, cx, cy, fl | SWP_MOVE); - } else - return WinSetWindowPos(hwnd, hwndInsertBehind, x, y, cx, cy, fl); + SWP swpDesktop, swp; + // Get desktop area + WinQueryWindowPos(HWND_DESKTOP, &swpDesktop); + + if ((fl & SWP_MOVE) && (fl & SWP_SIZE)) { + // If both moving and sizing, then change size and pos now!! + if (x + cx > swpDesktop.cx) + x = swpDesktop.cx - cx; + if (x < 0) + x = 0; + if (y < 0) + y = 0; + if (y + cy > swpDesktop.cy) + y = swpDesktop.cy - cy; + return WinSetWindowPos(hwnd, hwndInsertBehind, x, y, cx, cy, fl); + } else if (fl & SWP_MOVE) { + // Just moving + WinQueryWindowPos(hwnd, &swp); + if (x + swp.cx > swpDesktop.cx) + x = swpDesktop.cx - swp.cx; + if (x < 0) + x = 0; + if (y < 0) + y = 0; + if (y + swp.cy > swpDesktop.cy) + y = swpDesktop.cy - swp.cy; + return WinSetWindowPos(hwnd, hwndInsertBehind, x, y, cx, cy, fl); + } else if (fl & SWP_SIZE) { + // Just sizing + WinQueryWindowPos(hwnd, &swp); + x = swp.x; + y = swp.y; + if (x + cx > swpDesktop.cx) + x = swpDesktop.cx - cx; + if (x < 0) + x = 0; + if (y < 0) + y = 0; + if (y + cy > swpDesktop.cy) + y = swpDesktop.cy - cy; + return WinSetWindowPos(hwnd, hwndInsertBehind, x, y, cx, cy, + fl | SWP_MOVE); + } else + return WinSetWindowPos(hwnd, hwndInsertBehind, x, y, cx, cy, fl); } -static UniChar NativeCharToUniChar(int chcode) +static UniChar +NativeCharToUniChar(int chcode) { - UniChar ucResult = (UniChar) chcode; - int rc; - UconvObject ucoTemp; - char achFrom[2]; - char *pchFrom; - size_t iFromCount; - UniChar aucTo[10]; - UniChar *pucTo; - size_t iToCount; - size_t iNonIdentical; - - // Create unicode convert object - rc = UniCreateUconvObject(L"", &ucoTemp); - if (rc!=ULS_SUCCESS) - { - // Could not create convert object! - return ucResult; - } - - // Convert language code string to unicode string - achFrom[0] = (char) chcode; - achFrom[1] = 0; - iFromCount = sizeof(char) * 2; - iToCount = sizeof(UniChar) * 2; - pucTo = &(aucTo[0]); - pchFrom = &(achFrom[0]); - - rc = UniUconvToUcs(ucoTemp, - &pchFrom, - &iFromCount, - &pucTo, - &iToCount, - &iNonIdentical); - - if (rc!=ULS_SUCCESS) - { - // Could not convert language code to UCS string! - UniFreeUconvObject(ucoTemp); - return ucResult; - } + UniChar ucResult = (UniChar) chcode; + int rc; + UconvObject ucoTemp; + char achFrom[2]; + char *pchFrom; + size_t iFromCount; + UniChar aucTo[10]; + UniChar *pucTo; + size_t iToCount; + size_t iNonIdentical; + + // Create unicode convert object + rc = UniCreateUconvObject(L"", &ucoTemp); + if (rc != ULS_SUCCESS) { + // Could not create convert object! + return ucResult; + } + // Convert language code string to unicode string + achFrom[0] = (char) chcode; + achFrom[1] = 0; + iFromCount = sizeof(char) * 2; + iToCount = sizeof(UniChar) * 2; + pucTo = &(aucTo[0]); + pchFrom = &(achFrom[0]); + + rc = UniUconvToUcs(ucoTemp, + &pchFrom, + &iFromCount, &pucTo, &iToCount, &iNonIdentical); + + if (rc != ULS_SUCCESS) { + // Could not convert language code to UCS string! + UniFreeUconvObject(ucoTemp); + return ucResult; + } - UniFreeUconvObject(ucoTemp); + UniFreeUconvObject(ucoTemp); #ifdef DEBUG_BUILD - printf("%02x converted to %02x\n", (int) chcode, (int) (aucTo[0])); + printf("%02x converted to %02x\n", (int) chcode, (int) (aucTo[0])); #endif - return aucTo[0]; + return aucTo[0]; } ///////////////////////////////////////////////////////////////////// @@ -233,106 +222,104 @@ static UniChar NativeCharToUniChar(int chcode) // This creates SDL Keycodes from VK_ and hardware scan codes // ///////////////////////////////////////////////////////////////////// -static SDL_keysym *TranslateKey(int vkey, int chcode, int scancode, SDL_keysym *keysym, int iPressed) +static SDL_keysym * +TranslateKey(int vkey, int chcode, int scancode, SDL_keysym * keysym, + int iPressed) { - keysym->scancode = (unsigned char) scancode; - keysym->mod = KMOD_NONE; - keysym->unicode = 0; - - if (iPressed && SDL_TranslateUNICODE) - { - if (chcode) - keysym->unicode = NativeCharToUniChar(chcode); - else - keysym->unicode = vkey; - } - - keysym->sym = HWScanKeyMap[scancode]; - - // Now stuffs based on state of shift key(s)! - if (vkey == VK_SHIFT) - { - iShiftIsPressed = iPressed; - } - - if ((iShiftIsPressed) && (SDL_TranslateUNICODE)) - { - // Change syms, if Unicode stuff is required - // I think it's silly, but it's SDL... - switch (keysym->sym) - { - case SDLK_BACKQUOTE: - keysym->sym = '~'; - break; - case SDLK_1: - keysym->sym = SDLK_EXCLAIM; - break; - case SDLK_2: - keysym->sym = SDLK_AT; - break; - case SDLK_3: - keysym->sym = SDLK_HASH; - break; - case SDLK_4: - keysym->sym = SDLK_DOLLAR; - break; - case SDLK_5: - keysym->sym = '%'; - break; - case SDLK_6: - keysym->sym = SDLK_CARET; - break; - case SDLK_7: - keysym->sym = SDLK_AMPERSAND; - break; - case SDLK_8: - keysym->sym = SDLK_ASTERISK; - break; - case SDLK_9: - keysym->sym = SDLK_LEFTPAREN; - break; - case SDLK_0: - keysym->sym = SDLK_RIGHTPAREN; - break; - case SDLK_MINUS: - keysym->sym = SDLK_UNDERSCORE; - break; - case SDLK_PLUS: - keysym->sym = SDLK_EQUALS; - break; + keysym->scancode = (unsigned char) scancode; + keysym->mod = KMOD_NONE; + keysym->unicode = 0; - case SDLK_LEFTBRACKET: - keysym->sym = '{'; - break; - case SDLK_RIGHTBRACKET: - keysym->sym = '}'; - break; + if (iPressed && SDL_TranslateUNICODE) { + if (chcode) + keysym->unicode = NativeCharToUniChar(chcode); + else + keysym->unicode = vkey; + } - case SDLK_SEMICOLON: - keysym->sym = SDLK_COLON; - break; - case SDLK_QUOTE: - keysym->sym = SDLK_QUOTEDBL; - break; - case SDLK_BACKSLASH: - keysym->sym = '|'; - break; + keysym->sym = HWScanKeyMap[scancode]; - case SDLK_COMMA: - keysym->sym = SDLK_LESS; - break; - case SDLK_PERIOD: - keysym->sym = SDLK_GREATER; - break; - case SDLK_SLASH: - keysym->sym = SDLK_QUESTION; - break; + // Now stuffs based on state of shift key(s)! + if (vkey == VK_SHIFT) { + iShiftIsPressed = iPressed; + } - default: - break; + if ((iShiftIsPressed) && (SDL_TranslateUNICODE)) { + // Change syms, if Unicode stuff is required + // I think it's silly, but it's SDL... + switch (keysym->sym) { + case SDLK_BACKQUOTE: + keysym->sym = '~'; + break; + case SDLK_1: + keysym->sym = SDLK_EXCLAIM; + break; + case SDLK_2: + keysym->sym = SDLK_AT; + break; + case SDLK_3: + keysym->sym = SDLK_HASH; + break; + case SDLK_4: + keysym->sym = SDLK_DOLLAR; + break; + case SDLK_5: + keysym->sym = '%'; + break; + case SDLK_6: + keysym->sym = SDLK_CARET; + break; + case SDLK_7: + keysym->sym = SDLK_AMPERSAND; + break; + case SDLK_8: + keysym->sym = SDLK_ASTERISK; + break; + case SDLK_9: + keysym->sym = SDLK_LEFTPAREN; + break; + case SDLK_0: + keysym->sym = SDLK_RIGHTPAREN; + break; + case SDLK_MINUS: + keysym->sym = SDLK_UNDERSCORE; + break; + case SDLK_PLUS: + keysym->sym = SDLK_EQUALS; + break; + + case SDLK_LEFTBRACKET: + keysym->sym = '{'; + break; + case SDLK_RIGHTBRACKET: + keysym->sym = '}'; + break; + + case SDLK_SEMICOLON: + keysym->sym = SDLK_COLON; + break; + case SDLK_QUOTE: + keysym->sym = SDLK_QUOTEDBL; + break; + case SDLK_BACKSLASH: + keysym->sym = '|'; + break; + + case SDLK_COMMA: + keysym->sym = SDLK_LESS; + break; + case SDLK_PERIOD: + keysym->sym = SDLK_GREATER; + break; + case SDLK_SLASH: + keysym->sym = SDLK_QUESTION; + break; + + default: + break; + } } - } - return keysym; + return keysym; } #define CONVERTMOUSEPOSITION() \ @@ -379,666 +366,709 @@ static SDL_keysym *TranslateKey(int vkey, int chcode, int scancode, SDL_keysym * // and mouse events to where it has to be sent, etc... // ///////////////////////////////////////////////////////////////////// -static MRESULT EXPENTRY WndProc( HWND hwnd, ULONG msg, MPARAM mp1, MPARAM mp2) +static MRESULT EXPENTRY +WndProc(HWND hwnd, ULONG msg, MPARAM mp1, MPARAM mp2) { - HPS ps; - RECTL rcl; - SDL_VideoDevice *pVideo = NULL; + HPS ps; + RECTL rcl; + SDL_VideoDevice *pVideo = NULL; - switch (msg) - { - case WM_CHAR: // Keypress notification + switch (msg) { + case WM_CHAR: // Keypress notification #ifdef DEBUG_BUILD // printf("WM_CHAR\n"); fflush(stdout); #endif - pVideo = WinQueryWindowPtr(hwnd, 0); - if (pVideo) - { - /* - // We skip repeated keys: - if (CHARMSG(&msg)->cRepeat>1) - { -#ifdef DEBUG_BUILD -// printf("Repeated key (%d), skipping...\n", CHARMSG(&msg)->cRepeat); fflush(stdout); -#endif - return (MRESULT) TRUE; - } - */ - - // If it's not repeated, then let's see if its pressed or released! - if (SHORT1FROMMP(mp1) & KC_KEYUP) - { - // A key has been released - SDL_keysym keysym; + pVideo = WinQueryWindowPtr(hwnd, 0); + if (pVideo) { + /* + // We skip repeated keys: + if (CHARMSG(&msg)->cRepeat>1) + { + #ifdef DEBUG_BUILD + // printf("Repeated key (%d), skipping...\n", CHARMSG(&msg)->cRepeat); fflush(stdout); + #endif + return (MRESULT) TRUE; + } + */ + + // If it's not repeated, then let's see if its pressed or released! + if (SHORT1FROMMP(mp1) & KC_KEYUP) { + // A key has been released + SDL_keysym keysym; #ifdef DEBUG_BUILD // printf("WM_CHAR, keyup, code is [0x%0x]\n", CHAR4FROMMP(mp1)); // HW scan code #endif - // One problem is with F1, which gets only the keyup message because - // it is a system key. - // So, when we get keyup message, we simulate keydown too! - // UPDATE: - // This problem should be solved now, that the accelerator keys are - // disabled for this window! - /* - if (SHORT2FROMMP(mp2)==VK_F1) - { - SDL_PrivateKeyboard(SDL_PRESSED, TranslateKey(SHORT2FROMMP(mp2), // VK_ code - SHORT1FROMMP(mp2), // Character code - CHAR4FROMMP(mp1), // HW Scan code - &keysym,0)); - }*/ - - SDL_PrivateKeyboard(SDL_RELEASED, TranslateKey(SHORT2FROMMP(mp2), // VK_ code - SHORT1FROMMP(mp2), // Character code - CHAR4FROMMP(mp1), // HW Scan code - &keysym,0)); - - } else - { - // A key has been pressed - SDL_keysym keysym; + // One problem is with F1, which gets only the keyup message because + // it is a system key. + // So, when we get keyup message, we simulate keydown too! + // UPDATE: + // This problem should be solved now, that the accelerator keys are + // disabled for this window! + /* + if (SHORT2FROMMP(mp2)==VK_F1) + { + SDL_PrivateKeyboard(SDL_PRESSED, TranslateKey(SHORT2FROMMP(mp2), // VK_ code + SHORT1FROMMP(mp2), // Character code + CHAR4FROMMP(mp1), // HW Scan code + &keysym,0)); + } */ + + SDL_PrivateKeyboard(SDL_RELEASED, TranslateKey(SHORT2FROMMP(mp2), // VK_ code + SHORT1FROMMP(mp2), // Character code + CHAR4FROMMP(mp1), // HW Scan code + &keysym, 0)); + + } else { + // A key has been pressed + SDL_keysym keysym; #ifdef DEBUG_BUILD // printf("WM_CHAR, keydown, code is [0x%0x]\n", CHAR4FROMMP(mp1)); // HW scan code #endif - // Check for fastkeys: ALT+HOME to toggle FS mode - // ALT+END to close app - if ((SHORT1FROMMP(mp1) & KC_ALT) && - (SHORT2FROMMP(mp2) == VK_HOME)) - { -#ifdef DEBUG_BUILD - printf(" Pressed ALT+HOME!\n"); fflush(stdout); -#endif - // Only switch between fullscreen and back if it's not - // a resizable mode! - if ( - (!pVideo->hidden->pSDLSurface) || - ((pVideo->hidden->pSDLSurface) - && ((pVideo->hidden->pSDLSurface->flags & SDL_RESIZABLE)==0) - ) - ) - FSLib_ToggleFSMode(hwnd, !FSLib_QueryFSMode(hwnd)); -#ifdef DEBUG_BUILD - else - printf(" Resizable mode, so discarding ALT+HOME!\n"); fflush(stdout); -#endif - } else - if ((SHORT1FROMMP(mp1) & KC_ALT) && - (SHORT2FROMMP(mp2) == VK_END)) - { -#ifdef DEBUG_BUILD - printf(" Pressed ALT+END!\n"); fflush(stdout); -#endif - // Close window, and get out of loop! - // Also send event to SDL application, but we won't - // wait for it to be processed! - SDL_PrivateQuit(); - WinPostMsg(hwnd, WM_QUIT, 0, 0); - } else - { - - SDL_PrivateKeyboard(SDL_PRESSED, TranslateKey(SHORT2FROMMP(mp2), // VK_ code - SHORT1FROMMP(mp2), // Character code - CHAR4FROMMP(mp1), // HW Scan code - &keysym,1)); - - } + // Check for fastkeys: ALT+HOME to toggle FS mode + // ALT+END to close app + if ((SHORT1FROMMP(mp1) & KC_ALT) && + (SHORT2FROMMP(mp2) == VK_HOME)) { +#ifdef DEBUG_BUILD + printf(" Pressed ALT+HOME!\n"); + fflush(stdout); +#endif + // Only switch between fullscreen and back if it's not + // a resizable mode! + if ((!pVideo->hidden->pSDLSurface) || + ((pVideo->hidden->pSDLSurface) + && + ((pVideo->hidden->pSDLSurface-> + flags & SDL_RESIZABLE) == 0))) + FSLib_ToggleFSMode(hwnd, !FSLib_QueryFSMode(hwnd)); +#ifdef DEBUG_BUILD + else + printf(" Resizable mode, so discarding ALT+HOME!\n"); + fflush(stdout); +#endif + } else if ((SHORT1FROMMP(mp1) & KC_ALT) && + (SHORT2FROMMP(mp2) == VK_END)) { +#ifdef DEBUG_BUILD + printf(" Pressed ALT+END!\n"); + fflush(stdout); +#endif + // Close window, and get out of loop! + // Also send event to SDL application, but we won't + // wait for it to be processed! + SDL_PrivateQuit(); + WinPostMsg(hwnd, WM_QUIT, 0, 0); + } else { + + SDL_PrivateKeyboard(SDL_PRESSED, TranslateKey(SHORT2FROMMP(mp2), // VK_ code + SHORT1FROMMP(mp2), // Character code + CHAR4FROMMP(mp1), // HW Scan code + &keysym, + 1)); + + } + } } - } - return (MRESULT) TRUE; + return (MRESULT) TRUE; case WM_TRANSLATEACCEL: - { - PQMSG pqmsg; - pqmsg = (PQMSG) mp1; - if (mp1) { - if (pqmsg->msg == WM_CHAR) - { - // WM_CHAR message! - // Let's filter the ALT keypress and all other acceleration keys! - return (MRESULT) FALSE; - } + PQMSG pqmsg; + pqmsg = (PQMSG) mp1; + if (mp1) { + if (pqmsg->msg == WM_CHAR) { + // WM_CHAR message! + // Let's filter the ALT keypress and all other acceleration keys! + return (MRESULT) FALSE; + } + } + break; // Default processing (pass to parent until frame control) } - break; // Default processing (pass to parent until frame control) - } - case WM_PAINT: // Window redraw! -#ifdef DEBUG_BUILD - printf("WM_PAINT (0x%x)\n", hwnd); fflush(stdout); -#endif - ps = WinBeginPaint(hwnd,0,&rcl); - pVideo = FSLib_GetUserParm(hwnd); - if (pVideo) - { - if (!pVideo->hidden->pSDLSurface) - { - RECTL rclRect; - // So, don't blit now! + case WM_PAINT: // Window redraw! #ifdef DEBUG_BUILD - printf("WM_PAINT : Skipping blit while resizing (Pre!)!\n"); fflush(stdout); + printf("WM_PAINT (0x%x)\n", hwnd); + fflush(stdout); #endif - WinQueryWindowRect(hwnd, &rclRect); - // Fill with black - WinFillRect(ps, &rclRect, CLR_BLACK); - } else - { - if (DosRequestMutexSem(pVideo->hidden->hmtxUseSrcBuffer, 1000)==NO_ERROR) - { - int iTop, iLeft, iWidth, iHeight; - int iXScaleError, iYScaleError; - int iXScaleError2, iYScaleError2; - SWP swp; - - // Re-blit the modified area! - // For this, we have to calculate the points, scaled! - WinQueryWindowPos(hwnd, &swp); -#ifdef DEBUG_BUILD - printf("WM_PAINT : WinSize: %d %d, BufSize: %d %d\n", - swp.cx, - swp.cy, - pVideo->hidden->SrcBufferDesc.uiXResolution, - pVideo->hidden->SrcBufferDesc.uiYResolution - ); - fflush(stdout); + ps = WinBeginPaint(hwnd, 0, &rcl); + pVideo = FSLib_GetUserParm(hwnd); + if (pVideo) { + if (!pVideo->hidden->pSDLSurface) { + RECTL rclRect; + // So, don't blit now! +#ifdef DEBUG_BUILD + printf("WM_PAINT : Skipping blit while resizing (Pre!)!\n"); + fflush(stdout); +#endif + WinQueryWindowRect(hwnd, &rclRect); + // Fill with black + WinFillRect(ps, &rclRect, CLR_BLACK); + } else { + if (DosRequestMutexSem + (pVideo->hidden->hmtxUseSrcBuffer, 1000) == NO_ERROR) { + int iTop, iLeft, iWidth, iHeight; + int iXScaleError, iYScaleError; + int iXScaleError2, iYScaleError2; + SWP swp; + + // Re-blit the modified area! + // For this, we have to calculate the points, scaled! + WinQueryWindowPos(hwnd, &swp); +#ifdef DEBUG_BUILD + printf + ("WM_PAINT : WinSize: %d %d, BufSize: %d %d\n", + swp.cx, swp.cy, + pVideo->hidden->SrcBufferDesc.uiXResolution, + pVideo->hidden->SrcBufferDesc.uiYResolution); + fflush(stdout); #endif #ifndef RESIZE_EVEN_IF_RESIZABLE - // But only blit if the window is not resizable, or if - // the window is resizable and the source buffer size is the - // same as the destination buffer size! - if ((!pVideo->hidden->pSDLSurface) || - ((pVideo->hidden->pSDLSurface) && - (pVideo->hidden->pSDLSurface->flags & SDL_RESIZABLE) && - ((swp.cx != pVideo->hidden->SrcBufferDesc.uiXResolution) || - (swp.cy != pVideo->hidden->SrcBufferDesc.uiYResolution) - ) && - (!FSLib_QueryFSMode(hwnd)) - ) - ) - { - RECTL rclRect; - // Resizable surface and in resizing! - // So, don't blit now! -#ifdef DEBUG_BUILD - printf("WM_PAINT : Skipping blit while resizing!\n"); fflush(stdout); -#endif - WinQueryWindowRect(hwnd, &rclRect); - // Fill with black - WinFillRect(ps, &rclRect, CLR_BLACK); - } else -#endif - { - - iXScaleError = (pVideo->hidden->SrcBufferDesc.uiXResolution-1) / swp.cx; - iYScaleError = (pVideo->hidden->SrcBufferDesc.uiYResolution-1) / swp.cy; - if (iXScaleError<0) iXScaleError = 0; - if (iYScaleError<0) iYScaleError = 0; - iXScaleError2 = (swp.cx-1)/(pVideo->hidden->SrcBufferDesc.uiXResolution); - iYScaleError2 = (swp.cy-1)/(pVideo->hidden->SrcBufferDesc.uiYResolution); - if (iXScaleError2<0) iXScaleError2 = 0; - if (iYScaleError2<0) iYScaleError2 = 0; - - iTop = (swp.cy - rcl.yTop) * pVideo->hidden->SrcBufferDesc.uiYResolution / swp.cy - iYScaleError; - iLeft = rcl.xLeft * pVideo->hidden->SrcBufferDesc.uiXResolution / swp.cx - iXScaleError; - iWidth = ((rcl.xRight-rcl.xLeft) * pVideo->hidden->SrcBufferDesc.uiXResolution + swp.cx-1) - / swp.cx + 2*iXScaleError; - iHeight = ((rcl.yTop-rcl.yBottom) * pVideo->hidden->SrcBufferDesc.uiYResolution + swp.cy-1) - / swp.cy + 2*iYScaleError; - - iWidth+=iXScaleError2; - iHeight+=iYScaleError2; - - if (iTop<0) iTop = 0; - if (iLeft<0) iLeft = 0; - if (iTop+iHeight>pVideo->hidden->SrcBufferDesc.uiYResolution) iHeight = pVideo->hidden->SrcBufferDesc.uiYResolution-iTop; - if (iLeft+iWidth>pVideo->hidden->SrcBufferDesc.uiXResolution) iWidth = pVideo->hidden->SrcBufferDesc.uiXResolution-iLeft; - -#ifdef DEBUG_BUILD - printf("WM_PAINT : BitBlt: %d %d -> %d %d (Buf %d x %d)\n", - iTop, iLeft, iWidth, iHeight, - pVideo->hidden->SrcBufferDesc.uiXResolution, - pVideo->hidden->SrcBufferDesc.uiYResolution - ); - fflush(stdout); -#endif - - FSLIB_BITBLT(hwnd, pVideo->hidden->pchSrcBuffer, iTop, iLeft, iWidth, iHeight); + // But only blit if the window is not resizable, or if + // the window is resizable and the source buffer size is the + // same as the destination buffer size! + if ((!pVideo->hidden->pSDLSurface) || + ((pVideo->hidden->pSDLSurface) && + (pVideo->hidden->pSDLSurface->flags & SDL_RESIZABLE) + && + ((swp.cx != + pVideo->hidden->SrcBufferDesc.uiXResolution) + || (swp.cy != + pVideo->hidden->SrcBufferDesc.uiYResolution)) + && (!FSLib_QueryFSMode(hwnd)))) { + RECTL rclRect; + // Resizable surface and in resizing! + // So, don't blit now! +#ifdef DEBUG_BUILD + printf("WM_PAINT : Skipping blit while resizing!\n"); + fflush(stdout); +#endif + WinQueryWindowRect(hwnd, &rclRect); + // Fill with black + WinFillRect(ps, &rclRect, CLR_BLACK); + } else +#endif + { + + iXScaleError = + (pVideo->hidden->SrcBufferDesc. + uiXResolution - 1) / swp.cx; + iYScaleError = + (pVideo->hidden->SrcBufferDesc. + uiYResolution - 1) / swp.cy; + if (iXScaleError < 0) + iXScaleError = 0; + if (iYScaleError < 0) + iYScaleError = 0; + iXScaleError2 = + (swp.cx - + 1) / + (pVideo->hidden->SrcBufferDesc.uiXResolution); + iYScaleError2 = + (swp.cy - + 1) / + (pVideo->hidden->SrcBufferDesc.uiYResolution); + if (iXScaleError2 < 0) + iXScaleError2 = 0; + if (iYScaleError2 < 0) + iYScaleError2 = 0; + + iTop = + (swp.cy - + rcl.yTop) * + pVideo->hidden->SrcBufferDesc. + uiYResolution / swp.cy - iYScaleError; + iLeft = + rcl.xLeft * + pVideo->hidden->SrcBufferDesc. + uiXResolution / swp.cx - iXScaleError; + iWidth = + ((rcl.xRight - + rcl.xLeft) * + pVideo->hidden->SrcBufferDesc. + uiXResolution + swp.cx - 1) / swp.cx + + 2 * iXScaleError; + iHeight = + ((rcl.yTop - + rcl.yBottom) * + pVideo->hidden->SrcBufferDesc. + uiYResolution + swp.cy - 1) / swp.cy + + 2 * iYScaleError; + + iWidth += iXScaleError2; + iHeight += iYScaleError2; + + if (iTop < 0) + iTop = 0; + if (iLeft < 0) + iLeft = 0; + if (iTop + iHeight > + pVideo->hidden->SrcBufferDesc.uiYResolution) + iHeight = + pVideo->hidden->SrcBufferDesc. + uiYResolution - iTop; + if (iLeft + iWidth > + pVideo->hidden->SrcBufferDesc.uiXResolution) + iWidth = + pVideo->hidden->SrcBufferDesc. + uiXResolution - iLeft; + +#ifdef DEBUG_BUILD + printf + ("WM_PAINT : BitBlt: %d %d -> %d %d (Buf %d x %d)\n", + iTop, iLeft, iWidth, iHeight, + pVideo->hidden->SrcBufferDesc. + uiXResolution, + pVideo->hidden->SrcBufferDesc.uiYResolution); + fflush(stdout); +#endif + + FSLIB_BITBLT(hwnd, + pVideo->hidden->pchSrcBuffer, + iTop, iLeft, iWidth, iHeight); + } + + DosReleaseMutexSem(pVideo->hidden->hmtxUseSrcBuffer); + } } - - DosReleaseMutexSem(pVideo->hidden->hmtxUseSrcBuffer); - } } - } #ifdef DEBUG_BUILD - else - { - printf("WM_PAINT : No pVideo!\n"); fflush(stdout); - } + else { + printf("WM_PAINT : No pVideo!\n"); + fflush(stdout); + } #endif - WinEndPaint(ps); + WinEndPaint(ps); #ifdef DEBUG_BUILD - printf("WM_PAINT : Done.\n"); - fflush(stdout); + printf("WM_PAINT : Done.\n"); + fflush(stdout); #endif - return 0; + return 0; case WM_SIZE: - { + { #ifdef DEBUG_BUILD - printf("WM_SIZE : (%d %d)\n", - SHORT1FROMMP(mp2), SHORT2FROMMP(mp2)); fflush(stdout); + printf("WM_SIZE : (%d %d)\n", + SHORT1FROMMP(mp2), SHORT2FROMMP(mp2)); + fflush(stdout); #endif - iWindowSizeX = SHORT1FROMMP(mp2); - iWindowSizeY = SHORT2FROMMP(mp2); - bWindowResized = 1; + iWindowSizeX = SHORT1FROMMP(mp2); + iWindowSizeY = SHORT2FROMMP(mp2); + bWindowResized = 1; - // Make sure the window will be redrawn - WinInvalidateRegion(hwnd, NULL, TRUE); - } - break; + // Make sure the window will be redrawn + WinInvalidateRegion(hwnd, NULL, TRUE); + } + break; case WM_FSLIBNOTIFICATION: #ifdef DEBUG_BUILD - printf("WM_FSLIBNOTIFICATION\n"); fflush(stdout); -#endif - if ((int)mp1 == FSLN_TOGGLEFSMODE) - { - // FS mode changed, reblit image! - pVideo = FSLib_GetUserParm(hwnd); - if (pVideo) - { - if (!pVideo->hidden->pSDLSurface) - { - // Resizable surface and in resizing! - // So, don't blit now! -#ifdef DEBUG_BUILD - printf("WM_FSLIBNOTIFICATION : Can not blit if there is no surface, doing nothing.\n"); fflush(stdout); -#endif - } else - { - if (DosRequestMutexSem(pVideo->hidden->hmtxUseSrcBuffer, 1000)==NO_ERROR) - { - if (pVideo->hidden->pSDLSurface) - { + printf("WM_FSLIBNOTIFICATION\n"); + fflush(stdout); +#endif + if ((int) mp1 == FSLN_TOGGLEFSMODE) { + // FS mode changed, reblit image! + pVideo = FSLib_GetUserParm(hwnd); + if (pVideo) { + if (!pVideo->hidden->pSDLSurface) { + // Resizable surface and in resizing! + // So, don't blit now! +#ifdef DEBUG_BUILD + printf + ("WM_FSLIBNOTIFICATION : Can not blit if there is no surface, doing nothing.\n"); + fflush(stdout); +#endif + } else { + if (DosRequestMutexSem + (pVideo->hidden->hmtxUseSrcBuffer, + 1000) == NO_ERROR) { + if (pVideo->hidden->pSDLSurface) { #ifndef RESIZE_EVEN_IF_RESIZABLE - SWP swp; - - // But only blit if the window is not resizable, or if - // the window is resizable and the source buffer size is the - // same as the destination buffer size! - WinQueryWindowPos(hwnd, &swp); - if ((!pVideo->hidden->pSDLSurface) || - ( - (pVideo->hidden->pSDLSurface) && - (pVideo->hidden->pSDLSurface->flags & SDL_RESIZABLE) && - ((swp.cx != pVideo->hidden->SrcBufferDesc.uiXResolution) || - (swp.cy != pVideo->hidden->SrcBufferDesc.uiYResolution) - ) && - (!FSLib_QueryFSMode(hwnd)) - ) - ) - { - // Resizable surface and in resizing! - // So, don't blit now! -#ifdef DEBUG_BUILD - printf("WM_FSLIBNOTIFICATION : Cannot blit while resizing, doing nothing.\n"); fflush(stdout); -#endif - } else -#endif - { -#ifdef DEBUG_BUILD - printf("WM_FSLIBNOTIFICATION : Blitting!\n"); fflush(stdout); -#endif - FSLIB_BITBLT(hwnd, pVideo->hidden->pchSrcBuffer, - 0, 0, - pVideo->hidden->SrcBufferDesc.uiXResolution, - pVideo->hidden->SrcBufferDesc.uiYResolution); + SWP swp; + + // But only blit if the window is not resizable, or if + // the window is resizable and the source buffer size is the + // same as the destination buffer size! + WinQueryWindowPos(hwnd, &swp); + if ((!pVideo->hidden->pSDLSurface) || + ((pVideo->hidden->pSDLSurface) && + (pVideo->hidden->pSDLSurface-> + flags & SDL_RESIZABLE) + && + ((swp.cx != + pVideo->hidden->SrcBufferDesc. + uiXResolution) + || (swp.cy != + pVideo->hidden-> + SrcBufferDesc.uiYResolution)) + && (!FSLib_QueryFSMode(hwnd)))) { + // Resizable surface and in resizing! + // So, don't blit now! +#ifdef DEBUG_BUILD + printf + ("WM_FSLIBNOTIFICATION : Cannot blit while resizing, doing nothing.\n"); + fflush(stdout); +#endif + } else +#endif + { +#ifdef DEBUG_BUILD + printf("WM_FSLIBNOTIFICATION : Blitting!\n"); + fflush(stdout); +#endif + FSLIB_BITBLT(hwnd, + pVideo->hidden-> + pchSrcBuffer, 0, + 0, + pVideo->hidden-> + SrcBufferDesc. + uiXResolution, + pVideo->hidden-> + SrcBufferDesc.uiYResolution); + } + } +#ifdef DEBUG_BUILD + else + printf + ("WM_FSLIBNOTIFICATION : No public surface!\n"); + fflush(stdout); +#endif + + DosReleaseMutexSem(pVideo->hidden->hmtxUseSrcBuffer); + } } - } -#ifdef DEBUG_BUILD - else - printf("WM_FSLIBNOTIFICATION : No public surface!\n"); fflush(stdout); -#endif - - DosReleaseMutexSem(pVideo->hidden->hmtxUseSrcBuffer); } - } } - } - return (MPARAM) 1; + return (MPARAM) 1; case WM_ACTIVATE: #ifdef DEBUG_BUILD - printf("WM_ACTIVATE\n"); fflush(stdout); + printf("WM_ACTIVATE\n"); + fflush(stdout); #endif - pVideo = FSLib_GetUserParm(hwnd); - if (pVideo) - { - pVideo->hidden->fInFocus = (int) mp1; - if (pVideo->hidden->fInFocus) - { - // Went into focus - if ((pVideo->hidden->iMouseVisible) && (!bMouseCaptured)) - WinSetPointer(HWND_DESKTOP, WinQuerySysPointer(HWND_DESKTOP, SPTR_ARROW, FALSE)); - else - WinSetPointer(HWND_DESKTOP, NULL); - - if (bMouseCapturable) - { - // Re-capture the mouse, if we captured it before! - WinSetCapture(HWND_DESKTOP, hwnd); - bMouseCaptured = 1; - { - SWP swpClient; - POINTL ptl; - // Center the mouse to the middle of the window! - WinQueryWindowPos(pVideo->hidden->hwndClient, &swpClient); - ptl.x = 0; ptl.y = 0; - WinMapWindowPoints(pVideo->hidden->hwndClient, HWND_DESKTOP, &ptl, 1); - pVideo->hidden->iSkipWMMOUSEMOVE++; /* Don't take next WM_MOUSEMOVE into account! */ - WinSetPointerPos(HWND_DESKTOP, - ptl.x + swpClient.cx/2, - ptl.y + swpClient.cy/2); + pVideo = FSLib_GetUserParm(hwnd); + if (pVideo) { + pVideo->hidden->fInFocus = (int) mp1; + if (pVideo->hidden->fInFocus) { + // Went into focus + if ((pVideo->hidden->iMouseVisible) + && (!bMouseCaptured)) + WinSetPointer(HWND_DESKTOP, + WinQuerySysPointer(HWND_DESKTOP, + SPTR_ARROW, FALSE)); + else + WinSetPointer(HWND_DESKTOP, NULL); + + if (bMouseCapturable) { + // Re-capture the mouse, if we captured it before! + WinSetCapture(HWND_DESKTOP, hwnd); + bMouseCaptured = 1; + { + SWP swpClient; + POINTL ptl; + // Center the mouse to the middle of the window! + WinQueryWindowPos(pVideo->hidden->hwndClient, + &swpClient); + ptl.x = 0; + ptl.y = 0; + WinMapWindowPoints(pVideo->hidden-> + hwndClient, HWND_DESKTOP, &ptl, 1); + pVideo->hidden->iSkipWMMOUSEMOVE++; /* Don't take next WM_MOUSEMOVE into account! */ + WinSetPointerPos(HWND_DESKTOP, + ptl.x + swpClient.cx / 2, + ptl.y + swpClient.cy / 2); + } + } + } else { + // Went out of focus + WinSetPointer(HWND_DESKTOP, + WinQuerySysPointer(HWND_DESKTOP, + SPTR_ARROW, FALSE)); + + if (bMouseCaptured) { + // Release the mouse + WinSetCapture(HWND_DESKTOP, hwnd); + bMouseCaptured = 0; + } } - } - } else - { - // Went out of focus - WinSetPointer(HWND_DESKTOP, WinQuerySysPointer(HWND_DESKTOP, SPTR_ARROW, FALSE)); - - if (bMouseCaptured) - { - // Release the mouse - WinSetCapture(HWND_DESKTOP, hwnd); - bMouseCaptured = 0; - } } - } #ifdef DEBUG_BUILD - printf("WM_ACTIVATE done\n"); fflush(stdout); + printf("WM_ACTIVATE done\n"); + fflush(stdout); #endif - break; + break; case WM_BUTTON1DOWN: #ifdef DEBUG_BUILD - printf("WM_BUTTON1DOWN\n"); fflush(stdout); + printf("WM_BUTTON1DOWN\n"); + fflush(stdout); #endif - pVideo = FSLib_GetUserParm(hwnd); - if (pVideo) - { - SDL_PrivateMouseButton(SDL_PRESSED, - SDL_BUTTON_LEFT, - 0, 0); // Don't report mouse movement! - - if (bMouseCapturable) - { - // We should capture the mouse! - if (!bMouseCaptured) - { - WinSetCapture(HWND_DESKTOP, hwnd); - WinSetPointer(HWND_DESKTOP, NULL); - bMouseCaptured = 1; - { - SWP swpClient; - POINTL ptl; - // Center the mouse to the middle of the window! - WinQueryWindowPos(pVideo->hidden->hwndClient, &swpClient); - ptl.x = 0; ptl.y = 0; - WinMapWindowPoints(pVideo->hidden->hwndClient, HWND_DESKTOP, &ptl, 1); - pVideo->hidden->iSkipWMMOUSEMOVE++; /* Don't take next WM_MOUSEMOVE into account! */ - WinSetPointerPos(HWND_DESKTOP, - ptl.x + swpClient.cx/2, - ptl.y + swpClient.cy/2); + pVideo = FSLib_GetUserParm(hwnd); + if (pVideo) { + SDL_PrivateMouseButton(SDL_PRESSED, SDL_BUTTON_LEFT, 0, 0); // Don't report mouse movement! + + if (bMouseCapturable) { + // We should capture the mouse! + if (!bMouseCaptured) { + WinSetCapture(HWND_DESKTOP, hwnd); + WinSetPointer(HWND_DESKTOP, NULL); + bMouseCaptured = 1; + { + SWP swpClient; + POINTL ptl; + // Center the mouse to the middle of the window! + WinQueryWindowPos(pVideo->hidden->hwndClient, + &swpClient); + ptl.x = 0; + ptl.y = 0; + WinMapWindowPoints(pVideo->hidden-> + hwndClient, HWND_DESKTOP, &ptl, 1); + pVideo->hidden->iSkipWMMOUSEMOVE++; /* Don't take next WM_MOUSEMOVE into account! */ + WinSetPointerPos(HWND_DESKTOP, + ptl.x + swpClient.cx / 2, + ptl.y + swpClient.cy / 2); + } + } } - } } - } - break; + break; case WM_BUTTON1UP: #ifdef DEBUG_BUILD - printf("WM_BUTTON1UP\n"); fflush(stdout); + printf("WM_BUTTON1UP\n"); + fflush(stdout); #endif - SDL_PrivateMouseButton(SDL_RELEASED, - SDL_BUTTON_LEFT, - 0, 0); // Don't report mouse movement! - break; + SDL_PrivateMouseButton(SDL_RELEASED, SDL_BUTTON_LEFT, 0, 0); // Don't report mouse movement! + break; case WM_BUTTON2DOWN: #ifdef DEBUG_BUILD - printf("WM_BUTTON2DOWN\n"); fflush(stdout); + printf("WM_BUTTON2DOWN\n"); + fflush(stdout); #endif - pVideo = FSLib_GetUserParm(hwnd); - if (pVideo) - { - SDL_PrivateMouseButton(SDL_PRESSED, - SDL_BUTTON_RIGHT, - 0, 0); // Don't report mouse movement! - - if (bMouseCapturable) - { - // We should capture the mouse! - if (!bMouseCaptured) - { - WinSetCapture(HWND_DESKTOP, hwnd); - WinSetPointer(HWND_DESKTOP, NULL); - bMouseCaptured = 1; - { - SWP swpClient; - POINTL ptl; - // Center the mouse to the middle of the window! - WinQueryWindowPos(pVideo->hidden->hwndClient, &swpClient); - ptl.x = 0; ptl.y = 0; - WinMapWindowPoints(pVideo->hidden->hwndClient, HWND_DESKTOP, &ptl, 1); - pVideo->hidden->iSkipWMMOUSEMOVE++; /* Don't take next WM_MOUSEMOVE into account! */ - WinSetPointerPos(HWND_DESKTOP, - ptl.x + swpClient.cx/2, - ptl.y + swpClient.cy/2); + pVideo = FSLib_GetUserParm(hwnd); + if (pVideo) { + SDL_PrivateMouseButton(SDL_PRESSED, SDL_BUTTON_RIGHT, 0, 0); // Don't report mouse movement! + + if (bMouseCapturable) { + // We should capture the mouse! + if (!bMouseCaptured) { + WinSetCapture(HWND_DESKTOP, hwnd); + WinSetPointer(HWND_DESKTOP, NULL); + bMouseCaptured = 1; + { + SWP swpClient; + POINTL ptl; + // Center the mouse to the middle of the window! + WinQueryWindowPos(pVideo->hidden->hwndClient, + &swpClient); + ptl.x = 0; + ptl.y = 0; + WinMapWindowPoints(pVideo->hidden-> + hwndClient, HWND_DESKTOP, &ptl, 1); + pVideo->hidden->iSkipWMMOUSEMOVE++; /* Don't take next WM_MOUSEMOVE into account! */ + WinSetPointerPos(HWND_DESKTOP, + ptl.x + swpClient.cx / 2, + ptl.y + swpClient.cy / 2); + } + } } - } - } - } - break; + } + break; case WM_BUTTON2UP: #ifdef DEBUG_BUILD - printf("WM_BUTTON2UP\n"); fflush(stdout); + printf("WM_BUTTON2UP\n"); + fflush(stdout); #endif - SDL_PrivateMouseButton(SDL_RELEASED, - SDL_BUTTON_RIGHT, - 0, 0); // Don't report mouse movement! - break; + SDL_PrivateMouseButton(SDL_RELEASED, SDL_BUTTON_RIGHT, 0, 0); // Don't report mouse movement! + break; case WM_BUTTON3DOWN: #ifdef DEBUG_BUILD - printf("WM_BUTTON3DOWN\n"); fflush(stdout); + printf("WM_BUTTON3DOWN\n"); + fflush(stdout); #endif - pVideo = FSLib_GetUserParm(hwnd); - if (pVideo) - { - SDL_PrivateMouseButton(SDL_PRESSED, - SDL_BUTTON_MIDDLE, - 0, 0); // Don't report mouse movement! - - if (bMouseCapturable) - { - // We should capture the mouse! - if (!bMouseCaptured) - { - WinSetCapture(HWND_DESKTOP, hwnd); - WinSetPointer(HWND_DESKTOP, NULL); - bMouseCaptured = 1; - { - SWP swpClient; - POINTL ptl; - // Center the mouse to the middle of the window! - WinQueryWindowPos(pVideo->hidden->hwndClient, &swpClient); - ptl.x = 0; ptl.y = 0; - WinMapWindowPoints(pVideo->hidden->hwndClient, HWND_DESKTOP, &ptl, 1); - pVideo->hidden->iSkipWMMOUSEMOVE++; /* Don't take next WM_MOUSEMOVE into account! */ - WinSetPointerPos(HWND_DESKTOP, - ptl.x + swpClient.cx/2, - ptl.y + swpClient.cy/2); + pVideo = FSLib_GetUserParm(hwnd); + if (pVideo) { + SDL_PrivateMouseButton(SDL_PRESSED, SDL_BUTTON_MIDDLE, 0, 0); // Don't report mouse movement! + + if (bMouseCapturable) { + // We should capture the mouse! + if (!bMouseCaptured) { + WinSetCapture(HWND_DESKTOP, hwnd); + WinSetPointer(HWND_DESKTOP, NULL); + bMouseCaptured = 1; + { + SWP swpClient; + POINTL ptl; + // Center the mouse to the middle of the window! + WinQueryWindowPos(pVideo->hidden->hwndClient, + &swpClient); + ptl.x = 0; + ptl.y = 0; + WinMapWindowPoints(pVideo->hidden-> + hwndClient, HWND_DESKTOP, &ptl, 1); + pVideo->hidden->iSkipWMMOUSEMOVE++; /* Don't take next WM_MOUSEMOVE into account! */ + WinSetPointerPos(HWND_DESKTOP, + ptl.x + swpClient.cx / 2, + ptl.y + swpClient.cy / 2); + } + } } - } } - } - break; + break; case WM_BUTTON3UP: #ifdef DEBUG_BUILD - printf("WM_BUTTON3UP\n"); fflush(stdout); + printf("WM_BUTTON3UP\n"); + fflush(stdout); #endif - SDL_PrivateMouseButton(SDL_RELEASED, - SDL_BUTTON_MIDDLE, - 0, 0); // Don't report mouse movement! - break; + SDL_PrivateMouseButton(SDL_RELEASED, SDL_BUTTON_MIDDLE, 0, 0); // Don't report mouse movement! + break; case WM_MOUSEMOVE: #ifdef DEBUG_BUILD // printf("WM_MOUSEMOVE\n"); fflush(stdout); #endif - pVideo = FSLib_GetUserParm(hwnd); - if (pVideo) - { - if (pVideo->hidden->iSkipWMMOUSEMOVE) - { - pVideo->hidden->iSkipWMMOUSEMOVE--; - } else - { - POINTS *ppts = (POINTS *) (&mp1); - POINTL ptl; - - if (bMouseCaptured) - { - SWP swpClient; - - WinQueryWindowPos(pVideo->hidden->hwndClient, &swpClient); - - // Send relative mouse position, and re-center the mouse - // Reposition the mouse to the center of the screen/window - SDL_PrivateMouseMotion(0, // Buttons not changed - 1, // Relative position - ppts->x - (swpClient.cx/2), - (swpClient.cy/2) - ppts->y); - - ptl.x = 0; ptl.y = 0; - WinMapWindowPoints(pVideo->hidden->hwndClient, HWND_DESKTOP, &ptl, 1); - pVideo->hidden->iSkipWMMOUSEMOVE++; /* Don't take next WM_MOUSEMOVE into account! */ - // Center the mouse to the middle of the window! - WinSetPointerPos(HWND_DESKTOP, - ptl.x + swpClient.cx/2, - ptl.y + swpClient.cy/2); - } else - { - CONVERTMOUSEPOSITION(); - - // Send absolute mouse position - SDL_PrivateMouseMotion(0, // Buttons not changed - 0, // Absolute position - ppts->x, - ppts->y); - } - } - if ((pVideo->hidden->iMouseVisible) && (!bMouseCaptured)) - { + pVideo = FSLib_GetUserParm(hwnd); + if (pVideo) { + if (pVideo->hidden->iSkipWMMOUSEMOVE) { + pVideo->hidden->iSkipWMMOUSEMOVE--; + } else { + POINTS *ppts = (POINTS *) (&mp1); + POINTL ptl; + + if (bMouseCaptured) { + SWP swpClient; + + WinQueryWindowPos(pVideo->hidden->hwndClient, &swpClient); + + // Send relative mouse position, and re-center the mouse + // Reposition the mouse to the center of the screen/window + SDL_PrivateMouseMotion(0, // Buttons not changed + 1, // Relative position + ppts->x - + (swpClient.cx / 2), + (swpClient.cy / 2) - ppts->y); + + ptl.x = 0; + ptl.y = 0; + WinMapWindowPoints(pVideo->hidden->hwndClient, + HWND_DESKTOP, &ptl, 1); + pVideo->hidden->iSkipWMMOUSEMOVE++; /* Don't take next WM_MOUSEMOVE into account! */ + // Center the mouse to the middle of the window! + WinSetPointerPos(HWND_DESKTOP, + ptl.x + swpClient.cx / 2, + ptl.y + swpClient.cy / 2); + } else { + CONVERTMOUSEPOSITION(); + + // Send absolute mouse position + SDL_PrivateMouseMotion(0, // Buttons not changed + 0, // Absolute position + ppts->x, ppts->y); + } + } + if ((pVideo->hidden->iMouseVisible) && (!bMouseCaptured)) { #ifdef DEBUG_BUILD // printf("WM_MOUSEMOVE : ptr = %p\n", hptrGlobalPointer); fflush(stdout); #endif - if (hptrGlobalPointer) - WinSetPointer(HWND_DESKTOP, hptrGlobalPointer); - else - WinSetPointer(HWND_DESKTOP, WinQuerySysPointer(HWND_DESKTOP, SPTR_ARROW, FALSE)); - } - else - { - WinSetPointer(HWND_DESKTOP, NULL); + if (hptrGlobalPointer) + WinSetPointer(HWND_DESKTOP, hptrGlobalPointer); + else + WinSetPointer(HWND_DESKTOP, + WinQuerySysPointer(HWND_DESKTOP, + SPTR_ARROW, FALSE)); + } else { + WinSetPointer(HWND_DESKTOP, NULL); + } } - } #ifdef DEBUG_BUILD // printf("WM_MOUSEMOVE done\n"); fflush(stdout); #endif - return (MRESULT) FALSE; - case WM_CLOSE: // Window close + return (MRESULT) FALSE; + case WM_CLOSE: // Window close #ifdef DEBUG_BUILD - printf("WM_CLOSE\n"); fflush(stdout); + printf("WM_CLOSE\n"); + fflush(stdout); #endif - pVideo = FSLib_GetUserParm(hwnd); - if (pVideo) - { - // Send Quit message to the SDL application! - SDL_PrivateQuit(); - return 0; - } - break; + pVideo = FSLib_GetUserParm(hwnd); + if (pVideo) { + // Send Quit message to the SDL application! + SDL_PrivateQuit(); + return 0; + } + break; #ifdef BITBLT_IN_WINMESSAGEPROC case WM_UPDATERECTSREQUEST: - pVideo = FSLib_GetUserParm(hwnd); - if ((pVideo) && (pVideo->hidden->pSDLSurface)) - { - if (DosRequestMutexSem(pVideo->hidden->hmtxUseSrcBuffer, SEM_INDEFINITE_WAIT)==NO_ERROR) - { - int numrects; - SDL_Rect *rects; - int i; - SWP swp; + pVideo = FSLib_GetUserParm(hwnd); + if ((pVideo) && (pVideo->hidden->pSDLSurface)) { + if (DosRequestMutexSem + (pVideo->hidden->hmtxUseSrcBuffer, + SEM_INDEFINITE_WAIT) == NO_ERROR) { + int numrects; + SDL_Rect *rects; + int i; + SWP swp; - numrects = (int) mp1; - rects = (SDL_Rect *) mp2; + numrects = (int) mp1; + rects = (SDL_Rect *) mp2; - WinQueryWindowPos(hwnd, &swp); + WinQueryWindowPos(hwnd, &swp); #ifndef RESIZE_EVEN_IF_RESIZABLE - if ((!pVideo->hidden->pSDLSurface) || - ( - (pVideo->hidden->pSDLSurface) && - (pVideo->hidden->pSDLSurface->flags & SDL_RESIZABLE) && - ((swp.cx != pVideo->hidden->SrcBufferDesc.uiXResolution) || - (swp.cy != pVideo->hidden->SrcBufferDesc.uiYResolution) - ) && - (!FSLib_QueryFSMode(hwnd)) - ) - ) - { - // Resizable surface and in resizing! - // So, don't blit now! -#ifdef DEBUG_BUILD - printf("[WM_UPDATERECTSREQUEST] : Skipping blit while resizing!\n"); fflush(stdout); -#endif - } else -#endif - { -#ifdef DEBUG_BUILD - printf("[WM_UPDATERECTSREQUEST] : Blitting!\n"); fflush(stdout); -#endif - - // Blit the changed areas - for (i=0; ihidden->pchSrcBuffer, - rects[i].y, rects[i].x, rects[i].w, rects[i].h); - } - DosReleaseMutexSem(pVideo->hidden->hmtxUseSrcBuffer); + if ((!pVideo->hidden->pSDLSurface) || + ((pVideo->hidden->pSDLSurface) && + (pVideo->hidden->pSDLSurface->flags & SDL_RESIZABLE) + && + ((swp.cx != pVideo->hidden->SrcBufferDesc.uiXResolution) + || (swp.cy != + pVideo->hidden->SrcBufferDesc.uiYResolution)) + && (!FSLib_QueryFSMode(hwnd)))) { + // Resizable surface and in resizing! + // So, don't blit now! +#ifdef DEBUG_BUILD + printf + ("[WM_UPDATERECTSREQUEST] : Skipping blit while resizing!\n"); + fflush(stdout); +#endif + } else +#endif + { +#ifdef DEBUG_BUILD + printf("[WM_UPDATERECTSREQUEST] : Blitting!\n"); + fflush(stdout); +#endif + + // Blit the changed areas + for (i = 0; i < numrects; i++) + FSLIB_BITBLT(hwnd, + pVideo->hidden->pchSrcBuffer, + rects[i].y, rects[i].x, + rects[i].w, rects[i].h); + } + DosReleaseMutexSem(pVideo->hidden->hmtxUseSrcBuffer); + } } - } - return 0; + return 0; #endif default: #ifdef DEBUG_BUILD - printf("Unhandled: %x\n", msg); fflush(stdout); + printf("Unhandled: %x\n", msg); + fflush(stdout); #endif - break; - } - // Run the default window procedure for unhandled stuffs - return WinDefWindowProc(hwnd, msg, mp1, mp2); + break; + } + // Run the default window procedure for unhandled stuffs + return WinDefWindowProc(hwnd, msg, mp1, mp2); } ///////////////////////////////////////////////////////////////////// @@ -1049,88 +1079,88 @@ static MRESULT EXPENTRY WndProc( HWND hwnd, ULONG msg, MPARAM mp1, MPARAM mp2) // frame window of SDLWindowClass. // ///////////////////////////////////////////////////////////////////// -static MRESULT EXPENTRY FrameWndProc( HWND hwnd, ULONG msg, MPARAM mp1, MPARAM mp2) +static MRESULT EXPENTRY +FrameWndProc(HWND hwnd, ULONG msg, MPARAM mp1, MPARAM mp2) { - PFNWP pOldFrameProc; - MRESULT result; - PTRACKINFO ti; - int cx, cy, ncx, ncy; - RECTL rclTemp; - PSWP pswpTemp; - - SDL_VideoDevice *pVideo = NULL; - - pVideo = (SDL_VideoDevice *) WinQueryWindowULong(hwnd, QWL_USER); - - pOldFrameProc = pVideo->hidden->pfnOldFrameProc; - - if ((pVideo->hidden->bProportionalResize) && - (msg==WM_ADJUSTWINDOWPOS) && - (!FSLib_QueryFSMode(pVideo->hidden->hwndClient)) - ) - { - pswpTemp = (PSWP) mp1; - - /* Resizing? */ - if (pswpTemp->fl & SWP_SIZE) - { - /* Calculate client size */ - rclTemp.xLeft = pswpTemp->x; - rclTemp.xRight = pswpTemp->x + pswpTemp->cx; - rclTemp.yBottom = pswpTemp->y; - rclTemp.yTop = pswpTemp->y + pswpTemp->cy; - WinCalcFrameRect(hwnd, &rclTemp, TRUE); - - ncx = cx = rclTemp.xRight - rclTemp.xLeft; - ncy = cy = rclTemp.yTop - rclTemp.yBottom; - - /* Calculate new size to keep it proportional */ - - if ((pVideo->hidden->ulResizingFlag & TF_LEFT) || (pVideo->hidden->ulResizingFlag & TF_RIGHT)) - { - /* The window is resized horizontally */ - ncy = pVideo->hidden->SrcBufferDesc.uiYResolution * cx / pVideo->hidden->SrcBufferDesc.uiXResolution; - } else - if ((pVideo->hidden->ulResizingFlag & TF_TOP) || (pVideo->hidden->ulResizingFlag & TF_BOTTOM)) - { - /* The window is resized vertically */ - ncx = pVideo->hidden->SrcBufferDesc.uiXResolution * cy / pVideo->hidden->SrcBufferDesc.uiYResolution; - } - - /* Calculate back frame coordinates */ - rclTemp.xLeft = pswpTemp->x; - rclTemp.xRight = pswpTemp->x + ncx; - rclTemp.yBottom = pswpTemp->y; - rclTemp.yTop = pswpTemp->y + ncy; - WinCalcFrameRect(hwnd, &rclTemp, FALSE); - - /* Store new size/position info */ - pswpTemp->cx = rclTemp.xRight - rclTemp.xLeft; - - if (!(pVideo->hidden->ulResizingFlag & TF_TOP)) - { - pswpTemp->y = pswpTemp->y + pswpTemp->cy - (rclTemp.yTop - rclTemp.yBottom); - pswpTemp->cy = rclTemp.yTop - rclTemp.yBottom; - } else - { - pswpTemp->cy = rclTemp.yTop - rclTemp.yBottom; - } + PFNWP pOldFrameProc; + MRESULT result; + PTRACKINFO ti; + int cx, cy, ncx, ncy; + RECTL rclTemp; + PSWP pswpTemp; + + SDL_VideoDevice *pVideo = NULL; + + pVideo = (SDL_VideoDevice *) WinQueryWindowULong(hwnd, QWL_USER); + + pOldFrameProc = pVideo->hidden->pfnOldFrameProc; + + if ((pVideo->hidden->bProportionalResize) && + (msg == WM_ADJUSTWINDOWPOS) && + (!FSLib_QueryFSMode(pVideo->hidden->hwndClient))) { + pswpTemp = (PSWP) mp1; + + /* Resizing? */ + if (pswpTemp->fl & SWP_SIZE) { + /* Calculate client size */ + rclTemp.xLeft = pswpTemp->x; + rclTemp.xRight = pswpTemp->x + pswpTemp->cx; + rclTemp.yBottom = pswpTemp->y; + rclTemp.yTop = pswpTemp->y + pswpTemp->cy; + WinCalcFrameRect(hwnd, &rclTemp, TRUE); + + ncx = cx = rclTemp.xRight - rclTemp.xLeft; + ncy = cy = rclTemp.yTop - rclTemp.yBottom; + + /* Calculate new size to keep it proportional */ + + if ((pVideo->hidden->ulResizingFlag & TF_LEFT) + || (pVideo->hidden->ulResizingFlag & TF_RIGHT)) { + /* The window is resized horizontally */ + ncy = + pVideo->hidden->SrcBufferDesc.uiYResolution * cx / + pVideo->hidden->SrcBufferDesc.uiXResolution; + } else if ((pVideo->hidden->ulResizingFlag & TF_TOP) + || (pVideo->hidden->ulResizingFlag & TF_BOTTOM)) { + /* The window is resized vertically */ + ncx = + pVideo->hidden->SrcBufferDesc.uiXResolution * cy / + pVideo->hidden->SrcBufferDesc.uiYResolution; + } + + /* Calculate back frame coordinates */ + rclTemp.xLeft = pswpTemp->x; + rclTemp.xRight = pswpTemp->x + ncx; + rclTemp.yBottom = pswpTemp->y; + rclTemp.yTop = pswpTemp->y + ncy; + WinCalcFrameRect(hwnd, &rclTemp, FALSE); + + /* Store new size/position info */ + pswpTemp->cx = rclTemp.xRight - rclTemp.xLeft; + + if (!(pVideo->hidden->ulResizingFlag & TF_TOP)) { + pswpTemp->y = + pswpTemp->y + pswpTemp->cy - (rclTemp.yTop - + rclTemp.yBottom); + pswpTemp->cy = rclTemp.yTop - rclTemp.yBottom; + } else { + pswpTemp->cy = rclTemp.yTop - rclTemp.yBottom; + } + } } - } - result = (*pOldFrameProc)(hwnd, msg, mp1, mp2); + result = (*pOldFrameProc) (hwnd, msg, mp1, mp2); - if ((pVideo->hidden->bProportionalResize) && (msg==WM_QUERYTRACKINFO)) - { - ti = (PTRACKINFO) mp2; + if ((pVideo->hidden->bProportionalResize) && (msg == WM_QUERYTRACKINFO)) { + ti = (PTRACKINFO) mp2; - /* Store the direction of resizing */ - if ((ti->fs & TF_LEFT) || (ti->fs & TF_RIGHT) || - (ti->fs & TF_TOP) || (ti->fs & TF_BOTTOM)) - pVideo->hidden->ulResizingFlag = ti->fs; - } + /* Store the direction of resizing */ + if ((ti->fs & TF_LEFT) || (ti->fs & TF_RIGHT) || + (ti->fs & TF_TOP) || (ti->fs & TF_BOTTOM)) + pVideo->hidden->ulResizingFlag = ti->fs; + } - return result; + return result; } ///////////////////////////////////////////////////////////////////// @@ -1141,392 +1171,419 @@ static MRESULT EXPENTRY FrameWndProc( HWND hwnd, ULONG msg, MPARAM mp1, MPARAM m // application window itself, the DIVE, and start message processing. // ///////////////////////////////////////////////////////////////////// -int iNumOfPMThreadInstances = 0; // Global! -static void PMThreadFunc(void *pParm) +int iNumOfPMThreadInstances = 0; // Global! +static void +PMThreadFunc(void *pParm) { - SDL_VideoDevice *pVideo = pParm; - HAB hab; - HMQ hmq; - QMSG msg; - ULONG fcf; + SDL_VideoDevice *pVideo = pParm; + HAB hab; + HMQ hmq; + QMSG msg; + ULONG fcf; #ifdef DEBUG_BUILD - printf("[PMThreadFunc] : Starting\n"); fflush(stdout); + printf("[PMThreadFunc] : Starting\n"); + fflush(stdout); #endif - iNumOfPMThreadInstances++; + iNumOfPMThreadInstances++; - // Initialize PM, create a message queue. + // Initialize PM, create a message queue. - hab=WinInitialize(0); - hmq=WinCreateMsgQueue(hab,0); - if (hmq==0) - { + hab = WinInitialize(0); + hmq = WinCreateMsgQueue(hab, 0); + if (hmq == 0) { #ifdef DEBUG_BUILD - printf("[PMThreadFunc] : Could not create message queue!\n"); - printf(" It might be that the application using SDL is not a PM app!\n"); - fflush(stdout); + printf("[PMThreadFunc] : Could not create message queue!\n"); + printf + (" It might be that the application using SDL is not a PM app!\n"); + fflush(stdout); #endif - pVideo->hidden->iPMThreadStatus = 2; - } else - { - int rc; - RECTL rectl; + pVideo->hidden->iPMThreadStatus = 2; + } else { + int rc; + RECTL rectl; - fcf = ulFCFToUse; // Get from global setting + fcf = ulFCFToUse; // Get from global setting #ifdef DEBUG_BUILD - printf("[PMThreadFunc] : FSLib_CreateWindow()!\n"); - fflush(stdout); + printf("[PMThreadFunc] : FSLib_CreateWindow()!\n"); + fflush(stdout); #endif - rc = FSLib_CreateWindow(HWND_DESKTOP, 0, &fcf, - "SDL Application", - NULLHANDLE, 0, - &(pVideo->hidden->SrcBufferDesc), - WndProc, - &(pVideo->hidden->hwndClient), - &(pVideo->hidden->hwndFrame)); + rc = FSLib_CreateWindow(HWND_DESKTOP, 0, &fcf, + "SDL Application", + NULLHANDLE, 0, + &(pVideo->hidden->SrcBufferDesc), + WndProc, + &(pVideo->hidden->hwndClient), + &(pVideo->hidden->hwndFrame)); #ifdef DEBUG_BUILD - printf("[PMThreadFunc] : FSLib_CreateWindow() rc = %d\n", rc); - fflush(stdout); + printf("[PMThreadFunc] : FSLib_CreateWindow() rc = %d\n", rc); + fflush(stdout); #endif - if (!rc) - { + if (!rc) { #ifdef DEBUG_BUILD - printf("[PMThreadFunc] : Could not create FSLib window!\n"); - fflush(stdout); + printf("[PMThreadFunc] : Could not create FSLib window!\n"); + fflush(stdout); #endif - pVideo->hidden->iPMThreadStatus = 3; - } else - { + pVideo->hidden->iPMThreadStatus = 3; + } else { #ifdef DEBUG_BUILD - printf("[PMThreadFunc] : FSLib_AddUserParm()!\n"); - fflush(stdout); + printf("[PMThreadFunc] : FSLib_AddUserParm()!\n"); + fflush(stdout); #endif - // Store pVideo pointer in window data for client window, so - // it will know the instance to which it belongs to. - FSLib_AddUserParm(pVideo->hidden->hwndClient, pVideo); + // Store pVideo pointer in window data for client window, so + // it will know the instance to which it belongs to. + FSLib_AddUserParm(pVideo->hidden->hwndClient, pVideo); - // Now set default image width height and fourcc! + // Now set default image width height and fourcc! #ifdef DEBUG_BUILD - printf("[PMThreadFunc] : SetWindowPos()!\n"); - fflush(stdout); + printf("[PMThreadFunc] : SetWindowPos()!\n"); + fflush(stdout); #endif - // Set the position and size of the main window, - // and make it visible! - // Calculate frame window size from client window size - rectl.xLeft = 0; - rectl.yBottom = 0; - rectl.xRight = pVideo->hidden->SrcBufferDesc.uiXResolution; // Noninclusive - rectl.yTop = pVideo->hidden->SrcBufferDesc.uiYResolution; // Noninclusive - WinCalcFrameRect(pVideo->hidden->hwndFrame, &rectl, FALSE); - - SetAccessableWindowPos(pVideo->hidden->hwndFrame, - HWND_TOP, - (WinQuerySysValue (HWND_DESKTOP, SV_CXSCREEN) - (rectl.xRight-rectl.xLeft)) / 2, - (WinQuerySysValue (HWND_DESKTOP, SV_CYSCREEN) - (rectl.yTop-rectl.yBottom)) / 2, - (rectl.xRight-rectl.xLeft), - (rectl.yTop-rectl.yBottom), - SWP_SIZE | SWP_ACTIVATE | SWP_SHOW | SWP_MOVE); + // Set the position and size of the main window, + // and make it visible! + // Calculate frame window size from client window size + rectl.xLeft = 0; + rectl.yBottom = 0; + rectl.xRight = pVideo->hidden->SrcBufferDesc.uiXResolution; // Noninclusive + rectl.yTop = pVideo->hidden->SrcBufferDesc.uiYResolution; // Noninclusive + WinCalcFrameRect(pVideo->hidden->hwndFrame, &rectl, FALSE); + + SetAccessableWindowPos(pVideo->hidden->hwndFrame, + HWND_TOP, + (WinQuerySysValue + (HWND_DESKTOP, + SV_CXSCREEN) - (rectl.xRight - + rectl.xLeft)) / 2, + (WinQuerySysValue + (HWND_DESKTOP, + SV_CYSCREEN) - (rectl.yTop - + rectl.yBottom)) / 2, + (rectl.xRight - rectl.xLeft), + (rectl.yTop - rectl.yBottom), + SWP_SIZE | SWP_ACTIVATE | SWP_SHOW | + SWP_MOVE); + + // Subclass frame procedure and store old window proc address + pVideo->hidden->pfnOldFrameProc = + WinSubclassWindow(pVideo->hidden->hwndFrame, FrameWndProc); + WinSetWindowULong(pVideo->hidden->hwndFrame, QWL_USER, + (ULONG) pVideo); + +#ifdef DEBUG_BUILD + printf("[PMThreadFunc] : Entering message loop\n"); + fflush(stdout); +#endif + pVideo->hidden->iPMThreadStatus = 1; - // Subclass frame procedure and store old window proc address - pVideo->hidden->pfnOldFrameProc = - WinSubclassWindow(pVideo->hidden->hwndFrame, FrameWndProc); - WinSetWindowULong(pVideo->hidden->hwndFrame, QWL_USER, (ULONG) pVideo); + while (WinGetMsg(hab, (PQMSG) & msg, 0, 0, 0)) + WinDispatchMsg(hab, (PQMSG) & msg); #ifdef DEBUG_BUILD - printf("[PMThreadFunc] : Entering message loop\n"); fflush(stdout); + printf("[PMThreadFunc] : Leaving message loop\n"); + fflush(stdout); #endif - pVideo->hidden->iPMThreadStatus = 1; - - while (WinGetMsg(hab, (PQMSG)&msg, 0, 0, 0)) - WinDispatchMsg(hab, (PQMSG) &msg); - + // We should release the captured the mouse! + if (bMouseCaptured) { + WinSetCapture(HWND_DESKTOP, NULLHANDLE); + bMouseCaptured = 0; + } + // Destroy our window + WinDestroyWindow(pVideo->hidden->hwndFrame); + pVideo->hidden->hwndFrame = NULL; + // Show pointer to make sure it will not be left hidden. + WinSetPointer(HWND_DESKTOP, + WinQuerySysPointer(HWND_DESKTOP, SPTR_ARROW, + FALSE)); + WinShowPointer(HWND_DESKTOP, TRUE); + } + // Uninitialize PM + WinDestroyMsgQueue(hmq); + // All done! + pVideo->hidden->iPMThreadStatus = 0; + } + WinTerminate(hab); + /* Commented out, should not be needed anymore, because we send it + from WM_CLOSE. + // Notify SDL that it should really die now... + SDL_PrivateQuit(); SDL_PrivateQuit(); SDL_PrivateQuit(); //... :)) + */ #ifdef DEBUG_BUILD - printf("[PMThreadFunc] : Leaving message loop\n"); fflush(stdout); + printf("[PMThreadFunc] : End, status is %d!\n", + pVideo->hidden->iPMThreadStatus); + fflush(stdout); #endif - // We should release the captured the mouse! - if (bMouseCaptured) - { - WinSetCapture(HWND_DESKTOP, NULLHANDLE); - bMouseCaptured = 0; - } - // Destroy our window - WinDestroyWindow(pVideo->hidden->hwndFrame); pVideo->hidden->hwndFrame=NULL; - // Show pointer to make sure it will not be left hidden. - WinSetPointer(HWND_DESKTOP, WinQuerySysPointer(HWND_DESKTOP, SPTR_ARROW, FALSE)); - WinShowPointer(HWND_DESKTOP, TRUE); - } - // Uninitialize PM - WinDestroyMsgQueue(hmq); - // All done! - pVideo->hidden->iPMThreadStatus = 0; - } - WinTerminate(hab); - /* Commented out, should not be needed anymore, because we send it - from WM_CLOSE. - // Notify SDL that it should really die now... - SDL_PrivateQuit(); SDL_PrivateQuit(); SDL_PrivateQuit(); //... :)) - */ -#ifdef DEBUG_BUILD - printf("[PMThreadFunc] : End, status is %d!\n", pVideo->hidden->iPMThreadStatus); fflush(stdout); -#endif - - iNumOfPMThreadInstances--; - - // HACK to prevent zombie and hanging SDL applications, which does not take - // care of closing the window for some reason: - // There are some apps which do not process messages, so do a lot of things - // without noticing that the application should close. To close these, - // I've thought about the following: - // If the window is closed (the execution came here), I wait a bit to - // give time to the app to finish its execution. If it does not, I kill it - // using DosExit(). Brute force, but should work. - if (pVideo->hidden->iPMThreadStatus==0) - { - DosSleep(5000); // Wait 5 secs - // If a new PM thread has been spawned (reinitializing video mode), then all right. - // Otherwise, we have a problem, the app doesn't want to stop. Kill! - if (iNumOfPMThreadInstances==0) - { -#ifdef DEBUG_BUILD - printf("[PMThreadFunc] : It seems that the application haven't terminated itself\n"); fflush(stdout); - printf("[PMThreadFunc] : in the last 5 seconds, so we go berserk.\n"); fflush(stdout); - printf("[PMThreadFunc] : Brute force mode. :) Killing process! Dieeeee...\n"); fflush(stdout); -#endif - DosExit(EXIT_PROCESS, -1); + + iNumOfPMThreadInstances--; + + // HACK to prevent zombie and hanging SDL applications, which does not take + // care of closing the window for some reason: + // There are some apps which do not process messages, so do a lot of things + // without noticing that the application should close. To close these, + // I've thought about the following: + // If the window is closed (the execution came here), I wait a bit to + // give time to the app to finish its execution. If it does not, I kill it + // using DosExit(). Brute force, but should work. + if (pVideo->hidden->iPMThreadStatus == 0) { + DosSleep(5000); // Wait 5 secs + // If a new PM thread has been spawned (reinitializing video mode), then all right. + // Otherwise, we have a problem, the app doesn't want to stop. Kill! + if (iNumOfPMThreadInstances == 0) { +#ifdef DEBUG_BUILD + printf + ("[PMThreadFunc] : It seems that the application haven't terminated itself\n"); + fflush(stdout); + printf + ("[PMThreadFunc] : in the last 5 seconds, so we go berserk.\n"); + fflush(stdout); + printf + ("[PMThreadFunc] : Brute force mode. :) Killing process! Dieeeee...\n"); + fflush(stdout); +#endif + DosExit(EXIT_PROCESS, -1); + } } - } - _endthread(); + _endthread(); } struct WMcursor { - HBITMAP hbm; - HPOINTER hptr; - char *pchData; + HBITMAP hbm; + HPOINTER hptr; + char *pchData; }; /* Free a window manager cursor */ -void os2fslib_FreeWMCursor(_THIS, WMcursor *cursor) +void +os2fslib_FreeWMCursor(_THIS, WMcursor * cursor) { - if (cursor) - { - GpiDeleteBitmap(cursor->hbm); - WinDestroyPointer(cursor->hptr); - SDL_free(cursor->pchData); - SDL_free(cursor); - } + if (cursor) { + GpiDeleteBitmap(cursor->hbm); + WinDestroyPointer(cursor->hptr); + SDL_free(cursor->pchData); + SDL_free(cursor); + } } /* Local functions to convert the SDL cursor mask into OS/2 format */ -static void memnot(Uint8 *dst, Uint8 *src, int len) +static void +memnot(Uint8 * dst, Uint8 * src, int len) { - while ( len-- > 0 ) - *dst++ = ~*src++; + while (len-- > 0) + *dst++ = ~*src++; } -static void memxor(Uint8 *dst, Uint8 *src1, Uint8 *src2, int len) +static void +memxor(Uint8 * dst, Uint8 * src1, Uint8 * src2, int len) { - while ( len-- > 0 ) - *dst++ = (*src1++)^(*src2++); + while (len-- > 0) + *dst++ = (*src1++) ^ (*src2++); } /* Create a black/white window manager cursor */ -WMcursor *os2fslib_CreateWMCursor_Win(_THIS, Uint8 *data, Uint8 *mask, - int w, int h, int hot_x, int hot_y) +WMcursor * +os2fslib_CreateWMCursor_Win(_THIS, Uint8 * data, Uint8 * mask, + int w, int h, int hot_x, int hot_y) { - HPOINTER hptr; - HBITMAP hbm; - BITMAPINFOHEADER bmih; - BMPINFO bmi; - HPS hps; - char *pchTemp; - char *xptr, *aptr; - int maxx, maxy; - int i, run, pad; - WMcursor *pResult; - - maxx = WinQuerySysValue(HWND_DESKTOP, SV_CXPOINTER); - maxy = WinQuerySysValue(HWND_DESKTOP, SV_CYPOINTER); - - // Check for max size! - if ((w>maxx) || (h>maxy)) - return (WMcursor *) NULL; - - pResult = (WMcursor *) SDL_malloc(sizeof(WMcursor)); - if (!pResult) return (WMcursor *) NULL; - - pchTemp = (char *) SDL_malloc((maxx + 7)/8 * maxy*2); - if (!pchTemp) - { - SDL_free(pResult); - return (WMcursor *) NULL; - } - - SDL_memset(pchTemp, 0, (maxx + 7)/8 * maxy*2); - - hps = WinGetPS(_this->hidden->hwndClient); - - bmi.cbFix = sizeof(BITMAPINFOHEADER); - bmi.cx = maxx; - bmi.cy = 2*maxy; - bmi.cPlanes = 1; - bmi.cBitCount = 1; - bmi.argbColor[0].bBlue = 0x00; - bmi.argbColor[0].bGreen = 0x00; - bmi.argbColor[0].bRed = 0x00; - bmi.argbColor[1].bBlue = 0x00; - bmi.argbColor[1].bGreen = 0x00; - bmi.argbColor[1].bRed = 0xff; - - SDL_memset(&bmih, 0, sizeof(BITMAPINFOHEADER)); - bmih.cbFix = sizeof(BITMAPINFOHEADER); - bmih.cx = maxx; - bmih.cy = 2*maxy; - bmih.cPlanes = 1; - bmih.cBitCount = 1; - - run = (w+7)/8; - pad = (maxx+7)/8 - run; - - for (i=0; i maxx) || (h > maxy)) + return (WMcursor *) NULL; + + pResult = (WMcursor *) SDL_malloc(sizeof(WMcursor)); + if (!pResult) + return (WMcursor *) NULL; + + pchTemp = (char *) SDL_malloc((maxx + 7) / 8 * maxy * 2); + if (!pchTemp) { + SDL_free(pResult); + return (WMcursor *) NULL; + } - SDL_memset(xptr, 0, (maxx+7)/8); - xptr += (maxx+7)/8; - SDL_memset(aptr, ~0, (maxx+7)/8); - aptr += (maxx+7)/8; - } + SDL_memset(pchTemp, 0, (maxx + 7) / 8 * maxy * 2); + + hps = WinGetPS(_this->hidden->hwndClient); + + bmi.cbFix = sizeof(BITMAPINFOHEADER); + bmi.cx = maxx; + bmi.cy = 2 * maxy; + bmi.cPlanes = 1; + bmi.cBitCount = 1; + bmi.argbColor[0].bBlue = 0x00; + bmi.argbColor[0].bGreen = 0x00; + bmi.argbColor[0].bRed = 0x00; + bmi.argbColor[1].bBlue = 0x00; + bmi.argbColor[1].bGreen = 0x00; + bmi.argbColor[1].bRed = 0xff; + + SDL_memset(&bmih, 0, sizeof(BITMAPINFOHEADER)); + bmih.cbFix = sizeof(BITMAPINFOHEADER); + bmih.cx = maxx; + bmih.cy = 2 * maxy; + bmih.cPlanes = 1; + bmih.cBitCount = 1; + + run = (w + 7) / 8; + pad = (maxx + 7) / 8 - run; + + for (i = 0; i < h; i++) { + xptr = pchTemp + (maxx + 7) / 8 * (maxy - 1 - i); + aptr = pchTemp + (maxx + 7) / 8 * (maxy + maxy - 1 - i); + memxor(xptr, data, mask, run); + xptr += run; + data += run; + memnot(aptr, mask, run); + mask += run; + aptr += run; + SDL_memset(xptr, 0, pad); + xptr += pad; + SDL_memset(aptr, ~0, pad); + aptr += pad; + } + pad += run; + for (i = h; i < maxy; i++) { + xptr = pchTemp + (maxx + 7) / 8 * (maxy - 1 - i); + aptr = pchTemp + (maxx + 7) / 8 * (maxy + maxy - 1 - i); + + SDL_memset(xptr, 0, (maxx + 7) / 8); + xptr += (maxx + 7) / 8; + SDL_memset(aptr, ~0, (maxx + 7) / 8); + aptr += (maxx + 7) / 8; + } - hbm = GpiCreateBitmap(hps, (PBITMAPINFOHEADER2)&bmih, CBM_INIT, (PBYTE) pchTemp, (PBITMAPINFO2)&bmi); - hptr = WinCreatePointer(HWND_DESKTOP, hbm, TRUE, hot_x, maxy - hot_y - 1); + hbm = + GpiCreateBitmap(hps, (PBITMAPINFOHEADER2) & bmih, CBM_INIT, + (PBYTE) pchTemp, (PBITMAPINFO2) & bmi); + hptr = WinCreatePointer(HWND_DESKTOP, hbm, TRUE, hot_x, maxy - hot_y - 1); #ifdef DEBUG_BUILD - printf("HotSpot : %d ; %d\n", hot_x, hot_y); - printf("HPS returned : %x\n", (ULONG)hps); - printf("HBITMAP returned : %x\n", (ULONG)hbm); - printf("HPOINTER returned: %x\n", (ULONG)hptr); + printf("HotSpot : %d ; %d\n", hot_x, hot_y); + printf("HPS returned : %x\n", (ULONG) hps); + printf("HBITMAP returned : %x\n", (ULONG) hbm); + printf("HPOINTER returned: %x\n", (ULONG) hptr); #endif - WinReleasePS(hps); + WinReleasePS(hps); #ifdef DEBUG_BUILD - printf("[CreateWMCursor] : ptr = %p\n", hptr); fflush(stdout); + printf("[CreateWMCursor] : ptr = %p\n", hptr); + fflush(stdout); #endif - pResult->hptr = hptr; - pResult->hbm = hbm; - pResult->pchData = pchTemp; + pResult->hptr = hptr; + pResult->hbm = hbm; + pResult->pchData = pchTemp; #ifdef DEBUG_BUILD - printf("[CreateWMCursor] : ptr = %p return.\n", hptr); fflush(stdout); + printf("[CreateWMCursor] : ptr = %p return.\n", hptr); + fflush(stdout); #endif - return (WMcursor *) pResult; + return (WMcursor *) pResult; } -WMcursor *os2fslib_CreateWMCursor_FS(_THIS, Uint8 *data, Uint8 *mask, - int w, int h, int hot_x, int hot_y) +WMcursor * +os2fslib_CreateWMCursor_FS(_THIS, Uint8 * data, Uint8 * mask, + int w, int h, int hot_x, int hot_y) { #ifdef DEBUG_BUILD - printf("[CreateWMCursor_FS] : returning pointer NULL\n"); fflush(stdout); + printf("[CreateWMCursor_FS] : returning pointer NULL\n"); + fflush(stdout); #endif - // In FS mode we'll use software cursor - return (WMcursor *) NULL; + // In FS mode we'll use software cursor + return (WMcursor *) NULL; } /* Show the specified cursor, or hide if cursor is NULL */ -int os2fslib_ShowWMCursor(_THIS, WMcursor *cursor) +int +os2fslib_ShowWMCursor(_THIS, WMcursor * cursor) { #ifdef DEBUG_BUILD - printf("[ShowWMCursor] : ptr = %p\n", cursor); fflush(stdout); + printf("[ShowWMCursor] : ptr = %p\n", cursor); + fflush(stdout); #endif - if (cursor) - { - WinSetPointer(HWND_DESKTOP, cursor->hptr); - hptrGlobalPointer = cursor->hptr; - _this->hidden->iMouseVisible = 1; - } - else - { - WinSetPointer(HWND_DESKTOP, FALSE); - hptrGlobalPointer = NULL; - _this->hidden->iMouseVisible = 0; - } + if (cursor) { + WinSetPointer(HWND_DESKTOP, cursor->hptr); + hptrGlobalPointer = cursor->hptr; + _this->hidden->iMouseVisible = 1; + } else { + WinSetPointer(HWND_DESKTOP, FALSE); + hptrGlobalPointer = NULL; + _this->hidden->iMouseVisible = 0; + } #ifdef DEBUG_BUILD - printf("[ShowWMCursor] : ptr = %p, DONE\n", cursor); fflush(stdout); + printf("[ShowWMCursor] : ptr = %p, DONE\n", cursor); + fflush(stdout); #endif - return 1; + return 1; } /* Warp the window manager cursor to (x,y) If NULL, a mouse motion event is posted internally. */ -void os2fslib_WarpWMCursor(_THIS, Uint16 x, Uint16 y) +void +os2fslib_WarpWMCursor(_THIS, Uint16 x, Uint16 y) { - LONG lx, ly; - SWP swpClient; - POINTL ptlPoints; - WinQueryWindowPos(_this->hidden->hwndClient, &swpClient); - ptlPoints.x = swpClient.x; - ptlPoints.y = swpClient.y; - WinMapWindowPoints(_this->hidden->hwndFrame, HWND_DESKTOP, &ptlPoints, 1); - lx = ptlPoints.x + (x*swpClient.cx) / _this->hidden->SrcBufferDesc.uiXResolution; - ly = ptlPoints.y + swpClient.cy - ((y*swpClient.cy) / _this->hidden->SrcBufferDesc.uiYResolution) - 1; - - SDL_PrivateMouseMotion(0, // Buttons not changed - 0, // Absolute position - x, - y); - - WinSetPointerPos(HWND_DESKTOP, lx, ly); + LONG lx, ly; + SWP swpClient; + POINTL ptlPoints; + WinQueryWindowPos(_this->hidden->hwndClient, &swpClient); + ptlPoints.x = swpClient.x; + ptlPoints.y = swpClient.y; + WinMapWindowPoints(_this->hidden->hwndFrame, HWND_DESKTOP, &ptlPoints, 1); + lx = ptlPoints.x + + (x * swpClient.cx) / _this->hidden->SrcBufferDesc.uiXResolution; + ly = ptlPoints.y + swpClient.cy - + ((y * swpClient.cy) / _this->hidden->SrcBufferDesc.uiYResolution) - 1; + + SDL_PrivateMouseMotion(0, // Buttons not changed + 0, // Absolute position + x, y); + + WinSetPointerPos(HWND_DESKTOP, lx, ly); } /* If not NULL, this is called when a mouse motion event occurs */ -void os2fslib_MoveWMCursor(_THIS, int x, int y) +void +os2fslib_MoveWMCursor(_THIS, int x, int y) { - /* - SDL_Rect rect; - -#ifdef DEBUG_BUILD - printf("[MoveWMCursor] : at %d ; %d\n", x, y); fflush(stdout); -#endif - - rect.x = x; - rect.y = y; - rect.w = 32; - rect.h = 32; - os2fslib_UpdateRects(_this, 1, &rect); - // TODO! - */ + /* + SDL_Rect rect; + + #ifdef DEBUG_BUILD + printf("[MoveWMCursor] : at %d ; %d\n", x, y); fflush(stdout); + #endif + + rect.x = x; + rect.y = y; + rect.w = 32; + rect.h = 32; + os2fslib_UpdateRects(_this, 1, &rect); + // TODO! + */ } /* Determine whether the mouse should be in relative mode or not. @@ -1536,410 +1593,406 @@ void os2fslib_MoveWMCursor(_THIS, int x, int y) driver can place the mouse in relative mode, which may result in higher accuracy sampling of the pointer motion. */ -void os2fslib_CheckMouseMode(_THIS) +void +os2fslib_CheckMouseMode(_THIS) { } -static void os2fslib_PumpEvents(_THIS) +static void +os2fslib_PumpEvents(_THIS) { - // Notify SDL that if window has been resized! - if ( - (_this->hidden->pSDLSurface) && - (_this->hidden->pSDLSurface->flags & SDL_RESIZABLE) && - ( - (_this->hidden->SrcBufferDesc.uiXResolution!=iWindowSizeX) || - (_this->hidden->SrcBufferDesc.uiYResolution!=iWindowSizeY) - ) && - (iWindowSizeX>0) && - (iWindowSizeY>0) - ) - { - static time_t prev_time; - time_t curr_time; - - curr_time = time(NULL); - if ((difftime(curr_time, prev_time)>=0.25) || - (bWindowResized)) - { - // Make sure we won't flood the event queue with resize events, - // only send them at 250 msecs! - // (or when the window is resized) -#ifdef DEBUG_BUILD - printf("[os2fslib_PumpEvents] : Calling PrivateResize (%d %d).\n", - iWindowSizeX, iWindowSizeY); - fflush(stdout); -#endif - // Tell SDL the new size - SDL_PrivateResize(iWindowSizeX, iWindowSizeY); - prev_time = curr_time; - bWindowResized = 0; + // Notify SDL that if window has been resized! + if ((_this->hidden->pSDLSurface) && + (_this->hidden->pSDLSurface->flags & SDL_RESIZABLE) && + ((_this->hidden->SrcBufferDesc.uiXResolution != iWindowSizeX) || + (_this->hidden->SrcBufferDesc.uiYResolution != iWindowSizeY)) && + (iWindowSizeX > 0) && (iWindowSizeY > 0)) { + static time_t prev_time; + time_t curr_time; + + curr_time = time(NULL); + if ((difftime(curr_time, prev_time) >= 0.25) || (bWindowResized)) { + // Make sure we won't flood the event queue with resize events, + // only send them at 250 msecs! + // (or when the window is resized) +#ifdef DEBUG_BUILD + printf + ("[os2fslib_PumpEvents] : Calling PrivateResize (%d %d).\n", + iWindowSizeX, iWindowSizeY); + fflush(stdout); +#endif + // Tell SDL the new size + SDL_PrivateResize(iWindowSizeX, iWindowSizeY); + prev_time = curr_time; + bWindowResized = 0; + } } - } } /* We don't actually allow hardware surfaces other than the main one */ -static int os2fslib_AllocHWSurface(_THIS, SDL_Surface *surface) +static int +os2fslib_AllocHWSurface(_THIS, SDL_Surface * surface) { - return(-1); + return (-1); } -static void os2fslib_FreeHWSurface(_THIS, SDL_Surface *surface) +static void +os2fslib_FreeHWSurface(_THIS, SDL_Surface * surface) { - return; + return; } /* We need to wait for vertical retrace on page flipped displays */ -static int os2fslib_LockHWSurface(_THIS, SDL_Surface *surface) +static int +os2fslib_LockHWSurface(_THIS, SDL_Surface * surface) { - return(0); + return (0); } -static void os2fslib_UnlockHWSurface(_THIS, SDL_Surface *surface) +static void +os2fslib_UnlockHWSurface(_THIS, SDL_Surface * surface) { - return; + return; } -static int os2fslib_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color *colors) +static int +os2fslib_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color * colors) { - printf("[os2fslib_SetColors] : TODO!\n"); fflush(stdout); - // TODO: Implement paletted modes - return(1); + printf("[os2fslib_SetColors] : TODO!\n"); + fflush(stdout); + // TODO: Implement paletted modes + return (1); } -static void os2fslib_DestroyIcon(HWND hwndFrame) +static void +os2fslib_DestroyIcon(HWND hwndFrame) { - if (hptrCurrentIcon) - { - WinDestroyPointer(hptrCurrentIcon); - hptrCurrentIcon = NULL; + if (hptrCurrentIcon) { + WinDestroyPointer(hptrCurrentIcon); + hptrCurrentIcon = NULL; - WinSendMsg(hwndFrame, - WM_SETICON, - NULL, - NULL); - } + WinSendMsg(hwndFrame, WM_SETICON, NULL, NULL); + } } /* Set the window icon image */ -void os2fslib_SetIcon(_THIS, SDL_Surface *icon, Uint8 *mask) +void +os2fslib_SetIcon(_THIS, SDL_Surface * icon, Uint8 * mask) { - HWND hwndFrame; - SDL_Surface *icon_rgb; - HPOINTER hptrIcon; - HBITMAP hbm; - BITMAPINFOHEADER bmih; - BMPINFO bmi; - HPS hps; - char *pchTemp; - char *pptr, *mptr, *dptr, *dmptr; - int maxx, maxy, w, h, x, y; - SDL_Rect bounds; - -#ifdef DEBUG_BUILD - printf("[os2fslib_SetIcon] : Creating and setting new icon\n"); fflush(stdout); + HWND hwndFrame; + SDL_Surface *icon_rgb; + HPOINTER hptrIcon; + HBITMAP hbm; + BITMAPINFOHEADER bmih; + BMPINFO bmi; + HPS hps; + char *pchTemp; + char *pptr, *mptr, *dptr, *dmptr; + int maxx, maxy, w, h, x, y; + SDL_Rect bounds; + +#ifdef DEBUG_BUILD + printf("[os2fslib_SetIcon] : Creating and setting new icon\n"); + fflush(stdout); #endif - hwndFrame = WinQueryWindow(_this->hidden->hwndClient, QW_PARENT); + hwndFrame = WinQueryWindow(_this->hidden->hwndClient, QW_PARENT); - // Make sure the old icon resource will be free'd! - os2fslib_DestroyIcon(hwndFrame); + // Make sure the old icon resource will be free'd! + os2fslib_DestroyIcon(hwndFrame); - if ((!icon) || (!mask)) - return; + if ((!icon) || (!mask)) + return; - w = icon->w; - h = icon->h; + w = icon->w; + h = icon->h; - maxx = WinQuerySysValue(HWND_DESKTOP, SV_CXICON); - maxy = WinQuerySysValue(HWND_DESKTOP, SV_CYICON); + maxx = WinQuerySysValue(HWND_DESKTOP, SV_CXICON); + maxy = WinQuerySysValue(HWND_DESKTOP, SV_CYICON); - // Check for max size! - if ((w>maxx) || (h>maxy)) - return; + // Check for max size! + if ((w > maxx) || (h > maxy)) + return; - pchTemp = (char *) SDL_malloc(w * h*2 * 4); - if (!pchTemp) - return; + pchTemp = (char *) SDL_malloc(w * h * 2 * 4); + if (!pchTemp) + return; - SDL_memset(pchTemp, 0, w * h*2 * 4); + SDL_memset(pchTemp, 0, w * h * 2 * 4); - // Convert surface to RGB, if it's not RGB yet! - icon_rgb = SDL_CreateRGBSurface(SDL_SWSURFACE, icon->w, icon->h, - 32, 0, 0, 0, 0); - if ( icon_rgb == NULL ) - { - SDL_free(pchTemp); - return; - } - bounds.x = 0; - bounds.y = 0; - bounds.w = icon->w; - bounds.h = icon->h; - if ( SDL_LowerBlit(icon, &bounds, icon_rgb, &bounds) < 0 ) - { - SDL_FreeSurface(icon_rgb); - SDL_free(pchTemp); - return; - } - - /* Copy pixels upside-down from RGB surface into BMP, masked with the icon mask */ - - // Pixels - pptr = (char *) (icon_rgb->pixels); - // Mask - mptr = mask; - - for (y=0; yw, icon->h, + 32, 0, 0, 0, 0); + if (icon_rgb == NULL) { + SDL_free(pchTemp); + return; + } + bounds.x = 0; + bounds.y = 0; + bounds.w = icon->w; + bounds.h = icon->h; + if (SDL_LowerBlit(icon, &bounds, icon_rgb, &bounds) < 0) { + SDL_FreeSurface(icon_rgb); + SDL_free(pchTemp); + return; } - } - // There is no more need for the RGB surface - SDL_FreeSurface(icon_rgb); + /* Copy pixels upside-down from RGB surface into BMP, masked with the icon mask */ - hps = WinGetPS(_this->hidden->hwndClient); + // Pixels + pptr = (char *) (icon_rgb->pixels); + // Mask + mptr = mask; - bmi.cbFix = sizeof(BITMAPINFOHEADER); - bmi.cx = w; - bmi.cy = 2*h; - bmi.cPlanes = 1; - bmi.cBitCount = 32; + for (y = 0; y < h; y++) { + unsigned char uchMaskByte; - SDL_memset(&bmih, 0, sizeof(BITMAPINFOHEADER)); - bmih.cbFix = sizeof(BITMAPINFOHEADER); - bmih.cx = w; - bmih.cy = 2*h; - bmih.cPlanes = 1; - bmih.cBitCount = 32; + // Destination + dptr = pchTemp + w * 4 * (h - y - 1); + // Destination mask + dmptr = pchTemp + w * h * 4 + w * 4 * (h - y - 1); - hbm = GpiCreateBitmap(hps, (PBITMAPINFOHEADER2)&bmih, CBM_INIT, (PBYTE) pchTemp, (PBITMAPINFO2)&bmi); - hptrIcon = WinCreatePointer(HWND_DESKTOP, hbm, FALSE, 0, 0); + for (x = 0; x < w; x++) { + if (x % 8 == 0) { + uchMaskByte = (unsigned char) (*mptr); + mptr++; + } else + uchMaskByte <<= 1; + + if (uchMaskByte & 0x80) { + // Copy RGB + *dptr++ = *pptr++; + *dptr++ = *pptr++; + *dptr++ = *pptr++; + *dptr++ = *pptr++; + + *dmptr++ = 0; + *dmptr++ = 0; + *dmptr++ = 0; + *dmptr++ = 0; + } else { + // Set pixels to fully transparent + *dptr++ = 0; + pptr++; + *dptr++ = 0; + pptr++; + *dptr++ = 0; + pptr++; + *dptr++ = 0; + pptr++; + + *dmptr++ = 255; + *dmptr++ = 255; + *dmptr++ = 255; + *dmptr++ = 255; + } + } + } + + // There is no more need for the RGB surface + SDL_FreeSurface(icon_rgb); + + hps = WinGetPS(_this->hidden->hwndClient); - WinReleasePS(hps); + bmi.cbFix = sizeof(BITMAPINFOHEADER); + bmi.cx = w; + bmi.cy = 2 * h; + bmi.cPlanes = 1; + bmi.cBitCount = 32; - // Free pixel array - SDL_free(pchTemp); + SDL_memset(&bmih, 0, sizeof(BITMAPINFOHEADER)); + bmih.cbFix = sizeof(BITMAPINFOHEADER); + bmih.cx = w; + bmih.cy = 2 * h; + bmih.cPlanes = 1; + bmih.cBitCount = 32; - // Change icon in frame window - WinSendMsg(hwndFrame, - WM_SETICON, - (MPARAM) hptrIcon, - NULL); + hbm = + GpiCreateBitmap(hps, (PBITMAPINFOHEADER2) & bmih, CBM_INIT, + (PBYTE) pchTemp, (PBITMAPINFO2) & bmi); + hptrIcon = WinCreatePointer(HWND_DESKTOP, hbm, FALSE, 0, 0); + + WinReleasePS(hps); + + // Free pixel array + SDL_free(pchTemp); - /* - // Change icon in switchlist - // Seems like it's not needed, the WM_SETICON already does it. - { - PID pidFrame; - HSWITCH hswitchFrame; - SWCNTRL swctl; + // Change icon in frame window + WinSendMsg(hwndFrame, WM_SETICON, (MPARAM) hptrIcon, NULL); - WinQueryWindowProcess(hwndFrame, &pidFrame, NULL); - hswitchFrame = WinQuerySwitchHandle(hwndFrame, pidFrame); - WinQuerySwitchEntry(hswitchFrame, &swctl); + /* + // Change icon in switchlist + // Seems like it's not needed, the WM_SETICON already does it. + { + PID pidFrame; + HSWITCH hswitchFrame; + SWCNTRL swctl; - swctl.hwndIcon = hptrIcon; + WinQueryWindowProcess(hwndFrame, &pidFrame, NULL); + hswitchFrame = WinQuerySwitchHandle(hwndFrame, pidFrame); + WinQuerySwitchEntry(hswitchFrame, &swctl); - WinChangeSwitchEntry(hswitchFrame, &swctl); - } - */ + swctl.hwndIcon = hptrIcon; - // Store icon handle in global variable - hptrCurrentIcon = hptrIcon; + WinChangeSwitchEntry(hswitchFrame, &swctl); + } + */ + + // Store icon handle in global variable + hptrCurrentIcon = hptrIcon; } // ------------------------ REAL FUNCTIONS ----------------- -static void os2fslib_SetCursorManagementFunctions(_THIS, int iForWindowedMode) +static void +os2fslib_SetCursorManagementFunctions(_THIS, int iForWindowedMode) { - if (iForWindowedMode) - { - _this->FreeWMCursor = os2fslib_FreeWMCursor; - _this->CreateWMCursor = os2fslib_CreateWMCursor_Win; - _this->ShowWMCursor = os2fslib_ShowWMCursor; - _this->WarpWMCursor = os2fslib_WarpWMCursor; - _this->MoveWMCursor = os2fslib_MoveWMCursor; - _this->CheckMouseMode = NULL;//os2fslib_CheckMouseMode; - } else - { - // We'll have software mouse cursor in FS mode! - _this->FreeWMCursor = os2fslib_FreeWMCursor; - _this->CreateWMCursor = os2fslib_CreateWMCursor_FS; - _this->ShowWMCursor = os2fslib_ShowWMCursor; - _this->WarpWMCursor = os2fslib_WarpWMCursor; - _this->MoveWMCursor = os2fslib_MoveWMCursor; - _this->CheckMouseMode = NULL;//os2fslib_CheckMouseMode; - } + if (iForWindowedMode) { + _this->FreeWMCursor = os2fslib_FreeWMCursor; + _this->CreateWMCursor = os2fslib_CreateWMCursor_Win; + _this->ShowWMCursor = os2fslib_ShowWMCursor; + _this->WarpWMCursor = os2fslib_WarpWMCursor; + _this->MoveWMCursor = os2fslib_MoveWMCursor; + _this->CheckMouseMode = NULL; //os2fslib_CheckMouseMode; + } else { + // We'll have software mouse cursor in FS mode! + _this->FreeWMCursor = os2fslib_FreeWMCursor; + _this->CreateWMCursor = os2fslib_CreateWMCursor_FS; + _this->ShowWMCursor = os2fslib_ShowWMCursor; + _this->WarpWMCursor = os2fslib_WarpWMCursor; + _this->MoveWMCursor = os2fslib_MoveWMCursor; + _this->CheckMouseMode = NULL; //os2fslib_CheckMouseMode; + } } -static void os2fslib_InitOSKeymap(_THIS) +static void +os2fslib_InitOSKeymap(_THIS) { - int i; - - iShiftIsPressed = 0; - - /* Map the VK and CH keysyms */ - for ( i=0; i<=255; ++i ) - HWScanKeyMap[i] = SDLK_UNKNOWN; - - // First line of keyboard: - HWScanKeyMap[0x1] = SDLK_ESCAPE; - HWScanKeyMap[0x3b] = SDLK_F1; - HWScanKeyMap[0x3c] = SDLK_F2; - HWScanKeyMap[0x3d] = SDLK_F3; - HWScanKeyMap[0x3e] = SDLK_F4; - HWScanKeyMap[0x3f] = SDLK_F5; - HWScanKeyMap[0x40] = SDLK_F6; - HWScanKeyMap[0x41] = SDLK_F7; - HWScanKeyMap[0x42] = SDLK_F8; - HWScanKeyMap[0x43] = SDLK_F9; - HWScanKeyMap[0x44] = SDLK_F10; - HWScanKeyMap[0x57] = SDLK_F11; - HWScanKeyMap[0x58] = SDLK_F12; - HWScanKeyMap[0x5d] = SDLK_PRINT; - HWScanKeyMap[0x46] = SDLK_SCROLLOCK; - HWScanKeyMap[0x5f] = SDLK_PAUSE; - - // Second line of keyboard: - HWScanKeyMap[0x29] = SDLK_BACKQUOTE; - HWScanKeyMap[0x2] = SDLK_1; - HWScanKeyMap[0x3] = SDLK_2; - HWScanKeyMap[0x4] = SDLK_3; - HWScanKeyMap[0x5] = SDLK_4; - HWScanKeyMap[0x6] = SDLK_5; - HWScanKeyMap[0x7] = SDLK_6; - HWScanKeyMap[0x8] = SDLK_7; - HWScanKeyMap[0x9] = SDLK_8; - HWScanKeyMap[0xa] = SDLK_9; - HWScanKeyMap[0xb] = SDLK_0; - HWScanKeyMap[0xc] = SDLK_MINUS; - HWScanKeyMap[0xd] = SDLK_EQUALS; - HWScanKeyMap[0xe] = SDLK_BACKSPACE; - HWScanKeyMap[0x68] = SDLK_INSERT; - HWScanKeyMap[0x60] = SDLK_HOME; - HWScanKeyMap[0x62] = SDLK_PAGEUP; - HWScanKeyMap[0x45] = SDLK_NUMLOCK; - HWScanKeyMap[0x5c] = SDLK_KP_DIVIDE; - HWScanKeyMap[0x37] = SDLK_KP_MULTIPLY; - HWScanKeyMap[0x4a] = SDLK_KP_MINUS; - - // Third line of keyboard: - HWScanKeyMap[0xf] = SDLK_TAB; - HWScanKeyMap[0x10] = SDLK_q; - HWScanKeyMap[0x11] = SDLK_w; - HWScanKeyMap[0x12] = SDLK_e; - HWScanKeyMap[0x13] = SDLK_r; - HWScanKeyMap[0x14] = SDLK_t; - HWScanKeyMap[0x15] = SDLK_y; - HWScanKeyMap[0x16] = SDLK_u; - HWScanKeyMap[0x17] = SDLK_i; - HWScanKeyMap[0x18] = SDLK_o; - HWScanKeyMap[0x19] = SDLK_p; - HWScanKeyMap[0x1a] = SDLK_LEFTBRACKET; - HWScanKeyMap[0x1b] = SDLK_RIGHTBRACKET; - HWScanKeyMap[0x1c] = SDLK_RETURN; - HWScanKeyMap[0x69] = SDLK_DELETE; - HWScanKeyMap[0x65] = SDLK_END; - HWScanKeyMap[0x67] = SDLK_PAGEDOWN; - HWScanKeyMap[0x47] = SDLK_KP7; - HWScanKeyMap[0x48] = SDLK_KP8; - HWScanKeyMap[0x49] = SDLK_KP9; - HWScanKeyMap[0x4e] = SDLK_KP_PLUS; - - // Fourth line of keyboard: - HWScanKeyMap[0x3a] = SDLK_CAPSLOCK; - HWScanKeyMap[0x1e] = SDLK_a; - HWScanKeyMap[0x1f] = SDLK_s; - HWScanKeyMap[0x20] = SDLK_d; - HWScanKeyMap[0x21] = SDLK_f; - HWScanKeyMap[0x22] = SDLK_g; - HWScanKeyMap[0x23] = SDLK_h; - HWScanKeyMap[0x24] = SDLK_j; - HWScanKeyMap[0x25] = SDLK_k; - HWScanKeyMap[0x26] = SDLK_l; - HWScanKeyMap[0x27] = SDLK_SEMICOLON; - HWScanKeyMap[0x28] = SDLK_QUOTE; - HWScanKeyMap[0x2b] = SDLK_BACKSLASH; - HWScanKeyMap[0x4b] = SDLK_KP4; - HWScanKeyMap[0x4c] = SDLK_KP5; - HWScanKeyMap[0x4d] = SDLK_KP6; - - // Fifth line of keyboard: - HWScanKeyMap[0x2a] = SDLK_LSHIFT; - HWScanKeyMap[0x56] = SDLK_WORLD_1; // Code 161, letter i' on hungarian keyboard - HWScanKeyMap[0x2c] = SDLK_z; - HWScanKeyMap[0x2d] = SDLK_x; - HWScanKeyMap[0x2e] = SDLK_c; - HWScanKeyMap[0x2f] = SDLK_v; - HWScanKeyMap[0x30] = SDLK_b; - HWScanKeyMap[0x31] = SDLK_n; - HWScanKeyMap[0x32] = SDLK_m; - HWScanKeyMap[0x33] = SDLK_COMMA; - HWScanKeyMap[0x34] = SDLK_PERIOD; - HWScanKeyMap[0x35] = SDLK_SLASH; - HWScanKeyMap[0x36] = SDLK_RSHIFT; - HWScanKeyMap[0x61] = SDLK_UP; - HWScanKeyMap[0x4f] = SDLK_KP1; - HWScanKeyMap[0x50] = SDLK_KP2; - HWScanKeyMap[0x51] = SDLK_KP3; - HWScanKeyMap[0x5a] = SDLK_KP_ENTER; - - // Sixth line of keyboard: - HWScanKeyMap[0x1d] = SDLK_LCTRL; - HWScanKeyMap[0x7e] = SDLK_LSUPER; // Windows key - HWScanKeyMap[0x38] = SDLK_LALT; - HWScanKeyMap[0x39] = SDLK_SPACE; - HWScanKeyMap[0x5e] = SDLK_RALT;// Actually, altgr on my keyboard... - HWScanKeyMap[0x7f] = SDLK_RSUPER; - HWScanKeyMap[0x7c] = SDLK_MENU; - HWScanKeyMap[0x5b] = SDLK_RCTRL; - HWScanKeyMap[0x63] = SDLK_LEFT; - HWScanKeyMap[0x66] = SDLK_DOWN; - HWScanKeyMap[0x64] = SDLK_RIGHT; - HWScanKeyMap[0x52] = SDLK_KP0; - HWScanKeyMap[0x53] = SDLK_KP_PERIOD; + int i; + + iShiftIsPressed = 0; + + /* Map the VK and CH keysyms */ + for (i = 0; i <= 255; ++i) + HWScanKeyMap[i] = SDLK_UNKNOWN; + + // First line of keyboard: + HWScanKeyMap[0x1] = SDLK_ESCAPE; + HWScanKeyMap[0x3b] = SDLK_F1; + HWScanKeyMap[0x3c] = SDLK_F2; + HWScanKeyMap[0x3d] = SDLK_F3; + HWScanKeyMap[0x3e] = SDLK_F4; + HWScanKeyMap[0x3f] = SDLK_F5; + HWScanKeyMap[0x40] = SDLK_F6; + HWScanKeyMap[0x41] = SDLK_F7; + HWScanKeyMap[0x42] = SDLK_F8; + HWScanKeyMap[0x43] = SDLK_F9; + HWScanKeyMap[0x44] = SDLK_F10; + HWScanKeyMap[0x57] = SDLK_F11; + HWScanKeyMap[0x58] = SDLK_F12; + HWScanKeyMap[0x5d] = SDLK_PRINT; + HWScanKeyMap[0x46] = SDLK_SCROLLOCK; + HWScanKeyMap[0x5f] = SDLK_PAUSE; + + // Second line of keyboard: + HWScanKeyMap[0x29] = SDLK_BACKQUOTE; + HWScanKeyMap[0x2] = SDLK_1; + HWScanKeyMap[0x3] = SDLK_2; + HWScanKeyMap[0x4] = SDLK_3; + HWScanKeyMap[0x5] = SDLK_4; + HWScanKeyMap[0x6] = SDLK_5; + HWScanKeyMap[0x7] = SDLK_6; + HWScanKeyMap[0x8] = SDLK_7; + HWScanKeyMap[0x9] = SDLK_8; + HWScanKeyMap[0xa] = SDLK_9; + HWScanKeyMap[0xb] = SDLK_0; + HWScanKeyMap[0xc] = SDLK_MINUS; + HWScanKeyMap[0xd] = SDLK_EQUALS; + HWScanKeyMap[0xe] = SDLK_BACKSPACE; + HWScanKeyMap[0x68] = SDLK_INSERT; + HWScanKeyMap[0x60] = SDLK_HOME; + HWScanKeyMap[0x62] = SDLK_PAGEUP; + HWScanKeyMap[0x45] = SDLK_NUMLOCK; + HWScanKeyMap[0x5c] = SDLK_KP_DIVIDE; + HWScanKeyMap[0x37] = SDLK_KP_MULTIPLY; + HWScanKeyMap[0x4a] = SDLK_KP_MINUS; + + // Third line of keyboard: + HWScanKeyMap[0xf] = SDLK_TAB; + HWScanKeyMap[0x10] = SDLK_q; + HWScanKeyMap[0x11] = SDLK_w; + HWScanKeyMap[0x12] = SDLK_e; + HWScanKeyMap[0x13] = SDLK_r; + HWScanKeyMap[0x14] = SDLK_t; + HWScanKeyMap[0x15] = SDLK_y; + HWScanKeyMap[0x16] = SDLK_u; + HWScanKeyMap[0x17] = SDLK_i; + HWScanKeyMap[0x18] = SDLK_o; + HWScanKeyMap[0x19] = SDLK_p; + HWScanKeyMap[0x1a] = SDLK_LEFTBRACKET; + HWScanKeyMap[0x1b] = SDLK_RIGHTBRACKET; + HWScanKeyMap[0x1c] = SDLK_RETURN; + HWScanKeyMap[0x69] = SDLK_DELETE; + HWScanKeyMap[0x65] = SDLK_END; + HWScanKeyMap[0x67] = SDLK_PAGEDOWN; + HWScanKeyMap[0x47] = SDLK_KP7; + HWScanKeyMap[0x48] = SDLK_KP8; + HWScanKeyMap[0x49] = SDLK_KP9; + HWScanKeyMap[0x4e] = SDLK_KP_PLUS; + + // Fourth line of keyboard: + HWScanKeyMap[0x3a] = SDLK_CAPSLOCK; + HWScanKeyMap[0x1e] = SDLK_a; + HWScanKeyMap[0x1f] = SDLK_s; + HWScanKeyMap[0x20] = SDLK_d; + HWScanKeyMap[0x21] = SDLK_f; + HWScanKeyMap[0x22] = SDLK_g; + HWScanKeyMap[0x23] = SDLK_h; + HWScanKeyMap[0x24] = SDLK_j; + HWScanKeyMap[0x25] = SDLK_k; + HWScanKeyMap[0x26] = SDLK_l; + HWScanKeyMap[0x27] = SDLK_SEMICOLON; + HWScanKeyMap[0x28] = SDLK_QUOTE; + HWScanKeyMap[0x2b] = SDLK_BACKSLASH; + HWScanKeyMap[0x4b] = SDLK_KP4; + HWScanKeyMap[0x4c] = SDLK_KP5; + HWScanKeyMap[0x4d] = SDLK_KP6; + + // Fifth line of keyboard: + HWScanKeyMap[0x2a] = SDLK_LSHIFT; + HWScanKeyMap[0x56] = SDLK_WORLD_1; // Code 161, letter i' on hungarian keyboard + HWScanKeyMap[0x2c] = SDLK_z; + HWScanKeyMap[0x2d] = SDLK_x; + HWScanKeyMap[0x2e] = SDLK_c; + HWScanKeyMap[0x2f] = SDLK_v; + HWScanKeyMap[0x30] = SDLK_b; + HWScanKeyMap[0x31] = SDLK_n; + HWScanKeyMap[0x32] = SDLK_m; + HWScanKeyMap[0x33] = SDLK_COMMA; + HWScanKeyMap[0x34] = SDLK_PERIOD; + HWScanKeyMap[0x35] = SDLK_SLASH; + HWScanKeyMap[0x36] = SDLK_RSHIFT; + HWScanKeyMap[0x61] = SDLK_UP; + HWScanKeyMap[0x4f] = SDLK_KP1; + HWScanKeyMap[0x50] = SDLK_KP2; + HWScanKeyMap[0x51] = SDLK_KP3; + HWScanKeyMap[0x5a] = SDLK_KP_ENTER; + + // Sixth line of keyboard: + HWScanKeyMap[0x1d] = SDLK_LCTRL; + HWScanKeyMap[0x7e] = SDLK_LSUPER; // Windows key + HWScanKeyMap[0x38] = SDLK_LALT; + HWScanKeyMap[0x39] = SDLK_SPACE; + HWScanKeyMap[0x5e] = SDLK_RALT; // Actually, altgr on my keyboard... + HWScanKeyMap[0x7f] = SDLK_RSUPER; + HWScanKeyMap[0x7c] = SDLK_MENU; + HWScanKeyMap[0x5b] = SDLK_RCTRL; + HWScanKeyMap[0x63] = SDLK_LEFT; + HWScanKeyMap[0x66] = SDLK_DOWN; + HWScanKeyMap[0x64] = SDLK_RIGHT; + HWScanKeyMap[0x52] = SDLK_KP0; + HWScanKeyMap[0x53] = SDLK_KP_PERIOD; } @@ -1947,262 +2000,274 @@ static void os2fslib_InitOSKeymap(_THIS) This function returns 1 if there is a window manager and the window was actually iconified, it returns 0 otherwise. */ -int os2fslib_IconifyWindow(_THIS) +int +os2fslib_IconifyWindow(_THIS) { - HAB hab; - HMQ hmq; - ERRORID hmqerror; + HAB hab; + HMQ hmq; + ERRORID hmqerror; - // If there is no more window, nothing we can do! - if (_this->hidden->iPMThreadStatus!=1) return 0; + // If there is no more window, nothing we can do! + if (_this->hidden->iPMThreadStatus != 1) + return 0; - // Cannot do anything in fullscreen mode! - if (FSLib_QueryFSMode(_this->hidden->hwndClient)) - return 0; + // Cannot do anything in fullscreen mode! + if (FSLib_QueryFSMode(_this->hidden->hwndClient)) + return 0; - // Make sure this thread is prepared for using the Presentation Manager! - hab = WinInitialize(0); - hmq = WinCreateMsgQueue(hab,0); - // Remember if there was an error at WinCreateMsgQueue(), because we don't - // want to destroy somebody else's queue later. :) - hmqerror = WinGetLastError(hab); + // Make sure this thread is prepared for using the Presentation Manager! + hab = WinInitialize(0); + hmq = WinCreateMsgQueue(hab, 0); + // Remember if there was an error at WinCreateMsgQueue(), because we don't + // want to destroy somebody else's queue later. :) + hmqerror = WinGetLastError(hab); - WinSetWindowPos(_this->hidden->hwndFrame, HWND_TOP, - 0, 0, 0, 0, SWP_MINIMIZE); + WinSetWindowPos(_this->hidden->hwndFrame, HWND_TOP, + 0, 0, 0, 0, SWP_MINIMIZE); - // Now destroy the message queue, if we've created it! - if (ERRORIDERROR(hmqerror)==0) - WinDestroyMsgQueue(hmq); + // Now destroy the message queue, if we've created it! + if (ERRORIDERROR(hmqerror) == 0) + WinDestroyMsgQueue(hmq); - return 1; + return 1; } -static SDL_GrabMode os2fslib_GrabInput(_THIS, SDL_GrabMode mode) +static SDL_GrabMode +os2fslib_GrabInput(_THIS, SDL_GrabMode mode) { - HAB hab; - HMQ hmq; - ERRORID hmqerror; + HAB hab; + HMQ hmq; + ERRORID hmqerror; - // If there is no more window, nothing we can do! - if (_this->hidden->iPMThreadStatus!=1) - return SDL_GRAB_OFF; + // If there is no more window, nothing we can do! + if (_this->hidden->iPMThreadStatus != 1) + return SDL_GRAB_OFF; - // Make sure this thread is prepared for using the Presentation Manager! - hab = WinInitialize(0); - hmq = WinCreateMsgQueue(hab,0); - // Remember if there was an error at WinCreateMsgQueue(), because we don't - // want to destroy somebody else's queue later. :) - hmqerror = WinGetLastError(hab); + // Make sure this thread is prepared for using the Presentation Manager! + hab = WinInitialize(0); + hmq = WinCreateMsgQueue(hab, 0); + // Remember if there was an error at WinCreateMsgQueue(), because we don't + // want to destroy somebody else's queue later. :) + hmqerror = WinGetLastError(hab); - if (mode == SDL_GRAB_OFF) - { + if (mode == SDL_GRAB_OFF) { #ifdef DEBUG_BUILD - printf("[os2fslib_GrabInput] : Releasing mouse\n"); fflush(stdout); + printf("[os2fslib_GrabInput] : Releasing mouse\n"); + fflush(stdout); #endif - // Release the mouse - bMouseCapturable = 0; - if (bMouseCaptured) - { - WinSetCapture(HWND_DESKTOP, NULLHANDLE); - bMouseCaptured = 0; - } - } else - { -#ifdef DEBUG_BUILD - printf("[os2fslib_GrabInput] : Capturing mouse\n"); fflush(stdout); -#endif - - // Capture the mouse - bMouseCapturable = 1; - if (WinQueryFocus(HWND_DESKTOP) == _this->hidden->hwndClient) - { - WinSetCapture(HWND_DESKTOP, _this->hidden->hwndClient); - bMouseCaptured = 1; - { - SWP swpClient; - POINTL ptl; - // Center the mouse to the middle of the window! - WinQueryWindowPos(_this->hidden->hwndClient, &swpClient); - ptl.x = 0; ptl.y = 0; - WinMapWindowPoints(_this->hidden->hwndClient, HWND_DESKTOP, &ptl, 1); - _this->hidden->iSkipWMMOUSEMOVE++; /* Don't take next WM_MOUSEMOVE into account! */ - WinSetPointerPos(HWND_DESKTOP, - ptl.x + swpClient.cx/2, - ptl.y + swpClient.cy/2); - } + // Release the mouse + bMouseCapturable = 0; + if (bMouseCaptured) { + WinSetCapture(HWND_DESKTOP, NULLHANDLE); + bMouseCaptured = 0; + } + } else { +#ifdef DEBUG_BUILD + printf("[os2fslib_GrabInput] : Capturing mouse\n"); + fflush(stdout); +#endif + + // Capture the mouse + bMouseCapturable = 1; + if (WinQueryFocus(HWND_DESKTOP) == _this->hidden->hwndClient) { + WinSetCapture(HWND_DESKTOP, _this->hidden->hwndClient); + bMouseCaptured = 1; + { + SWP swpClient; + POINTL ptl; + // Center the mouse to the middle of the window! + WinQueryWindowPos(_this->hidden->hwndClient, &swpClient); + ptl.x = 0; + ptl.y = 0; + WinMapWindowPoints(_this->hidden->hwndClient, + HWND_DESKTOP, &ptl, 1); + _this->hidden->iSkipWMMOUSEMOVE++; /* Don't take next WM_MOUSEMOVE into account! */ + WinSetPointerPos(HWND_DESKTOP, + ptl.x + swpClient.cx / 2, + ptl.y + swpClient.cy / 2); + } + } } - } - // Now destroy the message queue, if we've created it! - if (ERRORIDERROR(hmqerror)==0) - WinDestroyMsgQueue(hmq); + // Now destroy the message queue, if we've created it! + if (ERRORIDERROR(hmqerror) == 0) + WinDestroyMsgQueue(hmq); - return mode; + return mode; } /* Set the title and icon text */ -static void os2fslib_SetCaption(_THIS, const char *title, const char *icon) +static void +os2fslib_SetCaption(_THIS, const char *title, const char *icon) { - HAB hab; - HMQ hmq; - ERRORID hmqerror; - - // If there is no more window, nothing we can do! - if (_this->hidden->iPMThreadStatus!=1) return; - - // Make sure this thread is prepared for using the Presentation Manager! - hab = WinInitialize(0); - hmq = WinCreateMsgQueue(hab,0); - // Remember if there was an error at WinCreateMsgQueue(), because we don't - // want to destroy somebody else's queue later. :) - hmqerror = WinGetLastError(hab); - - WinSetWindowText(_this->hidden->hwndFrame, (char *) title); - - // Now destroy the message queue, if we've created it! - if (ERRORIDERROR(hmqerror)==0) - WinDestroyMsgQueue(hmq); + HAB hab; + HMQ hmq; + ERRORID hmqerror; + + // If there is no more window, nothing we can do! + if (_this->hidden->iPMThreadStatus != 1) + return; + + // Make sure this thread is prepared for using the Presentation Manager! + hab = WinInitialize(0); + hmq = WinCreateMsgQueue(hab, 0); + // Remember if there was an error at WinCreateMsgQueue(), because we don't + // want to destroy somebody else's queue later. :) + hmqerror = WinGetLastError(hab); + + WinSetWindowText(_this->hidden->hwndFrame, (char *) title); + + // Now destroy the message queue, if we've created it! + if (ERRORIDERROR(hmqerror) == 0) + WinDestroyMsgQueue(hmq); } -static int os2fslib_ToggleFullScreen(_THIS, int on) +static int +os2fslib_ToggleFullScreen(_THIS, int on) { #ifdef DEBUG_BUILD - printf("[os2fslib_ToggleFullScreen] : %d\n", on); fflush(stdout); + printf("[os2fslib_ToggleFullScreen] : %d\n", on); + fflush(stdout); #endif - // If there is no more window, nothing we can do! - if (_this->hidden->iPMThreadStatus!=1) return 0; + // If there is no more window, nothing we can do! + if (_this->hidden->iPMThreadStatus != 1) + return 0; - FSLib_ToggleFSMode(_this->hidden->hwndClient, on); - /* Cursor manager functions to Windowed/FS mode*/ - os2fslib_SetCursorManagementFunctions(_this, !on); - return 1; + FSLib_ToggleFSMode(_this->hidden->hwndClient, on); + /* Cursor manager functions to Windowed/FS mode */ + os2fslib_SetCursorManagementFunctions(_this, !on); + return 1; } /* This is called after the video mode has been set, to get the initial mouse state. It should queue events as necessary to properly represent the current mouse focus and position. */ -static void os2fslib_UpdateMouse(_THIS) +static void +os2fslib_UpdateMouse(_THIS) { - POINTL ptl; - HAB hab; - HMQ hmq; - ERRORID hmqerror; - SWP swpClient; - - // If there is no more window, nothing we can do! - if (_this->hidden->iPMThreadStatus!=1) return; - - - // Make sure this thread is prepared for using the Presentation Manager! - hab = WinInitialize(0); - hmq = WinCreateMsgQueue(hab,0); - // Remember if there was an error at WinCreateMsgQueue(), because we don't - // want to destroy somebody else's queue later. :) - hmqerror = WinGetLastError(hab); - - - - if (_this->hidden->fInFocus) - { - // If our app is in focus - SDL_PrivateAppActive(1, SDL_APPMOUSEFOCUS); - SDL_PrivateAppActive(1, SDL_APPINPUTFOCUS); - SDL_PrivateAppActive(1, SDL_APPACTIVE); - WinQueryPointerPos(HWND_DESKTOP, &ptl); - WinMapWindowPoints(HWND_DESKTOP, _this->hidden->hwndClient, &ptl, 1); - WinQueryWindowPos(_this->hidden->hwndClient, &swpClient); - // Convert OS/2 mouse position to SDL position, and also scale it! - ptl.x = ptl.x * _this->hidden->SrcBufferDesc.uiXResolution / swpClient.cx; - ptl.y = ptl.y * _this->hidden->SrcBufferDesc.uiYResolution / swpClient.cy; - ptl.y = _this->hidden->SrcBufferDesc.uiYResolution - ptl.y - 1; - SDL_PrivateMouseMotion(0, 0, (Sint16) (ptl.x), (Sint16) (ptl.y)); - } else - { - // If we're not in focus - SDL_PrivateAppActive(0, SDL_APPMOUSEFOCUS); - SDL_PrivateAppActive(0, SDL_APPINPUTFOCUS); - SDL_PrivateAppActive(0, SDL_APPACTIVE); - SDL_PrivateMouseMotion(0, 0, (Sint16) -1, (Sint16) -1); - } - - // Now destroy the message queue, if we've created it! - if (ERRORIDERROR(hmqerror)==0) - WinDestroyMsgQueue(hmq); + POINTL ptl; + HAB hab; + HMQ hmq; + ERRORID hmqerror; + SWP swpClient; + + // If there is no more window, nothing we can do! + if (_this->hidden->iPMThreadStatus != 1) + return; + + + // Make sure this thread is prepared for using the Presentation Manager! + hab = WinInitialize(0); + hmq = WinCreateMsgQueue(hab, 0); + // Remember if there was an error at WinCreateMsgQueue(), because we don't + // want to destroy somebody else's queue later. :) + hmqerror = WinGetLastError(hab); + + + + if (_this->hidden->fInFocus) { + // If our app is in focus + SDL_PrivateAppActive(1, SDL_APPMOUSEFOCUS); + SDL_PrivateAppActive(1, SDL_APPINPUTFOCUS); + SDL_PrivateAppActive(1, SDL_APPACTIVE); + WinQueryPointerPos(HWND_DESKTOP, &ptl); + WinMapWindowPoints(HWND_DESKTOP, _this->hidden->hwndClient, &ptl, 1); + WinQueryWindowPos(_this->hidden->hwndClient, &swpClient); + // Convert OS/2 mouse position to SDL position, and also scale it! + ptl.x = + ptl.x * _this->hidden->SrcBufferDesc.uiXResolution / swpClient.cx; + ptl.y = + ptl.y * _this->hidden->SrcBufferDesc.uiYResolution / swpClient.cy; + ptl.y = _this->hidden->SrcBufferDesc.uiYResolution - ptl.y - 1; + SDL_PrivateMouseMotion(0, 0, (Sint16) (ptl.x), (Sint16) (ptl.y)); + } else { + // If we're not in focus + SDL_PrivateAppActive(0, SDL_APPMOUSEFOCUS); + SDL_PrivateAppActive(0, SDL_APPINPUTFOCUS); + SDL_PrivateAppActive(0, SDL_APPACTIVE); + SDL_PrivateMouseMotion(0, 0, (Sint16) - 1, (Sint16) - 1); + } + + // Now destroy the message queue, if we've created it! + if (ERRORIDERROR(hmqerror) == 0) + WinDestroyMsgQueue(hmq); } /* This pointer should exist in the native video subsystem and should point to an appropriate update function for the current video mode */ -static void os2fslib_UpdateRects(_THIS, int numrects, SDL_Rect *rects) +static void +os2fslib_UpdateRects(_THIS, int numrects, SDL_Rect * rects) { - // If there is no more window, nothing we can do! - if (_this->hidden->iPMThreadStatus!=1) return; + // If there is no more window, nothing we can do! + if (_this->hidden->iPMThreadStatus != 1) + return; #ifdef BITBLT_IN_WINMESSAGEPROC - WinSendMsg(_this->hidden->hwndClient, - WM_UPDATERECTSREQUEST, - (MPARAM) numrects, - (MPARAM) rects); + WinSendMsg(_this->hidden->hwndClient, + WM_UPDATERECTSREQUEST, (MPARAM) numrects, (MPARAM) rects); #else - if (DosRequestMutexSem(_this->hidden->hmtxUseSrcBuffer, SEM_INDEFINITE_WAIT)==NO_ERROR) - { - int i; + if (DosRequestMutexSem + (_this->hidden->hmtxUseSrcBuffer, SEM_INDEFINITE_WAIT) == NO_ERROR) { + int i; - if (_this->hidden->pSDLSurface) - { + if (_this->hidden->pSDLSurface) { #ifndef RESIZE_EVEN_IF_RESIZABLE - SWP swp; - // But only blit if the window is not resizable, or if - // the window is resizable and the source buffer size is the - // same as the destination buffer size! - WinQueryWindowPos(_this->hidden->hwndClient, &swp); - if ((_this->hidden->pSDLSurface) && - (_this->hidden->pSDLSurface->flags & SDL_RESIZABLE) && - ((swp.cx != _this->hidden->SrcBufferDesc.uiXResolution) || - (swp.cy != _this->hidden->SrcBufferDesc.uiYResolution) - ) && - (!FSLib_QueryFSMode(_this->hidden->hwndClient)) - ) - { - // Resizable surface and in resizing! - // So, don't blit now! -#ifdef DEBUG_BUILD - printf("[UpdateRects] : Skipping blit while resizing!\n"); fflush(stdout); -#endif - } else -#endif - { - /* - // Blit the whole window - FSLIB_BITBLT(_this->hidden->hwndClient, _this->hidden->pchSrcBuffer, - 0, 0, - _this->hidden->SrcBufferDesc.uiXResolution, - _this->hidden->SrcBufferDesc.uiYResolution); - */ -#ifdef DEBUG_BUILD - printf("[os2fslib_UpdateRects] : Blitting!\n"); fflush(stdout); -#endif - - // Blit the changed areas - for (i=0; ihidden->hwndClient, _this->hidden->pchSrcBuffer, - rects[i].y, rects[i].x, rects[i].w, rects[i].h); - } - } + SWP swp; + // But only blit if the window is not resizable, or if + // the window is resizable and the source buffer size is the + // same as the destination buffer size! + WinQueryWindowPos(_this->hidden->hwndClient, &swp); + if ((_this->hidden->pSDLSurface) && + (_this->hidden->pSDLSurface->flags & SDL_RESIZABLE) && + ((swp.cx != _this->hidden->SrcBufferDesc.uiXResolution) || + (swp.cy != _this->hidden->SrcBufferDesc.uiYResolution)) + && (!FSLib_QueryFSMode(_this->hidden->hwndClient))) { + // Resizable surface and in resizing! + // So, don't blit now! +#ifdef DEBUG_BUILD + printf("[UpdateRects] : Skipping blit while resizing!\n"); + fflush(stdout); +#endif + } else +#endif + { + /* + // Blit the whole window + FSLIB_BITBLT(_this->hidden->hwndClient, _this->hidden->pchSrcBuffer, + 0, 0, + _this->hidden->SrcBufferDesc.uiXResolution, + _this->hidden->SrcBufferDesc.uiYResolution); + */ +#ifdef DEBUG_BUILD + printf("[os2fslib_UpdateRects] : Blitting!\n"); + fflush(stdout); +#endif + + // Blit the changed areas + for (i = 0; i < numrects; i++) + FSLIB_BITBLT(_this->hidden->hwndClient, + _this->hidden->pchSrcBuffer, + rects[i].y, rects[i].x, rects[i].w, + rects[i].h); + } + } #ifdef DEBUG_BUILD - else - printf("[os2fslib_UpdateRects] : No public surface!\n"); fflush(stdout); + else + printf("[os2fslib_UpdateRects] : No public surface!\n"); + fflush(stdout); #endif - DosReleaseMutexSem(_this->hidden->hmtxUseSrcBuffer); - } + DosReleaseMutexSem(_this->hidden->hmtxUseSrcBuffer); + } #ifdef DEBUG_BUILD - else - printf("[os2fslib_UpdateRects] : Error in mutex!\n"); fflush(stdout); + else + printf("[os2fslib_UpdateRects] : Error in mutex!\n"); + fflush(stdout); #endif #endif } @@ -2211,77 +2276,75 @@ static void os2fslib_UpdateRects(_THIS, int numrects, SDL_Rect *rects) /* Reverse the effects VideoInit() -- called if VideoInit() fails or if the application is shutting down the video subsystem. */ -static void os2fslib_VideoQuit(_THIS) +static void +os2fslib_VideoQuit(_THIS) { #ifdef DEBUG_BUILD - printf("[os2fslib_VideoQuit]\n"); fflush(stdout); + printf("[os2fslib_VideoQuit]\n"); + fflush(stdout); #endif - // Close PM stuff if running! - if (_this->hidden->iPMThreadStatus == 1) - { - int iTimeout; - WinPostMsg(_this->hidden->hwndFrame, WM_QUIT, (MPARAM) 0, (MPARAM) 0); - // HACK: We had this line before: - //DosWaitThread((TID *) &(_this->hidden->tidPMThread), DCWW_WAIT); - // We don't use it, because the PMThread will never stop, or if it stops, - // it will kill the whole process as a emergency fallback. - // So, we only check for the iPMThreadStatus stuff! + // Close PM stuff if running! + if (_this->hidden->iPMThreadStatus == 1) { + int iTimeout; + WinPostMsg(_this->hidden->hwndFrame, WM_QUIT, (MPARAM) 0, (MPARAM) 0); + // HACK: We had this line before: + //DosWaitThread((TID *) &(_this->hidden->tidPMThread), DCWW_WAIT); + // We don't use it, because the PMThread will never stop, or if it stops, + // it will kill the whole process as a emergency fallback. + // So, we only check for the iPMThreadStatus stuff! #ifdef DEBUG_BUILD - printf("[os2fslib_VideoQuit] : Waiting for PM thread to die\n"); fflush(stdout); + printf("[os2fslib_VideoQuit] : Waiting for PM thread to die\n"); + fflush(stdout); #endif - iTimeout=0; - while ((_this->hidden->iPMThreadStatus == 1) && (iTimeout<100)) - { - iTimeout++; - DosSleep(64); - } + iTimeout = 0; + while ((_this->hidden->iPMThreadStatus == 1) && (iTimeout < 100)) { + iTimeout++; + DosSleep(64); + } #ifdef DEBUG_BUILD - printf("[os2fslib_VideoQuit] : End of wait.\n"); fflush(stdout); + printf("[os2fslib_VideoQuit] : End of wait.\n"); + fflush(stdout); #endif - if (_this->hidden->iPMThreadStatus == 1) - { + if (_this->hidden->iPMThreadStatus == 1) { #ifdef DEBUG_BUILD - printf("[os2fslib_VideoQuit] : Killing PM thread!\n"); fflush(stdout); + printf("[os2fslib_VideoQuit] : Killing PM thread!\n"); + fflush(stdout); #endif - - _this->hidden->iPMThreadStatus = 0; - DosKillThread(_this->hidden->tidPMThread); - if (_this->hidden->hwndFrame) - { + _this->hidden->iPMThreadStatus = 0; + DosKillThread(_this->hidden->tidPMThread); + + if (_this->hidden->hwndFrame) { #ifdef DEBUG_BUILD - printf("[os2fslib_VideoQuit] : Destroying PM window!\n"); fflush(stdout); + printf("[os2fslib_VideoQuit] : Destroying PM window!\n"); + fflush(stdout); #endif - WinDestroyWindow(_this->hidden->hwndFrame); _this->hidden->hwndFrame=NULL; - } - } - - } - - // Free result of an old ListModes() call, because there is - // no FreeListModes() call in SDL! - if (_this->hidden->pListModesResult) - { - SDL_free(_this->hidden->pListModesResult); _this->hidden->pListModesResult = NULL; - } + WinDestroyWindow(_this->hidden->hwndFrame); + _this->hidden->hwndFrame = NULL; + } + } - // Free list of available fullscreen modes - if (_this->hidden->pAvailableFSLibVideoModes) - { - FSLib_FreeVideoModeList(_this->hidden->pAvailableFSLibVideoModes); - _this->hidden->pAvailableFSLibVideoModes = NULL; - } - - // Free application icon if we had one - if (hptrCurrentIcon) - { - WinDestroyPointer(hptrCurrentIcon); - hptrCurrentIcon = NULL; - } + } + // Free result of an old ListModes() call, because there is + // no FreeListModes() call in SDL! + if (_this->hidden->pListModesResult) { + SDL_free(_this->hidden->pListModesResult); + _this->hidden->pListModesResult = NULL; + } + // Free list of available fullscreen modes + if (_this->hidden->pAvailableFSLibVideoModes) { + FSLib_FreeVideoModeList(_this->hidden->pAvailableFSLibVideoModes); + _this->hidden->pAvailableFSLibVideoModes = NULL; + } + // Free application icon if we had one + if (hptrCurrentIcon) { + WinDestroyPointer(hptrCurrentIcon); + hptrCurrentIcon = NULL; + } } /* Set the requested video mode, returning a surface which will be @@ -2292,727 +2355,767 @@ static void os2fslib_VideoQuit(_THIS) surface if necessary. If a new mode is returned, this function should take care of cleaning up the current mode. */ -static SDL_Surface *os2fslib_SetVideoMode(_THIS, SDL_Surface *current, - int width, int height, int bpp, Uint32 flags) +static SDL_Surface * +os2fslib_SetVideoMode(_THIS, SDL_Surface * current, + int width, int height, int bpp, Uint32 flags) { - static int bFirstCall = 1; - FSLib_VideoMode_p pModeInfo, pModeInfoFound; - FSLib_VideoMode TempModeInfo; - HAB hab; - HMQ hmq; - ERRORID hmqerror; - RECTL rectl; - SDL_Surface *pResult; - - // If there is no more window, nothing we can do! - if (_this->hidden->iPMThreadStatus!=1) return NULL; - -#ifdef DEBUG_BUILD - printf("[os2fslib_SetVideoMode] : Request for %dx%d @ %dBPP, flags=0x%x\n", width, height, bpp, flags); fflush(stdout); -#endif - - // We don't support palette modes! - if (bpp==8) bpp=32; - - // Also, we don't support resizable modes in fullscreen mode. - if (flags & SDL_RESIZABLE) - flags &= ~SDL_FULLSCREEN; - - // No double buffered mode - if (flags & SDL_DOUBLEBUF) - flags &= ~SDL_DOUBLEBUF; - - // And, we don't support HWSURFACE yet. - if (flags & SDL_HWSURFACE) - { - flags &= ~SDL_HWSURFACE; - flags |= SDL_SWSURFACE; - } - -#ifdef DEBUG_BUILD - printf("[os2fslib_SetVideoMode] : Changed request to %dx%d @ %dBPP, flags=0x%x\n", width, height, bpp, flags); fflush(stdout); -#endif - - // First check if there is such a video mode they want! - pModeInfoFound = NULL; - - // For fullscreen mode we don't support every resolution! - // So, go through the video modes, and check for such a resolution! - pModeInfoFound = NULL; - pModeInfo = _this->hidden->pAvailableFSLibVideoModes; - - while (pModeInfo) - { - // Check all available fullscreen modes for this resolution - if ((pModeInfo->uiXResolution == width) && - (pModeInfo->uiYResolution == height) && - (pModeInfo->uiBPP!=8)) // palettized modes not yet supported - { - // If good resolution, try to find the exact BPP, or at least - // something similar... - if (!pModeInfoFound) - pModeInfoFound = pModeInfo; - else - if ((pModeInfoFound->uiBPP!=bpp) && - (pModeInfoFound->uiBPPuiBPP)) - pModeInfoFound = pModeInfo; - } - pModeInfo = pModeInfo->pNext; - } + static int bFirstCall = 1; + FSLib_VideoMode_p pModeInfo, pModeInfoFound; + FSLib_VideoMode TempModeInfo; + HAB hab; + HMQ hmq; + ERRORID hmqerror; + RECTL rectl; + SDL_Surface *pResult; - // If we did not find a good fullscreen mode, then try a similar - if (!pModeInfoFound) - { -#ifdef DEBUG_BUILD - printf("[os2fslib_SetVideoMode] : Requested video mode not found, looking for a similar one!\n"); fflush(stdout); -#endif - // Go through the video modes again, and find a similar resolution! - pModeInfo = _this->hidden->pAvailableFSLibVideoModes; - while (pModeInfo) - { - // Check all available fullscreen modes for this resolution - if ((pModeInfo->uiXResolution >= width) && - (pModeInfo->uiYResolution >= height) && - (pModeInfo->uiBPP == bpp)) - { - if (!pModeInfoFound) - pModeInfoFound = pModeInfo; - else - if (((pModeInfoFound->uiXResolution-width)*(pModeInfoFound->uiYResolution-height))> - ((pModeInfo->uiXResolution-width)*(pModeInfo->uiYResolution-height))) - { - // Found a mode which is closer than the current one - pModeInfoFound = pModeInfo; - } - } - pModeInfo = pModeInfo->pNext; - } - } + // If there is no more window, nothing we can do! + if (_this->hidden->iPMThreadStatus != 1) + return NULL; - // If we did not find a good fullscreen mode, then return NULL - if (!pModeInfoFound) - { #ifdef DEBUG_BUILD - printf("[os2fslib_SetVideoMode] : Requested video mode not found!\n"); fflush(stdout); + printf + ("[os2fslib_SetVideoMode] : Request for %dx%d @ %dBPP, flags=0x%x\n", + width, height, bpp, flags); + fflush(stdout); #endif - return NULL; - } -#ifdef DEBUG_BUILD - printf("[os2fslib_SetVideoMode] : Found mode!\n"); fflush(stdout); -#endif + // We don't support palette modes! + if (bpp == 8) + bpp = 32; - // We'll possibly adjust the structure, so copy out the values - // into TempModeInfo! - SDL_memcpy(&TempModeInfo, pModeInfoFound, sizeof(TempModeInfo)); - pModeInfoFound = &TempModeInfo; + // Also, we don't support resizable modes in fullscreen mode. + if (flags & SDL_RESIZABLE) + flags &= ~SDL_FULLSCREEN; - if (flags & SDL_RESIZABLE) - { + // No double buffered mode + if (flags & SDL_DOUBLEBUF) + flags &= ~SDL_DOUBLEBUF; + + // And, we don't support HWSURFACE yet. + if (flags & SDL_HWSURFACE) { + flags &= ~SDL_HWSURFACE; + flags |= SDL_SWSURFACE; + } #ifdef DEBUG_BUILD - printf("[os2fslib_SetVideoMode] : Requested mode is resizable, changing width/height\n"); fflush(stdout); + printf + ("[os2fslib_SetVideoMode] : Changed request to %dx%d @ %dBPP, flags=0x%x\n", + width, height, bpp, flags); + fflush(stdout); #endif - // Change width and height to requested one! - TempModeInfo.uiXResolution = width; - TempModeInfo.uiYResolution = height; - TempModeInfo.uiScanLineSize = width * ((TempModeInfo.uiBPP+7)/8); - } - // We can try create new surface! + // First check if there is such a video mode they want! + pModeInfoFound = NULL; - // Make sure this thread is prepared for using the Presentation Manager! - hab = WinInitialize(0); - hmq = WinCreateMsgQueue(hab,0); - // Remember if there was an error at WinCreateMsgQueue(), because we don't - // want to destroy somebody else's queue later. :) - hmqerror = WinGetLastError(hab); + // For fullscreen mode we don't support every resolution! + // So, go through the video modes, and check for such a resolution! + pModeInfoFound = NULL; + pModeInfo = _this->hidden->pAvailableFSLibVideoModes; - + while (pModeInfo) { + // Check all available fullscreen modes for this resolution + if ((pModeInfo->uiXResolution == width) && (pModeInfo->uiYResolution == height) && (pModeInfo->uiBPP != 8)) // palettized modes not yet supported + { + // If good resolution, try to find the exact BPP, or at least + // something similar... + if (!pModeInfoFound) + pModeInfoFound = pModeInfo; + else if ((pModeInfoFound->uiBPP != bpp) && + (pModeInfoFound->uiBPP < pModeInfo->uiBPP)) + pModeInfoFound = pModeInfo; + } + pModeInfo = pModeInfo->pNext; + } - if (DosRequestMutexSem(_this->hidden->hmtxUseSrcBuffer, SEM_INDEFINITE_WAIT)==NO_ERROR) - { + // If we did not find a good fullscreen mode, then try a similar + if (!pModeInfoFound) { +#ifdef DEBUG_BUILD + printf + ("[os2fslib_SetVideoMode] : Requested video mode not found, looking for a similar one!\n"); + fflush(stdout); +#endif + // Go through the video modes again, and find a similar resolution! + pModeInfo = _this->hidden->pAvailableFSLibVideoModes; + while (pModeInfo) { + // Check all available fullscreen modes for this resolution + if ((pModeInfo->uiXResolution >= width) && + (pModeInfo->uiYResolution >= height) && + (pModeInfo->uiBPP == bpp)) { + if (!pModeInfoFound) + pModeInfoFound = pModeInfo; + else if (((pModeInfoFound->uiXResolution - + width) * (pModeInfoFound->uiYResolution - + height)) > + ((pModeInfo->uiXResolution - + width) * (pModeInfo->uiYResolution - height))) { + // Found a mode which is closer than the current one + pModeInfoFound = pModeInfo; + } + } + pModeInfo = pModeInfo->pNext; + } + } + // If we did not find a good fullscreen mode, then return NULL + if (!pModeInfoFound) { #ifdef DEBUG_BUILD - printf("[os2fslib_SetVideoMode] : Creating new SW surface\n"); fflush(stdout); + printf("[os2fslib_SetVideoMode] : Requested video mode not found!\n"); + fflush(stdout); #endif - - // Create new software surface! - pResult = SDL_CreateRGBSurface(SDL_SWSURFACE, - pModeInfoFound->uiXResolution, - pModeInfoFound->uiYResolution, - pModeInfoFound->uiBPP, - ((unsigned int) pModeInfoFound->PixelFormat.ucRedMask) << pModeInfoFound->PixelFormat.ucRedPosition, - ((unsigned int) pModeInfoFound->PixelFormat.ucGreenMask) << pModeInfoFound->PixelFormat.ucGreenPosition, - ((unsigned int) pModeInfoFound->PixelFormat.ucBlueMask) << pModeInfoFound->PixelFormat.ucBluePosition, - ((unsigned int) pModeInfoFound->PixelFormat.ucAlphaMask) << pModeInfoFound->PixelFormat.ucAlphaPosition); - - if (pResult == NULL) - { - DosReleaseMutexSem(_this->hidden->hmtxUseSrcBuffer); - SDL_OutOfMemory(); - return NULL; + return NULL; } - #ifdef DEBUG_BUILD - printf("[os2fslib_SetVideoMode] : Adjusting pixel format\n"); fflush(stdout); + printf("[os2fslib_SetVideoMode] : Found mode!\n"); + fflush(stdout); #endif - // Adjust pixel format mask! - pResult->format->Rmask = ((unsigned int) pModeInfoFound->PixelFormat.ucRedMask) << pModeInfoFound->PixelFormat.ucRedPosition; - pResult->format->Rshift = pModeInfoFound->PixelFormat.ucRedPosition; - pResult->format->Rloss = pModeInfoFound->PixelFormat.ucRedAdjust; - pResult->format->Gmask = ((unsigned int) pModeInfoFound->PixelFormat.ucGreenMask) << pModeInfoFound->PixelFormat.ucGreenPosition; - pResult->format->Gshift = pModeInfoFound->PixelFormat.ucGreenPosition; - pResult->format->Gloss = pModeInfoFound->PixelFormat.ucGreenAdjust; - pResult->format->Bmask = ((unsigned int) pModeInfoFound->PixelFormat.ucBlueMask) << pModeInfoFound->PixelFormat.ucBluePosition; - pResult->format->Bshift = pModeInfoFound->PixelFormat.ucBluePosition; - pResult->format->Bloss = pModeInfoFound->PixelFormat.ucBlueAdjust; - pResult->format->Amask = ((unsigned int) pModeInfoFound->PixelFormat.ucAlphaMask) << pModeInfoFound->PixelFormat.ucAlphaPosition; - pResult->format->Ashift = pModeInfoFound->PixelFormat.ucAlphaPosition; - pResult->format->Aloss = pModeInfoFound->PixelFormat.ucAlphaAdjust; + // We'll possibly adjust the structure, so copy out the values + // into TempModeInfo! + SDL_memcpy(&TempModeInfo, pModeInfoFound, sizeof(TempModeInfo)); + pModeInfoFound = &TempModeInfo; + + if (flags & SDL_RESIZABLE) { +#ifdef DEBUG_BUILD + printf + ("[os2fslib_SetVideoMode] : Requested mode is resizable, changing width/height\n"); + fflush(stdout); +#endif + // Change width and height to requested one! + TempModeInfo.uiXResolution = width; + TempModeInfo.uiYResolution = height; + TempModeInfo.uiScanLineSize = width * ((TempModeInfo.uiBPP + 7) / 8); + } + // We can try create new surface! + + // Make sure this thread is prepared for using the Presentation Manager! + hab = WinInitialize(0); + hmq = WinCreateMsgQueue(hab, 0); + // Remember if there was an error at WinCreateMsgQueue(), because we don't + // want to destroy somebody else's queue later. :) + hmqerror = WinGetLastError(hab); + + + + if (DosRequestMutexSem + (_this->hidden->hmtxUseSrcBuffer, SEM_INDEFINITE_WAIT) == NO_ERROR) { +#ifdef DEBUG_BUILD + printf("[os2fslib_SetVideoMode] : Creating new SW surface\n"); + fflush(stdout); +#endif + + // Create new software surface! + pResult = SDL_CreateRGBSurface(SDL_SWSURFACE, + pModeInfoFound->uiXResolution, + pModeInfoFound->uiYResolution, + pModeInfoFound->uiBPP, + ((unsigned int) pModeInfoFound-> + PixelFormat. + ucRedMask) << pModeInfoFound-> + PixelFormat.ucRedPosition, + ((unsigned int) pModeInfoFound-> + PixelFormat. + ucGreenMask) << pModeInfoFound-> + PixelFormat.ucGreenPosition, + ((unsigned int) pModeInfoFound-> + PixelFormat. + ucBlueMask) << pModeInfoFound-> + PixelFormat.ucBluePosition, + ((unsigned int) pModeInfoFound-> + PixelFormat. + ucAlphaMask) << pModeInfoFound-> + PixelFormat.ucAlphaPosition); + + if (pResult == NULL) { + DosReleaseMutexSem(_this->hidden->hmtxUseSrcBuffer); + SDL_OutOfMemory(); + return NULL; + } +#ifdef DEBUG_BUILD + printf("[os2fslib_SetVideoMode] : Adjusting pixel format\n"); + fflush(stdout); +#endif + + // Adjust pixel format mask! + pResult->format->Rmask = + ((unsigned int) pModeInfoFound->PixelFormat. + ucRedMask) << pModeInfoFound->PixelFormat.ucRedPosition; + pResult->format->Rshift = pModeInfoFound->PixelFormat.ucRedPosition; + pResult->format->Rloss = pModeInfoFound->PixelFormat.ucRedAdjust; + pResult->format->Gmask = + ((unsigned int) pModeInfoFound->PixelFormat. + ucGreenMask) << pModeInfoFound->PixelFormat.ucGreenPosition; + pResult->format->Gshift = pModeInfoFound->PixelFormat.ucGreenPosition; + pResult->format->Gloss = pModeInfoFound->PixelFormat.ucGreenAdjust; + pResult->format->Bmask = + ((unsigned int) pModeInfoFound->PixelFormat. + ucBlueMask) << pModeInfoFound->PixelFormat.ucBluePosition; + pResult->format->Bshift = pModeInfoFound->PixelFormat.ucBluePosition; + pResult->format->Bloss = pModeInfoFound->PixelFormat.ucBlueAdjust; + pResult->format->Amask = + ((unsigned int) pModeInfoFound->PixelFormat. + ucAlphaMask) << pModeInfoFound->PixelFormat.ucAlphaPosition; + pResult->format->Ashift = pModeInfoFound->PixelFormat.ucAlphaPosition; + pResult->format->Aloss = pModeInfoFound->PixelFormat.ucAlphaAdjust; #ifdef REPORT_EMPTY_ALPHA_MASK - pResult->format->Amask = - pResult->format->Ashift = - pResult->format->Aloss = 0; + pResult->format->Amask = + pResult->format->Ashift = pResult->format->Aloss = 0; #endif - // Adjust surface flags - pResult->flags |= (flags & SDL_FULLSCREEN); - pResult->flags |= (flags & SDL_RESIZABLE); + // Adjust surface flags + pResult->flags |= (flags & SDL_FULLSCREEN); + pResult->flags |= (flags & SDL_RESIZABLE); - // It might be that the software surface pitch is not the same as - // the pitch we have, so adjust that! - pModeInfoFound->uiScanLineSize = pResult->pitch; + // It might be that the software surface pitch is not the same as + // the pitch we have, so adjust that! + pModeInfoFound->uiScanLineSize = pResult->pitch; - // Store new source buffer parameters! - SDL_memcpy(&(_this->hidden->SrcBufferDesc), pModeInfoFound, sizeof(*pModeInfoFound)); - _this->hidden->pchSrcBuffer = pResult->pixels; + // Store new source buffer parameters! + SDL_memcpy(&(_this->hidden->SrcBufferDesc), pModeInfoFound, + sizeof(*pModeInfoFound)); + _this->hidden->pchSrcBuffer = pResult->pixels; #ifdef DEBUG_BUILD - printf("[os2fslib_SetVideoMode] : Telling FSLib the stuffs\n"); fflush(stdout); + printf("[os2fslib_SetVideoMode] : Telling FSLib the stuffs\n"); + fflush(stdout); #endif - // Tell the FSLib window the new source image format - FSLib_SetSrcBufferDesc(_this->hidden->hwndClient, &(_this->hidden->SrcBufferDesc)); + // Tell the FSLib window the new source image format + FSLib_SetSrcBufferDesc(_this->hidden->hwndClient, + &(_this->hidden->SrcBufferDesc)); - if ( - ((flags & SDL_RESIZABLE)==0) || - (bFirstCall) - ) - { - bFirstCall = 0; + if (((flags & SDL_RESIZABLE) == 0) || (bFirstCall)) { + bFirstCall = 0; #ifdef DEBUG_BUILD - printf("[os2fslib_SetVideoMode] : Modifying window size\n"); fflush(stdout); + printf("[os2fslib_SetVideoMode] : Modifying window size\n"); + fflush(stdout); #endif - // Calculate frame window size from client window size - rectl.xLeft = 0; - rectl.yBottom = 0; - rectl.xRight = pModeInfoFound->uiXResolution; // Noninclusive - rectl.yTop = pModeInfoFound->uiYResolution; // Noninclusive - WinCalcFrameRect(_this->hidden->hwndFrame, &rectl, FALSE); - - // Set the new size of the main window - SetAccessableWindowPos(_this->hidden->hwndFrame, - HWND_TOP, - 0, 0, - (rectl.xRight-rectl.xLeft), - (rectl.yTop-rectl.yBottom), - SWP_SIZE | SWP_ACTIVATE | SWP_SHOW); - } - - // Set fullscreen mode flag, and switch to fullscreen if needed! - if (flags & SDL_FULLSCREEN) - { + // Calculate frame window size from client window size + rectl.xLeft = 0; + rectl.yBottom = 0; + rectl.xRight = pModeInfoFound->uiXResolution; // Noninclusive + rectl.yTop = pModeInfoFound->uiYResolution; // Noninclusive + WinCalcFrameRect(_this->hidden->hwndFrame, &rectl, FALSE); + + // Set the new size of the main window + SetAccessableWindowPos(_this->hidden->hwndFrame, + HWND_TOP, + 0, 0, + (rectl.xRight - rectl.xLeft), + (rectl.yTop - rectl.yBottom), + SWP_SIZE | SWP_ACTIVATE | SWP_SHOW); + } + // Set fullscreen mode flag, and switch to fullscreen if needed! + if (flags & SDL_FULLSCREEN) { #ifdef DEBUG_BUILD - printf("[os2fslib_SetVideoMode] : Also trying to switch to fullscreen\n"); - fflush(stdout); + printf + ("[os2fslib_SetVideoMode] : Also trying to switch to fullscreen\n"); + fflush(stdout); #endif - FSLib_ToggleFSMode(_this->hidden->hwndClient, 1); - /* Cursor manager functions to FS mode*/ - os2fslib_SetCursorManagementFunctions(_this, 0); - } else - { + FSLib_ToggleFSMode(_this->hidden->hwndClient, 1); + /* Cursor manager functions to FS mode */ + os2fslib_SetCursorManagementFunctions(_this, 0); + } else { #ifdef DEBUG_BUILD - printf("[os2fslib_SetVideoMode] : Also trying to switch to desktop mode\n"); - fflush(stdout); + printf + ("[os2fslib_SetVideoMode] : Also trying to switch to desktop mode\n"); + fflush(stdout); #endif - FSLib_ToggleFSMode(_this->hidden->hwndClient, 0); - /* Cursor manager functions to Windowed mode*/ - os2fslib_SetCursorManagementFunctions(_this, 1); - } + FSLib_ToggleFSMode(_this->hidden->hwndClient, 0); + /* Cursor manager functions to Windowed mode */ + os2fslib_SetCursorManagementFunctions(_this, 1); + } - _this->hidden->pSDLSurface = pResult; + _this->hidden->pSDLSurface = pResult; - DosReleaseMutexSem(_this->hidden->hmtxUseSrcBuffer); - } else - { + DosReleaseMutexSem(_this->hidden->hmtxUseSrcBuffer); + } else { #ifdef DEBUG_BUILD - printf("[os2fslib_SetVideoMode] : Could not get hmtxUseSrcBuffer!\n"); fflush(stdout); + printf("[os2fslib_SetVideoMode] : Could not get hmtxUseSrcBuffer!\n"); + fflush(stdout); #endif - - pResult = NULL; - } - // As we have the new surface, we don't need the current one anymore! - if ((pResult) && (current)) - { + pResult = NULL; + } + + // As we have the new surface, we don't need the current one anymore! + if ((pResult) && (current)) { #ifdef DEBUG_BUILD - printf("[os2fslib_SetVideoMode] : Freeing old surface\n"); fflush(stdout); + printf("[os2fslib_SetVideoMode] : Freeing old surface\n"); + fflush(stdout); #endif - SDL_FreeSurface(current); - } - - // Redraw window - WinInvalidateRegion(_this->hidden->hwndClient, NULL, TRUE); + SDL_FreeSurface(current); + } + // Redraw window + WinInvalidateRegion(_this->hidden->hwndClient, NULL, TRUE); - // Now destroy the message queue, if we've created it! - if (ERRORIDERROR(hmqerror)==0) - { + // Now destroy the message queue, if we've created it! + if (ERRORIDERROR(hmqerror) == 0) { #ifdef DEBUG_BUILD - printf("[os2fslib_SetVideoMode] : Destroying message queue\n"); fflush(stdout); + printf("[os2fslib_SetVideoMode] : Destroying message queue\n"); + fflush(stdout); #endif - WinDestroyMsgQueue(hmq); - } - + WinDestroyMsgQueue(hmq); + } #ifdef DEBUG_BUILD - printf("[os2fslib_SetVideoMode] : Done\n"); fflush(stdout); + printf("[os2fslib_SetVideoMode] : Done\n"); + fflush(stdout); #endif - /* We're done */ + /* We're done */ - // Return with the new surface! - return pResult; + // Return with the new surface! + return pResult; } /* List the available video modes for the given pixel format, sorted from largest to smallest. */ -static SDL_Rect **os2fslib_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags) +static SDL_Rect ** +os2fslib_ListModes(_THIS, SDL_PixelFormat * format, Uint32 flags) { #ifdef DEBUG_BUILD - printf("[os2fslib_ListModes] : ListModes of %d Bpp\n", format->BitsPerPixel); + printf("[os2fslib_ListModes] : ListModes of %d Bpp\n", + format->BitsPerPixel); #endif - // Destroy result of previous call, if there is any - if (_this->hidden->pListModesResult) - { - SDL_free(_this->hidden->pListModesResult); _this->hidden->pListModesResult = NULL; - } - - // For resizable and windowed mode we support every resolution! - if ((flags & SDL_RESIZABLE) && ((flags & SDL_FULLSCREEN) == 0)) - return (SDL_Rect **)-1; - - // Check if they need fullscreen or non-fullscreen video modes! - if ((flags & SDL_FULLSCREEN) == 0) - - { - // For windowed mode we support every resolution! - return (SDL_Rect **)-1; - } else - { - FSLib_VideoMode_p pFSMode; - // For fullscreen mode we don't support every resolution! - // Now create a new list - pFSMode = _this->hidden->pAvailableFSLibVideoModes; - while (pFSMode) - { - if (pFSMode->uiBPP == format->BitsPerPixel) - { - SDL_Rect *pRect = (SDL_Rect *) SDL_malloc(sizeof(SDL_Rect)); - if (pRect) - { - // Fill description - pRect->x = 0; - pRect->y = 0; - pRect->w = pFSMode->uiXResolution; - pRect->h = pFSMode->uiYResolution; + // Destroy result of previous call, if there is any + if (_this->hidden->pListModesResult) { + SDL_free(_this->hidden->pListModesResult); + _this->hidden->pListModesResult = NULL; + } + // For resizable and windowed mode we support every resolution! + if ((flags & SDL_RESIZABLE) && ((flags & SDL_FULLSCREEN) == 0)) + return (SDL_Rect **) - 1; + + // Check if they need fullscreen or non-fullscreen video modes! + if ((flags & SDL_FULLSCREEN) == 0) { + // For windowed mode we support every resolution! + return (SDL_Rect **) - 1; + } else { + FSLib_VideoMode_p pFSMode; + // For fullscreen mode we don't support every resolution! + // Now create a new list + pFSMode = _this->hidden->pAvailableFSLibVideoModes; + while (pFSMode) { + if (pFSMode->uiBPP == format->BitsPerPixel) { + SDL_Rect *pRect = (SDL_Rect *) SDL_malloc(sizeof(SDL_Rect)); + if (pRect) { + // Fill description + pRect->x = 0; + pRect->y = 0; + pRect->w = pFSMode->uiXResolution; + pRect->h = pFSMode->uiYResolution; #ifdef DEBUG_BUILD // printf("!!! Seems to be good!\n"); // printf("F: %dx%d\n", pRect->w, pRect->h); #endif - // And insert into list of pRects - if (!(_this->hidden->pListModesResult)) - { + // And insert into list of pRects + if (!(_this->hidden->pListModesResult)) { #ifdef DEBUG_BUILD // printf("!!! Inserting to beginning\n"); #endif - // We're the first one to be inserted! - _this->hidden->pListModesResult = (SDL_Rect**) SDL_malloc(2*sizeof(SDL_Rect*)); - if (_this->hidden->pListModesResult) - { - _this->hidden->pListModesResult[0] = pRect; - _this->hidden->pListModesResult[1] = NULL; - } else - { - SDL_free(pRect); - } - } else - { - // We're not the first ones, so find the place where we - // have to insert ourselves - SDL_Rect **pNewList; - int iPlace, iNumOfSlots, i; + // We're the first one to be inserted! + _this->hidden->pListModesResult = + (SDL_Rect **) SDL_malloc(2 * sizeof(SDL_Rect *)); + if (_this->hidden->pListModesResult) { + _this->hidden->pListModesResult[0] = pRect; + _this->hidden->pListModesResult[1] = NULL; + } else { + SDL_free(pRect); + } + } else { + // We're not the first ones, so find the place where we + // have to insert ourselves + SDL_Rect **pNewList; + int iPlace, iNumOfSlots, i; #ifdef DEBUG_BUILD // printf("!!! Searching where to insert\n"); #endif - iPlace = -1; iNumOfSlots = 1; // Count the last NULL too! - for (i=0; _this->hidden->pListModesResult[i]; i++) - { - iNumOfSlots++; - if (iPlace==-1) - { - if ((_this->hidden->pListModesResult[i]->w*_this->hidden->pListModesResult[i]->h)< - (pRect->w*pRect->h)) - { - iPlace = i; - } - } - } - if (iPlace==-1) iPlace = iNumOfSlots-1; + iPlace = -1; + iNumOfSlots = 1; // Count the last NULL too! + for (i = 0; _this->hidden->pListModesResult[i]; i++) { + iNumOfSlots++; + if (iPlace == -1) { + if ((_this->hidden-> + pListModesResult[i]->w * + _this->hidden-> + pListModesResult[i]->h) < + (pRect->w * pRect->h)) { + iPlace = i; + } + } + } + if (iPlace == -1) + iPlace = iNumOfSlots - 1; #ifdef DEBUG_BUILD // printf("!!! From %d slots, it will be at %d\n", iNumOfSlots, iPlace); #endif - pNewList = (SDL_Rect**) SDL_realloc(_this->hidden->pListModesResult, (iNumOfSlots+1)*sizeof(SDL_Rect*)); - if (pNewList) - { - for (i=iNumOfSlots;i>iPlace;i--) - pNewList[i] = pNewList[i-1]; - pNewList[iPlace] = pRect; - _this->hidden->pListModesResult = pNewList; - } else - { - SDL_free(pRect); + pNewList = + (SDL_Rect **) SDL_realloc(_this-> + hidden-> + pListModesResult, + (iNumOfSlots + + + 1) * + sizeof(SDL_Rect *)); + if (pNewList) { + for (i = iNumOfSlots; i > iPlace; i--) + pNewList[i] = pNewList[i - 1]; + pNewList[iPlace] = pRect; + _this->hidden->pListModesResult = pNewList; + } else { + SDL_free(pRect); + } + } + } } - } + pFSMode = pFSMode->pNext; } - } - pFSMode = pFSMode->pNext; } - } #ifdef DEBUG_BUILD // printf("Returning list\n"); #endif - return _this->hidden->pListModesResult; + return _this->hidden->pListModesResult; } /* Initialize the native video subsystem, filling 'vformat' with the "best" display pixel format, returning 0 or -1 if there's an error. */ -static int os2fslib_VideoInit(_THIS, SDL_PixelFormat *vformat) +static int +os2fslib_VideoInit(_THIS, SDL_PixelFormat * vformat) { - FSLib_VideoMode_p pDesktopMode; + FSLib_VideoMode_p pDesktopMode; #ifdef DEBUG_BUILD - printf("[os2fslib_VideoInit] : Enter\n"); fflush(stdout); + printf("[os2fslib_VideoInit] : Enter\n"); + fflush(stdout); #endif - // Report the best pixel format. For this, - // we'll use the current desktop format. - pDesktopMode = FSLib_GetDesktopVideoMode(); - if (!pDesktopMode) - { - SDL_SetError("Could not query desktop video mode!"); + // Report the best pixel format. For this, + // we'll use the current desktop format. + pDesktopMode = FSLib_GetDesktopVideoMode(); + if (!pDesktopMode) { + SDL_SetError("Could not query desktop video mode!"); #ifdef DEBUG_BUILD - printf("[os2fslib_VideoInit] : Could not query desktop video mode!\n"); + printf + ("[os2fslib_VideoInit] : Could not query desktop video mode!\n"); #endif - return -1; - } - - /* Determine the current screen size */ - _this->info.current_w = pDesktopMode->uiXResolution; - _this->info.current_h = pDesktopMode->uiYResolution; - - /* Determine the screen depth */ - vformat->BitsPerPixel = pDesktopMode->uiBPP; - vformat->BytesPerPixel = (vformat->BitsPerPixel+7)/8; + return -1; + } - vformat->Rmask = ((unsigned int) pDesktopMode->PixelFormat.ucRedMask) << pDesktopMode->PixelFormat.ucRedPosition; - vformat->Rshift = pDesktopMode->PixelFormat.ucRedPosition; - vformat->Rloss = pDesktopMode->PixelFormat.ucRedAdjust; - vformat->Gmask = ((unsigned int) pDesktopMode->PixelFormat.ucGreenMask) << pDesktopMode->PixelFormat.ucGreenPosition; - vformat->Gshift = pDesktopMode->PixelFormat.ucGreenPosition; - vformat->Gloss = pDesktopMode->PixelFormat.ucGreenAdjust; - vformat->Bmask = ((unsigned int) pDesktopMode->PixelFormat.ucBlueMask) << pDesktopMode->PixelFormat.ucBluePosition; - vformat->Bshift = pDesktopMode->PixelFormat.ucBluePosition; - vformat->Bloss = pDesktopMode->PixelFormat.ucBlueAdjust; - vformat->Amask = ((unsigned int) pDesktopMode->PixelFormat.ucAlphaMask) << pDesktopMode->PixelFormat.ucAlphaPosition; - vformat->Ashift = pDesktopMode->PixelFormat.ucAlphaPosition; - vformat->Aloss = pDesktopMode->PixelFormat.ucAlphaAdjust; + /* Determine the current screen size */ + _this->info.current_w = pDesktopMode->uiXResolution; + _this->info.current_h = pDesktopMode->uiYResolution; + + /* Determine the screen depth */ + vformat->BitsPerPixel = pDesktopMode->uiBPP; + vformat->BytesPerPixel = (vformat->BitsPerPixel + 7) / 8; + + vformat->Rmask = + ((unsigned int) pDesktopMode->PixelFormat.ucRedMask) << pDesktopMode-> + PixelFormat.ucRedPosition; + vformat->Rshift = pDesktopMode->PixelFormat.ucRedPosition; + vformat->Rloss = pDesktopMode->PixelFormat.ucRedAdjust; + vformat->Gmask = + ((unsigned int) pDesktopMode->PixelFormat. + ucGreenMask) << pDesktopMode->PixelFormat.ucGreenPosition; + vformat->Gshift = pDesktopMode->PixelFormat.ucGreenPosition; + vformat->Gloss = pDesktopMode->PixelFormat.ucGreenAdjust; + vformat->Bmask = + ((unsigned int) pDesktopMode->PixelFormat. + ucBlueMask) << pDesktopMode->PixelFormat.ucBluePosition; + vformat->Bshift = pDesktopMode->PixelFormat.ucBluePosition; + vformat->Bloss = pDesktopMode->PixelFormat.ucBlueAdjust; + vformat->Amask = + ((unsigned int) pDesktopMode->PixelFormat. + ucAlphaMask) << pDesktopMode->PixelFormat.ucAlphaPosition; + vformat->Ashift = pDesktopMode->PixelFormat.ucAlphaPosition; + vformat->Aloss = pDesktopMode->PixelFormat.ucAlphaAdjust; #ifdef REPORT_EMPTY_ALPHA_MASK - vformat->Amask = - vformat->Ashift = - vformat->Aloss = 0; + vformat->Amask = vformat->Ashift = vformat->Aloss = 0; #endif - // Fill in some window manager capabilities - _this->info.wm_available = 1; - - // Initialize some internal variables - _this->hidden->pListModesResult = NULL; - _this->hidden->fInFocus = 0; - _this->hidden->iSkipWMMOUSEMOVE = 0; - _this->hidden->iMouseVisible = 1; + // Fill in some window manager capabilities + _this->info.wm_available = 1; - if (getenv("SDL_USE_PROPORTIONAL_WINDOW")) - _this->hidden->bProportionalResize = 1; - else - { - PPIB pib; - PTIB tib; - char *pchFileName, *pchTemp; - char achConfigFile[CCHMAXPATH]; - FILE *hFile; - - /* No environment variable to have proportional window. - * Ok, let's check if this executable is in config file! - */ - _this->hidden->bProportionalResize = 0; + // Initialize some internal variables + _this->hidden->pListModesResult = NULL; + _this->hidden->fInFocus = 0; + _this->hidden->iSkipWMMOUSEMOVE = 0; + _this->hidden->iMouseVisible = 1; - DosGetInfoBlocks(&tib, &pib); - pchTemp = pchFileName = pib->pib_pchcmd; - while (*pchTemp) - { - if (*pchTemp=='\\') - pchFileName = pchTemp+1; - pchTemp++; - } - if (getenv("HOME")) - { - sprintf(achConfigFile, "%s\\.sdl.proportionals", getenv("HOME")); - hFile = fopen(achConfigFile, "rt"); - if (!hFile) - { - /* Seems like the file cannot be opened or does not exist. - * Let's try to create it with defaults! + if (getenv("SDL_USE_PROPORTIONAL_WINDOW")) + _this->hidden->bProportionalResize = 1; + else { + PPIB pib; + PTIB tib; + char *pchFileName, *pchTemp; + char achConfigFile[CCHMAXPATH]; + FILE *hFile; + + /* No environment variable to have proportional window. + * Ok, let's check if this executable is in config file! */ - hFile = fopen(achConfigFile, "wt"); - if (hFile) - { - fprintf(hFile, "; This file is a config file of SDL/2, containing\n"); - fprintf(hFile, "; the list of executables that must have proportional\n"); - fprintf(hFile, "; windows.\n"); - fprintf(hFile, ";\n"); - fprintf(hFile, "; You can add executable filenames into this file,\n"); - fprintf(hFile, "; one under the other. If SDL finds that a given\n"); - fprintf(hFile, "; program is in this list, then that application\n"); - fprintf(hFile, "; will have proportional windows, just like if\n"); - fprintf(hFile, "; the SET SDL_USE_PROPORTIONAL_WINDOW env. variable\n"); - fprintf(hFile, "; would have been set for that process.\n"); - fprintf(hFile, ";\n"); - fprintf(hFile, "\n"); - fprintf(hFile, "dosbox.exe\n"); - fclose(hFile); + _this->hidden->bProportionalResize = 0; + + DosGetInfoBlocks(&tib, &pib); + pchTemp = pchFileName = pib->pib_pchcmd; + while (*pchTemp) { + if (*pchTemp == '\\') + pchFileName = pchTemp + 1; + pchTemp++; } + if (getenv("HOME")) { + sprintf(achConfigFile, "%s\\.sdl.proportionals", getenv("HOME")); + hFile = fopen(achConfigFile, "rt"); + if (!hFile) { + /* Seems like the file cannot be opened or does not exist. + * Let's try to create it with defaults! + */ + hFile = fopen(achConfigFile, "wt"); + if (hFile) { + fprintf(hFile, + "; This file is a config file of SDL/2, containing\n"); + fprintf(hFile, + "; the list of executables that must have proportional\n"); + fprintf(hFile, "; windows.\n"); + fprintf(hFile, ";\n"); + fprintf(hFile, + "; You can add executable filenames into this file,\n"); + fprintf(hFile, + "; one under the other. If SDL finds that a given\n"); + fprintf(hFile, + "; program is in this list, then that application\n"); + fprintf(hFile, + "; will have proportional windows, just like if\n"); + fprintf(hFile, + "; the SET SDL_USE_PROPORTIONAL_WINDOW env. variable\n"); + fprintf(hFile, + "; would have been set for that process.\n"); + fprintf(hFile, ";\n"); + fprintf(hFile, "\n"); + fprintf(hFile, "dosbox.exe\n"); + fclose(hFile); + } - hFile = fopen(achConfigFile, "rt"); - } + hFile = fopen(achConfigFile, "rt"); + } - if (hFile) - { - while (fgets(achConfigFile, sizeof(achConfigFile), hFile)) - { - /* Cut \n from end of string */ + if (hFile) { + while (fgets(achConfigFile, sizeof(achConfigFile), hFile)) { + /* Cut \n from end of string */ - while (achConfigFile[strlen(achConfigFile)-1] == '\n') - achConfigFile[strlen(achConfigFile)-1] = 0; + while (achConfigFile[strlen(achConfigFile) - 1] + == '\n') + achConfigFile[strlen(achConfigFile) - 1] = 0; - /* Compare... */ - if (stricmp(achConfigFile, pchFileName)==0) - { - /* Found it in config file! */ - _this->hidden->bProportionalResize = 1; - break; - } + /* Compare... */ + if (stricmp(achConfigFile, pchFileName) == 0) { + /* Found it in config file! */ + _this->hidden->bProportionalResize = 1; + break; + } + } + fclose(hFile); + } } - fclose(hFile); - } } - } - - DosCreateMutexSem(NULL, &(_this->hidden->hmtxUseSrcBuffer), 0, FALSE); - - // Now create our window with a default size - - // For this, we select the first available fullscreen mode as - // current window size! - SDL_memcpy(&(_this->hidden->SrcBufferDesc), _this->hidden->pAvailableFSLibVideoModes, sizeof(_this->hidden->SrcBufferDesc)); - // Allocate new video buffer! - _this->hidden->pchSrcBuffer = (char *) SDL_malloc(_this->hidden->pAvailableFSLibVideoModes->uiScanLineSize * _this->hidden->pAvailableFSLibVideoModes->uiYResolution); - if (!_this->hidden->pchSrcBuffer) - { -#ifdef DEBUG_BUILD - printf("[os2fslib_VideoInit] : Yikes, not enough memory for new video buffer!\n"); fflush(stdout); -#endif - SDL_SetError("Not enough memory for new video buffer!\n"); - return -1; - } - // For this, we need a message processing thread. - // We'll create a new thread for this, which will do everything - // what is related to PM - _this->hidden->iPMThreadStatus = 0; - _this->hidden->tidPMThread = _beginthread(PMThreadFunc, NULL, 65536, (void *) _this); - if (_this->hidden->tidPMThread <= 0) - { -#ifdef DEBUG_BUILD - printf("[os2fslib_VideoInit] : Could not create PM thread!\n"); -#endif - SDL_SetError("Could not create PM thread"); - return -1; - } + DosCreateMutexSem(NULL, &(_this->hidden->hmtxUseSrcBuffer), 0, FALSE); + + // Now create our window with a default size + + // For this, we select the first available fullscreen mode as + // current window size! + SDL_memcpy(&(_this->hidden->SrcBufferDesc), + _this->hidden->pAvailableFSLibVideoModes, + sizeof(_this->hidden->SrcBufferDesc)); + // Allocate new video buffer! + _this->hidden->pchSrcBuffer = + (char *) SDL_malloc(_this->hidden->pAvailableFSLibVideoModes-> + uiScanLineSize * + _this->hidden->pAvailableFSLibVideoModes-> + uiYResolution); + if (!_this->hidden->pchSrcBuffer) { +#ifdef DEBUG_BUILD + printf + ("[os2fslib_VideoInit] : Yikes, not enough memory for new video buffer!\n"); + fflush(stdout); +#endif + SDL_SetError("Not enough memory for new video buffer!\n"); + return -1; + } + // For this, we need a message processing thread. + // We'll create a new thread for this, which will do everything + // what is related to PM + _this->hidden->iPMThreadStatus = 0; + _this->hidden->tidPMThread = + _beginthread(PMThreadFunc, NULL, 65536, (void *) _this); + if (_this->hidden->tidPMThread <= 0) { +#ifdef DEBUG_BUILD + printf("[os2fslib_VideoInit] : Could not create PM thread!\n"); +#endif + SDL_SetError("Could not create PM thread"); + return -1; + } #ifdef USE_DOSSETPRIORITY - // Burst the priority of PM Thread! - DosSetPriority(PRTYS_THREAD, PRTYC_TIMECRITICAL, 0, _this->hidden->tidPMThread); -#endif - // Wait for the PM thread to initialize! - while (_this->hidden->iPMThreadStatus==0) - DosSleep(32); - // If the PM thread could not set up everything, then - // report an error! - if (_this->hidden->iPMThreadStatus!=1) - { -#ifdef DEBUG_BUILD - printf("[os2fslib_VideoInit] : PMThread reported an error : %d\n", _this->hidden->iPMThreadStatus); -#endif - SDL_SetError("Error initializing PM thread"); - return -1; - } + // Burst the priority of PM Thread! + DosSetPriority(PRTYS_THREAD, PRTYC_TIMECRITICAL, 0, + _this->hidden->tidPMThread); +#endif + // Wait for the PM thread to initialize! + while (_this->hidden->iPMThreadStatus == 0) + DosSleep(32); + // If the PM thread could not set up everything, then + // report an error! + if (_this->hidden->iPMThreadStatus != 1) { +#ifdef DEBUG_BUILD + printf("[os2fslib_VideoInit] : PMThread reported an error : %d\n", + _this->hidden->iPMThreadStatus); +#endif + SDL_SetError("Error initializing PM thread"); + return -1; + } - return 0; + return 0; } -static void os2fslib_DeleteDevice(_THIS) +static void +os2fslib_DeleteDevice(_THIS) { #ifdef DEBUG_BUILD - printf("[os2fslib_DeleteDevice]\n"); fflush(stdout); -#endif - // Free used memory - FSLib_FreeVideoModeList(_this->hidden->pAvailableFSLibVideoModes); - if (_this->hidden->pListModesResult) - SDL_free(_this->hidden->pListModesResult); - if (_this->hidden->pchSrcBuffer) - SDL_free(_this->hidden->pchSrcBuffer); - DosCloseMutexSem(_this->hidden->hmtxUseSrcBuffer); - SDL_free(_this->hidden); - SDL_free(_this); - FSLib_Uninitialize(); + printf("[os2fslib_DeleteDevice]\n"); + fflush(stdout); +#endif + // Free used memory + FSLib_FreeVideoModeList(_this->hidden->pAvailableFSLibVideoModes); + if (_this->hidden->pListModesResult) + SDL_free(_this->hidden->pListModesResult); + if (_this->hidden->pchSrcBuffer) + SDL_free(_this->hidden->pchSrcBuffer); + DosCloseMutexSem(_this->hidden->hmtxUseSrcBuffer); + SDL_free(_this->hidden); + SDL_free(_this); + FSLib_Uninitialize(); } -static int os2fslib_Available(void) +static int +os2fslib_Available(void) { - // If we can run, it means that we could load FSLib, - // so we assume that it's available then! - return 1; + // If we can run, it means that we could load FSLib, + // so we assume that it's available then! + return 1; } -static void os2fslib_MorphToPM() +static void +os2fslib_MorphToPM() { - PPIB pib; - PTIB tib; + PPIB pib; + PTIB tib; - DosGetInfoBlocks(&tib, &pib); + DosGetInfoBlocks(&tib, &pib); - // Change flag from VIO to PM: - if (pib->pib_ultype==2) pib->pib_ultype = 3; + // Change flag from VIO to PM: + if (pib->pib_ultype == 2) + pib->pib_ultype = 3; } -static SDL_VideoDevice *os2fslib_CreateDevice(int devindex) +static SDL_VideoDevice * +os2fslib_CreateDevice(int devindex) { - SDL_VideoDevice *device; - -#ifdef DEBUG_BUILD - printf("[os2fslib_CreateDevice] : Enter\n"); fflush(stdout); -#endif - - /* Initialize all variables that we clean on shutdown */ - device = (SDL_VideoDevice *)SDL_malloc(sizeof(SDL_VideoDevice)); - if ( device ) - { - SDL_memset(device, 0, (sizeof *device)); - // Also allocate memory for private data - device->hidden = (struct SDL_PrivateVideoData *) SDL_malloc((sizeof(struct SDL_PrivateVideoData))); - } - if ( (device == NULL) || (device->hidden == NULL) ) - { - SDL_OutOfMemory(); - if ( device ) - SDL_free(device); - return NULL; - } - SDL_memset(device->hidden, 0, (sizeof *device->hidden)); - - /* Set the function pointers */ -#ifdef DEBUG_BUILD - printf("[os2fslib_CreateDevice] : VideoInit is %p\n", os2fslib_VideoInit); fflush(stdout); -#endif - - /* Initialization/Query functions */ - device->VideoInit = os2fslib_VideoInit; - device->ListModes = os2fslib_ListModes; - device->SetVideoMode = os2fslib_SetVideoMode; - device->ToggleFullScreen = os2fslib_ToggleFullScreen; - device->UpdateMouse = os2fslib_UpdateMouse; - device->CreateYUVOverlay = NULL; - device->SetColors = os2fslib_SetColors; - device->UpdateRects = os2fslib_UpdateRects; - device->VideoQuit = os2fslib_VideoQuit; - /* Hardware acceleration functions */ - device->AllocHWSurface = os2fslib_AllocHWSurface; - device->CheckHWBlit = NULL; - device->FillHWRect = NULL; - device->SetHWColorKey = NULL; - device->SetHWAlpha = NULL; - device->LockHWSurface = os2fslib_LockHWSurface; - device->UnlockHWSurface = os2fslib_UnlockHWSurface; - device->FlipHWSurface = NULL; - device->FreeHWSurface = os2fslib_FreeHWSurface; - /* Window manager functions */ - device->SetCaption = os2fslib_SetCaption; - device->SetIcon = os2fslib_SetIcon; - device->IconifyWindow = os2fslib_IconifyWindow; - device->GrabInput = os2fslib_GrabInput; - device->GetWMInfo = NULL; - /* Cursor manager functions to Windowed mode*/ - os2fslib_SetCursorManagementFunctions(device, 1); - /* Event manager functions */ - device->InitOSKeymap = os2fslib_InitOSKeymap; - device->PumpEvents = os2fslib_PumpEvents; - /* The function used to dispose of this structure */ - device->free = os2fslib_DeleteDevice; - - // Make sure we'll be able to use Win* API even if the application - // was linked to be a VIO application! - os2fslib_MorphToPM(); - - // Now initialize FSLib, and query available video modes! - if (!FSLib_Initialize()) - { - // Could not initialize FSLib! -#ifdef DEBUG_BUILD - printf("[os2fslib_CreateDevice] : Could not initialize FSLib!\n"); -#endif - SDL_SetError("Could not initialize FSLib!"); - SDL_free(device->hidden); - SDL_free(device); - return NULL; - } - device->hidden->pAvailableFSLibVideoModes = - FSLib_GetVideoModeList(); - - return device; + SDL_VideoDevice *device; + +#ifdef DEBUG_BUILD + printf("[os2fslib_CreateDevice] : Enter\n"); + fflush(stdout); +#endif + + /* Initialize all variables that we clean on shutdown */ + device = (SDL_VideoDevice *) SDL_malloc(sizeof(SDL_VideoDevice)); + if (device) { + SDL_memset(device, 0, (sizeof *device)); + // Also allocate memory for private data + device->hidden = (struct SDL_PrivateVideoData *) + SDL_malloc((sizeof(struct SDL_PrivateVideoData))); + } + if ((device == NULL) || (device->hidden == NULL)) { + SDL_OutOfMemory(); + if (device) + SDL_free(device); + return NULL; + } + SDL_memset(device->hidden, 0, (sizeof *device->hidden)); + + /* Set the function pointers */ +#ifdef DEBUG_BUILD + printf("[os2fslib_CreateDevice] : VideoInit is %p\n", os2fslib_VideoInit); + fflush(stdout); +#endif + + /* Initialization/Query functions */ + device->VideoInit = os2fslib_VideoInit; + device->ListModes = os2fslib_ListModes; + device->SetVideoMode = os2fslib_SetVideoMode; + device->ToggleFullScreen = os2fslib_ToggleFullScreen; + device->UpdateMouse = os2fslib_UpdateMouse; + device->CreateYUVOverlay = NULL; + device->SetColors = os2fslib_SetColors; + device->UpdateRects = os2fslib_UpdateRects; + device->VideoQuit = os2fslib_VideoQuit; + /* Hardware acceleration functions */ + device->AllocHWSurface = os2fslib_AllocHWSurface; + device->CheckHWBlit = NULL; + device->FillHWRect = NULL; + device->SetHWColorKey = NULL; + device->SetHWAlpha = NULL; + device->LockHWSurface = os2fslib_LockHWSurface; + device->UnlockHWSurface = os2fslib_UnlockHWSurface; + device->FlipHWSurface = NULL; + device->FreeHWSurface = os2fslib_FreeHWSurface; + /* Window manager functions */ + device->SetCaption = os2fslib_SetCaption; + device->SetIcon = os2fslib_SetIcon; + device->IconifyWindow = os2fslib_IconifyWindow; + device->GrabInput = os2fslib_GrabInput; + device->GetWMInfo = NULL; + /* Cursor manager functions to Windowed mode */ + os2fslib_SetCursorManagementFunctions(device, 1); + /* Event manager functions */ + device->InitOSKeymap = os2fslib_InitOSKeymap; + device->PumpEvents = os2fslib_PumpEvents; + /* The function used to dispose of this structure */ + device->free = os2fslib_DeleteDevice; + + // Make sure we'll be able to use Win* API even if the application + // was linked to be a VIO application! + os2fslib_MorphToPM(); + + // Now initialize FSLib, and query available video modes! + if (!FSLib_Initialize()) { + // Could not initialize FSLib! +#ifdef DEBUG_BUILD + printf("[os2fslib_CreateDevice] : Could not initialize FSLib!\n"); +#endif + SDL_SetError("Could not initialize FSLib!"); + SDL_free(device->hidden); + SDL_free(device); + return NULL; + } + device->hidden->pAvailableFSLibVideoModes = FSLib_GetVideoModeList(); + + return device; } VideoBootStrap OS2FSLib_bootstrap = { - "os2fslib", "OS/2 Video Output using FSLib", - os2fslib_Available, os2fslib_CreateDevice + "os2fslib", "OS/2 Video Output using FSLib", + os2fslib_Available, os2fslib_CreateDevice }; +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/os2fslib/SDL_os2fslib.h b/src/video/os2fslib/SDL_os2fslib.h index 57b40c5de..cb77aa21e 100644 --- a/src/video/os2fslib/SDL_os2fslib.h +++ b/src/video/os2fslib/SDL_os2fslib.h @@ -42,26 +42,26 @@ /* Private display data */ struct SDL_PrivateVideoData { - FSLib_VideoMode_p pAvailableFSLibVideoModes; - SDL_Rect **pListModesResult; // Allocated memory to return list of modes for os2fslib_ListModes() API + FSLib_VideoMode_p pAvailableFSLibVideoModes; + SDL_Rect **pListModesResult; // Allocated memory to return list of modes for os2fslib_ListModes() API - FSLib_VideoMode SrcBufferDesc; // Description of current source image buffer - char *pchSrcBuffer; // The source image buffer itself - SDL_Surface *pSDLSurface; // The SDL surface describing the buffer - HMTX hmtxUseSrcBuffer; // Mutex semaphore to manipulate src buffer - HWND hwndFrame, hwndClient; // Window handle of frame and client - int iPMThreadStatus; // 0: Not running - // 1: Running - // Other: Not running, had an error - int tidPMThread; // Thread ID of PM Thread - int fInFocus; // True if we're in focus! - int iSkipWMMOUSEMOVE; // Number of WM_MOUSEMOVE messages to skip! - int iMouseVisible; // + FSLib_VideoMode SrcBufferDesc; // Description of current source image buffer + char *pchSrcBuffer; // The source image buffer itself + SDL_Surface *pSDLSurface; // The SDL surface describing the buffer + HMTX hmtxUseSrcBuffer; // Mutex semaphore to manipulate src buffer + HWND hwndFrame, hwndClient; // Window handle of frame and client + int iPMThreadStatus; // 0: Not running + // 1: Running + // Other: Not running, had an error + int tidPMThread; // Thread ID of PM Thread + int fInFocus; // True if we're in focus! + int iSkipWMMOUSEMOVE; // Number of WM_MOUSEMOVE messages to skip! + int iMouseVisible; // - PFNWP pfnOldFrameProc; // Old window frame procedure - int bProportionalResize; // 0: No proportional resizing - // 1: Do proportional resizing - ULONG ulResizingFlag; // First resizing flag value + PFNWP pfnOldFrameProc; // Old window frame procedure + int bProportionalResize; // 0: No proportional resizing + // 1: Do proportional resizing + ULONG ulResizingFlag; // First resizing flag value }; /* OS/2 specific backdoor function to be able to set FrameControlFlags of */ @@ -69,3 +69,4 @@ struct SDL_PrivateVideoData extern DECLSPEC void SDLCALL SDL_OS2FSLIB_SetFCFToUse(ULONG ulFCF); #endif /* _SDL_os2fslib_h */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/os2fslib/SDL_vkeys.h b/src/video/os2fslib/SDL_vkeys.h index 0676de9d3..c5014d393 100644 --- a/src/video/os2fslib/SDL_vkeys.h +++ b/src/video/os2fslib/SDL_vkeys.h @@ -72,3 +72,4 @@ #define VK_RBRACKET 0xDD #define VK_APOSTROPHE 0xDE #define VK_BACKTICK 0xDF +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/photon/SDL_ph_events.c b/src/video/photon/SDL_ph_events.c index 47405b743..6704e2377 100644 --- a/src/video/photon/SDL_ph_events.c +++ b/src/video/photon/SDL_ph_events.c @@ -44,13 +44,14 @@ /* The translation tables from a photon keysym to a SDL keysym */ static SDLKey ODD_keymap[256]; static SDLKey MISC_keymap[0xFF + 1]; -SDL_keysym *ph_TranslateKey(PhKeyEvent_t *key, SDL_keysym *keysym); +SDL_keysym *ph_TranslateKey(PhKeyEvent_t * key, SDL_keysym * keysym); /* Check to see if this is a repeated key. (idea shamelessly lifted from GII -- thanks guys! :) */ -static int ph_WarpedMotion(_THIS, PhEvent_t *winEvent) +static int +ph_WarpedMotion(_THIS, PhEvent_t * winEvent) { - PhRect_t *rect = PhGetRects( winEvent ); + PhRect_t *rect = PhGetRects(winEvent); int centre_x, centre_y; int dx, dy; @@ -63,10 +64,10 @@ static int ph_WarpedMotion(_THIS, PhEvent_t *winEvent) dx = rect->ul.x - centre_x; dy = rect->ul.y - centre_y; - posted = SDL_PrivateMouseMotion( 0, 1, dx, dy ); + posted = SDL_PrivateMouseMotion(0, 1, dx, dy); /* Move mouse cursor to middle of the window */ - PtGetAbsPosition( window, &abs_x, &abs_y ); + PtGetAbsPosition(window, &abs_x, &abs_y); PhMoveCursorAbs(PhInputGroup(NULL), abs_x + centre_x, abs_y + centre_y); return (posted); @@ -75,25 +76,26 @@ static int ph_WarpedMotion(_THIS, PhEvent_t *winEvent) /* Control which motion flags the window has set, a flags value of -1 sets * MOTION_BUTTON and MOTION_NOBUTTON */ -static void set_motion_sensitivity(_THIS, unsigned int flags) +static void +set_motion_sensitivity(_THIS, unsigned int flags) { int rid; int fields = Ph_EV_PTR_MOTION_BUTTON | Ph_EV_PTR_MOTION_NOBUTTON; PhRegion_t region; - if( window ) - { + if (window) { rid = PtWidgetRid(window); - if( rid != 0 && PhRegionQuery(rid, ®ion, NULL, NULL, 0) == 0 ) - { - region.events_sense=(region.events_sense & ~fields)|(flags & fields); + if (rid != 0 && PhRegionQuery(rid, ®ion, NULL, NULL, 0) == 0) { + region.events_sense = + (region.events_sense & ~fields) | (flags & fields); PhRegionChange(Ph_REGION_EV_SENSE, 0, ®ion, NULL, NULL); } } } /* Convert the photon button state value to an SDL value */ -static Uint8 ph2sdl_mousebutton(unsigned short button_state) +static Uint8 +ph2sdl_mousebutton(unsigned short button_state) { Uint8 mouse_button = 0; @@ -107,197 +109,174 @@ static Uint8 ph2sdl_mousebutton(unsigned short button_state) return (mouse_button); } -static int ph_DispatchEvent(_THIS) +static int +ph_DispatchEvent(_THIS) { int posted; - PhRect_t* rect; - PhPointerEvent_t* pointerEvent; - PhKeyEvent_t* keyEvent; - PhWindowEvent_t* winEvent; + PhRect_t *rect; + PhPointerEvent_t *pointerEvent; + PhKeyEvent_t *keyEvent; + PhWindowEvent_t *winEvent; int i, buttons; SDL_Rect sdlrects[PH_SDL_MAX_RECTS]; - + posted = 0; - - switch (phevent->type) - { - case Ph_EV_BOUNDARY: + + switch (phevent->type) { + case Ph_EV_BOUNDARY: { - if (phevent->subtype == Ph_EV_PTR_ENTER) - { + if (phevent->subtype == Ph_EV_PTR_ENTER) { posted = SDL_PrivateAppActive(1, SDL_APPMOUSEFOCUS); - } - else if (phevent->subtype ==Ph_EV_PTR_LEAVE) - { - posted = SDL_PrivateAppActive(0, SDL_APPMOUSEFOCUS); + } else if (phevent->subtype == Ph_EV_PTR_LEAVE) { + posted = SDL_PrivateAppActive(0, SDL_APPMOUSEFOCUS); } } break; - case Ph_EV_PTR_MOTION_BUTTON: - case Ph_EV_PTR_MOTION_NOBUTTON: + case Ph_EV_PTR_MOTION_BUTTON: + case Ph_EV_PTR_MOTION_NOBUTTON: { - if (SDL_VideoSurface) - { + if (SDL_VideoSurface) { pointerEvent = PhGetData(phevent); rect = PhGetRects(phevent); - if (mouse_relative) - { + if (mouse_relative) { posted = ph_WarpedMotion(this, phevent); - } - else - { - posted = SDL_PrivateMouseMotion(0, 0, rect->ul.x, rect->ul.y); + } else { + posted = + SDL_PrivateMouseMotion(0, 0, rect->ul.x, rect->ul.y); } } } break; - case Ph_EV_BUT_PRESS: + case Ph_EV_BUT_PRESS: { pointerEvent = PhGetData(phevent); buttons = ph2sdl_mousebutton(pointerEvent->buttons); - if (buttons != 0) - { + if (buttons != 0) { posted = SDL_PrivateMouseButton(SDL_PRESSED, buttons, 0, 0); } } break; - case Ph_EV_BUT_RELEASE: + case Ph_EV_BUT_RELEASE: { pointerEvent = PhGetData(phevent); buttons = ph2sdl_mousebutton(pointerEvent->buttons); - if (phevent->subtype == Ph_EV_RELEASE_REAL && buttons != 0) - { + if (phevent->subtype == Ph_EV_RELEASE_REAL && buttons != 0) { posted = SDL_PrivateMouseButton(SDL_RELEASED, buttons, 0, 0); - } - else if(phevent->subtype == Ph_EV_RELEASE_PHANTOM) - { + } else if (phevent->subtype == Ph_EV_RELEASE_PHANTOM) { /* If the mouse is outside the window, * only a phantom release event is sent, so * check if the window doesn't have mouse focus. * Not perfect, maybe checking the mouse button * state for Ph_EV_BOUNDARY events would be * better. */ - if ((SDL_GetAppState() & SDL_APPMOUSEFOCUS) == 0) - { - posted = SDL_PrivateMouseButton(SDL_RELEASED, buttons, 0, 0); + if ((SDL_GetAppState() & SDL_APPMOUSEFOCUS) == 0) { + posted = + SDL_PrivateMouseButton(SDL_RELEASED, buttons, 0, 0); } } } break; - case Ph_EV_WM: + case Ph_EV_WM: { winEvent = PhGetData(phevent); /* losing focus */ - if ((winEvent->event_f==Ph_WM_FOCUS) && (winEvent->event_state==Ph_WM_EVSTATE_FOCUSLOST)) - { + if ((winEvent->event_f == Ph_WM_FOCUS) + && (winEvent->event_state == Ph_WM_EVSTATE_FOCUSLOST)) { set_motion_sensitivity(this, Ph_EV_PTR_MOTION_BUTTON); - posted = SDL_PrivateAppActive(0, SDL_APPINPUTFOCUS); + posted = SDL_PrivateAppActive(0, SDL_APPINPUTFOCUS); } /* gaining focus */ - else if ((winEvent->event_f==Ph_WM_FOCUS) && (winEvent->event_state==Ph_WM_EVSTATE_FOCUS)) - { + else if ((winEvent->event_f == Ph_WM_FOCUS) + && (winEvent->event_state == Ph_WM_EVSTATE_FOCUS)) { set_motion_sensitivity(this, -1); posted = SDL_PrivateAppActive(1, SDL_APPINPUTFOCUS); } /* request quit */ - else if (winEvent->event_f==Ph_WM_CLOSE) - { + else if (winEvent->event_f == Ph_WM_CLOSE) { posted = SDL_PrivateQuit(); } /* request hide/unhide */ - else if (winEvent->event_f==Ph_WM_HIDE) - { - if (currently_hided) - { - /* got unhide window event */ - /* TODO: restore application's palette if in palette mode */ - currently_hided=0; - } - else - { - /* got hide window event */ - /* TODO: restore original palette if in palette mode */ - currently_hided=1; + else if (winEvent->event_f == Ph_WM_HIDE) { + if (currently_hided) { + /* got unhide window event */ + /* TODO: restore application's palette if in palette mode */ + currently_hided = 0; + } else { + /* got hide window event */ + /* TODO: restore original palette if in palette mode */ + currently_hided = 1; } } /* request to resize */ - else if (winEvent->event_f==Ph_WM_RESIZE) - { - currently_maximized=0; - #if (_NTO_VERSION < 630) - SDL_PrivateResize(winEvent->size.w+1, winEvent->size.h+1); - #else - /* QNX 6.3.0 have this bug fixed */ - SDL_PrivateResize(winEvent->size.w, winEvent->size.h); - #endif /* _NTO_VERSION */ + else if (winEvent->event_f == Ph_WM_RESIZE) { + currently_maximized = 0; +#if (_NTO_VERSION < 630) + SDL_PrivateResize(winEvent->size.w + 1, winEvent->size.h + 1); +#else + /* QNX 6.3.0 have this bug fixed */ + SDL_PrivateResize(winEvent->size.w, winEvent->size.h); +#endif /* _NTO_VERSION */ } /* request to move */ - else if (winEvent->event_f==Ph_WM_MOVE) - { - if (current_overlay!=NULL) - { - int lockedstate=current_overlay->hwdata->locked; - int chromastate=current_overlay->hwdata->ischromakey; - int error; - SDL_Rect src, dst; - - current_overlay->hwdata->locked=1; - src.x = 0; - src.y = 0; - src.w = current_overlay->w; - src.y = current_overlay->h; - dst.x=current_overlay->hwdata->CurrentViewPort.pos.x; - dst.y=current_overlay->hwdata->CurrentViewPort.pos.y; - dst.w=current_overlay->hwdata->CurrentViewPort.size.w; - dst.h=current_overlay->hwdata->CurrentViewPort.size.h; - current_overlay->hwdata->ischromakey=0; - error=ph_DisplayYUVOverlay(this, current_overlay, &src, &dst); - if (!error) - { - current_overlay->hwdata->ischromakey=chromastate; - current_overlay->hwdata->locked=lockedstate; - } + else if (winEvent->event_f == Ph_WM_MOVE) { + if (current_overlay != NULL) { + int lockedstate = current_overlay->hwdata->locked; + int chromastate = current_overlay->hwdata->ischromakey; + int error; + SDL_Rect src, dst; + + current_overlay->hwdata->locked = 1; + src.x = 0; + src.y = 0; + src.w = current_overlay->w; + src.y = current_overlay->h; + dst.x = current_overlay->hwdata->CurrentViewPort.pos.x; + dst.y = current_overlay->hwdata->CurrentViewPort.pos.y; + dst.w = current_overlay->hwdata->CurrentViewPort.size.w; + dst.h = current_overlay->hwdata->CurrentViewPort.size.h; + current_overlay->hwdata->ischromakey = 0; + error = + ph_DisplayYUVOverlay(this, current_overlay, + &src, &dst); + if (!error) { + current_overlay->hwdata->ischromakey = chromastate; + current_overlay->hwdata->locked = lockedstate; + } } } /* maximize request */ - else if (winEvent->event_f==Ph_WM_MAX) - { + else if (winEvent->event_f == Ph_WM_MAX) { /* window already moved and resized here */ - currently_maximized=1; + currently_maximized = 1; } /* restore request */ - else if (winEvent->event_f==Ph_WM_RESTORE) - { + else if (winEvent->event_f == Ph_WM_RESTORE) { /* window already moved and resized here */ - currently_maximized=0; + currently_maximized = 0; } } break; /* window has been resized, moved or removed */ - case Ph_EV_EXPOSE: + case Ph_EV_EXPOSE: { - if (phevent->num_rects!=0) - { + if (phevent->num_rects != 0) { int numrects; - if (SDL_VideoSurface) - { + if (SDL_VideoSurface) { rect = PhGetRects(phevent); - if (phevent->num_rects>PH_SDL_MAX_RECTS) - { - /* sorry, buffers underrun, we'll update only first PH_SDL_MAX_RECTS rects */ - numrects=PH_SDL_MAX_RECTS; + if (phevent->num_rects > PH_SDL_MAX_RECTS) { + /* sorry, buffers underrun, we'll update only first PH_SDL_MAX_RECTS rects */ + numrects = PH_SDL_MAX_RECTS; } - for(i=0; inum_rects; i++) - { + for (i = 0; i < phevent->num_rects; i++) { sdlrects[i].x = rect[i].ul.x; sdlrects[i].y = rect[i].ul.y; sdlrects[i].w = rect[i].lr.x - rect[i].ul.x + 1; @@ -306,35 +285,39 @@ static int ph_DispatchEvent(_THIS) this->UpdateRects(this, phevent->num_rects, sdlrects); - if (current_overlay!=NULL) - { - int lockedstate=current_overlay->hwdata->locked; + if (current_overlay != NULL) { + int lockedstate = current_overlay->hwdata->locked; int error; SDL_Rect src, dst; - current_overlay->hwdata->locked=1; + current_overlay->hwdata->locked = 1; src.x = 0; src.y = 0; src.w = current_overlay->w; src.y = current_overlay->h; - dst.x=current_overlay->hwdata->CurrentViewPort.pos.x; - dst.y=current_overlay->hwdata->CurrentViewPort.pos.y; - dst.w=current_overlay->hwdata->CurrentViewPort.size.w; - dst.h=current_overlay->hwdata->CurrentViewPort.size.h; - current_overlay->hwdata->forcedredraw=1; - error=ph_DisplayYUVOverlay(this, current_overlay, &src, &dst); - if (!error) - { - current_overlay->hwdata->forcedredraw=0; - current_overlay->hwdata->locked=lockedstate; + dst.x = + current_overlay->hwdata->CurrentViewPort.pos.x; + dst.y = + current_overlay->hwdata->CurrentViewPort.pos.y; + dst.w = + current_overlay->hwdata->CurrentViewPort.size.w; + dst.h = + current_overlay->hwdata->CurrentViewPort.size.h; + current_overlay->hwdata->forcedredraw = 1; + error = + ph_DisplayYUVOverlay(this, + current_overlay, &src, &dst); + if (!error) { + current_overlay->hwdata->forcedredraw = 0; + current_overlay->hwdata->locked = lockedstate; } } } } } - break; + break; - case Ph_EV_KEY: + case Ph_EV_KEY: { SDL_keysym keysym; @@ -342,208 +325,223 @@ static int ph_DispatchEvent(_THIS) keyEvent = PhGetData(phevent); - if (Pk_KF_Key_Down & keyEvent->key_flags) - { + if (Pk_KF_Key_Down & keyEvent->key_flags) { /* split the wheel events from real key events */ - if ((keyEvent->key_cap==Pk_Up) && (keyEvent->key_scan==0) && ((keyEvent->key_flags & Pk_KF_Scan_Valid)==Pk_KF_Scan_Valid)) - { - posted = SDL_PrivateMouseButton(SDL_PRESSED, SDL_BUTTON_WHEELUP, 0, 0); - break; + if ((keyEvent->key_cap == Pk_Up) + && (keyEvent->key_scan == 0) + && ((keyEvent->key_flags & Pk_KF_Scan_Valid) == + Pk_KF_Scan_Valid)) { + posted = + SDL_PrivateMouseButton(SDL_PRESSED, + SDL_BUTTON_WHEELUP, 0, 0); + break; } - if ((keyEvent->key_cap==Pk_Down) && (keyEvent->key_scan==0) && ((keyEvent->key_flags & Pk_KF_Scan_Valid)==Pk_KF_Scan_Valid)) - { - posted = SDL_PrivateMouseButton(SDL_PRESSED, SDL_BUTTON_WHEELDOWN, 0, 0); - break; + if ((keyEvent->key_cap == Pk_Down) + && (keyEvent->key_scan == 0) + && ((keyEvent->key_flags & Pk_KF_Scan_Valid) == + Pk_KF_Scan_Valid)) { + posted = + SDL_PrivateMouseButton(SDL_PRESSED, + SDL_BUTTON_WHEELDOWN, 0, 0); + break; } - posted = SDL_PrivateKeyboard(SDL_PRESSED, ph_TranslateKey(keyEvent, &keysym)); - } - else /* must be key release */ - { + posted = + SDL_PrivateKeyboard(SDL_PRESSED, + ph_TranslateKey(keyEvent, &keysym)); + } else { /* must be key release */ + /* split the wheel events from real key events */ - if ((keyEvent->key_cap==Pk_Up) && (keyEvent->key_scan==0) && ((keyEvent->key_flags & Pk_KF_Scan_Valid)==Pk_KF_Scan_Valid)) - { - posted = SDL_PrivateMouseButton(SDL_RELEASED, SDL_BUTTON_WHEELUP, 0, 0); - break; + if ((keyEvent->key_cap == Pk_Up) + && (keyEvent->key_scan == 0) + && ((keyEvent->key_flags & Pk_KF_Scan_Valid) == + Pk_KF_Scan_Valid)) { + posted = + SDL_PrivateMouseButton(SDL_RELEASED, + SDL_BUTTON_WHEELUP, 0, 0); + break; } - if ((keyEvent->key_cap==Pk_Down) && (keyEvent->key_scan==0) && ((keyEvent->key_flags & Pk_KF_Scan_Valid)==Pk_KF_Scan_Valid)) - { - posted = SDL_PrivateMouseButton(SDL_RELEASED, SDL_BUTTON_WHEELDOWN, 0, 0); - break; + if ((keyEvent->key_cap == Pk_Down) + && (keyEvent->key_scan == 0) + && ((keyEvent->key_flags & Pk_KF_Scan_Valid) == + Pk_KF_Scan_Valid)) { + posted = + SDL_PrivateMouseButton(SDL_RELEASED, + SDL_BUTTON_WHEELDOWN, 0, 0); + break; } - posted = SDL_PrivateKeyboard(SDL_RELEASED, ph_TranslateKey( keyEvent, &keysym)); + posted = + SDL_PrivateKeyboard(SDL_RELEASED, + ph_TranslateKey(keyEvent, &keysym)); } } break; - - case Ph_EV_INFO: + + case Ph_EV_INFO: { - if (phevent->subtype==Ph_OFFSCREEN_INVALID) - { - unsigned long* EvInfoData; - - EvInfoData=(unsigned long*)PhGetData(phevent); - - switch (*EvInfoData) - { - case Pg_VIDEO_MODE_SWITCHED: - { - } - break; - case Pg_ENTERED_DIRECT: - { - } - break; - case Pg_EXITED_DIRECT: - { - } - break; - case Pg_DRIVER_STARTED: - { - } - break; - } - } + if (phevent->subtype == Ph_OFFSCREEN_INVALID) { + unsigned long *EvInfoData; + + EvInfoData = (unsigned long *) PhGetData(phevent); + + switch (*EvInfoData) { + case Pg_VIDEO_MODE_SWITCHED: + { + } + break; + case Pg_ENTERED_DIRECT: + { + } + break; + case Pg_EXITED_DIRECT: + { + } + break; + case Pg_DRIVER_STARTED: + { + } + break; + } + } } break; } - return(posted); + return (posted); } /* perform a blocking read if no events available */ -int ph_Pending(_THIS) +int +ph_Pending(_THIS) { /* Flush the display connection and look to see if events are queued */ PgFlush(); - while (1) - { - switch(PhEventPeek(phevent, EVENT_SIZE)) - { - case Ph_EVENT_MSG: - return 1; - case -1: - SDL_SetError("ph_Pending(): PhEventNext failed.\n"); - return 0; - default: - return 0; + while (1) { + switch (PhEventPeek(phevent, EVENT_SIZE)) { + case Ph_EVENT_MSG: + return 1; + case -1: + SDL_SetError("ph_Pending(): PhEventNext failed.\n"); + return 0; + default: + return 0; } } /* Oh well, nothing is ready .. */ - return(0); + return (0); } -void ph_PumpEvents(_THIS) +void +ph_PumpEvents(_THIS) { /* Flush the display connection and look to see if events are queued */ PgFlush(); - while (ph_Pending(this)) - { + while (ph_Pending(this)) { PtEventHandler(phevent); ph_DispatchEvent(this); } } -void ph_InitKeymap(void) +void +ph_InitKeymap(void) { int i; /* Odd keys used in international keyboards */ - for (i=0; ikey_cap; - switch (cap>>8) - { - case 0x00: /* Latin 1 */ - case 0x01: /* Latin 2 */ - case 0x02: /* Latin 3 */ - case 0x03: /* Latin 4 */ - case 0x04: /* Katakana */ - case 0x05: /* Arabic */ - case 0x06: /* Cyrillic */ - case 0x07: /* Greek */ - case 0x08: /* Technical */ - case 0x0A: /* Publishing */ - case 0x0C: /* Hebrew */ - case 0x0D: /* Thai */ - keysym->sym = (SDLKey)(cap&0xFF); - /* Map capital letter syms to lowercase */ - if ((keysym->sym >= 'A')&&(keysym->sym <= 'Z')) - keysym->sym += ('a'-'A'); - break; - case 0xF0: - keysym->sym = MISC_keymap[cap&0xFF]; - break; - default: - keysym->sym = SDLK_UNKNOWN; - break; + switch (cap >> 8) { + case 0x00: /* Latin 1 */ + case 0x01: /* Latin 2 */ + case 0x02: /* Latin 3 */ + case 0x03: /* Latin 4 */ + case 0x04: /* Katakana */ + case 0x05: /* Arabic */ + case 0x06: /* Cyrillic */ + case 0x07: /* Greek */ + case 0x08: /* Technical */ + case 0x0A: /* Publishing */ + case 0x0C: /* Hebrew */ + case 0x0D: /* Thai */ + keysym->sym = (SDLKey) (cap & 0xFF); + /* Map capital letter syms to lowercase */ + if ((keysym->sym >= 'A') && (keysym->sym <= 'Z')) + keysym->sym += ('a' - 'A'); + break; + case 0xF0: + keysym->sym = MISC_keymap[cap & 0xFF]; + break; + default: + keysym->sym = SDLK_UNKNOWN; + break; } keysym->scancode = key->key_scan; keysym->unicode = 0; - if (SDL_TranslateUNICODE) - { + if (SDL_TranslateUNICODE) { char utf8[MB_CUR_MAX]; int utf8len; wchar_t unicode; - switch (keysym->scancode) - { - /* Esc key */ - case 0x01: keysym->unicode = 27; - break; - /* BackSpace key */ - case 0x0E: keysym->unicode = 127; - break; - /* Enter key */ - case 0x1C: keysym->unicode = 10; - break; - default: - utf8len = PhKeyToMb(utf8, key); - if (utf8len > 0) - { - utf8len = mbtowc(&unicode, utf8, utf8len); - if (utf8len > 0) - { - keysym->unicode = unicode; - } - } - break; + switch (keysym->scancode) { + /* Esc key */ + case 0x01: + keysym->unicode = 27; + break; + /* BackSpace key */ + case 0x0E: + keysym->unicode = 127; + break; + /* Enter key */ + case 0x1C: + keysym->unicode = 10; + break; + default: + utf8len = PhKeyToMb(utf8, key); + if (utf8len > 0) { + utf8len = mbtowc(&unicode, utf8, utf8len); + if (utf8len > 0) { + keysym->unicode = unicode; + } + } + break; } } @@ -618,7 +614,10 @@ SDL_keysym *ph_TranslateKey(PhKeyEvent_t *key, SDL_keysym *keysym) return (keysym); } -void ph_InitOSKeymap(_THIS) +void +ph_InitOSKeymap(_THIS) { ph_InitKeymap(); } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/photon/SDL_ph_events_c.h b/src/video/photon/SDL_ph_events_c.h index 04152fe50..1fce23db3 100644 --- a/src/video/photon/SDL_ph_events_c.h +++ b/src/video/photon/SDL_ph_events_c.h @@ -35,3 +35,4 @@ extern void ph_InitOSKeymap(_THIS); extern void ph_PumpEvents(_THIS); #endif /* __SDL_PH_EVENTS_H__ */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/photon/SDL_ph_gl.c b/src/video/photon/SDL_ph_gl.c index 97e16d2b9..09c0495c1 100644 --- a/src/video/photon/SDL_ph_gl.c +++ b/src/video/photon/SDL_ph_gl.c @@ -29,73 +29,76 @@ #if (_NTO_VERSION >= 630) /* PhotonGL functions */ - GLPH_DECLARE_FUNCS; +GLPH_DECLARE_FUNCS; #endif /* 6.3.0 */ #if (_NTO_VERSION < 630) -void ph_GL_SwapBuffers(_THIS) +void +ph_GL_SwapBuffers(_THIS) { PgSetRegion(PtWidgetRid(window)); PdOpenGLContextSwapBuffers(oglctx); } #else -void ph_GL_SwapBuffers(_THIS) +void +ph_GL_SwapBuffers(_THIS) { qnxgl_swap_buffers(oglbuffers); } #endif /* 6.3.0 */ -int ph_GL_GetAttribute(_THIS, SDL_GLattr attrib, int* value) +int +ph_GL_GetAttribute(_THIS, SDL_GLattr attrib, int *value) { - switch (attrib) - { - case SDL_GL_DOUBLEBUFFER: - *value=this->gl_config.double_buffer; - break; - case SDL_GL_STENCIL_SIZE: - *value=this->gl_config.stencil_size; - break; - case SDL_GL_DEPTH_SIZE: - *value=this->gl_config.depth_size; - break; + switch (attrib) { + case SDL_GL_DOUBLEBUFFER: + *value = this->gl_config.double_buffer; + break; + case SDL_GL_STENCIL_SIZE: + *value = this->gl_config.stencil_size; + break; + case SDL_GL_DEPTH_SIZE: + *value = this->gl_config.depth_size; + break; #if (_NTO_VERSION >= 630) - case SDL_GL_RED_SIZE: - *value=this->gl_config.red_size; - break; - case SDL_GL_GREEN_SIZE: - *value=this->gl_config.green_size; - break; - case SDL_GL_BLUE_SIZE: - *value=this->gl_config.blue_size; - break; - case SDL_GL_ALPHA_SIZE: - *value=this->gl_config.alpha_size; - break; - case SDL_GL_ACCUM_RED_SIZE: - *value=this->gl_config.accum_red_size; - break; - case SDL_GL_ACCUM_GREEN_SIZE: - *value=this->gl_config.accum_green_size; - break; - case SDL_GL_ACCUM_BLUE_SIZE: - *value=this->gl_config.accum_blue_size; - break; - case SDL_GL_ACCUM_ALPHA_SIZE: - *value=this->gl_config.accum_alpha_size; - break; - case SDL_GL_STEREO: - *value=this->gl_config.stereo; - break; + case SDL_GL_RED_SIZE: + *value = this->gl_config.red_size; + break; + case SDL_GL_GREEN_SIZE: + *value = this->gl_config.green_size; + break; + case SDL_GL_BLUE_SIZE: + *value = this->gl_config.blue_size; + break; + case SDL_GL_ALPHA_SIZE: + *value = this->gl_config.alpha_size; + break; + case SDL_GL_ACCUM_RED_SIZE: + *value = this->gl_config.accum_red_size; + break; + case SDL_GL_ACCUM_GREEN_SIZE: + *value = this->gl_config.accum_green_size; + break; + case SDL_GL_ACCUM_BLUE_SIZE: + *value = this->gl_config.accum_blue_size; + break; + case SDL_GL_ACCUM_ALPHA_SIZE: + *value = this->gl_config.accum_alpha_size; + break; + case SDL_GL_STEREO: + *value = this->gl_config.stereo; + break; #endif /* 6.3.0 */ - default: - *value=0; - return(-1); + default: + *value = 0; + return (-1); } return 0; } #if (_NTO_VERSION < 630) -int ph_GL_LoadLibrary(_THIS, const char* path) +int +ph_GL_LoadLibrary(_THIS, const char *path) { /* if code compiled with SDL_VIDEO_OPENGL, that mean that library already linked */ this->gl_config.driver_loaded = 1; @@ -103,20 +106,19 @@ int ph_GL_LoadLibrary(_THIS, const char* path) return 0; } #else -int ph_GL_LoadLibrary(_THIS, const char* path) +int +ph_GL_LoadLibrary(_THIS, const char *path) { - void* handle; - int dlopen_flags=RTLD_WORLD | RTLD_GROUP; + void *handle; + int dlopen_flags = RTLD_WORLD | RTLD_GROUP; - if (this->gl_config.dll_handle!=NULL) - { + if (this->gl_config.dll_handle != NULL) { return 0; } handle = dlopen(path, dlopen_flags); - if (handle==NULL) - { + if (handle == NULL) { SDL_SetError("ph_GL_LoadLibrary(): Could not load OpenGL library"); return -1; } @@ -124,35 +126,35 @@ int ph_GL_LoadLibrary(_THIS, const char* path) this->gl_config.dll_handle = handle; this->gl_config.driver_loaded = 1; - SDL_strlcpy(this->gl_config.driver_path, path, SDL_arraysize(this->gl_config.driver_path)); + SDL_strlcpy(this->gl_config.driver_path, path, + SDL_arraysize(this->gl_config.driver_path)); return 0; } #endif /* 6.3.0 */ #if (_NTO_VERSION < 630) -void* ph_GL_GetProcAddress(_THIS, const char* proc) +void * +ph_GL_GetProcAddress(_THIS, const char *proc) { return NULL; } #else -void* ph_GL_GetProcAddress(_THIS, const char* proc) +void * +ph_GL_GetProcAddress(_THIS, const char *proc) { - void* function; + void *function; - if (this->gl_config.dll_handle==NULL) - { + if (this->gl_config.dll_handle == NULL) { ph_GL_LoadLibrary(this, DEFAULT_OPENGL); - if (this->gl_config.dll_handle==NULL) - { + if (this->gl_config.dll_handle == NULL) { return NULL; } } - - function=qnxgl_get_func(proc, oglctx, 0); - if (function==NULL) - { - function=dlsym(this->gl_config.dll_handle, proc); + + function = qnxgl_get_func(proc, oglctx, 0); + if (function == NULL) { + function = dlsym(this->gl_config.dll_handle, proc); } return function; @@ -160,27 +162,26 @@ void* ph_GL_GetProcAddress(_THIS, const char* proc) #endif /* 6.3.0 */ #if (_NTO_VERSION < 630) -int ph_GL_MakeCurrent(_THIS) +int +ph_GL_MakeCurrent(_THIS) { PgSetRegion(PtWidgetRid(window)); - if (oglctx!=NULL) - { + if (oglctx != NULL) { PhDCSetCurrent(oglctx); } return 0; } #else -int ph_GL_MakeCurrent(_THIS) +int +ph_GL_MakeCurrent(_THIS) { PgSetRegion(PtWidgetRid(window)); - if (oglctx!=NULL) - { - if (qnxgl_set_current(oglctx) == -1) - { - return -1; + if (oglctx != NULL) { + if (qnxgl_set_current(oglctx) == -1) { + return -1; } } @@ -192,66 +193,57 @@ int ph_GL_MakeCurrent(_THIS) /* This code is actual for the Photon3D Runtime which was available prior to 6.3 only */ -int ph_SetupOpenGLContext(_THIS, int width, int height, int bpp, Uint32 flags) +int +ph_SetupOpenGLContext(_THIS, int width, int height, int bpp, Uint32 flags) { PhDim_t dim; uint64_t OGLAttrib[PH_OGL_MAX_ATTRIBS]; - int exposepost=0; + int exposepost = 0; int OGLargc; - dim.w=width; - dim.h=height; - - if ((oglctx!=NULL) && (oglflags==flags) && (oglbpp==bpp)) - { - PdOpenGLContextResize(oglctx, &dim); - PhDCSetCurrent(oglctx); - return 0; - } - else - { - if (oglctx!=NULL) - { - PhDCSetCurrent(NULL); - PhDCRelease(oglctx); - oglctx=NULL; - exposepost=1; - } + dim.w = width; + dim.h = height; + + if ((oglctx != NULL) && (oglflags == flags) && (oglbpp == bpp)) { + PdOpenGLContextResize(oglctx, &dim); + PhDCSetCurrent(oglctx); + return 0; + } else { + if (oglctx != NULL) { + PhDCSetCurrent(NULL); + PhDCRelease(oglctx); + oglctx = NULL; + exposepost = 1; + } } - OGLargc=0; - if (this->gl_config.depth_size) - { - OGLAttrib[OGLargc++]=PHOGL_ATTRIB_DEPTH_BITS; - OGLAttrib[OGLargc++]=this->gl_config.depth_size; + OGLargc = 0; + if (this->gl_config.depth_size) { + OGLAttrib[OGLargc++] = PHOGL_ATTRIB_DEPTH_BITS; + OGLAttrib[OGLargc++] = this->gl_config.depth_size; } - if (this->gl_config.stencil_size) - { - OGLAttrib[OGLargc++]=PHOGL_ATTRIB_STENCIL_BITS; - OGLAttrib[OGLargc++]=this->gl_config.stencil_size; + if (this->gl_config.stencil_size) { + OGLAttrib[OGLargc++] = PHOGL_ATTRIB_STENCIL_BITS; + OGLAttrib[OGLargc++] = this->gl_config.stencil_size; } - OGLAttrib[OGLargc++]=PHOGL_ATTRIB_FORCE_SW; - if (flags & SDL_FULLSCREEN) - { - OGLAttrib[OGLargc++]=PHOGL_ATTRIB_FULLSCREEN; - OGLAttrib[OGLargc++]=PHOGL_ATTRIB_DIRECT; - OGLAttrib[OGLargc++]=PHOGL_ATTRIB_FULLSCREEN_BEST; - OGLAttrib[OGLargc++]=PHOGL_ATTRIB_FULLSCREEN_CENTER; + OGLAttrib[OGLargc++] = PHOGL_ATTRIB_FORCE_SW; + if (flags & SDL_FULLSCREEN) { + OGLAttrib[OGLargc++] = PHOGL_ATTRIB_FULLSCREEN; + OGLAttrib[OGLargc++] = PHOGL_ATTRIB_DIRECT; + OGLAttrib[OGLargc++] = PHOGL_ATTRIB_FULLSCREEN_BEST; + OGLAttrib[OGLargc++] = PHOGL_ATTRIB_FULLSCREEN_CENTER; } - OGLAttrib[OGLargc++]=PHOGL_ATTRIB_NONE; + OGLAttrib[OGLargc++] = PHOGL_ATTRIB_NONE; - if (this->gl_config.double_buffer) - { - oglctx=PdCreateOpenGLContext(2, &dim, 0, OGLAttrib); - } - else - { - oglctx=PdCreateOpenGLContext(1, &dim, 0, OGLAttrib); + if (this->gl_config.double_buffer) { + oglctx = PdCreateOpenGLContext(2, &dim, 0, OGLAttrib); + } else { + oglctx = PdCreateOpenGLContext(1, &dim, 0, OGLAttrib); } - if (oglctx==NULL) - { - SDL_SetError("ph_SetupOpenGLContext(): cannot create OpenGL context !\n"); + if (oglctx == NULL) { + SDL_SetError + ("ph_SetupOpenGLContext(): cannot create OpenGL context !\n"); return -1; } @@ -259,11 +251,10 @@ int ph_SetupOpenGLContext(_THIS, int width, int height, int bpp, Uint32 flags) PtFlush(); - oglflags=flags; - oglbpp=bpp; + oglflags = flags; + oglbpp = bpp; - if (exposepost!=0) - { + if (exposepost != 0) { /* OpenGL context has been recreated, so report about this fact */ SDL_PrivateExpose(); } @@ -275,10 +266,11 @@ int ph_SetupOpenGLContext(_THIS, int width, int height, int bpp, Uint32 flags) /* This code is actual for the built-in PhGL support, which became available since 6.3 */ -int ph_SetupOpenGLContext(_THIS, int width, int height, int bpp, Uint32 flags) +int +ph_SetupOpenGLContext(_THIS, int width, int height, int bpp, Uint32 flags) { qnxgl_buf_attrib_t qnxgl_attribs[PH_OGL_MAX_ATTRIBS]; - qnxgl_buf_attrib_t* qnxgl_attribs_slide; + qnxgl_buf_attrib_t *qnxgl_attribs_slide; int num_interfaces = 0; int num_buffers = 0; @@ -286,88 +278,95 @@ int ph_SetupOpenGLContext(_THIS, int width, int height, int bpp, Uint32 flags) num_interfaces = qnxgl_init(NULL, NULL, 0); - if (num_interfaces < 0) - { - SDL_SetError("ph_SetupOpenGLContext(): cannot initialize OpenGL subsystem !\n"); + if (num_interfaces < 0) { + SDL_SetError + ("ph_SetupOpenGLContext(): cannot initialize OpenGL subsystem !\n"); return -1; } - if (num_interfaces == 0) - { - SDL_SetError("ph_SetupOpenGLContext(): there are no available OpenGL renderers was found !\n"); + if (num_interfaces == 0) { + SDL_SetError + ("ph_SetupOpenGLContext(): there are no available OpenGL renderers was found !\n"); return -1; } /* Driver is linked */ - this->gl_config.driver_loaded=1; + this->gl_config.driver_loaded = 1; /* Initialize the OpenGL context attributes */ - qnxgl_attribs_slide=qnxgl_attribs; + qnxgl_attribs_slide = qnxgl_attribs; /* Depth size */ - if (this->gl_config.depth_size) - { + if (this->gl_config.depth_size) { fprintf(stderr, "setted depth size %d\n", this->gl_config.depth_size); - qnxgl_attribs_slide = qnxgl_attrib_set_depth(qnxgl_attribs_slide, this->gl_config.depth_size); + qnxgl_attribs_slide = + qnxgl_attrib_set_depth(qnxgl_attribs_slide, + this->gl_config.depth_size); } /* Stencil size */ - if (this->gl_config.stencil_size) - { - qnxgl_attribs_slide = qnxgl_attrib_set_stencil(qnxgl_attribs_slide, this->gl_config.stencil_size); + if (this->gl_config.stencil_size) { + qnxgl_attribs_slide = + qnxgl_attrib_set_stencil(qnxgl_attribs_slide, + this->gl_config.stencil_size); } /* The sum of the accum bits of each channel */ - if ((this->gl_config.accum_red_size != 0) && (this->gl_config.accum_blue_size != 0) && - (this->gl_config.accum_green_size != 0)) - { + if ((this->gl_config.accum_red_size != 0) + && (this->gl_config.accum_blue_size != 0) + && (this->gl_config.accum_green_size != 0)) { qnxgl_attribs_slide = qnxgl_attrib_set_accum(qnxgl_attribs_slide, - this->gl_config.accum_red_size + this->gl_config.accum_blue_size + - this->gl_config.accum_green_size + this->gl_config.accum_alpha_size); + this->gl_config. + accum_red_size + + this->gl_config. + accum_blue_size + + this->gl_config. + accum_green_size + + this->gl_config. + accum_alpha_size); } - + /* Stereo mode */ - if (this->gl_config.stereo) - { + if (this->gl_config.stereo) { qnxgl_attribs_slide = qnxgl_attrib_set_stereo(qnxgl_attribs_slide); } /* Fullscreen mode */ - if ((flags & SDL_FULLSCREEN) == SDL_FULLSCREEN) - { - qnxgl_attribs_slide = qnxgl_attrib_set_hint_fullscreen(qnxgl_attribs_slide); + if ((flags & SDL_FULLSCREEN) == SDL_FULLSCREEN) { + qnxgl_attribs_slide = + qnxgl_attrib_set_hint_fullscreen(qnxgl_attribs_slide); } - + /* Double buffering mode */ - if (this->gl_config.double_buffer) - { - num_buffers=2; - } - else - { - num_buffers=1; + if (this->gl_config.double_buffer) { + num_buffers = 2; + } else { + num_buffers = 1; } /* Loading the function pointers so we can use the extensions */ GLPH_LOAD_FUNCS_GC(oglctx); /* Set the buffers region to be that of our window's region */ - qnxgl_attribs_slide = glph_attrib_set_region(qnxgl_attribs_slide, PtWidgetRid(window)); + qnxgl_attribs_slide = + glph_attrib_set_region(qnxgl_attribs_slide, PtWidgetRid(window)); /* End of the attributes array */ qnxgl_attribs_slide = qnxgl_attrib_set_end(qnxgl_attribs_slide); - + /* Create the buffers with the specified color model */ - fprintf(stderr, "ARGB: %d, %d, %d, %d\n", this->gl_config.alpha_size, this->gl_config.red_size, this->gl_config.green_size, this->gl_config.blue_size); - oglbuffers = qnxgl_buffers_create( - QNXGL_FORMAT_BEST_RGB, + fprintf(stderr, "ARGB: %d, %d, %d, %d\n", this->gl_config.alpha_size, + this->gl_config.red_size, this->gl_config.green_size, + this->gl_config.blue_size); + oglbuffers = qnxgl_buffers_create(QNXGL_FORMAT_BEST_RGB, /* __QNXGL_BUILD_FORMAT(0, __QNXGL_COLOR_MODEL_RGB, this->gl_config.alpha_size, this->gl_config.red_size, this->gl_config.green_size, this->gl_config.blue_size), */ - num_buffers, width, height, qnxgl_attribs, -1); + num_buffers, width, height, + qnxgl_attribs, -1); - if (oglbuffers == NULL) - { - SDL_SetError("ph_SetupOpenGLContext(): failed to create OpenGL buffers !\n"); + if (oglbuffers == NULL) { + SDL_SetError + ("ph_SetupOpenGLContext(): failed to create OpenGL buffers !\n"); qnxgl_finish(); return -1; } @@ -375,18 +374,18 @@ int ph_SetupOpenGLContext(_THIS, int width, int height, int bpp, Uint32 flags) /* Create a QNXGL context for the previously created buffer */ oglctx = qnxgl_context_create(oglbuffers, NULL); - if (oglctx == NULL) - { - SDL_SetError("ph_SetupOpenGLContext(): failed to create OpenGL context !\n"); + if (oglctx == NULL) { + SDL_SetError + ("ph_SetupOpenGLContext(): failed to create OpenGL context !\n"); qnxgl_buffers_destroy(oglbuffers); qnxgl_finish(); return -1; } /* Attempt to make the context current so we can use OpenGL commands */ - if (qnxgl_set_current(oglctx) == -1) - { - SDL_SetError("ph_SetupOpenGLContext(): failed to make the OpenGL context current !\n"); + if (qnxgl_set_current(oglctx) == -1) { + SDL_SetError + ("ph_SetupOpenGLContext(): failed to make the OpenGL context current !\n"); qnxgl_context_destroy(oglctx); qnxgl_buffers_destroy(oglbuffers); qnxgl_finish(); @@ -395,8 +394,8 @@ int ph_SetupOpenGLContext(_THIS, int width, int height, int bpp, Uint32 flags) PtFlush(); - oglflags=flags; - oglbpp=bpp; + oglflags = flags; + oglbpp = bpp; return 0; } @@ -404,3 +403,4 @@ int ph_SetupOpenGLContext(_THIS, int width, int height, int bpp, Uint32 flags) #endif /* _NTO_VERSION */ #endif /* SDL_VIDEO_OPENGL */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/photon/SDL_ph_gl.h b/src/video/photon/SDL_ph_gl.h index d749bd89a..3b5d39792 100644 --- a/src/video/photon/SDL_ph_gl.h +++ b/src/video/photon/SDL_ph_gl.h @@ -29,13 +29,15 @@ #define DEFAULT_OPENGL "/usr/lib/libGL.so" #if SDL_VIDEO_OPENGL - void ph_GL_SwapBuffers(_THIS); - int ph_GL_GetAttribute(_THIS, SDL_GLattr attrib, int* value); - int ph_GL_LoadLibrary(_THIS, const char* path); - void* ph_GL_GetProcAddress(_THIS, const char* proc); - int ph_GL_MakeCurrent(_THIS); - - int ph_SetupOpenGLContext(_THIS, int width, int height, int bpp, Uint32 flags); +void ph_GL_SwapBuffers(_THIS); +int ph_GL_GetAttribute(_THIS, SDL_GLattr attrib, int *value); +int ph_GL_LoadLibrary(_THIS, const char *path); +void *ph_GL_GetProcAddress(_THIS, const char *proc); +int ph_GL_MakeCurrent(_THIS); + +int ph_SetupOpenGLContext(_THIS, int width, int height, int bpp, + Uint32 flags); #endif /* SDL_VIDEO_OPENGL */ #endif /* __SDL_PH_GL_H__ */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/photon/SDL_ph_image.c b/src/video/photon/SDL_ph_image.c index 199ad9ef1..12bcc2a1c 100644 --- a/src/video/photon/SDL_ph_image.c +++ b/src/video/photon/SDL_ph_image.c @@ -32,38 +32,44 @@ #include "SDL_ph_modes_c.h" #include "SDL_ph_gl.h" -int ph_SetupImage(_THIS, SDL_Surface *screen) +int +ph_SetupImage(_THIS, SDL_Surface * screen) { - PgColor_t* palette=NULL; - int type=0; + PgColor_t *palette = NULL; + int type = 0; int bpp; - - bpp=screen->format->BitsPerPixel; + + bpp = screen->format->BitsPerPixel; /* Determine image type */ - switch(bpp) - { - case 8:{ + switch (bpp) { + case 8: + { type = Pg_IMAGE_PALETTE_BYTE; } break; - case 15:{ - type = Pg_IMAGE_DIRECT_555; + case 15: + { + type = Pg_IMAGE_DIRECT_555; } break; - case 16:{ - type = Pg_IMAGE_DIRECT_565; + case 16: + { + type = Pg_IMAGE_DIRECT_565; } break; - case 24:{ + case 24: + { type = Pg_IMAGE_DIRECT_888; } break; - case 32:{ + case 32: + { type = Pg_IMAGE_DIRECT_8888; } break; - default:{ + default: + { SDL_SetError("ph_SetupImage(): unsupported bpp=%d !\n", bpp); return -1; } @@ -71,31 +77,33 @@ int ph_SetupImage(_THIS, SDL_Surface *screen) } /* palette emulation code */ - if ((bpp==8) && (desktoppal==SDLPH_PAL_EMULATE)) - { + if ((bpp == 8) && (desktoppal == SDLPH_PAL_EMULATE)) { /* creating image palette */ - palette=SDL_malloc(_Pg_MAX_PALETTE*sizeof(PgColor_t)); - if (palette==NULL) - { - SDL_SetError("ph_SetupImage(): can't allocate memory for palette !\n"); + palette = SDL_malloc(_Pg_MAX_PALETTE * sizeof(PgColor_t)); + if (palette == NULL) { + SDL_SetError + ("ph_SetupImage(): can't allocate memory for palette !\n"); return -1; } PgGetPalette(palette); /* using shared memory for speed (set last param to 1) */ - if ((SDL_Image = PhCreateImage(NULL, screen->w, screen->h, type, palette, _Pg_MAX_PALETTE, 1)) == NULL) - { - SDL_SetError("ph_SetupImage(): PhCreateImage() failed for bpp=8 !\n"); + if ((SDL_Image = + PhCreateImage(NULL, screen->w, screen->h, type, palette, + _Pg_MAX_PALETTE, 1)) == NULL) { + SDL_SetError + ("ph_SetupImage(): PhCreateImage() failed for bpp=8 !\n"); SDL_free(palette); return -1; } - } - else - { + } else { /* using shared memory for speed (set last param to 1) */ - if ((SDL_Image = PhCreateImage(NULL, screen->w, screen->h, type, NULL, 0, 1)) == NULL) - { - SDL_SetError("ph_SetupImage(): PhCreateImage() failed for bpp=%d !\n", bpp); + if ((SDL_Image = + PhCreateImage(NULL, screen->w, screen->h, type, NULL, 0, + 1)) == NULL) { + SDL_SetError + ("ph_SetupImage(): PhCreateImage() failed for bpp=%d !\n", + bpp); return -1; } } @@ -108,61 +116,70 @@ int ph_SetupImage(_THIS, SDL_Surface *screen) return 0; } -int ph_SetupOCImage(_THIS, SDL_Surface *screen) +int +ph_SetupOCImage(_THIS, SDL_Surface * screen) { int type = 0; int bpp; OCImage.flags = screen->flags; - - bpp=screen->format->BitsPerPixel; + + bpp = screen->format->BitsPerPixel; /* Determine image type */ - switch(bpp) - { - case 8: { - type = Pg_IMAGE_PALETTE_BYTE; - } - break; - case 15:{ - type = Pg_IMAGE_DIRECT_555; - } - break; - case 16:{ - type = Pg_IMAGE_DIRECT_565; - } - break; - case 24:{ - type = Pg_IMAGE_DIRECT_888; - } - break; - case 32:{ - type = Pg_IMAGE_DIRECT_8888; - } - break; - default:{ - SDL_SetError("ph_SetupOCImage(): unsupported bpp=%d !\n", bpp); - return -1; - } - break; + switch (bpp) { + case 8: + { + type = Pg_IMAGE_PALETTE_BYTE; + } + break; + case 15: + { + type = Pg_IMAGE_DIRECT_555; + } + break; + case 16: + { + type = Pg_IMAGE_DIRECT_565; + } + break; + case 24: + { + type = Pg_IMAGE_DIRECT_888; + } + break; + case 32: + { + type = Pg_IMAGE_DIRECT_8888; + } + break; + default: + { + SDL_SetError("ph_SetupOCImage(): unsupported bpp=%d !\n", bpp); + return -1; + } + break; } /* Currently offscreen contexts with the same bit depth as display bpp only can be created */ - OCImage.offscreen_context = PdCreateOffscreenContext(0, screen->w, screen->h, Pg_OSC_MEM_PAGE_ALIGN); + OCImage.offscreen_context = + PdCreateOffscreenContext(0, screen->w, screen->h, + Pg_OSC_MEM_PAGE_ALIGN); - if (OCImage.offscreen_context == NULL) - { - SDL_SetError("ph_SetupOCImage(): PdCreateOffscreenContext() function failed !\n"); + if (OCImage.offscreen_context == NULL) { + SDL_SetError + ("ph_SetupOCImage(): PdCreateOffscreenContext() function failed !\n"); return -1; } screen->pitch = OCImage.offscreen_context->pitch; - OCImage.dc_ptr = (unsigned char *)PdGetOffscreenContextPtr(OCImage.offscreen_context); + OCImage.dc_ptr = + (unsigned char *) PdGetOffscreenContextPtr(OCImage.offscreen_context); - if (OCImage.dc_ptr == NULL) - { - SDL_SetError("ph_SetupOCImage(): PdGetOffscreenContextPtr function failed !\n"); + if (OCImage.dc_ptr == NULL) { + SDL_SetError + ("ph_SetupOCImage(): PdGetOffscreenContextPtr function failed !\n"); PhDCRelease(OCImage.offscreen_context); return -1; } @@ -180,54 +197,59 @@ int ph_SetupOCImage(_THIS, SDL_Surface *screen) return 0; } -int ph_SetupFullScreenImage(_THIS, SDL_Surface* screen) +int +ph_SetupFullScreenImage(_THIS, SDL_Surface * screen) { OCImage.flags = screen->flags; /* Begin direct and fullscreen mode */ - if (!ph_EnterFullScreen(this, screen, PH_ENTER_DIRECTMODE)) - { + if (!ph_EnterFullScreen(this, screen, PH_ENTER_DIRECTMODE)) { return -1; } /* store palette for fullscreen */ - if ((screen->format->BitsPerPixel==8) && (desktopbpp!=8)) - { + if ((screen->format->BitsPerPixel == 8) && (desktopbpp != 8)) { PgGetPalette(savedpal); PgGetPalette(syspalph); } - OCImage.offscreen_context = PdCreateOffscreenContext(0, 0, 0, Pg_OSC_MAIN_DISPLAY | Pg_OSC_MEM_PAGE_ALIGN | Pg_OSC_CRTC_SAFE); - if (OCImage.offscreen_context == NULL) - { - SDL_SetError("ph_SetupFullScreenImage(): PdCreateOffscreenContext() function failed !\n"); + OCImage.offscreen_context = + PdCreateOffscreenContext(0, 0, 0, + Pg_OSC_MAIN_DISPLAY | Pg_OSC_MEM_PAGE_ALIGN + | Pg_OSC_CRTC_SAFE); + if (OCImage.offscreen_context == NULL) { + SDL_SetError + ("ph_SetupFullScreenImage(): PdCreateOffscreenContext() function failed !\n"); return -1; } - - if ((screen->flags & SDL_DOUBLEBUF) == SDL_DOUBLEBUF) - { - OCImage.offscreen_backcontext = PdDupOffscreenContext(OCImage.offscreen_context, Pg_OSC_MEM_PAGE_ALIGN | Pg_OSC_CRTC_SAFE); - if (OCImage.offscreen_backcontext == NULL) - { - SDL_SetError("ph_SetupFullScreenImage(): PdCreateOffscreenContext(back) function failed !\n"); + + if ((screen->flags & SDL_DOUBLEBUF) == SDL_DOUBLEBUF) { + OCImage.offscreen_backcontext = + PdDupOffscreenContext(OCImage.offscreen_context, + Pg_OSC_MEM_PAGE_ALIGN | Pg_OSC_CRTC_SAFE); + if (OCImage.offscreen_backcontext == NULL) { + SDL_SetError + ("ph_SetupFullScreenImage(): PdCreateOffscreenContext(back) function failed !\n"); return -1; } } - OCImage.FrameData0 = (unsigned char *)PdGetOffscreenContextPtr(OCImage.offscreen_context); - if (OCImage.FrameData0 == NULL) - { - SDL_SetError("ph_SetupFullScreenImage(): PdGetOffscreenContextPtr() function failed !\n"); + OCImage.FrameData0 = + (unsigned char *) PdGetOffscreenContextPtr(OCImage.offscreen_context); + if (OCImage.FrameData0 == NULL) { + SDL_SetError + ("ph_SetupFullScreenImage(): PdGetOffscreenContextPtr() function failed !\n"); ph_DestroyImage(this, screen); return -1; } - if ((screen->flags & SDL_DOUBLEBUF) == SDL_DOUBLEBUF) - { - OCImage.FrameData1 = (unsigned char *)PdGetOffscreenContextPtr(OCImage.offscreen_backcontext); - if (OCImage.FrameData1 == NULL) - { - SDL_SetError("ph_SetupFullScreenImage(back): PdGetOffscreenContextPtr() function failed !\n"); + if ((screen->flags & SDL_DOUBLEBUF) == SDL_DOUBLEBUF) { + OCImage.FrameData1 = + (unsigned char *) PdGetOffscreenContextPtr(OCImage. + offscreen_backcontext); + if (OCImage.FrameData1 == NULL) { + SDL_SetError + ("ph_SetupFullScreenImage(back): PdGetOffscreenContextPtr() function failed !\n"); ph_DestroyImage(this, screen); return -1; } @@ -237,51 +259,46 @@ int ph_SetupFullScreenImage(_THIS, SDL_Surface* screen) PgFlush(); PgWaitHWIdle(); - if ((screen->flags & SDL_DOUBLEBUF) == SDL_DOUBLEBUF) - { + if ((screen->flags & SDL_DOUBLEBUF) == SDL_DOUBLEBUF) { OCImage.current = 0; PhDCSetCurrent(OCImage.offscreen_context); screen->pitch = OCImage.offscreen_context->pitch; screen->pixels = OCImage.FrameData0; - + /* emulate 640x400 videomode */ - if (videomode_emulatemode==1) - { - int i; - - for (i=0; i<40; i++) - { - SDL_memset(screen->pixels+screen->pitch*i, 0x00, screen->pitch); - } - for (i=440; i<480; i++) - { - SDL_memset(screen->pixels+screen->pitch*i, 0x00, screen->pitch); - } - screen->pixels+=screen->pitch*40; + if (videomode_emulatemode == 1) { + int i; + + for (i = 0; i < 40; i++) { + SDL_memset(screen->pixels + screen->pitch * i, 0x00, + screen->pitch); + } + for (i = 440; i < 480; i++) { + SDL_memset(screen->pixels + screen->pitch * i, 0x00, + screen->pitch); + } + screen->pixels += screen->pitch * 40; } PgSwapDisplay(OCImage.offscreen_backcontext, 0); - } - else - { + } else { OCImage.current = 0; PhDCSetCurrent(OCImage.offscreen_context); screen->pitch = OCImage.offscreen_context->pitch; screen->pixels = OCImage.FrameData0; /* emulate 640x400 videomode */ - if (videomode_emulatemode==1) - { - int i; - - for (i=0; i<40; i++) - { - SDL_memset(screen->pixels+screen->pitch*i, 0x00, screen->pitch); - } - for (i=440; i<480; i++) - { - SDL_memset(screen->pixels+screen->pitch*i, 0x00, screen->pitch); - } - screen->pixels+=screen->pitch*40; + if (videomode_emulatemode == 1) { + int i; + + for (i = 0; i < 40; i++) { + SDL_memset(screen->pixels + screen->pitch * i, 0x00, + screen->pitch); + } + for (i = 440; i < 480; i++) { + SDL_memset(screen->pixels + screen->pitch * i, 0x00, + screen->pitch); + } + screen->pixels += screen->pitch * 40; } } @@ -296,98 +313,90 @@ int ph_SetupFullScreenImage(_THIS, SDL_Surface* screen) #if SDL_VIDEO_OPENGL -int ph_SetupOpenGLImage(_THIS, SDL_Surface* screen) +int +ph_SetupOpenGLImage(_THIS, SDL_Surface * screen) { this->UpdateRects = ph_OpenGLUpdate; - screen->pixels=NULL; - screen->pitch=NULL; + screen->pixels = NULL; + screen->pitch = NULL; - #if (_NTO_VERSION >= 630) - if ((screen->flags & SDL_FULLSCREEN) == SDL_FULLSCREEN) - { - if (!ph_EnterFullScreen(this, screen, PH_IGNORE_DIRECTMODE)) - { - screen->flags &= ~SDL_FULLSCREEN; - return -1; - } +#if (_NTO_VERSION >= 630) + if ((screen->flags & SDL_FULLSCREEN) == SDL_FULLSCREEN) { + if (!ph_EnterFullScreen(this, screen, PH_IGNORE_DIRECTMODE)) { + screen->flags &= ~SDL_FULLSCREEN; + return -1; } - #endif /* 6.3.0 */ + } +#endif /* 6.3.0 */ - if (ph_SetupOpenGLContext(this, screen->w, screen->h, screen->format->BitsPerPixel, screen->flags)!=0) - { - screen->flags &= ~SDL_OPENGL; + if (ph_SetupOpenGLContext + (this, screen->w, screen->h, screen->format->BitsPerPixel, + screen->flags) != 0) { + screen->flags &= ~SDL_INTERNALOPENGL; return -1; } - + return 0; } #endif /* SDL_VIDEO_OPENGL */ -void ph_DestroyImage(_THIS, SDL_Surface* screen) +void +ph_DestroyImage(_THIS, SDL_Surface * screen) { #if SDL_VIDEO_OPENGL - if ((screen->flags & SDL_OPENGL)==SDL_OPENGL) - { - if (oglctx) - { - #if (_NTO_VERSION < 630) - PhDCSetCurrent(NULL); - PhDCRelease(oglctx); - #else - qnxgl_context_destroy(oglctx); - qnxgl_buffers_destroy(oglbuffers); - qnxgl_finish(); - #endif /* 6.3.0 */ - oglctx=NULL; - oglbuffers=NULL; - oglflags=0; - oglbpp=0; + if (screen->flags & SDL_INTERNALOPENGL) { + if (oglctx) { +#if (_NTO_VERSION < 630) + PhDCSetCurrent(NULL); + PhDCRelease(oglctx); +#else + qnxgl_context_destroy(oglctx); + qnxgl_buffers_destroy(oglbuffers); + qnxgl_finish(); +#endif /* 6.3.0 */ + oglctx = NULL; + oglbuffers = NULL; + oglflags = 0; + oglbpp = 0; } - - #if (_NTO_VERSION >= 630) - if (currently_fullscreen) - { - ph_LeaveFullScreen(this); - } - #endif /* 6.3.0 */ +#if (_NTO_VERSION >= 630) + if (currently_fullscreen) { + ph_LeaveFullScreen(this); + } +#endif /* 6.3.0 */ return; } #endif /* SDL_VIDEO_OPENGL */ - if (currently_fullscreen) - { + if (currently_fullscreen) { /* if we right now in 8bpp fullscreen we must release palette */ - if ((screen->format->BitsPerPixel==8) && (desktopbpp!=8)) - { + if ((screen->format->BitsPerPixel == 8) && (desktopbpp != 8)) { PgSetPalette(syspalph, 0, -1, 0, 0, 0); - PgSetPalette(savedpal, 0, 0, _Pg_MAX_PALETTE, Pg_PALSET_GLOBAL | Pg_PALSET_FORCE_EXPOSE, 0); + PgSetPalette(savedpal, 0, 0, _Pg_MAX_PALETTE, + Pg_PALSET_GLOBAL | Pg_PALSET_FORCE_EXPOSE, 0); PgFlush(); } ph_LeaveFullScreen(this); } - if (OCImage.offscreen_context != NULL) - { + if (OCImage.offscreen_context != NULL) { PhDCRelease(OCImage.offscreen_context); OCImage.offscreen_context = NULL; OCImage.FrameData0 = NULL; } - if (OCImage.offscreen_backcontext != NULL) - { + if (OCImage.offscreen_backcontext != NULL) { PhDCRelease(OCImage.offscreen_backcontext); OCImage.offscreen_backcontext = NULL; OCImage.FrameData1 = NULL; } OCImage.CurrentFrameData = NULL; - if (SDL_Image) - { + if (SDL_Image) { /* if palette allocated, free it */ - if (SDL_Image->palette) - { + if (SDL_Image->palette) { SDL_free(SDL_Image->palette); } PgShmemDestroy(SDL_Image->image); @@ -397,160 +406,141 @@ void ph_DestroyImage(_THIS, SDL_Surface* screen) /* Must be zeroed everytime */ SDL_Image = NULL; - if (screen) - { + if (screen) { screen->pixels = NULL; } } -int ph_UpdateHWInfo(_THIS) +int +ph_UpdateHWInfo(_THIS) { PgVideoModeInfo_t vmode; PgHWCaps_t hwcaps; /* Update video ram amount */ - if (PgGetGraphicsHWCaps(&hwcaps) < 0) - { - SDL_SetError("ph_UpdateHWInfo(): GetGraphicsHWCaps() function failed !\n"); + if (PgGetGraphicsHWCaps(&hwcaps) < 0) { + SDL_SetError + ("ph_UpdateHWInfo(): GetGraphicsHWCaps() function failed !\n"); return -1; } - this->info.video_mem=hwcaps.currently_available_video_ram/1024; + this->info.video_mem = hwcaps.currently_available_video_ram / 1024; /* obtain current mode capabilities */ - if (PgGetVideoModeInfo(hwcaps.current_video_mode, &vmode) < 0) - { - SDL_SetError("ph_UpdateHWInfo(): GetVideoModeInfo() function failed !\n"); + if (PgGetVideoModeInfo(hwcaps.current_video_mode, &vmode) < 0) { + SDL_SetError + ("ph_UpdateHWInfo(): GetVideoModeInfo() function failed !\n"); return -1; } - if ((vmode.mode_capabilities1 & PgVM_MODE_CAP1_OFFSCREEN) == PgVM_MODE_CAP1_OFFSCREEN) - { + if ((vmode.mode_capabilities1 & PgVM_MODE_CAP1_OFFSCREEN) == + PgVM_MODE_CAP1_OFFSCREEN) { /* this is a special test for drivers which tries to lie about offscreen capability */ - if (hwcaps.currently_available_video_ram!=0) - { - this->info.hw_available = 1; - } - else - { - this->info.hw_available = 0; + if (hwcaps.currently_available_video_ram != 0) { + this->info.hw_available = 1; + } else { + this->info.hw_available = 0; } - } - else - { + } else { this->info.hw_available = 0; } - if ((vmode.mode_capabilities2 & PgVM_MODE_CAP2_RECTANGLE) == PgVM_MODE_CAP2_RECTANGLE) - { + if ((vmode.mode_capabilities2 & PgVM_MODE_CAP2_RECTANGLE) == + PgVM_MODE_CAP2_RECTANGLE) { this->info.blit_fill = 1; - } - else - { + } else { this->info.blit_fill = 0; } - if ((vmode.mode_capabilities2 & PgVM_MODE_CAP2_BITBLT) == PgVM_MODE_CAP2_BITBLT) - { + if ((vmode.mode_capabilities2 & PgVM_MODE_CAP2_BITBLT) == + PgVM_MODE_CAP2_BITBLT) { this->info.blit_hw = 1; - } - else - { + } else { this->info.blit_hw = 0; } - if ((vmode.mode_capabilities2 & PgVM_MODE_CAP2_ALPHA_BLEND) == PgVM_MODE_CAP2_ALPHA_BLEND) - { + if ((vmode.mode_capabilities2 & PgVM_MODE_CAP2_ALPHA_BLEND) == + PgVM_MODE_CAP2_ALPHA_BLEND) { this->info.blit_hw_A = 1; - } - else - { + } else { this->info.blit_hw_A = 0; } - - if ((vmode.mode_capabilities2 & PgVM_MODE_CAP2_CHROMA) == PgVM_MODE_CAP2_CHROMA) - { + + if ((vmode.mode_capabilities2 & PgVM_MODE_CAP2_CHROMA) == + PgVM_MODE_CAP2_CHROMA) { this->info.blit_hw_CC = 1; - } - else - { + } else { this->info.blit_hw_CC = 0; } - + return 0; } -int ph_SetupUpdateFunction(_THIS, SDL_Surface* screen, Uint32 flags) +int +ph_SetupUpdateFunction(_THIS, SDL_Surface * screen, Uint32 flags) { - int setupresult=-1; + int setupresult = -1; ph_DestroyImage(this, screen); - + #if SDL_VIDEO_OPENGL - if ((flags & SDL_OPENGL)==SDL_OPENGL) - { - setupresult=ph_SetupOpenGLImage(this, screen); - } - else - { + if (flags & SDL_INTERNALOPENGL) { + setupresult = ph_SetupOpenGLImage(this, screen); + } else { #endif - if ((flags & SDL_FULLSCREEN)==SDL_FULLSCREEN) - { - setupresult=ph_SetupFullScreenImage(this, screen); - } - else - { - if ((flags & SDL_HWSURFACE)==SDL_HWSURFACE) - { - setupresult=ph_SetupOCImage(this, screen); - } - else - { - setupresult=ph_SetupImage(this, screen); - } - } + if ((flags & SDL_FULLSCREEN) == SDL_FULLSCREEN) { + setupresult = ph_SetupFullScreenImage(this, screen); + } else { + if ((flags & SDL_HWSURFACE) == SDL_HWSURFACE) { + setupresult = ph_SetupOCImage(this, screen); + } else { + setupresult = ph_SetupImage(this, screen); + } + } #if SDL_VIDEO_OPENGL } #endif - if (setupresult!=-1) - { - ph_UpdateHWInfo(this); + if (setupresult != -1) { + ph_UpdateHWInfo(this); } - + return setupresult; } -int ph_AllocHWSurface(_THIS, SDL_Surface* surface) +int +ph_AllocHWSurface(_THIS, SDL_Surface * surface) { PgHWCaps_t hwcaps; - if (surface->hwdata!=NULL) - { - SDL_SetError("ph_AllocHWSurface(): hwdata already exists!\n"); - return -1; + if (surface->hwdata != NULL) { + SDL_SetError("ph_AllocHWSurface(): hwdata already exists!\n"); + return -1; } - surface->hwdata=SDL_malloc(sizeof(struct private_hwdata)); + surface->hwdata = SDL_malloc(sizeof(struct private_hwdata)); SDL_memset(surface->hwdata, 0x00, sizeof(struct private_hwdata)); - surface->hwdata->offscreenctx=PdCreateOffscreenContext(0, surface->w, surface->h, Pg_OSC_MEM_PAGE_ALIGN); - if (surface->hwdata->offscreenctx == NULL) - { - SDL_SetError("ph_AllocHWSurface(): PdCreateOffscreenContext() function failed !\n"); + surface->hwdata->offscreenctx = + PdCreateOffscreenContext(0, surface->w, surface->h, + Pg_OSC_MEM_PAGE_ALIGN); + if (surface->hwdata->offscreenctx == NULL) { + SDL_SetError + ("ph_AllocHWSurface(): PdCreateOffscreenContext() function failed !\n"); return -1; } - surface->pixels=PdGetOffscreenContextPtr(surface->hwdata->offscreenctx); - if (surface->pixels==NULL) - { + surface->pixels = PdGetOffscreenContextPtr(surface->hwdata->offscreenctx); + if (surface->pixels == NULL) { PhDCRelease(surface->hwdata->offscreenctx); - SDL_SetError("ph_AllocHWSurface(): PdGetOffscreenContextPtr() function failed !\n"); + SDL_SetError + ("ph_AllocHWSurface(): PdGetOffscreenContextPtr() function failed !\n"); return -1; } - surface->pitch=surface->hwdata->offscreenctx->pitch; - surface->flags|=SDL_HWSURFACE; - surface->flags|=SDL_PREALLOC; - -#if 0 /* FIXME */ + surface->pitch = surface->hwdata->offscreenctx->pitch; + surface->flags |= SDL_HWSURFACE; + surface->flags |= SDL_PREALLOC; + +#if 0 /* FIXME */ /* create simple offscreen lock */ - surface->hwdata->crlockparam.flags=0; - if (PdCreateOffscreenLock(surface->hwdata->offscreenctx, &surface->hwdata->crlockparam)!=EOK) + surface->hwdata->crlockparam.flags = 0; + if (PdCreateOffscreenLock + (surface->hwdata->offscreenctx, &surface->hwdata->crlockparam) != EOK) { PhDCRelease(surface->hwdata->offscreenctx); SDL_SetError("ph_AllocHWSurface(): Can't create offscreen lock !\n"); @@ -559,189 +549,183 @@ int ph_AllocHWSurface(_THIS, SDL_Surface* surface) #endif /* 0 */ /* Update video ram amount */ - if (PgGetGraphicsHWCaps(&hwcaps) < 0) - { + if (PgGetGraphicsHWCaps(&hwcaps) < 0) { PdDestroyOffscreenLock(surface->hwdata->offscreenctx); PhDCRelease(surface->hwdata->offscreenctx); - SDL_SetError("ph_AllocHWSurface(): GetGraphicsHWCaps() function failed !\n"); + SDL_SetError + ("ph_AllocHWSurface(): GetGraphicsHWCaps() function failed !\n"); return -1; } - this->info.video_mem=hwcaps.currently_available_video_ram/1024; + this->info.video_mem = hwcaps.currently_available_video_ram / 1024; return 0; } -void ph_FreeHWSurface(_THIS, SDL_Surface* surface) +void +ph_FreeHWSurface(_THIS, SDL_Surface * surface) { PgHWCaps_t hwcaps; - if (surface->hwdata==NULL) - { - SDL_SetError("ph_FreeHWSurface(): no hwdata!\n"); - return; + if (surface->hwdata == NULL) { + SDL_SetError("ph_FreeHWSurface(): no hwdata!\n"); + return; } - if (surface->hwdata->offscreenctx == NULL) - { - SDL_SetError("ph_FreeHWSurface(): no offscreen context to delete!\n"); - return; + if (surface->hwdata->offscreenctx == NULL) { + SDL_SetError("ph_FreeHWSurface(): no offscreen context to delete!\n"); + return; } - -#if 0 /* FIXME */ +#if 0 /* FIXME */ /* unlock the offscreen context if it has been locked before destroy it */ - if (PdIsOffscreenLocked(surface->hwdata->offscreenctx)==Pg_OSC_LOCKED) - { - PdUnlockOffscreen(surface->hwdata->offscreenctx); + if (PdIsOffscreenLocked(surface->hwdata->offscreenctx) == Pg_OSC_LOCKED) { + PdUnlockOffscreen(surface->hwdata->offscreenctx); } PdDestroyOffscreenLock(surface->hwdata->offscreenctx); #endif /* 0 */ PhDCRelease(surface->hwdata->offscreenctx); - + SDL_free(surface->hwdata); - surface->hwdata=NULL; + surface->hwdata = NULL; /* Update video ram amount */ - if (PgGetGraphicsHWCaps(&hwcaps) < 0) - { - SDL_SetError("ph_FreeHWSurface(): GetGraphicsHWCaps() function failed !\n"); + if (PgGetGraphicsHWCaps(&hwcaps) < 0) { + SDL_SetError + ("ph_FreeHWSurface(): GetGraphicsHWCaps() function failed !\n"); return; } - this->info.video_mem=hwcaps.currently_available_video_ram/1024; + this->info.video_mem = hwcaps.currently_available_video_ram / 1024; return; } -int ph_CheckHWBlit(_THIS, SDL_Surface *src, SDL_Surface *dst) +int +ph_CheckHWBlit(_THIS, SDL_Surface * src, SDL_Surface * dst) { - if ((src->hwdata==NULL) && (src != this->screen)) - { - SDL_SetError("ph_CheckHWBlit(): Source surface haven't hardware specific data.\n"); - src->flags&=~SDL_HWACCEL; - return -1; - } - if ((src->flags & SDL_HWSURFACE) != SDL_HWSURFACE) - { - SDL_SetError("ph_CheckHWBlit(): Source surface isn't a hardware surface.\n"); - src->flags&=~SDL_HWACCEL; - return -1; - } - - if ((src->flags & SDL_SRCCOLORKEY) == SDL_SRCCOLORKEY) - { - if (this->info.blit_hw_CC!=1) - { - src->flags&=~SDL_HWACCEL; - src->map->hw_blit=NULL; - return -1; - } - } - - if ((src->flags & SDL_SRCALPHA) == SDL_SRCALPHA) - { - if (this->info.blit_hw_A!=1) - { - src->flags&=~SDL_HWACCEL; - src->map->hw_blit=NULL; - return -1; - } - } - - src->flags|=SDL_HWACCEL; - src->map->hw_blit = ph_HWAccelBlit; - - return 1; + if ((src->hwdata == NULL) && (src != this->screen)) { + SDL_SetError + ("ph_CheckHWBlit(): Source surface haven't hardware specific data.\n"); + src->flags &= ~SDL_HWACCEL; + return -1; + } + if ((src->flags & SDL_HWSURFACE) != SDL_HWSURFACE) { + SDL_SetError + ("ph_CheckHWBlit(): Source surface isn't a hardware surface.\n"); + src->flags &= ~SDL_HWACCEL; + return -1; + } + + if ((src->flags & SDL_SRCCOLORKEY) == SDL_SRCCOLORKEY) { + if (this->info.blit_hw_CC != 1) { + src->flags &= ~SDL_HWACCEL; + src->map->hw_blit = NULL; + return -1; + } + } + + if ((src->flags & SDL_SRCALPHA) == SDL_SRCALPHA) { + if (this->info.blit_hw_A != 1) { + src->flags &= ~SDL_HWACCEL; + src->map->hw_blit = NULL; + return -1; + } + } + + src->flags |= SDL_HWACCEL; + src->map->hw_blit = ph_HWAccelBlit; + + return 1; } -PgColor_t ph_ExpandColor(_THIS, SDL_Surface* surface, Uint32 color) +PgColor_t +ph_ExpandColor(_THIS, SDL_Surface * surface, Uint32 color) { Uint32 truecolor; /* Photon API accepts true colors only during hw filling operations */ - switch(surface->format->BitsPerPixel) - { - case 8: - { - if ((surface->format->palette) && (color<=surface->format->palette->ncolors)) - { - truecolor=PgRGB(surface->format->palette->colors[color].r, - surface->format->palette->colors[color].g, - surface->format->palette->colors[color].b); - } - else - { - SDL_SetError("ph_ExpandColor(): Color out of range for the 8bpp mode !\n"); - return 0xFFFFFFFFUL; - } - } - break; - case 15: - { - truecolor = ((color & 0x00007C00UL) << 9) | /* R */ - ((color & 0x000003E0UL) << 6) | /* G */ - ((color & 0x0000001FUL) << 3) | /* B */ - ((color & 0x00007000UL) << 4) | /* R compensation */ - ((color & 0x00000380UL) << 1) | /* G compensation */ - ((color & 0x0000001CUL) >> 2); /* B compensation */ - } - break; - case 16: - { - truecolor = ((color & 0x0000F800UL) << 8) | /* R */ - ((color & 0x000007E0UL) << 5) | /* G */ - ((color & 0x0000001FUL) << 3) | /* B */ - ((color & 0x0000E000UL) << 3) | /* R compensation */ - ((color & 0x00000600UL) >> 1) | /* G compensation */ - ((color & 0x0000001CUL) >> 2); /* B compensation */ - - } - break; - case 24: - { - truecolor=color & 0x00FFFFFFUL; - } - break; - case 32: - { - truecolor=color; - } - break; - default: - { - SDL_SetError("ph_ExpandColor(): Unsupported depth for the hardware operations !\n"); + switch (surface->format->BitsPerPixel) { + case 8: + { + if ((surface->format->palette) + && (color <= surface->format->palette->ncolors)) { + truecolor = + PgRGB(surface->format->palette->colors[color].r, + surface->format->palette->colors[color].g, + surface->format->palette->colors[color].b); + } else { + SDL_SetError + ("ph_ExpandColor(): Color out of range for the 8bpp mode !\n"); return 0xFFFFFFFFUL; } + } + break; + case 15: + { + truecolor = ((color & 0x00007C00UL) << 9) | /* R */ + ((color & 0x000003E0UL) << 6) | /* G */ + ((color & 0x0000001FUL) << 3) | /* B */ + ((color & 0x00007000UL) << 4) | /* R compensation */ + ((color & 0x00000380UL) << 1) | /* G compensation */ + ((color & 0x0000001CUL) >> 2); /* B compensation */ + } + break; + case 16: + { + truecolor = ((color & 0x0000F800UL) << 8) | /* R */ + ((color & 0x000007E0UL) << 5) | /* G */ + ((color & 0x0000001FUL) << 3) | /* B */ + ((color & 0x0000E000UL) << 3) | /* R compensation */ + ((color & 0x00000600UL) >> 1) | /* G compensation */ + ((color & 0x0000001CUL) >> 2); /* B compensation */ + + } + break; + case 24: + { + truecolor = color & 0x00FFFFFFUL; + } + break; + case 32: + { + truecolor = color; + } + break; + default: + { + SDL_SetError + ("ph_ExpandColor(): Unsupported depth for the hardware operations !\n"); + return 0xFFFFFFFFUL; + } } return truecolor; } -int ph_FillHWRect(_THIS, SDL_Surface* surface, SDL_Rect* rect, Uint32 color) +int +ph_FillHWRect(_THIS, SDL_Surface * surface, SDL_Rect * rect, Uint32 color) { PgColor_t oldcolor; Uint32 truecolor; - int ydisp=0; + int ydisp = 0; - if (this->info.blit_fill!=1) - { - return -1; + if (this->info.blit_fill != 1) { + return -1; } - truecolor=ph_ExpandColor(this, surface, color); - if (truecolor==0xFFFFFFFFUL) - { + truecolor = ph_ExpandColor(this, surface, color); + if (truecolor == 0xFFFFFFFFUL) { return -1; } - oldcolor=PgSetFillColor(truecolor); + oldcolor = PgSetFillColor(truecolor); /* 640x400 videomode emulation */ - if (videomode_emulatemode==1) - { - ydisp+=40; + if (videomode_emulatemode == 1) { + ydisp += 40; } - PgDrawIRect(rect->x, rect->y+ydisp, rect->w+rect->x-1, rect->h+rect->y+ydisp-1, Pg_DRAW_FILL); + PgDrawIRect(rect->x, rect->y + ydisp, rect->w + rect->x - 1, + rect->h + rect->y + ydisp - 1, Pg_DRAW_FILL); PgSetFillColor(oldcolor); PgFlush(); PgWaitHWIdle(); @@ -749,28 +733,28 @@ int ph_FillHWRect(_THIS, SDL_Surface* surface, SDL_Rect* rect, Uint32 color) return 0; } -int ph_FlipHWSurface(_THIS, SDL_Surface* screen) +int +ph_FlipHWSurface(_THIS, SDL_Surface * screen) { PhArea_t farea; - if ((screen->flags & SDL_FULLSCREEN) == SDL_FULLSCREEN) - { + if ((screen->flags & SDL_FULLSCREEN) == SDL_FULLSCREEN) { /* flush all drawing ops before blitting */ PgFlush(); PgWaitHWIdle(); - farea.pos.x=0; - farea.pos.y=0; - farea.size.w=screen->w; - farea.size.h=screen->h; + farea.pos.x = 0; + farea.pos.y = 0; + farea.size.w = screen->w; + farea.size.h = screen->h; /* emulate 640x400 videomode */ - if (videomode_emulatemode==1) - { - farea.pos.y+=40; + if (videomode_emulatemode == 1) { + farea.pos.y += 40; } - PgContextBlitArea(OCImage.offscreen_context, &farea, OCImage.offscreen_backcontext, &farea); + PgContextBlitArea(OCImage.offscreen_context, &farea, + OCImage.offscreen_backcontext, &farea); /* flush the blitting */ PgFlush(); @@ -779,141 +763,132 @@ int ph_FlipHWSurface(_THIS, SDL_Surface* screen) return 0; } -int ph_LockHWSurface(_THIS, SDL_Surface* surface) +int +ph_LockHWSurface(_THIS, SDL_Surface * surface) { -#if 0 /* FIXME */ +#if 0 /* FIXME */ int lockresult; - if (surface->hwdata == NULL) - { + if (surface->hwdata == NULL) { return; } - surface->hwdata->lockparam.flags=0; - surface->hwdata->lockparam.time_out=NULL; - lockresult=PdLockOffscreen(surface->hwdata->offscreenctx, &surface->hwdata->lockparam); + surface->hwdata->lockparam.flags = 0; + surface->hwdata->lockparam.time_out = NULL; + lockresult = + PdLockOffscreen(surface->hwdata->offscreenctx, + &surface->hwdata->lockparam); - switch (lockresult) - { - case EOK: - break; - case Pg_OSC_LOCK_DEADLOCK: - SDL_SetError("ph_LockHWSurface(): Deadlock detected !\n"); - return -1; - case Pg_OSC_LOCK_INVALID: - SDL_SetError("ph_LockHWSurface(): Lock invalid !\n"); - return -1; - default: - SDL_SetError("ph_LockHWSurface(): Can't lock the surface !\n"); - return -1; + switch (lockresult) { + case EOK: + break; + case Pg_OSC_LOCK_DEADLOCK: + SDL_SetError("ph_LockHWSurface(): Deadlock detected !\n"); + return -1; + case Pg_OSC_LOCK_INVALID: + SDL_SetError("ph_LockHWSurface(): Lock invalid !\n"); + return -1; + default: + SDL_SetError("ph_LockHWSurface(): Can't lock the surface !\n"); + return -1; } #endif /* 0 */ return 0; } -void ph_UnlockHWSurface(_THIS, SDL_Surface* surface) +void +ph_UnlockHWSurface(_THIS, SDL_Surface * surface) { -#if 0 /* FIXME */ +#if 0 /* FIXME */ int unlockresult; - if ((surface == NULL) || (surface->hwdata == NULL)) - { + if ((surface == NULL) || (surface->hwdata == NULL)) { return; } - if (PdIsOffscreenLocked(surface->hwdata->offscreenctx)==Pg_OSC_LOCKED) - { - unlockresult=PdUnlockOffscreen(surface->hwdata->offscreenctx); + if (PdIsOffscreenLocked(surface->hwdata->offscreenctx) == Pg_OSC_LOCKED) { + unlockresult = PdUnlockOffscreen(surface->hwdata->offscreenctx); } #endif /* 0 */ return; } -int ph_HWAccelBlit(SDL_Surface* src, SDL_Rect* srcrect, SDL_Surface* dst, SDL_Rect* dstrect) +int +ph_HWAccelBlit(SDL_Surface * src, SDL_Rect * srcrect, SDL_Surface * dst, + SDL_Rect * dstrect) { - SDL_VideoDevice* this=current_video; + SDL_VideoDevice *this = current_video; PhArea_t srcarea; PhArea_t dstarea; - int ydisp=0; + int ydisp = 0; /* 640x400 videomode emulation */ - if (videomode_emulatemode==1) - { - ydisp+=40; + if (videomode_emulatemode == 1) { + ydisp += 40; } - srcarea.pos.x=srcrect->x; - srcarea.pos.y=srcrect->y; - srcarea.size.w=srcrect->w; - srcarea.size.h=srcrect->h; + srcarea.pos.x = srcrect->x; + srcarea.pos.y = srcrect->y; + srcarea.size.w = srcrect->w; + srcarea.size.h = srcrect->h; - dstarea.pos.x=dstrect->x; - dstarea.pos.y=dstrect->y; - dstarea.size.w=dstrect->w; - dstarea.size.h=dstrect->h; + dstarea.pos.x = dstrect->x; + dstarea.pos.y = dstrect->y; + dstarea.size.w = dstrect->w; + dstarea.size.h = dstrect->h; - if (((src == this->screen) || (src->hwdata!=NULL)) && ((dst == this->screen) || (dst->hwdata!=NULL))) - { - if ((src->flags & SDL_SRCCOLORKEY) == SDL_SRCCOLORKEY) - { + if (((src == this->screen) || (src->hwdata != NULL)) + && ((dst == this->screen) || (dst->hwdata != NULL))) { + if ((src->flags & SDL_SRCCOLORKEY) == SDL_SRCCOLORKEY) { ph_SetHWColorKey(this, src, src->format->colorkey); PgChromaOn(); } - if ((src->flags & SDL_SRCALPHA) == SDL_SRCALPHA) - { + if ((src->flags & SDL_SRCALPHA) == SDL_SRCALPHA) { ph_SetHWAlpha(this, src, src->format->alpha); PgAlphaOn(); } - if (dst == this->screen) - { - if (src == this->screen) - { + if (dst == this->screen) { + if (src == this->screen) { /* blitting from main screen to main screen */ - dstarea.pos.y+=ydisp; - srcarea.pos.y+=ydisp; - PgContextBlitArea(OCImage.offscreen_context, &srcarea, OCImage.offscreen_context, &dstarea); - } - else - { + dstarea.pos.y += ydisp; + srcarea.pos.y += ydisp; + PgContextBlitArea(OCImage.offscreen_context, &srcarea, + OCImage.offscreen_context, &dstarea); + } else { /* blitting from offscreen to main screen */ - dstarea.pos.y+=ydisp; - PgContextBlitArea(src->hwdata->offscreenctx, &srcarea, OCImage.offscreen_context, &dstarea); + dstarea.pos.y += ydisp; + PgContextBlitArea(src->hwdata->offscreenctx, &srcarea, + OCImage.offscreen_context, &dstarea); } - } - else - { - if (src == this->screen) - { + } else { + if (src == this->screen) { /* blitting from main screen to offscreen */ - srcarea.pos.y+=ydisp; - PgContextBlitArea(OCImage.offscreen_context, &srcarea, dst->hwdata->offscreenctx, &dstarea); - } - else - { + srcarea.pos.y += ydisp; + PgContextBlitArea(OCImage.offscreen_context, &srcarea, + dst->hwdata->offscreenctx, &dstarea); + } else { /* blitting offscreen to offscreen */ - PgContextBlitArea(src->hwdata->offscreenctx, &srcarea, dst->hwdata->offscreenctx, &dstarea); + PgContextBlitArea(src->hwdata->offscreenctx, &srcarea, + dst->hwdata->offscreenctx, &dstarea); } } - if ((src->flags & SDL_SRCALPHA) == SDL_SRCALPHA) - { + if ((src->flags & SDL_SRCALPHA) == SDL_SRCALPHA) { PgAlphaOff(); } - if ((src->flags & SDL_SRCCOLORKEY) == SDL_SRCCOLORKEY) - { + if ((src->flags & SDL_SRCCOLORKEY) == SDL_SRCCOLORKEY) { PgChromaOff(); } - } - else - { - SDL_SetError("ph_HWAccelBlit(): Source or target surface is not a hardware surface !\n"); + } else { + SDL_SetError + ("ph_HWAccelBlit(): Source or target surface is not a hardware surface !\n"); return -1; } @@ -923,31 +898,30 @@ int ph_HWAccelBlit(SDL_Surface* src, SDL_Rect* srcrect, SDL_Surface* dst, SDL_Re return 0; } -int ph_SetHWColorKey(_THIS, SDL_Surface *surface, Uint32 key) +int +ph_SetHWColorKey(_THIS, SDL_Surface * surface, Uint32 key) { - if (this->info.blit_hw_CC!=1) - { - return -1; + if (this->info.blit_hw_CC != 1) { + return -1; } - if (surface->hwdata!=NULL) - { - surface->hwdata->colorkey=ph_ExpandColor(this, surface, key); - if (surface->hwdata->colorkey==0xFFFFFFFFUL) - { + if (surface->hwdata != NULL) { + surface->hwdata->colorkey = ph_ExpandColor(this, surface, key); + if (surface->hwdata->colorkey == 0xFFFFFFFFUL) { return -1; } } - PgSetChroma(surface->hwdata->colorkey, Pg_CHROMA_SRC_MATCH | Pg_CHROMA_NODRAW); + PgSetChroma(surface->hwdata->colorkey, + Pg_CHROMA_SRC_MATCH | Pg_CHROMA_NODRAW); return 0; } -int ph_SetHWAlpha(_THIS, SDL_Surface* surface, Uint8 alpha) +int +ph_SetHWAlpha(_THIS, SDL_Surface * surface, Uint8 alpha) { - if (this->info.blit_hw_A!=1) - { - return -1; + if (this->info.blit_hw_A != 1) { + return -1; } PgSetAlphaBlend(NULL, alpha); @@ -956,29 +930,28 @@ int ph_SetHWAlpha(_THIS, SDL_Surface* surface, Uint8 alpha) } #if SDL_VIDEO_OPENGL -void ph_OpenGLUpdate(_THIS, int numrects, SDL_Rect* rects) +void +ph_OpenGLUpdate(_THIS, int numrects, SDL_Rect * rects) { - this->GL_SwapBuffers(this); - - return; + this->GL_SwapBuffers(this); + + return; } #endif /* SDL_VIDEO_OPENGL */ -void ph_NormalUpdate(_THIS, int numrects, SDL_Rect *rects) +void +ph_NormalUpdate(_THIS, int numrects, SDL_Rect * rects) { PhPoint_t ph_pos; PhRect_t ph_rect; int i; - for (i=0; iBitsPerPixel) - { + if (mode_info.bits_per_pixel == format->BitsPerPixel) { Amodelist[j].w = mode_info.width; Amodelist[j].h = mode_info.height; Amodelist[j].x = 0; Amodelist[j].y = 0; - j++; + j++; } } - + /* reorder biggest for smallest, assume width dominates */ - for(i=0; iflags & SDL_ANYFORMAT) - { - if ((mode = get_mode_any_format(screen->w, screen->h, screen->format->BitsPerPixel)) == 0) - { - SDL_SetError("ph_EnterFullScreen(): can't find appropriate video mode !\n"); + if (screen->flags & SDL_ANYFORMAT) { + if ((mode = + get_mode_any_format(screen->w, screen->h, + screen->format->BitsPerPixel)) == 0) { + SDL_SetError + ("ph_EnterFullScreen(): can't find appropriate video mode !\n"); return 0; } - } - else - { - if ((mode = ph_GetVideoMode(screen->w, screen->h, screen->format->BitsPerPixel)) == 0) - { - SDL_SetError("ph_EnterFullScreen(): can't find appropriate video mode !\n"); + } else { + if ((mode = + ph_GetVideoMode(screen->w, screen->h, + screen->format->BitsPerPixel)) == 0) { + SDL_SetError + ("ph_EnterFullScreen(): can't find appropriate video mode !\n"); return 0; } - if (PgGetVideoModeInfo(mode, &mode_info) < 0) - { - SDL_SetError("ph_EnterFullScreen(): can't get video mode capabilities !\n"); + if (PgGetVideoModeInfo(mode, &mode_info) < 0) { + SDL_SetError + ("ph_EnterFullScreen(): can't get video mode capabilities !\n"); return 0; } - if (mode_info.height != screen->h) - { - if ((mode_info.height==480) && (screen->h==400)) - { - videomode_emulatemode=1; - } - } - else - { - videomode_emulatemode=0; + if (mode_info.height != screen->h) { + if ((mode_info.height == 480) && (screen->h == 400)) { + videomode_emulatemode = 1; + } + } else { + videomode_emulatemode = 0; } } /* save old video mode caps */ PgGetVideoMode(&settings); - old_video_mode=settings.mode; - old_refresh_rate=settings.refresh; + old_video_mode = settings.mode; + old_refresh_rate = settings.refresh; /* setup new video mode */ settings.mode = mode; settings.refresh = 0; settings.flags = 0; - refreshrate=SDL_getenv("SDL_PHOTON_FULLSCREEN_REFRESH"); - if (refreshrate!=NULL) - { - if (SDL_sscanf(refreshrate, "%d", &refreshratenum)==1) - { - settings.refresh = refreshratenum; - } + refreshrate = SDL_getenv("SDL_PHOTON_FULLSCREEN_REFRESH"); + if (refreshrate != NULL) { + if (SDL_sscanf(refreshrate, "%d", &refreshratenum) == 1) { + settings.refresh = refreshratenum; + } } - if (PgSetVideoMode(&settings) < 0) - { - SDL_SetError("ph_EnterFullScreen(): PgSetVideoMode() call failed !\n"); + if (PgSetVideoMode(&settings) < 0) { + SDL_SetError + ("ph_EnterFullScreen(): PgSetVideoMode() call failed !\n"); return 0; } - if (this->screen) - { - if ((this->screen->flags & SDL_OPENGL)==SDL_OPENGL) - { + if (this->screen) { + if (this->screen->flags & SDL_INTERNALOPENGL) { #if !SDL_VIDEO_OPENGL || (_NTO_VERSION < 630) - return 0; /* 6.3.0 */ + return 0; /* 6.3.0 */ #endif } } - if (fmode==0) - { - if (OCImage.direct_context==NULL) - { - OCImage.direct_context=(PdDirectContext_t*)PdCreateDirectContext(); - if (!OCImage.direct_context) - { - SDL_SetError("ph_EnterFullScreen(): Can't create direct context !\n"); + if (fmode == 0) { + if (OCImage.direct_context == NULL) { + OCImage.direct_context = + (PdDirectContext_t *) PdCreateDirectContext(); + if (!OCImage.direct_context) { + SDL_SetError + ("ph_EnterFullScreen(): Can't create direct context !\n"); ph_LeaveFullScreen(this); return 0; } } - OCImage.oldDC=PdDirectStart(OCImage.direct_context); + OCImage.oldDC = PdDirectStart(OCImage.direct_context); } currently_fullscreen = 1; @@ -339,14 +308,13 @@ int ph_EnterFullScreen(_THIS, SDL_Surface* screen, int fmode) return 1; } -int ph_LeaveFullScreen(_THIS) +int +ph_LeaveFullScreen(_THIS) { PgDisplaySettings_t oldmode_settings; - - if (currently_fullscreen) - { - if ((this->screen) && ((this->screen->flags & SDL_OPENGL)==SDL_OPENGL)) - { + + if (currently_fullscreen) { + if ((this->screen) && (this->screen->flags & SDL_INTERNALOPENGL)) { #if !SDL_VIDEO_OPENGL || (_NTO_VERSION < 630) return 0; #endif @@ -354,37 +322,36 @@ int ph_LeaveFullScreen(_THIS) /* release routines starts here */ { - if (OCImage.direct_context) - { + if (OCImage.direct_context) { PdDirectStop(OCImage.direct_context); PdReleaseDirectContext(OCImage.direct_context); - OCImage.direct_context=NULL; + OCImage.direct_context = NULL; } - if (OCImage.oldDC) - { + if (OCImage.oldDC) { PhDCSetCurrent(OCImage.oldDC); - OCImage.oldDC=NULL; + OCImage.oldDC = NULL; } - currently_fullscreen=0; + currently_fullscreen = 0; /* Restore old video mode */ - if (old_video_mode != -1) - { + if (old_video_mode != -1) { oldmode_settings.mode = (unsigned short) old_video_mode; oldmode_settings.refresh = (unsigned short) old_refresh_rate; oldmode_settings.flags = 0; - - if (PgSetVideoMode(&oldmode_settings) < 0) - { - SDL_SetError("Ph_LeaveFullScreen(): PgSetVideoMode() function failed !\n"); + + if (PgSetVideoMode(&oldmode_settings) < 0) { + SDL_SetError + ("Ph_LeaveFullScreen(): PgSetVideoMode() function failed !\n"); return 0; } } - old_video_mode=-1; - old_refresh_rate=-1; + old_video_mode = -1; + old_refresh_rate = -1; } } return 1; } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/photon/SDL_ph_modes_c.h b/src/video/photon/SDL_ph_modes_c.h index 86e494cf7..9ce8ae6bf 100644 --- a/src/video/photon/SDL_ph_modes_c.h +++ b/src/video/photon/SDL_ph_modes_c.h @@ -31,13 +31,14 @@ #define PH_ENTER_DIRECTMODE 0 #define PH_IGNORE_DIRECTMODE 1 -extern SDL_Rect **ph_ListModes(_THIS,SDL_PixelFormat *format, Uint32 flags); +extern SDL_Rect **ph_ListModes(_THIS, SDL_PixelFormat * format, Uint32 flags); extern void ph_FreeVideoModes(_THIS); extern int ph_ResizeFullScreen(_THIS); -extern int ph_EnterFullScreen(_THIS, SDL_Surface* screen, int fmode); +extern int ph_EnterFullScreen(_THIS, SDL_Surface * screen, int fmode); extern int ph_LeaveFullScreen(_THIS); extern int ph_GetVideoMode(int width, int height, int bpp); extern int get_mode_any_format(int width, int height, int bpp); extern int ph_ToggleFullScreen(_THIS, int on); #endif /* __SDL_PH_MODES_H__ */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/photon/SDL_ph_mouse.c b/src/video/photon/SDL_ph_mouse.c index e0868bc8e..23ccc9a84 100644 --- a/src/video/photon/SDL_ph_mouse.c +++ b/src/video/photon/SDL_ph_mouse.c @@ -28,138 +28,133 @@ struct WMcursor { - PhCursorDef_t *ph_cursor ; + PhCursorDef_t *ph_cursor; }; -void ph_FreeWMCursor(_THIS, WMcursor *cursor) +void +ph_FreeWMCursor(_THIS, WMcursor * cursor) { - if (window != NULL) - { + if (window != NULL) { SDL_Lock_EventThread(); - if (PtSetResource(window, Pt_ARG_CURSOR_TYPE, Ph_CURSOR_INHERIT, 0) < 0) - { + if (PtSetResource(window, Pt_ARG_CURSOR_TYPE, Ph_CURSOR_INHERIT, 0) + < 0) { /* TODO: output error msg */ } SDL_Unlock_EventThread(); - } + } SDL_free(cursor); } -WMcursor *ph_CreateWMCursor(_THIS, Uint8 *data, Uint8 *mask, int w, int h, int hot_x, int hot_y) +WMcursor * +ph_CreateWMCursor(_THIS, Uint8 * data, Uint8 * mask, int w, int h, int hot_x, + int hot_y) { - WMcursor* cursor; + WMcursor *cursor; int clen, i; unsigned char bit, databit, maskbit; /* Allocate and initialize the cursor memory */ - if ((cursor = (WMcursor*)SDL_malloc(sizeof(WMcursor))) == NULL) - { + if ((cursor = (WMcursor *) SDL_malloc(sizeof(WMcursor))) == NULL) { SDL_OutOfMemory(); - return(NULL); + return (NULL); } - SDL_memset(cursor,0,sizeof(WMcursor)); + SDL_memset(cursor, 0, sizeof(WMcursor)); - cursor->ph_cursor = (PhCursorDef_t *) SDL_malloc(sizeof(PhCursorDef_t) + 32*4*2); + cursor->ph_cursor = + (PhCursorDef_t *) SDL_malloc(sizeof(PhCursorDef_t) + 32 * 4 * 2); - if (cursor->ph_cursor == NULL) - { + if (cursor->ph_cursor == NULL) { SDL_SetError("ph_CreateWMCursor(): cursor malloc failed !\n"); return NULL; } - SDL_memset(cursor->ph_cursor,0,(sizeof(PhCursorDef_t) + 32*4*2)); + SDL_memset(cursor->ph_cursor, 0, (sizeof(PhCursorDef_t) + 32 * 4 * 2)); - cursor->ph_cursor->hdr.type =Ph_RDATA_CURSOR; - cursor->ph_cursor->size1.x = (short)w; - cursor->ph_cursor->size1.y = (short)h; - cursor->ph_cursor->offset1.x = (short)hot_x; - cursor->ph_cursor->offset1.y = (short)hot_y; - cursor->ph_cursor->bytesperline1 = (char)w/8; + cursor->ph_cursor->hdr.type = Ph_RDATA_CURSOR; + cursor->ph_cursor->size1.x = (short) w; + cursor->ph_cursor->size1.y = (short) h; + cursor->ph_cursor->offset1.x = (short) hot_x; + cursor->ph_cursor->offset1.y = (short) hot_y; + cursor->ph_cursor->bytesperline1 = (char) w / 8; cursor->ph_cursor->color1 = Pg_WHITE; - cursor->ph_cursor->size2.x = (short)w; - cursor->ph_cursor->size2.y = (short)h; - cursor->ph_cursor->offset2.x = (short)hot_x; - cursor->ph_cursor->offset2.y = (short)hot_y; - cursor->ph_cursor->bytesperline2 = (char)w/8; + cursor->ph_cursor->size2.x = (short) w; + cursor->ph_cursor->size2.y = (short) h; + cursor->ph_cursor->offset2.x = (short) hot_x; + cursor->ph_cursor->offset2.y = (short) hot_y; + cursor->ph_cursor->bytesperline2 = (char) w / 8; cursor->ph_cursor->color2 = Pg_BLACK; - clen = (w/8)*h; + clen = (w / 8) * h; /* Copy the mask and the data to different bitmap planes */ - for (i=0; iph_cursor->images[i] |= (databit == 0) ? maskbit : 0; /* If the databit != 0, treat it as a black pixel and * ignore the maskbit (can't do an inverted color) */ - cursor->ph_cursor->images[i+clen] |= databit; + cursor->ph_cursor->images[i + clen] |= databit; } } /* #bytes following the hdr struct */ - cursor->ph_cursor->hdr.len =sizeof(PhCursorDef_t) + clen*2 - sizeof(PhRegionDataHdr_t); + cursor->ph_cursor->hdr.len = + sizeof(PhCursorDef_t) + clen * 2 - sizeof(PhRegionDataHdr_t); return (cursor); } -PhCursorDef_t ph_GetWMPhCursor(WMcursor *cursor) +PhCursorDef_t +ph_GetWMPhCursor(WMcursor * cursor) { return (*cursor->ph_cursor); } -int ph_ShowWMCursor(_THIS, WMcursor* cursor) +int +ph_ShowWMCursor(_THIS, WMcursor * cursor) { PtArg_t args[3]; int nargs = 0; /* Don't do anything if the display is gone */ - if (window == NULL) - { + if (window == NULL) { return (0); } /* looks like photon can't draw mouse cursor in direct mode */ - if ((this->screen->flags & SDL_FULLSCREEN) == SDL_FULLSCREEN) - { - /* disable the fake mouse in the fullscreen OpenGL mode */ - if ((this->screen->flags & SDL_OPENGL) == SDL_OPENGL) - { - cursor=NULL; - } - else - { - return (0); - } + if (this->screen->flags & SDL_FULLSCREEN) { + /* disable the fake mouse in the fullscreen OpenGL mode */ + if (this->screen->flags & SDL_INTERNALOPENGL) { + cursor = NULL; + } else { + return (0); + } } /* Set the photon cursor, or blank if cursor is NULL */ - if (cursor!=NULL) - { + if (cursor != NULL) { PtSetArg(&args[0], Pt_ARG_CURSOR_TYPE, Ph_CURSOR_BITMAP, 0); /* Could set next to any PgColor_t value */ - PtSetArg(&args[1], Pt_ARG_CURSOR_COLOR, Ph_CURSOR_DEFAULT_COLOR , 0); - PtSetArg(&args[2], Pt_ARG_BITMAP_CURSOR, cursor->ph_cursor, (cursor->ph_cursor->hdr.len + sizeof(PhRegionDataHdr_t))); + PtSetArg(&args[1], Pt_ARG_CURSOR_COLOR, Ph_CURSOR_DEFAULT_COLOR, 0); + PtSetArg(&args[2], Pt_ARG_BITMAP_CURSOR, cursor->ph_cursor, + (cursor->ph_cursor->hdr.len + sizeof(PhRegionDataHdr_t))); nargs = 3; - } - else /* Ph_CURSOR_NONE */ - { + } else { /* Ph_CURSOR_NONE */ + PtSetArg(&args[0], Pt_ARG_CURSOR_TYPE, Ph_CURSOR_NONE, 0); nargs = 1; } SDL_Lock_EventThread(); - if (PtSetResources(window, nargs, args) < 0 ) - { + if (PtSetResources(window, nargs, args) < 0) { return (0); - } + } SDL_Unlock_EventThread(); @@ -167,32 +162,33 @@ int ph_ShowWMCursor(_THIS, WMcursor* cursor) } -void ph_WarpWMCursor(_THIS, Uint16 x, Uint16 y) +void +ph_WarpWMCursor(_THIS, Uint16 x, Uint16 y) { short abs_x, abs_y; SDL_Lock_EventThread(); - PtGetAbsPosition( window, &abs_x, &abs_y ); - PhMoveCursorAbs( PhInputGroup(NULL), x + abs_x, y + abs_y ); + PtGetAbsPosition(window, &abs_x, &abs_y); + PhMoveCursorAbs(PhInputGroup(NULL), x + abs_x, y + abs_y); SDL_Unlock_EventThread(); } -void ph_CheckMouseMode(_THIS) +void +ph_CheckMouseMode(_THIS) { /* If the mouse is hidden and input is grabbed, we use relative mode */ - if ( !(SDL_cursorstate & CURSOR_VISIBLE) && (this->input_grab != SDL_GRAB_OFF)) - { + if (!(SDL_cursorstate & CURSOR_VISIBLE) + && (this->input_grab != SDL_GRAB_OFF)) { mouse_relative = 1; - } - else - { + } else { mouse_relative = 0; } } -void ph_UpdateMouse(_THIS) +void +ph_UpdateMouse(_THIS) { PhCursorInfo_t phcursor; short abs_x; @@ -204,17 +200,19 @@ void ph_UpdateMouse(_THIS) /* synchronizing photon mouse cursor position and SDL mouse position, if cursor appears over window. */ PtGetAbsPosition(window, &abs_x, &abs_y); PhQueryCursor(PhInputGroup(NULL), &phcursor); - if (((phcursor.pos.x >= abs_x) && (phcursor.pos.x <= abs_x + this->screen->w)) && - ((phcursor.pos.y >= abs_y) && (phcursor.pos.y <= abs_y + this->screen->h))) - { + if (((phcursor.pos.x >= abs_x) + && (phcursor.pos.x <= abs_x + this->screen->w)) + && ((phcursor.pos.y >= abs_y) + && (phcursor.pos.y <= abs_y + this->screen->h))) { SDL_PrivateAppActive(1, SDL_APPMOUSEFOCUS); - SDL_PrivateMouseMotion(0, 0, phcursor.pos.x-abs_x, phcursor.pos.y-abs_y); - } - else - { + SDL_PrivateMouseMotion(0, 0, phcursor.pos.x - abs_x, + phcursor.pos.y - abs_y); + } else { SDL_PrivateAppActive(0, SDL_APPMOUSEFOCUS); } /* Unlock the event thread, in multi-threading environments */ SDL_Unlock_EventThread(); } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/photon/SDL_ph_mouse_c.h b/src/video/photon/SDL_ph_mouse_c.h index e54ff1d8e..87d767013 100644 --- a/src/video/photon/SDL_ph_mouse_c.h +++ b/src/video/photon/SDL_ph_mouse_c.h @@ -27,13 +27,15 @@ #include "SDL_ph_video.h" /* Functions to be exported */ -extern void ph_FreeWMCursor(_THIS, WMcursor *cursor); +extern void ph_FreeWMCursor(_THIS, WMcursor * cursor); extern WMcursor *ph_CreateWMCursor(_THIS, - Uint8 *data, Uint8 *mask, int w, int h, int hot_x, int hot_y); -extern PhCursorDef_t ph_GetWMPhCursor(WMcursor *cursor); -extern int ph_ShowWMCursor(_THIS, WMcursor *cursor); + Uint8 * data, Uint8 * mask, int w, int h, + int hot_x, int hot_y); +extern PhCursorDef_t ph_GetWMPhCursor(WMcursor * cursor); +extern int ph_ShowWMCursor(_THIS, WMcursor * cursor); extern void ph_WarpWMCursor(_THIS, Uint16 x, Uint16 y); extern void ph_CheckMouseMode(_THIS); extern void ph_UpdateMouse(_THIS); #endif /* __SDL_PH_MOUSE_H__ */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/photon/SDL_ph_video.c b/src/video/photon/SDL_ph_video.c index ad6266ee8..2b9545d94 100644 --- a/src/video/photon/SDL_ph_video.c +++ b/src/video/photon/SDL_ph_video.c @@ -42,45 +42,44 @@ #include "SDL_phyuv_c.h" #include "../blank_cursor.h" -static int ph_VideoInit(_THIS, SDL_PixelFormat *vformat); -static SDL_Surface *ph_SetVideoMode(_THIS, SDL_Surface *current, int width, int height, int bpp, Uint32 flags); -static int ph_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color *colors); +static int ph_VideoInit(_THIS, SDL_PixelFormat * vformat); +static SDL_Surface *ph_SetVideoMode(_THIS, SDL_Surface * current, int width, + int height, int bpp, Uint32 flags); +static int ph_SetColors(_THIS, int firstcolor, int ncolors, + SDL_Color * colors); static void ph_VideoQuit(_THIS); -static void ph_DeleteDevice(SDL_VideoDevice *device); +static void ph_DeleteDevice(SDL_VideoDevice * device); -static int phstatus=-1; +static int phstatus = -1; -static int ph_Available(void) +static int +ph_Available(void) { - if (phstatus!=0) - { - phstatus=PtInit(NULL); - if (phstatus==0) - { - return 1; - } - else - { - return 0; + if (phstatus != 0) { + phstatus = PtInit(NULL); + if (phstatus == 0) { + return 1; + } else { + return 0; } } return 1; } -static SDL_VideoDevice* ph_CreateDevice(int devindex) +static SDL_VideoDevice * +ph_CreateDevice(int devindex) { - SDL_VideoDevice* device; + SDL_VideoDevice *device; /* Initialize all variables that we clean on shutdown */ - device = (SDL_VideoDevice *)SDL_malloc(sizeof(SDL_VideoDevice)); - if (device) - { + device = (SDL_VideoDevice *) SDL_malloc(sizeof(SDL_VideoDevice)); + if (device) { SDL_memset(device, 0, (sizeof *device)); - device->hidden = (struct SDL_PrivateVideoData*)SDL_malloc((sizeof *device->hidden)); + device->hidden = (struct SDL_PrivateVideoData *) + SDL_malloc((sizeof *device->hidden)); device->gl_data = NULL; } - if ((device == NULL) || (device->hidden == NULL)) - { + if ((device == NULL) || (device->hidden == NULL)) { SDL_OutOfMemory(); ph_DeleteDevice(device); return NULL; @@ -98,7 +97,7 @@ static SDL_VideoDevice* ph_CreateDevice(int devindex) device->ToggleFullScreen = ph_ToggleFullScreen; device->UpdateMouse = ph_UpdateMouse; device->SetColors = ph_SetColors; - device->UpdateRects = NULL; /* set up in ph_SetupUpdateFunction */ + device->UpdateRects = NULL; /* set up in ph_SetupUpdateFunction */ device->VideoQuit = ph_VideoQuit; device->AllocHWSurface = ph_AllocHWSurface; device->CheckHWBlit = ph_CheckHWBlit; @@ -133,7 +132,7 @@ static SDL_VideoDevice* ph_CreateDevice(int devindex) #endif /* SDL_VIDEO_OPENGL */ device->free = ph_DeleteDevice; - + return device; } @@ -142,17 +141,15 @@ VideoBootStrap ph_bootstrap = { ph_Available, ph_CreateDevice }; -static void ph_DeleteDevice(SDL_VideoDevice *device) +static void +ph_DeleteDevice(SDL_VideoDevice * device) { - if (device) - { - if (device->hidden) - { + if (device) { + if (device->hidden) { SDL_free(device->hidden); device->hidden = NULL; } - if (device->gl_data) - { + if (device->gl_data) { SDL_free(device->gl_data); device->gl_data = NULL; } @@ -161,122 +158,129 @@ static void ph_DeleteDevice(SDL_VideoDevice *device) } } -static PtWidget_t *ph_CreateWindow(_THIS) +static PtWidget_t * +ph_CreateWindow(_THIS) { PtWidget_t *widget; - + widget = PtCreateWidget(PtWindow, NULL, 0, NULL); return widget; } -static int ph_SetupWindow(_THIS, int w, int h, int flags) +static int +ph_SetupWindow(_THIS, int w, int h, int flags) { - PtArg_t args[32]; - PhPoint_t pos = {0, 0}; - PhDim_t* olddim; - PhDim_t dim = {w, h}; - PhRect_t desktopextent; - int nargs = 0; - const char* windowpos; - const char* iscentered; - int x, y; + PtArg_t args[32]; + PhPoint_t pos = { 0, 0 }; + PhDim_t *olddim; + PhDim_t dim = { w, h }; + PhRect_t desktopextent; + int nargs = 0; + const char *windowpos; + const char *iscentered; + int x, y; /* check if window size has been changed by Window Manager */ PtGetResource(window, Pt_ARG_DIM, &olddim, 0); - if ((olddim->w!=w) || (olddim->h!=h)) - { - PtSetArg(&args[nargs++], Pt_ARG_DIM, &dim, 0); - } - - if ((flags & SDL_RESIZABLE) == SDL_RESIZABLE) - { - PtSetArg(&args[nargs++], Pt_ARG_WINDOW_MANAGED_FLAGS, Pt_FALSE, Ph_WM_CLOSE); - PtSetArg(&args[nargs++], Pt_ARG_WINDOW_MANAGED_FLAGS, Pt_TRUE, Ph_WM_MAX | Ph_WM_RESTORE | Ph_WM_RESIZE); - PtSetArg(&args[nargs++], Pt_ARG_WINDOW_NOTIFY_FLAGS, Pt_TRUE, Ph_WM_RESIZE | Ph_WM_MOVE | Ph_WM_CLOSE | Ph_WM_MAX | Ph_WM_RESTORE); - PtSetArg(&args[nargs++], Pt_ARG_WINDOW_RENDER_FLAGS, Pt_TRUE, Ph_WM_RENDER_RESIZE | Ph_WM_RENDER_MAX | Ph_WM_RENDER_COLLAPSE | Ph_WM_RENDER_RETURN); - PtSetArg(&args[nargs++], Pt_ARG_RESIZE_FLAGS, Pt_TRUE, Pt_RESIZE_XY_AS_REQUIRED); - } - else - { - PtSetArg(&args[nargs++], Pt_ARG_WINDOW_MANAGED_FLAGS, Pt_FALSE, Ph_WM_RESIZE | Ph_WM_MAX | Ph_WM_RESTORE | Ph_WM_CLOSE); - PtSetArg(&args[nargs++], Pt_ARG_WINDOW_NOTIFY_FLAGS, Pt_FALSE, Ph_WM_RESIZE | Ph_WM_MAX | Ph_WM_RESTORE); - PtSetArg(&args[nargs++], Pt_ARG_WINDOW_NOTIFY_FLAGS, Pt_TRUE, Ph_WM_MOVE | Ph_WM_CLOSE); - PtSetArg(&args[nargs++], Pt_ARG_WINDOW_RENDER_FLAGS, Pt_FALSE, Ph_WM_RENDER_RESIZE | Ph_WM_RENDER_MAX | Ph_WM_RENDER_COLLAPSE | Ph_WM_RENDER_RETURN); - PtSetArg(&args[nargs++], Pt_ARG_RESIZE_FLAGS, Pt_FALSE, Pt_RESIZE_XY_AS_REQUIRED); - } - - if (((flags & SDL_NOFRAME)==SDL_NOFRAME) || ((flags & SDL_FULLSCREEN)==SDL_FULLSCREEN)) - { - if ((flags & SDL_RESIZABLE) != SDL_RESIZABLE) - { - PtSetArg(&args[nargs++], Pt_ARG_WINDOW_RENDER_FLAGS, Pt_FALSE, Pt_TRUE); - } - else - { - PtSetArg(&args[nargs++], Pt_ARG_WINDOW_RENDER_FLAGS, Pt_FALSE, Pt_TRUE); - PtSetArg(&args[nargs++], Pt_ARG_WINDOW_RENDER_FLAGS, Pt_TRUE, Ph_WM_RENDER_RESIZE | Ph_WM_RENDER_BORDER); - } - } - else - { - PtSetArg(&args[nargs++], Pt_ARG_WINDOW_RENDER_FLAGS, Pt_TRUE, Ph_WM_RENDER_BORDER | Ph_WM_RENDER_TITLE | - Ph_WM_RENDER_CLOSE | Ph_WM_RENDER_MENU | Ph_WM_RENDER_MIN); + if ((olddim->w != w) || (olddim->h != h)) { + PtSetArg(&args[nargs++], Pt_ARG_DIM, &dim, 0); + } + + if ((flags & SDL_RESIZABLE) == SDL_RESIZABLE) { + PtSetArg(&args[nargs++], Pt_ARG_WINDOW_MANAGED_FLAGS, Pt_FALSE, + Ph_WM_CLOSE); + PtSetArg(&args[nargs++], Pt_ARG_WINDOW_MANAGED_FLAGS, Pt_TRUE, + Ph_WM_MAX | Ph_WM_RESTORE | Ph_WM_RESIZE); + PtSetArg(&args[nargs++], Pt_ARG_WINDOW_NOTIFY_FLAGS, Pt_TRUE, + Ph_WM_RESIZE | Ph_WM_MOVE | Ph_WM_CLOSE | Ph_WM_MAX | + Ph_WM_RESTORE); + PtSetArg(&args[nargs++], Pt_ARG_WINDOW_RENDER_FLAGS, Pt_TRUE, + Ph_WM_RENDER_RESIZE | Ph_WM_RENDER_MAX | + Ph_WM_RENDER_COLLAPSE | Ph_WM_RENDER_RETURN); + PtSetArg(&args[nargs++], Pt_ARG_RESIZE_FLAGS, Pt_TRUE, + Pt_RESIZE_XY_AS_REQUIRED); + } else { + PtSetArg(&args[nargs++], Pt_ARG_WINDOW_MANAGED_FLAGS, Pt_FALSE, + Ph_WM_RESIZE | Ph_WM_MAX | Ph_WM_RESTORE | Ph_WM_CLOSE); + PtSetArg(&args[nargs++], Pt_ARG_WINDOW_NOTIFY_FLAGS, Pt_FALSE, + Ph_WM_RESIZE | Ph_WM_MAX | Ph_WM_RESTORE); + PtSetArg(&args[nargs++], Pt_ARG_WINDOW_NOTIFY_FLAGS, Pt_TRUE, + Ph_WM_MOVE | Ph_WM_CLOSE); + PtSetArg(&args[nargs++], Pt_ARG_WINDOW_RENDER_FLAGS, Pt_FALSE, + Ph_WM_RENDER_RESIZE | Ph_WM_RENDER_MAX | + Ph_WM_RENDER_COLLAPSE | Ph_WM_RENDER_RETURN); + PtSetArg(&args[nargs++], Pt_ARG_RESIZE_FLAGS, Pt_FALSE, + Pt_RESIZE_XY_AS_REQUIRED); + } + + if (((flags & SDL_NOFRAME) == SDL_NOFRAME) + || ((flags & SDL_FULLSCREEN) == SDL_FULLSCREEN)) { + if ((flags & SDL_RESIZABLE) != SDL_RESIZABLE) { + PtSetArg(&args[nargs++], Pt_ARG_WINDOW_RENDER_FLAGS, + Pt_FALSE, Pt_TRUE); + } else { + PtSetArg(&args[nargs++], Pt_ARG_WINDOW_RENDER_FLAGS, + Pt_FALSE, Pt_TRUE); + PtSetArg(&args[nargs++], Pt_ARG_WINDOW_RENDER_FLAGS, Pt_TRUE, + Ph_WM_RENDER_RESIZE | Ph_WM_RENDER_BORDER); + } + } else { + PtSetArg(&args[nargs++], Pt_ARG_WINDOW_RENDER_FLAGS, Pt_TRUE, + Ph_WM_RENDER_BORDER | Ph_WM_RENDER_TITLE | + Ph_WM_RENDER_CLOSE | Ph_WM_RENDER_MENU | Ph_WM_RENDER_MIN); } - if ((flags & SDL_FULLSCREEN) == SDL_FULLSCREEN) - { + if ((flags & SDL_FULLSCREEN) == SDL_FULLSCREEN) { PtSetArg(&args[nargs++], Pt_ARG_POS, &pos, 0); - PtSetArg(&args[nargs++], Pt_ARG_BASIC_FLAGS, Pt_TRUE, Pt_BASIC_PREVENT_FILL); - PtSetArg(&args[nargs++], Pt_ARG_WINDOW_MANAGED_FLAGS, Pt_TRUE, Ph_WM_FFRONT | Ph_WM_MAX | Ph_WM_TOFRONT | Ph_WM_CONSWITCH); - PtSetArg(&args[nargs++], Pt_ARG_WINDOW_STATE, Pt_TRUE, Ph_WM_STATE_ISFRONT | Ph_WM_STATE_ISFOCUS | Ph_WM_STATE_ISALTKEY); - } - else - { - PtSetArg(&args[nargs++], Pt_ARG_WINDOW_MANAGED_FLAGS, Pt_FALSE, Ph_WM_FFRONT | Ph_WM_CONSWITCH); - PtSetArg(&args[nargs++], Pt_ARG_WINDOW_STATE, Pt_FALSE, Ph_WM_STATE_ISFRONT); - PtSetArg(&args[nargs++], Pt_ARG_WINDOW_STATE, Pt_TRUE, Ph_WM_STATE_ISALTKEY); - - if ((flags & SDL_HWSURFACE) == SDL_HWSURFACE) - { - PtSetArg(&args[nargs++], Pt_ARG_BASIC_FLAGS, Pt_TRUE, Pt_BASIC_PREVENT_FILL); - } - else - { + PtSetArg(&args[nargs++], Pt_ARG_BASIC_FLAGS, Pt_TRUE, + Pt_BASIC_PREVENT_FILL); + PtSetArg(&args[nargs++], Pt_ARG_WINDOW_MANAGED_FLAGS, Pt_TRUE, + Ph_WM_FFRONT | Ph_WM_MAX | Ph_WM_TOFRONT | Ph_WM_CONSWITCH); + PtSetArg(&args[nargs++], Pt_ARG_WINDOW_STATE, Pt_TRUE, + Ph_WM_STATE_ISFRONT | Ph_WM_STATE_ISFOCUS | + Ph_WM_STATE_ISALTKEY); + } else { + PtSetArg(&args[nargs++], Pt_ARG_WINDOW_MANAGED_FLAGS, Pt_FALSE, + Ph_WM_FFRONT | Ph_WM_CONSWITCH); + PtSetArg(&args[nargs++], Pt_ARG_WINDOW_STATE, Pt_FALSE, + Ph_WM_STATE_ISFRONT); + PtSetArg(&args[nargs++], Pt_ARG_WINDOW_STATE, Pt_TRUE, + Ph_WM_STATE_ISALTKEY); + + if ((flags & SDL_HWSURFACE) == SDL_HWSURFACE) { + PtSetArg(&args[nargs++], Pt_ARG_BASIC_FLAGS, Pt_TRUE, + Pt_BASIC_PREVENT_FILL); + } else { PtSetArg(&args[nargs++], Pt_ARG_FILL_COLOR, Pg_BLACK, 0); } - if (!currently_maximized) - { + if (!currently_maximized) { windowpos = SDL_getenv("SDL_VIDEO_WINDOW_POS"); iscentered = SDL_getenv("SDL_VIDEO_CENTERED"); - if ((iscentered) || ((windowpos) && (SDL_strcmp(windowpos, "center")==0))) - { + if ((iscentered) + || ((windowpos) + && (SDL_strcmp(windowpos, "center") == 0))) { PhWindowQueryVisible(Ph_QUERY_CONSOLE, 0, 0, &desktopextent); - if (desktop_mode.width>w) - { - pos.x = (desktop_mode.width - w)/2; + if (desktop_mode.width > w) { + pos.x = (desktop_mode.width - w) / 2; } - if (desktop_mode.height>h) - { - pos.y = (desktop_mode.height - h)/2; + if (desktop_mode.height > h) { + pos.y = (desktop_mode.height - h) / 2; } - pos.x+=desktopextent.ul.x; - pos.y+=desktopextent.ul.y; + pos.x += desktopextent.ul.x; + pos.y += desktopextent.ul.y; PtSetArg(&args[nargs++], Pt_ARG_POS, &pos, 0); - } - else - { - if (windowpos) - { - if (SDL_sscanf(windowpos, "%d,%d", &x, &y) == 2) - { - if ((xw, olddim->h); #endif @@ -317,113 +324,110 @@ static int ph_SetupWindow(_THIS, int w, int h, int flags) return 0; } -static const struct ColourMasks* ph_GetColourMasks(int bpp) +static const struct ColourMasks * +ph_GetColourMasks(int bpp) { /* The alpha mask doesn't appears to be needed */ static const struct ColourMasks phColorMasks[5] = { - /* 8 bit */ {0, 0, 0, 0, 8}, - /* 15 bit ARGB */ {0x7C00, 0x03E0, 0x001F, 0x8000, 15}, - /* 16 bit RGB */ {0xF800, 0x07E0, 0x001F, 0x0000, 16}, - /* 24 bit RGB */ {0xFF0000, 0x00FF00, 0x0000FF, 0x000000, 24}, - /* 32 bit ARGB */ {0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000, 32}, + /* 8 bit */ {0, 0, 0, 0, 8}, + /* 15 bit ARGB */ {0x7C00, 0x03E0, 0x001F, 0x8000, 15}, + /* 16 bit RGB */ {0xF800, 0x07E0, 0x001F, 0x0000, 16}, + /* 24 bit RGB */ {0xFF0000, 0x00FF00, 0x0000FF, 0x000000, 24}, + /* 32 bit ARGB */ {0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000, + 32}, }; - switch (bpp) - { - case 8: - return &phColorMasks[0]; - case 15: - return &phColorMasks[1]; - case 16: - return &phColorMasks[2]; - case 24: - return &phColorMasks[3]; - case 32: - return &phColorMasks[4]; + switch (bpp) { + case 8: + return &phColorMasks[0]; + case 15: + return &phColorMasks[1]; + case 16: + return &phColorMasks[2]; + case 24: + return &phColorMasks[3]; + case 32: + return &phColorMasks[4]; } return NULL; } -static int ph_VideoInit(_THIS, SDL_PixelFormat* vformat) +static int +ph_VideoInit(_THIS, SDL_PixelFormat * vformat) { PgHWCaps_t hwcaps; int i; - window=NULL; - desktoppal=SDLPH_PAL_NONE; + window = NULL; + desktoppal = SDLPH_PAL_NONE; #if SDL_VIDEO_OPENGL - oglctx=NULL; - oglbuffers=NULL; - oglflags=0; - oglbpp=0; + oglctx = NULL; + oglbuffers = NULL; + oglflags = 0; + oglbpp = 0; #endif - - old_video_mode=-1; - old_refresh_rate=-1; - - if (NULL == (phevent = SDL_malloc(EVENT_SIZE))) - { + + old_video_mode = -1; + old_refresh_rate = -1; + + if (NULL == (phevent = SDL_malloc(EVENT_SIZE))) { SDL_OutOfMemory(); return -1; } SDL_memset(phevent, 0x00, EVENT_SIZE); window = ph_CreateWindow(this); - if (window == NULL) - { + if (window == NULL) { SDL_SetError("ph_VideoInit(): Couldn't create video window !\n"); return -1; } /* Create the blank cursor */ SDL_BlankCursor = this->CreateWMCursor(this, blank_cdata, blank_cmask, - (int)BLANK_CWIDTH, (int)BLANK_CHEIGHT, - (int)BLANK_CHOTX, (int)BLANK_CHOTY); + (int) BLANK_CWIDTH, + (int) BLANK_CHEIGHT, + (int) BLANK_CHOTX, + (int) BLANK_CHOTY); - if (SDL_BlankCursor == NULL) - { + if (SDL_BlankCursor == NULL) { return -1; } - if (PgGetGraphicsHWCaps(&hwcaps) < 0) - { + if (PgGetGraphicsHWCaps(&hwcaps) < 0) { SDL_SetError("ph_VideoInit(): GetGraphicsHWCaps function failed !\n"); this->FreeWMCursor(this, SDL_BlankCursor); return -1; } - if (PgGetVideoModeInfo(hwcaps.current_video_mode, &desktop_mode) < 0) - { - SDL_SetError("ph_VideoInit(): PgGetVideoModeInfo function failed !\n"); + if (PgGetVideoModeInfo(hwcaps.current_video_mode, &desktop_mode) < 0) { + SDL_SetError + ("ph_VideoInit(): PgGetVideoModeInfo function failed !\n"); this->FreeWMCursor(this, SDL_BlankCursor); return -1; } - /* Determine the current screen size */ - this->info.current_w = desktop_mode.width; - this->info.current_h = desktop_mode.height; + /* Determine the current screen size */ + this->info.current_w = desktop_mode.width; + this->info.current_h = desktop_mode.height; /* We need to return BytesPerPixel as it in used by CreateRGBsurface */ vformat->BitsPerPixel = desktop_mode.bits_per_pixel; - vformat->BytesPerPixel = desktop_mode.bytes_per_scanline/desktop_mode.width; + vformat->BytesPerPixel = + desktop_mode.bytes_per_scanline / desktop_mode.width; desktopbpp = desktop_mode.bits_per_pixel; - + /* save current palette */ - if (desktopbpp==8) - { + if (desktopbpp == 8) { PgGetPalette(savedpal); PgGetPalette(syspalph); - } - else - { - for(i=0; i<_Pg_MAX_PALETTE; i++) - { - savedpal[i]=PgRGB(0, 0, 0); - syspalph[i]=PgRGB(0, 0, 0); + } else { + for (i = 0; i < _Pg_MAX_PALETTE; i++) { + savedpal[i] = PgRGB(0, 0, 0); + syspalph[i] = PgRGB(0, 0, 0); } } - + currently_fullscreen = 0; currently_hided = 0; currently_maximized = 0; @@ -437,17 +441,19 @@ static int ph_VideoInit(_THIS, SDL_PixelFormat* vformat) OCImage.FrameData0 = NULL; OCImage.FrameData1 = NULL; videomode_emulatemode = 0; - + this->info.wm_available = 1; ph_UpdateHWInfo(this); - + return 0; } -static SDL_Surface* ph_SetVideoMode(_THIS, SDL_Surface *current, int width, int height, int bpp, Uint32 flags) +static SDL_Surface * +ph_SetVideoMode(_THIS, SDL_Surface * current, int width, int height, int bpp, + Uint32 flags) { - const struct ColourMasks* mask; + const struct ColourMasks *mask; /* Lock the event thread, in multi-threading environments */ SDL_Lock_EventThread(); @@ -455,77 +461,62 @@ static SDL_Surface* ph_SetVideoMode(_THIS, SDL_Surface *current, int width, int current->flags = flags; /* if we do not have desired fullscreen mode, then fallback into window mode */ - if (((current->flags & SDL_FULLSCREEN) == SDL_FULLSCREEN) && (ph_GetVideoMode(width, height, bpp)==0)) - { - current->flags &= ~SDL_FULLSCREEN; - current->flags &= ~SDL_NOFRAME; - current->flags &= ~SDL_RESIZABLE; + if (((current->flags & SDL_FULLSCREEN) == SDL_FULLSCREEN) + && (ph_GetVideoMode(width, height, bpp) == 0)) { + current->flags &= ~SDL_FULLSCREEN; + current->flags &= ~SDL_NOFRAME; + current->flags &= ~SDL_RESIZABLE; } ph_SetupWindow(this, width, height, current->flags); mask = ph_GetColourMasks(bpp); - if (mask != NULL) - { - SDL_ReallocFormat(current, mask->bpp, mask->red, mask->green, mask->blue, 0); - } - else - { - SDL_SetError("ph_SetVideoMode(): desired bpp is not supported by photon !\n"); + if (mask != NULL) { + SDL_ReallocFormat(current, mask->bpp, mask->red, mask->green, + mask->blue, 0); + } else { + SDL_SetError + ("ph_SetVideoMode(): desired bpp is not supported by photon !\n"); return NULL; } - if ((current->flags & SDL_OPENGL)==SDL_OPENGL) - { + if (current->flags & SDL_INTERNALOPENGL) { #if !SDL_VIDEO_OPENGL /* if no built-in OpenGL support */ - SDL_SetError("ph_SetVideoMode(): no OpenGL support, you need to recompile SDL.\n"); - current->flags &= ~SDL_OPENGL; + SDL_SetError + ("ph_SetVideoMode(): no OpenGL support, you need to recompile SDL.\n"); + current->flags &= ~SDL_INTERNALOPENGL; return NULL; #endif /* SDL_VIDEO_OPENGL */ - } - else - { + } else { /* Initialize internal variables */ - if ((current->flags & SDL_FULLSCREEN) == SDL_FULLSCREEN) - { - if (bpp==8) - { - desktoppal=SDLPH_PAL_SYSTEM; + if ((current->flags & SDL_FULLSCREEN) == SDL_FULLSCREEN) { + if (bpp == 8) { + desktoppal = SDLPH_PAL_SYSTEM; } - current->flags &= ~SDL_RESIZABLE; /* no resize for Direct Context */ + current->flags &= ~SDL_RESIZABLE; /* no resize for Direct Context */ current->flags |= SDL_HWSURFACE; - } - else - { + } else { /* remove this if we'll have support for the non-fullscreen sw/hw+doublebuf one day */ current->flags &= ~SDL_DOUBLEBUF; /* Use offscreen memory if SDL_HWSURFACE flag is set */ - if ((current->flags & SDL_HWSURFACE) == SDL_HWSURFACE) - { - if (desktopbpp!=bpp) - { - current->flags &= ~SDL_HWSURFACE; + if ((current->flags & SDL_HWSURFACE) == SDL_HWSURFACE) { + if (desktopbpp != bpp) { + current->flags &= ~SDL_HWSURFACE; } } /* using palette emulation code in window mode */ - if (bpp==8) - { - if (desktopbpp>=15) - { + if (bpp == 8) { + if (desktopbpp >= 15) { desktoppal = SDLPH_PAL_EMULATE; - } - else - { + } else { desktoppal = SDLPH_PAL_SYSTEM; } - } - else - { - desktoppal = SDLPH_PAL_NONE; + } else { + desktoppal = SDLPH_PAL_NONE; } } } @@ -533,29 +524,24 @@ static SDL_Surface* ph_SetVideoMode(_THIS, SDL_Surface *current, int width, int current->w = width; current->h = height; - if (desktoppal==SDLPH_PAL_SYSTEM) - { - current->flags|=SDL_HWPALETTE; + if (desktoppal == SDLPH_PAL_SYSTEM) { + current->flags |= SDL_HWPALETTE; } /* Must call at least once for setup image planes */ - if (ph_SetupUpdateFunction(this, current, current->flags)==-1) - { + if (ph_SetupUpdateFunction(this, current, current->flags) == -1) { /* Error string was filled in the ph_SetupUpdateFunction() */ return NULL; } /* finish window drawing, if we are not in fullscreen, of course */ - if ((current->flags & SDL_FULLSCREEN) != SDL_FULLSCREEN) - { - PtFlush(); - } - else - { - PgFlush(); + if ((current->flags & SDL_FULLSCREEN) != SDL_FULLSCREEN) { + PtFlush(); + } else { + PgFlush(); } - visualbpp=bpp; + visualbpp = bpp; ph_UpdateHWInfo(this); @@ -565,33 +551,33 @@ static SDL_Surface* ph_SetVideoMode(_THIS, SDL_Surface *current, int width, int return (current); } -static void ph_VideoQuit(_THIS) +static void +ph_VideoQuit(_THIS) { /* restore palette */ - if (desktopbpp==8) - { + if (desktopbpp == 8) { PgSetPalette(syspalph, 0, -1, 0, 0, 0); - PgSetPalette(savedpal, 0, 0, _Pg_MAX_PALETTE, Pg_PALSET_GLOBAL | Pg_PALSET_FORCE_EXPOSE, 0); + PgSetPalette(savedpal, 0, 0, _Pg_MAX_PALETTE, + Pg_PALSET_GLOBAL | Pg_PALSET_FORCE_EXPOSE, 0); PgFlush(); } - ph_DestroyImage(this, SDL_VideoSurface); + ph_DestroyImage(this, SDL_VideoSurface); - if (window) - { + if (window) { PtUnrealizeWidget(window); PtDestroyWidget(window); - window=NULL; + window = NULL; } - if (phevent!=NULL) - { + if (phevent != NULL) { SDL_free(phevent); - phevent=NULL; + phevent = NULL; } } -static int ph_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color *colors) +static int +ph_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color * colors) { int i; SDL_Rect updaterect; @@ -601,48 +587,43 @@ static int ph_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color *colors) updaterect.h = this->screen->h; /* palette emulation code, using palette of the PhImage_t struct */ - if (desktoppal==SDLPH_PAL_EMULATE) - { - if ((SDL_Image) && (SDL_Image->palette)) - { - for (i=firstcolor; ipalette)) { + for (i = firstcolor; i < firstcolor + ncolors; i++) { + syspalph[i] = + PgRGB(colors[i - firstcolor].r, + colors[i - firstcolor].g, colors[i - firstcolor].b); SDL_Image->palette[i] = syspalph[i]; } /* image needs to be redrawn */ this->UpdateRects(this, 1, &updaterect); } - } - else - { - if (desktoppal==SDLPH_PAL_SYSTEM) - { - for (i=firstcolor; iscreen->flags & SDL_FULLSCREEN) != SDL_FULLSCREEN) - { - /* window mode must use soft palette */ - PgSetPalette(&syspalph[firstcolor], 0, firstcolor, ncolors, Pg_PALSET_GLOBAL, 0); + if ((this->screen->flags & SDL_FULLSCREEN) != SDL_FULLSCREEN) { + /* window mode must use soft palette */ + PgSetPalette(&syspalph[firstcolor], 0, firstcolor, + ncolors, Pg_PALSET_GLOBAL, 0); /* image needs to be redrawn */ this->UpdateRects(this, 1, &updaterect); - } - else - { + } else { /* fullscreen mode must use hardware palette */ - PgSetPalette(&syspalph[firstcolor], 0, firstcolor, ncolors, Pg_PALSET_GLOBAL, 0); + PgSetPalette(&syspalph[firstcolor], 0, firstcolor, + ncolors, Pg_PALSET_GLOBAL, 0); } - } - else - { + } else { /* SDLPH_PAL_NONE do nothing */ } } - + return 1; } +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/photon/SDL_ph_video.h b/src/video/photon/SDL_ph_video.h index 0eac5b1d8..fb0d9b56b 100644 --- a/src/video/photon/SDL_ph_video.h +++ b/src/video/photon/SDL_ph_video.h @@ -35,12 +35,12 @@ #include #if SDL_VIDEO_OPENGL - #if (_NTO_VERSION < 630) - #include - #else - #include - #include - #endif /* 6.3.0 */ +#if (_NTO_VERSION < 630) +#include +#else +#include +#include +#endif /* 6.3.0 */ #endif /* SDL_VIDEO_OPENGL */ /* Hidden "this" pointer for the video functions */ @@ -54,9 +54,9 @@ typedef struct { - unsigned char* Y; - unsigned char* V; - unsigned char* U; + unsigned char *Y; + unsigned char *V; + unsigned char *U; } FRAMEDATA; /* Mask values for SDL_ReallocFormat() */ @@ -72,57 +72,57 @@ struct ColourMasks /* Private display data */ struct SDL_PrivateVideoData { - PgDisplaySettings_t mode_settings; - PtWidget_t *Window; /* used to handle input events */ - PhImage_t *image; /* used to display image */ + PgDisplaySettings_t mode_settings; + PtWidget_t *Window; /* used to handle input events */ + PhImage_t *image; /* used to display image */ #if SDL_VIDEO_OPENGL - #if (_NTO_VERSION < 630) - PdOpenGLContext_t* OGLContext; /* OpenGL context */ - void* OGLBuffers; /* OpenGL buffers (unused) */ - #else - qnxglc_t* OGLContext; /* OpenGL context for the 6.3 */ - qnxgl_bufs_t* OGLBuffers; /* OpenGL buffers for the 6.3 */ - #endif /* 630 */ - - Uint32 OGLFlags; /* OpenGL flags */ - Uint32 OGLBPP; /* OpenGL bpp */ -#endif /* SDL_VIDEO_OPENGL */ +#if (_NTO_VERSION < 630) + PdOpenGLContext_t *OGLContext; /* OpenGL context */ + void *OGLBuffers; /* OpenGL buffers (unused) */ +#else + qnxglc_t *OGLContext; /* OpenGL context for the 6.3 */ + qnxgl_bufs_t *OGLBuffers; /* OpenGL buffers for the 6.3 */ +#endif /* 630 */ + + Uint32 OGLFlags; /* OpenGL flags */ + Uint32 OGLBPP; /* OpenGL bpp */ +#endif /* SDL_VIDEO_OPENGL */ PgColor_t savedpal[_Pg_MAX_PALETTE]; PgColor_t syspalph[_Pg_MAX_PALETTE]; struct { - PdDirectContext_t* direct_context; - PdOffscreenContext_t* offscreen_context; - PdOffscreenContext_t* offscreen_backcontext; - PhDrawContext_t* oldDC; - uint8_t* dc_ptr; - unsigned char* CurrentFrameData; - unsigned char* FrameData0; - unsigned char* FrameData1; - Uint32 current; - Uint32 flags; + PdDirectContext_t *direct_context; + PdOffscreenContext_t *offscreen_context; + PdOffscreenContext_t *offscreen_backcontext; + PhDrawContext_t *oldDC; + uint8_t *dc_ptr; + unsigned char *CurrentFrameData; + unsigned char *FrameData0; + unsigned char *FrameData1; + Uint32 current; + Uint32 flags; } ocimage; - PgHWCaps_t graphics_card_caps; /* Graphics card caps at the moment of start */ - PgVideoModeInfo_t desktop_mode; /* Current desktop video mode information */ - int old_video_mode; /* Stored mode before fullscreen switch */ - int old_refresh_rate; /* Stored refresh rate befor fullscreen switch */ + PgHWCaps_t graphics_card_caps; /* Graphics card caps at the moment of start */ + PgVideoModeInfo_t desktop_mode; /* Current desktop video mode information */ + int old_video_mode; /* Stored mode before fullscreen switch */ + int old_refresh_rate; /* Stored refresh rate befor fullscreen switch */ int mouse_relative; - WMcursor* BlankCursor; + WMcursor *BlankCursor; uint32_t videomode_emulatemode; - Uint32 visualbpp; /* current visual bpp */ - Uint32 desktopbpp; /* bpp of desktop at the moment of start */ - Uint32 desktoppal; /* palette mode emulation or system */ + Uint32 visualbpp; /* current visual bpp */ + Uint32 desktopbpp; /* bpp of desktop at the moment of start */ + Uint32 desktoppal; /* palette mode emulation or system */ int currently_fullscreen; - int currently_hided; /* 1 - window hided (minimazed), 0 - normal */ - int currently_maximized; /* 1 - window hided (minimazed), 0 - normal */ + int currently_hided; /* 1 - window hided (minimazed), 0 - normal */ + int currently_maximized; /* 1 - window hided (minimazed), 0 - normal */ - PhEvent_t* event; - SDL_Overlay* overlay; + PhEvent_t *event; + SDL_Overlay *overlay; }; #define mode_settings (this->hidden->mode_settings) @@ -148,10 +148,11 @@ struct SDL_PrivateVideoData #define videomode_emulatemode (this->hidden->videomode_emulatemode) #if SDL_VIDEO_OPENGL - #define oglctx (this->hidden->OGLContext) - #define oglbuffers (this->hidden->OGLBuffers) - #define oglflags (this->hidden->OGLFlags) - #define oglbpp (this->hidden->OGLBPP) +#define oglctx (this->hidden->OGLContext) +#define oglbuffers (this->hidden->OGLBuffers) +#define oglflags (this->hidden->OGLFlags) +#define oglbpp (this->hidden->OGLBPP) #endif /* SDL_VIDEO_OPENGL */ #endif /* __SDL_PH_VIDEO_H__ */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/photon/SDL_ph_wm.c b/src/video/photon/SDL_ph_wm.c index 68dc780fc..80d7b7ca2 100644 --- a/src/video/photon/SDL_ph_wm.c +++ b/src/video/photon/SDL_ph_wm.c @@ -35,19 +35,20 @@ #include "SDL_ph_modes_c.h" #include "SDL_ph_wm_c.h" -void ph_SetIcon(_THIS, SDL_Surface *icon, Uint8 *mask) +void +ph_SetIcon(_THIS, SDL_Surface * icon, Uint8 * mask) { return; } /* Set window caption */ -void ph_SetCaption(_THIS, const char *title, const char *icon) +void +ph_SetCaption(_THIS, const char *title, const char *icon) { SDL_Lock_EventThread(); /* sanity check for set caption call before window init */ - if (window!=NULL) - { + if (window != NULL) { PtSetResource(window, Pt_ARG_WINDOW_TITLE, title, 0); } @@ -55,7 +56,8 @@ void ph_SetCaption(_THIS, const char *title, const char *icon) } /* Iconify current window */ -int ph_IconifyWindow(_THIS) +int +ph_IconifyWindow(_THIS) { PhWindowEvent_t windowevent; @@ -72,47 +74,50 @@ int ph_IconifyWindow(_THIS) return 0; } -SDL_GrabMode ph_GrabInputNoLock(_THIS, SDL_GrabMode mode) +SDL_GrabMode +ph_GrabInputNoLock(_THIS, SDL_GrabMode mode) { short abs_x, abs_y; - if( mode == SDL_GRAB_OFF ) - { - PtSetResource(window, Pt_ARG_WINDOW_STATE, Pt_FALSE, Ph_WM_STATE_ISALTKEY); - } - else - { - PtSetResource(window, Pt_ARG_WINDOW_STATE, Pt_TRUE, Ph_WM_STATE_ISALTKEY); + if (mode == SDL_GRAB_OFF) { + PtSetResource(window, Pt_ARG_WINDOW_STATE, Pt_FALSE, + Ph_WM_STATE_ISALTKEY); + } else { + PtSetResource(window, Pt_ARG_WINDOW_STATE, Pt_TRUE, + Ph_WM_STATE_ISALTKEY); PtGetAbsPosition(window, &abs_x, &abs_y); - PhMoveCursorAbs(PhInputGroup(NULL), abs_x + SDL_VideoSurface->w/2, abs_y + SDL_VideoSurface->h/2); + PhMoveCursorAbs(PhInputGroup(NULL), + abs_x + SDL_VideoSurface->w / 2, + abs_y + SDL_VideoSurface->h / 2); } SDL_Unlock_EventThread(); - return(mode); + return (mode); } -SDL_GrabMode ph_GrabInput(_THIS, SDL_GrabMode mode) +SDL_GrabMode +ph_GrabInput(_THIS, SDL_GrabMode mode) { SDL_Lock_EventThread(); mode = ph_GrabInputNoLock(this, mode); SDL_Unlock_EventThread(); - return(mode); + return (mode); } -int ph_GetWMInfo(_THIS, SDL_SysWMinfo *info) +int +ph_GetWMInfo(_THIS, SDL_SysWMinfo * info) { - if (info->version.major <= SDL_MAJOR_VERSION) - { + if (info->version.major <= SDL_MAJOR_VERSION) { return 1; - } - else - { + } else { SDL_SetError("Application not compiled with SDL %d.%d\n", - SDL_MAJOR_VERSION, SDL_MINOR_VERSION); + SDL_MAJOR_VERSION, SDL_MINOR_VERSION); return -1; } } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/photon/SDL_ph_wm_c.h b/src/video/photon/SDL_ph_wm_c.h index 2122d239f..1cd10bbba 100644 --- a/src/video/photon/SDL_ph_wm_c.h +++ b/src/video/photon/SDL_ph_wm_c.h @@ -28,10 +28,11 @@ /* Functions to be exported */ extern void ph_SetCaption(_THIS, const char *title, const char *icon); -extern void ph_SetIcon(_THIS, SDL_Surface *icon, Uint8 *mask); +extern void ph_SetIcon(_THIS, SDL_Surface * icon, Uint8 * mask); extern int ph_IconifyWindow(_THIS); extern SDL_GrabMode ph_GrabInputNoLock(_THIS, SDL_GrabMode mode); extern SDL_GrabMode ph_GrabInput(_THIS, SDL_GrabMode mode); -extern int ph_GetWMInfo(_THIS, SDL_SysWMinfo *info); +extern int ph_GetWMInfo(_THIS, SDL_SysWMinfo * info); #endif /* __SDL_PH_WM_H__ */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/photon/SDL_phyuv.c b/src/video/photon/SDL_phyuv.c index 62ec04147..a2b9962c4 100644 --- a/src/video/photon/SDL_phyuv.c +++ b/src/video/photon/SDL_phyuv.c @@ -36,25 +36,25 @@ #define OVERLAY_STATE_ACTIVE 1 /* The functions are used to manipulate software video overlays */ -static struct private_yuvhwfuncs ph_yuvfuncs = -{ +static struct private_yuvhwfuncs ph_yuvfuncs = { ph_LockYUVOverlay, ph_UnlockYUVOverlay, ph_DisplayYUVOverlay, ph_FreeYUVOverlay }; -int grab_ptrs2(PgVideoChannel_t* channel, FRAMEDATA* Frame0, FRAMEDATA* Frame1) +int +grab_ptrs2(PgVideoChannel_t * channel, FRAMEDATA * Frame0, FRAMEDATA * Frame1) { int planes = 0; /* Buffers have moved; re-obtain the pointers */ - Frame0->Y = (unsigned char *)PdGetOffscreenContextPtr(channel->yplane1); - Frame1->Y = (unsigned char *)PdGetOffscreenContextPtr(channel->yplane2); - Frame0->U = (unsigned char *)PdGetOffscreenContextPtr(channel->vplane1); - Frame1->U = (unsigned char *)PdGetOffscreenContextPtr(channel->vplane2); - Frame0->V = (unsigned char *)PdGetOffscreenContextPtr(channel->uplane1); - Frame1->V = (unsigned char *)PdGetOffscreenContextPtr(channel->uplane2); + Frame0->Y = (unsigned char *) PdGetOffscreenContextPtr(channel->yplane1); + Frame1->Y = (unsigned char *) PdGetOffscreenContextPtr(channel->yplane2); + Frame0->U = (unsigned char *) PdGetOffscreenContextPtr(channel->vplane1); + Frame1->U = (unsigned char *) PdGetOffscreenContextPtr(channel->vplane2); + Frame0->V = (unsigned char *) PdGetOffscreenContextPtr(channel->uplane1); + Frame1->V = (unsigned char *) PdGetOffscreenContextPtr(channel->uplane2); if (Frame0->Y) planes++; @@ -68,21 +68,22 @@ int grab_ptrs2(PgVideoChannel_t* channel, FRAMEDATA* Frame0, FRAMEDATA* Frame1) return planes; } -SDL_Overlay* ph_CreateYUVOverlay(_THIS, int width, int height, Uint32 format, SDL_Surface* display) +SDL_Overlay * +ph_CreateYUVOverlay(_THIS, int width, int height, Uint32 format, + SDL_Surface * display) { - SDL_Overlay* overlay; - struct private_yuvhwdata* hwdata; + SDL_Overlay *overlay; + struct private_yuvhwdata *hwdata; int vidport; int rtncode; int planes; - int i=0; + int i = 0; PhPoint_t pos; /* Create the overlay structure */ overlay = SDL_calloc(1, sizeof(SDL_Overlay)); - if (overlay == NULL) - { + if (overlay == NULL) { SDL_OutOfMemory(); return NULL; } @@ -92,15 +93,14 @@ SDL_Overlay* ph_CreateYUVOverlay(_THIS, int width, int height, Uint32 format, SD overlay->w = width; overlay->h = height; overlay->hwdata = NULL; - + /* Set up the YUV surface function structure */ overlay->hwfuncs = &ph_yuvfuncs; /* Create the pixel data and lookup tables */ hwdata = SDL_calloc(1, sizeof(struct private_yuvhwdata)); - if (hwdata == NULL) - { + if (hwdata == NULL) { SDL_OutOfMemory(); SDL_FreeYUVOverlay(overlay); return NULL; @@ -109,18 +109,19 @@ SDL_Overlay* ph_CreateYUVOverlay(_THIS, int width, int height, Uint32 format, SD overlay->hwdata = hwdata; PhDCSetCurrent(0); - if (overlay->hwdata->channel == NULL) - { - if ((overlay->hwdata->channel = PgCreateVideoChannel(Pg_VIDEO_CHANNEL_SCALER, 0)) == NULL) - { - SDL_SetError("ph_CreateYUVOverlay(): Create channel failed: %s\n", strerror(errno)); + if (overlay->hwdata->channel == NULL) { + if ((overlay->hwdata->channel = + PgCreateVideoChannel(Pg_VIDEO_CHANNEL_SCALER, 0)) == NULL) { + SDL_SetError + ("ph_CreateYUVOverlay(): Create channel failed: %s\n", + strerror(errno)); SDL_FreeYUVOverlay(overlay); return NULL; } } - overlay->hwdata->forcedredraw=0; + overlay->hwdata->forcedredraw = 0; PtGetAbsPosition(window, &pos.x, &pos.y); overlay->hwdata->CurrentWindowPos.x = pos.x; @@ -130,40 +131,41 @@ SDL_Overlay* ph_CreateYUVOverlay(_THIS, int width, int height, Uint32 format, SD overlay->hwdata->CurrentViewPort.size.w = width; overlay->hwdata->CurrentViewPort.size.h = height; overlay->hwdata->State = OVERLAY_STATE_UNINIT; - overlay->hwdata->FrameData0 = (FRAMEDATA *) SDL_calloc(1, sizeof(FRAMEDATA)); - overlay->hwdata->FrameData1 = (FRAMEDATA *) SDL_calloc(1, sizeof(FRAMEDATA)); + overlay->hwdata->FrameData0 = + (FRAMEDATA *) SDL_calloc(1, sizeof(FRAMEDATA)); + overlay->hwdata->FrameData1 = + (FRAMEDATA *) SDL_calloc(1, sizeof(FRAMEDATA)); vidport = -1; - i=0; - - overlay->hwdata->ischromakey=0; + i = 0; + + overlay->hwdata->ischromakey = 0; do { SDL_memset(&overlay->hwdata->caps, 0x00, sizeof(PgScalerCaps_t)); overlay->hwdata->caps.size = sizeof(PgScalerCaps_t); - rtncode = PgGetScalerCapabilities(overlay->hwdata->channel, i, &overlay->hwdata->caps); - if (rtncode==0) - { - if (overlay->hwdata->caps.format==format) - { - if ((overlay->hwdata->caps.flags & Pg_SCALER_CAP_DST_CHROMA_KEY) == Pg_SCALER_CAP_DST_CHROMA_KEY) - { - overlay->hwdata->ischromakey=1; - } - vidport=1; - break; + rtncode = + PgGetScalerCapabilities(overlay->hwdata->channel, i, + &overlay->hwdata->caps); + if (rtncode == 0) { + if (overlay->hwdata->caps.format == format) { + if ((overlay->hwdata->caps. + flags & Pg_SCALER_CAP_DST_CHROMA_KEY) == + Pg_SCALER_CAP_DST_CHROMA_KEY) { + overlay->hwdata->ischromakey = 1; + } + vidport = 1; + break; } - } - else - { - break; + } else { + break; } i++; - } while(1); + } + while (1); - if (vidport == -1) - { + if (vidport == -1) { SDL_SetError("No available video ports for requested format\n"); SDL_FreeYUVOverlay(overlay); return NULL; @@ -176,53 +178,55 @@ SDL_Overlay* ph_CreateYUVOverlay(_THIS, int width, int height, Uint32 format, SD overlay->hwdata->props.src_dim.h = height; /* overlay->hwdata->chromakey = PgGetOverlayChromaColor(); */ - overlay->hwdata->chromakey = PgRGB(12, 6, 12); /* very dark pink color */ + overlay->hwdata->chromakey = PgRGB(12, 6, 12); /* very dark pink color */ overlay->hwdata->props.color_key = overlay->hwdata->chromakey; - PhAreaToRect(&overlay->hwdata->CurrentViewPort, &overlay->hwdata->props.viewport); + PhAreaToRect(&overlay->hwdata->CurrentViewPort, + &overlay->hwdata->props.viewport); overlay->hwdata->props.flags = Pg_SCALER_PROP_DOUBLE_BUFFER; - if ((overlay->hwdata->ischromakey)&&(overlay->hwdata->chromakey)) - { + if ((overlay->hwdata->ischromakey) && (overlay->hwdata->chromakey)) { overlay->hwdata->props.flags |= Pg_SCALER_PROP_CHROMA_ENABLE; - overlay->hwdata->props.flags |= Pg_SCALER_PROP_CHROMA_SPECIFY_KEY_MASK; - } - else - { + overlay->hwdata->props.flags |= + Pg_SCALER_PROP_CHROMA_SPECIFY_KEY_MASK; + } else { overlay->hwdata->props.flags &= ~Pg_SCALER_PROP_CHROMA_ENABLE; } - rtncode = PgConfigScalerChannel(overlay->hwdata->channel, &overlay->hwdata->props); + rtncode = + PgConfigScalerChannel(overlay->hwdata->channel, + &overlay->hwdata->props); - switch(rtncode) - { - case -1: SDL_SetError("PgConfigScalerChannel failed\n"); - SDL_FreeYUVOverlay(overlay); - return NULL; - case 1: - case 0: - default: - break; + switch (rtncode) { + case -1: + SDL_SetError("PgConfigScalerChannel failed\n"); + SDL_FreeYUVOverlay(overlay); + return NULL; + case 1: + case 0: + default: + break; } - planes = grab_ptrs2(overlay->hwdata->channel, overlay->hwdata->FrameData0, overlay->hwdata->FrameData1); + planes = + grab_ptrs2(overlay->hwdata->channel, overlay->hwdata->FrameData0, + overlay->hwdata->FrameData1); - if(overlay->hwdata->channel->yplane1 != NULL) + if (overlay->hwdata->channel->yplane1 != NULL) overlay->hwdata->YStride = overlay->hwdata->channel->yplane1->pitch; - if(overlay->hwdata->channel->vplane1 != NULL) + if (overlay->hwdata->channel->vplane1 != NULL) overlay->hwdata->UStride = overlay->hwdata->channel->vplane1->pitch; - if(overlay->hwdata->channel->uplane1 != NULL) + if (overlay->hwdata->channel->uplane1 != NULL) overlay->hwdata->VStride = overlay->hwdata->channel->uplane1->pitch; /* check for the validness of all planes */ if ((overlay->hwdata->channel->yplane1 == NULL) && (overlay->hwdata->channel->uplane1 == NULL) && - (overlay->hwdata->channel->vplane1 == NULL)) - { - SDL_FreeYUVOverlay(overlay); - SDL_SetError("PgConfigScaler() returns all planes equal NULL\n"); - return NULL; + (overlay->hwdata->channel->vplane1 == NULL)) { + SDL_FreeYUVOverlay(overlay); + SDL_SetError("PgConfigScaler() returns all planes equal NULL\n"); + return NULL; } /* overlay->hwdata->current = PgNextVideoFrame(overlay->hwdata->channel); @@ -245,43 +249,39 @@ SDL_Overlay* ph_CreateYUVOverlay(_THIS, int width, int height, Uint32 format, SD /* Find the pitch and offset values for the overlay */ overlay->planes = planes; overlay->pitches = SDL_calloc(overlay->planes, sizeof(Uint16)); - overlay->pixels = SDL_calloc(overlay->planes, sizeof(Uint8*)); - if (!overlay->pitches || !overlay->pixels) - { + overlay->pixels = SDL_calloc(overlay->planes, sizeof(Uint8 *)); + if (!overlay->pitches || !overlay->pixels) { SDL_OutOfMemory(); SDL_FreeYUVOverlay(overlay); - return(NULL); + return (NULL); } - if (overlay->planes > 0) - { + if (overlay->planes > 0) { overlay->pitches[0] = overlay->hwdata->channel->yplane1->pitch; - overlay->pixels[0] = overlay->hwdata->CurrentFrameData->Y; + overlay->pixels[0] = overlay->hwdata->CurrentFrameData->Y; } - if (overlay->planes > 1) - { + if (overlay->planes > 1) { overlay->pitches[1] = overlay->hwdata->channel->vplane1->pitch; - overlay->pixels[1] = overlay->hwdata->CurrentFrameData->U; + overlay->pixels[1] = overlay->hwdata->CurrentFrameData->U; } - if (overlay->planes > 2) - { + if (overlay->planes > 2) { overlay->pitches[2] = overlay->hwdata->channel->uplane1->pitch; - overlay->pixels[2] = overlay->hwdata->CurrentFrameData->V; + overlay->pixels[2] = overlay->hwdata->CurrentFrameData->V; } overlay->hwdata->State = OVERLAY_STATE_ACTIVE; overlay->hwdata->scaler_on = 0; overlay->hw_overlay = 1; - current_overlay=overlay; + current_overlay = overlay; return overlay; } -int ph_LockYUVOverlay(_THIS, SDL_Overlay* overlay) +int +ph_LockYUVOverlay(_THIS, SDL_Overlay * overlay) { - if (overlay == NULL) - { + if (overlay == NULL) { return -1; } @@ -321,44 +321,43 @@ int ph_LockYUVOverlay(_THIS, SDL_Overlay* overlay) } */ - return(0); + return (0); } -void ph_UnlockYUVOverlay(_THIS, SDL_Overlay* overlay) +void +ph_UnlockYUVOverlay(_THIS, SDL_Overlay * overlay) { - if (overlay == NULL) - { + if (overlay == NULL) { return; } overlay->hwdata->locked = 0; } -int ph_DisplayYUVOverlay(_THIS, SDL_Overlay* overlay, SDL_Rect* src, SDL_Rect* dst) +int +ph_DisplayYUVOverlay(_THIS, SDL_Overlay * overlay, SDL_Rect * src, + SDL_Rect * dst) { int rtncode; PhPoint_t pos; SDL_Rect backrect; PhRect_t windowextent; - int winchanged=0; + int winchanged = 0; - if ((overlay == NULL) || (overlay->hwdata==NULL)) - { + if ((overlay == NULL) || (overlay->hwdata == NULL)) { return -1; } - if (overlay->hwdata->State == OVERLAY_STATE_UNINIT) - { + if (overlay->hwdata->State == OVERLAY_STATE_UNINIT) { return -1; } PtGetAbsPosition(window, &pos.x, &pos.y); - if ((pos.x!=overlay->hwdata->CurrentWindowPos.x) || - (pos.y!=overlay->hwdata->CurrentWindowPos.y)) - { - winchanged=1; - overlay->hwdata->CurrentWindowPos.x=pos.x; - overlay->hwdata->CurrentWindowPos.y=pos.y; + if ((pos.x != overlay->hwdata->CurrentWindowPos.x) || + (pos.y != overlay->hwdata->CurrentWindowPos.y)) { + winchanged = 1; + overlay->hwdata->CurrentWindowPos.x = pos.x; + overlay->hwdata->CurrentWindowPos.y = pos.y; } /* If CurrentViewPort position/size has been changed, then move/resize the viewport */ @@ -366,51 +365,57 @@ int ph_DisplayYUVOverlay(_THIS, SDL_Overlay* overlay, SDL_Rect* src, SDL_Rect* d (overlay->hwdata->CurrentViewPort.pos.y != dst->y) || (overlay->hwdata->CurrentViewPort.size.w != dst->w) || (overlay->hwdata->CurrentViewPort.size.h != dst->h) || - (overlay->hwdata->scaler_on==0) || (winchanged==1) || - (overlay->hwdata->forcedredraw==1)) - { + (overlay->hwdata->scaler_on == 0) || (winchanged == 1) || + (overlay->hwdata->forcedredraw == 1)) { - if (overlay->hwdata->ischromakey==1) - { + if (overlay->hwdata->ischromakey == 1) { /* restore screen behind the overlay/chroma color. */ - backrect.x=overlay->hwdata->CurrentViewPort.pos.x; - backrect.y=overlay->hwdata->CurrentViewPort.pos.y; - backrect.w=overlay->hwdata->CurrentViewPort.size.w; - backrect.h=overlay->hwdata->CurrentViewPort.size.h; + backrect.x = overlay->hwdata->CurrentViewPort.pos.x; + backrect.y = overlay->hwdata->CurrentViewPort.pos.y; + backrect.w = overlay->hwdata->CurrentViewPort.size.w; + backrect.h = overlay->hwdata->CurrentViewPort.size.h; this->UpdateRects(this, 1, &backrect); /* Draw the new rectangle of the chroma color at the viewport position */ PgSetFillColor(overlay->hwdata->chromakey); - PgDrawIRect(dst->x, dst->y, dst->x+dst->w-1, dst->y+dst->h-1, Pg_DRAW_FILL); + PgDrawIRect(dst->x, dst->y, dst->x + dst->w - 1, + dst->y + dst->h - 1, Pg_DRAW_FILL); PgFlush(); } overlay->hwdata->props.flags |= Pg_SCALER_PROP_SCALER_ENABLE; overlay->hwdata->scaler_on = 1; - PhWindowQueryVisible(Ph_QUERY_CONSOLE, 0, PtWidgetRid(window), &windowextent); - overlay->hwdata->CurrentViewPort.pos.x = pos.x-windowextent.ul.x+dst->x; - overlay->hwdata->CurrentViewPort.pos.y = pos.y-windowextent.ul.y+dst->y; + PhWindowQueryVisible(Ph_QUERY_CONSOLE, 0, PtWidgetRid(window), + &windowextent); + overlay->hwdata->CurrentViewPort.pos.x = + pos.x - windowextent.ul.x + dst->x; + overlay->hwdata->CurrentViewPort.pos.y = + pos.y - windowextent.ul.y + dst->y; overlay->hwdata->CurrentViewPort.size.w = dst->w; overlay->hwdata->CurrentViewPort.size.h = dst->h; - PhAreaToRect(&overlay->hwdata->CurrentViewPort, &overlay->hwdata->props.viewport); + PhAreaToRect(&overlay->hwdata->CurrentViewPort, + &overlay->hwdata->props.viewport); overlay->hwdata->CurrentViewPort.pos.x = dst->x; overlay->hwdata->CurrentViewPort.pos.y = dst->y; - rtncode = PgConfigScalerChannel(overlay->hwdata->channel, &(overlay->hwdata->props)); + rtncode = + PgConfigScalerChannel(overlay->hwdata->channel, + &(overlay->hwdata->props)); - switch(rtncode) - { - case -1: - SDL_SetError("PgConfigScalerChannel() function failed\n"); - SDL_FreeYUVOverlay(overlay); - return -1; - case 1: - grab_ptrs2(overlay->hwdata->channel, overlay->hwdata->FrameData0, overlay->hwdata->FrameData1); - break; - case 0: - default: - break; + switch (rtncode) { + case -1: + SDL_SetError("PgConfigScalerChannel() function failed\n"); + SDL_FreeYUVOverlay(overlay); + return -1; + case 1: + grab_ptrs2(overlay->hwdata->channel, + overlay->hwdata->FrameData0, + overlay->hwdata->FrameData1); + break; + case 0: + default: + break; } } @@ -452,53 +457,54 @@ int ph_DisplayYUVOverlay(_THIS, SDL_Overlay* overlay, SDL_Rect* src, SDL_Rect* d } } */ - + return 0; } -void ph_FreeYUVOverlay(_THIS, SDL_Overlay *overlay) +void +ph_FreeYUVOverlay(_THIS, SDL_Overlay * overlay) { SDL_Rect backrect; - if (overlay == NULL) - { + if (overlay == NULL) { return; } - if (overlay->hwdata == NULL) - { + if (overlay->hwdata == NULL) { return; } - current_overlay=NULL; + current_overlay = NULL; /* restore screen behind the overlay/chroma color. */ - backrect.x=overlay->hwdata->CurrentViewPort.pos.x; - backrect.y=overlay->hwdata->CurrentViewPort.pos.y; - backrect.w=overlay->hwdata->CurrentViewPort.size.w; - backrect.h=overlay->hwdata->CurrentViewPort.size.h; + backrect.x = overlay->hwdata->CurrentViewPort.pos.x; + backrect.y = overlay->hwdata->CurrentViewPort.pos.y; + backrect.w = overlay->hwdata->CurrentViewPort.size.w; + backrect.h = overlay->hwdata->CurrentViewPort.size.h; this->UpdateRects(this, 1, &backrect); /* it is need for some buggy drivers, that can't hide overlay before */ /* freeing buffer, so we got trash on the srceen */ overlay->hwdata->props.flags &= ~Pg_SCALER_PROP_SCALER_ENABLE; - PgConfigScalerChannel(overlay->hwdata->channel, &(overlay->hwdata->props)); + PgConfigScalerChannel(overlay->hwdata->channel, + &(overlay->hwdata->props)); overlay->hwdata->scaler_on = 0; overlay->hwdata->State = OVERLAY_STATE_UNINIT; - if (overlay->hwdata->channel != NULL) - { + if (overlay->hwdata->channel != NULL) { PgDestroyVideoChannel(overlay->hwdata->channel); overlay->hwdata->channel = NULL; return; - } + } + + overlay->hwdata->CurrentFrameData = NULL; - overlay->hwdata->CurrentFrameData = NULL; - SDL_free(overlay->hwdata->FrameData0); SDL_free(overlay->hwdata->FrameData1); overlay->hwdata->FrameData0 = NULL; overlay->hwdata->FrameData1 = NULL; SDL_free(overlay->hwdata); } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/photon/SDL_phyuv_c.h b/src/video/photon/SDL_phyuv_c.h index a004a03e2..dd9f7ea99 100644 --- a/src/video/photon/SDL_phyuv_c.h +++ b/src/video/photon/SDL_phyuv_c.h @@ -31,12 +31,12 @@ struct private_yuvhwdata { - FRAMEDATA* CurrentFrameData; - FRAMEDATA* FrameData0; - FRAMEDATA* FrameData1; - PgScalerProps_t props; - PgScalerCaps_t caps; - PgVideoChannel_t* channel; + FRAMEDATA *CurrentFrameData; + FRAMEDATA *FrameData0; + FRAMEDATA *FrameData1; + PgScalerProps_t props; + PgScalerCaps_t caps; + PgVideoChannel_t *channel; PhArea_t CurrentViewPort; PhPoint_t CurrentWindowPos; long format; @@ -53,10 +53,13 @@ struct private_yuvhwdata int locked; }; -extern SDL_Overlay* ph_CreateYUVOverlay(_THIS, int width, int height, Uint32 format, SDL_Surface* display); -extern int ph_LockYUVOverlay(_THIS, SDL_Overlay* overlay); -extern void ph_UnlockYUVOverlay(_THIS, SDL_Overlay* overlay); -extern int ph_DisplayYUVOverlay(_THIS, SDL_Overlay* overlay, SDL_Rect* src, SDL_Rect* dst); -extern void ph_FreeYUVOverlay(_THIS, SDL_Overlay* overlay); +extern SDL_Overlay *ph_CreateYUVOverlay(_THIS, int width, int height, + Uint32 format, SDL_Surface * display); +extern int ph_LockYUVOverlay(_THIS, SDL_Overlay * overlay); +extern void ph_UnlockYUVOverlay(_THIS, SDL_Overlay * overlay); +extern int ph_DisplayYUVOverlay(_THIS, SDL_Overlay * overlay, SDL_Rect * src, + SDL_Rect * dst); +extern void ph_FreeYUVOverlay(_THIS, SDL_Overlay * overlay); #endif /* __SDL_PH_YUV_H__ */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/picogui/SDL_pgevents.c b/src/video/picogui/SDL_pgevents.c index 0d6b530b2..692dea4c6 100644 --- a/src/video/picogui/SDL_pgevents.c +++ b/src/video/picogui/SDL_pgevents.c @@ -30,88 +30,100 @@ #include "SDL_pgvideo.h" #include "SDL_pgevents_c.h" -int PG_HandleClose(struct pgEvent *evt) +int +PG_HandleClose(struct pgEvent *evt) { - SDL_PrivateQuit(); - return 1; /* Intercept the event's normal quit handling */ + SDL_PrivateQuit(); + return 1; /* Intercept the event's normal quit handling */ } -int PG_HandleResize(struct pgEvent *evt) +int +PG_HandleResize(struct pgEvent *evt) { - SDL_PrivateResize(evt->e.size.w, evt->e.size.h); - return 0; + SDL_PrivateResize(evt->e.size.w, evt->e.size.h); + return 0; } -int PG_HandleKey(struct pgEvent *evt) +int +PG_HandleKey(struct pgEvent *evt) { - SDL_keysym sym; - SDL_memset(&sym,0,sizeof(sym)); - sym.sym = evt->e.kbd.key; - sym.mod = evt->e.kbd.mods; - SDL_PrivateKeyboard(evt->type == PG_WE_KBD_KEYDOWN, &sym); - return 0; + SDL_keysym sym; + SDL_memset(&sym, 0, sizeof(sym)); + sym.sym = evt->e.kbd.key; + sym.mod = evt->e.kbd.mods; + SDL_PrivateKeyboard(evt->type == PG_WE_KBD_KEYDOWN, &sym); + return 0; } -int PG_HandleChar(struct pgEvent *evt) +int +PG_HandleChar(struct pgEvent *evt) { - SDL_keysym sym; - SDL_memset(&sym,0,sizeof(sym)); - sym.unicode = evt->e.kbd.key; - sym.mod = evt->e.kbd.mods; - SDL_PrivateKeyboard(evt->type == PG_WE_KBD_KEYDOWN, &sym); - return 0; + SDL_keysym sym; + SDL_memset(&sym, 0, sizeof(sym)); + sym.unicode = evt->e.kbd.key; + sym.mod = evt->e.kbd.mods; + SDL_PrivateKeyboard(evt->type == PG_WE_KBD_KEYDOWN, &sym); + return 0; } -int PG_HandleMouseButton(struct pgEvent *evt) -{ - /* We need to focus the canvas when it's clicked */ - if (evt->extra) { - SDL_VideoDevice *this = (SDL_VideoDevice *) evt->extra; - pgFocus(this->hidden->wCanvas); - } - SDL_PrivateMouseButton(evt->type == PG_WE_PNTR_DOWN, evt->e.pntr.chbtn, - evt->e.pntr.x, evt->e.pntr.y); - return 0; +int +PG_HandleMouseButton(struct pgEvent *evt) +{ + /* We need to focus the canvas when it's clicked */ + if (evt->extra) { + SDL_VideoDevice *this = (SDL_VideoDevice *) evt->extra; + pgFocus(this->hidden->wCanvas); + } + SDL_PrivateMouseButton(evt->type == PG_WE_PNTR_DOWN, evt->e.pntr.chbtn, + evt->e.pntr.x, evt->e.pntr.y); + return 0; } -int PG_HandleMouseMotion(struct pgEvent *evt) +int +PG_HandleMouseMotion(struct pgEvent *evt) { - SDL_PrivateMouseMotion(evt->e.pntr.btn,0,evt->e.pntr.x, evt->e.pntr.y); - return 0; + SDL_PrivateMouseMotion(evt->e.pntr.btn, 0, evt->e.pntr.x, evt->e.pntr.y); + return 0; } -void PG_PumpEvents(_THIS) +void +PG_PumpEvents(_THIS) { - /* Process all pending events */ - pgEventPoll(); + /* Process all pending events */ + pgEventPoll(); } -void PG_InitOSKeymap(_THIS) +void +PG_InitOSKeymap(_THIS) { - /* We need no keymap */ + /* We need no keymap */ } -void PG_InitEvents(_THIS) +void +PG_InitEvents(_THIS) { - /* Turn on all the mouse and keyboard triggers for our canvas, normally less important - * events like mouse movement are ignored to save bandwidth. */ - pgSetWidget(this->hidden->wCanvas, PG_WP_TRIGGERMASK, - pgGetWidget(this->hidden->wCanvas, PG_WP_TRIGGERMASK) | - PG_TRIGGER_UP | PG_TRIGGER_DOWN | PG_TRIGGER_MOVE | - PG_TRIGGER_KEYUP | PG_TRIGGER_KEYDOWN | PG_TRIGGER_CHAR,0); - - /* Start our canvas out focused, so we get keyboard input */ - pgFocus(this->hidden->wCanvas); - - /* Set up bindings for all the above event handlers */ - pgBind(this->hidden->wApp, PG_WE_CLOSE, &PG_HandleClose, NULL); - pgBind(this->hidden->wCanvas, PG_WE_BUILD, &PG_HandleResize, NULL); - pgBind(this->hidden->wCanvas, PG_WE_KBD_CHAR, &PG_HandleChar, NULL); - pgBind(this->hidden->wCanvas, PG_WE_KBD_KEYUP, &PG_HandleKey, NULL); - pgBind(this->hidden->wCanvas, PG_WE_KBD_KEYDOWN, &PG_HandleKey, NULL); - pgBind(this->hidden->wCanvas, PG_WE_PNTR_MOVE, &PG_HandleMouseMotion, NULL); - pgBind(this->hidden->wCanvas, PG_WE_PNTR_UP, &PG_HandleMouseButton, NULL); - pgBind(this->hidden->wCanvas, PG_WE_PNTR_DOWN, &PG_HandleMouseButton, this); + /* Turn on all the mouse and keyboard triggers for our canvas, normally less important + * events like mouse movement are ignored to save bandwidth. */ + pgSetWidget(this->hidden->wCanvas, PG_WP_TRIGGERMASK, + pgGetWidget(this->hidden->wCanvas, PG_WP_TRIGGERMASK) | + PG_TRIGGER_UP | PG_TRIGGER_DOWN | PG_TRIGGER_MOVE | + PG_TRIGGER_KEYUP | PG_TRIGGER_KEYDOWN | PG_TRIGGER_CHAR, 0); + + /* Start our canvas out focused, so we get keyboard input */ + pgFocus(this->hidden->wCanvas); + + /* Set up bindings for all the above event handlers */ + pgBind(this->hidden->wApp, PG_WE_CLOSE, &PG_HandleClose, NULL); + pgBind(this->hidden->wCanvas, PG_WE_BUILD, &PG_HandleResize, NULL); + pgBind(this->hidden->wCanvas, PG_WE_KBD_CHAR, &PG_HandleChar, NULL); + pgBind(this->hidden->wCanvas, PG_WE_KBD_KEYUP, &PG_HandleKey, NULL); + pgBind(this->hidden->wCanvas, PG_WE_KBD_KEYDOWN, &PG_HandleKey, NULL); + pgBind(this->hidden->wCanvas, PG_WE_PNTR_MOVE, &PG_HandleMouseMotion, + NULL); + pgBind(this->hidden->wCanvas, PG_WE_PNTR_UP, &PG_HandleMouseButton, NULL); + pgBind(this->hidden->wCanvas, PG_WE_PNTR_DOWN, &PG_HandleMouseButton, + this); } /* end of SDL_pgevents.c ... */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/picogui/SDL_pgevents_c.h b/src/video/picogui/SDL_pgevents_c.h index 2b7124f7d..891aa4db7 100644 --- a/src/video/picogui/SDL_pgevents_c.h +++ b/src/video/picogui/SDL_pgevents_c.h @@ -34,4 +34,4 @@ extern void PG_InitEvents(_THIS); extern void PG_InitOSKeymap(_THIS); /* end of SDL_pgevents_c.h ... */ - +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/picogui/SDL_pgvideo.c b/src/video/picogui/SDL_pgvideo.c index 04464afb0..0ae49b48b 100644 --- a/src/video/picogui/SDL_pgvideo.c +++ b/src/video/picogui/SDL_pgvideo.c @@ -36,329 +36,351 @@ #define PGVID_DRIVER_NAME "picogui" /* Initialization/Query functions */ -static int PG_VideoInit(_THIS, SDL_PixelFormat *vformat); -static SDL_Rect **PG_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags); -static SDL_Surface *PG_SetVideoMode(_THIS, SDL_Surface *current, int width, int height, int bpp, Uint32 flags); -static int PG_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color *colors); +static int PG_VideoInit(_THIS, SDL_PixelFormat * vformat); +static SDL_Rect **PG_ListModes(_THIS, SDL_PixelFormat * format, Uint32 flags); +static SDL_Surface *PG_SetVideoMode(_THIS, SDL_Surface * current, int width, + int height, int bpp, Uint32 flags); +static int PG_SetColors(_THIS, int firstcolor, int ncolors, + SDL_Color * colors); static void PG_VideoQuit(_THIS); /* Hardware surface functions */ -static int PG_AllocHWSurface(_THIS, SDL_Surface *surface); -static int PG_LockHWSurface(_THIS, SDL_Surface *surface); -static void PG_UnlockHWSurface(_THIS, SDL_Surface *surface); -static void PG_FreeHWSurface(_THIS, SDL_Surface *surface); +static int PG_AllocHWSurface(_THIS, SDL_Surface * surface); +static int PG_LockHWSurface(_THIS, SDL_Surface * surface); +static void PG_UnlockHWSurface(_THIS, SDL_Surface * surface); +static void PG_FreeHWSurface(_THIS, SDL_Surface * surface); /* etc. */ -static void PG_UpdateRects(_THIS, int numrects, SDL_Rect *rects); +static void PG_UpdateRects(_THIS, int numrects, SDL_Rect * rects); // The implementation dependent data for the window manager cursor -struct WMcursor { - /* Our cursor is a PicoGUI theme */ - pghandle theme; -} ; +struct WMcursor +{ + /* Our cursor is a PicoGUI theme */ + pghandle theme; +}; /* WM functions */ void PG_SetCaption(_THIS, const char *title, const char *icon); -WMcursor * PG_CreateWMCursor (_THIS,Uint8 * data, Uint8 * mask, - int w, int h, int hot_x, int hot_y); -void PG_FreeWMCursor (_THIS, WMcursor * cursor); +WMcursor *PG_CreateWMCursor(_THIS, Uint8 * data, Uint8 * mask, + int w, int h, int hot_x, int hot_y); +void PG_FreeWMCursor(_THIS, WMcursor * cursor); void PG_WarpWMCursor(_THIS, Uint16 x, Uint16 y); -int PG_ShowWMCursor (_THIS, WMcursor * cursor); +int PG_ShowWMCursor(_THIS, WMcursor * cursor); /* PicoGUI driver bootstrap functions */ -static int PG_Available(void) +static int +PG_Available(void) { - /* FIXME: The current client lib doesn't give a way to see if the picogui - * server is reachable without causing a fatal error if it isn't. - * This should be fixed in cli_c2, but until then assume we can - * connect. Since more common drivers like X11 are probed first anyway, - * this shouldn't be a huge problem. - */ - return(1); + /* FIXME: The current client lib doesn't give a way to see if the picogui + * server is reachable without causing a fatal error if it isn't. + * This should be fixed in cli_c2, but until then assume we can + * connect. Since more common drivers like X11 are probed first anyway, + * this shouldn't be a huge problem. + */ + return (1); } -static void PG_DeleteDevice(SDL_VideoDevice *device) +static void +PG_DeleteDevice(SDL_VideoDevice * device) { - SDL_free(device->hidden); - SDL_free(device); + SDL_free(device->hidden); + SDL_free(device); } -static SDL_VideoDevice *PG_CreateDevice(int devindex) +static SDL_VideoDevice * +PG_CreateDevice(int devindex) { - SDL_VideoDevice *device; - - /* Initialize all variables that we clean on shutdown */ - device = (SDL_VideoDevice *)SDL_malloc(sizeof(SDL_VideoDevice)); - if ( device ) { - SDL_memset(device, 0, (sizeof *device)); - device->hidden = (struct SDL_PrivateVideoData *) - SDL_malloc((sizeof *device->hidden)); - } - if ( (device == NULL) || (device->hidden == NULL) ) { - SDL_OutOfMemory(); - if ( device ) { - SDL_free(device); - } - return(0); - } - SDL_memset(device->hidden, 0, (sizeof *device->hidden)); - - /* Set the function pointers */ - device->VideoInit = PG_VideoInit; - device->ListModes = PG_ListModes; - device->SetVideoMode = PG_SetVideoMode; - device->CreateYUVOverlay = NULL; - device->SetColors = PG_SetColors; - device->UpdateRects = PG_UpdateRects; - device->VideoQuit = PG_VideoQuit; - device->AllocHWSurface = PG_AllocHWSurface; - device->CheckHWBlit = NULL; - device->FillHWRect = NULL; - device->SetHWColorKey = NULL; - device->SetHWAlpha = NULL; - device->LockHWSurface = PG_LockHWSurface; - device->UnlockHWSurface = PG_UnlockHWSurface; - device->FlipHWSurface = NULL; - device->FreeHWSurface = PG_FreeHWSurface; - device->SetCaption = PG_SetCaption; - device->SetIcon = NULL; - device->IconifyWindow = NULL; - device->GrabInput = NULL; - - device->PumpEvents = PG_PumpEvents; - device->InitOSKeymap = PG_InitOSKeymap; - - device->ShowWMCursor = PG_ShowWMCursor; - device->CreateWMCursor = PG_CreateWMCursor; - device->FreeWMCursor = PG_FreeWMCursor; - device->WarpWMCursor = PG_WarpWMCursor; - - device->free = PG_DeleteDevice; - - return device; + SDL_VideoDevice *device; + + /* Initialize all variables that we clean on shutdown */ + device = (SDL_VideoDevice *) SDL_malloc(sizeof(SDL_VideoDevice)); + if (device) { + SDL_memset(device, 0, (sizeof *device)); + device->hidden = (struct SDL_PrivateVideoData *) + SDL_malloc((sizeof *device->hidden)); + } + if ((device == NULL) || (device->hidden == NULL)) { + SDL_OutOfMemory(); + if (device) { + SDL_free(device); + } + return (0); + } + SDL_memset(device->hidden, 0, (sizeof *device->hidden)); + + /* Set the function pointers */ + device->VideoInit = PG_VideoInit; + device->ListModes = PG_ListModes; + device->SetVideoMode = PG_SetVideoMode; + device->CreateYUVOverlay = NULL; + device->SetColors = PG_SetColors; + device->UpdateRects = PG_UpdateRects; + device->VideoQuit = PG_VideoQuit; + device->AllocHWSurface = PG_AllocHWSurface; + device->CheckHWBlit = NULL; + device->FillHWRect = NULL; + device->SetHWColorKey = NULL; + device->SetHWAlpha = NULL; + device->LockHWSurface = PG_LockHWSurface; + device->UnlockHWSurface = PG_UnlockHWSurface; + device->FlipHWSurface = NULL; + device->FreeHWSurface = PG_FreeHWSurface; + device->SetCaption = PG_SetCaption; + device->SetIcon = NULL; + device->IconifyWindow = NULL; + device->GrabInput = NULL; + + device->PumpEvents = PG_PumpEvents; + device->InitOSKeymap = PG_InitOSKeymap; + + device->ShowWMCursor = PG_ShowWMCursor; + device->CreateWMCursor = PG_CreateWMCursor; + device->FreeWMCursor = PG_FreeWMCursor; + device->WarpWMCursor = PG_WarpWMCursor; + + device->free = PG_DeleteDevice; + + return device; } VideoBootStrap PG_bootstrap = { - PGVID_DRIVER_NAME, "PicoGUI SDL driver", - PG_Available, PG_CreateDevice + PGVID_DRIVER_NAME, "PicoGUI SDL driver", + PG_Available, PG_CreateDevice }; -int PG_VideoInit(_THIS, SDL_PixelFormat *vformat) +int +PG_VideoInit(_THIS, SDL_PixelFormat * vformat) { - /* Connect to the PicoGUI server. No way to process command line args yet, - * but since this is based on SHM it's not important to be able to specify - * a remote PicoGUI server. - * - * FIXME: Another nitpick about the current client lib is there's no - * clean way to indicate that command line args are not available. - */ - pgInit(0,(char**)""); - this->hidden->mi = *pgGetVideoMode(); - - /* Create a picogui application and canvas. We'll populate the canvas later. */ - this->hidden->wApp = pgRegisterApp(PG_APP_NORMAL,"SDL",0); - this->hidden->wCanvas = pgNewWidget(PG_WIDGET_CANVAS,0,0); - pgSetWidget(PGDEFAULT, - PG_WP_SIDE, PG_S_ALL, - 0); - - PG_InitEvents(this); - - /* Determine the current screen size */ - this->info.current_w = this->hidden->mi.lxres; - this->info.current_h = this->hidden->mi.lyres; - - /* Determine the screen depth. - * We change this during the SDL_SetVideoMode implementation... - * Round up to the nearest Bytes per pixel - */ - vformat->BitsPerPixel = this->hidden->mi.bpp; - vformat->BytesPerPixel = this->hidden->mi.bpp >> 3; - if (this->hidden->mi.bpp & 7) - vformat->BytesPerPixel++; - - /* We're done! */ - return(0); + /* Connect to the PicoGUI server. No way to process command line args yet, + * but since this is based on SHM it's not important to be able to specify + * a remote PicoGUI server. + * + * FIXME: Another nitpick about the current client lib is there's no + * clean way to indicate that command line args are not available. + */ + pgInit(0, (char **) ""); + this->hidden->mi = *pgGetVideoMode(); + + /* Create a picogui application and canvas. We'll populate the canvas later. */ + this->hidden->wApp = pgRegisterApp(PG_APP_NORMAL, "SDL", 0); + this->hidden->wCanvas = pgNewWidget(PG_WIDGET_CANVAS, 0, 0); + pgSetWidget(PGDEFAULT, PG_WP_SIDE, PG_S_ALL, 0); + + PG_InitEvents(this); + + /* Determine the current screen size */ + this->info.current_w = this->hidden->mi.lxres; + this->info.current_h = this->hidden->mi.lyres; + + /* Determine the screen depth. + * We change this during the SDL_SetVideoMode implementation... + * Round up to the nearest Bytes per pixel + */ + vformat->BitsPerPixel = this->hidden->mi.bpp; + vformat->BytesPerPixel = this->hidden->mi.bpp >> 3; + if (this->hidden->mi.bpp & 7) + vformat->BytesPerPixel++; + + /* We're done! */ + return (0); } -SDL_Rect **PG_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags) +SDL_Rect ** +PG_ListModes(_THIS, SDL_PixelFormat * format, Uint32 flags) { - return (SDL_Rect **) -1; + return (SDL_Rect **) - 1; } -SDL_Surface *PG_SetVideoMode(_THIS, SDL_Surface *current, - int width, int height, int bpp, Uint32 flags) +SDL_Surface * +PG_SetVideoMode(_THIS, SDL_Surface * current, + int width, int height, int bpp, Uint32 flags) { - if ( this->hidden->bitmap ) { - /* Free old bitmap */ - if (current->pixels) { - shmdt(current->pixels); - current->pixels = NULL; - } - pgDelete(this->hidden->bitmap); - } - - /* Allocate the new pixel format for the screen */ - if ( ! SDL_ReallocFormat(current, bpp, 0, 0, 0, 0) ) { - SDL_SetError("Couldn't allocate new pixel format for requested mode"); - return(NULL); - } - - /* Create a new picogui bitmap */ - this->hidden->bitmap = pgCreateBitmap(width,height); - this->hidden->shm = *pgMakeSHMBitmap(this->hidden->bitmap); - current->pixels = shmat(shmget(this->hidden->shm.shm_key, - this->hidden->shm.shm_length,0),NULL,0); - - /* Reset the canvas, and draw persistent and incremental grops. - * Use mapping and offsets to center it. - */ - - pgWriteCmd(this->hidden->wCanvas, PGCANVAS_NUKE, 0); - - /* 0. Set the source position during incremental rendering - */ - pgWriteCmd(this->hidden->wCanvas, PGCANVAS_GROP, 5, PG_GROP_SETSRC,0,0,0,0); - pgWriteCmd(this->hidden->wCanvas, PGCANVAS_GROPFLAGS, 1, PG_GROPF_INCREMENTAL); - - /* 1. Incremental bitmap rendering - */ - pgWriteCmd(this->hidden->wCanvas, PGCANVAS_GROP, 6, PG_GROP_BITMAP, - 0,0,0,0,this->hidden->bitmap); - pgWriteCmd(this->hidden->wCanvas, PGCANVAS_GROPFLAGS, 1, PG_GROPF_INCREMENTAL); - - /* 2. Normal bitmap rendering - */ - pgWriteCmd(this->hidden->wCanvas, PGCANVAS_GROP, 6, PG_GROP_BITMAP, - 0,0,this->hidden->shm.width,this->hidden->shm.height,this->hidden->bitmap); - - /* Set up the new mode framebuffer */ - current->flags = 0; - current->w = this->hidden->shm.width; - current->h = this->hidden->shm.height; - current->pitch = this->hidden->shm.pitch; - - /* Set up pixel format */ - current->format->BitsPerPixel = this->hidden->shm.bpp; - current->format->BytesPerPixel = this->hidden->shm.bpp >> 3; - if (this->hidden->shm.bpp & 7) - current->format->BytesPerPixel++; - current->format->palette = NULL; - current->format->Rmask = this->hidden->shm.red_mask; - current->format->Gmask = this->hidden->shm.green_mask; - current->format->Bmask = this->hidden->shm.blue_mask; - current->format->Amask = this->hidden->shm.alpha_mask; - current->format->Rshift = this->hidden->shm.red_shift; - current->format->Gshift = this->hidden->shm.green_shift; - current->format->Bshift = this->hidden->shm.blue_shift; - current->format->Ashift = this->hidden->shm.alpha_shift; - current->format->Rloss = 8 - this->hidden->shm.red_length; - current->format->Gloss = 8 - this->hidden->shm.green_length; - current->format->Bloss = 8 - this->hidden->shm.blue_length; - current->format->Aloss = 8 - this->hidden->shm.alpha_length; - - /* Draw the app */ - pgUpdate(); - - /* We're done */ - return(current); + if (this->hidden->bitmap) { + /* Free old bitmap */ + if (current->pixels) { + shmdt(current->pixels); + current->pixels = NULL; + } + pgDelete(this->hidden->bitmap); + } + + /* Allocate the new pixel format for the screen */ + if (!SDL_ReallocFormat(current, bpp, 0, 0, 0, 0)) { + SDL_SetError("Couldn't allocate new pixel format for requested mode"); + return (NULL); + } + + /* Create a new picogui bitmap */ + this->hidden->bitmap = pgCreateBitmap(width, height); + this->hidden->shm = *pgMakeSHMBitmap(this->hidden->bitmap); + current->pixels = shmat(shmget(this->hidden->shm.shm_key, + this->hidden->shm.shm_length, 0), NULL, 0); + + /* Reset the canvas, and draw persistent and incremental grops. + * Use mapping and offsets to center it. + */ + + pgWriteCmd(this->hidden->wCanvas, PGCANVAS_NUKE, 0); + + /* 0. Set the source position during incremental rendering + */ + pgWriteCmd(this->hidden->wCanvas, PGCANVAS_GROP, 5, PG_GROP_SETSRC, 0, 0, + 0, 0); + pgWriteCmd(this->hidden->wCanvas, PGCANVAS_GROPFLAGS, 1, + PG_GROPF_INCREMENTAL); + + /* 1. Incremental bitmap rendering + */ + pgWriteCmd(this->hidden->wCanvas, PGCANVAS_GROP, 6, PG_GROP_BITMAP, + 0, 0, 0, 0, this->hidden->bitmap); + pgWriteCmd(this->hidden->wCanvas, PGCANVAS_GROPFLAGS, 1, + PG_GROPF_INCREMENTAL); + + /* 2. Normal bitmap rendering + */ + pgWriteCmd(this->hidden->wCanvas, PGCANVAS_GROP, 6, PG_GROP_BITMAP, + 0, 0, this->hidden->shm.width, this->hidden->shm.height, + this->hidden->bitmap); + + /* Set up the new mode framebuffer */ + current->flags = 0; + current->w = this->hidden->shm.width; + current->h = this->hidden->shm.height; + current->pitch = this->hidden->shm.pitch; + + /* Set up pixel format */ + current->format->BitsPerPixel = this->hidden->shm.bpp; + current->format->BytesPerPixel = this->hidden->shm.bpp >> 3; + if (this->hidden->shm.bpp & 7) + current->format->BytesPerPixel++; + current->format->palette = NULL; + current->format->Rmask = this->hidden->shm.red_mask; + current->format->Gmask = this->hidden->shm.green_mask; + current->format->Bmask = this->hidden->shm.blue_mask; + current->format->Amask = this->hidden->shm.alpha_mask; + current->format->Rshift = this->hidden->shm.red_shift; + current->format->Gshift = this->hidden->shm.green_shift; + current->format->Bshift = this->hidden->shm.blue_shift; + current->format->Ashift = this->hidden->shm.alpha_shift; + current->format->Rloss = 8 - this->hidden->shm.red_length; + current->format->Gloss = 8 - this->hidden->shm.green_length; + current->format->Bloss = 8 - this->hidden->shm.blue_length; + current->format->Aloss = 8 - this->hidden->shm.alpha_length; + + /* Draw the app */ + pgUpdate(); + + /* We're done */ + return (current); } /* We don't actually allow hardware surfaces other than the main one */ -static int PG_AllocHWSurface(_THIS, SDL_Surface *surface) +static int +PG_AllocHWSurface(_THIS, SDL_Surface * surface) { - return(-1); + return (-1); } -static void PG_FreeHWSurface(_THIS, SDL_Surface *surface) +static void +PG_FreeHWSurface(_THIS, SDL_Surface * surface) { - return; + return; } /* We need to wait for vertical retrace on page flipped displays */ -static int PG_LockHWSurface(_THIS, SDL_Surface *surface) +static int +PG_LockHWSurface(_THIS, SDL_Surface * surface) { - return(0); + return (0); } -static void PG_UnlockHWSurface(_THIS, SDL_Surface *surface) +static void +PG_UnlockHWSurface(_THIS, SDL_Surface * surface) { - return; + return; } -static void PG_UpdateRects(_THIS, int numrects, SDL_Rect *rects) +static void +PG_UpdateRects(_THIS, int numrects, SDL_Rect * rects) { - int i; - - for (i = 0; i < numrects; i++) { - if (rects[i].w <= 0 || rects[i].h <= 0) - continue; - - /* Schedule an incremental update for this rectangle, using - * the canvas gropnodes we've loaded beforehand. - */ - pgWriteCmd(this->hidden->wCanvas, PGCANVAS_FINDGROP, 1, 0); - pgWriteCmd(this->hidden->wCanvas, PGCANVAS_MOVEGROP, 4, - rects[i].x, rects[i].y, - rects[i].w, rects[i].h); - pgWriteCmd(this->hidden->wCanvas, PGCANVAS_FINDGROP, 1, 1); - pgWriteCmd(this->hidden->wCanvas, PGCANVAS_MOVEGROP, 4, - rects[i].x, rects[i].y, - rects[i].w, rects[i].h); - - /* Go perform the update */ - pgWriteCmd(this->hidden->wCanvas, PGCANVAS_INCREMENTAL, 0); - pgSubUpdate(this->hidden->wCanvas); - } + int i; + + for (i = 0; i < numrects; i++) { + if (rects[i].w <= 0 || rects[i].h <= 0) + continue; + + /* Schedule an incremental update for this rectangle, using + * the canvas gropnodes we've loaded beforehand. + */ + pgWriteCmd(this->hidden->wCanvas, PGCANVAS_FINDGROP, 1, 0); + pgWriteCmd(this->hidden->wCanvas, PGCANVAS_MOVEGROP, 4, + rects[i].x, rects[i].y, rects[i].w, rects[i].h); + pgWriteCmd(this->hidden->wCanvas, PGCANVAS_FINDGROP, 1, 1); + pgWriteCmd(this->hidden->wCanvas, PGCANVAS_MOVEGROP, 4, + rects[i].x, rects[i].y, rects[i].w, rects[i].h); + + /* Go perform the update */ + pgWriteCmd(this->hidden->wCanvas, PGCANVAS_INCREMENTAL, 0); + pgSubUpdate(this->hidden->wCanvas); + } } -int PG_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color *colors) +int +PG_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color * colors) { - /* do nothing of note. */ - return(1); + /* do nothing of note. */ + return (1); } /* Note: If we are terminated, this could be called in the middle of another SDL video routine -- notably UpdateRects. */ -void PG_VideoQuit(_THIS) +void +PG_VideoQuit(_THIS) { - if (this->screen->pixels != NULL) - { - shmdt(this->screen->pixels); - this->screen->pixels = NULL; - pgDelete(this->hidden->bitmap); - } - pgDelete(this->hidden->wCanvas); - pgDelete(this->hidden->wApp); + if (this->screen->pixels != NULL) { + shmdt(this->screen->pixels); + this->screen->pixels = NULL; + pgDelete(this->hidden->bitmap); + } + pgDelete(this->hidden->wCanvas); + pgDelete(this->hidden->wApp); } -void PG_SetCaption(_THIS, const char *title, const char *icon) +void +PG_SetCaption(_THIS, const char *title, const char *icon) { - if (title != NULL) - pgReplaceText(this->hidden->wApp, title); - pgUpdate(); + if (title != NULL) + pgReplaceText(this->hidden->wApp, title); + pgUpdate(); } /* FIXME: The cursor stuff isn't implemented yet! */ -WMcursor * PG_CreateWMCursor (_THIS,Uint8 * data, Uint8 * mask, - int w, int h, int hot_x, int hot_y) +WMcursor * +PG_CreateWMCursor(_THIS, Uint8 * data, Uint8 * mask, + int w, int h, int hot_x, int hot_y) { - static WMcursor dummy; - return &dummy; + static WMcursor dummy; + return &dummy; } -void PG_FreeWMCursor (_THIS, WMcursor * cursor) +void +PG_FreeWMCursor(_THIS, WMcursor * cursor) { } -void PG_WarpWMCursor(_THIS, Uint16 x, Uint16 y) +void +PG_WarpWMCursor(_THIS, Uint16 x, Uint16 y) { } -int PG_ShowWMCursor (_THIS, WMcursor * cursor) +int +PG_ShowWMCursor(_THIS, WMcursor * cursor) { - return 1; + return 1; } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/picogui/SDL_pgvideo.h b/src/video/picogui/SDL_pgvideo.h index f3d0e1d98..ce41b2629 100644 --- a/src/video/picogui/SDL_pgvideo.h +++ b/src/video/picogui/SDL_pgvideo.h @@ -40,11 +40,13 @@ /* Private display data */ -struct SDL_PrivateVideoData { - pghandle wApp, wCanvas; /* PicoGUI widgets */ - pghandle bitmap; - struct pgshmbitmap shm; /* shared memory info */ - struct pgmodeinfo mi; /* PicoGUI video mode info structure */ +struct SDL_PrivateVideoData +{ + pghandle wApp, wCanvas; /* PicoGUI widgets */ + pghandle bitmap; + struct pgshmbitmap shm; /* shared memory info */ + struct pgmodeinfo mi; /* PicoGUI video mode info structure */ }; #endif /* _SDL_pgvideo_h */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/ps2gs/SDL_gsevents.c b/src/video/ps2gs/SDL_gsevents.c index 13f96b5d2..c41274977 100644 --- a/src/video/ps2gs/SDL_gsevents.c +++ b/src/video/ps2gs/SDL_gsevents.c @@ -56,333 +56,347 @@ static Uint16 vga_keymap[NUM_VGAKEYMAPS][NR_KEYS]; static SDLKey keymap[128]; static Uint16 keymap_temp[128]; /* only used at startup */ -static SDL_keysym *TranslateKey(int scancode, SDL_keysym *keysym); +static SDL_keysym *TranslateKey(int scancode, SDL_keysym * keysym); /* Ugh, we have to duplicate the kernel's keysym mapping code... Oh, it's not so bad. :-) FIXME: Add keyboard LED handling code */ -static void GS_vgainitkeymaps(int fd) +static void +GS_vgainitkeymaps(int fd) { - struct kbentry entry; - int map, i; - - /* Don't do anything if we are passed a closed keyboard */ - if ( fd < 0 ) { - return; - } - - /* Load all the keysym mappings */ - for ( map=0; map= 0) && (saved_kbd_mode >= 0)); + return ((keyboard_fd >= 0) && (saved_kbd_mode >= 0)); } -int GS_EnterGraphicsMode(_THIS) +int +GS_EnterGraphicsMode(_THIS) { - struct termios keyboard_termios; - - /* Set medium-raw keyboard mode */ - if ( (keyboard_fd >= 0) && !GS_InGraphicsMode(this) ) { - - /* Switch to the correct virtual terminal */ - if ( current_vt > 0 ) { - struct vt_stat vtstate; - - if ( ioctl(keyboard_fd, VT_GETSTATE, &vtstate) == 0 ) { - saved_vt = vtstate.v_active; - } - if ( ioctl(keyboard_fd, VT_ACTIVATE, current_vt) == 0 ) { - ioctl(keyboard_fd, VT_WAITACTIVE, current_vt); - } - } - - /* Set the terminal input mode */ - if ( tcgetattr(keyboard_fd, &saved_kbd_termios) < 0 ) { - SDL_SetError("Unable to get terminal attributes"); - if ( keyboard_fd > 0 ) { - close(keyboard_fd); - } - keyboard_fd = -1; - return(-1); - } - if ( ioctl(keyboard_fd, KDGKBMODE, &saved_kbd_mode) < 0 ) { - SDL_SetError("Unable to get current keyboard mode"); - if ( keyboard_fd > 0 ) { - close(keyboard_fd); - } - keyboard_fd = -1; - return(-1); - } - keyboard_termios = saved_kbd_termios; - keyboard_termios.c_lflag &= ~(ICANON | ECHO | ISIG); - keyboard_termios.c_iflag &= ~(ISTRIP | IGNCR | ICRNL | INLCR | IXOFF | IXON); - keyboard_termios.c_cc[VMIN] = 0; - keyboard_termios.c_cc[VTIME] = 0; - if (tcsetattr(keyboard_fd, TCSAFLUSH, &keyboard_termios) < 0) { - GS_CloseKeyboard(this); - SDL_SetError("Unable to set terminal attributes"); - return(-1); - } - /* This will fail if we aren't root or this isn't our tty */ - if ( ioctl(keyboard_fd, KDSKBMODE, K_MEDIUMRAW) < 0 ) { - GS_CloseKeyboard(this); - SDL_SetError("Unable to set keyboard in raw mode"); - return(-1); - } - if ( ioctl(keyboard_fd, KDSETMODE, KD_GRAPHICS) < 0 ) { - GS_CloseKeyboard(this); - SDL_SetError("Unable to set keyboard in graphics mode"); - return(-1); - } - } - return(keyboard_fd); + struct termios keyboard_termios; + + /* Set medium-raw keyboard mode */ + if ((keyboard_fd >= 0) && !GS_InGraphicsMode(this)) { + + /* Switch to the correct virtual terminal */ + if (current_vt > 0) { + struct vt_stat vtstate; + + if (ioctl(keyboard_fd, VT_GETSTATE, &vtstate) == 0) { + saved_vt = vtstate.v_active; + } + if (ioctl(keyboard_fd, VT_ACTIVATE, current_vt) == 0) { + ioctl(keyboard_fd, VT_WAITACTIVE, current_vt); + } + } + + /* Set the terminal input mode */ + if (tcgetattr(keyboard_fd, &saved_kbd_termios) < 0) { + SDL_SetError("Unable to get terminal attributes"); + if (keyboard_fd > 0) { + close(keyboard_fd); + } + keyboard_fd = -1; + return (-1); + } + if (ioctl(keyboard_fd, KDGKBMODE, &saved_kbd_mode) < 0) { + SDL_SetError("Unable to get current keyboard mode"); + if (keyboard_fd > 0) { + close(keyboard_fd); + } + keyboard_fd = -1; + return (-1); + } + keyboard_termios = saved_kbd_termios; + keyboard_termios.c_lflag &= ~(ICANON | ECHO | ISIG); + keyboard_termios.c_iflag &= + ~(ISTRIP | IGNCR | ICRNL | INLCR | IXOFF | IXON); + keyboard_termios.c_cc[VMIN] = 0; + keyboard_termios.c_cc[VTIME] = 0; + if (tcsetattr(keyboard_fd, TCSAFLUSH, &keyboard_termios) < 0) { + GS_CloseKeyboard(this); + SDL_SetError("Unable to set terminal attributes"); + return (-1); + } + /* This will fail if we aren't root or this isn't our tty */ + if (ioctl(keyboard_fd, KDSKBMODE, K_MEDIUMRAW) < 0) { + GS_CloseKeyboard(this); + SDL_SetError("Unable to set keyboard in raw mode"); + return (-1); + } + if (ioctl(keyboard_fd, KDSETMODE, KD_GRAPHICS) < 0) { + GS_CloseKeyboard(this); + SDL_SetError("Unable to set keyboard in graphics mode"); + return (-1); + } + } + return (keyboard_fd); } -void GS_LeaveGraphicsMode(_THIS) +void +GS_LeaveGraphicsMode(_THIS) { - if ( GS_InGraphicsMode(this) ) { - ioctl(keyboard_fd, KDSETMODE, KD_TEXT); - ioctl(keyboard_fd, KDSKBMODE, saved_kbd_mode); - tcsetattr(keyboard_fd, TCSAFLUSH, &saved_kbd_termios); - saved_kbd_mode = -1; - - /* Head back over to the original virtual terminal */ - if ( saved_vt > 0 ) { - ioctl(keyboard_fd, VT_ACTIVATE, saved_vt); - } - } + if (GS_InGraphicsMode(this)) { + ioctl(keyboard_fd, KDSETMODE, KD_TEXT); + ioctl(keyboard_fd, KDSKBMODE, saved_kbd_mode); + tcsetattr(keyboard_fd, TCSAFLUSH, &saved_kbd_termios); + saved_kbd_mode = -1; + + /* Head back over to the original virtual terminal */ + if (saved_vt > 0) { + ioctl(keyboard_fd, VT_ACTIVATE, saved_vt); + } + } } -void GS_CloseKeyboard(_THIS) +void +GS_CloseKeyboard(_THIS) { - if ( keyboard_fd >= 0 ) { - GS_LeaveGraphicsMode(this); - if ( keyboard_fd > 0 ) { - close(keyboard_fd); - } - } - keyboard_fd = -1; + if (keyboard_fd >= 0) { + GS_LeaveGraphicsMode(this); + if (keyboard_fd > 0) { + close(keyboard_fd); + } + } + keyboard_fd = -1; } -int GS_OpenKeyboard(_THIS) +int +GS_OpenKeyboard(_THIS) { - /* Open only if not already opened */ - if ( keyboard_fd < 0 ) { - char *tty0[] = { "/dev/tty0", "/dev/vc/0", NULL }; - char *vcs[] = { "/dev/vc/%d", "/dev/tty%d", NULL }; - int i, tty0_fd; - - /* Try to query for a free virtual terminal */ - tty0_fd = -1; - for ( i=0; tty0[i] && (tty0_fd < 0); ++i ) { - tty0_fd = open(tty0[i], O_WRONLY, 0); - } - if ( tty0_fd < 0 ) { - tty0_fd = dup(0); /* Maybe stdin is a VT? */ - } - ioctl(tty0_fd, VT_OPENQRY, ¤t_vt); - close(tty0_fd); - if ( (geteuid() == 0) && (current_vt > 0) ) { - for ( i=0; vcs[i] && (keyboard_fd < 0); ++i ) { - char vtpath[12]; - - SDL_snprintf(vtpath, SDL_arraysize(vtpath), vcs[i], current_vt); - keyboard_fd = open(vtpath, O_RDWR, 0); + /* Open only if not already opened */ + if (keyboard_fd < 0) { + char *tty0[] = { "/dev/tty0", "/dev/vc/0", NULL }; + char *vcs[] = { "/dev/vc/%d", "/dev/tty%d", NULL }; + int i, tty0_fd; + + /* Try to query for a free virtual terminal */ + tty0_fd = -1; + for (i = 0; tty0[i] && (tty0_fd < 0); ++i) { + tty0_fd = open(tty0[i], O_WRONLY, 0); + } + if (tty0_fd < 0) { + tty0_fd = dup(0); /* Maybe stdin is a VT? */ + } + ioctl(tty0_fd, VT_OPENQRY, ¤t_vt); + close(tty0_fd); + if ((geteuid() == 0) && (current_vt > 0)) { + for (i = 0; vcs[i] && (keyboard_fd < 0); ++i) { + char vtpath[12]; + + SDL_snprintf(vtpath, SDL_arraysize(vtpath), vcs[i], + current_vt); + keyboard_fd = open(vtpath, O_RDWR, 0); #ifdef DEBUG_KEYBOARD - fprintf(stderr, "vtpath = %s, fd = %d\n", - vtpath, keyboard_fd); + fprintf(stderr, "vtpath = %s, fd = %d\n", + vtpath, keyboard_fd); #endif /* DEBUG_KEYBOARD */ - /* This needs to be our controlling tty - so that the kernel ioctl() calls work - */ - if ( keyboard_fd >= 0 ) { - tty0_fd = open("/dev/tty", O_RDWR, 0); - if ( tty0_fd >= 0 ) { - ioctl(tty0_fd, TIOCNOTTY, 0); - close(tty0_fd); - } - } - } - } - if ( keyboard_fd < 0 ) { - /* Last resort, maybe our tty is a usable VT */ - current_vt = 0; - keyboard_fd = open("/dev/tty", O_RDWR); - } + /* This needs to be our controlling tty + so that the kernel ioctl() calls work + */ + if (keyboard_fd >= 0) { + tty0_fd = open("/dev/tty", O_RDWR, 0); + if (tty0_fd >= 0) { + ioctl(tty0_fd, TIOCNOTTY, 0); + close(tty0_fd); + } + } + } + } + if (keyboard_fd < 0) { + /* Last resort, maybe our tty is a usable VT */ + current_vt = 0; + keyboard_fd = open("/dev/tty", O_RDWR); + } #ifdef DEBUG_KEYBOARD - fprintf(stderr, "Current VT: %d\n", current_vt); + fprintf(stderr, "Current VT: %d\n", current_vt); #endif - saved_kbd_mode = -1; - - /* Make sure that our input is a console terminal */ - { int dummy; - if ( ioctl(keyboard_fd, KDGKBMODE, &dummy) < 0 ) { - close(keyboard_fd); - keyboard_fd = -1; - SDL_SetError("Unable to open a console terminal"); - } - } - - /* Set up keymap */ - GS_vgainitkeymaps(keyboard_fd); - } - return(keyboard_fd); + saved_kbd_mode = -1; + + /* Make sure that our input is a console terminal */ + { + int dummy; + if (ioctl(keyboard_fd, KDGKBMODE, &dummy) < 0) { + close(keyboard_fd); + keyboard_fd = -1; + SDL_SetError("Unable to open a console terminal"); + } + } + + /* Set up keymap */ + GS_vgainitkeymaps(keyboard_fd); + } + return (keyboard_fd); } -static enum { - MOUSE_NONE = -1, - MOUSE_GPM, /* Note: GPM uses the MSC protocol */ - MOUSE_PS2, - MOUSE_IMPS2, - MOUSE_MS, - MOUSE_BM, - NUM_MOUSE_DRVS +static enum +{ + MOUSE_NONE = -1, + MOUSE_GPM, /* Note: GPM uses the MSC protocol */ + MOUSE_PS2, + MOUSE_IMPS2, + MOUSE_MS, + MOUSE_BM, + NUM_MOUSE_DRVS } mouse_drv = MOUSE_NONE; -void GS_CloseMouse(_THIS) +void +GS_CloseMouse(_THIS) { - if ( mouse_fd > 0 ) { - close(mouse_fd); - } - mouse_fd = -1; + if (mouse_fd > 0) { + close(mouse_fd); + } + mouse_fd = -1; } /* Returns processes listed in /proc with the desired name */ -static int find_pid(DIR *proc, const char *wanted_name) +static int +find_pid(DIR * proc, const char *wanted_name) { - struct dirent *entry; - int pid; - - /* First scan proc for the gpm process */ - pid = 0; - while ( (pid == 0) && ((entry=readdir(proc)) != NULL) ) { - if ( isdigit(entry->d_name[0]) ) { - FILE *status; - char path[PATH_MAX]; - char name[PATH_MAX]; - - SDL_snprintf(path, SDL_arraysize(path), "/proc/%s/status", entry->d_name); - status=fopen(path, "r"); - if ( status ) { - name[0] = '\0'; - fscanf(status, "Name: %s", name); - if ( SDL_strcmp(name, wanted_name) == 0 ) { - pid = atoi(entry->d_name); - } - fclose(status); - } - } - } - return pid; + struct dirent *entry; + int pid; + + /* First scan proc for the gpm process */ + pid = 0; + while ((pid == 0) && ((entry = readdir(proc)) != NULL)) { + if (isdigit(entry->d_name[0])) { + FILE *status; + char path[PATH_MAX]; + char name[PATH_MAX]; + + SDL_snprintf(path, SDL_arraysize(path), "/proc/%s/status", + entry->d_name); + status = fopen(path, "r"); + if (status) { + name[0] = '\0'; + fscanf(status, "Name: %s", name); + if (SDL_strcmp(name, wanted_name) == 0) { + pid = atoi(entry->d_name); + } + fclose(status); + } + } + } + return pid; } /* Returns true if /dev/gpmdata is being written to by gpm */ -static int gpm_available(void) +static int +gpm_available(void) { - int available; - DIR *proc; - int pid; - int cmdline, len, arglen; - char path[PATH_MAX]; - char args[PATH_MAX], *arg; - - /* Don't bother looking if the fifo isn't there */ - if ( access(GPM_NODE_FIFO, F_OK) < 0 ) { - return(0); - } - - available = 0; - proc = opendir("/proc"); - if ( proc ) { - while ( (pid=find_pid(proc, "gpm")) > 0 ) { - SDL_snprintf(path, SDL_arraysize(path), "/proc/%d/cmdline", pid); - cmdline = open(path, O_RDONLY, 0); - if ( cmdline >= 0 ) { - len = read(cmdline, args, sizeof(args)); - arg = args; - while ( len > 0 ) { - if ( SDL_strcmp(arg, "-R") == 0 ) { - available = 1; - } - arglen = SDL_strlen(arg)+1; - len -= arglen; - arg += arglen; - } - close(cmdline); - } - } - closedir(proc); - } - return available; + int available; + DIR *proc; + int pid; + int cmdline, len, arglen; + char path[PATH_MAX]; + char args[PATH_MAX], *arg; + + /* Don't bother looking if the fifo isn't there */ + if (access(GPM_NODE_FIFO, F_OK) < 0) { + return (0); + } + + available = 0; + proc = opendir("/proc"); + if (proc) { + while ((pid = find_pid(proc, "gpm")) > 0) { + SDL_snprintf(path, SDL_arraysize(path), "/proc/%d/cmdline", pid); + cmdline = open(path, O_RDONLY, 0); + if (cmdline >= 0) { + len = read(cmdline, args, sizeof(args)); + arg = args; + while (len > 0) { + if (SDL_strcmp(arg, "-R") == 0) { + available = 1; + } + arglen = SDL_strlen(arg) + 1; + len -= arglen; + arg += arglen; + } + close(cmdline); + } + } + closedir(proc); + } + return available; } @@ -391,587 +405,701 @@ static int gpm_available(void) * writes to device failed, but you still need to query the * device to see which mode it's actually in. */ -static int set_imps2_mode(int fd) +static int +set_imps2_mode(int fd) { - /* If you wanted to control the mouse mode (and we do :) ) ... - Set IMPS/2 protocol: - {0xf3,200,0xf3,100,0xf3,80} - Reset mouse device: - {0xFF} - */ - Uint8 set_imps2[] = {0xf3, 200, 0xf3, 100, 0xf3, 80}; - Uint8 reset = 0xff; - fd_set fdset; - struct timeval tv; - int retval = 0; - - if ( write(fd, &set_imps2, sizeof(set_imps2)) == sizeof(set_imps2) ) { - if (write(fd, &reset, sizeof (reset)) == sizeof (reset) ) { - retval = 1; - } - } - - /* Get rid of any chatter from the above */ - FD_ZERO(&fdset); - FD_SET(fd, &fdset); - tv.tv_sec = 0; - tv.tv_usec = 0; - while ( select(fd+1, &fdset, 0, 0, &tv) > 0 ) { - char temp[32]; - read(fd, temp, sizeof(temp)); - } - - return retval; + /* If you wanted to control the mouse mode (and we do :) ) ... + Set IMPS/2 protocol: + {0xf3,200,0xf3,100,0xf3,80} + Reset mouse device: + {0xFF} + */ + Uint8 set_imps2[] = { 0xf3, 200, 0xf3, 100, 0xf3, 80 }; + Uint8 reset = 0xff; + fd_set fdset; + struct timeval tv; + int retval = 0; + + if (write(fd, &set_imps2, sizeof(set_imps2)) == sizeof(set_imps2)) { + if (write(fd, &reset, sizeof(reset)) == sizeof(reset)) { + retval = 1; + } + } + + /* Get rid of any chatter from the above */ + FD_ZERO(&fdset); + FD_SET(fd, &fdset); + tv.tv_sec = 0; + tv.tv_usec = 0; + while (select(fd + 1, &fdset, 0, 0, &tv) > 0) { + char temp[32]; + read(fd, temp, sizeof(temp)); + } + + return retval; } /* Returns true if the mouse uses the IMPS/2 protocol */ -static int detect_imps2(int fd) +static int +detect_imps2(int fd) { - int imps2; - - imps2 = 0; - - if ( SDL_getenv("SDL_MOUSEDEV_IMPS2") ) { - imps2 = 1; - } - if ( ! imps2 ) { - Uint8 query_ps2 = 0xF2; - fd_set fdset; - struct timeval tv; - - /* Get rid of any mouse motion noise */ - FD_ZERO(&fdset); - FD_SET(fd, &fdset); - tv.tv_sec = 0; - tv.tv_usec = 0; - while ( select(fd+1, &fdset, 0, 0, &tv) > 0 ) { - char temp[32]; - read(fd, temp, sizeof(temp)); - } - - /* Query for the type of mouse protocol */ - if ( write(fd, &query_ps2, sizeof (query_ps2)) == sizeof (query_ps2)) { - Uint8 ch = 0; - - /* Get the mouse protocol response */ - do { - FD_ZERO(&fdset); - FD_SET(fd, &fdset); - tv.tv_sec = 1; - tv.tv_usec = 0; - if ( select(fd+1, &fdset, 0, 0, &tv) < 1 ) { - break; - } - } while ( (read(fd, &ch, sizeof (ch)) == sizeof (ch)) && - ((ch == 0xFA) || (ch == 0xAA)) ); - - /* Experimental values (Logitech wheelmouse) */ + int imps2; + + imps2 = 0; + + if (SDL_getenv("SDL_MOUSEDEV_IMPS2")) { + imps2 = 1; + } + if (!imps2) { + Uint8 query_ps2 = 0xF2; + fd_set fdset; + struct timeval tv; + + /* Get rid of any mouse motion noise */ + FD_ZERO(&fdset); + FD_SET(fd, &fdset); + tv.tv_sec = 0; + tv.tv_usec = 0; + while (select(fd + 1, &fdset, 0, 0, &tv) > 0) { + char temp[32]; + read(fd, temp, sizeof(temp)); + } + + /* Query for the type of mouse protocol */ + if (write(fd, &query_ps2, sizeof(query_ps2)) == sizeof(query_ps2)) { + Uint8 ch = 0; + + /* Get the mouse protocol response */ + do { + FD_ZERO(&fdset); + FD_SET(fd, &fdset); + tv.tv_sec = 1; + tv.tv_usec = 0; + if (select(fd + 1, &fdset, 0, 0, &tv) < 1) { + break; + } + } + while ((read(fd, &ch, sizeof(ch)) == sizeof(ch)) && + ((ch == 0xFA) || (ch == 0xAA))); + + /* Experimental values (Logitech wheelmouse) */ #ifdef DEBUG_MOUSE -fprintf(stderr, "Last mouse mode: 0x%x\n", ch); + fprintf(stderr, "Last mouse mode: 0x%x\n", ch); #endif - if ( ch == 3 ) { - imps2 = 1; - } - } - } - return imps2; + if (ch == 3) { + imps2 = 1; + } + } + } + return imps2; } -int GS_OpenMouse(_THIS) +int +GS_OpenMouse(_THIS) { - int i; - const char *mousedev; - const char *mousedrv; - - mousedrv = SDL_getenv("SDL_MOUSEDRV"); - mousedev = SDL_getenv("SDL_MOUSEDEV"); - mouse_fd = -1; - - /* STD MICE */ - - if ( mousedev == NULL ) { - /* FIXME someday... allow multiple mice in this driver */ - char *ps2mice[] = { - "/dev/input/mice", "/dev/usbmouse", "/dev/psaux", NULL - }; - /* First try to use GPM in repeater mode */ - if ( mouse_fd < 0 ) { - if ( gpm_available() ) { - mouse_fd = open(GPM_NODE_FIFO, O_RDONLY, 0); - if ( mouse_fd >= 0 ) { + int i; + const char *mousedev; + const char *mousedrv; + + mousedrv = SDL_getenv("SDL_MOUSEDRV"); + mousedev = SDL_getenv("SDL_MOUSEDEV"); + mouse_fd = -1; + + /* STD MICE */ + + if (mousedev == NULL) { + /* FIXME someday... allow multiple mice in this driver */ + char *ps2mice[] = { + "/dev/input/mice", "/dev/usbmouse", "/dev/psaux", NULL + }; + /* First try to use GPM in repeater mode */ + if (mouse_fd < 0) { + if (gpm_available()) { + mouse_fd = open(GPM_NODE_FIFO, O_RDONLY, 0); + if (mouse_fd >= 0) { #ifdef DEBUG_MOUSE -fprintf(stderr, "Using GPM mouse\n"); + fprintf(stderr, "Using GPM mouse\n"); #endif - mouse_drv = MOUSE_GPM; - } - } - } - /* Now try to use a modern PS/2 mouse */ - for ( i=0; (mouse_fd < 0) && ps2mice[i]; ++i ) { - mouse_fd = open(ps2mice[i], O_RDWR, 0); - if (mouse_fd < 0) { - mouse_fd = open(ps2mice[i], O_RDONLY, 0); - } - if (mouse_fd >= 0) { - /* rcg06112001 Attempt to set IMPS/2 mode */ - if ( i == 0 ) { - set_imps2_mode(mouse_fd); - } - if (detect_imps2(mouse_fd)) { + mouse_drv = MOUSE_GPM; + } + } + } + /* Now try to use a modern PS/2 mouse */ + for (i = 0; (mouse_fd < 0) && ps2mice[i]; ++i) { + mouse_fd = open(ps2mice[i], O_RDWR, 0); + if (mouse_fd < 0) { + mouse_fd = open(ps2mice[i], O_RDONLY, 0); + } + if (mouse_fd >= 0) { + /* rcg06112001 Attempt to set IMPS/2 mode */ + if (i == 0) { + set_imps2_mode(mouse_fd); + } + if (detect_imps2(mouse_fd)) { #ifdef DEBUG_MOUSE -fprintf(stderr, "Using IMPS2 mouse\n"); + fprintf(stderr, "Using IMPS2 mouse\n"); #endif - mouse_drv = MOUSE_IMPS2; - } else { - mouse_drv = MOUSE_PS2; + mouse_drv = MOUSE_IMPS2; + } else { + mouse_drv = MOUSE_PS2; #ifdef DEBUG_MOUSE -fprintf(stderr, "Using PS2 mouse\n"); + fprintf(stderr, "Using PS2 mouse\n"); #endif - } - } - } - /* Next try to use a PPC ADB port mouse */ - if ( mouse_fd < 0 ) { - mouse_fd = open("/dev/adbmouse", O_RDONLY, 0); - if ( mouse_fd >= 0 ) { + } + } + } + /* Next try to use a PPC ADB port mouse */ + if (mouse_fd < 0) { + mouse_fd = open("/dev/adbmouse", O_RDONLY, 0); + if (mouse_fd >= 0) { #ifdef DEBUG_MOUSE -fprintf(stderr, "Using ADB mouse\n"); + fprintf(stderr, "Using ADB mouse\n"); #endif - mouse_drv = MOUSE_BM; - } - } - } - /* Default to a serial Microsoft mouse */ - if ( mouse_fd < 0 ) { - if ( mousedev == NULL ) { - mousedev = "/dev/mouse"; - } - mouse_fd = open(mousedev, O_RDONLY, 0); - if ( mouse_fd >= 0 ) { - struct termios mouse_termios; - - /* Set the sampling speed to 1200 baud */ - tcgetattr(mouse_fd, &mouse_termios); - mouse_termios.c_iflag = IGNBRK | IGNPAR; - mouse_termios.c_oflag = 0; - mouse_termios.c_lflag = 0; - mouse_termios.c_line = 0; - mouse_termios.c_cc[VTIME] = 0; - mouse_termios.c_cc[VMIN] = 1; - mouse_termios.c_cflag = CREAD | CLOCAL | HUPCL; - mouse_termios.c_cflag |= CS8; - mouse_termios.c_cflag |= B1200; - tcsetattr(mouse_fd, TCSAFLUSH, &mouse_termios); + mouse_drv = MOUSE_BM; + } + } + } + /* Default to a serial Microsoft mouse */ + if (mouse_fd < 0) { + if (mousedev == NULL) { + mousedev = "/dev/mouse"; + } + mouse_fd = open(mousedev, O_RDONLY, 0); + if (mouse_fd >= 0) { + struct termios mouse_termios; + + /* Set the sampling speed to 1200 baud */ + tcgetattr(mouse_fd, &mouse_termios); + mouse_termios.c_iflag = IGNBRK | IGNPAR; + mouse_termios.c_oflag = 0; + mouse_termios.c_lflag = 0; + mouse_termios.c_line = 0; + mouse_termios.c_cc[VTIME] = 0; + mouse_termios.c_cc[VMIN] = 1; + mouse_termios.c_cflag = CREAD | CLOCAL | HUPCL; + mouse_termios.c_cflag |= CS8; + mouse_termios.c_cflag |= B1200; + tcsetattr(mouse_fd, TCSAFLUSH, &mouse_termios); #ifdef DEBUG_MOUSE -fprintf(stderr, "Using Microsoft mouse on %s\n", mousedev); + fprintf(stderr, "Using Microsoft mouse on %s\n", mousedev); #endif - mouse_drv = MOUSE_MS; - } - } - if ( mouse_fd < 0 ) { - mouse_drv = MOUSE_NONE; - } - return(mouse_fd); + mouse_drv = MOUSE_MS; + } + } + if (mouse_fd < 0) { + mouse_drv = MOUSE_NONE; + } + return (mouse_fd); } static int posted = 0; -void GS_vgamousecallback(int button, int dx, int dy) +void +GS_vgamousecallback(int button, int dx, int dy) { - int button_1, button_3; - int button_state; - int state_changed; - int i; - Uint8 state; - - if ( dx || dy ) { - posted += SDL_PrivateMouseMotion(0, 1, dx, dy); - } - - /* Swap button 1 and 3 */ - button_1 = (button & 0x04) >> 2; - button_3 = (button & 0x01) << 2; - button &= ~0x05; - button |= (button_1|button_3); - - /* See what changed */ - button_state = SDL_GetMouseState(NULL, NULL); - state_changed = button_state ^ button; - for ( i=0; i<8; ++i ) { - if ( state_changed & (1<> 2; + button_3 = (button & 0x01) << 2; + button &= ~0x05; + button |= (button_1 | button_3); + + /* See what changed */ + button_state = SDL_GetMouseState(NULL, NULL); + state_changed = button_state ^ button; + for (i = 0; i < 8; ++i) { + if (state_changed & (1 << i)) { + if (button & (1 << i)) { + state = SDL_PRESSED; + } else { + state = SDL_RELEASED; + } + posted += SDL_PrivateMouseButton(state, i + 1, 0, 0); + } + } } /* For now, use GPM, PS/2, and MS protocols Driver adapted from the SVGAlib mouse driver code (taken from gpm, etc.) */ -static void handle_mouse(_THIS) +static void +handle_mouse(_THIS) { - static int start = 0; - static unsigned char mousebuf[BUFSIZ]; - int i, nread; - int button = 0; - int dx = 0, dy = 0; - int packetsize = 0; - - /* Figure out the mouse packet size */ - switch (mouse_drv) { - case MOUSE_NONE: - /* Ack! */ - read(mouse_fd, mousebuf, BUFSIZ); - return; - case MOUSE_GPM: - packetsize = 5; - break; - case MOUSE_IMPS2: - packetsize = 4; - break; - case MOUSE_PS2: - case MOUSE_MS: - case MOUSE_BM: - packetsize = 3; - break; - case NUM_MOUSE_DRVS: - /* Uh oh.. */ - packetsize = 0; - break; - } - - /* Read as many packets as possible */ - nread = read(mouse_fd, &mousebuf[start], BUFSIZ-start); - if ( nread < 0 ) { - return; - } - nread += start; + static int start = 0; + static unsigned char mousebuf[BUFSIZ]; + int i, nread; + int button = 0; + int dx = 0, dy = 0; + int packetsize = 0; + + /* Figure out the mouse packet size */ + switch (mouse_drv) { + case MOUSE_NONE: + /* Ack! */ + read(mouse_fd, mousebuf, BUFSIZ); + return; + case MOUSE_GPM: + packetsize = 5; + break; + case MOUSE_IMPS2: + packetsize = 4; + break; + case MOUSE_PS2: + case MOUSE_MS: + case MOUSE_BM: + packetsize = 3; + break; + case NUM_MOUSE_DRVS: + /* Uh oh.. */ + packetsize = 0; + break; + } + + /* Read as many packets as possible */ + nread = read(mouse_fd, &mousebuf[start], BUFSIZ - start); + if (nread < 0) { + return; + } + nread += start; #ifdef DEBUG_MOUSE - fprintf(stderr, "Read %d bytes from mouse, start = %d\n", nread, start); + fprintf(stderr, "Read %d bytes from mouse, start = %d\n", nread, start); #endif - for ( i=0; i<(nread-(packetsize-1)); i += packetsize ) { - switch (mouse_drv) { - case MOUSE_NONE: - break; - case MOUSE_GPM: - /* GPM protocol has 0x80 in high byte */ - if ( (mousebuf[i] & 0xF8) != 0x80 ) { - /* Go to next byte */ - i -= (packetsize-1); - continue; - } - /* Get current mouse state */ - button = (~mousebuf[i]) & 0x07; - dx = (signed char)(mousebuf[i+1]) + - (signed char)(mousebuf[i+3]); - dy = -((signed char)(mousebuf[i+2]) + - (signed char)(mousebuf[i+4])); - break; - case MOUSE_PS2: - /* PS/2 protocol has nothing in high byte */ - if ( (mousebuf[i] & 0xC0) != 0 ) { - /* Go to next byte */ - i -= (packetsize-1); - continue; - } - /* Get current mouse state */ - button = (mousebuf[i] & 0x04) >> 1 | /*Middle*/ - (mousebuf[i] & 0x02) >> 1 | /*Right*/ - (mousebuf[i] & 0x01) << 2; /*Left*/ - dx = (mousebuf[i] & 0x10) ? - mousebuf[i+1] - 256 : mousebuf[i+1]; - dy = (mousebuf[i] & 0x20) ? - -(mousebuf[i+2] - 256) : -mousebuf[i+2]; - break; - case MOUSE_IMPS2: - /* Get current mouse state */ - button = (mousebuf[i] & 0x04) >> 1 | /*Middle*/ - (mousebuf[i] & 0x02) >> 1 | /*Right*/ - (mousebuf[i] & 0x01) << 2 | /*Left*/ - (mousebuf[i] & 0x40) >> 3 | /* 4 */ - (mousebuf[i] & 0x80) >> 3; /* 5 */ - dx = (mousebuf[i] & 0x10) ? - mousebuf[i+1] - 256 : mousebuf[i+1]; - dy = (mousebuf[i] & 0x20) ? - -(mousebuf[i+2] - 256) : -mousebuf[i+2]; - switch (mousebuf[i+3]&0x0F) { - case 0x0E: /* DX = +1 */ - case 0x02: /* DX = -1 */ - break; - case 0x0F: /* DY = +1 (map button 4) */ - FB_vgamousecallback(button | (1<<3), - 1, 0, 0); - break; - case 0x01: /* DY = -1 (map button 5) */ - FB_vgamousecallback(button | (1<<4), - 1, 0, 0); - break; - } - break; - case MOUSE_MS: - /* Microsoft protocol has 0x40 in high byte */ - if ( (mousebuf[i] & 0x40) != 0x40 ) { - /* Go to next byte */ - i -= (packetsize-1); - continue; - } - /* Get current mouse state */ - button = ((mousebuf[i] & 0x20) >> 3) | - ((mousebuf[i] & 0x10) >> 4); - dx = (signed char)(((mousebuf[i] & 0x03) << 6) | - (mousebuf[i + 1] & 0x3F)); - dy = (signed char)(((mousebuf[i] & 0x0C) << 4) | - (mousebuf[i + 2] & 0x3F)); - break; - case MOUSE_BM: - /* BusMouse protocol has 0xF8 in high byte */ - if ( (mousebuf[i] & 0xF8) != 0x80 ) { - /* Go to next byte */ - i -= (packetsize-1); - continue; - } - /* Get current mouse state */ - button = (~mousebuf[i]) & 0x07; - dx = (signed char)mousebuf[i+1]; - dy = -(signed char)mousebuf[i+2]; - break; - case NUM_MOUSE_DRVS: - /* Uh oh.. */ - dx = 0; - dy = 0; - break; - } - GS_vgamousecallback(button, dx, dy); - } - if ( i < nread ) { - SDL_memcpy(mousebuf, &mousebuf[i], (nread-i)); - start = (nread-i); - } else { - start = 0; - } - return; + for (i = 0; i < (nread - (packetsize - 1)); i += packetsize) { + switch (mouse_drv) { + case MOUSE_NONE: + break; + case MOUSE_GPM: + /* GPM protocol has 0x80 in high byte */ + if ((mousebuf[i] & 0xF8) != 0x80) { + /* Go to next byte */ + i -= (packetsize - 1); + continue; + } + /* Get current mouse state */ + button = (~mousebuf[i]) & 0x07; + dx = (signed char) (mousebuf[i + 1]) + + (signed char) (mousebuf[i + 3]); + dy = -((signed char) (mousebuf[i + 2]) + + (signed char) (mousebuf[i + 4])); + break; + case MOUSE_PS2: + /* PS/2 protocol has nothing in high byte */ + if ((mousebuf[i] & 0xC0) != 0) { + /* Go to next byte */ + i -= (packetsize - 1); + continue; + } + /* Get current mouse state */ + button = (mousebuf[i] & 0x04) >> 1 | /*Middle */ + (mousebuf[i] & 0x02) >> 1 | /*Right */ + (mousebuf[i] & 0x01) << 2; /*Left */ + dx = (mousebuf[i] & 0x10) ? + mousebuf[i + 1] - 256 : mousebuf[i + 1]; + dy = (mousebuf[i] & 0x20) ? + -(mousebuf[i + 2] - 256) : -mousebuf[i + 2]; + break; + case MOUSE_IMPS2: + /* Get current mouse state */ + button = (mousebuf[i] & 0x04) >> 1 | /*Middle */ + (mousebuf[i] & 0x02) >> 1 | /*Right */ + (mousebuf[i] & 0x01) << 2 | /*Left */ + (mousebuf[i] & 0x40) >> 3 | /* 4 */ + (mousebuf[i] & 0x80) >> 3; /* 5 */ + dx = (mousebuf[i] & 0x10) ? + mousebuf[i + 1] - 256 : mousebuf[i + 1]; + dy = (mousebuf[i] & 0x20) ? + -(mousebuf[i + 2] - 256) : -mousebuf[i + 2]; + switch (mousebuf[i + 3] & 0x0F) { + case 0x0E: /* DX = +1 */ + case 0x02: /* DX = -1 */ + break; + case 0x0F: /* DY = +1 (map button 4) */ + FB_vgamousecallback(button | (1 << 3), 1, 0, 0); + break; + case 0x01: /* DY = -1 (map button 5) */ + FB_vgamousecallback(button | (1 << 4), 1, 0, 0); + break; + } + break; + case MOUSE_MS: + /* Microsoft protocol has 0x40 in high byte */ + if ((mousebuf[i] & 0x40) != 0x40) { + /* Go to next byte */ + i -= (packetsize - 1); + continue; + } + /* Get current mouse state */ + button = ((mousebuf[i] & 0x20) >> 3) | + ((mousebuf[i] & 0x10) >> 4); + dx = (signed char) (((mousebuf[i] & 0x03) << 6) | + (mousebuf[i + 1] & 0x3F)); + dy = (signed char) (((mousebuf[i] & 0x0C) << 4) | + (mousebuf[i + 2] & 0x3F)); + break; + case MOUSE_BM: + /* BusMouse protocol has 0xF8 in high byte */ + if ((mousebuf[i] & 0xF8) != 0x80) { + /* Go to next byte */ + i -= (packetsize - 1); + continue; + } + /* Get current mouse state */ + button = (~mousebuf[i]) & 0x07; + dx = (signed char) mousebuf[i + 1]; + dy = -(signed char) mousebuf[i + 2]; + break; + case NUM_MOUSE_DRVS: + /* Uh oh.. */ + dx = 0; + dy = 0; + break; + } + GS_vgamousecallback(button, dx, dy); + } + if (i < nread) { + SDL_memcpy(mousebuf, &mousebuf[i], (nread - i)); + start = (nread - i); + } else { + start = 0; + } + return; } -static void handle_keyboard(_THIS) +static void +handle_keyboard(_THIS) { - unsigned char keybuf[BUFSIZ]; - int i, nread; - int pressed; - int scancode; - SDL_keysym keysym; - - nread = read(keyboard_fd, keybuf, BUFSIZ); - for ( i=0; i= 0 ) { - FD_SET(keyboard_fd, &fdset); - if ( max_fd < keyboard_fd ) { - max_fd = keyboard_fd; - } - } - if ( mouse_fd >= 0 ) { - FD_SET(mouse_fd, &fdset); - if ( max_fd < mouse_fd ) { - max_fd = mouse_fd; - } - } - if ( select(max_fd+1, &fdset, NULL, NULL, &zero) > 0 ) { - if ( keyboard_fd >= 0 ) { - if ( FD_ISSET(keyboard_fd, &fdset) ) { - handle_keyboard(this); - } - } - if ( mouse_fd >= 0 ) { - if ( FD_ISSET(mouse_fd, &fdset) ) { - handle_mouse(this); - } - } - } - } while ( posted ); + fd_set fdset; + int max_fd; + static struct timeval zero; + + do { + posted = 0; + + FD_ZERO(&fdset); + max_fd = 0; + if (keyboard_fd >= 0) { + FD_SET(keyboard_fd, &fdset); + if (max_fd < keyboard_fd) { + max_fd = keyboard_fd; + } + } + if (mouse_fd >= 0) { + FD_SET(mouse_fd, &fdset); + if (max_fd < mouse_fd) { + max_fd = mouse_fd; + } + } + if (select(max_fd + 1, &fdset, NULL, NULL, &zero) > 0) { + if (keyboard_fd >= 0) { + if (FD_ISSET(keyboard_fd, &fdset)) { + handle_keyboard(this); + } + } + if (mouse_fd >= 0) { + if (FD_ISSET(mouse_fd, &fdset)) { + handle_mouse(this); + } + } + } + } + while (posted); } -void GS_InitOSKeymap(_THIS) +void +GS_InitOSKeymap(_THIS) { - int i; - - /* Initialize the Linux key translation table */ - - /* First get the ascii keys and others not well handled */ - for (i=0; iscancode = scancode; - keysym->sym = keymap[scancode]; - keysym->mod = KMOD_NONE; - - /* If UNICODE is on, get the UNICODE value for the key */ - keysym->unicode = 0; - if ( SDL_TranslateUNICODE ) { - int map; - SDLMod modstate; - - modstate = SDL_GetModState(); - map = 0; - if ( modstate & KMOD_SHIFT ) { - map |= (1<unicode=KVAL(vga_keymap[map][scancode]); - } - } else { - keysym->unicode = KVAL(vga_keymap[map][scancode]); - } - } - return(keysym); + /* Set the keysym information */ + keysym->scancode = scancode; + keysym->sym = keymap[scancode]; + keysym->mod = KMOD_NONE; + + /* If UNICODE is on, get the UNICODE value for the key */ + keysym->unicode = 0; + if (SDL_TranslateUNICODE) { + int map; + SDLMod modstate; + + modstate = SDL_GetModState(); + map = 0; + if (modstate & KMOD_SHIFT) { + map |= (1 << KG_SHIFT); + } + if (modstate & KMOD_CTRL) { + map |= (1 << KG_CTRL); + } + if (modstate & KMOD_ALT) { + map |= (1 << KG_ALT); + } + if (modstate & KMOD_MODE) { + map |= (1 << KG_ALTGR); + } + if (KTYP(vga_keymap[map][scancode]) == KT_LETTER) { + if (modstate & KMOD_CAPS) { + map ^= (1 << KG_SHIFT); + } + } + if (KTYP(vga_keymap[map][scancode]) == KT_PAD) { + if (modstate & KMOD_NUM) { + keysym->unicode = KVAL(vga_keymap[map][scancode]); + } + } else { + keysym->unicode = KVAL(vga_keymap[map][scancode]); + } + } + return (keysym); } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/ps2gs/SDL_gsevents_c.h b/src/video/ps2gs/SDL_gsevents_c.h index 515294a5d..f6129d3ea 100644 --- a/src/video/ps2gs/SDL_gsevents_c.h +++ b/src/video/ps2gs/SDL_gsevents_c.h @@ -36,3 +36,4 @@ extern void GS_LeaveGraphicsMode(_THIS); extern void GS_InitOSKeymap(_THIS); extern void GS_PumpEvents(_THIS); +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/ps2gs/SDL_gskeys.h b/src/video/ps2gs/SDL_gskeys.h index 2b01b6b2e..1f5117c32 100644 --- a/src/video/ps2gs/SDL_gskeys.h +++ b/src/video/ps2gs/SDL_gskeys.h @@ -120,20 +120,20 @@ #define SCANCODE_KEYPADDIVIDE 98 #define SCANCODE_PRINTSCREEN 99 #define SCANCODE_RIGHTALT 100 -#define SCANCODE_BREAK 101 /* Beware: is 119 */ -#define SCANCODE_BREAK_ALTERNATIVE 119 /* on some keyboards! */ +#define SCANCODE_BREAK 101 /* Beware: is 119 */ +#define SCANCODE_BREAK_ALTERNATIVE 119 /* on some keyboards! */ #define SCANCODE_HOME 102 -#define SCANCODE_CURSORBLOCKUP 103 /* Cursor key block */ +#define SCANCODE_CURSORBLOCKUP 103 /* Cursor key block */ #define SCANCODE_PAGEUP 104 -#define SCANCODE_CURSORBLOCKLEFT 105 /* Cursor key block */ -#define SCANCODE_CURSORBLOCKRIGHT 106 /* Cursor key block */ +#define SCANCODE_CURSORBLOCKLEFT 105 /* Cursor key block */ +#define SCANCODE_CURSORBLOCKRIGHT 106 /* Cursor key block */ #define SCANCODE_END 107 -#define SCANCODE_CURSORBLOCKDOWN 108 /* Cursor key block */ +#define SCANCODE_CURSORBLOCKDOWN 108 /* Cursor key block */ #define SCANCODE_PAGEDOWN 109 #define SCANCODE_INSERT 110 #define SCANCODE_REMOVE 111 #define SCANCODE_RIGHTWIN 126 #define SCANCODE_LEFTWIN 125 - +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/ps2gs/SDL_gsmouse.c b/src/video/ps2gs/SDL_gsmouse.c index 50da17911..79c6e79c4 100644 --- a/src/video/ps2gs/SDL_gsmouse.c +++ b/src/video/ps2gs/SDL_gsmouse.c @@ -31,116 +31,123 @@ /* The implementation dependent data for the window manager cursor */ -struct WMcursor { - int unused; +struct WMcursor +{ + int unused; }; /* There isn't any implementation dependent data */ -void GS_FreeWMCursor(_THIS, WMcursor *cursor) +void +GS_FreeWMCursor(_THIS, WMcursor * cursor) { - return; + return; } /* There isn't any implementation dependent data */ -WMcursor *GS_CreateWMCursor(_THIS, - Uint8 *data, Uint8 *mask, int w, int h, int hot_x, int hot_y) +WMcursor * +GS_CreateWMCursor(_THIS, + Uint8 * data, Uint8 * mask, int w, int h, int hot_x, + int hot_y) { - return((WMcursor *)0x01); + return ((WMcursor *) 0x01); } -static void GS_MoveCursor(_THIS, SDL_Cursor *cursor, int x, int y) +static void +GS_MoveCursor(_THIS, SDL_Cursor * cursor, int x, int y) { - SDL_Surface *screen; - struct ps2_image image; - SDL_Rect area; - int mouse_y1, mouse_y2; - void *saved_pixels; - int screen_updated; - - /* Lock so we don't interrupt an update with mouse motion */ - SDL_LockCursor(); - - /* Make sure any pending DMA has completed */ - if ( dma_pending ) { - ioctl(console_fd, PS2IOC_SENDQCT, 1); - dma_pending = 0; - } - - /* Remove the cursor image from the DMA area */ - screen = this->screen; - saved_pixels = screen->pixels; - screen->pixels = mapped_mem + screen->offset; - screen_updated = 0; - if ( cursor_drawn ) { - SDL_EraseCursorNoLock(screen); - cursor_drawn = 0; - screen_updated = 1; - } - - /* Save the current mouse area */ - SDL_MouseRect(&area); - mouse_y1 = area.y; - mouse_y2 = area.y+area.h; - - /* Only draw the new cursor if there was one passed in */ - if ( cursor ) { - /* Set the new location */ - cursor->area.x = (x - cursor->hot_x); - cursor->area.y = (y - cursor->hot_y); - - /* Draw the cursor at the new location */ - if ( (SDL_cursorstate & CURSOR_VISIBLE) && screen->pixels ) { - SDL_DrawCursorNoLock(screen); - cursor_drawn = 1; - screen_updated = 1; - } - } - screen->pixels = saved_pixels; - - /* Update the affected area of the screen */ - if ( screen_updated ) { - SDL_MouseRect(&area); - if ( area.y < mouse_y1 ) { - mouse_y1 = area.y; - } - if ( (area.y+area.h) > mouse_y2 ) { - mouse_y2 = area.y+area.h; - } - image = screen_image; - image.y += screen->offset / screen->pitch + mouse_y1; - image.h = mouse_y2 - mouse_y1; - image.ptr = mapped_mem + - (image.y - screen_image.y) * screen->pitch; - ioctl(console_fd, PS2IOC_LOADIMAGE, &image); - - /* Need to scale offscreen image to TV output */ - if ( image.y > 0 ) { - scaleimage_nonblock(console_fd, - tex_tags_mem, scale_tags_mem); - } - } - - /* We're finished */ - SDL_UnlockCursor(); + SDL_Surface *screen; + struct ps2_image image; + SDL_Rect area; + int mouse_y1, mouse_y2; + void *saved_pixels; + int screen_updated; + + /* Lock so we don't interrupt an update with mouse motion */ + SDL_LockCursor(); + + /* Make sure any pending DMA has completed */ + if (dma_pending) { + ioctl(console_fd, PS2IOC_SENDQCT, 1); + dma_pending = 0; + } + + /* Remove the cursor image from the DMA area */ + screen = this->screen; + saved_pixels = screen->pixels; + screen->pixels = mapped_mem + screen->offset; + screen_updated = 0; + if (cursor_drawn) { + SDL_EraseCursorNoLock(screen); + cursor_drawn = 0; + screen_updated = 1; + } + + /* Save the current mouse area */ + SDL_MouseRect(&area); + mouse_y1 = area.y; + mouse_y2 = area.y + area.h; + + /* Only draw the new cursor if there was one passed in */ + if (cursor) { + /* Set the new location */ + cursor->area.x = (x - cursor->hot_x); + cursor->area.y = (y - cursor->hot_y); + + /* Draw the cursor at the new location */ + if ((SDL_cursorstate & CURSOR_VISIBLE) && screen->pixels) { + SDL_DrawCursorNoLock(screen); + cursor_drawn = 1; + screen_updated = 1; + } + } + screen->pixels = saved_pixels; + + /* Update the affected area of the screen */ + if (screen_updated) { + SDL_MouseRect(&area); + if (area.y < mouse_y1) { + mouse_y1 = area.y; + } + if ((area.y + area.h) > mouse_y2) { + mouse_y2 = area.y + area.h; + } + image = screen_image; + image.y += screen->offset / screen->pitch + mouse_y1; + image.h = mouse_y2 - mouse_y1; + image.ptr = mapped_mem + (image.y - screen_image.y) * screen->pitch; + ioctl(console_fd, PS2IOC_LOADIMAGE, &image); + + /* Need to scale offscreen image to TV output */ + if (image.y > 0) { + scaleimage_nonblock(console_fd, tex_tags_mem, scale_tags_mem); + } + } + + /* We're finished */ + SDL_UnlockCursor(); } -void GS_MoveWMCursor(_THIS, int x, int y) +void +GS_MoveWMCursor(_THIS, int x, int y) { - GS_MoveCursor(this, SDL_cursor, x, y); + GS_MoveCursor(this, SDL_cursor, x, y); } -int GS_ShowWMCursor(_THIS, WMcursor *wmcursor) +int +GS_ShowWMCursor(_THIS, WMcursor * wmcursor) { - SDL_Cursor *cursor; - int x, y; - - /* Draw the cursor at the appropriate location */ - SDL_GetMouseState(&x, &y); - if ( wmcursor ) { - cursor = SDL_cursor; - } else { - cursor = NULL; - } - GS_MoveCursor(this, cursor, x, y); - return(1); + SDL_Cursor *cursor; + int x, y; + + /* Draw the cursor at the appropriate location */ + SDL_GetMouseState(&x, &y); + if (wmcursor) { + cursor = SDL_cursor; + } else { + cursor = NULL; + } + GS_MoveCursor(this, cursor, x, y); + return (1); } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/ps2gs/SDL_gsmouse_c.h b/src/video/ps2gs/SDL_gsmouse_c.h index 72616a4b0..048198236 100644 --- a/src/video/ps2gs/SDL_gsmouse_c.h +++ b/src/video/ps2gs/SDL_gsmouse_c.h @@ -26,12 +26,14 @@ /* This is the maximum size of the cursor sprite */ #define CURSOR_W 32 #define CURSOR_H 32 -#define CURSOR_W_POW 5 /* 32 = 2^5 */ -#define CURSOR_H_POW 5 /* 32 = 2^5 */ +#define CURSOR_W_POW 5 /* 32 = 2^5 */ +#define CURSOR_H_POW 5 /* 32 = 2^5 */ /* Functions to be exported */ -extern void GS_FreeWMCursor(_THIS, WMcursor *cursor); +extern void GS_FreeWMCursor(_THIS, WMcursor * cursor); extern WMcursor *GS_CreateWMCursor(_THIS, - Uint8 *data, Uint8 *mask, int w, int h, int hot_x, int hot_y); + Uint8 * data, Uint8 * mask, int w, int h, + int hot_x, int hot_y); extern void GS_MoveWMCursor(_THIS, int x, int y); -extern int GS_ShowWMCursor(_THIS, WMcursor *cursor); +extern int GS_ShowWMCursor(_THIS, WMcursor * cursor); +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/ps2gs/SDL_gsvideo.c b/src/video/ps2gs/SDL_gsvideo.c index 878b32abf..cef67b120 100644 --- a/src/video/ps2gs/SDL_gsvideo.c +++ b/src/video/ps2gs/SDL_gsvideo.c @@ -42,648 +42,648 @@ /* Initialization/Query functions */ -static int GS_VideoInit(_THIS, SDL_PixelFormat *vformat); -static SDL_Rect **GS_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags); -static SDL_Surface *GS_SetVideoMode(_THIS, SDL_Surface *current, int width, int height, int bpp, Uint32 flags); -static int GS_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color *colors); +static int GS_VideoInit(_THIS, SDL_PixelFormat * vformat); +static SDL_Rect **GS_ListModes(_THIS, SDL_PixelFormat * format, Uint32 flags); +static SDL_Surface *GS_SetVideoMode(_THIS, SDL_Surface * current, int width, + int height, int bpp, Uint32 flags); +static int GS_SetColors(_THIS, int firstcolor, int ncolors, + SDL_Color * colors); static void GS_VideoQuit(_THIS); /* Hardware surface functions */ -static int GS_AllocHWSurface(_THIS, SDL_Surface *surface); -static int GS_LockHWSurface(_THIS, SDL_Surface *surface); -static void GS_UnlockHWSurface(_THIS, SDL_Surface *surface); -static void GS_FreeHWSurface(_THIS, SDL_Surface *surface); +static int GS_AllocHWSurface(_THIS, SDL_Surface * surface); +static int GS_LockHWSurface(_THIS, SDL_Surface * surface); +static void GS_UnlockHWSurface(_THIS, SDL_Surface * surface); +static void GS_FreeHWSurface(_THIS, SDL_Surface * surface); /* GS driver bootstrap functions */ -static int GS_Available(void) +static int +GS_Available(void) { - int console, memory; - - console = open(PS2_DEV_GS, O_RDWR, 0); - if ( console >= 0 ) { - close(console); - } - memory = open(PS2_DEV_MEM, O_RDWR, 0); - if ( memory >= 0 ) { - close(memory); - } - return((console >= 0) && (memory >= 0)); + int console, memory; + + console = open(PS2_DEV_GS, O_RDWR, 0); + if (console >= 0) { + close(console); + } + memory = open(PS2_DEV_MEM, O_RDWR, 0); + if (memory >= 0) { + close(memory); + } + return ((console >= 0) && (memory >= 0)); } -static void GS_DeleteDevice(SDL_VideoDevice *device) +static void +GS_DeleteDevice(SDL_VideoDevice * device) { - SDL_free(device->hidden); - SDL_free(device); + SDL_free(device->hidden); + SDL_free(device); } -static SDL_VideoDevice *GS_CreateDevice(int devindex) +static SDL_VideoDevice * +GS_CreateDevice(int devindex) { - SDL_VideoDevice *this; - - /* Initialize all variables that we clean on shutdown */ - this = (SDL_VideoDevice *)SDL_malloc(sizeof(SDL_VideoDevice)); - if ( this ) { - SDL_memset(this, 0, (sizeof *this)); - this->hidden = (struct SDL_PrivateVideoData *) - SDL_malloc((sizeof *this->hidden)); - } - if ( (this == NULL) || (this->hidden == NULL) ) { - SDL_OutOfMemory(); - if ( this ) { - SDL_free(this); - } - return(0); - } - SDL_memset(this->hidden, 0, (sizeof *this->hidden)); - mouse_fd = -1; - keyboard_fd = -1; - - /* Set the function pointers */ - this->VideoInit = GS_VideoInit; - this->ListModes = GS_ListModes; - this->SetVideoMode = GS_SetVideoMode; - this->CreateYUVOverlay = GS_CreateYUVOverlay; - this->SetColors = GS_SetColors; - this->UpdateRects = NULL; - this->VideoQuit = GS_VideoQuit; - this->AllocHWSurface = GS_AllocHWSurface; - this->CheckHWBlit = NULL; - this->FillHWRect = NULL; - this->SetHWColorKey = NULL; - this->SetHWAlpha = NULL; - this->LockHWSurface = GS_LockHWSurface; - this->UnlockHWSurface = GS_UnlockHWSurface; - this->FlipHWSurface = NULL; - this->FreeHWSurface = GS_FreeHWSurface; - this->SetIcon = NULL; - this->SetCaption = NULL; - this->GetWMInfo = NULL; - this->FreeWMCursor = GS_FreeWMCursor; - this->CreateWMCursor = GS_CreateWMCursor; - this->ShowWMCursor = GS_ShowWMCursor; - this->MoveWMCursor = GS_MoveWMCursor; - this->InitOSKeymap = GS_InitOSKeymap; - this->PumpEvents = GS_PumpEvents; - - this->free = GS_DeleteDevice; - - return this; + SDL_VideoDevice *this; + + /* Initialize all variables that we clean on shutdown */ + this = (SDL_VideoDevice *) SDL_malloc(sizeof(SDL_VideoDevice)); + if (this) { + SDL_memset(this, 0, (sizeof *this)); + this->hidden = (struct SDL_PrivateVideoData *) + SDL_malloc((sizeof *this->hidden)); + } + if ((this == NULL) || (this->hidden == NULL)) { + SDL_OutOfMemory(); + if (this) { + SDL_free(this); + } + return (0); + } + SDL_memset(this->hidden, 0, (sizeof *this->hidden)); + mouse_fd = -1; + keyboard_fd = -1; + + /* Set the function pointers */ + this->VideoInit = GS_VideoInit; + this->ListModes = GS_ListModes; + this->SetVideoMode = GS_SetVideoMode; + this->CreateYUVOverlay = GS_CreateYUVOverlay; + this->SetColors = GS_SetColors; + this->UpdateRects = NULL; + this->VideoQuit = GS_VideoQuit; + this->AllocHWSurface = GS_AllocHWSurface; + this->CheckHWBlit = NULL; + this->FillHWRect = NULL; + this->SetHWColorKey = NULL; + this->SetHWAlpha = NULL; + this->LockHWSurface = GS_LockHWSurface; + this->UnlockHWSurface = GS_UnlockHWSurface; + this->FlipHWSurface = NULL; + this->FreeHWSurface = GS_FreeHWSurface; + this->SetIcon = NULL; + this->SetCaption = NULL; + this->GetWMInfo = NULL; + this->FreeWMCursor = GS_FreeWMCursor; + this->CreateWMCursor = GS_CreateWMCursor; + this->ShowWMCursor = GS_ShowWMCursor; + this->MoveWMCursor = GS_MoveWMCursor; + this->InitOSKeymap = GS_InitOSKeymap; + this->PumpEvents = GS_PumpEvents; + + this->free = GS_DeleteDevice; + + return this; } VideoBootStrap PS2GS_bootstrap = { - "ps2gs", "PlayStation 2 Graphics Synthesizer", - GS_Available, GS_CreateDevice + "ps2gs", "PlayStation 2 Graphics Synthesizer", + GS_Available, GS_CreateDevice }; /* These are the pixel formats for the 32, 24, and 16 bit video modes */ -static struct { - int bpp; - Uint32 r; - Uint32 g; - Uint32 b; +static struct +{ + int bpp; + Uint32 r; + Uint32 g; + Uint32 b; } GS_pixelmasks[] = { - { 32, 0x000000FF, /* RGB little-endian */ - 0x0000FF00, - 0x00FF0000 }, - { 24, 0x000000FF, /* RGB little-endian */ - 0x0000FF00, - 0x00FF0000 }, - { 16, 0x0000001f, /* RGB little-endian */ - 0x000003e0, - 0x00007c00 }, -}; + { + 32, 0x000000FF, /* RGB little-endian */ + 0x0000FF00, 0x00FF0000}, { + 24, 0x000000FF, /* RGB little-endian */ + 0x0000FF00, 0x00FF0000}, { + 16, 0x0000001f, /* RGB little-endian */ +0x000003e0, 0x00007c00},}; + /* This is a mapping from SDL bytes-per-pixel to GS pixel format */ static int GS_formatmap[] = { - -1, /* 0 bpp, not a legal value */ - -1, /* 8 bpp, not supported (yet?) */ - PS2_GS_PSMCT16, /* 16 bpp */ - PS2_GS_PSMCT24, /* 24 bpp */ - PS2_GS_PSMCT32 /* 32 bpp */ + -1, /* 0 bpp, not a legal value */ + -1, /* 8 bpp, not supported (yet?) */ + PS2_GS_PSMCT16, /* 16 bpp */ + PS2_GS_PSMCT24, /* 24 bpp */ + PS2_GS_PSMCT32 /* 32 bpp */ }; -static unsigned long long head_tags[] __attribute__((aligned(16))) = { - 4 | (1LL << 60), /* GIFtag */ - 0x0e, /* A+D */ - 0, /* 2 */ - PS2_GS_BITBLTBUF, - 0, /* 4 */ - PS2_GS_TRXPOS, - 0, /* 6 */ - PS2_GS_TRXREG, - 0, /* 8 */ - PS2_GS_TRXDIR -}; +static unsigned long long head_tags[] __attribute__ ((aligned(16))) = { + 4 | (1LL << 60), /* GIFtag */ + 0x0e, /* A+D */ + 0, /* 2 */ + PS2_GS_BITBLTBUF, 0, /* 4 */ + PS2_GS_TRXPOS, 0, /* 6 */ + PS2_GS_TRXREG, 0, /* 8 */ +PS2_GS_TRXDIR}; #define MAXIMG (32767 * 16) #define MAXTAGS 8 -static inline int loadimage_nonblock(int fd, struct ps2_image *image, int size, - unsigned long long *hm, - unsigned long long *im) +static inline int +loadimage_nonblock(int fd, struct ps2_image *image, int size, + unsigned long long *hm, unsigned long long *im) { - struct ps2_plist plist; - struct ps2_packet packet[1 + MAXTAGS * 2]; - int isize; - int pnum, it, eop; - char *data; - - /* initialize the variables */ - data = (char *)image->ptr; - pnum = it = eop = 0; - plist.packet = packet; - - /* make BITBLT packet */ - packet[pnum].ptr = hm; - packet[pnum].len = sizeof(head_tags); - pnum++; - hm[2] = ((unsigned long long)image->fbp << 32) | - ((unsigned long long)image->fbw << 48) | - ((unsigned long long)image->psm << 56); - hm[4] = ((unsigned long long)image->x << 32) | - ((unsigned long long)image->y << 48); - hm[6] = (unsigned long long)image->w | - ((unsigned long long)image->h << 32); - - /* make image mode tags */ - while (!eop) { - isize = size > MAXIMG ? MAXIMG : size; - size -= isize; - eop = (size == 0); - - packet[pnum].ptr = &im[it]; - packet[pnum].len = sizeof(unsigned long long) * 2; - pnum++; - im[it++] = (isize >> 4) | (eop ? (1 << 15) : 0) | (2LL << 58); - im[it++] = 0; - - packet[pnum].ptr = (void *)data; - packet[pnum].len = isize; - pnum++; - data += isize; - } - plist.num = pnum; - - return ioctl(fd, PS2IOC_SENDL, &plist); + struct ps2_plist plist; + struct ps2_packet packet[1 + MAXTAGS * 2]; + int isize; + int pnum, it, eop; + char *data; + + /* initialize the variables */ + data = (char *) image->ptr; + pnum = it = eop = 0; + plist.packet = packet; + + /* make BITBLT packet */ + packet[pnum].ptr = hm; + packet[pnum].len = sizeof(head_tags); + pnum++; + hm[2] = ((unsigned long long) image->fbp << 32) | + ((unsigned long long) image->fbw << 48) | + ((unsigned long long) image->psm << 56); + hm[4] = ((unsigned long long) image->x << 32) | + ((unsigned long long) image->y << 48); + hm[6] = (unsigned long long) image->w | + ((unsigned long long) image->h << 32); + + /* make image mode tags */ + while (!eop) { + isize = size > MAXIMG ? MAXIMG : size; + size -= isize; + eop = (size == 0); + + packet[pnum].ptr = &im[it]; + packet[pnum].len = sizeof(unsigned long long) * 2; + pnum++; + im[it++] = (isize >> 4) | (eop ? (1 << 15) : 0) | (2LL << 58); + im[it++] = 0; + + packet[pnum].ptr = (void *) data; + packet[pnum].len = isize; + pnum++; + data += isize; + } + plist.num = pnum; + + return ioctl(fd, PS2IOC_SENDL, &plist); } -static unsigned long long tex_tags[] __attribute__((aligned(16))) = { - 3 | (1LL << 60), /* GIFtag */ - 0x0e, /* A+D */ - 0, /* 2 */ - PS2_GS_TEX0_1, - (1 << 5) + (1 << 6), - PS2_GS_TEX1_1, - 0, - PS2_GS_TEXFLUSH -}; -static unsigned long long scale_tags[] __attribute__((aligned(16))) = { - 5 | (1LL << 60), /* GIFtag */ - 0x0e, /* A+D */ - 6 + (1 << 4) + (1 << 8), - PS2_GS_PRIM, - ((unsigned long long)0 * 16) + (((unsigned long long)0 * 16) << 16), - PS2_GS_UV, - ((unsigned long long)0 * 16) + (((unsigned long long)0 * 16) << 16), - PS2_GS_XYZ2, - 0, /* 8 */ - PS2_GS_UV, - 0, /* 10 */ - PS2_GS_XYZ2 -}; - - -int scaleimage_nonblock(int fd, unsigned long long *tm, unsigned long long *sm) +static unsigned long long tex_tags[] __attribute__ ((aligned(16))) = { + 3 | (1LL << 60), /* GIFtag */ + 0x0e, /* A+D */ + 0, /* 2 */ +PS2_GS_TEX0_1, (1 << 5) + (1 << 6), PS2_GS_TEX1_1, 0, PS2_GS_TEXFLUSH}; +static unsigned long long scale_tags[] __attribute__ ((aligned(16))) = { + 5 | (1LL << 60), /* GIFtag */ + 0x0e, /* A+D */ + 6 + (1 << 4) + (1 << 8), PS2_GS_PRIM, ((unsigned long long) 0 * 16) + (((unsigned long long) 0 * 16) << 16), PS2_GS_UV, ((unsigned long long) 0 * 16) + (((unsigned long long) 0 * 16) << 16), PS2_GS_XYZ2, 0, /* 8 */ + PS2_GS_UV, 0, /* 10 */ +PS2_GS_XYZ2}; + + +int +scaleimage_nonblock(int fd, unsigned long long *tm, unsigned long long *sm) { - struct ps2_plist plist; - struct ps2_packet packet[2]; + struct ps2_plist plist; + struct ps2_packet packet[2]; - /* initialize the variables */ - plist.num = 2; - plist.packet = packet; + /* initialize the variables */ + plist.num = 2; + plist.packet = packet; - packet[0].ptr = tm; - packet[0].len = sizeof(tex_tags); - packet[1].ptr = sm; - packet[1].len = sizeof(scale_tags); + packet[0].ptr = tm; + packet[0].len = sizeof(tex_tags); + packet[1].ptr = sm; + packet[1].len = sizeof(scale_tags); - return ioctl(fd, PS2IOC_SENDL, &plist); + return ioctl(fd, PS2IOC_SENDL, &plist); } -static int power_of_2(int value) +static int +power_of_2(int value) { - int shift; + int shift; - for ( shift = 0; (1<info.current_w = vinfo.w; - this->info.current_h = vinfo.h; - - /* Determine the current screen depth */ - switch (vinfo.psm) { - /* Supported pixel formats */ - case PS2_GS_PSMCT32: - case PS2_GS_PSMCT24: - case PS2_GS_PSMCT16: - break; - default: - GS_VideoQuit(this); - SDL_SetError("Unknown console pixel format: %d", vinfo.psm); - return(-1); - } - vformat->BitsPerPixel = GS_pixelmasks[vinfo.psm].bpp; - vformat->Rmask = GS_pixelmasks[vinfo.psm].r; - vformat->Gmask = GS_pixelmasks[vinfo.psm].g; - vformat->Bmask = GS_pixelmasks[vinfo.psm].b; - saved_vinfo = vinfo; - - /* Enable mouse and keyboard support */ - if ( GS_OpenKeyboard(this) < 0 ) { - GS_VideoQuit(this); - SDL_SetError("Unable to open keyboard"); - return(-1); - } - if ( GS_OpenMouse(this) < 0 ) { - const char *sdl_nomouse; - - sdl_nomouse = SDL_getenv("SDL_NOMOUSE"); - if ( ! sdl_nomouse ) { - GS_VideoQuit(this); - SDL_SetError("Unable to open mouse"); - return(-1); - } - } - - /* We're done! */ - return(0); + struct ps2_screeninfo vinfo; + + /* Initialize the library */ + console_fd = open(PS2_DEV_GS, O_RDWR, 0); + if (console_fd < 0) { + SDL_SetError("Unable to open %s", PS2_DEV_GS); + return (-1); + } + memory_fd = open(PS2_DEV_MEM, O_RDWR, 0); + if (memory_fd < 0) { + close(console_fd); + console_fd = -1; + SDL_SetError("Unable to open %s", PS2_DEV_MEM); + return (-1); + } + + if (ioctl(console_fd, PS2IOC_GSCREENINFO, &vinfo) < 0) { + close(memory_fd); + close(console_fd); + console_fd = -1; + SDL_SetError("Couldn't get console pixel format"); + return (-1); + } + + /* Determine the current screen size */ + this->info.current_w = vinfo.w; + this->info.current_h = vinfo.h; + + /* Determine the current screen depth */ + switch (vinfo.psm) { + /* Supported pixel formats */ + case PS2_GS_PSMCT32: + case PS2_GS_PSMCT24: + case PS2_GS_PSMCT16: + break; + default: + GS_VideoQuit(this); + SDL_SetError("Unknown console pixel format: %d", vinfo.psm); + return (-1); + } + vformat->BitsPerPixel = GS_pixelmasks[vinfo.psm].bpp; + vformat->Rmask = GS_pixelmasks[vinfo.psm].r; + vformat->Gmask = GS_pixelmasks[vinfo.psm].g; + vformat->Bmask = GS_pixelmasks[vinfo.psm].b; + saved_vinfo = vinfo; + + /* Enable mouse and keyboard support */ + if (GS_OpenKeyboard(this) < 0) { + GS_VideoQuit(this); + SDL_SetError("Unable to open keyboard"); + return (-1); + } + if (GS_OpenMouse(this) < 0) { + const char *sdl_nomouse; + + sdl_nomouse = SDL_getenv("SDL_NOMOUSE"); + if (!sdl_nomouse) { + GS_VideoQuit(this); + SDL_SetError("Unable to open mouse"); + return (-1); + } + } + + /* We're done! */ + return (0); } -static SDL_Rect **GS_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags) +static SDL_Rect ** +GS_ListModes(_THIS, SDL_PixelFormat * format, Uint32 flags) { - static SDL_Rect GS_vesa_mode_list[] = { - { 0, 0, 1280, 1024 }, - { 0, 0, 1024, 768 }, - { 0, 0, 800, 600 }, - { 0, 0, 640, 480 } - }; - static SDL_Rect *GS_vesa_modes[] = { - &GS_vesa_mode_list[0], - &GS_vesa_mode_list[1], - &GS_vesa_mode_list[2], - &GS_vesa_mode_list[3], - NULL - }; - static SDL_Rect GS_tvout_stretch; - static SDL_Rect GS_tvout_mode; - static SDL_Rect *GS_tvout_modes[3]; - SDL_Rect **modes = NULL; - - switch (format->BitsPerPixel) { - case 16: - case 24: - case 32: - if ( saved_vinfo.mode == PS2_GS_VESA ) { - modes = GS_vesa_modes; - } else { - int i, j = 0; + static SDL_Rect GS_vesa_mode_list[] = { + {0, 0, 1280, 1024}, + {0, 0, 1024, 768}, + {0, 0, 800, 600}, + {0, 0, 640, 480} + }; + static SDL_Rect *GS_vesa_modes[] = { + &GS_vesa_mode_list[0], + &GS_vesa_mode_list[1], + &GS_vesa_mode_list[2], + &GS_vesa_mode_list[3], + NULL + }; + static SDL_Rect GS_tvout_stretch; + static SDL_Rect GS_tvout_mode; + static SDL_Rect *GS_tvout_modes[3]; + SDL_Rect **modes = NULL; + + switch (format->BitsPerPixel) { + case 16: + case 24: + case 32: + if (saved_vinfo.mode == PS2_GS_VESA) { + modes = GS_vesa_modes; + } else { + int i, j = 0; // FIXME - what's wrong with the stretch code at 16 bpp? -if ( format->BitsPerPixel != 32 ) break; - /* Add a mode that we could possibly stretch to */ - for ( i=0; GS_vesa_modes[i]; ++i ) { - if ( (GS_vesa_modes[i]->w == saved_vinfo.w) && - (GS_vesa_modes[i]->h != saved_vinfo.h) ) { - GS_tvout_stretch.w=GS_vesa_modes[i]->w; - GS_tvout_stretch.h=GS_vesa_modes[i]->h; - GS_tvout_modes[j++] = &GS_tvout_stretch; - break; - } - } - /* Add the current TV video mode */ - GS_tvout_mode.w = saved_vinfo.w; - GS_tvout_mode.h = saved_vinfo.h; - GS_tvout_modes[j++] = &GS_tvout_mode; - GS_tvout_modes[j++] = NULL; - - /* Return the created list of modes */ - modes = GS_tvout_modes; - } - break; - default: - break; - } - return(modes); + if (format->BitsPerPixel != 32) + break; + /* Add a mode that we could possibly stretch to */ + for (i = 0; GS_vesa_modes[i]; ++i) { + if ((GS_vesa_modes[i]->w == saved_vinfo.w) && + (GS_vesa_modes[i]->h != saved_vinfo.h)) { + GS_tvout_stretch.w = GS_vesa_modes[i]->w; + GS_tvout_stretch.h = GS_vesa_modes[i]->h; + GS_tvout_modes[j++] = &GS_tvout_stretch; + break; + } + } + /* Add the current TV video mode */ + GS_tvout_mode.w = saved_vinfo.w; + GS_tvout_mode.h = saved_vinfo.h; + GS_tvout_modes[j++] = &GS_tvout_mode; + GS_tvout_modes[j++] = NULL; + + /* Return the created list of modes */ + modes = GS_tvout_modes; + } + break; + default: + break; + } + return (modes); } /* Various screen update functions available */ -static void GS_DMAFullUpdate(_THIS, int numrects, SDL_Rect *rects); +static void GS_DMAFullUpdate(_THIS, int numrects, SDL_Rect * rects); -static SDL_Surface *GS_SetVideoMode(_THIS, SDL_Surface *current, - int width, int height, int bpp, Uint32 flags) +static SDL_Surface * +GS_SetVideoMode(_THIS, SDL_Surface * current, + int width, int height, int bpp, Uint32 flags) { - struct ps2_screeninfo vinfo; - - /* Set the terminal into graphics mode */ - if ( GS_EnterGraphicsMode(this) < 0 ) { - return(NULL); - } - - /* Set the video mode and get the final screen format */ - if ( ioctl(console_fd, PS2IOC_GSCREENINFO, &vinfo) < 0 ) { - SDL_SetError("Couldn't get console screen info"); - return(NULL); - } - if ( (vinfo.w != width) || (vinfo.h != height) || - (GS_pixelmasks[vinfo.psm].bpp != bpp) ) { - /* If we're not in VESA mode, we have to scale resolution */ - if ( saved_vinfo.mode == PS2_GS_VESA ) { - switch (width) { - case 640: - vinfo.res = PS2_GS_640x480; - break; - case 800: - vinfo.res = PS2_GS_800x600; - break; - case 1024: - vinfo.res = PS2_GS_1024x768; - break; - case 1280: - vinfo.res = PS2_GS_1280x1024; - break; - default: - SDL_SetError("Unsupported resolution: %dx%d\n", - width, height); - return(NULL); - } - vinfo.res |= (PS2_GS_75Hz << 8); - vinfo.w = width; - vinfo.h = height; - } - vinfo.fbp = 0; - vinfo.psm = GS_formatmap[bpp/8]; - if ( vinfo.psm < 0 ) { - SDL_SetError("Unsupported depth: %d bpp\n", bpp); - return(NULL); - } - if ( ioctl(console_fd, PS2IOC_SSCREENINFO, &vinfo) < 0 ) { - SDL_SetError("Couldn't set console screen info"); - return(NULL); - } - - /* Unmap the previous DMA buffer */ - if ( mapped_mem ) { - munmap(mapped_mem, mapped_len); - mapped_mem = NULL; - } - } - if ( ! SDL_ReallocFormat(current, GS_pixelmasks[vinfo.psm].bpp, - GS_pixelmasks[vinfo.psm].r, - GS_pixelmasks[vinfo.psm].g, - GS_pixelmasks[vinfo.psm].b, 0) ) { - return(NULL); - } - - /* Set up the new mode framebuffer */ - current->flags = SDL_FULLSCREEN; - current->w = width; - current->h = height; - current->pitch = SDL_CalculatePitch(current); - - /* Memory map the DMA area for block memory transfer */ - if ( ! mapped_mem ) { - pixels_len = height * current->pitch; - mapped_len = pixels_len + - /* Screen update DMA command area */ - sizeof(head_tags) + ((2 * MAXTAGS) * 16); - if ( saved_vinfo.mode != PS2_GS_VESA ) { - mapped_len += sizeof(tex_tags) + sizeof(scale_tags); - } - mapped_mem = mmap(0, mapped_len, PROT_READ|PROT_WRITE, - MAP_SHARED, memory_fd, 0); - if ( mapped_mem == MAP_FAILED ) { - SDL_SetError("Unable to map %d bytes for DMA", - mapped_len); - mapped_mem = NULL; - return(NULL); - } - - /* Set up the entire screen for DMA transfer */ - screen_image.ptr = mapped_mem; - screen_image.fbp = 0; - screen_image.fbw = (vinfo.w + 63) / 64; - screen_image.psm = vinfo.psm; - screen_image.x = 0; - if ( vinfo.h == height ) { - screen_image.y = 0; - } else { - /* Put image offscreen and scale to screen height */ - screen_image.y = vinfo.h; - } - screen_image.w = current->w; - screen_image.h = current->h; - - /* get screen image data size (qword aligned) */ - screen_image_size = (screen_image.w * screen_image.h); - switch (screen_image.psm) { - case PS2_GS_PSMCT32: - screen_image_size *= 4; - break; - case PS2_GS_PSMCT24: - screen_image_size *= 3; - break; - case PS2_GS_PSMCT16: - screen_image_size *= 2; - break; - } - screen_image_size = (screen_image_size + 15) & ~15; - - /* Set up the memory for screen update DMA commands */ - head_tags_mem = (unsigned long long *) - (mapped_mem + pixels_len); - image_tags_mem = (unsigned long long *) - ((caddr_t)head_tags_mem + sizeof(head_tags)); - SDL_memcpy(head_tags_mem, head_tags, sizeof(head_tags)); - if ( saved_vinfo.mode != PS2_GS_VESA ) { - tex_tags_mem = (unsigned long long *) - ((caddr_t)image_tags_mem + ((2*MAXTAGS)*16)); - scale_tags_mem = (unsigned long long *) - ((caddr_t)tex_tags_mem + sizeof(tex_tags)); - SDL_memcpy(tex_tags_mem, tex_tags, sizeof(tex_tags)); - tex_tags_mem[2] = - (vinfo.h * vinfo.w) / 64 + - ((unsigned long long)screen_image.fbw << 14) + - ((unsigned long long)screen_image.psm << 20) + - ((unsigned long long)power_of_2(screen_image.w) << 26) + - ((unsigned long long)power_of_2(screen_image.h) << 30) + - ((unsigned long long)1 << 34) + - ((unsigned long long)1 << 35); - SDL_memcpy(scale_tags_mem, scale_tags, sizeof(scale_tags)); - scale_tags_mem[8] = - ((unsigned long long)screen_image.w * 16) + - (((unsigned long long)screen_image.h * 16) << 16); - scale_tags_mem[10] = - ((unsigned long long)vinfo.w * 16) + - (((unsigned long long)vinfo.h * 16) << 16); - } - } - current->pixels = NULL; - if ( SDL_getenv("SDL_FULLSCREEN_UPDATE") ) { - /* Correct semantics */ - current->flags |= SDL_ASYNCBLIT; - } else { - /* We lie here - the screen memory isn't really the visible - display memory and still requires an update, but this - has the desired effect for most applications. - */ - current->flags |= SDL_HWSURFACE; - } - - /* Set the update rectangle function */ - this->UpdateRects = GS_DMAFullUpdate; - - /* We're done */ - return(current); + struct ps2_screeninfo vinfo; + + /* Set the terminal into graphics mode */ + if (GS_EnterGraphicsMode(this) < 0) { + return (NULL); + } + + /* Set the video mode and get the final screen format */ + if (ioctl(console_fd, PS2IOC_GSCREENINFO, &vinfo) < 0) { + SDL_SetError("Couldn't get console screen info"); + return (NULL); + } + if ((vinfo.w != width) || (vinfo.h != height) || + (GS_pixelmasks[vinfo.psm].bpp != bpp)) { + /* If we're not in VESA mode, we have to scale resolution */ + if (saved_vinfo.mode == PS2_GS_VESA) { + switch (width) { + case 640: + vinfo.res = PS2_GS_640x480; + break; + case 800: + vinfo.res = PS2_GS_800x600; + break; + case 1024: + vinfo.res = PS2_GS_1024x768; + break; + case 1280: + vinfo.res = PS2_GS_1280x1024; + break; + default: + SDL_SetError("Unsupported resolution: %dx%d\n", + width, height); + return (NULL); + } + vinfo.res |= (PS2_GS_75Hz << 8); + vinfo.w = width; + vinfo.h = height; + } + vinfo.fbp = 0; + vinfo.psm = GS_formatmap[bpp / 8]; + if (vinfo.psm < 0) { + SDL_SetError("Unsupported depth: %d bpp\n", bpp); + return (NULL); + } + if (ioctl(console_fd, PS2IOC_SSCREENINFO, &vinfo) < 0) { + SDL_SetError("Couldn't set console screen info"); + return (NULL); + } + + /* Unmap the previous DMA buffer */ + if (mapped_mem) { + munmap(mapped_mem, mapped_len); + mapped_mem = NULL; + } + } + if (!SDL_ReallocFormat(current, GS_pixelmasks[vinfo.psm].bpp, + GS_pixelmasks[vinfo.psm].r, + GS_pixelmasks[vinfo.psm].g, + GS_pixelmasks[vinfo.psm].b, 0)) { + return (NULL); + } + + /* Set up the new mode framebuffer */ + current->flags = SDL_FULLSCREEN; + current->w = width; + current->h = height; + current->pitch = SDL_CalculatePitch(current); + + /* Memory map the DMA area for block memory transfer */ + if (!mapped_mem) { + pixels_len = height * current->pitch; + mapped_len = pixels_len + + /* Screen update DMA command area */ + sizeof(head_tags) + ((2 * MAXTAGS) * 16); + if (saved_vinfo.mode != PS2_GS_VESA) { + mapped_len += sizeof(tex_tags) + sizeof(scale_tags); + } + mapped_mem = mmap(0, mapped_len, PROT_READ | PROT_WRITE, + MAP_SHARED, memory_fd, 0); + if (mapped_mem == MAP_FAILED) { + SDL_SetError("Unable to map %d bytes for DMA", mapped_len); + mapped_mem = NULL; + return (NULL); + } + + /* Set up the entire screen for DMA transfer */ + screen_image.ptr = mapped_mem; + screen_image.fbp = 0; + screen_image.fbw = (vinfo.w + 63) / 64; + screen_image.psm = vinfo.psm; + screen_image.x = 0; + if (vinfo.h == height) { + screen_image.y = 0; + } else { + /* Put image offscreen and scale to screen height */ + screen_image.y = vinfo.h; + } + screen_image.w = current->w; + screen_image.h = current->h; + + /* get screen image data size (qword aligned) */ + screen_image_size = (screen_image.w * screen_image.h); + switch (screen_image.psm) { + case PS2_GS_PSMCT32: + screen_image_size *= 4; + break; + case PS2_GS_PSMCT24: + screen_image_size *= 3; + break; + case PS2_GS_PSMCT16: + screen_image_size *= 2; + break; + } + screen_image_size = (screen_image_size + 15) & ~15; + + /* Set up the memory for screen update DMA commands */ + head_tags_mem = (unsigned long long *) (mapped_mem + pixels_len); + image_tags_mem = (unsigned long long *) + ((caddr_t) head_tags_mem + sizeof(head_tags)); + SDL_memcpy(head_tags_mem, head_tags, sizeof(head_tags)); + if (saved_vinfo.mode != PS2_GS_VESA) { + tex_tags_mem = (unsigned long long *) + ((caddr_t) image_tags_mem + ((2 * MAXTAGS) * 16)); + scale_tags_mem = (unsigned long long *) + ((caddr_t) tex_tags_mem + sizeof(tex_tags)); + SDL_memcpy(tex_tags_mem, tex_tags, sizeof(tex_tags)); + tex_tags_mem[2] = + (vinfo.h * vinfo.w) / 64 + + ((unsigned long long) screen_image.fbw << 14) + + ((unsigned long long) screen_image.psm << 20) + + ((unsigned long long) power_of_2(screen_image.w) << 26) + + ((unsigned long long) power_of_2(screen_image.h) << 30) + + ((unsigned long long) 1 << 34) + + ((unsigned long long) 1 << 35); + SDL_memcpy(scale_tags_mem, scale_tags, sizeof(scale_tags)); + scale_tags_mem[8] = + ((unsigned long long) screen_image.w * 16) + + (((unsigned long long) screen_image.h * 16) << 16); + scale_tags_mem[10] = + ((unsigned long long) vinfo.w * 16) + + (((unsigned long long) vinfo.h * 16) << 16); + } + } + current->pixels = NULL; + if (SDL_getenv("SDL_FULLSCREEN_UPDATE")) { + /* Correct semantics */ + current->flags |= SDL_ASYNCBLIT; + } else { + /* We lie here - the screen memory isn't really the visible + display memory and still requires an update, but this + has the desired effect for most applications. + */ + current->flags |= SDL_HWSURFACE; + } + + /* Set the update rectangle function */ + this->UpdateRects = GS_DMAFullUpdate; + + /* We're done */ + return (current); } /* We don't support hardware surfaces yet */ -static int GS_AllocHWSurface(_THIS, SDL_Surface *surface) +static int +GS_AllocHWSurface(_THIS, SDL_Surface * surface) { - return(-1); + return (-1); } -static void GS_FreeHWSurface(_THIS, SDL_Surface *surface) +static void +GS_FreeHWSurface(_THIS, SDL_Surface * surface) { - return; + return; } -static int GS_LockHWSurface(_THIS, SDL_Surface *surface) +static int +GS_LockHWSurface(_THIS, SDL_Surface * surface) { - if ( surface == this->screen ) { - /* Since mouse motion affects 'pixels', lock it */ - SDL_LockCursor(); - - /* Make sure any pending DMA has completed */ - if ( dma_pending ) { - ioctl(console_fd, PS2IOC_SENDQCT, 1); - dma_pending = 0; - } - - /* If the cursor is drawn on the DMA area, remove it */ - if ( cursor_drawn ) { - surface->pixels = mapped_mem + surface->offset; - SDL_EraseCursorNoLock(this->screen); - cursor_drawn = 0; - } - - /* Set the surface pixels to the base of the DMA area */ - surface->pixels = mapped_mem; - - /* We're finished! */ - SDL_UnlockCursor(); - } - return(0); + if (surface == this->screen) { + /* Since mouse motion affects 'pixels', lock it */ + SDL_LockCursor(); + + /* Make sure any pending DMA has completed */ + if (dma_pending) { + ioctl(console_fd, PS2IOC_SENDQCT, 1); + dma_pending = 0; + } + + /* If the cursor is drawn on the DMA area, remove it */ + if (cursor_drawn) { + surface->pixels = mapped_mem + surface->offset; + SDL_EraseCursorNoLock(this->screen); + cursor_drawn = 0; + } + + /* Set the surface pixels to the base of the DMA area */ + surface->pixels = mapped_mem; + + /* We're finished! */ + SDL_UnlockCursor(); + } + return (0); } -static void GS_UnlockHWSurface(_THIS, SDL_Surface *surface) +static void +GS_UnlockHWSurface(_THIS, SDL_Surface * surface) { - if ( surface == this->screen ) { - /* Since mouse motion affects 'pixels', lock it */ - SDL_LockCursor(); - surface->pixels = NULL; - SDL_UnlockCursor(); - } + if (surface == this->screen) { + /* Since mouse motion affects 'pixels', lock it */ + SDL_LockCursor(); + surface->pixels = NULL; + SDL_UnlockCursor(); + } } -static void GS_DMAFullUpdate(_THIS, int numrects, SDL_Rect *rects) +static void +GS_DMAFullUpdate(_THIS, int numrects, SDL_Rect * rects) { - /* Lock so we aren't interrupted by a mouse update */ - SDL_LockCursor(); - - /* Make sure any pending DMA has completed */ - if ( dma_pending ) { - ioctl(console_fd, PS2IOC_SENDQCT, 1); - dma_pending = 0; - } - - /* If the mouse is visible, draw it on the DMA area */ - if ( (SDL_cursorstate & CURSOR_VISIBLE) && !cursor_drawn ) { - this->screen->pixels = mapped_mem + this->screen->offset; - SDL_DrawCursorNoLock(this->screen); - this->screen->pixels = NULL; - cursor_drawn = 1; - } - - /* Put the image onto the screen */ - loadimage_nonblock(console_fd, - &screen_image, screen_image_size, - head_tags_mem, image_tags_mem); - if ( screen_image.y > 0 ) { - /* Need to scale offscreen image to TV output */ - ioctl(console_fd, PS2IOC_SENDQCT, 1); - dma_pending = 0; - scaleimage_nonblock(console_fd, tex_tags_mem, scale_tags_mem); - } else { - dma_pending = 1; - } - - /* We're finished! */ - SDL_UnlockCursor(); + /* Lock so we aren't interrupted by a mouse update */ + SDL_LockCursor(); + + /* Make sure any pending DMA has completed */ + if (dma_pending) { + ioctl(console_fd, PS2IOC_SENDQCT, 1); + dma_pending = 0; + } + + /* If the mouse is visible, draw it on the DMA area */ + if ((SDL_cursorstate & CURSOR_VISIBLE) && !cursor_drawn) { + this->screen->pixels = mapped_mem + this->screen->offset; + SDL_DrawCursorNoLock(this->screen); + this->screen->pixels = NULL; + cursor_drawn = 1; + } + + /* Put the image onto the screen */ + loadimage_nonblock(console_fd, + &screen_image, screen_image_size, + head_tags_mem, image_tags_mem); + if (screen_image.y > 0) { + /* Need to scale offscreen image to TV output */ + ioctl(console_fd, PS2IOC_SENDQCT, 1); + dma_pending = 0; + scaleimage_nonblock(console_fd, tex_tags_mem, scale_tags_mem); + } else { + dma_pending = 1; + } + + /* We're finished! */ + SDL_UnlockCursor(); } -static int GS_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color *colors) +static int +GS_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color * colors) { - return(0); + return (0); } -static void GS_VideoQuit(_THIS) +static void +GS_VideoQuit(_THIS) { - /* Close console and input file descriptors */ - if ( console_fd > 0 ) { - /* Unmap the video framebuffer */ - if ( mapped_mem ) { - /* Unmap the video framebuffer */ - munmap(mapped_mem, mapped_len); - mapped_mem = NULL; - } - close(memory_fd); - - /* Restore the original video mode */ - if ( GS_InGraphicsMode(this) ) { - ioctl(console_fd, PS2IOC_SSCREENINFO, &saved_vinfo); - } - - /* We're all done with the graphics device */ - close(console_fd); - console_fd = -1; - } - GS_CloseMouse(this); - GS_CloseKeyboard(this); + /* Close console and input file descriptors */ + if (console_fd > 0) { + /* Unmap the video framebuffer */ + if (mapped_mem) { + /* Unmap the video framebuffer */ + munmap(mapped_mem, mapped_len); + mapped_mem = NULL; + } + close(memory_fd); + + /* Restore the original video mode */ + if (GS_InGraphicsMode(this)) { + ioctl(console_fd, PS2IOC_SSCREENINFO, &saved_vinfo); + } + + /* We're all done with the graphics device */ + close(console_fd); + console_fd = -1; + } + GS_CloseMouse(this); + GS_CloseKeyboard(this); } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/ps2gs/SDL_gsvideo.h b/src/video/ps2gs/SDL_gsvideo.h index e81131189..344ff5448 100644 --- a/src/video/ps2gs/SDL_gsvideo.h +++ b/src/video/ps2gs/SDL_gsvideo.h @@ -38,34 +38,35 @@ /* Private display data */ -struct SDL_PrivateVideoData { - /* Gotta love that simple PS2 graphics interface. :) */ - int console_fd; - int memory_fd; - struct ps2_screeninfo saved_vinfo; +struct SDL_PrivateVideoData +{ + /* Gotta love that simple PS2 graphics interface. :) */ + int console_fd; + int memory_fd; + struct ps2_screeninfo saved_vinfo; - /* Ye olde linux keyboard code */ - int current_vt; - int saved_vt; - int keyboard_fd; - int saved_kbd_mode; - struct termios saved_kbd_termios; + /* Ye olde linux keyboard code */ + int current_vt; + int saved_vt; + int keyboard_fd; + int saved_kbd_mode; + struct termios saved_kbd_termios; - /* Ye olde linux mouse code */ - int mouse_fd; - int cursor_drawn; + /* Ye olde linux mouse code */ + int mouse_fd; + int cursor_drawn; - /* The memory mapped DMA area and associated variables */ - caddr_t mapped_mem; - int pixels_len; - int mapped_len; - struct ps2_image screen_image; - int screen_image_size; - unsigned long long *head_tags_mem; - unsigned long long *image_tags_mem; - unsigned long long *tex_tags_mem; - unsigned long long *scale_tags_mem; - int dma_pending; + /* The memory mapped DMA area and associated variables */ + caddr_t mapped_mem; + int pixels_len; + int mapped_len; + struct ps2_image screen_image; + int screen_image_size; + unsigned long long *head_tags_mem; + unsigned long long *image_tags_mem; + unsigned long long *tex_tags_mem; + unsigned long long *scale_tags_mem; + int dma_pending; }; /* Old variable names */ #define console_fd (this->hidden->console_fd) @@ -91,5 +92,7 @@ struct SDL_PrivateVideoData { /* Shared between the mouse and video code for screen update scaling */ extern int scaleimage_nonblock(int fd, - unsigned long long *tm, unsigned long long *sm); + unsigned long long *tm, + unsigned long long *sm); #endif /* _SDL_gsvideo_h */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/ps2gs/SDL_gsyuv.c b/src/video/ps2gs/SDL_gsyuv.c index 849633c1a..c993ed255 100644 --- a/src/video/ps2gs/SDL_gsyuv.c +++ b/src/video/ps2gs/SDL_gsyuv.c @@ -27,435 +27,445 @@ #include #include #include -#include /* For definition of PAGE_SIZE */ +#include /* For definition of PAGE_SIZE */ #include "SDL_video.h" #include "SDL_gsyuv_c.h" #include "../SDL_yuvfuncs.h" /* The maximum number of 16x16 pixel block converted at once */ -#define MAX_MACROBLOCKS 1024 /* 2^10 macroblocks at once */ +#define MAX_MACROBLOCKS 1024 /* 2^10 macroblocks at once */ /* The functions used to manipulate video overlays */ static struct private_yuvhwfuncs gs_yuvfuncs = { - GS_LockYUVOverlay, - GS_UnlockYUVOverlay, - GS_DisplayYUVOverlay, - GS_FreeYUVOverlay + GS_LockYUVOverlay, + GS_UnlockYUVOverlay, + GS_DisplayYUVOverlay, + GS_FreeYUVOverlay }; -struct private_yuvhwdata { - int ipu_fd; - Uint8 *pixels; - int macroblocks; - int dma_len; - caddr_t dma_mem; - caddr_t ipu_imem; - caddr_t ipu_omem; - caddr_t dma_tags; - unsigned long long *stretch_x1y1; - unsigned long long *stretch_x2y2; - struct ps2_plist plist; - - /* These are just so we don't have to allocate them separately */ - Uint16 pitches[3]; - Uint8 *planes[3]; +struct private_yuvhwdata +{ + int ipu_fd; + Uint8 *pixels; + int macroblocks; + int dma_len; + caddr_t dma_mem; + caddr_t ipu_imem; + caddr_t ipu_omem; + caddr_t dma_tags; + unsigned long long *stretch_x1y1; + unsigned long long *stretch_x2y2; + struct ps2_plist plist; + + /* These are just so we don't have to allocate them separately */ + Uint16 pitches[3]; + Uint8 *planes[3]; }; -static int power_of_2(int value) +static int +power_of_2(int value) { - int shift; + int shift; - for ( shift = 0; (1< MAX_MACROBLOCKS ) { - SDL_SetError("Overlay too large (maximum size: %d pixels)", - MAX_MACROBLOCKS * 16 * 16); - return(NULL); - } - - /* Double-check the requested format. For simplicity, we'll only - support planar YUV formats. - */ - switch (format) { - case SDL_YV12_OVERLAY: - case SDL_IYUV_OVERLAY: - /* Supported planar YUV format */ - break; - default: - SDL_SetError("Unsupported YUV format"); - return(NULL); - } - - /* Create the overlay structure */ - overlay = (SDL_Overlay *)SDL_malloc(sizeof *overlay); - if ( overlay == NULL ) { - SDL_OutOfMemory(); - return(NULL); - } - SDL_memset(overlay, 0, (sizeof *overlay)); - - /* Fill in the basic members */ - overlay->format = format; - overlay->w = width; - overlay->h = height; - - /* Set up the YUV surface function structure */ - overlay->hwfuncs = &gs_yuvfuncs; - overlay->hw_overlay = 1; - - /* Create the pixel data */ - hwdata = (struct private_yuvhwdata *)SDL_malloc(sizeof *hwdata); - overlay->hwdata = hwdata; - if ( hwdata == NULL ) { - SDL_FreeYUVOverlay(overlay); - SDL_OutOfMemory(); - return(NULL); - } - hwdata->ipu_fd = -1; - hwdata->pixels = (Uint8 *)SDL_malloc(width*height*2); - if ( hwdata->pixels == NULL ) { - SDL_FreeYUVOverlay(overlay); - SDL_OutOfMemory(); - return(NULL); - } - hwdata->macroblocks = (width/16) * (height/16); - - /* Find the pitch and offset values for the overlay */ - overlay->pitches = hwdata->pitches; - overlay->pixels = hwdata->planes; - switch (format) { - case SDL_YV12_OVERLAY: - case SDL_IYUV_OVERLAY: - overlay->pitches[0] = overlay->w; - overlay->pitches[1] = overlay->pitches[0] / 2; - overlay->pitches[2] = overlay->pitches[0] / 2; - overlay->pixels[0] = hwdata->pixels; - overlay->pixels[1] = overlay->pixels[0] + - overlay->pitches[0] * overlay->h; - overlay->pixels[2] = overlay->pixels[1] + - overlay->pitches[1] * overlay->h / 2; - overlay->planes = 3; - break; - default: - /* We should never get here (caught above) */ - break; - } - - /* Theoretically we could support several concurrent decode - streams queueing up on the same file descriptor, but for - simplicity we'll support only one. Opening the IPU more - than once will fail with EBUSY. - */ - hwdata->ipu_fd = open("/dev/ps2ipu", O_RDWR); - if ( hwdata->ipu_fd < 0 ) { - SDL_FreeYUVOverlay(overlay); - SDL_SetError("Playstation 2 IPU busy"); - return(NULL); - } - - /* Allocate a DMA area for pixel conversion */ - bpp = this->screen->format->BytesPerPixel; - map_offset = (mapped_len + (PAGE_SIZE - 1)) & ~(PAGE_SIZE - 1); - hwdata->dma_len = hwdata->macroblocks * (16 * 16 + 8 * 8 + 8 * 8) + - width * height * bpp + - hwdata->macroblocks * (16 * sizeof(long long)) + - 12 * sizeof(long long); - hwdata->dma_mem = mmap(0, hwdata->dma_len, PROT_READ|PROT_WRITE, - MAP_SHARED, memory_fd, map_offset); - if ( hwdata->dma_mem == MAP_FAILED ) { - hwdata->ipu_imem = (caddr_t)0; - SDL_FreeYUVOverlay(overlay); - SDL_SetError("Unable to map %d bytes for DMA", hwdata->dma_len); - return(NULL); - } - hwdata->ipu_imem = hwdata->dma_mem; - hwdata->ipu_omem = hwdata->ipu_imem + - hwdata->macroblocks * (16 * 16 + 8 * 8 + 8 * 8); - hwdata->dma_tags = hwdata->ipu_omem + width * height * bpp; - - /* Allocate memory for the DMA packets */ - hwdata->plist.num = hwdata->macroblocks * 4 + 1; - hwdata->plist.packet = (struct ps2_packet *)SDL_malloc( - hwdata->plist.num*sizeof(struct ps2_packet)); - if ( ! hwdata->plist.packet ) { - SDL_FreeYUVOverlay(overlay); - SDL_OutOfMemory(); - return(NULL); - } - pnum = 0; - packet = hwdata->plist.packet; - - /* Set up the tags to send the image to the screen */ - tags = (unsigned long long *)hwdata->dma_tags; - base = hwdata->ipu_omem; - fbp = screen_image.fbp; - fbw = screen_image.fbw; - psm = screen_image.psm; - y = screen_image.y + screen_image.h; /* Offscreen video memory */ - for ( h=height/16; h; --h ) { - x = 0; /* Visible video memory */ - for ( w=width/16; w; --w ) { - /* The head tag */ - packet[pnum].ptr = &tags[0]; - packet[pnum].len = 10 * sizeof(*tags); - ++pnum; - tags[0] = 4 | (1LL << 60); /* GIFtag */ - tags[1] = 0x0e; /* A+D */ - tags[2] = ((unsigned long long)fbp << 32) | - ((unsigned long long)fbw << 48) | - ((unsigned long long)psm << 56); - tags[3] = PS2_GS_BITBLTBUF; - tags[4] = ((unsigned long long)x << 32) | - ((unsigned long long)y << 48); - tags[5] = PS2_GS_TRXPOS; - tags[6] = (unsigned long long)16 | - ((unsigned long long)16 << 32); - tags[7] = PS2_GS_TRXREG; - tags[8] = 0; - tags[9] = PS2_GS_TRXDIR; - /* Now the actual image data */ - packet[pnum].ptr = &tags[10]; - packet[pnum].len = 2 * sizeof(*tags); - ++pnum; - tags[10] = ((16*16*bpp) >> 4) | (2LL << 58); - tags[11] = 0; - packet[pnum].ptr = (void *)base; - packet[pnum].len = 16 * 16 * bpp; - ++pnum; - packet[pnum].ptr = &tags[12]; - packet[pnum].len = 2 * sizeof(*tags); - ++pnum; - tags[12] = (0 >> 4) | (1 << 15) | (2LL << 58); - tags[13] = 0; - - tags += 16; - base += 16 * 16 * bpp; - - x += 16; - } - y += 16; - } - - /* Set up the texture memory area for the video */ - tex_packet.ptr = tags; - tex_packet.len = 8 * sizeof(*tags); - tags[0] = 3 | (1LL << 60); /* GIFtag */ - tags[1] = 0x0e; /* A+D */ - tags[2] = ((screen_image.y + screen_image.h) * screen_image.w) / 64 + - ((unsigned long long)fbw << 14) + - ((unsigned long long)psm << 20) + - ((unsigned long long)power_of_2(width) << 26) + - ((unsigned long long)power_of_2(height) << 30) + - ((unsigned long long)1 << 34) + - ((unsigned long long)1 << 35); - tags[3] = PS2_GS_TEX0_1; - tags[4] = (1 << 5) + (1 << 6); - tags[5] = PS2_GS_TEX1_1; - tags[6] = 0; - tags[7] = PS2_GS_TEXFLUSH; - ioctl(console_fd, PS2IOC_SEND, &tex_packet); - - /* Set up the tags for scaling the image */ - packet[pnum].ptr = tags; - packet[pnum].len = 12 * sizeof(*tags); - ++pnum; - tags[0] = 5 | (1LL << 60); /* GIFtag */ - tags[1] = 0x0e; /* A+D */ - tags[2] = 6 + (1 << 4) + (1 << 8); - tags[3] = PS2_GS_PRIM; - tags[4] = ((unsigned long long)0 * 16) + - (((unsigned long long)0 * 16) << 16); - tags[5] = PS2_GS_UV; - tags[6] = 0; /* X1, Y1 */ - tags[7] = PS2_GS_XYZ2; - hwdata->stretch_x1y1 = &tags[6]; - tags[8] = ((unsigned long long)overlay->w * 16) + - (((unsigned long long)overlay->h * 16) << 16); - tags[9] = PS2_GS_UV; - tags[10] = 0; /* X2, Y2 */ - tags[11] = PS2_GS_XYZ2; - hwdata->stretch_x2y2 = &tags[10]; - - /* We're all done.. */ - return(overlay); + SDL_Overlay *overlay; + struct private_yuvhwdata *hwdata; + int map_offset; + unsigned long long *tags; + caddr_t base; + int bpp; + int fbp, fbw, psm; + int x, y, w, h; + int pnum; + struct ps2_packet *packet; + struct ps2_packet tex_packet; + + /* We can only decode blocks of 16x16 pixels */ + if ((width & 15) || (height & 15)) { + SDL_SetError("Overlay width/height must be multiples of 16"); + return (NULL); + } + /* Make sure the image isn't too large for a single DMA transfer */ + if (((width / 16) * (height / 16)) > MAX_MACROBLOCKS) { + SDL_SetError("Overlay too large (maximum size: %d pixels)", + MAX_MACROBLOCKS * 16 * 16); + return (NULL); + } + + /* Double-check the requested format. For simplicity, we'll only + support planar YUV formats. + */ + switch (format) { + case SDL_YV12_OVERLAY: + case SDL_IYUV_OVERLAY: + /* Supported planar YUV format */ + break; + default: + SDL_SetError("Unsupported YUV format"); + return (NULL); + } + + /* Create the overlay structure */ + overlay = (SDL_Overlay *) SDL_malloc(sizeof *overlay); + if (overlay == NULL) { + SDL_OutOfMemory(); + return (NULL); + } + SDL_memset(overlay, 0, (sizeof *overlay)); + + /* Fill in the basic members */ + overlay->format = format; + overlay->w = width; + overlay->h = height; + + /* Set up the YUV surface function structure */ + overlay->hwfuncs = &gs_yuvfuncs; + overlay->hw_overlay = 1; + + /* Create the pixel data */ + hwdata = (struct private_yuvhwdata *) SDL_malloc(sizeof *hwdata); + overlay->hwdata = hwdata; + if (hwdata == NULL) { + SDL_FreeYUVOverlay(overlay); + SDL_OutOfMemory(); + return (NULL); + } + hwdata->ipu_fd = -1; + hwdata->pixels = (Uint8 *) SDL_malloc(width * height * 2); + if (hwdata->pixels == NULL) { + SDL_FreeYUVOverlay(overlay); + SDL_OutOfMemory(); + return (NULL); + } + hwdata->macroblocks = (width / 16) * (height / 16); + + /* Find the pitch and offset values for the overlay */ + overlay->pitches = hwdata->pitches; + overlay->pixels = hwdata->planes; + switch (format) { + case SDL_YV12_OVERLAY: + case SDL_IYUV_OVERLAY: + overlay->pitches[0] = overlay->w; + overlay->pitches[1] = overlay->pitches[0] / 2; + overlay->pitches[2] = overlay->pitches[0] / 2; + overlay->pixels[0] = hwdata->pixels; + overlay->pixels[1] = overlay->pixels[0] + + overlay->pitches[0] * overlay->h; + overlay->pixels[2] = overlay->pixels[1] + + overlay->pitches[1] * overlay->h / 2; + overlay->planes = 3; + break; + default: + /* We should never get here (caught above) */ + break; + } + + /* Theoretically we could support several concurrent decode + streams queueing up on the same file descriptor, but for + simplicity we'll support only one. Opening the IPU more + than once will fail with EBUSY. + */ + hwdata->ipu_fd = open("/dev/ps2ipu", O_RDWR); + if (hwdata->ipu_fd < 0) { + SDL_FreeYUVOverlay(overlay); + SDL_SetError("Playstation 2 IPU busy"); + return (NULL); + } + + /* Allocate a DMA area for pixel conversion */ + bpp = this->screen->format->BytesPerPixel; + map_offset = (mapped_len + (PAGE_SIZE - 1)) & ~(PAGE_SIZE - 1); + hwdata->dma_len = hwdata->macroblocks * (16 * 16 + 8 * 8 + 8 * 8) + + width * height * bpp + + hwdata->macroblocks * (16 * sizeof(long long)) + + 12 * sizeof(long long); + hwdata->dma_mem = mmap(0, hwdata->dma_len, PROT_READ | PROT_WRITE, + MAP_SHARED, memory_fd, map_offset); + if (hwdata->dma_mem == MAP_FAILED) { + hwdata->ipu_imem = (caddr_t) 0; + SDL_FreeYUVOverlay(overlay); + SDL_SetError("Unable to map %d bytes for DMA", hwdata->dma_len); + return (NULL); + } + hwdata->ipu_imem = hwdata->dma_mem; + hwdata->ipu_omem = hwdata->ipu_imem + + hwdata->macroblocks * (16 * 16 + 8 * 8 + 8 * 8); + hwdata->dma_tags = hwdata->ipu_omem + width * height * bpp; + + /* Allocate memory for the DMA packets */ + hwdata->plist.num = hwdata->macroblocks * 4 + 1; + hwdata->plist.packet = + (struct ps2_packet *) SDL_malloc(hwdata->plist.num * + sizeof(struct ps2_packet)); + if (!hwdata->plist.packet) { + SDL_FreeYUVOverlay(overlay); + SDL_OutOfMemory(); + return (NULL); + } + pnum = 0; + packet = hwdata->plist.packet; + + /* Set up the tags to send the image to the screen */ + tags = (unsigned long long *) hwdata->dma_tags; + base = hwdata->ipu_omem; + fbp = screen_image.fbp; + fbw = screen_image.fbw; + psm = screen_image.psm; + y = screen_image.y + screen_image.h; /* Offscreen video memory */ + for (h = height / 16; h; --h) { + x = 0; /* Visible video memory */ + for (w = width / 16; w; --w) { + /* The head tag */ + packet[pnum].ptr = &tags[0]; + packet[pnum].len = 10 * sizeof(*tags); + ++pnum; + tags[0] = 4 | (1LL << 60); /* GIFtag */ + tags[1] = 0x0e; /* A+D */ + tags[2] = ((unsigned long long) fbp << 32) | + ((unsigned long long) fbw << 48) | + ((unsigned long long) psm << 56); + tags[3] = PS2_GS_BITBLTBUF; + tags[4] = ((unsigned long long) x << 32) | + ((unsigned long long) y << 48); + tags[5] = PS2_GS_TRXPOS; + tags[6] = (unsigned long long) 16 | + ((unsigned long long) 16 << 32); + tags[7] = PS2_GS_TRXREG; + tags[8] = 0; + tags[9] = PS2_GS_TRXDIR; + /* Now the actual image data */ + packet[pnum].ptr = &tags[10]; + packet[pnum].len = 2 * sizeof(*tags); + ++pnum; + tags[10] = ((16 * 16 * bpp) >> 4) | (2LL << 58); + tags[11] = 0; + packet[pnum].ptr = (void *) base; + packet[pnum].len = 16 * 16 * bpp; + ++pnum; + packet[pnum].ptr = &tags[12]; + packet[pnum].len = 2 * sizeof(*tags); + ++pnum; + tags[12] = (0 >> 4) | (1 << 15) | (2LL << 58); + tags[13] = 0; + + tags += 16; + base += 16 * 16 * bpp; + + x += 16; + } + y += 16; + } + + /* Set up the texture memory area for the video */ + tex_packet.ptr = tags; + tex_packet.len = 8 * sizeof(*tags); + tags[0] = 3 | (1LL << 60); /* GIFtag */ + tags[1] = 0x0e; /* A+D */ + tags[2] = ((screen_image.y + screen_image.h) * screen_image.w) / 64 + + ((unsigned long long) fbw << 14) + + ((unsigned long long) psm << 20) + + ((unsigned long long) power_of_2(width) << 26) + + ((unsigned long long) power_of_2(height) << 30) + + ((unsigned long long) 1 << 34) + ((unsigned long long) 1 << 35); + tags[3] = PS2_GS_TEX0_1; + tags[4] = (1 << 5) + (1 << 6); + tags[5] = PS2_GS_TEX1_1; + tags[6] = 0; + tags[7] = PS2_GS_TEXFLUSH; + ioctl(console_fd, PS2IOC_SEND, &tex_packet); + + /* Set up the tags for scaling the image */ + packet[pnum].ptr = tags; + packet[pnum].len = 12 * sizeof(*tags); + ++pnum; + tags[0] = 5 | (1LL << 60); /* GIFtag */ + tags[1] = 0x0e; /* A+D */ + tags[2] = 6 + (1 << 4) + (1 << 8); + tags[3] = PS2_GS_PRIM; + tags[4] = ((unsigned long long) 0 * 16) + + (((unsigned long long) 0 * 16) << 16); + tags[5] = PS2_GS_UV; + tags[6] = 0; /* X1, Y1 */ + tags[7] = PS2_GS_XYZ2; + hwdata->stretch_x1y1 = &tags[6]; + tags[8] = ((unsigned long long) overlay->w * 16) + + (((unsigned long long) overlay->h * 16) << 16); + tags[9] = PS2_GS_UV; + tags[10] = 0; /* X2, Y2 */ + tags[11] = PS2_GS_XYZ2; + hwdata->stretch_x2y2 = &tags[10]; + + /* We're all done.. */ + return (overlay); } -int GS_LockYUVOverlay(_THIS, SDL_Overlay *overlay) +int +GS_LockYUVOverlay(_THIS, SDL_Overlay * overlay) { - return(0); + return (0); } -void GS_UnlockYUVOverlay(_THIS, SDL_Overlay *overlay) +void +GS_UnlockYUVOverlay(_THIS, SDL_Overlay * overlay) { - return; + return; } -int GS_DisplayYUVOverlay(_THIS, SDL_Overlay *overlay, SDL_Rect *src, SDL_Rect *dst) +int +GS_DisplayYUVOverlay(_THIS, SDL_Overlay * overlay, SDL_Rect * src, + SDL_Rect * dst) { - struct private_yuvhwdata *hwdata; - __u32 cmd; - struct ps2_packet packet; - int h, w, i; - Uint32 *lum, *Cr, *Cb; - int lum_pitch; - int crb_pitch; - Uint32 *lum_src, *Cr_src, *Cb_src; - Uint32 *srcp, *dstp; - unsigned int x, y; - SDL_Surface *screen; - - /* Find out where the various portions of the image are */ - hwdata = overlay->hwdata; - switch (overlay->format) { - case SDL_YV12_OVERLAY: - lum = (Uint32 *)overlay->pixels[0]; - Cr = (Uint32 *)overlay->pixels[1]; - Cb = (Uint32 *)overlay->pixels[2]; - break; - case SDL_IYUV_OVERLAY: - lum = (Uint32 *)overlay->pixels[0]; - Cr = (Uint32 *)overlay->pixels[2]; - Cb = (Uint32 *)overlay->pixels[1]; - default: - SDL_SetError("Unsupported YUV format in blit (?)"); - return(-1); - } - dstp = (Uint32 *)hwdata->ipu_imem; - lum_pitch = overlay->w/4; - crb_pitch = (overlay->w/2)/4; - - /* Copy blocks of 16x16 pixels to the DMA area */ - for ( h=overlay->h/16; h; --h ) { - lum_src = lum; - Cr_src = Cr; - Cb_src = Cb; - for ( w=overlay->w/16; w; --w ) { - srcp = lum_src; - for ( i=0; i<16; ++i ) { - dstp[0] = srcp[0]; - dstp[1] = srcp[1]; - dstp[2] = srcp[2]; - dstp[3] = srcp[3]; - srcp += lum_pitch; - dstp += 4; - } - srcp = Cb_src; - for ( i=0; i<8; ++i ) { - dstp[0] = srcp[0]; - dstp[1] = srcp[1]; - srcp += crb_pitch; - dstp += 2; - } - srcp = Cr_src; - for ( i=0; i<8; ++i ) { - dstp[0] = srcp[0]; - dstp[1] = srcp[1]; - srcp += crb_pitch; - dstp += 2; - } - lum_src += 16 / 4; - Cb_src += 8 / 4; - Cr_src += 8 / 4; - } - lum += lum_pitch * 16; - Cr += crb_pitch * 8; - Cb += crb_pitch * 8; - } - - /* Send the macroblock data to the IPU */ + struct private_yuvhwdata *hwdata; + __u32 cmd; + struct ps2_packet packet; + int h, w, i; + Uint32 *lum, *Cr, *Cb; + int lum_pitch; + int crb_pitch; + Uint32 *lum_src, *Cr_src, *Cb_src; + Uint32 *srcp, *dstp; + unsigned int x, y; + SDL_Surface *screen; + + /* Find out where the various portions of the image are */ + hwdata = overlay->hwdata; + switch (overlay->format) { + case SDL_YV12_OVERLAY: + lum = (Uint32 *) overlay->pixels[0]; + Cr = (Uint32 *) overlay->pixels[1]; + Cb = (Uint32 *) overlay->pixels[2]; + break; + case SDL_IYUV_OVERLAY: + lum = (Uint32 *) overlay->pixels[0]; + Cr = (Uint32 *) overlay->pixels[2]; + Cb = (Uint32 *) overlay->pixels[1]; + default: + SDL_SetError("Unsupported YUV format in blit (?)"); + return (-1); + } + dstp = (Uint32 *) hwdata->ipu_imem; + lum_pitch = overlay->w / 4; + crb_pitch = (overlay->w / 2) / 4; + + /* Copy blocks of 16x16 pixels to the DMA area */ + for (h = overlay->h / 16; h; --h) { + lum_src = lum; + Cr_src = Cr; + Cb_src = Cb; + for (w = overlay->w / 16; w; --w) { + srcp = lum_src; + for (i = 0; i < 16; ++i) { + dstp[0] = srcp[0]; + dstp[1] = srcp[1]; + dstp[2] = srcp[2]; + dstp[3] = srcp[3]; + srcp += lum_pitch; + dstp += 4; + } + srcp = Cb_src; + for (i = 0; i < 8; ++i) { + dstp[0] = srcp[0]; + dstp[1] = srcp[1]; + srcp += crb_pitch; + dstp += 2; + } + srcp = Cr_src; + for (i = 0; i < 8; ++i) { + dstp[0] = srcp[0]; + dstp[1] = srcp[1]; + srcp += crb_pitch; + dstp += 2; + } + lum_src += 16 / 4; + Cb_src += 8 / 4; + Cr_src += 8 / 4; + } + lum += lum_pitch * 16; + Cr += crb_pitch * 8; + Cb += crb_pitch * 8; + } + + /* Send the macroblock data to the IPU */ #ifdef DEBUG_YUV - fprintf(stderr, "Sending data to IPU..\n"); + fprintf(stderr, "Sending data to IPU..\n"); #endif - packet.ptr = hwdata->ipu_imem; - packet.len = hwdata->macroblocks * (16 * 16 + 8 * 8 + 8 * 8); - ioctl(hwdata->ipu_fd, PS2IOC_SENDA, &packet); + packet.ptr = hwdata->ipu_imem; + packet.len = hwdata->macroblocks * (16 * 16 + 8 * 8 + 8 * 8); + ioctl(hwdata->ipu_fd, PS2IOC_SENDA, &packet); - /* Trigger the DMA to the IPU for conversion */ + /* Trigger the DMA to the IPU for conversion */ #ifdef DEBUG_YUV - fprintf(stderr, "Trigging conversion command\n"); + fprintf(stderr, "Trigging conversion command\n"); #endif - cmd = (7 << 28) + hwdata->macroblocks; - if ( screen_image.psm == PS2_GS_PSMCT16 ) { - cmd += (1 << 27) + /* Output RGB 555 */ - (1 << 26); /* Dither output */ - } - ioctl(hwdata->ipu_fd, PS2IOC_SIPUCMD, &cmd); - - /* Retrieve the converted image from the IPU */ + cmd = (7 << 28) + hwdata->macroblocks; + if (screen_image.psm == PS2_GS_PSMCT16) { + cmd += (1 << 27) + /* Output RGB 555 */ + (1 << 26); /* Dither output */ + } + ioctl(hwdata->ipu_fd, PS2IOC_SIPUCMD, &cmd); + + /* Retrieve the converted image from the IPU */ #ifdef DEBUG_YUV - fprintf(stderr, "Retrieving data from IPU..\n"); + fprintf(stderr, "Retrieving data from IPU..\n"); #endif - packet.ptr = hwdata->ipu_omem; - packet.len = overlay->w * overlay->h * - this->screen->format->BytesPerPixel; - ioctl(hwdata->ipu_fd, PS2IOC_RECV, &packet); + packet.ptr = hwdata->ipu_omem; + packet.len = overlay->w * overlay->h * + this->screen->format->BytesPerPixel; + ioctl(hwdata->ipu_fd, PS2IOC_RECV, &packet); #ifdef DEBUG_YUV - fprintf(stderr, "Copying image to screen..\n"); + fprintf(stderr, "Copying image to screen..\n"); #endif - /* Wait for previous DMA to complete */ - ioctl(console_fd, PS2IOC_SENDQCT, 1); - - /* Send the current image to the screen and scale it */ - screen = this->screen; - x = (unsigned int)dst->x; - y = (unsigned int)dst->y; - if ( screen->offset ) { - x += (screen->offset % screen->pitch) / - screen->format->BytesPerPixel; - y += (screen->offset / screen->pitch); - } - y += screen_image.y; - *hwdata->stretch_x1y1 = (x * 16) + ((y * 16) << 16); - x += (unsigned int)dst->w; - y += (unsigned int)dst->h; - *hwdata->stretch_x2y2 = (x * 16) + ((y * 16) << 16); - return ioctl(console_fd, PS2IOC_SENDL, &hwdata->plist); + /* Wait for previous DMA to complete */ + ioctl(console_fd, PS2IOC_SENDQCT, 1); + + /* Send the current image to the screen and scale it */ + screen = this->screen; + x = (unsigned int) dst->x; + y = (unsigned int) dst->y; + if (screen->offset) { + x += (screen->offset % screen->pitch) / screen->format->BytesPerPixel; + y += (screen->offset / screen->pitch); + } + y += screen_image.y; + *hwdata->stretch_x1y1 = (x * 16) + ((y * 16) << 16); + x += (unsigned int) dst->w; + y += (unsigned int) dst->h; + *hwdata->stretch_x2y2 = (x * 16) + ((y * 16) << 16); + return ioctl(console_fd, PS2IOC_SENDL, &hwdata->plist); } -void GS_FreeYUVOverlay(_THIS, SDL_Overlay *overlay) +void +GS_FreeYUVOverlay(_THIS, SDL_Overlay * overlay) { - struct private_yuvhwdata *hwdata; - - hwdata = overlay->hwdata; - if ( hwdata ) { - if ( hwdata->ipu_fd >= 0 ) { - close(hwdata->ipu_fd); - } - if ( hwdata->dma_mem ) { - munmap(hwdata->dma_mem, hwdata->dma_len); - } - if ( hwdata->plist.packet ) { - SDL_free(hwdata->plist.packet); - } - if ( hwdata->pixels ) { - SDL_free(hwdata->pixels); - } - SDL_free(hwdata); - } + struct private_yuvhwdata *hwdata; + + hwdata = overlay->hwdata; + if (hwdata) { + if (hwdata->ipu_fd >= 0) { + close(hwdata->ipu_fd); + } + if (hwdata->dma_mem) { + munmap(hwdata->dma_mem, hwdata->dma_len); + } + if (hwdata->plist.packet) { + SDL_free(hwdata->plist.packet); + } + if (hwdata->pixels) { + SDL_free(hwdata->pixels); + } + SDL_free(hwdata); + } } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/ps2gs/SDL_gsyuv_c.h b/src/video/ps2gs/SDL_gsyuv_c.h index 970e05436..a44366867 100644 --- a/src/video/ps2gs/SDL_gsyuv_c.h +++ b/src/video/ps2gs/SDL_gsyuv_c.h @@ -26,12 +26,15 @@ #include "SDL_video.h" #include "SDL_gsvideo.h" -extern SDL_Overlay *GS_CreateYUVOverlay(_THIS, int width, int height, Uint32 format, SDL_Surface *display); +extern SDL_Overlay *GS_CreateYUVOverlay(_THIS, int width, int height, + Uint32 format, SDL_Surface * display); -extern int GS_LockYUVOverlay(_THIS, SDL_Overlay *overlay); +extern int GS_LockYUVOverlay(_THIS, SDL_Overlay * overlay); -extern void GS_UnlockYUVOverlay(_THIS, SDL_Overlay *overlay); +extern void GS_UnlockYUVOverlay(_THIS, SDL_Overlay * overlay); -extern int GS_DisplayYUVOverlay(_THIS, SDL_Overlay *overlay, SDL_Rect *src, SDL_Rect *dst); +extern int GS_DisplayYUVOverlay(_THIS, SDL_Overlay * overlay, SDL_Rect * src, + SDL_Rect * dst); -extern void GS_FreeYUVOverlay(_THIS, SDL_Overlay *overlay); +extern void GS_FreeYUVOverlay(_THIS, SDL_Overlay * overlay); +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/qtopia/SDL_QPEApp.cc b/src/video/qtopia/SDL_QPEApp.cc index 9623c5733..3e405dde0 100644 --- a/src/video/qtopia/SDL_QPEApp.cc +++ b/src/video/qtopia/SDL_QPEApp.cc @@ -33,31 +33,36 @@ int SDL_QPEAppActive = 0; static QPEApplication *app; -int SDL_InitQPEApp() { - if(SDL_QPEAppActive <= 0) { - if(!qApp) { - int argc = 1; - char *argv[] = { { "SDLApp" } }; - app = new QPEApplication(argc, argv); - QWidget dummy; - app->showMainWidget(&dummy); - } else { - app = (QPEApplication*)qApp; +int +SDL_InitQPEApp() +{ + if (SDL_QPEAppActive <= 0) { + if (!qApp) { + int argc = 1; + char *argv[] = { {"SDLApp"} }; + app = new QPEApplication(argc, argv); + QWidget dummy; + app->showMainWidget(&dummy); + } else { + app = (QPEApplication *) qApp; + } + SDL_QPEAppActive++; } - SDL_QPEAppActive++; - } - return 0; + return 0; } /* Quit the QPE Application, if there's nothing left to do */ -void SDL_QuitQPEApp(void) +void +SDL_QuitQPEApp(void) { - /* Decrement the application reference count */ - SDL_QPEAppActive--; - /* If the reference count reached zero, clean up the app */ - if ( SDL_QPEAppActive == 0 && app) { - delete app; - app = 0; - qApp = 0; - } + /* Decrement the application reference count */ + SDL_QPEAppActive--; + /* If the reference count reached zero, clean up the app */ + if (SDL_QPEAppActive == 0 && app) { + delete app; + app = 0; + qApp = 0; + } } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/qtopia/SDL_QPEApp.h b/src/video/qtopia/SDL_QPEApp.h index 1011ad948..781133b6c 100644 --- a/src/video/qtopia/SDL_QPEApp.h +++ b/src/video/qtopia/SDL_QPEApp.h @@ -31,3 +31,4 @@ extern void SDL_QuitQPEApp(void); /* Flag to tell whether the app is active or not */ extern int SDL_QPEAppActive; +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/qtopia/SDL_QWin.cc b/src/video/qtopia/SDL_QWin.cc index 5036246a5..90df71478 100644 --- a/src/video/qtopia/SDL_QWin.cc +++ b/src/video/qtopia/SDL_QWin.cc @@ -27,501 +27,667 @@ screenRotationT screenRotation = SDL_QT_NO_ROTATION; -SDL_QWin::SDL_QWin(const QSize& size) - : QWidget(0, "SDL_main"), my_painter(0), my_image(0), - my_inhibit_resize(false), my_mouse_pos(-1,-1), my_flags(0), - my_has_fullscreen(false), my_locked(0) +SDL_QWin::SDL_QWin(const QSize & size): +QWidget(0, "SDL_main"), +my_painter(0), +my_image(0), +my_inhibit_resize(false), +my_mouse_pos(-1, -1), +my_flags(0), +my_has_fullscreen(false), +my_locked(0) { - setBackgroundMode(NoBackground); + setBackgroundMode(NoBackground); } -SDL_QWin::~SDL_QWin() { - // Nothing to do yet. - if(my_image) { - delete my_image; - } +SDL_QWin::~SDL_QWin() +{ + // Nothing to do yet. + if (my_image) { + delete my_image; + } } -void SDL_QWin::setImage(QImage *image) { - if ( my_image ) { - delete my_image; - } - my_image = image; - // setFixedSize(image->size()); +void +SDL_QWin::setImage(QImage * image) +{ + if (my_image) { + delete my_image; + } + my_image = image; + // setFixedSize(image->size()); } -void SDL_QWin::resizeEvent(QResizeEvent *e) { - if(size() != qApp->desktop()->size()) { - // Widget is not the correct size, so do the fullscreen magic - my_has_fullscreen = false; - enableFullscreen(); - } - if(my_inhibit_resize) { - my_inhibit_resize = false; - } else { - SDL_PrivateResize(e->size().width(), e->size().height()); - } +void +SDL_QWin::resizeEvent(QResizeEvent * e) +{ + if (size() != qApp->desktop()->size()) { + // Widget is not the correct size, so do the fullscreen magic + my_has_fullscreen = false; + enableFullscreen(); + } + if (my_inhibit_resize) { + my_inhibit_resize = false; + } else { + SDL_PrivateResize(e->size().width(), e->size().height()); + } } -void SDL_QWin::focusInEvent(QFocusEvent *) { - // Always do it here, no matter the size. - enableFullscreen(); - SDL_PrivateAppActive(true, SDL_APPINPUTFOCUS); +void +SDL_QWin::focusInEvent(QFocusEvent *) +{ + // Always do it here, no matter the size. + enableFullscreen(); + SDL_PrivateAppActive(true, SDL_APPINPUTFOCUS); } -void SDL_QWin::focusOutEvent(QFocusEvent *) { - my_has_fullscreen = false; - SDL_PrivateAppActive(false, SDL_APPINPUTFOCUS); +void +SDL_QWin::focusOutEvent(QFocusEvent *) +{ + my_has_fullscreen = false; + SDL_PrivateAppActive(false, SDL_APPINPUTFOCUS); } -void SDL_QWin::closeEvent(QCloseEvent *e) { - SDL_PrivateQuit(); - e->ignore(); +void +SDL_QWin::closeEvent(QCloseEvent * e) +{ + SDL_PrivateQuit(); + e->ignore(); } -void SDL_QWin::setMousePos(const QPoint &pos) { - if(my_image->width() == height()) { - if (screenRotation == SDL_QT_ROTATION_90) - my_mouse_pos = QPoint(height()-pos.y(), pos.x()); - else if (screenRotation == SDL_QT_ROTATION_270) - my_mouse_pos = QPoint(pos.y(), width()-pos.x()); - } else { - my_mouse_pos = pos; - } +void +SDL_QWin::setMousePos(const QPoint & pos) +{ + if (my_image->width() == height()) { + if (screenRotation == SDL_QT_ROTATION_90) + my_mouse_pos = QPoint(height() - pos.y(), pos.x()); + else if (screenRotation == SDL_QT_ROTATION_270) + my_mouse_pos = QPoint(pos.y(), width() - pos.x()); + } else { + my_mouse_pos = pos; + } } -void SDL_QWin::mouseMoveEvent(QMouseEvent *e) { - Qt::ButtonState button = e->button(); - int sdlstate = 0; - if( (button & Qt::LeftButton)) { - sdlstate |= SDL_BUTTON_LMASK; - } - if( (button & Qt::RightButton)) { - sdlstate |= SDL_BUTTON_RMASK; - } - if( (button & Qt::MidButton)) { - sdlstate |= SDL_BUTTON_MMASK; - } - setMousePos(e->pos()); - SDL_PrivateMouseMotion(sdlstate, 0, my_mouse_pos.x(), my_mouse_pos.y()); +void +SDL_QWin::mouseMoveEvent(QMouseEvent * e) +{ + Qt::ButtonState button = e->button(); + int sdlstate = 0; + if ((button & Qt::LeftButton)) { + sdlstate |= SDL_BUTTON_LMASK; + } + if ((button & Qt::RightButton)) { + sdlstate |= SDL_BUTTON_RMASK; + } + if ((button & Qt::MidButton)) { + sdlstate |= SDL_BUTTON_MMASK; + } + setMousePos(e->pos()); + SDL_PrivateMouseMotion(sdlstate, 0, my_mouse_pos.x(), my_mouse_pos.y()); } -void SDL_QWin::mousePressEvent(QMouseEvent *e) { - mouseMoveEvent(e); - Qt::ButtonState button = e->button(); - SDL_PrivateMouseButton(SDL_PRESSED, - (button & Qt::LeftButton) ? 1 : - ((button & Qt::RightButton) ? 2 : 3), - my_mouse_pos.x(), my_mouse_pos.y()); +void +SDL_QWin::mousePressEvent(QMouseEvent * e) +{ + mouseMoveEvent(e); + Qt::ButtonState button = e->button(); + SDL_PrivateMouseButton(SDL_PRESSED, + (button & Qt::LeftButton) ? 1 : + ((button & Qt::RightButton) ? 2 : 3), + my_mouse_pos.x(), my_mouse_pos.y()); } -void SDL_QWin::mouseReleaseEvent(QMouseEvent *e) { - setMousePos(e->pos()); - Qt::ButtonState button = e->button(); - SDL_PrivateMouseButton(SDL_RELEASED, - (button & Qt::LeftButton) ? 1 : - ((button & Qt::RightButton) ? 2 : 3), - my_mouse_pos.x(), my_mouse_pos.y()); - my_mouse_pos = QPoint(-1, -1); +void +SDL_QWin::mouseReleaseEvent(QMouseEvent * e) +{ + setMousePos(e->pos()); + Qt::ButtonState button = e->button(); + SDL_PrivateMouseButton(SDL_RELEASED, + (button & Qt::LeftButton) ? 1 : + ((button & Qt::RightButton) ? 2 : 3), + my_mouse_pos.x(), my_mouse_pos.y()); + my_mouse_pos = QPoint(-1, -1); } static inline void -gs_fastRotateBlit_3 ( unsigned short *fb, - unsigned short *bits, - const QRect& rect ) +gs_fastRotateBlit_3(unsigned short *fb, + unsigned short *bits, const QRect & rect) { - // FIXME: this only works correctly for 240x320 displays - int startx, starty; - int width, height; - - startx = rect.left() >> 1; - starty = rect.top() >> 1; - width = ((rect.right() - rect.left()) >> 1) + 2; - height = ((rect.bottom() - rect.top()) >> 1) + 2; - - if((startx+width) > 120) { - width = 120 - startx; // avoid horizontal overflow - } - if((starty+height) > 160) { - height = 160 - starty; // avoid vertical overflow - } - - ulong *sp1, *sp2, *dp1, *dp2; - ulong stop, sbot, dtop, dbot; - - sp1 = (ulong*)bits + startx + starty*240; - sp2 = sp1 + 120; - dp1 = (ulong *)fb + (159 - starty) + startx*320; - dp2 = dp1 + 160; - int rowadd = (-320*width) - 1; - int rowadd2 = 240 - width; - // transfer in cells of 2x2 pixels in words - for (int y=0; y>16) + (stop & 0xffff0000); - // write to framebuffer - *dp1 = dtop; - *dp2 = dbot; - // update source ptrs - sp1++; sp2++; - // update dest ptrs - 2 pix at a time - dp1 += 320; - dp2 += 320; + // FIXME: this only works correctly for 240x320 displays + int startx, starty; + int width, height; + + startx = rect.left() >> 1; + starty = rect.top() >> 1; + width = ((rect.right() - rect.left()) >> 1) + 2; + height = ((rect.bottom() - rect.top()) >> 1) + 2; + + if ((startx + width) > 120) { + width = 120 - startx; // avoid horizontal overflow + } + if ((starty + height) > 160) { + height = 160 - starty; // avoid vertical overflow + } + + ulong *sp1, *sp2, *dp1, *dp2; + ulong stop, sbot, dtop, dbot; + + sp1 = (ulong *) bits + startx + starty * 240; + sp2 = sp1 + 120; + dp1 = (ulong *) fb + (159 - starty) + startx * 320; + dp2 = dp1 + 160; + int rowadd = (-320 * width) - 1; + int rowadd2 = 240 - width; + // transfer in cells of 2x2 pixels in words + for (int y = 0; y < height; y++) { + for (int x = 0; x < width; x++) { + // read source pixels + stop = *sp1; + sbot = *sp2; + // rotate pixels + dtop = (sbot & 0xffff) + ((stop & 0xffff) << 16); + dbot = ((sbot & 0xffff0000) >> 16) + (stop & 0xffff0000); + // write to framebuffer + *dp1 = dtop; + *dp2 = dbot; + // update source ptrs + sp1++; + sp2++; + // update dest ptrs - 2 pix at a time + dp1 += 320; + dp2 += 320; + } + // adjust src ptrs - skip a row as we work in pairs + sp1 += rowadd2; + sp2 += rowadd2; + // adjust dest ptrs for rotation + dp1 += rowadd; + dp2 += rowadd; } - // adjust src ptrs - skip a row as we work in pairs - sp1 += rowadd2; - sp2 += rowadd2; - // adjust dest ptrs for rotation - dp1 += rowadd; - dp2 += rowadd; - } } static inline void -gs_fastRotateBlit_1 ( unsigned short *fb, - unsigned short *bits, - const QRect& rect ) { - // FIXME: this only works correctly for 240x320 displays - int startx, starty; - int width, height; - - startx = rect.left() >> 1; - starty = rect.top() >> 1; - width = ((rect.right() - rect.left()) >> 1) + 2; - height = ((rect.bottom() - rect.top()) >> 1) + 2; - - if((startx+width) > 120) { - width = 120 - startx; // avoid horizontal overflow - } - if((starty+height) > 160) { - height = 160 - starty; // avoid vertical overflow - } - - ulong *sp1, *sp2, *dp1, *dp2; - ulong stop, sbot, dtop, dbot; - fb += 320*239; // Move "fb" to top left corner - sp1 = (ulong*)bits + startx + starty*240; - sp2 = sp1 + 120; - dp1 = (ulong*)fb - startx * 320 - starty; - dp2 = dp1 - 160; - int rowadd = (320*width) + 1; - int rowadd2 = 240 - width; - // transfer in cells of 2x2 pixels in words - for (int y=0; y>16) + (sbot & 0xffff0000); - // write - *dp1 = dtop; - *dp2 = dbot; - // update source ptrs - sp1++; sp2++; - // update dest ptrs - 2 pix at a time - dp1 -= 320; - dp2 -= 320; +gs_fastRotateBlit_1(unsigned short *fb, + unsigned short *bits, const QRect & rect) +{ + // FIXME: this only works correctly for 240x320 displays + int startx, starty; + int width, height; + + startx = rect.left() >> 1; + starty = rect.top() >> 1; + width = ((rect.right() - rect.left()) >> 1) + 2; + height = ((rect.bottom() - rect.top()) >> 1) + 2; + + if ((startx + width) > 120) { + width = 120 - startx; // avoid horizontal overflow + } + if ((starty + height) > 160) { + height = 160 - starty; // avoid vertical overflow + } + + ulong *sp1, *sp2, *dp1, *dp2; + ulong stop, sbot, dtop, dbot; + fb += 320 * 239; // Move "fb" to top left corner + sp1 = (ulong *) bits + startx + starty * 240; + sp2 = sp1 + 120; + dp1 = (ulong *) fb - startx * 320 - starty; + dp2 = dp1 - 160; + int rowadd = (320 * width) + 1; + int rowadd2 = 240 - width; + // transfer in cells of 2x2 pixels in words + for (int y = 0; y < height; y++) { + for (int x = 0; x < width; x++) { + // read + stop = *sp1; + sbot = *sp2; + // rotate + dtop = (stop & 0xffff) + ((sbot & 0xffff) << 16); + dbot = ((stop & 0xffff0000) >> 16) + (sbot & 0xffff0000); + // write + *dp1 = dtop; + *dp2 = dbot; + // update source ptrs + sp1++; + sp2++; + // update dest ptrs - 2 pix at a time + dp1 -= 320; + dp2 -= 320; + } + // adjust src ptrs - skip a row as we work in pairs + sp1 += rowadd2; + sp2 += rowadd2; + // adjust dest ptrs for rotation + dp1 += rowadd; + dp2 += rowadd; } - // adjust src ptrs - skip a row as we work in pairs - sp1 += rowadd2; - sp2 += rowadd2; - // adjust dest ptrs for rotation - dp1 += rowadd; - dp2 += rowadd; - } } // desktop, SL-A300 etc -bool SDL_QWin::repaintRotation0(const QRect& rect) { - if(my_image->width() == width()) { - uchar *fb = (uchar*)my_painter->frameBuffer(); - uchar *buf = (uchar*)my_image->bits(); - if(rect == my_image->rect()) { - SDL_memcpy(fb, buf, width()*height()*2); +/* *INDENT-OFF* */ +bool SDL_QWin::repaintRotation0 (const QRect & rect) +{ + if (my_image->width () == width ()) { + uchar * fb = (uchar *) my_painter->frameBuffer (); + uchar * buf = (uchar *) my_image->bits (); + if (rect == my_image->rect ()) { + SDL_memcpy (fb, buf, width () * height () * 2); + } else { + int h = rect.height (); + int wd = rect.width () << 1; + int fblineadd = my_painter->lineStep (); + int buflineadd = my_image->bytesPerLine (); + fb += (rect.left () << 1) + rect.top () * my_painter->lineStep (); + buf += (rect.left () << 1) + rect.top () * my_image->bytesPerLine (); + while (h--) { + SDL_memcpy (fb, buf, wd); + fb += fblineadd; + buf += buflineadd; + } + } } else { - int h = rect.height(); - int wd = rect.width()<<1; - int fblineadd = my_painter->lineStep(); - int buflineadd = my_image->bytesPerLine(); - fb += (rect.left()<<1) + rect.top() * my_painter->lineStep(); - buf += (rect.left()<<1) + rect.top() * my_image->bytesPerLine(); - while(h--) { - SDL_memcpy(fb, buf, wd); - fb += fblineadd; - buf += buflineadd; - } + return false; // FIXME: Landscape } - } else { - return false; // FIXME: Landscape - } #ifdef __i386__ - my_painter->fillRect( rect, QBrush( Qt::NoBrush ) ); + my_painter->fillRect (rect, QBrush (Qt::NoBrush)); #endif - return true; + return true; } +/* *INDENT-ON* */ + - // Sharp Zaurus SL-5500 etc -bool SDL_QWin::repaintRotation3(const QRect& rect) { - if(my_image->width() == width()) { - ushort *fb = (ushort*)my_painter->frameBuffer(); - ushort *buf = (ushort*)my_image->bits(); - gs_fastRotateBlit_3(fb, buf, rect); - } else { - // landscape mode - if (screenRotation == SDL_QT_ROTATION_90) { - uchar *fb = (uchar*)my_painter->frameBuffer(); - uchar *buf = (uchar*)my_image->bits(); - if(rect == my_image->rect()) { - SDL_memcpy(fb, buf, width()*height()*2); - } else { - int h = rect.height(); - int wd = rect.width()<<1; - int fblineadd = my_painter->lineStep(); - int buflineadd = my_image->bytesPerLine(); - fb += (rect.left()<<1) + rect.top() * my_painter->lineStep(); - buf += (rect.left()<<1) + rect.top() * my_image->bytesPerLine(); - while(h--) { - SDL_memcpy(fb, buf, wd); - fb += fblineadd; - buf += buflineadd; - } - } - } else if (screenRotation == SDL_QT_ROTATION_270) { - int h = rect.height(); - int wd = rect.width(); - int fblineadd = my_painter->lineStep() - (rect.width() << 1); - int buflineadd = my_image->bytesPerLine() - (rect.width() << 1); - int w; - - uchar *fb = (uchar*)my_painter->frameBuffer(); - uchar *buf = (uchar*)my_image->bits(); - - fb += ((my_painter->width() - (rect.top() + rect.height())) * - my_painter->lineStep()) + ((my_painter->height() - ((rect.left() + - rect.width()))) << 1); - - buf += my_image->bytesPerLine() * (rect.top() + rect.height()) - - (((my_image->width() - (rect.left() + rect.width())) << 1) + 2); - - while(h--) { - w = wd; - while(w--) *((unsigned short*)fb)++ = *((unsigned short*)buf)--; - fb += fblineadd; - buf -= buflineadd; - } +/* *INDENT-OFF* */ +bool SDL_QWin::repaintRotation3 (const QRect & rect) +{ + if (my_image->width () == width ()) { + ushort * fb = (ushort *) my_painter->frameBuffer (); + ushort * buf = (ushort *) my_image->bits (); + gs_fastRotateBlit_3 (fb, buf, rect); + } else { + // landscape mode + if (screenRotation == SDL_QT_ROTATION_90) { + uchar * fb = (uchar *) my_painter->frameBuffer (); + uchar * buf = (uchar *) my_image->bits (); + if (rect == my_image->rect ()) { + SDL_memcpy (fb, buf, width () * height () * 2); + } else { + int h = rect.height (); + int wd = rect.width () << 1; + int fblineadd = my_painter->lineStep (); + int buflineadd = my_image->bytesPerLine (); + fb += + (rect.left () << 1) + + rect.top () * my_painter->lineStep (); + buf += + (rect.left () << 1) + + rect.top () * my_image->bytesPerLine (); + while (h--) { + SDL_memcpy (fb, buf, wd); + fb += fblineadd; + buf += buflineadd; + } + } + } else if (screenRotation == SDL_QT_ROTATION_270) { + int h = rect.height (); + int wd = rect.width (); + int fblineadd = my_painter->lineStep () - (rect.width () << 1); + int buflineadd = my_image->bytesPerLine () - (rect.width () << 1); + int w; + + uchar * fb = (uchar *) my_painter->frameBuffer (); + uchar * buf = (uchar *) my_image->bits (); + + fb += + ((my_painter->width () - + (rect.top () + + rect.height ())) * my_painter->lineStep ()) + + ((my_painter->height () - + ((rect.left () + rect.width ()))) << 1); + + buf += + my_image->bytesPerLine () * (rect.top () + + rect.height ()) - + (((my_image->width () - + (rect.left () + rect.width ())) << 1) + 2); + + while (h--) { + w = wd; + while (w--) + *((unsigned short *) fb)++ = *((unsigned short *) buf)--; + fb += fblineadd; + buf -= buflineadd; + } + } } - } - return true; + return true; } +/* *INDENT-ON* */ // ipaq 3800... -bool SDL_QWin::repaintRotation1(const QRect& rect) { - if(my_image->width() == width()) { - ushort *fb = (ushort*)my_painter->frameBuffer(); - ushort *buf = (ushort*)my_image->bits(); - gs_fastRotateBlit_1(fb, buf, rect); - } else { - return false; // FIXME: landscape mode - } - return true; +/* *INDENT-OFF* */ +bool SDL_QWin::repaintRotation1 (const QRect & rect) +{ + if (my_image->width () == width ()) { + ushort *fb = (ushort *) my_painter->frameBuffer (); + ushort *buf = (ushort *) my_image->bits (); + gs_fastRotateBlit_1 (fb, buf, rect); + } else { + return false; // FIXME: landscape mode + } + return true; } +/* *INDENT-ON* */ + +void +SDL_QWin::repaintRect(const QRect & rect) +{ + if (!my_painter || !rect.width() || !rect.height()) { + return; + } -void SDL_QWin::repaintRect(const QRect& rect) { - if(!my_painter || !rect.width() || !rect.height()) { - return; - } - - if(QPixmap::defaultDepth() == 16) { - switch(my_painter->transformOrientation()) { - case 3: - if(repaintRotation3(rect)) { return; } - break; - case 1: - if(repaintRotation1(rect)) { return; } - break; - case 0: - if(repaintRotation0(rect)) { return; } - break; + if (QPixmap::defaultDepth() == 16) { + switch (my_painter->transformOrientation()) { + case 3: + if (repaintRotation3(rect)) { + return; + } + break; + case 1: + if (repaintRotation1(rect)) { + return; + } + break; + case 0: + if (repaintRotation0(rect)) { + return; + } + break; + } } - } - my_painter->drawImage(rect.topLeft(), *my_image, rect); + my_painter->drawImage(rect.topLeft(), *my_image, rect); } // This paints the current buffer to the screen, when desired. -void SDL_QWin::paintEvent(QPaintEvent *ev) { - if(my_image) { - lockScreen(true); - repaintRect(ev->rect()); - unlockScreen(); - } -} +void +SDL_QWin::paintEvent(QPaintEvent * ev) +{ + if (my_image) { + lockScreen(true); + repaintRect(ev->rect()); + unlockScreen(); + } +} /* Function to translate a keyboard transition and queue the key event * This should probably be a table although this method isn't exactly * slow. */ -void SDL_QWin::QueueKey(QKeyEvent *e, int pressed) -{ - SDL_keysym keysym; - int scancode = e->key(); - /* Set the keysym information */ - if(scancode >= 'A' && scancode <= 'Z') { - // Qt sends uppercase, SDL wants lowercase - keysym.sym = static_cast(scancode + 32); - } else if(scancode >= 0x1000) { - // Special keys - switch(scancode) { - case Qt::Key_Escape: scancode = SDLK_ESCAPE; break; - case Qt::Key_Tab: scancode = SDLK_TAB; break; - case Qt::Key_Backspace: scancode = SDLK_BACKSPACE; break; - case Qt::Key_Return: scancode = SDLK_RETURN; break; - case Qt::Key_Enter: scancode = SDLK_KP_ENTER; break; - case Qt::Key_Insert: scancode = SDLK_INSERT; break; - case Qt::Key_Delete: scancode = SDLK_DELETE; break; - case Qt::Key_Pause: scancode = SDLK_PAUSE; break; - case Qt::Key_Print: scancode = SDLK_PRINT; break; - case Qt::Key_SysReq: scancode = SDLK_SYSREQ; break; - case Qt::Key_Home: scancode = SDLK_HOME; break; - case Qt::Key_End: scancode = SDLK_END; break; - // We want the control keys to rotate with the screen - case Qt::Key_Left: - if (screenRotation == SDL_QT_ROTATION_90) scancode = SDLK_UP; - else if (screenRotation == SDL_QT_ROTATION_270) scancode = SDLK_DOWN; - else scancode = SDLK_LEFT; - break; - case Qt::Key_Up: - if (screenRotation == SDL_QT_ROTATION_90) scancode = SDLK_RIGHT; - else if (screenRotation == SDL_QT_ROTATION_270) scancode = SDLK_LEFT; - else scancode = SDLK_UP; - break; - case Qt::Key_Right: - if (screenRotation == SDL_QT_ROTATION_90) scancode = SDLK_DOWN; - else if (screenRotation == SDL_QT_ROTATION_270) scancode = SDLK_UP; - else scancode = SDLK_RIGHT; - break; - case Qt::Key_Down: - if (screenRotation == SDL_QT_ROTATION_90) scancode = SDLK_LEFT; - else if (screenRotation == SDL_QT_ROTATION_270) scancode = SDLK_RIGHT; - else scancode = SDLK_DOWN; - break; - case Qt::Key_Prior: scancode = SDLK_PAGEUP; break; - case Qt::Key_Next: scancode = SDLK_PAGEDOWN; break; - case Qt::Key_Shift: scancode = SDLK_LSHIFT; break; - case Qt::Key_Control: scancode = SDLK_LCTRL; break; - case Qt::Key_Meta: scancode = SDLK_LMETA; break; - case Qt::Key_Alt: scancode = SDLK_LALT; break; - case Qt::Key_CapsLock: scancode = SDLK_CAPSLOCK; break; - case Qt::Key_NumLock: scancode = SDLK_NUMLOCK; break; - case Qt::Key_ScrollLock: scancode = SDLK_SCROLLOCK; break; - case Qt::Key_F1: scancode = SDLK_F1; break; - case Qt::Key_F2: scancode = SDLK_F2; break; - case Qt::Key_F3: scancode = SDLK_F3; break; - case Qt::Key_F4: scancode = SDLK_F4; break; - case Qt::Key_F5: scancode = SDLK_F5; break; - case Qt::Key_F6: scancode = SDLK_F6; break; - case Qt::Key_F7: scancode = SDLK_F7; break; - case Qt::Key_F8: scancode = SDLK_F8; break; - case Qt::Key_F9: scancode = SDLK_F9; break; - case Qt::Key_F10: scancode = SDLK_F10; break; - case Qt::Key_F11: scancode = SDLK_F11; break; - case Qt::Key_F12: scancode = SDLK_F12; break; - case Qt::Key_F13: scancode = SDLK_F13; break; - case Qt::Key_F14: scancode = SDLK_F14; break; - case Qt::Key_F15: scancode = SDLK_F15; break; - case Qt::Key_Super_L: scancode = SDLK_LSUPER; break; - case Qt::Key_Super_R: scancode = SDLK_RSUPER; break; - case Qt::Key_Menu: scancode = SDLK_MENU; break; - case Qt::Key_Help: scancode = SDLK_HELP; break; - - case Qt::Key_F33: - // FIXME: This is a hack to enable the OK key on - // Zaurii devices. SDLK_RETURN is a suitable key to use - // since it often is used as such. - // david@hedbor.org - scancode = SDLK_RETURN; - break; - default: - scancode = SDLK_UNKNOWN; - break; +void +SDL_QWin::QueueKey(QKeyEvent * e, int pressed) +{ + SDL_keysym keysym; + int scancode = e->key(); + /* Set the keysym information */ + if (scancode >= 'A' && scancode <= 'Z') { + // Qt sends uppercase, SDL wants lowercase + keysym.sym = static_cast < SDLKey > (scancode + 32); + } else if (scancode >= 0x1000) { + // Special keys + switch (scancode) { + case Qt::Key_Escape: + scancode = SDLK_ESCAPE; + break; + case Qt::Key_Tab: + scancode = SDLK_TAB; + break; + case Qt::Key_Backspace: + scancode = SDLK_BACKSPACE; + break; + case Qt::Key_Return: + scancode = SDLK_RETURN; + break; + case Qt::Key_Enter: + scancode = SDLK_KP_ENTER; + break; + case Qt::Key_Insert: + scancode = SDLK_INSERT; + break; + case Qt::Key_Delete: + scancode = SDLK_DELETE; + break; + case Qt::Key_Pause: + scancode = SDLK_PAUSE; + break; + case Qt::Key_Print: + scancode = SDLK_PRINT; + break; + case Qt::Key_SysReq: + scancode = SDLK_SYSREQ; + break; + case Qt::Key_Home: + scancode = SDLK_HOME; + break; + case Qt::Key_End: + scancode = SDLK_END; + break; + // We want the control keys to rotate with the screen + case Qt::Key_Left: + if (screenRotation == SDL_QT_ROTATION_90) + scancode = SDLK_UP; + else if (screenRotation == SDL_QT_ROTATION_270) + scancode = SDLK_DOWN; + else + scancode = SDLK_LEFT; + break; + case Qt::Key_Up: + if (screenRotation == SDL_QT_ROTATION_90) + scancode = SDLK_RIGHT; + else if (screenRotation == SDL_QT_ROTATION_270) + scancode = SDLK_LEFT; + else + scancode = SDLK_UP; + break; + case Qt::Key_Right: + if (screenRotation == SDL_QT_ROTATION_90) + scancode = SDLK_DOWN; + else if (screenRotation == SDL_QT_ROTATION_270) + scancode = SDLK_UP; + else + scancode = SDLK_RIGHT; + break; + case Qt::Key_Down: + if (screenRotation == SDL_QT_ROTATION_90) + scancode = SDLK_LEFT; + else if (screenRotation == SDL_QT_ROTATION_270) + scancode = SDLK_RIGHT; + else + scancode = SDLK_DOWN; + break; + case Qt::Key_Prior: + scancode = SDLK_PAGEUP; + break; + case Qt::Key_Next: + scancode = SDLK_PAGEDOWN; + break; + case Qt::Key_Shift: + scancode = SDLK_LSHIFT; + break; + case Qt::Key_Control: + scancode = SDLK_LCTRL; + break; + case Qt::Key_Meta: + scancode = SDLK_LMETA; + break; + case Qt::Key_Alt: + scancode = SDLK_LALT; + break; + case Qt::Key_CapsLock: + scancode = SDLK_CAPSLOCK; + break; + case Qt::Key_NumLock: + scancode = SDLK_NUMLOCK; + break; + case Qt::Key_ScrollLock: + scancode = SDLK_SCROLLOCK; + break; + case Qt::Key_F1: + scancode = SDLK_F1; + break; + case Qt::Key_F2: + scancode = SDLK_F2; + break; + case Qt::Key_F3: + scancode = SDLK_F3; + break; + case Qt::Key_F4: + scancode = SDLK_F4; + break; + case Qt::Key_F5: + scancode = SDLK_F5; + break; + case Qt::Key_F6: + scancode = SDLK_F6; + break; + case Qt::Key_F7: + scancode = SDLK_F7; + break; + case Qt::Key_F8: + scancode = SDLK_F8; + break; + case Qt::Key_F9: + scancode = SDLK_F9; + break; + case Qt::Key_F10: + scancode = SDLK_F10; + break; + case Qt::Key_F11: + scancode = SDLK_F11; + break; + case Qt::Key_F12: + scancode = SDLK_F12; + break; + case Qt::Key_F13: + scancode = SDLK_F13; + break; + case Qt::Key_F14: + scancode = SDLK_F14; + break; + case Qt::Key_F15: + scancode = SDLK_F15; + break; + case Qt::Key_Super_L: + scancode = SDLK_LSUPER; + break; + case Qt::Key_Super_R: + scancode = SDLK_RSUPER; + break; + case Qt::Key_Menu: + scancode = SDLK_MENU; + break; + case Qt::Key_Help: + scancode = SDLK_HELP; + break; + + case Qt::Key_F33: + // FIXME: This is a hack to enable the OK key on + // Zaurii devices. SDLK_RETURN is a suitable key to use + // since it often is used as such. + // david@hedbor.org + scancode = SDLK_RETURN; + break; + default: + scancode = SDLK_UNKNOWN; + break; + } + keysym.sym = static_cast < SDLKey > (scancode); + } else { + keysym.sym = static_cast < SDLKey > (scancode); + } + keysym.scancode = scancode; + keysym.mod = KMOD_NONE; + ButtonState st = e->state(); + if ((st & ShiftButton)) { + keysym.mod = static_cast < SDLMod > (keysym.mod | KMOD_LSHIFT); + } + if ((st & ControlButton)) { + keysym.mod = static_cast < SDLMod > (keysym.mod | KMOD_LCTRL); + } + if ((st & AltButton)) { + keysym.mod = static_cast < SDLMod > (keysym.mod | KMOD_LALT); + } + if (SDL_TranslateUNICODE) { + QChar qchar = e->text()[0]; + keysym.unicode = qchar.unicode(); + } else { + keysym.unicode = 0; + } + + /* NUMLOCK and CAPSLOCK are implemented as double-presses in reality */ + // if ( (keysym.sym == SDLK_NUMLOCK) || (keysym.sym == SDLK_CAPSLOCK) ) { + // pressed = 1; + // } + + /* Queue the key event */ + if (pressed) { + SDL_PrivateKeyboard(SDL_PRESSED, &keysym); + } else { + SDL_PrivateKeyboard(SDL_RELEASED, &keysym); } - keysym.sym = static_cast(scancode); - } else { - keysym.sym = static_cast(scancode); - } - keysym.scancode = scancode; - keysym.mod = KMOD_NONE; - ButtonState st = e->state(); - if( (st & ShiftButton) ) { keysym.mod = static_cast(keysym.mod | KMOD_LSHIFT); } - if( (st & ControlButton) ) { keysym.mod = static_cast(keysym.mod | KMOD_LCTRL); } - if( (st & AltButton) ) { keysym.mod = static_cast(keysym.mod | KMOD_LALT); } - if ( SDL_TranslateUNICODE ) { - QChar qchar = e->text()[0]; - keysym.unicode = qchar.unicode(); - } else { - keysym.unicode = 0; - } - - /* NUMLOCK and CAPSLOCK are implemented as double-presses in reality */ - // if ( (keysym.sym == SDLK_NUMLOCK) || (keysym.sym == SDLK_CAPSLOCK) ) { - // pressed = 1; - // } - - /* Queue the key event */ - if ( pressed ) { - SDL_PrivateKeyboard(SDL_PRESSED, &keysym); - } else { - SDL_PrivateKeyboard(SDL_RELEASED, &keysym); - } } -void SDL_QWin::setFullscreen(bool fs_on) { - my_has_fullscreen = false; - enableFullscreen(); +void +SDL_QWin::setFullscreen(bool fs_on) +{ + my_has_fullscreen = false; + enableFullscreen(); } -void SDL_QWin::enableFullscreen() { - // Make sure size is correct - if(!my_has_fullscreen) { - setFixedSize(qApp->desktop()->size()); - // This call is needed because showFullScreen won't work - // correctly if the widget already considers itself to be fullscreen. - showNormal(); - // This is needed because showNormal() forcefully changes the window - // style to WSTyle_TopLevel. - setWFlags(WStyle_Customize | WStyle_NoBorder); - // Enable fullscreen. - showFullScreen(); - my_has_fullscreen = true; - } +void +SDL_QWin::enableFullscreen() +{ + // Make sure size is correct + if (!my_has_fullscreen) { + setFixedSize(qApp->desktop()->size()); + // This call is needed because showFullScreen won't work + // correctly if the widget already considers itself to be fullscreen. + showNormal(); + // This is needed because showNormal() forcefully changes the window + // style to WSTyle_TopLevel. + setWFlags(WStyle_Customize | WStyle_NoBorder); + // Enable fullscreen. + showFullScreen(); + my_has_fullscreen = true; + } } -bool SDL_QWin::lockScreen(bool force) { - if(!my_painter) { - if(force || (isVisible() && isActiveWindow())) { - my_painter = new QDirectPainter(this); - } else { - return false; +/* *INDENT-OFF* */ +bool +SDL_QWin::lockScreen (bool force) +{ + if (!my_painter) { + if (force || (isVisible () && isActiveWindow ())) { + my_painter = new QDirectPainter (this); + } else { + return false; + } } - } - my_locked++; // Increate lock refcount - return true; + my_locked++; // Increate lock refcount + return true; } +/* *INDENT-ON* */ -void SDL_QWin::unlockScreen() { - if(my_locked > 0) { - my_locked--; // decrease lock refcount; - } - if(!my_locked && my_painter) { - my_painter->end(); - delete my_painter; - my_painter = 0; - } +void +SDL_QWin::unlockScreen() +{ + if (my_locked > 0) { + my_locked--; // decrease lock refcount; + } + if (!my_locked && my_painter) { + my_painter->end(); + delete my_painter; + my_painter = 0; + } } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/qtopia/SDL_QWin.h b/src/video/qtopia/SDL_QWin.h index 47636dfe4..b137e34c3 100644 --- a/src/video/qtopia/SDL_QWin.h +++ b/src/video/qtopia/SDL_QWin.h @@ -34,77 +34,97 @@ #include "SDL_events.h" -extern "C" { +extern "C" +{ #include "../../events/SDL_events_c.h" }; -typedef enum { - SDL_QT_NO_ROTATION = 0, - SDL_QT_ROTATION_90, - SDL_QT_ROTATION_270 +typedef enum +{ + SDL_QT_NO_ROTATION = 0, + SDL_QT_ROTATION_90, + SDL_QT_ROTATION_270 } screenRotationT; extern screenRotationT screenRotation; -class SDL_QWin : public QWidget +class SDL_QWin:public QWidget { - void QueueKey(QKeyEvent *e, int pressed); - public: - SDL_QWin(const QSize& size); - virtual ~SDL_QWin(); - virtual bool shown(void) { - return isVisible(); - } - /* If called, the next resize event will not be forwarded to SDL. */ - virtual void inhibitResize(void) { - my_inhibit_resize = true; - } - void setImage(QImage *image); - void setOffset(int x, int y) { - my_offset = QPoint(x, y); - } - void GetXYOffset(int &x, int &y) { - x = my_offset.x(); - y = my_offset.y(); - } - QImage *image(void) { return my_image; } - - void setWFlags(WFlags flags) { - QWidget::setWFlags(flags); - my_flags = flags; - } - const QPoint& mousePos() const { return my_mouse_pos; } - void setMousePos(const QPoint& newpos); - void setFullscreen(bool); + void QueueKey(QKeyEvent * e, int pressed); + public: + SDL_QWin(const QSize & size); + virtual ~ SDL_QWin(); + virtual bool shown(void) + { + return isVisible(); + } + /* If called, the next resize event will not be forwarded to SDL. */ + virtual void inhibitResize(void) + { + my_inhibit_resize = true; + } + void setImage(QImage * image); + void setOffset(int x, int y) + { + my_offset = QPoint(x, y); + } + void GetXYOffset(int &x, int &y) + { + x = my_offset.x(); + y = my_offset.y(); + } + QImage *image(void) + { + return my_image; + } + + void setWFlags(WFlags flags) + { + QWidget::setWFlags(flags); + my_flags = flags; + } + const QPoint & mousePos() const + { + return my_mouse_pos; + } + void setMousePos(const QPoint & newpos); + void setFullscreen(bool); - bool lockScreen(bool force=false); - void unlockScreen(); - void repaintRect(const QRect& rect); - protected: - /* Handle resizing of the window */ - virtual void resizeEvent(QResizeEvent *e); - void focusInEvent(QFocusEvent *); - void focusOutEvent(QFocusEvent *); - void closeEvent(QCloseEvent *e); - void mouseMoveEvent(QMouseEvent *e); - void mousePressEvent(QMouseEvent *e); - void mouseReleaseEvent(QMouseEvent *e); - void paintEvent(QPaintEvent *ev); - void keyPressEvent(QKeyEvent *e) { QueueKey(e, 1); } - void keyReleaseEvent(QKeyEvent *e) { QueueKey(e, 0); } - private: - bool repaintRotation0(const QRect& rect); - bool repaintRotation1(const QRect& rect); - bool repaintRotation3(const QRect& rect); - void enableFullscreen(); - QDirectPainter *my_painter; - QImage *my_image; - bool my_inhibit_resize; - QPoint my_offset; - QPoint my_mouse_pos; - WFlags my_flags; - WFlags my_has_fullscreen; - unsigned int my_locked; + bool lockScreen(bool force = false); + void unlockScreen(); + void repaintRect(const QRect & rect); + protected: + /* Handle resizing of the window */ + virtual void resizeEvent(QResizeEvent * e); + void focusInEvent(QFocusEvent *); + void focusOutEvent(QFocusEvent *); + void closeEvent(QCloseEvent * e); + void mouseMoveEvent(QMouseEvent * e); + void mousePressEvent(QMouseEvent * e); + void mouseReleaseEvent(QMouseEvent * e); + void paintEvent(QPaintEvent * ev); + void keyPressEvent(QKeyEvent * e) + { + QueueKey(e, 1); + } + void keyReleaseEvent(QKeyEvent * e) + { + QueueKey(e, 0); + } + private: + bool repaintRotation0(const QRect & rect); + bool repaintRotation1(const QRect & rect); + bool repaintRotation3(const QRect & rect); + void enableFullscreen(); + QDirectPainter *my_painter; + QImage *my_image; + bool my_inhibit_resize; + QPoint my_offset; + QPoint my_mouse_pos; + WFlags my_flags; + WFlags my_has_fullscreen; + unsigned int my_locked; }; #endif /* _SDL_QWin_h */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/qtopia/SDL_lowvideo.h b/src/video/qtopia/SDL_lowvideo.h index c3c09a0b4..65c2e9ce9 100644 --- a/src/video/qtopia/SDL_lowvideo.h +++ b/src/video/qtopia/SDL_lowvideo.h @@ -31,25 +31,26 @@ #define _THIS SDL_VideoDevice *_this /* Private display data */ -struct SDL_PrivateVideoData { - /* The main window */ - SDL_QWin *SDL_Win; +struct SDL_PrivateVideoData +{ + /* The main window */ + SDL_QWin *SDL_Win; - /* The fullscreen mode list */ -#define NUM_MODELISTS 4 /* 8, 16, 24, and 32 bits-per-pixel */ - int SDL_nummodes[NUM_MODELISTS]; - SDL_Rect **SDL_modelist[NUM_MODELISTS]; + /* The fullscreen mode list */ +#define NUM_MODELISTS 4 /* 8, 16, 24, and 32 bits-per-pixel */ + int SDL_nummodes[NUM_MODELISTS]; + SDL_Rect **SDL_modelist[NUM_MODELISTS]; - /* A completely clear cursor */ - WMcursor *BlankCursor; + /* A completely clear cursor */ + WMcursor *BlankCursor; - /* Mouse state variables */ - Uint32 last_buttons; - QPoint last_point; + /* Mouse state variables */ + Uint32 last_buttons; + QPoint last_point; - /* Keyboard state variables */ - int key_flip; - //struct key_info keyinfo[2]; + /* Keyboard state variables */ + int key_flip; + //struct key_info keyinfo[2]; }; /* Old variable names */ #define SDL_Win (_this->hidden->SDL_Win) @@ -63,3 +64,4 @@ struct SDL_PrivateVideoData { #define keyinfo (_this->hidden->keyinfo) #endif /* _SDL_lowvideo_h */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/qtopia/SDL_sysevents.cc b/src/video/qtopia/SDL_sysevents.cc index 2b8114232..857276116 100644 --- a/src/video/qtopia/SDL_sysevents.cc +++ b/src/video/qtopia/SDL_sysevents.cc @@ -31,239 +31,242 @@ #include "SDL_lowvideo.h" #include "SDL_timer.h" -extern "C" { +extern "C" +{ #include "../../events/SDL_sysevents.h" #include "../../events/SDL_events_c.h" #include "SDL_sysevents_c.h" - // static SDLKey keymap[128]; + // static SDLKey keymap[128]; /* This is special because we know it will be run in a loop in a separate thread. Normally this function should loop as long as there are input states changing, i.e. new events arriving. */ -void QT_PumpEvents(_THIS) -{ - if(!qApp) { - return; - } - // printf("processing events: %p\n", qApp); - //qApp->processOneEvent(); // wait for a event - qApp->processEvents(); // and process all outstanding ones + void QT_PumpEvents(_THIS) + { + if (!qApp) { + return; + } + // printf("processing events: %p\n", qApp); + //qApp->processOneEvent(); // wait for a event + qApp->processEvents(); // and process all outstanding ones #if 0 - BView *view; - BRect bounds; - BPoint point; - uint32 buttons; - const uint32 button_masks[3] = { - B_PRIMARY_MOUSE_BUTTON, - B_TERTIARY_MOUSE_BUTTON, - B_SECONDARY_MOUSE_BUTTON, - }; - unsigned int i, j; + BView *view; + BRect bounds; + BPoint point; + uint32 buttons; + const uint32 button_masks[3] = { + B_PRIMARY_MOUSE_BUTTON, + B_TERTIARY_MOUSE_BUTTON, + B_SECONDARY_MOUSE_BUTTON, + }; + unsigned int i, j; - /* Check out the mouse buttons and position (slight race condition) */ - if ( SDL_Win->Lock() ) { - /* Don't do anything if we have no view */ - view = SDL_Win->View(); - if ( ! view ) { - SDL_Win->Unlock(); - return; - } - bounds = view->Bounds(); - /* Get new input state, if still active */ - if ( SDL_Win->IsActive() ) { - key_flip = !key_flip; - get_key_info(&keyinfo[key_flip]); - view->GetMouse(&point, &buttons, true); - } else { - key_flip = key_flip; - point = last_point; - buttons = last_buttons; - } - SDL_Win->Unlock(); - } else { - return; - } + /* Check out the mouse buttons and position (slight race condition) */ + if (SDL_Win->Lock()) { + /* Don't do anything if we have no view */ + view = SDL_Win->View(); + if (!view) { + SDL_Win->Unlock(); + return; + } + bounds = view->Bounds(); + /* Get new input state, if still active */ + if (SDL_Win->IsActive()) { + key_flip = !key_flip; + get_key_info(&keyinfo[key_flip]); + view->GetMouse(&point, &buttons, true); + } else { + key_flip = key_flip; + point = last_point; + buttons = last_buttons; + } + SDL_Win->Unlock(); + } else { + return; + } - /* If our view is active, we'll find key changes here */ - if ( SDL_memcmp(keyinfo[0].key_states, keyinfo[1].key_states, 16) != 0 ) { - for ( i=0; i<16; ++i ) { - Uint8 new_state, transition; + /* If our view is active, we'll find key changes here */ + if (SDL_memcmp(keyinfo[0].key_states, keyinfo[1].key_states, 16) != 0) { + for (i = 0; i < 16; ++i) { + Uint8 new_state, transition; - new_state = keyinfo[key_flip].key_states[i]; - transition = keyinfo[!key_flip].key_states[i] ^ - keyinfo[ key_flip].key_states[i]; - for ( j=0; j<8; ++j ) { - if ( transition&0x80 ) - QueueKey(i*8+j, new_state&0x80); - transition <<= 1; - new_state <<= 1; - } - } - } + new_state = keyinfo[key_flip].key_states[i]; + transition = keyinfo[!key_flip].key_states[i] ^ + keyinfo[key_flip].key_states[i]; + for (j = 0; j < 8; ++j) { + if (transition & 0x80) + QueueKey(i * 8 + j, new_state & 0x80); + transition <<= 1; + new_state <<= 1; + } + } + } - /* We check keyboard, but not mouse if mouse isn't in window */ - if ( ! bounds.Contains(point) ) { - /* Mouse moved outside our view? */ - if ( SDL_GetAppState() & SDL_APPMOUSEFOCUS ) { - SDL_PrivateAppActive(0, SDL_APPMOUSEFOCUS); - be_app->SetCursor(B_HAND_CURSOR); - } - return; - } - /* Has the mouse moved back into our view? */ - if ( ! (SDL_GetAppState() & SDL_APPMOUSEFOCUS) ) { - /* Reset the B_HAND_CURSOR to our own */ - SDL_PrivateAppActive(1, SDL_APPMOUSEFOCUS); - SDL_SetCursor(NULL); - } + /* We check keyboard, but not mouse if mouse isn't in window */ + if (!bounds.Contains(point)) { + /* Mouse moved outside our view? */ + if (SDL_GetAppState() & SDL_APPMOUSEFOCUS) { + SDL_PrivateAppActive(0, SDL_APPMOUSEFOCUS); + be_app->SetCursor(B_HAND_CURSOR); + } + return; + } + /* Has the mouse moved back into our view? */ + if (!(SDL_GetAppState() & SDL_APPMOUSEFOCUS)) { + /* Reset the B_HAND_CURSOR to our own */ + SDL_PrivateAppActive(1, SDL_APPMOUSEFOCUS); + SDL_SetCursor(NULL); + } - /* Check for mouse motion */ - if ( point != last_point ) { - int x, y; + /* Check for mouse motion */ + if (point != last_point) { + int x, y; - SDL_Win->GetXYOffset(x, y); - x = (int)point.x - x; - y = (int)point.y - y; - SDL_PrivateMouseMotion(0, 0, x, y); - } - last_point = point; + SDL_Win->GetXYOffset(x, y); + x = (int) point.x - x; + y = (int) point.y - y; + SDL_PrivateMouseMotion(0, 0, x, y); + } + last_point = point; - /* Add any mouse button events */ - for ( i=0; isetMousePos(QPoint(x, y)); -} - -}; /* Extern C */ + struct WMcursor + { + char *bits; + }; + WMcursor *QT_CreateWMCursor(_THIS, + Uint8 * data, Uint8 * mask, int w, int h, + int hot_x, int hot_y) + { + static WMcursor dummy; + dummy.bits = 0; + return &dummy; + } + + int QT_ShowWMCursor(_THIS, WMcursor * cursor) + { + return 1; + } + + void QT_FreeWMCursor(_THIS, WMcursor * cursor) + { + } + + void QT_WarpWMCursor(_THIS, Uint16 x, Uint16 y) + { + SDL_Win->setMousePos(QPoint(x, y)); + } + +}; /* Extern C */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/qtopia/SDL_sysmouse_c.h b/src/video/qtopia/SDL_sysmouse_c.h index 73202fca8..e68bc1a6c 100644 --- a/src/video/qtopia/SDL_sysmouse_c.h +++ b/src/video/qtopia/SDL_sysmouse_c.h @@ -24,9 +24,10 @@ #include "SDL_lowvideo.h" /* Functions to be exported */ -extern void QT_FreeWMCursor(_THIS, WMcursor *cursor); +extern void QT_FreeWMCursor(_THIS, WMcursor * cursor); extern WMcursor *QT_CreateWMCursor(_THIS, - Uint8 *data, Uint8 *mask, int w, int h, int hot_x, int hot_y); -extern int QT_ShowWMCursor(_THIS, WMcursor *cursor); + Uint8 * data, Uint8 * mask, int w, int h, + int hot_x, int hot_y); +extern int QT_ShowWMCursor(_THIS, WMcursor * cursor); extern void QT_WarpWMCursor(_THIS, Uint16 x, Uint16 y); - +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/qtopia/SDL_sysvideo.cc b/src/video/qtopia/SDL_sysvideo.cc index c556d79d3..0fde7271e 100644 --- a/src/video/qtopia/SDL_sysvideo.cc +++ b/src/video/qtopia/SDL_sysvideo.cc @@ -32,7 +32,8 @@ #include "SDL_QWin.h" -extern "C" { +extern "C" +{ #include "../SDL_sysvideo.h" #include "../../events/SDL_events_c.h" @@ -41,363 +42,373 @@ extern "C" { #include "SDL_syswm_c.h" #include "SDL_lowvideo.h" - //#define QTOPIA_DEBUG -#define QT_HIDDEN_SIZE 32 /* starting hidden window size */ + //#define QTOPIA_DEBUG +#define QT_HIDDEN_SIZE 32 /* starting hidden window size */ - /* Name of the environment variable used to invert the screen rotation or not: - Possible values: - !=0 : Screen is 270° rotated - 0: Screen is 90° rotated*/ + /* Name of the environment variable used to invert the screen rotation or not: + Possible values: + !=0 : Screen is 270° rotated + 0: Screen is 90° rotated */ #define SDL_QT_ROTATION_ENV_NAME "SDL_QT_INVERT_ROTATION" - - /* Initialization/Query functions */ - static int QT_VideoInit(_THIS, SDL_PixelFormat *vformat); - static SDL_Rect **QT_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags); - static SDL_Surface *QT_SetVideoMode(_THIS, SDL_Surface *current, int width, int height, int bpp, Uint32 flags); - static void QT_UpdateMouse(_THIS); - static int QT_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color *colors); - static void QT_VideoQuit(_THIS); - - /* Hardware surface functions */ - static int QT_AllocHWSurface(_THIS, SDL_Surface *surface); - static int QT_LockHWSurface(_THIS, SDL_Surface *surface); - static void QT_UnlockHWSurface(_THIS, SDL_Surface *surface); - static void QT_FreeHWSurface(_THIS, SDL_Surface *surface); - - static int QT_ToggleFullScreen(_THIS, int fullscreen); - - static int QT_IconifyWindow(_THIS); - static SDL_GrabMode QT_GrabInput(_THIS, SDL_GrabMode mode); - - /* FB driver bootstrap functions */ - - static int QT_Available(void) - { - return(1); - } - - static void QT_DeleteDevice(SDL_VideoDevice *device) - { - SDL_free(device->hidden); - SDL_free(device); - } - - static SDL_VideoDevice *QT_CreateDevice(int devindex) - { - SDL_VideoDevice *device; - - /* Initialize all variables that we clean on shutdown */ - device = (SDL_VideoDevice *)SDL_malloc(sizeof(SDL_VideoDevice)); - if ( device ) { - SDL_memset(device, 0, (sizeof *device)); - device->hidden = (struct SDL_PrivateVideoData *) - SDL_malloc((sizeof *device->hidden)); + + /* Initialization/Query functions */ + static int QT_VideoInit(_THIS, SDL_PixelFormat * vformat); + static SDL_Rect **QT_ListModes(_THIS, SDL_PixelFormat * format, + Uint32 flags); + static SDL_Surface *QT_SetVideoMode(_THIS, SDL_Surface * current, + int width, int height, int bpp, + Uint32 flags); + static void QT_UpdateMouse(_THIS); + static int QT_SetColors(_THIS, int firstcolor, int ncolors, + SDL_Color * colors); + static void QT_VideoQuit(_THIS); + + /* Hardware surface functions */ + static int QT_AllocHWSurface(_THIS, SDL_Surface * surface); + static int QT_LockHWSurface(_THIS, SDL_Surface * surface); + static void QT_UnlockHWSurface(_THIS, SDL_Surface * surface); + static void QT_FreeHWSurface(_THIS, SDL_Surface * surface); + + static int QT_ToggleFullScreen(_THIS, int fullscreen); + + static int QT_IconifyWindow(_THIS); + static SDL_GrabMode QT_GrabInput(_THIS, SDL_GrabMode mode); + + /* FB driver bootstrap functions */ + + static int QT_Available(void) + { + return (1); } - if ( (device == NULL) || (device->hidden == NULL) ) { - SDL_OutOfMemory(); - if ( device ) { - SDL_free(device); - } - return(0); + + static void QT_DeleteDevice(SDL_VideoDevice * device) + { + SDL_free(device->hidden); + SDL_free(device); } - SDL_memset(device->hidden, 0, (sizeof *device->hidden)); - - /* Set the function pointers */ - device->VideoInit = QT_VideoInit; - device->ListModes = QT_ListModes; - device->SetVideoMode = QT_SetVideoMode; - device->UpdateMouse = QT_UpdateMouse; - device->SetColors = QT_SetColors; - device->UpdateRects = NULL; - device->VideoQuit = QT_VideoQuit; - device->AllocHWSurface = QT_AllocHWSurface; - device->CheckHWBlit = NULL; - device->FillHWRect = NULL; - device->SetHWColorKey = NULL; - device->SetHWAlpha = NULL; - device->LockHWSurface = QT_LockHWSurface; - device->UnlockHWSurface = QT_UnlockHWSurface; - device->FlipHWSurface = NULL; - device->FreeHWSurface = QT_FreeHWSurface; - device->SetIcon = NULL; - device->SetCaption = QT_SetWMCaption; - device->IconifyWindow = QT_IconifyWindow; - device->GrabInput = QT_GrabInput; - device->GetWMInfo = NULL; - device->FreeWMCursor = QT_FreeWMCursor; - device->CreateWMCursor = QT_CreateWMCursor; - device->ShowWMCursor = QT_ShowWMCursor; - device->WarpWMCursor = QT_WarpWMCursor; - device->InitOSKeymap = QT_InitOSKeymap; - device->PumpEvents = QT_PumpEvents; - - device->free = QT_DeleteDevice; - device->ToggleFullScreen = QT_ToggleFullScreen; - - /* Set the driver flags */ - device->handles_any_size = 0; - - return device; - } - - VideoBootStrap Qtopia_bootstrap = { - "qtopia", "Qtopia / QPE graphics", - QT_Available, QT_CreateDevice - }; - - /* Function to sort the display_list */ - static int CompareModes(const void *A, const void *B) - { -#if 0 - const display_mode *a = (display_mode *)A; - const display_mode *b = (display_mode *)B; - - if ( a->space == b->space ) { - return((b->virtual_width*b->virtual_height)- - (a->virtual_width*a->virtual_height)); - } else { - return(ColorSpaceToBitsPerPixel(b->space)- - ColorSpaceToBitsPerPixel(a->space)); + + static SDL_VideoDevice *QT_CreateDevice(int devindex) + { + SDL_VideoDevice *device; + + /* Initialize all variables that we clean on shutdown */ + device = (SDL_VideoDevice *) SDL_malloc(sizeof(SDL_VideoDevice)); + if (device) { + SDL_memset(device, 0, (sizeof *device)); + device->hidden = (struct SDL_PrivateVideoData *) + SDL_malloc((sizeof *device->hidden)); + } + if ((device == NULL) || (device->hidden == NULL)) { + SDL_OutOfMemory(); + if (device) { + SDL_free(device); + } + return (0); + } + SDL_memset(device->hidden, 0, (sizeof *device->hidden)); + + /* Set the function pointers */ + device->VideoInit = QT_VideoInit; + device->ListModes = QT_ListModes; + device->SetVideoMode = QT_SetVideoMode; + device->UpdateMouse = QT_UpdateMouse; + device->SetColors = QT_SetColors; + device->UpdateRects = NULL; + device->VideoQuit = QT_VideoQuit; + device->AllocHWSurface = QT_AllocHWSurface; + device->CheckHWBlit = NULL; + device->FillHWRect = NULL; + device->SetHWColorKey = NULL; + device->SetHWAlpha = NULL; + device->LockHWSurface = QT_LockHWSurface; + device->UnlockHWSurface = QT_UnlockHWSurface; + device->FlipHWSurface = NULL; + device->FreeHWSurface = QT_FreeHWSurface; + device->SetIcon = NULL; + device->SetCaption = QT_SetWMCaption; + device->IconifyWindow = QT_IconifyWindow; + device->GrabInput = QT_GrabInput; + device->GetWMInfo = NULL; + device->FreeWMCursor = QT_FreeWMCursor; + device->CreateWMCursor = QT_CreateWMCursor; + device->ShowWMCursor = QT_ShowWMCursor; + device->WarpWMCursor = QT_WarpWMCursor; + device->InitOSKeymap = QT_InitOSKeymap; + device->PumpEvents = QT_PumpEvents; + + device->free = QT_DeleteDevice; + device->ToggleFullScreen = QT_ToggleFullScreen; + + /* Set the driver flags */ + device->handles_any_size = 0; + + return device; } + + VideoBootStrap Qtopia_bootstrap = { + "qtopia", "Qtopia / QPE graphics", + QT_Available, QT_CreateDevice + }; + + /* Function to sort the display_list */ + static int CompareModes(const void *A, const void *B) + { +#if 0 + const display_mode *a = (display_mode *) A; + const display_mode *b = (display_mode *) B; + + if (a->space == b->space) { + return ((b->virtual_width * b->virtual_height) - + (a->virtual_width * a->virtual_height)); + } else { + return (ColorSpaceToBitsPerPixel(b->space) - + ColorSpaceToBitsPerPixel(a->space)); + } #endif - return 0; - } - - /* Yes, this isn't the fastest it could be, but it works nicely */ - static int QT_AddMode(_THIS, int index, unsigned int w, unsigned int h) - { - SDL_Rect *mode; - int i; - int next_mode; - - /* Check to see if we already have this mode */ - if ( SDL_nummodes[index] > 0 ) { - for ( i=SDL_nummodes[index]-1; i >= 0; --i ) { - mode = SDL_modelist[index][i]; - if ( (mode->w == w) && (mode->h == h) ) { - return(0); - } - } + return 0; } - /* Set up the new video mode rectangle */ - mode = (SDL_Rect *)SDL_malloc(sizeof *mode); - if ( mode == NULL ) { - SDL_OutOfMemory(); - return(-1); - } - mode->x = 0; - mode->y = 0; - mode->w = w; - mode->h = h; + /* Yes, this isn't the fastest it could be, but it works nicely */ + static int QT_AddMode(_THIS, int index, unsigned int w, unsigned int h) + { + SDL_Rect *mode; + int i; + int next_mode; + + /* Check to see if we already have this mode */ + if (SDL_nummodes[index] > 0) { + for (i = SDL_nummodes[index] - 1; i >= 0; --i) { + mode = SDL_modelist[index][i]; + if ((mode->w == w) && (mode->h == h)) { + return (0); + } + } + } + + /* Set up the new video mode rectangle */ + mode = (SDL_Rect *) SDL_malloc(sizeof *mode); + if (mode == NULL) { + SDL_OutOfMemory(); + return (-1); + } + mode->x = 0; + mode->y = 0; + mode->w = w; + mode->h = h; #ifdef QTOPIA_DEBUG - fprintf(stderr, "Adding mode %dx%d at %d bytes per pixel\n", w, h, index+1); + fprintf(stderr, "Adding mode %dx%d at %d bytes per pixel\n", w, h, + index + 1); #endif - /* Allocate the new list of modes, and fill in the new mode */ - next_mode = SDL_nummodes[index]; - SDL_modelist[index] = (SDL_Rect **) - SDL_realloc(SDL_modelist[index], (1+next_mode+1)*sizeof(SDL_Rect *)); - if ( SDL_modelist[index] == NULL ) { - SDL_OutOfMemory(); - SDL_nummodes[index] = 0; - SDL_free(mode); - return(-1); + /* Allocate the new list of modes, and fill in the new mode */ + next_mode = SDL_nummodes[index]; + SDL_modelist[index] = (SDL_Rect **) + SDL_realloc(SDL_modelist[index], + (1 + next_mode + 1) * sizeof(SDL_Rect *)); + if (SDL_modelist[index] == NULL) { + SDL_OutOfMemory(); + SDL_nummodes[index] = 0; + SDL_free(mode); + return (-1); + } + SDL_modelist[index][next_mode] = mode; + SDL_modelist[index][next_mode + 1] = NULL; + SDL_nummodes[index]++; + + return (0); + } + + int QT_VideoInit(_THIS, SDL_PixelFormat * vformat) + { + /* Initialize the QPE Application */ + /* Determine the screen depth */ + vformat->BitsPerPixel = QPixmap::defaultDepth(); + + // For now we hardcode the current depth because anything else + // might as well be emulated by SDL rather than by Qtopia. + + QSize desktop_size = qApp->desktop()->size(); + QT_AddMode(_this, ((vformat->BitsPerPixel + 7) / 8) - 1, + desktop_size.width(), desktop_size.height()); + QT_AddMode(_this, ((vformat->BitsPerPixel + 7) / 8) - 1, + desktop_size.height(), desktop_size.width()); + + /* Determine the current screen size */ + this->info.current_w = desktop_size.width(); + this->info.current_h = desktop_size.height(); + + /* Create the window / widget */ + SDL_Win = new SDL_QWin(QSize(QT_HIDDEN_SIZE, QT_HIDDEN_SIZE)); + ((QPEApplication *) qApp)->showMainWidget(SDL_Win); + /* Fill in some window manager capabilities */ + _this->info.wm_available = 0; + + /* We're done! */ + return (0); + } + + /* We support any dimension at our bit-depth */ + SDL_Rect **QT_ListModes(_THIS, SDL_PixelFormat * format, Uint32 flags) + { + SDL_Rect **modes; + + modes = ((SDL_Rect **) 0); + if ((flags & SDL_FULLSCREEN) == SDL_FULLSCREEN) { + modes = SDL_modelist[((format->BitsPerPixel + 7) / 8) - 1]; + } else { + if (format->BitsPerPixel == _this->screen->format->BitsPerPixel) { + modes = ((SDL_Rect **) - 1); + } + } + return (modes); + } + + /* Various screen update functions available */ + static void QT_NormalUpdate(_THIS, int numrects, SDL_Rect * rects); + + + static int QT_SetFullScreen(_THIS, SDL_Surface * screen, int fullscreen) + { + return -1; } - SDL_modelist[index][next_mode] = mode; - SDL_modelist[index][next_mode+1] = NULL; - SDL_nummodes[index]++; - - return(0); - } - - int QT_VideoInit(_THIS, SDL_PixelFormat *vformat) - { - /* Initialize the QPE Application */ - /* Determine the screen depth */ - vformat->BitsPerPixel = QPixmap::defaultDepth(); - - // For now we hardcode the current depth because anything else - // might as well be emulated by SDL rather than by Qtopia. - - QSize desktop_size = qApp->desktop()->size(); - QT_AddMode(_this, ((vformat->BitsPerPixel+7)/8)-1, - desktop_size.width(), desktop_size.height()); - QT_AddMode(_this, ((vformat->BitsPerPixel+7)/8)-1, - desktop_size.height(), desktop_size.width()); - - /* Determine the current screen size */ - this->info.current_w = desktop_size.width(); - this->info.current_h = desktop_size.height(); - - /* Create the window / widget */ - SDL_Win = new SDL_QWin(QSize(QT_HIDDEN_SIZE, QT_HIDDEN_SIZE)); - ((QPEApplication*)qApp)->showMainWidget(SDL_Win); - /* Fill in some window manager capabilities */ - _this->info.wm_available = 0; - - /* We're done! */ - return(0); - } - - /* We support any dimension at our bit-depth */ - SDL_Rect **QT_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags) - { - SDL_Rect **modes; - - modes = ((SDL_Rect **)0); - if ( (flags & SDL_FULLSCREEN) == SDL_FULLSCREEN ) { - modes = SDL_modelist[((format->BitsPerPixel+7)/8)-1]; - } else { - if ( format->BitsPerPixel == - _this->screen->format->BitsPerPixel ) { - modes = ((SDL_Rect **)-1); - } + + static int QT_ToggleFullScreen(_THIS, int fullscreen) + { + return -1; + } + + /* FIXME: check return values and cleanup here */ + SDL_Surface *QT_SetVideoMode(_THIS, SDL_Surface * current, + int width, int height, int bpp, Uint32 flags) + { + + QImage *qimage; + QSize desktop_size = qApp->desktop()->size(); + + + current->flags = 0; //SDL_FULLSCREEN; // We always run fullscreen. + + if (width <= desktop_size.width() + && height <= desktop_size.height()) { + current->w = desktop_size.width(); + current->h = desktop_size.height(); + } else if (width <= desktop_size.height() + && height <= desktop_size.width()) { + // Landscape mode + char *envString = SDL_getenv(SDL_QT_ROTATION_ENV_NAME); + int envValue = envString ? atoi(envString) : 0; + screenRotation = + envValue ? SDL_QT_ROTATION_270 : SDL_QT_ROTATION_90; + current->h = desktop_size.width(); + current->w = desktop_size.height(); + } else { + SDL_SetError("Unsupported resolution, %dx%d\n", width, height); + } + if (flags & SDL_INTERNALOPENGL) { + SDL_SetError("OpenGL not supported"); + return (NULL); + } + /* Create the QImage framebuffer */ + qimage = new QImage(current->w, current->h, bpp); + if (qimage->isNull()) { + SDL_SetError("Couldn't create screen bitmap"); + delete qimage; + return (NULL); + } + current->pitch = qimage->bytesPerLine(); + current->pixels = (void *) qimage->bits(); + SDL_Win->setImage(qimage); + _this->UpdateRects = QT_NormalUpdate; + SDL_Win->setFullscreen(true); + /* We're done */ + return (current); + } + + /* Update the current mouse state and position */ + void QT_UpdateMouse(_THIS) + { + QPoint point(-1, -1); + if (SDL_Win->isActiveWindow()) { + point = SDL_Win->mousePos(); + } + + if ((point.x() >= 0) && (point.x() < SDL_VideoSurface->w) && + (point.y() >= 0) && (point.y() < SDL_VideoSurface->h)) { + SDL_PrivateAppActive(1, SDL_APPMOUSEFOCUS); + SDL_PrivateMouseMotion(0, 0, + (Sint16) point.x(), (Sint16) point.y()); + } else { + SDL_PrivateAppActive(0, SDL_APPMOUSEFOCUS); + } + } + + /* We don't actually allow hardware surfaces other than the main one */ + static int QT_AllocHWSurface(_THIS, SDL_Surface * surface) + { + return (-1); + } + static void QT_FreeHWSurface(_THIS, SDL_Surface * surface) + { + return; } - return(modes); - } - - /* Various screen update functions available */ - static void QT_NormalUpdate(_THIS, int numrects, SDL_Rect *rects); - - - static int QT_SetFullScreen(_THIS, SDL_Surface *screen, int fullscreen) - { - return -1; - } - - static int QT_ToggleFullScreen(_THIS, int fullscreen) - { - return -1; - } - - /* FIXME: check return values and cleanup here */ - SDL_Surface *QT_SetVideoMode(_THIS, SDL_Surface *current, - int width, int height, int bpp, Uint32 flags) - { - - QImage *qimage; - QSize desktop_size = qApp->desktop()->size(); - - - current->flags = 0; //SDL_FULLSCREEN; // We always run fullscreen. - - if(width <= desktop_size.width() - && height <= desktop_size.height()) { - current->w = desktop_size.width(); - current->h = desktop_size.height(); - } else if(width <= desktop_size.height() && height <= desktop_size.width()) { - // Landscape mode - char * envString = SDL_getenv(SDL_QT_ROTATION_ENV_NAME); - int envValue = envString ? atoi(envString) : 0; - screenRotation = envValue ? SDL_QT_ROTATION_270 : SDL_QT_ROTATION_90; - current->h = desktop_size.width(); - current->w = desktop_size.height(); - } else { - SDL_SetError("Unsupported resolution, %dx%d\n", width, height); + static int QT_LockHWSurface(_THIS, SDL_Surface * surface) + { + return (0); } - if ( flags & SDL_OPENGL ) { - SDL_SetError("OpenGL not supported"); - return(NULL); - } - /* Create the QImage framebuffer */ - qimage = new QImage(current->w, current->h, bpp); - if (qimage->isNull()) { - SDL_SetError("Couldn't create screen bitmap"); - delete qimage; - return(NULL); + static void QT_UnlockHWSurface(_THIS, SDL_Surface * surface) + { + return; } - current->pitch = qimage->bytesPerLine(); - current->pixels = (void *)qimage->bits(); - SDL_Win->setImage(qimage); - _this->UpdateRects = QT_NormalUpdate; - SDL_Win->setFullscreen(true); - /* We're done */ - return(current); - } - - /* Update the current mouse state and position */ - void QT_UpdateMouse(_THIS) - { - QPoint point(-1, -1); - if ( SDL_Win->isActiveWindow() ) { - point = SDL_Win->mousePos(); + + static void QT_NormalUpdate(_THIS, int numrects, SDL_Rect * rects) + { + if (SDL_Win->lockScreen()) { + for (int i = 0; i < numrects; ++i) { + QRect rect(rects[i].x, rects[i].y, rects[i].w, rects[i].h); + SDL_Win->repaintRect(rect); + } + SDL_Win->unlockScreen(); + } + } + /* Is the system palette settable? */ + int QT_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color * colors) + { + return -1; } - - if ( (point.x() >= 0) && (point.x() < SDL_VideoSurface->w) && - (point.y() >= 0) && (point.y() < SDL_VideoSurface->h) ) { - SDL_PrivateAppActive(1, SDL_APPMOUSEFOCUS); - SDL_PrivateMouseMotion(0, 0, - (Sint16)point.x(), (Sint16)point.y()); - } else { - SDL_PrivateAppActive(0, SDL_APPMOUSEFOCUS); + + void QT_VideoQuit(_THIS) + { + // This is dumb, but if I free this, the app doesn't exit correctly. + // Of course, this will leak memory if init video is done more than once. + // Sucks but such is life. + + // -- David Hedbor + // delete SDL_Win; + // SDL_Win = 0; + _this->screen->pixels = NULL; + QT_GrabInput(_this, SDL_GRAB_OFF); } - } - - /* We don't actually allow hardware surfaces other than the main one */ - static int QT_AllocHWSurface(_THIS, SDL_Surface *surface) - { - return(-1); - } - static void QT_FreeHWSurface(_THIS, SDL_Surface *surface) - { - return; - } - static int QT_LockHWSurface(_THIS, SDL_Surface *surface) - { - return(0); - } - static void QT_UnlockHWSurface(_THIS, SDL_Surface *surface) - { - return; - } - - static void QT_NormalUpdate(_THIS, int numrects, SDL_Rect *rects) - { - if(SDL_Win->lockScreen()) { - for(int i=0; irepaintRect(rect); - } - SDL_Win->unlockScreen(); + + static int QT_IconifyWindow(_THIS) + { + SDL_Win->hide(); + + return true; } - } - /* Is the system palette settable? */ - int QT_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color *colors) - { - return -1; - } - - void QT_VideoQuit(_THIS) - { - // This is dumb, but if I free this, the app doesn't exit correctly. - // Of course, this will leak memory if init video is done more than once. - // Sucks but such is life. - - // -- David Hedbor - // delete SDL_Win; - // SDL_Win = 0; - _this->screen->pixels = NULL; - QT_GrabInput(_this, SDL_GRAB_OFF); - } - - static int QT_IconifyWindow(_THIS) { - SDL_Win->hide(); - - return true; - } - - static SDL_GrabMode QT_GrabInput(_THIS, SDL_GrabMode mode) { - if(mode == SDL_GRAB_OFF) { - QPEApplication::grabKeyboard(); - qApp->processEvents(); - QPEApplication::ungrabKeyboard(); - } else { - QPEApplication::grabKeyboard(); + + static SDL_GrabMode QT_GrabInput(_THIS, SDL_GrabMode mode) + { + if (mode == SDL_GRAB_OFF) { + QPEApplication::grabKeyboard(); + qApp->processEvents(); + QPEApplication::ungrabKeyboard(); + } else { + QPEApplication::grabKeyboard(); + } + qApp->processEvents(); + return mode; } - qApp->processEvents(); - return mode; - } - -}; /* Extern C */ + +}; /* Extern C */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/qtopia/SDL_syswm.cc b/src/video/qtopia/SDL_syswm.cc index 0385dbb38..8893d25b1 100644 --- a/src/video/qtopia/SDL_syswm.cc +++ b/src/video/qtopia/SDL_syswm.cc @@ -23,13 +23,15 @@ #include "SDL_QWin.h" -extern "C" { +extern "C" +{ #include "SDL_syswm_c.h" -void QT_SetWMCaption(_THIS, const char *title, const char *icon) -{ - SDL_Win->setCaption(title); -} + void QT_SetWMCaption(_THIS, const char *title, const char *icon) + { + SDL_Win->setCaption(title); + } -}; /* Extern C */ +}; /* Extern C */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/qtopia/SDL_syswm_c.h b/src/video/qtopia/SDL_syswm_c.h index 031269fe1..00e7d53ff 100644 --- a/src/video/qtopia/SDL_syswm_c.h +++ b/src/video/qtopia/SDL_syswm_c.h @@ -25,4 +25,4 @@ /* Functions to be exported */ extern void QT_SetWMCaption(_THIS, const char *title, const char *icon); - +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/quartz/CGS.h b/src/video/quartz/CGS.h index 234ff771c..308cb06d7 100644 --- a/src/video/quartz/CGS.h +++ b/src/video/quartz/CGS.h @@ -49,36 +49,37 @@ #define kCGSWindowLevelDesktop -2147483648 */ -typedef CGError CGSError; -typedef long CGSWindowCount; -typedef void * CGSConnectionID; -typedef int CGSWindowID; -typedef CGSWindowID* CGSWindowIDList; +typedef CGError CGSError; +typedef long CGSWindowCount; +typedef void *CGSConnectionID; +typedef int CGSWindowID; +typedef CGSWindowID *CGSWindowIDList; typedef CGWindowLevel CGSWindowLevel; -typedef NSRect CGSRect; +typedef NSRect CGSRect; -extern CGSConnectionID _CGSDefaultConnection (); +extern CGSConnectionID _CGSDefaultConnection(); -extern CGSError CGSGetOnScreenWindowList (CGSConnectionID cid, - CGSConnectionID owner, - CGSWindowCount listCapacity, - CGSWindowIDList list, - CGSWindowCount *listCount); +extern CGSError CGSGetOnScreenWindowList(CGSConnectionID cid, + CGSConnectionID owner, + CGSWindowCount listCapacity, + CGSWindowIDList list, + CGSWindowCount * listCount); -extern CGSError CGSGetScreenRectForWindow (CGSConnectionID cid, - CGSWindowID wid, - CGSRect *rect); +extern CGSError CGSGetScreenRectForWindow(CGSConnectionID cid, + CGSWindowID wid, CGSRect * rect); -extern CGWindowLevel CGSGetWindowLevel (CGSConnectionID cid, - CGSWindowID wid, - CGSWindowLevel *level); +extern CGWindowLevel CGSGetWindowLevel(CGSConnectionID cid, + CGSWindowID wid, + CGSWindowLevel * level); -extern CGSError CGSDisplayHWFill (CGDirectDisplayID id, unsigned int x, unsigned int y, - unsigned int w, unsigned int h, unsigned int color); +extern CGSError CGSDisplayHWFill(CGDirectDisplayID id, unsigned int x, + unsigned int y, unsigned int w, + unsigned int h, unsigned int color); -extern CGSError CGSDisplayCanHWFill (CGDirectDisplayID id); +extern CGSError CGSDisplayCanHWFill(CGDirectDisplayID id); -extern CGSError CGSGetMouseEnabledFlags (CGSConnectionID cid, CGSWindowID wid, int *flags); - -int CGSDisplayHWSync (CGDirectDisplayID id); +extern CGSError CGSGetMouseEnabledFlags(CGSConnectionID cid, CGSWindowID wid, + int *flags); +int CGSDisplayHWSync(CGDirectDisplayID id); +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/quartz/SDL_QuartzEvents.m b/src/video/quartz/SDL_QuartzEvents.m index b18598c66..db31b5737 100644 --- a/src/video/quartz/SDL_QuartzEvents.m +++ b/src/video/quartz/SDL_QuartzEvents.m @@ -23,8 +23,8 @@ #include "SDL_QuartzVideo.h" -#include /* For wake from sleep detection */ -#include /* For wake from sleep detection */ +#include /* For wake from sleep detection */ +#include /* For wake from sleep detection */ #include "SDL_QuartzKeys.h" /* @@ -39,38 +39,40 @@ * on systems without these, I will define if they don't exist. */ #ifndef NX_DEVICERCTLKEYMASK - #define NX_DEVICELCTLKEYMASK 0x00000001 +#define NX_DEVICELCTLKEYMASK 0x00000001 #endif #ifndef NX_DEVICELSHIFTKEYMASK - #define NX_DEVICELSHIFTKEYMASK 0x00000002 +#define NX_DEVICELSHIFTKEYMASK 0x00000002 #endif #ifndef NX_DEVICERSHIFTKEYMASK - #define NX_DEVICERSHIFTKEYMASK 0x00000004 +#define NX_DEVICERSHIFTKEYMASK 0x00000004 #endif #ifndef NX_DEVICELCMDKEYMASK - #define NX_DEVICELCMDKEYMASK 0x00000008 +#define NX_DEVICELCMDKEYMASK 0x00000008 #endif #ifndef NX_DEVICERCMDKEYMASK - #define NX_DEVICERCMDKEYMASK 0x00000010 +#define NX_DEVICERCMDKEYMASK 0x00000010 #endif #ifndef NX_DEVICELALTKEYMASK - #define NX_DEVICELALTKEYMASK 0x00000020 +#define NX_DEVICELALTKEYMASK 0x00000020 #endif #ifndef NX_DEVICERALTKEYMASK - #define NX_DEVICERALTKEYMASK 0x00000040 +#define NX_DEVICERALTKEYMASK 0x00000040 #endif #ifndef NX_DEVICERCTLKEYMASK - #define NX_DEVICERCTLKEYMASK 0x00002000 +#define NX_DEVICERCTLKEYMASK 0x00002000 #endif -void QZ_InitOSKeymap (_THIS) { +void +QZ_InitOSKeymap (_THIS) +{ const void *KCHRPtr; UInt32 state; UInt32 value; int i; int world = SDLK_WORLD_0; - for ( i=0; ikeysym map. However, it will not - work very well on international keyboard. Hence we now query MacOS - for its own keymap to adjust our own mapping table. However, this is - basically only useful for ascii char keys. This is also the reason - why we keep the static table, too. + Up there we setup a static scancode->keysym map. However, it will not + work very well on international keyboard. Hence we now query MacOS + for its own keymap to adjust our own mapping table. However, this is + basically only useful for ascii char keys. This is also the reason + why we keep the static table, too. */ /* Get a pointer to the systems cached KCHR */ - KCHRPtr = (void *)GetScriptManagerVariable(smKCHRCache); - if (KCHRPtr) - { + KCHRPtr = (void *) GetScriptManagerVariable (smKCHRCache); + if (KCHRPtr) { /* Loop over all 127 possible scan codes */ - for (i = 0; i < 0x7F; i++) - { + for (i = 0; i < 0x7F; i++) { /* We pretend a clean start to begin with (i.e. no dead keys active */ state = 0; /* Now translate the key code to a key value */ - value = KeyTranslate(KCHRPtr, i, &state) & 0xff; + value = KeyTranslate (KCHRPtr, i, &state) & 0xff; /* If the state become 0, it was a dead key. We need to translate again, - passing in the new state, to get the actual key value */ + passing in the new state, to get the actual key value */ if (state != 0) - value = KeyTranslate(KCHRPtr, i, &state) & 0xff; + value = KeyTranslate (KCHRPtr, i, &state) & 0xff; /* Now we should have an ascii value, or 0. Try to figure out to which SDL symbol it maps */ - if (value >= 128) /* Some non-ASCII char, map it to SDLK_WORLD_* */ + if (value >= 128) /* Some non-ASCII char, map it to SDLK_WORLD_* */ keymap[i] = world++; - else if (value >= 32) /* non-control ASCII char */ + else if (value >= 32) /* non-control ASCII char */ keymap[i] = value; } } /* - The keypad codes are re-setup here, because the loop above cannot - distinguish between a key on the keypad and a regular key. We maybe - could get around this problem in another fashion: NSEvent's flags - include a "NSNumericPadKeyMask" bit; we could check that and modify - the symbol we return on the fly. However, this flag seems to exhibit - some weird behaviour related to the num lock key - */ + The keypad codes are re-setup here, because the loop above cannot + distinguish between a key on the keypad and a regular key. We maybe + could get around this problem in another fashion: NSEvent's flags + include a "NSNumericPadKeyMask" bit; we could check that and modify + the symbol we return on the fly. However, this flag seems to exhibit + some weird behaviour related to the num lock key + */ keymap[QZ_KP0] = SDLK_KP0; keymap[QZ_KP1] = SDLK_KP1; keymap[QZ_KP2] = SDLK_KP2; @@ -246,104 +246,102 @@ void QZ_InitOSKeymap (_THIS) { keymap[QZ_KP_ENTER] = SDLK_KP_ENTER; } -static void QZ_DoKey (_THIS, int state, NSEvent *event) { +static void +QZ_DoKey (_THIS, int state, NSEvent * event) +{ NSString *chars; unsigned int numChars; SDL_keysym key; - + /* - A key event can contain multiple characters, - or no characters at all. In most cases, it - will contain a single character. If it contains - 0 characters, we'll use 0 as the unicode. If it - contains multiple characters, we'll use 0 as - the scancode/keysym. - */ - if (SDL_TranslateUNICODE) { - chars = [ event characters ]; - numChars = [ chars length ]; - } else { - numChars = 0; - } + A key event can contain multiple characters, + or no characters at all. In most cases, it + will contain a single character. If it contains + 0 characters, we'll use 0 as the unicode. If it + contains multiple characters, we'll use 0 as + the scancode/keysym. + */ + chars =[event characters]; + numChars =[chars length]; + + if (numChars == 1) { - if (numChars == 0) { - - key.scancode = [ event keyCode ]; - key.sym = keymap [ key.scancode ]; - key.unicode = 0; - key.mod = KMOD_NONE; + key.scancode =[event keyCode]; + key.sym = keymap[key.scancode]; + key.unicode =[chars characterAtIndex:0]; + key.mod = KMOD_NONE; SDL_PrivateKeyboard (state, &key); - } - else if (numChars == 1) { + } else if (numChars == 0) { - key.scancode = [ event keyCode ]; - key.sym = keymap [ key.scancode ]; - key.unicode = [ chars characterAtIndex:0 ]; - key.mod = KMOD_NONE; + key.scancode =[event keyCode]; + key.sym = keymap[key.scancode]; + key.unicode = 0; + key.mod = KMOD_NONE; SDL_PrivateKeyboard (state, &key); - } - else /* (numChars > 1) */ { - + } else { /* (numChars > 1) */ + + int i; for (i = 0; i < numChars; i++) { key.scancode = 0; - key.sym = 0; - key.unicode = [ chars characterAtIndex:i]; - key.mod = KMOD_NONE; + key.sym = 0; + key.unicode =[chars characterAtIndex:i]; + key.mod = KMOD_NONE; SDL_PrivateKeyboard (state, &key); } } - + if (SDL_getenv ("SDL_ENABLEAPPEVENTS")) - [ NSApp sendEvent:event ]; + [NSApp sendEvent:event]; } /* This is the original behavior, before support was added for * differentiating between left and right versions of the keys. */ -static void QZ_DoUnsidedModifiers (_THIS, unsigned int newMods) { +static void +QZ_DoUnsidedModifiers (_THIS, unsigned int newMods) +{ - const int mapping[] = { SDLK_CAPSLOCK, SDLK_LSHIFT, SDLK_LCTRL, SDLK_LALT, SDLK_LMETA }; + const int mapping[] = + { SDLK_CAPSLOCK, SDLK_LSHIFT, SDLK_LCTRL, SDLK_LALT, SDLK_LMETA }; int i; int bit; SDL_keysym key; - - key.scancode = 0; - key.sym = SDLK_UNKNOWN; - key.unicode = 0; - key.mod = KMOD_NONE; + + key.scancode = 0; + key.sym = SDLK_UNKNOWN; + key.unicode = 0; + key.mod = KMOD_NONE; /* Iterate through the bits, testing each against the current modifiers */ - for (i = 0, bit = NSAlphaShiftKeyMask; bit <= NSCommandKeyMask; bit <<= 1, ++i) { + for (i = 0, bit = NSAlphaShiftKeyMask; bit <= NSCommandKeyMask; + bit <<= 1, ++i) { unsigned int currentMask, newMask; currentMask = current_mods & bit; - newMask = newMods & bit; - - if ( currentMask && - currentMask != newMask ) { /* modifier up event */ - - key.sym = mapping[i]; - /* If this was Caps Lock, we need some additional voodoo to make SDL happy */ - if (bit == NSAlphaShiftKeyMask) - SDL_PrivateKeyboard (SDL_PRESSED, &key); - SDL_PrivateKeyboard (SDL_RELEASED, &key); - } - else if ( newMask && - currentMask != newMask ) { /* modifier down event */ - - key.sym = mapping[i]; - SDL_PrivateKeyboard (SDL_PRESSED, &key); - /* If this was Caps Lock, we need some additional voodoo to make SDL happy */ - if (bit == NSAlphaShiftKeyMask) - SDL_PrivateKeyboard (SDL_RELEASED, &key); + newMask = newMods & bit; + + if (currentMask && currentMask != newMask) { /* modifier up event */ + + key.sym = mapping[i]; + /* If this was Caps Lock, we need some additional voodoo to make SDL happy */ + if (bit == NSAlphaShiftKeyMask) + SDL_PrivateKeyboard (SDL_PRESSED, &key); + SDL_PrivateKeyboard (SDL_RELEASED, &key); + } else if (newMask && currentMask != newMask) { /* modifier down event */ + + key.sym = mapping[i]; + SDL_PrivateKeyboard (SDL_PRESSED, &key); + /* If this was Caps Lock, we need some additional voodoo to make SDL happy */ + if (bit == NSAlphaShiftKeyMask) + SDL_PrivateKeyboard (SDL_RELEASED, &key); } } } @@ -352,62 +350,63 @@ static void QZ_DoUnsidedModifiers (_THIS, unsigned int newMods) { * function reverts back to behavior before the distinction between * sides was made. */ -static void QZ_HandleNonDeviceModifier ( _THIS, unsigned int device_independent_mask, unsigned int newMods, unsigned int key_sym) { +static void +QZ_HandleNonDeviceModifier (_THIS, unsigned int device_independent_mask, + unsigned int newMods, unsigned int key_sym) +{ unsigned int currentMask, newMask; SDL_keysym key; - - key.scancode = 0; - key.sym = key_sym; - key.unicode = 0; - key.mod = KMOD_NONE; - + + key.scancode = 0; + key.sym = key_sym; + key.unicode = 0; + key.mod = KMOD_NONE; + /* Isolate just the bits we care about in the depedent bits so we can * figure out what changed - */ + */ currentMask = current_mods & device_independent_mask; - newMask = newMods & device_independent_mask; - - if ( currentMask && - currentMask != newMask ) { /* modifier up event */ - SDL_PrivateKeyboard (SDL_RELEASED, &key); - } - else if ( newMask && - currentMask != newMask ) { /* modifier down event */ - SDL_PrivateKeyboard (SDL_PRESSED, &key); + newMask = newMods & device_independent_mask; + + if (currentMask && currentMask != newMask) { /* modifier up event */ + SDL_PrivateKeyboard (SDL_RELEASED, &key); + } else if (newMask && currentMask != newMask) { /* modifier down event */ + SDL_PrivateKeyboard (SDL_PRESSED, &key); } } /* This is a helper function for QZ_HandleModifierSide. * This function sets the actual SDL_PrivateKeyboard event. */ -static void QZ_HandleModifierOneSide ( _THIS, unsigned int newMods, - unsigned int key_sym, - unsigned int sided_device_dependent_mask ) { - +static void +QZ_HandleModifierOneSide (_THIS, unsigned int newMods, + unsigned int key_sym, + unsigned int sided_device_dependent_mask) +{ + SDL_keysym key; unsigned int current_dep_mask, new_dep_mask; - - key.scancode = 0; - key.sym = key_sym; - key.unicode = 0; - key.mod = KMOD_NONE; - + + key.scancode = 0; + key.sym = key_sym; + key.unicode = 0; + key.mod = KMOD_NONE; + /* Isolate just the bits we care about in the depedent bits so we can * figure out what changed - */ + */ current_dep_mask = current_mods & sided_device_dependent_mask; - new_dep_mask = newMods & sided_device_dependent_mask; - + new_dep_mask = newMods & sided_device_dependent_mask; + /* We now know that this side bit flipped. But we don't know if * it went pressed to released or released to pressed, so we must * find out which it is. */ - if( new_dep_mask && - current_dep_mask != new_dep_mask ) { + if (new_dep_mask && current_dep_mask != new_dep_mask) { /* Modifier down event */ SDL_PrivateKeyboard (SDL_PRESSED, &key); - } - else /* Modifier up event */ { + } else { /* Modifier up event */ + SDL_PrivateKeyboard (SDL_RELEASED, &key); } } @@ -416,70 +415,79 @@ static void QZ_HandleModifierOneSide ( _THIS, unsigned int newMods, * This function will figure out if the modifier key is the left or right side, * e.g. left-shift vs right-shift. */ -static void QZ_HandleModifierSide ( _THIS, int device_independent_mask, - unsigned int newMods, - unsigned int left_key_sym, - unsigned int right_key_sym, - unsigned int left_device_dependent_mask, - unsigned int right_device_dependent_mask ) { +static void +QZ_HandleModifierSide (_THIS, int device_independent_mask, + unsigned int newMods, + unsigned int left_key_sym, + unsigned int right_key_sym, + unsigned int left_device_dependent_mask, + unsigned int right_device_dependent_mask) +{ unsigned int device_dependent_mask = 0; unsigned int diff_mod = 0; - - device_dependent_mask = left_device_dependent_mask | right_device_dependent_mask; + + device_dependent_mask = + left_device_dependent_mask | right_device_dependent_mask; /* On the basis that the device independent mask is set, but there are * no device dependent flags set, we'll assume that we can't detect this * keyboard and revert to the unsided behavior. */ - if ( (device_dependent_mask & newMods) == 0 ) { + if ((device_dependent_mask & newMods) == 0) { /* Revert to the old behavior */ - QZ_HandleNonDeviceModifier ( this, device_independent_mask, newMods, left_key_sym ); + QZ_HandleNonDeviceModifier (this, device_independent_mask, newMods, + left_key_sym); return; } - + /* XOR the previous state against the new state to see if there's a change */ diff_mod = (device_dependent_mask & current_mods) ^ (device_dependent_mask & newMods); - if ( diff_mod ) { + if (diff_mod) { /* A change in state was found. Isolate the left and right bits * to handle them separately just in case the values can simulataneously * change or if the bits don't both exist. */ - if ( left_device_dependent_mask & diff_mod ) { - QZ_HandleModifierOneSide ( this, newMods, left_key_sym, left_device_dependent_mask ); + if (left_device_dependent_mask & diff_mod) { + QZ_HandleModifierOneSide (this, newMods, left_key_sym, + left_device_dependent_mask); } - if ( right_device_dependent_mask & diff_mod ) { - QZ_HandleModifierOneSide ( this, newMods, right_key_sym, right_device_dependent_mask ); + if (right_device_dependent_mask & diff_mod) { + QZ_HandleModifierOneSide (this, newMods, right_key_sym, + right_device_dependent_mask); } } } - + /* This is a helper function for QZ_DoSidedModifiers. * This function will release a key press in the case that * it is clear that the modifier has been released (i.e. one side * can't still be down). */ -static void QZ_ReleaseModifierSide ( _THIS, - unsigned int device_independent_mask, - unsigned int newMods, - unsigned int left_key_sym, - unsigned int right_key_sym, - unsigned int left_device_dependent_mask, - unsigned int right_device_dependent_mask ) { +static void +QZ_ReleaseModifierSide (_THIS, + unsigned int device_independent_mask, + unsigned int newMods, + unsigned int left_key_sym, + unsigned int right_key_sym, + unsigned int left_device_dependent_mask, + unsigned int right_device_dependent_mask) +{ unsigned int device_dependent_mask = 0; SDL_keysym key; - - key.scancode = 0; - key.sym = SDLK_UNKNOWN; - key.unicode = 0; - key.mod = KMOD_NONE; - - device_dependent_mask = left_device_dependent_mask | right_device_dependent_mask; + + key.scancode = 0; + key.sym = SDLK_UNKNOWN; + key.unicode = 0; + key.mod = KMOD_NONE; + + device_dependent_mask = + left_device_dependent_mask | right_device_dependent_mask; /* On the basis that the device independent mask is set, but there are * no device dependent flags set, we'll assume that we can't detect this * keyboard and revert to the unsided behavior. */ - if ( (device_dependent_mask & current_mods) == 0 ) { + if ((device_dependent_mask & current_mods) == 0) { /* In this case, we can't detect the keyboard, so use the left side * to represent both, and release it. */ @@ -488,19 +496,19 @@ static void QZ_ReleaseModifierSide ( _THIS, return; } - - + + /* * This could have been done in an if-else case because at this point, * we know that all keys have been released when calling this function. * But I'm being paranoid so I want to handle each separately, * so I hope this doesn't cause other problems. */ - if ( left_device_dependent_mask & current_mods ) { + if (left_device_dependent_mask & current_mods) { key.sym = left_key_sym; SDL_PrivateKeyboard (SDL_RELEASED, &key); } - if ( right_device_dependent_mask & current_mods ) { + if (right_device_dependent_mask & current_mods) { key.sym = right_key_sym; SDL_PrivateKeyboard (SDL_RELEASED, &key); } @@ -509,26 +517,25 @@ static void QZ_ReleaseModifierSide ( _THIS, /* This is a helper function for QZ_DoSidedModifiers. * This function handles the CapsLock case. */ -static void QZ_HandleCapsLock (_THIS, unsigned int newMods) { +static void +QZ_HandleCapsLock (_THIS, unsigned int newMods) +{ unsigned int currentMask, newMask; SDL_keysym key; - - key.scancode = 0; - key.sym = SDLK_CAPSLOCK; - key.unicode = 0; - key.mod = KMOD_NONE; - + + key.scancode = 0; + key.sym = SDLK_CAPSLOCK; + key.unicode = 0; + key.mod = KMOD_NONE; + currentMask = current_mods & NSAlphaShiftKeyMask; - newMask = newMods & NSAlphaShiftKeyMask; + newMask = newMods & NSAlphaShiftKeyMask; - if ( currentMask && - currentMask != newMask ) { /* modifier up event */ - /* If this was Caps Lock, we need some additional voodoo to make SDL happy */ - SDL_PrivateKeyboard (SDL_PRESSED, &key); - SDL_PrivateKeyboard (SDL_RELEASED, &key); - } - else if ( newMask && - currentMask != newMask ) { /* modifier down event */ + if (currentMask && currentMask != newMask) { /* modifier up event */ + /* If this was Caps Lock, we need some additional voodoo to make SDL happy */ + SDL_PrivateKeyboard (SDL_PRESSED, &key); + SDL_PrivateKeyboard (SDL_RELEASED, &key); + } else if (newMask && currentMask != newMask) { /* modifier down event */ /* If this was Caps Lock, we need some additional voodoo to make SDL happy */ SDL_PrivateKeyboard (SDL_PRESSED, &key); SDL_PrivateKeyboard (SDL_RELEASED, &key); @@ -538,50 +545,59 @@ static void QZ_HandleCapsLock (_THIS, unsigned int newMods) { /* This function will handle the modifier keys and also determine the * correct side of the key. */ -static void QZ_DoSidedModifiers (_THIS, unsigned int newMods) { - /* Set up arrays for the key syms for the left and right side. */ - const unsigned int left_mapping[] = { SDLK_LSHIFT, SDLK_LCTRL, SDLK_LALT, SDLK_LMETA }; - const unsigned int right_mapping[] = { SDLK_RSHIFT, SDLK_RCTRL, SDLK_RALT, SDLK_RMETA }; - /* Set up arrays for the device dependent masks with indices that +static void +QZ_DoSidedModifiers (_THIS, unsigned int newMods) +{ + /* Set up arrays for the key syms for the left and right side. */ + const unsigned int left_mapping[] = + { SDLK_LSHIFT, SDLK_LCTRL, SDLK_LALT, SDLK_LMETA }; + const unsigned int right_mapping[] = + { SDLK_RSHIFT, SDLK_RCTRL, SDLK_RALT, SDLK_RMETA }; + /* Set up arrays for the device dependent masks with indices that * correspond to the _mapping arrays */ - const unsigned int left_device_mapping[] = { NX_DEVICELSHIFTKEYMASK, NX_DEVICELCTLKEYMASK, NX_DEVICELALTKEYMASK, NX_DEVICELCMDKEYMASK }; - const unsigned int right_device_mapping[] = { NX_DEVICERSHIFTKEYMASK, NX_DEVICERCTLKEYMASK, NX_DEVICERALTKEYMASK, NX_DEVICERCMDKEYMASK }; + const unsigned int left_device_mapping[] = + { NX_DEVICELSHIFTKEYMASK, NX_DEVICELCTLKEYMASK, NX_DEVICELALTKEYMASK, + NX_DEVICELCMDKEYMASK + }; + const unsigned int right_device_mapping[] = + { NX_DEVICERSHIFTKEYMASK, NX_DEVICERCTLKEYMASK, NX_DEVICERALTKEYMASK, + NX_DEVICERCMDKEYMASK + }; unsigned int i; unsigned int bit; - + /* Handle CAPSLOCK separately because it doesn't have a left/right side */ - QZ_HandleCapsLock ( this, newMods ); - + QZ_HandleCapsLock (this, newMods); + /* Iterate through the bits, testing each against the current modifiers */ for (i = 0, bit = NSShiftKeyMask; bit <= NSCommandKeyMask; bit <<= 1, ++i) { - + unsigned int currentMask, newMask; - + currentMask = current_mods & bit; - newMask = newMods & bit; - + newMask = newMods & bit; + /* If the bit is set, we must always examine it because the left * and right side keys may alternate or both may be pressed. */ - if ( newMask ) { - QZ_HandleModifierSide ( this, bit, newMods, - left_mapping[i], - right_mapping[i], - left_device_mapping[i], - right_device_mapping[i] ); + if (newMask) { + QZ_HandleModifierSide (this, bit, newMods, + left_mapping[i], + right_mapping[i], + left_device_mapping[i], + right_device_mapping[i]); } /* If the state changed from pressed to unpressed, we must examine - * the device dependent bits to release the correct keys. - */ - else if ( currentMask && - currentMask != newMask ) { /* modifier up event */ - QZ_ReleaseModifierSide ( this, bit, newMods, - left_mapping[i], - right_mapping[i], - left_device_mapping[i], - right_device_mapping[i] ); + * the device dependent bits to release the correct keys. + */ + else if (currentMask && currentMask != newMask) { /* modifier up event */ + QZ_ReleaseModifierSide (this, bit, newMods, + left_mapping[i], + right_mapping[i], + left_device_mapping[i], + right_device_mapping[i]); } } } @@ -592,48 +608,54 @@ static void QZ_DoSidedModifiers (_THIS, unsigned int newMods) { * operating system version supports it. Otherwise, the code * will not try to make the distinction. */ -static void QZ_DoModifiers (_THIS, unsigned int newMods) { - +static void +QZ_DoModifiers (_THIS, unsigned int newMods) +{ + if (current_mods == newMods) - return; - + return; + /* * Starting with Panther (10.3.0), the ability to distinguish between * left side and right side modifiers is available. */ - if( system_version >= 0x1030 ) { + if (system_version >= 0x1030) { QZ_DoSidedModifiers (this, newMods); - } - else { + } else { QZ_DoUnsidedModifiers (this, newMods); } - + current_mods = newMods; } -static void QZ_GetMouseLocation (_THIS, NSPoint *p) { - *p = [ NSEvent mouseLocation ]; /* global coordinates */ +static void +QZ_GetMouseLocation (_THIS, NSPoint * p) +{ + *p =[NSEvent mouseLocation]; /* global coordinates */ if (qz_window) QZ_PrivateGlobalToLocal (this, p); QZ_PrivateCocoaToSDL (this, p); } -void QZ_DoActivate (_THIS) { +void +QZ_DoActivate (_THIS) +{ + + SDL_PrivateAppActive (1, + SDL_APPINPUTFOCUS | (QZ_IsMouseInWindow (this) ? + SDL_APPMOUSEFOCUS : 0)); - SDL_PrivateAppActive (1, SDL_APPINPUTFOCUS | (QZ_IsMouseInWindow (this) ? SDL_APPMOUSEFOCUS : 0)); - /* Hide the cursor if it was hidden by SDL_ShowCursor() */ if (!cursor_should_be_visible) QZ_HideMouse (this); /* Regrab input, only if it was previously grabbed */ - if ( current_grab_mode == SDL_GRAB_ON ) { - + if (current_grab_mode == SDL_GRAB_ON) { + /* Restore cursor location if input was grabbed */ QZ_PrivateWarpCursor (this, cursor_loc.x, cursor_loc.y); QZ_ChangeGrabState (this, QZ_ENABLE_GRAB); - } - else { + } else { /* Update SDL's mouse location */ NSPoint p; QZ_GetMouseLocation (this, &p); @@ -641,13 +663,15 @@ void QZ_DoActivate (_THIS) { } } -void QZ_DoDeactivate (_THIS) { - +void +QZ_DoDeactivate (_THIS) +{ + SDL_PrivateAppActive (0, SDL_APPINPUTFOCUS | SDL_APPMOUSEFOCUS); /* Get the current cursor location, for restore on activate */ QZ_GetMouseLocation (this, &cursor_loc); - + /* Reassociate mouse and cursor */ CGAssociateMouseAndMouseCursorPosition (1); @@ -656,64 +680,68 @@ void QZ_DoDeactivate (_THIS) { QZ_ShowMouse (this); } -void QZ_SleepNotificationHandler (void * refcon, - io_service_t service, - natural_t messageType, - void * messageArgument ) +void +QZ_SleepNotificationHandler (void *refcon, + io_service_t service, + natural_t messageType, void *messageArgument) { - SDL_VideoDevice *this = (SDL_VideoDevice*)refcon; - - switch(messageType) - { - case kIOMessageSystemWillSleep: - IOAllowPowerChange(power_connection, (long) messageArgument); - break; - case kIOMessageCanSystemSleep: - IOAllowPowerChange(power_connection, (long) messageArgument); - break; - case kIOMessageSystemHasPoweredOn: - /* awake */ - SDL_PrivateExpose(); - break; - } + SDL_VideoDevice *this = (SDL_VideoDevice *) refcon; + + switch (messageType) { + case kIOMessageSystemWillSleep: + IOAllowPowerChange (power_connection, (long) messageArgument); + break; + case kIOMessageCanSystemSleep: + IOAllowPowerChange (power_connection, (long) messageArgument); + break; + case kIOMessageSystemHasPoweredOn: + /* awake */ + SDL_PrivateExpose (); + break; + } } -void QZ_RegisterForSleepNotifications (_THIS) +void +QZ_RegisterForSleepNotifications (_THIS) { - CFRunLoopSourceRef rls; - IONotificationPortRef thePortRef; - io_object_t notifier; + CFRunLoopSourceRef rls; + IONotificationPortRef thePortRef; + io_object_t notifier; - power_connection = IORegisterForSystemPower (this, &thePortRef, QZ_SleepNotificationHandler, ¬ifier); + power_connection = + IORegisterForSystemPower (this, &thePortRef, + QZ_SleepNotificationHandler, ¬ifier); - if (power_connection == 0) - NSLog(@"SDL: QZ_SleepNotificationHandler() IORegisterForSystemPower failed."); + if (power_connection == 0) + NSLog + (@"SDL: QZ_SleepNotificationHandler() IORegisterForSystemPower failed."); - rls = IONotificationPortGetRunLoopSource (thePortRef); - CFRunLoopAddSource (CFRunLoopGetCurrent(), rls, kCFRunLoopDefaultMode); - CFRelease (rls); + rls = IONotificationPortGetRunLoopSource (thePortRef); + CFRunLoopAddSource (CFRunLoopGetCurrent (), rls, kCFRunLoopDefaultMode); + CFRelease (rls); } /* Try to map Quartz mouse buttons to SDL's lingo... */ -static int QZ_OtherMouseButtonToSDL(int button) +static int +QZ_OtherMouseButtonToSDL (int button) { - switch (button) - { - case 0: - return(SDL_BUTTON_LEFT); /* 1 */ - case 1: - return(SDL_BUTTON_RIGHT); /* 3 */ - case 2: - return(SDL_BUTTON_MIDDLE); /* 2 */ + switch (button) { + case 0: + return (SDL_BUTTON_LEFT); /* 1 */ + case 1: + return (SDL_BUTTON_RIGHT); /* 3 */ + case 2: + return (SDL_BUTTON_MIDDLE); /* 2 */ } /* >= 3: skip 4 & 5, since those are the SDL mousewheel buttons. */ - return(button + 3); + return (button + 3); } -void QZ_PumpEvents (_THIS) +void +QZ_PumpEvents (_THIS) { static Uint32 screensaverTicks = 0; Uint32 nowTicks; @@ -726,251 +754,246 @@ void QZ_PumpEvents (_THIS) NSAutoreleasePool *pool; if (!SDL_VideoSurface) - return; /* don't do anything if there's no screen surface. */ + return; /* don't do anything if there's no screen surface. */ /* Update activity every five seconds to prevent screensaver. --ryan. */ - nowTicks = SDL_GetTicks(); - if ((nowTicks - screensaverTicks) > 5000) - { - UpdateSystemActivity(UsrActivity); + nowTicks = SDL_GetTicks (); + if ((nowTicks - screensaverTicks) > 5000) { + UpdateSystemActivity (UsrActivity); screensaverTicks = nowTicks; } - pool = [ [ NSAutoreleasePool alloc ] init ]; - distantPast = [ NSDate distantPast ]; + pool =[[NSAutoreleasePool alloc] init]; + distantPast =[NSDate distantPast]; winRect = NSMakeRect (0, 0, SDL_VideoSurface->w, SDL_VideoSurface->h); - + /* send the first mouse event in absolute coordinates */ firstMouseEvent = 1; - + /* accumulate any additional mouse moved events into one SDL mouse event */ dx = 0; dy = 0; - + do { - + /* Poll for an event. This will not block */ - event = [ NSApp nextEventMatchingMask:NSAnyEventMask - untilDate:distantPast - inMode: NSDefaultRunLoopMode dequeue:YES ]; + event =[NSApp nextEventMatchingMask: NSAnyEventMask untilDate: distantPast inMode: NSDefaultRunLoopMode dequeue:YES]; if (event != nil) { int button; unsigned int type; BOOL isInGameWin; - - #define DO_MOUSE_DOWN(button) do { \ + +#define DO_MOUSE_DOWN(button) do { \ if ( SDL_GetAppState() & SDL_APPMOUSEFOCUS ) { \ SDL_PrivateMouseButton (SDL_PRESSED, button, 0, 0); \ expect_mouse_up |= 1<= winRect.size.width ) - p.x = winRect.size.width-1; - - if ( p.y >= winRect.size.height ) - p.y = winRect.size.height-1; - - QZ_PrivateWarpCursor (this, p.x, p.y); + Get the amount moved since the last drag or move event, + add it on for one big move event at the end. + */ + dx +=[event deltaX]; + dy +=[event deltaY]; + } + + /* + Handle grab input+cursor visible by warping the cursor back + into the game window. This still generates a mouse moved event, + but not as a result of the warp (so it's in the right direction). + */ + if (grab_state == QZ_VISIBLE_GRAB && !isInGameWin) { + + NSPoint p; + QZ_GetMouseLocation (this, &p); + + if (p.x < 0.0) + p.x = 0.0; + + if (p.y < 0.0) + p.y = 0.0; + + if (p.x >= winRect.size.width) + p.x = winRect.size.width - 1; + + if (p.y >= winRect.size.height) + p.y = winRect.size.height - 1; + + QZ_PrivateWarpCursor (this, p.x, p.y); + } else if (!isInGameWin + && (SDL_GetAppState () & SDL_APPMOUSEFOCUS)) { + + SDL_PrivateAppActive (0, SDL_APPMOUSEFOCUS); + if (grab_state == QZ_INVISIBLE_GRAB) + /*The cursor has left the window even though it is + disassociated from the mouse (and therefore + shouldn't move): this can happen with Wacom + tablets, and it effectively breaks the grab, since + mouse down events now go to background + applications. The only possibility to avoid this + seems to be talking to the tablet driver + (AppleEvents) to constrain its mapped area to the + window, which may not be worth the effort. For + now, handle the condition more gracefully than + before by reassociating cursor and mouse until the + cursor enters the window again, making it obvious + to the user that the grab is broken. */ + CGAssociateMouseAndMouseCursorPosition (1); + if (!cursor_should_be_visible) + QZ_ShowMouse (this); + } else if (isInGameWin + && (SDL_GetAppState () & + (SDL_APPMOUSEFOCUS | SDL_APPINPUTFOCUS)) == + SDL_APPINPUTFOCUS) { + + SDL_PrivateAppActive (1, SDL_APPMOUSEFOCUS); + if (!cursor_should_be_visible) + QZ_HideMouse (this); + if (grab_state == QZ_INVISIBLE_GRAB) { /*see comment above */ + QZ_PrivateWarpCursor (this, + SDL_VideoSurface->w / + 2, SDL_VideoSurface->h / 2); + CGAssociateMouseAndMouseCursorPosition (0); } - else - if ( !isInGameWin && (SDL_GetAppState() & SDL_APPMOUSEFOCUS) ) { - - SDL_PrivateAppActive (0, SDL_APPMOUSEFOCUS); - if (grab_state == QZ_INVISIBLE_GRAB) - /*The cursor has left the window even though it is - disassociated from the mouse (and therefore - shouldn't move): this can happen with Wacom - tablets, and it effectively breaks the grab, since - mouse down events now go to background - applications. The only possibility to avoid this - seems to be talking to the tablet driver - (AppleEvents) to constrain its mapped area to the - window, which may not be worth the effort. For - now, handle the condition more gracefully than - before by reassociating cursor and mouse until the - cursor enters the window again, making it obvious - to the user that the grab is broken.*/ - CGAssociateMouseAndMouseCursorPosition (1); - if (!cursor_should_be_visible) - QZ_ShowMouse (this); - } - else - if ( isInGameWin && (SDL_GetAppState() & (SDL_APPMOUSEFOCUS | SDL_APPINPUTFOCUS)) == SDL_APPINPUTFOCUS ) { - - SDL_PrivateAppActive (1, SDL_APPMOUSEFOCUS); - if (!cursor_should_be_visible) - QZ_HideMouse (this); - if (grab_state == QZ_INVISIBLE_GRAB) { /*see comment above*/ - QZ_PrivateWarpCursor (this, SDL_VideoSurface->w / 2, SDL_VideoSurface->h / 2); - CGAssociateMouseAndMouseCursorPosition (0); - } - } - break; - case NSScrollWheel: - if ( isInGameWin ) { - float dy, dx; - Uint8 button; - dy = [ event deltaY ]; - dx = [ event deltaX ]; - if ( dy > 0.0 || dx > 0.0 ) /* Scroll up */ - button = SDL_BUTTON_WHEELUP; - else /* Scroll down */ - button = SDL_BUTTON_WHEELDOWN; - /* For now, wheel is sent as a quick down+up */ - SDL_PrivateMouseButton (SDL_PRESSED, button, 0, 0); - SDL_PrivateMouseButton (SDL_RELEASED, button, 0, 0); - } - break; - case NSKeyUp: - QZ_DoKey (this, SDL_RELEASED, event); - break; - case NSKeyDown: - QZ_DoKey (this, SDL_PRESSED, event); - break; - case NSFlagsChanged: - break; - /* case NSAppKitDefined: break; */ - /* case NSApplicationDefined: break; */ - /* case NSPeriodic: break; */ - /* case NSCursorUpdate: break; */ - default: - [ NSApp sendEvent:event ]; + } + break; + case NSScrollWheel: + if (isInGameWin) { + float dy, dx; + Uint8 button; + dy =[event deltaY]; + dx =[event deltaX]; + if (dy > 0.0 || dx > 0.0) /* Scroll up */ + button = SDL_BUTTON_WHEELUP; + else /* Scroll down */ + button = SDL_BUTTON_WHEELDOWN; + /* For now, wheel is sent as a quick down+up */ + SDL_PrivateMouseButton (SDL_PRESSED, button, 0, 0); + SDL_PrivateMouseButton (SDL_RELEASED, button, 0, 0); + } + break; + case NSKeyUp: + QZ_DoKey (this, SDL_RELEASED, event); + break; + case NSKeyDown: + QZ_DoKey (this, SDL_PRESSED, event); + break; + case NSFlagsChanged: + break; + /* case NSAppKitDefined: break; */ + /* case NSApplicationDefined: break; */ + /* case NSPeriodic: break; */ + /* case NSCursorUpdate: break; */ + default: + [NSApp sendEvent:event]; } } - } while (event != nil); - + } + while (event != nil); + /* handle accumulated mouse moved events */ if (dx != 0 || dy != 0) SDL_PrivateMouseMotion (0, 1, dx, dy); - - [ pool release ]; + + [pool release]; } -void QZ_UpdateMouse (_THIS) +void +QZ_UpdateMouse (_THIS) { NSPoint p; QZ_GetMouseLocation (this, &p); diff --git a/src/video/quartz/SDL_QuartzGL.m b/src/video/quartz/SDL_QuartzGL.m index ef447451b..923d4a92f 100644 --- a/src/video/quartz/SDL_QuartzGL.m +++ b/src/video/quartz/SDL_QuartzGL.m @@ -42,16 +42,17 @@ #endif -@implementation NSOpenGLContext (CGLContextAccess) -- (CGLContextObj) cglContext; +@ implementation NSOpenGLContext (CGLContextAccess) + - (CGLContextObj) cglContext; { return _contextAuxiliary; } -@end +@end /* OpenGL helper functions (used internally) */ - -int QZ_SetupOpenGL (_THIS, int bpp, Uint32 flags) { + int +QZ_SetupOpenGL (_THIS, int bpp, Uint32 flags) +{ NSOpenGLPixelFormatAttribute attr[32]; NSOpenGLPixelFormat *fmt; @@ -60,16 +61,16 @@ int QZ_SetupOpenGL (_THIS, int bpp, Uint32 flags) { /* if a GL library hasn't been loaded at this point, load the default. */ if (!this->gl_config.driver_loaded) { - if (QZ_GL_LoadLibrary(this, NULL) == -1) + if (QZ_GL_LoadLibrary (this, NULL) == -1) return 0; } - if ( flags & SDL_FULLSCREEN ) { + if (flags & SDL_FULLSCREEN) { attr[i++] = NSOpenGLPFAFullScreen; } /* In windowed mode, the OpenGL pixel depth must match device pixel depth */ - else if ( colorBits != device_bpp ) { + else if (colorBits != device_bpp) { colorBits = device_bpp; } @@ -80,39 +81,43 @@ int QZ_SetupOpenGL (_THIS, int bpp, Uint32 flags) { attr[i++] = NSOpenGLPFADepthSize; attr[i++] = this->gl_config.depth_size; - if ( this->gl_config.double_buffer ) { + if (this->gl_config.double_buffer) { attr[i++] = NSOpenGLPFADoubleBuffer; } - if ( this->gl_config.stereo ) { + if (this->gl_config.stereo) { attr[i++] = NSOpenGLPFAStereo; } - if ( this->gl_config.stencil_size != 0 ) { + if (this->gl_config.stencil_size != 0) { attr[i++] = NSOpenGLPFAStencilSize; attr[i++] = this->gl_config.stencil_size; } - if ( (this->gl_config.accum_red_size + - this->gl_config.accum_green_size + - this->gl_config.accum_blue_size + - this->gl_config.accum_alpha_size) > 0 ) { + if ((this->gl_config.accum_red_size + + this->gl_config.accum_green_size + + this->gl_config.accum_blue_size + + this->gl_config.accum_alpha_size) > 0) { attr[i++] = NSOpenGLPFAAccumSize; - attr[i++] = this->gl_config.accum_red_size + this->gl_config.accum_green_size + this->gl_config.accum_blue_size + this->gl_config.accum_alpha_size; + attr[i++] = + this->gl_config.accum_red_size + + this->gl_config.accum_green_size + + this->gl_config.accum_blue_size + + this->gl_config.accum_alpha_size; } - if ( this->gl_config.multisamplebuffers != 0 ) { + if (this->gl_config.multisamplebuffers != 0) { attr[i++] = NSOpenGLPFASampleBuffers; attr[i++] = this->gl_config.multisamplebuffers; } - if ( this->gl_config.multisamplesamples != 0 ) { + if (this->gl_config.multisamplesamples != 0) { attr[i++] = NSOpenGLPFASamples; attr[i++] = this->gl_config.multisamplesamples; attr[i++] = NSOpenGLPFANoRecovery; } - if ( this->gl_config.accelerated > 0 ) { + if (this->gl_config.accelerated > 0) { attr[i++] = NSOpenGLPFAAccelerated; } @@ -120,16 +125,15 @@ int QZ_SetupOpenGL (_THIS, int bpp, Uint32 flags) { attr[i++] = CGDisplayIDToOpenGLDisplayMask (display_id); attr[i] = 0; - fmt = [ [ NSOpenGLPixelFormat alloc ] initWithAttributes:attr ]; + fmt =[[NSOpenGLPixelFormat alloc] initWithAttributes:attr]; if (fmt == nil) { SDL_SetError ("Failed creating OpenGL pixel format"); return 0; } - gl_context = [ [ NSOpenGLContext alloc ] initWithFormat:fmt - shareContext:nil]; + gl_context =[[NSOpenGLContext alloc] initWithFormat: fmt shareContext:nil]; - [ fmt release ]; + [fmt release]; if (gl_context == nil) { SDL_SetError ("Failed creating OpenGL context"); @@ -141,10 +145,10 @@ int QZ_SetupOpenGL (_THIS, int bpp, Uint32 flags) { * exactly does, IMHO - for a detailed explanation see * http://lists.apple.com/archives/mac-opengl/2006/Jan/msg00080.html ) */ - if ( this->gl_config.swap_control >= 0 ) { + if (this->gl_config.swap_control >= 0) { long value; value = this->gl_config.swap_control; - [ gl_context setValues: &value forParameter: NSOpenGLCPSwapInterval ]; + [gl_context setValues: &value forParameter:NSOpenGLCPSwapInterval]; } /* @@ -155,17 +159,17 @@ int QZ_SetupOpenGL (_THIS, int bpp, Uint32 flags) { * the OpenGL context. The default cache size is 16." --ryan. */ - #ifndef GLI_ARRAY_FUNC_CACHE_MAX - #define GLI_ARRAY_FUNC_CACHE_MAX 284 - #endif +#ifndef GLI_ARRAY_FUNC_CACHE_MAX +#define GLI_ARRAY_FUNC_CACHE_MAX 284 +#endif - #ifndef GLI_SUBMIT_FUNC_CACHE_MAX - #define GLI_SUBMIT_FUNC_CACHE_MAX 280 - #endif +#ifndef GLI_SUBMIT_FUNC_CACHE_MAX +#define GLI_SUBMIT_FUNC_CACHE_MAX 280 +#endif { long cache_max = 64; - CGLContextObj ctx = [ gl_context cglContext ]; + CGLContextObj ctx =[gl_context cglContext]; CGLSetParameter (ctx, GLI_SUBMIT_FUNC_CACHE_MAX, &cache_max); CGLSetParameter (ctx, GLI_ARRAY_FUNC_CACHE_MAX, &cache_max); } @@ -175,11 +179,13 @@ int QZ_SetupOpenGL (_THIS, int bpp, Uint32 flags) { return 1; } -void QZ_TearDownOpenGL (_THIS) { +void +QZ_TearDownOpenGL (_THIS) +{ - [ NSOpenGLContext clearCurrentContext ]; - [ gl_context clearDrawable ]; - [ gl_context release ]; + [NSOpenGLContext clearCurrentContext]; + [gl_context clearDrawable]; + [gl_context release]; } @@ -187,19 +193,21 @@ void QZ_TearDownOpenGL (_THIS) { static const char *DEFAULT_OPENGL_LIB_NAME = "/System/Library/Frameworks/OpenGL.framework/Libraries/libGL.dylib"; -int QZ_GL_LoadLibrary (_THIS, const char *location) { - if ( gl_context != NULL ) { - SDL_SetError("OpenGL context already created"); +int +QZ_GL_LoadLibrary (_THIS, const char *location) +{ + if (gl_context != NULL) { + SDL_SetError ("OpenGL context already created"); return -1; } if (opengl_library != NULL) - SDL_UnloadObject(opengl_library); + SDL_UnloadObject (opengl_library); if (location == NULL) location = DEFAULT_OPENGL_LIB_NAME; - opengl_library = SDL_LoadObject(location); + opengl_library = SDL_LoadObject (location); if (opengl_library != NULL) { this->gl_config.driver_loaded = 1; return 0; @@ -209,73 +217,113 @@ int QZ_GL_LoadLibrary (_THIS, const char *location) { return -1; } -void* QZ_GL_GetProcAddress (_THIS, const char *proc) { - return SDL_LoadFunction(opengl_library, proc); +void * +QZ_GL_GetProcAddress (_THIS, const char *proc) +{ + return SDL_LoadFunction (opengl_library, proc); } -int QZ_GL_GetAttribute (_THIS, SDL_GLattr attrib, int* value) { +int +QZ_GL_GetAttribute (_THIS, SDL_GLattr attrib, int *value) +{ GLenum attr = 0; QZ_GL_MakeCurrent (this); switch (attrib) { - case SDL_GL_RED_SIZE: attr = GL_RED_BITS; break; - case SDL_GL_BLUE_SIZE: attr = GL_BLUE_BITS; break; - case SDL_GL_GREEN_SIZE: attr = GL_GREEN_BITS; break; - case SDL_GL_ALPHA_SIZE: attr = GL_ALPHA_BITS; break; - case SDL_GL_DOUBLEBUFFER: attr = GL_DOUBLEBUFFER; break; - case SDL_GL_DEPTH_SIZE: attr = GL_DEPTH_BITS; break; - case SDL_GL_STENCIL_SIZE: attr = GL_STENCIL_BITS; break; - case SDL_GL_ACCUM_RED_SIZE: attr = GL_ACCUM_RED_BITS; break; - case SDL_GL_ACCUM_GREEN_SIZE: attr = GL_ACCUM_GREEN_BITS; break; - case SDL_GL_ACCUM_BLUE_SIZE: attr = GL_ACCUM_BLUE_BITS; break; - case SDL_GL_ACCUM_ALPHA_SIZE: attr = GL_ACCUM_ALPHA_BITS; break; - case SDL_GL_STEREO: attr = GL_STEREO; break; - case SDL_GL_MULTISAMPLEBUFFERS: attr = GL_SAMPLE_BUFFERS_ARB; break; - case SDL_GL_MULTISAMPLESAMPLES: attr = GL_SAMPLES_ARB; break; - case SDL_GL_BUFFER_SIZE: + case SDL_GL_RED_SIZE: + attr = GL_RED_BITS; + break; + case SDL_GL_BLUE_SIZE: + attr = GL_BLUE_BITS; + break; + case SDL_GL_GREEN_SIZE: + attr = GL_GREEN_BITS; + break; + case SDL_GL_ALPHA_SIZE: + attr = GL_ALPHA_BITS; + break; + case SDL_GL_DOUBLEBUFFER: + attr = GL_DOUBLEBUFFER; + break; + case SDL_GL_DEPTH_SIZE: + attr = GL_DEPTH_BITS; + break; + case SDL_GL_STENCIL_SIZE: + attr = GL_STENCIL_BITS; + break; + case SDL_GL_ACCUM_RED_SIZE: + attr = GL_ACCUM_RED_BITS; + break; + case SDL_GL_ACCUM_GREEN_SIZE: + attr = GL_ACCUM_GREEN_BITS; + break; + case SDL_GL_ACCUM_BLUE_SIZE: + attr = GL_ACCUM_BLUE_BITS; + break; + case SDL_GL_ACCUM_ALPHA_SIZE: + attr = GL_ACCUM_ALPHA_BITS; + break; + case SDL_GL_STEREO: + attr = GL_STEREO; + break; + case SDL_GL_MULTISAMPLEBUFFERS: + attr = GL_SAMPLE_BUFFERS_ARB; + break; + case SDL_GL_MULTISAMPLESAMPLES: + attr = GL_SAMPLES_ARB; + break; + case SDL_GL_BUFFER_SIZE: { GLint bits = 0; GLint component; /* there doesn't seem to be a single flag in OpenGL for this! */ - glGetIntegerv (GL_RED_BITS, &component); bits += component; - glGetIntegerv (GL_GREEN_BITS,&component); bits += component; - glGetIntegerv (GL_BLUE_BITS, &component); bits += component; - glGetIntegerv (GL_ALPHA_BITS, &component); bits += component; + glGetIntegerv (GL_RED_BITS, &component); + bits += component; + glGetIntegerv (GL_GREEN_BITS, &component); + bits += component; + glGetIntegerv (GL_BLUE_BITS, &component); + bits += component; + glGetIntegerv (GL_ALPHA_BITS, &component); + bits += component; *value = bits; return 0; } - case SDL_GL_ACCELERATED_VISUAL: + case SDL_GL_ACCELERATED_VISUAL: { long val; - /* FIXME: How do we get this information here? - [fmt getValues: &val forAttribute: NSOpenGLPFAAccelerated attr forVirtualScreen: 0]; - */ - val = (this->gl_config.accelerated != 0);; + /* FIXME: How do we get this information here? + [fmt getValues: &val forAttribute: NSOpenGLPFAAccelerated attr forVirtualScreen: 0]; + */ + val = (this->gl_config.accelerated != 0);; *value = val; return 0; } - case SDL_GL_SWAP_CONTROL: + case SDL_GL_SWAP_CONTROL: { long val; - [ gl_context getValues: &val forParameter: NSOpenGLCPSwapInterval ]; + [gl_context getValues: &val forParameter:NSOpenGLCPSwapInterval]; *value = val; return 0; } } - glGetIntegerv (attr, (GLint *)value); + glGetIntegerv (attr, (GLint *) value); return 0; } -int QZ_GL_MakeCurrent (_THIS) { - [ gl_context makeCurrentContext ]; +int +QZ_GL_MakeCurrent (_THIS) +{ + [gl_context makeCurrentContext]; return 0; } -void QZ_GL_SwapBuffers (_THIS) { - [ gl_context flushBuffer ]; +void +QZ_GL_SwapBuffers (_THIS) +{ + [gl_context flushBuffer]; } diff --git a/src/video/quartz/SDL_QuartzKeys.h b/src/video/quartz/SDL_QuartzKeys.h index 19389126d..86a5aea9b 100644 --- a/src/video/quartz/SDL_QuartzKeys.h +++ b/src/video/quartz/SDL_QuartzKeys.h @@ -110,7 +110,7 @@ #define QZ_COMMA 0x2B #define QZ_PERIOD 0x2F #define QZ_SLASH 0x2C -#if 1 /* Panther now defines right side keys */ +#if 1 /* Panther now defines right side keys */ #define QZ_RSHIFT 0x3C #endif #define QZ_UP 0x7E @@ -122,7 +122,7 @@ #define QZ_LALT 0x3A #define QZ_LMETA 0x37 #define QZ_SPACE 0x31 -#if 1 /* Panther now defines right side keys */ +#if 1 /* Panther now defines right side keys */ #define QZ_RMETA 0x36 #define QZ_RALT 0x3D #define QZ_RCTRL 0x3E @@ -139,3 +139,4 @@ #define QZ_IBOOK_RIGHT 0x3C #define QZ_IBOOK_DOWN 0x3D #define QZ_IBOOK_UP 0x3E +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/quartz/SDL_QuartzVideo.h b/src/video/quartz/SDL_QuartzVideo.h index c7b68ec34..d9f3d856d 100644 --- a/src/video/quartz/SDL_QuartzVideo.h +++ b/src/video/quartz/SDL_QuartzVideo.h @@ -54,8 +54,8 @@ #include #include #include -#include /* For CGLContextObj */ -#include /* For powersave handling */ +#include /* For CGLContextObj */ +#include /* For powersave handling */ #include #include "SDL_thread.h" @@ -72,56 +72,97 @@ This is a workaround to directly access NSOpenGLContext's CGL context We need this to check for errors NSOpenGLContext doesn't support */ -@interface NSOpenGLContext (CGLContextAccess) -- (CGLContextObj) cglContext; +@ interface NSOpenGLContext(CGLContextAccess) - (CGLContextObj) cglContext; @end +/* Main driver structure to store required state information */ + typedef struct SDL_PrivateVideoData + { + CGDirectDisplayID + display; /* 0 == main display (only support single display) */ + CFDictionaryRef + mode; /* current mode of the display */ + CFDictionaryRef + save_mode; /* original mode of the display */ + CFArrayRef + mode_list; /* list of available fullscreen modes */ + CGDirectPaletteRef + palette; /* palette of an 8-bit display */ + NSOpenGLContext * + gl_context; /* OpenGL rendering context */ + Uint32 + width, + height, + bpp; /* frequently used data about the display */ + Uint32 + flags; /* flags for current mode, for teardown purposes */ + Uint32 + video_set; /* boolean; indicates if video was set correctly */ + Uint32 + warp_flag; /* boolean; notify to event loop that a warp just occured */ + Uint32 + warp_ticks; /* timestamp when the warp occured */ + NSWindow * + window; /* Cocoa window to implement the SDL window */ + NSQuickDrawView * + view; /* the window's view; draw 2D and OpenGL into this view */ + SDL_Surface * + resize_icon; /* icon for the resize badge, we have to draw it by hand */ + SDL_GrabMode + current_grab_mode; /* default value is SDL_GRAB_OFF */ + SDL_Rect ** + client_mode_list; /* resolution list to pass back to client */ + SDLKey + keymap[256]; /* Mac OS X to SDL key mapping */ + Uint32 + current_mods; /* current keyboard modifiers, to track modifier state */ + Uint32 + last_virtual_button; /* last virtual mouse button pressed */ + io_connect_t + power_connection; /* used with IOKit to detect wake from sleep */ + Uint8 + expect_mouse_up; /* used to determine when to send mouse up events */ + Uint8 + grab_state; /* used to manage grab behavior */ + NSPoint + cursor_loc; /* saved cursor coords, for activate/deactivate when grabbed */ + BOOL + cursor_should_be_visible; /* tells if cursor is supposed to be visible (SDL_ShowCursor) */ + BOOL + cursor_visible; /* tells if cursor is *actually* visible or not */ + Uint8 * + sw_buffers[2]; /* pointers to the two software buffers for double-buffer emulation */ + SDL_Thread * + thread; /* thread for async updates to the screen */ + SDL_sem * + sem1, * + sem2; /* synchronization for async screen updates */ + Uint8 * + current_buffer; /* the buffer being copied to the screen */ + BOOL + quit_thread; /* used to quit the async blitting thread */ + SInt32 + system_version; /* used to dis-/enable workarounds depending on the system version */ -/* Main driver structure to store required state information */ -typedef struct SDL_PrivateVideoData { - - CGDirectDisplayID display; /* 0 == main display (only support single display) */ - CFDictionaryRef mode; /* current mode of the display */ - CFDictionaryRef save_mode; /* original mode of the display */ - CFArrayRef mode_list; /* list of available fullscreen modes */ - CGDirectPaletteRef palette; /* palette of an 8-bit display */ - NSOpenGLContext *gl_context; /* OpenGL rendering context */ - Uint32 width, height, bpp; /* frequently used data about the display */ - Uint32 flags; /* flags for current mode, for teardown purposes */ - Uint32 video_set; /* boolean; indicates if video was set correctly */ - Uint32 warp_flag; /* boolean; notify to event loop that a warp just occured */ - Uint32 warp_ticks; /* timestamp when the warp occured */ - NSWindow *window; /* Cocoa window to implement the SDL window */ - NSQuickDrawView *view; /* the window's view; draw 2D and OpenGL into this view */ - SDL_Surface *resize_icon; /* icon for the resize badge, we have to draw it by hand */ - SDL_GrabMode current_grab_mode; /* default value is SDL_GRAB_OFF */ - SDL_Rect **client_mode_list; /* resolution list to pass back to client */ - SDLKey keymap[256]; /* Mac OS X to SDL key mapping */ - Uint32 current_mods; /* current keyboard modifiers, to track modifier state */ - Uint32 last_virtual_button;/* last virtual mouse button pressed */ - io_connect_t power_connection; /* used with IOKit to detect wake from sleep */ - Uint8 expect_mouse_up; /* used to determine when to send mouse up events */ - Uint8 grab_state; /* used to manage grab behavior */ - NSPoint cursor_loc; /* saved cursor coords, for activate/deactivate when grabbed */ - BOOL cursor_should_be_visible; /* tells if cursor is supposed to be visible (SDL_ShowCursor) */ - BOOL cursor_visible; /* tells if cursor is *actually* visible or not */ - Uint8* sw_buffers[2]; /* pointers to the two software buffers for double-buffer emulation */ - SDL_Thread *thread; /* thread for async updates to the screen */ - SDL_sem *sem1, *sem2; /* synchronization for async screen updates */ - Uint8 *current_buffer; /* the buffer being copied to the screen */ - BOOL quit_thread; /* used to quit the async blitting thread */ - SInt32 system_version; /* used to dis-/enable workarounds depending on the system version */ - - ImageDescriptionHandle yuv_idh; - MatrixRecordPtr yuv_matrix; - DecompressorComponent yuv_codec; - ImageSequence yuv_seq; - PlanarPixmapInfoYUV420 *yuv_pixmap; - Sint16 yuv_width, yuv_height; - CGrafPtr yuv_port; + ImageDescriptionHandle + yuv_idh; + MatrixRecordPtr + yuv_matrix; + DecompressorComponent + yuv_codec; + ImageSequence + yuv_seq; + PlanarPixmapInfoYUV420 * + yuv_pixmap; + Sint16 + yuv_width, + yuv_height; + CGrafPtr + yuv_port; - void *opengl_library; /* dynamically loaded OpenGL library. */ -} SDL_PrivateVideoData; + void * + opengl_library; /* dynamically loaded OpenGL library. */ + } SDL_PrivateVideoData; #define _THIS SDL_VideoDevice *this #define display_id (this->hidden->display) @@ -161,69 +202,97 @@ typedef struct SDL_PrivateVideoData { #define opengl_library (this->hidden->opengl_library) /* grab states - the input is in one of these states */ -enum { - QZ_UNGRABBED = 0, - QZ_VISIBLE_GRAB, - QZ_INVISIBLE_GRAB -}; + enum + { + QZ_UNGRABBED = 0, + QZ_VISIBLE_GRAB, + QZ_INVISIBLE_GRAB + }; /* grab actions - these can change the grabbed state */ -enum { - QZ_ENABLE_GRAB = 0, - QZ_DISABLE_GRAB, - QZ_HIDECURSOR, - QZ_SHOWCURSOR -}; + enum + { + QZ_ENABLE_GRAB = 0, + QZ_DISABLE_GRAB, + QZ_HIDECURSOR, + QZ_SHOWCURSOR + }; /* Gamma Functions */ -int QZ_SetGamma (_THIS, float red, float green, float blue); -int QZ_GetGamma (_THIS, float *red, float *green, float *blue); -int QZ_SetGammaRamp (_THIS, Uint16 *ramp); -int QZ_GetGammaRamp (_THIS, Uint16 *ramp); + int + QZ_SetGamma(_THIS, float red, float green, float blue); + int + QZ_GetGamma(_THIS, float *red, float *green, float *blue); + int + QZ_SetGammaRamp(_THIS, Uint16 * ramp); + int + QZ_GetGammaRamp(_THIS, Uint16 * ramp); /* OpenGL functions */ -int QZ_SetupOpenGL (_THIS, int bpp, Uint32 flags); -void QZ_TearDownOpenGL (_THIS); -void* QZ_GL_GetProcAddress (_THIS, const char *proc); -int QZ_GL_GetAttribute (_THIS, SDL_GLattr attrib, int* value); -int QZ_GL_MakeCurrent (_THIS); -void QZ_GL_SwapBuffers (_THIS); -int QZ_GL_LoadLibrary (_THIS, const char *location); + int + QZ_SetupOpenGL(_THIS, int bpp, Uint32 flags); + void + QZ_TearDownOpenGL(_THIS); + void * + QZ_GL_GetProcAddress(_THIS, const char *proc); + int + QZ_GL_GetAttribute(_THIS, SDL_GLattr attrib, int *value); + int + QZ_GL_MakeCurrent(_THIS); + void + QZ_GL_SwapBuffers(_THIS); + int + QZ_GL_LoadLibrary(_THIS, const char *location); /* Cursor and Mouse functions */ -void QZ_FreeWMCursor (_THIS, WMcursor *cursor); -WMcursor* QZ_CreateWMCursor (_THIS, Uint8 *data, Uint8 *mask, - int w, int h, int hot_x, int hot_y); -int QZ_ShowWMCursor (_THIS, WMcursor *cursor); -void QZ_WarpWMCursor (_THIS, Uint16 x, Uint16 y); -void QZ_MoveWMCursor (_THIS, int x, int y); -void QZ_CheckMouseMode (_THIS); -void QZ_UpdateMouse (_THIS); + void + QZ_FreeWMCursor(_THIS, WMcursor * cursor); + WMcursor * + QZ_CreateWMCursor(_THIS, Uint8 * data, Uint8 * mask, + int w, int h, int hot_x, int hot_y); + int + QZ_ShowWMCursor(_THIS, WMcursor * cursor); + void + QZ_WarpWMCursor(_THIS, Uint16 x, Uint16 y); + void + QZ_MoveWMCursor(_THIS, int x, int y); + void + QZ_CheckMouseMode(_THIS); + void + QZ_UpdateMouse(_THIS); /* Event functions */ -void QZ_InitOSKeymap (_THIS); -void QZ_PumpEvents (_THIS); + void + QZ_InitOSKeymap(_THIS); + void + QZ_PumpEvents(_THIS); /* Window Manager functions */ -void QZ_SetCaption (_THIS, const char *title, const char *icon); -void QZ_SetIcon (_THIS, SDL_Surface *icon, Uint8 *mask); -int QZ_IconifyWindow (_THIS); -SDL_GrabMode QZ_GrabInput (_THIS, SDL_GrabMode grab_mode); + void + QZ_SetCaption(_THIS, const char *title, const char *icon); + void + QZ_SetIcon(_THIS, SDL_Surface * icon, Uint8 * mask); + int + QZ_IconifyWindow(_THIS); +SDL_GrabMode +QZ_GrabInput(_THIS, SDL_GrabMode grab_mode); /*int QZ_GetWMInfo (_THIS, SDL_SysWMinfo *info);*/ /* YUV functions */ -SDL_Overlay* QZ_CreateYUVOverlay (_THIS, int width, int height, - Uint32 format, SDL_Surface *display); + SDL_Overlay *QZ_CreateYUVOverlay(_THIS, int width, int height, + Uint32 format, SDL_Surface * display); /* Private functions (used internally) */ -void QZ_PrivateWarpCursor (_THIS, int x, int y); -void QZ_ChangeGrabState (_THIS, int action); -void QZ_RegisterForSleepNotifications (_THIS); -void QZ_ShowMouse (_THIS); -void QZ_HideMouse (_THIS); -void QZ_PrivateGlobalToLocal (_THIS, NSPoint *p); -void QZ_PrivateCocoaToSDL (_THIS, NSPoint *p); -BOOL QZ_IsMouseInWindow (_THIS); -void QZ_DoActivate (_THIS); -void QZ_DoDeactivate (_THIS); + void QZ_PrivateWarpCursor(_THIS, int x, int y); + void QZ_ChangeGrabState(_THIS, int action); + void QZ_RegisterForSleepNotifications(_THIS); + void QZ_ShowMouse(_THIS); + void QZ_HideMouse(_THIS); + void QZ_PrivateGlobalToLocal(_THIS, NSPoint * p); + void QZ_PrivateCocoaToSDL(_THIS, NSPoint * p); +BOOL +QZ_IsMouseInWindow(_THIS); + void QZ_DoActivate(_THIS); + void QZ_DoDeactivate(_THIS); +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/quartz/SDL_QuartzVideo.m b/src/video/quartz/SDL_QuartzVideo.m index 8d41169ce..d9e29a575 100644 --- a/src/video/quartz/SDL_QuartzVideo.m +++ b/src/video/quartz/SDL_QuartzVideo.m @@ -31,25 +31,21 @@ to fullscreen, we'll set it manually (but only for the main screen). */ -@interface NSScreen (NSScreenAccess) -- (void) setFrame:(NSRect)frame; -@end - -@implementation NSScreen (NSScreenAccess) -- (void) setFrame:(NSRect)frame; +@ interface NSScreen (NSScreenAccess) - (void) setFrame:(NSRect) frame; +@end @ implementation NSScreen (NSScreenAccess) - (void) setFrame:(NSRect) + frame; { _frame = frame; } -@end - +@end /* Structure for rez switch gamma fades We can hide the monitor flicker by setting the gamma tables to 0 */ #define QZ_GAMMA_TABLE_SIZE 256 - -typedef struct { + typedef struct +{ CGGammaValue red[QZ_GAMMA_TABLE_SIZE]; CGGammaValue green[QZ_GAMMA_TABLE_SIZE]; @@ -59,44 +55,45 @@ - (void) setFrame:(NSRect)frame; /* Bootstrap functions */ -static int QZ_Available (); -static SDL_VideoDevice* QZ_CreateDevice (int device_index); -static void QZ_DeleteDevice (SDL_VideoDevice *device); +static int QZ_Available (); +static SDL_VideoDevice *QZ_CreateDevice (int device_index); +static void QZ_DeleteDevice (SDL_VideoDevice * device); /* Initialization, Query, Setup, and Redrawing functions */ -static int QZ_VideoInit (_THIS, SDL_PixelFormat *video_format); - -static SDL_Rect** QZ_ListModes (_THIS, SDL_PixelFormat *format, - Uint32 flags); -static void QZ_UnsetVideoMode (_THIS, BOOL to_desktop); - -static SDL_Surface* QZ_SetVideoMode (_THIS, SDL_Surface *current, - int width, int height, int bpp, - Uint32 flags); -static int QZ_ToggleFullScreen (_THIS, int on); -static int QZ_SetColors (_THIS, int first_color, - int num_colors, SDL_Color *colors); - -static int QZ_LockDoubleBuffer (_THIS, SDL_Surface *surface); -static void QZ_UnlockDoubleBuffer (_THIS, SDL_Surface *surface); -static int QZ_ThreadFlip (_THIS); -static int QZ_FlipDoubleBuffer (_THIS, SDL_Surface *surface); -static void QZ_DoubleBufferUpdate (_THIS, int num_rects, SDL_Rect *rects); - -static void QZ_DirectUpdate (_THIS, int num_rects, SDL_Rect *rects); -static int QZ_LockWindow (_THIS, SDL_Surface *surface); -static void QZ_UnlockWindow (_THIS, SDL_Surface *surface); -static void QZ_UpdateRects (_THIS, int num_rects, SDL_Rect *rects); -static void QZ_VideoQuit (_THIS); +static int QZ_VideoInit (_THIS, SDL_PixelFormat * video_format); + +static SDL_Rect **QZ_ListModes (_THIS, SDL_PixelFormat * format, + Uint32 flags); +static void QZ_UnsetVideoMode (_THIS, BOOL to_desktop); + +static SDL_Surface *QZ_SetVideoMode (_THIS, SDL_Surface * current, + int width, int height, int bpp, + Uint32 flags); +static int QZ_ToggleFullScreen (_THIS, int on); +static int QZ_SetColors (_THIS, int first_color, + int num_colors, SDL_Color * colors); + +static int QZ_LockDoubleBuffer (_THIS, SDL_Surface * surface); +static void QZ_UnlockDoubleBuffer (_THIS, SDL_Surface * surface); +static int QZ_ThreadFlip (_THIS); +static int QZ_FlipDoubleBuffer (_THIS, SDL_Surface * surface); +static void QZ_DoubleBufferUpdate (_THIS, int num_rects, SDL_Rect * rects); + +static void QZ_DirectUpdate (_THIS, int num_rects, SDL_Rect * rects); +static int QZ_LockWindow (_THIS, SDL_Surface * surface); +static void QZ_UnlockWindow (_THIS, SDL_Surface * surface); +static void QZ_UpdateRects (_THIS, int num_rects, SDL_Rect * rects); +static void QZ_VideoQuit (_THIS); /* Hardware surface functions (for fullscreen mode only) */ -#if 0 /* Not used (apparently, it's really slow) */ -static int QZ_FillHWRect (_THIS, SDL_Surface *dst, SDL_Rect *rect, Uint32 color); +#if 0 /* Not used (apparently, it's really slow) */ +static int QZ_FillHWRect (_THIS, SDL_Surface * dst, SDL_Rect * rect, + Uint32 color); #endif -static int QZ_LockHWSurface(_THIS, SDL_Surface *surface); -static void QZ_UnlockHWSurface(_THIS, SDL_Surface *surface); -static int QZ_AllocHWSurface(_THIS, SDL_Surface *surface); -static void QZ_FreeHWSurface (_THIS, SDL_Surface *surface); +static int QZ_LockHWSurface (_THIS, SDL_Surface * surface); +static void QZ_UnlockHWSurface (_THIS, SDL_Surface * surface); +static int QZ_AllocHWSurface (_THIS, SDL_Surface * surface); +static void QZ_FreeHWSurface (_THIS, SDL_Surface * surface); /* static int QZ_FlipHWSurface (_THIS, SDL_Surface *surface); */ /* Bootstrap binding, enables entry point into the driver */ @@ -106,92 +103,101 @@ static int QZ_SetColors (_THIS, int first_color, /* Bootstrap functions */ -static int QZ_Available () { +static int +QZ_Available () +{ return 1; } -static SDL_VideoDevice* QZ_CreateDevice (int device_index) { +static SDL_VideoDevice * +QZ_CreateDevice (int device_index) +{ #pragma unused (device_index) SDL_VideoDevice *device; SDL_PrivateVideoData *hidden; - device = (SDL_VideoDevice*) SDL_malloc (sizeof (*device) ); - hidden = (SDL_PrivateVideoData*) SDL_malloc (sizeof (*hidden) ); + device = (SDL_VideoDevice *) SDL_malloc (sizeof (*device)); + hidden = (SDL_PrivateVideoData *) SDL_malloc (sizeof (*hidden)); if (device == NULL || hidden == NULL) SDL_OutOfMemory (); - SDL_memset (device, 0, sizeof (*device) ); - SDL_memset (hidden, 0, sizeof (*hidden) ); + SDL_memset (device, 0, sizeof (*device)); + SDL_memset (hidden, 0, sizeof (*hidden)); device->hidden = hidden; - device->VideoInit = QZ_VideoInit; - device->ListModes = QZ_ListModes; - device->SetVideoMode = QZ_SetVideoMode; + device->VideoInit = QZ_VideoInit; + device->ListModes = QZ_ListModes; + device->SetVideoMode = QZ_SetVideoMode; device->ToggleFullScreen = QZ_ToggleFullScreen; - device->UpdateMouse = QZ_UpdateMouse; - device->SetColors = QZ_SetColors; + device->UpdateMouse = QZ_UpdateMouse; + device->SetColors = QZ_SetColors; /* device->UpdateRects = QZ_UpdateRects; this is determined by SetVideoMode() */ - device->VideoQuit = QZ_VideoQuit; + device->VideoQuit = QZ_VideoQuit; - device->LockHWSurface = QZ_LockHWSurface; + device->LockHWSurface = QZ_LockHWSurface; device->UnlockHWSurface = QZ_UnlockHWSurface; - device->AllocHWSurface = QZ_AllocHWSurface; - device->FreeHWSurface = QZ_FreeHWSurface; - /* device->FlipHWSurface = QZ_FlipHWSurface */; + device->AllocHWSurface = QZ_AllocHWSurface; + device->FreeHWSurface = QZ_FreeHWSurface; + /* device->FlipHWSurface = QZ_FlipHWSurface */ ; - device->SetGamma = QZ_SetGamma; - device->GetGamma = QZ_GetGamma; + device->SetGamma = QZ_SetGamma; + device->GetGamma = QZ_GetGamma; device->SetGammaRamp = QZ_SetGammaRamp; device->GetGammaRamp = QZ_GetGammaRamp; device->GL_GetProcAddress = QZ_GL_GetProcAddress; - device->GL_GetAttribute = QZ_GL_GetAttribute; - device->GL_MakeCurrent = QZ_GL_MakeCurrent; - device->GL_SwapBuffers = QZ_GL_SwapBuffers; - device->GL_LoadLibrary = QZ_GL_LoadLibrary; + device->GL_GetAttribute = QZ_GL_GetAttribute; + device->GL_MakeCurrent = QZ_GL_MakeCurrent; + device->GL_SwapBuffers = QZ_GL_SwapBuffers; + device->GL_LoadLibrary = QZ_GL_LoadLibrary; - device->FreeWMCursor = QZ_FreeWMCursor; + device->FreeWMCursor = QZ_FreeWMCursor; device->CreateWMCursor = QZ_CreateWMCursor; - device->ShowWMCursor = QZ_ShowWMCursor; - device->WarpWMCursor = QZ_WarpWMCursor; - device->MoveWMCursor = QZ_MoveWMCursor; + device->ShowWMCursor = QZ_ShowWMCursor; + device->WarpWMCursor = QZ_WarpWMCursor; + device->MoveWMCursor = QZ_MoveWMCursor; device->CheckMouseMode = QZ_CheckMouseMode; - device->InitOSKeymap = QZ_InitOSKeymap; - device->PumpEvents = QZ_PumpEvents; + device->InitOSKeymap = QZ_InitOSKeymap; + device->PumpEvents = QZ_PumpEvents; - device->SetCaption = QZ_SetCaption; - device->SetIcon = QZ_SetIcon; + device->SetCaption = QZ_SetCaption; + device->SetIcon = QZ_SetIcon; device->IconifyWindow = QZ_IconifyWindow; - /*device->GetWMInfo = QZ_GetWMInfo;*/ - device->GrabInput = QZ_GrabInput; + /*device->GetWMInfo = QZ_GetWMInfo; */ + device->GrabInput = QZ_GrabInput; - device->CreateYUVOverlay = QZ_CreateYUVOverlay; + device->CreateYUVOverlay = QZ_CreateYUVOverlay; - device->free = QZ_DeleteDevice; + device->free = QZ_DeleteDevice; return device; } -static void QZ_DeleteDevice (SDL_VideoDevice *device) { +static void +QZ_DeleteDevice (SDL_VideoDevice * device) +{ SDL_free (device->hidden); SDL_free (device); } -static int QZ_VideoInit (_THIS, SDL_PixelFormat *video_format) { +static int +QZ_VideoInit (_THIS, SDL_PixelFormat * video_format) +{ /* Initialize the video settings; this data persists between mode switches */ display_id = kCGDirectMainDisplay; - save_mode = CGDisplayCurrentMode (display_id); - mode_list = CGDisplayAvailableModes (display_id); - palette = CGPaletteCreateDefaultColorPalette (); + save_mode = CGDisplayCurrentMode (display_id); + mode_list = CGDisplayAvailableModes (display_id); + palette = CGPaletteCreateDefaultColorPalette (); /* Gather some information that is useful to know about the display */ - CFNumberGetValue (CFDictionaryGetValue (save_mode, kCGDisplayBitsPerPixel), + CFNumberGetValue (CFDictionaryGetValue + (save_mode, kCGDisplayBitsPerPixel), kCFNumberSInt32Type, &device_bpp); CFNumberGetValue (CFDictionaryGetValue (save_mode, kCGDisplayWidth), @@ -209,23 +215,25 @@ static int QZ_VideoInit (_THIS, SDL_PixelFormat *video_format) { /* Set misc globals */ current_grab_mode = SDL_GRAB_OFF; - cursor_should_be_visible = YES; - cursor_visible = YES; + cursor_should_be_visible = YES; + cursor_visible = YES; current_mods = 0; - - if ( Gestalt(gestaltSystemVersion, &system_version) != noErr ) + + if (Gestalt (gestaltSystemVersion, &system_version) != noErr) system_version = 0; - + /* register for sleep notifications so wake from sleep generates SDL_VIDEOEXPOSE */ QZ_RegisterForSleepNotifications (this); - + /* Fill in some window manager capabilities */ this->info.wm_available = 1; return 0; } -static SDL_Rect** QZ_ListModes (_THIS, SDL_PixelFormat *format, Uint32 flags) { +static SDL_Rect ** +QZ_ListModes (_THIS, SDL_PixelFormat * format, Uint32 flags) +{ CFIndex num_modes; CFIndex i; @@ -233,11 +241,11 @@ static int QZ_VideoInit (_THIS, SDL_PixelFormat *video_format) { int list_size = 0; /* Any windowed mode is acceptable */ - if ( (flags & SDL_FULLSCREEN) == 0 ) - return (SDL_Rect**)-1; + if ((flags & SDL_FULLSCREEN) == 0) + return (SDL_Rect **) - 1; /* Free memory from previous call, if any */ - if ( client_mode_list != NULL ) { + if (client_mode_list != NULL) { int i; @@ -254,7 +262,7 @@ static int QZ_VideoInit (_THIS, SDL_PixelFormat *video_format) { for (i = 0; i < num_modes; i++) { CFDictionaryRef onemode; - CFNumberRef number; + CFNumberRef number; int bpp; onemode = CFArrayGetValueAtIndex (mode_list, i); @@ -280,7 +288,7 @@ static int QZ_VideoInit (_THIS, SDL_PixelFormat *video_format) { int i; hasMode = SDL_FALSE; for (i = 0; i < list_size; i++) { - if (client_mode_list[i]->w == width && + if (client_mode_list[i]->w == width && client_mode_list[i]->h == height) { hasMode = SDL_TRUE; break; @@ -289,20 +297,24 @@ static int QZ_VideoInit (_THIS, SDL_PixelFormat *video_format) { } /* Grow the list and add mode to the list */ - if ( ! hasMode ) { + if (!hasMode) { SDL_Rect *rect; list_size++; if (client_mode_list == NULL) - client_mode_list = (SDL_Rect**) - SDL_malloc (sizeof(*client_mode_list) * (list_size+1) ); + client_mode_list = (SDL_Rect **) + SDL_malloc (sizeof (*client_mode_list) * + (list_size + 1)); else - client_mode_list = (SDL_Rect**) - SDL_realloc (client_mode_list, sizeof(*client_mode_list) * (list_size+1)); + client_mode_list = (SDL_Rect **) + SDL_realloc (client_mode_list, + sizeof (*client_mode_list) * + (list_size + 1)); - rect = (SDL_Rect*) SDL_malloc (sizeof(**client_mode_list)); + rect = (SDL_Rect *) + SDL_malloc (sizeof (**client_mode_list)); if (client_mode_list == NULL || rect == NULL) { SDL_OutOfMemory (); @@ -313,8 +325,8 @@ static int QZ_VideoInit (_THIS, SDL_PixelFormat *video_format) { rect->w = width; rect->h = height; - client_mode_list[list_size-1] = rect; - client_mode_list[list_size] = NULL; + client_mode_list[list_size - 1] = rect; + client_mode_list[list_size] = NULL; } } } @@ -323,16 +335,17 @@ static int QZ_VideoInit (_THIS, SDL_PixelFormat *video_format) { { int i, j; for (i = 0; i < list_size; i++) { - for (j = 0; j < list_size-1; j++) { + for (j = 0; j < list_size - 1; j++) { int area1, area2; area1 = client_mode_list[j]->w * client_mode_list[j]->h; - area2 = client_mode_list[j+1]->w * client_mode_list[j+1]->h; + area2 = + client_mode_list[j + 1]->w * client_mode_list[j + 1]->h; if (area1 < area2) { SDL_Rect *tmp = client_mode_list[j]; - client_mode_list[j] = client_mode_list[j+1]; - client_mode_list[j+1] = tmp; + client_mode_list[j] = client_mode_list[j + 1]; + client_mode_list[j + 1] = tmp; } } } @@ -340,33 +353,36 @@ static int QZ_VideoInit (_THIS, SDL_PixelFormat *video_format) { return client_mode_list; } -static SDL_bool QZ_WindowPosition(_THIS, int *x, int *y) +static SDL_bool +QZ_WindowPosition (_THIS, int *x, int *y) { - const char *window = getenv("SDL_VIDEO_WINDOW_POS"); - if ( window ) { - if ( sscanf(window, "%d,%d", x, y) == 2 ) { + const char *window = getenv ("SDL_VIDEO_WINDOW_POS"); + if (window) { + if (sscanf (window, "%d,%d", x, y) == 2) { return SDL_TRUE; } } return SDL_FALSE; } -static void QZ_UnsetVideoMode (_THIS, BOOL to_desktop) { +static void +QZ_UnsetVideoMode (_THIS, BOOL to_desktop) +{ /* Reset values that may change between switches */ - this->info.blit_fill = 0; - this->FillHWRect = NULL; - this->UpdateRects = NULL; - this->LockHWSurface = NULL; + this->info.blit_fill = 0; + this->FillHWRect = NULL; + this->UpdateRects = NULL; + this->LockHWSurface = NULL; this->UnlockHWSurface = NULL; - + /* Release fullscreen resources */ - if ( mode_flags & SDL_FULLSCREEN ) { + if (mode_flags & SDL_FULLSCREEN) { NSRect screen_rect; - + /* Release double buffer stuff */ - if ( mode_flags & SDL_DOUBLEBUF) { + if (mode_flags & SDL_DOUBLEBUF) { quit_thread = YES; SDL_SemPost (sem1); SDL_WaitThread (thread, NULL); @@ -374,13 +390,13 @@ static void QZ_UnsetVideoMode (_THIS, BOOL to_desktop) { SDL_DestroySemaphore (sem2); SDL_free (sw_buffers[0]); } - + /* - Release the OpenGL context - Do this first to avoid trash on the display before fade - */ - if ( mode_flags & SDL_OPENGL ) { - + Release the OpenGL context + Do this first to avoid trash on the display before fade + */ + if (mode_flags & SDL_INTERNALOPENGL) { + QZ_TearDownOpenGL (this); CGLSetFullScreen (NULL); } @@ -390,23 +406,23 @@ static void QZ_UnsetVideoMode (_THIS, BOOL to_desktop) { CGReleaseAllDisplays (); ShowMenuBar (); /* - Reset the main screen's rectangle - See comment in QZ_SetVideoFullscreen for why we do this - */ - screen_rect = NSMakeRect(0,0,device_width,device_height); - [ [ NSScreen mainScreen ] setFrame:screen_rect ]; + Reset the main screen's rectangle + See comment in QZ_SetVideoFullscreen for why we do this + */ + screen_rect = NSMakeRect (0, 0, device_width, device_height); + [[NSScreen mainScreen] setFrame:screen_rect]; } } /* Release window mode resources */ else { - - [ qz_window close ]; - [ qz_window release ]; + + [qz_window close]; + [qz_window release]; qz_window = nil; window_view = nil; /* Release the OpenGL context */ - if ( mode_flags & SDL_OPENGL ) + if (mode_flags & SDL_INTERNALOPENGL) QZ_TearDownOpenGL (this); } @@ -414,19 +430,23 @@ static void QZ_UnsetVideoMode (_THIS, BOOL to_desktop) { video_set = SDL_FALSE; } -static SDL_Surface* QZ_SetVideoFullScreen (_THIS, SDL_Surface *current, int width, - int height, int bpp, Uint32 flags) { +static SDL_Surface * +QZ_SetVideoFullScreen (_THIS, SDL_Surface * current, int width, + int height, int bpp, Uint32 flags) +{ boolean_t exact_match = 0; NSRect screen_rect; CGError error; - CGDisplayFadeReservationToken fade_token = kCGDisplayFadeReservationInvalidToken; - + CGDisplayFadeReservationToken fade_token = + kCGDisplayFadeReservationInvalidToken; + /* Fade to black to hide resolution-switching flicker (and garbage that is displayed by a destroyed OpenGL context, if applicable) */ - if ( CGAcquireDisplayFadeReservation (5, &fade_token) == kCGErrorSuccess ) { - CGDisplayFade (fade_token, 0.3, kCGDisplayBlendNormal, kCGDisplayBlendSolidColor, 0.0, 0.0, 0.0, TRUE); + if (CGAcquireDisplayFadeReservation (5, &fade_token) == kCGErrorSuccess) { + CGDisplayFade (fade_token, 0.3, kCGDisplayBlendNormal, + kCGDisplayBlendSolidColor, 0.0, 0.0, 0.0, TRUE); } - + /* Destroy any previous mode */ if (video_set == SDL_TRUE) QZ_UnsetVideoMode (this, FALSE); @@ -436,8 +456,9 @@ static void QZ_UnsetVideoMode (_THIS, BOOL to_desktop) { height, &exact_match); /* Require an exact match to the requested mode */ - if ( ! exact_match ) { - SDL_SetError ("Failed to find display resolution: %dx%dx%d", width, height, bpp); + if (!exact_match) { + SDL_SetError ("Failed to find display resolution: %dx%dx%d", width, + height, bpp); goto ERR_NO_MATCH; } @@ -446,20 +467,20 @@ static void QZ_UnsetVideoMode (_THIS, BOOL to_desktop) { error = CGDisplayCapture (display_id); else error = CGCaptureAllDisplays (); - - if ( CGDisplayNoErr != error ) { + + if (CGDisplayNoErr != error) { SDL_SetError ("Failed capturing display"); goto ERR_NO_CAPTURE; } /* Do the physical switch */ - if ( CGDisplayNoErr != CGDisplaySwitchToMode (display_id, mode) ) { + if (CGDisplayNoErr != CGDisplaySwitchToMode (display_id, mode)) { SDL_SetError ("Failed switching display resolution"); goto ERR_NO_SWITCH; } - current->pixels = (Uint32*) CGDisplayBaseAddress (display_id); - current->pitch = CGDisplayBytesPerRow (display_id); + current->pixels = (Uint32 *) CGDisplayBaseAddress (display_id); + current->pitch = CGDisplayBytesPerRow (display_id); current->flags = 0; current->w = width; @@ -467,27 +488,27 @@ static void QZ_UnsetVideoMode (_THIS, BOOL to_desktop) { current->flags |= SDL_FULLSCREEN; current->flags |= SDL_HWSURFACE; current->flags |= SDL_PREALLOC; - - this->UpdateRects = QZ_DirectUpdate; - this->LockHWSurface = QZ_LockHWSurface; + + this->UpdateRects = QZ_DirectUpdate; + this->LockHWSurface = QZ_LockHWSurface; this->UnlockHWSurface = QZ_UnlockHWSurface; /* Setup double-buffer emulation */ - if ( flags & SDL_DOUBLEBUF ) { - + if (flags & SDL_DOUBLEBUF) { + /* - Setup a software backing store for reasonable results when - double buffering is requested (since a single-buffered hardware - surface looks hideous). - - The actual screen blit occurs in a separate thread to allow - other blitting while waiting on the VBL (and hence results in higher framerates). - */ + Setup a software backing store for reasonable results when + double buffering is requested (since a single-buffered hardware + surface looks hideous). + + The actual screen blit occurs in a separate thread to allow + other blitting while waiting on the VBL (and hence results in higher framerates). + */ this->LockHWSurface = NULL; this->UnlockHWSurface = NULL; this->UpdateRects = NULL; - - current->flags |= (SDL_HWSURFACE|SDL_DOUBLEBUF); + + current->flags |= (SDL_HWSURFACE | SDL_DOUBLEBUF); this->UpdateRects = QZ_DoubleBufferUpdate; this->LockHWSurface = QZ_LockDoubleBuffer; this->UnlockHWSurface = QZ_UnlockDoubleBuffer; @@ -498,234 +519,244 @@ other blitting while waiting on the VBL (and hence results in higher framerates) SDL_OutOfMemory (); goto ERR_DOUBLEBUF; } - + sw_buffers[0] = current->pixels; - sw_buffers[1] = (Uint8*)current->pixels + current->pitch * current->h; - + sw_buffers[1] = + (Uint8 *) current->pixels + current->pitch * current->h; + quit_thread = NO; sem1 = SDL_CreateSemaphore (0); sem2 = SDL_CreateSemaphore (1); - thread = SDL_CreateThread ((int (*)(void *))QZ_ThreadFlip, this); + thread = SDL_CreateThread ((int (*)(void *)) QZ_ThreadFlip, this); } - if ( CGDisplayCanSetPalette (display_id) ) + if (CGDisplayCanSetPalette (display_id)) current->flags |= SDL_HWPALETTE; /* Setup OpenGL for a fullscreen context */ - if (flags & SDL_OPENGL) { + if (flags & SDL_INTERNALOPENGL) { CGLError err; CGLContextObj ctx; - if ( ! QZ_SetupOpenGL (this, bpp, flags) ) { + if (!QZ_SetupOpenGL (this, bpp, flags)) { goto ERR_NO_GL; } - ctx = [ gl_context cglContext ]; + ctx =[gl_context cglContext]; err = CGLSetFullScreen (ctx); if (err) { - SDL_SetError ("Error setting OpenGL fullscreen: %s", CGLErrorString(err)); + SDL_SetError ("Error setting OpenGL fullscreen: %s", + CGLErrorString (err)); goto ERR_NO_GL; } - [ gl_context makeCurrentContext]; + [gl_context makeCurrentContext]; glClear (GL_COLOR_BUFFER_BIT); - [ gl_context flushBuffer ]; + [gl_context flushBuffer]; - current->flags |= SDL_OPENGL; + current->flags |= SDL_INTERNALOPENGL; } /* If we don't hide menu bar, it will get events and interrupt the program */ HideMenuBar (); /* Fade in again (asynchronously) */ - if ( fade_token != kCGDisplayFadeReservationInvalidToken ) { - CGDisplayFade (fade_token, 0.5, kCGDisplayBlendSolidColor, kCGDisplayBlendNormal, 0.0, 0.0, 0.0, FALSE); - CGReleaseDisplayFadeReservation(fade_token); + if (fade_token != kCGDisplayFadeReservationInvalidToken) { + CGDisplayFade (fade_token, 0.5, kCGDisplayBlendSolidColor, + kCGDisplayBlendNormal, 0.0, 0.0, 0.0, FALSE); + CGReleaseDisplayFadeReservation (fade_token); } /* - There is a bug in Cocoa where NSScreen doesn't synchronize - with CGDirectDisplay, so the main screen's frame is wrong. - As a result, coordinate translation produces incorrect results. - We can hack around this bug by setting the screen rect - ourselves. This hack should be removed if/when the bug is fixed. - */ - screen_rect = NSMakeRect(0,0,width,height); - [ [ NSScreen mainScreen ] setFrame:screen_rect ]; + There is a bug in Cocoa where NSScreen doesn't synchronize + with CGDirectDisplay, so the main screen's frame is wrong. + As a result, coordinate translation produces incorrect results. + We can hack around this bug by setting the screen rect + ourselves. This hack should be removed if/when the bug is fixed. + */ + screen_rect = NSMakeRect (0, 0, width, height); + [[NSScreen mainScreen] setFrame:screen_rect]; /* Save the flags to ensure correct tear-down */ mode_flags = current->flags; /* Set app state, hide cursor if necessary, ... */ - QZ_DoActivate(this); + QZ_DoActivate (this); return current; /* Since the blanking window covers *all* windows (even force quit) correct recovery is crucial */ -ERR_NO_GL: -ERR_DOUBLEBUF: CGDisplaySwitchToMode (display_id, save_mode); -ERR_NO_SWITCH: CGReleaseAllDisplays (); -ERR_NO_CAPTURE: -ERR_NO_MATCH: if ( fade_token != kCGDisplayFadeReservationInvalidToken ) { - CGDisplayFade (fade_token, 0.5, kCGDisplayBlendSolidColor, kCGDisplayBlendNormal, 0.0, 0.0, 0.0, FALSE); - CGReleaseDisplayFadeReservation (fade_token); - } - return NULL; + ERR_NO_GL: + ERR_DOUBLEBUF:CGDisplaySwitchToMode (display_id, save_mode); + ERR_NO_SWITCH:CGReleaseAllDisplays (); + ERR_NO_CAPTURE: + ERR_NO_MATCH:if (fade_token != kCGDisplayFadeReservationInvalidToken) { + CGDisplayFade (fade_token, 0.5, kCGDisplayBlendSolidColor, + kCGDisplayBlendNormal, 0.0, 0.0, 0.0, FALSE); + CGReleaseDisplayFadeReservation (fade_token); + } + return NULL; } -static SDL_Surface* QZ_SetVideoWindowed (_THIS, SDL_Surface *current, int width, - int height, int *bpp, Uint32 flags) { +static SDL_Surface * +QZ_SetVideoWindowed (_THIS, SDL_Surface * current, int width, + int height, int *bpp, Uint32 flags) +{ unsigned int style; NSRect contentRect; BOOL isCustom = NO; int center_window = 1; int origin_x, origin_y; - CGDisplayFadeReservationToken fade_token = kCGDisplayFadeReservationInvalidToken; + CGDisplayFadeReservationToken fade_token = + kCGDisplayFadeReservationInvalidToken; current->flags = 0; current->w = width; current->h = height; - + contentRect = NSMakeRect (0, 0, width, height); - + /* - Check if we should completely destroy the previous mode - - If it is fullscreen - - If it has different noframe or resizable attribute - - If it is OpenGL (since gl attributes could be different) - - If new mode is OpenGL, but previous mode wasn't - */ + Check if we should completely destroy the previous mode + - If it is fullscreen + - If it has different noframe or resizable attribute + - If it is OpenGL (since gl attributes could be different) + - If new mode is OpenGL, but previous mode wasn't + */ if (video_set == SDL_TRUE) { if (mode_flags & SDL_FULLSCREEN) { /* Fade to black to hide resolution-switching flicker (and garbage that is displayed by a destroyed OpenGL context, if applicable) */ - if (CGAcquireDisplayFadeReservation (5, &fade_token) == kCGErrorSuccess) { - CGDisplayFade (fade_token, 0.3, kCGDisplayBlendNormal, kCGDisplayBlendSolidColor, 0.0, 0.0, 0.0, TRUE); + if (CGAcquireDisplayFadeReservation (5, &fade_token) == + kCGErrorSuccess) { + CGDisplayFade (fade_token, 0.3, kCGDisplayBlendNormal, + kCGDisplayBlendSolidColor, 0.0, 0.0, 0.0, + TRUE); } QZ_UnsetVideoMode (this, TRUE); - } - else if ( ((mode_flags ^ flags) & (SDL_NOFRAME|SDL_RESIZABLE)) || - (mode_flags & SDL_OPENGL) || - (flags & SDL_OPENGL) ) { + } else if (((mode_flags ^ flags) & (SDL_NOFRAME | SDL_RESIZABLE)) || + (mode_flags & SDL_INTERNALOPENGL) || + (flags & SDL_INTERNALOPENGL)) { QZ_UnsetVideoMode (this, TRUE); } } - + /* Check for user-specified window and view */ { char *windowPtrString = getenv ("SDL_NSWindowPointer"); char *viewPtrString = getenv ("SDL_NSQuickDrawViewPointer"); - + if (windowPtrString && viewPtrString) { - + /* Release any previous window */ - if ( qz_window ) { - [ qz_window release ]; + if (qz_window) { + [qz_window release]; qz_window = nil; } - - qz_window = (NSWindow*)atoi(windowPtrString); - window_view = (NSQuickDrawView*)atoi(viewPtrString); + + qz_window = (NSWindow *) atoi (windowPtrString); + window_view = (NSQuickDrawView *) atoi (viewPtrString); isCustom = YES; - + /* - Retain reference to window because we - might release it in QZ_UnsetVideoMode - */ - [ qz_window retain ]; - - style = [ qz_window styleMask ]; + Retain reference to window because we + might release it in QZ_UnsetVideoMode + */ + [qz_window retain]; + + style =[qz_window styleMask]; /* Check resizability */ - if ( style & NSResizableWindowMask ) + if (style & NSResizableWindowMask) current->flags |= SDL_RESIZABLE; - + /* Check frame */ - if ( style & NSBorderlessWindowMask ) + if (style & NSBorderlessWindowMask) current->flags |= SDL_NOFRAME; } } - + /* Check if we should recreate the window */ if (qz_window == nil) { - + /* Set the window style based on input flags */ - if ( flags & SDL_NOFRAME ) { + if (flags & SDL_NOFRAME) { style = NSBorderlessWindowMask; current->flags |= SDL_NOFRAME; } else { style = NSTitledWindowMask; style |= (NSMiniaturizableWindowMask | NSClosableWindowMask); - if ( flags & SDL_RESIZABLE ) { + if (flags & SDL_RESIZABLE) { style |= NSResizableWindowMask; current->flags |= SDL_RESIZABLE; } } - - if ( QZ_WindowPosition(this, &origin_x, &origin_y) ) { + + if (QZ_WindowPosition (this, &origin_x, &origin_y)) { center_window = 0; - contentRect.origin.x = (float)origin_x; - contentRect.origin.y = (float)origin_y; + contentRect.origin.x = (float) origin_x; + contentRect.origin.y = (float) origin_y; } - + /* Manually create a window, avoids having a nib file resource */ - qz_window = [ [ SDL_QuartzWindow alloc ] - initWithContentRect:contentRect - styleMask:style - backing:NSBackingStoreBuffered - defer:NO ]; - + qz_window =[[SDL_QuartzWindow alloc] initWithContentRect: contentRect styleMask: style backing: NSBackingStoreBuffered defer:NO]; + if (qz_window == nil) { SDL_SetError ("Could not create the Cocoa window"); if (fade_token != kCGDisplayFadeReservationInvalidToken) { - CGDisplayFade (fade_token, 0.5, kCGDisplayBlendSolidColor, kCGDisplayBlendNormal, 0.0, 0.0, 0.0, FALSE); + CGDisplayFade (fade_token, 0.5, + kCGDisplayBlendSolidColor, + kCGDisplayBlendNormal, 0.0, 0.0, 0.0, FALSE); CGReleaseDisplayFadeReservation (fade_token); } return NULL; } - - /*[ qz_window setReleasedWhenClosed:YES ];*/ - QZ_SetCaption(this, this->wm_title, this->wm_icon); - [ qz_window setAcceptsMouseMovedEvents:YES ]; - [ qz_window setViewsNeedDisplay:NO ]; - if ( center_window ) { - [ qz_window center ]; + + /*[ qz_window setReleasedWhenClosed:YES ]; */ + QZ_SetCaption (this, this->wm_title, this->wm_icon); + [qz_window setAcceptsMouseMovedEvents:YES]; + [qz_window setViewsNeedDisplay:NO]; + if (center_window) { + [qz_window center]; } - [ qz_window setDelegate: - [ [ [ SDL_QuartzWindowDelegate alloc ] init ] autorelease ] ]; + [qz_window setDelegate: +[[[SDL_QuartzWindowDelegate alloc] init] autorelease]]; } /* We already have a window, just change its size */ else { - + if (!isCustom) { - [ qz_window setContentSize:contentRect.size ]; - current->flags |= (SDL_NOFRAME|SDL_RESIZABLE) & mode_flags; - [ window_view setFrameSize:contentRect.size ]; + [qz_window setContentSize:contentRect.size]; + current->flags |= (SDL_NOFRAME | SDL_RESIZABLE) & mode_flags; + [window_view setFrameSize:contentRect.size]; } } /* For OpenGL, we bind the context to a subview */ - if ( flags & SDL_OPENGL ) { + if (flags & SDL_INTERNALOPENGL) { - if ( ! QZ_SetupOpenGL (this, *bpp, flags) ) { + if (!QZ_SetupOpenGL (this, *bpp, flags)) { if (fade_token != kCGDisplayFadeReservationInvalidToken) { - CGDisplayFade (fade_token, 0.5, kCGDisplayBlendSolidColor, kCGDisplayBlendNormal, 0.0, 0.0, 0.0, FALSE); + CGDisplayFade (fade_token, 0.5, + kCGDisplayBlendSolidColor, + kCGDisplayBlendNormal, 0.0, 0.0, 0.0, FALSE); CGReleaseDisplayFadeReservation (fade_token); } return NULL; } - window_view = [ [ NSView alloc ] initWithFrame:contentRect ]; - [ window_view setAutoresizingMask: NSViewWidthSizable | NSViewHeightSizable ]; - [ [ qz_window contentView ] addSubview:window_view ]; - [ gl_context setView: window_view ]; - [ window_view release ]; - [ gl_context makeCurrentContext]; - [ qz_window makeKeyAndOrderFront:nil ]; - current->flags |= SDL_OPENGL; + window_view =[[NSView alloc] initWithFrame:contentRect]; + [window_view setAutoresizingMask:NSViewWidthSizable | + NSViewHeightSizable]; + [[qz_window contentView] addSubview:window_view]; + [gl_context setView:window_view]; + [window_view release]; + [gl_context makeCurrentContext]; + [qz_window makeKeyAndOrderFront:nil]; + current->flags |= SDL_INTERNALOPENGL; } /* For 2D, we set the subview to an NSQuickDrawView */ else { @@ -733,19 +764,22 @@ other blitting while waiting on the VBL (and hence results in higher framerates) /* Only recreate the view if it doesn't already exist */ if (window_view == nil) { - - window_view = [ [ NSQuickDrawView alloc ] initWithFrame:contentRect ]; - [ window_view setAutoresizingMask: NSViewWidthSizable | NSViewHeightSizable ]; - [ [ qz_window contentView ] addSubview:window_view ]; - [ window_view release ]; - [ qz_window makeKeyAndOrderFront:nil ]; + + window_view =[[NSQuickDrawView alloc] initWithFrame:contentRect]; + [window_view setAutoresizingMask:NSViewWidthSizable | + NSViewHeightSizable]; + [[qz_window contentView] addSubview:window_view]; + [window_view release]; + [qz_window makeKeyAndOrderFront:nil]; } - - LockPortBits ( [ window_view qdPort ] ); - current->pixels = GetPixBaseAddr ( GetPortPixMap ( [ window_view qdPort ] ) ); - current->pitch = GetPixRowBytes ( GetPortPixMap ( [ window_view qdPort ] ) ); - qdbpp = GetPixDepth ( GetPortPixMap ( [ window_view qdPort ] ) ); - UnlockPortBits ( [ window_view qdPort ] ); + + LockPortBits ([window_view qdPort]); + current->pixels = + GetPixBaseAddr (GetPortPixMap ([window_view qdPort])); + current->pitch = + GetPixRowBytes (GetPortPixMap ([window_view qdPort])); + qdbpp = GetPixDepth (GetPortPixMap ([window_view qdPort])); + UnlockPortBits ([window_view qdPort]); /* QuickDraw may give a 16-bit shadow surface on 8-bit displays! */ *bpp = qdbpp; @@ -753,21 +787,23 @@ other blitting while waiting on the VBL (and hence results in higher framerates) current->flags |= SDL_SWSURFACE; current->flags |= SDL_PREALLOC; current->flags |= SDL_ASYNCBLIT; - + /* - current->pixels now points to the window's pixels - We want it to point to the *view's* pixels - */ - { - int vOffset = [ qz_window frame ].size.height - - [ window_view frame ].size.height - [ window_view frame ].origin.y; - - int hOffset = [ window_view frame ].origin.x; - - current->pixels = (Uint8 *)current->pixels + (vOffset * current->pitch) + hOffset * (qdbpp/8); + current->pixels now points to the window's pixels + We want it to point to the *view's* pixels + */ + { + int vOffset =[qz_window frame].size.height - + [window_view frame].size.height -[window_view frame].origin.y; + + int hOffset =[window_view frame].origin.x; + + current->pixels = + (Uint8 *) current->pixels + (vOffset * current->pitch) + + hOffset * (qdbpp / 8); } - this->UpdateRects = QZ_UpdateRects; - this->LockHWSurface = QZ_LockWindow; + this->UpdateRects = QZ_UpdateRects; + this->LockHWSurface = QZ_LockWindow; this->UnlockHWSurface = QZ_UnlockWindow; } @@ -776,22 +812,26 @@ other blitting while waiting on the VBL (and hence results in higher framerates) /* Fade in again (asynchronously) if we came from a fullscreen mode and faded to black */ if (fade_token != kCGDisplayFadeReservationInvalidToken) { - CGDisplayFade (fade_token, 0.5, kCGDisplayBlendSolidColor, kCGDisplayBlendNormal, 0.0, 0.0, 0.0, FALSE); + CGDisplayFade (fade_token, 0.5, kCGDisplayBlendSolidColor, + kCGDisplayBlendNormal, 0.0, 0.0, 0.0, FALSE); CGReleaseDisplayFadeReservation (fade_token); } return current; } -static SDL_Surface* QZ_SetVideoMode (_THIS, SDL_Surface *current, int width, - int height, int bpp, Uint32 flags) { +static SDL_Surface * +QZ_SetVideoMode (_THIS, SDL_Surface * current, int width, + int height, int bpp, Uint32 flags) +{ current->flags = 0; current->pixels = NULL; /* Setup full screen video */ - if ( flags & SDL_FULLSCREEN ) { - current = QZ_SetVideoFullScreen (this, current, width, height, bpp, flags ); + if (flags & SDL_FULLSCREEN) { + current = + QZ_SetVideoFullScreen (this, current, width, height, bpp, flags); if (current == NULL) return NULL; } @@ -799,41 +839,38 @@ other blitting while waiting on the VBL (and hence results in higher framerates) else { /* Force bpp to the device's bpp */ bpp = device_bpp; - current = QZ_SetVideoWindowed (this, current, width, height, &bpp, flags); + current = + QZ_SetVideoWindowed (this, current, width, height, &bpp, flags); if (current == NULL) return NULL; } /* Setup the new pixel format */ { - int amask = 0, - rmask = 0, - gmask = 0, - bmask = 0; + int amask = 0, rmask = 0, gmask = 0, bmask = 0; switch (bpp) { - case 16: /* (1)-5-5-5 RGB */ - amask = 0; - rmask = 0x7C00; - gmask = 0x03E0; - bmask = 0x001F; - break; - case 24: - SDL_SetError ("24bpp is not available"); - return NULL; - case 32: /* (8)-8-8-8 ARGB */ - amask = 0x00000000; - rmask = 0x00FF0000; - gmask = 0x0000FF00; - bmask = 0x000000FF; - break; + case 16: /* (1)-5-5-5 RGB */ + amask = 0; + rmask = 0x7C00; + gmask = 0x03E0; + bmask = 0x001F; + break; + case 24: + SDL_SetError ("24bpp is not available"); + return NULL; + case 32: /* (8)-8-8-8 ARGB */ + amask = 0x00000000; + rmask = 0x00FF0000; + gmask = 0x0000FF00; + bmask = 0x000000FF; + break; } - if ( ! SDL_ReallocFormat (current, bpp, - rmask, gmask, bmask, amask ) ) { + if (!SDL_ReallocFormat (current, bpp, rmask, gmask, bmask, amask)) { SDL_SetError ("Couldn't reallocate pixel format"); return NULL; - } + } } /* Signal successful completion (used internally) */ @@ -842,21 +879,24 @@ other blitting while waiting on the VBL (and hence results in higher framerates) return current; } -static int QZ_ToggleFullScreen (_THIS, int on) { +static int +QZ_ToggleFullScreen (_THIS, int on) +{ return 0; } -static int QZ_SetColors (_THIS, int first_color, int num_colors, - SDL_Color *colors) { +static int +QZ_SetColors (_THIS, int first_color, int num_colors, SDL_Color * colors) +{ - CGTableCount index; + CGTableCount index; CGDeviceColor color; - for (index = first_color; index < first_color+num_colors; index++) { + for (index = first_color; index < first_color + num_colors; index++) { /* Clamp colors between 0.0 and 1.0 */ - color.red = colors->r / 255.0; - color.blue = colors->b / 255.0; + color.red = colors->r / 255.0; + color.blue = colors->b / 255.0; color.green = colors->g / 255.0; colors++; @@ -864,164 +904,185 @@ static int QZ_SetColors (_THIS, int first_color, int num_colors, CGPaletteSetColorAtIndex (palette, color, index); } - if ( CGDisplayNoErr != CGDisplaySetPalette (display_id, palette) ) + if (CGDisplayNoErr != CGDisplaySetPalette (display_id, palette)) return 0; return 1; } -static int QZ_LockDoubleBuffer (_THIS, SDL_Surface *surface) { +static int +QZ_LockDoubleBuffer (_THIS, SDL_Surface * surface) +{ return 1; } -static void QZ_UnlockDoubleBuffer (_THIS, SDL_Surface *surface) { +static void +QZ_UnlockDoubleBuffer (_THIS, SDL_Surface * surface) +{ } /* The VBL delay is based on code by Ian R Ollmann's RezLib */ - static AbsoluteTime QZ_SecondsToAbsolute ( double seconds ) { - +static AbsoluteTime +QZ_SecondsToAbsolute (double seconds) +{ + union { UInt64 i; Nanoseconds ns; } temp; - + temp.i = seconds * 1000000000.0; - - return NanosecondsToAbsolute ( temp.ns ); + + return NanosecondsToAbsolute (temp.ns); } -static int QZ_ThreadFlip (_THIS) { +static int +QZ_ThreadFlip (_THIS) +{ Uint8 *src, *dst; int skip, len, h; - + /* - Give this thread the highest scheduling priority possible, - in the hopes that it will immediately run after the VBL delay - */ + Give this thread the highest scheduling priority possible, + in the hopes that it will immediately run after the VBL delay + */ { pthread_t current_thread; int policy; struct sched_param param; - + current_thread = pthread_self (); pthread_getschedparam (current_thread, &policy, ¶m); policy = SCHED_RR; param.sched_priority = sched_get_priority_max (policy); pthread_setschedparam (current_thread, policy, ¶m); } - + while (1) { - + SDL_SemWait (sem1); if (quit_thread) return 0; - + /* * We have to add SDL_VideoSurface->offset here, since we might be a * smaller surface in the center of the framebuffer (you asked for * a fullscreen resolution smaller than the hardware could supply * so SDL is centering it in a bigger resolution)... */ - dst = (Uint8 *)CGDisplayBaseAddress (display_id) + SDL_VideoSurface->offset; + dst = + (Uint8 *) CGDisplayBaseAddress (display_id) + + SDL_VideoSurface->offset; src = current_buffer + SDL_VideoSurface->offset; len = SDL_VideoSurface->w * SDL_VideoSurface->format->BytesPerPixel; h = SDL_VideoSurface->h; skip = SDL_VideoSurface->pitch; - + /* Wait for the VBL to occur (estimated since we don't have a hardware interrupt) */ { - + /* The VBL delay is based on Ian Ollmann's RezLib */ double refreshRate; double linesPerSecond; double target; double position; double adjustment; - AbsoluteTime nextTime; + AbsoluteTime nextTime; CFNumberRef refreshRateCFNumber; - - refreshRateCFNumber = CFDictionaryGetValue (mode, kCGDisplayRefreshRate); - if ( NULL == refreshRateCFNumber ) { + + refreshRateCFNumber = + CFDictionaryGetValue (mode, kCGDisplayRefreshRate); + if (NULL == refreshRateCFNumber) { SDL_SetError ("Mode has no refresh rate"); goto ERROR; } - - if ( 0 == CFNumberGetValue (refreshRateCFNumber, kCFNumberDoubleType, &refreshRate) ) { + + if (0 == + CFNumberGetValue (refreshRateCFNumber, kCFNumberDoubleType, + &refreshRate)) { SDL_SetError ("Error getting refresh rate"); goto ERROR; } - - if ( 0 == refreshRate ) { - - SDL_SetError ("Display has no refresh rate, using 60hz"); - + + if (0 == refreshRate) { + + SDL_SetError ("Display has no refresh rate, using 60hz"); + /* ok, for LCD's we'll emulate a 60hz refresh, which may or may not look right */ refreshRate = 60.0; } - + linesPerSecond = refreshRate * h; target = h; - + /* Figure out the first delay so we start off about right */ position = CGDisplayBeamPosition (display_id); if (position > target) position = 0; - - adjustment = (target - position) / linesPerSecond; - - nextTime = AddAbsoluteToAbsolute (UpTime (), QZ_SecondsToAbsolute (adjustment)); - + + adjustment = (target - position) / linesPerSecond; + + nextTime = + AddAbsoluteToAbsolute (UpTime (), + QZ_SecondsToAbsolute (adjustment)); + MPDelayUntil (&nextTime); } - - + + /* On error, skip VBL delay */ - ERROR: - - while ( h-- ) { - + ERROR: + + while (h--) { + SDL_memcpy (dst, src, len); src += skip; dst += skip; } - + /* signal flip completion */ SDL_SemPost (sem2); } - + return 0; } - -static int QZ_FlipDoubleBuffer (_THIS, SDL_Surface *surface) { + +static int +QZ_FlipDoubleBuffer (_THIS, SDL_Surface * surface) +{ /* wait for previous flip to complete */ SDL_SemWait (sem2); - + current_buffer = surface->pixels; - + if (surface->pixels == sw_buffers[0]) surface->pixels = sw_buffers[1]; else surface->pixels = sw_buffers[0]; - + /* signal worker thread to do the flip */ SDL_SemPost (sem1); - + return 0; } -static void QZ_DoubleBufferUpdate (_THIS, int num_rects, SDL_Rect *rects) { +static void +QZ_DoubleBufferUpdate (_THIS, int num_rects, SDL_Rect * rects) +{ /* perform a flip if someone calls updaterects on a doublebuferred surface */ this->FlipHWSurface (this, SDL_VideoSurface); } -static void QZ_DirectUpdate (_THIS, int num_rects, SDL_Rect *rects) { +static void +QZ_DirectUpdate (_THIS, int num_rects, SDL_Rect * rects) +{ #pragma unused(this,num_rects,rects) } @@ -1036,97 +1097,101 @@ static void QZ_DirectUpdate (_THIS, int num_rects, SDL_Rect *rects) { #include "CGS.h" #endif -static int QZ_IsWindowObscured (NSWindow *window) { +static int +QZ_IsWindowObscured (NSWindow * window) +{ #if TEST_OBSCURED /* - In order to determine if a direct copy to the screen is possible, - we must figure out if there are any windows covering ours (including shadows). - This can be done by querying the window server about the on screen - windows for their screen rectangle and window level. - The procedure used below is puts accuracy before speed; however, it aims to call - the window server the fewest number of times possible to keep things reasonable. - In my testing on a 300mhz G3, this routine typically takes < 2 ms. -DW - - Notes: - -Calls into the Window Server involve IPC which is slow. - -Getting a rectangle seems slower than getting the window level - -The window list we get back is in sorted order, top to bottom - -On average, I suspect, most windows above ours are dock icon windows (hence optimization) - -Some windows above ours are always there, and cannot move or obscure us (menu bar) - - Bugs: - -no way (yet) to deactivate direct drawing when a window is dragged, - or suddenly obscured, so drawing continues and can produce garbage - We need some kind of locking mechanism on window movement to prevent this - - -deactivated normal windows use activated normal - window shadows (slight inaccuraccy) - */ + In order to determine if a direct copy to the screen is possible, + we must figure out if there are any windows covering ours (including shadows). + This can be done by querying the window server about the on screen + windows for their screen rectangle and window level. + The procedure used below is puts accuracy before speed; however, it aims to call + the window server the fewest number of times possible to keep things reasonable. + In my testing on a 300mhz G3, this routine typically takes < 2 ms. -DW + + Notes: + -Calls into the Window Server involve IPC which is slow. + -Getting a rectangle seems slower than getting the window level + -The window list we get back is in sorted order, top to bottom + -On average, I suspect, most windows above ours are dock icon windows (hence optimization) + -Some windows above ours are always there, and cannot move or obscure us (menu bar) + + Bugs: + -no way (yet) to deactivate direct drawing when a window is dragged, + or suddenly obscured, so drawing continues and can produce garbage + We need some kind of locking mechanism on window movement to prevent this + + -deactivated normal windows use activated normal + window shadows (slight inaccuraccy) + */ /* Cache the connection to the window server */ - static CGSConnectionID cgsConnection = (CGSConnectionID) -1; + static CGSConnectionID cgsConnection = (CGSConnectionID) - 1; /* Cache the dock icon windows */ - static CGSWindowID dockIcons[kMaxWindows]; - static int numCachedDockIcons = 0; + static CGSWindowID dockIcons[kMaxWindows]; + static int numCachedDockIcons = 0; - CGSWindowID windows[kMaxWindows]; - CGSWindowCount i, count; - CGSWindowLevel winLevel; - CGSRect winRect; + CGSWindowID windows[kMaxWindows]; + CGSWindowCount i, count; + CGSWindowLevel winLevel; + CGSRect winRect; CGSRect contentRect; - int windowNumber; - int firstDockIcon; - int dockIconCacheMiss; - int windowContentOffset; + int windowNumber; + int firstDockIcon; + int dockIconCacheMiss; + int windowContentOffset; - int obscured = SDL_TRUE; + int obscured = SDL_TRUE; - if ( [ window isVisible ] ) { + if ([window isVisible]) { /* - walk the window list looking for windows over top of - (or casting a shadow on) ours - */ + walk the window list looking for windows over top of + (or casting a shadow on) ours + */ /* Get a connection to the window server Should probably be moved out into SetVideoMode() or InitVideo() - */ - if (cgsConnection == (CGSConnectionID) -1) { + */ + if (cgsConnection == (CGSConnectionID) - 1) { cgsConnection = (CGSConnectionID) 0; cgsConnection = _CGSDefaultConnection (); } if (cgsConnection) { - if ( ! [ window styleMask ] & NSBorderlessWindowMask ) + if (![window styleMask] & NSBorderlessWindowMask) windowContentOffset = 22; else windowContentOffset = 0; - windowNumber = [ window windowNumber ]; + windowNumber =[window windowNumber]; /* The window list is sorted according to order on the screen */ count = 0; - CGSGetOnScreenWindowList (cgsConnection, 0, kMaxWindows, windows, &count); - CGSGetScreenRectForWindow (cgsConnection, windowNumber, &contentRect); + CGSGetOnScreenWindowList (cgsConnection, 0, kMaxWindows, + windows, &count); + CGSGetScreenRectForWindow (cgsConnection, windowNumber, + &contentRect); /* adjust rect for window title bar (if present) */ - contentRect.origin.y += windowContentOffset; + contentRect.origin.y += windowContentOffset; contentRect.size.height -= windowContentOffset; firstDockIcon = -1; dockIconCacheMiss = SDL_FALSE; /* - The first window is always an empty window with level kCGSWindowLevelTop - so start at index 1 - */ + The first window is always an empty window with level kCGSWindowLevelTop + so start at index 1 + */ for (i = 1; i < count; i++) { /* If we reach our window in the list, it cannot be obscured */ @@ -1134,8 +1199,7 @@ Should probably be moved out into SetVideoMode() or InitVideo() obscured = SDL_FALSE; break; - } - else { + } else { float shadowSide; float shadowTop; @@ -1175,58 +1239,54 @@ Should probably be moved out into SetVideoMode() or InitVideo() } continue; - } - else if (winLevel == kCGSWindowLevelMenuIgnore - /* winLevel == kCGSWindowLevelTop */) { + } else if (winLevel == kCGSWindowLevelMenuIgnore + /* winLevel == kCGSWindowLevelTop */ ) { - continue; /* cannot obscure window */ - } - else if (winLevel == kCGSWindowLevelDockMenu || - winLevel == kCGSWindowLevelMenu) { + continue; /* cannot obscure window */ + } else if (winLevel == kCGSWindowLevelDockMenu || + winLevel == kCGSWindowLevelMenu) { shadowSide = 18; shadowTop = 4; shadowBottom = 22; - } - else if (winLevel == kCGSWindowLevelUtility) { + } else if (winLevel == kCGSWindowLevelUtility) { shadowSide = 8; shadowTop = 4; shadowBottom = 12; - } - else if (winLevel == kCGSWindowLevelNormal) { + } else if (winLevel == kCGSWindowLevelNormal) { /* - These numbers are for foreground windows, - they are too big (but will work) for background windows - */ + These numbers are for foreground windows, + they are too big (but will work) for background windows + */ shadowSide = 20; shadowTop = 10; shadowBottom = 24; - } - else if (winLevel == kCGSWindowLevelDock) { + } else if (winLevel == kCGSWindowLevelDock) { /* Create dock icon cache */ - if (numCachedDockIcons != (i-firstDockIcon) || - dockIconCacheMiss) { + if (numCachedDockIcons != (i - firstDockIcon) + || dockIconCacheMiss) { numCachedDockIcons = i - firstDockIcon; - SDL_memcpy (dockIcons, &(windows[firstDockIcon]), - numCachedDockIcons * sizeof(*windows)); + SDL_memcpy (dockIcons, + &(windows[firstDockIcon]), + numCachedDockIcons * + sizeof (*windows)); } /* no shadow */ shadowSide = 0; shadowTop = 0; shadowBottom = 0; - } - else { + } else { /* - kCGSWindowLevelDockLabel, - kCGSWindowLevelDock, - kOther??? - */ + kCGSWindowLevelDockLabel, + kCGSWindowLevelDock, + kOther??? + */ /* no shadow */ shadowSide = 0; @@ -1234,7 +1294,8 @@ they are too big (but will work) for background windows shadowBottom = 0; } - CGSGetScreenRectForWindow (cgsConnection, windows[i], &winRect); + CGSGetScreenRectForWindow (cgsConnection, + windows[i], &winRect); winRect.origin.x -= shadowSide; winRect.origin.y -= shadowTop; @@ -1247,14 +1308,14 @@ they are too big (but will work) for background windows break; } - } /* window was not our window */ + } /* window was not our window */ - } /* iterate over windows */ + } /* iterate over windows */ - } /* get cgsConnection */ - - } /* window is visible */ - + } + /* get cgsConnection */ + } + /* window is visible */ return obscured; #else return SDL_TRUE; @@ -1263,118 +1324,162 @@ they are too big (but will work) for background windows /* Locking functions for the software window buffer */ -static int QZ_LockWindow (_THIS, SDL_Surface *surface) { - - return LockPortBits ( [ window_view qdPort ] ); +static int +QZ_LockWindow (_THIS, SDL_Surface * surface) +{ + + return LockPortBits ([window_view qdPort]); } -static void QZ_UnlockWindow (_THIS, SDL_Surface *surface) { +static void +QZ_UnlockWindow (_THIS, SDL_Surface * surface) +{ - UnlockPortBits ( [ window_view qdPort ] ); + UnlockPortBits ([window_view qdPort]); } /* Resize icon, BMP format */ static const unsigned char QZ_ResizeIcon[] = { - 0x42,0x4d,0x31,0x02,0x00,0x00,0x00,0x00,0x00,0x00,0x36,0x00,0x00,0x00,0x28,0x00, - 0x00,0x00,0x0d,0x00,0x00,0x00,0x0d,0x00,0x00,0x00,0x01,0x00,0x18,0x00,0x00,0x00, - 0x00,0x00,0xfb,0x01,0x00,0x00,0x13,0x0b,0x00,0x00,0x13,0x0b,0x00,0x00,0x00,0x00, - 0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, - 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, - 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x0b,0xff,0xff, - 0xff,0xda,0xda,0xda,0x87,0x87,0x87,0xe8,0xe8,0xe8,0xff,0xff,0xff,0xda,0xda,0xda, - 0x87,0x87,0x87,0xe8,0xe8,0xe8,0xff,0xff,0xff,0xda,0xda,0xda,0x87,0x87,0x87,0xe8, - 0xe8,0xe8,0xff,0xff,0xff,0x0b,0xff,0xff,0xff,0xff,0xff,0xff,0xda,0xda,0xda,0x87, - 0x87,0x87,0xe8,0xe8,0xe8,0xff,0xff,0xff,0xda,0xda,0xda,0x87,0x87,0x87,0xe8,0xe8, - 0xe8,0xff,0xff,0xff,0xda,0xda,0xda,0x87,0x87,0x87,0xff,0xff,0xff,0x0b,0xff,0xff, - 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xd5,0xd5,0xd5,0x87,0x87,0x87,0xe8,0xe8,0xe8, - 0xff,0xff,0xff,0xda,0xda,0xda,0x87,0x87,0x87,0xe8,0xe8,0xe8,0xff,0xff,0xff,0xda, - 0xda,0xda,0xff,0xff,0xff,0x0b,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, - 0xff,0xff,0xd7,0xd7,0xd7,0x87,0x87,0x87,0xe8,0xe8,0xe8,0xff,0xff,0xff,0xda,0xda, - 0xda,0x87,0x87,0x87,0xe8,0xe8,0xe8,0xff,0xff,0xff,0xff,0xff,0xff,0x0b,0xff,0xff, - 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xd7,0xd7,0xd7, - 0x87,0x87,0x87,0xe8,0xe8,0xe8,0xff,0xff,0xff,0xda,0xda,0xda,0x87,0x87,0x87,0xe8, - 0xe8,0xe8,0xff,0xff,0xff,0x0b,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, - 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xd7,0xd7,0xd7,0x87,0x87,0x87,0xe8,0xe8, - 0xe8,0xff,0xff,0xff,0xdc,0xdc,0xdc,0x87,0x87,0x87,0xff,0xff,0xff,0x0b,0xff,0xff, - 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, - 0xff,0xff,0xff,0xd9,0xd9,0xd9,0x87,0x87,0x87,0xe8,0xe8,0xe8,0xff,0xff,0xff,0xdc, - 0xdc,0xdc,0xff,0xff,0xff,0x0b,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, - 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xdb,0xdb, - 0xdb,0x87,0x87,0x87,0xe8,0xe8,0xe8,0xff,0xff,0xff,0xff,0xff,0xff,0x0b,0xff,0xff, - 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, - 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xdb,0xdb,0xdb,0x87,0x87,0x87,0xe8, - 0xe8,0xe8,0xff,0xff,0xff,0x0b,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, - 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, - 0xff,0xff,0xff,0xff,0xdc,0xdc,0xdc,0x87,0x87,0x87,0xff,0xff,0xff,0x0b,0xff,0xff, - 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, - 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xdc, - 0xdc,0xdc,0xff,0xff,0xff,0x0b,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, - 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, - 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x0b + 0x42, 0x4d, 0x31, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x36, 0x00, + 0x00, 0x00, 0x28, 0x00, + 0x00, 0x00, 0x0d, 0x00, 0x00, 0x00, 0x0d, 0x00, 0x00, 0x00, 0x01, 0x00, + 0x18, 0x00, 0x00, 0x00, + 0x00, 0x00, 0xfb, 0x01, 0x00, 0x00, 0x13, 0x0b, 0x00, 0x00, 0x13, 0x0b, + 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0x0b, 0xff, 0xff, + 0xff, 0xda, 0xda, 0xda, 0x87, 0x87, 0x87, 0xe8, 0xe8, 0xe8, 0xff, 0xff, + 0xff, 0xda, 0xda, 0xda, + 0x87, 0x87, 0x87, 0xe8, 0xe8, 0xe8, 0xff, 0xff, 0xff, 0xda, 0xda, 0xda, + 0x87, 0x87, 0x87, 0xe8, + 0xe8, 0xe8, 0xff, 0xff, 0xff, 0x0b, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xda, 0xda, 0xda, 0x87, + 0x87, 0x87, 0xe8, 0xe8, 0xe8, 0xff, 0xff, 0xff, 0xda, 0xda, 0xda, 0x87, + 0x87, 0x87, 0xe8, 0xe8, + 0xe8, 0xff, 0xff, 0xff, 0xda, 0xda, 0xda, 0x87, 0x87, 0x87, 0xff, 0xff, + 0xff, 0x0b, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xd5, 0xd5, 0xd5, 0x87, 0x87, + 0x87, 0xe8, 0xe8, 0xe8, + 0xff, 0xff, 0xff, 0xda, 0xda, 0xda, 0x87, 0x87, 0x87, 0xe8, 0xe8, 0xe8, + 0xff, 0xff, 0xff, 0xda, + 0xda, 0xda, 0xff, 0xff, 0xff, 0x0b, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xd7, 0xd7, 0xd7, 0x87, 0x87, 0x87, 0xe8, 0xe8, 0xe8, 0xff, + 0xff, 0xff, 0xda, 0xda, + 0xda, 0x87, 0x87, 0x87, 0xe8, 0xe8, 0xe8, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0x0b, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xd7, 0xd7, 0xd7, + 0x87, 0x87, 0x87, 0xe8, 0xe8, 0xe8, 0xff, 0xff, 0xff, 0xda, 0xda, 0xda, + 0x87, 0x87, 0x87, 0xe8, + 0xe8, 0xe8, 0xff, 0xff, 0xff, 0x0b, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xd7, 0xd7, 0xd7, 0x87, + 0x87, 0x87, 0xe8, 0xe8, + 0xe8, 0xff, 0xff, 0xff, 0xdc, 0xdc, 0xdc, 0x87, 0x87, 0x87, 0xff, 0xff, + 0xff, 0x0b, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xd9, 0xd9, 0xd9, 0x87, 0x87, 0x87, 0xe8, 0xe8, 0xe8, + 0xff, 0xff, 0xff, 0xdc, + 0xdc, 0xdc, 0xff, 0xff, 0xff, 0x0b, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xdb, 0xdb, + 0xdb, 0x87, 0x87, 0x87, 0xe8, 0xe8, 0xe8, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0x0b, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xdb, 0xdb, 0xdb, + 0x87, 0x87, 0x87, 0xe8, + 0xe8, 0xe8, 0xff, 0xff, 0xff, 0x0b, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xdc, 0xdc, 0xdc, 0x87, 0x87, 0x87, 0xff, 0xff, + 0xff, 0x0b, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xdc, + 0xdc, 0xdc, 0xff, 0xff, 0xff, 0x0b, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0x0b }; -static void QZ_DrawResizeIcon (_THIS, RgnHandle dirtyRegion) { +static void +QZ_DrawResizeIcon (_THIS, RgnHandle dirtyRegion) +{ /* Check if we should draw the resize icon */ if (SDL_VideoSurface->flags & SDL_RESIZABLE) { - - Rect icon; - SetRect (&icon, SDL_VideoSurface->w - 13, SDL_VideoSurface->h - 13, - SDL_VideoSurface->w, SDL_VideoSurface->h); - + + Rect icon; + SetRect (&icon, SDL_VideoSurface->w - 13, SDL_VideoSurface->h - 13, + SDL_VideoSurface->w, SDL_VideoSurface->h); + if (RectInRgn (&icon, dirtyRegion)) { - + SDL_Rect icon_rect; - + /* Create the icon image */ if (resize_icon == NULL) { - + SDL_RWops *rw; SDL_Surface *tmp; - - rw = SDL_RWFromConstMem (QZ_ResizeIcon, sizeof(QZ_ResizeIcon)); + + rw = SDL_RWFromConstMem (QZ_ResizeIcon, + sizeof (QZ_ResizeIcon)); tmp = SDL_LoadBMP_RW (rw, SDL_TRUE); - - resize_icon = SDL_ConvertSurface (tmp, SDL_VideoSurface->format, SDL_SRCCOLORKEY); + + resize_icon = + SDL_ConvertSurface (tmp, SDL_VideoSurface->format, + SDL_SRCCOLORKEY); SDL_SetColorKey (resize_icon, SDL_SRCCOLORKEY, 0xFFFFFF); - + SDL_FreeSurface (tmp); } - + icon_rect.x = SDL_VideoSurface->w - 13; icon_rect.y = SDL_VideoSurface->h - 13; icon_rect.w = 13; icon_rect.h = 13; - + SDL_BlitSurface (resize_icon, NULL, SDL_VideoSurface, &icon_rect); } } } -static void QZ_UpdateRects (_THIS, int numRects, SDL_Rect *rects) { +static void +QZ_UpdateRects (_THIS, int numRects, SDL_Rect * rects) +{ + + if ([qz_window isMiniaturized]) { - if (SDL_VideoSurface->flags & SDL_OPENGLBLIT) { - QZ_GL_SwapBuffers (this); - } - else if ( [ qz_window isMiniaturized ] ) { - /* Do nothing if miniaturized */ } - - else if ( ! QZ_IsWindowObscured (qz_window) ) { + + else if (!QZ_IsWindowObscured (qz_window)) { /* Use direct copy to flush contents to the display */ CGrafPtr savePort; CGrafPtr dstPort, srcPort; - const BitMap *dstBits, *srcBits; - Rect dstRect, srcRect; - Point offset; + const BitMap *dstBits, *srcBits; + Rect dstRect, srcRect; + Point offset; int i; GetPort (&savePort); - dstPort = CreateNewPortForCGDisplayID ((UInt32)display_id); - srcPort = [ window_view qdPort ]; + dstPort = CreateNewPortForCGDisplayID ((UInt32) display_id); + srcPort =[window_view qdPort]; offset.h = 0; offset.v = 0; @@ -1392,8 +1497,7 @@ static void QZ_UpdateRects (_THIS, int numRects, SDL_Rect *rects) { for (i = 0; i < numRects; i++) { SetRect (&srcRect, rects[i].x, rects[i].y, - rects[i].x + rects[i].w, - rects[i].y + rects[i].h); + rects[i].x + rects[i].w, rects[i].y + rects[i].h); SetRect (&dstRect, rects[i].x + offset.h, @@ -1401,18 +1505,16 @@ static void QZ_UpdateRects (_THIS, int numRects, SDL_Rect *rects) { rects[i].x + rects[i].w + offset.h, rects[i].y + rects[i].h + offset.v); - CopyBits (srcBits, dstBits, - &srcRect, &dstRect, srcCopy, NULL); + CopyBits (srcBits, dstBits, &srcRect, &dstRect, srcCopy, NULL); } SetPort (savePort); - } - else { + } else { /* Use QDFlushPortBuffer() to flush content to display */ int i; RgnHandle dirty = NewRgn (); - RgnHandle temp = NewRgn (); + RgnHandle temp = NewRgn (); SetEmptyRgn (dirty); @@ -1420,22 +1522,25 @@ static void QZ_UpdateRects (_THIS, int numRects, SDL_Rect *rects) { for (i = 0; i < numRects; i++) { MacSetRectRgn (temp, rects[i].x, rects[i].y, - rects[i].x + rects[i].w, rects[i].y + rects[i].h); + rects[i].x + rects[i].w, rects[i].y + rects[i].h); MacUnionRgn (dirty, temp, dirty); } QZ_DrawResizeIcon (this, dirty); - + /* Flush the dirty region */ - QDFlushPortBuffer ( [ window_view qdPort ], dirty ); + QDFlushPortBuffer ([window_view qdPort], dirty); DisposeRgn (dirty); DisposeRgn (temp); } } -static void QZ_VideoQuit (_THIS) { +static void +QZ_VideoQuit (_THIS) +{ - CGDisplayFadeReservationToken fade_token = kCGDisplayFadeReservationInvalidToken; + CGDisplayFadeReservationToken fade_token = + kCGDisplayFadeReservationInvalidToken; /* Restore gamma settings */ CGDisplayRestoreColorSyncSettings (); @@ -1443,33 +1548,37 @@ static void QZ_VideoQuit (_THIS) { /* Ensure the cursor will be visible and working when we quit */ CGDisplayShowCursor (display_id); CGAssociateMouseAndMouseCursorPosition (1); - + if (mode_flags & SDL_FULLSCREEN) { /* Fade to black to hide resolution-switching flicker (and garbage that is displayed by a destroyed OpenGL context, if applicable) */ - if (CGAcquireDisplayFadeReservation (5, &fade_token) == kCGErrorSuccess) { - CGDisplayFade (fade_token, 0.3, kCGDisplayBlendNormal, kCGDisplayBlendSolidColor, 0.0, 0.0, 0.0, TRUE); + if (CGAcquireDisplayFadeReservation (5, &fade_token) == + kCGErrorSuccess) { + CGDisplayFade (fade_token, 0.3, kCGDisplayBlendNormal, + kCGDisplayBlendSolidColor, 0.0, 0.0, 0.0, TRUE); } QZ_UnsetVideoMode (this, TRUE); if (fade_token != kCGDisplayFadeReservationInvalidToken) { - CGDisplayFade (fade_token, 0.5, kCGDisplayBlendSolidColor, kCGDisplayBlendNormal, 0.0, 0.0, 0.0, FALSE); + CGDisplayFade (fade_token, 0.5, kCGDisplayBlendSolidColor, + kCGDisplayBlendNormal, 0.0, 0.0, 0.0, FALSE); CGReleaseDisplayFadeReservation (fade_token); } - } - else + } else QZ_UnsetVideoMode (this, TRUE); - + CGPaletteRelease (palette); if (opengl_library) { - SDL_UnloadObject(opengl_library); + SDL_UnloadObject (opengl_library); opengl_library = NULL; } this->gl_config.driver_loaded = 0; } -#if 0 /* Not used (apparently, it's really slow) */ -static int QZ_FillHWRect (_THIS, SDL_Surface *dst, SDL_Rect *rect, Uint32 color) { +#if 0 /* Not used (apparently, it's really slow) */ +static int +QZ_FillHWRect (_THIS, SDL_Surface * dst, SDL_Rect * rect, Uint32 color) +{ CGSDisplayHWFill (display_id, rect->x, rect->y, rect->w, rect->h, color); @@ -1477,20 +1586,28 @@ static int QZ_FillHWRect (_THIS, SDL_Surface *dst, SDL_Rect *rect, Uint32 color } #endif -static int QZ_LockHWSurface(_THIS, SDL_Surface *surface) { +static int +QZ_LockHWSurface (_THIS, SDL_Surface * surface) +{ return 1; } -static void QZ_UnlockHWSurface(_THIS, SDL_Surface *surface) { +static void +QZ_UnlockHWSurface (_THIS, SDL_Surface * surface) +{ } -static int QZ_AllocHWSurface(_THIS, SDL_Surface *surface) { - return(-1); /* unallowed (no HWSURFACE support here). */ +static int +QZ_AllocHWSurface (_THIS, SDL_Surface * surface) +{ + return (-1); /* unallowed (no HWSURFACE support here). */ } -static void QZ_FreeHWSurface (_THIS, SDL_Surface *surface) { +static void +QZ_FreeHWSurface (_THIS, SDL_Surface * surface) +{ } /* @@ -1500,7 +1617,9 @@ int QZ_FlipHWSurface (_THIS, SDL_Surface *surface) { */ /* Gamma functions */ -int QZ_SetGamma (_THIS, float red, float green, float blue) { +int +QZ_SetGamma (_THIS, float red, float green, float blue) +{ const CGGammaValue min = 0.0, max = 1.0; @@ -1517,32 +1636,35 @@ int QZ_SetGamma (_THIS, float red, float green, float blue) { if (blue == 0.0) blue = FLT_MAX; else - blue = 1.0 / blue; + blue = 1.0 / blue; - if ( CGDisplayNoErr == CGSetDisplayTransferByFormula - (display_id, min, max, red, min, max, green, min, max, blue) ) { + if (CGDisplayNoErr == CGSetDisplayTransferByFormula + (display_id, min, max, red, min, max, green, min, max, blue)) { return 0; - } - else { + } else { return -1; } } -int QZ_GetGamma (_THIS, float *red, float *green, float *blue) { +int +QZ_GetGamma (_THIS, float *red, float *green, float *blue) +{ CGGammaValue dummy; - if ( CGDisplayNoErr == CGGetDisplayTransferByFormula - (display_id, &dummy, &dummy, red, - &dummy, &dummy, green, &dummy, &dummy, blue) ) + if (CGDisplayNoErr == CGGetDisplayTransferByFormula + (display_id, &dummy, &dummy, red, + &dummy, &dummy, green, &dummy, &dummy, blue)) return 0; else return -1; } -int QZ_SetGammaRamp (_THIS, Uint16 *ramp) { +int +QZ_SetGammaRamp (_THIS, Uint16 * ramp) +{ const CGTableCount tableSize = 255; CGGammaValue redTable[tableSize]; @@ -1555,20 +1677,22 @@ int QZ_SetGammaRamp (_THIS, Uint16 *ramp) { for (i = 0; i < 256; i++) redTable[i % 256] = ramp[i] / 65535.0; - for (i=256; i < 512; i++) + for (i = 256; i < 512; i++) greenTable[i % 256] = ramp[i] / 65535.0; - for (i=512; i < 768; i++) + for (i = 512; i < 768; i++) blueTable[i % 256] = ramp[i] / 65535.0; - if ( CGDisplayNoErr == CGSetDisplayTransferByTable - (display_id, tableSize, redTable, greenTable, blueTable) ) + if (CGDisplayNoErr == CGSetDisplayTransferByTable + (display_id, tableSize, redTable, greenTable, blueTable)) return 0; else return -1; } -int QZ_GetGammaRamp (_THIS, Uint16 *ramp) { +int +QZ_GetGammaRamp (_THIS, Uint16 * ramp) +{ const CGTableCount tableSize = 255; CGGammaValue redTable[tableSize]; @@ -1577,9 +1701,9 @@ int QZ_GetGammaRamp (_THIS, Uint16 *ramp) { CGTableCount actual; int i; - if ( CGDisplayNoErr != CGGetDisplayTransferByTable - (display_id, tableSize, redTable, greenTable, blueTable, &actual) || - actual != tableSize) + if (CGDisplayNoErr != CGGetDisplayTransferByTable + (display_id, tableSize, redTable, greenTable, blueTable, &actual) || + actual != tableSize) return -1; @@ -1587,12 +1711,11 @@ int QZ_GetGammaRamp (_THIS, Uint16 *ramp) { for (i = 0; i < 256; i++) ramp[i] = redTable[i % 256] * 65535.0; - for (i=256; i < 512; i++) + for (i = 256; i < 512; i++) ramp[i] = greenTable[i % 256] * 65535.0; - for (i=512; i < 768; i++) + for (i = 512; i < 768; i++) ramp[i] = blueTable[i % 256] * 65535.0; return 0; } - diff --git a/src/video/quartz/SDL_QuartzWM.m b/src/video/quartz/SDL_QuartzWM.m index dab99f6c1..edda9428f 100644 --- a/src/video/quartz/SDL_QuartzWM.m +++ b/src/video/quartz/SDL_QuartzWM.m @@ -24,110 +24,128 @@ #include "SDL_QuartzVideo.h" -struct WMcursor { +struct WMcursor +{ NSCursor *nscursor; }; -void QZ_FreeWMCursor (_THIS, WMcursor *cursor) { +void +QZ_FreeWMCursor(_THIS, WMcursor * cursor) +{ - if ( cursor != NULL ) { - [ cursor->nscursor release ]; - free (cursor); + if (cursor != NULL) { + [cursor->nscursor release]; + free(cursor); } } -WMcursor* QZ_CreateWMCursor (_THIS, Uint8 *data, Uint8 *mask, - int w, int h, int hot_x, int hot_y) { +WMcursor * +QZ_CreateWMCursor(_THIS, Uint8 * data, Uint8 * mask, + int w, int h, int hot_x, int hot_y) +{ WMcursor *cursor; NSBitmapImageRep *imgrep; NSImage *img; unsigned char *planes[5]; int i; NSAutoreleasePool *pool; - - pool = [ [ NSAutoreleasePool alloc ] init ]; - + + pool =[[NSAutoreleasePool alloc] init]; + /* Allocate the cursor memory */ - cursor = (WMcursor *)SDL_malloc(sizeof(WMcursor)); - if (cursor == NULL) goto outOfMemory; - + cursor = (WMcursor *) SDL_malloc(sizeof(WMcursor)); + if (cursor == NULL) + goto outOfMemory; + /* create the image representation and get the pointers to its storage */ - imgrep = [ [ [ NSBitmapImageRep alloc ] initWithBitmapDataPlanes: NULL pixelsWide: w pixelsHigh: h bitsPerSample: 1 samplesPerPixel: 2 hasAlpha: YES isPlanar: YES colorSpaceName: NSDeviceBlackColorSpace bytesPerRow: (w+7)/8 bitsPerPixel: 0 ] autorelease ]; - if (imgrep == nil) goto outOfMemory; - [ imgrep getBitmapDataPlanes: planes ]; - + imgrep =[[[NSBitmapImageRep alloc] initWithBitmapDataPlanes: NULL pixelsWide: w pixelsHigh: h bitsPerSample: 1 samplesPerPixel: 2 hasAlpha: YES isPlanar: YES colorSpaceName: NSDeviceBlackColorSpace bytesPerRow: (w + 7) / 8 bitsPerPixel:0] autorelease]; + if (imgrep == nil) + goto outOfMemory; + [imgrep getBitmapDataPlanes:planes]; + /* copy data and mask, extending the mask to all black pixels because the inversion effect doesn't work with Cocoa's alpha-blended cursors */ - for (i = 0; i < (w+7)/8*h; i++) { + for (i = 0; i < (w + 7) / 8 * h; i++) { planes[0][i] = data[i]; planes[1][i] = mask[i] | data[i]; } - + /* create image and cursor */ - img = [ [ [ NSImage alloc ] initWithSize: NSMakeSize(w, h) ] autorelease ]; - if (img == nil) goto outOfMemory; - [ img addRepresentation: imgrep ]; - if (system_version < 0x1030) { /* on 10.2, cursors must be 16*16 */ + img =[[[NSImage alloc] initWithSize:NSMakeSize(w, h)] autorelease]; + if (img == nil) + goto outOfMemory; + [img addRepresentation:imgrep]; + if (system_version < 0x1030) { /* on 10.2, cursors must be 16*16 */ if (w > 16 || h > 16) { /* too big: scale it down */ - [ img setScalesWhenResized: YES ]; - hot_x = hot_x*16/w; - hot_y = hot_y*16/h; - } - else { /* too small (or just right): extend it (from the bottom left corner, so hot_y must be adjusted) */ + [img setScalesWhenResized:YES]; + hot_x = hot_x * 16 / w; + hot_y = hot_y * 16 / h; + } else { /* too small (or just right): extend it (from the bottom left corner, so hot_y must be adjusted) */ hot_y += 16 - h; } - [ img setSize: NSMakeSize(16, 16) ]; + [img setSize:NSMakeSize(16, 16)]; } - cursor->nscursor = [ [ NSCursor alloc ] initWithImage: img hotSpot: NSMakePoint(hot_x, hot_y) ]; - if (cursor->nscursor == nil) goto outOfMemory; - - [ pool release ]; - return(cursor); - -outOfMemory: - [ pool release ]; - if (cursor != NULL) SDL_free(cursor); + cursor->nscursor =[[NSCursor alloc] initWithImage: img hotSpot:NSMakePoint(hot_x, + hot_y)]; + if (cursor->nscursor == nil) + goto outOfMemory; + + [pool release]; + return (cursor); + + outOfMemory: + [pool release]; + if (cursor != NULL) + SDL_free(cursor); SDL_OutOfMemory(); - return(NULL); + return (NULL); } -void QZ_ShowMouse (_THIS) { +void +QZ_ShowMouse(_THIS) +{ if (!cursor_visible) { - [ NSCursor unhide ]; + [NSCursor unhide]; cursor_visible = YES; } } -void QZ_HideMouse (_THIS) { +void +QZ_HideMouse(_THIS) +{ if ((SDL_GetAppState() & SDL_APPMOUSEFOCUS) && cursor_visible) { - [ NSCursor hide ]; + [NSCursor hide]; cursor_visible = NO; } } -BOOL QZ_IsMouseInWindow (_THIS) { - if (qz_window == nil) return YES; /*fullscreen*/ +BOOL +QZ_IsMouseInWindow(_THIS) +{ + if (qz_window == nil) + return YES; /*fullscreen */ else { - NSPoint p = [ qz_window mouseLocationOutsideOfEventStream ]; - p.y -= 1.0f; /* Apparently y goes from 1 to h, not from 0 to h-1 (i.e. the "location of the mouse" seems to be defined as "the location of the top left corner of the mouse pointer's hot pixel" */ - return NSPointInRect(p, [ window_view frame ]); + NSPoint p =[qz_window mouseLocationOutsideOfEventStream]; + p.y -= 1.0f; /* Apparently y goes from 1 to h, not from 0 to h-1 (i.e. the "location of the mouse" seems to be defined as "the location of the top left corner of the mouse pointer's hot pixel" */ + return NSPointInRect(p,[window_view frame]); } } -int QZ_ShowWMCursor (_THIS, WMcursor *cursor) { +int +QZ_ShowWMCursor(_THIS, WMcursor * cursor) +{ - if ( cursor == NULL) { - if ( cursor_should_be_visible ) { - QZ_HideMouse (this); + if (cursor == NULL) { + if (cursor_should_be_visible) { + QZ_HideMouse(this); cursor_should_be_visible = NO; - QZ_ChangeGrabState (this, QZ_HIDECURSOR); + QZ_ChangeGrabState(this, QZ_HIDECURSOR); } - } - else { - [ cursor->nscursor set ]; - if ( ! cursor_should_be_visible ) { - QZ_ShowMouse (this); + } else { + [cursor->nscursor set]; + if (!cursor_should_be_visible) { + QZ_ShowMouse(this); cursor_should_be_visible = YES; - QZ_ChangeGrabState (this, QZ_SHOWCURSOR); + QZ_ChangeGrabState(this, QZ_SHOWCURSOR); } } @@ -143,141 +161,166 @@ int QZ_ShowWMCursor (_THIS, WMcursor *cursor) { */ /* Convert Cocoa screen coordinate to Cocoa window coordinate */ -void QZ_PrivateGlobalToLocal (_THIS, NSPoint *p) { +void +QZ_PrivateGlobalToLocal(_THIS, NSPoint * p) +{ - *p = [ qz_window convertScreenToBase:*p ]; + *p =[qz_window convertScreenToBase:*p]; } /* Convert Cocoa window coordinate to Cocoa screen coordinate */ -void QZ_PrivateLocalToGlobal (_THIS, NSPoint *p) { +void +QZ_PrivateLocalToGlobal(_THIS, NSPoint * p) +{ - *p = [ qz_window convertBaseToScreen:*p ]; + *p =[qz_window convertBaseToScreen:*p]; } /* Convert SDL coordinate to Cocoa coordinate */ -void QZ_PrivateSDLToCocoa (_THIS, NSPoint *p) { +void +QZ_PrivateSDLToCocoa(_THIS, NSPoint * p) +{ + + if (CGDisplayIsCaptured(display_id)) { /* capture signals fullscreen */ + + p->y = CGDisplayPixelsHigh(display_id) - p->y; + } else { + + *p =[window_view convertPoint: *p toView:nil]; - if ( CGDisplayIsCaptured (display_id) ) { /* capture signals fullscreen */ - - p->y = CGDisplayPixelsHigh (display_id) - p->y; - } - else { - - *p = [ window_view convertPoint:*p toView: nil ]; - /* We need a workaround in OpenGL mode */ - if ( SDL_VideoSurface->flags & SDL_OPENGL ) { - p->y = [window_view frame].size.height - p->y; + if (SDL_VideoSurface->flags & SDL_OPENGL) { + p->y =[window_view frame].size.height - p->y; } } } /* Convert Cocoa coordinate to SDL coordinate */ -void QZ_PrivateCocoaToSDL (_THIS, NSPoint *p) { +void +QZ_PrivateCocoaToSDL(_THIS, NSPoint * p) +{ - if ( CGDisplayIsCaptured (display_id) ) { /* capture signals fullscreen */ - - p->y = CGDisplayPixelsHigh (display_id) - p->y; - } - else { + if (CGDisplayIsCaptured(display_id)) { /* capture signals fullscreen */ + + p->y = CGDisplayPixelsHigh(display_id) - p->y; + } else { + + *p =[window_view convertPoint: *p fromView:nil]; - *p = [ window_view convertPoint:*p fromView: nil ]; - /* We need a workaround in OpenGL mode */ - if ( SDL_VideoSurface != NULL && (SDL_VideoSurface->flags & SDL_OPENGL) ) { - p->y = [window_view frame].size.height - p->y; + if (SDL_VideoSurface != NULL + && (SDL_VideoSurface->flags & SDL_OPENGL)) { + p->y =[window_view frame].size.height - p->y; } } } /* Convert SDL coordinate to window server (CoreGraphics) coordinate */ -CGPoint QZ_PrivateSDLToCG (_THIS, NSPoint *p) { - +CGPoint +QZ_PrivateSDLToCG(_THIS, NSPoint * p) +{ + CGPoint cgp; - - if ( ! CGDisplayIsCaptured (display_id) ) { /* not captured => not fullscreen => local coord */ - + + if (!CGDisplayIsCaptured(display_id)) { /* not captured => not fullscreen => local coord */ + int height; - - QZ_PrivateSDLToCocoa (this, p); - QZ_PrivateLocalToGlobal (this, p); - - height = CGDisplayPixelsHigh (display_id); + + QZ_PrivateSDLToCocoa(this, p); + QZ_PrivateLocalToGlobal(this, p); + + height = CGDisplayPixelsHigh(display_id); p->y = height - p->y; } - + cgp.x = p->x; cgp.y = p->y; - + return cgp; } -#if 0 /* Dead code */ +#if 0 /* Dead code */ /* Convert window server (CoreGraphics) coordinate to SDL coordinate */ -void QZ_PrivateCGToSDL (_THIS, NSPoint *p) { - - if ( ! CGDisplayIsCaptured (display_id) ) { /* not captured => not fullscreen => local coord */ - +void +QZ_PrivateCGToSDL(_THIS, NSPoint * p) +{ + + if (!CGDisplayIsCaptured(display_id)) { /* not captured => not fullscreen => local coord */ + int height; /* Convert CG Global to Cocoa Global */ - height = CGDisplayPixelsHigh (display_id); + height = CGDisplayPixelsHigh(display_id); p->y = height - p->y; - QZ_PrivateGlobalToLocal (this, p); - QZ_PrivateCocoaToSDL (this, p); + QZ_PrivateGlobalToLocal(this, p); + QZ_PrivateCocoaToSDL(this, p); } } #endif /* Dead code */ -void QZ_PrivateWarpCursor (_THIS, int x, int y) { - +void +QZ_PrivateWarpCursor(_THIS, int x, int y) +{ + NSPoint p; CGPoint cgp; - - p = NSMakePoint (x, y); - cgp = QZ_PrivateSDLToCG (this, &p); - + + p = NSMakePoint(x, y); + cgp = QZ_PrivateSDLToCG(this, &p); + /* this is the magic call that fixes cursor "freezing" after warp */ - CGSetLocalEventsSuppressionInterval (0.0); - CGWarpMouseCursorPosition (cgp); + CGSetLocalEventsSuppressionInterval(0.0); + CGWarpMouseCursorPosition(cgp); } -void QZ_WarpWMCursor (_THIS, Uint16 x, Uint16 y) { +void +QZ_WarpWMCursor(_THIS, Uint16 x, Uint16 y) +{ /* Only allow warping when in foreground */ - if ( ! [ NSApp isActive ] ) + if (![NSApp isActive]) return; - + /* Do the actual warp */ - if (grab_state != QZ_INVISIBLE_GRAB) QZ_PrivateWarpCursor (this, x, y); + if (grab_state != QZ_INVISIBLE_GRAB) + QZ_PrivateWarpCursor(this, x, y); /* Generate the mouse moved event */ - SDL_PrivateMouseMotion (0, 0, x, y); + SDL_PrivateMouseMotion(0, 0, x, y); } -void QZ_MoveWMCursor (_THIS, int x, int y) { } -void QZ_CheckMouseMode (_THIS) { } +void +QZ_MoveWMCursor(_THIS, int x, int y) +{ +} +void +QZ_CheckMouseMode(_THIS) +{ +} -void QZ_SetCaption (_THIS, const char *title, const char *icon) { +void +QZ_SetCaption(_THIS, const char *title, const char *icon) +{ - if ( qz_window != nil ) { + if (qz_window != nil) { NSString *string; - if ( title != NULL ) { - string = [ [ NSString alloc ] initWithUTF8String:title ]; - [ qz_window setTitle:string ]; - [ string release ]; + if (title != NULL) { + string =[[NSString alloc] initWithUTF8String:title]; + [qz_window setTitle:string]; + [string release]; } - if ( icon != NULL ) { - string = [ [ NSString alloc ] initWithUTF8String:icon ]; - [ qz_window setMiniwindowTitle:string ]; - [ string release ]; + if (icon != NULL) { + string =[[NSString alloc] initWithUTF8String:icon]; + [qz_window setMiniwindowTitle:string]; + [string release]; } } } -void QZ_SetIcon (_THIS, SDL_Surface *icon, Uint8 *mask) +void +QZ_SetIcon(_THIS, SDL_Surface * icon, Uint8 * mask) { NSBitmapImageRep *imgrep; NSImage *img; @@ -287,72 +330,82 @@ void QZ_SetIcon (_THIS, SDL_Surface *icon, Uint8 *mask) SDL_bool iconSrcAlpha; Uint8 iconAlphaValue; int i, j, maskPitch, index; - - pool = [ [ NSAutoreleasePool alloc ] init ]; - - imgrep = [ [ [ NSBitmapImageRep alloc ] initWithBitmapDataPlanes: NULL pixelsWide: icon->w pixelsHigh: icon->h bitsPerSample: 8 samplesPerPixel: 4 hasAlpha: YES isPlanar: NO colorSpaceName: NSDeviceRGBColorSpace bytesPerRow: 4*icon->w bitsPerPixel: 32 ] autorelease ]; - if (imgrep == nil) goto freePool; - pixels = [ imgrep bitmapData ]; - SDL_memset(pixels, 0, 4*icon->w*icon->h); /* make the background, which will survive in colorkeyed areas, completely transparent */ - + + pool =[[NSAutoreleasePool alloc] init]; + + imgrep =[[[NSBitmapImageRep alloc] initWithBitmapDataPlanes: NULL pixelsWide: icon->w pixelsHigh: icon->h bitsPerSample: 8 samplesPerPixel: 4 hasAlpha: YES isPlanar: NO colorSpaceName: NSDeviceRGBColorSpace bytesPerRow: 4 * icon->w bitsPerPixel:32] autorelease]; + if (imgrep == nil) + goto freePool; + pixels =[imgrep bitmapData]; + SDL_memset(pixels, 0, 4 * icon->w * icon->h); /* make the background, which will survive in colorkeyed areas, completely transparent */ + #if SDL_BYTEORDER == SDL_BIG_ENDIAN #define BYTEORDER_DEPENDENT_RGBA_MASKS 0xFF000000, 0x00FF0000, 0x0000FF00, 0x000000FF #else #define BYTEORDER_DEPENDENT_RGBA_MASKS 0x000000FF, 0x0000FF00, 0x00FF0000, 0xFF000000 #endif - mergedSurface = SDL_CreateRGBSurfaceFrom(pixels, icon->w, icon->h, 32, 4*icon->w, BYTEORDER_DEPENDENT_RGBA_MASKS); - if (mergedSurface == NULL) goto freePool; - + mergedSurface = + SDL_CreateRGBSurfaceFrom(pixels, icon->w, icon->h, 32, 4 * icon->w, + BYTEORDER_DEPENDENT_RGBA_MASKS); + if (mergedSurface == NULL) + goto freePool; + /* blit, with temporarily cleared SRCALPHA flag because we want to copy, not alpha-blend */ iconSrcAlpha = ((icon->flags & SDL_SRCALPHA) != 0); iconAlphaValue = icon->format->alpha; SDL_SetAlpha(icon, 0, 255); SDL_BlitSurface(icon, NULL, mergedSurface, NULL); - if (iconSrcAlpha) SDL_SetAlpha(icon, SDL_SRCALPHA, iconAlphaValue); - + if (iconSrcAlpha) + SDL_SetAlpha(icon, SDL_SRCALPHA, iconAlphaValue); + SDL_FreeSurface(mergedSurface); - + /* apply mask, source alpha, and premultiply color values by alpha */ - maskPitch = (icon->w+7)/8; + maskPitch = (icon->w + 7) / 8; for (i = 0; i < icon->h; i++) { for (j = 0; j < icon->w; j++) { - index = i*4*icon->w + j*4; - if (!(mask[i*maskPitch + j/8] & (128 >> j%8))) { + index = i * 4 * icon->w + j * 4; + if (!(mask[i * maskPitch + j / 8] & (128 >> j % 8))) { pixels[index + 3] = 0; - } - else { + } else { if (iconSrcAlpha) { - if (icon->format->Amask == 0) pixels[index + 3] = icon->format->alpha; - } - else { + if (icon->format->Amask == 0) + pixels[index + 3] = icon->format->alpha; + } else { pixels[index + 3] = 255; } } if (pixels[index + 3] < 255) { - pixels[index + 0] = (Uint16)pixels[index + 0]*pixels[index + 3]/255; - pixels[index + 1] = (Uint16)pixels[index + 1]*pixels[index + 3]/255; - pixels[index + 2] = (Uint16)pixels[index + 2]*pixels[index + 3]/255; + pixels[index + 0] = + (Uint16) pixels[index + 0] * pixels[index + 3] / 255; + pixels[index + 1] = + (Uint16) pixels[index + 1] * pixels[index + 3] / 255; + pixels[index + 2] = + (Uint16) pixels[index + 2] * pixels[index + 3] / 255; } } } - - img = [ [ [ NSImage alloc ] initWithSize: NSMakeSize(icon->w, icon->h) ] autorelease ]; - if (img == nil) goto freePool; - [ img addRepresentation: imgrep ]; - [ NSApp setApplicationIconImage:img ]; - -freePool: - [ pool release ]; + + img =[[[NSImage alloc] initWithSize:NSMakeSize(icon->w, + icon->h)] autorelease]; + if (img == nil) + goto freePool; + [img addRepresentation:imgrep]; + [NSApp setApplicationIconImage:img]; + + freePool: + [pool release]; } -int QZ_IconifyWindow (_THIS) { +int +QZ_IconifyWindow(_THIS) +{ - if ( ! [ qz_window isMiniaturized ] ) { - [ qz_window miniaturize:nil ]; + if (![qz_window isMiniaturized]) { + [qz_window miniaturize:nil]; return 1; - } - else { - SDL_SetError ("window already iconified"); + } else { + SDL_SetError("window already iconified"); return 0; } } @@ -363,74 +416,75 @@ int QZ_GetWMInfo (_THIS, SDL_SysWMinfo *info) { return 0; }*/ -void QZ_ChangeGrabState (_THIS, int action) { +void +QZ_ChangeGrabState(_THIS, int action) +{ /* - Figure out what the next state should be based on the action. - Ignore actions that can't change the current state. - */ - if ( grab_state == QZ_UNGRABBED ) { - if ( action == QZ_ENABLE_GRAB ) { - if ( cursor_should_be_visible ) + Figure out what the next state should be based on the action. + Ignore actions that can't change the current state. + */ + if (grab_state == QZ_UNGRABBED) { + if (action == QZ_ENABLE_GRAB) { + if (cursor_should_be_visible) grab_state = QZ_VISIBLE_GRAB; else grab_state = QZ_INVISIBLE_GRAB; } - } - else if ( grab_state == QZ_VISIBLE_GRAB ) { - if ( action == QZ_DISABLE_GRAB ) + } else if (grab_state == QZ_VISIBLE_GRAB) { + if (action == QZ_DISABLE_GRAB) grab_state = QZ_UNGRABBED; - else if ( action == QZ_HIDECURSOR ) + else if (action == QZ_HIDECURSOR) grab_state = QZ_INVISIBLE_GRAB; - } - else { - assert( grab_state == QZ_INVISIBLE_GRAB ); - - if ( action == QZ_DISABLE_GRAB ) + } else { + assert(grab_state == QZ_INVISIBLE_GRAB); + + if (action == QZ_DISABLE_GRAB) grab_state = QZ_UNGRABBED; - else if ( action == QZ_SHOWCURSOR ) + else if (action == QZ_SHOWCURSOR) grab_state = QZ_VISIBLE_GRAB; } - + /* now apply the new state */ if (grab_state == QZ_UNGRABBED) { - - CGAssociateMouseAndMouseCursorPosition (1); - } - else if (grab_state == QZ_VISIBLE_GRAB) { - - CGAssociateMouseAndMouseCursorPosition (1); - } - else { - assert( grab_state == QZ_INVISIBLE_GRAB ); - QZ_PrivateWarpCursor (this, SDL_VideoSurface->w / 2, SDL_VideoSurface->h / 2); - CGAssociateMouseAndMouseCursorPosition (0); + CGAssociateMouseAndMouseCursorPosition(1); + } else if (grab_state == QZ_VISIBLE_GRAB) { + + CGAssociateMouseAndMouseCursorPosition(1); + } else { + assert(grab_state == QZ_INVISIBLE_GRAB); + + QZ_PrivateWarpCursor(this, SDL_VideoSurface->w / 2, + SDL_VideoSurface->h / 2); + CGAssociateMouseAndMouseCursorPosition(0); } } -SDL_GrabMode QZ_GrabInput (_THIS, SDL_GrabMode grab_mode) { +SDL_GrabMode +QZ_GrabInput(_THIS, SDL_GrabMode grab_mode) +{ int doGrab = grab_mode & SDL_GRAB_ON; - /*int fullscreen = grab_mode & SDL_GRAB_FULLSCREEN;*/ + /*int fullscreen = grab_mode & SDL_GRAB_FULLSCREEN; */ - if ( this->screen == NULL ) { - SDL_SetError ("QZ_GrabInput: screen is NULL"); + if (this->screen == NULL) { + SDL_SetError("QZ_GrabInput: screen is NULL"); return SDL_GRAB_OFF; } - - if ( ! video_set ) { + + if (!video_set) { /*SDL_SetError ("QZ_GrabInput: video is not set, grab will take effect on mode switch"); */ current_grab_mode = grab_mode; return grab_mode; /* Will be set later on mode switch */ } - if ( grab_mode != SDL_GRAB_QUERY ) { - if ( doGrab ) - QZ_ChangeGrabState (this, QZ_ENABLE_GRAB); + if (grab_mode != SDL_GRAB_QUERY) { + if (doGrab) + QZ_ChangeGrabState(this, QZ_ENABLE_GRAB); else - QZ_ChangeGrabState (this, QZ_DISABLE_GRAB); - + QZ_ChangeGrabState(this, QZ_DISABLE_GRAB); + current_grab_mode = doGrab ? SDL_GRAB_ON : SDL_GRAB_OFF; } diff --git a/src/video/quartz/SDL_QuartzWindow.h b/src/video/quartz/SDL_QuartzWindow.h index 20077ee89..d162ca217 100644 --- a/src/video/quartz/SDL_QuartzWindow.h +++ b/src/video/quartz/SDL_QuartzWindow.h @@ -22,18 +22,20 @@ #include "SDL_config.h" /* Subclass of NSWindow to fix genie effect and support resize events */ -@interface SDL_QuartzWindow : NSWindow -- (void)miniaturize:(id)sender; -- (void)display; -- (void)setFrame:(NSRect)frameRect display:(BOOL)flag; -- (void)appDidHide:(NSNotification*)note; -- (void)appWillUnhide:(NSNotification*)note; -- (void)appDidUnhide:(NSNotification*)note; -- (id)initWithContentRect:(NSRect)contentRect styleMask:(unsigned int)styleMask backing:(NSBackingStoreType)backingType defer:(BOOL)flag; +@ interface SDL_QuartzWindow: NSWindow - (void) miniaturize:(id) sender; +-(void) display; +-(void) setFrame:(NSRect) + frameRect display:(BOOL) flag; +-(void) appDidHide:(NSNotification *) note; +-(void) appWillUnhide:(NSNotification *) note; +-(void) appDidUnhide:(NSNotification *) note; +-(id) initWithContentRect:(NSRect) + contentRect styleMask:(unsigned int) + styleMask backing:(NSBackingStoreType) + backingType defer:(BOOL) flag; @end - /* Delegate for our NSWindow to send SDLQuit() on close */ -@interface SDL_QuartzWindowDelegate : NSObject -- (BOOL)windowShouldClose:(id)sender; +@ interface SDL_QuartzWindowDelegate: NSObject - (BOOL) windowShouldClose:(id) + sender; @end - +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/quartz/SDL_QuartzWindow.m b/src/video/quartz/SDL_QuartzWindow.m index ffbf1eadf..1ae8409a1 100644 --- a/src/video/quartz/SDL_QuartzWindow.m +++ b/src/video/quartz/SDL_QuartzWindow.m @@ -29,190 +29,185 @@ The genie effect uses the alpha component. Otherwise, it doesn't seem to matter what value it has. */ -static void QZ_SetPortAlphaOpaque () { - +static void +QZ_SetPortAlphaOpaque () +{ + SDL_Surface *surface = current_video->screen; int bpp; - + bpp = surface->format->BitsPerPixel; - + if (bpp == 32) { - - Uint32 *pixels = (Uint32*) surface->pixels; - Uint32 rowPixels = surface->pitch / 4; - Uint32 i, j; - + + Uint32 *pixels = (Uint32 *) surface->pixels; + Uint32 rowPixels = surface->pitch / 4; + Uint32 i, j; + for (i = 0; i < surface->h; i++) for (j = 0; j < surface->w; j++) { - - pixels[ (i * rowPixels) + j ] |= 0xFF000000; + + pixels[(i * rowPixels) + j] |= 0xFF000000; } } } @implementation SDL_QuartzWindow - /* we override these methods to fix the miniaturize animation/dock icon bug */ -- (void)miniaturize:(id)sender -{ - if (SDL_VideoSurface->flags & SDL_OPENGL) { - +- (void) miniaturize:(id) sender { + if (SDL_VideoSurface->flags & SDL_INTERNALOPENGL) { + /* - Future: Grab framebuffer and put into NSImage - [ qz_window setMiniwindowImage:image ]; - */ - } - else { - + Future: Grab framebuffer and put into NSImage + [ qz_window setMiniwindowImage:image ]; + */ + } else { + /* make the alpha channel opaque so anim won't have holes in it */ QZ_SetPortAlphaOpaque (); } - + /* window is hidden now */ SDL_PrivateAppActive (0, SDL_APPACTIVE); - - [ super miniaturize:sender ]; + + [super miniaturize:sender]; } -- (void)display -{ +-(void) display { /* - This method fires just before the window deminaturizes from the Dock. - - We'll save the current visible surface, let the window manager redraw any - UI elements, and restore the SDL surface. This way, no expose event - is required, and the deminiaturize works perfectly. - */ - SDL_VideoDevice *this = (SDL_VideoDevice*)current_video; - + This method fires just before the window deminaturizes from the Dock. + + We'll save the current visible surface, let the window manager redraw any + UI elements, and restore the SDL surface. This way, no expose event + is required, and the deminiaturize works perfectly. + */ + SDL_VideoDevice *this = (SDL_VideoDevice *) current_video; + /* make sure pixels are fully opaque */ - if (! ( SDL_VideoSurface->flags & SDL_OPENGL ) ) + if (!(SDL_VideoSurface->flags & SDL_INTERNALOPENGL)) QZ_SetPortAlphaOpaque (); - + /* save current visible SDL surface */ - [ self cacheImageInRect:[ window_view frame ] ]; - + [self cacheImageInRect:[window_view frame]]; + /* let the window manager redraw controls, border, etc */ - [ super display ]; - + [super display]; + /* restore visible SDL surface */ - [ self restoreCachedImage ]; - + [self restoreCachedImage]; + /* window is visible again */ SDL_PrivateAppActive (1, SDL_APPACTIVE); } -- (void)setFrame:(NSRect)frameRect display:(BOOL)flag +-(void) setFrame:(NSRect) + frameRect display:(BOOL) flag { /* - If the video surface is NULL, this originated from QZ_SetVideoMode, - so don't send the resize event. - */ - SDL_VideoDevice *this = (SDL_VideoDevice*)current_video; - + If the video surface is NULL, this originated from QZ_SetVideoMode, + so don't send the resize event. + */ + SDL_VideoDevice *this = (SDL_VideoDevice *) current_video; + if (this && SDL_VideoSurface == NULL) { - [ super setFrame:frameRect display:flag ]; - } - else if (this && qz_window) { + [super setFrame: frameRect display:flag]; + } else if (this && qz_window) { NSRect newViewFrame; - - [ super setFrame:frameRect display:flag ]; - - newViewFrame = [ window_view frame ]; - + + [super setFrame: frameRect display:flag]; + + newViewFrame =[window_view frame]; + SDL_PrivateResize (newViewFrame.size.width, newViewFrame.size.height); /* If not OpenGL, we have to update the pixels and pitch */ - if ( ! ( SDL_VideoSurface->flags & SDL_OPENGL ) ) { - - CGrafPtr thePort = [ window_view qdPort ]; - LockPortBits ( thePort ); - - SDL_VideoSurface->pixels = GetPixBaseAddr ( GetPortPixMap ( thePort ) ); - SDL_VideoSurface->pitch = GetPixRowBytes ( GetPortPixMap ( thePort ) ); - + if (!(SDL_VideoSurface->flags & SDL_INTERNALOPENGL)) { + + CGrafPtr thePort =[window_view qdPort]; + LockPortBits (thePort); + + SDL_VideoSurface->pixels = + GetPixBaseAddr (GetPortPixMap (thePort)); + SDL_VideoSurface->pitch = + GetPixRowBytes (GetPortPixMap (thePort)); + /* - SDL_VideoSurface->pixels now points to the window's pixels - We want it to point to the *view's* pixels - */ - { - int vOffset = [ qz_window frame ].size.height - + SDL_VideoSurface->pixels now points to the window's pixels + We want it to point to the *view's* pixels + */ + { + int vOffset =[qz_window frame].size.height - newViewFrame.size.height - newViewFrame.origin.y; - + int hOffset = newViewFrame.origin.x; - - SDL_VideoSurface->pixels = (Uint8 *)SDL_VideoSurface->pixels + (vOffset * SDL_VideoSurface->pitch) + hOffset * (device_bpp/8); + + SDL_VideoSurface->pixels = + (Uint8 *) SDL_VideoSurface->pixels + + (vOffset * SDL_VideoSurface->pitch) + + hOffset * (device_bpp / 8); } - - UnlockPortBits ( thePort ); + + UnlockPortBits (thePort); } } } -- (void)appDidHide:(NSNotification*)note -{ +-(void) appDidHide:(NSNotification *) note { SDL_PrivateAppActive (0, SDL_APPACTIVE); } -- (void)appWillUnhide:(NSNotification*)note -{ - SDL_VideoDevice *this = (SDL_VideoDevice*)current_video; - - if ( this ) { - +-(void) appWillUnhide:(NSNotification *) note { + SDL_VideoDevice *this = (SDL_VideoDevice *) current_video; + + if (this) { + /* make sure pixels are fully opaque */ - if (! ( SDL_VideoSurface->flags & SDL_OPENGL ) ) + if (!(SDL_VideoSurface->flags & SDL_INTERNALOPENGL)) QZ_SetPortAlphaOpaque (); - + /* save current visible SDL surface */ - [ self cacheImageInRect:[ window_view frame ] ]; + [self cacheImageInRect:[window_view frame]]; } } -- (void)appDidUnhide:(NSNotification*)note -{ +-(void) appDidUnhide:(NSNotification *) note { /* restore cached image, since it may not be current, post expose event too */ - [ self restoreCachedImage ]; - - /*SDL_PrivateExpose ();*/ - + [self restoreCachedImage]; + + /*SDL_PrivateExpose (); */ + SDL_PrivateAppActive (1, SDL_APPACTIVE); } -- (id)initWithContentRect:(NSRect)contentRect styleMask:(unsigned int)styleMask backing:(NSBackingStoreType)backingType defer:(BOOL)flag +-(id) initWithContentRect:(NSRect) + contentRect styleMask:(unsigned int) + styleMask backing:(NSBackingStoreType) + backingType defer:(BOOL) flag { /* Make our window subclass receive these application notifications */ - [ [ NSNotificationCenter defaultCenter ] addObserver:self - selector:@selector(appDidHide:) name:NSApplicationDidHideNotification object:NSApp ]; - - [ [ NSNotificationCenter defaultCenter ] addObserver:self - selector:@selector(appDidUnhide:) name:NSApplicationDidUnhideNotification object:NSApp ]; - - [ [ NSNotificationCenter defaultCenter ] addObserver:self - selector:@selector(appWillUnhide:) name:NSApplicationWillUnhideNotification object:NSApp ]; - - return [ super initWithContentRect:contentRect styleMask:styleMask backing:backingType defer:flag ]; -} + [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector (appDidHide: )name: NSApplicationDidHideNotification object:NSApp]; -@end + [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector (appDidUnhide: )name: NSApplicationDidUnhideNotification object:NSApp]; -@implementation SDL_QuartzWindowDelegate -- (BOOL)windowShouldClose:(id)sender + [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector (appWillUnhide: )name: NSApplicationWillUnhideNotification object:NSApp]; + + return[super initWithContentRect: contentRect styleMask: styleMask backing: backingType defer:flag]; +} + +@end @ implementation SDL_QuartzWindowDelegate - (BOOL) windowShouldClose:(id) sender { - SDL_PrivateQuit(); + SDL_PrivateQuit (); return NO; } -- (void)windowDidBecomeKey:(NSNotification *)aNotification -{ +-(void) windowDidBecomeKey:(NSNotification *) aNotification { QZ_DoActivate (current_video); } -- (void)windowDidResignKey:(NSNotification *)aNotification -{ +-(void) windowDidResignKey:(NSNotification *) aNotification { QZ_DoDeactivate (current_video); } diff --git a/src/video/quartz/SDL_QuartzYUV.m b/src/video/quartz/SDL_QuartzYUV.m index 96539d679..fb318ac29 100644 --- a/src/video/quartz/SDL_QuartzYUV.m +++ b/src/video/quartz/SDL_QuartzYUV.m @@ -37,17 +37,23 @@ #define yuv_port (this->hidden->yuv_port) -static int QZ_LockYUV (_THIS, SDL_Overlay *overlay) { +static int +QZ_LockYUV (_THIS, SDL_Overlay * overlay) +{ return 0; } -static void QZ_UnlockYUV (_THIS, SDL_Overlay *overlay) { +static void +QZ_UnlockYUV (_THIS, SDL_Overlay * overlay) +{ ; } -static int QZ_DisplayYUV (_THIS, SDL_Overlay *overlay, SDL_Rect *src, SDL_Rect *dst) { +static int +QZ_DisplayYUV (_THIS, SDL_Overlay * overlay, SDL_Rect * src, SDL_Rect * dst) +{ OSErr err; CodecFlags flags; @@ -62,11 +68,12 @@ static int QZ_DisplayYUV (_THIS, SDL_Overlay *overlay, SDL_Rect *src, SDL_Rect * Fixed scale_x, scale_y; - scale_x = FixDiv ( Long2Fix (dst->w), Long2Fix (overlay->w) ); - scale_y = FixDiv ( Long2Fix (dst->h), Long2Fix (overlay->h) ); + scale_x = FixDiv (Long2Fix (dst->w), Long2Fix (overlay->w)); + scale_y = FixDiv (Long2Fix (dst->h), Long2Fix (overlay->h)); SetIdentityMatrix (yuv_matrix); - ScaleMatrix (yuv_matrix, scale_x, scale_y, Long2Fix (0), Long2Fix (0)); + ScaleMatrix (yuv_matrix, scale_x, scale_y, Long2Fix (0), + Long2Fix (0)); SetDSequenceMatrix (yuv_seq, yuv_matrix); @@ -74,34 +81,35 @@ static int QZ_DisplayYUV (_THIS, SDL_Overlay *overlay, SDL_Rect *src, SDL_Rect * yuv_height = dst->h; } - if( ( err = DecompressSequenceFrameS( - yuv_seq, - (void*)yuv_pixmap, + if ((err = DecompressSequenceFrameS (yuv_seq, + (void *) yuv_pixmap, sizeof (PlanarPixmapInfoYUV420), - codecFlagUseImageBuffer, &flags, nil ) != noErr ) ) - { + codecFlagUseImageBuffer, &flags, + nil) != noErr)) { SDL_SetError ("DecompressSequenceFrameS failed"); } return err != noErr; } -static void QZ_FreeHWYUV (_THIS, SDL_Overlay *overlay) { +static void +QZ_FreeHWYUV (_THIS, SDL_Overlay * overlay) +{ CDSequenceEnd (yuv_seq); - ExitMovies(); + ExitMovies (); SDL_free (overlay->hwfuncs); SDL_free (overlay->pitches); SDL_free (overlay->pixels); if (SDL_VideoSurface->flags & SDL_FULLSCREEN) { - [ qz_window close ]; + [qz_window close]; qz_window = nil; } SDL_free (yuv_matrix); - DisposeHandle ((Handle)yuv_idh); + DisposeHandle ((Handle) yuv_idh); } /* check for 16 byte alignment, bail otherwise */ @@ -110,37 +118,38 @@ static void QZ_FreeHWYUV (_THIS, SDL_Overlay *overlay) { /* align a byte offset, return how much to add to make it a multiple of 16 */ #define ALIGN(x) ((16 - (x & 15)) & 15) -SDL_Overlay* QZ_CreateYUVOverlay (_THIS, int width, int height, - Uint32 format, SDL_Surface *display) { +SDL_Overlay * +QZ_CreateYUVOverlay (_THIS, int width, int height, + Uint32 format, SDL_Surface * display) +{ Uint32 codec; OSStatus err; CGrafPtr port; SDL_Overlay *overlay; - if (format == SDL_YV12_OVERLAY || - format == SDL_IYUV_OVERLAY) { + if (format == SDL_YV12_OVERLAY || format == SDL_IYUV_OVERLAY) { codec = kYUV420CodecType; - } - else { + } else { SDL_SetError ("Hardware: unsupported video format"); return NULL; } - yuv_idh = (ImageDescriptionHandle) NewHandleClear (sizeof(ImageDescription)); + yuv_idh = + (ImageDescriptionHandle) NewHandleClear (sizeof (ImageDescription)); if (yuv_idh == NULL) { - SDL_OutOfMemory(); + SDL_OutOfMemory (); return NULL; } - yuv_matrix = (MatrixRecordPtr) SDL_malloc (sizeof(MatrixRecord)); + yuv_matrix = (MatrixRecordPtr) SDL_malloc (sizeof (MatrixRecord)); if (yuv_matrix == NULL) { - SDL_OutOfMemory(); + SDL_OutOfMemory (); return NULL; } - if ( EnterMovies() != noErr ) { + if (EnterMovies () != noErr) { SDL_SetError ("Could not init QuickTime for YUV playback"); return NULL; } @@ -154,68 +163,64 @@ static void QZ_FreeHWYUV (_THIS, SDL_Overlay *overlay) { if (SDL_VideoSurface->flags & SDL_FULLSCREEN) { /* - Acceleration requires a window to be present. - A CGrafPtr that points to the screen isn't good enough - */ - NSRect content = NSMakeRect (0, 0, SDL_VideoSurface->w, SDL_VideoSurface->h); + Acceleration requires a window to be present. + A CGrafPtr that points to the screen isn't good enough + */ + NSRect content = + NSMakeRect (0, 0, SDL_VideoSurface->w, SDL_VideoSurface->h); - qz_window = [ [ SDL_QuartzWindow alloc ] - initWithContentRect:content - styleMask:NSBorderlessWindowMask - backing:NSBackingStoreBuffered defer:NO ]; + qz_window =[[SDL_QuartzWindow alloc] initWithContentRect: content styleMask: NSBorderlessWindowMask backing: NSBackingStoreBuffered defer:NO]; if (qz_window == nil) { SDL_SetError ("Could not create the Cocoa window"); return NULL; } - [ qz_window setContentView:[ [ NSQuickDrawView alloc ] init ] ]; - [ qz_window setReleasedWhenClosed:YES ]; - [ qz_window center ]; - [ qz_window setAcceptsMouseMovedEvents:YES ]; - [ qz_window setLevel:CGShieldingWindowLevel() ]; - [ qz_window makeKeyAndOrderFront:nil ]; + [qz_window setContentView:[[NSQuickDrawView alloc] init]]; + [qz_window setReleasedWhenClosed:YES]; + [qz_window center]; + [qz_window setAcceptsMouseMovedEvents:YES]; + [qz_window setLevel:CGShieldingWindowLevel ()]; + [qz_window makeKeyAndOrderFront:nil]; - port = [ [ qz_window contentView ] qdPort ]; + port =[[qz_window contentView] qdPort]; SetPort (port); - + /* - BUG: would like to remove white flash when window kicks in - { - Rect r; - SetRect (&r, 0, 0, SDL_VideoSurface->w, SDL_VideoSurface->h); - PaintRect (&r); - QDFlushPortBuffer (port, nil); - } - */ - } - else { - port = [ window_view qdPort ]; + BUG: would like to remove white flash when window kicks in + { + Rect r; + SetRect (&r, 0, 0, SDL_VideoSurface->w, SDL_VideoSurface->h); + PaintRect (&r); + QDFlushPortBuffer (port, nil); + } + */ + } else { + port =[window_view qdPort]; SetPort (port); } - + SetIdentityMatrix (yuv_matrix); - - HLock ((Handle)yuv_idh); - - (**yuv_idh).idSize = sizeof(ImageDescription); - (**yuv_idh).cType = codec; + + HLock ((Handle) yuv_idh); + + (**yuv_idh).idSize = sizeof (ImageDescription); + (**yuv_idh).cType = codec; (**yuv_idh).version = 1; (**yuv_idh).revisionLevel = 0; (**yuv_idh).width = width; (**yuv_idh).height = height; - (**yuv_idh).hRes = Long2Fix(72); - (**yuv_idh).vRes = Long2Fix(72); + (**yuv_idh).hRes = Long2Fix (72); + (**yuv_idh).vRes = Long2Fix (72); (**yuv_idh).spatialQuality = codecLosslessQuality; (**yuv_idh).frameCount = 1; (**yuv_idh).clutID = -1; (**yuv_idh).dataSize = 0; (**yuv_idh).depth = 24; - - HUnlock ((Handle)yuv_idh); - - err = DecompressSequenceBeginS ( - &yuv_seq, + + HUnlock ((Handle) yuv_idh); + + err = DecompressSequenceBeginS (&yuv_seq, yuv_idh, NULL, 0, @@ -226,68 +231,65 @@ static void QZ_FreeHWYUV (_THIS, SDL_Overlay *overlay) { 0, NULL, codecFlagUseImageBuffer, - codecLosslessQuality, - yuv_codec); - + codecLosslessQuality, yuv_codec); + if (err != noErr) { SDL_SetError ("Error trying to start YUV codec."); return NULL; } - - overlay = (SDL_Overlay*) SDL_malloc (sizeof(*overlay)); + + overlay = (SDL_Overlay *) SDL_malloc (sizeof (*overlay)); if (overlay == NULL) { - SDL_OutOfMemory(); + SDL_OutOfMemory (); return NULL; } - - overlay->format = format; - overlay->w = width; - overlay->h = height; - overlay->planes = 3; - overlay->hw_overlay = 1; + + overlay->format = format; + overlay->w = width; + overlay->h = height; + overlay->planes = 3; + overlay->hw_overlay = 1; { - int offset; - Uint8 **pixels; - Uint16 *pitches; - int plane2, plane3; + int offset; + Uint8 **pixels; + Uint16 *pitches; + int plane2, plane3; if (format == SDL_IYUV_OVERLAY) { - plane2 = 1; /* Native codec format */ + plane2 = 1; /* Native codec format */ plane3 = 2; - } - else if (format == SDL_YV12_OVERLAY) { + } else if (format == SDL_YV12_OVERLAY) { /* switch the U and V planes */ - plane2 = 2; /* U plane maps to plane 3 */ - plane3 = 1; /* V plane maps to plane 2 */ - } - else { - SDL_SetError("Unsupported YUV format"); + plane2 = 2; /* U plane maps to plane 3 */ + plane3 = 1; /* V plane maps to plane 2 */ + } else { + SDL_SetError ("Unsupported YUV format"); return NULL; } - pixels = (Uint8**) SDL_malloc (sizeof(*pixels) * 3); - pitches = (Uint16*) SDL_malloc (sizeof(*pitches) * 3); + pixels = (Uint8 **) SDL_malloc (sizeof (*pixels) * 3); + pitches = (Uint16 *) SDL_malloc (sizeof (*pitches) * 3); if (pixels == NULL || pitches == NULL) { - SDL_OutOfMemory(); + SDL_OutOfMemory (); return NULL; } - yuv_pixmap = (PlanarPixmapInfoYUV420*) - SDL_malloc (sizeof(PlanarPixmapInfoYUV420) + - (width * height * 2)); + yuv_pixmap = (PlanarPixmapInfoYUV420 *) + SDL_malloc (sizeof (PlanarPixmapInfoYUV420) + + (width * height * 2)); if (yuv_pixmap == NULL) { SDL_OutOfMemory (); return NULL; } /* CHECK_ALIGN(yuv_pixmap); */ - offset = sizeof(PlanarPixmapInfoYUV420); + offset = sizeof (PlanarPixmapInfoYUV420); /* offset += ALIGN(offset); */ /* CHECK_ALIGN(offset); */ - pixels[0] = (Uint8*)yuv_pixmap + offset; + pixels[0] = (Uint8 *) yuv_pixmap + offset; /* CHECK_ALIGN(pixels[0]); */ pitches[0] = width; @@ -295,13 +297,13 @@ static void QZ_FreeHWYUV (_THIS, SDL_Overlay *overlay) { yuv_pixmap->componentInfoY.rowBytes = width; offset += width * height; - pixels[plane2] = (Uint8*)yuv_pixmap + offset; + pixels[plane2] = (Uint8 *) yuv_pixmap + offset; pitches[plane2] = width / 2; yuv_pixmap->componentInfoCb.offset = offset; yuv_pixmap->componentInfoCb.rowBytes = width / 2; offset += (width * height / 4); - pixels[plane3] = (Uint8*)yuv_pixmap + offset; + pixels[plane3] = (Uint8 *) yuv_pixmap + offset; pitches[plane3] = width / 2; yuv_pixmap->componentInfoCr.offset = offset; yuv_pixmap->componentInfoCr.rowBytes = width / 2; @@ -310,19 +312,19 @@ static void QZ_FreeHWYUV (_THIS, SDL_Overlay *overlay) { overlay->pitches = pitches; } - overlay->hwfuncs = SDL_malloc (sizeof(*overlay->hwfuncs)); + overlay->hwfuncs = SDL_malloc (sizeof (*overlay->hwfuncs)); if (overlay->hwfuncs == NULL) { - SDL_OutOfMemory(); + SDL_OutOfMemory (); return NULL; } - - overlay->hwfuncs->Lock = QZ_LockYUV; - overlay->hwfuncs->Unlock = QZ_UnlockYUV; + + overlay->hwfuncs->Lock = QZ_LockYUV; + overlay->hwfuncs->Unlock = QZ_UnlockYUV; overlay->hwfuncs->Display = QZ_DisplayYUV; - overlay->hwfuncs->FreeHW = QZ_FreeHWYUV; + overlay->hwfuncs->FreeHW = QZ_FreeHWYUV; yuv_width = overlay->w; yuv_height = overlay->h; - + return overlay; } diff --git a/src/video/riscos/SDL_riscosFullScreenVideo.c b/src/video/riscos/SDL_riscosFullScreenVideo.c index 36047386d..01bd966b0 100644 --- a/src/video/riscos/SDL_riscosFullScreenVideo.c +++ b/src/video/riscos/SDL_riscosFullScreenVideo.c @@ -47,12 +47,12 @@ /* Private structures */ typedef struct tagScreenModeBlock { - int flags; // mode selector flags, bit 0 = 1, bit 1-7 format specifier, 8-31 reserved - int x_pixels; - int y_pixels; - int pixel_depth; // 2^pixel_depth = bpp,i.e. 0 = 1, 1 = 2, 4 = 16, 5 = 32 - int frame_rate; // -1 use first match - int mode_vars[5]; // array of index, value pairs terminated by -1 + int flags; // mode selector flags, bit 0 = 1, bit 1-7 format specifier, 8-31 reserved + int x_pixels; + int y_pixels; + int pixel_depth; // 2^pixel_depth = bpp,i.e. 0 = 1, 1 = 2, 4 = 16, 5 = 32 + int frame_rate; // -1 use first match + int mode_vars[5]; // array of index, value pairs terminated by -1 } SCREENMODEBLOCK; @@ -62,18 +62,22 @@ int FULLSCREEN_SetMode(int width, int height, int bpp); void FULLSCREEN_SetupBanks(_THIS); /* SDL video device functions for fullscreen mode */ -static int FULLSCREEN_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color *colors); -static int FULLSCREEN_FlipHWSurface(_THIS, SDL_Surface *surface); +static int FULLSCREEN_SetColors(_THIS, int firstcolor, int ncolors, + SDL_Color * colors); +static int FULLSCREEN_FlipHWSurface(_THIS, SDL_Surface * surface); void FULLSCREEN_SetWMCaption(_THIS, const char *title, const char *icon); -extern int RISCOS_GetWmInfo(_THIS, SDL_SysWMinfo *info); +extern int RISCOS_GetWmInfo(_THIS, SDL_SysWMinfo * info); /* UpdateRects variants */ -static void FULLSCREEN_UpdateRects(_THIS, int numrects, SDL_Rect *rects); -static void FULLSCREEN_UpdateRectsMemCpy(_THIS, int numrects, SDL_Rect *rects); -static void FULLSCREEN_UpdateRects8bpp(_THIS, int numrects, SDL_Rect *rects); -static void FULLSCREEN_UpdateRects16bpp(_THIS, int numrects, SDL_Rect *rects); -static void FULLSCREEN_UpdateRects32bpp(_THIS, int numrects, SDL_Rect *rects); -static void FULLSCREEN_UpdateRectsOS(_THIS, int numrects, SDL_Rect *rects); +static void FULLSCREEN_UpdateRects(_THIS, int numrects, SDL_Rect * rects); +static void FULLSCREEN_UpdateRectsMemCpy(_THIS, int numrects, + SDL_Rect * rects); +static void FULLSCREEN_UpdateRects8bpp(_THIS, int numrects, SDL_Rect * rects); +static void FULLSCREEN_UpdateRects16bpp(_THIS, int numrects, + SDL_Rect * rects); +static void FULLSCREEN_UpdateRects32bpp(_THIS, int numrects, + SDL_Rect * rects); +static void FULLSCREEN_UpdateRectsOS(_THIS, int numrects, SDL_Rect * rects); /* Local helper functions */ static int cmpmodes(const void *va, const void *vb); @@ -85,580 +89,587 @@ static void FULLSCREEN_EnableEscape(); void FULLSCREEN_BuildModeList(_THIS); /* Following variable is set up in riskosTask.c */ -extern int riscos_backbuffer; /* Create a back buffer in system memory for full screen mode */ +extern int riscos_backbuffer; /* Create a back buffer in system memory for full screen mode */ /* Following is used to create a sprite back buffer */ extern unsigned char *WIMP_CreateBuffer(int width, int height, int bpp); /* Fast assembler copy */ -extern void RISCOS_Put32(void *to, int pixels, int pitch, int rows, void *from, int src_skip_bytes); +extern void RISCOS_Put32(void *to, int pixels, int pitch, int rows, + void *from, int src_skip_bytes); -SDL_Surface *FULLSCREEN_SetVideoMode(_THIS, SDL_Surface *current, - int width, int height, int bpp, Uint32 flags) +SDL_Surface * +FULLSCREEN_SetVideoMode(_THIS, SDL_Surface * current, + int width, int height, int bpp, Uint32 flags) { - _kernel_swi_regs regs; - Uint32 Rmask = 0; - Uint32 Gmask = 0; - Uint32 Bmask = 0; - int create_back_buffer = riscos_backbuffer; - - switch(bpp) - { - case 8: - flags |= SDL_HWPALETTE; - break; - - case 15: - case 16: - Bmask = 0x00007c00; - Gmask = 0x000003e0; - Rmask = 0x0000001f; - break; - - case 32: - Bmask = 0x00ff0000; - Gmask = 0x0000ff00; - Rmask = 0x000000ff; - break; - - default: - SDL_SetError("Pixel depth not supported"); - return NULL; - break; - } - - if (FULLSCREEN_SetMode(width, height, bpp) == 0) - { - SDL_SetError("Couldn't set requested mode"); - return (NULL); - } + _kernel_swi_regs regs; + Uint32 Rmask = 0; + Uint32 Gmask = 0; + Uint32 Bmask = 0; + int create_back_buffer = riscos_backbuffer; + + switch (bpp) { + case 8: + flags |= SDL_HWPALETTE; + break; + + case 15: + case 16: + Bmask = 0x00007c00; + Gmask = 0x000003e0; + Rmask = 0x0000001f; + break; + + case 32: + Bmask = 0x00ff0000; + Gmask = 0x0000ff00; + Rmask = 0x000000ff; + break; + + default: + SDL_SetError("Pixel depth not supported"); + return NULL; + break; + } + + if (FULLSCREEN_SetMode(width, height, bpp) == 0) { + SDL_SetError("Couldn't set requested mode"); + return (NULL); + } /* printf("Setting mode %dx%d\n", width, height); */ - /* Allocate the new pixel format for the screen */ - if ( ! SDL_ReallocFormat(current, bpp, Rmask, Gmask, Bmask, 0) ) { - RISCOS_RestoreWimpMode(); - SDL_SetError("Couldn't allocate new pixel format for requested mode"); - return(NULL); - } - - /* Set up the new mode framebuffer */ - current->w = width; - this->hidden->height = current->h = height; - - regs.r[0] = -1; /* -1 for current screen mode */ - - /* Get screen width in bytes */ - regs.r[1] = 6; // Screen Width in bytes - _kernel_swi(OS_ReadModeVariable, ®s, ®s); - - current->pitch = regs.r[2]; - - if (flags & SDL_DOUBLEBUF) - { - regs.r[0] = 2; /* Screen area */ - _kernel_swi(OS_ReadDynamicArea, ®s, ®s); - - /* Reg 1 has amount of memory currently used for display */ - regs.r[0] = 2; /* Screen area */ - regs.r[1] = (current->pitch * height * 2) - regs.r[1]; - if (_kernel_swi(OS_ChangeDynamicArea, ®s, ®s) != NULL) - { - /* Can't allocate enough screen memory for double buffer */ - flags &= ~SDL_DOUBLEBUF; - } - } - - current->flags = flags | SDL_FULLSCREEN | SDL_HWSURFACE | SDL_PREALLOC; - - - /* Need to set display banks here for double buffering */ - if (flags & SDL_DOUBLEBUF) - { - FULLSCREEN_SetWriteBank(0); - FULLSCREEN_SetDisplayBank(1); - - create_back_buffer = 0; /* Don't need a back buffer for a double buffered display */ + /* Allocate the new pixel format for the screen */ + if (!SDL_ReallocFormat(current, bpp, Rmask, Gmask, Bmask, 0)) { + RISCOS_RestoreWimpMode(); + SDL_SetError("Couldn't allocate new pixel format for requested mode"); + return (NULL); + } + + /* Set up the new mode framebuffer */ + current->w = width; + this->hidden->height = current->h = height; + + regs.r[0] = -1; /* -1 for current screen mode */ + + /* Get screen width in bytes */ + regs.r[1] = 6; // Screen Width in bytes + _kernel_swi(OS_ReadModeVariable, ®s, ®s); + + current->pitch = regs.r[2]; + + if (flags & SDL_DOUBLEBUF) { + regs.r[0] = 2; /* Screen area */ + _kernel_swi(OS_ReadDynamicArea, ®s, ®s); + + /* Reg 1 has amount of memory currently used for display */ + regs.r[0] = 2; /* Screen area */ + regs.r[1] = (current->pitch * height * 2) - regs.r[1]; + if (_kernel_swi(OS_ChangeDynamicArea, ®s, ®s) != NULL) { + /* Can't allocate enough screen memory for double buffer */ + flags &= ~SDL_DOUBLEBUF; + } + } + + current->flags = flags | SDL_FULLSCREEN | SDL_HWSURFACE | SDL_PREALLOC; + + + /* Need to set display banks here for double buffering */ + if (flags & SDL_DOUBLEBUF) { + FULLSCREEN_SetWriteBank(0); + FULLSCREEN_SetDisplayBank(1); + + create_back_buffer = 0; /* Don't need a back buffer for a double buffered display */ } FULLSCREEN_SetupBanks(this); - if (create_back_buffer) - { - /* If not double buffered we may need to create a memory + if (create_back_buffer) { + /* If not double buffered we may need to create a memory ** back buffer to simulate processing on other OSes. ** This is turned on by setting the enviromental variable ** SDL$$BackBuffer >= 1 */ - if (riscos_backbuffer == 3) - this->hidden->bank[0] = WIMP_CreateBuffer(width, height, bpp); - else - this->hidden->bank[0] = SDL_malloc(height * current->pitch); - if (this->hidden->bank[0] == 0) - { - RISCOS_RestoreWimpMode(); - SDL_SetError("Couldnt allocate memory for back buffer"); - return (NULL); - } - /* Surface updated in programs is now a software surface */ - current->flags &= ~SDL_HWSURFACE; + if (riscos_backbuffer == 3) + this->hidden->bank[0] = WIMP_CreateBuffer(width, height, bpp); + else + this->hidden->bank[0] = SDL_malloc(height * current->pitch); + if (this->hidden->bank[0] == 0) { + RISCOS_RestoreWimpMode(); + SDL_SetError("Couldnt allocate memory for back buffer"); + return (NULL); + } + /* Surface updated in programs is now a software surface */ + current->flags &= ~SDL_HWSURFACE; } /* Store address of allocated screen bank to be freed later */ - if (this->hidden->alloc_bank) SDL_free(this->hidden->alloc_bank); - if (create_back_buffer) - { + if (this->hidden->alloc_bank) + SDL_free(this->hidden->alloc_bank); + if (create_back_buffer) { this->hidden->alloc_bank = this->hidden->bank[0]; - if (riscos_backbuffer == 3) - { - this->hidden->bank[0] += 60; /* Start of sprite data */ - if (bpp == 8) this->hidden->bank[0] += 2048; /* 8bpp sprite have palette first */ + if (riscos_backbuffer == 3) { + this->hidden->bank[0] += 60; /* Start of sprite data */ + if (bpp == 8) + this->hidden->bank[0] += 2048; /* 8bpp sprite have palette first */ } } else - this->hidden->alloc_bank = 0; + this->hidden->alloc_bank = 0; // Clear both banks to black SDL_memset(this->hidden->bank[0], 0, height * current->pitch); SDL_memset(this->hidden->bank[1], 0, height * current->pitch); - this->hidden->current_bank = 0; - current->pixels = this->hidden->bank[0]; + this->hidden->current_bank = 0; + current->pixels = this->hidden->bank[0]; /* Have to set the screen here, so SetDeviceMode will pick it up */ this->screen = current; - /* Reset device functions for the wimp */ - FULLSCREEN_SetDeviceMode(this); + /* Reset device functions for the wimp */ + FULLSCREEN_SetDeviceMode(this); /* FULLSCREEN_DisableEscape(); */ - /* We're done */ - return(current); + /* We're done */ + return (current); } /* Reset any device functions that have been changed because we have run in WIMP mode */ -void FULLSCREEN_SetDeviceMode(_THIS) +void +FULLSCREEN_SetDeviceMode(_THIS) { - /* Update rects is different if we have a backbuffer */ - - if (riscos_backbuffer && (this->screen->flags & SDL_DOUBLEBUF) == 0) - { - switch(riscos_backbuffer) - { - case 2: /* ARM code full word copy */ - switch(this->screen->format->BytesPerPixel) - { - case 1: /* 8bpp modes */ - this->UpdateRects = FULLSCREEN_UpdateRects8bpp; - break; - case 2: /* 15/16bpp modes */ - this->UpdateRects = FULLSCREEN_UpdateRects16bpp; - break; - case 4: /* 32 bpp modes */ - this->UpdateRects = FULLSCREEN_UpdateRects32bpp; - break; - - default: /* Just default to the memcpy routine */ - this->UpdateRects = FULLSCREEN_UpdateRectsMemCpy; - break; - } - break; - - case 3: /* Use OS sprite plot routine */ - this->UpdateRects = FULLSCREEN_UpdateRectsOS; - break; - - default: /* Old but safe memcpy */ - this->UpdateRects = FULLSCREEN_UpdateRectsMemCpy; - break; - } - } else - this->UpdateRects = FULLSCREEN_UpdateRects; /* Default do nothing implementation */ - - this->SetColors = FULLSCREEN_SetColors; - - this->FlipHWSurface = FULLSCREEN_FlipHWSurface; - - this->SetCaption = FULLSCREEN_SetWMCaption; - this->SetIcon = NULL; - this->IconifyWindow = NULL; - - this->ShowWMCursor = RISCOS_ShowWMCursor; - this->WarpWMCursor = FULLSCREEN_WarpWMCursor; - - this->PumpEvents = FULLSCREEN_PumpEvents; + /* Update rects is different if we have a backbuffer */ + + if (riscos_backbuffer && (this->screen->flags & SDL_DOUBLEBUF) == 0) { + switch (riscos_backbuffer) { + case 2: /* ARM code full word copy */ + switch (this->screen->format->BytesPerPixel) { + case 1: /* 8bpp modes */ + this->UpdateRects = FULLSCREEN_UpdateRects8bpp; + break; + case 2: /* 15/16bpp modes */ + this->UpdateRects = FULLSCREEN_UpdateRects16bpp; + break; + case 4: /* 32 bpp modes */ + this->UpdateRects = FULLSCREEN_UpdateRects32bpp; + break; + + default: /* Just default to the memcpy routine */ + this->UpdateRects = FULLSCREEN_UpdateRectsMemCpy; + break; + } + break; + + case 3: /* Use OS sprite plot routine */ + this->UpdateRects = FULLSCREEN_UpdateRectsOS; + break; + + default: /* Old but safe memcpy */ + this->UpdateRects = FULLSCREEN_UpdateRectsMemCpy; + break; + } + } else + this->UpdateRects = FULLSCREEN_UpdateRects; /* Default do nothing implementation */ + + this->SetColors = FULLSCREEN_SetColors; + + this->FlipHWSurface = FULLSCREEN_FlipHWSurface; + + this->SetCaption = FULLSCREEN_SetWMCaption; + this->SetIcon = NULL; + this->IconifyWindow = NULL; + + this->ShowWMCursor = RISCOS_ShowWMCursor; + this->WarpWMCursor = FULLSCREEN_WarpWMCursor; + + this->PumpEvents = FULLSCREEN_PumpEvents; } /* Query for the list of available video modes */ -void FULLSCREEN_BuildModeList(_THIS) +void +FULLSCREEN_BuildModeList(_THIS) { - _kernel_swi_regs regs; - char *enumInfo = NULL; - char *enum_ptr; - int *blockInfo; - int j; - int num_modes; - - /* Find out how much space we need */ - regs.r[0] = 2; /* Reason code */ - regs.r[2] = 0; /* Number of modes to skip */ - regs.r[6] = 0; /* pointer to block or 0 for count */ - regs.r[7] = 0; /* Size of block in bytes */ - _kernel_swi(OS_ScreenMode, ®s, ®s); + _kernel_swi_regs regs; + char *enumInfo = NULL; + char *enum_ptr; + int *blockInfo; + int j; + int num_modes; + + /* Find out how much space we need */ + regs.r[0] = 2; /* Reason code */ + regs.r[2] = 0; /* Number of modes to skip */ + regs.r[6] = 0; /* pointer to block or 0 for count */ + regs.r[7] = 0; /* Size of block in bytes */ + _kernel_swi(OS_ScreenMode, ®s, ®s); num_modes = -regs.r[2]; - /* Video memory should be in r[5] */ - this->info.video_mem = regs.r[5]/1024; - - enumInfo = (unsigned char *)SDL_malloc(-regs.r[7]); - if (enumInfo == NULL) - { - SDL_OutOfMemory(); - return; - } - /* Read mode information into block */ - regs.r[2] = 0; - regs.r[6] = (int)enumInfo; - regs.r[7] = -regs.r[7]; - _kernel_swi(OS_ScreenMode, ®s, ®s); - - enum_ptr = enumInfo; - - for (j =0; j < num_modes;j++) - { - blockInfo = (int *)enum_ptr; - if ((blockInfo[1] & 255) == 1) /* We understand this format */ - { - switch(blockInfo[4]) - { - case 3: /* 8 bits per pixel */ - FULLSCREEN_AddMode(this, 8, blockInfo[2], blockInfo[3]); - break; - case 4: /* 15 bits per pixel */ - FULLSCREEN_AddMode(this, 15, blockInfo[2], blockInfo[3]); - break; - case 5: /* 32 bits per pixel */ - FULLSCREEN_AddMode(this, 32, blockInfo[2], blockInfo[3]); - break; - } - } - - enum_ptr += blockInfo[0]; - } - - SDL_free(enumInfo); - - /* Sort the mode lists */ - for ( j=0; j 0 ) { - SDL_qsort(SDL_modelist[j], SDL_nummodes[j], sizeof *SDL_modelist[j], cmpmodes); - } - } + /* Video memory should be in r[5] */ + this->info.video_mem = regs.r[5] / 1024; + + enumInfo = (unsigned char *) SDL_malloc(-regs.r[7]); + if (enumInfo == NULL) { + SDL_OutOfMemory(); + return; + } + /* Read mode information into block */ + regs.r[2] = 0; + regs.r[6] = (int) enumInfo; + regs.r[7] = -regs.r[7]; + _kernel_swi(OS_ScreenMode, ®s, ®s); + + enum_ptr = enumInfo; + + for (j = 0; j < num_modes; j++) { + blockInfo = (int *) enum_ptr; + if ((blockInfo[1] & 255) == 1) { /* We understand this format */ + switch (blockInfo[4]) { + case 3: /* 8 bits per pixel */ + FULLSCREEN_AddMode(this, 8, blockInfo[2], blockInfo[3]); + break; + case 4: /* 15 bits per pixel */ + FULLSCREEN_AddMode(this, 15, blockInfo[2], blockInfo[3]); + break; + case 5: /* 32 bits per pixel */ + FULLSCREEN_AddMode(this, 32, blockInfo[2], blockInfo[3]); + break; + } + } + + enum_ptr += blockInfo[0]; + } + + SDL_free(enumInfo); + + /* Sort the mode lists */ + for (j = 0; j < NUM_MODELISTS; ++j) { + if (SDL_nummodes[j] > 0) { + SDL_qsort(SDL_modelist[j], SDL_nummodes[j], + sizeof *SDL_modelist[j], cmpmodes); + } + } } -static int FULLSCREEN_FlipHWSurface(_THIS, SDL_Surface *surface) +static int +FULLSCREEN_FlipHWSurface(_THIS, SDL_Surface * surface) { - _kernel_swi_regs regs; - regs.r[0] = 19; + _kernel_swi_regs regs; + regs.r[0] = 19; - FULLSCREEN_SetDisplayBank(this->hidden->current_bank); - this->hidden->current_bank ^= 1; - FULLSCREEN_SetWriteBank(this->hidden->current_bank); - surface->pixels = this->hidden->bank[this->hidden->current_bank]; + FULLSCREEN_SetDisplayBank(this->hidden->current_bank); + this->hidden->current_bank ^= 1; + FULLSCREEN_SetWriteBank(this->hidden->current_bank); + surface->pixels = this->hidden->bank[this->hidden->current_bank]; - /* Wait for Vsync */ - _kernel_swi(OS_Byte, ®s, ®s); + /* Wait for Vsync */ + _kernel_swi(OS_Byte, ®s, ®s); - return(0); + return (0); } /* Nothing to do if we are writing direct to hardware */ -static void FULLSCREEN_UpdateRects(_THIS, int numrects, SDL_Rect *rects) +static void +FULLSCREEN_UpdateRects(_THIS, int numrects, SDL_Rect * rects) { } /* Safe but slower Memory copy from our allocated back buffer */ -static void FULLSCREEN_UpdateRectsMemCpy(_THIS, int numrects, SDL_Rect *rects) +static void +FULLSCREEN_UpdateRectsMemCpy(_THIS, int numrects, SDL_Rect * rects) { - int j; - char *to, *from; - int pitch = this->screen->pitch; - int row; - int xmult = this->screen->format->BytesPerPixel; - for (j = 0; j < numrects; j++) - { - from = this->hidden->bank[0] + rects->x * xmult + rects->y * pitch; - to = this->hidden->bank[1] + rects->x * xmult + rects->y * pitch; - for (row = 0; row < rects->h; row++) - { - SDL_memcpy(to, from, rects->w * xmult); - from += pitch; - to += pitch; - } - rects++; - } + int j; + char *to, *from; + int pitch = this->screen->pitch; + int row; + int xmult = this->screen->format->BytesPerPixel; + for (j = 0; j < numrects; j++) { + from = this->hidden->bank[0] + rects->x * xmult + rects->y * pitch; + to = this->hidden->bank[1] + rects->x * xmult + rects->y * pitch; + for (row = 0; row < rects->h; row++) { + SDL_memcpy(to, from, rects->w * xmult); + from += pitch; + to += pitch; + } + rects++; + } } /* Use optimized assembler memory copy. Deliberately copies extra columns if necessary to ensure the rectangle is word aligned. */ -static void FULLSCREEN_UpdateRects8bpp(_THIS, int numrects, SDL_Rect *rects) +static void +FULLSCREEN_UpdateRects8bpp(_THIS, int numrects, SDL_Rect * rects) { - int j; - char *to, *from; - int pitch = this->screen->pitch; - int width_bytes; - int src_skip_bytes; - - for (j = 0; j < numrects; j++) - { - from = this->hidden->bank[0] + rects->x + rects->y * pitch; - to = this->hidden->bank[1] + rects->x + rects->y * pitch; - width_bytes = rects->w; - if ((int)from & 3) - { - int extra = ((int)from & 3); - from -= extra; - to -= extra; - width_bytes += extra; - } - if (width_bytes & 3) width_bytes += 4 - (width_bytes & 3); - src_skip_bytes = pitch - width_bytes; - - RISCOS_Put32(to, (width_bytes >> 2), pitch, (int)rects->h, from, src_skip_bytes); - rects++; - } + int j; + char *to, *from; + int pitch = this->screen->pitch; + int width_bytes; + int src_skip_bytes; + + for (j = 0; j < numrects; j++) { + from = this->hidden->bank[0] + rects->x + rects->y * pitch; + to = this->hidden->bank[1] + rects->x + rects->y * pitch; + width_bytes = rects->w; + if ((int) from & 3) { + int extra = ((int) from & 3); + from -= extra; + to -= extra; + width_bytes += extra; + } + if (width_bytes & 3) + width_bytes += 4 - (width_bytes & 3); + src_skip_bytes = pitch - width_bytes; + + RISCOS_Put32(to, (width_bytes >> 2), pitch, (int) rects->h, from, + src_skip_bytes); + rects++; + } } /* Use optimized assembler memory copy. Deliberately copies extra columns if necessary to ensure the rectangle is word aligned. */ -static void FULLSCREEN_UpdateRects16bpp(_THIS, int numrects, SDL_Rect *rects) +static void +FULLSCREEN_UpdateRects16bpp(_THIS, int numrects, SDL_Rect * rects) { - int j; - char *to, *from; - int pitch = this->screen->pitch; - int width_bytes; - int src_skip_bytes; - - for (j = 0; j < numrects; j++) - { - from = this->hidden->bank[0] + (rects->x << 1) + rects->y * pitch; - to = this->hidden->bank[1] + (rects->x << 1) + rects->y * pitch; - width_bytes = (((int)rects->w) << 1); - if ((int)from & 3) - { - from -= 2; - to -= 2; - width_bytes += 2; - } - if (width_bytes & 3) width_bytes += 2; - src_skip_bytes = pitch - width_bytes; - - RISCOS_Put32(to, (width_bytes >> 2), pitch, (int)rects->h, from, src_skip_bytes); - rects++; - } + int j; + char *to, *from; + int pitch = this->screen->pitch; + int width_bytes; + int src_skip_bytes; + + for (j = 0; j < numrects; j++) { + from = this->hidden->bank[0] + (rects->x << 1) + rects->y * pitch; + to = this->hidden->bank[1] + (rects->x << 1) + rects->y * pitch; + width_bytes = (((int) rects->w) << 1); + if ((int) from & 3) { + from -= 2; + to -= 2; + width_bytes += 2; + } + if (width_bytes & 3) + width_bytes += 2; + src_skip_bytes = pitch - width_bytes; + + RISCOS_Put32(to, (width_bytes >> 2), pitch, (int) rects->h, from, + src_skip_bytes); + rects++; + } } /* Use optimized assembler memory copy. 32 bpp modes are always word aligned */ -static void FULLSCREEN_UpdateRects32bpp(_THIS, int numrects, SDL_Rect *rects) +static void +FULLSCREEN_UpdateRects32bpp(_THIS, int numrects, SDL_Rect * rects) { - int j; - char *to, *from; - int pitch = this->screen->pitch; - int width; - - for (j = 0; j < numrects; j++) - { - from = this->hidden->bank[0] + (rects->x << 2) + rects->y * pitch; - to = this->hidden->bank[1] + (rects->x << 2) + rects->y * pitch; - width = (int)rects->w ; - - RISCOS_Put32(to, width, pitch, (int)rects->h, from, pitch - (width << 2)); - rects++; - } + int j; + char *to, *from; + int pitch = this->screen->pitch; + int width; + + for (j = 0; j < numrects; j++) { + from = this->hidden->bank[0] + (rects->x << 2) + rects->y * pitch; + to = this->hidden->bank[1] + (rects->x << 2) + rects->y * pitch; + width = (int) rects->w; + + RISCOS_Put32(to, width, pitch, (int) rects->h, from, + pitch - (width << 2)); + rects++; + } } /* Use operating system sprite plots. Currently this is much slower than the other variants however accelerated sprite plotting can be seen on the horizon so this prepares for it. */ -static void FULLSCREEN_UpdateRectsOS(_THIS, int numrects, SDL_Rect *rects) +static void +FULLSCREEN_UpdateRectsOS(_THIS, int numrects, SDL_Rect * rects) { - _kernel_swi_regs regs; - _kernel_oserror *err; - int j; - int y; - - regs.r[0] = 28 + 512; - regs.r[1] = (unsigned int)this->hidden->alloc_bank; - regs.r[2] = (unsigned int)this->hidden->alloc_bank+16; - regs.r[5] = 0; - - for (j = 0; j < numrects; j++) - { - y = this->screen->h - rects->y; /* top of clipping region */ - _kernel_oswrch(24); /* Set graphics clip region */ - _kernel_oswrch((rects->x << this->hidden->xeig) & 0xFF); /* left */ - _kernel_oswrch(((rects->x << this->hidden->xeig) >> 8) & 0xFF); - _kernel_oswrch(((y - rects->h) << this->hidden->yeig) & 0xFF); /* bottom */ - _kernel_oswrch((((y - rects->h) << this->hidden->yeig)>> 8) & 0xFF); - _kernel_oswrch(((rects->x + rects->w - 1) << this->hidden->xeig) & 0xFF); /* right */ - _kernel_oswrch((((rects->x + rects->w - 1)<< this->hidden->xeig) >> 8) & 0xFF); - _kernel_oswrch(((y-1) << this->hidden->yeig) & 0xFF); /* top */ - _kernel_oswrch((((y-1) << this->hidden->yeig) >> 8) & 0xFF); - - regs.r[3] = 0; - regs.r[4] = 0; - - if ((err = _kernel_swi(OS_SpriteOp, ®s, ®s)) != 0) - { - printf("OS_SpriteOp failed \n%s\n",err->errmess); - } - - rects++; - - /* Reset to full screen clipping */ - _kernel_oswrch(24); /* Set graphics clip region */ - _kernel_oswrch(0); /* left */ - _kernel_oswrch(0); - _kernel_oswrch(0); /* bottom */ - _kernel_oswrch(0); - _kernel_oswrch(((this->screen->w-1) << this->hidden->xeig) & 0xFF); /* right */ - _kernel_oswrch((((this->screen->w-1) << this->hidden->xeig) >> 8) & 0xFF); - _kernel_oswrch(((this->screen->h-1) << this->hidden->yeig) & 0xFF); /* top */ - _kernel_oswrch((((this->screen->h-1) << this->hidden->yeig) >> 8) & 0xFF); - } + _kernel_swi_regs regs; + _kernel_oserror *err; + int j; + int y; + + regs.r[0] = 28 + 512; + regs.r[1] = (unsigned int) this->hidden->alloc_bank; + regs.r[2] = (unsigned int) this->hidden->alloc_bank + 16; + regs.r[5] = 0; + + for (j = 0; j < numrects; j++) { + y = this->screen->h - rects->y; /* top of clipping region */ + _kernel_oswrch(24); /* Set graphics clip region */ + _kernel_oswrch((rects->x << this->hidden->xeig) & 0xFF); /* left */ + _kernel_oswrch(((rects->x << this->hidden->xeig) >> 8) & 0xFF); + _kernel_oswrch(((y - rects->h) << this->hidden->yeig) & 0xFF); /* bottom */ + _kernel_oswrch((((y - rects->h) << this->hidden->yeig) >> 8) & 0xFF); + _kernel_oswrch(((rects->x + rects->w - 1) << this->hidden->xeig) & 0xFF); /* right */ + _kernel_oswrch((((rects->x + rects->w - + 1) << this->hidden->xeig) >> 8) & 0xFF); + _kernel_oswrch(((y - 1) << this->hidden->yeig) & 0xFF); /* top */ + _kernel_oswrch((((y - 1) << this->hidden->yeig) >> 8) & 0xFF); + + regs.r[3] = 0; + regs.r[4] = 0; + + if ((err = _kernel_swi(OS_SpriteOp, ®s, ®s)) != 0) { + printf("OS_SpriteOp failed \n%s\n", err->errmess); + } + + rects++; + + /* Reset to full screen clipping */ + _kernel_oswrch(24); /* Set graphics clip region */ + _kernel_oswrch(0); /* left */ + _kernel_oswrch(0); + _kernel_oswrch(0); /* bottom */ + _kernel_oswrch(0); + _kernel_oswrch(((this->screen->w - 1) << this->hidden->xeig) & 0xFF); /* right */ + _kernel_oswrch((((this->screen->w - + 1) << this->hidden->xeig) >> 8) & 0xFF); + _kernel_oswrch(((this->screen->h - 1) << this->hidden->yeig) & 0xFF); /* top */ + _kernel_oswrch((((this->screen->h - + 1) << this->hidden->yeig) >> 8) & 0xFF); + } } -int FULLSCREEN_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color *colors) +int +FULLSCREEN_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color * colors) { - _kernel_swi_regs regs; - int palette[256]; - - regs.r[0] = -1; - regs.r[1] = -1; - regs.r[2] = (int)palette; - regs.r[3] = 1024; - regs.r[4] = 0; - _kernel_swi(ColourTrans_ReadPalette, ®s, ®s); - - while(ncolors--) - { - palette[firstcolor] = ((colors->b) << 24) | ((colors->g) << 16) | ((colors->r) << 8); - firstcolor++; - colors++; - } - - regs.r[0] = -1; - regs.r[1] = -1; - regs.r[2] = (int)palette; - regs.r[3] = 0; - regs.r[4] = 0; - _kernel_swi(ColourTrans_WritePalette, ®s, ®s); - - return(1); + _kernel_swi_regs regs; + int palette[256]; + + regs.r[0] = -1; + regs.r[1] = -1; + regs.r[2] = (int) palette; + regs.r[3] = 1024; + regs.r[4] = 0; + _kernel_swi(ColourTrans_ReadPalette, ®s, ®s); + + while (ncolors--) { + palette[firstcolor] = + ((colors->b) << 24) | ((colors->g) << 16) | ((colors->r) << 8); + firstcolor++; + colors++; + } + + regs.r[0] = -1; + regs.r[1] = -1; + regs.r[2] = (int) palette; + regs.r[3] = 0; + regs.r[4] = 0; + _kernel_swi(ColourTrans_WritePalette, ®s, ®s); + + return (1); } -static int cmpmodes(const void *va, const void *vb) +static int +cmpmodes(const void *va, const void *vb) { - SDL_Rect *a = *(SDL_Rect **)va; - SDL_Rect *b = *(SDL_Rect **)vb; - if(a->w == b->w) + SDL_Rect *a = *(SDL_Rect **) va; + SDL_Rect *b = *(SDL_Rect **) vb; + if (a->w == b->w) return b->h - a->h; else return b->w - a->w; } -static int FULLSCREEN_AddMode(_THIS, int bpp, int w, int h) +static int +FULLSCREEN_AddMode(_THIS, int bpp, int w, int h) { - SDL_Rect *mode; - int i, index; - int next_mode; - - /* Check to see if we already have this mode */ - if ( bpp < 8 ) { /* Not supported */ - return(0); - } - index = ((bpp+7)/8)-1; - for ( i=0; iw == w) && (mode->h == h) ) { - return(0); - } - } - - /* Set up the new video mode rectangle */ - mode = (SDL_Rect *)SDL_malloc(sizeof *mode); - if ( mode == NULL ) { - SDL_OutOfMemory(); - return(-1); - } - mode->x = 0; - mode->y = 0; - mode->w = w; - mode->h = h; - - /* Allocate the new list of modes, and fill in the new mode */ - next_mode = SDL_nummodes[index]; - SDL_modelist[index] = (SDL_Rect **) - SDL_realloc(SDL_modelist[index], (1+next_mode+1)*sizeof(SDL_Rect *)); - if ( SDL_modelist[index] == NULL ) { - SDL_OutOfMemory(); - SDL_nummodes[index] = 0; - SDL_free(mode); - return(-1); - } - SDL_modelist[index][next_mode] = mode; - SDL_modelist[index][next_mode+1] = NULL; - SDL_nummodes[index]++; - - return(0); + SDL_Rect *mode; + int i, index; + int next_mode; + + /* Check to see if we already have this mode */ + if (bpp < 8) { /* Not supported */ + return (0); + } + index = ((bpp + 7) / 8) - 1; + for (i = 0; i < SDL_nummodes[index]; ++i) { + mode = SDL_modelist[index][i]; + if ((mode->w == w) && (mode->h == h)) { + return (0); + } + } + + /* Set up the new video mode rectangle */ + mode = (SDL_Rect *) SDL_malloc(sizeof *mode); + if (mode == NULL) { + SDL_OutOfMemory(); + return (-1); + } + mode->x = 0; + mode->y = 0; + mode->w = w; + mode->h = h; + + /* Allocate the new list of modes, and fill in the new mode */ + next_mode = SDL_nummodes[index]; + SDL_modelist[index] = (SDL_Rect **) + SDL_realloc(SDL_modelist[index], + (1 + next_mode + 1) * sizeof(SDL_Rect *)); + if (SDL_modelist[index] == NULL) { + SDL_OutOfMemory(); + SDL_nummodes[index] = 0; + SDL_free(mode); + return (-1); + } + SDL_modelist[index][next_mode] = mode; + SDL_modelist[index][next_mode + 1] = NULL; + SDL_nummodes[index]++; + + return (0); } -void FULLSCREEN_SetWriteBank(int bank) +void +FULLSCREEN_SetWriteBank(int bank) { - _kernel_swi_regs regs; - regs.r[0] = 112; - regs.r[1] = bank+1; - _kernel_swi(OS_Byte, ®s, ®s); + _kernel_swi_regs regs; + regs.r[0] = 112; + regs.r[1] = bank + 1; + _kernel_swi(OS_Byte, ®s, ®s); } -void FULLSCREEN_SetDisplayBank(int bank) +void +FULLSCREEN_SetDisplayBank(int bank) { - _kernel_swi_regs regs; - regs.r[0] = 113; - regs.r[1] = bank+1; - _kernel_swi(OS_Byte, ®s, ®s); + _kernel_swi_regs regs; + regs.r[0] = 113; + regs.r[1] = bank + 1; + _kernel_swi(OS_Byte, ®s, ®s); } /** Disable special escape key processing */ -static void FULLSCREEN_DisableEscape() +static void +FULLSCREEN_DisableEscape() { - _kernel_swi_regs regs; - regs.r[0] = 229; - regs.r[1] = 1; - regs.r[2] = 0; - _kernel_swi(OS_Byte, ®s, ®s); - + _kernel_swi_regs regs; + regs.r[0] = 229; + regs.r[1] = 1; + regs.r[2] = 0; + _kernel_swi(OS_Byte, ®s, ®s); + } /** Enable special escape key processing */ -static void FULLSCREEN_EnableEscape() +static void +FULLSCREEN_EnableEscape() { - _kernel_swi_regs regs; - regs.r[0] = 229; - regs.r[1] = 0; - regs.r[2] = 0; - _kernel_swi(OS_Byte, ®s, ®s); - + _kernel_swi_regs regs; + regs.r[0] = 229; + regs.r[1] = 0; + regs.r[2] = 0; + _kernel_swi(OS_Byte, ®s, ®s); + } /** Store caption in case this is called before we create a window */ -void FULLSCREEN_SetWMCaption(_THIS, const char *title, const char *icon) +void +FULLSCREEN_SetWMCaption(_THIS, const char *title, const char *icon) { - SDL_strlcpy(this->hidden->title, title, SDL_arraysize(this->hidden->title)); + SDL_strlcpy(this->hidden->title, title, + SDL_arraysize(this->hidden->title)); } /* Set screen mode @@ -666,112 +677,126 @@ void FULLSCREEN_SetWMCaption(_THIS, const char *title, const char *icon) * Returns 1 if mode is set ok, otherwise 0 */ -int FULLSCREEN_SetMode(int width, int height, int bpp) +int +FULLSCREEN_SetMode(int width, int height, int bpp) { - SCREENMODEBLOCK smb; - _kernel_swi_regs regs; - - smb.flags = 1; - smb.x_pixels = width; - smb.y_pixels = height; - smb.mode_vars[0] = -1; - - switch(bpp) - { - case 8: - smb.pixel_depth = 3; - /* Note: Need to set ModeFlags to 128 and NColour variables to 255 get full 8 bit palette */ - smb.mode_vars[0] = 0; smb.mode_vars[1] = 128; /* Mode flags */ - smb.mode_vars[2] = 3; smb.mode_vars[3] = 255; /* NColour (number of colours -1) */ - smb.mode_vars[4] = -1; /* End of list */ - break; - - case 15: - case 16: - smb.pixel_depth = 4; - break; - - case 32: - smb.pixel_depth = 5; - break; - - default: - SDL_SetError("Pixel depth not supported"); - return 0; - break; - } - - smb.frame_rate = -1; - - regs.r[0] = 0; - regs.r[1] = (int)&smb; - - if (_kernel_swi(OS_ScreenMode, ®s, ®s) != 0) - { - SDL_SetError("Couldn't set requested mode"); - return 0; - } - - /* Turn cursor off*/ - _kernel_oswrch(23);_kernel_oswrch(1);_kernel_oswrch(0); - _kernel_oswrch(0);_kernel_oswrch(0);_kernel_oswrch(0); - _kernel_oswrch(0);_kernel_oswrch(0);_kernel_oswrch(0); - _kernel_oswrch(0);_kernel_oswrch(0); - - return 1; + SCREENMODEBLOCK smb; + _kernel_swi_regs regs; + + smb.flags = 1; + smb.x_pixels = width; + smb.y_pixels = height; + smb.mode_vars[0] = -1; + + switch (bpp) { + case 8: + smb.pixel_depth = 3; + /* Note: Need to set ModeFlags to 128 and NColour variables to 255 get full 8 bit palette */ + smb.mode_vars[0] = 0; + smb.mode_vars[1] = 128; /* Mode flags */ + smb.mode_vars[2] = 3; + smb.mode_vars[3] = 255; /* NColour (number of colours -1) */ + smb.mode_vars[4] = -1; /* End of list */ + break; + + case 15: + case 16: + smb.pixel_depth = 4; + break; + + case 32: + smb.pixel_depth = 5; + break; + + default: + SDL_SetError("Pixel depth not supported"); + return 0; + break; + } + + smb.frame_rate = -1; + + regs.r[0] = 0; + regs.r[1] = (int) &smb; + + if (_kernel_swi(OS_ScreenMode, ®s, ®s) != 0) { + SDL_SetError("Couldn't set requested mode"); + return 0; + } + + /* Turn cursor off */ + _kernel_oswrch(23); + _kernel_oswrch(1); + _kernel_oswrch(0); + _kernel_oswrch(0); + _kernel_oswrch(0); + _kernel_oswrch(0); + _kernel_oswrch(0); + _kernel_oswrch(0); + _kernel_oswrch(0); + _kernel_oswrch(0); + _kernel_oswrch(0); + + return 1; } /* Get Start addresses for the screen banks */ -void FULLSCREEN_SetupBanks(_THIS) +void +FULLSCREEN_SetupBanks(_THIS) { - _kernel_swi_regs regs; - int block[5]; - block[0] = 148; /* Write screen start */ - block[1] = 149; /* Display screen start */ - block[2] = 4; /* X eig factor */ - block[3] = 5; /* Y eig factor */ - block[4] = -1; /* End of list of variables to request */ - - regs.r[0] = (int)block; - regs.r[1] = (int)block; - _kernel_swi(OS_ReadVduVariables, ®s, ®s); - - this->hidden->bank[0] = (void *)block[0]; - this->hidden->bank[1] = (void *)block[1]; - this->hidden->xeig = block[2]; - this->hidden->yeig = block[3]; + _kernel_swi_regs regs; + int block[5]; + block[0] = 148; /* Write screen start */ + block[1] = 149; /* Display screen start */ + block[2] = 4; /* X eig factor */ + block[3] = 5; /* Y eig factor */ + block[4] = -1; /* End of list of variables to request */ + + regs.r[0] = (int) block; + regs.r[1] = (int) block; + _kernel_swi(OS_ReadVduVariables, ®s, ®s); + + this->hidden->bank[0] = (void *) block[0]; + this->hidden->bank[1] = (void *) block[1]; + this->hidden->xeig = block[2]; + this->hidden->yeig = block[3]; } /* Toggle to full screen mode from the WIMP */ -int FULLSCREEN_ToggleFromWimp(_THIS) +int +FULLSCREEN_ToggleFromWimp(_THIS) { - int width = this->screen->w; - int height = this->screen->h; - int bpp = this->screen->format->BitsPerPixel; + int width = this->screen->w; + int height = this->screen->h; + int bpp = this->screen->format->BitsPerPixel; - RISCOS_StoreWimpMode(); - if (FULLSCREEN_SetMode(width, height, bpp)) - { - char *buffer = this->hidden->alloc_bank; /* This is start of sprite data */ - /* Support back buffer mode only */ - if (riscos_backbuffer == 0) riscos_backbuffer = 1; + RISCOS_StoreWimpMode(); + if (FULLSCREEN_SetMode(width, height, bpp)) { + char *buffer = this->hidden->alloc_bank; /* This is start of sprite data */ + /* Support back buffer mode only */ + if (riscos_backbuffer == 0) + riscos_backbuffer = 1; - FULLSCREEN_SetupBanks(this); + FULLSCREEN_SetupBanks(this); - this->hidden->bank[0] = buffer + 60; /* Start of sprite data */ - if (bpp == 8) this->hidden->bank[0] += 2048; /* 8bpp sprite have palette first */ + this->hidden->bank[0] = buffer + 60; /* Start of sprite data */ + if (bpp == 8) + this->hidden->bank[0] += 2048; /* 8bpp sprite have palette first */ - this->hidden->current_bank = 0; - this->screen->pixels = this->hidden->bank[0]; + this->hidden->current_bank = 0; + this->screen->pixels = this->hidden->bank[0]; - /* Copy back buffer to screen memory */ - SDL_memcpy(this->hidden->bank[1], this->hidden->bank[0], width * height * this->screen->format->BytesPerPixel); + /* Copy back buffer to screen memory */ + SDL_memcpy(this->hidden->bank[1], this->hidden->bank[0], + width * height * this->screen->format->BytesPerPixel); - FULLSCREEN_SetDeviceMode(this); - return 1; - } else - RISCOS_RestoreWimpMode(); + FULLSCREEN_SetDeviceMode(this); + return 1; + } else + RISCOS_RestoreWimpMode(); - return 0; + return 0; } + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/src/video/riscos/SDL_riscosevents.c b/src/video/riscos/SDL_riscosevents.c index 83bcd44c8..f3019e393 100644 --- a/src/video/riscos/SDL_riscosevents.c +++ b/src/video/riscos/SDL_riscosevents.c @@ -70,7 +70,7 @@ static SDLKey RO_keymap[SDLK_LAST]; static char RO_pressed[ROKEYBD_ARRAYSIZE]; -static SDL_keysym *TranslateKey(int intkey, SDL_keysym *keysym, int pressed); +static SDL_keysym *TranslateKey(int intkey, SDL_keysym * keysym, int pressed); void RISCOS_PollMouse(_THIS); void RISCOS_PollKeyboard(); @@ -85,133 +85,135 @@ extern void RISCOS_CheckTimer(); #endif -void FULLSCREEN_PumpEvents(_THIS) +void +FULLSCREEN_PumpEvents(_THIS) { /* Current implementation requires keyboard and mouse polling */ - RISCOS_PollKeyboard(); - RISCOS_PollMouse(this); + RISCOS_PollKeyboard(); + RISCOS_PollMouse(this); #if SDL_THREADS_DISABLED -// DRenderer_FillBuffers(); - if (SDL_timer_running) RISCOS_CheckTimer(); +// DRenderer_FillBuffers(); + if (SDL_timer_running) + RISCOS_CheckTimer(); #endif } -void RISCOS_InitOSKeymap(_THIS) +void +RISCOS_InitOSKeymap(_THIS) { - int i; - - /* Map the VK keysyms */ - for ( i=0; i