diff options
author | Rémi Verschelde <rverschelde@gmail.com> | 2017-03-05 16:44:50 +0100 |
---|---|---|
committer | Rémi Verschelde <rverschelde@gmail.com> | 2017-03-05 16:44:50 +0100 |
commit | 5dbf1809c6e3e905b94b8764e99491e608122261 (patch) | |
tree | 5e5a5360db15d86d59ec8c6e4f7eb511388c5a9a /core/io | |
parent | 45438e9918d421b244bfd7776a30e67dc7f2d3e3 (diff) |
A Whole New World (clang-format edition)
I can show you the code
Pretty, with proper whitespace
Tell me, coder, now when did
You last write readable code?
I can open your eyes
Make you see your bad indent
Force you to respect the style
The core devs agreed upon
A whole new world
A new fantastic code format
A de facto standard
With some sugar
Enforced with clang-format
A whole new world
A dazzling style we all dreamed of
And when we read it through
It's crystal clear
That now we're in a whole new world of code
Diffstat (limited to 'core/io')
60 files changed, 3515 insertions, 4235 deletions
diff --git a/core/io/compression.cpp b/core/io/compression.cpp index 6fda7d52f3..25fd2ad2ee 100644 --- a/core/io/compression.cpp +++ b/core/io/compression.cpp @@ -26,25 +26,25 @@ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -#include "zlib.h" -#include "os/copymem.h" #include "compression.h" +#include "os/copymem.h" +#include "zlib.h" #include "fastlz.h" #include "zip_io.h" -int Compression::compress(uint8_t *p_dst, const uint8_t *p_src, int p_src_size,Mode p_mode) { +int Compression::compress(uint8_t *p_dst, const uint8_t *p_src, int p_src_size, Mode p_mode) { - switch(p_mode) { + switch (p_mode) { case MODE_FASTLZ: { - if (p_src_size<16) { + if (p_src_size < 16) { uint8_t src[16]; - zeromem(&src[p_src_size],16-p_src_size); - copymem(src,p_src,p_src_size); - return fastlz_compress(src,16,p_dst); + zeromem(&src[p_src_size], 16 - p_src_size); + copymem(src, p_src, p_src_size); + return fastlz_compress(src, 16, p_dst); } else { - return fastlz_compress(p_src,p_src_size,p_dst); + return fastlz_compress(p_src, p_src_size, p_dst); } } break; @@ -54,20 +54,20 @@ int Compression::compress(uint8_t *p_dst, const uint8_t *p_src, int p_src_size,M strm.zalloc = zipio_alloc; strm.zfree = zipio_free; strm.opaque = Z_NULL; - int err = deflateInit(&strm,Z_DEFAULT_COMPRESSION); - if (err!=Z_OK) - return -1; + int err = deflateInit(&strm, Z_DEFAULT_COMPRESSION); + if (err != Z_OK) + return -1; - strm.avail_in=p_src_size; - int aout = deflateBound(&strm,p_src_size); + strm.avail_in = p_src_size; + int aout = deflateBound(&strm, p_src_size); /*if (aout>p_src_size) { deflateEnd(&strm); return -1; }*/ - strm.avail_out=aout; - strm.next_in=(Bytef*)p_src; - strm.next_out=p_dst; - deflate(&strm,Z_FINISH); + strm.avail_out = aout; + strm.next_in = (Bytef *)p_src; + strm.next_out = p_dst; + deflate(&strm, Z_FINISH); aout = aout - strm.avail_out; deflateEnd(&strm); return aout; @@ -78,15 +78,14 @@ int Compression::compress(uint8_t *p_dst, const uint8_t *p_src, int p_src_size,M ERR_FAIL_V(-1); } -int Compression::get_max_compressed_buffer_size(int p_src_size,Mode p_mode){ +int Compression::get_max_compressed_buffer_size(int p_src_size, Mode p_mode) { - switch(p_mode) { + switch (p_mode) { case MODE_FASTLZ: { - - int ss = p_src_size+p_src_size*6/100; - if (ss<66) - ss=66; + int ss = p_src_size + p_src_size * 6 / 100; + if (ss < 66) + ss = 66; return ss; } break; @@ -96,34 +95,31 @@ int Compression::get_max_compressed_buffer_size(int p_src_size,Mode p_mode){ strm.zalloc = zipio_alloc; strm.zfree = zipio_free; strm.opaque = Z_NULL; - int err = deflateInit(&strm,Z_DEFAULT_COMPRESSION); - if (err!=Z_OK) - return -1; - int aout = deflateBound(&strm,p_src_size); + int err = deflateInit(&strm, Z_DEFAULT_COMPRESSION); + if (err != Z_OK) + return -1; + int aout = deflateBound(&strm, p_src_size); deflateEnd(&strm); return aout; } break; } ERR_FAIL_V(-1); - } +int Compression::decompress(uint8_t *p_dst, int p_dst_max_size, const uint8_t *p_src, int p_src_size, Mode p_mode) { - -int Compression::decompress(uint8_t *p_dst, int p_dst_max_size, const uint8_t *p_src, int p_src_size,Mode p_mode){ - - switch(p_mode) { + switch (p_mode) { case MODE_FASTLZ: { - int ret_size=0; + int ret_size = 0; - if (p_dst_max_size<16) { + if (p_dst_max_size < 16) { uint8_t dst[16]; - ret_size = fastlz_decompress(p_src,p_src_size,dst,16); - copymem(p_dst,dst,p_dst_max_size); + ret_size = fastlz_decompress(p_src, p_src_size, dst, 16); + copymem(p_dst, dst, p_dst_max_size); } else { - ret_size = fastlz_decompress(p_src,p_src_size,p_dst,p_dst_max_size); + ret_size = fastlz_decompress(p_src, p_src_size, p_dst, p_dst_max_size); } return ret_size; } break; @@ -133,20 +129,20 @@ int Compression::decompress(uint8_t *p_dst, int p_dst_max_size, const uint8_t *p strm.zalloc = zipio_alloc; strm.zfree = zipio_free; strm.opaque = Z_NULL; - strm.avail_in= 0; - strm.next_in=Z_NULL; + strm.avail_in = 0; + strm.next_in = Z_NULL; int err = inflateInit(&strm); - ERR_FAIL_COND_V(err!=Z_OK,-1); + ERR_FAIL_COND_V(err != Z_OK, -1); - strm.avail_in=p_src_size; - strm.avail_out=p_dst_max_size; - strm.next_in=(Bytef*)p_src; - strm.next_out=p_dst; + strm.avail_in = p_src_size; + strm.avail_out = p_dst_max_size; + strm.next_in = (Bytef *)p_src; + strm.next_out = p_dst; - err = inflate(&strm,Z_FINISH); + err = inflate(&strm, Z_FINISH); int total = strm.total_out; inflateEnd(&strm); - ERR_FAIL_COND_V(err!=Z_STREAM_END,-1); + ERR_FAIL_COND_V(err != Z_STREAM_END, -1); return total; } break; } diff --git a/core/io/compression.h b/core/io/compression.h index fc00d02dda..5156919867 100644 --- a/core/io/compression.h +++ b/core/io/compression.h @@ -31,23 +31,18 @@ #include "typedefs.h" -class Compression -{ +class Compression { public: - enum Mode { MODE_FASTLZ, MODE_DEFLATE }; - - static int compress(uint8_t *p_dst, const uint8_t *p_src, int p_src_size,Mode p_mode=MODE_FASTLZ); - static int get_max_compressed_buffer_size(int p_src_size,Mode p_mode=MODE_FASTLZ); - static int decompress(uint8_t *p_dst, int p_dst_max_size, const uint8_t *p_src, int p_src_size,Mode p_mode=MODE_FASTLZ); + static int compress(uint8_t *p_dst, const uint8_t *p_src, int p_src_size, Mode p_mode = MODE_FASTLZ); + static int get_max_compressed_buffer_size(int p_src_size, Mode p_mode = MODE_FASTLZ); + static int decompress(uint8_t *p_dst, int p_dst_max_size, const uint8_t *p_src, int p_src_size, Mode p_mode = MODE_FASTLZ); Compression(); }; - - #endif // COMPRESSION_H diff --git a/core/io/config_file.cpp b/core/io/config_file.cpp index fdfcc3ae3a..052a83168d 100644 --- a/core/io/config_file.cpp +++ b/core/io/config_file.cpp @@ -27,8 +27,8 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "config_file.h" -#include "os/keyboard.h" #include "os/file_access.h" +#include "os/keyboard.h" #include "variant_parser.h" PoolStringArray ConfigFile::_get_sections() const { @@ -37,35 +37,33 @@ PoolStringArray ConfigFile::_get_sections() const { get_sections(&s); PoolStringArray arr; arr.resize(s.size()); - int idx=0; - for(const List<String>::Element *E=s.front();E;E=E->next()) { + int idx = 0; + for (const List<String>::Element *E = s.front(); E; E = E->next()) { - arr.set(idx++,E->get()); + arr.set(idx++, E->get()); } return arr; } -PoolStringArray ConfigFile::_get_section_keys(const String& p_section) const{ +PoolStringArray ConfigFile::_get_section_keys(const String &p_section) const { List<String> s; - get_section_keys(p_section,&s); + get_section_keys(p_section, &s); PoolStringArray arr; arr.resize(s.size()); - int idx=0; - for(const List<String>::Element *E=s.front();E;E=E->next()) { + int idx = 0; + for (const List<String>::Element *E = s.front(); E; E = E->next()) { - arr.set(idx++,E->get()); + arr.set(idx++, E->get()); } return arr; - } +void ConfigFile::set_value(const String &p_section, const String &p_key, const Variant &p_value) { -void ConfigFile::set_value(const String& p_section, const String& p_key, const Variant& p_value){ - - if (p_value.get_type()==Variant::NIL) { + if (p_value.get_type() == Variant::NIL) { //erase if (!values.has(p_section)) return; // ? @@ -76,58 +74,54 @@ void ConfigFile::set_value(const String& p_section, const String& p_key, const V } else { if (!values.has(p_section)) { - values[p_section]=Map<String, Variant>(); + values[p_section] = Map<String, Variant>(); } - values[p_section][p_key]=p_value; - + values[p_section][p_key] = p_value; } - } -Variant ConfigFile::get_value(const String& p_section, const String& p_key, Variant p_default) const { +Variant ConfigFile::get_value(const String &p_section, const String &p_key, Variant p_default) const { - ERR_FAIL_COND_V(!values.has(p_section),p_default); - ERR_FAIL_COND_V(!values[p_section].has(p_key),p_default); + ERR_FAIL_COND_V(!values.has(p_section), p_default); + ERR_FAIL_COND_V(!values[p_section].has(p_key), p_default); return values[p_section][p_key]; - } -bool ConfigFile::has_section(const String& p_section) const { +bool ConfigFile::has_section(const String &p_section) const { return values.has(p_section); } -bool ConfigFile::has_section_key(const String& p_section,const String& p_key) const { +bool ConfigFile::has_section_key(const String &p_section, const String &p_key) const { if (!values.has(p_section)) return false; return values[p_section].has(p_key); } -void ConfigFile::get_sections(List<String> *r_sections) const{ +void ConfigFile::get_sections(List<String> *r_sections) const { - for(const Map< String, Map<String, Variant> >::Element *E=values.front();E;E=E->next()) { + for (const Map<String, Map<String, Variant> >::Element *E = values.front(); E; E = E->next()) { r_sections->push_back(E->key()); } } -void ConfigFile::get_section_keys(const String& p_section,List<String> *r_keys) const{ +void ConfigFile::get_section_keys(const String &p_section, List<String> *r_keys) const { ERR_FAIL_COND(!values.has(p_section)); - for(const Map<String, Variant> ::Element *E=values[p_section].front();E;E=E->next()) { + for (const Map<String, Variant>::Element *E = values[p_section].front(); E; E = E->next()) { r_keys->push_back(E->key()); } - } -void ConfigFile::erase_section(const String& p_section) { +void ConfigFile::erase_section(const String &p_section) { values.erase(p_section); } -Error ConfigFile::save(const String& p_path){ +Error ConfigFile::save(const String &p_path) { Error err; - FileAccess *file = FileAccess::open(p_path,FileAccess::WRITE,&err); + FileAccess *file = FileAccess::open(p_path, FileAccess::WRITE, &err); if (err) { if (file) @@ -135,18 +129,17 @@ Error ConfigFile::save(const String& p_path){ return err; } + for (Map<String, Map<String, Variant> >::Element *E = values.front(); E; E = E->next()) { - for(Map< String, Map<String, Variant> >::Element *E=values.front();E;E=E->next()) { - - if (E!=values.front()) + if (E != values.front()) file->store_string("\n"); - file->store_string("["+E->key()+"]\n\n"); + file->store_string("[" + E->key() + "]\n\n"); - for(Map<String, Variant>::Element *F=E->get().front();F;F=F->next()) { + for (Map<String, Variant>::Element *F = E->get().front(); F; F = F->next()) { String vstr; - VariantWriter::write_to_string(F->get(),vstr); - file->store_string(F->key()+"="+vstr+"\n"); + VariantWriter::write_to_string(F->get(), vstr); + file->store_string(F->key() + "=" + vstr + "\n"); } } @@ -155,48 +148,46 @@ Error ConfigFile::save(const String& p_path){ return OK; } - -Error ConfigFile::load(const String& p_path) { +Error ConfigFile::load(const String &p_path) { Error err; - FileAccess *f= FileAccess::open(p_path,FileAccess::READ,&err); + FileAccess *f = FileAccess::open(p_path, FileAccess::READ, &err); if (!f) return ERR_CANT_OPEN; VariantParser::StreamFile stream; - stream.f=f; + stream.f = f; String assign; Variant value; VariantParser::Tag next_tag; - int lines=0; + int lines = 0; String error_text; String section; - while(true) { + while (true) { - assign=Variant(); + assign = Variant(); next_tag.fields.clear(); - next_tag.name=String(); + next_tag.name = String(); - err = VariantParser::parse_tag_assign_eof(&stream,lines,error_text,next_tag,assign,value,NULL,true); - if (err==ERR_FILE_EOF) { + err = VariantParser::parse_tag_assign_eof(&stream, lines, error_text, next_tag, assign, value, NULL, true); + if (err == ERR_FILE_EOF) { memdelete(f); return OK; - } - else if (err!=OK) { - ERR_PRINTS("ConfgFile::load - "+p_path+":"+itos(lines)+" error: "+error_text); + } else if (err != OK) { + ERR_PRINTS("ConfgFile::load - " + p_path + ":" + itos(lines) + " error: " + error_text); memdelete(f); return err; } - if (assign!=String()) { - set_value(section,assign,value); - } else if (next_tag.name!=String()) { - section=next_tag.name; + if (assign != String()) { + set_value(section, assign, value); + } else if (next_tag.name != String()) { + section = next_tag.name; } } @@ -205,27 +196,22 @@ Error ConfigFile::load(const String& p_path) { return OK; } +void ConfigFile::_bind_methods() { + ClassDB::bind_method(D_METHOD("set_value", "section", "key", "value"), &ConfigFile::set_value); + ClassDB::bind_method(D_METHOD("get_value:Variant", "section", "key", "default"), &ConfigFile::get_value, DEFVAL(Variant())); -void ConfigFile::_bind_methods(){ - - ClassDB::bind_method(D_METHOD("set_value","section","key","value"),&ConfigFile::set_value); - ClassDB::bind_method(D_METHOD("get_value:Variant","section","key","default"),&ConfigFile::get_value,DEFVAL(Variant())); + ClassDB::bind_method(D_METHOD("has_section", "section"), &ConfigFile::has_section); + ClassDB::bind_method(D_METHOD("has_section_key", "section", "key"), &ConfigFile::has_section_key); - ClassDB::bind_method(D_METHOD("has_section","section"),&ConfigFile::has_section); - ClassDB::bind_method(D_METHOD("has_section_key","section","key"),&ConfigFile::has_section_key); + ClassDB::bind_method(D_METHOD("get_sections"), &ConfigFile::_get_sections); + ClassDB::bind_method(D_METHOD("get_section_keys", "section"), &ConfigFile::_get_section_keys); - ClassDB::bind_method(D_METHOD("get_sections"),&ConfigFile::_get_sections); - ClassDB::bind_method(D_METHOD("get_section_keys","section"),&ConfigFile::_get_section_keys); - - ClassDB::bind_method(D_METHOD("erase_section","section"),&ConfigFile::erase_section); - - ClassDB::bind_method(D_METHOD("load:Error","path"),&ConfigFile::load); - ClassDB::bind_method(D_METHOD("save:Error","path"),&ConfigFile::save); + ClassDB::bind_method(D_METHOD("erase_section", "section"), &ConfigFile::erase_section); + ClassDB::bind_method(D_METHOD("load:Error", "path"), &ConfigFile::load); + ClassDB::bind_method(D_METHOD("save:Error", "path"), &ConfigFile::save); } - -ConfigFile::ConfigFile() -{ +ConfigFile::ConfigFile() { } diff --git a/core/io/config_file.h b/core/io/config_file.h index c9c4a9fbc0..4d179bd137 100644 --- a/core/io/config_file.h +++ b/core/io/config_file.h @@ -31,33 +31,32 @@ #include "reference.h" - class ConfigFile : public Reference { - GDCLASS(ConfigFile,Reference); + GDCLASS(ConfigFile, Reference); - Map< String, Map<String, Variant> > values; + Map<String, Map<String, Variant> > values; PoolStringArray _get_sections() const; - PoolStringArray _get_section_keys(const String& p_section) const; -protected: + PoolStringArray _get_section_keys(const String &p_section) const; +protected: static void _bind_methods(); -public: - void set_value(const String& p_section, const String& p_key, const Variant& p_value); - Variant get_value(const String& p_section, const String& p_key, Variant p_default=Variant()) const; +public: + void set_value(const String &p_section, const String &p_key, const Variant &p_value); + Variant get_value(const String &p_section, const String &p_key, Variant p_default = Variant()) const; - bool has_section(const String& p_section) const; - bool has_section_key(const String& p_section,const String& p_key) const; + bool has_section(const String &p_section) const; + bool has_section_key(const String &p_section, const String &p_key) const; void get_sections(List<String> *r_sections) const; - void get_section_keys(const String& p_section,List<String> *r_keys) const; + void get_section_keys(const String &p_section, List<String> *r_keys) const; - void erase_section(const String& p_section); + void erase_section(const String &p_section); - Error save(const String& p_path); - Error load(const String& p_path); + Error save(const String &p_path); + Error load(const String &p_path); ConfigFile(); }; diff --git a/core/io/file_access_buffered.cpp b/core/io/file_access_buffered.cpp index 71518de38b..dd4d3e6e8f 100644 --- a/core/io/file_access_buffered.cpp +++ b/core/io/file_access_buffered.cpp @@ -92,7 +92,7 @@ bool FileAccessBuffered::eof_reached() const { uint8_t FileAccessBuffered::get_8() const { - ERR_FAIL_COND_V(!file.open,0); + ERR_FAIL_COND_V(!file.open, 0); uint8_t byte = 0; if (cache_data_left() >= 1) { @@ -105,7 +105,7 @@ uint8_t FileAccessBuffered::get_8() const { return byte; }; -int FileAccessBuffered::get_buffer(uint8_t *p_dest,int p_elements) const { +int FileAccessBuffered::get_buffer(uint8_t *p_dest, int p_elements) const { ERR_FAIL_COND_V(!file.open, -1); @@ -135,7 +135,6 @@ int FileAccessBuffered::get_buffer(uint8_t *p_dest,int p_elements) const { return total_read; }; - int to_read = p_elements; int total_read = 0; while (to_read > 0) { @@ -154,7 +153,7 @@ int FileAccessBuffered::get_buffer(uint8_t *p_dest,int p_elements) const { int r = MIN(left, to_read); //PoolVector<uint8_t>::Read read = cache.buffer.read(); //memcpy(p_dest+total_read, &read.ptr()[file.offset - cache.offset], r); - memcpy(p_dest+total_read, cache.buffer.ptr() + (file.offset - cache.offset), r); + memcpy(p_dest + total_read, cache.buffer.ptr() + (file.offset - cache.offset), r); file.offset += r; total_read += r; @@ -179,6 +178,5 @@ FileAccessBuffered::FileAccessBuffered() { cache_size = DEFAULT_CACHE_SIZE; }; -FileAccessBuffered::~FileAccessBuffered(){ - +FileAccessBuffered::~FileAccessBuffered() { } diff --git a/core/io/file_access_buffered.h b/core/io/file_access_buffered.h index be8ea714b1..964152af5e 100644 --- a/core/io/file_access_buffered.h +++ b/core/io/file_access_buffered.h @@ -42,14 +42,12 @@ public: }; private: - int cache_size; int cache_data_left() const; mutable Error last_error; protected: - Error set_error(Error p_error) const; mutable struct File { @@ -67,23 +65,22 @@ protected: int offset; } cache; - virtual int read_data_block(int p_offset, int p_size, uint8_t *p_dest = 0) const =0; + virtual int read_data_block(int p_offset, int p_size, uint8_t *p_dest = 0) const = 0; void set_cache_size(int p_size); int get_cache_size(); public: - virtual size_t get_pos() const; ///< get position in the file virtual size_t get_len() const; ///< get size of the file virtual void seek(size_t p_position); ///< seek to a given position - virtual void seek_end(int64_t p_position=0); ///< seek from the end of file + virtual void seek_end(int64_t p_position = 0); ///< seek from the end of file virtual bool eof_reached() const; virtual uint8_t get_8() const; - virtual int get_buffer(uint8_t *p_dst,int p_length) const; ///< get an array of bytes + virtual int get_buffer(uint8_t *p_dst, int p_length) const; ///< get an array of bytes virtual bool is_open() const; @@ -94,4 +91,3 @@ public: }; #endif - diff --git a/core/io/file_access_buffered_fa.h b/core/io/file_access_buffered_fa.h index 000c2b45f3..dd1e99f8f6 100644 --- a/core/io/file_access_buffered_fa.h +++ b/core/io/file_access_buffered_fa.h @@ -31,16 +31,16 @@ #include "core/io/file_access_buffered.h" -template<class T> +template <class T> class FileAccessBufferedFA : public FileAccessBuffered { T f; int read_data_block(int p_offset, int p_size, uint8_t *p_dest = 0) const { - ERR_FAIL_COND_V( !f.is_open(), -1 ); + ERR_FAIL_COND_V(!f.is_open(), -1); - ((T*)&f)->seek(p_offset); + ((T *)&f)->seek(p_offset); if (p_dest) { @@ -63,9 +63,9 @@ class FileAccessBufferedFA : public FileAccessBuffered { }; }; - static FileAccess* create() { + static FileAccess *create() { - return memnew( FileAccessBufferedFA<T>() ); + return memnew(FileAccessBufferedFA<T>()); }; protected: @@ -75,29 +75,27 @@ protected: }; public: - - void store_8(uint8_t p_dest) { f.store_8(p_dest); }; - void store_buffer(const uint8_t *p_src,int p_length) { + void store_buffer(const uint8_t *p_src, int p_length) { f.store_buffer(p_src, p_length); }; - bool file_exists(const String& p_name) { + bool file_exists(const String &p_name) { return f.file_exists(p_name); }; - Error _open(const String& p_path, int p_mode_flags) { + Error _open(const String &p_path, int p_mode_flags) { close(); Error ret = f._open(p_path, p_mode_flags); - if (ret !=OK) + if (ret != OK) return ret; //ERR_FAIL_COND_V( ret != OK, ret ); @@ -133,16 +131,14 @@ public: }; */ - virtual uint64_t _get_modified_time(const String& p_file) { + virtual uint64_t _get_modified_time(const String &p_file) { return f._get_modified_time(p_file); } - FileAccessBufferedFA() { - + FileAccessBufferedFA(){ }; }; - #endif // FILE_ACCESS_BUFFERED_FA_H diff --git a/core/io/file_access_compressed.cpp b/core/io/file_access_compressed.cpp index 3bcfade526..d8ae3e6ff1 100644 --- a/core/io/file_access_compressed.cpp +++ b/core/io/file_access_compressed.cpp @@ -28,244 +28,223 @@ /*************************************************************************/ #include "file_access_compressed.h" #include "print_string.h" -void FileAccessCompressed::configure(const String& p_magic, Compression::Mode p_mode, int p_block_size) { +void FileAccessCompressed::configure(const String &p_magic, Compression::Mode p_mode, int p_block_size) { - magic=p_magic.ascii().get_data(); - if (magic.length()>4) - magic=magic.substr(0,4); + magic = p_magic.ascii().get_data(); + if (magic.length() > 4) + magic = magic.substr(0, 4); else { - while(magic.length()<4) - magic+=" "; + while (magic.length() < 4) + magic += " "; } - cmode=p_mode; - block_size=p_block_size; - -} - - -#define WRITE_FIT(m_bytes) \ -{\ -if (write_pos+(m_bytes) > write_max) {\ - write_max=write_pos+(m_bytes);\ -}\ -if (write_max > write_buffer_size) {\ - write_buffer_size = nearest_power_of_2( write_max );\ - buffer.resize(write_buffer_size);\ - write_ptr=buffer.ptr();\ -}\ + cmode = p_mode; + block_size = p_block_size; } +#define WRITE_FIT(m_bytes) \ + { \ + if (write_pos + (m_bytes) > write_max) { \ + write_max = write_pos + (m_bytes); \ + } \ + if (write_max > write_buffer_size) { \ + write_buffer_size = nearest_power_of_2(write_max); \ + buffer.resize(write_buffer_size); \ + write_ptr = buffer.ptr(); \ + } \ + } Error FileAccessCompressed::open_after_magic(FileAccess *p_base) { - - f=p_base; - cmode=(Compression::Mode)f->get_32(); - block_size=f->get_32(); - read_total=f->get_32(); - int bc = (read_total/block_size)+1; - int acc_ofs=f->get_pos()+bc*4; - int max_bs=0; - for(int i=0;i<bc;i++) { + f = p_base; + cmode = (Compression::Mode)f->get_32(); + block_size = f->get_32(); + read_total = f->get_32(); + int bc = (read_total / block_size) + 1; + int acc_ofs = f->get_pos() + bc * 4; + int max_bs = 0; + for (int i = 0; i < bc; i++) { ReadBlock rb; - rb.offset=acc_ofs; - rb.csize=f->get_32(); - acc_ofs+=rb.csize; - max_bs=MAX(max_bs,rb.csize); + rb.offset = acc_ofs; + rb.csize = f->get_32(); + acc_ofs += rb.csize; + max_bs = MAX(max_bs, rb.csize); read_blocks.push_back(rb); - - } comp_buffer.resize(max_bs); buffer.resize(block_size); - read_ptr=buffer.ptr(); - f->get_buffer(comp_buffer.ptr(),read_blocks[0].csize); - at_end=false; - read_eof=false; - read_block_count=bc; - read_block_size=read_blocks.size()==1?read_total:block_size; + read_ptr = buffer.ptr(); + f->get_buffer(comp_buffer.ptr(), read_blocks[0].csize); + at_end = false; + read_eof = false; + read_block_count = bc; + read_block_size = read_blocks.size() == 1 ? read_total : block_size; - Compression::decompress(buffer.ptr(),read_block_size,comp_buffer.ptr(),read_blocks[0].csize,cmode); - read_block=0; - read_pos=0; + Compression::decompress(buffer.ptr(), read_block_size, comp_buffer.ptr(), read_blocks[0].csize, cmode); + read_block = 0; + read_pos = 0; return OK; - } -Error FileAccessCompressed::_open(const String& p_path, int p_mode_flags){ +Error FileAccessCompressed::_open(const String &p_path, int p_mode_flags) { - ERR_FAIL_COND_V(p_mode_flags==READ_WRITE,ERR_UNAVAILABLE); + ERR_FAIL_COND_V(p_mode_flags == READ_WRITE, ERR_UNAVAILABLE); if (f) close(); - Error err; - f = FileAccess::open(p_path,p_mode_flags,&err); - if (err!=OK) { + f = FileAccess::open(p_path, p_mode_flags, &err); + if (err != OK) { //not openable - f=NULL; + f = NULL; return err; } - if (p_mode_flags&WRITE) { + if (p_mode_flags & WRITE) { buffer.clear(); - writing=true; - write_pos=0; - write_buffer_size=256; + writing = true; + write_pos = 0; + write_buffer_size = 256; buffer.resize(256); - write_max=0; - write_ptr=buffer.ptr(); - - + write_max = 0; + write_ptr = buffer.ptr(); //don't store anything else unless it's done saving! } else { char rmagic[5]; - f->get_buffer((uint8_t*)rmagic,4); - rmagic[4]=0; - if (magic!=rmagic) { + f->get_buffer((uint8_t *)rmagic, 4); + rmagic[4] = 0; + if (magic != rmagic) { memdelete(f); - f=NULL; + f = NULL; return ERR_FILE_UNRECOGNIZED; } open_after_magic(f); - } return OK; - } -void FileAccessCompressed::close(){ +void FileAccessCompressed::close() { if (!f) return; - if (writing) { //save block table and all compressed blocks CharString mgc = magic.utf8(); - f->store_buffer((const uint8_t*)mgc.get_data(),mgc.length()); //write header 4 + f->store_buffer((const uint8_t *)mgc.get_data(), mgc.length()); //write header 4 f->store_32(cmode); //write compression mode 4 f->store_32(block_size); //write block size 4 f->store_32(write_max); //max amount of data written 4 - int bc=(write_max/block_size)+1; + int bc = (write_max / block_size) + 1; - for(int i=0;i<bc;i++) { + for (int i = 0; i < bc; i++) { f->store_32(0); //compressed sizes, will update later } - Vector<int> block_sizes; - for(int i=0;i<bc;i++) { + for (int i = 0; i < bc; i++) { - int bl = i==(bc-1) ? write_max % block_size : block_size; - uint8_t *bp = &write_ptr[i*block_size]; + int bl = i == (bc - 1) ? write_max % block_size : block_size; + uint8_t *bp = &write_ptr[i * block_size]; Vector<uint8_t> cblock; - cblock.resize(Compression::get_max_compressed_buffer_size(bl,cmode)); - int s = Compression::compress(cblock.ptr(),bp,bl,cmode); + cblock.resize(Compression::get_max_compressed_buffer_size(bl, cmode)); + int s = Compression::compress(cblock.ptr(), bp, bl, cmode); - f->store_buffer(cblock.ptr(),s); + f->store_buffer(cblock.ptr(), s); block_sizes.push_back(s); } f->seek(16); //ok write block sizes - for(int i=0;i<bc;i++) + for (int i = 0; i < bc; i++) f->store_32(block_sizes[i]); f->seek_end(); - f->store_buffer((const uint8_t*)mgc.get_data(),mgc.length()); //magic at the end too + f->store_buffer((const uint8_t *)mgc.get_data(), mgc.length()); //magic at the end too buffer.clear(); } else { - comp_buffer.clear(); buffer.clear(); read_blocks.clear(); } memdelete(f); - f=NULL; - + f = NULL; } -bool FileAccessCompressed::is_open() const{ +bool FileAccessCompressed::is_open() const { - return f!=NULL; + return f != NULL; } -void FileAccessCompressed::seek(size_t p_position){ +void FileAccessCompressed::seek(size_t p_position) { ERR_FAIL_COND(!f); if (writing) { - ERR_FAIL_COND(p_position>write_max); + ERR_FAIL_COND(p_position > write_max); - write_pos=p_position; + write_pos = p_position; } else { - ERR_FAIL_COND(p_position>read_total); - if (p_position==read_total) { - at_end=true; + ERR_FAIL_COND(p_position > read_total); + if (p_position == read_total) { + at_end = true; } else { - int block_idx = p_position/block_size; - if (block_idx!=read_block) { + int block_idx = p_position / block_size; + if (block_idx != read_block) { - read_block=block_idx; + read_block = block_idx; f->seek(read_blocks[read_block].offset); - f->get_buffer(comp_buffer.ptr(),read_blocks[read_block].csize); - Compression::decompress(buffer.ptr(),read_blocks.size()==1?read_total:block_size,comp_buffer.ptr(),read_blocks[read_block].csize,cmode); - read_block_size=read_block==read_block_count-1?read_total%block_size:block_size; + f->get_buffer(comp_buffer.ptr(), read_blocks[read_block].csize); + Compression::decompress(buffer.ptr(), read_blocks.size() == 1 ? read_total : block_size, comp_buffer.ptr(), read_blocks[read_block].csize, cmode); + read_block_size = read_block == read_block_count - 1 ? read_total % block_size : block_size; } - read_pos=p_position%block_size; + read_pos = p_position % block_size; } } } - -void FileAccessCompressed::seek_end(int64_t p_position){ +void FileAccessCompressed::seek_end(int64_t p_position) { ERR_FAIL_COND(!f); if (writing) { - seek(write_max+p_position); + seek(write_max + p_position); } else { - seek(read_total+p_position); - + seek(read_total + p_position); } - - } -size_t FileAccessCompressed::get_pos() const{ +size_t FileAccessCompressed::get_pos() const { - ERR_FAIL_COND_V(!f,0); + ERR_FAIL_COND_V(!f, 0); if (writing) { return write_pos; } else { - return read_block*block_size+read_pos; + return read_block * block_size + read_pos; } - } -size_t FileAccessCompressed::get_len() const{ +size_t FileAccessCompressed::get_len() const { - ERR_FAIL_COND_V(!f,0); + ERR_FAIL_COND_V(!f, 0); if (writing) { return write_max; @@ -274,9 +253,9 @@ size_t FileAccessCompressed::get_len() const{ } } -bool FileAccessCompressed::eof_reached() const{ +bool FileAccessCompressed::eof_reached() const { - ERR_FAIL_COND_V(!f,false); + ERR_FAIL_COND_V(!f, false); if (writing) { return false; } else { @@ -284,106 +263,99 @@ bool FileAccessCompressed::eof_reached() const{ } } -uint8_t FileAccessCompressed::get_8() const{ +uint8_t FileAccessCompressed::get_8() const { - ERR_FAIL_COND_V(writing,0); - ERR_FAIL_COND_V(!f,0); + ERR_FAIL_COND_V(writing, 0); + ERR_FAIL_COND_V(!f, 0); if (at_end) { - read_eof=true; + read_eof = true; return 0; } uint8_t ret = read_ptr[read_pos]; read_pos++; - if (read_pos>=read_block_size) { + if (read_pos >= read_block_size) { read_block++; - if (read_block<read_block_count) { + if (read_block < read_block_count) { //read another block of compressed data - f->get_buffer(comp_buffer.ptr(),read_blocks[read_block].csize); - Compression::decompress(buffer.ptr(),read_blocks.size()==1?read_total:block_size,comp_buffer.ptr(),read_blocks[read_block].csize,cmode); - read_block_size=read_block==read_block_count-1?read_total%block_size:block_size; - read_pos=0; + f->get_buffer(comp_buffer.ptr(), read_blocks[read_block].csize); + Compression::decompress(buffer.ptr(), read_blocks.size() == 1 ? read_total : block_size, comp_buffer.ptr(), read_blocks[read_block].csize, cmode); + read_block_size = read_block == read_block_count - 1 ? read_total % block_size : block_size; + read_pos = 0; } else { read_block--; - at_end=true; - ret =0; + at_end = true; + ret = 0; } } return ret; - } -int FileAccessCompressed::get_buffer(uint8_t *p_dst, int p_length) const{ +int FileAccessCompressed::get_buffer(uint8_t *p_dst, int p_length) const { - ERR_FAIL_COND_V(writing,0); - ERR_FAIL_COND_V(!f,0); + ERR_FAIL_COND_V(writing, 0); + ERR_FAIL_COND_V(!f, 0); if (at_end) { - read_eof=true; + read_eof = true; return 0; } + for (int i = 0; i < p_length; i++) { - for(int i=0;i<p_length;i++) { - - - p_dst[i]=read_ptr[read_pos]; + p_dst[i] = read_ptr[read_pos]; read_pos++; - if (read_pos>=read_block_size) { + if (read_pos >= read_block_size) { read_block++; - if (read_block<read_block_count) { + if (read_block < read_block_count) { //read another block of compressed data - f->get_buffer(comp_buffer.ptr(),read_blocks[read_block].csize); - Compression::decompress(buffer.ptr(),read_blocks.size()==1?read_total:block_size,comp_buffer.ptr(),read_blocks[read_block].csize,cmode); - read_block_size=read_block==read_block_count-1?read_total%block_size:block_size; - read_pos=0; + f->get_buffer(comp_buffer.ptr(), read_blocks[read_block].csize); + Compression::decompress(buffer.ptr(), read_blocks.size() == 1 ? read_total : block_size, comp_buffer.ptr(), read_blocks[read_block].csize, cmode); + read_block_size = read_block == read_block_count - 1 ? read_total % block_size : block_size; + read_pos = 0; } else { read_block--; - at_end=true; - if (i<p_length-1) - read_eof=true; + at_end = true; + if (i < p_length - 1) + read_eof = true; return i; - } } - } return p_length; - } -Error FileAccessCompressed::get_error() const{ +Error FileAccessCompressed::get_error() const { - return read_eof?ERR_FILE_EOF:OK; + return read_eof ? ERR_FILE_EOF : OK; } -void FileAccessCompressed::store_8(uint8_t p_dest){ +void FileAccessCompressed::store_8(uint8_t p_dest) { ERR_FAIL_COND(!f); ERR_FAIL_COND(!writing); WRITE_FIT(1); - write_ptr[write_pos++]=p_dest; - + write_ptr[write_pos++] = p_dest; } -bool FileAccessCompressed::file_exists(const String& p_name){ +bool FileAccessCompressed::file_exists(const String &p_name) { - FileAccess *fa = FileAccess::open(p_name,FileAccess::READ); + FileAccess *fa = FileAccess::open(p_name, FileAccess::READ); if (!fa) return false; memdelete(fa); return true; } -uint64_t FileAccessCompressed::_get_modified_time(const String& p_file) { +uint64_t FileAccessCompressed::_get_modified_time(const String &p_file) { if (f) return f->get_modified_time(p_file); @@ -393,29 +365,27 @@ uint64_t FileAccessCompressed::_get_modified_time(const String& p_file) { FileAccessCompressed::FileAccessCompressed() { - f=NULL; - magic="GCMP"; - block_size=16384; - cmode=Compression::MODE_DEFLATE; - writing=false; - write_ptr=0; - write_buffer_size=0; - write_max=0; - block_size=0; - read_eof=false; - at_end=false; - read_total=0; - read_ptr=NULL; - read_block=0; - read_block_count=0; - read_block_size=0; - read_pos=0; - + f = NULL; + magic = "GCMP"; + block_size = 16384; + cmode = Compression::MODE_DEFLATE; + writing = false; + write_ptr = 0; + write_buffer_size = 0; + write_max = 0; + block_size = 0; + read_eof = false; + at_end = false; + read_total = 0; + read_ptr = NULL; + read_block = 0; + read_block_count = 0; + read_block_size = 0; + read_pos = 0; } -FileAccessCompressed::~FileAccessCompressed(){ +FileAccessCompressed::~FileAccessCompressed() { if (f) close(); - } diff --git a/core/io/file_access_compressed.h b/core/io/file_access_compressed.h index 70034120f9..ea45c110d2 100644 --- a/core/io/file_access_compressed.h +++ b/core/io/file_access_compressed.h @@ -37,7 +37,7 @@ class FileAccessCompressed : public FileAccess { Compression::Mode cmode; bool writing; int write_pos; - uint8_t*write_ptr; + uint8_t *write_ptr; int write_buffer_size; int write_max; int block_size; @@ -58,24 +58,21 @@ class FileAccessCompressed : public FileAccess { Vector<ReadBlock> read_blocks; int read_total; - - - String magic; mutable Vector<uint8_t> buffer; FileAccess *f; -public: - void configure(const String& p_magic, Compression::Mode p_mode=Compression::MODE_FASTLZ, int p_block_size=4096); +public: + void configure(const String &p_magic, Compression::Mode p_mode = Compression::MODE_FASTLZ, int p_block_size = 4096); Error open_after_magic(FileAccess *p_base); - virtual Error _open(const String& p_path, int p_mode_flags); ///< open a file + virtual Error _open(const String &p_path, int p_mode_flags); ///< open a file virtual void close(); ///< close a file virtual bool is_open() const; ///< true when file is open virtual void seek(size_t p_position); ///< seek to a given position - virtual void seek_end(int64_t p_position=0); ///< seek from the end of file + virtual void seek_end(int64_t p_position = 0); ///< seek from the end of file virtual size_t get_pos() const; ///< get position in the file virtual size_t get_len() const; ///< get size of the file @@ -88,14 +85,12 @@ public: virtual void store_8(uint8_t p_dest); ///< store a byte - virtual bool file_exists(const String& p_name); ///< return true if a file exists - - virtual uint64_t _get_modified_time(const String& p_file); + virtual bool file_exists(const String &p_name); ///< return true if a file exists + virtual uint64_t _get_modified_time(const String &p_file); FileAccessCompressed(); virtual ~FileAccessCompressed(); - }; #endif // FILE_ACCESS_COMPRESSED_H diff --git a/core/io/file_access_encrypted.cpp b/core/io/file_access_encrypted.cpp index 039458237d..03700cad48 100644 --- a/core/io/file_access_encrypted.cpp +++ b/core/io/file_access_encrypted.cpp @@ -36,55 +36,55 @@ #include "core/variant.h" #include <stdio.h> -Error FileAccessEncrypted::open_and_parse(FileAccess *p_base,const Vector<uint8_t>& p_key,Mode p_mode) { +Error FileAccessEncrypted::open_and_parse(FileAccess *p_base, const Vector<uint8_t> &p_key, Mode p_mode) { //print_line("open and parse!"); - ERR_FAIL_COND_V(file!=NULL,ERR_ALREADY_IN_USE); - ERR_FAIL_COND_V(p_key.size()!=32,ERR_INVALID_PARAMETER); + ERR_FAIL_COND_V(file != NULL, ERR_ALREADY_IN_USE); + ERR_FAIL_COND_V(p_key.size() != 32, ERR_INVALID_PARAMETER); - pos=0; - eofed=false; + pos = 0; + eofed = false; - if (p_mode==MODE_WRITE_AES256) { + if (p_mode == MODE_WRITE_AES256) { data.clear(); - writing=true; - file=p_base; - mode=p_mode; - key=p_key; + writing = true; + file = p_base; + mode = p_mode; + key = p_key; - } else if (p_mode==MODE_READ) { + } else if (p_mode == MODE_READ) { - writing=false; - key=p_key; + writing = false; + key = p_key; uint32_t magic = p_base->get_32(); - print_line("MAGIC: "+itos(magic)); - ERR_FAIL_COND_V(magic!=COMP_MAGIC,ERR_FILE_UNRECOGNIZED); - mode=Mode(p_base->get_32()); - ERR_FAIL_INDEX_V(mode,MODE_MAX,ERR_FILE_CORRUPT); - ERR_FAIL_COND_V(mode==0,ERR_FILE_CORRUPT); - print_line("MODE: "+itos(mode)); + print_line("MAGIC: " + itos(magic)); + ERR_FAIL_COND_V(magic != COMP_MAGIC, ERR_FILE_UNRECOGNIZED); + mode = Mode(p_base->get_32()); + ERR_FAIL_INDEX_V(mode, MODE_MAX, ERR_FILE_CORRUPT); + ERR_FAIL_COND_V(mode == 0, ERR_FILE_CORRUPT); + print_line("MODE: " + itos(mode)); unsigned char md5d[16]; - p_base->get_buffer(md5d,16); - length=p_base->get_64(); - base=p_base->get_pos(); - ERR_FAIL_COND_V(p_base->get_len() < base+length, ERR_FILE_CORRUPT ); + p_base->get_buffer(md5d, 16); + length = p_base->get_64(); + base = p_base->get_pos(); + ERR_FAIL_COND_V(p_base->get_len() < base + length, ERR_FILE_CORRUPT); int ds = length; if (ds % 16) { - ds+=16-(ds % 16); + ds += 16 - (ds % 16); } data.resize(ds); - int blen = p_base->get_buffer(data.ptr(),ds); - ERR_FAIL_COND_V(blen!=ds,ERR_FILE_CORRUPT); + int blen = p_base->get_buffer(data.ptr(), ds); + ERR_FAIL_COND_V(blen != ds, ERR_FILE_CORRUPT); aes256_context ctx; - aes256_init(&ctx,key.ptr()); + aes256_init(&ctx, key.ptr()); - for(size_t i=0;i<ds;i+=16) { + for (size_t i = 0; i < ds; i += 16) { - aes256_decrypt_ecb(&ctx,&data[i]); + aes256_decrypt_ecb(&ctx, &data[i]); } aes256_done(&ctx); @@ -93,37 +93,32 @@ Error FileAccessEncrypted::open_and_parse(FileAccess *p_base,const Vector<uint8_ MD5_CTX md5; MD5Init(&md5); - MD5Update(&md5,data.ptr(),data.size()); + MD5Update(&md5, data.ptr(), data.size()); MD5Final(&md5); + ERR_FAIL_COND_V(String::md5(md5.digest) != String::md5(md5d), ERR_FILE_CORRUPT); - ERR_FAIL_COND_V(String::md5(md5.digest)!=String::md5(md5d),ERR_FILE_CORRUPT) ; - - - file=p_base; + file = p_base; } return OK; } -Error FileAccessEncrypted::open_and_parse_password(FileAccess *p_base,const String& p_key,Mode p_mode){ - +Error FileAccessEncrypted::open_and_parse_password(FileAccess *p_base, const String &p_key, Mode p_mode) { String cs = p_key.md5_text(); - ERR_FAIL_COND_V(cs.length()!=32,ERR_INVALID_PARAMETER); + ERR_FAIL_COND_V(cs.length() != 32, ERR_INVALID_PARAMETER); Vector<uint8_t> key; key.resize(32); - for(int i=0;i<32;i++) { + for (int i = 0; i < 32; i++) { - key[i]=cs[i]; + key[i] = cs[i]; } - return open_and_parse(p_base,key,p_mode); + return open_and_parse(p_base, key, p_mode); } - - -Error FileAccessEncrypted::_open(const String& p_path, int p_mode_flags) { +Error FileAccessEncrypted::_open(const String &p_path, int p_mode_flags) { return OK; } @@ -137,26 +132,26 @@ void FileAccessEncrypted::close() { Vector<uint8_t> compressed; size_t len = data.size(); if (len % 16) { - len+=16-(len % 16); + len += 16 - (len % 16); } MD5_CTX md5; MD5Init(&md5); - MD5Update(&md5,data.ptr(),data.size()); + MD5Update(&md5, data.ptr(), data.size()); MD5Final(&md5); compressed.resize(len); - zeromem( compressed.ptr(), len ); - for(int i=0;i<data.size();i++) { - compressed[i]=data[i]; + zeromem(compressed.ptr(), len); + for (int i = 0; i < data.size(); i++) { + compressed[i] = data[i]; } aes256_context ctx; - aes256_init(&ctx,key.ptr()); + aes256_init(&ctx, key.ptr()); - for(size_t i=0;i<len;i+=16) { + for (size_t i = 0; i < len; i += 16) { - aes256_encrypt_ecb(&ctx,&compressed[i]); + aes256_encrypt_ecb(&ctx, &compressed[i]); } aes256_done(&ctx); @@ -164,14 +159,13 @@ void FileAccessEncrypted::close() { file->store_32(COMP_MAGIC); file->store_32(mode); - - file->store_buffer(md5.digest,16); + file->store_buffer(md5.digest, 16); file->store_64(data.size()); - file->store_buffer(compressed.ptr(),compressed.size()); + file->store_buffer(compressed.ptr(), compressed.size()); file->close(); memdelete(file); - file=NULL; + file = NULL; data.clear(); } else { @@ -179,143 +173,133 @@ void FileAccessEncrypted::close() { file->close(); memdelete(file); data.clear(); - file=NULL; + file = NULL; } - - - } -bool FileAccessEncrypted::is_open() const{ +bool FileAccessEncrypted::is_open() const { - return file!=NULL; + return file != NULL; } -void FileAccessEncrypted::seek(size_t p_position){ +void FileAccessEncrypted::seek(size_t p_position) { if (p_position > (size_t)data.size()) - p_position=data.size(); - - pos=p_position; - eofed=false; + p_position = data.size(); + pos = p_position; + eofed = false; } +void FileAccessEncrypted::seek_end(int64_t p_position) { -void FileAccessEncrypted::seek_end(int64_t p_position){ - - seek( data.size() + p_position ); + seek(data.size() + p_position); } -size_t FileAccessEncrypted::get_pos() const{ +size_t FileAccessEncrypted::get_pos() const { return pos; } -size_t FileAccessEncrypted::get_len() const{ +size_t FileAccessEncrypted::get_len() const { return data.size(); } -bool FileAccessEncrypted::eof_reached() const{ +bool FileAccessEncrypted::eof_reached() const { return eofed; } -uint8_t FileAccessEncrypted::get_8() const{ +uint8_t FileAccessEncrypted::get_8() const { - ERR_FAIL_COND_V(writing,0); - if (pos>=data.size()) { - eofed=true; + ERR_FAIL_COND_V(writing, 0); + if (pos >= data.size()) { + eofed = true; return 0; } uint8_t b = data[pos]; pos++; return b; - } -int FileAccessEncrypted::get_buffer(uint8_t *p_dst, int p_length) const{ +int FileAccessEncrypted::get_buffer(uint8_t *p_dst, int p_length) const { - ERR_FAIL_COND_V(writing,0); + ERR_FAIL_COND_V(writing, 0); - int to_copy=MIN(p_length,data.size()-pos); - for(int i=0;i<to_copy;i++) { + int to_copy = MIN(p_length, data.size() - pos); + for (int i = 0; i < to_copy; i++) { - p_dst[i]=data[pos++]; + p_dst[i] = data[pos++]; } - if (to_copy<p_length) { - eofed=true; + if (to_copy < p_length) { + eofed = true; } - return to_copy; } -Error FileAccessEncrypted::get_error() const{ +Error FileAccessEncrypted::get_error() const { - return eofed?ERR_FILE_EOF:OK; + return eofed ? ERR_FILE_EOF : OK; } -void FileAccessEncrypted::store_buffer(const uint8_t *p_src,int p_length) { +void FileAccessEncrypted::store_buffer(const uint8_t *p_src, int p_length) { ERR_FAIL_COND(!writing); - if (pos<data.size()) { + if (pos < data.size()) { - for(int i=0;i<p_length;i++) { + for (int i = 0; i < p_length; i++) { store_8(p_src[i]); } - } else if (pos==data.size()) { + } else if (pos == data.size()) { - data.resize(pos+p_length); - for(int i=0;i<p_length;i++) { + data.resize(pos + p_length); + for (int i = 0; i < p_length; i++) { - data[pos+i]=p_src[i]; + data[pos + i] = p_src[i]; } - pos+=p_length; + pos += p_length; } } - -void FileAccessEncrypted::store_8(uint8_t p_dest){ +void FileAccessEncrypted::store_8(uint8_t p_dest) { ERR_FAIL_COND(!writing); - if (pos<data.size()) { - data[pos]=p_dest; + if (pos < data.size()) { + data[pos] = p_dest; pos++; - } else if (pos==data.size()){ + } else if (pos == data.size()) { data.push_back(p_dest); pos++; } } -bool FileAccessEncrypted::file_exists(const String& p_name){ +bool FileAccessEncrypted::file_exists(const String &p_name) { - FileAccess *fa = FileAccess::open(p_name,FileAccess::READ); + FileAccess *fa = FileAccess::open(p_name, FileAccess::READ); if (!fa) return false; memdelete(fa); return true; } -uint64_t FileAccessEncrypted::_get_modified_time(const String& p_file){ - +uint64_t FileAccessEncrypted::_get_modified_time(const String &p_file) { return 0; } FileAccessEncrypted::FileAccessEncrypted() { - file=NULL; - pos=0; - eofed=false; - mode=MODE_MAX; - writing=false; + file = NULL; + pos = 0; + eofed = false; + mode = MODE_MAX; + writing = false; } - FileAccessEncrypted::~FileAccessEncrypted() { if (file) diff --git a/core/io/file_access_encrypted.h b/core/io/file_access_encrypted.h index 51ed9a8677..ac4d2bd1c7 100644 --- a/core/io/file_access_encrypted.h +++ b/core/io/file_access_encrypted.h @@ -29,12 +29,10 @@ #ifndef FILE_ACCESS_ENCRYPTED_H #define FILE_ACCESS_ENCRYPTED_H - #include "os/file_access.h" class FileAccessEncrypted : public FileAccess { public: - enum Mode { MODE_READ, MODE_WRITE_AES256, @@ -42,8 +40,6 @@ public: }; private: - - Mode mode; Vector<uint8_t> key; bool writing; @@ -54,21 +50,16 @@ private: mutable size_t pos; mutable bool eofed; - public: + Error open_and_parse(FileAccess *p_base, const Vector<uint8_t> &p_key, Mode p_mode); + Error open_and_parse_password(FileAccess *p_base, const String &p_key, Mode p_mode); - - - - Error open_and_parse(FileAccess *p_base,const Vector<uint8_t>& p_key,Mode p_mode); - Error open_and_parse_password(FileAccess *p_base,const String& p_key,Mode p_mode); - - virtual Error _open(const String& p_path, int p_mode_flags); ///< open a file + virtual Error _open(const String &p_path, int p_mode_flags); ///< open a file virtual void close(); ///< close a file virtual bool is_open() const; ///< true when file is open virtual void seek(size_t p_position); ///< seek to a given position - virtual void seek_end(int64_t p_position=0); ///< seek from the end of file + virtual void seek_end(int64_t p_position = 0); ///< seek from the end of file virtual size_t get_pos() const; ///< get position in the file virtual size_t get_len() const; ///< get size of the file @@ -80,11 +71,11 @@ public: virtual Error get_error() const; ///< get last error virtual void store_8(uint8_t p_dest); ///< store a byte - virtual void store_buffer(const uint8_t *p_src,int p_length); ///< store an array of bytes + virtual void store_buffer(const uint8_t *p_src, int p_length); ///< store an array of bytes - virtual bool file_exists(const String& p_name); ///< return true if a file exists + virtual bool file_exists(const String &p_name); ///< return true if a file exists - virtual uint64_t _get_modified_time(const String& p_file); + virtual uint64_t _get_modified_time(const String &p_file); FileAccessEncrypted(); ~FileAccessEncrypted(); diff --git a/core/io/file_access_memory.cpp b/core/io/file_access_memory.cpp index b4ba14ddc9..966109bfe1 100644 --- a/core/io/file_access_memory.cpp +++ b/core/io/file_access_memory.cpp @@ -28,12 +28,12 @@ /*************************************************************************/ #include "file_access_memory.h" -#include "os/dir_access.h" -#include "os/copymem.h" #include "global_config.h" #include "map.h" +#include "os/copymem.h" +#include "os/dir_access.h" -static Map<String, Vector<uint8_t> >* files = NULL; +static Map<String, Vector<uint8_t> > *files = NULL; void FileAccessMemory::register_file(String p_name, Vector<uint8_t> p_data) { @@ -59,13 +59,12 @@ void FileAccessMemory::cleanup() { memdelete(files); } - -FileAccess* FileAccessMemory::create() { +FileAccess *FileAccessMemory::create() { return memnew(FileAccessMemory); } -bool FileAccessMemory::file_exists(const String& p_name) { +bool FileAccessMemory::file_exists(const String &p_name) { String name = fix_path(p_name); //name = DirAccess::normalize_path(name); @@ -73,23 +72,22 @@ bool FileAccessMemory::file_exists(const String& p_name) { return files && (files->find(name) != NULL); } +Error FileAccessMemory::open_custom(const uint8_t *p_data, int p_len) { -Error FileAccessMemory::open_custom(const uint8_t* p_data, int p_len) { - - data=(uint8_t*)p_data; - length=p_len; - pos=0; + data = (uint8_t *)p_data; + length = p_len; + pos = 0; return OK; } -Error FileAccessMemory::_open(const String& p_path, int p_mode_flags) { +Error FileAccessMemory::_open(const String &p_path, int p_mode_flags) { ERR_FAIL_COND_V(!files, ERR_FILE_NOT_FOUND); String name = fix_path(p_path); //name = DirAccess::normalize_path(name); - Map<String, Vector<uint8_t> >::Element* E = files->find(name); + Map<String, Vector<uint8_t> >::Element *E = files->find(name); ERR_FAIL_COND_V(!E, ERR_FILE_NOT_FOUND); data = &(E->get()[0]); @@ -149,7 +147,7 @@ uint8_t FileAccessMemory::get_8() const { return ret; } -int FileAccessMemory::get_buffer(uint8_t *p_dst,int p_length) const { +int FileAccessMemory::get_buffer(uint8_t *p_dst, int p_length) const { ERR_FAIL_COND_V(!data, -1); @@ -178,7 +176,7 @@ void FileAccessMemory::store_8(uint8_t p_byte) { data[pos++] = p_byte; } -void FileAccessMemory::store_buffer(const uint8_t *p_src,int p_length) { +void FileAccessMemory::store_buffer(const uint8_t *p_src, int p_length) { int left = length - pos; int write = MIN(p_length, left); diff --git a/core/io/file_access_memory.h b/core/io/file_access_memory.h index c6dda07971..687e3e9bee 100644 --- a/core/io/file_access_memory.h +++ b/core/io/file_access_memory.h @@ -33,19 +33,18 @@ class FileAccessMemory : public FileAccess { - uint8_t* data; + uint8_t *data; int length; mutable int pos; - static FileAccess* create(); + static FileAccess *create(); public: - static void register_file(String p_name, Vector<uint8_t> p_data); static void cleanup(); - virtual Error open_custom(const uint8_t* p_data, int p_len); ///< open a file - virtual Error _open(const String& p_path, int p_mode_flags); ///< open a file + virtual Error open_custom(const uint8_t *p_data, int p_len); ///< open a file + virtual Error _open(const String &p_path, int p_mode_flags); ///< open a file virtual void close(); ///< close a file virtual bool is_open() const; ///< true when file is open @@ -58,18 +57,16 @@ public: virtual uint8_t get_8() const; ///< get a byte - virtual int get_buffer(uint8_t *p_dst,int p_length) const; ///< get an array of bytes + virtual int get_buffer(uint8_t *p_dst, int p_length) const; ///< get an array of bytes virtual Error get_error() const; ///< get last error virtual void store_8(uint8_t p_dest); ///< store a byte - virtual void store_buffer(const uint8_t *p_src,int p_length); ///< store an array of bytes - - virtual bool file_exists(const String& p_name); ///< return true if a file exists - - virtual uint64_t _get_modified_time(const String& p_file) { return 0; } + virtual void store_buffer(const uint8_t *p_src, int p_length); ///< store an array of bytes + virtual bool file_exists(const String &p_name); ///< return true if a file exists + virtual uint64_t _get_modified_time(const String &p_file) { return 0; } FileAccessMemory(); }; diff --git a/core/io/file_access_network.cpp b/core/io/file_access_network.cpp index d9fdc9cedc..9120b55565 100644 --- a/core/io/file_access_network.cpp +++ b/core/io/file_access_network.cpp @@ -27,19 +27,16 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "file_access_network.h" -#include "marshalls.h" #include "global_config.h" -#include "os/os.h" #include "io/ip.h" - - +#include "marshalls.h" +#include "os/os.h" //#define DEBUG_PRINT(m_p) print_line(m_p) //#define DEBUG_TIME(m_what) printf("MS: %s - %lli\n",m_what,OS::get_singleton()->get_ticks_usec()); #define DEBUG_PRINT(m_p) #define DEBUG_TIME(m_what) - void FileAccessNetworkClient::lock_mutex() { mutex->lock(); @@ -50,59 +47,55 @@ void FileAccessNetworkClient::unlock_mutex() { lockcount--; mutex->unlock(); - } void FileAccessNetworkClient::put_32(int p_32) { uint8_t buf[4]; - encode_uint32(p_32,buf); - client->put_data(buf,4); - DEBUG_PRINT("put32: "+itos(p_32)); + encode_uint32(p_32, buf); + client->put_data(buf, 4); + DEBUG_PRINT("put32: " + itos(p_32)); } void FileAccessNetworkClient::put_64(int64_t p_64) { uint8_t buf[8]; - encode_uint64(p_64,buf); - client->put_data(buf,8); - DEBUG_PRINT("put64: "+itos(p_64)); - + encode_uint64(p_64, buf); + client->put_data(buf, 8); + DEBUG_PRINT("put64: " + itos(p_64)); } int FileAccessNetworkClient::get_32() { uint8_t buf[4]; - client->get_data(buf,4); + client->get_data(buf, 4); return decode_uint32(buf); - } int64_t FileAccessNetworkClient::get_64() { uint8_t buf[8]; - client->get_data(buf,8); + client->get_data(buf, 8); return decode_uint64(buf); - } void FileAccessNetworkClient::_thread_func() { client->set_nodelay(true); - while(!quit) { + while (!quit) { - DEBUG_PRINT("SEM WAIT - "+itos(sem->get())); + DEBUG_PRINT("SEM WAIT - " + itos(sem->get())); Error err = sem->wait(); DEBUG_TIME("sem_unlock"); //DEBUG_PRINT("semwait returned "+itos(werr)); - DEBUG_PRINT("MUTEX LOCK "+itos(lockcount)); + DEBUG_PRINT("MUTEX LOCK " + itos(lockcount)); DEBUG_PRINT("POPO"); DEBUG_PRINT("PEPE"); lock_mutex(); DEBUG_PRINT("MUTEX PASS"); blockrequest_mutex->lock(); - while(block_requests.size()) { + while (block_requests.size()) { put_32(block_requests.front()->get().id); put_32(FileAccessNetwork::COMMAND_READ_BLOCK); put_64(block_requests.front()->get().offset); @@ -117,35 +110,32 @@ void FileAccessNetworkClient::_thread_func() { int id = get_32(); int response = get_32(); - DEBUG_PRINT("GET RESPONSE: "+itos(response)); + DEBUG_PRINT("GET RESPONSE: " + itos(response)); - FileAccessNetwork *fa=NULL; + FileAccessNetwork *fa = NULL; - if (response!=FileAccessNetwork::RESPONSE_DATA) { + if (response != FileAccessNetwork::RESPONSE_DATA) { ERR_FAIL_COND(!accesses.has(id)); } if (accesses.has(id)) - fa=accesses[id]; + fa = accesses[id]; - - switch(response) { + switch (response) { case FileAccessNetwork::RESPONSE_OPEN: { - DEBUG_TIME("sem_open"); int status = get_32(); - if (status!=OK) { - fa->_respond(0,Error(status)); + if (status != OK) { + fa->_respond(0, Error(status)); } else { uint64_t len = get_64(); - fa->_respond(len,Error(status)); + fa->_respond(len, Error(status)); } fa->sem->post(); - } break; case FileAccessNetwork::RESPONSE_DATA: { @@ -154,104 +144,95 @@ void FileAccessNetworkClient::_thread_func() { Vector<uint8_t> block; block.resize(len); - client->get_data(block.ptr(),len); + client->get_data(block.ptr(), len); if (fa) //may have been queued - fa->_set_block(offset,block); + fa->_set_block(offset, block); } break; case FileAccessNetwork::RESPONSE_FILE_EXISTS: { - int status = get_32(); - fa->exists_modtime=status!=0; + fa->exists_modtime = status != 0; fa->sem->post(); - - } break; case FileAccessNetwork::RESPONSE_GET_MODTIME: { - uint64_t status = get_64(); - fa->exists_modtime=status; + fa->exists_modtime = status; fa->sem->post(); } break; - } - unlock_mutex(); } - } void FileAccessNetworkClient::_thread_func(void *s) { - FileAccessNetworkClient *self =(FileAccessNetworkClient*)s; + FileAccessNetworkClient *self = (FileAccessNetworkClient *)s; self->_thread_func(); - } -Error FileAccessNetworkClient::connect(const String& p_host,int p_port,const String& p_password) { +Error FileAccessNetworkClient::connect(const String &p_host, int p_port, const String &p_password) { IP_Address ip; if (p_host.is_valid_ip_address()) { - ip=p_host; + ip = p_host; } else { - ip=IP::get_singleton()->resolve_hostname(p_host); + ip = IP::get_singleton()->resolve_hostname(p_host); } - DEBUG_PRINT("IP: "+String(ip)+" port "+itos(p_port)); - Error err = client->connect_to_host(ip,p_port); - ERR_FAIL_COND_V(err,err); - while(client->get_status()==StreamPeerTCP::STATUS_CONNECTING) { -//DEBUG_PRINT("trying to connect...."); + DEBUG_PRINT("IP: " + String(ip) + " port " + itos(p_port)); + Error err = client->connect_to_host(ip, p_port); + ERR_FAIL_COND_V(err, err); + while (client->get_status() == StreamPeerTCP::STATUS_CONNECTING) { + //DEBUG_PRINT("trying to connect...."); OS::get_singleton()->delay_usec(1000); } - if (client->get_status()!=StreamPeerTCP::STATUS_CONNECTED) { + if (client->get_status() != StreamPeerTCP::STATUS_CONNECTED) { return ERR_CANT_CONNECT; } CharString cs = p_password.utf8(); put_32(cs.length()); - client->put_data((const uint8_t*)cs.ptr(),cs.length()); + client->put_data((const uint8_t *)cs.ptr(), cs.length()); int e = get_32(); - if (e!=OK) { + if (e != OK) { return ERR_INVALID_PARAMETER; } - thread = Thread::create(_thread_func,this); + thread = Thread::create(_thread_func, this); return OK; } -FileAccessNetworkClient *FileAccessNetworkClient::singleton=NULL; - +FileAccessNetworkClient *FileAccessNetworkClient::singleton = NULL; FileAccessNetworkClient::FileAccessNetworkClient() { - thread=NULL; + thread = NULL; mutex = Mutex::create(); blockrequest_mutex = Mutex::create(); - quit=false; - singleton=this; - last_id=0; - client = Ref<StreamPeerTCP>( StreamPeerTCP::create_ref() ); - sem=Semaphore::create(); - lockcount=0; + quit = false; + singleton = this; + last_id = 0; + client = Ref<StreamPeerTCP>(StreamPeerTCP::create_ref()); + sem = Semaphore::create(); + lockcount = 0; } FileAccessNetworkClient::~FileAccessNetworkClient() { if (thread) { - quit=true; + quit = true; sem->post(); Thread::wait_to_finish(thread); memdelete(thread); @@ -260,70 +241,62 @@ FileAccessNetworkClient::~FileAccessNetworkClient() { memdelete(blockrequest_mutex); memdelete(mutex); memdelete(sem); - - } -void FileAccessNetwork::_set_block(size_t p_offset,const Vector<uint8_t>& p_block) { +void FileAccessNetwork::_set_block(size_t p_offset, const Vector<uint8_t> &p_block) { - - int page = p_offset/page_size; - ERR_FAIL_INDEX(page,pages.size()); - if (page<pages.size()-1) { - ERR_FAIL_COND(p_block.size()!=page_size); + int page = p_offset / page_size; + ERR_FAIL_INDEX(page, pages.size()); + if (page < pages.size() - 1) { + ERR_FAIL_COND(p_block.size() != page_size); } else { - ERR_FAIL_COND( (p_block.size() != (total_size%page_size))); + ERR_FAIL_COND((p_block.size() != (total_size % page_size))); } buffer_mutex->lock(); - pages[page].buffer=p_block; - pages[page].queued=false; + pages[page].buffer = p_block; + pages[page].queued = false; buffer_mutex->unlock(); - if (waiting_on_page==page) { - waiting_on_page=-1; + if (waiting_on_page == page) { + waiting_on_page = -1; page_sem->post(); } } +void FileAccessNetwork::_respond(size_t p_len, Error p_status) { -void FileAccessNetwork::_respond(size_t p_len,Error p_status) { - - DEBUG_PRINT("GOT RESPONSE - len: "+itos(p_len)+" status: "+itos(p_status)); - response=p_status; - if (response!=OK) + DEBUG_PRINT("GOT RESPONSE - len: " + itos(p_len) + " status: " + itos(p_status)); + response = p_status; + if (response != OK) return; - opened=true; - total_size=p_len; - int pc = ((total_size-1)/page_size)+1; + opened = true; + total_size = p_len; + int pc = ((total_size - 1) / page_size) + 1; pages.resize(pc); - - - - } -Error FileAccessNetwork::_open(const String& p_path, int p_mode_flags) { +Error FileAccessNetwork::_open(const String &p_path, int p_mode_flags) { - ERR_FAIL_COND_V(p_mode_flags!=READ,ERR_UNAVAILABLE); + ERR_FAIL_COND_V(p_mode_flags != READ, ERR_UNAVAILABLE); if (opened) close(); FileAccessNetworkClient *nc = FileAccessNetworkClient::singleton; - DEBUG_PRINT("open: "+p_path); + DEBUG_PRINT("open: " + p_path); DEBUG_TIME("open_begin"); nc->lock_mutex(); nc->put_32(id); - nc->accesses[id]=this; + nc->accesses[id] = this; nc->put_32(COMMAND_OPEN_FILE); - CharString cs =p_path.utf8(); + CharString cs = p_path.utf8(); nc->put_32(cs.length()); - nc->client->put_data((const uint8_t*)cs.ptr(),cs.length()); - pos=0; - eof_flag=false; - last_page=-1; - last_page_buff=NULL; + nc->client->put_data((const uint8_t *)cs.ptr(), cs.length()); + pos = 0; + eof_flag = false; + last_page = -1; + last_page_buff = NULL; //buffers.clear(); nc->unlock_mutex(); @@ -338,7 +311,7 @@ Error FileAccessNetwork::_open(const String& p_path, int p_mode_flags) { return response; } -void FileAccessNetwork::close(){ +void FileAccessNetwork::close() { if (!opened) return; @@ -350,110 +323,103 @@ void FileAccessNetwork::close(){ nc->put_32(id); nc->put_32(COMMAND_CLOSE); pages.clear(); - opened=false; + opened = false; nc->unlock_mutex(); - - } -bool FileAccessNetwork::is_open() const{ +bool FileAccessNetwork::is_open() const { return opened; } -void FileAccessNetwork::seek(size_t p_position){ +void FileAccessNetwork::seek(size_t p_position) { ERR_FAIL_COND(!opened); - eof_flag=p_position>total_size; + eof_flag = p_position > total_size; - if (p_position>=total_size) { - p_position=total_size; + if (p_position >= total_size) { + p_position = total_size; } - pos=p_position; + pos = p_position; } -void FileAccessNetwork::seek_end(int64_t p_position){ - - seek(total_size+p_position); +void FileAccessNetwork::seek_end(int64_t p_position) { + seek(total_size + p_position); } -size_t FileAccessNetwork::get_pos() const{ +size_t FileAccessNetwork::get_pos() const { - ERR_FAIL_COND_V(!opened,0); + ERR_FAIL_COND_V(!opened, 0); return pos; } -size_t FileAccessNetwork::get_len() const{ +size_t FileAccessNetwork::get_len() const { - ERR_FAIL_COND_V(!opened,0); + ERR_FAIL_COND_V(!opened, 0); return total_size; } -bool FileAccessNetwork::eof_reached() const{ +bool FileAccessNetwork::eof_reached() const { - ERR_FAIL_COND_V(!opened,false); + ERR_FAIL_COND_V(!opened, false); return eof_flag; } -uint8_t FileAccessNetwork::get_8() const{ +uint8_t FileAccessNetwork::get_8() const { uint8_t v; - get_buffer(&v,1); + get_buffer(&v, 1); return v; - } - void FileAccessNetwork::_queue_page(int p_page) const { - if (p_page>=pages.size()) + if (p_page >= pages.size()) return; if (pages[p_page].buffer.empty() && !pages[p_page].queued) { - FileAccessNetworkClient *nc = FileAccessNetworkClient::singleton; nc->blockrequest_mutex->lock(); FileAccessNetworkClient::BlockRequest br; - br.id=id; - br.offset=size_t(p_page)*page_size; - br.size=page_size; + br.id = id; + br.offset = size_t(p_page) * page_size; + br.size = page_size; nc->block_requests.push_back(br); - pages[p_page].queued=true; + pages[p_page].queued = true; nc->blockrequest_mutex->unlock(); DEBUG_PRINT("QUEUE PAGE POST"); nc->sem->post(); - DEBUG_PRINT("queued "+itos(p_page)); + DEBUG_PRINT("queued " + itos(p_page)); } - } -int FileAccessNetwork::get_buffer(uint8_t *p_dst, int p_length) const{ +int FileAccessNetwork::get_buffer(uint8_t *p_dst, int p_length) const { //bool eof=false; - if (pos+p_length>total_size) { - eof_flag=true; + if (pos + p_length > total_size) { + eof_flag = true; } - if (pos+p_length>=total_size) { - p_length=total_size-pos; + if (pos + p_length >= total_size) { + p_length = total_size - pos; } //FileAccessNetworkClient *nc = FileAccessNetworkClient::singleton; - uint8_t *buff=last_page_buff; + uint8_t *buff = last_page_buff; - for(int i=0;i<p_length;i++) { + for (int i = 0; i < p_length; i++) { - int page=pos/page_size; + int page = pos / page_size; - if (page!=last_page) { + if (page != last_page) { buffer_mutex->lock(); if (pages[page].buffer.empty()) { //fuck - waiting_on_page=page; - for(int j=0;j<read_ahead;j++) { + waiting_on_page = page; + for (int j = 0; j < read_ahead; j++) { - _queue_page(page+j); + _queue_page(page + j); } buffer_mutex->unlock(); DEBUG_PRINT("wait"); @@ -461,30 +427,30 @@ int FileAccessNetwork::get_buffer(uint8_t *p_dst, int p_length) const{ DEBUG_PRINT("done"); } else { - for(int j=0;j<read_ahead;j++) { + for (int j = 0; j < read_ahead; j++) { - _queue_page(page+j); + _queue_page(page + j); } - buff=pages[page].buffer.ptr(); + buff = pages[page].buffer.ptr(); //queue pages buffer_mutex->unlock(); } - buff=pages[page].buffer.ptr(); - last_page_buff=buff; - last_page=page; + buff = pages[page].buffer.ptr(); + last_page_buff = buff; + last_page = page; } - p_dst[i]=buff[pos-uint64_t(page)*page_size]; + p_dst[i] = buff[pos - uint64_t(page) * page_size]; pos++; } return p_length; } -Error FileAccessNetwork::get_error() const{ +Error FileAccessNetwork::get_error() const { - return pos==total_size?ERR_FILE_EOF:OK; + return pos == total_size ? ERR_FILE_EOF : OK; } void FileAccessNetwork::store_8(uint8_t p_dest) { @@ -492,71 +458,66 @@ void FileAccessNetwork::store_8(uint8_t p_dest) { ERR_FAIL(); } -bool FileAccessNetwork::file_exists(const String& p_path){ +bool FileAccessNetwork::file_exists(const String &p_path) { FileAccessNetworkClient *nc = FileAccessNetworkClient::singleton; nc->lock_mutex(); nc->put_32(id); nc->put_32(COMMAND_FILE_EXISTS); - CharString cs=p_path.utf8(); + CharString cs = p_path.utf8(); nc->put_32(cs.length()); - nc->client->put_data((const uint8_t*)cs.ptr(),cs.length()); + nc->client->put_data((const uint8_t *)cs.ptr(), cs.length()); nc->unlock_mutex(); DEBUG_PRINT("FILE EXISTS POST"); nc->sem->post(); sem->wait(); - return exists_modtime!=0; - + return exists_modtime != 0; } -uint64_t FileAccessNetwork::_get_modified_time(const String& p_file){ +uint64_t FileAccessNetwork::_get_modified_time(const String &p_file) { FileAccessNetworkClient *nc = FileAccessNetworkClient::singleton; nc->lock_mutex(); nc->put_32(id); nc->put_32(COMMAND_GET_MODTIME); - CharString cs=p_file.utf8(); + CharString cs = p_file.utf8(); nc->put_32(cs.length()); - nc->client->put_data((const uint8_t*)cs.ptr(),cs.length()); + nc->client->put_data((const uint8_t *)cs.ptr(), cs.length()); nc->unlock_mutex(); DEBUG_PRINT("MODTIME POST"); nc->sem->post(); sem->wait(); return exists_modtime; - } void FileAccessNetwork::configure() { - GLOBAL_DEF("network/remote_fs/page_size",65536); - GLOBAL_DEF("network/remote_fs/page_read_ahead",4); - GLOBAL_DEF("network/remote_fs/max_pages",20); - + GLOBAL_DEF("network/remote_fs/page_size", 65536); + GLOBAL_DEF("network/remote_fs/page_read_ahead", 4); + GLOBAL_DEF("network/remote_fs/max_pages", 20); } FileAccessNetwork::FileAccessNetwork() { - eof_flag=false; - opened=false; - pos=0; - sem=Semaphore::create(); - page_sem=Semaphore::create(); - buffer_mutex=Mutex::create(); + eof_flag = false; + opened = false; + pos = 0; + sem = Semaphore::create(); + page_sem = Semaphore::create(); + buffer_mutex = Mutex::create(); FileAccessNetworkClient *nc = FileAccessNetworkClient::singleton; nc->lock_mutex(); - id=nc->last_id++; - nc->accesses[id]=this; + id = nc->last_id++; + nc->accesses[id] = this; nc->unlock_mutex(); page_size = GLOBAL_GET("network/remote_fs/page_size"); read_ahead = GLOBAL_GET("network/remote_fs/page_read_ahead"); max_pages = GLOBAL_GET("network/remote_fs/max_pages"); - last_activity_val=0; - waiting_on_page=-1; - last_page=-1; - - + last_activity_val = 0; + waiting_on_page = -1; + last_page = -1; } FileAccessNetwork::~FileAccessNetwork() { @@ -568,8 +529,7 @@ FileAccessNetwork::~FileAccessNetwork() { FileAccessNetworkClient *nc = FileAccessNetworkClient::singleton; nc->lock_mutex(); - id=nc->last_id++; + id = nc->last_id++; nc->accesses.erase(id); nc->unlock_mutex(); - } diff --git a/core/io/file_access_network.h b/core/io/file_access_network.h index 4dbfb04b10..bb3d22c1e9 100644 --- a/core/io/file_access_network.h +++ b/core/io/file_access_network.h @@ -29,16 +29,15 @@ #ifndef FILE_ACCESS_NETWORK_H #define FILE_ACCESS_NETWORK_H +#include "io/stream_peer_tcp.h" #include "os/file_access.h" #include "os/semaphore.h" #include "os/thread.h" -#include "io/stream_peer_tcp.h" class FileAccessNetwork; class FileAccessNetworkClient { - struct BlockRequest { int id; @@ -55,7 +54,7 @@ class FileAccessNetworkClient { bool quit; Mutex *mutex; Mutex *blockrequest_mutex; - Map<int,FileAccessNetwork*> accesses; + Map<int, FileAccessNetwork *> accesses; Ref<StreamPeerTCP> client; int last_id; @@ -72,18 +71,16 @@ class FileAccessNetworkClient { void lock_mutex(); void unlock_mutex(); -friend class FileAccessNetwork; + friend class FileAccessNetwork; static FileAccessNetworkClient *singleton; public: - static FileAccessNetworkClient *get_singleton() { return singleton; } - Error connect(const String& p_host,int p_port,const String& p_password=""); + Error connect(const String &p_host, int p_port, const String &p_password = ""); FileAccessNetworkClient(); ~FileAccessNetworkClient(); - }; class FileAccessNetwork : public FileAccess { @@ -109,21 +106,23 @@ class FileAccessNetwork : public FileAccess { int activity; bool queued; Vector<uint8_t> buffer; - Page() { activity=0; queued=false; } + Page() { + activity = 0; + queued = false; + } }; - mutable Vector< Page > pages; + mutable Vector<Page> pages; mutable Error response; uint64_t exists_modtime; -friend class FileAccessNetworkClient; + friend class FileAccessNetworkClient; void _queue_page(int p_page) const; - void _respond(size_t p_len,Error p_status); - void _set_block(size_t p_offset,const Vector<uint8_t>& p_block); + void _respond(size_t p_len, Error p_status); + void _set_block(size_t p_offset, const Vector<uint8_t> &p_block); public: - enum Command { COMMAND_OPEN_FILE, COMMAND_READ_BLOCK, @@ -139,13 +138,12 @@ public: RESPONSE_GET_MODTIME, }; - - virtual Error _open(const String& p_path, int p_mode_flags); ///< open a file + virtual Error _open(const String &p_path, int p_mode_flags); ///< open a file virtual void close(); ///< close a file virtual bool is_open() const; ///< true when file is open virtual void seek(size_t p_position); ///< seek to a given position - virtual void seek_end(int64_t p_position=0); ///< seek from the end of file + virtual void seek_end(int64_t p_position = 0); ///< seek from the end of file virtual size_t get_pos() const; ///< get position in the file virtual size_t get_len() const; ///< get size of the file @@ -158,9 +156,9 @@ public: virtual void store_8(uint8_t p_dest); ///< store a byte - virtual bool file_exists(const String& p_path); ///< return true if a file exists + virtual bool file_exists(const String &p_path); ///< return true if a file exists - virtual uint64_t _get_modified_time(const String& p_file); + virtual uint64_t _get_modified_time(const String &p_file); static void configure(); diff --git a/core/io/file_access_pack.cpp b/core/io/file_access_pack.cpp index fa1bebde16..91d256ee2b 100644 --- a/core/io/file_access_pack.cpp +++ b/core/io/file_access_pack.cpp @@ -33,9 +33,9 @@ #define PACK_VERSION 1 -Error PackedData::add_pack(const String& p_path) { +Error PackedData::add_pack(const String &p_path) { - for (int i=0; i<sources.size(); i++) { + for (int i = 0; i < sources.size(); i++) { if (sources[i]->try_open_pack(p_path)) { @@ -46,7 +46,7 @@ Error PackedData::add_pack(const String& p_path) { return ERR_FILE_UNRECOGNIZED; }; -void PackedData::add_path(const String& pkg_path, const String& path, uint64_t ofs, uint64_t size,const uint8_t* p_md5, PackSource* p_src) { +void PackedData::add_path(const String &pkg_path, const String &path, uint64_t ofs, uint64_t size, const uint8_t *p_md5, PackSource *p_src) { PathMD5 pmd5(path.md5_buffer()); //printf("adding path %ls, %lli, %lli\n", path.c_str(), pmd5.a, pmd5.b); @@ -54,35 +54,35 @@ void PackedData::add_path(const String& pkg_path, const String& path, uint64_t o bool exists = files.has(pmd5); PackedFile pf; - pf.pack=pkg_path; - pf.offset=ofs; - pf.size=size; - for(int i=0;i<16;i++) - pf.md5[i]=p_md5[i]; + pf.pack = pkg_path; + pf.offset = ofs; + pf.size = size; + for (int i = 0; i < 16; i++) + pf.md5[i] = p_md5[i]; pf.src = p_src; - files[pmd5]=pf; + files[pmd5] = pf; if (!exists) { //search for dir - String p = path.replace_first("res://",""); - PackedDir *cd=root; + String p = path.replace_first("res://", ""); + PackedDir *cd = root; - if (p.find("/")!=-1) { //in a subdir + if (p.find("/") != -1) { //in a subdir - Vector<String> ds=p.get_base_dir().split("/"); + Vector<String> ds = p.get_base_dir().split("/"); - for(int j=0;j<ds.size();j++) { + for (int j = 0; j < ds.size(); j++) { if (!cd->subdirs.has(ds[j])) { - PackedDir *pd = memnew( PackedDir ); - pd->name=ds[j]; - pd->parent=cd; - cd->subdirs[pd->name]=pd; - cd=pd; + PackedDir *pd = memnew(PackedDir); + pd->name = ds[j]; + pd->parent = cd; + cd->subdirs[pd->name] = pd; + cd = pd; } else { - cd=cd->subdirs[ds[j]]; + cd = cd->subdirs[ds[j]]; } } } @@ -97,61 +97,59 @@ void PackedData::add_pack_source(PackSource *p_source) { } }; -PackedData *PackedData::singleton=NULL; +PackedData *PackedData::singleton = NULL; PackedData::PackedData() { - singleton=this; - root=memnew(PackedDir); - root->parent=NULL; - disabled=false; + singleton = this; + root = memnew(PackedDir); + root->parent = NULL; + disabled = false; add_pack_source(memnew(PackedSourcePCK)); } void PackedData::_free_packed_dirs(PackedDir *p_dir) { - for (Map<String,PackedDir*>::Element *E=p_dir->subdirs.front();E;E=E->next()) + for (Map<String, PackedDir *>::Element *E = p_dir->subdirs.front(); E; E = E->next()) _free_packed_dirs(E->get()); memdelete(p_dir); } PackedData::~PackedData() { - for(int i=0;i<sources.size();i++) { + for (int i = 0; i < sources.size(); i++) { memdelete(sources[i]); } _free_packed_dirs(root); } - ////////////////////////////////////////////////////////////////// -bool PackedSourcePCK::try_open_pack(const String& p_path) { +bool PackedSourcePCK::try_open_pack(const String &p_path) { - FileAccess *f = FileAccess::open(p_path,FileAccess::READ); + FileAccess *f = FileAccess::open(p_path, FileAccess::READ); if (!f) return false; //printf("try open %ls!\n", p_path.c_str()); - uint32_t magic= f->get_32(); + uint32_t magic = f->get_32(); if (magic != 0x43504447) { //maybe at he end.... self contained exe f->seek_end(); - f->seek( f->get_pos() -4 ); + f->seek(f->get_pos() - 4); magic = f->get_32(); if (magic != 0x43504447) { memdelete(f); return false; } - f->seek( f->get_pos() -12 ); - + f->seek(f->get_pos() - 12); uint64_t ds = f->get_64(); - f->seek( f->get_pos() -ds-8 ); + f->seek(f->get_pos() - ds - 8); magic = f->get_32(); if (magic != 0x43504447) { @@ -159,7 +157,6 @@ bool PackedSourcePCK::try_open_pack(const String& p_path) { memdelete(f); return false; } - } uint32_t version = f->get_32(); @@ -167,25 +164,25 @@ bool PackedSourcePCK::try_open_pack(const String& p_path) { uint32_t ver_minor = f->get_32(); uint32_t ver_rev = f->get_32(); - ERR_EXPLAIN("Pack version unsupported: "+itos(version)); - ERR_FAIL_COND_V( version != PACK_VERSION, ERR_INVALID_DATA); - ERR_EXPLAIN("Pack created with a newer version of the engine: "+itos(ver_major)+"."+itos(ver_minor)+"."+itos(ver_rev)); - ERR_FAIL_COND_V( ver_major > VERSION_MAJOR || (ver_major == VERSION_MAJOR && ver_minor > VERSION_MINOR), ERR_INVALID_DATA); + ERR_EXPLAIN("Pack version unsupported: " + itos(version)); + ERR_FAIL_COND_V(version != PACK_VERSION, ERR_INVALID_DATA); + ERR_EXPLAIN("Pack created with a newer version of the engine: " + itos(ver_major) + "." + itos(ver_minor) + "." + itos(ver_rev)); + ERR_FAIL_COND_V(ver_major > VERSION_MAJOR || (ver_major == VERSION_MAJOR && ver_minor > VERSION_MINOR), ERR_INVALID_DATA); - for(int i=0;i<16;i++) { + for (int i = 0; i < 16; i++) { //reserved f->get_32(); } int file_count = f->get_32(); - for(int i=0;i<file_count;i++) { + for (int i = 0; i < file_count; i++) { uint32_t sl = f->get_32(); CharString cs; - cs.resize(sl+1); - f->get_buffer((uint8_t*)cs.ptr(),sl); - cs[sl]=0; + cs.resize(sl + 1); + f->get_buffer((uint8_t *)cs.ptr(), sl); + cs[sl] = 0; String path; path.parse_utf8(cs.ptr()); @@ -193,22 +190,21 @@ bool PackedSourcePCK::try_open_pack(const String& p_path) { uint64_t ofs = f->get_64(); uint64_t size = f->get_64(); uint8_t md5[16]; - f->get_buffer(md5,16); - PackedData::get_singleton()->add_path(p_path, path, ofs, size, md5,this); + f->get_buffer(md5, 16); + PackedData::get_singleton()->add_path(p_path, path, ofs, size, md5, this); }; return true; }; -FileAccess* PackedSourcePCK::get_file(const String &p_path, PackedData::PackedFile* p_file) { +FileAccess *PackedSourcePCK::get_file(const String &p_path, PackedData::PackedFile *p_file) { - return memnew( FileAccessPack(p_path, *p_file)); + return memnew(FileAccessPack(p_path, *p_file)); }; ////////////////////////////////////////////////////////////////// - -Error FileAccessPack::_open(const String& p_path, int p_mode_flags) { +Error FileAccessPack::_open(const String &p_path, int p_mode_flags) { ERR_FAIL_V(ERR_UNAVAILABLE); return ERR_UNAVAILABLE; @@ -219,45 +215,44 @@ void FileAccessPack::close() { f->close(); } -bool FileAccessPack::is_open() const{ +bool FileAccessPack::is_open() const { return f->is_open(); } -void FileAccessPack::seek(size_t p_position){ +void FileAccessPack::seek(size_t p_position) { - if (p_position>pf.size) { - eof=true; + if (p_position > pf.size) { + eof = true; } else { - eof=false; + eof = false; } - f->seek(pf.offset+p_position); - pos=p_position; + f->seek(pf.offset + p_position); + pos = p_position; } -void FileAccessPack::seek_end(int64_t p_position){ - - seek(pf.size+p_position); +void FileAccessPack::seek_end(int64_t p_position) { + seek(pf.size + p_position); } size_t FileAccessPack::get_pos() const { return pos; } -size_t FileAccessPack::get_len() const{ +size_t FileAccessPack::get_len() const { return pf.size; } -bool FileAccessPack::eof_reached() const{ +bool FileAccessPack::eof_reached() const { return eof; } uint8_t FileAccessPack::get_8() const { - if (pos>=pf.size) { - eof=true; + if (pos >= pf.size) { + eof = true; return 0; } @@ -265,23 +260,22 @@ uint8_t FileAccessPack::get_8() const { return f->get_8(); } - -int FileAccessPack::get_buffer(uint8_t *p_dst,int p_length) const { +int FileAccessPack::get_buffer(uint8_t *p_dst, int p_length) const { if (eof) return 0; - int64_t to_read=p_length; - if (to_read+pos > pf.size) { - eof=true; - to_read=int64_t(pf.size)-int64_t(pos); + int64_t to_read = p_length; + if (to_read + pos > pf.size) { + eof = true; + to_read = int64_t(pf.size) - int64_t(pos); } - pos+=p_length; + pos += p_length; - if (to_read<=0) + if (to_read <= 0) return 0; - f->get_buffer(p_dst,to_read); + f->get_buffer(p_dst, to_read); return to_read; } @@ -301,32 +295,29 @@ Error FileAccessPack::get_error() const { void FileAccessPack::store_8(uint8_t p_dest) { ERR_FAIL(); - } -void FileAccessPack::store_buffer(const uint8_t *p_src,int p_length) { +void FileAccessPack::store_buffer(const uint8_t *p_src, int p_length) { ERR_FAIL(); - } -bool FileAccessPack::file_exists(const String& p_name) { +bool FileAccessPack::file_exists(const String &p_name) { return false; } +FileAccessPack::FileAccessPack(const String &p_path, const PackedData::PackedFile &p_file) { -FileAccessPack::FileAccessPack(const String& p_path, const PackedData::PackedFile& p_file) { - - pf=p_file; - f=FileAccess::open(pf.pack,FileAccess::READ); + pf = p_file; + f = FileAccess::open(pf.pack, FileAccess::READ); if (!f) { - ERR_EXPLAIN("Can't open pack-referenced file: "+String(pf.pack)); + ERR_EXPLAIN("Can't open pack-referenced file: " + String(pf.pack)); ERR_FAIL_COND(!f); } f->seek(pf.offset); - pos=0; - eof=false; + pos = 0; + eof = false; } FileAccessPack::~FileAccessPack() { @@ -334,24 +325,21 @@ FileAccessPack::~FileAccessPack() { memdelete(f); } - ////////////////////////////////////////////////////////////////////////////////// // DIR ACCESS ////////////////////////////////////////////////////////////////////////////////// - Error DirAccessPack::list_dir_begin() { - list_dirs.clear(); list_files.clear(); - for (Map<String,PackedData::PackedDir*>::Element *E=current->subdirs.front();E;E=E->next()) { + for (Map<String, PackedData::PackedDir *>::Element *E = current->subdirs.front(); E; E = E->next()) { list_dirs.push_back(E->key()); } - for (Set<String>::Element *E=current->files.front();E;E=E->next()) { + for (Set<String>::Element *E = current->files.front(); E; E = E->next()) { list_files.push_back(E->get()); } @@ -359,15 +347,15 @@ Error DirAccessPack::list_dir_begin() { return OK; } -String DirAccessPack::get_next(){ +String DirAccessPack::get_next() { if (list_dirs.size()) { - cdir=true; + cdir = true; String d = list_dirs.front()->get(); list_dirs.pop_front(); return d; } else if (list_files.size()) { - cdir=false; + cdir = false; String f = list_files.front()->get(); list_files.pop_front(); return f; @@ -375,11 +363,11 @@ String DirAccessPack::get_next(){ return String(); } } -bool DirAccessPack::current_is_dir() const{ +bool DirAccessPack::current_is_dir() const { return cdir; } -bool DirAccessPack::current_is_hidden() const{ +bool DirAccessPack::current_is_hidden() const { return false; } @@ -400,20 +388,20 @@ String DirAccessPack::get_drive(int p_drive) { Error DirAccessPack::change_dir(String p_dir) { - String nd = p_dir.replace("\\","/"); - bool absolute=false; + String nd = p_dir.replace("\\", "/"); + bool absolute = false; if (nd.begins_with("res://")) { - nd=nd.replace_first("res://",""); - absolute=true; + nd = nd.replace_first("res://", ""); + absolute = true; } - nd=nd.simplify_path(); + nd = nd.simplify_path(); if (nd == "") nd = "."; if (nd.begins_with("/")) { - nd=nd.replace_first("/","") ; - absolute=true; + nd = nd.replace_first("/", ""); + absolute = true; } Vector<String> paths = nd.split("/"); @@ -425,18 +413,18 @@ Error DirAccessPack::change_dir(String p_dir) { else pd = current; - for(int i=0;i<paths.size();i++) { + for (int i = 0; i < paths.size(); i++) { String p = paths[i]; - if (p==".") { + if (p == ".") { continue; - } else if (p=="..") { + } else if (p == "..") { if (pd->parent) { - pd=pd->parent; + pd = pd->parent; } } else if (pd->subdirs.has(p)) { - pd=pd->subdirs[p]; + pd = pd->subdirs[p]; } else { @@ -444,29 +432,26 @@ Error DirAccessPack::change_dir(String p_dir) { } } - current=pd; + current = pd; return OK; - - } String DirAccessPack::get_current_dir() { String p; PackedData::PackedDir *pd = current; - while(pd->parent) { + while (pd->parent) { - if (pd!=current) - p="/"+p; - p=p+pd->name; + if (pd != current) + p = "/" + p; + p = p + pd->name; } - return "res://"+p; - + return "res://" + p; } -bool DirAccessPack::file_exists(String p_file){ +bool DirAccessPack::file_exists(String p_file) { return current->files.has(p_file); } @@ -476,36 +461,30 @@ bool DirAccessPack::dir_exists(String p_dir) { return current->subdirs.has(p_dir); } -Error DirAccessPack::make_dir(String p_dir){ +Error DirAccessPack::make_dir(String p_dir) { return ERR_UNAVAILABLE; } -Error DirAccessPack::rename(String p_from, String p_to){ +Error DirAccessPack::rename(String p_from, String p_to) { return ERR_UNAVAILABLE; - } -Error DirAccessPack::remove(String p_name){ +Error DirAccessPack::remove(String p_name) { return ERR_UNAVAILABLE; - } -size_t DirAccessPack::get_space_left(){ +size_t DirAccessPack::get_space_left() { return 0; } DirAccessPack::DirAccessPack() { - current=PackedData::get_singleton()->root; - cdir=false; + current = PackedData::get_singleton()->root; + cdir = false; } DirAccessPack::~DirAccessPack() { - - } - - diff --git a/core/io/file_access_pack.h b/core/io/file_access_pack.h index 0a1320e57b..d16f5c461e 100644 --- a/core/io/file_access_pack.h +++ b/core/io/file_access_pack.h @@ -29,18 +29,18 @@ #ifndef FILE_ACCESS_PACK_H #define FILE_ACCESS_PACK_H -#include "os/file_access.h" -#include "os/dir_access.h" -#include "map.h" #include "list.h" +#include "map.h" +#include "os/dir_access.h" +#include "os/file_access.h" #include "print_string.h" class PackSource; class PackedData { -friend class FileAccessPack; -friend class DirAccessPack; -friend class PackSource; + friend class FileAccessPack; + friend class DirAccessPack; + friend class PackSource; public: struct PackedFile { @@ -49,21 +49,21 @@ public: uint64_t offset; //if offset is ZERO, the file was ERASED uint64_t size; uint8_t md5[16]; - PackSource* src; + PackSource *src; }; private: struct PackedDir { PackedDir *parent; String name; - Map<String,PackedDir*> subdirs; + Map<String, PackedDir *> subdirs; Set<String> files; }; struct PathMD5 { uint64_t a; uint64_t b; - bool operator < (const PathMD5& p_md5) const { + bool operator<(const PathMD5 &p_md5) const { if (p_md5.a == a) { return b < p_md5.b; @@ -72,7 +72,7 @@ private: } } - bool operator == (const PathMD5& p_md5) const { + bool operator==(const PathMD5 &p_md5) const { return a == p_md5.a && b == p_md5.b; }; @@ -81,14 +81,14 @@ private: }; PathMD5(const Vector<uint8_t> p_buf) { - a = *((uint64_t*)&p_buf[0]); - b = *((uint64_t*)&p_buf[8]); + a = *((uint64_t *)&p_buf[0]); + b = *((uint64_t *)&p_buf[8]); }; }; - Map<PathMD5,PackedFile> files; + Map<PathMD5, PackedFile> files; - Vector<PackSource*> sources; + Vector<PackSource *> sources; PackedDir *root; //Map<String,PackedDir*> dirs; @@ -99,18 +99,17 @@ private: void _free_packed_dirs(PackedDir *p_dir); public: + void add_pack_source(PackSource *p_source); + void add_path(const String &pkg_path, const String &path, uint64_t ofs, uint64_t size, const uint8_t *p_md5, PackSource *p_src); // for PackSource - void add_pack_source(PackSource* p_source); - void add_path(const String& pkg_path, const String& path, uint64_t ofs, uint64_t size,const uint8_t* p_md5, PackSource* p_src); // for PackSource - - void set_disabled(bool p_disabled) { disabled=p_disabled; } + void set_disabled(bool p_disabled) { disabled = p_disabled; } _FORCE_INLINE_ bool is_disabled() const { return disabled; } static PackedData *get_singleton() { return singleton; } - Error add_pack(const String& p_path); + Error add_pack(const String &p_path); - _FORCE_INLINE_ FileAccess *try_open_path(const String& p_path); - _FORCE_INLINE_ bool has_path(const String& p_path); + _FORCE_INLINE_ FileAccess *try_open_path(const String &p_path); + _FORCE_INLINE_ bool has_path(const String &p_path); PackedData(); ~PackedData(); @@ -119,21 +118,18 @@ public: class PackSource { public: - - virtual bool try_open_pack(const String& p_path)=0; - virtual FileAccess* get_file(const String& p_path, PackedData::PackedFile* p_file)=0; + virtual bool try_open_pack(const String &p_path) = 0; + virtual FileAccess *get_file(const String &p_path, PackedData::PackedFile *p_file) = 0; virtual ~PackSource() {} }; class PackedSourcePCK : public PackSource { public: - virtual bool try_open_pack(const String &p_path); - virtual FileAccess* get_file(const String& p_path, PackedData::PackedFile* p_file); + virtual FileAccess *get_file(const String &p_path, PackedData::PackedFile *p_file); }; - class FileAccessPack : public FileAccess { PackedData::PackedFile pf; @@ -142,17 +138,15 @@ class FileAccessPack : public FileAccess { mutable bool eof; FileAccess *f; - virtual Error _open(const String& p_path, int p_mode_flags); - virtual uint64_t _get_modified_time(const String& p_file) { return 0; } + virtual Error _open(const String &p_path, int p_mode_flags); + virtual uint64_t _get_modified_time(const String &p_file) { return 0; } public: - - virtual void close(); virtual bool is_open() const; virtual void seek(size_t p_position); - virtual void seek_end(int64_t p_position=0); + virtual void seek_end(int64_t p_position = 0); virtual size_t get_pos() const; virtual size_t get_len() const; @@ -160,8 +154,7 @@ public: virtual uint8_t get_8() const; - - virtual int get_buffer(uint8_t *p_dst,int p_length) const; + virtual int get_buffer(uint8_t *p_dst, int p_length) const; virtual void set_endian_swap(bool p_swap); @@ -169,38 +162,34 @@ public: virtual void store_8(uint8_t p_dest); - virtual void store_buffer(const uint8_t *p_src,int p_length); - - virtual bool file_exists(const String& p_name); + virtual void store_buffer(const uint8_t *p_src, int p_length); + virtual bool file_exists(const String &p_name); - FileAccessPack(const String& p_path, const PackedData::PackedFile& p_file); + FileAccessPack(const String &p_path, const PackedData::PackedFile &p_file); ~FileAccessPack(); }; - -FileAccess *PackedData::try_open_path(const String& p_path) { +FileAccess *PackedData::try_open_path(const String &p_path) { //print_line("try open path " + p_path); PathMD5 pmd5(p_path.md5_buffer()); - Map<PathMD5,PackedFile>::Element *E=files.find(pmd5); + Map<PathMD5, PackedFile>::Element *E = files.find(pmd5); if (!E) return NULL; //not found - if (E->get().offset==0) + if (E->get().offset == 0) return NULL; //was erased return E->get().src->get_file(p_path, &E->get()); } -bool PackedData::has_path(const String& p_path) { +bool PackedData::has_path(const String &p_path) { return files.has(PathMD5(p_path.md5_buffer())); } - class DirAccessPack : public DirAccess { - PackedData::PackedDir *current; List<String> list_dirs; @@ -208,7 +197,6 @@ class DirAccessPack : public DirAccess { bool cdir; public: - virtual Error list_dir_begin(); virtual String get_next(); virtual bool current_is_dir() const; @@ -221,7 +209,6 @@ public: virtual Error change_dir(String p_dir); virtual String get_current_dir(); - virtual bool file_exists(String p_file); virtual bool dir_exists(String p_dir); @@ -234,8 +221,6 @@ public: DirAccessPack(); ~DirAccessPack(); - }; - #endif // FILE_ACCESS_PACK_H diff --git a/core/io/file_access_zip.cpp b/core/io/file_access_zip.cpp index 87f07cb7b1..4cc2edd1c3 100644 --- a/core/io/file_access_zip.cpp +++ b/core/io/file_access_zip.cpp @@ -30,78 +30,75 @@ #include "file_access_zip.h" -#include "core/os/file_access.h" #include "core/os/copymem.h" +#include "core/os/file_access.h" -ZipArchive* ZipArchive::instance = NULL; +ZipArchive *ZipArchive::instance = NULL; extern "C" { -static void* godot_open(void* data, const char* p_fname, int mode) { +static void *godot_open(void *data, const char *p_fname, int mode) { if (mode & ZLIB_FILEFUNC_MODE_WRITE) { return NULL; }; - FileAccess* f = (FileAccess*)data; + FileAccess *f = (FileAccess *)data; f->open(p_fname, FileAccess::READ); - return f->is_open()?data:NULL; - + return f->is_open() ? data : NULL; }; -static uLong godot_read(void* data, void* fdata, void* buf, uLong size) { +static uLong godot_read(void *data, void *fdata, void *buf, uLong size) { - FileAccess* f = (FileAccess*)data; - f->get_buffer((uint8_t*)buf, size); + FileAccess *f = (FileAccess *)data; + f->get_buffer((uint8_t *)buf, size); return size; }; -static uLong godot_write(voidpf opaque, voidpf stream, const void* buf, uLong size) { +static uLong godot_write(voidpf opaque, voidpf stream, const void *buf, uLong size) { return 0; }; +static long godot_tell(voidpf opaque, voidpf stream) { -static long godot_tell (voidpf opaque, voidpf stream) { - - FileAccess* f = (FileAccess*)opaque; + FileAccess *f = (FileAccess *)opaque; return f->get_pos(); }; static long godot_seek(voidpf opaque, voidpf stream, uLong offset, int origin) { - FileAccess* f = (FileAccess*)opaque; + FileAccess *f = (FileAccess *)opaque; int pos = offset; switch (origin) { - case ZLIB_FILEFUNC_SEEK_CUR: - pos = f->get_pos() + offset; - break; - case ZLIB_FILEFUNC_SEEK_END: - pos = f->get_len() + offset; - break; - default: - break; + case ZLIB_FILEFUNC_SEEK_CUR: + pos = f->get_pos() + offset; + break; + case ZLIB_FILEFUNC_SEEK_END: + pos = f->get_len() + offset; + break; + default: + break; }; f->seek(pos); return 0; }; - static int godot_close(voidpf opaque, voidpf stream) { - FileAccess* f = (FileAccess*)opaque; + FileAccess *f = (FileAccess *)opaque; f->close(); return 0; }; static int godot_testerror(voidpf opaque, voidpf stream) { - FileAccess* f = (FileAccess*)opaque; - return f->get_error()!=OK?1:0; + FileAccess *f = (FileAccess *)opaque; + return f->get_error() != OK ? 1 : 0; }; static voidpf godot_alloc(voidpf opaque, uInt items, uInt size) { @@ -119,7 +116,7 @@ static void godot_free(voidpf opaque, voidpf address) { void ZipArchive::close_handle(unzFile p_file) const { ERR_FAIL_COND(!p_file); - FileAccess* f = (FileAccess*)unzGetOpaque(p_file); + FileAccess *f = (FileAccess *)unzGetOpaque(p_file); unzCloseCurrentFile(p_file); unzClose(p_file); memdelete(f); @@ -130,7 +127,7 @@ unzFile ZipArchive::get_file_handle(String p_file) const { ERR_FAIL_COND_V(!file_exists(p_file), NULL); File file = files[p_file]; - FileAccess* f = FileAccess::open(packages[file.package].filename, FileAccess::READ); + FileAccess *f = FileAccess::open(packages[file.package].filename, FileAccess::READ); ERR_FAIL_COND_V(!f, NULL); zlib_filefunc_def io; @@ -162,7 +159,7 @@ unzFile ZipArchive::get_file_handle(String p_file) const { return pkg; }; -bool ZipArchive::try_open_pack(const String& p_name) { +bool ZipArchive::try_open_pack(const String &p_name) { //printf("opening zip pack %ls, %i, %i\n", p_name.c_str(), p_name.extension().nocasecmp_to("zip"), p_name.extension().nocasecmp_to("pcz")); if (p_name.get_extension().nocasecmp_to("zip") != 0 && p_name.get_extension().nocasecmp_to("pcz") != 0) @@ -170,7 +167,7 @@ bool ZipArchive::try_open_pack(const String& p_name) { zlib_filefunc_def io; - FileAccess* f = FileAccess::open(p_name, FileAccess::READ); + FileAccess *f = FileAccess::open(p_name, FileAccess::READ); if (!f) return false; io.opaque = f; @@ -188,20 +185,20 @@ bool ZipArchive::try_open_pack(const String& p_name) { unz_global_info64 gi; int err = unzGetGlobalInfo64(zfile, &gi); - ERR_FAIL_COND_V(err!=UNZ_OK, false); + ERR_FAIL_COND_V(err != UNZ_OK, false); Package pkg; pkg.filename = p_name; pkg.zfile = zfile; packages.push_back(pkg); - int pkg_num = packages.size()-1; + int pkg_num = packages.size() - 1; - for (unsigned int i=0;i<gi.number_entry;i++) { + for (unsigned int i = 0; i < gi.number_entry; i++) { char filename_inzip[256]; unz_file_info64 file_info; - err = unzGetCurrentFileInfo64(zfile,&file_info,filename_inzip,sizeof(filename_inzip),NULL,0,NULL,0); + err = unzGetCurrentFileInfo64(zfile, &file_info, filename_inzip, sizeof(filename_inzip), NULL, 0, NULL, 0); ERR_CONTINUE(err != UNZ_OK); File f; @@ -211,11 +208,11 @@ bool ZipArchive::try_open_pack(const String& p_name) { String fname = String("res://") + filename_inzip; files[fname] = f; - uint8_t md5[16]={0,0,0,0,0,0,0,0 , 0,0,0,0,0,0,0,0}; + uint8_t md5[16] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; PackedData::get_singleton()->add_path(p_name, fname, 1, 0, md5, this); //printf("packed data add path %ls, %ls\n", p_name.c_str(), fname.c_str()); - if ((i+1)<gi.number_entry) { + if ((i + 1) < gi.number_entry) { unzGoToNextFile(zfile); }; }; @@ -228,13 +225,12 @@ bool ZipArchive::file_exists(String p_name) const { return files.has(p_name); }; -FileAccess* ZipArchive::get_file(const String& p_path, PackedData::PackedFile* p_file) { +FileAccess *ZipArchive::get_file(const String &p_path, PackedData::PackedFile *p_file) { return memnew(FileAccessZip(p_path, *p_file)); }; - -ZipArchive* ZipArchive::get_singleton() { +ZipArchive *ZipArchive::get_singleton() { if (instance == NULL) { instance = memnew(ZipArchive); @@ -251,9 +247,9 @@ ZipArchive::ZipArchive() { ZipArchive::~ZipArchive() { - for (int i=0; i<packages.size(); i++) { + for (int i = 0; i < packages.size(); i++) { - FileAccess* f = (FileAccess*)unzGetOpaque(packages[i].zfile); + FileAccess *f = (FileAccess *)unzGetOpaque(packages[i].zfile); unzClose(packages[i].zfile); memdelete(f); }; @@ -261,18 +257,17 @@ ZipArchive::~ZipArchive() { packages.clear(); }; - -Error FileAccessZip::_open(const String& p_path, int p_mode_flags) { +Error FileAccessZip::_open(const String &p_path, int p_mode_flags) { close(); ERR_FAIL_COND_V(p_mode_flags & FileAccess::WRITE, FAILED); - ZipArchive* arch = ZipArchive::get_singleton(); + ZipArchive *arch = ZipArchive::get_singleton(); ERR_FAIL_COND_V(!arch, FAILED); zfile = arch->get_file_handle(p_path); ERR_FAIL_COND_V(!zfile, FAILED); - int err = unzGetCurrentFileInfo64(zfile,&file_info,NULL,0,NULL,0,NULL,0); + int err = unzGetCurrentFileInfo64(zfile, &file_info, NULL, 0, NULL, 0, NULL, 0); ERR_FAIL_COND_V(err != UNZ_OK, FAILED); return OK; @@ -283,7 +278,7 @@ void FileAccessZip::close() { if (!zfile) return; - ZipArchive* arch = ZipArchive::get_singleton(); + ZipArchive *arch = ZipArchive::get_singleton(); ERR_FAIL_COND(!arch); arch->close_handle(zfile); zfile = NULL; @@ -332,7 +327,7 @@ uint8_t FileAccessZip::get_8() const { return ret; }; -int FileAccessZip::get_buffer(uint8_t *p_dst,int p_length) const { +int FileAccessZip::get_buffer(uint8_t *p_dst, int p_length) const { ERR_FAIL_COND_V(!zfile, -1); at_eof = unzeof(zfile); @@ -363,13 +358,12 @@ void FileAccessZip::store_8(uint8_t p_dest) { ERR_FAIL(); }; -bool FileAccessZip::file_exists(const String& p_name) { +bool FileAccessZip::file_exists(const String &p_name) { return false; }; - -FileAccessZip::FileAccessZip(const String& p_path, const PackedData::PackedFile& p_file) { +FileAccessZip::FileAccessZip(const String &p_path, const PackedData::PackedFile &p_file) { zfile = NULL; _open(p_path, FileAccess::READ); diff --git a/core/io/file_access_zip.h b/core/io/file_access_zip.h index e34bc1283a..7d5be8678d 100644 --- a/core/io/file_access_zip.h +++ b/core/io/file_access_zip.h @@ -31,15 +31,14 @@ #ifndef FILE_ACCESS_Zip_H #define FILE_ACCESS_Zip_H -#include <stdlib.h> #include "core/io/file_access_pack.h" -#include "unzip.h" #include "map.h" +#include "unzip.h" +#include <stdlib.h> class ZipArchive : public PackSource { public: - struct File { int package; @@ -50,23 +49,20 @@ public: }; }; - private: - struct Package { String filename; unzFile zfile; }; Vector<Package> packages; - Map<String,File> files; + Map<String, File> files; - static ZipArchive* instance; + static ZipArchive *instance; FileAccess::CreateFunc fa_create_func; public: - void close_handle(unzFile p_file) const; unzFile get_file_handle(String p_file) const; @@ -74,49 +70,47 @@ public: bool file_exists(String p_name) const; - virtual bool try_open_pack(const String& p_path); - FileAccess* get_file(const String& p_path, PackedData::PackedFile* p_file); + virtual bool try_open_pack(const String &p_path); + FileAccess *get_file(const String &p_path, PackedData::PackedFile *p_file); - static ZipArchive* get_singleton(); + static ZipArchive *get_singleton(); ZipArchive(); ~ZipArchive(); }; - class FileAccessZip : public FileAccess { unzFile zfile; - unz_file_info64 file_info; + unz_file_info64 file_info; mutable bool at_eof; - ZipArchive* archive; + ZipArchive *archive; public: - - virtual Error _open(const String& p_path, int p_mode_flags); ///< open a file + virtual Error _open(const String &p_path, int p_mode_flags); ///< open a file virtual void close(); ///< close a file virtual bool is_open() const; ///< true when file is open virtual void seek(size_t p_position); ///< seek to a given position - virtual void seek_end(int64_t p_position=0); ///< seek from the end of file + virtual void seek_end(int64_t p_position = 0); ///< seek from the end of file virtual size_t get_pos() const; ///< get position in the file virtual size_t get_len() const; ///< get size of the file virtual bool eof_reached() const; ///< reading passed EOF virtual uint8_t get_8() const; ///< get a byte - virtual int get_buffer(uint8_t *p_dst,int p_length) const; + virtual int get_buffer(uint8_t *p_dst, int p_length) const; virtual Error get_error() const; ///< get last error virtual void store_8(uint8_t p_dest); ///< store a byte - virtual bool file_exists(const String& p_name); ///< return true if a file exists + virtual bool file_exists(const String &p_name); ///< return true if a file exists - virtual uint64_t _get_modified_time(const String& p_file) { return 0; } // todo + virtual uint64_t _get_modified_time(const String &p_file) { return 0; } // todo - FileAccessZip(const String& p_path, const PackedData::PackedFile& p_file); + FileAccessZip(const String &p_path, const PackedData::PackedFile &p_file); ~FileAccessZip(); }; diff --git a/core/io/http_client.cpp b/core/io/http_client.cpp index ae14f8fa38..be5309ddfa 100644 --- a/core/io/http_client.cpp +++ b/core/io/http_client.cpp @@ -29,52 +29,47 @@ #include "http_client.h" #include "io/stream_peer_ssl.h" -Error HTTPClient::connect_to_host(const String &p_host, int p_port, bool p_ssl,bool p_verify_host){ +Error HTTPClient::connect_to_host(const String &p_host, int p_port, bool p_ssl, bool p_verify_host) { close(); - conn_port=p_port; - conn_host=p_host; + conn_port = p_port; + conn_host = p_host; if (conn_host.begins_with("http://")) { - conn_host=conn_host.replace_first("http://",""); + conn_host = conn_host.replace_first("http://", ""); } else if (conn_host.begins_with("https://")) { //use https - conn_host=conn_host.replace_first("https://",""); + conn_host = conn_host.replace_first("https://", ""); } - - ssl=p_ssl; - ssl_verify_host=p_verify_host; - connection=tcp_connection; - - + ssl = p_ssl; + ssl_verify_host = p_verify_host; + connection = tcp_connection; if (conn_host.is_valid_ip_address()) { //is ip - Error err = tcp_connection->connect_to_host(IP_Address(conn_host),p_port); + Error err = tcp_connection->connect_to_host(IP_Address(conn_host), p_port); if (err) { - status=STATUS_CANT_CONNECT; + status = STATUS_CANT_CONNECT; return err; } - status=STATUS_CONNECTING; + status = STATUS_CONNECTING; } else { //is hostname - resolving=IP::get_singleton()->resolve_hostname_queue_item(conn_host); - status=STATUS_RESOLVING; - + resolving = IP::get_singleton()->resolve_hostname_queue_item(conn_host); + status = STATUS_RESOLVING; } return OK; } -void HTTPClient::set_connection(const Ref<StreamPeer>& p_connection){ +void HTTPClient::set_connection(const Ref<StreamPeer> &p_connection) { close(); - connection=p_connection; - status=STATUS_CONNECTED; - + connection = p_connection; + status = STATUS_CONNECTED; } Ref<StreamPeer> HTTPClient::get_connection() const { @@ -82,14 +77,13 @@ Ref<StreamPeer> HTTPClient::get_connection() const { return connection; } -Error HTTPClient::request_raw( Method p_method, const String& p_url, const Vector<String>& p_headers,const PoolVector<uint8_t>& p_body) { - - ERR_FAIL_INDEX_V(p_method,METHOD_MAX,ERR_INVALID_PARAMETER); - ERR_FAIL_COND_V(status!=STATUS_CONNECTED,ERR_INVALID_PARAMETER); - ERR_FAIL_COND_V(connection.is_null(),ERR_INVALID_DATA); +Error HTTPClient::request_raw(Method p_method, const String &p_url, const Vector<String> &p_headers, const PoolVector<uint8_t> &p_body) { + ERR_FAIL_INDEX_V(p_method, METHOD_MAX, ERR_INVALID_PARAMETER); + ERR_FAIL_COND_V(status != STATUS_CONNECTED, ERR_INVALID_PARAMETER); + ERR_FAIL_COND_V(connection.is_null(), ERR_INVALID_DATA); - static const char* _methods[METHOD_MAX]={ + static const char *_methods[METHOD_MAX] = { "GET", "HEAD", "POST", @@ -97,54 +91,54 @@ Error HTTPClient::request_raw( Method p_method, const String& p_url, const Vecto "DELETE", "OPTIONS", "TRACE", - "CONNECT"}; - - String request=String(_methods[p_method])+" "+p_url+" HTTP/1.1\r\n"; - request+="Host: "+conn_host+":"+itos(conn_port)+"\r\n"; - bool add_clen=p_body.size()>0; - for(int i=0;i<p_headers.size();i++) { - request+=p_headers[i]+"\r\n"; - if (add_clen && p_headers[i].find("Content-Length:")==0) { - add_clen=false; + "CONNECT" + }; + + String request = String(_methods[p_method]) + " " + p_url + " HTTP/1.1\r\n"; + request += "Host: " + conn_host + ":" + itos(conn_port) + "\r\n"; + bool add_clen = p_body.size() > 0; + for (int i = 0; i < p_headers.size(); i++) { + request += p_headers[i] + "\r\n"; + if (add_clen && p_headers[i].find("Content-Length:") == 0) { + add_clen = false; } } if (add_clen) { - request+="Content-Length: "+itos(p_body.size())+"\r\n"; + request += "Content-Length: " + itos(p_body.size()) + "\r\n"; //should it add utf8 encoding? not sure } - request+="\r\n"; - CharString cs=request.utf8(); + request += "\r\n"; + CharString cs = request.utf8(); PoolVector<uint8_t> data; //Maybe this goes faster somehow? - for(int i=0;i<cs.length();i++) { - data.append( cs[i] ); + for (int i = 0; i < cs.length(); i++) { + data.append(cs[i]); } - data.append_array( p_body ); + data.append_array(p_body); PoolVector<uint8_t>::Read r = data.read(); Error err = connection->put_data(&r[0], data.size()); if (err) { close(); - status=STATUS_CONNECTION_ERROR; + status = STATUS_CONNECTION_ERROR; return err; } - status=STATUS_REQUESTING; + status = STATUS_REQUESTING; return OK; } -Error HTTPClient::request( Method p_method, const String& p_url, const Vector<String>& p_headers,const String& p_body) { +Error HTTPClient::request(Method p_method, const String &p_url, const Vector<String> &p_headers, const String &p_body) { - ERR_FAIL_INDEX_V(p_method,METHOD_MAX,ERR_INVALID_PARAMETER); - ERR_FAIL_COND_V(status!=STATUS_CONNECTED,ERR_INVALID_PARAMETER); - ERR_FAIL_COND_V(connection.is_null(),ERR_INVALID_DATA); + ERR_FAIL_INDEX_V(p_method, METHOD_MAX, ERR_INVALID_PARAMETER); + ERR_FAIL_COND_V(status != STATUS_CONNECTED, ERR_INVALID_PARAMETER); + ERR_FAIL_COND_V(connection.is_null(), ERR_INVALID_DATA); - - static const char* _methods[METHOD_MAX]={ + static const char *_methods[METHOD_MAX] = { "GET", "HEAD", "POST", @@ -152,50 +146,51 @@ Error HTTPClient::request( Method p_method, const String& p_url, const Vector<St "DELETE", "OPTIONS", "TRACE", - "CONNECT"}; - - String request=String(_methods[p_method])+" "+p_url+" HTTP/1.1\r\n"; - request+="Host: "+conn_host+":"+itos(conn_port)+"\r\n"; - bool add_clen=p_body.length()>0; - for(int i=0;i<p_headers.size();i++) { - request+=p_headers[i]+"\r\n"; - if (add_clen && p_headers[i].find("Content-Length:")==0) { - add_clen=false; + "CONNECT" + }; + + String request = String(_methods[p_method]) + " " + p_url + " HTTP/1.1\r\n"; + request += "Host: " + conn_host + ":" + itos(conn_port) + "\r\n"; + bool add_clen = p_body.length() > 0; + for (int i = 0; i < p_headers.size(); i++) { + request += p_headers[i] + "\r\n"; + if (add_clen && p_headers[i].find("Content-Length:") == 0) { + add_clen = false; } } if (add_clen) { - request+="Content-Length: "+itos(p_body.utf8().length())+"\r\n"; + request += "Content-Length: " + itos(p_body.utf8().length()) + "\r\n"; //should it add utf8 encoding? not sure } - request+="\r\n"; - request+=p_body; + request += "\r\n"; + request += p_body; - CharString cs=request.utf8(); - Error err = connection->put_data((const uint8_t*)cs.ptr(),cs.length()); + CharString cs = request.utf8(); + Error err = connection->put_data((const uint8_t *)cs.ptr(), cs.length()); if (err) { close(); - status=STATUS_CONNECTION_ERROR; + status = STATUS_CONNECTION_ERROR; return err; } - status=STATUS_REQUESTING; + status = STATUS_REQUESTING; return OK; } -Error HTTPClient::send_body_text(const String& p_body){ +Error HTTPClient::send_body_text(const String &p_body) { return OK; } -Error HTTPClient::send_body_data(const PoolByteArray& p_body){ +Error HTTPClient::send_body_data(const PoolByteArray &p_body) { return OK; } bool HTTPClient::has_response() const { - return response_headers.size()!=0; + return response_headers.size() != 0; } bool HTTPClient::is_response_chunked() const { @@ -213,7 +208,7 @@ Error HTTPClient::get_response_headers(List<String> *r_response) { if (!response_headers.size()) return ERR_INVALID_PARAMETER; - for(int i=0;i<response_headers.size();i++) { + for (int i = 0; i < response_headers.size(); i++) { r_response->push_back(response_headers[i]); } @@ -223,71 +218,67 @@ Error HTTPClient::get_response_headers(List<String> *r_response) { return OK; } +void HTTPClient::close() { -void HTTPClient::close(){ - - if (tcp_connection->get_status()!=StreamPeerTCP::STATUS_NONE) + if (tcp_connection->get_status() != StreamPeerTCP::STATUS_NONE) tcp_connection->disconnect_from_host(); connection.unref(); - status=STATUS_DISCONNECTED; - if (resolving!=IP::RESOLVER_INVALID_ID) { + status = STATUS_DISCONNECTED; + if (resolving != IP::RESOLVER_INVALID_ID) { IP::get_singleton()->erase_resolve_item(resolving); - resolving=IP::RESOLVER_INVALID_ID; - + resolving = IP::RESOLVER_INVALID_ID; } response_headers.clear(); response_str.clear(); - body_size=0; - body_left=0; - chunk_left=0; - response_num=0; + body_size = 0; + body_left = 0; + chunk_left = 0; + response_num = 0; } +Error HTTPClient::poll() { -Error HTTPClient::poll(){ - - switch(status) { - + switch (status) { case STATUS_RESOLVING: { - ERR_FAIL_COND_V(resolving==IP::RESOLVER_INVALID_ID,ERR_BUG); + ERR_FAIL_COND_V(resolving == IP::RESOLVER_INVALID_ID, ERR_BUG); IP::ResolverStatus rstatus = IP::get_singleton()->get_resolve_item_status(resolving); - switch(rstatus) { - case IP::RESOLVER_STATUS_WAITING: return OK; //still resolving + switch (rstatus) { + case IP::RESOLVER_STATUS_WAITING: + return OK; //still resolving case IP::RESOLVER_STATUS_DONE: { IP_Address host = IP::get_singleton()->get_resolve_item_address(resolving); - Error err = tcp_connection->connect_to_host(host,conn_port); + Error err = tcp_connection->connect_to_host(host, conn_port); IP::get_singleton()->erase_resolve_item(resolving); - resolving=IP::RESOLVER_INVALID_ID; + resolving = IP::RESOLVER_INVALID_ID; if (err) { - status=STATUS_CANT_CONNECT; + status = STATUS_CANT_CONNECT; return err; } - status=STATUS_CONNECTING; + status = STATUS_CONNECTING; } break; case IP::RESOLVER_STATUS_NONE: case IP::RESOLVER_STATUS_ERROR: { IP::get_singleton()->erase_resolve_item(resolving); - resolving=IP::RESOLVER_INVALID_ID; + resolving = IP::RESOLVER_INVALID_ID; close(); - status=STATUS_CANT_RESOLVE; + status = STATUS_CANT_RESOLVE; return ERR_CANT_RESOLVE; } break; - } } break; case STATUS_CONNECTING: { StreamPeerTCP::Status s = tcp_connection->get_status(); - switch(s) { + switch (s) { case StreamPeerTCP::STATUS_CONNECTING: { return OK; //do none @@ -295,23 +286,23 @@ Error HTTPClient::poll(){ case StreamPeerTCP::STATUS_CONNECTED: { if (ssl) { Ref<StreamPeerSSL> ssl = StreamPeerSSL::create(); - Error err = ssl->connect_to_stream(tcp_connection,true,ssl_verify_host?conn_host:String()); - if (err!=OK) { + Error err = ssl->connect_to_stream(tcp_connection, true, ssl_verify_host ? conn_host : String()); + if (err != OK) { close(); - status=STATUS_SSL_HANDSHAKE_ERROR; + status = STATUS_SSL_HANDSHAKE_ERROR; return ERR_CANT_CONNECT; } //print_line("SSL! TURNED ON!"); - connection=ssl; + connection = ssl; } - status=STATUS_CONNECTED; + status = STATUS_CONNECTED; return OK; } break; case StreamPeerTCP::STATUS_ERROR: case StreamPeerTCP::STATUS_NONE: { close(); - status=STATUS_CANT_CONNECT; + status = STATUS_CANT_CONNECT; return ERR_CANT_CONNECT; } break; } @@ -322,78 +313,73 @@ Error HTTPClient::poll(){ } break; case STATUS_REQUESTING: { - - while(true) { + while (true) { uint8_t byte; - int rec=0; - Error err = _get_http_data(&byte,1,rec); - if (err!=OK) { + int rec = 0; + Error err = _get_http_data(&byte, 1, rec); + if (err != OK) { close(); - status=STATUS_CONNECTION_ERROR; + status = STATUS_CONNECTION_ERROR; return ERR_CONNECTION_ERROR; } - if (rec==0) + if (rec == 0) return OK; //keep trying! response_str.push_back(byte); int rs = response_str.size(); if ( - (rs>=2 && response_str[rs-2]=='\n' && response_str[rs-1]=='\n') || - (rs>=4 && response_str[rs-4]=='\r' && response_str[rs-3]=='\n' && response_str[rs-2]=='\r' && response_str[rs-1]=='\n') - ) { - + (rs >= 2 && response_str[rs - 2] == '\n' && response_str[rs - 1] == '\n') || + (rs >= 4 && response_str[rs - 4] == '\r' && response_str[rs - 3] == '\n' && response_str[rs - 2] == '\r' && response_str[rs - 1] == '\n')) { //end of response, parse. response_str.push_back(0); String response; - response.parse_utf8((const char*)response_str.ptr()); + response.parse_utf8((const char *)response_str.ptr()); //print_line("END OF RESPONSE? :\n"+response+"\n------"); Vector<String> responses = response.split("\n"); - body_size=0; - chunked=false; - body_left=0; - chunk_left=0; + body_size = 0; + chunked = false; + body_left = 0; + chunk_left = 0; response_str.clear(); response_headers.clear(); response_num = RESPONSE_OK; - for(int i=0;i<responses.size();i++) { + for (int i = 0; i < responses.size(); i++) { String header = responses[i].strip_edges(); String s = header.to_lower(); - if (s.length()==0) + if (s.length() == 0) continue; if (s.begins_with("content-length:")) { - body_size = s.substr(s.find(":")+1,s.length()).strip_edges().to_int(); - body_left=body_size; + body_size = s.substr(s.find(":") + 1, s.length()).strip_edges().to_int(); + body_left = body_size; } if (s.begins_with("transfer-encoding:")) { - String encoding = header.substr(header.find(":")+1,header.length()).strip_edges(); + String encoding = header.substr(header.find(":") + 1, header.length()).strip_edges(); //print_line("TRANSFER ENCODING: "+encoding); - if (encoding=="chunked") { - chunked=true; + if (encoding == "chunked") { + chunked = true; } - } - if (i==0 && responses[i].begins_with("HTTP")) { + if (i == 0 && responses[i].begins_with("HTTP")) { - String num = responses[i].get_slicec(' ',1); - response_num=num.to_int(); + String num = responses[i].get_slicec(' ', 1); + response_num = num.to_int(); } else { response_headers.push_back(header); } - } - if (body_size==0 && !chunked) { + if (body_size == 0 && !chunked) { - status=STATUS_CONNECTED; //ask for something again? + status = STATUS_CONNECTED; //ask for something again? } else { - status=STATUS_BODY; + status = STATUS_BODY; } return OK; } @@ -415,25 +401,22 @@ Error HTTPClient::poll(){ } break; } - return OK; } - Dictionary HTTPClient::_get_response_headers_as_dictionary() { List<String> rh; get_response_headers(&rh); Dictionary ret; - for(const List<String>::Element *E=rh.front();E;E=E->next()) { + for (const List<String>::Element *E = rh.front(); E; E = E->next()) { String s = E->get(); int sp = s.find(":"); - if (sp==-1) + if (sp == -1) continue; - String key = s.substr(0,sp).strip_edges(); - String value = s.substr(sp+1,s.length()).strip_edges(); - ret[key]=value; - + String key = s.substr(0, sp).strip_edges(); + String value = s.substr(sp + 1, s.length()).strip_edges(); + ret[key] = value; } return ret; @@ -445,9 +428,9 @@ PoolStringArray HTTPClient::_get_response_headers() { get_response_headers(&rh); PoolStringArray ret; ret.resize(rh.size()); - int idx=0; - for(const List<String>::Element *E=rh.front();E;E=E->next()) { - ret.set(idx++,E->get()); + int idx = 0; + for (const List<String>::Element *E = rh.front(); E; E = E->next()) { + ret.set(idx++, E->get()); } return ret; @@ -460,96 +443,93 @@ int HTTPClient::get_response_body_length() const { PoolByteArray HTTPClient::read_response_body_chunk() { - ERR_FAIL_COND_V( status !=STATUS_BODY, PoolByteArray() ); + ERR_FAIL_COND_V(status != STATUS_BODY, PoolByteArray()); - Error err=OK; + Error err = OK; if (chunked) { - while(true) { + while (true) { - if (chunk_left==0) { + if (chunk_left == 0) { //reading len uint8_t b; - int rec=0; - err = _get_http_data(&b,1,rec); + int rec = 0; + err = _get_http_data(&b, 1, rec); - if (rec==0) + if (rec == 0) break; chunk.push_back(b); - if (chunk.size()>32) { + if (chunk.size() > 32) { ERR_PRINT("HTTP Invalid chunk hex len"); - status=STATUS_CONNECTION_ERROR; + status = STATUS_CONNECTION_ERROR; return PoolByteArray(); } - if (chunk.size()>2 && chunk[chunk.size()-2]=='\r' && chunk[chunk.size()-1]=='\n') { + if (chunk.size() > 2 && chunk[chunk.size() - 2] == '\r' && chunk[chunk.size() - 1] == '\n') { - int len=0; - for(int i=0;i<chunk.size()-2;i++) { + int len = 0; + for (int i = 0; i < chunk.size() - 2; i++) { char c = chunk[i]; - int v=0; - if (c>='0' && c<='9') - v=c-'0'; - else if (c>='a' && c<='f') - v=c-'a'+10; - else if (c>='A' && c<='F') - v=c-'A'+10; + int v = 0; + if (c >= '0' && c <= '9') + v = c - '0'; + else if (c >= 'a' && c <= 'f') + v = c - 'a' + 10; + else if (c >= 'A' && c <= 'F') + v = c - 'A' + 10; else { ERR_PRINT("HTTP Chunk len not in hex!!"); - status=STATUS_CONNECTION_ERROR; + status = STATUS_CONNECTION_ERROR; return PoolByteArray(); } - len<<=4; - len|=v; - if (len>(1<<24)) { + len <<= 4; + len |= v; + if (len > (1 << 24)) { ERR_PRINT("HTTP Chunk too big!! >16mb"); - status=STATUS_CONNECTION_ERROR; + status = STATUS_CONNECTION_ERROR; return PoolByteArray(); } - } - if (len==0) { + if (len == 0) { //end! - status=STATUS_CONNECTED; + status = STATUS_CONNECTED; chunk.clear(); return PoolByteArray(); } - chunk_left=len+2; + chunk_left = len + 2; chunk.resize(chunk_left); - } } else { - int rec=0; - err = _get_http_data(&chunk[chunk.size()-chunk_left],chunk_left,rec); - if (rec==0) { + int rec = 0; + err = _get_http_data(&chunk[chunk.size() - chunk_left], chunk_left, rec); + if (rec == 0) { break; } - chunk_left-=rec; + chunk_left -= rec; - if (chunk_left==0) { + if (chunk_left == 0) { - if (chunk[chunk.size()-2]!='\r' || chunk[chunk.size()-1]!='\n') { + if (chunk[chunk.size() - 2] != '\r' || chunk[chunk.size() - 1] != '\n') { ERR_PRINT("HTTP Invalid chunk terminator (not \\r\\n)"); - status=STATUS_CONNECTION_ERROR; + status = STATUS_CONNECTION_ERROR; return PoolByteArray(); } PoolByteArray ret; - ret.resize(chunk.size()-2); + ret.resize(chunk.size() - 2); { PoolByteArray::Write w = ret.write(); - copymem(w.ptr(),chunk.ptr(),chunk.size()-2); + copymem(w.ptr(), chunk.ptr(), chunk.size() - 2); } chunk.clear(); return ret; - } break; @@ -558,46 +538,44 @@ PoolByteArray HTTPClient::read_response_body_chunk() { } else { - int to_read = MIN(body_left,read_chunk_size); + int to_read = MIN(body_left, read_chunk_size); PoolByteArray ret; ret.resize(to_read); int _offset = 0; while (to_read > 0) { - int rec=0; + int rec = 0; { PoolByteArray::Write w = ret.write(); - err = _get_http_data(w.ptr()+_offset,to_read,rec); + err = _get_http_data(w.ptr() + _offset, to_read, rec); } - if (rec>0) { - body_left-=rec; - to_read-=rec; + if (rec > 0) { + body_left -= rec; + to_read -= rec; _offset += rec; } else { - if (to_read>0) //ended up reading less + if (to_read > 0) //ended up reading less ret.resize(_offset); break; } } - if (body_left==0) { - status=STATUS_CONNECTED; + if (body_left == 0) { + status = STATUS_CONNECTED; } return ret; - } - - if (err!=OK) { + if (err != OK) { close(); - if (err==ERR_FILE_EOF) { + if (err == ERR_FILE_EOF) { - status=STATUS_DISCONNECTED; //server disconnected + status = STATUS_DISCONNECTED; //server disconnected } else { - status=STATUS_CONNECTION_ERROR; + status = STATUS_CONNECTION_ERROR; } - } else if (body_left==0 && !chunked) { + } else if (body_left == 0 && !chunked) { - status=STATUS_CONNECTED; + status = STATUS_CONNECTED; } return PoolByteArray(); @@ -605,179 +583,172 @@ PoolByteArray HTTPClient::read_response_body_chunk() { HTTPClient::Status HTTPClient::get_status() const { - return status; } void HTTPClient::set_blocking_mode(bool p_enable) { - blocking=p_enable; + blocking = p_enable; } -bool HTTPClient::is_blocking_mode_enabled() const{ +bool HTTPClient::is_blocking_mode_enabled() const { return blocking; } -Error HTTPClient::_get_http_data(uint8_t* p_buffer, int p_bytes,int &r_received) { +Error HTTPClient::_get_http_data(uint8_t *p_buffer, int p_bytes, int &r_received) { if (blocking) { - Error err = connection->get_data(p_buffer,p_bytes); - if (err==OK) - r_received=p_bytes; + Error err = connection->get_data(p_buffer, p_bytes); + if (err == OK) + r_received = p_bytes; else - r_received=0; + r_received = 0; return err; } else { - return connection->get_partial_data(p_buffer,p_bytes,r_received); + return connection->get_partial_data(p_buffer, p_bytes, r_received); } } void HTTPClient::_bind_methods() { - ClassDB::bind_method(D_METHOD("connect_to_host:Error","host","port","use_ssl","verify_host"),&HTTPClient::connect_to_host,DEFVAL(false),DEFVAL(true)); - ClassDB::bind_method(D_METHOD("set_connection","connection:StreamPeer"),&HTTPClient::set_connection); - ClassDB::bind_method(D_METHOD("get_connection:StreamPeer"),&HTTPClient::get_connection); - ClassDB::bind_method(D_METHOD("request_raw","method","url","headers","body"),&HTTPClient::request_raw); - ClassDB::bind_method(D_METHOD("request","method","url","headers","body"),&HTTPClient::request,DEFVAL(String())); - ClassDB::bind_method(D_METHOD("send_body_text","body"),&HTTPClient::send_body_text); - ClassDB::bind_method(D_METHOD("send_body_data","body"),&HTTPClient::send_body_data); - ClassDB::bind_method(D_METHOD("close"),&HTTPClient::close); - - ClassDB::bind_method(D_METHOD("has_response"),&HTTPClient::has_response); - ClassDB::bind_method(D_METHOD("is_response_chunked"),&HTTPClient::is_response_chunked); - ClassDB::bind_method(D_METHOD("get_response_code"),&HTTPClient::get_response_code); - ClassDB::bind_method(D_METHOD("get_response_headers"),&HTTPClient::_get_response_headers); - ClassDB::bind_method(D_METHOD("get_response_headers_as_dictionary"),&HTTPClient::_get_response_headers_as_dictionary); - ClassDB::bind_method(D_METHOD("get_response_body_length"),&HTTPClient::get_response_body_length); - ClassDB::bind_method(D_METHOD("read_response_body_chunk"),&HTTPClient::read_response_body_chunk); - ClassDB::bind_method(D_METHOD("set_read_chunk_size","bytes"),&HTTPClient::set_read_chunk_size); - - ClassDB::bind_method(D_METHOD("set_blocking_mode","enabled"),&HTTPClient::set_blocking_mode); - ClassDB::bind_method(D_METHOD("is_blocking_mode_enabled"),&HTTPClient::is_blocking_mode_enabled); - - ClassDB::bind_method(D_METHOD("get_status"),&HTTPClient::get_status); - ClassDB::bind_method(D_METHOD("poll:Error"),&HTTPClient::poll); - - ClassDB::bind_method(D_METHOD("query_string_from_dict:String","fields"),&HTTPClient::query_string_from_dict); - - - BIND_CONSTANT( METHOD_GET ); - BIND_CONSTANT( METHOD_HEAD ); - BIND_CONSTANT( METHOD_POST ); - BIND_CONSTANT( METHOD_PUT ); - BIND_CONSTANT( METHOD_DELETE ); - BIND_CONSTANT( METHOD_OPTIONS ); - BIND_CONSTANT( METHOD_TRACE ); - BIND_CONSTANT( METHOD_CONNECT ); - BIND_CONSTANT( METHOD_MAX ); - - BIND_CONSTANT( STATUS_DISCONNECTED ); - BIND_CONSTANT( STATUS_RESOLVING ); //resolving hostname (if passed a hostname) - BIND_CONSTANT( STATUS_CANT_RESOLVE ); - BIND_CONSTANT( STATUS_CONNECTING ); //connecting to ip - BIND_CONSTANT( STATUS_CANT_CONNECT ); - BIND_CONSTANT( STATUS_CONNECTED ); //connected ); requests only accepted here - BIND_CONSTANT( STATUS_REQUESTING ); // request in progress - BIND_CONSTANT( STATUS_BODY ); // request resulted in body ); which must be read - BIND_CONSTANT( STATUS_CONNECTION_ERROR ); - BIND_CONSTANT( STATUS_SSL_HANDSHAKE_ERROR ); - - - BIND_CONSTANT( RESPONSE_CONTINUE ); - BIND_CONSTANT( RESPONSE_SWITCHING_PROTOCOLS ); - BIND_CONSTANT( RESPONSE_PROCESSING ); + ClassDB::bind_method(D_METHOD("connect_to_host:Error", "host", "port", "use_ssl", "verify_host"), &HTTPClient::connect_to_host, DEFVAL(false), DEFVAL(true)); + ClassDB::bind_method(D_METHOD("set_connection", "connection:StreamPeer"), &HTTPClient::set_connection); + ClassDB::bind_method(D_METHOD("get_connection:StreamPeer"), &HTTPClient::get_connection); + ClassDB::bind_method(D_METHOD("request_raw", "method", "url", "headers", "body"), &HTTPClient::request_raw); + ClassDB::bind_method(D_METHOD("request", "method", "url", "headers", "body"), &HTTPClient::request, DEFVAL(String())); + ClassDB::bind_method(D_METHOD("send_body_text", "body"), &HTTPClient::send_body_text); + ClassDB::bind_method(D_METHOD("send_body_data", "body"), &HTTPClient::send_body_data); + ClassDB::bind_method(D_METHOD("close"), &HTTPClient::close); + + ClassDB::bind_method(D_METHOD("has_response"), &HTTPClient::has_response); + ClassDB::bind_method(D_METHOD("is_response_chunked"), &HTTPClient::is_response_chunked); + ClassDB::bind_method(D_METHOD("get_response_code"), &HTTPClient::get_response_code); + ClassDB::bind_method(D_METHOD("get_response_headers"), &HTTPClient::_get_response_headers); + ClassDB::bind_method(D_METHOD("get_response_headers_as_dictionary"), &HTTPClient::_get_response_headers_as_dictionary); + ClassDB::bind_method(D_METHOD("get_response_body_length"), &HTTPClient::get_response_body_length); + ClassDB::bind_method(D_METHOD("read_response_body_chunk"), &HTTPClient::read_response_body_chunk); + ClassDB::bind_method(D_METHOD("set_read_chunk_size", "bytes"), &HTTPClient::set_read_chunk_size); + + ClassDB::bind_method(D_METHOD("set_blocking_mode", "enabled"), &HTTPClient::set_blocking_mode); + ClassDB::bind_method(D_METHOD("is_blocking_mode_enabled"), &HTTPClient::is_blocking_mode_enabled); + + ClassDB::bind_method(D_METHOD("get_status"), &HTTPClient::get_status); + ClassDB::bind_method(D_METHOD("poll:Error"), &HTTPClient::poll); + + ClassDB::bind_method(D_METHOD("query_string_from_dict:String", "fields"), &HTTPClient::query_string_from_dict); + + BIND_CONSTANT(METHOD_GET); + BIND_CONSTANT(METHOD_HEAD); + BIND_CONSTANT(METHOD_POST); + BIND_CONSTANT(METHOD_PUT); + BIND_CONSTANT(METHOD_DELETE); + BIND_CONSTANT(METHOD_OPTIONS); + BIND_CONSTANT(METHOD_TRACE); + BIND_CONSTANT(METHOD_CONNECT); + BIND_CONSTANT(METHOD_MAX); + + BIND_CONSTANT(STATUS_DISCONNECTED); + BIND_CONSTANT(STATUS_RESOLVING); //resolving hostname (if passed a hostname) + BIND_CONSTANT(STATUS_CANT_RESOLVE); + BIND_CONSTANT(STATUS_CONNECTING); //connecting to ip + BIND_CONSTANT(STATUS_CANT_CONNECT); + BIND_CONSTANT(STATUS_CONNECTED); //connected ); requests only accepted here + BIND_CONSTANT(STATUS_REQUESTING); // request in progress + BIND_CONSTANT(STATUS_BODY); // request resulted in body ); which must be read + BIND_CONSTANT(STATUS_CONNECTION_ERROR); + BIND_CONSTANT(STATUS_SSL_HANDSHAKE_ERROR); + + BIND_CONSTANT(RESPONSE_CONTINUE); + BIND_CONSTANT(RESPONSE_SWITCHING_PROTOCOLS); + BIND_CONSTANT(RESPONSE_PROCESSING); // 2xx successful - BIND_CONSTANT( RESPONSE_OK ); - BIND_CONSTANT( RESPONSE_CREATED ); - BIND_CONSTANT( RESPONSE_ACCEPTED ); - BIND_CONSTANT( RESPONSE_NON_AUTHORITATIVE_INFORMATION ); - BIND_CONSTANT( RESPONSE_NO_CONTENT ); - BIND_CONSTANT( RESPONSE_RESET_CONTENT ); - BIND_CONSTANT( RESPONSE_PARTIAL_CONTENT ); - BIND_CONSTANT( RESPONSE_MULTI_STATUS ); - BIND_CONSTANT( RESPONSE_IM_USED ); + BIND_CONSTANT(RESPONSE_OK); + BIND_CONSTANT(RESPONSE_CREATED); + BIND_CONSTANT(RESPONSE_ACCEPTED); + BIND_CONSTANT(RESPONSE_NON_AUTHORITATIVE_INFORMATION); + BIND_CONSTANT(RESPONSE_NO_CONTENT); + BIND_CONSTANT(RESPONSE_RESET_CONTENT); + BIND_CONSTANT(RESPONSE_PARTIAL_CONTENT); + BIND_CONSTANT(RESPONSE_MULTI_STATUS); + BIND_CONSTANT(RESPONSE_IM_USED); // 3xx redirection - BIND_CONSTANT( RESPONSE_MULTIPLE_CHOICES ); - BIND_CONSTANT( RESPONSE_MOVED_PERMANENTLY ); - BIND_CONSTANT( RESPONSE_FOUND ); - BIND_CONSTANT( RESPONSE_SEE_OTHER ); - BIND_CONSTANT( RESPONSE_NOT_MODIFIED ); - BIND_CONSTANT( RESPONSE_USE_PROXY ); - BIND_CONSTANT( RESPONSE_TEMPORARY_REDIRECT ); + BIND_CONSTANT(RESPONSE_MULTIPLE_CHOICES); + BIND_CONSTANT(RESPONSE_MOVED_PERMANENTLY); + BIND_CONSTANT(RESPONSE_FOUND); + BIND_CONSTANT(RESPONSE_SEE_OTHER); + BIND_CONSTANT(RESPONSE_NOT_MODIFIED); + BIND_CONSTANT(RESPONSE_USE_PROXY); + BIND_CONSTANT(RESPONSE_TEMPORARY_REDIRECT); // 4xx client error - BIND_CONSTANT( RESPONSE_BAD_REQUEST ); - BIND_CONSTANT( RESPONSE_UNAUTHORIZED ); - BIND_CONSTANT( RESPONSE_PAYMENT_REQUIRED ); - BIND_CONSTANT( RESPONSE_FORBIDDEN ); - BIND_CONSTANT( RESPONSE_NOT_FOUND ); - BIND_CONSTANT( RESPONSE_METHOD_NOT_ALLOWED ); - BIND_CONSTANT( RESPONSE_NOT_ACCEPTABLE ); - BIND_CONSTANT( RESPONSE_PROXY_AUTHENTICATION_REQUIRED ); - BIND_CONSTANT( RESPONSE_REQUEST_TIMEOUT ); - BIND_CONSTANT( RESPONSE_CONFLICT ); - BIND_CONSTANT( RESPONSE_GONE ); - BIND_CONSTANT( RESPONSE_LENGTH_REQUIRED ); - BIND_CONSTANT( RESPONSE_PRECONDITION_FAILED ); - BIND_CONSTANT( RESPONSE_REQUEST_ENTITY_TOO_LARGE ); - BIND_CONSTANT( RESPONSE_REQUEST_URI_TOO_LONG ); - BIND_CONSTANT( RESPONSE_UNSUPPORTED_MEDIA_TYPE ); - BIND_CONSTANT( RESPONSE_REQUESTED_RANGE_NOT_SATISFIABLE ); - BIND_CONSTANT( RESPONSE_EXPECTATION_FAILED ); - BIND_CONSTANT( RESPONSE_UNPROCESSABLE_ENTITY ); - BIND_CONSTANT( RESPONSE_LOCKED ); - BIND_CONSTANT( RESPONSE_FAILED_DEPENDENCY ); - BIND_CONSTANT( RESPONSE_UPGRADE_REQUIRED ); + BIND_CONSTANT(RESPONSE_BAD_REQUEST); + BIND_CONSTANT(RESPONSE_UNAUTHORIZED); + BIND_CONSTANT(RESPONSE_PAYMENT_REQUIRED); + BIND_CONSTANT(RESPONSE_FORBIDDEN); + BIND_CONSTANT(RESPONSE_NOT_FOUND); + BIND_CONSTANT(RESPONSE_METHOD_NOT_ALLOWED); + BIND_CONSTANT(RESPONSE_NOT_ACCEPTABLE); + BIND_CONSTANT(RESPONSE_PROXY_AUTHENTICATION_REQUIRED); + BIND_CONSTANT(RESPONSE_REQUEST_TIMEOUT); + BIND_CONSTANT(RESPONSE_CONFLICT); + BIND_CONSTANT(RESPONSE_GONE); + BIND_CONSTANT(RESPONSE_LENGTH_REQUIRED); + BIND_CONSTANT(RESPONSE_PRECONDITION_FAILED); + BIND_CONSTANT(RESPONSE_REQUEST_ENTITY_TOO_LARGE); + BIND_CONSTANT(RESPONSE_REQUEST_URI_TOO_LONG); + BIND_CONSTANT(RESPONSE_UNSUPPORTED_MEDIA_TYPE); + BIND_CONSTANT(RESPONSE_REQUESTED_RANGE_NOT_SATISFIABLE); + BIND_CONSTANT(RESPONSE_EXPECTATION_FAILED); + BIND_CONSTANT(RESPONSE_UNPROCESSABLE_ENTITY); + BIND_CONSTANT(RESPONSE_LOCKED); + BIND_CONSTANT(RESPONSE_FAILED_DEPENDENCY); + BIND_CONSTANT(RESPONSE_UPGRADE_REQUIRED); // 5xx server error - BIND_CONSTANT( RESPONSE_INTERNAL_SERVER_ERROR ); - BIND_CONSTANT( RESPONSE_NOT_IMPLEMENTED ); - BIND_CONSTANT( RESPONSE_BAD_GATEWAY ); - BIND_CONSTANT( RESPONSE_SERVICE_UNAVAILABLE ); - BIND_CONSTANT( RESPONSE_GATEWAY_TIMEOUT ); - BIND_CONSTANT( RESPONSE_HTTP_VERSION_NOT_SUPPORTED ); - BIND_CONSTANT( RESPONSE_INSUFFICIENT_STORAGE ); - BIND_CONSTANT( RESPONSE_NOT_EXTENDED ); - + BIND_CONSTANT(RESPONSE_INTERNAL_SERVER_ERROR); + BIND_CONSTANT(RESPONSE_NOT_IMPLEMENTED); + BIND_CONSTANT(RESPONSE_BAD_GATEWAY); + BIND_CONSTANT(RESPONSE_SERVICE_UNAVAILABLE); + BIND_CONSTANT(RESPONSE_GATEWAY_TIMEOUT); + BIND_CONSTANT(RESPONSE_HTTP_VERSION_NOT_SUPPORTED); + BIND_CONSTANT(RESPONSE_INSUFFICIENT_STORAGE); + BIND_CONSTANT(RESPONSE_NOT_EXTENDED); } void HTTPClient::set_read_chunk_size(int p_size) { - ERR_FAIL_COND(p_size<256 || p_size>(1<<24)); - read_chunk_size=p_size; + ERR_FAIL_COND(p_size < 256 || p_size > (1 << 24)); + read_chunk_size = p_size; } -String HTTPClient::query_string_from_dict(const Dictionary& p_dict) { - String query = ""; - Array keys = p_dict.keys(); - for (int i = 0; i < keys.size(); ++i) { - query += "&" + String(keys[i]).http_escape() + "=" + String(p_dict[keys[i]]).http_escape(); - } - query.erase(0, 1); - return query; +String HTTPClient::query_string_from_dict(const Dictionary &p_dict) { + String query = ""; + Array keys = p_dict.keys(); + for (int i = 0; i < keys.size(); ++i) { + query += "&" + String(keys[i]).http_escape() + "=" + String(p_dict[keys[i]]).http_escape(); + } + query.erase(0, 1); + return query; } -HTTPClient::HTTPClient(){ +HTTPClient::HTTPClient() { tcp_connection = StreamPeerTCP::create_ref(); resolving = IP::RESOLVER_INVALID_ID; - status=STATUS_DISCONNECTED; - conn_port=80; - body_size=0; - chunked=false; - body_left=0; - chunk_left=0; - response_num=0; - ssl=false; - blocking=false; - read_chunk_size=4096; + status = STATUS_DISCONNECTED; + conn_port = 80; + body_size = 0; + chunked = false; + body_left = 0; + chunk_left = 0; + response_num = 0; + ssl = false; + blocking = false; + read_chunk_size = 4096; } -HTTPClient::~HTTPClient(){ - - +HTTPClient::~HTTPClient() { } - diff --git a/core/io/http_client.h b/core/io/http_client.h index 4b0c1b730f..e2b0e9ccea 100644 --- a/core/io/http_client.h +++ b/core/io/http_client.h @@ -29,17 +29,16 @@ #ifndef HTTP_CLIENT_H #define HTTP_CLIENT_H +#include "io/ip.h" #include "io/stream_peer.h" #include "io/stream_peer_tcp.h" -#include "io/ip.h" #include "reference.h" - class HTTPClient : public Reference { - GDCLASS(HTTPClient,Reference); -public: + GDCLASS(HTTPClient, Reference); +public: enum ResponseCode { // 1xx informational @@ -131,7 +130,6 @@ public: }; private: - Status status; IP::ResolverID resolving; int conn_port; @@ -159,21 +157,19 @@ private: Dictionary _get_response_headers_as_dictionary(); int read_chunk_size; - Error _get_http_data(uint8_t* p_buffer, int p_bytes,int &r_received); + Error _get_http_data(uint8_t *p_buffer, int p_bytes, int &r_received); public: - - //Error connect_and_get(const String& p_url,bool p_verify_host=true); //connects to a full url and perform request - Error connect_to_host(const String &p_host,int p_port,bool p_ssl=false,bool p_verify_host=true); + Error connect_to_host(const String &p_host, int p_port, bool p_ssl = false, bool p_verify_host = true); - void set_connection(const Ref<StreamPeer>& p_connection); + void set_connection(const Ref<StreamPeer> &p_connection); Ref<StreamPeer> get_connection() const; - Error request_raw( Method p_method, const String& p_url, const Vector<String>& p_headers,const PoolVector<uint8_t>& p_body); - Error request( Method p_method, const String& p_url, const Vector<String>& p_headers,const String& p_body=String()); - Error send_body_text(const String& p_body); - Error send_body_data(const PoolByteArray& p_body); + Error request_raw(Method p_method, const String &p_url, const Vector<String> &p_headers, const PoolVector<uint8_t> &p_body); + Error request(Method p_method, const String &p_url, const Vector<String> &p_headers, const String &p_body = String()); + Error send_body_text(const String &p_body); + Error send_body_data(const PoolByteArray &p_body); void close(); @@ -194,7 +190,7 @@ public: Error poll(); - String query_string_from_dict(const Dictionary& p_dict); + String query_string_from_dict(const Dictionary &p_dict); HTTPClient(); ~HTTPClient(); diff --git a/core/io/image_loader.cpp b/core/io/image_loader.cpp index 2b01e865f4..5f88ca65e3 100644 --- a/core/io/image_loader.cpp +++ b/core/io/image_loader.cpp @@ -29,90 +29,78 @@ #include "image_loader.h" #include "print_string.h" -bool ImageFormatLoader::recognize(const String& p_extension) const { - +bool ImageFormatLoader::recognize(const String &p_extension) const { List<String> extensions; get_recognized_extensions(&extensions); - for (List<String>::Element *E=extensions.front();E;E=E->next()) { + for (List<String>::Element *E = extensions.front(); E; E = E->next()) { - if (E->get().nocasecmp_to(p_extension.get_extension())==0) + if (E->get().nocasecmp_to(p_extension.get_extension()) == 0) return true; } return false; } -Error ImageLoader::load_image(String p_file,Image *p_image, FileAccess *p_custom) { - +Error ImageLoader::load_image(String p_file, Image *p_image, FileAccess *p_custom) { - FileAccess *f=p_custom; + FileAccess *f = p_custom; if (!f) { Error err; - f=FileAccess::open(p_file,FileAccess::READ,&err); + f = FileAccess::open(p_file, FileAccess::READ, &err); if (!f) { - ERR_PRINTS("Error opening file: "+p_file); + ERR_PRINTS("Error opening file: " + p_file); return err; } } String extension = p_file.get_extension(); - - for (int i=0;i<loader_count;i++) { + for (int i = 0; i < loader_count; i++) { if (!loader[i]->recognize(extension)) continue; - Error err = loader[i]->load_image(p_image,f); - - if (err!=ERR_FILE_UNRECOGNIZED) { + Error err = loader[i]->load_image(p_image, f); + if (err != ERR_FILE_UNRECOGNIZED) { if (!p_custom) memdelete(f); return err; } - - } if (!p_custom) memdelete(f); return ERR_FILE_UNRECOGNIZED; - } void ImageLoader::get_recognized_extensions(List<String> *p_extensions) { - for (int i=0;i<loader_count;i++) { + for (int i = 0; i < loader_count; i++) { loader[i]->get_recognized_extensions(p_extensions); - } } -bool ImageLoader::recognize(const String& p_extension) { +bool ImageLoader::recognize(const String &p_extension) { - for (int i=0;i<loader_count;i++) { + for (int i = 0; i < loader_count; i++) { if (loader[i]->recognize(p_extension)) return true; - } return false; } ImageFormatLoader *ImageLoader::loader[MAX_LOADERS]; -int ImageLoader::loader_count=0; +int ImageLoader::loader_count = 0; void ImageLoader::add_image_format_loader(ImageFormatLoader *p_loader) { - ERR_FAIL_COND(loader_count >=MAX_LOADERS ); - loader[loader_count++]=p_loader; + ERR_FAIL_COND(loader_count >= MAX_LOADERS); + loader[loader_count++] = p_loader; } - - - diff --git a/core/io/image_loader.h b/core/io/image_loader.h index 4de7706ab0..b70170303d 100644 --- a/core/io/image_loader.h +++ b/core/io/image_loader.h @@ -30,14 +30,13 @@ #define IMAGE_LOADER_H #include "image.h" -#include "ustring.h" -#include "os/file_access.h" #include "list.h" +#include "os/file_access.h" +#include "ustring.h" /** @author Juan Linietsky <reduzio@gmail.com> */ - /** * @class ImageScanLineLoader * @author Juan Linietsky <reduzio@gmail.com> @@ -46,21 +45,19 @@ */ class ImageLoader; - /** * @class ImageLoader * Base Class and singleton for loading images from disk * Can load images in one go, or by scanline */ - class ImageFormatLoader { -friend class ImageLoader; -protected: - virtual Error load_image(Image *p_image,FileAccess *p_fileaccess)=0; - virtual void get_recognized_extensions(List<String> *p_extensions) const=0; - bool recognize(const String& p_extension) const; + friend class ImageLoader; +protected: + virtual Error load_image(Image *p_image, FileAccess *p_fileaccess) = 0; + virtual void get_recognized_extensions(List<String> *p_extensions) const = 0; + bool recognize(const String &p_extension) const; public: virtual ~ImageFormatLoader() {} @@ -69,23 +66,19 @@ public: class ImageLoader { enum { - MAX_LOADERS=8 + MAX_LOADERS = 8 }; static ImageFormatLoader *loader[MAX_LOADERS]; static int loader_count; protected: - - public: - - static Error load_image(String p_file,Image *p_image, FileAccess *p_custom=NULL); - static void get_recognized_extensions(List<String> *p_extensions) ; - static bool recognize(const String& p_extension) ; + static Error load_image(String p_file, Image *p_image, FileAccess *p_custom = NULL); + static void get_recognized_extensions(List<String> *p_extensions); + static bool recognize(const String &p_extension); static void add_image_format_loader(ImageFormatLoader *p_loader); - }; #endif diff --git a/core/io/ip.cpp b/core/io/ip.cpp index d820273a14..6713963495 100644 --- a/core/io/ip.cpp +++ b/core/io/ip.cpp @@ -27,15 +27,14 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "ip.h" -#include "os/thread.h" -#include "os/semaphore.h" #include "hash_map.h" +#include "os/semaphore.h" +#include "os/thread.h" VARIANT_ENUM_CAST(IP::ResolverStatus); /************* RESOLVER ******************/ - struct _IP_ResolverPrivate { struct QueueItem { @@ -49,7 +48,7 @@ struct _IP_ResolverPrivate { status = IP::RESOLVER_STATUS_NONE; response = IP_Address(); type = IP::TYPE_NONE; - hostname=""; + hostname = ""; }; QueueItem() { @@ -61,8 +60,8 @@ struct _IP_ResolverPrivate { IP::ResolverID find_empty_id() const { - for(int i=0;i<IP::RESOLVER_MAX_QUERIES;i++) { - if (queue[i].status==IP::RESOLVER_STATUS_NONE) + for (int i = 0; i < IP::RESOLVER_MAX_QUERIES; i++) { + if (queue[i].status == IP::RESOLVER_STATUS_NONE) return i; } return IP::RESOLVER_INVALID_ID; @@ -70,39 +69,35 @@ struct _IP_ResolverPrivate { Semaphore *sem; - Thread* thread; + Thread *thread; //Semaphore* semaphore; bool thread_abort; void resolve_queues() { - for(int i=0;i<IP::RESOLVER_MAX_QUERIES;i++) { + for (int i = 0; i < IP::RESOLVER_MAX_QUERIES; i++) { - if (queue[i].status!=IP::RESOLVER_STATUS_WAITING) + if (queue[i].status != IP::RESOLVER_STATUS_WAITING) continue; - queue[i].response=IP::get_singleton()->resolve_hostname(queue[i].hostname, queue[i].type); + queue[i].response = IP::get_singleton()->resolve_hostname(queue[i].hostname, queue[i].type); if (!queue[i].response.is_valid()) - queue[i].status=IP::RESOLVER_STATUS_ERROR; + queue[i].status = IP::RESOLVER_STATUS_ERROR; else - queue[i].status=IP::RESOLVER_STATUS_DONE; - + queue[i].status = IP::RESOLVER_STATUS_DONE; } } - static void _thread_function(void *self) { - _IP_ResolverPrivate *ipr=(_IP_ResolverPrivate*)self; + _IP_ResolverPrivate *ipr = (_IP_ResolverPrivate *)self; - while(!ipr->thread_abort) { + while (!ipr->thread_abort) { ipr->sem->wait(); GLOBAL_LOCK_FUNCTION; ipr->resolve_queues(); - } - } HashMap<String, IP_Address> cache; @@ -110,12 +105,9 @@ struct _IP_ResolverPrivate { static String get_cache_key(String p_hostname, IP::Type p_type) { return itos(p_type) + p_hostname; } - }; - - -IP_Address IP::resolve_hostname(const String& p_hostname, IP::Type p_type) { +IP_Address IP::resolve_hostname(const String &p_hostname, IP::Type p_type) { GLOBAL_LOCK_FUNCTION; @@ -124,30 +116,29 @@ IP_Address IP::resolve_hostname(const String& p_hostname, IP::Type p_type) { return resolver->cache[key]; IP_Address res = _resolve_hostname(p_hostname, p_type); - resolver->cache[key]=res; + resolver->cache[key] = res; return res; - } -IP::ResolverID IP::resolve_hostname_queue_item(const String& p_hostname, IP::Type p_type) { +IP::ResolverID IP::resolve_hostname_queue_item(const String &p_hostname, IP::Type p_type) { GLOBAL_LOCK_FUNCTION; ResolverID id = resolver->find_empty_id(); - if (id==RESOLVER_INVALID_ID) { + if (id == RESOLVER_INVALID_ID) { WARN_PRINT("Out of resolver queries"); return id; } String key = _IP_ResolverPrivate::get_cache_key(p_hostname, p_type); - resolver->queue[id].hostname=p_hostname; + resolver->queue[id].hostname = p_hostname; resolver->queue[id].type = p_type; if (resolver->cache.has(key)) { - resolver->queue[id].response=resolver->cache[key]; - resolver->queue[id].status=IP::RESOLVER_STATUS_DONE; + resolver->queue[id].response = resolver->cache[key]; + resolver->queue[id].status = IP::RESOLVER_STATUS_DONE; } else { - resolver->queue[id].response=IP_Address(); - resolver->queue[id].status=IP::RESOLVER_STATUS_WAITING; + resolver->queue[id].response = IP_Address(); + resolver->queue[id].status = IP::RESOLVER_STATUS_WAITING; if (resolver->thread) resolver->sem->post(); else @@ -159,37 +150,33 @@ IP::ResolverID IP::resolve_hostname_queue_item(const String& p_hostname, IP::Typ IP::ResolverStatus IP::get_resolve_item_status(ResolverID p_id) const { - ERR_FAIL_INDEX_V(p_id,IP::RESOLVER_MAX_QUERIES,IP::RESOLVER_STATUS_NONE); + ERR_FAIL_INDEX_V(p_id, IP::RESOLVER_MAX_QUERIES, IP::RESOLVER_STATUS_NONE); GLOBAL_LOCK_FUNCTION; - ERR_FAIL_COND_V(resolver->queue[p_id].status==IP::RESOLVER_STATUS_NONE,IP::RESOLVER_STATUS_NONE); + ERR_FAIL_COND_V(resolver->queue[p_id].status == IP::RESOLVER_STATUS_NONE, IP::RESOLVER_STATUS_NONE); return resolver->queue[p_id].status; - } IP_Address IP::get_resolve_item_address(ResolverID p_id) const { - ERR_FAIL_INDEX_V(p_id,IP::RESOLVER_MAX_QUERIES,IP_Address()); + ERR_FAIL_INDEX_V(p_id, IP::RESOLVER_MAX_QUERIES, IP_Address()); GLOBAL_LOCK_FUNCTION; - if (resolver->queue[p_id].status!=IP::RESOLVER_STATUS_DONE) { - ERR_EXPLAIN("Resolve of '"+resolver->queue[p_id].hostname+"'' didn't complete yet."); - ERR_FAIL_COND_V(resolver->queue[p_id].status!=IP::RESOLVER_STATUS_DONE,IP_Address()); + if (resolver->queue[p_id].status != IP::RESOLVER_STATUS_DONE) { + ERR_EXPLAIN("Resolve of '" + resolver->queue[p_id].hostname + "'' didn't complete yet."); + ERR_FAIL_COND_V(resolver->queue[p_id].status != IP::RESOLVER_STATUS_DONE, IP_Address()); } - return resolver->queue[p_id].response; - } void IP::erase_resolve_item(ResolverID p_id) { - ERR_FAIL_INDEX(p_id,IP::RESOLVER_MAX_QUERIES); + ERR_FAIL_INDEX(p_id, IP::RESOLVER_MAX_QUERIES); GLOBAL_LOCK_FUNCTION; - resolver->queue[p_id].status=IP::RESOLVER_STATUS_NONE; - + resolver->queue[p_id].status = IP::RESOLVER_STATUS_NONE; } void IP::clear_cache(const String &p_hostname) { @@ -209,7 +196,7 @@ Array IP::_get_local_addresses() const { Array addresses; List<IP_Address> ip_addresses; get_local_addresses(&ip_addresses); - for(List<IP_Address>::Element *E=ip_addresses.front();E;E=E->next()) { + for (List<IP_Address>::Element *E = ip_addresses.front(); E; E = E->next()) { addresses.push_back(E->get()); } @@ -218,87 +205,82 @@ Array IP::_get_local_addresses() const { void IP::_bind_methods() { - ClassDB::bind_method(D_METHOD("resolve_hostname","host","ip_type"),&IP::resolve_hostname,DEFVAL(IP::TYPE_ANY)); - ClassDB::bind_method(D_METHOD("resolve_hostname_queue_item","host","ip_type"),&IP::resolve_hostname_queue_item,DEFVAL(IP::TYPE_ANY)); - ClassDB::bind_method(D_METHOD("get_resolve_item_status","id"),&IP::get_resolve_item_status); - ClassDB::bind_method(D_METHOD("get_resolve_item_address","id"),&IP::get_resolve_item_address); - ClassDB::bind_method(D_METHOD("erase_resolve_item","id"),&IP::erase_resolve_item); - ClassDB::bind_method(D_METHOD("get_local_addresses"),&IP::_get_local_addresses); - ClassDB::bind_method(D_METHOD("clear_cache"),&IP::clear_cache, DEFVAL("")); - - BIND_CONSTANT( RESOLVER_STATUS_NONE ); - BIND_CONSTANT( RESOLVER_STATUS_WAITING ); - BIND_CONSTANT( RESOLVER_STATUS_DONE ); - BIND_CONSTANT( RESOLVER_STATUS_ERROR ); - - BIND_CONSTANT( RESOLVER_MAX_QUERIES ); - BIND_CONSTANT( RESOLVER_INVALID_ID ); - - BIND_CONSTANT( TYPE_NONE ); - BIND_CONSTANT( TYPE_IPV4 ); - BIND_CONSTANT( TYPE_IPV6 ); - BIND_CONSTANT( TYPE_ANY ); + ClassDB::bind_method(D_METHOD("resolve_hostname", "host", "ip_type"), &IP::resolve_hostname, DEFVAL(IP::TYPE_ANY)); + ClassDB::bind_method(D_METHOD("resolve_hostname_queue_item", "host", "ip_type"), &IP::resolve_hostname_queue_item, DEFVAL(IP::TYPE_ANY)); + ClassDB::bind_method(D_METHOD("get_resolve_item_status", "id"), &IP::get_resolve_item_status); + ClassDB::bind_method(D_METHOD("get_resolve_item_address", "id"), &IP::get_resolve_item_address); + ClassDB::bind_method(D_METHOD("erase_resolve_item", "id"), &IP::erase_resolve_item); + ClassDB::bind_method(D_METHOD("get_local_addresses"), &IP::_get_local_addresses); + ClassDB::bind_method(D_METHOD("clear_cache"), &IP::clear_cache, DEFVAL("")); + + BIND_CONSTANT(RESOLVER_STATUS_NONE); + BIND_CONSTANT(RESOLVER_STATUS_WAITING); + BIND_CONSTANT(RESOLVER_STATUS_DONE); + BIND_CONSTANT(RESOLVER_STATUS_ERROR); + + BIND_CONSTANT(RESOLVER_MAX_QUERIES); + BIND_CONSTANT(RESOLVER_INVALID_ID); + + BIND_CONSTANT(TYPE_NONE); + BIND_CONSTANT(TYPE_IPV4); + BIND_CONSTANT(TYPE_IPV6); + BIND_CONSTANT(TYPE_ANY); } +IP *IP::singleton = NULL; -IP*IP::singleton=NULL; - -IP* IP::get_singleton() { +IP *IP::get_singleton() { return singleton; } +IP *(*IP::_create)() = NULL; -IP* (*IP::_create)()=NULL; +IP *IP::create() { -IP* IP::create() { - - ERR_FAIL_COND_V(singleton,NULL); - ERR_FAIL_COND_V(!_create,NULL); + ERR_FAIL_COND_V(singleton, NULL); + ERR_FAIL_COND_V(!_create, NULL); return _create(); } IP::IP() { - singleton=this; - resolver = memnew( _IP_ResolverPrivate ); - resolver->sem=NULL; + singleton = this; + resolver = memnew(_IP_ResolverPrivate); + resolver->sem = NULL; #ifndef NO_THREADS //resolver->sem = Semaphore::create(); - resolver->sem=NULL; + resolver->sem = NULL; if (resolver->sem) { - resolver->thread_abort=false; + resolver->thread_abort = false; - resolver->thread = Thread::create( _IP_ResolverPrivate::_thread_function,resolver ); + resolver->thread = Thread::create(_IP_ResolverPrivate::_thread_function, resolver); if (!resolver->thread) memdelete(resolver->sem); //wtf } else { - resolver->thread=NULL; + resolver->thread = NULL; } #else resolver->sem = NULL; - resolver->thread=NULL; + resolver->thread = NULL; #endif - - } IP::~IP() { #ifndef NO_THREADS if (resolver->thread) { - resolver->thread_abort=true; + resolver->thread_abort = true; resolver->sem->post(); Thread::wait_to_finish(resolver->thread); - memdelete( resolver->thread ); - memdelete( resolver->sem); + memdelete(resolver->thread); + memdelete(resolver->sem); } memdelete(resolver); #endif - } diff --git a/core/io/ip.h b/core/io/ip.h index 3e028f2613..052a0e08cc 100644 --- a/core/io/ip.h +++ b/core/io/ip.h @@ -29,17 +29,16 @@ #ifndef IP_H #define IP_H - -#include "os/os.h" #include "io/ip_address.h" +#include "os/os.h" struct _IP_ResolverPrivate; class IP : public Object { - GDCLASS( IP, Object ); + GDCLASS(IP, Object); OBJ_CATEGORY("Networking"); -public: +public: enum ResolverStatus { RESOLVER_STATUS_NONE, @@ -58,47 +57,40 @@ public: enum { RESOLVER_MAX_QUERIES = 32, - RESOLVER_INVALID_ID=-1 + RESOLVER_INVALID_ID = -1 }; - typedef int ResolverID; - private: - _IP_ResolverPrivate *resolver; -protected: - static IP*singleton; +protected: + static IP *singleton; static void _bind_methods(); - virtual IP_Address _resolve_hostname(const String& p_hostname, Type p_type = TYPE_ANY)=0; + virtual IP_Address _resolve_hostname(const String &p_hostname, Type p_type = TYPE_ANY) = 0; Array _get_local_addresses() const; - static IP* (*_create)(); -public: - + static IP *(*_create)(); - - IP_Address resolve_hostname(const String& p_hostname, Type p_type = TYPE_ANY); +public: + IP_Address resolve_hostname(const String &p_hostname, Type p_type = TYPE_ANY); // async resolver hostname - ResolverID resolve_hostname_queue_item(const String& p_hostname, Type p_type = TYPE_ANY); + ResolverID resolve_hostname_queue_item(const String &p_hostname, Type p_type = TYPE_ANY); ResolverStatus get_resolve_item_status(ResolverID p_id) const; IP_Address get_resolve_item_address(ResolverID p_id) const; - virtual void get_local_addresses(List<IP_Address> *r_addresses) const=0; + virtual void get_local_addresses(List<IP_Address> *r_addresses) const = 0; void erase_resolve_item(ResolverID p_id); - void clear_cache(const String& p_hostname = ""); + void clear_cache(const String &p_hostname = ""); - static IP* get_singleton(); + static IP *get_singleton(); - static IP* create(); + static IP *create(); IP(); ~IP(); - - }; VARIANT_ENUM_CAST(IP::Type); diff --git a/core/io/ip_address.cpp b/core/io/ip_address.cpp index 69c7df619d..fa0eab4f0d 100644 --- a/core/io/ip_address.cpp +++ b/core/io/ip_address.cpp @@ -33,32 +33,32 @@ IP_Address::operator Variant() const { return operator String(); }*/ -#include <string.h> #include <stdio.h> +#include <string.h> IP_Address::operator String() const { - if(!valid) + if (!valid) return ""; - if(is_ipv4()) + if (is_ipv4()) // IPv4 address mapped to IPv6 - return itos(field8[12])+"."+itos(field8[13])+"."+itos(field8[14])+"."+itos(field8[15]); + return itos(field8[12]) + "." + itos(field8[13]) + "." + itos(field8[14]) + "." + itos(field8[15]); String ret; - for (int i=0; i<8; i++) { + for (int i = 0; i < 8; i++) { if (i > 0) ret = ret + ":"; - uint16_t num = (field8[i*2] << 8) + field8[i*2+1]; + uint16_t num = (field8[i * 2] << 8) + field8[i * 2 + 1]; ret = ret + String::num_int64(num, 16); }; return ret; } -static void _parse_hex(const String& p_string, int p_start, uint8_t* p_dst) { +static void _parse_hex(const String &p_string, int p_start, uint8_t *p_dst) { uint16_t ret = 0; - for (int i=p_start; i<p_start + 4; i++) { + for (int i = p_start; i < p_start + 4; i++) { if (i >= p_string.length()) { break; @@ -87,17 +87,17 @@ static void _parse_hex(const String& p_string, int p_start, uint8_t* p_dst) { p_dst[1] = ret & 0xff; }; -void IP_Address::_parse_ipv6(const String& p_string) { +void IP_Address::_parse_ipv6(const String &p_string) { static const int parts_total = 8; - int parts[parts_total] = {0}; + int parts[parts_total] = { 0 }; int parts_count = 0; bool part_found = false; bool part_skip = false; bool part_ipv4 = false; int parts_idx = 0; - for (int i=0; i<p_string.length(); i++) { + for (int i = 0; i < p_string.length(); i++) { CharType c = p_string[i]; if (c == ':') { @@ -133,26 +133,25 @@ void IP_Address::_parse_ipv6(const String& p_string) { }; int idx = 0; - for (int i=0; i<parts_idx; i++) { + for (int i = 0; i < parts_idx; i++) { if (parts[i] == -1) { - for (int j=0; j<parts_extra; j++) { + for (int j = 0; j < parts_extra; j++) { field16[idx++] = 0; }; continue; }; if (part_ipv4 && i == parts_idx - 1) { - _parse_ipv4(p_string, parts[i], (uint8_t*)&field16[idx]); // should be the last one + _parse_ipv4(p_string, parts[i], (uint8_t *)&field16[idx]); // should be the last one } else { - _parse_hex(p_string, parts[i], (uint8_t*)&(field16[idx++])); + _parse_hex(p_string, parts[i], (uint8_t *)&(field16[idx++])); }; }; - }; -void IP_Address::_parse_ipv4(const String& p_string, int p_start, uint8_t* p_ret) { +void IP_Address::_parse_ipv4(const String &p_string, int p_start, uint8_t *p_ret) { String ip; if (p_start != 0) { @@ -162,12 +161,12 @@ void IP_Address::_parse_ipv4(const String& p_string, int p_start, uint8_t* p_ret }; int slices = ip.get_slice_count("."); - if (slices!=4) { - ERR_EXPLAIN("Invalid IP Address String: "+ip); + if (slices != 4) { + ERR_EXPLAIN("Invalid IP Address String: " + ip); ERR_FAIL(); } - for(int i=0;i<4;i++) { - p_ret[i]=ip.get_slicec('.',i).to_int(); + for (int i = 0; i < 4; i++) { + p_ret[i] = ip.get_slicec('.', i).to_int(); } }; @@ -178,34 +177,34 @@ void IP_Address::clear() { wildcard = false; }; -bool IP_Address::is_ipv4() const{ - return (field32[0]==0 && field32[1]==0 && field16[4]==0 && field16[5]==0xffff); +bool IP_Address::is_ipv4() const { + return (field32[0] == 0 && field32[1] == 0 && field16[4] == 0 && field16[5] == 0xffff); } -const uint8_t *IP_Address::get_ipv4() const{ - ERR_FAIL_COND_V(!is_ipv4(),0); +const uint8_t *IP_Address::get_ipv4() const { + ERR_FAIL_COND_V(!is_ipv4(), 0); return &(field8[12]); } void IP_Address::set_ipv4(const uint8_t *p_ip) { clear(); valid = true; - field16[5]=0xffff; - field32[3]=*((const uint32_t *)p_ip); + field16[5] = 0xffff; + field32[3] = *((const uint32_t *)p_ip); } -const uint8_t *IP_Address::get_ipv6() const{ +const uint8_t *IP_Address::get_ipv6() const { return field8; } void IP_Address::set_ipv6(const uint8_t *p_buf) { clear(); valid = true; - for (int i=0; i<16; i++) + for (int i = 0; i < 16; i++) field8[i] = p_buf[i]; } -IP_Address::IP_Address(const String& p_string) { +IP_Address::IP_Address(const String &p_string) { clear(); @@ -229,7 +228,7 @@ IP_Address::IP_Address(const String& p_string) { } } -_FORCE_INLINE_ static void _32_to_buf(uint8_t* p_dst, uint32_t p_n) { +_FORCE_INLINE_ static void _32_to_buf(uint8_t *p_dst, uint32_t p_n) { p_dst[0] = (p_n >> 24) & 0xff; p_dst[1] = (p_n >> 16) & 0xff; @@ -237,17 +236,17 @@ _FORCE_INLINE_ static void _32_to_buf(uint8_t* p_dst, uint32_t p_n) { p_dst[3] = (p_n >> 0) & 0xff; }; -IP_Address::IP_Address(uint32_t p_a,uint32_t p_b,uint32_t p_c,uint32_t p_d, bool is_v6) { +IP_Address::IP_Address(uint32_t p_a, uint32_t p_b, uint32_t p_c, uint32_t p_d, bool is_v6) { clear(); valid = true; if (!is_v6) { // Mapped to IPv6 - field16[5]=0xffff; - field8[12]=p_a; - field8[13]=p_b; - field8[14]=p_c; - field8[15]=p_d; + field16[5] = 0xffff; + field8[12] = p_a; + field8[13] = p_b; + field8[14] = p_c; + field8[15] = p_d; } else { _32_to_buf(&field8[0], p_a); @@ -255,5 +254,4 @@ IP_Address::IP_Address(uint32_t p_a,uint32_t p_b,uint32_t p_c,uint32_t p_d, bool _32_to_buf(&field8[8], p_c); _32_to_buf(&field8[12], p_d); } - } diff --git a/core/io/ip_address.h b/core/io/ip_address.h index 257836601a..52d6974d5e 100644 --- a/core/io/ip_address.h +++ b/core/io/ip_address.h @@ -34,7 +34,6 @@ struct IP_Address { private: - union { uint8_t field8[16]; uint16_t field16[8]; @@ -45,31 +44,31 @@ private: bool wildcard; protected: - void _parse_ipv6(const String& p_string); - void _parse_ipv4(const String& p_string, int p_start, uint8_t* p_ret); + void _parse_ipv6(const String &p_string); + void _parse_ipv4(const String &p_string, int p_start, uint8_t *p_ret); public: //operator Variant() const; - bool operator==(const IP_Address& p_ip) const { + bool operator==(const IP_Address &p_ip) const { if (p_ip.valid != valid) return false; if (!valid) return false; - for (int i=0; i<4; i++) + for (int i = 0; i < 4; i++) if (field32[i] != p_ip.field32[i]) return false; return true; } - bool operator!=(const IP_Address& p_ip) const { + bool operator!=(const IP_Address &p_ip) const { if (p_ip.valid != valid) return true; if (!valid) return true; - for (int i=0; i<4; i++) + for (int i = 0; i < 4; i++) if (field32[i] != p_ip.field32[i]) return true; return false; } void clear(); - bool is_wildcard() const {return wildcard;} - bool is_valid() const {return valid;} + bool is_wildcard() const { return wildcard; } + bool is_valid() const { return valid; } bool is_ipv4() const; const uint8_t *get_ipv4() const; void set_ipv4(const uint8_t *p_ip); @@ -78,11 +77,9 @@ public: void set_ipv6(const uint8_t *buf); operator String() const; - IP_Address(const String& p_string); - IP_Address(uint32_t p_a,uint32_t p_b,uint32_t p_c,uint32_t p_d, bool is_v6=false); + IP_Address(const String &p_string); + IP_Address(uint32_t p_a, uint32_t p_b, uint32_t p_c, uint32_t p_d, bool is_v6 = false); IP_Address() { clear(); } }; - - #endif // IP_ADDRESS_H diff --git a/core/io/json.cpp b/core/io/json.cpp index 5ade25aab4..98d48ce4ae 100644 --- a/core/io/json.cpp +++ b/core/io/json.cpp @@ -29,7 +29,7 @@ #include "json.h" #include "print_string.h" -const char * JSON::tk_name[TK_MAX] = { +const char *JSON::tk_name[TK_MAX] = { "'{'", "'}'", "'['", @@ -42,14 +42,12 @@ const char * JSON::tk_name[TK_MAX] = { "EOF", }; +String JSON::_print_var(const Variant &p_var) { - -String JSON::_print_var(const Variant& p_var) { - - switch(p_var.get_type()) { + switch (p_var.get_type()) { case Variant::NIL: return "null"; - case Variant::BOOL: return p_var.operator bool() ? "true": "false"; + case Variant::BOOL: return p_var.operator bool() ? "true" : "false"; case Variant::INT: return itos(p_var); case Variant::REAL: return rtos(p_var); case Variant::POOL_INT_ARRAY: @@ -59,12 +57,12 @@ String JSON::_print_var(const Variant& p_var) { String s = "["; Array a = p_var; - for(int i=0;i<a.size();i++) { - if (i>0) - s+=", "; - s+=_print_var(a[i]); + for (int i = 0; i < a.size(); i++) { + if (i > 0) + s += ", "; + s += _print_var(a[i]); } - s+="]"; + s += "]"; return s; }; case Variant::DICTIONARY: { @@ -74,34 +72,31 @@ String JSON::_print_var(const Variant& p_var) { List<Variant> keys; d.get_key_list(&keys); - for (List<Variant>::Element *E=keys.front();E;E=E->next()) { + for (List<Variant>::Element *E = keys.front(); E; E = E->next()) { - if (E!=keys.front()) - s+=", "; - s+=_print_var(String(E->get())); - s+=":"; - s+=_print_var(d[E->get()]); + if (E != keys.front()) + s += ", "; + s += _print_var(String(E->get())); + s += ":"; + s += _print_var(d[E->get()]); } - s+="}"; + s += "}"; return s; }; - default: return "\""+String(p_var).json_escape()+"\""; - + default: return "\"" + String(p_var).json_escape() + "\""; } - } -String JSON::print(const Variant& p_var) { +String JSON::print(const Variant &p_var) { return _print_var(p_var); } - -Error JSON::_get_token(const CharType *p_str, int &idx, int p_len, Token& r_token,int &line,String &r_err_str) { +Error JSON::_get_token(const CharType *p_str, int &idx, int p_len, Token &r_token, int &line, String &r_err_str) { while (p_len > 0) { - switch(p_str[idx]) { + switch (p_str[idx]) { case '\n': { @@ -110,42 +105,42 @@ Error JSON::_get_token(const CharType *p_str, int &idx, int p_len, Token& r_toke break; }; case 0: { - r_token.type=TK_EOF; + r_token.type = TK_EOF; return OK; } break; case '{': { - r_token.type=TK_CURLY_BRACKET_OPEN; + r_token.type = TK_CURLY_BRACKET_OPEN; idx++; return OK; }; case '}': { - r_token.type=TK_CURLY_BRACKET_CLOSE; + r_token.type = TK_CURLY_BRACKET_CLOSE; idx++; return OK; }; case '[': { - r_token.type=TK_BRACKET_OPEN; + r_token.type = TK_BRACKET_OPEN; idx++; return OK; }; case ']': { - r_token.type=TK_BRACKET_CLOSE; + r_token.type = TK_BRACKET_CLOSE; idx++; return OK; }; case ':': { - r_token.type=TK_COLON; + r_token.type = TK_COLON; idx++; return OK; }; case ',': { - r_token.type=TK_COMMA; + r_token.type = TK_COMMA; idx++; return OK; }; @@ -153,66 +148,62 @@ Error JSON::_get_token(const CharType *p_str, int &idx, int p_len, Token& r_toke idx++; String str; - while(true) { - if (p_str[idx]==0) { - r_err_str="Unterminated String"; + while (true) { + if (p_str[idx] == 0) { + r_err_str = "Unterminated String"; return ERR_PARSE_ERROR; - } else if (p_str[idx]=='"') { + } else if (p_str[idx] == '"') { idx++; break; - } else if (p_str[idx]=='\\') { + } else if (p_str[idx] == '\\') { //escaped characters... idx++; CharType next = p_str[idx]; - if (next==0) { - r_err_str="Unterminated String"; - return ERR_PARSE_ERROR; + if (next == 0) { + r_err_str = "Unterminated String"; + return ERR_PARSE_ERROR; } - CharType res=0; + CharType res = 0; - switch(next) { + switch (next) { - case 'b': res=8; break; - case 't': res=9; break; - case 'n': res=10; break; - case 'f': res=12; break; - case 'r': res=13; break; + case 'b': res = 8; break; + case 't': res = 9; break; + case 'n': res = 10; break; + case 'f': res = 12; break; + case 'r': res = 13; break; case 'u': { //hexnumbarh - oct is deprecated - - for(int j=0;j<4;j++) { - CharType c = p_str[idx+j+1]; - if (c==0) { - r_err_str="Unterminated String"; + for (int j = 0; j < 4; j++) { + CharType c = p_str[idx + j + 1]; + if (c == 0) { + r_err_str = "Unterminated String"; return ERR_PARSE_ERROR; } - if (!((c>='0' && c<='9') || (c>='a' && c<='f') || (c>='A' && c<='F'))) { + if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'))) { - r_err_str="Malformed hex constant in string"; + r_err_str = "Malformed hex constant in string"; return ERR_PARSE_ERROR; } CharType v; - if (c>='0' && c<='9') { - v=c-'0'; - } else if (c>='a' && c<='f') { - v=c-'a'; - v+=10; - } else if (c>='A' && c<='F') { - v=c-'A'; - v+=10; + if (c >= '0' && c <= '9') { + v = c - '0'; + } else if (c >= 'a' && c <= 'f') { + v = c - 'a'; + v += 10; + } else if (c >= 'A' && c <= 'F') { + v = c - 'A'; + v += 10; } else { ERR_PRINT("BUG"); - v=0; + v = 0; } - res<<=4; - res|=v; - - + res <<= 4; + res |= v; } - idx+=4; //will add at the end anyway - + idx += 4; //will add at the end anyway } break; //case '\"': res='\"'; break; @@ -225,250 +216,232 @@ Error JSON::_get_token(const CharType *p_str, int &idx, int p_len, Token& r_toke } break; } - str+=res; + str += res; } else { - if (p_str[idx]=='\n') + if (p_str[idx] == '\n') line++; - str+=p_str[idx]; + str += p_str[idx]; } idx++; } - r_token.type=TK_STRING; - r_token.value=str; + r_token.type = TK_STRING; + r_token.value = str; return OK; } break; default: { - if (p_str[idx]<=32) { + if (p_str[idx] <= 32) { idx++; break; } - if (p_str[idx]=='-' || (p_str[idx]>='0' && p_str[idx]<='9')) { + if (p_str[idx] == '-' || (p_str[idx] >= '0' && p_str[idx] <= '9')) { //a number const CharType *rptr; - double number = String::to_double(&p_str[idx],&rptr); - idx+=(rptr - &p_str[idx]); - r_token.type=TK_NUMBER; - r_token.value=number; + double number = String::to_double(&p_str[idx], &rptr); + idx += (rptr - &p_str[idx]); + r_token.type = TK_NUMBER; + r_token.value = number; return OK; - } else if ((p_str[idx]>='A' && p_str[idx]<='Z') || (p_str[idx]>='a' && p_str[idx]<='z')) { + } else if ((p_str[idx] >= 'A' && p_str[idx] <= 'Z') || (p_str[idx] >= 'a' && p_str[idx] <= 'z')) { String id; - while((p_str[idx]>='A' && p_str[idx]<='Z') || (p_str[idx]>='a' && p_str[idx]<='z')) { + while ((p_str[idx] >= 'A' && p_str[idx] <= 'Z') || (p_str[idx] >= 'a' && p_str[idx] <= 'z')) { - id+=p_str[idx]; + id += p_str[idx]; idx++; } - r_token.type=TK_IDENTIFIER; - r_token.value=id; + r_token.type = TK_IDENTIFIER; + r_token.value = id; return OK; } else { - r_err_str="Unexpected character."; + r_err_str = "Unexpected character."; return ERR_PARSE_ERROR; } } - } } return ERR_PARSE_ERROR; } +Error JSON::_parse_value(Variant &value, Token &token, const CharType *p_str, int &index, int p_len, int &line, String &r_err_str) { - -Error JSON::_parse_value(Variant &value,Token& token,const CharType *p_str,int &index, int p_len,int &line,String &r_err_str) { - - - if (token.type==TK_CURLY_BRACKET_OPEN) { + if (token.type == TK_CURLY_BRACKET_OPEN) { Dictionary d; - Error err = _parse_object(d,p_str,index,p_len,line,r_err_str); + Error err = _parse_object(d, p_str, index, p_len, line, r_err_str); if (err) return err; - value=d; + value = d; return OK; - } else if (token.type==TK_BRACKET_OPEN) { + } else if (token.type == TK_BRACKET_OPEN) { Array a; - Error err = _parse_array(a,p_str,index,p_len,line,r_err_str); + Error err = _parse_array(a, p_str, index, p_len, line, r_err_str); if (err) return err; - value=a; + value = a; return OK; - } else if (token.type==TK_IDENTIFIER) { + } else if (token.type == TK_IDENTIFIER) { String id = token.value; - if (id=="true") - value=true; - else if (id=="false") - value=false; - else if (id=="null") - value=Variant(); + if (id == "true") + value = true; + else if (id == "false") + value = false; + else if (id == "null") + value = Variant(); else { - r_err_str="Expected 'true','false' or 'null', got '"+id+"'."; + r_err_str = "Expected 'true','false' or 'null', got '" + id + "'."; return ERR_PARSE_ERROR; } return OK; - } else if (token.type==TK_NUMBER) { + } else if (token.type == TK_NUMBER) { - value=token.value; + value = token.value; return OK; - } else if (token.type==TK_STRING) { + } else if (token.type == TK_STRING) { - value=token.value; + value = token.value; return OK; } else { - r_err_str="Expected value, got "+String(tk_name[token.type])+"."; + r_err_str = "Expected value, got " + String(tk_name[token.type]) + "."; return ERR_PARSE_ERROR; } return ERR_PARSE_ERROR; } - -Error JSON::_parse_array(Array &array,const CharType *p_str,int &index, int p_len,int &line,String &r_err_str) { +Error JSON::_parse_array(Array &array, const CharType *p_str, int &index, int p_len, int &line, String &r_err_str) { Token token; - bool need_comma=false; - + bool need_comma = false; - while(index<p_len) { + while (index < p_len) { - Error err = _get_token(p_str,index,p_len,token,line,r_err_str); - if (err!=OK) + Error err = _get_token(p_str, index, p_len, token, line, r_err_str); + if (err != OK) return err; - if (token.type==TK_BRACKET_CLOSE) { + if (token.type == TK_BRACKET_CLOSE) { return OK; } if (need_comma) { - if (token.type!=TK_COMMA) { + if (token.type != TK_COMMA) { - r_err_str="Expected ','"; + r_err_str = "Expected ','"; return ERR_PARSE_ERROR; } else { - need_comma=false; + need_comma = false; continue; } } Variant v; - err = _parse_value(v,token,p_str,index,p_len,line,r_err_str); + err = _parse_value(v, token, p_str, index, p_len, line, r_err_str); if (err) return err; array.push_back(v); - need_comma=true; - + need_comma = true; } return ERR_PARSE_ERROR; - } -Error JSON::_parse_object(Dictionary &object,const CharType *p_str,int &index, int p_len,int &line,String &r_err_str) { +Error JSON::_parse_object(Dictionary &object, const CharType *p_str, int &index, int p_len, int &line, String &r_err_str) { - bool at_key=true; + bool at_key = true; String key; Token token; - bool need_comma=false; - - - while(index<p_len) { + bool need_comma = false; + while (index < p_len) { if (at_key) { - Error err = _get_token(p_str,index,p_len,token,line,r_err_str); - if (err!=OK) + Error err = _get_token(p_str, index, p_len, token, line, r_err_str); + if (err != OK) return err; - if (token.type==TK_CURLY_BRACKET_CLOSE) { + if (token.type == TK_CURLY_BRACKET_CLOSE) { return OK; } if (need_comma) { - if (token.type!=TK_COMMA) { + if (token.type != TK_COMMA) { - r_err_str="Expected '}' or ','"; + r_err_str = "Expected '}' or ','"; return ERR_PARSE_ERROR; } else { - need_comma=false; + need_comma = false; continue; } } - if (token.type!=TK_STRING) { - + if (token.type != TK_STRING) { - r_err_str="Expected key"; + r_err_str = "Expected key"; return ERR_PARSE_ERROR; } - key=token.value; - err = _get_token(p_str,index,p_len,token,line,r_err_str); - if (err!=OK) + key = token.value; + err = _get_token(p_str, index, p_len, token, line, r_err_str); + if (err != OK) return err; - if (token.type!=TK_COLON) { + if (token.type != TK_COLON) { - r_err_str="Expected ':'"; + r_err_str = "Expected ':'"; return ERR_PARSE_ERROR; } - at_key=false; + at_key = false; } else { - - Error err = _get_token(p_str,index,p_len,token,line,r_err_str); - if (err!=OK) + Error err = _get_token(p_str, index, p_len, token, line, r_err_str); + if (err != OK) return err; Variant v; - err = _parse_value(v,token,p_str,index,p_len,line,r_err_str); + err = _parse_value(v, token, p_str, index, p_len, line, r_err_str); if (err) return err; - object[key]=v; - need_comma=true; - at_key=true; + object[key] = v; + need_comma = true; + at_key = true; } } return ERR_PARSE_ERROR; } - -Error JSON::parse(const String& p_json, Variant &r_ret, String &r_err_str, int &r_err_line) { - +Error JSON::parse(const String &p_json, Variant &r_ret, String &r_err_str, int &r_err_line) { const CharType *str = p_json.ptr(); int idx = 0; int len = p_json.length(); Token token; - r_err_line=0; + r_err_line = 0; String aux_key; - Error err = _get_token(str,idx,len,token,r_err_line,r_err_str); + Error err = _get_token(str, idx, len, token, r_err_line, r_err_str); if (err) return err; - err = _parse_value(r_ret,token,str,idx,len,r_err_line,r_err_str); + err = _parse_value(r_ret, token, str, idx, len, r_err_line, r_err_str); return err; - - } - - diff --git a/core/io/json.h b/core/io/json.h index 97457d223e..afd97c85b5 100644 --- a/core/io/json.h +++ b/core/io/json.h @@ -29,11 +29,8 @@ #ifndef JSON_H #define JSON_H - - #include "variant.h" - class JSON { enum TokenType { @@ -64,18 +61,18 @@ class JSON { Variant value; }; - static const char * tk_name[TK_MAX]; + static const char *tk_name[TK_MAX]; - static String _print_var(const Variant& p_var); + static String _print_var(const Variant &p_var); - static Error _get_token(const CharType *p_str,int &index, int p_len,Token& r_token,int &line,String &r_err_str); - static Error _parse_value(Variant &value,Token& token,const CharType *p_str,int &index, int p_len,int &line,String &r_err_str); - static Error _parse_array(Array &array,const CharType *p_str,int &index, int p_len,int &line,String &r_err_str); - static Error _parse_object(Dictionary &object,const CharType *p_str,int &index, int p_len,int &line,String &r_err_str); + static Error _get_token(const CharType *p_str, int &index, int p_len, Token &r_token, int &line, String &r_err_str); + static Error _parse_value(Variant &value, Token &token, const CharType *p_str, int &index, int p_len, int &line, String &r_err_str); + static Error _parse_array(Array &array, const CharType *p_str, int &index, int p_len, int &line, String &r_err_str); + static Error _parse_object(Dictionary &object, const CharType *p_str, int &index, int p_len, int &line, String &r_err_str); public: static String print(const Variant &p_var); - static Error parse(const String& p_json,Variant& r_ret,String &r_err_str,int &r_err_line); + static Error parse(const String &p_json, Variant &r_ret, String &r_err_str, int &r_err_line); }; #endif // JSON_H diff --git a/core/io/marshalls.cpp b/core/io/marshalls.cpp index a8c1cd0a10..927ce31744 100644 --- a/core/io/marshalls.cpp +++ b/core/io/marshalls.cpp @@ -27,99 +27,96 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "marshalls.h" -#include "print_string.h" #include "os/keyboard.h" +#include "print_string.h" #include <stdio.h> +#define ENCODE_MASK 0xFF +#define ENCODE_FLAG_64 1 << 16 -#define ENCODE_MASK 0xFF -#define ENCODE_FLAG_64 1<<16 +Error decode_variant(Variant &r_variant, const uint8_t *p_buffer, int p_len, int *r_len) { -Error decode_variant(Variant& r_variant,const uint8_t *p_buffer, int p_len,int *r_len) { + const uint8_t *buf = p_buffer; + int len = p_len; - const uint8_t * buf=p_buffer; - int len=p_len; + if (len < 4) { - if (len<4) { - - ERR_FAIL_COND_V(len<4,ERR_INVALID_DATA); + ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA); } + uint32_t type = decode_uint32(buf); - uint32_t type=decode_uint32(buf); - - ERR_FAIL_COND_V((type&ENCODE_MASK)>=Variant::VARIANT_MAX,ERR_INVALID_DATA); + ERR_FAIL_COND_V((type & ENCODE_MASK) >= Variant::VARIANT_MAX, ERR_INVALID_DATA); - buf+=4; - len-=4; + buf += 4; + len -= 4; if (r_len) - *r_len=4; + *r_len = 4; - switch(type&ENCODE_MASK) { + switch (type & ENCODE_MASK) { case Variant::NIL: { - r_variant=Variant(); + r_variant = Variant(); } break; case Variant::BOOL: { - ERR_FAIL_COND_V(len<4,ERR_INVALID_DATA); + ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA); bool val = decode_uint32(buf); - r_variant=val; + r_variant = val; if (r_len) - (*r_len)+=4; + (*r_len) += 4; } break; case Variant::INT: { - ERR_FAIL_COND_V(len<4,ERR_INVALID_DATA); - if (type&ENCODE_FLAG_64) { + ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA); + if (type & ENCODE_FLAG_64) { int64_t val = decode_uint64(buf); - r_variant=val; + r_variant = val; if (r_len) - (*r_len)+=8; + (*r_len) += 8; } else { int32_t val = decode_uint32(buf); - r_variant=val; + r_variant = val; if (r_len) - (*r_len)+=4; + (*r_len) += 4; } } break; case Variant::REAL: { - ERR_FAIL_COND_V(len<(int)4,ERR_INVALID_DATA); + ERR_FAIL_COND_V(len < (int)4, ERR_INVALID_DATA); - if (type&ENCODE_FLAG_64) { + if (type & ENCODE_FLAG_64) { double val = decode_double(buf); - r_variant=val; + r_variant = val; if (r_len) - (*r_len)+=8; + (*r_len) += 8; } else { float val = decode_float(buf); - r_variant=val; + r_variant = val; if (r_len) - (*r_len)+=4; + (*r_len) += 4; } } break; case Variant::STRING: { - ERR_FAIL_COND_V(len<4,ERR_INVALID_DATA); + ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA); uint32_t strlen = decode_uint32(buf); - buf+=4; - len-=4; - ERR_FAIL_COND_V((int)strlen>len,ERR_INVALID_DATA); + buf += 4; + len -= 4; + ERR_FAIL_COND_V((int)strlen > len, ERR_INVALID_DATA); String str; - str.parse_utf8((const char*)buf,strlen); - r_variant=str; + str.parse_utf8((const char *)buf, strlen); + r_variant = str; if (r_len) { - if (strlen%4) - (*r_len)+=4-strlen%4; - (*r_len)+=4+strlen; - + if (strlen % 4) + (*r_len) += 4 - strlen % 4; + (*r_len) += 4 + strlen; } } break; @@ -127,268 +124,262 @@ Error decode_variant(Variant& r_variant,const uint8_t *p_buffer, int p_len,int * case Variant::VECTOR2: { - ERR_FAIL_COND_V(len<(int)4*2,ERR_INVALID_DATA); + ERR_FAIL_COND_V(len < (int)4 * 2, ERR_INVALID_DATA); Vector2 val; - val.x=decode_float(&buf[0]); - val.y=decode_float(&buf[4]); - r_variant=val; + val.x = decode_float(&buf[0]); + val.y = decode_float(&buf[4]); + r_variant = val; if (r_len) - (*r_len)+=4*2; + (*r_len) += 4 * 2; - } break; // 5 + } break; // 5 case Variant::RECT2: { - ERR_FAIL_COND_V(len<(int)4*4,ERR_INVALID_DATA); + ERR_FAIL_COND_V(len < (int)4 * 4, ERR_INVALID_DATA); Rect2 val; - val.pos.x=decode_float(&buf[0]); - val.pos.y=decode_float(&buf[4]); - val.size.x=decode_float(&buf[8]); - val.size.y=decode_float(&buf[12]); - r_variant=val; + val.pos.x = decode_float(&buf[0]); + val.pos.y = decode_float(&buf[4]); + val.size.x = decode_float(&buf[8]); + val.size.y = decode_float(&buf[12]); + r_variant = val; if (r_len) - (*r_len)+=4*4; + (*r_len) += 4 * 4; } break; case Variant::VECTOR3: { - ERR_FAIL_COND_V(len<(int)4*3,ERR_INVALID_DATA); + ERR_FAIL_COND_V(len < (int)4 * 3, ERR_INVALID_DATA); Vector3 val; - val.x=decode_float(&buf[0]); - val.y=decode_float(&buf[4]); - val.z=decode_float(&buf[8]); - r_variant=val; + val.x = decode_float(&buf[0]); + val.y = decode_float(&buf[4]); + val.z = decode_float(&buf[8]); + r_variant = val; if (r_len) - (*r_len)+=4*3; + (*r_len) += 4 * 3; } break; case Variant::TRANSFORM2D: { - ERR_FAIL_COND_V(len<(int)4*6,ERR_INVALID_DATA); + ERR_FAIL_COND_V(len < (int)4 * 6, ERR_INVALID_DATA); Transform2D val; - for(int i=0;i<3;i++) { - for(int j=0;j<2;j++) { + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 2; j++) { - val.elements[i][j]=decode_float(&buf[(i*2+j)*4]); + val.elements[i][j] = decode_float(&buf[(i * 2 + j) * 4]); } } - r_variant=val; + r_variant = val; if (r_len) - (*r_len)+=4*6; + (*r_len) += 4 * 6; } break; case Variant::PLANE: { - ERR_FAIL_COND_V(len<(int)4*4,ERR_INVALID_DATA); + ERR_FAIL_COND_V(len < (int)4 * 4, ERR_INVALID_DATA); Plane val; - val.normal.x=decode_float(&buf[0]); - val.normal.y=decode_float(&buf[4]); - val.normal.z=decode_float(&buf[8]); - val.d=decode_float(&buf[12]); - r_variant=val; + val.normal.x = decode_float(&buf[0]); + val.normal.y = decode_float(&buf[4]); + val.normal.z = decode_float(&buf[8]); + val.d = decode_float(&buf[12]); + r_variant = val; if (r_len) - (*r_len)+=4*4; + (*r_len) += 4 * 4; } break; case Variant::QUAT: { - ERR_FAIL_COND_V(len<(int)4*4,ERR_INVALID_DATA); + ERR_FAIL_COND_V(len < (int)4 * 4, ERR_INVALID_DATA); Quat val; - val.x=decode_float(&buf[0]); - val.y=decode_float(&buf[4]); - val.z=decode_float(&buf[8]); - val.w=decode_float(&buf[12]); - r_variant=val; + val.x = decode_float(&buf[0]); + val.y = decode_float(&buf[4]); + val.z = decode_float(&buf[8]); + val.w = decode_float(&buf[12]); + r_variant = val; if (r_len) - (*r_len)+=4*4; + (*r_len) += 4 * 4; } break; case Variant::RECT3: { - ERR_FAIL_COND_V(len<(int)4*6,ERR_INVALID_DATA); + ERR_FAIL_COND_V(len < (int)4 * 6, ERR_INVALID_DATA); Rect3 val; - val.pos.x=decode_float(&buf[0]); - val.pos.y=decode_float(&buf[4]); - val.pos.z=decode_float(&buf[8]); - val.size.x=decode_float(&buf[12]); - val.size.y=decode_float(&buf[16]); - val.size.z=decode_float(&buf[20]); - r_variant=val; + val.pos.x = decode_float(&buf[0]); + val.pos.y = decode_float(&buf[4]); + val.pos.z = decode_float(&buf[8]); + val.size.x = decode_float(&buf[12]); + val.size.y = decode_float(&buf[16]); + val.size.z = decode_float(&buf[20]); + r_variant = val; if (r_len) - (*r_len)+=4*6; + (*r_len) += 4 * 6; } break; case Variant::BASIS: { - ERR_FAIL_COND_V(len<(int)4*9,ERR_INVALID_DATA); + ERR_FAIL_COND_V(len < (int)4 * 9, ERR_INVALID_DATA); Basis val; - for(int i=0;i<3;i++) { - for(int j=0;j<3;j++) { + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 3; j++) { - val.elements[i][j]=decode_float(&buf[(i*3+j)*4]); + val.elements[i][j] = decode_float(&buf[(i * 3 + j) * 4]); } } - r_variant=val; + r_variant = val; if (r_len) - (*r_len)+=4*9; + (*r_len) += 4 * 9; } break; case Variant::TRANSFORM: { - ERR_FAIL_COND_V(len<(int)4*12,ERR_INVALID_DATA); + ERR_FAIL_COND_V(len < (int)4 * 12, ERR_INVALID_DATA); Transform val; - for(int i=0;i<3;i++) { - for(int j=0;j<3;j++) { + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 3; j++) { - val.basis.elements[i][j]=decode_float(&buf[(i*3+j)*4]); + val.basis.elements[i][j] = decode_float(&buf[(i * 3 + j) * 4]); } } - val.origin[0]=decode_float(&buf[36]); - val.origin[1]=decode_float(&buf[40]); - val.origin[2]=decode_float(&buf[44]); + val.origin[0] = decode_float(&buf[36]); + val.origin[1] = decode_float(&buf[40]); + val.origin[2] = decode_float(&buf[44]); - r_variant=val; + r_variant = val; if (r_len) - (*r_len)+=4*12; + (*r_len) += 4 * 12; } break; // misc types case Variant::COLOR: { - ERR_FAIL_COND_V(len<(int)4*4,ERR_INVALID_DATA); + ERR_FAIL_COND_V(len < (int)4 * 4, ERR_INVALID_DATA); Color val; - val.r=decode_float(&buf[0]); - val.g=decode_float(&buf[4]); - val.b=decode_float(&buf[8]); - val.a=decode_float(&buf[12]); - r_variant=val; + val.r = decode_float(&buf[0]); + val.g = decode_float(&buf[4]); + val.b = decode_float(&buf[8]); + val.a = decode_float(&buf[12]); + r_variant = val; if (r_len) - (*r_len)+=4*4; + (*r_len) += 4 * 4; } break; case Variant::IMAGE: { - ERR_FAIL_COND_V(len<(int)5*4,ERR_INVALID_DATA); + ERR_FAIL_COND_V(len < (int)5 * 4, ERR_INVALID_DATA); Image::Format fmt = (Image::Format)decode_uint32(&buf[0]); - ERR_FAIL_INDEX_V( fmt, Image::FORMAT_MAX, ERR_INVALID_DATA); + ERR_FAIL_INDEX_V(fmt, Image::FORMAT_MAX, ERR_INVALID_DATA); uint32_t mipmaps = decode_uint32(&buf[4]); uint32_t w = decode_uint32(&buf[8]); uint32_t h = decode_uint32(&buf[12]); uint32_t datalen = decode_uint32(&buf[16]); Image img; - if (datalen>0) { - len-=5*4; - ERR_FAIL_COND_V( len < datalen, ERR_INVALID_DATA ); + if (datalen > 0) { + len -= 5 * 4; + ERR_FAIL_COND_V(len < datalen, ERR_INVALID_DATA); PoolVector<uint8_t> data; data.resize(datalen); PoolVector<uint8_t>::Write wr = data.write(); - copymem(&wr[0],&buf[20],datalen); + copymem(&wr[0], &buf[20], datalen); wr = PoolVector<uint8_t>::Write(); - - - img=Image(w,h,mipmaps,fmt,data); + img = Image(w, h, mipmaps, fmt, data); } - r_variant=img; + r_variant = img; if (r_len) { - if (datalen%4) - (*r_len)+=4-datalen%4; + if (datalen % 4) + (*r_len) += 4 - datalen % 4; - (*r_len)+=4*5+datalen; + (*r_len) += 4 * 5 + datalen; } } break; case Variant::NODE_PATH: { - ERR_FAIL_COND_V(len<4,ERR_INVALID_DATA); + ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA); uint32_t strlen = decode_uint32(buf); - if (strlen&0x80000000) { + if (strlen & 0x80000000) { //new format - ERR_FAIL_COND_V(len<12,ERR_INVALID_DATA); + ERR_FAIL_COND_V(len < 12, ERR_INVALID_DATA); Vector<StringName> names; Vector<StringName> subnames; StringName prop; - uint32_t namecount=strlen&=0x7FFFFFFF; - uint32_t subnamecount = decode_uint32(buf+4); - uint32_t flags = decode_uint32(buf+8); + uint32_t namecount = strlen &= 0x7FFFFFFF; + uint32_t subnamecount = decode_uint32(buf + 4); + uint32_t flags = decode_uint32(buf + 8); - len-=12; - buf+=12; + len -= 12; + buf += 12; - int total=namecount+subnamecount; - if (flags&2) + int total = namecount + subnamecount; + if (flags & 2) total++; if (r_len) - (*r_len)+=12; - + (*r_len) += 12; - for(int i=0;i<total;i++) { + for (int i = 0; i < total; i++) { - ERR_FAIL_COND_V((int)len<4,ERR_INVALID_DATA); + ERR_FAIL_COND_V((int)len < 4, ERR_INVALID_DATA); strlen = decode_uint32(buf); - int pad=0; + int pad = 0; - if (strlen%4) - pad+=4-strlen%4; + if (strlen % 4) + pad += 4 - strlen % 4; - buf+=4; - len-=4; - ERR_FAIL_COND_V((int)strlen+pad>len,ERR_INVALID_DATA); + buf += 4; + len -= 4; + ERR_FAIL_COND_V((int)strlen + pad > len, ERR_INVALID_DATA); String str; - str.parse_utf8((const char*)buf,strlen); - + str.parse_utf8((const char *)buf, strlen); - if (i<namecount) + if (i < namecount) names.push_back(str); - else if (i<namecount+subnamecount) + else if (i < namecount + subnamecount) subnames.push_back(str); else - prop=str; + prop = str; - buf+=strlen+pad; - len-=strlen+pad; + buf += strlen + pad; + len -= strlen + pad; if (r_len) - (*r_len)+=4+strlen+pad; - + (*r_len) += 4 + strlen + pad; } - r_variant=NodePath(names,subnames,flags&1,prop); + r_variant = NodePath(names, subnames, flags & 1, prop); } else { //old format, just a string - buf+=4; - len-=4; - ERR_FAIL_COND_V((int)strlen>len,ERR_INVALID_DATA); - + buf += 4; + len -= 4; + ERR_FAIL_COND_V((int)strlen > len, ERR_INVALID_DATA); String str; - str.parse_utf8((const char*)buf,strlen); + str.parse_utf8((const char *)buf, strlen); - r_variant=NodePath(str); + r_variant = NodePath(str); if (r_len) - (*r_len)+=4+strlen; + (*r_len) += 4 + strlen; } } break; @@ -403,64 +394,62 @@ Error decode_variant(Variant& r_variant,const uint8_t *p_buffer, int p_len,int * } break; case Variant::OBJECT: { - - r_variant = (Object*)NULL; + r_variant = (Object *)NULL; } break; case Variant::INPUT_EVENT: { InputEvent ie; - ie.type=decode_uint32(&buf[0]); - ie.device=decode_uint32(&buf[4]); + ie.type = decode_uint32(&buf[0]); + ie.device = decode_uint32(&buf[4]); if (r_len) - (*r_len)+=12; + (*r_len) += 12; - switch(ie.type) { + switch (ie.type) { case InputEvent::KEY: { - uint32_t mods=decode_uint32(&buf[12]); - if (mods&KEY_MASK_SHIFT) - ie.key.mod.shift=true; - if (mods&KEY_MASK_CTRL) - ie.key.mod.control=true; - if (mods&KEY_MASK_ALT) - ie.key.mod.alt=true; - if (mods&KEY_MASK_META) - ie.key.mod.meta=true; - ie.key.scancode=decode_uint32(&buf[16]); + uint32_t mods = decode_uint32(&buf[12]); + if (mods & KEY_MASK_SHIFT) + ie.key.mod.shift = true; + if (mods & KEY_MASK_CTRL) + ie.key.mod.control = true; + if (mods & KEY_MASK_ALT) + ie.key.mod.alt = true; + if (mods & KEY_MASK_META) + ie.key.mod.meta = true; + ie.key.scancode = decode_uint32(&buf[16]); if (r_len) - (*r_len)+=8; - + (*r_len) += 8; } break; case InputEvent::MOUSE_BUTTON: { - ie.mouse_button.button_index=decode_uint32(&buf[12]); + ie.mouse_button.button_index = decode_uint32(&buf[12]); if (r_len) - (*r_len)+=4; + (*r_len) += 4; } break; case InputEvent::JOYPAD_BUTTON: { - ie.joy_button.button_index=decode_uint32(&buf[12]); + ie.joy_button.button_index = decode_uint32(&buf[12]); if (r_len) - (*r_len)+=4; + (*r_len) += 4; } break; case InputEvent::SCREEN_TOUCH: { - ie.screen_touch.index=decode_uint32(&buf[12]); + ie.screen_touch.index = decode_uint32(&buf[12]); if (r_len) - (*r_len)+=4; + (*r_len) += 4; } break; case InputEvent::JOYPAD_MOTION: { - ie.joy_motion.axis=decode_uint32(&buf[12]); - ie.joy_motion.axis_value=decode_float(&buf[16]); + ie.joy_motion.axis = decode_uint32(&buf[12]); + ie.joy_motion.axis_value = decode_float(&buf[16]); if (r_len) - (*r_len)+=8; + (*r_len) += 8; } break; } @@ -469,125 +458,121 @@ Error decode_variant(Variant& r_variant,const uint8_t *p_buffer, int p_len,int * } break; case Variant::DICTIONARY: { - ERR_FAIL_COND_V(len<4,ERR_INVALID_DATA); - uint32_t count = decode_uint32(buf); - // bool shared = count&0x80000000; - count&=0x7FFFFFFF; + ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA); + uint32_t count = decode_uint32(buf); + // bool shared = count&0x80000000; + count &= 0x7FFFFFFF; - buf+=4; - len-=4; + buf += 4; + len -= 4; if (r_len) { - (*r_len)+=4; + (*r_len) += 4; } - Dictionary d; + Dictionary d; - for(uint32_t i=0;i<count;i++) { + for (uint32_t i = 0; i < count; i++) { - Variant key,value; + Variant key, value; int used; - Error err = decode_variant(key,buf,len,&used); - ERR_FAIL_COND_V(err,err); + Error err = decode_variant(key, buf, len, &used); + ERR_FAIL_COND_V(err, err); - buf+=used; - len-=used; + buf += used; + len -= used; if (r_len) { - (*r_len)+=used; + (*r_len) += used; } - err = decode_variant(value,buf,len,&used); - ERR_FAIL_COND_V(err,err); + err = decode_variant(value, buf, len, &used); + ERR_FAIL_COND_V(err, err); - buf+=used; - len-=used; + buf += used; + len -= used; if (r_len) { - (*r_len)+=used; + (*r_len) += used; } - d[key]=value; + d[key] = value; } - r_variant=d; + r_variant = d; } break; case Variant::ARRAY: { - ERR_FAIL_COND_V(len<4,ERR_INVALID_DATA); + ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA); uint32_t count = decode_uint32(buf); - // bool shared = count&0x80000000; - count&=0x7FFFFFFF; + // bool shared = count&0x80000000; + count &= 0x7FFFFFFF; - buf+=4; - len-=4; + buf += 4; + len -= 4; if (r_len) { - (*r_len)+=4; + (*r_len) += 4; } - Array varr; + Array varr; - for(uint32_t i=0;i<count;i++) { + for (uint32_t i = 0; i < count; i++) { - int used=0; + int used = 0; Variant v; - Error err = decode_variant(v,buf,len,&used); - ERR_FAIL_COND_V(err,err); - buf+=used; - len-=used; + Error err = decode_variant(v, buf, len, &used); + ERR_FAIL_COND_V(err, err); + buf += used; + len -= used; varr.push_back(v); if (r_len) { - (*r_len)+=used; + (*r_len) += used; } } - r_variant=varr; - + r_variant = varr; } break; // arrays case Variant::POOL_BYTE_ARRAY: { - ERR_FAIL_COND_V(len<4,ERR_INVALID_DATA); + ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA); uint32_t count = decode_uint32(buf); - buf+=4; - len-=4; - ERR_FAIL_COND_V((int)count>len,ERR_INVALID_DATA); - + buf += 4; + len -= 4; + ERR_FAIL_COND_V((int)count > len, ERR_INVALID_DATA); PoolVector<uint8_t> data; if (count) { data.resize(count); PoolVector<uint8_t>::Write w = data.write(); - for(int i=0;i<count;i++) { + for (int i = 0; i < count; i++) { - w[i]=buf[i]; + w[i] = buf[i]; } w = PoolVector<uint8_t>::Write(); } - r_variant=data; + r_variant = data; if (r_len) { - if (count%4) - (*r_len)+=4-count%4; - (*r_len)+=4+count; + if (count % 4) + (*r_len) += 4 - count % 4; + (*r_len) += 4 + count; } - - } break; case Variant::POOL_INT_ARRAY: { - ERR_FAIL_COND_V(len<4,ERR_INVALID_DATA); + ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA); uint32_t count = decode_uint32(buf); - buf+=4; - len-=4; - ERR_FAIL_COND_V((int)count*4>len,ERR_INVALID_DATA); + buf += 4; + len -= 4; + ERR_FAIL_COND_V((int)count * 4 > len, ERR_INVALID_DATA); PoolVector<int> data; @@ -595,26 +580,26 @@ Error decode_variant(Variant& r_variant,const uint8_t *p_buffer, int p_len,int * //const int*rbuf=(const int*)buf; data.resize(count); PoolVector<int>::Write w = data.write(); - for(int i=0;i<count;i++) { + for (int i = 0; i < count; i++) { - w[i]=decode_uint32(&buf[i*4]); + w[i] = decode_uint32(&buf[i * 4]); } w = PoolVector<int>::Write(); } - r_variant=Variant(data); + r_variant = Variant(data); if (r_len) { - (*r_len)+=4+count*sizeof(int); + (*r_len) += 4 + count * sizeof(int); } } break; case Variant::POOL_REAL_ARRAY: { - ERR_FAIL_COND_V(len<4,ERR_INVALID_DATA); + ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA); uint32_t count = decode_uint32(buf); - buf+=4; - len-=4; - ERR_FAIL_COND_V((int)count*4>len,ERR_INVALID_DATA); + buf += 4; + len -= 4; + ERR_FAIL_COND_V((int)count * 4 > len, ERR_INVALID_DATA); PoolVector<float> data; @@ -622,182 +607,173 @@ Error decode_variant(Variant& r_variant,const uint8_t *p_buffer, int p_len,int * //const float*rbuf=(const float*)buf; data.resize(count); PoolVector<float>::Write w = data.write(); - for(int i=0;i<count;i++) { + for (int i = 0; i < count; i++) { - w[i]=decode_float(&buf[i*4]); + w[i] = decode_float(&buf[i * 4]); } w = PoolVector<float>::Write(); } - r_variant=data; + r_variant = data; if (r_len) { - (*r_len)+=4+count*sizeof(float); + (*r_len) += 4 + count * sizeof(float); } - } break; case Variant::POOL_STRING_ARRAY: { - ERR_FAIL_COND_V(len<4,ERR_INVALID_DATA); + ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA); uint32_t count = decode_uint32(buf); PoolVector<String> strings; - buf+=4; - len-=4; + buf += 4; + len -= 4; if (r_len) - (*r_len)+=4; + (*r_len) += 4; //printf("string count: %i\n",count); - for(int i=0;i<(int)count;i++) { + for (int i = 0; i < (int)count; i++) { - ERR_FAIL_COND_V(len<4,ERR_INVALID_DATA); + ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA); uint32_t strlen = decode_uint32(buf); - buf+=4; - len-=4; - ERR_FAIL_COND_V((int)strlen>len,ERR_INVALID_DATA); + buf += 4; + len -= 4; + ERR_FAIL_COND_V((int)strlen > len, ERR_INVALID_DATA); //printf("loaded string: %s\n",(const char*)buf); String str; - str.parse_utf8((const char*)buf,strlen); + str.parse_utf8((const char *)buf, strlen); strings.push_back(str); - buf+=strlen; - len-=strlen; + buf += strlen; + len -= strlen; if (r_len) - (*r_len)+=4+strlen; + (*r_len) += 4 + strlen; - if (strlen%4) { - int pad = 4-(strlen%4); - buf+=pad; - len-=pad; + if (strlen % 4) { + int pad = 4 - (strlen % 4); + buf += pad; + len -= pad; if (r_len) { - (*r_len)+=pad; + (*r_len) += pad; } } - } - r_variant=strings; - + r_variant = strings; } break; case Variant::POOL_VECTOR2_ARRAY: { - ERR_FAIL_COND_V(len<4,ERR_INVALID_DATA); + ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA); uint32_t count = decode_uint32(buf); - buf+=4; - len-=4; + buf += 4; + len -= 4; - ERR_FAIL_COND_V((int)count*4*2>len,ERR_INVALID_DATA); + ERR_FAIL_COND_V((int)count * 4 * 2 > len, ERR_INVALID_DATA); PoolVector<Vector2> varray; if (r_len) { - (*r_len)+=4; + (*r_len) += 4; } if (count) { varray.resize(count); PoolVector<Vector2>::Write w = varray.write(); - for(int i=0;i<(int)count;i++) { - - w[i].x=decode_float(buf+i*4*2+4*0); - w[i].y=decode_float(buf+i*4*2+4*1); + for (int i = 0; i < (int)count; i++) { + w[i].x = decode_float(buf + i * 4 * 2 + 4 * 0); + w[i].y = decode_float(buf + i * 4 * 2 + 4 * 1); } - int adv = 4*2*count; + int adv = 4 * 2 * count; if (r_len) - (*r_len)+=adv; - len-=adv; - buf+=adv; - + (*r_len) += adv; + len -= adv; + buf += adv; } - r_variant=varray; + r_variant = varray; } break; case Variant::POOL_VECTOR3_ARRAY: { - ERR_FAIL_COND_V(len<4,ERR_INVALID_DATA); + ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA); uint32_t count = decode_uint32(buf); - buf+=4; - len-=4; + buf += 4; + len -= 4; - ERR_FAIL_COND_V((int)count*4*3>len,ERR_INVALID_DATA); + ERR_FAIL_COND_V((int)count * 4 * 3 > len, ERR_INVALID_DATA); PoolVector<Vector3> varray; if (r_len) { - (*r_len)+=4; + (*r_len) += 4; } if (count) { varray.resize(count); PoolVector<Vector3>::Write w = varray.write(); - for(int i=0;i<(int)count;i++) { - - w[i].x=decode_float(buf+i*4*3+4*0); - w[i].y=decode_float(buf+i*4*3+4*1); - w[i].z=decode_float(buf+i*4*3+4*2); + for (int i = 0; i < (int)count; i++) { + w[i].x = decode_float(buf + i * 4 * 3 + 4 * 0); + w[i].y = decode_float(buf + i * 4 * 3 + 4 * 1); + w[i].z = decode_float(buf + i * 4 * 3 + 4 * 2); } - int adv = 4*3*count; + int adv = 4 * 3 * count; if (r_len) - (*r_len)+=adv; - len-=adv; - buf+=adv; - + (*r_len) += adv; + len -= adv; + buf += adv; } - r_variant=varray; + r_variant = varray; } break; case Variant::POOL_COLOR_ARRAY: { - ERR_FAIL_COND_V(len<4,ERR_INVALID_DATA); + ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA); uint32_t count = decode_uint32(buf); - buf+=4; - len-=4; + buf += 4; + len -= 4; - ERR_FAIL_COND_V((int)count*4*4>len,ERR_INVALID_DATA); + ERR_FAIL_COND_V((int)count * 4 * 4 > len, ERR_INVALID_DATA); PoolVector<Color> carray; if (r_len) { - (*r_len)+=4; + (*r_len) += 4; } if (count) { carray.resize(count); PoolVector<Color>::Write w = carray.write(); - for(int i=0;i<(int)count;i++) { - - w[i].r=decode_float(buf+i*4*4+4*0); - w[i].g=decode_float(buf+i*4*4+4*1); - w[i].b=decode_float(buf+i*4*4+4*2); - w[i].a=decode_float(buf+i*4*4+4*3); + for (int i = 0; i < (int)count; i++) { + w[i].r = decode_float(buf + i * 4 * 4 + 4 * 0); + w[i].g = decode_float(buf + i * 4 * 4 + 4 * 1); + w[i].b = decode_float(buf + i * 4 * 4 + 4 * 2); + w[i].a = decode_float(buf + i * 4 * 4 + 4 * 3); } - int adv = 4*4*count; + int adv = 4 * 4 * count; if (r_len) - (*r_len)+=adv; - len-=adv; - buf+=adv; - + (*r_len) += adv; + len -= adv; + buf += adv; } - r_variant=carray; + r_variant = carray; } break; default: { ERR_FAIL_V(ERR_BUG); } @@ -806,39 +782,39 @@ Error decode_variant(Variant& r_variant,const uint8_t *p_buffer, int p_len,int * return OK; } -Error encode_variant(const Variant& p_variant, uint8_t *r_buffer, int &r_len) { +Error encode_variant(const Variant &p_variant, uint8_t *r_buffer, int &r_len) { - uint8_t * buf=r_buffer; + uint8_t *buf = r_buffer; - r_len=0; + r_len = 0; - uint32_t flags=0; + uint32_t flags = 0; - switch(p_variant.get_type()) { + switch (p_variant.get_type()) { case Variant::INT: { int64_t val = p_variant; - if (val>0x7FFFFFFF || val < -0x80000000) { - flags|=ENCODE_FLAG_64; + if (val > 0x7FFFFFFF || val < -0x80000000) { + flags |= ENCODE_FLAG_64; } } break; case Variant::REAL: { double d = p_variant; float f = d; - if (double(f)!=d) { - flags|=ENCODE_FLAG_64; //always encode real as double + if (double(f) != d) { + flags |= ENCODE_FLAG_64; //always encode real as double } } break; } if (buf) { - encode_uint32(p_variant.get_type()|flags,buf); - buf+=4; + encode_uint32(p_variant.get_type() | flags, buf); + buf += 4; } - r_len+=4; + r_len += 4; - switch(p_variant.get_type()) { + switch (p_variant.get_type()) { case Variant::NIL: { @@ -847,118 +823,115 @@ Error encode_variant(const Variant& p_variant, uint8_t *r_buffer, int &r_len) { case Variant::BOOL: { if (buf) { - encode_uint32(p_variant.operator bool(),buf); + encode_uint32(p_variant.operator bool(), buf); } - r_len+=4; + r_len += 4; } break; case Variant::INT: { int64_t val = p_variant; - if (val>0x7FFFFFFF || val < -0x80000000) { + if (val > 0x7FFFFFFF || val < -0x80000000) { //64 bits if (buf) { - encode_uint64(val,buf); + encode_uint64(val, buf); } - r_len+=8; + r_len += 8; } else { if (buf) { - encode_uint32(int32_t(val),buf); + encode_uint32(int32_t(val), buf); } - r_len+=4; + r_len += 4; } } break; case Variant::REAL: { double d = p_variant; float f = d; - if (double(f)!=d) { + if (double(f) != d) { if (buf) { - encode_double(p_variant.operator double(),buf); + encode_double(p_variant.operator double(), buf); } - r_len+=8; + r_len += 8; } else { if (buf) { - encode_double(p_variant.operator float(),buf); + encode_double(p_variant.operator float(), buf); } - r_len+=4; + r_len += 4; } - } break; case Variant::NODE_PATH: { - NodePath np=p_variant; + NodePath np = p_variant; if (buf) { - encode_uint32(uint32_t(np.get_name_count())|0x80000000,buf); //for compatibility with the old format - encode_uint32(np.get_subname_count(),buf+4); - uint32_t flags=0; + encode_uint32(uint32_t(np.get_name_count()) | 0x80000000, buf); //for compatibility with the old format + encode_uint32(np.get_subname_count(), buf + 4); + uint32_t flags = 0; if (np.is_absolute()) - flags|=1; - if (np.get_property()!=StringName()) - flags|=2; + flags |= 1; + if (np.get_property() != StringName()) + flags |= 2; - encode_uint32(flags,buf+8); + encode_uint32(flags, buf + 8); - buf+=12; + buf += 12; } - r_len+=12; + r_len += 12; - int total = np.get_name_count()+np.get_subname_count(); - if (np.get_property()!=StringName()) + int total = np.get_name_count() + np.get_subname_count(); + if (np.get_property() != StringName()) total++; - for(int i=0;i<total;i++) { + for (int i = 0; i < total; i++) { String str; - if (i<np.get_name_count()) - str=np.get_name(i); - else if (i<np.get_name_count()+np.get_subname_count()) - str=np.get_subname(i-np.get_subname_count()); + if (i < np.get_name_count()) + str = np.get_name(i); + else if (i < np.get_name_count() + np.get_subname_count()) + str = np.get_subname(i - np.get_subname_count()); else - str=np.get_property(); + str = np.get_property(); CharString utf8 = str.utf8(); int pad = 0; - if (utf8.length()%4) - pad=4-utf8.length()%4; + if (utf8.length() % 4) + pad = 4 - utf8.length() % 4; if (buf) { - encode_uint32(utf8.length(),buf); - buf+=4; - copymem(buf,utf8.get_data(),utf8.length()); - buf+=pad+utf8.length(); + encode_uint32(utf8.length(), buf); + buf += 4; + copymem(buf, utf8.get_data(), utf8.length()); + buf += pad + utf8.length(); } - - r_len+=4+utf8.length()+pad; + r_len += 4 + utf8.length() + pad; } } break; case Variant::STRING: { - CharString utf8 = p_variant.operator String().utf8(); if (buf) { - encode_uint32(utf8.length(),buf); - buf+=4; - copymem(buf,utf8.get_data(),utf8.length()); + encode_uint32(utf8.length(), buf); + buf += 4; + copymem(buf, utf8.get_data(), utf8.length()); } - r_len+=4+utf8.length(); - while (r_len%4) + r_len += 4 + utf8.length(); + while (r_len % 4) r_len++; //pad } break; @@ -967,132 +940,126 @@ Error encode_variant(const Variant& p_variant, uint8_t *r_buffer, int &r_len) { case Variant::VECTOR2: { if (buf) { - Vector2 v2=p_variant; - encode_float(v2.x,&buf[0]); - encode_float(v2.y,&buf[4]); - + Vector2 v2 = p_variant; + encode_float(v2.x, &buf[0]); + encode_float(v2.y, &buf[4]); } - r_len+=2*4; + r_len += 2 * 4; - } break; // 5 + } break; // 5 case Variant::RECT2: { if (buf) { - Rect2 r2=p_variant; - encode_float(r2.pos.x,&buf[0]); - encode_float(r2.pos.y,&buf[4]); - encode_float(r2.size.x,&buf[8]); - encode_float(r2.size.y,&buf[12]); + Rect2 r2 = p_variant; + encode_float(r2.pos.x, &buf[0]); + encode_float(r2.pos.y, &buf[4]); + encode_float(r2.size.x, &buf[8]); + encode_float(r2.size.y, &buf[12]); } - r_len+=4*4; + r_len += 4 * 4; } break; case Variant::VECTOR3: { if (buf) { - Vector3 v3=p_variant; - encode_float(v3.x,&buf[0]); - encode_float(v3.y,&buf[4]); - encode_float(v3.z,&buf[8]); + Vector3 v3 = p_variant; + encode_float(v3.x, &buf[0]); + encode_float(v3.y, &buf[4]); + encode_float(v3.z, &buf[8]); } - r_len+=3*4; + r_len += 3 * 4; } break; case Variant::TRANSFORM2D: { if (buf) { - Transform2D val=p_variant; - for(int i=0;i<3;i++) { - for(int j=0;j<2;j++) { + Transform2D val = p_variant; + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 2; j++) { - copymem(&buf[(i*2+j)*4],&val.elements[i][j],sizeof(float)); + copymem(&buf[(i * 2 + j) * 4], &val.elements[i][j], sizeof(float)); } } } - - r_len+=6*4; + r_len += 6 * 4; } break; case Variant::PLANE: { if (buf) { - Plane p=p_variant; - encode_float(p.normal.x,&buf[0]); - encode_float(p.normal.y,&buf[4]); - encode_float(p.normal.z,&buf[8]); - encode_float(p.d,&buf[12]); + Plane p = p_variant; + encode_float(p.normal.x, &buf[0]); + encode_float(p.normal.y, &buf[4]); + encode_float(p.normal.z, &buf[8]); + encode_float(p.d, &buf[12]); } - r_len+=4*4; + r_len += 4 * 4; } break; case Variant::QUAT: { if (buf) { - Quat q=p_variant; - encode_float(q.x,&buf[0]); - encode_float(q.y,&buf[4]); - encode_float(q.z,&buf[8]); - encode_float(q.w,&buf[12]); + Quat q = p_variant; + encode_float(q.x, &buf[0]); + encode_float(q.y, &buf[4]); + encode_float(q.z, &buf[8]); + encode_float(q.w, &buf[12]); } - r_len+=4*4; + r_len += 4 * 4; } break; case Variant::RECT3: { if (buf) { - Rect3 aabb=p_variant; - encode_float(aabb.pos.x,&buf[0]); - encode_float(aabb.pos.y,&buf[4]); - encode_float(aabb.pos.z,&buf[8]); - encode_float(aabb.size.x,&buf[12]); - encode_float(aabb.size.y,&buf[16]); - encode_float(aabb.size.z,&buf[20]); + Rect3 aabb = p_variant; + encode_float(aabb.pos.x, &buf[0]); + encode_float(aabb.pos.y, &buf[4]); + encode_float(aabb.pos.z, &buf[8]); + encode_float(aabb.size.x, &buf[12]); + encode_float(aabb.size.y, &buf[16]); + encode_float(aabb.size.z, &buf[20]); } - r_len+=6*4; - + r_len += 6 * 4; } break; case Variant::BASIS: { if (buf) { - Basis val=p_variant; - for(int i=0;i<3;i++) { - for(int j=0;j<3;j++) { + Basis val = p_variant; + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 3; j++) { - copymem(&buf[(i*3+j)*4],&val.elements[i][j],sizeof(float)); + copymem(&buf[(i * 3 + j) * 4], &val.elements[i][j], sizeof(float)); } } } - - r_len+=9*4; + r_len += 9 * 4; } break; case Variant::TRANSFORM: { if (buf) { - Transform val=p_variant; - for(int i=0;i<3;i++) { - for(int j=0;j<3;j++) { + Transform val = p_variant; + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 3; j++) { - copymem(&buf[(i*3+j)*4],&val.basis.elements[i][j],sizeof(float)); + copymem(&buf[(i * 3 + j) * 4], &val.basis.elements[i][j], sizeof(float)); } } - encode_float(val.origin.x,&buf[36]); - encode_float(val.origin.y,&buf[40]); - encode_float(val.origin.z,&buf[44]); - - + encode_float(val.origin.x, &buf[36]); + encode_float(val.origin.y, &buf[40]); + encode_float(val.origin.z, &buf[44]); } - r_len+=12*4; + r_len += 12 * 4; } break; @@ -1100,38 +1067,38 @@ Error encode_variant(const Variant& p_variant, uint8_t *r_buffer, int &r_len) { case Variant::COLOR: { if (buf) { - Color c=p_variant; - encode_float(c.r,&buf[0]); - encode_float(c.g,&buf[4]); - encode_float(c.b,&buf[8]); - encode_float(c.a,&buf[12]); + Color c = p_variant; + encode_float(c.r, &buf[0]); + encode_float(c.g, &buf[4]); + encode_float(c.b, &buf[8]); + encode_float(c.a, &buf[12]); } - r_len+=4*4; + r_len += 4 * 4; } break; case Variant::IMAGE: { Image image = p_variant; - PoolVector<uint8_t> data=image.get_data(); + PoolVector<uint8_t> data = image.get_data(); if (buf) { - encode_uint32(image.get_format(),&buf[0]); - encode_uint32(image.has_mipmaps(),&buf[4]); - encode_uint32(image.get_width(),&buf[8]); - encode_uint32(image.get_height(),&buf[12]); - int ds=data.size(); - encode_uint32(ds,&buf[16]); + encode_uint32(image.get_format(), &buf[0]); + encode_uint32(image.has_mipmaps(), &buf[4]); + encode_uint32(image.get_width(), &buf[8]); + encode_uint32(image.get_height(), &buf[12]); + int ds = data.size(); + encode_uint32(ds, &buf[16]); PoolVector<uint8_t>::Read r = data.read(); - copymem(&buf[20],&r[0],ds); + copymem(&buf[20], &r[0], ds); } - int pad=0; - if (data.size()%4) - pad=4-data.size()%4; + int pad = 0; + if (data.size() % 4) + pad = 4 - data.size() % 4; - r_len+=data.size()+5*4+pad; + r_len += data.size() + 5 * 4 + pad; } break; /*case Variant::RESOURCE: { @@ -1142,84 +1109,81 @@ Error encode_variant(const Variant& p_variant, uint8_t *r_buffer, int &r_len) { case Variant::_RID: case Variant::OBJECT: { - } break; case Variant::INPUT_EVENT: { - - InputEvent ie=p_variant; + InputEvent ie = p_variant; if (buf) { - encode_uint32(ie.type,&buf[0]); - encode_uint32(ie.device,&buf[4]); - encode_uint32(0,&buf[8]); + encode_uint32(ie.type, &buf[0]); + encode_uint32(ie.device, &buf[4]); + encode_uint32(0, &buf[8]); } - int llen=12; + int llen = 12; - switch(ie.type) { + switch (ie.type) { case InputEvent::KEY: { if (buf) { - uint32_t mods=0; + uint32_t mods = 0; if (ie.key.mod.shift) - mods|=KEY_MASK_SHIFT; + mods |= KEY_MASK_SHIFT; if (ie.key.mod.control) - mods|=KEY_MASK_CTRL; + mods |= KEY_MASK_CTRL; if (ie.key.mod.alt) - mods|=KEY_MASK_ALT; + mods |= KEY_MASK_ALT; if (ie.key.mod.meta) - mods|=KEY_MASK_META; + mods |= KEY_MASK_META; - encode_uint32(mods,&buf[llen]); - encode_uint32(ie.key.scancode,&buf[llen+4]); + encode_uint32(mods, &buf[llen]); + encode_uint32(ie.key.scancode, &buf[llen + 4]); } - llen+=8; + llen += 8; } break; case InputEvent::MOUSE_BUTTON: { if (buf) { - encode_uint32(ie.mouse_button.button_index,&buf[llen]); + encode_uint32(ie.mouse_button.button_index, &buf[llen]); } - llen+=4; + llen += 4; } break; case InputEvent::JOYPAD_BUTTON: { if (buf) { - encode_uint32(ie.joy_button.button_index,&buf[llen]); + encode_uint32(ie.joy_button.button_index, &buf[llen]); } - llen+=4; + llen += 4; } break; case InputEvent::SCREEN_TOUCH: { if (buf) { - encode_uint32(ie.screen_touch.index,&buf[llen]); + encode_uint32(ie.screen_touch.index, &buf[llen]); } - llen+=4; + llen += 4; } break; case InputEvent::JOYPAD_MOTION: { if (buf) { int axis = ie.joy_motion.axis; - encode_uint32(axis,&buf[llen]); - encode_float(ie.joy_motion.axis_value, &buf[llen+4]); + encode_uint32(axis, &buf[llen]); + encode_float(ie.joy_motion.axis_value, &buf[llen + 4]); } - llen+=8; + llen += 8; } break; } if (buf) - encode_uint32(llen,&buf[8]); - r_len+=llen; - + encode_uint32(llen, &buf[8]); + r_len += llen; // not supported } break; @@ -1228,16 +1192,15 @@ Error encode_variant(const Variant& p_variant, uint8_t *r_buffer, int &r_len) { Dictionary d = p_variant; if (buf) { - encode_uint32(uint32_t(d.size()),buf); - buf+=4; + encode_uint32(uint32_t(d.size()), buf); + buf += 4; } - r_len+=4; + r_len += 4; List<Variant> keys; d.get_key_list(&keys); - - for(List<Variant>::Element *E=keys.front();E;E=E->next()) { + for (List<Variant>::Element *E = keys.front(); E; E = E->next()) { /* CharString utf8 = E->->utf8(); @@ -1253,14 +1216,14 @@ Error encode_variant(const Variant& p_variant, uint8_t *r_buffer, int &r_len) { r_len++; //pad */ int len; - encode_variant(E->get(),buf,len); - ERR_FAIL_COND_V(len%4,ERR_BUG); - r_len+=len; + encode_variant(E->get(), buf, len); + ERR_FAIL_COND_V(len % 4, ERR_BUG); + r_len += len; if (buf) buf += len; - encode_variant(d[E->get()],buf,len); - ERR_FAIL_COND_V(len%4,ERR_BUG); - r_len+=len; + encode_variant(d[E->get()], buf, len); + ERR_FAIL_COND_V(len % 4, ERR_BUG); + r_len += len; if (buf) buf += len; } @@ -1271,107 +1234,101 @@ Error encode_variant(const Variant& p_variant, uint8_t *r_buffer, int &r_len) { Array v = p_variant; if (buf) { - encode_uint32(uint32_t(v.size()),buf); - buf+=4; + encode_uint32(uint32_t(v.size()), buf); + buf += 4; } - r_len+=4; + r_len += 4; - for(int i=0;i<v.size();i++) { + for (int i = 0; i < v.size(); i++) { int len; - encode_variant(v.get(i),buf,len); - ERR_FAIL_COND_V(len%4,ERR_BUG); - r_len+=len; + encode_variant(v.get(i), buf, len); + ERR_FAIL_COND_V(len % 4, ERR_BUG); + r_len += len; if (buf) - buf+=len; + buf += len; } - } break; // arrays case Variant::POOL_BYTE_ARRAY: { PoolVector<uint8_t> data = p_variant; - int datalen=data.size(); - int datasize=sizeof(uint8_t); + int datalen = data.size(); + int datasize = sizeof(uint8_t); if (buf) { - encode_uint32(datalen,buf); - buf+=4; + encode_uint32(datalen, buf); + buf += 4; PoolVector<uint8_t>::Read r = data.read(); - copymem(buf,&r[0],datalen*datasize); - + copymem(buf, &r[0], datalen * datasize); } - r_len+=4+datalen*datasize; - while(r_len%4) + r_len += 4 + datalen * datasize; + while (r_len % 4) r_len++; } break; case Variant::POOL_INT_ARRAY: { PoolVector<int> data = p_variant; - int datalen=data.size(); - int datasize=sizeof(int32_t); + int datalen = data.size(); + int datasize = sizeof(int32_t); if (buf) { - encode_uint32(datalen,buf); - buf+=4; + encode_uint32(datalen, buf); + buf += 4; PoolVector<int>::Read r = data.read(); - for(int i=0;i<datalen;i++) - encode_uint32(r[i],&buf[i*datasize]); - + for (int i = 0; i < datalen; i++) + encode_uint32(r[i], &buf[i * datasize]); } - r_len+=4+datalen*datasize; + r_len += 4 + datalen * datasize; } break; case Variant::POOL_REAL_ARRAY: { PoolVector<real_t> data = p_variant; - int datalen=data.size(); - int datasize=sizeof(real_t); + int datalen = data.size(); + int datasize = sizeof(real_t); if (buf) { - encode_uint32(datalen,buf); - buf+=4; + encode_uint32(datalen, buf); + buf += 4; PoolVector<real_t>::Read r = data.read(); - for(int i=0;i<datalen;i++) - encode_float(r[i],&buf[i*datasize]); - + for (int i = 0; i < datalen; i++) + encode_float(r[i], &buf[i * datasize]); } - r_len+=4+datalen*datasize; + r_len += 4 + datalen * datasize; } break; case Variant::POOL_STRING_ARRAY: { - PoolVector<String> data = p_variant; - int len=data.size(); + int len = data.size(); if (buf) { - encode_uint32(len,buf); - buf+=4; + encode_uint32(len, buf); + buf += 4; } - r_len+=4; - - for(int i=0;i<len;i++) { + r_len += 4; + for (int i = 0; i < len; i++) { CharString utf8 = data.get(i).utf8(); if (buf) { - encode_uint32(utf8.length()+1,buf); - buf+=4; - copymem(buf,utf8.get_data(),utf8.length()+1); - buf+=utf8.length()+1; + encode_uint32(utf8.length() + 1, buf); + buf += 4; + copymem(buf, utf8.get_data(), utf8.length() + 1); + buf += utf8.length() + 1; } - r_len+=4+utf8.length()+1; - while (r_len%4) { + r_len += 4 + utf8.length() + 1; + while (r_len % 4) { r_len++; //pad if (buf) buf++; @@ -1382,95 +1339,89 @@ Error encode_variant(const Variant& p_variant, uint8_t *r_buffer, int &r_len) { case Variant::POOL_VECTOR2_ARRAY: { PoolVector<Vector2> data = p_variant; - int len=data.size(); + int len = data.size(); if (buf) { - encode_uint32(len,buf); - buf+=4; + encode_uint32(len, buf); + buf += 4; } - r_len+=4; + r_len += 4; if (buf) { - for(int i=0;i<len;i++) { + for (int i = 0; i < len; i++) { Vector2 v = data.get(i); - encode_float(v.x,&buf[0]); - encode_float(v.y,&buf[4]); - buf+=4*2; - + encode_float(v.x, &buf[0]); + encode_float(v.y, &buf[4]); + buf += 4 * 2; } } - r_len+=4*2*len; + r_len += 4 * 2 * len; } break; case Variant::POOL_VECTOR3_ARRAY: { PoolVector<Vector3> data = p_variant; - int len=data.size(); + int len = data.size(); if (buf) { - encode_uint32(len,buf); - buf+=4; + encode_uint32(len, buf); + buf += 4; } - r_len+=4; + r_len += 4; if (buf) { - for(int i=0;i<len;i++) { + for (int i = 0; i < len; i++) { Vector3 v = data.get(i); - encode_float(v.x,&buf[0]); - encode_float(v.y,&buf[4]); - encode_float(v.z,&buf[8]); - buf+=4*3; - + encode_float(v.x, &buf[0]); + encode_float(v.y, &buf[4]); + encode_float(v.z, &buf[8]); + buf += 4 * 3; } } - r_len+=4*3*len; + r_len += 4 * 3 * len; } break; case Variant::POOL_COLOR_ARRAY: { PoolVector<Color> data = p_variant; - int len=data.size(); + int len = data.size(); if (buf) { - encode_uint32(len,buf); - buf+=4; + encode_uint32(len, buf); + buf += 4; } - r_len+=4; + r_len += 4; if (buf) { - for(int i=0;i<len;i++) { + for (int i = 0; i < len; i++) { Color c = data.get(i); - - encode_float(c.r,&buf[0]); - encode_float(c.g,&buf[4]); - encode_float(c.b,&buf[8]); - encode_float(c.a,&buf[12]); - buf+=4*4; + encode_float(c.r, &buf[0]); + encode_float(c.g, &buf[4]); + encode_float(c.b, &buf[8]); + encode_float(c.a, &buf[12]); + buf += 4 * 4; } } - r_len+=4*4*len; + r_len += 4 * 4 * len; } break; default: { ERR_FAIL_V(ERR_BUG); } } return OK; - } - - diff --git a/core/io/marshalls.h b/core/io/marshalls.h index f04ec9a256..939ed9cea9 100644 --- a/core/io/marshalls.h +++ b/core/io/marshalls.h @@ -38,7 +38,6 @@ * in an endian independent way */ - union MarshallFloat { uint32_t i; ///< int @@ -53,41 +52,44 @@ union MarshallDouble { static inline unsigned int encode_uint16(uint16_t p_uint, uint8_t *p_arr) { - for (int i=0;i<2;i++) { + for (int i = 0; i < 2; i++) { - *p_arr=p_uint&0xFF; - p_arr++; p_uint>>=8; + *p_arr = p_uint & 0xFF; + p_arr++; + p_uint >>= 8; } - return sizeof( uint16_t ); + return sizeof(uint16_t); } static inline unsigned int encode_uint32(uint32_t p_uint, uint8_t *p_arr) { - for (int i=0;i<4;i++) { + for (int i = 0; i < 4; i++) { - *p_arr=p_uint&0xFF; - p_arr++; p_uint>>=8; + *p_arr = p_uint & 0xFF; + p_arr++; + p_uint >>= 8; } - return sizeof( uint32_t ); + return sizeof(uint32_t); } static inline unsigned int encode_float(float p_float, uint8_t *p_arr) { MarshallFloat mf; - mf.f=p_float; - encode_uint32( mf.i, p_arr ); + mf.f = p_float; + encode_uint32(mf.i, p_arr); - return sizeof( uint32_t ); + return sizeof(uint32_t); } static inline unsigned int encode_uint64(uint64_t p_uint, uint8_t *p_arr) { - for (int i=0;i<8;i++) { + for (int i = 0; i < 8; i++) { - *p_arr=p_uint&0xFF; - p_arr++; p_uint>>=8; + *p_arr = p_uint & 0xFF; + p_arr++; + p_uint >>= 8; } return sizeof(uint64_t); @@ -96,23 +98,21 @@ static inline unsigned int encode_uint64(uint64_t p_uint, uint8_t *p_arr) { static inline unsigned int encode_double(double p_double, uint8_t *p_arr) { MarshallDouble md; - md.d=p_double; - encode_uint64( md.l, p_arr ); + md.d = p_double; + encode_uint64(md.l, p_arr); return sizeof(uint64_t); - } +static inline int encode_cstring(const char *p_string, uint8_t *p_data) { -static inline int encode_cstring(const char *p_string, uint8_t * p_data) { - - int len=0; + int len = 0; while (*p_string) { if (p_data) { - *p_data=(uint8_t)*p_string; + *p_data = (uint8_t)*p_string; p_data++; } p_string++; @@ -120,18 +120,18 @@ static inline int encode_cstring(const char *p_string, uint8_t * p_data) { }; if (p_data) *p_data = 0; - return len+1; + return len + 1; } static inline uint16_t decode_uint16(const uint8_t *p_arr) { - uint16_t u=0; + uint16_t u = 0; - for (int i=0;i<2;i++) { + for (int i = 0; i < 2; i++) { uint16_t b = *p_arr; - b<<=(i*8); - u|=b; + b <<= (i * 8); + u |= b; p_arr++; } @@ -140,13 +140,13 @@ static inline uint16_t decode_uint16(const uint8_t *p_arr) { static inline uint32_t decode_uint32(const uint8_t *p_arr) { - uint32_t u=0; + uint32_t u = 0; - for (int i=0;i<4;i++) { + for (int i = 0; i < 4; i++) { uint32_t b = *p_arr; - b<<=(i*8); - u|=b; + b <<= (i * 8); + u |= b; p_arr++; } @@ -162,13 +162,13 @@ static inline float decode_float(const uint8_t *p_arr) { static inline uint64_t decode_uint64(const uint8_t *p_arr) { - uint64_t u=0; + uint64_t u = 0; - for (int i=0;i<8;i++) { + for (int i = 0; i < 8; i++) { - uint64_t b = (*p_arr)&0xFF; - b<<=(i*8); - u|=b; + uint64_t b = (*p_arr) & 0xFF; + b <<= (i * 8); + u |= b; p_arr++; } @@ -178,13 +178,11 @@ static inline uint64_t decode_uint64(const uint8_t *p_arr) { static inline double decode_double(const uint8_t *p_arr) { MarshallDouble md; - md.l = decode_uint64( p_arr ); + md.l = decode_uint64(p_arr); return md.d; - } - -Error decode_variant(Variant& r_variant,const uint8_t *p_buffer, int p_len,int *r_len=NULL); -Error encode_variant(const Variant& p_variant, uint8_t *r_buffer, int &r_len); +Error decode_variant(Variant &r_variant, const uint8_t *p_buffer, int p_len, int *r_len = NULL); +Error encode_variant(const Variant &p_variant, uint8_t *r_buffer, int &r_len); #endif diff --git a/core/io/networked_multiplayer_peer.cpp b/core/io/networked_multiplayer_peer.cpp index fb81a806e2..da661d0981 100644 --- a/core/io/networked_multiplayer_peer.cpp +++ b/core/io/networked_multiplayer_peer.cpp @@ -28,42 +28,38 @@ /*************************************************************************/ #include "networked_multiplayer_peer.h" - void NetworkedMultiplayerPeer::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_transfer_mode","mode"), &NetworkedMultiplayerPeer::set_transfer_mode ); - ClassDB::bind_method(D_METHOD("set_target_peer","id"), &NetworkedMultiplayerPeer::set_target_peer ); - - ClassDB::bind_method(D_METHOD("get_packet_peer"), &NetworkedMultiplayerPeer::get_packet_peer ); + ClassDB::bind_method(D_METHOD("set_transfer_mode", "mode"), &NetworkedMultiplayerPeer::set_transfer_mode); + ClassDB::bind_method(D_METHOD("set_target_peer", "id"), &NetworkedMultiplayerPeer::set_target_peer); - ClassDB::bind_method(D_METHOD("poll"), &NetworkedMultiplayerPeer::poll ); + ClassDB::bind_method(D_METHOD("get_packet_peer"), &NetworkedMultiplayerPeer::get_packet_peer); - ClassDB::bind_method(D_METHOD("get_connection_status"), &NetworkedMultiplayerPeer::get_connection_status ); - ClassDB::bind_method(D_METHOD("get_unique_id"), &NetworkedMultiplayerPeer::get_unique_id ); + ClassDB::bind_method(D_METHOD("poll"), &NetworkedMultiplayerPeer::poll); - ClassDB::bind_method(D_METHOD("set_refuse_new_connections","enable"), &NetworkedMultiplayerPeer::set_refuse_new_connections ); - ClassDB::bind_method(D_METHOD("is_refusing_new_connections"), &NetworkedMultiplayerPeer::is_refusing_new_connections ); + ClassDB::bind_method(D_METHOD("get_connection_status"), &NetworkedMultiplayerPeer::get_connection_status); + ClassDB::bind_method(D_METHOD("get_unique_id"), &NetworkedMultiplayerPeer::get_unique_id); - BIND_CONSTANT( TRANSFER_MODE_UNRELIABLE ); - BIND_CONSTANT( TRANSFER_MODE_UNRELIABLE_ORDERED ); - BIND_CONSTANT( TRANSFER_MODE_RELIABLE ); + ClassDB::bind_method(D_METHOD("set_refuse_new_connections", "enable"), &NetworkedMultiplayerPeer::set_refuse_new_connections); + ClassDB::bind_method(D_METHOD("is_refusing_new_connections"), &NetworkedMultiplayerPeer::is_refusing_new_connections); - BIND_CONSTANT( CONNECTION_DISCONNECTED ); - BIND_CONSTANT( CONNECTION_CONNECTING ); - BIND_CONSTANT( CONNECTION_CONNECTED ); + BIND_CONSTANT(TRANSFER_MODE_UNRELIABLE); + BIND_CONSTANT(TRANSFER_MODE_UNRELIABLE_ORDERED); + BIND_CONSTANT(TRANSFER_MODE_RELIABLE); - BIND_CONSTANT( TARGET_PEER_BROADCAST ); - BIND_CONSTANT( TARGET_PEER_SERVER ); + BIND_CONSTANT(CONNECTION_DISCONNECTED); + BIND_CONSTANT(CONNECTION_CONNECTING); + BIND_CONSTANT(CONNECTION_CONNECTED); + BIND_CONSTANT(TARGET_PEER_BROADCAST); + BIND_CONSTANT(TARGET_PEER_SERVER); - ADD_SIGNAL( MethodInfo("peer_connected",PropertyInfo(Variant::INT,"id"))); - ADD_SIGNAL( MethodInfo("peer_disconnected",PropertyInfo(Variant::INT,"id"))); - ADD_SIGNAL( MethodInfo("server_disconnected")); - ADD_SIGNAL( MethodInfo("connection_succeeded") ); - ADD_SIGNAL( MethodInfo("connection_failed") ); + ADD_SIGNAL(MethodInfo("peer_connected", PropertyInfo(Variant::INT, "id"))); + ADD_SIGNAL(MethodInfo("peer_disconnected", PropertyInfo(Variant::INT, "id"))); + ADD_SIGNAL(MethodInfo("server_disconnected")); + ADD_SIGNAL(MethodInfo("connection_succeeded")); + ADD_SIGNAL(MethodInfo("connection_failed")); } NetworkedMultiplayerPeer::NetworkedMultiplayerPeer() { - - } diff --git a/core/io/networked_multiplayer_peer.h b/core/io/networked_multiplayer_peer.h index 5d859a2f25..1324a61c72 100644 --- a/core/io/networked_multiplayer_peer.h +++ b/core/io/networked_multiplayer_peer.h @@ -33,15 +33,15 @@ class NetworkedMultiplayerPeer : public PacketPeer { - GDCLASS(NetworkedMultiplayerPeer,PacketPeer); + GDCLASS(NetworkedMultiplayerPeer, PacketPeer); protected: static void _bind_methods(); -public: +public: enum { - TARGET_PEER_BROADCAST=0, - TARGET_PEER_SERVER=1 + TARGET_PEER_BROADCAST = 0, + TARGET_PEER_SERVER = 1 }; enum TransferMode { TRANSFER_MODE_UNRELIABLE, @@ -55,28 +55,26 @@ public: CONNECTION_CONNECTED, }; + virtual void set_transfer_mode(TransferMode p_mode) = 0; + virtual void set_target_peer(int p_peer_id) = 0; - virtual void set_transfer_mode(TransferMode p_mode)=0; - virtual void set_target_peer(int p_peer_id)=0; - - virtual int get_packet_peer() const=0; - - virtual bool is_server() const=0; + virtual int get_packet_peer() const = 0; - virtual void poll()=0; + virtual bool is_server() const = 0; - virtual int get_unique_id() const=0; + virtual void poll() = 0; - virtual void set_refuse_new_connections(bool p_enable)=0; - virtual bool is_refusing_new_connections() const=0; + virtual int get_unique_id() const = 0; + virtual void set_refuse_new_connections(bool p_enable) = 0; + virtual bool is_refusing_new_connections() const = 0; - virtual ConnectionStatus get_connection_status() const=0; + virtual ConnectionStatus get_connection_status() const = 0; NetworkedMultiplayerPeer(); }; -VARIANT_ENUM_CAST( NetworkedMultiplayerPeer::TransferMode ) -VARIANT_ENUM_CAST( NetworkedMultiplayerPeer::ConnectionStatus ) +VARIANT_ENUM_CAST(NetworkedMultiplayerPeer::TransferMode) +VARIANT_ENUM_CAST(NetworkedMultiplayerPeer::ConnectionStatus) #endif // NetworkedMultiplayerPeer_H diff --git a/core/io/packet_peer.cpp b/core/io/packet_peer.cpp index cf5883121f..8115673d46 100644 --- a/core/io/packet_peer.cpp +++ b/core/io/packet_peer.cpp @@ -28,77 +28,71 @@ /*************************************************************************/ #include "packet_peer.h" -#include "io/marshalls.h" #include "global_config.h" +#include "io/marshalls.h" /* helpers / binders */ - - PacketPeer::PacketPeer() { - last_get_error=OK; + last_get_error = OK; } Error PacketPeer::get_packet_buffer(PoolVector<uint8_t> &r_buffer) const { const uint8_t *buffer; int buffer_size; - Error err = get_packet(&buffer,buffer_size); + Error err = get_packet(&buffer, buffer_size); if (err) return err; r_buffer.resize(buffer_size); - if (buffer_size==0) + if (buffer_size == 0) return OK; PoolVector<uint8_t>::Write w = r_buffer.write(); - for(int i=0;i<buffer_size;i++) - w[i]=buffer[i]; + for (int i = 0; i < buffer_size; i++) + w[i] = buffer[i]; return OK; - } Error PacketPeer::put_packet_buffer(const PoolVector<uint8_t> &p_buffer) { int len = p_buffer.size(); - if (len==0) + if (len == 0) return OK; PoolVector<uint8_t>::Read r = p_buffer.read(); - return put_packet(&r[0],len); - + return put_packet(&r[0], len); } Error PacketPeer::get_var(Variant &r_variant) const { const uint8_t *buffer; int buffer_size; - Error err = get_packet(&buffer,buffer_size); + Error err = get_packet(&buffer, buffer_size); if (err) return err; - return decode_variant(r_variant,buffer,buffer_size); - + return decode_variant(r_variant, buffer, buffer_size); } -Error PacketPeer::put_var(const Variant& p_packet) { +Error PacketPeer::put_var(const Variant &p_packet) { int len; - Error err = encode_variant(p_packet,NULL,len); // compute len first + Error err = encode_variant(p_packet, NULL, len); // compute len first if (err) return err; - if (len==0) + if (len == 0) return OK; - uint8_t *buf = (uint8_t*)alloca(len); - ERR_FAIL_COND_V(!buf,ERR_OUT_OF_MEMORY); - err = encode_variant(p_packet,buf,len); + uint8_t *buf = (uint8_t *)alloca(len); + ERR_FAIL_COND_V(!buf, ERR_OUT_OF_MEMORY); + err = encode_variant(p_packet, buf, len); ERR_FAIL_COND_V(err, err); return put_packet(buf, len); - } Variant PacketPeer::_bnd_get_var() const { @@ -108,13 +102,13 @@ Variant PacketPeer::_bnd_get_var() const { return var; }; -Error PacketPeer::_put_packet(const PoolVector<uint8_t> &p_buffer) { +Error PacketPeer::_put_packet(const PoolVector<uint8_t> &p_buffer) { return put_packet_buffer(p_buffer); } PoolVector<uint8_t> PacketPeer::_get_packet() const { PoolVector<uint8_t> raw; - last_get_error=get_packet_buffer(raw); + last_get_error = get_packet_buffer(raw); return raw; } @@ -123,20 +117,18 @@ Error PacketPeer::_get_packet_error() const { return last_get_error; } - void PacketPeer::_bind_methods() { - ClassDB::bind_method(D_METHOD("get_var:Variant"),&PacketPeer::_bnd_get_var); - ClassDB::bind_method(D_METHOD("put_var", "var:Variant"),&PacketPeer::put_var); - ClassDB::bind_method(D_METHOD("get_packet"),&PacketPeer::_get_packet); - ClassDB::bind_method(D_METHOD("put_packet:Error", "buffer"),&PacketPeer::_put_packet); - ClassDB::bind_method(D_METHOD("get_packet_error:Error"),&PacketPeer::_get_packet_error); - ClassDB::bind_method(D_METHOD("get_available_packet_count"),&PacketPeer::get_available_packet_count); + ClassDB::bind_method(D_METHOD("get_var:Variant"), &PacketPeer::_bnd_get_var); + ClassDB::bind_method(D_METHOD("put_var", "var:Variant"), &PacketPeer::put_var); + ClassDB::bind_method(D_METHOD("get_packet"), &PacketPeer::_get_packet); + ClassDB::bind_method(D_METHOD("put_packet:Error", "buffer"), &PacketPeer::_put_packet); + ClassDB::bind_method(D_METHOD("get_packet_error:Error"), &PacketPeer::_get_packet_error); + ClassDB::bind_method(D_METHOD("get_available_packet_count"), &PacketPeer::get_available_packet_count); }; /***************/ - void PacketPeerStream::_set_stream_peer(REF p_peer) { ERR_FAIL_COND(p_peer.is_null()); @@ -145,22 +137,22 @@ void PacketPeerStream::_set_stream_peer(REF p_peer) { void PacketPeerStream::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_stream_peer","peer:StreamPeer"),&PacketPeerStream::_set_stream_peer); + ClassDB::bind_method(D_METHOD("set_stream_peer", "peer:StreamPeer"), &PacketPeerStream::_set_stream_peer); } Error PacketPeerStream::_poll_buffer() const { - ERR_FAIL_COND_V(peer.is_null(),ERR_UNCONFIGURED); + ERR_FAIL_COND_V(peer.is_null(), ERR_UNCONFIGURED); int read = 0; Error err = peer->get_partial_data(&temp_buffer[0], ring_buffer.space_left(), read); if (err) return err; - if (read==0) + if (read == 0) return OK; - int w = ring_buffer.write(&temp_buffer[0],read); - ERR_FAIL_COND_V(w!=read,ERR_BUG); + int w = ring_buffer.write(&temp_buffer[0], read); + ERR_FAIL_COND_V(w != read, ERR_BUG); return OK; } @@ -171,73 +163,71 @@ int PacketPeerStream::get_available_packet_count() const { uint32_t remaining = ring_buffer.data_left(); - int ofs=0; - int count=0; + int ofs = 0; + int count = 0; - while(remaining>=4) { + while (remaining >= 4) { uint8_t lbuf[4]; - ring_buffer.copy(lbuf,ofs,4); + ring_buffer.copy(lbuf, ofs, 4); uint32_t len = decode_uint32(lbuf); - remaining-=4; - ofs+=4; - if (len>remaining) + remaining -= 4; + ofs += 4; + if (len > remaining) break; - remaining-=len; - ofs+=len; + remaining -= len; + ofs += len; count++; } return count; } -Error PacketPeerStream::get_packet(const uint8_t **r_buffer,int &r_buffer_size) const { +Error PacketPeerStream::get_packet(const uint8_t **r_buffer, int &r_buffer_size) const { - ERR_FAIL_COND_V(peer.is_null(),ERR_UNCONFIGURED); + ERR_FAIL_COND_V(peer.is_null(), ERR_UNCONFIGURED); _poll_buffer(); int remaining = ring_buffer.data_left(); - ERR_FAIL_COND_V(remaining<4,ERR_UNAVAILABLE); + ERR_FAIL_COND_V(remaining < 4, ERR_UNAVAILABLE); uint8_t lbuf[4]; - ring_buffer.copy(lbuf,0,4); - remaining-=4; + ring_buffer.copy(lbuf, 0, 4); + remaining -= 4; uint32_t len = decode_uint32(lbuf); - ERR_FAIL_COND_V(remaining<(int)len,ERR_UNAVAILABLE); + ERR_FAIL_COND_V(remaining < (int)len, ERR_UNAVAILABLE); - ring_buffer.read(lbuf,4); //get rid of first 4 bytes - ring_buffer.read(&temp_buffer[0],len); // read packet + ring_buffer.read(lbuf, 4); //get rid of first 4 bytes + ring_buffer.read(&temp_buffer[0], len); // read packet - *r_buffer=&temp_buffer[0]; - r_buffer_size=len; + *r_buffer = &temp_buffer[0]; + r_buffer_size = len; return OK; - } -Error PacketPeerStream::put_packet(const uint8_t *p_buffer,int p_buffer_size) { +Error PacketPeerStream::put_packet(const uint8_t *p_buffer, int p_buffer_size) { - ERR_FAIL_COND_V(peer.is_null(),ERR_UNCONFIGURED); + ERR_FAIL_COND_V(peer.is_null(), ERR_UNCONFIGURED); Error err = _poll_buffer(); //won't hurt to poll here too if (err) return err; - if (p_buffer_size==0) + if (p_buffer_size == 0) return OK; - ERR_FAIL_COND_V( p_buffer_size<0, ERR_INVALID_PARAMETER); - ERR_FAIL_COND_V( p_buffer_size+4 > temp_buffer.size(), ERR_INVALID_PARAMETER ); + ERR_FAIL_COND_V(p_buffer_size < 0, ERR_INVALID_PARAMETER); + ERR_FAIL_COND_V(p_buffer_size + 4 > temp_buffer.size(), ERR_INVALID_PARAMETER); - encode_uint32(p_buffer_size,&temp_buffer[0]); - uint8_t *dst=&temp_buffer[4]; - for(int i=0;i<p_buffer_size;i++) - dst[i]=p_buffer[i]; + encode_uint32(p_buffer_size, &temp_buffer[0]); + uint8_t *dst = &temp_buffer[4]; + for (int i = 0; i < p_buffer_size; i++) + dst[i] = p_buffer[i]; - return peer->put_data(&temp_buffer[0],p_buffer_size+4); + return peer->put_data(&temp_buffer[0], p_buffer_size + 4); } int PacketPeerStream::get_max_packet_size() const { - return temp_buffer.size(); } @@ -249,7 +239,7 @@ void PacketPeerStream::set_stream_peer(const Ref<StreamPeer> &p_peer) { ring_buffer.advance_read(ring_buffer.data_left()); // reset the ring buffer }; - peer=p_peer; + peer = p_peer; } void PacketPeerStream::set_input_buffer_max_size(int p_max_size) { @@ -257,19 +247,14 @@ void PacketPeerStream::set_input_buffer_max_size(int p_max_size) { //warning may lose packets ERR_EXPLAIN("Buffer in use, resizing would cause loss of data"); ERR_FAIL_COND(ring_buffer.data_left()); - ring_buffer.resize(nearest_shift(p_max_size+4)); - temp_buffer.resize(nearest_power_of_2(p_max_size+4)); - + ring_buffer.resize(nearest_shift(p_max_size + 4)); + temp_buffer.resize(nearest_power_of_2(p_max_size + 4)); } PacketPeerStream::PacketPeerStream() { - - int rbsize=GLOBAL_GET( "network/packets/packet_stream_peer_max_buffer_po2"); - + int rbsize = GLOBAL_GET("network/packets/packet_stream_peer_max_buffer_po2"); ring_buffer.resize(rbsize); - temp_buffer.resize(1<<rbsize); - - + temp_buffer.resize(1 << rbsize); } diff --git a/core/io/packet_peer.h b/core/io/packet_peer.h index bacd5214f1..5f8d63f8c8 100644 --- a/core/io/packet_peer.h +++ b/core/io/packet_peer.h @@ -29,33 +29,30 @@ #ifndef PACKET_PEER_H #define PACKET_PEER_H -#include "object.h" #include "io/stream_peer.h" +#include "object.h" #include "ring_buffer.h" class PacketPeer : public Reference { - GDCLASS( PacketPeer, Reference ); + GDCLASS(PacketPeer, Reference); Variant _bnd_get_var() const; - void _bnd_put_var(const Variant& p_var); + void _bnd_put_var(const Variant &p_var); static void _bind_methods(); - Error _put_packet(const PoolVector<uint8_t> &p_buffer); PoolVector<uint8_t> _get_packet() const; Error _get_packet_error() const; - mutable Error last_get_error; public: + virtual int get_available_packet_count() const = 0; + virtual Error get_packet(const uint8_t **r_buffer, int &r_buffer_size) const = 0; ///< buffer is GONE after next get_packet + virtual Error put_packet(const uint8_t *p_buffer, int p_buffer_size) = 0; - virtual int get_available_packet_count() const=0; - virtual Error get_packet(const uint8_t **r_buffer,int &r_buffer_size) const=0; ///< buffer is GONE after next get_packet - virtual Error put_packet(const uint8_t *p_buffer,int p_buffer_size)=0; - - virtual int get_max_packet_size() const=0; + virtual int get_max_packet_size() const = 0; /* helpers / binders */ @@ -63,15 +60,15 @@ public: virtual Error put_packet_buffer(const PoolVector<uint8_t> &p_buffer); virtual Error get_var(Variant &r_variant) const; - virtual Error put_var(const Variant& p_packet); + virtual Error put_var(const Variant &p_packet); PacketPeer(); - ~PacketPeer(){} + ~PacketPeer() {} }; class PacketPeerStream : public PacketPeer { - GDCLASS(PacketPeerStream,PacketPeer); + GDCLASS(PacketPeerStream, PacketPeer); //the way the buffers work sucks, will change later @@ -80,25 +77,21 @@ class PacketPeerStream : public PacketPeer { mutable Vector<uint8_t> temp_buffer; Error _poll_buffer() const; -protected: +protected: void _set_stream_peer(REF p_peer); static void _bind_methods(); -public: +public: virtual int get_available_packet_count() const; - virtual Error get_packet(const uint8_t **r_buffer,int &r_buffer_size) const; - virtual Error put_packet(const uint8_t *p_buffer,int p_buffer_size); + virtual Error get_packet(const uint8_t **r_buffer, int &r_buffer_size) const; + virtual Error put_packet(const uint8_t *p_buffer, int p_buffer_size); virtual int get_max_packet_size() const; - - - void set_stream_peer(const Ref<StreamPeer>& p_peer); + void set_stream_peer(const Ref<StreamPeer> &p_peer); void set_input_buffer_max_size(int p_max_size); PacketPeerStream(); - }; - #endif // PACKET_STREAM_H diff --git a/core/io/packet_peer_udp.cpp b/core/io/packet_peer_udp.cpp index c4a6fd79a8..46accf420a 100644 --- a/core/io/packet_peer_udp.cpp +++ b/core/io/packet_peer_udp.cpp @@ -29,40 +29,38 @@ #include "packet_peer_udp.h" #include "io/ip.h" -PacketPeerUDP* (*PacketPeerUDP::_create)()=NULL; +PacketPeerUDP *(*PacketPeerUDP::_create)() = NULL; String PacketPeerUDP::_get_packet_ip() const { return get_packet_address(); } -Error PacketPeerUDP::_set_dest_address(const String& p_address, int p_port) { +Error PacketPeerUDP::_set_dest_address(const String &p_address, int p_port) { IP_Address ip; if (p_address.is_valid_ip_address()) { - ip=p_address; + ip = p_address; } else { - ip=IP::get_singleton()->resolve_hostname(p_address); + ip = IP::get_singleton()->resolve_hostname(p_address); if (!ip.is_valid()) return ERR_CANT_RESOLVE; } - set_dest_address(ip,p_port); + set_dest_address(ip, p_port); return OK; } void PacketPeerUDP::_bind_methods() { - ClassDB::bind_method(D_METHOD("listen:Error","port", "bind_address", "recv_buf_size"),&PacketPeerUDP::listen,DEFVAL("*"),DEFVAL(65536)); - ClassDB::bind_method(D_METHOD("close"),&PacketPeerUDP::close); - ClassDB::bind_method(D_METHOD("wait:Error"),&PacketPeerUDP::wait); - ClassDB::bind_method(D_METHOD("is_listening"),&PacketPeerUDP::is_listening); - ClassDB::bind_method(D_METHOD("get_packet_ip"),&PacketPeerUDP::_get_packet_ip); + ClassDB::bind_method(D_METHOD("listen:Error", "port", "bind_address", "recv_buf_size"), &PacketPeerUDP::listen, DEFVAL("*"), DEFVAL(65536)); + ClassDB::bind_method(D_METHOD("close"), &PacketPeerUDP::close); + ClassDB::bind_method(D_METHOD("wait:Error"), &PacketPeerUDP::wait); + ClassDB::bind_method(D_METHOD("is_listening"), &PacketPeerUDP::is_listening); + ClassDB::bind_method(D_METHOD("get_packet_ip"), &PacketPeerUDP::_get_packet_ip); //ClassDB::bind_method(D_METHOD("get_packet_address"),&PacketPeerUDP::_get_packet_address); - ClassDB::bind_method(D_METHOD("get_packet_port"),&PacketPeerUDP::get_packet_port); - ClassDB::bind_method(D_METHOD("set_dest_address","host","port"),&PacketPeerUDP::_set_dest_address); - - + ClassDB::bind_method(D_METHOD("get_packet_port"), &PacketPeerUDP::get_packet_port); + ClassDB::bind_method(D_METHOD("set_dest_address", "host", "port"), &PacketPeerUDP::_set_dest_address); } Ref<PacketPeerUDP> PacketPeerUDP::create_ref() { @@ -72,14 +70,12 @@ Ref<PacketPeerUDP> PacketPeerUDP::create_ref() { return Ref<PacketPeerUDP>(_create()); } -PacketPeerUDP* PacketPeerUDP::create() { +PacketPeerUDP *PacketPeerUDP::create() { if (!_create) return NULL; return _create(); } -PacketPeerUDP::PacketPeerUDP() -{ - +PacketPeerUDP::PacketPeerUDP() { } diff --git a/core/io/packet_peer_udp.h b/core/io/packet_peer_udp.h index 726406887c..c316faad4b 100644 --- a/core/io/packet_peer_udp.h +++ b/core/io/packet_peer_udp.h @@ -29,35 +29,31 @@ #ifndef PACKET_PEER_UDP_H #define PACKET_PEER_UDP_H - #include "io/ip.h" #include "io/packet_peer.h" class PacketPeerUDP : public PacketPeer { - GDCLASS(PacketPeerUDP,PacketPeer); + GDCLASS(PacketPeerUDP, PacketPeer); protected: - - static PacketPeerUDP* (*_create)(); + static PacketPeerUDP *(*_create)(); static void _bind_methods(); String _get_packet_ip() const; - Error _set_dest_address(const String& p_address,int p_port); + Error _set_dest_address(const String &p_address, int p_port); public: - - virtual Error listen(int p_port, IP_Address p_bind_address=IP_Address("*"), int p_recv_buffer_size=65536)=0; - virtual void close()=0; - virtual Error wait()=0; - virtual bool is_listening() const=0; - virtual IP_Address get_packet_address() const=0; - virtual int get_packet_port() const=0; - virtual void set_dest_address(const IP_Address& p_address,int p_port)=0; - + virtual Error listen(int p_port, IP_Address p_bind_address = IP_Address("*"), int p_recv_buffer_size = 65536) = 0; + virtual void close() = 0; + virtual Error wait() = 0; + virtual bool is_listening() const = 0; + virtual IP_Address get_packet_address() const = 0; + virtual int get_packet_port() const = 0; + virtual void set_dest_address(const IP_Address &p_address, int p_port) = 0; static Ref<PacketPeerUDP> create_ref(); - static PacketPeerUDP* create(); + static PacketPeerUDP *create(); PacketPeerUDP(); }; diff --git a/core/io/pck_packer.cpp b/core/io/pck_packer.cpp index 2cd46843e8..9dd9b044a2 100644 --- a/core/io/pck_packer.cpp +++ b/core/io/pck_packer.cpp @@ -42,9 +42,9 @@ static uint64_t _align(uint64_t p_n, int p_alignment) { return p_n + (p_alignment - rest); }; -static void _pad(FileAccess* p_file, int p_bytes) { +static void _pad(FileAccess *p_file, int p_bytes) { - for (int i=0; i<p_bytes; i++) { + for (int i = 0; i < p_bytes; i++) { p_file->store_8(0); }; @@ -52,13 +52,12 @@ static void _pad(FileAccess* p_file, int p_bytes) { void PCKPacker::_bind_methods() { - ClassDB::bind_method(D_METHOD("pck_start","pck_name","alignment"),&PCKPacker::pck_start); - ClassDB::bind_method(D_METHOD("add_file","pck_path","source_path"),&PCKPacker::add_file); - ClassDB::bind_method(D_METHOD("flush","verbose"),&PCKPacker::flush); + ClassDB::bind_method(D_METHOD("pck_start", "pck_name", "alignment"), &PCKPacker::pck_start); + ClassDB::bind_method(D_METHOD("add_file", "pck_path", "source_path"), &PCKPacker::add_file); + ClassDB::bind_method(D_METHOD("flush", "verbose"), &PCKPacker::flush); }; - -Error PCKPacker::pck_start(const String& p_file, int p_alignment) { +Error PCKPacker::pck_start(const String &p_file, int p_alignment) { file = FileAccess::open(p_file, FileAccess::WRITE); if (file == NULL) { @@ -74,7 +73,7 @@ Error PCKPacker::pck_start(const String& p_file, int p_alignment) { file->store_32(0); // # minor file->store_32(0); // # revision - for (int i=0; i<16; i++) { + for (int i = 0; i < 16; i++) { file->store_32(0); // reserved }; @@ -84,9 +83,9 @@ Error PCKPacker::pck_start(const String& p_file, int p_alignment) { return OK; }; -Error PCKPacker::add_file(const String& p_file, const String& p_src) { +Error PCKPacker::add_file(const String &p_file, const String &p_src) { - FileAccess* f = FileAccess::open(p_src, FileAccess::READ); + FileAccess *f = FileAccess::open(p_src, FileAccess::READ); if (!f) { return ERR_FILE_CANT_OPEN; }; @@ -116,7 +115,7 @@ Error PCKPacker::flush(bool p_verbose) { file->store_32(files.size()); - for (int i=0; i<files.size(); i++) { + for (int i = 0; i < files.size(); i++) { file->store_pascal_string(files[i].path); files[i].offset_offset = file->get_pos(); @@ -130,7 +129,6 @@ Error PCKPacker::flush(bool p_verbose) { file->store_32(0); }; - uint64_t ofs = file->get_pos(); ofs = _align(ofs, alignment); @@ -140,9 +138,9 @@ Error PCKPacker::flush(bool p_verbose) { uint8_t *buf = memnew_arr(uint8_t, buf_max); int count = 0; - for (int i=0; i<files.size(); i++) { + for (int i = 0; i < files.size(); i++) { - FileAccess* src = FileAccess::open(files[i].src_path, FileAccess::READ); + FileAccess *src = FileAccess::open(files[i].src_path, FileAccess::READ); uint64_t to_write = files[i].size; while (to_write > 0) { diff --git a/core/io/pck_packer.h b/core/io/pck_packer.h index a4eba04f2d..1edb14ab27 100644 --- a/core/io/pck_packer.h +++ b/core/io/pck_packer.h @@ -34,7 +34,7 @@ class PCKPacker : public Reference { GDCLASS(PCKPacker, Reference); - FileAccess* file; + FileAccess *file; int alignment; static void _bind_methods(); @@ -49,11 +49,10 @@ class PCKPacker : public Reference { Vector<File> files; public: - Error pck_start(const String& p_file, int p_alignment); - Error add_file(const String& p_file, const String& p_src); + Error pck_start(const String &p_file, int p_alignment); + Error add_file(const String &p_file, const String &p_src); Error flush(bool p_verbose = false); - PCKPacker(); ~PCKPacker(); }; diff --git a/core/io/resource_format_binary.cpp b/core/io/resource_format_binary.cpp index 2d733842fa..60dccebebf 100644 --- a/core/io/resource_format_binary.cpp +++ b/core/io/resource_format_binary.cpp @@ -26,315 +26,303 @@ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -#include "version.h" #include "resource_format_binary.h" #include "global_config.h" #include "io/file_access_compressed.h" #include "io/marshalls.h" #include "os/dir_access.h" +#include "version.h" //#define print_bl(m_what) print_line(m_what) #define print_bl(m_what) - enum { //numbering must be different from variant, in case new variant types are added (variant must be always contiguous for jumptable optimization) - VARIANT_NIL=1, - VARIANT_BOOL=2, - VARIANT_INT=3, - VARIANT_REAL=4, - VARIANT_STRING=5, - VARIANT_VECTOR2=10, - VARIANT_RECT2=11, - VARIANT_VECTOR3=12, - VARIANT_PLANE=13, - VARIANT_QUAT=14, - VARIANT_AABB=15, - VARIANT_MATRIX3=16, - VARIANT_TRANSFORM=17, - VARIANT_MATRIX32=18, - VARIANT_COLOR=20, - VARIANT_IMAGE=21, - VARIANT_NODE_PATH=22, - VARIANT_RID=23, - VARIANT_OBJECT=24, - VARIANT_INPUT_EVENT=25, - VARIANT_DICTIONARY=26, - VARIANT_ARRAY=30, - VARIANT_RAW_ARRAY=31, - VARIANT_INT_ARRAY=32, - VARIANT_REAL_ARRAY=33, - VARIANT_STRING_ARRAY=34, - VARIANT_VECTOR3_ARRAY=35, - VARIANT_COLOR_ARRAY=36, - VARIANT_VECTOR2_ARRAY=37, - VARIANT_INT64=40, - VARIANT_DOUBLE=41, - - IMAGE_ENCODING_EMPTY=0, - IMAGE_ENCODING_RAW=1, - IMAGE_ENCODING_LOSSLESS=2, - IMAGE_ENCODING_LOSSY=3, - - OBJECT_EMPTY=0, - OBJECT_EXTERNAL_RESOURCE=1, - OBJECT_INTERNAL_RESOURCE=2, - OBJECT_EXTERNAL_RESOURCE_INDEX=3, + VARIANT_NIL = 1, + VARIANT_BOOL = 2, + VARIANT_INT = 3, + VARIANT_REAL = 4, + VARIANT_STRING = 5, + VARIANT_VECTOR2 = 10, + VARIANT_RECT2 = 11, + VARIANT_VECTOR3 = 12, + VARIANT_PLANE = 13, + VARIANT_QUAT = 14, + VARIANT_AABB = 15, + VARIANT_MATRIX3 = 16, + VARIANT_TRANSFORM = 17, + VARIANT_MATRIX32 = 18, + VARIANT_COLOR = 20, + VARIANT_IMAGE = 21, + VARIANT_NODE_PATH = 22, + VARIANT_RID = 23, + VARIANT_OBJECT = 24, + VARIANT_INPUT_EVENT = 25, + VARIANT_DICTIONARY = 26, + VARIANT_ARRAY = 30, + VARIANT_RAW_ARRAY = 31, + VARIANT_INT_ARRAY = 32, + VARIANT_REAL_ARRAY = 33, + VARIANT_STRING_ARRAY = 34, + VARIANT_VECTOR3_ARRAY = 35, + VARIANT_COLOR_ARRAY = 36, + VARIANT_VECTOR2_ARRAY = 37, + VARIANT_INT64 = 40, + VARIANT_DOUBLE = 41, + + IMAGE_ENCODING_EMPTY = 0, + IMAGE_ENCODING_RAW = 1, + IMAGE_ENCODING_LOSSLESS = 2, + IMAGE_ENCODING_LOSSY = 3, + + OBJECT_EMPTY = 0, + OBJECT_EXTERNAL_RESOURCE = 1, + OBJECT_INTERNAL_RESOURCE = 2, + OBJECT_EXTERNAL_RESOURCE_INDEX = 3, //version 2: added 64 bits support for float and int - FORMAT_VERSION=2, - FORMAT_VERSION_CAN_RENAME_DEPS=1 - + FORMAT_VERSION = 2, + FORMAT_VERSION_CAN_RENAME_DEPS = 1 }; - void ResourceInteractiveLoaderBinary::_advance_padding(uint32_t p_len) { - uint32_t extra = 4-(p_len%4); - if (extra<4) { - for(uint32_t i=0;i<extra;i++) + uint32_t extra = 4 - (p_len % 4); + if (extra < 4) { + for (uint32_t i = 0; i < extra; i++) f->get_8(); //pad to 32 } - } - StringName ResourceInteractiveLoaderBinary::_get_string() { uint32_t id = f->get_32(); - if (id&0x80000000) { - uint32_t len = id&0x7FFFFFFF; - if (len>str_buf.size()) { + if (id & 0x80000000) { + uint32_t len = id & 0x7FFFFFFF; + if (len > str_buf.size()) { str_buf.resize(len); } - if (len==0) + if (len == 0) return StringName(); - f->get_buffer((uint8_t*)&str_buf[0],len); + f->get_buffer((uint8_t *)&str_buf[0], len); String s; s.parse_utf8(&str_buf[0]); return s; } return string_map[id]; - } -Error ResourceInteractiveLoaderBinary::parse_variant(Variant& r_v) { - +Error ResourceInteractiveLoaderBinary::parse_variant(Variant &r_v) { uint32_t type = f->get_32(); - print_bl("find property of type: "+itos(type)); - + print_bl("find property of type: " + itos(type)); - switch(type) { + switch (type) { case VARIANT_NIL: { - r_v=Variant(); + r_v = Variant(); } break; case VARIANT_BOOL: { - r_v=bool(f->get_32()); + r_v = bool(f->get_32()); } break; case VARIANT_INT: { - r_v=int(f->get_32()); + r_v = int(f->get_32()); } break; case VARIANT_INT64: { - r_v=int64_t(f->get_64()); + r_v = int64_t(f->get_64()); } break; case VARIANT_REAL: { - r_v=f->get_real(); + r_v = f->get_real(); } break; case VARIANT_DOUBLE: { - r_v=f->get_double(); + r_v = f->get_double(); } break; case VARIANT_STRING: { - r_v=get_unicode_string(); + r_v = get_unicode_string(); } break; case VARIANT_VECTOR2: { Vector2 v; - v.x=f->get_real(); - v.y=f->get_real(); - r_v=v; + v.x = f->get_real(); + v.y = f->get_real(); + r_v = v; } break; case VARIANT_RECT2: { Rect2 v; - v.pos.x=f->get_real(); - v.pos.y=f->get_real(); - v.size.x=f->get_real(); - v.size.y=f->get_real(); - r_v=v; + v.pos.x = f->get_real(); + v.pos.y = f->get_real(); + v.size.x = f->get_real(); + v.size.y = f->get_real(); + r_v = v; } break; case VARIANT_VECTOR3: { Vector3 v; - v.x=f->get_real(); - v.y=f->get_real(); - v.z=f->get_real(); - r_v=v; + v.x = f->get_real(); + v.y = f->get_real(); + v.z = f->get_real(); + r_v = v; } break; case VARIANT_PLANE: { Plane v; - v.normal.x=f->get_real(); - v.normal.y=f->get_real(); - v.normal.z=f->get_real(); - v.d=f->get_real(); - r_v=v; + v.normal.x = f->get_real(); + v.normal.y = f->get_real(); + v.normal.z = f->get_real(); + v.d = f->get_real(); + r_v = v; } break; case VARIANT_QUAT: { Quat v; - v.x=f->get_real(); - v.y=f->get_real(); - v.z=f->get_real(); - v.w=f->get_real(); - r_v=v; + v.x = f->get_real(); + v.y = f->get_real(); + v.z = f->get_real(); + v.w = f->get_real(); + r_v = v; } break; case VARIANT_AABB: { Rect3 v; - v.pos.x=f->get_real(); - v.pos.y=f->get_real(); - v.pos.z=f->get_real(); - v.size.x=f->get_real(); - v.size.y=f->get_real(); - v.size.z=f->get_real(); - r_v=v; + v.pos.x = f->get_real(); + v.pos.y = f->get_real(); + v.pos.z = f->get_real(); + v.size.x = f->get_real(); + v.size.y = f->get_real(); + v.size.z = f->get_real(); + r_v = v; } break; case VARIANT_MATRIX32: { Transform2D v; - v.elements[0].x=f->get_real(); - v.elements[0].y=f->get_real(); - v.elements[1].x=f->get_real(); - v.elements[1].y=f->get_real(); - v.elements[2].x=f->get_real(); - v.elements[2].y=f->get_real(); - r_v=v; + v.elements[0].x = f->get_real(); + v.elements[0].y = f->get_real(); + v.elements[1].x = f->get_real(); + v.elements[1].y = f->get_real(); + v.elements[2].x = f->get_real(); + v.elements[2].y = f->get_real(); + r_v = v; } break; case VARIANT_MATRIX3: { Basis v; - v.elements[0].x=f->get_real(); - v.elements[0].y=f->get_real(); - v.elements[0].z=f->get_real(); - v.elements[1].x=f->get_real(); - v.elements[1].y=f->get_real(); - v.elements[1].z=f->get_real(); - v.elements[2].x=f->get_real(); - v.elements[2].y=f->get_real(); - v.elements[2].z=f->get_real(); - r_v=v; + v.elements[0].x = f->get_real(); + v.elements[0].y = f->get_real(); + v.elements[0].z = f->get_real(); + v.elements[1].x = f->get_real(); + v.elements[1].y = f->get_real(); + v.elements[1].z = f->get_real(); + v.elements[2].x = f->get_real(); + v.elements[2].y = f->get_real(); + v.elements[2].z = f->get_real(); + r_v = v; } break; case VARIANT_TRANSFORM: { Transform v; - v.basis.elements[0].x=f->get_real(); - v.basis.elements[0].y=f->get_real(); - v.basis.elements[0].z=f->get_real(); - v.basis.elements[1].x=f->get_real(); - v.basis.elements[1].y=f->get_real(); - v.basis.elements[1].z=f->get_real(); - v.basis.elements[2].x=f->get_real(); - v.basis.elements[2].y=f->get_real(); - v.basis.elements[2].z=f->get_real(); - v.origin.x=f->get_real(); - v.origin.y=f->get_real(); - v.origin.z=f->get_real(); - r_v=v; + v.basis.elements[0].x = f->get_real(); + v.basis.elements[0].y = f->get_real(); + v.basis.elements[0].z = f->get_real(); + v.basis.elements[1].x = f->get_real(); + v.basis.elements[1].y = f->get_real(); + v.basis.elements[1].z = f->get_real(); + v.basis.elements[2].x = f->get_real(); + v.basis.elements[2].y = f->get_real(); + v.basis.elements[2].z = f->get_real(); + v.origin.x = f->get_real(); + v.origin.y = f->get_real(); + v.origin.z = f->get_real(); + r_v = v; } break; case VARIANT_COLOR: { Color v; - v.r=f->get_real(); - v.g=f->get_real(); - v.b=f->get_real(); - v.a=f->get_real(); - r_v=v; + v.r = f->get_real(); + v.g = f->get_real(); + v.b = f->get_real(); + v.a = f->get_real(); + r_v = v; } break; case VARIANT_IMAGE: { - uint32_t encoding = f->get_32(); - if (encoding==IMAGE_ENCODING_EMPTY) { - r_v=Variant(); + if (encoding == IMAGE_ENCODING_EMPTY) { + r_v = Variant(); break; - } else if (encoding==IMAGE_ENCODING_RAW) { + } else if (encoding == IMAGE_ENCODING_RAW) { uint32_t width = f->get_32(); uint32_t height = f->get_32(); uint32_t mipmaps = f->get_32(); uint32_t format = f->get_32(); - const uint32_t format_version_shift=24; - const uint32_t format_version_mask=format_version_shift-1; + const uint32_t format_version_shift = 24; + const uint32_t format_version_mask = format_version_shift - 1; - uint32_t format_version = format>>format_version_shift; + uint32_t format_version = format >> format_version_shift; const uint32_t current_version = 0; - if (format_version>current_version) { + if (format_version > current_version) { ERR_PRINT("Format version for encoded binary image is too new"); return ERR_PARSE_ERROR; } - - Image::Format fmt=Image::Format(format&format_version_mask); //if format changes, we can add a compatibility bit on top + Image::Format fmt = Image::Format(format & format_version_mask); //if format changes, we can add a compatibility bit on top uint32_t datalen = f->get_32(); - print_line("image format: "+String(Image::get_format_name(fmt))+" datalen "+itos(datalen)); + print_line("image format: " + String(Image::get_format_name(fmt)) + " datalen " + itos(datalen)); PoolVector<uint8_t> imgdata; imgdata.resize(datalen); PoolVector<uint8_t>::Write w = imgdata.write(); - f->get_buffer(w.ptr(),datalen); + f->get_buffer(w.ptr(), datalen); _advance_padding(datalen); - w=PoolVector<uint8_t>::Write(); + w = PoolVector<uint8_t>::Write(); #ifdef TOOLS_ENABLED -//compatibility - int correct_size = Image::get_image_data_size(width,height,fmt,mipmaps?-1:0); + //compatibility + int correct_size = Image::get_image_data_size(width, height, fmt, mipmaps ? -1 : 0); if (correct_size < datalen) { WARN_PRINT("Image data was too large, shrinking for compatibility") imgdata.resize(correct_size); } #endif - r_v=Image(width,height,mipmaps,fmt,imgdata); + r_v = Image(width, height, mipmaps, fmt, imgdata); } else { //compressed PoolVector<uint8_t> data; data.resize(f->get_32()); PoolVector<uint8_t>::Write w = data.write(); - f->get_buffer(w.ptr(),data.size()); + f->get_buffer(w.ptr(), data.size()); w = PoolVector<uint8_t>::Write(); Image img; - if (encoding==IMAGE_ENCODING_LOSSY && Image::lossy_unpacker) { + if (encoding == IMAGE_ENCODING_LOSSY && Image::lossy_unpacker) { img = Image::lossy_unpacker(data); - } else if (encoding==IMAGE_ENCODING_LOSSLESS && Image::lossless_unpacker) { + } else if (encoding == IMAGE_ENCODING_LOSSLESS && Image::lossless_unpacker) { img = Image::lossless_unpacker(data); } _advance_padding(data.size()); - - r_v=img; - + r_v = img; } } break; @@ -347,44 +335,43 @@ Error ResourceInteractiveLoaderBinary::parse_variant(Variant& r_v) { int name_count = f->get_16(); uint32_t subname_count = f->get_16(); - absolute=subname_count&0x8000; - subname_count&=0x7FFF; - + absolute = subname_count & 0x8000; + subname_count &= 0x7FFF; - for(int i=0;i<name_count;i++) + for (int i = 0; i < name_count; i++) names.push_back(_get_string()); - for(uint32_t i=0;i<subname_count;i++) + for (uint32_t i = 0; i < subname_count; i++) subnames.push_back(_get_string()); - property=_get_string(); + property = _get_string(); - NodePath np = NodePath(names,subnames,absolute,property); + NodePath np = NodePath(names, subnames, absolute, property); //print_line("got path: "+String(np)); - r_v=np; + r_v = np; } break; case VARIANT_RID: { - r_v=f->get_32(); + r_v = f->get_32(); } break; case VARIANT_OBJECT: { - uint32_t type=f->get_32(); + uint32_t type = f->get_32(); - switch(type) { + switch (type) { case OBJECT_EMPTY: { //do none } break; case OBJECT_INTERNAL_RESOURCE: { - uint32_t index=f->get_32(); - String path = res_path+"::"+itos(index); + uint32_t index = f->get_32(); + String path = res_path + "::" + itos(index); RES res = ResourceLoader::load(path); if (res.is_null()) { - WARN_PRINT(String("Couldn't load resource: "+path).utf8().get_data()); + WARN_PRINT(String("Couldn't load resource: " + path).utf8().get_data()); } - r_v=res; + r_v = res; } break; case OBJECT_EXTERNAL_RESOURCE: { @@ -393,51 +380,48 @@ Error ResourceInteractiveLoaderBinary::parse_variant(Variant& r_v) { String type = get_unicode_string(); String path = get_unicode_string(); - if (path.find("://")==-1 && path.is_rel_path()) { + if (path.find("://") == -1 && path.is_rel_path()) { // path is relative to file being loaded, so convert to a resource path - path=GlobalConfig::get_singleton()->localize_path(res_path.get_base_dir().plus_file(path)); - + path = GlobalConfig::get_singleton()->localize_path(res_path.get_base_dir().plus_file(path)); } if (remaps.find(path)) { - path=remaps[path]; + path = remaps[path]; } - RES res=ResourceLoader::load(path,type); + RES res = ResourceLoader::load(path, type); if (res.is_null()) { - WARN_PRINT(String("Couldn't load resource: "+path).utf8().get_data()); + WARN_PRINT(String("Couldn't load resource: " + path).utf8().get_data()); } - r_v=res; + r_v = res; } break; case OBJECT_EXTERNAL_RESOURCE_INDEX: { //new file format, just refers to an index in the external list uint32_t erindex = f->get_32(); - if (erindex>=external_resources.size()) { + if (erindex >= external_resources.size()) { WARN_PRINT("Broken external resource! (index out of size"); - r_v=Variant(); + r_v = Variant(); } else { String type = external_resources[erindex].type; String path = external_resources[erindex].path; - if (path.find("://")==-1 && path.is_rel_path()) { + if (path.find("://") == -1 && path.is_rel_path()) { // path is relative to file being loaded, so convert to a resource path - path=GlobalConfig::get_singleton()->localize_path(res_path.get_base_dir().plus_file(path)); - + path = GlobalConfig::get_singleton()->localize_path(res_path.get_base_dir().plus_file(path)); } - RES res=ResourceLoader::load(path,type); + RES res = ResourceLoader::load(path, type); if (res.is_null()) { - WARN_PRINT(String("Couldn't load resource: "+path).utf8().get_data()); + WARN_PRINT(String("Couldn't load resource: " + path).utf8().get_data()); } - r_v=res; + r_v = res; } - } break; default: { @@ -449,39 +433,39 @@ Error ResourceInteractiveLoaderBinary::parse_variant(Variant& r_v) { case VARIANT_INPUT_EVENT: { InputEvent ev; - ev.type=f->get_32(); //will only work for null though. - r_v=ev; + ev.type = f->get_32(); //will only work for null though. + r_v = ev; } break; case VARIANT_DICTIONARY: { - uint32_t len=f->get_32(); + uint32_t len = f->get_32(); Dictionary d; //last bit means shared - len&=0x7FFFFFFF; - for(uint32_t i=0;i<len;i++) { + len &= 0x7FFFFFFF; + for (uint32_t i = 0; i < len; i++) { Variant key; Error err = parse_variant(key); - ERR_FAIL_COND_V(err,ERR_FILE_CORRUPT); + ERR_FAIL_COND_V(err, ERR_FILE_CORRUPT); Variant value; err = parse_variant(value); - ERR_FAIL_COND_V(err,ERR_FILE_CORRUPT); - d[key]=value; + ERR_FAIL_COND_V(err, ERR_FILE_CORRUPT); + d[key] = value; } - r_v=d; + r_v = d; } break; case VARIANT_ARRAY: { - uint32_t len=f->get_32(); + uint32_t len = f->get_32(); Array a; //last bit means shared - len&=0x7FFFFFFF; + len &= 0x7FFFFFFF; a.resize(len); - for(uint32_t i=0;i<len;i++) { + for (uint32_t i = 0; i < len; i++) { Variant val; Error err = parse_variant(val); - ERR_FAIL_COND_V(err,ERR_FILE_CORRUPT); - a[i]=val; + ERR_FAIL_COND_V(err, ERR_FILE_CORRUPT); + a[i] = val; } - r_v=a; + r_v = a; } break; case VARIANT_RAW_ARRAY: { @@ -491,10 +475,10 @@ Error ResourceInteractiveLoaderBinary::parse_variant(Variant& r_v) { PoolVector<uint8_t> array; array.resize(len); PoolVector<uint8_t>::Write w = array.write(); - f->get_buffer(w.ptr(),len); + f->get_buffer(w.ptr(), len); _advance_padding(len); - w=PoolVector<uint8_t>::Write(); - r_v=array; + w = PoolVector<uint8_t>::Write(); + r_v = array; } break; case VARIANT_INT_ARRAY: { @@ -504,19 +488,19 @@ Error ResourceInteractiveLoaderBinary::parse_variant(Variant& r_v) { PoolVector<int> array; array.resize(len); PoolVector<int>::Write w = array.write(); - f->get_buffer((uint8_t*)w.ptr(),len*4); + f->get_buffer((uint8_t *)w.ptr(), len * 4); #ifdef BIG_ENDIAN_ENABLED { - uint32_t *ptr=(uint32_t*)w.ptr(); - for(int i=0;i<len;i++) { + uint32_t *ptr = (uint32_t *)w.ptr(); + for (int i = 0; i < len; i++) { - ptr[i]=BSWAP32(ptr[i]); + ptr[i] = BSWAP32(ptr[i]); } } #endif - w=PoolVector<int>::Write(); - r_v=array; + w = PoolVector<int>::Write(); + r_v = array; } break; case VARIANT_REAL_ARRAY: { @@ -525,20 +509,20 @@ Error ResourceInteractiveLoaderBinary::parse_variant(Variant& r_v) { PoolVector<real_t> array; array.resize(len); PoolVector<real_t>::Write w = array.write(); - f->get_buffer((uint8_t*)w.ptr(),len*sizeof(real_t)); + f->get_buffer((uint8_t *)w.ptr(), len * sizeof(real_t)); #ifdef BIG_ENDIAN_ENABLED { - uint32_t *ptr=(uint32_t*)w.ptr(); - for(int i=0;i<len;i++) { + uint32_t *ptr = (uint32_t *)w.ptr(); + for (int i = 0; i < len; i++) { - ptr[i]=BSWAP32(ptr[i]); + ptr[i] = BSWAP32(ptr[i]); } } #endif - w=PoolVector<real_t>::Write(); - r_v=array; + w = PoolVector<real_t>::Write(); + r_v = array; } break; case VARIANT_STRING_ARRAY: { @@ -546,11 +530,10 @@ Error ResourceInteractiveLoaderBinary::parse_variant(Variant& r_v) { PoolVector<String> array; array.resize(len); PoolVector<String>::Write w = array.write(); - for(uint32_t i=0;i<len;i++) - w[i]=get_unicode_string(); - w=PoolVector<String>::Write(); - r_v=array; - + for (uint32_t i = 0; i < len; i++) + w[i] = get_unicode_string(); + w = PoolVector<String>::Write(); + r_v = array; } break; case VARIANT_VECTOR2_ARRAY: { @@ -560,16 +543,16 @@ Error ResourceInteractiveLoaderBinary::parse_variant(Variant& r_v) { PoolVector<Vector2> array; array.resize(len); PoolVector<Vector2>::Write w = array.write(); - if (sizeof(Vector2)==8) { - f->get_buffer((uint8_t*)w.ptr(),len*sizeof(real_t)*2); + if (sizeof(Vector2) == 8) { + f->get_buffer((uint8_t *)w.ptr(), len * sizeof(real_t) * 2); #ifdef BIG_ENDIAN_ENABLED - { - uint32_t *ptr=(uint32_t*)w.ptr(); - for(int i=0;i<len*2;i++) { + { + uint32_t *ptr = (uint32_t *)w.ptr(); + for (int i = 0; i < len * 2; i++) { - ptr[i]=BSWAP32(ptr[i]); + ptr[i] = BSWAP32(ptr[i]); + } } - } #endif @@ -577,8 +560,8 @@ Error ResourceInteractiveLoaderBinary::parse_variant(Variant& r_v) { ERR_EXPLAIN("Vector2 size is NOT 8!"); ERR_FAIL_V(ERR_UNAVAILABLE); } - w=PoolVector<Vector2>::Write(); - r_v=array; + w = PoolVector<Vector2>::Write(); + r_v = array; } break; case VARIANT_VECTOR3_ARRAY: { @@ -588,14 +571,14 @@ Error ResourceInteractiveLoaderBinary::parse_variant(Variant& r_v) { PoolVector<Vector3> array; array.resize(len); PoolVector<Vector3>::Write w = array.write(); - if (sizeof(Vector3)==12) { - f->get_buffer((uint8_t*)w.ptr(),len*sizeof(real_t)*3); + if (sizeof(Vector3) == 12) { + f->get_buffer((uint8_t *)w.ptr(), len * sizeof(real_t) * 3); #ifdef BIG_ENDIAN_ENABLED { - uint32_t *ptr=(uint32_t*)w.ptr(); - for(int i=0;i<len*3;i++) { + uint32_t *ptr = (uint32_t *)w.ptr(); + for (int i = 0; i < len * 3; i++) { - ptr[i]=BSWAP32(ptr[i]); + ptr[i] = BSWAP32(ptr[i]); } } @@ -605,8 +588,8 @@ Error ResourceInteractiveLoaderBinary::parse_variant(Variant& r_v) { ERR_EXPLAIN("Vector3 size is NOT 12!"); ERR_FAIL_V(ERR_UNAVAILABLE); } - w=PoolVector<Vector3>::Write(); - r_v=array; + w = PoolVector<Vector3>::Write(); + r_v = array; } break; case VARIANT_COLOR_ARRAY: { @@ -616,16 +599,16 @@ Error ResourceInteractiveLoaderBinary::parse_variant(Variant& r_v) { PoolVector<Color> array; array.resize(len); PoolVector<Color>::Write w = array.write(); - if (sizeof(Color)==16) { - f->get_buffer((uint8_t*)w.ptr(),len*sizeof(real_t)*4); + if (sizeof(Color) == 16) { + f->get_buffer((uint8_t *)w.ptr(), len * sizeof(real_t) * 4); #ifdef BIG_ENDIAN_ENABLED - { - uint32_t *ptr=(uint32_t*)w.ptr(); - for(int i=0;i<len*4;i++) { + { + uint32_t *ptr = (uint32_t *)w.ptr(); + for (int i = 0; i < len * 4; i++) { - ptr[i]=BSWAP32(ptr[i]); + ptr[i] = BSWAP32(ptr[i]); + } } - } #endif @@ -633,8 +616,8 @@ Error ResourceInteractiveLoaderBinary::parse_variant(Variant& r_v) { ERR_EXPLAIN("Color size is NOT 16!"); ERR_FAIL_V(ERR_UNAVAILABLE); } - w=PoolVector<Color>::Write(); - r_v=array; + w = PoolVector<Color>::Write(); + r_v = array; } break; default: { @@ -642,49 +625,43 @@ Error ResourceInteractiveLoaderBinary::parse_variant(Variant& r_v) { } break; } - - return OK; //never reach anyway - } +void ResourceInteractiveLoaderBinary::set_local_path(const String &p_local_path) { -void ResourceInteractiveLoaderBinary::set_local_path(const String& p_local_path) { - - res_path=p_local_path; + res_path = p_local_path; } -Ref<Resource> ResourceInteractiveLoaderBinary::get_resource(){ - +Ref<Resource> ResourceInteractiveLoaderBinary::get_resource() { return resource; } -Error ResourceInteractiveLoaderBinary::poll(){ +Error ResourceInteractiveLoaderBinary::poll() { - if (error!=OK) + if (error != OK) return error; - int s = stage; - if (s<external_resources.size()) { + if (s < external_resources.size()) { String path = external_resources[s].path; - print_line("load external res: "+path); + print_line("load external res: " + path); if (remaps.has(path)) { - path=remaps[path]; + path = remaps[path]; } - RES res = ResourceLoader::load(path,external_resources[s].type); + RES res = ResourceLoader::load(path, external_resources[s].type); if (res.is_null()) { if (!ResourceLoader::get_abort_on_missing_resources()) { - ResourceLoader::notify_dependency_error(local_path,path,external_resources[s].type); + ResourceLoader::notify_dependency_error(local_path, path, external_resources[s].type); } else { - error=ERR_FILE_MISSING_DEPENDENCIES; - ERR_EXPLAIN("Can't load dependency: "+path); + error = ERR_FILE_MISSING_DEPENDENCIES; + ERR_EXPLAIN("Can't load dependency: " + path); ERR_FAIL_V(error); } @@ -696,44 +673,39 @@ Error ResourceInteractiveLoaderBinary::poll(){ return error; } - s-=external_resources.size(); - + s -= external_resources.size(); - if (s>=internal_resources.size()) { + if (s >= internal_resources.size()) { - error=ERR_BUG; - ERR_FAIL_COND_V(s>=internal_resources.size(),error); + error = ERR_BUG; + ERR_FAIL_COND_V(s >= internal_resources.size(), error); } - bool main = s==(internal_resources.size()-1); + bool main = s == (internal_resources.size() - 1); //maybe it is loaded already String path; - int subindex=0; - - + int subindex = 0; if (!main) { - path=internal_resources[s].path; + path = internal_resources[s].path; if (path.begins_with("local://")) { - path=path.replace_first("local://",""); + path = path.replace_first("local://", ""); subindex = path.to_int(); - path=res_path+"::"+path; + path = res_path + "::" + path; } - - if (ResourceCache::has(path)) { //already loaded, don't do anything stage++; - error=OK; + error = OK; return error; } } else { if (!ResourceCache::has(res_path)) - path=res_path; + path = res_path; } uint64_t offset = internal_resources[s].offset; @@ -742,24 +714,24 @@ Error ResourceInteractiveLoaderBinary::poll(){ String t = get_unicode_string(); -// print_line("loading resource of type "+t+" path is "+path); + // print_line("loading resource of type "+t+" path is "+path); Object *obj = ClassDB::instance(t); if (!obj) { - error=ERR_FILE_CORRUPT; - ERR_EXPLAIN(local_path+":Resource of unrecognized type in file: "+t); + error = ERR_FILE_CORRUPT; + ERR_EXPLAIN(local_path + ":Resource of unrecognized type in file: " + t); } - ERR_FAIL_COND_V(!obj,ERR_FILE_CORRUPT); + ERR_FAIL_COND_V(!obj, ERR_FILE_CORRUPT); Resource *r = obj->cast_to<Resource>(); if (!r) { - error=ERR_FILE_CORRUPT; + error = ERR_FILE_CORRUPT; memdelete(obj); //bye - ERR_EXPLAIN(local_path+":Resoucre type in resource field not a resource, type is: "+obj->get_class()); - ERR_FAIL_COND_V(!r,ERR_FILE_CORRUPT); + ERR_EXPLAIN(local_path + ":Resoucre type in resource field not a resource, type is: " + obj->get_class()); + ERR_FAIL_COND_V(!r, ERR_FILE_CORRUPT); } - RES res = RES( r ); + RES res = RES(r); r->set_path(path); r->set_subindex(subindex); @@ -768,11 +740,11 @@ Error ResourceInteractiveLoaderBinary::poll(){ //set properties - for(int i=0;i<pc;i++) { + for (int i = 0; i < pc; i++) { StringName name = _get_string(); - if (name==StringName()) { - error=ERR_FILE_CORRUPT; + if (name == StringName()) { + error = ERR_FILE_CORRUPT; ERR_FAIL_V(ERR_FILE_CORRUPT); } @@ -782,7 +754,7 @@ Error ResourceInteractiveLoaderBinary::poll(){ if (error) return error; - res->set(name,value); + res->set(name, value); } #ifdef TOOLS_ENABLED res->set_edited(false); @@ -794,41 +766,37 @@ Error ResourceInteractiveLoaderBinary::poll(){ if (main) { f->close(); - resource=res; - error=ERR_FILE_EOF; + resource = res; + error = ERR_FILE_EOF; } else { - error=OK; + error = OK; } return OK; - } -int ResourceInteractiveLoaderBinary::get_stage() const{ +int ResourceInteractiveLoaderBinary::get_stage() const { return stage; } int ResourceInteractiveLoaderBinary::get_stage_count() const { - return external_resources.size()+internal_resources.size(); + return external_resources.size() + internal_resources.size(); } - -static void save_ustring(FileAccess* f,const String& p_string) { - +static void save_ustring(FileAccess *f, const String &p_string) { CharString utf8 = p_string.utf8(); - f->store_32(utf8.length()+1); - f->store_buffer((const uint8_t*)utf8.get_data(),utf8.length()+1); + f->store_32(utf8.length() + 1); + f->store_buffer((const uint8_t *)utf8.get_data(), utf8.length() + 1); } - static String get_ustring(FileAccess *f) { int len = f->get_32(); Vector<char> str_buf; str_buf.resize(len); - f->get_buffer((uint8_t*)&str_buf[0],len); + f->get_buffer((uint8_t *)&str_buf[0], len); String s; s.parse_utf8(&str_buf[0]); return s; @@ -837,60 +805,53 @@ static String get_ustring(FileAccess *f) { String ResourceInteractiveLoaderBinary::get_unicode_string() { int len = f->get_32(); - if (len>str_buf.size()) { + if (len > str_buf.size()) { str_buf.resize(len); } - if (len==0) + if (len == 0) return String(); - f->get_buffer((uint8_t*)&str_buf[0],len); + f->get_buffer((uint8_t *)&str_buf[0], len); String s; s.parse_utf8(&str_buf[0]); return s; } - - -void ResourceInteractiveLoaderBinary::get_dependencies(FileAccess *p_f,List<String> *p_dependencies,bool p_add_types) { +void ResourceInteractiveLoaderBinary::get_dependencies(FileAccess *p_f, List<String> *p_dependencies, bool p_add_types) { open(p_f); if (error) return; - for(int i=0;i<external_resources.size();i++) { + for (int i = 0; i < external_resources.size(); i++) { - String dep=external_resources[i].path; + String dep = external_resources[i].path; - if (p_add_types && external_resources[i].type!=String()) { - dep+="::"+external_resources[i].type; + if (p_add_types && external_resources[i].type != String()) { + dep += "::" + external_resources[i].type; } p_dependencies->push_back(dep); } - } - - - void ResourceInteractiveLoaderBinary::open(FileAccess *p_f) { + error = OK; - error=OK; - - f=p_f; + f = p_f; uint8_t header[4]; - f->get_buffer(header,4); - if (header[0]=='R' && header[1]=='S' && header[2]=='C' && header[3]=='C') { + f->get_buffer(header, 4); + if (header[0] == 'R' && header[1] == 'S' && header[2] == 'C' && header[3] == 'C') { //compressed - FileAccessCompressed *fac = memnew( FileAccessCompressed ); + FileAccessCompressed *fac = memnew(FileAccessCompressed); fac->open_after_magic(f); - f=fac; + f = fac; - } else if (header[0]!='R' || header[1]!='S' || header[2]!='R' || header[3]!='C') { + } else if (header[0] != 'R' || header[1] != 'S' || header[2] != 'R' || header[3] != 'C') { //not normal - error=ERR_FILE_UNRECOGNIZED; - ERR_EXPLAIN("Unrecognized binary resource file: "+local_path); + error = ERR_FILE_UNRECOGNIZED; + ERR_EXPLAIN("Unrecognized binary resource file: " + local_path); ERR_FAIL(); } @@ -903,53 +864,51 @@ void ResourceInteractiveLoaderBinary::open(FileAccess *p_f) { bool use_real64 = f->get_32(); - f->set_endian_swap(big_endian!=0); //read big endian if saved as big endian + f->set_endian_swap(big_endian != 0); //read big endian if saved as big endian - uint32_t ver_major=f->get_32(); - uint32_t ver_minor=f->get_32(); - uint32_t ver_format=f->get_32(); + uint32_t ver_major = f->get_32(); + uint32_t ver_minor = f->get_32(); + uint32_t ver_format = f->get_32(); - print_bl("big endian: "+itos(big_endian)); - print_bl("endian swap: "+itos(endian_swap)); - print_bl("real64: "+itos(use_real64)); - print_bl("major: "+itos(ver_major)); - print_bl("minor: "+itos(ver_minor)); - print_bl("format: "+itos(ver_format)); + print_bl("big endian: " + itos(big_endian)); + print_bl("endian swap: " + itos(endian_swap)); + print_bl("real64: " + itos(use_real64)); + print_bl("major: " + itos(ver_major)); + print_bl("minor: " + itos(ver_minor)); + print_bl("format: " + itos(ver_format)); - if (ver_format>FORMAT_VERSION || ver_major>VERSION_MAJOR) { + if (ver_format > FORMAT_VERSION || ver_major > VERSION_MAJOR) { f->close(); - ERR_EXPLAIN("File Format '"+itos(FORMAT_VERSION)+"."+itos(ver_major)+"."+itos(ver_minor)+"' is too new! Please upgrade to a a new engine version: "+local_path); + ERR_EXPLAIN("File Format '" + itos(FORMAT_VERSION) + "." + itos(ver_major) + "." + itos(ver_minor) + "' is too new! Please upgrade to a a new engine version: " + local_path); ERR_FAIL(); - } - type=get_unicode_string(); + type = get_unicode_string(); - print_bl("type: "+type); + print_bl("type: " + type); importmd_ofs = f->get_64(); - for(int i=0;i<14;i++) + for (int i = 0; i < 14; i++) f->get_32(); //skip a few reserved fields - uint32_t string_table_size=f->get_32(); + uint32_t string_table_size = f->get_32(); string_map.resize(string_table_size); - for(uint32_t i=0;i<string_table_size;i++) { + for (uint32_t i = 0; i < string_table_size; i++) { StringName s = get_unicode_string(); - string_map[i]=s; + string_map[i] = s; } - print_bl("strings: "+itos(string_table_size)); + print_bl("strings: " + itos(string_table_size)); - uint32_t ext_resources_size=f->get_32(); - for(uint32_t i=0;i<ext_resources_size;i++) { + uint32_t ext_resources_size = f->get_32(); + for (uint32_t i = 0; i < ext_resources_size; i++) { ExtResoucre er; - er.type=get_unicode_string(); - er.path=get_unicode_string(); + er.type = get_unicode_string(); + er.path = get_unicode_string(); external_resources.push_back(er); - } //see if the exporter has different set of external resources for more efficient loading @@ -966,46 +925,43 @@ void ResourceInteractiveLoaderBinary::open(FileAccess *p_f) { print_line(res_path+" - EXTERNAL RESOURCES: "+itos(external_resources.size())); }*/ - print_bl("ext resources: "+itos(ext_resources_size)); - uint32_t int_resources_size=f->get_32(); + print_bl("ext resources: " + itos(ext_resources_size)); + uint32_t int_resources_size = f->get_32(); - for(uint32_t i=0;i<int_resources_size;i++) { + for (uint32_t i = 0; i < int_resources_size; i++) { IntResoucre ir; - ir.path=get_unicode_string(); - ir.offset=f->get_64(); + ir.path = get_unicode_string(); + ir.offset = f->get_64(); internal_resources.push_back(ir); } - print_bl("int resources: "+itos(int_resources_size)); - + print_bl("int resources: " + itos(int_resources_size)); if (f->eof_reached()) { - error=ERR_FILE_CORRUPT; - ERR_EXPLAIN("Premature End Of File: "+local_path); + error = ERR_FILE_CORRUPT; + ERR_EXPLAIN("Premature End Of File: " + local_path); ERR_FAIL(); } - } String ResourceInteractiveLoaderBinary::recognize(FileAccess *p_f) { - error=OK; + error = OK; - - f=p_f; + f = p_f; uint8_t header[4]; - f->get_buffer(header,4); - if (header[0]=='R' && header[1]=='S' && header[2]=='C' && header[3]=='C') { + f->get_buffer(header, 4); + if (header[0] == 'R' && header[1] == 'S' && header[2] == 'C' && header[3] == 'C') { //compressed - FileAccessCompressed *fac = memnew( FileAccessCompressed ); + FileAccessCompressed *fac = memnew(FileAccessCompressed); fac->open_after_magic(f); - f=fac; + f = fac; - } else if (header[0]!='R' || header[1]!='S' || header[2]!='R' || header[3]!='C') { + } else if (header[0] != 'R' || header[1] != 'S' || header[2] != 'R' || header[3] != 'C') { //not normal - error=ERR_FILE_UNRECOGNIZED; + error = ERR_FILE_UNRECOGNIZED; return ""; } @@ -1018,30 +974,30 @@ String ResourceInteractiveLoaderBinary::recognize(FileAccess *p_f) { bool use_real64 = f->get_32(); - f->set_endian_swap(big_endian!=0); //read big endian if saved as big endian + f->set_endian_swap(big_endian != 0); //read big endian if saved as big endian - uint32_t ver_major=f->get_32(); - uint32_t ver_minor=f->get_32(); - uint32_t ver_format=f->get_32(); + uint32_t ver_major = f->get_32(); + uint32_t ver_minor = f->get_32(); + uint32_t ver_format = f->get_32(); - if (ver_format>FORMAT_VERSION || ver_major>VERSION_MAJOR) { + if (ver_format > FORMAT_VERSION || ver_major > VERSION_MAJOR) { f->close(); return ""; } - String type=get_unicode_string(); + String type = get_unicode_string(); return type; } ResourceInteractiveLoaderBinary::ResourceInteractiveLoaderBinary() { - f=NULL; - stage=0; - endian_swap=false; - use_real64=false; - error=OK; + f = NULL; + stage = 0; + endian_swap = false; + use_real64 = false; + error = OK; } ResourceInteractiveLoaderBinary::~ResourceInteractiveLoaderBinary() { @@ -1050,126 +1006,117 @@ ResourceInteractiveLoaderBinary::~ResourceInteractiveLoaderBinary() { memdelete(f); } - Ref<ResourceInteractiveLoader> ResourceFormatLoaderBinary::load_interactive(const String &p_path, Error *r_error) { if (r_error) - *r_error=ERR_FILE_CANT_OPEN; + *r_error = ERR_FILE_CANT_OPEN; Error err; - FileAccess *f = FileAccess::open(p_path,FileAccess::READ,&err); + FileAccess *f = FileAccess::open(p_path, FileAccess::READ, &err); - if (err!=OK) { + if (err != OK) { - ERR_FAIL_COND_V(err!=OK,Ref<ResourceInteractiveLoader>()); + ERR_FAIL_COND_V(err != OK, Ref<ResourceInteractiveLoader>()); } - Ref<ResourceInteractiveLoaderBinary> ria = memnew( ResourceInteractiveLoaderBinary ); - ria->local_path=GlobalConfig::get_singleton()->localize_path(p_path); - ria->res_path=ria->local_path; + Ref<ResourceInteractiveLoaderBinary> ria = memnew(ResourceInteractiveLoaderBinary); + ria->local_path = GlobalConfig::get_singleton()->localize_path(p_path); + ria->res_path = ria->local_path; //ria->set_local_path( Globals::get_singleton()->localize_path(p_path) ); ria->open(f); - return ria; } -void ResourceFormatLoaderBinary::get_recognized_extensions_for_type(const String& p_type,List<String> *p_extensions) const { +void ResourceFormatLoaderBinary::get_recognized_extensions_for_type(const String &p_type, List<String> *p_extensions) const { - if (p_type=="") { + if (p_type == "") { get_recognized_extensions(p_extensions); return; } List<String> extensions; - ClassDB::get_extensions_for_type(p_type,&extensions); + ClassDB::get_extensions_for_type(p_type, &extensions); extensions.sort(); - for(List<String>::Element *E=extensions.front();E;E=E->next()) { + for (List<String>::Element *E = extensions.front(); E; E = E->next()) { String ext = E->get().to_lower(); p_extensions->push_back(ext); } - } -void ResourceFormatLoaderBinary::get_recognized_extensions(List<String> *p_extensions) const{ +void ResourceFormatLoaderBinary::get_recognized_extensions(List<String> *p_extensions) const { List<String> extensions; ClassDB::get_resource_base_extensions(&extensions); extensions.sort(); - for(List<String>::Element *E=extensions.front();E;E=E->next()) { + for (List<String>::Element *E = extensions.front(); E; E = E->next()) { String ext = E->get().to_lower(); p_extensions->push_back(ext); } - } -bool ResourceFormatLoaderBinary::handles_type(const String& p_type) const{ - +bool ResourceFormatLoaderBinary::handles_type(const String &p_type) const { return true; //handles all } +void ResourceFormatLoaderBinary::get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types) { -void ResourceFormatLoaderBinary::get_dependencies(const String& p_path,List<String> *p_dependencies,bool p_add_types) { - - FileAccess *f = FileAccess::open(p_path,FileAccess::READ); + FileAccess *f = FileAccess::open(p_path, FileAccess::READ); ERR_FAIL_COND(!f); - Ref<ResourceInteractiveLoaderBinary> ria = memnew( ResourceInteractiveLoaderBinary ); - ria->local_path=GlobalConfig::get_singleton()->localize_path(p_path); - ria->res_path=ria->local_path; + Ref<ResourceInteractiveLoaderBinary> ria = memnew(ResourceInteractiveLoaderBinary); + ria->local_path = GlobalConfig::get_singleton()->localize_path(p_path); + ria->res_path = ria->local_path; //ria->set_local_path( Globals::get_singleton()->localize_path(p_path) ); - ria->get_dependencies(f,p_dependencies,p_add_types); + ria->get_dependencies(f, p_dependencies, p_add_types); } -Error ResourceFormatLoaderBinary::rename_dependencies(const String &p_path,const Map<String,String>& p_map) { - +Error ResourceFormatLoaderBinary::rename_dependencies(const String &p_path, const Map<String, String> &p_map) { //Error error=OK; + FileAccess *f = FileAccess::open(p_path, FileAccess::READ); + ERR_FAIL_COND_V(!f, ERR_CANT_OPEN); - FileAccess *f=FileAccess::open(p_path,FileAccess::READ); - ERR_FAIL_COND_V(!f,ERR_CANT_OPEN); - - FileAccess* fw=NULL;//=FileAccess::open(p_path+".depren"); + FileAccess *fw = NULL; //=FileAccess::open(p_path+".depren"); - String local_path=p_path.get_base_dir(); + String local_path = p_path.get_base_dir(); uint8_t header[4]; - f->get_buffer(header,4); - if (header[0]=='R' && header[1]=='S' && header[2]=='C' && header[3]=='C') { + f->get_buffer(header, 4); + if (header[0] == 'R' && header[1] == 'S' && header[2] == 'C' && header[3] == 'C') { //compressed - FileAccessCompressed *fac = memnew( FileAccessCompressed ); + FileAccessCompressed *fac = memnew(FileAccessCompressed); fac->open_after_magic(f); - f=fac; + f = fac; - FileAccessCompressed *facw = memnew( FileAccessCompressed ); + FileAccessCompressed *facw = memnew(FileAccessCompressed); facw->configure("RSCC"); - Error err = facw->_open(p_path+".depren",FileAccess::WRITE); + Error err = facw->_open(p_path + ".depren", FileAccess::WRITE); if (err) { memdelete(fac); memdelete(facw); - ERR_FAIL_COND_V(err,ERR_FILE_CORRUPT); + ERR_FAIL_COND_V(err, ERR_FILE_CORRUPT); } - fw=facw; + fw = facw; - - } else if (header[0]!='R' || header[1]!='S' || header[2]!='R' || header[3]!='C') { + } else if (header[0] != 'R' || header[1] != 'S' || header[2] != 'R' || header[3] != 'C') { //not normal //error=ERR_FILE_UNRECOGNIZED; memdelete(f); - ERR_EXPLAIN("Unrecognized binary resource file: "+local_path); + ERR_EXPLAIN("Unrecognized binary resource file: " + local_path); ERR_FAIL_V(ERR_FILE_UNRECOGNIZED); } else { - fw = FileAccess::open(p_path+".depren",FileAccess::WRITE); + fw = FileAccess::open(p_path + ".depren", FileAccess::WRITE); if (!fw) { memdelete(f); } - ERR_FAIL_COND_V(!fw,ERR_CANT_CREATE); + ERR_FAIL_COND_V(!fw, ERR_CANT_CREATE); } bool big_endian = f->get_32(); @@ -1181,144 +1128,139 @@ Error ResourceFormatLoaderBinary::rename_dependencies(const String &p_path,const bool use_real64 = f->get_32(); - f->set_endian_swap(big_endian!=0); //read big endian if saved as big endian + f->set_endian_swap(big_endian != 0); //read big endian if saved as big endian fw->store_32(endian_swap); - fw->set_endian_swap(big_endian!=0); + fw->set_endian_swap(big_endian != 0); fw->store_32(use_real64); //use real64 - uint32_t ver_major=f->get_32(); - uint32_t ver_minor=f->get_32(); - uint32_t ver_format=f->get_32(); + uint32_t ver_major = f->get_32(); + uint32_t ver_minor = f->get_32(); + uint32_t ver_format = f->get_32(); - if (ver_format<FORMAT_VERSION_CAN_RENAME_DEPS) { + if (ver_format < FORMAT_VERSION_CAN_RENAME_DEPS) { memdelete(f); memdelete(fw); DirAccess *da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); - da->remove(p_path+".depren"); + da->remove(p_path + ".depren"); memdelete(da); //fuck it, use the old approach; - WARN_PRINT(("This file is old, so it can't refactor dependencies, opening and resaving: "+p_path).utf8().get_data()); + WARN_PRINT(("This file is old, so it can't refactor dependencies, opening and resaving: " + p_path).utf8().get_data()); Error err; - f = FileAccess::open(p_path,FileAccess::READ,&err); - if (err!=OK) { - ERR_FAIL_COND_V(err!=OK,ERR_FILE_CANT_OPEN); + f = FileAccess::open(p_path, FileAccess::READ, &err); + if (err != OK) { + ERR_FAIL_COND_V(err != OK, ERR_FILE_CANT_OPEN); } - Ref<ResourceInteractiveLoaderBinary> ria = memnew( ResourceInteractiveLoaderBinary ); - ria->local_path=GlobalConfig::get_singleton()->localize_path(p_path); - ria->res_path=ria->local_path; - ria->remaps=p_map; + Ref<ResourceInteractiveLoaderBinary> ria = memnew(ResourceInteractiveLoaderBinary); + ria->local_path = GlobalConfig::get_singleton()->localize_path(p_path); + ria->res_path = ria->local_path; + ria->remaps = p_map; //ria->set_local_path( Globals::get_singleton()->localize_path(p_path) ); ria->open(f); err = ria->poll(); - while(err==OK) { - err=ria->poll(); + while (err == OK) { + err = ria->poll(); } - ERR_FAIL_COND_V(err!=ERR_FILE_EOF,ERR_FILE_CORRUPT); + ERR_FAIL_COND_V(err != ERR_FILE_EOF, ERR_FILE_CORRUPT); RES res = ria->get_resource(); - ERR_FAIL_COND_V(!res.is_valid(),ERR_FILE_CORRUPT); + ERR_FAIL_COND_V(!res.is_valid(), ERR_FILE_CORRUPT); - return ResourceFormatSaverBinary::singleton->save(p_path,res); + return ResourceFormatSaverBinary::singleton->save(p_path, res); } - if (ver_format>FORMAT_VERSION || ver_major>VERSION_MAJOR) { + if (ver_format > FORMAT_VERSION || ver_major > VERSION_MAJOR) { memdelete(f); memdelete(fw); - ERR_EXPLAIN("File Format '"+itos(FORMAT_VERSION)+"."+itos(ver_major)+"."+itos(ver_minor)+"' is too new! Please upgrade to a a new engine version: "+local_path); + ERR_EXPLAIN("File Format '" + itos(FORMAT_VERSION) + "." + itos(ver_major) + "." + itos(ver_minor) + "' is too new! Please upgrade to a a new engine version: " + local_path); ERR_FAIL_V(ERR_FILE_UNRECOGNIZED); - } - fw->store_32( VERSION_MAJOR ); //current version - fw->store_32( VERSION_MINOR ); - fw->store_32( FORMAT_VERSION ); - - save_ustring(fw,get_ustring(f)); //type + fw->store_32(VERSION_MAJOR); //current version + fw->store_32(VERSION_MINOR); + fw->store_32(FORMAT_VERSION); + save_ustring(fw, get_ustring(f)); //type size_t md_ofs = f->get_pos(); size_t importmd_ofs = f->get_64(); fw->store_64(0); //metadata offset - for(int i=0;i<14;i++) { + for (int i = 0; i < 14; i++) { fw->store_32(0); f->get_32(); } //string table - uint32_t string_table_size=f->get_32(); + uint32_t string_table_size = f->get_32(); fw->store_32(string_table_size); - for(uint32_t i=0;i<string_table_size;i++) { + for (uint32_t i = 0; i < string_table_size; i++) { String s = get_ustring(f); - save_ustring(fw,s); + save_ustring(fw, s); } //external resources - uint32_t ext_resources_size=f->get_32(); + uint32_t ext_resources_size = f->get_32(); fw->store_32(ext_resources_size); - for(uint32_t i=0;i<ext_resources_size;i++) { + for (uint32_t i = 0; i < ext_resources_size; i++) { String type = get_ustring(f); String path = get_ustring(f); - bool relative=false; + bool relative = false; if (!path.begins_with("res://")) { - path=local_path.plus_file(path).simplify_path(); - relative=true; + path = local_path.plus_file(path).simplify_path(); + relative = true; } - if (p_map.has(path)) { - String np=p_map[path]; - path=np; + String np = p_map[path]; + path = np; } if (relative) { //restore relative - path=local_path.path_to_file(path); + path = local_path.path_to_file(path); } - save_ustring(fw,type); - save_ustring(fw,path); + save_ustring(fw, type); + save_ustring(fw, path); } int64_t size_diff = (int64_t)fw->get_pos() - (int64_t)f->get_pos(); //internal resources - uint32_t int_resources_size=f->get_32(); + uint32_t int_resources_size = f->get_32(); fw->store_32(int_resources_size); - for(uint32_t i=0;i<int_resources_size;i++) { + for (uint32_t i = 0; i < int_resources_size; i++) { - - String path=get_ustring(f); - uint64_t offset=f->get_64(); - save_ustring(fw,path); - fw->store_64(offset+size_diff); + String path = get_ustring(f); + uint64_t offset = f->get_64(); + save_ustring(fw, path); + fw->store_64(offset + size_diff); } //rest of file uint8_t b = f->get_8(); - while(!f->eof_reached()) { + while (!f->eof_reached()) { fw->store_8(b); b = f->get_8(); } - bool all_ok = fw->get_error()==OK; + bool all_ok = fw->get_error() == OK; fw->seek(md_ofs); - fw->store_64(importmd_ofs+size_diff); - + fw->store_64(importmd_ofs + size_diff); memdelete(f); memdelete(fw); @@ -1329,50 +1271,42 @@ Error ResourceFormatLoaderBinary::rename_dependencies(const String &p_path,const DirAccess *da = DirAccess::create(DirAccess::ACCESS_RESOURCES); da->remove(p_path); - da->rename(p_path+".depren",p_path); + da->rename(p_path + ".depren", p_path); memdelete(da); return OK; } - String ResourceFormatLoaderBinary::get_resource_type(const String &p_path) const { - FileAccess *f = FileAccess::open(p_path,FileAccess::READ); + FileAccess *f = FileAccess::open(p_path, FileAccess::READ); if (!f) { return ""; //could not rwead } - Ref<ResourceInteractiveLoaderBinary> ria = memnew( ResourceInteractiveLoaderBinary ); - ria->local_path=GlobalConfig::get_singleton()->localize_path(p_path); - ria->res_path=ria->local_path; + Ref<ResourceInteractiveLoaderBinary> ria = memnew(ResourceInteractiveLoaderBinary); + ria->local_path = GlobalConfig::get_singleton()->localize_path(p_path); + ria->res_path = ria->local_path; //ria->set_local_path( Globals::get_singleton()->localize_path(p_path) ); String r = ria->recognize(f); return r; - - } - - /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// - void ResourceFormatSaverBinaryInstance::_pad_buffer(int p_bytes) { - int extra = 4-(p_bytes%4); - if (extra<4) { - for(int i=0;i<extra;i++) + int extra = 4 - (p_bytes % 4); + if (extra < 4) { + for (int i = 0; i < extra; i++) f->store_8(0); //pad to 32 } - } +void ResourceFormatSaverBinaryInstance::write_variant(const Variant &p_property, const PropertyInfo &p_hint) { -void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property,const PropertyInfo& p_hint) { - - switch(p_property.get_type()) { + switch (p_property.get_type()) { case Variant::NIL: { @@ -1382,51 +1316,48 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, case Variant::BOOL: { f->store_32(VARIANT_BOOL); - bool val=p_property; + bool val = p_property; f->store_32(val); } break; case Variant::INT: { int64_t val = p_property; - if (val>0x7FFFFFFF || val < -0x80000000) { + if (val > 0x7FFFFFFF || val < -0x80000000) { f->store_32(VARIANT_INT64); f->store_64(val); } else { f->store_32(VARIANT_INT); - int val=p_property; + int val = p_property; f->store_32(int32_t(val)); - } } break; case Variant::REAL: { - double d = p_property; float fl = d; - if (double(fl)!=d) { + if (double(fl) != d) { f->store_32(VARIANT_DOUBLE); f->store_double(d); } else { f->store_32(VARIANT_REAL); f->store_real(fl); - } } break; case Variant::STRING: { f->store_32(VARIANT_STRING); - String val=p_property; + String val = p_property; save_unicode_string(val); } break; case Variant::VECTOR2: { f->store_32(VARIANT_VECTOR2); - Vector2 val=p_property; + Vector2 val = p_property; f->store_real(val.x); f->store_real(val.y); @@ -1434,7 +1365,7 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, case Variant::RECT2: { f->store_32(VARIANT_RECT2); - Rect2 val=p_property; + Rect2 val = p_property; f->store_real(val.pos.x); f->store_real(val.pos.y); f->store_real(val.size.x); @@ -1444,7 +1375,7 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, case Variant::VECTOR3: { f->store_32(VARIANT_VECTOR3); - Vector3 val=p_property; + Vector3 val = p_property; f->store_real(val.x); f->store_real(val.y); f->store_real(val.z); @@ -1453,7 +1384,7 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, case Variant::PLANE: { f->store_32(VARIANT_PLANE); - Plane val=p_property; + Plane val = p_property; f->store_real(val.normal.x); f->store_real(val.normal.y); f->store_real(val.normal.z); @@ -1463,7 +1394,7 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, case Variant::QUAT: { f->store_32(VARIANT_QUAT); - Quat val=p_property; + Quat val = p_property; f->store_real(val.x); f->store_real(val.y); f->store_real(val.z); @@ -1473,7 +1404,7 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, case Variant::RECT3: { f->store_32(VARIANT_AABB); - Rect3 val=p_property; + Rect3 val = p_property; f->store_real(val.pos.x); f->store_real(val.pos.y); f->store_real(val.pos.z); @@ -1485,7 +1416,7 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, case Variant::TRANSFORM2D: { f->store_32(VARIANT_MATRIX32); - Transform2D val=p_property; + Transform2D val = p_property; f->store_real(val.elements[0].x); f->store_real(val.elements[0].y); f->store_real(val.elements[1].x); @@ -1497,7 +1428,7 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, case Variant::BASIS: { f->store_32(VARIANT_MATRIX3); - Basis val=p_property; + Basis val = p_property; f->store_real(val.elements[0].x); f->store_real(val.elements[0].y); f->store_real(val.elements[0].z); @@ -1512,7 +1443,7 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, case Variant::TRANSFORM: { f->store_32(VARIANT_TRANSFORM); - Transform val=p_property; + Transform val = p_property; f->store_real(val.basis.elements[0].x); f->store_real(val.basis.elements[0].y); f->store_real(val.basis.elements[0].z); @@ -1530,7 +1461,7 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, case Variant::COLOR: { f->store_32(VARIANT_COLOR); - Color val=p_property; + Color val = p_property; f->store_real(val.r); f->store_real(val.g); f->store_real(val.b); @@ -1540,34 +1471,32 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, case Variant::IMAGE: { f->store_32(VARIANT_IMAGE); - Image val =p_property; + Image val = p_property; if (val.empty()) { f->store_32(IMAGE_ENCODING_EMPTY); break; } - int encoding=IMAGE_ENCODING_RAW; - float quality=0.7; + int encoding = IMAGE_ENCODING_RAW; + float quality = 0.7; if (!val.is_compressed()) { //can only compress uncompressed stuff - if (p_hint.hint==PROPERTY_HINT_IMAGE_COMPRESS_LOSSY && Image::lossy_packer) { - encoding=IMAGE_ENCODING_LOSSY; - float qs=p_hint.hint_string.to_double(); - if (qs!=0.0) - quality=qs; - - } else if (p_hint.hint==PROPERTY_HINT_IMAGE_COMPRESS_LOSSLESS && Image::lossless_packer) { - encoding=IMAGE_ENCODING_LOSSLESS; + if (p_hint.hint == PROPERTY_HINT_IMAGE_COMPRESS_LOSSY && Image::lossy_packer) { + encoding = IMAGE_ENCODING_LOSSY; + float qs = p_hint.hint_string.to_double(); + if (qs != 0.0) + quality = qs; + } else if (p_hint.hint == PROPERTY_HINT_IMAGE_COMPRESS_LOSSLESS && Image::lossless_packer) { + encoding = IMAGE_ENCODING_LOSSLESS; } } f->store_32(encoding); //raw encoding - if (encoding==IMAGE_ENCODING_RAW) { - + if (encoding == IMAGE_ENCODING_RAW) { f->store_32(val.get_width()); f->store_32(val.get_height()); @@ -1577,42 +1506,40 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, int dlen = val.get_data().size(); f->store_32(dlen); PoolVector<uint8_t>::Read r = val.get_data().read(); - f->store_buffer(r.ptr(),dlen); + f->store_buffer(r.ptr(), dlen); _pad_buffer(dlen); } else { PoolVector<uint8_t> data; - if (encoding==IMAGE_ENCODING_LOSSY) { - data=Image::lossy_packer(val,quality); - - } else if (encoding==IMAGE_ENCODING_LOSSLESS) { - data=Image::lossless_packer(val); + if (encoding == IMAGE_ENCODING_LOSSY) { + data = Image::lossy_packer(val, quality); + } else if (encoding == IMAGE_ENCODING_LOSSLESS) { + data = Image::lossless_packer(val); } - int ds=data.size(); + int ds = data.size(); f->store_32(ds); - if (ds>0) { + if (ds > 0) { PoolVector<uint8_t>::Read r = data.read(); - f->store_buffer(r.ptr(),ds); + f->store_buffer(r.ptr(), ds); _pad_buffer(ds); - } } } break; case Variant::NODE_PATH: { f->store_32(VARIANT_NODE_PATH); - NodePath np=p_property; + NodePath np = p_property; f->store_16(np.get_name_count()); uint16_t snc = np.get_subname_count(); if (np.is_absolute()) - snc|=0x8000; + snc |= 0x8000; f->store_16(snc); - for(int i=0;i<np.get_name_count();i++) + for (int i = 0; i < np.get_name_count(); i++) f->store_32(get_string_index(np.get_name(i))); - for(int i=0;i<np.get_subname_count();i++) + for (int i = 0; i < np.get_subname_count(); i++) f->store_32(get_string_index(np.get_subname(i))); f->store_32(get_string_index(np.get_property())); @@ -1633,7 +1560,7 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, return; // don't save it } - if (res->get_path().length() && res->get_path().find("::")==-1) { + if (res->get_path().length() && res->get_path().find("::") == -1) { f->store_32(OBJECT_EXTERNAL_RESOURCE_INDEX); f->store_32(external_resources[res]); } else { @@ -1649,12 +1576,11 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, //internal resource } - } break; case Variant::INPUT_EVENT: { f->store_32(VARIANT_INPUT_EVENT); - InputEvent event=p_property; + InputEvent event = p_property; f->store_32(0); //event type none, nothing else suported for now. } break; @@ -1667,7 +1593,7 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, List<Variant> keys; d.get_key_list(&keys); - for(List<Variant>::Element *E=keys.front();E;E=E->next()) { + for (List<Variant>::Element *E = keys.front(); E; E = E->next()) { /* if (!_check_type(dict[E->get()])) @@ -1678,14 +1604,13 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, write_variant(d[E->get()]); } - } break; case Variant::ARRAY: { f->store_32(VARIANT_ARRAY); - Array a=p_property; + Array a = p_property; f->store_32(uint32_t(a.size())); - for(int i=0;i<a.size();i++) { + for (int i = 0; i < a.size(); i++) { write_variant(a[i]); } @@ -1695,10 +1620,10 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, f->store_32(VARIANT_RAW_ARRAY); PoolVector<uint8_t> arr = p_property; - int len=arr.size(); + int len = arr.size(); f->store_32(len); PoolVector<uint8_t>::Read r = arr.read(); - f->store_buffer(r.ptr(),len); + f->store_buffer(r.ptr(), len); _pad_buffer(len); } break; @@ -1706,10 +1631,10 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, f->store_32(VARIANT_INT_ARRAY); PoolVector<int> arr = p_property; - int len=arr.size(); + int len = arr.size(); f->store_32(len); PoolVector<int>::Read r = arr.read(); - for(int i=0;i<len;i++) + for (int i = 0; i < len; i++) f->store_32(r[i]); } break; @@ -1717,10 +1642,10 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, f->store_32(VARIANT_REAL_ARRAY); PoolVector<real_t> arr = p_property; - int len=arr.size(); + int len = arr.size(); f->store_32(len); PoolVector<real_t>::Read r = arr.read(); - for(int i=0;i<len;i++) { + for (int i = 0; i < len; i++) { f->store_real(r[i]); } @@ -1729,10 +1654,10 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, f->store_32(VARIANT_STRING_ARRAY); PoolVector<String> arr = p_property; - int len=arr.size(); + int len = arr.size(); f->store_32(len); PoolVector<String>::Read r = arr.read(); - for(int i=0;i<len;i++) { + for (int i = 0; i < len; i++) { save_unicode_string(r[i]); } @@ -1741,10 +1666,10 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, f->store_32(VARIANT_VECTOR3_ARRAY); PoolVector<Vector3> arr = p_property; - int len=arr.size(); + int len = arr.size(); f->store_32(len); PoolVector<Vector3>::Read r = arr.read(); - for(int i=0;i<len;i++) { + for (int i = 0; i < len; i++) { f->store_real(r[i].x); f->store_real(r[i].y); f->store_real(r[i].z); @@ -1755,10 +1680,10 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, f->store_32(VARIANT_VECTOR2_ARRAY); PoolVector<Vector2> arr = p_property; - int len=arr.size(); + int len = arr.size(); f->store_32(len); PoolVector<Vector2>::Read r = arr.read(); - for(int i=0;i<len;i++) { + for (int i = 0; i < len; i++) { f->store_real(r[i].x); f->store_real(r[i].y); } @@ -1768,10 +1693,10 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, f->store_32(VARIANT_COLOR_ARRAY); PoolVector<Color> arr = p_property; - int len=arr.size(); + int len = arr.size(); f->store_32(len); PoolVector<Color>::Read r = arr.read(); - for(int i=0;i<len;i++) { + for (int i = 0; i < len; i++) { f->store_real(r[i].r); f->store_real(r[i].g); f->store_real(r[i].b); @@ -1787,26 +1712,22 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, } } +void ResourceFormatSaverBinaryInstance::_find_resources(const Variant &p_variant, bool p_main) { -void ResourceFormatSaverBinaryInstance::_find_resources(const Variant& p_variant,bool p_main) { - - - switch(p_variant.get_type()) { + switch (p_variant.get_type()) { case Variant::OBJECT: { - RES res = p_variant.operator RefPtr(); if (res.is_null() || external_resources.has(res)) return; - if (!p_main && (!bundle_resources ) && res->get_path().length() && res->get_path().find("::") == -1 ) { + if (!p_main && (!bundle_resources) && res->get_path().length() && res->get_path().find("::") == -1) { int idx = external_resources.size(); - external_resources[res]=idx; + external_resources[res] = idx; return; } - if (resource_set.has(res)) return; @@ -1814,9 +1735,9 @@ void ResourceFormatSaverBinaryInstance::_find_resources(const Variant& p_variant res->get_property_list(&property_list); - for(List<PropertyInfo>::Element *E=property_list.front();E;E=E->next()) { + for (List<PropertyInfo>::Element *E = property_list.front(); E; E = E->next()) { - if (E->get().usage&PROPERTY_USAGE_STORAGE) { + if (E->get().usage & PROPERTY_USAGE_STORAGE) { _find_resources(res->get(E->get().name)); } @@ -1829,11 +1750,11 @@ void ResourceFormatSaverBinaryInstance::_find_resources(const Variant& p_variant case Variant::ARRAY: { - Array varray=p_variant; - int len=varray.size(); - for(int i=0;i<len;i++) { + Array varray = p_variant; + int len = varray.size(); + for (int i = 0; i < len; i++) { - Variant v=varray.get(i); + Variant v = varray.get(i); _find_resources(v); } @@ -1841,10 +1762,10 @@ void ResourceFormatSaverBinaryInstance::_find_resources(const Variant& p_variant case Variant::DICTIONARY: { - Dictionary d=p_variant; + Dictionary d = p_variant; List<Variant> keys; d.get_key_list(&keys); - for(List<Variant>::Element *E=keys.front();E;E=E->next()) { + for (List<Variant>::Element *E = keys.front(); E; E = E->next()) { _find_resources(E->get()); Variant v = d[E->get()]; @@ -1854,18 +1775,16 @@ void ResourceFormatSaverBinaryInstance::_find_resources(const Variant& p_variant case Variant::NODE_PATH: { //take the chance and save node path strings NodePath np = p_variant; - for(int i=0;i<np.get_name_count();i++) + for (int i = 0; i < np.get_name_count(); i++) get_string_index(np.get_name(i)); - for(int i=0;i<np.get_subname_count();i++) + for (int i = 0; i < np.get_subname_count(); i++) get_string_index(np.get_subname(i)); get_string_index(np.get_property()); - } break; default: {} } - } #if 0 Error ResourceFormatSaverBinary::_save_obj(const Object *p_object,SavedObject *so) { @@ -1916,64 +1835,60 @@ Error ResourceFormatSaverBinary::save(const Object *p_object,const Variant &p_me } #endif -void ResourceFormatSaverBinaryInstance::save_unicode_string(const String& p_string) { - +void ResourceFormatSaverBinaryInstance::save_unicode_string(const String &p_string) { CharString utf8 = p_string.utf8(); - f->store_32(utf8.length()+1); - f->store_buffer((const uint8_t*)utf8.get_data(),utf8.length()+1); + f->store_32(utf8.length() + 1); + f->store_buffer((const uint8_t *)utf8.get_data(), utf8.length() + 1); } -int ResourceFormatSaverBinaryInstance::get_string_index(const String& p_string) { +int ResourceFormatSaverBinaryInstance::get_string_index(const String &p_string) { - StringName s=p_string; + StringName s = p_string; if (string_map.has(s)) return string_map[s]; - string_map[s]=strings.size(); + string_map[s] = strings.size(); strings.push_back(s); - return strings.size()-1; + return strings.size() - 1; } - -Error ResourceFormatSaverBinaryInstance::save(const String &p_path,const RES& p_resource,uint32_t p_flags) { +Error ResourceFormatSaverBinaryInstance::save(const String &p_path, const RES &p_resource, uint32_t p_flags) { Error err; - if (p_flags&ResourceSaver::FLAG_COMPRESS) { - FileAccessCompressed *fac = memnew( FileAccessCompressed ); + if (p_flags & ResourceSaver::FLAG_COMPRESS) { + FileAccessCompressed *fac = memnew(FileAccessCompressed); fac->configure("RSCC"); - f=fac; - err = fac->_open(p_path,FileAccess::WRITE); + f = fac; + err = fac->_open(p_path, FileAccess::WRITE); if (err) memdelete(f); } else { - f=FileAccess::open(p_path,FileAccess::WRITE,&err); + f = FileAccess::open(p_path, FileAccess::WRITE, &err); } - - ERR_FAIL_COND_V(err,err); + ERR_FAIL_COND_V(err, err); FileAccessRef _fref(f); - - relative_paths=p_flags&ResourceSaver::FLAG_RELATIVE_PATHS; - skip_editor=p_flags&ResourceSaver::FLAG_OMIT_EDITOR_PROPERTIES; - bundle_resources=p_flags&ResourceSaver::FLAG_BUNDLE_RESOURCES; - big_endian=p_flags&ResourceSaver::FLAG_SAVE_BIG_ENDIAN; - takeover_paths=p_flags&ResourceSaver::FLAG_REPLACE_SUBRESOURCE_PATHS; + relative_paths = p_flags & ResourceSaver::FLAG_RELATIVE_PATHS; + skip_editor = p_flags & ResourceSaver::FLAG_OMIT_EDITOR_PROPERTIES; + bundle_resources = p_flags & ResourceSaver::FLAG_BUNDLE_RESOURCES; + big_endian = p_flags & ResourceSaver::FLAG_SAVE_BIG_ENDIAN; + takeover_paths = p_flags & ResourceSaver::FLAG_REPLACE_SUBRESOURCE_PATHS; if (!p_path.begins_with("res://")) - takeover_paths=false; + takeover_paths = false; - local_path=p_path.get_base_dir(); + local_path = p_path.get_base_dir(); //bin_meta_idx = get_string_index("__bin_meta__"); //is often used, so create - _find_resources(p_resource,true); + _find_resources(p_resource, true); - if (!(p_flags&ResourceSaver::FLAG_COMPRESS)) { + if (!(p_flags & ResourceSaver::FLAG_COMPRESS)) { //save header compressed - static const uint8_t header[4]={'R','S','R','C'}; - f->store_buffer(header,4); + static const uint8_t header[4] = { 'R', 'S', 'R', 'C' }; + f->store_buffer(header, 4); } if (big_endian) { @@ -1987,7 +1902,7 @@ Error ResourceFormatSaverBinaryInstance::save(const String &p_path,const RES& p_ f->store_32(VERSION_MINOR); f->store_32(FORMAT_VERSION); - if (f->get_error()!=OK && f->get_error()!=ERR_FILE_EOF) { + if (f->get_error() != OK && f->get_error() != ERR_FILE_EOF) { f->close(); return ERR_CANT_CREATE; } @@ -1996,50 +1911,41 @@ Error ResourceFormatSaverBinaryInstance::save(const String &p_path,const RES& p_ save_unicode_string(p_resource->get_class()); uint64_t md_at = f->get_pos(); f->store_64(0); //offset to impoty metadata - for(int i=0;i<14;i++) + for (int i = 0; i < 14; i++) f->store_32(0); // reserved - List<ResourceData> resources; - { - - for(List<RES>::Element *E=saved_resources.front();E;E=E->next()) { - + for (List<RES>::Element *E = saved_resources.front(); E; E = E->next()) { ResourceData &rd = resources.push_back(ResourceData())->get(); - rd.type=E->get()->get_class(); + rd.type = E->get()->get_class(); List<PropertyInfo> property_list; - E->get()->get_property_list( &property_list ); + E->get()->get_property_list(&property_list); - for(List<PropertyInfo>::Element *F=property_list.front();F;F=F->next()) { + for (List<PropertyInfo>::Element *F = property_list.front(); F; F = F->next()) { if (skip_editor && F->get().name.begins_with("__editor")) continue; - if (F->get().usage&PROPERTY_USAGE_STORAGE ) { + if (F->get().usage & PROPERTY_USAGE_STORAGE) { Property p; - p.name_idx=get_string_index(F->get().name); - p.value=E->get()->get(F->get().name); - if ((F->get().usage&PROPERTY_USAGE_STORE_IF_NONZERO && p.value.is_zero())||(F->get().usage&PROPERTY_USAGE_STORE_IF_NONONE && p.value.is_one()) ) + p.name_idx = get_string_index(F->get().name); + p.value = E->get()->get(F->get().name); + if ((F->get().usage & PROPERTY_USAGE_STORE_IF_NONZERO && p.value.is_zero()) || (F->get().usage & PROPERTY_USAGE_STORE_IF_NONONE && p.value.is_one())) continue; - p.pi=F->get(); + p.pi = F->get(); rd.properties.push_back(p); - } } - - - } } - f->store_32(strings.size()); //string table size - for(int i=0;i<strings.size();i++) { + for (int i = 0; i < strings.size(); i++) { //print_bl("saving string: "+strings[i]); save_unicode_string(strings[i]); } @@ -2049,15 +1955,15 @@ Error ResourceFormatSaverBinaryInstance::save(const String &p_path,const RES& p_ Vector<RES> save_order; save_order.resize(external_resources.size()); - for(Map<RES,int>::Element *E=external_resources.front();E;E=E->next()) { - save_order[E->get()]=E->key(); + for (Map<RES, int>::Element *E = external_resources.front(); E; E = E->next()) { + save_order[E->get()] = E->key(); } - for(int i=0;i<save_order.size();i++) { + for (int i = 0; i < save_order.size(); i++) { save_unicode_string(save_order[i]->get_save_class()); String path = save_order[i]->get_path(); - path=relative_paths?local_path.path_to_file(path):path; + path = relative_paths ? local_path.path_to_file(path) : path; save_unicode_string(path); } // save internal resource table @@ -2065,12 +1971,12 @@ Error ResourceFormatSaverBinaryInstance::save(const String &p_path,const RES& p_ Vector<uint64_t> ofs_pos; Set<int> used_indices; - for(List<RES>::Element *E=saved_resources.front();E;E=E->next()) { + for (List<RES>::Element *E = saved_resources.front(); E; E = E->next()) { RES r = E->get(); - if (r->get_path()=="" || r->get_path().find("::")!=-1) { + if (r->get_path() == "" || r->get_path().find("::") != -1) { - if (r->get_subindex()!=0) { + if (r->get_subindex() != 0) { if (used_indices.has(r->get_subindex())) { r->set_subindex(0); //repeated } else { @@ -2078,29 +1984,25 @@ Error ResourceFormatSaverBinaryInstance::save(const String &p_path,const RES& p_ } } } - } - - for(List<RES>::Element *E=saved_resources.front();E;E=E->next()) { - + for (List<RES>::Element *E = saved_resources.front(); E; E = E->next()) { RES r = E->get(); - if (r->get_path()=="" || r->get_path().find("::")!=-1) { - if (r->get_subindex()==0) { - int new_subindex=1; + if (r->get_path() == "" || r->get_path().find("::") != -1) { + if (r->get_subindex() == 0) { + int new_subindex = 1; if (used_indices.size()) { - new_subindex=used_indices.back()->get()+1; + new_subindex = used_indices.back()->get() + 1; } r->set_subindex(new_subindex); used_indices.insert(new_subindex); - } - save_unicode_string("local://"+itos(r->get_subindex())); + save_unicode_string("local://" + itos(r->get_subindex())); if (takeover_paths) { - r->set_path(p_path+"::"+itos(r->get_subindex()),true); + r->set_path(p_path + "::" + itos(r->get_subindex()), true); } #ifdef TOOLS_ENABLED r->set_edited(false); @@ -2116,74 +2018,64 @@ Error ResourceFormatSaverBinaryInstance::save(const String &p_path,const RES& p_ //int saved_idx=0; //now actually save the resources - for(List<ResourceData>::Element *E=resources.front();E;E=E->next()) { + for (List<ResourceData>::Element *E = resources.front(); E; E = E->next()) { - ResourceData & rd = E->get(); + ResourceData &rd = E->get(); ofs_table.push_back(f->get_pos()); save_unicode_string(rd.type); f->store_32(rd.properties.size()); - for (List<Property>::Element *F=rd.properties.front();F;F=F->next()) { + for (List<Property>::Element *F = rd.properties.front(); F; F = F->next()) { - Property &p=F->get(); + Property &p = F->get(); f->store_32(p.name_idx); - write_variant(p.value,F->get().pi); + write_variant(p.value, F->get().pi); } - } - for(int i=0;i<ofs_table.size();i++) { + for (int i = 0; i < ofs_table.size(); i++) { f->seek(ofs_pos[i]); f->store_64(ofs_table[i]); } f->seek_end(); + f->store_buffer((const uint8_t *)"RSRC", 4); //magic at end - f->store_buffer((const uint8_t*)"RSRC",4); //magic at end - - if (f->get_error()!=OK && f->get_error()!=ERR_FILE_EOF) { + if (f->get_error() != OK && f->get_error() != ERR_FILE_EOF) { f->close(); return ERR_CANT_CREATE; } f->close(); - return OK; } - - -Error ResourceFormatSaverBinary::save(const String &p_path,const RES& p_resource,uint32_t p_flags) { - +Error ResourceFormatSaverBinary::save(const String &p_path, const RES &p_resource, uint32_t p_flags) { String local_path = GlobalConfig::get_singleton()->localize_path(p_path); ResourceFormatSaverBinaryInstance saver; - return saver.save(local_path,p_resource,p_flags); - + return saver.save(local_path, p_resource, p_flags); } - -bool ResourceFormatSaverBinary::recognize(const RES& p_resource) const { +bool ResourceFormatSaverBinary::recognize(const RES &p_resource) const { return true; //all recognized - } -void ResourceFormatSaverBinary::get_recognized_extensions(const RES& p_resource,List<String> *p_extensions) const { +void ResourceFormatSaverBinary::get_recognized_extensions(const RES &p_resource, List<String> *p_extensions) const { String base = p_resource->get_base_extension().to_lower(); p_extensions->push_back(base); - if (base!="res") + if (base != "res") p_extensions->push_back("res"); - } -ResourceFormatSaverBinary* ResourceFormatSaverBinary::singleton=NULL; +ResourceFormatSaverBinary *ResourceFormatSaverBinary::singleton = NULL; ResourceFormatSaverBinary::ResourceFormatSaverBinary() { - singleton=this; + singleton = this; } diff --git a/core/io/resource_format_binary.h b/core/io/resource_format_binary.h index 1fab6144d5..f378d0eae9 100644 --- a/core/io/resource_format_binary.h +++ b/core/io/resource_format_binary.h @@ -33,7 +33,6 @@ #include "io/resource_saver.h" #include "os/file_access.h" - class ResourceInteractiveLoaderBinary : public ResourceInteractiveLoader { String local_path; @@ -43,7 +42,6 @@ class ResourceInteractiveLoaderBinary : public ResourceInteractiveLoader { FileAccess *f; - bool endian_swap; bool use_real64; uint64_t importmd_ofs; @@ -73,58 +71,46 @@ class ResourceInteractiveLoaderBinary : public ResourceInteractiveLoader { String get_unicode_string(); void _advance_padding(uint32_t p_len); - Map<String,String> remaps; + Map<String, String> remaps; Error error; int stage; -friend class ResourceFormatLoaderBinary; + friend class ResourceFormatLoaderBinary; - - Error parse_variant(Variant& r_v); + Error parse_variant(Variant &r_v); public: - - virtual void set_local_path(const String& p_local_path); + virtual void set_local_path(const String &p_local_path); virtual Ref<Resource> get_resource(); virtual Error poll(); virtual int get_stage() const; virtual int get_stage_count() const; - void set_remaps(const Map<String,String>& p_remaps) { remaps=p_remaps; } + void set_remaps(const Map<String, String> &p_remaps) { remaps = p_remaps; } void open(FileAccess *p_f); String recognize(FileAccess *p_f); void get_dependencies(FileAccess *p_f, List<String> *p_dependencies, bool p_add_types); - ResourceInteractiveLoaderBinary(); ~ResourceInteractiveLoaderBinary(); - }; class ResourceFormatLoaderBinary : public ResourceFormatLoader { public: - - virtual Ref<ResourceInteractiveLoader> load_interactive(const String &p_path,Error *r_error=NULL); - virtual void get_recognized_extensions_for_type(const String& p_type,List<String> *p_extensions) const; + virtual Ref<ResourceInteractiveLoader> load_interactive(const String &p_path, Error *r_error = NULL); + virtual void get_recognized_extensions_for_type(const String &p_type, List<String> *p_extensions) const; virtual void get_recognized_extensions(List<String> *p_extensions) const; - virtual bool handles_type(const String& p_type) const; + virtual bool handles_type(const String &p_type) const; virtual String get_resource_type(const String &p_path) const; - virtual void get_dependencies(const String& p_path, List<String> *p_dependencies, bool p_add_types=false); - virtual Error rename_dependencies(const String &p_path,const Map<String,String>& p_map); - - - + virtual void get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types = false); + virtual Error rename_dependencies(const String &p_path, const Map<String, String> &p_map); }; - - - -class ResourceFormatSaverBinaryInstance { +class ResourceFormatSaverBinaryInstance { String local_path; - bool relative_paths; bool bundle_resources; bool skip_editor; @@ -134,19 +120,16 @@ class ResourceFormatSaverBinaryInstance { FileAccess *f; String magic; Set<RES> resource_set; - Map<StringName,int> string_map; + Map<StringName, int> string_map; Vector<StringName> strings; - - Map<RES,int> external_resources; + Map<RES, int> external_resources; List<RES> saved_resources; - struct Property { int name_idx; Variant value; PropertyInfo pi; - }; struct ResourceData { @@ -155,36 +138,25 @@ class ResourceFormatSaverBinaryInstance { List<Property> properties; }; - - - void _pad_buffer(int p_bytes); - void write_variant(const Variant& p_property,const PropertyInfo& p_hint=PropertyInfo()); - void _find_resources(const Variant& p_variant,bool p_main=false); - void save_unicode_string(const String& p_string); - int get_string_index(const String& p_string); -public: + void write_variant(const Variant &p_property, const PropertyInfo &p_hint = PropertyInfo()); + void _find_resources(const Variant &p_variant, bool p_main = false); + void save_unicode_string(const String &p_string); + int get_string_index(const String &p_string); - - Error save(const String &p_path,const RES& p_resource,uint32_t p_flags=0); +public: + Error save(const String &p_path, const RES &p_resource, uint32_t p_flags = 0); }; - - -class ResourceFormatSaverBinary : public ResourceFormatSaver { - - - +class ResourceFormatSaverBinary : public ResourceFormatSaver { public: - - static ResourceFormatSaverBinary* singleton; - virtual Error save(const String &p_path,const RES& p_resource,uint32_t p_flags=0); - virtual bool recognize(const RES& p_resource) const; - virtual void get_recognized_extensions(const RES& p_resource,List<String> *p_extensions) const; + static ResourceFormatSaverBinary *singleton; + virtual Error save(const String &p_path, const RES &p_resource, uint32_t p_flags = 0); + virtual bool recognize(const RES &p_resource) const; + virtual void get_recognized_extensions(const RES &p_resource, List<String> *p_extensions) const; ResourceFormatSaverBinary(); }; - #endif // RESOURCE_FORMAT_BINARY_H diff --git a/core/io/resource_import.cpp b/core/io/resource_import.cpp index 41245db173..27173a721d 100644 --- a/core/io/resource_import.cpp +++ b/core/io/resource_import.cpp @@ -28,106 +28,101 @@ /*************************************************************************/ #include "resource_import.h" -#include "variant_parser.h" #include "os/os.h" +#include "variant_parser.h" -Error ResourceFormatImporter::_get_path_and_type(const String& p_path, PathAndType &r_path_and_type) const { +Error ResourceFormatImporter::_get_path_and_type(const String &p_path, PathAndType &r_path_and_type) const { Error err; - FileAccess *f= FileAccess::open(p_path+".import",FileAccess::READ,&err); + FileAccess *f = FileAccess::open(p_path + ".import", FileAccess::READ, &err); if (!f) return err; VariantParser::StreamFile stream; - stream.f=f; + stream.f = f; String assign; Variant value; VariantParser::Tag next_tag; - int lines=0; + int lines = 0; String error_text; - while(true) { + while (true) { - assign=Variant(); + assign = Variant(); next_tag.fields.clear(); - next_tag.name=String(); + next_tag.name = String(); - err = VariantParser::parse_tag_assign_eof(&stream,lines,error_text,next_tag,assign,value,NULL,true); - if (err==ERR_FILE_EOF) { + err = VariantParser::parse_tag_assign_eof(&stream, lines, error_text, next_tag, assign, value, NULL, true); + if (err == ERR_FILE_EOF) { memdelete(f); return OK; - } - else if (err!=OK) { - ERR_PRINTS("ResourceFormatImporter::load - "+p_path+".import:"+itos(lines)+" error: "+error_text); + } else if (err != OK) { + ERR_PRINTS("ResourceFormatImporter::load - " + p_path + ".import:" + itos(lines) + " error: " + error_text); memdelete(f); return err; } - if (assign!=String()) { - if (assign.begins_with("path.") && r_path_and_type.path==String()) { - String feature = assign.get_slicec('.',1); + if (assign != String()) { + if (assign.begins_with("path.") && r_path_and_type.path == String()) { + String feature = assign.get_slicec('.', 1); if (OS::get_singleton()->check_feature_support(feature)) { - r_path_and_type.path=value; + r_path_and_type.path = value; } - } else if (assign=="path") { - r_path_and_type.path=value; - } else if (assign=="type") { - r_path_and_type.type=value; + } else if (assign == "path") { + r_path_and_type.path = value; + } else if (assign == "type") { + r_path_and_type.type = value; } - } else if (next_tag.name!="remap") { + } else if (next_tag.name != "remap") { break; } } memdelete(f); - if (r_path_and_type.path==String() || r_path_and_type.type==String()) { + if (r_path_and_type.path == String() || r_path_and_type.type == String()) { return ERR_FILE_CORRUPT; } return OK; - } - -RES ResourceFormatImporter::load(const String &p_path,const String& p_original_path,Error *r_error) { +RES ResourceFormatImporter::load(const String &p_path, const String &p_original_path, Error *r_error) { PathAndType pat; - Error err = _get_path_and_type(p_path,pat); + Error err = _get_path_and_type(p_path, pat); - if (err!=OK) { + if (err != OK) { if (r_error) - *r_error=err; + *r_error = err; return RES(); } - - RES res = ResourceLoader::load(pat.path,pat.type,false,r_error); + RES res = ResourceLoader::load(pat.path, pat.type, false, r_error); #ifdef TOOLS_ENABLED if (res.is_valid()) { - res->set_import_last_modified_time( res->get_last_modified_time() ); //pass this, if used + res->set_import_last_modified_time(res->get_last_modified_time()); //pass this, if used res->set_import_path(pat.path); } #endif return res; - } -void ResourceFormatImporter::get_recognized_extensions(List<String> *p_extensions) const{ +void ResourceFormatImporter::get_recognized_extensions(List<String> *p_extensions) const { Set<String> found; - for (Set< Ref<ResourceImporter> >::Element *E=importers.front();E;E=E->next()) { + for (Set<Ref<ResourceImporter> >::Element *E = importers.front(); E; E = E->next()) { List<String> local_exts; E->get()->get_recognized_extensions(&local_exts); - for (List<String>::Element *F=local_exts.front();F;F=F->next()) { + for (List<String>::Element *F = local_exts.front(); F; F = F->next()) { if (!found.has(F->get())) { p_extensions->push_back(F->get()); found.insert(F->get()); @@ -136,25 +131,25 @@ void ResourceFormatImporter::get_recognized_extensions(List<String> *p_extension } } -void ResourceFormatImporter::get_recognized_extensions_for_type(const String& p_type,List<String> *p_extensions) const{ +void ResourceFormatImporter::get_recognized_extensions_for_type(const String &p_type, List<String> *p_extensions) const { - if (p_type=="") { + if (p_type == "") { return get_recognized_extensions(p_extensions); } Set<String> found; - for (Set< Ref<ResourceImporter> >::Element *E=importers.front();E;E=E->next()) { + for (Set<Ref<ResourceImporter> >::Element *E = importers.front(); E; E = E->next()) { String res_type = E->get()->get_resource_type(); - if (res_type==String()) + if (res_type == String()) continue; - if (!ClassDB::is_parent_class(res_type,p_type)) + if (!ClassDB::is_parent_class(res_type, p_type)) continue; List<String> local_exts; E->get()->get_recognized_extensions(&local_exts); - for (List<String>::Element *F=local_exts.front();F;F=F->next()) { + for (List<String>::Element *F = local_exts.front(); F; F = F->next()) { if (!found.has(F->get())) { p_extensions->push_back(F->get()); found.insert(F->get()); @@ -163,40 +158,36 @@ void ResourceFormatImporter::get_recognized_extensions_for_type(const String& p_ } } -bool ResourceFormatImporter::recognize_path(const String& p_path,const String& p_for_type) const{ - - return FileAccess::exists(p_path+".import"); +bool ResourceFormatImporter::recognize_path(const String &p_path, const String &p_for_type) const { + return FileAccess::exists(p_path + ".import"); } -bool ResourceFormatImporter::can_be_imported(const String& p_path) const { +bool ResourceFormatImporter::can_be_imported(const String &p_path) const { return ResourceFormatLoader::recognize_path(p_path); } +bool ResourceFormatImporter::handles_type(const String &p_type) const { -bool ResourceFormatImporter::handles_type(const String& p_type) const { - - for (Set< Ref<ResourceImporter> >::Element *E=importers.front();E;E=E->next()) { + for (Set<Ref<ResourceImporter> >::Element *E = importers.front(); E; E = E->next()) { String res_type = E->get()->get_resource_type(); - if (res_type==String()) + if (res_type == String()) continue; - if (ClassDB::is_parent_class(res_type,p_type)) + if (ClassDB::is_parent_class(res_type, p_type)) return true; - } return true; } - -String ResourceFormatImporter::get_internal_resource_path(const String& p_path) const { +String ResourceFormatImporter::get_internal_resource_path(const String &p_path) const { PathAndType pat; - Error err = _get_path_and_type(p_path,pat); + Error err = _get_path_and_type(p_path, pat); - if (err!=OK) { + if (err != OK) { return String(); } @@ -207,9 +198,9 @@ String ResourceFormatImporter::get_internal_resource_path(const String& p_path) String ResourceFormatImporter::get_resource_type(const String &p_path) const { PathAndType pat; - Error err = _get_path_and_type(p_path,pat); + Error err = _get_path_and_type(p_path, pat); - if (err!=OK) { + if (err != OK) { return ""; } @@ -217,23 +208,23 @@ String ResourceFormatImporter::get_resource_type(const String &p_path) const { return pat.type; } -void ResourceFormatImporter::get_dependencies(const String& p_path,List<String> *p_dependencies,bool p_add_types){ +void ResourceFormatImporter::get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types) { PathAndType pat; - Error err = _get_path_and_type(p_path,pat); + Error err = _get_path_and_type(p_path, pat); - if (err!=OK) { + if (err != OK) { return; } - return ResourceLoader::get_dependencies(pat.path,p_dependencies,p_add_types); + return ResourceLoader::get_dependencies(pat.path, p_dependencies, p_add_types); } -Ref<ResourceImporter> ResourceFormatImporter::get_importer_by_name(const String& p_name) { +Ref<ResourceImporter> ResourceFormatImporter::get_importer_by_name(const String &p_name) { - for (Set< Ref<ResourceImporter> >::Element *E=importers.front();E;E=E->next()) { - if (E->get()->get_importer_name()==p_name) { + for (Set<Ref<ResourceImporter> >::Element *E = importers.front(); E; E = E->next()) { + if (E->get()->get_importer_name() == p_name) { return E->get(); } } @@ -241,34 +232,32 @@ Ref<ResourceImporter> ResourceFormatImporter::get_importer_by_name(const String& return Ref<ResourceImporter>(); } +void ResourceFormatImporter::get_importers_for_extension(const String &p_extension, List<Ref<ResourceImporter> > *r_importers) { -void ResourceFormatImporter::get_importers_for_extension(const String& p_extension,List<Ref<ResourceImporter> > *r_importers) { - - for (Set< Ref<ResourceImporter> >::Element *E=importers.front();E;E=E->next()) { + for (Set<Ref<ResourceImporter> >::Element *E = importers.front(); E; E = E->next()) { List<String> local_exts; E->get()->get_recognized_extensions(&local_exts); - for (List<String>::Element *F=local_exts.front();F;F=F->next()) { - if (p_extension.to_lower()==F->get()) { + for (List<String>::Element *F = local_exts.front(); F; F = F->next()) { + if (p_extension.to_lower() == F->get()) { r_importers->push_back(E->get()); } } } } -Ref<ResourceImporter> ResourceFormatImporter::get_importer_by_extension(const String& p_extension) { - +Ref<ResourceImporter> ResourceFormatImporter::get_importer_by_extension(const String &p_extension) { Ref<ResourceImporter> importer; - float priority=0; + float priority = 0; - for (Set< Ref<ResourceImporter> >::Element *E=importers.front();E;E=E->next()) { + for (Set<Ref<ResourceImporter> >::Element *E = importers.front(); E; E = E->next()) { List<String> local_exts; E->get()->get_recognized_extensions(&local_exts); - for (List<String>::Element *F=local_exts.front();F;F=F->next()) { - if (p_extension.to_lower()==F->get() && E->get()->get_priority() > priority) { - importer=E->get(); - priority=E->get()->get_priority(); + for (List<String>::Element *F = local_exts.front(); F; F = F->next()) { + if (p_extension.to_lower() == F->get() && E->get()->get_priority() > priority) { + importer = E->get(); + priority = E->get()->get_priority(); } } } @@ -276,13 +265,13 @@ Ref<ResourceImporter> ResourceFormatImporter::get_importer_by_extension(const St return importer; } -String ResourceFormatImporter::get_import_base_path(const String& p_for_file) const { +String ResourceFormatImporter::get_import_base_path(const String &p_for_file) const { - return "res://.import/"+p_for_file.get_file()+"-"+p_for_file.md5_text(); + return "res://.import/" + p_for_file.get_file() + "-" + p_for_file.md5_text(); } -ResourceFormatImporter *ResourceFormatImporter::singleton=NULL; +ResourceFormatImporter *ResourceFormatImporter::singleton = NULL; ResourceFormatImporter::ResourceFormatImporter() { - singleton=this; + singleton = this; } diff --git a/core/io/resource_import.h b/core/io/resource_import.h index dd7a82fe75..f4349a9c61 100644 --- a/core/io/resource_import.h +++ b/core/io/resource_import.h @@ -29,7 +29,6 @@ #ifndef RESOURCE_IMPORT_H #define RESOURCE_IMPORT_H - #include "io/resource_loader.h" class ResourceImporter; @@ -40,66 +39,64 @@ class ResourceFormatImporter : public ResourceFormatLoader { String type; }; - - Error _get_path_and_type(const String& p_path,PathAndType & r_path_and_type) const; + Error _get_path_and_type(const String &p_path, PathAndType &r_path_and_type) const; static ResourceFormatImporter *singleton; - Set< Ref<ResourceImporter> > importers; -public: + Set<Ref<ResourceImporter> > importers; +public: static ResourceFormatImporter *get_singleton() { return singleton; } - virtual RES load(const String &p_path,const String& p_original_path="",Error *r_error=NULL); + virtual RES load(const String &p_path, const String &p_original_path = "", Error *r_error = NULL); virtual void get_recognized_extensions(List<String> *p_extensions) const; - virtual void get_recognized_extensions_for_type(const String& p_type,List<String> *p_extensions) const; - virtual bool recognize_path(const String& p_path,const String& p_for_type=String()) const; - virtual bool handles_type(const String& p_type) const; + virtual void get_recognized_extensions_for_type(const String &p_type, List<String> *p_extensions) const; + virtual bool recognize_path(const String &p_path, const String &p_for_type = String()) const; + virtual bool handles_type(const String &p_type) const; virtual String get_resource_type(const String &p_path) const; - virtual void get_dependencies(const String& p_path,List<String> *p_dependencies,bool p_add_types=false); + virtual void get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types = false); - virtual bool can_be_imported(const String& p_path) const; + virtual bool can_be_imported(const String &p_path) const; - String get_internal_resource_path(const String& p_path) const; + String get_internal_resource_path(const String &p_path) const; - void add_importer(const Ref<ResourceImporter>& p_importer) { importers.insert(p_importer); } - Ref<ResourceImporter> get_importer_by_name(const String& p_name); - Ref<ResourceImporter> get_importer_by_extension(const String& p_extension); - void get_importers_for_extension(const String& p_extension,List<Ref<ResourceImporter> > *r_importers); + void add_importer(const Ref<ResourceImporter> &p_importer) { importers.insert(p_importer); } + Ref<ResourceImporter> get_importer_by_name(const String &p_name); + Ref<ResourceImporter> get_importer_by_extension(const String &p_extension); + void get_importers_for_extension(const String &p_extension, List<Ref<ResourceImporter> > *r_importers); - String get_import_base_path(const String& p_for_file) const; + String get_import_base_path(const String &p_for_file) const; ResourceFormatImporter(); }; - class ResourceImporter : public Reference { - GDCLASS(ResourceImporter,Reference) + GDCLASS(ResourceImporter, Reference) public: - virtual String get_importer_name() const=0; - virtual String get_visible_name() const=0; - virtual void get_recognized_extensions(List<String> *p_extensions) const=0; - virtual String get_save_extension() const=0; - virtual String get_resource_type() const=0; + virtual String get_importer_name() const = 0; + virtual String get_visible_name() const = 0; + virtual void get_recognized_extensions(List<String> *p_extensions) const = 0; + virtual String get_save_extension() const = 0; + virtual String get_resource_type() const = 0; virtual float get_priority() const { return 1.0; } struct ImportOption { PropertyInfo option; Variant default_value; - ImportOption(const PropertyInfo& p_info,const Variant& p_default) { option=p_info; default_value=p_default; } + ImportOption(const PropertyInfo &p_info, const Variant &p_default) { + option = p_info; + default_value = p_default; + } ImportOption() {} }; - virtual int get_preset_count() const { return 0; } virtual String get_preset_name(int p_idx) const { return String(); } - virtual void get_import_options(List<ImportOption> *r_options,int p_preset=0) const=0; - virtual bool get_option_visibility(const String& p_option,const Map<StringName,Variant>& p_options) const=0; - - - virtual Error import(const String& p_source_file,const String& p_save_path,const Map<StringName,Variant>& p_options,List<String>* r_platform_variants,List<String>* r_gen_files=NULL)=0; + virtual void get_import_options(List<ImportOption> *r_options, int p_preset = 0) const = 0; + virtual bool get_option_visibility(const String &p_option, const Map<StringName, Variant> &p_options) const = 0; + virtual Error import(const String &p_source_file, const String &p_save_path, const Map<StringName, Variant> &p_options, List<String> *r_platform_variants, List<String> *r_gen_files = NULL) = 0; }; #endif // RESOURCE_IMPORT_H diff --git a/core/io/resource_loader.cpp b/core/io/resource_loader.cpp index c14389eefa..5d8ec57ee0 100644 --- a/core/io/resource_loader.cpp +++ b/core/io/resource_loader.cpp @@ -27,81 +27,76 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "resource_loader.h" -#include "print_string.h" #include "global_config.h" -#include "path_remap.h" #include "os/file_access.h" #include "os/os.h" +#include "path_remap.h" +#include "print_string.h" ResourceFormatLoader *ResourceLoader::loader[MAX_LOADERS]; -int ResourceLoader::loader_count=0; - +int ResourceLoader::loader_count = 0; Error ResourceInteractiveLoader::wait() { Error err = poll(); - while (err==OK) { - err=poll(); + while (err == OK) { + err = poll(); } return err; } -bool ResourceFormatLoader::recognize_path(const String& p_path,const String& p_for_type) const { - +bool ResourceFormatLoader::recognize_path(const String &p_path, const String &p_for_type) const { String extension = p_path.get_extension(); List<String> extensions; - if (p_for_type==String()) { + if (p_for_type == String()) { get_recognized_extensions(&extensions); } else { - get_recognized_extensions_for_type(p_for_type,&extensions); + get_recognized_extensions_for_type(p_for_type, &extensions); } - for (List<String>::Element *E=extensions.front();E;E=E->next()) { - + for (List<String>::Element *E = extensions.front(); E; E = E->next()) { - if (E->get().nocasecmp_to(extension)==0) + if (E->get().nocasecmp_to(extension) == 0) return true; } return false; - } +void ResourceFormatLoader::get_recognized_extensions_for_type(const String &p_type, List<String> *p_extensions) const { -void ResourceFormatLoader::get_recognized_extensions_for_type(const String& p_type,List<String> *p_extensions) const { - - if (p_type=="" || handles_type(p_type)) + if (p_type == "" || handles_type(p_type)) get_recognized_extensions(p_extensions); } -void ResourceLoader::get_recognized_extensions_for_type(const String& p_type,List<String> *p_extensions) { +void ResourceLoader::get_recognized_extensions_for_type(const String &p_type, List<String> *p_extensions) { - for (int i=0;i<loader_count;i++) { - loader[i]->get_recognized_extensions_for_type(p_type,p_extensions); + for (int i = 0; i < loader_count; i++) { + loader[i]->get_recognized_extensions_for_type(p_type, p_extensions); } - } void ResourceInteractiveLoader::_bind_methods() { - ClassDB::bind_method(D_METHOD("get_resource"),&ResourceInteractiveLoader::get_resource); - ClassDB::bind_method(D_METHOD("poll"),&ResourceInteractiveLoader::poll); - ClassDB::bind_method(D_METHOD("wait"),&ResourceInteractiveLoader::wait); - ClassDB::bind_method(D_METHOD("get_stage"),&ResourceInteractiveLoader::get_stage); - ClassDB::bind_method(D_METHOD("get_stage_count"),&ResourceInteractiveLoader::get_stage_count); + ClassDB::bind_method(D_METHOD("get_resource"), &ResourceInteractiveLoader::get_resource); + ClassDB::bind_method(D_METHOD("poll"), &ResourceInteractiveLoader::poll); + ClassDB::bind_method(D_METHOD("wait"), &ResourceInteractiveLoader::wait); + ClassDB::bind_method(D_METHOD("get_stage"), &ResourceInteractiveLoader::get_stage); + ClassDB::bind_method(D_METHOD("get_stage_count"), &ResourceInteractiveLoader::get_stage_count); } class ResourceInteractiveLoaderDefault : public ResourceInteractiveLoader { - GDCLASS( ResourceInteractiveLoaderDefault, ResourceInteractiveLoader ); -public: + GDCLASS(ResourceInteractiveLoaderDefault, ResourceInteractiveLoader); +public: Ref<Resource> resource; - virtual void set_local_path(const String& p_local_path) { /*scene->set_filename(p_local_path);*/ } + virtual void set_local_path(const String &p_local_path) { /*scene->set_filename(p_local_path);*/ + } virtual Ref<Resource> get_resource() { return resource; } virtual Error poll() { return ERR_FILE_EOF; } virtual int get_stage() const { return 1; } @@ -110,94 +105,87 @@ public: ResourceInteractiveLoaderDefault() {} }; - - Ref<ResourceInteractiveLoader> ResourceFormatLoader::load_interactive(const String &p_path, Error *r_error) { //either this - Ref<Resource> res = load(p_path,p_path,r_error); + Ref<Resource> res = load(p_path, p_path, r_error); if (res.is_null()) return Ref<ResourceInteractiveLoader>(); - Ref<ResourceInteractiveLoaderDefault> ril = Ref<ResourceInteractiveLoaderDefault>( memnew( ResourceInteractiveLoaderDefault )); - ril->resource=res; + Ref<ResourceInteractiveLoaderDefault> ril = Ref<ResourceInteractiveLoaderDefault>(memnew(ResourceInteractiveLoaderDefault)); + ril->resource = res; return ril; } -RES ResourceFormatLoader::load(const String &p_path, const String& p_original_path, Error *r_error) { +RES ResourceFormatLoader::load(const String &p_path, const String &p_original_path, Error *r_error) { - - String path=p_path; + String path = p_path; //or this must be implemented - Ref<ResourceInteractiveLoader> ril = load_interactive(p_path,r_error); + Ref<ResourceInteractiveLoader> ril = load_interactive(p_path, r_error); if (!ril.is_valid()) return RES(); ril->set_local_path(p_original_path); - while(true) { + while (true) { Error err = ril->poll(); - if (err==ERR_FILE_EOF) { + if (err == ERR_FILE_EOF) { if (r_error) - *r_error=OK; + *r_error = OK; return ril->get_resource(); } if (r_error) - *r_error=err; + *r_error = err; - ERR_FAIL_COND_V(err!=OK,RES()); + ERR_FAIL_COND_V(err != OK, RES()); } return RES(); - } -void ResourceFormatLoader::get_dependencies(const String& p_path, List<String> *p_dependencies, bool p_add_types) { +void ResourceFormatLoader::get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types) { //do nothing by default } - /////////////////////////////////// - -RES ResourceLoader::load(const String &p_path, const String& p_type_hint, bool p_no_cache, Error *r_error) { +RES ResourceLoader::load(const String &p_path, const String &p_type_hint, bool p_no_cache, Error *r_error) { if (r_error) - *r_error=ERR_CANT_OPEN; + *r_error = ERR_CANT_OPEN; String local_path; if (p_path.is_rel_path()) - local_path="res://"+p_path; + local_path = "res://" + p_path; else local_path = GlobalConfig::get_singleton()->localize_path(p_path); - - ERR_FAIL_COND_V(local_path=="",RES()); + ERR_FAIL_COND_V(local_path == "", RES()); if (!p_no_cache && ResourceCache::has(local_path)) { if (OS::get_singleton()->is_stdout_verbose()) - print_line("load resource: "+local_path+" (cached)"); + print_line("load resource: " + local_path + " (cached)"); - return RES( ResourceCache::get(local_path ) ); + return RES(ResourceCache::get(local_path)); } if (OS::get_singleton()->is_stdout_verbose()) - print_line("load resource: "+local_path); - bool found=false; + print_line("load resource: " + local_path); + bool found = false; - for (int i=0;i<loader_count;i++) { + for (int i = 0; i < loader_count; i++) { - if (!loader[i]->recognize_path(local_path,p_type_hint)) { + if (!loader[i]->recognize_path(local_path, p_type_hint)) { print_line("path not recognized"); continue; } - found=true; - RES res = loader[i]->load(local_path,local_path,r_error); + found = true; + RES res = loader[i]->load(local_path, local_path, r_error); if (res.is_null()) { continue; } @@ -217,37 +205,31 @@ RES ResourceLoader::load(const String &p_path, const String& p_type_hint, bool p } if (found) { - ERR_EXPLAIN("Failed loading resource: "+p_path); + ERR_EXPLAIN("Failed loading resource: " + p_path); } else { - ERR_EXPLAIN("No loader found for resource: "+p_path); + ERR_EXPLAIN("No loader found for resource: " + p_path); } ERR_FAIL_V(RES()); return RES(); } - - -Ref<ResourceInteractiveLoader> ResourceLoader::load_interactive(const String &p_path,const String& p_type_hint,bool p_no_cache,Error *r_error) { - +Ref<ResourceInteractiveLoader> ResourceLoader::load_interactive(const String &p_path, const String &p_type_hint, bool p_no_cache, Error *r_error) { if (r_error) - *r_error=ERR_CANT_OPEN; + *r_error = ERR_CANT_OPEN; String local_path; if (p_path.is_rel_path()) - local_path="res://"+p_path; + local_path = "res://" + p_path; else local_path = GlobalConfig::get_singleton()->localize_path(p_path); - - ERR_FAIL_COND_V(local_path=="",Ref<ResourceInteractiveLoader>()); - - + ERR_FAIL_COND_V(local_path == "", Ref<ResourceInteractiveLoader>()); if (!p_no_cache && ResourceCache::has(local_path)) { if (OS::get_singleton()->is_stdout_verbose()) - print_line("load resource: "+local_path+" (cached)"); + print_line("load resource: " + local_path + " (cached)"); Ref<Resource> res_cached = ResourceCache::get(local_path); Ref<ResourceInteractiveLoaderDefault> ril = Ref<ResourceInteractiveLoaderDefault>(memnew(ResourceInteractiveLoaderDefault)); @@ -259,14 +241,14 @@ Ref<ResourceInteractiveLoader> ResourceLoader::load_interactive(const String &p_ if (OS::get_singleton()->is_stdout_verbose()) print_line("load resource: "); - bool found=false; + bool found = false; - for (int i=0;i<loader_count;i++) { + for (int i = 0; i < loader_count; i++) { - if (!loader[i]->recognize_path(local_path,p_type_hint)) + if (!loader[i]->recognize_path(local_path, p_type_hint)) continue; - found=true; - Ref<ResourceInteractiveLoader> ril = loader[i]->load_interactive(local_path,r_error); + found = true; + Ref<ResourceInteractiveLoader> ril = loader[i]->load_interactive(local_path, r_error); if (ril.is_null()) continue; if (!p_no_cache) @@ -276,39 +258,37 @@ Ref<ResourceInteractiveLoader> ResourceLoader::load_interactive(const String &p_ } if (found) { - ERR_EXPLAIN("Failed loading resource: "+p_path); + ERR_EXPLAIN("Failed loading resource: " + p_path); } else { - ERR_EXPLAIN("No loader found for resource: "+p_path); + ERR_EXPLAIN("No loader found for resource: " + p_path); } ERR_FAIL_V(Ref<ResourceInteractiveLoader>()); return Ref<ResourceInteractiveLoader>(); - } void ResourceLoader::add_resource_format_loader(ResourceFormatLoader *p_format_loader, bool p_at_front) { - ERR_FAIL_COND( loader_count >= MAX_LOADERS ); + ERR_FAIL_COND(loader_count >= MAX_LOADERS); if (p_at_front) { - for(int i=loader_count;i>0;i--) { - loader[i]=loader[i-1]; + for (int i = loader_count; i > 0; i--) { + loader[i] = loader[i - 1]; } - loader[0]=p_format_loader; + loader[0] = p_format_loader; loader_count++; } else { - loader[loader_count++]=p_format_loader; + loader[loader_count++] = p_format_loader; } } -void ResourceLoader::get_dependencies(const String& p_path, List<String> *p_dependencies, bool p_add_types) { - +void ResourceLoader::get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types) { String local_path; if (p_path.is_rel_path()) - local_path="res://"+p_path; + local_path = "res://" + p_path; else local_path = GlobalConfig::get_singleton()->localize_path(p_path); - for (int i=0;i<loader_count;i++) { + for (int i = 0; i < loader_count; i++) { if (!loader[i]->recognize_path(local_path)) continue; @@ -317,22 +297,19 @@ void ResourceLoader::get_dependencies(const String& p_path, List<String> *p_depe continue; */ - loader[i]->get_dependencies(local_path,p_dependencies,p_add_types); - + loader[i]->get_dependencies(local_path, p_dependencies, p_add_types); } } -Error ResourceLoader::rename_dependencies(const String &p_path,const Map<String,String>& p_map) { - +Error ResourceLoader::rename_dependencies(const String &p_path, const Map<String, String> &p_map) { String local_path; if (p_path.is_rel_path()) - local_path="res://"+p_path; + local_path = "res://" + p_path; else local_path = GlobalConfig::get_singleton()->localize_path(p_path); - - for (int i=0;i<loader_count;i++) { + for (int i = 0; i < loader_count; i++) { if (!loader[i]->recognize_path(local_path)) continue; @@ -341,41 +318,34 @@ Error ResourceLoader::rename_dependencies(const String &p_path,const Map<String, continue; */ - return loader[i]->rename_dependencies(local_path,p_map); - + return loader[i]->rename_dependencies(local_path, p_map); } return OK; // ?? - } - - String ResourceLoader::get_resource_type(const String &p_path) { String local_path; if (p_path.is_rel_path()) - local_path="res://"+p_path; + local_path = "res://" + p_path; else local_path = GlobalConfig::get_singleton()->localize_path(p_path); - - for (int i=0;i<loader_count;i++) { + for (int i = 0; i < loader_count; i++) { String result = loader[i]->get_resource_type(local_path); - if (result!="") + if (result != "") return result; } return ""; - } -ResourceLoadErrorNotify ResourceLoader::err_notify=NULL; -void *ResourceLoader::err_notify_ud=NULL; - -DependencyErrorNotify ResourceLoader::dep_err_notify=NULL; -void *ResourceLoader::dep_err_notify_ud=NULL; +ResourceLoadErrorNotify ResourceLoader::err_notify = NULL; +void *ResourceLoader::err_notify_ud = NULL; -bool ResourceLoader::abort_on_missing_resource=true; -bool ResourceLoader::timestamp_on_load=false; +DependencyErrorNotify ResourceLoader::dep_err_notify = NULL; +void *ResourceLoader::dep_err_notify_ud = NULL; +bool ResourceLoader::abort_on_missing_resource = true; +bool ResourceLoader::timestamp_on_load = false; diff --git a/core/io/resource_loader.h b/core/io/resource_loader.h index f464415e12..0d51b07414 100644 --- a/core/io/resource_loader.h +++ b/core/io/resource_loader.h @@ -37,86 +37,86 @@ class ResourceInteractiveLoader : public Reference { - GDCLASS(ResourceInteractiveLoader,Reference); -protected: + GDCLASS(ResourceInteractiveLoader, Reference); +protected: static void _bind_methods(); -public: - virtual void set_local_path(const String& p_local_path)=0; - virtual Ref<Resource> get_resource()=0; - virtual Error poll()=0; - virtual int get_stage() const=0; - virtual int get_stage_count() const=0; +public: + virtual void set_local_path(const String &p_local_path) = 0; + virtual Ref<Resource> get_resource() = 0; + virtual Error poll() = 0; + virtual int get_stage() const = 0; + virtual int get_stage_count() const = 0; virtual Error wait(); ResourceInteractiveLoader() {} }; - class ResourceFormatLoader { public: - - virtual Ref<ResourceInteractiveLoader> load_interactive(const String &p_path,Error *r_error=NULL); - virtual RES load(const String &p_path,const String& p_original_path="",Error *r_error=NULL); - virtual void get_recognized_extensions(List<String> *p_extensions) const=0; - virtual void get_recognized_extensions_for_type(const String& p_type,List<String> *p_extensions) const; - virtual bool recognize_path(const String& p_path,const String& p_for_type=String()) const; - virtual bool handles_type(const String& p_type) const=0; - virtual String get_resource_type(const String &p_path) const=0; - virtual void get_dependencies(const String& p_path,List<String> *p_dependencies,bool p_add_types=false); - virtual Error rename_dependencies(const String &p_path,const Map<String,String>& p_map) { return OK; } + virtual Ref<ResourceInteractiveLoader> load_interactive(const String &p_path, Error *r_error = NULL); + virtual RES load(const String &p_path, const String &p_original_path = "", Error *r_error = NULL); + virtual void get_recognized_extensions(List<String> *p_extensions) const = 0; + virtual void get_recognized_extensions_for_type(const String &p_type, List<String> *p_extensions) const; + virtual bool recognize_path(const String &p_path, const String &p_for_type = String()) const; + virtual bool handles_type(const String &p_type) const = 0; + virtual String get_resource_type(const String &p_path) const = 0; + virtual void get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types = false); + virtual Error rename_dependencies(const String &p_path, const Map<String, String> &p_map) { return OK; } virtual ~ResourceFormatLoader() {} }; - -typedef void (*ResourceLoadErrorNotify)(void *p_ud,const String& p_text); -typedef void (*DependencyErrorNotify)(void *p_ud,const String& p_loading,const String& p_which,const String& p_type); - +typedef void (*ResourceLoadErrorNotify)(void *p_ud, const String &p_text); +typedef void (*DependencyErrorNotify)(void *p_ud, const String &p_loading, const String &p_which, const String &p_type); class ResourceLoader { enum { - MAX_LOADERS=64 + MAX_LOADERS = 64 }; static ResourceFormatLoader *loader[MAX_LOADERS]; static int loader_count; static bool timestamp_on_load; - static void* err_notify_ud; + static void *err_notify_ud; static ResourceLoadErrorNotify err_notify; - static void* dep_err_notify_ud; + static void *dep_err_notify_ud; static DependencyErrorNotify dep_err_notify; static bool abort_on_missing_resource; public: + static Ref<ResourceInteractiveLoader> load_interactive(const String &p_path, const String &p_type_hint = "", bool p_no_cache = false, Error *r_error = NULL); + static RES load(const String &p_path, const String &p_type_hint = "", bool p_no_cache = false, Error *r_error = NULL); - - - static Ref<ResourceInteractiveLoader> load_interactive(const String &p_path,const String& p_type_hint="",bool p_no_cache=false,Error *r_error=NULL); - static RES load(const String &p_path,const String& p_type_hint="",bool p_no_cache=false,Error *r_error=NULL); - - static void get_recognized_extensions_for_type(const String& p_type,List<String> *p_extensions); - static void add_resource_format_loader(ResourceFormatLoader *p_format_loader,bool p_at_front=false); + static void get_recognized_extensions_for_type(const String &p_type, List<String> *p_extensions); + static void add_resource_format_loader(ResourceFormatLoader *p_format_loader, bool p_at_front = false); static String get_resource_type(const String &p_path); - static void get_dependencies(const String& p_path,List<String> *p_dependencies,bool p_add_types=false); - static Error rename_dependencies(const String &p_path,const Map<String,String>& p_map); - - static void set_timestamp_on_load(bool p_timestamp) { timestamp_on_load=p_timestamp; } - - static void notify_load_error(const String& p_err) { if (err_notify) err_notify(err_notify_ud,p_err); } - static void set_error_notify_func(void* p_ud,ResourceLoadErrorNotify p_err_notify) { err_notify=p_err_notify; err_notify_ud=p_ud;} - - static void notify_dependency_error(const String& p_path,const String& p_dependency,const String& p_type) { if (dep_err_notify) dep_err_notify(dep_err_notify_ud,p_path,p_dependency,p_type); } - static void set_dependency_error_notify_func(void* p_ud,DependencyErrorNotify p_err_notify) { dep_err_notify=p_err_notify; dep_err_notify_ud=p_ud;} - - - static void set_abort_on_missing_resources(bool p_abort) { abort_on_missing_resource=p_abort; } + static void get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types = false); + static Error rename_dependencies(const String &p_path, const Map<String, String> &p_map); + + static void set_timestamp_on_load(bool p_timestamp) { timestamp_on_load = p_timestamp; } + + static void notify_load_error(const String &p_err) { + if (err_notify) err_notify(err_notify_ud, p_err); + } + static void set_error_notify_func(void *p_ud, ResourceLoadErrorNotify p_err_notify) { + err_notify = p_err_notify; + err_notify_ud = p_ud; + } + + static void notify_dependency_error(const String &p_path, const String &p_dependency, const String &p_type) { + if (dep_err_notify) dep_err_notify(dep_err_notify_ud, p_path, p_dependency, p_type); + } + static void set_dependency_error_notify_func(void *p_ud, DependencyErrorNotify p_err_notify) { + dep_err_notify = p_err_notify; + dep_err_notify_ud = p_ud; + } + + static void set_abort_on_missing_resources(bool p_abort) { abort_on_missing_resource = p_abort; } static bool get_abort_on_missing_resources() { return abort_on_missing_resource; } }; - - #endif diff --git a/core/io/resource_saver.cpp b/core/io/resource_saver.cpp index f0bea30051..e4548b16ff 100644 --- a/core/io/resource_saver.cpp +++ b/core/io/resource_saver.cpp @@ -29,62 +29,61 @@ #include "resource_saver.h" #include "global_config.h" #include "os/file_access.h" -#include "script_language.h" #include "resource_loader.h" +#include "script_language.h" ResourceFormatSaver *ResourceSaver::saver[MAX_SAVERS]; -int ResourceSaver::saver_count=0; -bool ResourceSaver::timestamp_on_save=false; -ResourceSavedCallback ResourceSaver::save_callback=0; +int ResourceSaver::saver_count = 0; +bool ResourceSaver::timestamp_on_save = false; +ResourceSavedCallback ResourceSaver::save_callback = 0; -Error ResourceSaver::save(const String &p_path,const RES& p_resource,uint32_t p_flags) { +Error ResourceSaver::save(const String &p_path, const RES &p_resource, uint32_t p_flags) { - String extension=p_path.get_extension(); - Error err=ERR_FILE_UNRECOGNIZED; + String extension = p_path.get_extension(); + Error err = ERR_FILE_UNRECOGNIZED; - for (int i=0;i<saver_count;i++) { + for (int i = 0; i < saver_count; i++) { if (!saver[i]->recognize(p_resource)) continue; List<String> extensions; - bool recognized=false; - saver[i]->get_recognized_extensions(p_resource,&extensions); + bool recognized = false; + saver[i]->get_recognized_extensions(p_resource, &extensions); - for (List<String>::Element *E=extensions.front();E;E=E->next()) { + for (List<String>::Element *E = extensions.front(); E; E = E->next()) { - if (E->get().nocasecmp_to(extension.get_extension())==0) - recognized=true; + if (E->get().nocasecmp_to(extension.get_extension()) == 0) + recognized = true; } if (!recognized) continue; - String old_path=p_resource->get_path(); + String old_path = p_resource->get_path(); - - String local_path=GlobalConfig::get_singleton()->localize_path(p_path); + String local_path = GlobalConfig::get_singleton()->localize_path(p_path); RES rwcopy = p_resource; - if (p_flags&FLAG_CHANGE_PATH) + if (p_flags & FLAG_CHANGE_PATH) rwcopy->set_path(local_path); - err = saver[i]->save(p_path,p_resource,p_flags); + err = saver[i]->save(p_path, p_resource, p_flags); - if (err == OK ) { + if (err == OK) { #ifdef TOOLS_ENABLED - ((Resource*)p_resource.ptr())->set_edited(false); + ((Resource *)p_resource.ptr())->set_edited(false); if (timestamp_on_save) { uint64_t mt = FileAccess::get_modified_time(p_path); - ((Resource*)p_resource.ptr())->set_last_modified_time(mt); + ((Resource *)p_resource.ptr())->set_last_modified_time(mt); } #endif - if (p_flags&FLAG_CHANGE_PATH) + if (p_flags & FLAG_CHANGE_PATH) rwcopy->set_path(old_path); if (save_callback && p_path.begins_with("res://")) @@ -92,46 +91,36 @@ Error ResourceSaver::save(const String &p_path,const RES& p_resource,uint32_t p_ return OK; } else { - } } return err; } - void ResourceSaver::set_save_callback(ResourceSavedCallback p_callback) { - save_callback=p_callback; + save_callback = p_callback; } +void ResourceSaver::get_recognized_extensions(const RES &p_resource, List<String> *p_extensions) { -void ResourceSaver::get_recognized_extensions(const RES& p_resource,List<String> *p_extensions) { - - - for (int i=0;i<saver_count;i++) { + for (int i = 0; i < saver_count; i++) { - saver[i]->get_recognized_extensions(p_resource,p_extensions); + saver[i]->get_recognized_extensions(p_resource, p_extensions); } - } void ResourceSaver::add_resource_format_saver(ResourceFormatSaver *p_format_saver, bool p_at_front) { - ERR_FAIL_COND( saver_count >= MAX_SAVERS ); + ERR_FAIL_COND(saver_count >= MAX_SAVERS); if (p_at_front) { - for(int i=saver_count;i>0;i--) { - saver[i]=saver[i-1]; + for (int i = saver_count; i > 0; i--) { + saver[i] = saver[i - 1]; } - saver[0]=p_format_saver; + saver[0] = p_format_saver; saver_count++; } else { - saver[saver_count++]=p_format_saver; + saver[saver_count++] = p_format_saver; } - } - - - - diff --git a/core/io/resource_saver.h b/core/io/resource_saver.h index f00f074090..b9bb2aafae 100644 --- a/core/io/resource_saver.h +++ b/core/io/resource_saver.h @@ -35,27 +35,21 @@ @author Juan Linietsky <reduzio@gmail.com> */ - - - - - class ResourceFormatSaver { public: - - virtual Error save(const String &p_path,const RES& p_resource,uint32_t p_flags=0)=0; - virtual bool recognize(const RES& p_resource) const=0; - virtual void get_recognized_extensions(const RES& p_resource,List<String> *p_extensions) const=0; + virtual Error save(const String &p_path, const RES &p_resource, uint32_t p_flags = 0) = 0; + virtual bool recognize(const RES &p_resource) const = 0; + virtual void get_recognized_extensions(const RES &p_resource, List<String> *p_extensions) const = 0; virtual ~ResourceFormatSaver() {} }; -typedef void (*ResourceSavedCallback)(const String& p_path); +typedef void (*ResourceSavedCallback)(const String &p_path); class ResourceSaver { enum { - MAX_SAVERS=64 + MAX_SAVERS = 64 }; static ResourceFormatSaver *saver[MAX_SAVERS]; @@ -63,31 +57,24 @@ class ResourceSaver { static bool timestamp_on_save; static ResourceSavedCallback save_callback; - public: - enum SaverFlags { - FLAG_RELATIVE_PATHS=1, - FLAG_BUNDLE_RESOURCES=2, - FLAG_CHANGE_PATH=4, - FLAG_OMIT_EDITOR_PROPERTIES=8, - FLAG_SAVE_BIG_ENDIAN=16, - FLAG_COMPRESS=32, - FLAG_REPLACE_SUBRESOURCE_PATHS=64, + FLAG_RELATIVE_PATHS = 1, + FLAG_BUNDLE_RESOURCES = 2, + FLAG_CHANGE_PATH = 4, + FLAG_OMIT_EDITOR_PROPERTIES = 8, + FLAG_SAVE_BIG_ENDIAN = 16, + FLAG_COMPRESS = 32, + FLAG_REPLACE_SUBRESOURCE_PATHS = 64, }; + static Error save(const String &p_path, const RES &p_resource, uint32_t p_flags = 0); + static void get_recognized_extensions(const RES &p_resource, List<String> *p_extensions); + static void add_resource_format_saver(ResourceFormatSaver *p_format_saver, bool p_at_front = false); - static Error save(const String &p_path,const RES& p_resource,uint32_t p_flags=0); - static void get_recognized_extensions(const RES& p_resource,List<String> *p_extensions); - static void add_resource_format_saver(ResourceFormatSaver *p_format_saver,bool p_at_front=false); - - static void set_timestamp_on_save(bool p_timestamp) { timestamp_on_save=p_timestamp; } + static void set_timestamp_on_save(bool p_timestamp) { timestamp_on_save = p_timestamp; } static void set_save_callback(ResourceSavedCallback p_callback); - - - }; - #endif diff --git a/core/io/stream_peer.cpp b/core/io/stream_peer.cpp index 3c4719269f..07df47f8c0 100644 --- a/core/io/stream_peer.cpp +++ b/core/io/stream_peer.cpp @@ -29,21 +29,21 @@ #include "stream_peer.h" #include "io/marshalls.h" -Error StreamPeer::_put_data(const PoolVector<uint8_t>& p_data) { +Error StreamPeer::_put_data(const PoolVector<uint8_t> &p_data) { int len = p_data.size(); - if (len==0) + if (len == 0) return OK; PoolVector<uint8_t>::Read r = p_data.read(); - return put_data(&r[0],len); + return put_data(&r[0], len); } -Array StreamPeer::_put_partial_data(const PoolVector<uint8_t>& p_data) { +Array StreamPeer::_put_partial_data(const PoolVector<uint8_t> &p_data) { Array ret; int len = p_data.size(); - if (len==0) { + if (len == 0) { ret.push_back(OK); ret.push_back(0); return ret; @@ -51,24 +51,23 @@ Array StreamPeer::_put_partial_data(const PoolVector<uint8_t>& p_data) { PoolVector<uint8_t>::Read r = p_data.read(); int sent; - Error err = put_partial_data(&r[0],len,sent); + Error err = put_partial_data(&r[0], len, sent); - if (err!=OK) { - sent=0; + if (err != OK) { + sent = 0; } ret.push_back(err); ret.push_back(sent); return ret; } - Array StreamPeer::_get_data(int p_bytes) { Array ret; PoolVector<uint8_t> data; data.resize(p_bytes); - if (data.size()!=p_bytes) { + if (data.size() != p_bytes) { ret.push_back(ERR_OUT_OF_MEMORY); ret.push_back(PoolVector<uint8_t>()); @@ -76,12 +75,11 @@ Array StreamPeer::_get_data(int p_bytes) { } PoolVector<uint8_t>::Write w = data.write(); - Error err = get_data(&w[0],p_bytes); + Error err = get_data(&w[0], p_bytes); w = PoolVector<uint8_t>::Write(); ret.push_back(err); ret.push_back(data); return ret; - } Array StreamPeer::_get_partial_data(int p_bytes) { @@ -90,7 +88,7 @@ Array StreamPeer::_get_partial_data(int p_bytes) { PoolVector<uint8_t> data; data.resize(p_bytes); - if (data.size()!=p_bytes) { + if (data.size() != p_bytes) { ret.push_back(ERR_OUT_OF_MEMORY); ret.push_back(PoolVector<uint8_t>()); @@ -99,12 +97,12 @@ Array StreamPeer::_get_partial_data(int p_bytes) { PoolVector<uint8_t>::Write w = data.write(); int received; - Error err = get_partial_data(&w[0],p_bytes,received); + Error err = get_partial_data(&w[0], p_bytes, received); w = PoolVector<uint8_t>::Write(); - if (err!=OK) { + if (err != OK) { data.resize(0); - } else if (received!=data.size()) { + } else if (received != data.size()) { data.resize(received); } @@ -112,12 +110,11 @@ Array StreamPeer::_get_partial_data(int p_bytes) { ret.push_back(err); ret.push_back(data); return ret; - } void StreamPeer::set_big_endian(bool p_enable) { - big_endian=p_enable; + big_endian = p_enable; } bool StreamPeer::is_big_endian_enabled() const { @@ -125,389 +122,359 @@ bool StreamPeer::is_big_endian_enabled() const { return big_endian; } - void StreamPeer::put_u8(uint8_t p_val) { - put_data((const uint8_t*)&p_val,1); - + put_data((const uint8_t *)&p_val, 1); } -void StreamPeer::put_8(int8_t p_val){ +void StreamPeer::put_8(int8_t p_val) { - put_data((const uint8_t*)&p_val,1); + put_data((const uint8_t *)&p_val, 1); } -void StreamPeer::put_u16(uint16_t p_val){ +void StreamPeer::put_u16(uint16_t p_val) { if (big_endian) { - p_val=BSWAP16(p_val); + p_val = BSWAP16(p_val); } uint8_t buf[2]; - encode_uint16(p_val,buf); - put_data(buf,2); - + encode_uint16(p_val, buf); + put_data(buf, 2); } -void StreamPeer::put_16(int16_t p_val){ +void StreamPeer::put_16(int16_t p_val) { if (big_endian) { - p_val=BSWAP16(p_val); + p_val = BSWAP16(p_val); } uint8_t buf[2]; - encode_uint16(p_val,buf); - put_data(buf,2); - + encode_uint16(p_val, buf); + put_data(buf, 2); } -void StreamPeer::put_u32(uint32_t p_val){ +void StreamPeer::put_u32(uint32_t p_val) { if (big_endian) { - p_val=BSWAP32(p_val); + p_val = BSWAP32(p_val); } uint8_t buf[4]; - encode_uint32(p_val,buf); - put_data(buf,4); - + encode_uint32(p_val, buf); + put_data(buf, 4); } -void StreamPeer::put_32(int32_t p_val){ +void StreamPeer::put_32(int32_t p_val) { if (big_endian) { - p_val=BSWAP32(p_val); + p_val = BSWAP32(p_val); } uint8_t buf[4]; - encode_uint32(p_val,buf); - put_data(buf,4); - + encode_uint32(p_val, buf); + put_data(buf, 4); } -void StreamPeer::put_u64(uint64_t p_val){ +void StreamPeer::put_u64(uint64_t p_val) { if (big_endian) { - p_val=BSWAP64(p_val); + p_val = BSWAP64(p_val); } uint8_t buf[8]; - encode_uint64(p_val,buf); - put_data(buf,8); - + encode_uint64(p_val, buf); + put_data(buf, 8); } -void StreamPeer::put_64(int64_t p_val){ +void StreamPeer::put_64(int64_t p_val) { if (big_endian) { - p_val=BSWAP64(p_val); + p_val = BSWAP64(p_val); } uint8_t buf[8]; - encode_uint64(p_val,buf); - put_data(buf,8); - + encode_uint64(p_val, buf); + put_data(buf, 8); } -void StreamPeer::put_float(float p_val){ +void StreamPeer::put_float(float p_val) { uint8_t buf[4]; - encode_float(p_val,buf); + encode_float(p_val, buf); if (big_endian) { - uint32_t *p32=(uint32_t *)buf; - *p32=BSWAP32(*p32); + uint32_t *p32 = (uint32_t *)buf; + *p32 = BSWAP32(*p32); } - put_data(buf,4); - + put_data(buf, 4); } -void StreamPeer::put_double(double p_val){ +void StreamPeer::put_double(double p_val) { uint8_t buf[8]; - encode_double(p_val,buf); + encode_double(p_val, buf); if (big_endian) { - uint64_t *p64=(uint64_t *)buf; - *p64=BSWAP64(*p64); + uint64_t *p64 = (uint64_t *)buf; + *p64 = BSWAP64(*p64); } - put_data(buf,8); - + put_data(buf, 8); } -void StreamPeer::put_utf8_string(const String& p_string) { +void StreamPeer::put_utf8_string(const String &p_string) { - CharString cs=p_string.utf8(); + CharString cs = p_string.utf8(); put_u32(p_string.length()); - put_data((const uint8_t*)cs.get_data(),cs.length()); - + put_data((const uint8_t *)cs.get_data(), cs.length()); } -void StreamPeer::put_var(const Variant& p_variant){ +void StreamPeer::put_var(const Variant &p_variant) { - int len=0; + int len = 0; Vector<uint8_t> buf; - encode_variant(p_variant,NULL,len); + encode_variant(p_variant, NULL, len); buf.resize(len); put_32(len); - encode_variant(p_variant,buf.ptr(),len); - put_data(buf.ptr(),buf.size()); - - + encode_variant(p_variant, buf.ptr(), len); + put_data(buf.ptr(), buf.size()); } -uint8_t StreamPeer::get_u8(){ +uint8_t StreamPeer::get_u8() { uint8_t buf[1]; - get_data(buf,1); + get_data(buf, 1); return buf[0]; } -int8_t StreamPeer::get_8(){ +int8_t StreamPeer::get_8() { uint8_t buf[1]; - get_data(buf,1); + get_data(buf, 1); return buf[0]; - } -uint16_t StreamPeer::get_u16(){ +uint16_t StreamPeer::get_u16() { uint8_t buf[2]; - get_data(buf,2); + get_data(buf, 2); uint16_t r = decode_uint16(buf); if (big_endian) { - r=BSWAP16(r); + r = BSWAP16(r); } return r; - } -int16_t StreamPeer::get_16(){ +int16_t StreamPeer::get_16() { uint8_t buf[2]; - get_data(buf,2); + get_data(buf, 2); uint16_t r = decode_uint16(buf); if (big_endian) { - r=BSWAP16(r); + r = BSWAP16(r); } return r; - } -uint32_t StreamPeer::get_u32(){ +uint32_t StreamPeer::get_u32() { uint8_t buf[4]; - get_data(buf,4); + get_data(buf, 4); uint32_t r = decode_uint32(buf); if (big_endian) { - r=BSWAP32(r); + r = BSWAP32(r); } return r; - } -int32_t StreamPeer::get_32(){ +int32_t StreamPeer::get_32() { uint8_t buf[4]; - get_data(buf,4); + get_data(buf, 4); uint32_t r = decode_uint32(buf); if (big_endian) { - r=BSWAP32(r); + r = BSWAP32(r); } return r; - } -uint64_t StreamPeer::get_u64(){ +uint64_t StreamPeer::get_u64() { uint8_t buf[8]; - get_data(buf,8); + get_data(buf, 8); uint64_t r = decode_uint64(buf); if (big_endian) { - r=BSWAP64(r); + r = BSWAP64(r); } return r; - } -int64_t StreamPeer::get_64(){ +int64_t StreamPeer::get_64() { uint8_t buf[8]; - get_data(buf,8); + get_data(buf, 8); uint64_t r = decode_uint64(buf); if (big_endian) { - r=BSWAP64(r); + r = BSWAP64(r); } return r; - } -float StreamPeer::get_float(){ +float StreamPeer::get_float() { uint8_t buf[4]; - get_data(buf,4); + get_data(buf, 4); if (big_endian) { - uint32_t *p32=(uint32_t *)buf; - *p32=BSWAP32(*p32); + uint32_t *p32 = (uint32_t *)buf; + *p32 = BSWAP32(*p32); } return decode_float(buf); } -float StreamPeer::get_double(){ +float StreamPeer::get_double() { uint8_t buf[8]; - get_data(buf,8); + get_data(buf, 8); if (big_endian) { - uint64_t *p64=(uint64_t *)buf; - *p64=BSWAP64(*p64); + uint64_t *p64 = (uint64_t *)buf; + *p64 = BSWAP64(*p64); } return decode_double(buf); - } -String StreamPeer::get_string(int p_bytes){ +String StreamPeer::get_string(int p_bytes) { - ERR_FAIL_COND_V(p_bytes<0,String()); + ERR_FAIL_COND_V(p_bytes < 0, String()); Vector<char> buf; - Error err = buf.resize(p_bytes+1); - ERR_FAIL_COND_V(err!=OK,String()); - err = get_data((uint8_t*)&buf[0],p_bytes); - ERR_FAIL_COND_V(err!=OK,String()); - buf[p_bytes]=0; + Error err = buf.resize(p_bytes + 1); + ERR_FAIL_COND_V(err != OK, String()); + err = get_data((uint8_t *)&buf[0], p_bytes); + ERR_FAIL_COND_V(err != OK, String()); + buf[p_bytes] = 0; return buf.ptr(); - } -String StreamPeer::get_utf8_string(int p_bytes){ +String StreamPeer::get_utf8_string(int p_bytes) { - ERR_FAIL_COND_V(p_bytes<0,String()); + ERR_FAIL_COND_V(p_bytes < 0, String()); Vector<uint8_t> buf; Error err = buf.resize(p_bytes); - ERR_FAIL_COND_V(err!=OK,String()); - err = get_data(buf.ptr(),p_bytes); - ERR_FAIL_COND_V(err!=OK,String()); + ERR_FAIL_COND_V(err != OK, String()); + err = get_data(buf.ptr(), p_bytes); + ERR_FAIL_COND_V(err != OK, String()); String ret; - ret.parse_utf8((const char*)buf.ptr(),buf.size()); + ret.parse_utf8((const char *)buf.ptr(), buf.size()); return ret; - } -Variant StreamPeer::get_var(){ +Variant StreamPeer::get_var() { int len = get_32(); Vector<uint8_t> var; Error err = var.resize(len); - ERR_FAIL_COND_V(err!=OK,Variant()); - err = get_data(var.ptr(),len); - ERR_FAIL_COND_V(err!=OK,Variant()); + ERR_FAIL_COND_V(err != OK, Variant()); + err = get_data(var.ptr(), len); + ERR_FAIL_COND_V(err != OK, Variant()); Variant ret; - decode_variant(ret,var.ptr(),len); + decode_variant(ret, var.ptr(), len); return ret; } - void StreamPeer::_bind_methods() { - ClassDB::bind_method(D_METHOD("put_data","data"),&StreamPeer::_put_data); - ClassDB::bind_method(D_METHOD("put_partial_data","data"),&StreamPeer::_put_partial_data); - - ClassDB::bind_method(D_METHOD("get_data","bytes"),&StreamPeer::_get_data); - ClassDB::bind_method(D_METHOD("get_partial_data","bytes"),&StreamPeer::_get_partial_data); - - ClassDB::bind_method(D_METHOD("get_available_bytes"),&StreamPeer::get_available_bytes); - - ClassDB::bind_method(D_METHOD("set_big_endian","enable"),&StreamPeer::set_big_endian); - ClassDB::bind_method(D_METHOD("is_big_endian_enabled"),&StreamPeer::is_big_endian_enabled); - - ClassDB::bind_method(D_METHOD("put_8","val"),&StreamPeer::put_8); - ClassDB::bind_method(D_METHOD("put_u8","val"),&StreamPeer::put_u8); - ClassDB::bind_method(D_METHOD("put_16","val"),&StreamPeer::put_16); - ClassDB::bind_method(D_METHOD("put_u16","val"),&StreamPeer::put_u16); - ClassDB::bind_method(D_METHOD("put_32","val"),&StreamPeer::put_32); - ClassDB::bind_method(D_METHOD("put_u32","val"),&StreamPeer::put_u32); - ClassDB::bind_method(D_METHOD("put_64","val"),&StreamPeer::put_64); - ClassDB::bind_method(D_METHOD("put_u64","val"),&StreamPeer::put_u64); - ClassDB::bind_method(D_METHOD("put_float","val"),&StreamPeer::put_float); - ClassDB::bind_method(D_METHOD("put_double","val"),&StreamPeer::put_double); - ClassDB::bind_method(D_METHOD("put_utf8_string","val"),&StreamPeer::put_utf8_string); - ClassDB::bind_method(D_METHOD("put_var","val:Variant"),&StreamPeer::put_var); - - ClassDB::bind_method(D_METHOD("get_8"),&StreamPeer::get_8); - ClassDB::bind_method(D_METHOD("get_u8"),&StreamPeer::get_u8); - ClassDB::bind_method(D_METHOD("get_16"),&StreamPeer::get_16); - ClassDB::bind_method(D_METHOD("get_u16"),&StreamPeer::get_u16); - ClassDB::bind_method(D_METHOD("get_32"),&StreamPeer::get_32); - ClassDB::bind_method(D_METHOD("get_u32"),&StreamPeer::get_u32); - ClassDB::bind_method(D_METHOD("get_64"),&StreamPeer::get_64); - ClassDB::bind_method(D_METHOD("get_u64"),&StreamPeer::get_u64); - ClassDB::bind_method(D_METHOD("get_float"),&StreamPeer::get_float); - ClassDB::bind_method(D_METHOD("get_double"),&StreamPeer::get_double); - ClassDB::bind_method(D_METHOD("get_string","bytes"),&StreamPeer::get_string); - ClassDB::bind_method(D_METHOD("get_utf8_string","bytes"),&StreamPeer::get_utf8_string); - ClassDB::bind_method(D_METHOD("get_var:Variant"),&StreamPeer::get_var); + ClassDB::bind_method(D_METHOD("put_data", "data"), &StreamPeer::_put_data); + ClassDB::bind_method(D_METHOD("put_partial_data", "data"), &StreamPeer::_put_partial_data); + + ClassDB::bind_method(D_METHOD("get_data", "bytes"), &StreamPeer::_get_data); + ClassDB::bind_method(D_METHOD("get_partial_data", "bytes"), &StreamPeer::_get_partial_data); + + ClassDB::bind_method(D_METHOD("get_available_bytes"), &StreamPeer::get_available_bytes); + + ClassDB::bind_method(D_METHOD("set_big_endian", "enable"), &StreamPeer::set_big_endian); + ClassDB::bind_method(D_METHOD("is_big_endian_enabled"), &StreamPeer::is_big_endian_enabled); + + ClassDB::bind_method(D_METHOD("put_8", "val"), &StreamPeer::put_8); + ClassDB::bind_method(D_METHOD("put_u8", "val"), &StreamPeer::put_u8); + ClassDB::bind_method(D_METHOD("put_16", "val"), &StreamPeer::put_16); + ClassDB::bind_method(D_METHOD("put_u16", "val"), &StreamPeer::put_u16); + ClassDB::bind_method(D_METHOD("put_32", "val"), &StreamPeer::put_32); + ClassDB::bind_method(D_METHOD("put_u32", "val"), &StreamPeer::put_u32); + ClassDB::bind_method(D_METHOD("put_64", "val"), &StreamPeer::put_64); + ClassDB::bind_method(D_METHOD("put_u64", "val"), &StreamPeer::put_u64); + ClassDB::bind_method(D_METHOD("put_float", "val"), &StreamPeer::put_float); + ClassDB::bind_method(D_METHOD("put_double", "val"), &StreamPeer::put_double); + ClassDB::bind_method(D_METHOD("put_utf8_string", "val"), &StreamPeer::put_utf8_string); + ClassDB::bind_method(D_METHOD("put_var", "val:Variant"), &StreamPeer::put_var); + + ClassDB::bind_method(D_METHOD("get_8"), &StreamPeer::get_8); + ClassDB::bind_method(D_METHOD("get_u8"), &StreamPeer::get_u8); + ClassDB::bind_method(D_METHOD("get_16"), &StreamPeer::get_16); + ClassDB::bind_method(D_METHOD("get_u16"), &StreamPeer::get_u16); + ClassDB::bind_method(D_METHOD("get_32"), &StreamPeer::get_32); + ClassDB::bind_method(D_METHOD("get_u32"), &StreamPeer::get_u32); + ClassDB::bind_method(D_METHOD("get_64"), &StreamPeer::get_64); + ClassDB::bind_method(D_METHOD("get_u64"), &StreamPeer::get_u64); + ClassDB::bind_method(D_METHOD("get_float"), &StreamPeer::get_float); + ClassDB::bind_method(D_METHOD("get_double"), &StreamPeer::get_double); + ClassDB::bind_method(D_METHOD("get_string", "bytes"), &StreamPeer::get_string); + ClassDB::bind_method(D_METHOD("get_utf8_string", "bytes"), &StreamPeer::get_utf8_string); + ClassDB::bind_method(D_METHOD("get_var:Variant"), &StreamPeer::get_var); } //////////////////////////////// - void StreamPeerBuffer::_bind_methods() { - ClassDB::bind_method(D_METHOD("seek","pos"),&StreamPeerBuffer::seek); - ClassDB::bind_method(D_METHOD("get_size"),&StreamPeerBuffer::get_size); - ClassDB::bind_method(D_METHOD("get_pos"),&StreamPeerBuffer::get_pos); - ClassDB::bind_method(D_METHOD("resize","size"),&StreamPeerBuffer::resize); - ClassDB::bind_method(D_METHOD("set_data_array","data"),&StreamPeerBuffer::set_data_array); - ClassDB::bind_method(D_METHOD("get_data_array"),&StreamPeerBuffer::get_data_array); - ClassDB::bind_method(D_METHOD("clear"),&StreamPeerBuffer::clear); - ClassDB::bind_method(D_METHOD("duplicate:StreamPeerBuffer"),&StreamPeerBuffer::duplicate); - + ClassDB::bind_method(D_METHOD("seek", "pos"), &StreamPeerBuffer::seek); + ClassDB::bind_method(D_METHOD("get_size"), &StreamPeerBuffer::get_size); + ClassDB::bind_method(D_METHOD("get_pos"), &StreamPeerBuffer::get_pos); + ClassDB::bind_method(D_METHOD("resize", "size"), &StreamPeerBuffer::resize); + ClassDB::bind_method(D_METHOD("set_data_array", "data"), &StreamPeerBuffer::set_data_array); + ClassDB::bind_method(D_METHOD("get_data_array"), &StreamPeerBuffer::get_data_array); + ClassDB::bind_method(D_METHOD("clear"), &StreamPeerBuffer::clear); + ClassDB::bind_method(D_METHOD("duplicate:StreamPeerBuffer"), &StreamPeerBuffer::duplicate); } +Error StreamPeerBuffer::put_data(const uint8_t *p_data, int p_bytes) { -Error StreamPeerBuffer::put_data(const uint8_t* p_data,int p_bytes) { - - if (p_bytes<=0) + if (p_bytes <= 0) return OK; - if (pointer+p_bytes > data.size()) { - data.resize(pointer+p_bytes); - + if (pointer + p_bytes > data.size()) { + data.resize(pointer + p_bytes); } PoolVector<uint8_t>::Write w = data.write(); - copymem(&w[pointer],p_data,p_bytes); + copymem(&w[pointer], p_data, p_bytes); - pointer+=p_bytes; + pointer += p_bytes; return OK; } -Error StreamPeerBuffer::put_partial_data(const uint8_t* p_data,int p_bytes, int &r_sent){ +Error StreamPeerBuffer::put_partial_data(const uint8_t *p_data, int p_bytes, int &r_sent) { - r_sent=p_bytes; - return put_data(p_data,p_bytes); + r_sent = p_bytes; + return put_data(p_data, p_bytes); } -Error StreamPeerBuffer::get_data(uint8_t* p_buffer, int p_bytes){ +Error StreamPeerBuffer::get_data(uint8_t *p_buffer, int p_bytes) { int recv; - get_partial_data(p_buffer,p_bytes,recv); - if (recv!=p_bytes) + get_partial_data(p_buffer, p_bytes, recv); + if (recv != p_bytes) return ERR_INVALID_PARAMETER; return OK; - } -Error StreamPeerBuffer::get_partial_data(uint8_t* p_buffer, int p_bytes,int &r_received){ - +Error StreamPeerBuffer::get_partial_data(uint8_t *p_buffer, int p_bytes, int &r_received) { - if (pointer+p_bytes > data.size()) { - r_received=data.size()-pointer; - if (r_received<=0) { - r_received=0; + if (pointer + p_bytes > data.size()) { + r_received = data.size() - pointer; + if (r_received <= 0) { + r_received = 0; return OK; //you got 0 } } else { - r_received=p_bytes; + r_received = p_bytes; } PoolVector<uint8_t>::Read r = data.read(); - copymem(p_buffer,r.ptr(),r_received); - + copymem(p_buffer, r.ptr(), r_received); + // FIXME: return what? OK or ERR_* } int StreamPeerBuffer::get_available_bytes() const { - return data.size()-pointer; + return data.size() - pointer; } -void StreamPeerBuffer::seek(int p_pos){ +void StreamPeerBuffer::seek(int p_pos) { ERR_FAIL_COND(p_pos < 0); ERR_FAIL_COND(p_pos > data.size()); - pointer=p_pos; + pointer = p_pos; } -int StreamPeerBuffer::get_size() const{ +int StreamPeerBuffer::get_size() const { return data.size(); } @@ -517,40 +484,37 @@ int StreamPeerBuffer::get_pos() const { return pointer; } -void StreamPeerBuffer::resize(int p_size){ +void StreamPeerBuffer::resize(int p_size) { data.resize(p_size); } -void StreamPeerBuffer::set_data_array(const PoolVector<uint8_t> & p_data){ +void StreamPeerBuffer::set_data_array(const PoolVector<uint8_t> &p_data) { - data=p_data; - pointer=0; + data = p_data; + pointer = 0; } -PoolVector<uint8_t> StreamPeerBuffer::get_data_array() const{ +PoolVector<uint8_t> StreamPeerBuffer::get_data_array() const { return data; } - void StreamPeerBuffer::clear() { data.resize(0); - pointer=0; + pointer = 0; } - Ref<StreamPeerBuffer> StreamPeerBuffer::duplicate() const { Ref<StreamPeerBuffer> spb; spb.instance(); - spb->data=data; + spb->data = data; return spb; } - StreamPeerBuffer::StreamPeerBuffer() { - pointer=0; + pointer = 0; } diff --git a/core/io/stream_peer.h b/core/io/stream_peer.h index eb0f90ba50..7c20d10b10 100644 --- a/core/io/stream_peer.h +++ b/core/io/stream_peer.h @@ -32,14 +32,15 @@ #include "reference.h" class StreamPeer : public Reference { - GDCLASS( StreamPeer, Reference ); + GDCLASS(StreamPeer, Reference); OBJ_CATEGORY("Networking"); + protected: static void _bind_methods(); //bind helpers - Error _put_data(const PoolVector<uint8_t>& p_data); - Array _put_partial_data(const PoolVector<uint8_t>& p_data); + Error _put_data(const PoolVector<uint8_t> &p_data); + Array _put_partial_data(const PoolVector<uint8_t> &p_data); Array _get_data(int p_bytes); Array _get_partial_data(int p_bytes); @@ -47,14 +48,13 @@ protected: bool big_endian; public: + virtual Error put_data(const uint8_t *p_data, int p_bytes) = 0; ///< put a whole chunk of data, blocking until it sent + virtual Error put_partial_data(const uint8_t *p_data, int p_bytes, int &r_sent) = 0; ///< put as much data as possible, without blocking. - virtual Error put_data(const uint8_t* p_data,int p_bytes)=0; ///< put a whole chunk of data, blocking until it sent - virtual Error put_partial_data(const uint8_t* p_data,int p_bytes, int &r_sent)=0; ///< put as much data as possible, without blocking. - - virtual Error get_data(uint8_t* p_buffer, int p_bytes)=0; ///< read p_bytes of data, if p_bytes > available, it will block - virtual Error get_partial_data(uint8_t* p_buffer, int p_bytes,int &r_received)=0; ///< read as much data as p_bytes into buffer, if less was read, return in r_received + virtual Error get_data(uint8_t *p_buffer, int p_bytes) = 0; ///< read p_bytes of data, if p_bytes > available, it will block + virtual Error get_partial_data(uint8_t *p_buffer, int p_bytes, int &r_received) = 0; ///< read as much data as p_bytes into buffer, if less was read, return in r_received - virtual int get_available_bytes() const=0; + virtual int get_available_bytes() const = 0; void set_big_endian(bool p_enable); bool is_big_endian_enabled() const; @@ -69,8 +69,8 @@ public: void put_u64(uint64_t p_val); void put_float(float p_val); void put_double(double p_val); - void put_utf8_string(const String& p_string); - void put_var(const Variant& p_variant); + void put_utf8_string(const String &p_string); + void put_var(const Variant &p_variant); uint8_t get_u8(); int8_t get_8(); @@ -86,27 +86,25 @@ public: String get_utf8_string(int p_bytes); Variant get_var(); - - - StreamPeer() { big_endian=false; } + StreamPeer() { big_endian = false; } }; - class StreamPeerBuffer : public StreamPeer { - GDCLASS(StreamPeerBuffer,StreamPeer); + GDCLASS(StreamPeerBuffer, StreamPeer); PoolVector<uint8_t> data; int pointer; -protected: +protected: static void _bind_methods(); + public: - Error put_data(const uint8_t* p_data,int p_bytes); - Error put_partial_data(const uint8_t* p_data,int p_bytes, int &r_sent); + Error put_data(const uint8_t *p_data, int p_bytes); + Error put_partial_data(const uint8_t *p_data, int p_bytes, int &r_sent); - Error get_data(uint8_t* p_buffer, int p_bytes); - Error get_partial_data(uint8_t* p_buffer, int p_bytes,int &r_received); + Error get_data(uint8_t *p_buffer, int p_bytes); + Error get_partial_data(uint8_t *p_buffer, int p_bytes, int &r_received); virtual int get_available_bytes() const; @@ -115,8 +113,7 @@ public: int get_pos() const; void resize(int p_size); - - void set_data_array(const PoolVector<uint8_t> & p_data); + void set_data_array(const PoolVector<uint8_t> &p_data); PoolVector<uint8_t> get_data_array() const; void clear(); @@ -126,5 +123,4 @@ public: StreamPeerBuffer(); }; - #endif // STREAM_PEER_H diff --git a/core/io/stream_peer_ssl.cpp b/core/io/stream_peer_ssl.cpp index 5f7247bd7a..6db6eb30ed 100644 --- a/core/io/stream_peer_ssl.cpp +++ b/core/io/stream_peer_ssl.cpp @@ -28,24 +28,18 @@ /*************************************************************************/ #include "stream_peer_ssl.h" - -StreamPeerSSL* (*StreamPeerSSL::_create)()=NULL; - - - +StreamPeerSSL *(*StreamPeerSSL::_create)() = NULL; StreamPeerSSL *StreamPeerSSL::create() { return _create(); } +StreamPeerSSL::LoadCertsFromMemory StreamPeerSSL::load_certs_func = NULL; +bool StreamPeerSSL::available = false; +bool StreamPeerSSL::initialize_certs = true; - -StreamPeerSSL::LoadCertsFromMemory StreamPeerSSL::load_certs_func=NULL; -bool StreamPeerSSL::available=false; -bool StreamPeerSSL::initialize_certs=true; - -void StreamPeerSSL::load_certs_from_memory(const PoolByteArray& p_memory) { +void StreamPeerSSL::load_certs_from_memory(const PoolByteArray &p_memory) { if (load_certs_func) load_certs_func(p_memory); } @@ -56,18 +50,15 @@ bool StreamPeerSSL::is_available() { void StreamPeerSSL::_bind_methods() { - - ClassDB::bind_method(D_METHOD("accept_stream:Error","stream:StreamPeer"),&StreamPeerSSL::accept_stream); - ClassDB::bind_method(D_METHOD("connect_to_stream:Error","stream:StreamPeer","validate_certs","for_hostname"),&StreamPeerSSL::connect_to_stream,DEFVAL(false),DEFVAL(String())); - ClassDB::bind_method(D_METHOD("get_status"),&StreamPeerSSL::get_status); - ClassDB::bind_method(D_METHOD("disconnect_from_stream"),&StreamPeerSSL::disconnect_from_stream); - BIND_CONSTANT( STATUS_DISCONNECTED ); - BIND_CONSTANT( STATUS_CONNECTED ); - BIND_CONSTANT( STATUS_ERROR_NO_CERTIFICATE ); - BIND_CONSTANT( STATUS_ERROR_HOSTNAME_MISMATCH ); - + ClassDB::bind_method(D_METHOD("accept_stream:Error", "stream:StreamPeer"), &StreamPeerSSL::accept_stream); + ClassDB::bind_method(D_METHOD("connect_to_stream:Error", "stream:StreamPeer", "validate_certs", "for_hostname"), &StreamPeerSSL::connect_to_stream, DEFVAL(false), DEFVAL(String())); + ClassDB::bind_method(D_METHOD("get_status"), &StreamPeerSSL::get_status); + ClassDB::bind_method(D_METHOD("disconnect_from_stream"), &StreamPeerSSL::disconnect_from_stream); + BIND_CONSTANT(STATUS_DISCONNECTED); + BIND_CONSTANT(STATUS_CONNECTED); + BIND_CONSTANT(STATUS_ERROR_NO_CERTIFICATE); + BIND_CONSTANT(STATUS_ERROR_HOSTNAME_MISMATCH); } -StreamPeerSSL::StreamPeerSSL() -{ +StreamPeerSSL::StreamPeerSSL() { } diff --git a/core/io/stream_peer_ssl.h b/core/io/stream_peer_ssl.h index 9aafac874d..468cef66a2 100644 --- a/core/io/stream_peer_ssl.h +++ b/core/io/stream_peer_ssl.h @@ -32,24 +32,22 @@ #include "io/stream_peer.h" class StreamPeerSSL : public StreamPeer { - GDCLASS(StreamPeerSSL,StreamPeer); + GDCLASS(StreamPeerSSL, StreamPeer); + public: + typedef void (*LoadCertsFromMemory)(const PoolByteArray &p_certs); - typedef void (*LoadCertsFromMemory)(const PoolByteArray& p_certs); protected: - static StreamPeerSSL* (*_create)(); + static StreamPeerSSL *(*_create)(); static void _bind_methods(); static LoadCertsFromMemory load_certs_func; static bool available; - -friend class Main; + friend class Main; static bool initialize_certs; public: - - enum Status { STATUS_DISCONNECTED, STATUS_CONNECTED, @@ -57,20 +55,20 @@ public: STATUS_ERROR_HOSTNAME_MISMATCH }; - virtual Error accept_stream(Ref<StreamPeer> p_base)=0; - virtual Error connect_to_stream(Ref<StreamPeer> p_base,bool p_validate_certs=false,const String& p_for_hostname=String())=0; - virtual Status get_status() const=0; + virtual Error accept_stream(Ref<StreamPeer> p_base) = 0; + virtual Error connect_to_stream(Ref<StreamPeer> p_base, bool p_validate_certs = false, const String &p_for_hostname = String()) = 0; + virtual Status get_status() const = 0; - virtual void disconnect_from_stream()=0; + virtual void disconnect_from_stream() = 0; - static StreamPeerSSL* create(); + static StreamPeerSSL *create(); - static void load_certs_from_memory(const PoolByteArray& p_memory); + static void load_certs_from_memory(const PoolByteArray &p_memory); static bool is_available(); StreamPeerSSL(); }; -VARIANT_ENUM_CAST( StreamPeerSSL::Status ); +VARIANT_ENUM_CAST(StreamPeerSSL::Status); #endif // STREAM_PEER_SSL_H diff --git a/core/io/stream_peer_tcp.cpp b/core/io/stream_peer_tcp.cpp index cedc33079e..db5952e16f 100644 --- a/core/io/stream_peer_tcp.cpp +++ b/core/io/stream_peer_tcp.cpp @@ -28,37 +28,36 @@ /*************************************************************************/ #include "stream_peer_tcp.h" -StreamPeerTCP* (*StreamPeerTCP::_create)()=NULL; +StreamPeerTCP *(*StreamPeerTCP::_create)() = NULL; -Error StreamPeerTCP::_connect(const String& p_address,int p_port) { +Error StreamPeerTCP::_connect(const String &p_address, int p_port) { IP_Address ip; if (p_address.is_valid_ip_address()) { - ip=p_address; + ip = p_address; } else { - ip=IP::get_singleton()->resolve_hostname(p_address); + ip = IP::get_singleton()->resolve_hostname(p_address); if (!ip.is_valid()) return ERR_CANT_RESOLVE; } - connect_to_host(ip,p_port); + connect_to_host(ip, p_port); return OK; } void StreamPeerTCP::_bind_methods() { - ClassDB::bind_method(D_METHOD("connect_to_host","host","port"),&StreamPeerTCP::_connect); - ClassDB::bind_method(D_METHOD("is_connected_to_host"),&StreamPeerTCP::is_connected_to_host); - ClassDB::bind_method(D_METHOD("get_status"),&StreamPeerTCP::get_status); - ClassDB::bind_method(D_METHOD("get_connected_host"),&StreamPeerTCP::get_connected_host); - ClassDB::bind_method(D_METHOD("get_connected_port"),&StreamPeerTCP::get_connected_port); - ClassDB::bind_method(D_METHOD("disconnect_from_host"),&StreamPeerTCP::disconnect_from_host); - - BIND_CONSTANT( STATUS_NONE ); - BIND_CONSTANT( STATUS_CONNECTING ); - BIND_CONSTANT( STATUS_CONNECTED ); - BIND_CONSTANT( STATUS_ERROR ); - + ClassDB::bind_method(D_METHOD("connect_to_host", "host", "port"), &StreamPeerTCP::_connect); + ClassDB::bind_method(D_METHOD("is_connected_to_host"), &StreamPeerTCP::is_connected_to_host); + ClassDB::bind_method(D_METHOD("get_status"), &StreamPeerTCP::get_status); + ClassDB::bind_method(D_METHOD("get_connected_host"), &StreamPeerTCP::get_connected_host); + ClassDB::bind_method(D_METHOD("get_connected_port"), &StreamPeerTCP::get_connected_port); + ClassDB::bind_method(D_METHOD("disconnect_from_host"), &StreamPeerTCP::disconnect_from_host); + + BIND_CONSTANT(STATUS_NONE); + BIND_CONSTANT(STATUS_CONNECTING); + BIND_CONSTANT(STATUS_CONNECTED); + BIND_CONSTANT(STATUS_ERROR); } Ref<StreamPeerTCP> StreamPeerTCP::create_ref() { @@ -68,7 +67,7 @@ Ref<StreamPeerTCP> StreamPeerTCP::create_ref() { return Ref<StreamPeerTCP>(_create()); } -StreamPeerTCP* StreamPeerTCP::create() { +StreamPeerTCP *StreamPeerTCP::create() { if (!_create) return NULL; @@ -76,10 +75,8 @@ StreamPeerTCP* StreamPeerTCP::create() { } StreamPeerTCP::StreamPeerTCP() { - } -StreamPeerTCP::~StreamPeerTCP() { +StreamPeerTCP::~StreamPeerTCP(){ }; - diff --git a/core/io/stream_peer_tcp.h b/core/io/stream_peer_tcp.h index 4401378743..1733619a1c 100644 --- a/core/io/stream_peer_tcp.h +++ b/core/io/stream_peer_tcp.h @@ -31,16 +31,15 @@ #include "stream_peer.h" -#include "ip_address.h" #include "io/ip.h" +#include "ip_address.h" class StreamPeerTCP : public StreamPeer { - GDCLASS( StreamPeerTCP, StreamPeer ); + GDCLASS(StreamPeerTCP, StreamPeer); OBJ_CATEGORY("Networking"); public: - enum Status { STATUS_NONE, @@ -50,31 +49,29 @@ public: }; protected: - - virtual Error _connect(const String& p_address, int p_port); - static StreamPeerTCP* (*_create)(); + virtual Error _connect(const String &p_address, int p_port); + static StreamPeerTCP *(*_create)(); static void _bind_methods(); public: - - virtual Error connect_to_host(const IP_Address& p_host, uint16_t p_port)=0; + virtual Error connect_to_host(const IP_Address &p_host, uint16_t p_port) = 0; //read/write from streampeer - virtual bool is_connected_to_host() const=0; - virtual Status get_status() const=0; - virtual void disconnect_from_host()=0; - virtual IP_Address get_connected_host() const=0; - virtual uint16_t get_connected_port() const=0; - virtual void set_nodelay(bool p_enabled)=0; + virtual bool is_connected_to_host() const = 0; + virtual Status get_status() const = 0; + virtual void disconnect_from_host() = 0; + virtual IP_Address get_connected_host() const = 0; + virtual uint16_t get_connected_port() const = 0; + virtual void set_nodelay(bool p_enabled) = 0; static Ref<StreamPeerTCP> create_ref(); - static StreamPeerTCP* create(); + static StreamPeerTCP *create(); StreamPeerTCP(); ~StreamPeerTCP(); }; -VARIANT_ENUM_CAST( StreamPeerTCP::Status ); +VARIANT_ENUM_CAST(StreamPeerTCP::Status); #endif diff --git a/core/io/tcp_server.cpp b/core/io/tcp_server.cpp index 5127bd6e3b..f602b569ad 100644 --- a/core/io/tcp_server.cpp +++ b/core/io/tcp_server.cpp @@ -28,7 +28,7 @@ /*************************************************************************/ #include "tcp_server.h" -TCP_Server* (*TCP_Server::_create)()=NULL; +TCP_Server *(*TCP_Server::_create)() = NULL; Ref<TCP_Server> TCP_Server::create_ref() { @@ -37,7 +37,7 @@ Ref<TCP_Server> TCP_Server::create_ref() { return Ref<TCP_Server>(_create()); } -TCP_Server* TCP_Server::create() { +TCP_Server *TCP_Server::create() { if (!_create) return NULL; @@ -46,15 +46,11 @@ TCP_Server* TCP_Server::create() { void TCP_Server::_bind_methods() { - ClassDB::bind_method(D_METHOD("listen","port","bind_address"),&TCP_Server::listen,DEFVAL("*")); - ClassDB::bind_method(D_METHOD("is_connection_available"),&TCP_Server::is_connection_available); - ClassDB::bind_method(D_METHOD("take_connection"),&TCP_Server::take_connection); - ClassDB::bind_method(D_METHOD("stop"),&TCP_Server::stop); - + ClassDB::bind_method(D_METHOD("listen", "port", "bind_address"), &TCP_Server::listen, DEFVAL("*")); + ClassDB::bind_method(D_METHOD("is_connection_available"), &TCP_Server::is_connection_available); + ClassDB::bind_method(D_METHOD("take_connection"), &TCP_Server::take_connection); + ClassDB::bind_method(D_METHOD("stop"), &TCP_Server::stop); } - -TCP_Server::TCP_Server() -{ - +TCP_Server::TCP_Server() { } diff --git a/core/io/tcp_server.h b/core/io/tcp_server.h index 3cbd8c58cf..736aa16f99 100644 --- a/core/io/tcp_server.h +++ b/core/io/tcp_server.h @@ -29,29 +29,29 @@ #ifndef TCP_SERVER_H #define TCP_SERVER_H -#include "io/stream_peer.h" #include "io/ip.h" +#include "io/stream_peer.h" #include "stream_peer_tcp.h" class TCP_Server : public Reference { - GDCLASS( TCP_Server, Reference ); -protected: + GDCLASS(TCP_Server, Reference); - static TCP_Server* (*_create)(); +protected: + static TCP_Server *(*_create)(); //bind helper static void _bind_methods(); -public: - virtual Error listen(uint16_t p_port, const IP_Address p_bind_address=IP_Address("*"))=0; - virtual bool is_connection_available() const=0; - virtual Ref<StreamPeerTCP> take_connection()=0; +public: + virtual Error listen(uint16_t p_port, const IP_Address p_bind_address = IP_Address("*")) = 0; + virtual bool is_connection_available() const = 0; + virtual Ref<StreamPeerTCP> take_connection() = 0; - virtual void stop()=0; //stop listening + virtual void stop() = 0; //stop listening static Ref<TCP_Server> create_ref(); - static TCP_Server* create(); + static TCP_Server *create(); TCP_Server(); }; diff --git a/core/io/translation_loader_po.cpp b/core/io/translation_loader_po.cpp index bee38e037f..4da661e675 100644 --- a/core/io/translation_loader_po.cpp +++ b/core/io/translation_loader_po.cpp @@ -30,7 +30,6 @@ #include "os/file_access.h" #include "translation.h" - RES TranslationLoaderPO::load_translation(FileAccess *f, Error *r_error, const String &p_path) { enum Status { @@ -40,175 +39,169 @@ RES TranslationLoaderPO::load_translation(FileAccess *f, Error *r_error, const S STATUS_READING_STRING, }; - Status status=STATUS_NONE; + Status status = STATUS_NONE; String msg_id; String msg_str; String config; if (r_error) - *r_error=ERR_FILE_CORRUPT; + *r_error = ERR_FILE_CORRUPT; - Ref<Translation> translation = Ref<Translation>( memnew( Translation )); + Ref<Translation> translation = Ref<Translation>(memnew(Translation)); int line = 1; - while(true) { + while (true) { String l = f->get_line(); if (f->eof_reached()) { - if ( status == STATUS_READING_STRING) { + if (status == STATUS_READING_STRING) { - if (msg_id!="") - translation->add_message(msg_id,msg_str); - else if (config=="") - config=msg_str; + if (msg_id != "") + translation->add_message(msg_id, msg_str); + else if (config == "") + config = msg_str; break; - } else if ( status==STATUS_NONE) + } else if (status == STATUS_NONE) break; memdelete(f); - ERR_EXPLAIN(p_path+":"+itos(line)+" Unexpected EOF while reading 'msgid' at file: "); + ERR_EXPLAIN(p_path + ":" + itos(line) + " Unexpected EOF while reading 'msgid' at file: "); ERR_FAIL_V(RES()); } - l=l.strip_edges(); + l = l.strip_edges(); if (l.begins_with("msgid")) { - if (status==STATUS_READING_ID) { + if (status == STATUS_READING_ID) { memdelete(f); - ERR_EXPLAIN(p_path+":"+itos(line)+" Unexpected 'msgid', was expecting 'msgstr' while parsing: "); + ERR_EXPLAIN(p_path + ":" + itos(line) + " Unexpected 'msgid', was expecting 'msgstr' while parsing: "); ERR_FAIL_V(RES()); } - if (msg_id!="") - translation->add_message(msg_id,msg_str); - else if (config=="") - config=msg_str; + if (msg_id != "") + translation->add_message(msg_id, msg_str); + else if (config == "") + config = msg_str; - l=l.substr(5,l.length()).strip_edges(); - status=STATUS_READING_ID; - msg_id=""; - msg_str=""; + l = l.substr(5, l.length()).strip_edges(); + status = STATUS_READING_ID; + msg_id = ""; + msg_str = ""; } if (l.begins_with("msgstr")) { - if (status!=STATUS_READING_ID) { + if (status != STATUS_READING_ID) { memdelete(f); - ERR_EXPLAIN(p_path+":"+itos(line)+" Unexpected 'msgstr', was expecting 'msgid' while parsing: "); + ERR_EXPLAIN(p_path + ":" + itos(line) + " Unexpected 'msgstr', was expecting 'msgid' while parsing: "); ERR_FAIL_V(RES()); } - l=l.substr(6,l.length()).strip_edges(); - status=STATUS_READING_STRING; + l = l.substr(6, l.length()).strip_edges(); + status = STATUS_READING_STRING; } - if (l=="" || l.begins_with("#")) { + if (l == "" || l.begins_with("#")) { line++; continue; //nothing to read or comment } - if (!l.begins_with("\"") || status==STATUS_NONE) { + if (!l.begins_with("\"") || status == STATUS_NONE) { //not a string? failure! - ERR_EXPLAIN(p_path+":"+itos(line)+" Invalid line '"+l+"' while parsing: "); + ERR_EXPLAIN(p_path + ":" + itos(line) + " Invalid line '" + l + "' while parsing: "); ERR_FAIL_V(RES()); - } - l=l.substr(1,l.length()); + l = l.substr(1, l.length()); //find final quote - int end_pos=-1; - for(int i=0;i<l.length();i++) { + int end_pos = -1; + for (int i = 0; i < l.length(); i++) { - if (l[i]=='"' && (i==0 || l[i-1]!='\\')) { - end_pos=i; + if (l[i] == '"' && (i == 0 || l[i - 1] != '\\')) { + end_pos = i; break; } } - if (end_pos==-1) { - ERR_EXPLAIN(p_path+":"+itos(line)+" Expected '\"' at end of message while parsing file: "); + if (end_pos == -1) { + ERR_EXPLAIN(p_path + ":" + itos(line) + " Expected '\"' at end of message while parsing file: "); ERR_FAIL_V(RES()); } - l=l.substr(0,end_pos); - l=l.c_unescape(); - + l = l.substr(0, end_pos); + l = l.c_unescape(); - if (status==STATUS_READING_ID) - msg_id+=l; + if (status == STATUS_READING_ID) + msg_id += l; else - msg_str+=l; + msg_str += l; line++; } - f->close(); memdelete(f); - if (config=="") { - ERR_EXPLAIN("No config found in file: "+p_path); + if (config == "") { + ERR_EXPLAIN("No config found in file: " + p_path); ERR_FAIL_V(RES()); } Vector<String> configs = config.split("\n"); - for(int i=0;i<configs.size();i++) { + for (int i = 0; i < configs.size(); i++) { String c = configs[i].strip_edges(); int p = c.find(":"); - if (p==-1) + if (p == -1) continue; - String prop = c.substr(0,p).strip_edges(); - String value = c.substr(p+1,c.length()).strip_edges(); + String prop = c.substr(0, p).strip_edges(); + String value = c.substr(p + 1, c.length()).strip_edges(); - if (prop=="X-Language") { + if (prop == "X-Language") { translation->set_locale(value); } } if (r_error) - *r_error=OK; + *r_error = OK; return translation; } -RES TranslationLoaderPO::load(const String &p_path, const String& p_original_path, Error *r_error) { +RES TranslationLoaderPO::load(const String &p_path, const String &p_original_path, Error *r_error) { if (r_error) - *r_error=ERR_CANT_OPEN; - - FileAccess *f=FileAccess::open(p_path,FileAccess::READ); - ERR_FAIL_COND_V(!f,RES()); - + *r_error = ERR_CANT_OPEN; - return load_translation(f,r_error); + FileAccess *f = FileAccess::open(p_path, FileAccess::READ); + ERR_FAIL_COND_V(!f, RES()); + return load_translation(f, r_error); } -void TranslationLoaderPO::get_recognized_extensions(List<String> *p_extensions) const{ +void TranslationLoaderPO::get_recognized_extensions(List<String> *p_extensions) const { p_extensions->push_back("po"); //p_extensions->push_back("mo"); //mo in the future... } -bool TranslationLoaderPO::handles_type(const String& p_type) const{ +bool TranslationLoaderPO::handles_type(const String &p_type) const { - return (p_type=="Translation"); + return (p_type == "Translation"); } String TranslationLoaderPO::get_resource_type(const String &p_path) const { - if (p_path.get_extension().to_lower()=="po") + if (p_path.get_extension().to_lower() == "po") return "Translation"; return ""; } -TranslationLoaderPO::TranslationLoaderPO() -{ +TranslationLoaderPO::TranslationLoaderPO() { } diff --git a/core/io/translation_loader_po.h b/core/io/translation_loader_po.h index 127c8dafab..fe0440cb2a 100644 --- a/core/io/translation_loader_po.h +++ b/core/io/translation_loader_po.h @@ -30,18 +30,16 @@ #define TRANSLATION_LOADER_PO_H #include "io/resource_loader.h" -#include "translation.h" #include "os/file_access.h" +#include "translation.h" class TranslationLoaderPO : public ResourceFormatLoader { public: - - static RES load_translation(FileAccess *f, Error *r_error,const String& p_path=String()); - virtual RES load(const String &p_path,const String& p_original_path="",Error *r_error=NULL); + static RES load_translation(FileAccess *f, Error *r_error, const String &p_path = String()); + virtual RES load(const String &p_path, const String &p_original_path = "", Error *r_error = NULL); virtual void get_recognized_extensions(List<String> *p_extensions) const; - virtual bool handles_type(const String& p_type) const; + virtual bool handles_type(const String &p_type) const; virtual String get_resource_type(const String &p_path) const; - TranslationLoaderPO(); }; diff --git a/core/io/xml_parser.cpp b/core/io/xml_parser.cpp index 1a4ff1a8d4..e3b669409a 100644 --- a/core/io/xml_parser.cpp +++ b/core/io/xml_parser.cpp @@ -32,19 +32,18 @@ VARIANT_ENUM_CAST(XMLParser::NodeType); -static bool _equalsn(const CharType* str1, const CharType* str2, int len) { +static bool _equalsn(const CharType *str1, const CharType *str2, int len) { int i; - for(i=0; i < len && str1[i] && str2[i] ; ++i) - if (str1[i] != str2[i]) - return false; + for (i = 0; i < len && str1[i] && str2[i]; ++i) + if (str1[i] != str2[i]) + return false; // if one (or both) of the strings was smaller then they // are only equal if they have the same lenght return (i == len) || (str1[i] == 0 && str2[i] == 0); } - -String XMLParser::_replace_special_characters(const String& origstr) { +String XMLParser::_replace_special_characters(const String &origstr) { int pos = origstr.find("&"); int oldPos = 0; @@ -54,30 +53,25 @@ String XMLParser::_replace_special_characters(const String& origstr) { String newstr; - while(pos != -1 && pos < origstr.length()-2) { + while (pos != -1 && pos < origstr.length() - 2) { // check if it is one of the special characters int specialChar = -1; - for (int i=0; i<(int)special_characters.size(); ++i) - { - const CharType* p = &origstr[pos]+1; + for (int i = 0; i < (int)special_characters.size(); ++i) { + const CharType *p = &origstr[pos] + 1; - if (_equalsn(&special_characters[i][1], p, special_characters[i].length()-1)) - { + if (_equalsn(&special_characters[i][1], p, special_characters[i].length() - 1)) { specialChar = i; break; } } - if (specialChar != -1) - { - newstr+=(origstr.substr(oldPos, pos - oldPos)); - newstr+=(special_characters[specialChar][0]); + if (specialChar != -1) { + newstr += (origstr.substr(oldPos, pos - oldPos)); + newstr += (special_characters[specialChar][0]); pos += special_characters[specialChar].length(); - } - else - { - newstr+=(origstr.substr(oldPos, pos - oldPos + 1)); + } else { + newstr += (origstr.substr(oldPos, pos - oldPos + 1)); pos += 1; } @@ -86,27 +80,23 @@ String XMLParser::_replace_special_characters(const String& origstr) { pos = origstr.find("&", pos); } - if (oldPos < origstr.length()-1) - newstr+=(origstr.substr(oldPos, origstr.length()-oldPos)); + if (oldPos < origstr.length() - 1) + newstr += (origstr.substr(oldPos, origstr.length() - oldPos)); return newstr; } - -static inline bool _is_white_space(char c) -{ - return (c==' ' || c=='\t' || c=='\n' || c=='\r'); +static inline bool _is_white_space(char c) { + return (c == ' ' || c == '\t' || c == '\n' || c == '\r'); } - //! sets the state that text was found. Returns true if set should be set -bool XMLParser::_set_text(char* start, char* end) { +bool XMLParser::_set_text(char *start, char *end) { // check if text is more than 2 characters, and if not, check if there is // only white space, so that this text won't be reported - if (end - start < 3) - { - char* p = start; - for(; p != end; ++p) + if (end - start < 3) { + char *p = start; + for (; p != end; ++p) if (!_is_white_space(*p)) break; @@ -130,14 +120,14 @@ void XMLParser::_parse_closing_xml_element() { attributes.clear(); ++P; - const char* pBeginClose = P; + const char *pBeginClose = P; - while(*P != '>') + while (*P != '>') ++P; node_name = String::utf8(pBeginClose, (int)(P - pBeginClose)); #ifdef DEBUG_XML - print_line("XML CLOSE: "+node_name); + print_line("XML CLOSE: " + node_name); #endif ++P; } @@ -145,25 +135,24 @@ void XMLParser::_parse_closing_xml_element() { void XMLParser::_ignore_definition() { node_type = NODE_UNKNOWN; - char *F=P; + char *F = P; // move until end marked with '>' reached - while(*P != '>') + while (*P != '>') ++P; - node_name.parse_utf8(F,P-F); + node_name.parse_utf8(F, P - F); ++P; } bool XMLParser::_parse_cdata() { - if (*(P+1) != '[') + if (*(P + 1) != '[') return false; node_type = NODE_CDATA; // skip '<![CDATA[' - int count=0; - while( *P && count<8 ) - { + int count = 0; + while (*P && count < 8) { ++P; ++count; } @@ -175,23 +164,22 @@ bool XMLParser::_parse_cdata() { char *cDataEnd = 0; // find end of CDATA - while(*P && !cDataEnd) { + while (*P && !cDataEnd) { if (*P == '>' && - (*(P-1) == ']') && - (*(P-2) == ']')) - { + (*(P - 1) == ']') && + (*(P - 2) == ']')) { cDataEnd = P - 2; } ++P; } - if ( cDataEnd ) + if (cDataEnd) node_name = String::utf8(cDataBegin, (int)(cDataEnd - cDataBegin)); else node_name = ""; #ifdef DEBUG_XML - print_line("XML CDATA: "+node_name); + print_line("XML CDATA: " + node_name); #endif return true; @@ -207,24 +195,21 @@ void XMLParser::_parse_comment() { int count = 1; // move until end of comment reached - while(count) - { + while (count) { if (*P == '>') --count; - else - if (*P == '<') + else if (*P == '<') ++count; ++P; } P -= 3; - node_name = String::utf8(pCommentBegin+2, (int)(P - pCommentBegin-2)); + node_name = String::utf8(pCommentBegin + 2, (int)(P - pCommentBegin - 2)); P += 3; #ifdef DEBUG_XML - print_line("XML COMMENT: "+node_name); + print_line("XML COMMENT: " + node_name); #endif - } void XMLParser::_parse_opening_xml_element() { @@ -234,37 +219,34 @@ void XMLParser::_parse_opening_xml_element() { attributes.clear(); // find name - const char* startName = P; + const char *startName = P; // find end of element - while(*P != '>' && !_is_white_space(*P)) + while (*P != '>' && !_is_white_space(*P)) ++P; - const char* endName = P; + const char *endName = P; // find attributes - while(*P != '>') - { + while (*P != '>') { if (_is_white_space(*P)) ++P; - else - { - if (*P != '/') - { + else { + if (*P != '/') { // we've got an attribute // read the attribute names - const char* attributeNameBegin = P; + const char *attributeNameBegin = P; - while(!_is_white_space(*P) && *P != '=') + while (!_is_white_space(*P) && *P != '=') ++P; - const char* attributeNameEnd = P; + const char *attributeNameEnd = P; ++P; // read the attribute value // check for quotes and single quotes, thx to murphy - while( (*P != '\"') && (*P != '\'') && *P) + while ((*P != '\"') && (*P != '\'') && *P) ++P; if (!*P) // malformatted xml file @@ -273,29 +255,27 @@ void XMLParser::_parse_opening_xml_element() { const char attributeQuoteChar = *P; ++P; - const char* attributeValueBegin = P; + const char *attributeValueBegin = P; - while(*P != attributeQuoteChar && *P) + while (*P != attributeQuoteChar && *P) ++P; if (!*P) // malformatted xml file return; - const char* attributeValueEnd = P; + const char *attributeValueEnd = P; ++P; Attribute attr; attr.name = String::utf8(attributeNameBegin, - (int)(attributeNameEnd - attributeNameBegin)); + (int)(attributeNameEnd - attributeNameBegin)); - String s =String::utf8(attributeValueBegin, - (int)(attributeValueEnd - attributeValueBegin)); + String s = String::utf8(attributeValueBegin, + (int)(attributeValueEnd - attributeValueBegin)); attr.value = _replace_special_characters(s); attributes.push_back(attr); - } - else - { + } else { // tag is closed directly ++P; node_empty = true; @@ -305,8 +285,7 @@ void XMLParser::_parse_opening_xml_element() { } // check if this tag is closing directly - if (endName > startName && *(endName-1) == '/') - { + if (endName > startName && *(endName - 1) == '/') { // directly closing tag node_empty = true; endName--; @@ -314,27 +293,25 @@ void XMLParser::_parse_opening_xml_element() { node_name = String::utf8(startName, (int)(endName - startName)); #ifdef DEBUG_XML - print_line("XML OPEN: "+node_name); + print_line("XML OPEN: " + node_name); #endif ++P; } - void XMLParser::_parse_current_node() { - char* start = P; + char *start = P; node_offset = P - data; // more forward until '<' found - while(*P != '<' && *P) + while (*P != '<' && *P) ++P; if (!*P) return; - if (P - start > 0) - { + if (P - start > 0) { // we found some text, store it if (_set_text(start, P)) return; @@ -343,25 +320,23 @@ void XMLParser::_parse_current_node() { ++P; // based on current token, parse and report next element - switch(*P) - { - case '/': - _parse_closing_xml_element(); - break; - case '?': - _ignore_definition(); - break; - case '!': - if (!_parse_cdata()) - _parse_comment(); - break; - default: - _parse_opening_xml_element(); - break; + switch (*P) { + case '/': + _parse_closing_xml_element(); + break; + case '?': + _ignore_definition(); + break; + case '!': + if (!_parse_cdata()) + _parse_comment(); + break; + default: + _parse_opening_xml_element(); + break; } } - uint64_t XMLParser::get_node_offset() const { return node_offset; @@ -379,41 +354,37 @@ Error XMLParser::seek(uint64_t p_pos) { void XMLParser::_bind_methods() { - ClassDB::bind_method(D_METHOD("read"),&XMLParser::read); - ClassDB::bind_method(D_METHOD("get_node_type"),&XMLParser::get_node_type); - ClassDB::bind_method(D_METHOD("get_node_name"),&XMLParser::get_node_name); - ClassDB::bind_method(D_METHOD("get_node_data"),&XMLParser::get_node_data); - ClassDB::bind_method(D_METHOD("get_node_offset"),&XMLParser::get_node_offset); - ClassDB::bind_method(D_METHOD("get_attribute_count"),&XMLParser::get_attribute_count); - ClassDB::bind_method(D_METHOD("get_attribute_name","idx"),&XMLParser::get_attribute_name); - ClassDB::bind_method(D_METHOD("get_attribute_value","idx"),(String (XMLParser::*)(int) const) &XMLParser::get_attribute_value); - ClassDB::bind_method(D_METHOD("has_attribute","name"),&XMLParser::has_attribute); - ClassDB::bind_method(D_METHOD("get_named_attribute_value","name"), (String (XMLParser::*)(const String&) const) &XMLParser::get_attribute_value); - ClassDB::bind_method(D_METHOD("get_named_attribute_value_safe","name"), &XMLParser::get_attribute_value_safe); - ClassDB::bind_method(D_METHOD("is_empty"),&XMLParser::is_empty); - ClassDB::bind_method(D_METHOD("get_current_line"),&XMLParser::get_current_line); - ClassDB::bind_method(D_METHOD("skip_section"),&XMLParser::skip_section); - ClassDB::bind_method(D_METHOD("seek","pos"),&XMLParser::seek); - ClassDB::bind_method(D_METHOD("open","file"),&XMLParser::open); - ClassDB::bind_method(D_METHOD("open_buffer","buffer"),&XMLParser::open_buffer); - - BIND_CONSTANT( NODE_NONE ); - BIND_CONSTANT( NODE_ELEMENT ); - BIND_CONSTANT( NODE_ELEMENT_END ); - BIND_CONSTANT( NODE_TEXT ); - BIND_CONSTANT( NODE_COMMENT ); - BIND_CONSTANT( NODE_CDATA ); - BIND_CONSTANT( NODE_UNKNOWN ); - + ClassDB::bind_method(D_METHOD("read"), &XMLParser::read); + ClassDB::bind_method(D_METHOD("get_node_type"), &XMLParser::get_node_type); + ClassDB::bind_method(D_METHOD("get_node_name"), &XMLParser::get_node_name); + ClassDB::bind_method(D_METHOD("get_node_data"), &XMLParser::get_node_data); + ClassDB::bind_method(D_METHOD("get_node_offset"), &XMLParser::get_node_offset); + ClassDB::bind_method(D_METHOD("get_attribute_count"), &XMLParser::get_attribute_count); + ClassDB::bind_method(D_METHOD("get_attribute_name", "idx"), &XMLParser::get_attribute_name); + ClassDB::bind_method(D_METHOD("get_attribute_value", "idx"), (String(XMLParser::*)(int) const) & XMLParser::get_attribute_value); + ClassDB::bind_method(D_METHOD("has_attribute", "name"), &XMLParser::has_attribute); + ClassDB::bind_method(D_METHOD("get_named_attribute_value", "name"), (String(XMLParser::*)(const String &) const) & XMLParser::get_attribute_value); + ClassDB::bind_method(D_METHOD("get_named_attribute_value_safe", "name"), &XMLParser::get_attribute_value_safe); + ClassDB::bind_method(D_METHOD("is_empty"), &XMLParser::is_empty); + ClassDB::bind_method(D_METHOD("get_current_line"), &XMLParser::get_current_line); + ClassDB::bind_method(D_METHOD("skip_section"), &XMLParser::skip_section); + ClassDB::bind_method(D_METHOD("seek", "pos"), &XMLParser::seek); + ClassDB::bind_method(D_METHOD("open", "file"), &XMLParser::open); + ClassDB::bind_method(D_METHOD("open_buffer", "buffer"), &XMLParser::open_buffer); + + BIND_CONSTANT(NODE_NONE); + BIND_CONSTANT(NODE_ELEMENT); + BIND_CONSTANT(NODE_ELEMENT_END); + BIND_CONSTANT(NODE_TEXT); + BIND_CONSTANT(NODE_COMMENT); + BIND_CONSTANT(NODE_CDATA); + BIND_CONSTANT(NODE_UNKNOWN); }; - - Error XMLParser::read() { // if not end reached, parse the node - if (P && (P - data) < length - 1 && *P != 0) - { + if (P && (P - data) < length - 1 && *P != 0) { _parse_current_node(); return OK; } @@ -427,12 +398,12 @@ XMLParser::NodeType XMLParser::get_node_type() { } String XMLParser::get_node_data() const { - ERR_FAIL_COND_V( node_type != NODE_TEXT, ""); + ERR_FAIL_COND_V(node_type != NODE_TEXT, ""); return node_name; } String XMLParser::get_node_name() const { - ERR_FAIL_COND_V( node_type == NODE_TEXT, ""); + ERR_FAIL_COND_V(node_type == NODE_TEXT, ""); return node_name; } int XMLParser::get_attribute_count() const { @@ -441,95 +412,91 @@ int XMLParser::get_attribute_count() const { } String XMLParser::get_attribute_name(int p_idx) const { - ERR_FAIL_INDEX_V(p_idx,attributes.size(),""); + ERR_FAIL_INDEX_V(p_idx, attributes.size(), ""); return attributes[p_idx].name; } String XMLParser::get_attribute_value(int p_idx) const { - ERR_FAIL_INDEX_V(p_idx,attributes.size(),""); + ERR_FAIL_INDEX_V(p_idx, attributes.size(), ""); return attributes[p_idx].value; } -bool XMLParser::has_attribute(const String& p_name) const { +bool XMLParser::has_attribute(const String &p_name) const { - for(int i=0;i<attributes.size();i++) { - if (attributes[i].name==p_name) + for (int i = 0; i < attributes.size(); i++) { + if (attributes[i].name == p_name) return true; } return false; } -String XMLParser::get_attribute_value(const String& p_name) const { +String XMLParser::get_attribute_value(const String &p_name) const { - int idx=-1; - for(int i=0;i<attributes.size();i++) { - if (attributes[i].name==p_name) { - idx=i; + int idx = -1; + for (int i = 0; i < attributes.size(); i++) { + if (attributes[i].name == p_name) { + idx = i; break; } } - if (idx<0) { - ERR_EXPLAIN("Attribute not found: "+p_name); + if (idx < 0) { + ERR_EXPLAIN("Attribute not found: " + p_name); } - ERR_FAIL_COND_V(idx<0,""); + ERR_FAIL_COND_V(idx < 0, ""); return attributes[idx].value; - } -String XMLParser::get_attribute_value_safe(const String& p_name) const { +String XMLParser::get_attribute_value_safe(const String &p_name) const { - int idx=-1; - for(int i=0;i<attributes.size();i++) { - if (attributes[i].name==p_name) { - idx=i; + int idx = -1; + for (int i = 0; i < attributes.size(); i++) { + if (attributes[i].name == p_name) { + idx = i; break; } } - if (idx<0) + if (idx < 0) return ""; return attributes[idx].value; - } bool XMLParser::is_empty() const { return node_empty; } -Error XMLParser::open_buffer(const Vector<uint8_t>& p_buffer) { +Error XMLParser::open_buffer(const Vector<uint8_t> &p_buffer) { - ERR_FAIL_COND_V(p_buffer.size()==0,ERR_INVALID_DATA); + ERR_FAIL_COND_V(p_buffer.size() == 0, ERR_INVALID_DATA); length = p_buffer.size(); - data = memnew_arr( char, length+1); - copymem(data,p_buffer.ptr(),length); - data[length]=0; - P=data; + data = memnew_arr(char, length + 1); + copymem(data, p_buffer.ptr(), length); + data[length] = 0; + P = data; return OK; - } -Error XMLParser::open(const String& p_path) { +Error XMLParser::open(const String &p_path) { Error err; - FileAccess * file = FileAccess::open(p_path,FileAccess::READ,&err); + FileAccess *file = FileAccess::open(p_path, FileAccess::READ, &err); if (err) { - ERR_FAIL_COND_V(err!=OK,err); + ERR_FAIL_COND_V(err != OK, err); } length = file->get_len(); - ERR_FAIL_COND_V(length<1, ERR_FILE_CORRUPT); + ERR_FAIL_COND_V(length < 1, ERR_FILE_CORRUPT); - data = memnew_arr( char, length+1); - file->get_buffer((uint8_t*)data,length); - data[length]=0; - P=data; + data = memnew_arr(char, length + 1); + file->get_buffer((uint8_t *)data, length); + data[length] = 0; + P = data; memdelete(file); return OK; - } void XMLParser::skip_section() { @@ -541,29 +508,24 @@ void XMLParser::skip_section() { // read until we've reached the last element in this section int tagcount = 1; - while(tagcount && read()==OK) - { + while (tagcount && read() == OK) { if (get_node_type() == XMLParser::NODE_ELEMENT && - !is_empty()) - { + !is_empty()) { ++tagcount; - } - else - if (get_node_type() == XMLParser::NODE_ELEMENT_END) + } else if (get_node_type() == XMLParser::NODE_ELEMENT_END) --tagcount; } - } void XMLParser::close() { if (data) memdelete_arr(data); - data=NULL; - length=0; - P=NULL; - node_empty=false; - node_type=NODE_NONE; + data = NULL; + length = 0; + P = NULL; + node_empty = false; + node_type = NODE_NONE; node_offset = 0; } @@ -574,19 +536,16 @@ int XMLParser::get_current_line() const { XMLParser::XMLParser() { - data=NULL; + data = NULL; close(); special_characters.push_back("&"); special_characters.push_back("<lt;"); special_characters.push_back(">gt;"); special_characters.push_back("\"quot;"); special_characters.push_back("'apos;"); - - } XMLParser::~XMLParser() { - if (data) memdelete_arr(data); } diff --git a/core/io/xml_parser.h b/core/io/xml_parser.h index 7f80751156..631d77a41e 100644 --- a/core/io/xml_parser.h +++ b/core/io/xml_parser.h @@ -29,10 +29,10 @@ #ifndef XML_PARSER_H #define XML_PARSER_H -#include "ustring.h" -#include "vector.h" #include "os/file_access.h" #include "reference.h" +#include "ustring.h" +#include "vector.h" /* Based on irrXML (see their zlib license). Added mainly for compatibility with their Collada loader. @@ -40,7 +40,8 @@ class XMLParser : public Reference { - GDCLASS( XMLParser, Reference ); + GDCLASS(XMLParser, Reference); + public: //! Enumeration of all supported source text file formats enum SourceFormat { @@ -63,11 +64,10 @@ public: }; private: - char *data; char *P; int length; - void unescape(String& p_str); + void unescape(String &p_str); Vector<String> special_characters; String node_name; bool node_empty; @@ -81,8 +81,8 @@ private: Vector<Attribute> attributes; - String _replace_special_characters(const String& origstr); - bool _set_text(char* start, char* end); + String _replace_special_characters(const String &origstr); + bool _set_text(char *start, char *end); void _parse_closing_xml_element(); void _ignore_definition(); bool _parse_cdata(); @@ -93,8 +93,6 @@ private: static void _bind_methods(); public: - - Error read(); NodeType get_node_type(); String get_node_name() const; @@ -103,17 +101,17 @@ public: int get_attribute_count() const; String get_attribute_name(int p_idx) const; String get_attribute_value(int p_idx) const; - bool has_attribute(const String& p_name) const; - String get_attribute_value(const String& p_name) const; - String get_attribute_value_safe(const String& p_name) const; // do not print error if doesn't exist + bool has_attribute(const String &p_name) const; + String get_attribute_value(const String &p_name) const; + String get_attribute_value_safe(const String &p_name) const; // do not print error if doesn't exist bool is_empty() const; int get_current_line() const; void skip_section(); Error seek(uint64_t p_pos); - Error open(const String& p_path); - Error open_buffer(const Vector<uint8_t>& p_buffer); + Error open(const String &p_path); + Error open_buffer(const Vector<uint8_t> &p_buffer); void close(); @@ -122,4 +120,3 @@ public: }; #endif - diff --git a/core/io/zip_io.h b/core/io/zip_io.h index c994593518..4da9fc9c8d 100644 --- a/core/io/zip_io.h +++ b/core/io/zip_io.h @@ -29,69 +29,65 @@ #ifndef ZIP_IO_H #define ZIP_IO_H -#include "io/zip.h" #include "io/unzip.h" -#include "os/file_access.h" +#include "io/zip.h" #include "os/copymem.h" +#include "os/file_access.h" +static void *zipio_open(void *data, const char *p_fname, int mode) { -static void* zipio_open(void* data, const char* p_fname, int mode) { - - FileAccess *&f = *(FileAccess**)data; + FileAccess *&f = *(FileAccess **)data; String fname; fname.parse_utf8(p_fname); if (mode & ZLIB_FILEFUNC_MODE_WRITE) { - f = FileAccess::open(fname,FileAccess::WRITE); + f = FileAccess::open(fname, FileAccess::WRITE); } else { - f = FileAccess::open(fname,FileAccess::READ); + f = FileAccess::open(fname, FileAccess::READ); } if (!f) return NULL; return data; - }; -static uLong zipio_read(void* data, void* fdata, void* buf, uLong size) { - - FileAccess* f = *(FileAccess**)data; - return f->get_buffer((uint8_t*)buf, size); +static uLong zipio_read(void *data, void *fdata, void *buf, uLong size) { + FileAccess *f = *(FileAccess **)data; + return f->get_buffer((uint8_t *)buf, size); }; -static uLong zipio_write(voidpf opaque, voidpf stream, const void* buf, uLong size) { +static uLong zipio_write(voidpf opaque, voidpf stream, const void *buf, uLong size) { - FileAccess* f = *(FileAccess**)opaque; - f->store_buffer((uint8_t*)buf, size); + FileAccess *f = *(FileAccess **)opaque; + f->store_buffer((uint8_t *)buf, size); return size; }; +static long zipio_tell(voidpf opaque, voidpf stream) { -static long zipio_tell (voidpf opaque, voidpf stream) { - - FileAccess* f = *(FileAccess**)opaque; + FileAccess *f = *(FileAccess **)opaque; return f->get_pos(); }; static long zipio_seek(voidpf opaque, voidpf stream, uLong offset, int origin) { - FileAccess* f = *(FileAccess**)opaque; + FileAccess *f = *(FileAccess **)opaque; int pos = offset; switch (origin) { - case ZLIB_FILEFUNC_SEEK_CUR: - pos = f->get_pos() + offset; - break; - case ZLIB_FILEFUNC_SEEK_END: - pos = f->get_len() + offset; - break; - default: - break; + case ZLIB_FILEFUNC_SEEK_CUR: + pos = f->get_pos() + offset; + break; + case ZLIB_FILEFUNC_SEEK_END: + pos = f->get_len() + offset; + break; + default: + break; }; f->seek(pos); @@ -100,36 +96,32 @@ static long zipio_seek(voidpf opaque, voidpf stream, uLong offset, int origin) { static int zipio_close(voidpf opaque, voidpf stream) { - FileAccess*& f = *(FileAccess**)opaque; + FileAccess *&f = *(FileAccess **)opaque; if (f) { f->close(); - f=NULL; + f = NULL; } return 0; }; static int zipio_testerror(voidpf opaque, voidpf stream) { - FileAccess* f = *(FileAccess**)opaque; - return (f && f->get_error()!=OK)?1:0; + FileAccess *f = *(FileAccess **)opaque; + return (f && f->get_error() != OK) ? 1 : 0; }; - - static voidpf zipio_alloc(voidpf opaque, uInt items, uInt size) { - voidpf ptr =memalloc(items*size); - zeromem(ptr,items*size); + voidpf ptr = memalloc(items * size); + zeromem(ptr, items * size); return ptr; } - static void zipio_free(voidpf opaque, voidpf address) { memfree(address); } - static zlib_filefunc_def zipio_create_io_from_file(FileAccess **p_file) { zlib_filefunc_def io; @@ -141,11 +133,9 @@ static zlib_filefunc_def zipio_create_io_from_file(FileAccess **p_file) { io.zseek_file = zipio_seek; io.zclose_file = zipio_close; io.zerror_file = zipio_testerror; - io.alloc_mem=zipio_alloc; - io.free_mem=zipio_free; + io.alloc_mem = zipio_alloc; + io.free_mem = zipio_free; return io; } - - #endif // ZIP_IO_H |