renamed all .h to .hpp
[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
30 static int funcSeek(struct SDL_RWops* context, int offset, int whence)
31 {
32     PHYSFS_file* file = (PHYSFS_file*) context->hidden.unknown.data1;
33     int res;
34     switch(whence) {
35         case SEEK_SET:
36             res = PHYSFS_seek(file, offset);
37             break;
38         case SEEK_CUR:
39             res = PHYSFS_seek(file, PHYSFS_tell(file) + offset);
40             break;
41         case SEEK_END:
42             res = PHYSFS_seek(file, PHYSFS_fileLength(file) + offset);
43             break;
44         default:
45             res = 0;
46             assert(false);
47             break;
48     }
49     if(res == 0) {
50         std::cerr << "Error seeking in file: " << PHYSFS_getLastError() << "\n";
51         return -1;
52     }
53
54     return (int) PHYSFS_tell(file);
55 }
56
57 static int funcRead(struct SDL_RWops* context, void* ptr, int size, int maxnum)
58 {
59     PHYSFS_file* file = (PHYSFS_file*) context->hidden.unknown.data1;
60
61     int res = PHYSFS_read(file, ptr, size, maxnum);
62     return res;
63 }
64
65 static int funcClose(struct SDL_RWops* context)
66 {
67     PHYSFS_file* file = (PHYSFS_file*) context->hidden.unknown.data1;
68     
69     PHYSFS_close(file);
70     delete context;
71
72     return 0;
73 }
74
75 SDL_RWops* get_physfs_SDLRWops(const std::string& filename)
76 {
77     PHYSFS_file* file = (PHYSFS_file*) PHYSFS_openRead(filename.c_str());
78     if(!file) {
79         std::stringstream msg;
80         msg << "Couldn't open '" << filename << "': "
81             << PHYSFS_getLastError();
82         throw std::runtime_error(msg.str());
83     }
84     
85     SDL_RWops* ops = new SDL_RWops();
86     ops->type = 0;
87     ops->hidden.unknown.data1 = file;
88     ops->seek = funcSeek;
89     ops->read = funcRead;
90     ops->write = 0;
91     ops->close = funcClose;
92     return ops;
93 }