fade out console
[supertux.git] / src / physfs / physfs_sdl.cpp
1 /*
2 Copyright (C) 2005 Matthias Braun <matze@braunis.de>
3
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2 of the License, or
7 (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
17 */
18 #include <config.h>
19
20 #include "physfs_sdl.hpp"
21
22 #include <physfs.h>
23
24 #include <stdexcept>
25 #include <sstream>
26 #include <iostream>
27
28 #include <assert.h>
29 #include "log.hpp"
30
31 static int funcSeek(struct SDL_RWops* context, int offset, int whence)
32 {
33     PHYSFS_file* file = (PHYSFS_file*) context->hidden.unknown.data1;
34     int res;
35     switch(whence) {
36         case SEEK_SET:
37             res = PHYSFS_seek(file, offset);
38             break;
39         case SEEK_CUR:
40             res = PHYSFS_seek(file, PHYSFS_tell(file) + offset);
41             break;
42         case SEEK_END:
43             res = PHYSFS_seek(file, PHYSFS_fileLength(file) + offset);
44             break;
45         default:
46             res = 0;
47             assert(false);
48             break;
49     }
50     if(res == 0) {
51         log_warning << "Error seeking in file: " << PHYSFS_getLastError() << std::endl;
52         return -1;
53     }
54
55     return (int) PHYSFS_tell(file);
56 }
57
58 static int funcRead(struct SDL_RWops* context, void* ptr, int size, int maxnum)
59 {
60     PHYSFS_file* file = (PHYSFS_file*) context->hidden.unknown.data1;
61
62     int res = PHYSFS_read(file, ptr, size, maxnum);
63     return res;
64 }
65
66 static int funcClose(struct SDL_RWops* context)
67 {
68     PHYSFS_file* file = (PHYSFS_file*) context->hidden.unknown.data1;
69     
70     PHYSFS_close(file);
71     delete context;
72
73     return 0;
74 }
75
76 SDL_RWops* get_physfs_SDLRWops(const std::string& filename)
77 {
78     PHYSFS_file* file = (PHYSFS_file*) PHYSFS_openRead(filename.c_str());
79     if(!file) {
80         std::stringstream msg;
81         msg << "Couldn't open '" << filename << "': "
82             << PHYSFS_getLastError();
83         throw std::runtime_error(msg.str());
84     }
85     
86     SDL_RWops* ops = new SDL_RWops();
87     ops->type = 0;
88     ops->hidden.unknown.data1 = file;
89     ops->seek = funcSeek;
90     ops->read = funcRead;
91     ops->write = 0;
92     ops->close = funcClose;
93     return ops;
94 }