diff --git a/core/allocators.h b/core/allocators.h index 14deeb87391..de92d022264 100644 --- a/core/allocators.h +++ b/core/allocators.h @@ -30,13 +30,13 @@ #define ALLOCATORS_H #include "os/memory.h" -template +template class BalloonAllocator { enum { - USED_FLAG=(1<<30), - USED_MASK=USED_FLAG-1 + USED_FLAG = (1 << 30), + USED_MASK = USED_FLAG - 1 }; struct Balloon { @@ -46,7 +46,6 @@ class BalloonAllocator { uint32_t hand; }; - struct Hand { int used; @@ -55,136 +54,132 @@ class BalloonAllocator { Balloon *last; }; - Hand hands[MAX_HANDS]; - - public: + void *alloc(size_t p_size) { - void* alloc(size_t p_size) { + size_t max = (1 << MAX_HANDS); + ERR_FAIL_COND_V(p_size > max, NULL); - size_t max=(1<max, NULL ); + unsigned int hand = 0; - unsigned int hand=0; + while (p_size > (size_t)(1 << hand)) + ++hand; - while(p_size>(size_t)(1<hand=hand; + Balloon *b = (Balloon *)memalloc(sizeof(Balloon) + (1 << hand)); + b->hand = hand; if (h.last) { - b->prev=h.last; - h.last->next=b; - h.last=b; + b->prev = h.last; + h.last->next = b; + h.last = b; } else { - b->prev=NULL; - h.last=b; - h.first=b; + b->prev = NULL; + h.last = b; + h.first = b; } } - h.last->next=NULL; - h.allocated+=PREALLOC_COUNT; + h.last->next = NULL; + h.allocated += PREALLOC_COUNT; } - Balloon *pick=h.last; + Balloon *pick = h.last; - ERR_FAIL_COND_V( (pick->hand&USED_FLAG), NULL ); + ERR_FAIL_COND_V((pick->hand & USED_FLAG), NULL); // remove last - h.last=h.last->prev; - h.last->next=NULL; + h.last = h.last->prev; + h.last->next = NULL; - pick->next=h.first; - h.first->prev=pick; - pick->prev=NULL; - h.first=pick; + pick->next = h.first; + h.first->prev = pick; + pick->prev = NULL; + h.first = pick; h.used++; - pick->hand|=USED_FLAG; + pick->hand |= USED_FLAG; - return (void*)(pick+1); + return (void *)(pick + 1); } - void free(void* p_ptr) { + void free(void *p_ptr) { - Balloon *b=(Balloon*)p_ptr; - b-=1; + Balloon *b = (Balloon *)p_ptr; + b -= 1; - ERR_FAIL_COND(!(b->hand&USED_FLAG) ); + ERR_FAIL_COND(!(b->hand & USED_FLAG)); - b->hand=b->hand&USED_MASK; // not used - int hand=b->hand; + b->hand = b->hand & USED_MASK; // not used + int hand = b->hand; - Hand &h=hands[hand]; + Hand &h = hands[hand]; - if (b==h.first) - h.first=b->next; + if (b == h.first) + h.first = b->next; if (b->prev) - b->prev->next=b->next; + b->prev->next = b->next; if (b->next) - b->next->prev=b->prev; + b->next->prev = b->prev; - if (h.last!=b) { - h.last->next=b; - b->prev=h.last; - b->next=NULL; - h.last=b; + if (h.last != b) { + h.last->next = b; + b->prev = h.last; + b->next = NULL; + h.last = b; } h.used--; - if (h.used<=(h.allocated-(PREALLOC_COUNT*2))) { // this is done to ensure no alloc/free is done constantly + if (h.used <= (h.allocated - (PREALLOC_COUNT * 2))) { // this is done to ensure no alloc/free is done constantly - for(int i=0;ihand& USED_FLAG ); + for (int i = 0; i < PREALLOC_COUNT; i++) { + ERR_CONTINUE(h.last->hand & USED_FLAG); - Balloon *new_last=h.last->prev; + Balloon *new_last = h.last->prev; if (new_last) - new_last->next=NULL; - memfree( h.last ); - h.last=new_last; + new_last->next = NULL; + memfree(h.last); + h.last = new_last; } - h.allocated-=PREALLOC_COUNT; + h.allocated -= PREALLOC_COUNT; } } BalloonAllocator() { - for(int i=0;inext; + Balloon *b = hands[i].first; + hands[i].first = b->next; memfree(b); } - hands[i].allocated=0; - hands[i].used=0; - hands[i].first=NULL; - hands[i].last=NULL; + hands[i].allocated = 0; + hands[i].used = 0; + hands[i].first = NULL; + hands[i].last = NULL; } } @@ -194,5 +189,4 @@ public: } }; - #endif // ALLOCATORS_H diff --git a/core/array.cpp b/core/array.cpp index ca405fb69d3..092d0efe99b 100644 --- a/core/array.cpp +++ b/core/array.cpp @@ -27,10 +27,10 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "array.h" -#include "vector.h" #include "hashfuncs.h" -#include "variant.h" #include "object.h" +#include "variant.h" +#include "vector.h" struct ArrayPrivate { @@ -39,7 +39,7 @@ struct ArrayPrivate { bool shared; }; -void Array::_ref(const Array& p_from) const { +void Array::_ref(const Array &p_from) const { ArrayPrivate *_fp = p_from._p; @@ -60,10 +60,10 @@ void Array::_ref(const Array& p_from) const { } else { - _p = memnew( ArrayPrivate ); - _p->shared=false; + _p = memnew(ArrayPrivate); + _p->shared = false; _p->refcount.init(); - _p->array=_fp->array; + _p->array = _fp->array; if (_fp->refcount.unref()) memdelete(_fp); @@ -78,19 +78,17 @@ void Array::_unref() const { if (_p->refcount.unref()) { memdelete(_p); } - _p=NULL; + _p = NULL; } - -Variant& Array::operator[](int p_idx) { +Variant &Array::operator[](int p_idx) { return _p->array[p_idx]; } -const Variant& Array::operator[](int p_idx) const { +const Variant &Array::operator[](int p_idx) const { return _p->array[p_idx]; - } int Array::size() const { @@ -108,29 +106,29 @@ void Array::clear() { bool Array::is_shared() const { - return _p->shared; + return _p->shared; } -bool Array::operator==(const Array& p_array) const { +bool Array::operator==(const Array &p_array) const { - return _p==p_array._p; + return _p == p_array._p; } uint32_t Array::hash() const { - uint32_t h=hash_djb2_one_32(0); + uint32_t h = hash_djb2_one_32(0); - for (int i=0;i<_p->array.size();i++) { + for (int i = 0; i < _p->array.size(); i++) { - h = hash_djb2_one_32( _p->array[i].hash(), h); + h = hash_djb2_one_32(_p->array[i].hash(), h); } return h; } -void Array::operator=(const Array& p_array) { +void Array::operator=(const Array &p_array) { _ref(p_array); } -void Array::push_back(const Variant& p_value) { +void Array::push_back(const Variant &p_value) { _p->array.push_back(p_value); } @@ -140,12 +138,12 @@ Error Array::resize(int p_new_size) { return _p->array.resize(p_new_size); } -void Array::insert(int p_pos, const Variant& p_value) { +void Array::insert(int p_pos, const Variant &p_value) { - _p->array.insert(p_pos,p_value); + _p->array.insert(p_pos, p_value); } -void Array::erase(const Variant& p_value) { +void Array::erase(const Variant &p_value) { _p->array.erase(p_value); } @@ -160,12 +158,12 @@ Variant Array::back() const { return operator[](_p->array.size() - 1); } -int Array::find(const Variant& p_value, int p_from) const { +int Array::find(const Variant &p_value, int p_from) const { return _p->array.find(p_value, p_from); } -int Array::rfind(const Variant& p_value, int p_from) const { +int Array::rfind(const Variant &p_value, int p_from) const { if (_p->array.size() == 0) return -1; @@ -179,9 +177,9 @@ int Array::rfind(const Variant& p_value, int p_from) const { p_from = _p->array.size() - 1; } - for (int i=p_from; i>=0; i--) { + for (int i = p_from; i >= 0; i--) { - if(_p->array[i] == p_value){ + if (_p->array[i] == p_value) { return i; }; }; @@ -189,20 +187,20 @@ int Array::rfind(const Variant& p_value, int p_from) const { return -1; } -int Array::find_last(const Variant& p_value) const { +int Array::find_last(const Variant &p_value) const { return rfind(p_value); } -int Array::count(const Variant& p_value) const { +int Array::count(const Variant &p_value) const { - if(_p->array.size() == 0) + if (_p->array.size() == 0) return 0; - int amount=0; - for (int i=0; i<_p->array.size(); i++) { + int amount = 0; + for (int i = 0; i < _p->array.size(); i++) { - if(_p->array[i] == p_value){ + if (_p->array[i] == p_value) { amount++; }; }; @@ -210,7 +208,7 @@ int Array::count(const Variant& p_value) const { return amount; } -bool Array::has(const Variant& p_value) const { +bool Array::has(const Variant &p_value) const { return _p->array.find(p_value, 0) != -1; } @@ -219,25 +217,24 @@ void Array::remove(int p_pos) { _p->array.remove(p_pos); } +void Array::set(int p_idx, const Variant &p_value) { -void Array::set(int p_idx,const Variant& p_value) { - - operator[](p_idx)=p_value; + operator[](p_idx) = p_value; } -const Variant& Array::get(int p_idx) const { +const Variant &Array::get(int p_idx) const { return operator[](p_idx); } struct _ArrayVariantSort { - _FORCE_INLINE_ bool operator()(const Variant& p_l, const Variant& p_r) const { - bool valid=false; + _FORCE_INLINE_ bool operator()(const Variant &p_l, const Variant &p_r) const { + bool valid = false; Variant res; - Variant::evaluate(Variant::OP_LESS,p_l,p_r,res,valid); + Variant::evaluate(Variant::OP_LESS, p_l, p_r, res, valid); if (!valid) - res=false; + res = false; return res; } }; @@ -245,7 +242,6 @@ struct _ArrayVariantSort { void Array::sort() { _p->array.sort_custom<_ArrayVariantSort>(); - } struct _ArrayVariantSortCustom { @@ -253,64 +249,57 @@ struct _ArrayVariantSortCustom { Object *obj; StringName func; - _FORCE_INLINE_ bool operator()(const Variant& p_l, const Variant& p_r) const { + _FORCE_INLINE_ bool operator()(const Variant &p_l, const Variant &p_r) const { - const Variant*args[2]={&p_l,&p_r}; + const Variant *args[2] = { &p_l, &p_r }; Variant::CallError err; - bool res = obj->call(func,args,2,err); - if (err.error!=Variant::CallError::CALL_OK) - res=false; + bool res = obj->call(func, args, 2, err); + if (err.error != Variant::CallError::CALL_OK) + res = false; return res; - } }; -void Array::sort_custom(Object *p_obj,const StringName& p_function){ +void Array::sort_custom(Object *p_obj, const StringName &p_function) { ERR_FAIL_NULL(p_obj); - SortArray avs; - avs.compare.obj=p_obj; - avs.compare.func=p_function; - avs.sort(_p->array.ptr(),_p->array.size()); - + SortArray avs; + avs.compare.obj = p_obj; + avs.compare.func = p_function; + avs.sort(_p->array.ptr(), _p->array.size()); } -void Array::invert(){ +void Array::invert() { _p->array.invert(); } +void Array::push_front(const Variant &p_value) { -void Array::push_front(const Variant& p_value) { - - _p->array.insert(0,p_value); + _p->array.insert(0, p_value); } -void Array::pop_back(){ +void Array::pop_back() { if (!_p->array.empty()) - _p->array.resize( _p->array.size() -1 ); - + _p->array.resize(_p->array.size() - 1); } -void Array::pop_front(){ +void Array::pop_front() { if (!_p->array.empty()) _p->array.remove(0); - } +Array::Array(const Array &p_from) { -Array::Array(const Array& p_from) { - - _p=NULL; + _p = NULL; _ref(p_from); - } Array::Array(bool p_shared) { - _p = memnew( ArrayPrivate ); + _p = memnew(ArrayPrivate); _p->refcount.init(); - _p->shared=p_shared; + _p->shared = p_shared; } Array::~Array() { diff --git a/core/array.h b/core/array.h index fc1e718ce40..6ea843775cd 100644 --- a/core/array.h +++ b/core/array.h @@ -38,16 +38,15 @@ class StringName; class Array { mutable ArrayPrivate *_p; - void _ref(const Array& p_from) const; + void _ref(const Array &p_from) const; void _unref() const; public: + Variant &operator[](int p_idx); + const Variant &operator[](int p_idx) const; - Variant& operator[](int p_idx); - const Variant& operator[](int p_idx) const; - - void set(int p_idx,const Variant& p_value); - const Variant& get(int p_idx) const; + void set(int p_idx, const Variant &p_value); + const Variant &get(int p_idx) const; int size() const; bool empty() const; @@ -55,41 +54,40 @@ public: bool is_shared() const; - bool operator==(const Array& p_array) const; + bool operator==(const Array &p_array) const; uint32_t hash() const; - void operator=(const Array& p_array); + void operator=(const Array &p_array); - void push_back(const Variant& p_value); - _FORCE_INLINE_ void append(const Variant& p_value) { push_back(p_value); } //for python compatibility + void push_back(const Variant &p_value); + _FORCE_INLINE_ void append(const Variant &p_value) { push_back(p_value); } //for python compatibility Error resize(int p_new_size); - void insert(int p_pos, const Variant& p_value); + void insert(int p_pos, const Variant &p_value); void remove(int p_pos); Variant front() const; Variant back() const; void sort(); - void sort_custom(Object *p_obj,const StringName& p_function); + void sort_custom(Object *p_obj, const StringName &p_function); void invert(); - int find(const Variant& p_value, int p_from=0) const; - int rfind(const Variant& p_value, int p_from=-1) const; - int find_last(const Variant& p_value) const; - int count(const Variant& p_value) const; - bool has(const Variant& p_value) const; + int find(const Variant &p_value, int p_from = 0) const; + int rfind(const Variant &p_value, int p_from = -1) const; + int find_last(const Variant &p_value) const; + int count(const Variant &p_value) const; + bool has(const Variant &p_value) const; - void erase(const Variant& p_value); + void erase(const Variant &p_value); - void push_front(const Variant& p_value); + void push_front(const Variant &p_value); void pop_back(); void pop_front(); - Array(const Array& p_from); - Array(bool p_shared=false); + Array(const Array &p_from); + Array(bool p_shared = false); ~Array(); - }; #endif // ARRAY_H diff --git a/core/bind/core_bind.cpp b/core/bind/core_bind.cpp index a4748784d2d..ba3bb8e7b94 100644 --- a/core/bind/core_bind.cpp +++ b/core/bind/core_bind.cpp @@ -27,21 +27,21 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "core_bind.h" -#include "os/os.h" -#include "geometry.h" -#include "io/marshalls.h" -#include "io/base64.h" #include "core/globals.h" +#include "geometry.h" +#include "io/base64.h" #include "io/file_access_encrypted.h" +#include "io/marshalls.h" #include "os/keyboard.h" +#include "os/os.h" /** * Time constants borrowed from loc_time.h */ -#define EPOCH_YR 1970 /* EPOCH = Jan 1 1970 00:00:00 */ -#define SECS_DAY (24L * 60L * 60L) -#define LEAPYEAR(year) (!((year) % 4) && (((year) % 100) || !((year) % 400))) -#define YEARSIZE(year) (LEAPYEAR(year) ? 366 : 365) +#define EPOCH_YR 1970 /* EPOCH = Jan 1 1970 00:00:00 */ +#define SECS_DAY (24L * 60L * 60L) +#define LEAPYEAR(year) (!((year) % 4) && (((year) % 100) || !((year) % 400))) +#define YEARSIZE(year) (LEAPYEAR(year) ? 366 : 365) #define SECOND_KEY "second" #define MINUTE_KEY "minute" #define HOUR_KEY "hour" @@ -57,24 +57,24 @@ static const unsigned int MONTH_DAYS_TABLE[2][12] = { { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 } }; -_ResourceLoader *_ResourceLoader::singleton=NULL; +_ResourceLoader *_ResourceLoader::singleton = NULL; -Ref _ResourceLoader::load_interactive(const String& p_path,const String& p_type_hint) { - return ResourceLoader::load_interactive(p_path,p_type_hint); +Ref _ResourceLoader::load_interactive(const String &p_path, const String &p_type_hint) { + return ResourceLoader::load_interactive(p_path, p_type_hint); } -RES _ResourceLoader::load(const String &p_path,const String& p_type_hint, bool p_no_cache) { +RES _ResourceLoader::load(const String &p_path, const String &p_type_hint, bool p_no_cache) { - RES ret = ResourceLoader::load(p_path,p_type_hint, p_no_cache); + RES ret = ResourceLoader::load(p_path, p_type_hint, p_no_cache); return ret; } -DVector _ResourceLoader::get_recognized_extensions_for_type(const String& p_type) { +DVector _ResourceLoader::get_recognized_extensions_for_type(const String &p_type) { List exts; - ResourceLoader::get_recognized_extensions_for_type(p_type,&exts); + ResourceLoader::get_recognized_extensions_for_type(p_type, &exts); DVector ret; - for(List::Element *E=exts.front();E;E=E->next()) { + for (List::Element *E = exts.front(); E; E = E->next()) { ret.push_back(E->get()); } @@ -87,13 +87,13 @@ void _ResourceLoader::set_abort_on_missing_resources(bool p_abort) { ResourceLoader::set_abort_on_missing_resources(p_abort); } -StringArray _ResourceLoader::get_dependencies(const String& p_path) { +StringArray _ResourceLoader::get_dependencies(const String &p_path) { List deps; ResourceLoader::get_dependencies(p_path, &deps); StringArray ret; - for(List::Element *E=deps.front();E;E=E->next()) { + for (List::Element *E = deps.front(); E; E = E->next()) { ret.push_back(E->get()); } @@ -106,55 +106,52 @@ bool _ResourceLoader::has(const String &p_path) { return ResourceCache::has(local_path); }; -Ref _ResourceLoader::load_import_metadata(const String& p_path) { +Ref _ResourceLoader::load_import_metadata(const String &p_path) { return ResourceLoader::load_import_metadata(p_path); } void _ResourceLoader::_bind_methods() { - - ObjectTypeDB::bind_method(_MD("load_interactive:ResourceInteractiveLoader","path","type_hint"),&_ResourceLoader::load_interactive,DEFVAL("")); - ObjectTypeDB::bind_method(_MD("load:Resource","path","type_hint", "p_no_cache"),&_ResourceLoader::load,DEFVAL(""), DEFVAL(false)); - ObjectTypeDB::bind_method(_MD("load_import_metadata:ResourceImportMetadata","path"),&_ResourceLoader::load_import_metadata); - ObjectTypeDB::bind_method(_MD("get_recognized_extensions_for_type","type"),&_ResourceLoader::get_recognized_extensions_for_type); - ObjectTypeDB::bind_method(_MD("set_abort_on_missing_resources","abort"),&_ResourceLoader::set_abort_on_missing_resources); - ObjectTypeDB::bind_method(_MD("get_dependencies","path"),&_ResourceLoader::get_dependencies); - ObjectTypeDB::bind_method(_MD("has","path"),&_ResourceLoader::has); + ObjectTypeDB::bind_method(_MD("load_interactive:ResourceInteractiveLoader", "path", "type_hint"), &_ResourceLoader::load_interactive, DEFVAL("")); + ObjectTypeDB::bind_method(_MD("load:Resource", "path", "type_hint", "p_no_cache"), &_ResourceLoader::load, DEFVAL(""), DEFVAL(false)); + ObjectTypeDB::bind_method(_MD("load_import_metadata:ResourceImportMetadata", "path"), &_ResourceLoader::load_import_metadata); + ObjectTypeDB::bind_method(_MD("get_recognized_extensions_for_type", "type"), &_ResourceLoader::get_recognized_extensions_for_type); + ObjectTypeDB::bind_method(_MD("set_abort_on_missing_resources", "abort"), &_ResourceLoader::set_abort_on_missing_resources); + ObjectTypeDB::bind_method(_MD("get_dependencies", "path"), &_ResourceLoader::get_dependencies); + ObjectTypeDB::bind_method(_MD("has", "path"), &_ResourceLoader::has); } _ResourceLoader::_ResourceLoader() { - singleton=this; + singleton = this; } +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) { - - ERR_FAIL_COND_V(p_resource.is_null(),ERR_INVALID_PARAMETER); - return ResourceSaver::save(p_path,p_resource, p_flags); + ERR_FAIL_COND_V(p_resource.is_null(), ERR_INVALID_PARAMETER); + return ResourceSaver::save(p_path, p_resource, p_flags); } -DVector _ResourceSaver::get_recognized_extensions(const RES& p_resource) { +DVector _ResourceSaver::get_recognized_extensions(const RES &p_resource) { - ERR_FAIL_COND_V(p_resource.is_null(),DVector()); + ERR_FAIL_COND_V(p_resource.is_null(), DVector()); List exts; - ResourceSaver::get_recognized_extensions(p_resource,&exts); + ResourceSaver::get_recognized_extensions(p_resource, &exts); DVector ret; - for(List::Element *E=exts.front();E;E=E->next()) { + for (List::Element *E = exts.front(); E; E = E->next()) { ret.push_back(E->get()); } return ret; } -_ResourceSaver *_ResourceSaver::singleton=NULL; - +_ResourceSaver *_ResourceSaver::singleton = NULL; void _ResourceSaver::_bind_methods() { - ObjectTypeDB::bind_method(_MD("save","path","resource:Resource","flags"),&_ResourceSaver::save,DEFVAL(0)); - ObjectTypeDB::bind_method(_MD("get_recognized_extensions","type"),&_ResourceSaver::get_recognized_extensions); + ObjectTypeDB::bind_method(_MD("save", "path", "resource:Resource", "flags"), &_ResourceSaver::save, DEFVAL(0)); + ObjectTypeDB::bind_method(_MD("get_recognized_extensions", "type"), &_ResourceSaver::get_recognized_extensions); BIND_CONSTANT(FLAG_RELATIVE_PATHS); BIND_CONSTANT(FLAG_BUNDLE_RESOURCES); @@ -166,21 +163,18 @@ void _ResourceSaver::_bind_methods() { _ResourceSaver::_ResourceSaver() { - singleton=this; + singleton = this; } - /////////////////OS - Point2 _OS::get_mouse_pos() const { return OS::get_singleton()->get_mouse_pos(); } -void _OS::set_window_title(const String& p_title) { +void _OS::set_window_title(const String &p_title) { OS::get_singleton()->set_window_title(p_title); - } int _OS::get_mouse_button_state() const { @@ -196,44 +190,37 @@ bool _OS::has_touchscreen_ui_hint() const { return OS::get_singleton()->has_touchscreen_ui_hint(); } -void _OS::set_clipboard(const String& p_text) { - +void _OS::set_clipboard(const String &p_text) { OS::get_singleton()->set_clipboard(p_text); } String _OS::get_clipboard() const { return OS::get_singleton()->get_clipboard(); - } -void _OS::set_video_mode(const Size2& p_size, bool p_fullscreen,bool p_resizeable,int p_screen) { +void _OS::set_video_mode(const Size2 &p_size, bool p_fullscreen, bool p_resizeable, int p_screen) { OS::VideoMode vm; - vm.width=p_size.width; - vm.height=p_size.height; - vm.fullscreen=p_fullscreen; - vm.resizable=p_resizeable; - OS::get_singleton()->set_video_mode( vm,p_screen); - - + vm.width = p_size.width; + vm.height = p_size.height; + vm.fullscreen = p_fullscreen; + vm.resizable = p_resizeable; + OS::get_singleton()->set_video_mode(vm, p_screen); } Size2 _OS::get_video_mode(int p_screen) const { OS::VideoMode vm; vm = OS::get_singleton()->get_video_mode(p_screen); - return Size2(vm.width,vm.height); - + return Size2(vm.width, vm.height); } bool _OS::is_video_mode_fullscreen(int p_screen) const { OS::VideoMode vm; vm = OS::get_singleton()->get_video_mode(p_screen); return vm.fullscreen; - } - int _OS::get_screen_count() const { return OS::get_singleton()->get_screen_count(); } @@ -256,14 +243,14 @@ Size2 _OS::get_screen_size(int p_screen) const { int _OS::get_screen_dpi(int p_screen) const { - return OS::get_singleton()->get_screen_dpi(p_screen); + return OS::get_singleton()->get_screen_dpi(p_screen); } Point2 _OS::get_window_position() const { return OS::get_singleton()->get_window_position(); } -void _OS::set_window_position(const Point2& p_position) { +void _OS::set_window_position(const Point2 &p_position) { OS::get_singleton()->set_window_position(p_position); } @@ -271,7 +258,7 @@ Size2 _OS::get_window_size() const { return OS::get_singleton()->get_window_size(); } -void _OS::set_window_size(const Size2& p_size) { +void _OS::set_window_size(const Size2 &p_size) { OS::get_singleton()->set_window_size(p_size); } @@ -330,11 +317,11 @@ bool _OS::is_video_mode_resizable(int p_screen) const { Array _OS::get_fullscreen_mode_list(int p_screen) const { List vmlist; - OS::get_singleton()->get_fullscreen_mode_list(&vmlist,p_screen); + OS::get_singleton()->get_fullscreen_mode_list(&vmlist, p_screen); Array vmarr; - for(List::Element *E=vmlist.front();E;E=E->next() ){ + for (List::Element *E = vmlist.front(); E; E = E->next()) { - vmarr.push_back(Size2(E->get().width,E->get().height)); + vmarr.push_back(Size2(E->get().width, E->get().height)); } return vmarr; @@ -347,7 +334,6 @@ void _OS::set_iterations_per_second(int p_ips) { int _OS::get_iterations_per_second() const { return OS::get_singleton()->get_iterations_per_second(); - } void _OS::set_target_fps(int p_fps) { @@ -377,22 +363,20 @@ Error _OS::shell_open(String p_uri) { return OS::get_singleton()->shell_open(p_uri); }; - -int _OS::execute(const String& p_path, const Vector & p_arguments, bool p_blocking, Array p_output) { +int _OS::execute(const String &p_path, const Vector &p_arguments, bool p_blocking, Array p_output) { OS::ProcessID pid; List args; - for(int i=0;iexecute(p_path,args,p_blocking,&pid, &pipe); + Error err = OS::get_singleton()->execute(p_path, args, p_blocking, &pid, &pipe); p_output.clear(); p_output.push_back(pipe); if (err != OK) return -1; else return pid; - } Error _OS::kill(int p_pid) { @@ -404,12 +388,11 @@ int _OS::get_process_ID() const { return OS::get_singleton()->get_process_ID(); }; - -bool _OS::has_environment(const String& p_var) const { +bool _OS::has_environment(const String &p_var) const { return OS::get_singleton()->has_environment(p_var); } -String _OS::get_environment(const String& p_var) const { +String _OS::get_environment(const String &p_var) const { return OS::get_singleton()->get_environment(p_var); } @@ -422,7 +405,7 @@ Vector _OS::get_cmdline_args() { List cmdline = OS::get_singleton()->get_cmdline_args(); Vector cmdlinev; - for(List::Element *E=cmdline.front();E;E=E->next()) { + for (List::Element *E = cmdline.front(); E; E = E->next()) { cmdlinev.push_back(E->get()); } @@ -436,20 +419,20 @@ String _OS::get_locale() const { } String _OS::get_latin_keyboard_variant() const { - switch( OS::get_singleton()->get_latin_keyboard_variant() ) { + switch (OS::get_singleton()->get_latin_keyboard_variant()) { case OS::LATIN_KEYBOARD_QWERTY: return "QWERTY"; case OS::LATIN_KEYBOARD_QWERTZ: return "QWERTZ"; case OS::LATIN_KEYBOARD_AZERTY: return "AZERTY"; case OS::LATIN_KEYBOARD_QZERTY: return "QZERTY"; case OS::LATIN_KEYBOARD_DVORAK: return "DVORAK"; - case OS::LATIN_KEYBOARD_NEO : return "NEO"; + case OS::LATIN_KEYBOARD_NEO: return "NEO"; default: return "ERROR"; } } String _OS::get_model_name() const { - return OS::get_singleton()->get_model_name(); + return OS::get_singleton()->get_model_name(); } MainLoop *_OS::get_main_loop() const { @@ -471,7 +454,7 @@ bool _OS::is_ok_left_and_cancel_right() const { return OS::get_singleton()->get_swap_ok_cancel(); } -Error _OS::set_thread_name(const String& p_name) { +Error _OS::set_thread_name(const String &p_name) { return Thread::set_name(p_name); }; @@ -485,7 +468,6 @@ bool _OS::is_vsync_enabled() const { return OS::get_singleton()->is_vsync_enabled(); } - /* enum Weekday { DAY_SUNDAY, @@ -533,22 +515,19 @@ struct Time { int _OS::get_static_memory_usage() const { return OS::get_singleton()->get_static_memory_usage(); - } int _OS::get_static_memory_peak_usage() const { return OS::get_singleton()->get_static_memory_peak_usage(); - } -int _OS::get_dynamic_memory_usage() const{ +int _OS::get_dynamic_memory_usage() const { return OS::get_singleton()->get_dynamic_memory_usage(); } - -void _OS::set_icon(const Image& p_icon) { +void _OS::set_icon(const Image &p_icon) { OS::get_singleton()->set_icon(p_icon); } @@ -575,7 +554,7 @@ Dictionary _OS::get_datetime(bool utc) const { List keys; timed.get_key_list(&keys); - for(int i = 0; i < keys.size(); i++) { + for (int i = 0; i < keys.size(); i++) { dated[keys[i]] = timed[keys[i]]; } @@ -586,11 +565,11 @@ Dictionary _OS::get_date(bool utc) const { OS::Date date = OS::get_singleton()->get_date(utc); Dictionary dated; - dated[YEAR_KEY]=date.year; - dated[MONTH_KEY]=date.month; - dated[DAY_KEY]=date.day; - dated[WEEKDAY_KEY]=date.weekday; - dated[DST_KEY]=date.dst; + dated[YEAR_KEY] = date.year; + dated[MONTH_KEY] = date.month; + dated[DAY_KEY] = date.day; + dated[WEEKDAY_KEY] = date.weekday; + dated[DST_KEY] = date.dst; return dated; } @@ -598,9 +577,9 @@ Dictionary _OS::get_time(bool utc) const { OS::Time time = OS::get_singleton()->get_time(utc); Dictionary timed; - timed[HOUR_KEY]=time.hour; - timed[MINUTE_KEY]=time.min; - timed[SECOND_KEY]=time.sec; + timed[HOUR_KEY] = time.hour; + timed[MINUTE_KEY] = time.min; + timed[SECOND_KEY] = time.sec; return timed; } @@ -627,12 +606,12 @@ uint64_t _OS::get_unix_time_from_datetime(Dictionary datetime) const { // Get all time values from the dictionary, set to zero if it doesn't exist. // Risk incorrect calculation over throwing errors - unsigned int second = ((datetime.has(SECOND_KEY)) ? static_cast(datetime[SECOND_KEY]): 0); - unsigned int minute = ((datetime.has(MINUTE_KEY)) ? static_cast(datetime[MINUTE_KEY]): 0); - unsigned int hour = ((datetime.has(HOUR_KEY)) ? static_cast(datetime[HOUR_KEY]): 0); - unsigned int day = ((datetime.has(DAY_KEY)) ? static_cast(datetime[DAY_KEY]): 0); - unsigned int month = ((datetime.has(MONTH_KEY)) ? static_cast(datetime[MONTH_KEY]) -1: 0); - unsigned int year = ((datetime.has(YEAR_KEY)) ? static_cast(datetime[YEAR_KEY]):0); + unsigned int second = ((datetime.has(SECOND_KEY)) ? static_cast(datetime[SECOND_KEY]) : 0); + unsigned int minute = ((datetime.has(MINUTE_KEY)) ? static_cast(datetime[MINUTE_KEY]) : 0); + unsigned int hour = ((datetime.has(HOUR_KEY)) ? static_cast(datetime[HOUR_KEY]) : 0); + unsigned int day = ((datetime.has(DAY_KEY)) ? static_cast(datetime[DAY_KEY]) : 0); + unsigned int month = ((datetime.has(MONTH_KEY)) ? static_cast(datetime[MONTH_KEY]) - 1 : 0); + unsigned int year = ((datetime.has(YEAR_KEY)) ? static_cast(datetime[YEAR_KEY]) : 0); /// How many days come before each month (0-12) static const unsigned short int DAYS_PAST_THIS_YEAR_TABLE[2][13] = { @@ -643,41 +622,40 @@ uint64_t _OS::get_unix_time_from_datetime(Dictionary datetime) const { }; ERR_EXPLAIN("Invalid second value of: " + itos(second)); - ERR_FAIL_COND_V( second > 59, 0); + ERR_FAIL_COND_V(second > 59, 0); ERR_EXPLAIN("Invalid minute value of: " + itos(minute)); - ERR_FAIL_COND_V( minute > 59, 0); + ERR_FAIL_COND_V(minute > 59, 0); ERR_EXPLAIN("Invalid hour value of: " + itos(hour)); - ERR_FAIL_COND_V( hour > 23, 0); + ERR_FAIL_COND_V(hour > 23, 0); - ERR_EXPLAIN("Invalid month value of: " + itos(month+1)); - ERR_FAIL_COND_V( month+1 > 12, 0); + ERR_EXPLAIN("Invalid month value of: " + itos(month + 1)); + ERR_FAIL_COND_V(month + 1 > 12, 0); // Do this check after month is tested as valid - ERR_EXPLAIN("Invalid day value of: " + itos(day) + " which is larger than "+ itos(MONTH_DAYS_TABLE[LEAPYEAR(year)][month])); - ERR_FAIL_COND_V( day > MONTH_DAYS_TABLE[LEAPYEAR(year)][month], 0); + ERR_EXPLAIN("Invalid day value of: " + itos(day) + " which is larger than " + itos(MONTH_DAYS_TABLE[LEAPYEAR(year)][month])); + ERR_FAIL_COND_V(day > MONTH_DAYS_TABLE[LEAPYEAR(year)][month], 0); // Calculate all the seconds from months past in this year uint64_t SECONDS_FROM_MONTHS_PAST_THIS_YEAR = DAYS_PAST_THIS_YEAR_TABLE[LEAPYEAR(year)][month] * SECONDS_PER_DAY; uint64_t SECONDS_FROM_YEARS_PAST = 0; - for(unsigned int iyear = EPOCH_YR; iyear < year; iyear++) { + for (unsigned int iyear = EPOCH_YR; iyear < year; iyear++) { SECONDS_FROM_YEARS_PAST += YEARSIZE(iyear) * SECONDS_PER_DAY; } uint64_t epoch = - second + - minute * SECONDS_PER_MINUTE + - hour * SECONDS_PER_HOUR + - // Subtract 1 from day, since the current day isn't over yet - // and we cannot count all 24 hours. - (day-1) * SECONDS_PER_DAY + - SECONDS_FROM_MONTHS_PAST_THIS_YEAR + - SECONDS_FROM_YEARS_PAST; + second + + minute * SECONDS_PER_MINUTE + + hour * SECONDS_PER_HOUR + + // Subtract 1 from day, since the current day isn't over yet + // and we cannot count all 24 hours. + (day - 1) * SECONDS_PER_DAY + + SECONDS_FROM_MONTHS_PAST_THIS_YEAR + + SECONDS_FROM_YEARS_PAST; return epoch; - } /** @@ -691,12 +669,12 @@ uint64_t _OS::get_unix_time_from_datetime(Dictionary datetime) const { * * @return dictionary of date and time values */ -Dictionary _OS::get_datetime_from_unix_time( uint64_t unix_time_val) const { +Dictionary _OS::get_datetime_from_unix_time(uint64_t unix_time_val) const { // Just fail if unix time is negative (when interpreted as an int). // This means the user passed in a negative value by accident - ERR_EXPLAIN("unix_time_val was really huge!"+ itos(unix_time_val) + " You probably passed in a negative value!"); - ERR_FAIL_COND_V( (int64_t)unix_time_val < 0, Dictionary()); + ERR_EXPLAIN("unix_time_val was really huge!" + itos(unix_time_val) + " You probably passed in a negative value!"); + ERR_FAIL_COND_V((int64_t)unix_time_val < 0, Dictionary()); OS::Date date; OS::Time time; @@ -729,18 +707,18 @@ Dictionary _OS::get_datetime_from_unix_time( uint64_t unix_time_val) const { } /// Add 1 to month to make sure months are indexed starting at 1 - date.month = static_cast(imonth+1); + date.month = static_cast(imonth + 1); date.day = dayno + 1; Dictionary timed; - timed[HOUR_KEY]=time.hour; - timed[MINUTE_KEY]=time.min; - timed[SECOND_KEY]=time.sec; - timed[YEAR_KEY]=date.year; - timed[MONTH_KEY]=date.month; - timed[DAY_KEY]=date.day; - timed[WEEKDAY_KEY]=date.weekday; + timed[HOUR_KEY] = time.hour; + timed[MINUTE_KEY] = time.min; + timed[SECOND_KEY] = time.sec; + timed[YEAR_KEY] = date.year; + timed[MONTH_KEY] = date.month; + timed[DAY_KEY] = date.day; + timed[WEEKDAY_KEY] = date.weekday; return timed; } @@ -769,7 +747,7 @@ void _OS::delay_usec(uint32_t p_usec) const { void _OS::delay_msec(uint32_t p_msec) const { - OS::get_singleton()->delay_usec(int64_t(p_msec)*1000); + OS::get_singleton()->delay_usec(int64_t(p_msec) * 1000); } uint32_t _OS::get_ticks_msec() const { @@ -792,7 +770,7 @@ bool _OS::can_draw() const { return OS::get_singleton()->can_draw(); } -int _OS::get_frames_drawn() { +int _OS::get_frames_drawn() { return OS::get_singleton()->get_frames_drawn(); } @@ -805,10 +783,9 @@ int _OS::get_processor_count() const { bool _OS::is_stdout_verbose() const { return OS::get_singleton()->is_stdout_verbose(); - } -void _OS::dump_memory_to_file(const String& p_file) { +void _OS::dump_memory_to_file(const String &p_file) { OS::get_singleton()->dump_memory_to_file(p_file.utf8().get_data()); } @@ -820,19 +797,18 @@ struct _OSCoreBindImg { int fmt; ObjectID id; int vram; - bool operator<(const _OSCoreBindImg& p_img) const { return vram==p_img.vram ? id p_img.vram; } + bool operator<(const _OSCoreBindImg &p_img) const { return vram == p_img.vram ? id < p_img.id : vram > p_img.vram; } }; void _OS::print_all_textures_by_size() { - List<_OSCoreBindImg> imgs; - int total=0; + int total = 0; { List > rsrc; ResourceCache::get_cached_resources(&rsrc); - for (List >::Element *E=rsrc.front();E;E=E->next()) { + for (List >::Element *E = rsrc.front(); E; E = E->next()) { if (!E->get()->is_type("ImageTexture")) continue; @@ -841,27 +817,27 @@ void _OS::print_all_textures_by_size() { int fmt = E->get()->call("get_format"); _OSCoreBindImg img; - img.size=size; - img.fmt=fmt; - img.path=E->get()->get_path(); - img.vram=Image::get_image_data_size(img.size.width,img.size.height,Image::Format(img.fmt)); - img.id=E->get()->get_instance_ID(); - total+=img.vram; + img.size = size; + img.fmt = fmt; + img.path = E->get()->get_path(); + img.vram = Image::get_image_data_size(img.size.width, img.size.height, Image::Format(img.fmt)); + img.id = E->get()->get_instance_ID(); + total += img.vram; imgs.push_back(img); } } imgs.sort(); - for(List<_OSCoreBindImg>::Element *E=imgs.front();E;E=E->next()) { + for (List<_OSCoreBindImg>::Element *E = imgs.front(); E; E = E->next()) { - total-=E->get().vram; + total -= E->get().vram; } } -void _OS::print_resources_by_type(const Vector& p_types) { +void _OS::print_resources_by_type(const Vector &p_types) { - Map type_count; + Map type_count; List > resources; ResourceCache::get_cached_resources(&resources); @@ -869,13 +845,13 @@ void _OS::print_resources_by_type(const Vector& p_types) { List > rsrc; ResourceCache::get_cached_resources(&rsrc); - for (List >::Element *E=rsrc.front();E;E=E->next()) { + for (List >::Element *E = rsrc.front(); E; E = E->next()) { Ref r = E->get(); bool found = false; - for (int i=0; iis_type(p_types[i])) found = true; } @@ -883,20 +859,18 @@ void _OS::print_resources_by_type(const Vector& p_types) { continue; if (!type_count.has(r->get_type())) { - type_count[r->get_type()]=0; + type_count[r->get_type()] = 0; } - type_count[r->get_type()]++; } - }; bool _OS::has_virtual_keyboard() const { return OS::get_singleton()->has_virtual_keyboard(); } -void _OS::show_virtual_keyboard(const String& p_existing_text) { +void _OS::show_virtual_keyboard(const String &p_existing_text) { OS::get_singleton()->show_virtual_keyboard(p_existing_text, Rect2()); } @@ -904,7 +878,7 @@ void _OS::hide_virtual_keyboard() { OS::get_singleton()->hide_virtual_keyboard(); } -void _OS::print_all_resources(const String& p_to_file ) { +void _OS::print_all_resources(const String &p_to_file) { OS::get_singleton()->print_all_resources(p_to_file); } @@ -914,7 +888,7 @@ void _OS::print_resources_in_use(bool p_short) { OS::get_singleton()->print_resources_in_use(p_short); } -void _OS::dump_resources_to_file(const String& p_file) { +void _OS::dump_resources_to_file(const String &p_file) { OS::get_singleton()->dump_resources_to_file(p_file.utf8().get_data()); } @@ -965,7 +939,6 @@ bool _OS::is_debug_build() const { #else return false; #endif - } void _OS::set_screen_orientation(ScreenOrientation p_orientation) { @@ -1006,14 +979,14 @@ bool _OS::is_scancode_unicode(uint32_t p_unicode) const { return keycode_has_unicode(p_unicode); } -int _OS::find_scancode_from_string(const String& p_code) const { +int _OS::find_scancode_from_string(const String &p_code) const { return find_keycode(p_code); } -void _OS::alert(const String& p_alert,const String& p_title) { +void _OS::alert(const String &p_alert, const String &p_title) { - OS::get_singleton()->alert(p_alert,p_title); + OS::get_singleton()->alert(p_alert, p_title); } Dictionary _OS::get_engine_version() const { @@ -1021,238 +994,234 @@ Dictionary _OS::get_engine_version() const { return OS::get_singleton()->get_engine_version(); } -_OS *_OS::singleton=NULL; +_OS *_OS::singleton = NULL; void _OS::_bind_methods() { //ObjectTypeDB::bind_method(_MD("get_mouse_pos"),&_OS::get_mouse_pos); //ObjectTypeDB::bind_method(_MD("is_mouse_grab_enabled"),&_OS::is_mouse_grab_enabled); - ObjectTypeDB::bind_method(_MD("set_clipboard","clipboard"),&_OS::set_clipboard); - ObjectTypeDB::bind_method(_MD("get_clipboard"),&_OS::get_clipboard); + ObjectTypeDB::bind_method(_MD("set_clipboard", "clipboard"), &_OS::set_clipboard); + ObjectTypeDB::bind_method(_MD("get_clipboard"), &_OS::get_clipboard); - ObjectTypeDB::bind_method(_MD("set_video_mode","size","fullscreen","resizable","screen"),&_OS::set_video_mode,DEFVAL(0)); - ObjectTypeDB::bind_method(_MD("get_video_mode_size","screen"),&_OS::get_video_mode,DEFVAL(0)); - ObjectTypeDB::bind_method(_MD("is_video_mode_fullscreen","screen"),&_OS::is_video_mode_fullscreen,DEFVAL(0)); - ObjectTypeDB::bind_method(_MD("is_video_mode_resizable","screen"),&_OS::is_video_mode_resizable,DEFVAL(0)); - ObjectTypeDB::bind_method(_MD("get_fullscreen_mode_list","screen"),&_OS::get_fullscreen_mode_list,DEFVAL(0)); + ObjectTypeDB::bind_method(_MD("set_video_mode", "size", "fullscreen", "resizable", "screen"), &_OS::set_video_mode, DEFVAL(0)); + ObjectTypeDB::bind_method(_MD("get_video_mode_size", "screen"), &_OS::get_video_mode, DEFVAL(0)); + ObjectTypeDB::bind_method(_MD("is_video_mode_fullscreen", "screen"), &_OS::is_video_mode_fullscreen, DEFVAL(0)); + ObjectTypeDB::bind_method(_MD("is_video_mode_resizable", "screen"), &_OS::is_video_mode_resizable, DEFVAL(0)); + ObjectTypeDB::bind_method(_MD("get_fullscreen_mode_list", "screen"), &_OS::get_fullscreen_mode_list, DEFVAL(0)); - - ObjectTypeDB::bind_method(_MD("get_screen_count"),&_OS::get_screen_count); - ObjectTypeDB::bind_method(_MD("get_current_screen"),&_OS::get_current_screen); - ObjectTypeDB::bind_method(_MD("set_current_screen","screen"),&_OS::set_current_screen); - ObjectTypeDB::bind_method(_MD("get_screen_position","screen"),&_OS::get_screen_position,DEFVAL(0)); - ObjectTypeDB::bind_method(_MD("get_screen_size","screen"),&_OS::get_screen_size,DEFVAL(0)); - ObjectTypeDB::bind_method(_MD("get_screen_dpi","screen"),&_OS::get_screen_dpi,DEFVAL(0)); - ObjectTypeDB::bind_method(_MD("get_window_position"),&_OS::get_window_position); - ObjectTypeDB::bind_method(_MD("set_window_position","position"),&_OS::set_window_position); - ObjectTypeDB::bind_method(_MD("get_window_size"),&_OS::get_window_size); - ObjectTypeDB::bind_method(_MD("set_window_size","size"),&_OS::set_window_size); - ObjectTypeDB::bind_method(_MD("set_window_fullscreen","enabled"),&_OS::set_window_fullscreen); - ObjectTypeDB::bind_method(_MD("is_window_fullscreen"),&_OS::is_window_fullscreen); - ObjectTypeDB::bind_method(_MD("set_window_resizable","enabled"),&_OS::set_window_resizable); - ObjectTypeDB::bind_method(_MD("is_window_resizable"),&_OS::is_window_resizable); - ObjectTypeDB::bind_method(_MD("set_window_minimized", "enabled"),&_OS::set_window_minimized); - ObjectTypeDB::bind_method(_MD("is_window_minimized"),&_OS::is_window_minimized); - ObjectTypeDB::bind_method(_MD("set_window_maximized", "enabled"),&_OS::set_window_maximized); - ObjectTypeDB::bind_method(_MD("is_window_maximized"),&_OS::is_window_maximized); + ObjectTypeDB::bind_method(_MD("get_screen_count"), &_OS::get_screen_count); + ObjectTypeDB::bind_method(_MD("get_current_screen"), &_OS::get_current_screen); + ObjectTypeDB::bind_method(_MD("set_current_screen", "screen"), &_OS::set_current_screen); + ObjectTypeDB::bind_method(_MD("get_screen_position", "screen"), &_OS::get_screen_position, DEFVAL(0)); + ObjectTypeDB::bind_method(_MD("get_screen_size", "screen"), &_OS::get_screen_size, DEFVAL(0)); + ObjectTypeDB::bind_method(_MD("get_screen_dpi", "screen"), &_OS::get_screen_dpi, DEFVAL(0)); + ObjectTypeDB::bind_method(_MD("get_window_position"), &_OS::get_window_position); + ObjectTypeDB::bind_method(_MD("set_window_position", "position"), &_OS::set_window_position); + ObjectTypeDB::bind_method(_MD("get_window_size"), &_OS::get_window_size); + ObjectTypeDB::bind_method(_MD("set_window_size", "size"), &_OS::set_window_size); + ObjectTypeDB::bind_method(_MD("set_window_fullscreen", "enabled"), &_OS::set_window_fullscreen); + ObjectTypeDB::bind_method(_MD("is_window_fullscreen"), &_OS::is_window_fullscreen); + ObjectTypeDB::bind_method(_MD("set_window_resizable", "enabled"), &_OS::set_window_resizable); + ObjectTypeDB::bind_method(_MD("is_window_resizable"), &_OS::is_window_resizable); + ObjectTypeDB::bind_method(_MD("set_window_minimized", "enabled"), &_OS::set_window_minimized); + ObjectTypeDB::bind_method(_MD("is_window_minimized"), &_OS::is_window_minimized); + ObjectTypeDB::bind_method(_MD("set_window_maximized", "enabled"), &_OS::set_window_maximized); + ObjectTypeDB::bind_method(_MD("is_window_maximized"), &_OS::is_window_maximized); ObjectTypeDB::bind_method(_MD("request_attention"), &_OS::request_attention); ObjectTypeDB::bind_method(_MD("set_borderless_window", "borderless"), &_OS::set_borderless_window); ObjectTypeDB::bind_method(_MD("get_borderless_window"), &_OS::get_borderless_window); - ObjectTypeDB::bind_method(_MD("set_screen_orientation","orientation"),&_OS::set_screen_orientation); - ObjectTypeDB::bind_method(_MD("get_screen_orientation"),&_OS::get_screen_orientation); + ObjectTypeDB::bind_method(_MD("set_screen_orientation", "orientation"), &_OS::set_screen_orientation); + ObjectTypeDB::bind_method(_MD("get_screen_orientation"), &_OS::get_screen_orientation); - ObjectTypeDB::bind_method(_MD("set_keep_screen_on","enabled"),&_OS::set_keep_screen_on); - ObjectTypeDB::bind_method(_MD("is_keep_screen_on"),&_OS::is_keep_screen_on); + ObjectTypeDB::bind_method(_MD("set_keep_screen_on", "enabled"), &_OS::set_keep_screen_on); + ObjectTypeDB::bind_method(_MD("is_keep_screen_on"), &_OS::is_keep_screen_on); - ObjectTypeDB::bind_method(_MD("set_iterations_per_second","iterations_per_second"),&_OS::set_iterations_per_second); - ObjectTypeDB::bind_method(_MD("get_iterations_per_second"),&_OS::get_iterations_per_second); - ObjectTypeDB::bind_method(_MD("set_target_fps","target_fps"),&_OS::set_target_fps); - ObjectTypeDB::bind_method(_MD("get_target_fps"),&_OS::get_target_fps); + ObjectTypeDB::bind_method(_MD("set_iterations_per_second", "iterations_per_second"), &_OS::set_iterations_per_second); + ObjectTypeDB::bind_method(_MD("get_iterations_per_second"), &_OS::get_iterations_per_second); + ObjectTypeDB::bind_method(_MD("set_target_fps", "target_fps"), &_OS::set_target_fps); + ObjectTypeDB::bind_method(_MD("get_target_fps"), &_OS::get_target_fps); - ObjectTypeDB::bind_method(_MD("set_time_scale","time_scale"),&_OS::set_time_scale); - ObjectTypeDB::bind_method(_MD("get_time_scale"),&_OS::get_time_scale); + ObjectTypeDB::bind_method(_MD("set_time_scale", "time_scale"), &_OS::set_time_scale); + ObjectTypeDB::bind_method(_MD("get_time_scale"), &_OS::get_time_scale); - ObjectTypeDB::bind_method(_MD("has_touchscreen_ui_hint"),&_OS::has_touchscreen_ui_hint); + ObjectTypeDB::bind_method(_MD("has_touchscreen_ui_hint"), &_OS::has_touchscreen_ui_hint); - ObjectTypeDB::bind_method(_MD("set_window_title","title"),&_OS::set_window_title); + ObjectTypeDB::bind_method(_MD("set_window_title", "title"), &_OS::set_window_title); - ObjectTypeDB::bind_method(_MD("set_low_processor_usage_mode","enable"),&_OS::set_low_processor_usage_mode); - ObjectTypeDB::bind_method(_MD("is_in_low_processor_usage_mode"),&_OS::is_in_low_processor_usage_mode); + ObjectTypeDB::bind_method(_MD("set_low_processor_usage_mode", "enable"), &_OS::set_low_processor_usage_mode); + ObjectTypeDB::bind_method(_MD("is_in_low_processor_usage_mode"), &_OS::is_in_low_processor_usage_mode); - ObjectTypeDB::bind_method(_MD("get_processor_count"),&_OS::get_processor_count); + ObjectTypeDB::bind_method(_MD("get_processor_count"), &_OS::get_processor_count); - ObjectTypeDB::bind_method(_MD("get_executable_path"),&_OS::get_executable_path); - ObjectTypeDB::bind_method(_MD("execute","path","arguments","blocking","output"),&_OS::execute,DEFVAL(Array())); - ObjectTypeDB::bind_method(_MD("kill","pid"),&_OS::kill); - ObjectTypeDB::bind_method(_MD("shell_open","uri"),&_OS::shell_open); - ObjectTypeDB::bind_method(_MD("get_process_ID"),&_OS::get_process_ID); + ObjectTypeDB::bind_method(_MD("get_executable_path"), &_OS::get_executable_path); + ObjectTypeDB::bind_method(_MD("execute", "path", "arguments", "blocking", "output"), &_OS::execute, DEFVAL(Array())); + ObjectTypeDB::bind_method(_MD("kill", "pid"), &_OS::kill); + ObjectTypeDB::bind_method(_MD("shell_open", "uri"), &_OS::shell_open); + ObjectTypeDB::bind_method(_MD("get_process_ID"), &_OS::get_process_ID); - ObjectTypeDB::bind_method(_MD("get_environment","environment"),&_OS::get_environment); - ObjectTypeDB::bind_method(_MD("has_environment","environment"),&_OS::has_environment); + ObjectTypeDB::bind_method(_MD("get_environment", "environment"), &_OS::get_environment); + ObjectTypeDB::bind_method(_MD("has_environment", "environment"), &_OS::has_environment); - ObjectTypeDB::bind_method(_MD("get_name"),&_OS::get_name); - ObjectTypeDB::bind_method(_MD("get_cmdline_args"),&_OS::get_cmdline_args); - ObjectTypeDB::bind_method(_MD("get_main_loop"),&_OS::get_main_loop); + ObjectTypeDB::bind_method(_MD("get_name"), &_OS::get_name); + ObjectTypeDB::bind_method(_MD("get_cmdline_args"), &_OS::get_cmdline_args); + ObjectTypeDB::bind_method(_MD("get_main_loop"), &_OS::get_main_loop); - ObjectTypeDB::bind_method(_MD("get_datetime","utc"),&_OS::get_datetime,DEFVAL(false)); - ObjectTypeDB::bind_method(_MD("get_date","utc"),&_OS::get_date,DEFVAL(false)); - ObjectTypeDB::bind_method(_MD("get_time","utc"),&_OS::get_time,DEFVAL(false)); - ObjectTypeDB::bind_method(_MD("get_time_zone_info"),&_OS::get_time_zone_info); - ObjectTypeDB::bind_method(_MD("get_unix_time"),&_OS::get_unix_time); + ObjectTypeDB::bind_method(_MD("get_datetime", "utc"), &_OS::get_datetime, DEFVAL(false)); + ObjectTypeDB::bind_method(_MD("get_date", "utc"), &_OS::get_date, DEFVAL(false)); + ObjectTypeDB::bind_method(_MD("get_time", "utc"), &_OS::get_time, DEFVAL(false)); + ObjectTypeDB::bind_method(_MD("get_time_zone_info"), &_OS::get_time_zone_info); + ObjectTypeDB::bind_method(_MD("get_unix_time"), &_OS::get_unix_time); ObjectTypeDB::bind_method(_MD("get_datetime_from_unix_time", "unix_time_val"), &_OS::get_datetime_from_unix_time); ObjectTypeDB::bind_method(_MD("get_unix_time_from_datetime", "datetime"), &_OS::get_unix_time_from_datetime); ObjectTypeDB::bind_method(_MD("get_system_time_secs"), &_OS::get_system_time_secs); - ObjectTypeDB::bind_method(_MD("set_icon","icon"),&_OS::set_icon); + ObjectTypeDB::bind_method(_MD("set_icon", "icon"), &_OS::set_icon); - ObjectTypeDB::bind_method(_MD("get_exit_code"),&_OS::get_exit_code); - ObjectTypeDB::bind_method(_MD("set_exit_code","code"),&_OS::set_exit_code); + ObjectTypeDB::bind_method(_MD("get_exit_code"), &_OS::get_exit_code); + ObjectTypeDB::bind_method(_MD("set_exit_code", "code"), &_OS::set_exit_code); - ObjectTypeDB::bind_method(_MD("delay_usec","usec"),&_OS::delay_usec); - ObjectTypeDB::bind_method(_MD("delay_msec","msec"),&_OS::delay_msec); - ObjectTypeDB::bind_method(_MD("get_ticks_msec"),&_OS::get_ticks_msec); - ObjectTypeDB::bind_method(_MD("get_splash_tick_msec"),&_OS::get_splash_tick_msec); - ObjectTypeDB::bind_method(_MD("get_locale"),&_OS::get_locale); - ObjectTypeDB::bind_method(_MD("get_latin_keyboard_variant"),&_OS::get_latin_keyboard_variant); - ObjectTypeDB::bind_method(_MD("get_model_name"),&_OS::get_model_name); + ObjectTypeDB::bind_method(_MD("delay_usec", "usec"), &_OS::delay_usec); + ObjectTypeDB::bind_method(_MD("delay_msec", "msec"), &_OS::delay_msec); + ObjectTypeDB::bind_method(_MD("get_ticks_msec"), &_OS::get_ticks_msec); + ObjectTypeDB::bind_method(_MD("get_splash_tick_msec"), &_OS::get_splash_tick_msec); + ObjectTypeDB::bind_method(_MD("get_locale"), &_OS::get_locale); + ObjectTypeDB::bind_method(_MD("get_latin_keyboard_variant"), &_OS::get_latin_keyboard_variant); + ObjectTypeDB::bind_method(_MD("get_model_name"), &_OS::get_model_name); - ObjectTypeDB::bind_method(_MD("get_custom_level"),&_OS::get_custom_level); + ObjectTypeDB::bind_method(_MD("get_custom_level"), &_OS::get_custom_level); - ObjectTypeDB::bind_method(_MD("can_draw"),&_OS::can_draw); - ObjectTypeDB::bind_method(_MD("get_frames_drawn"),&_OS::get_frames_drawn); - ObjectTypeDB::bind_method(_MD("is_stdout_verbose"),&_OS::is_stdout_verbose); + ObjectTypeDB::bind_method(_MD("can_draw"), &_OS::can_draw); + ObjectTypeDB::bind_method(_MD("get_frames_drawn"), &_OS::get_frames_drawn); + ObjectTypeDB::bind_method(_MD("is_stdout_verbose"), &_OS::is_stdout_verbose); - ObjectTypeDB::bind_method(_MD("can_use_threads"),&_OS::can_use_threads); + ObjectTypeDB::bind_method(_MD("can_use_threads"), &_OS::can_use_threads); - ObjectTypeDB::bind_method(_MD("is_debug_build"),&_OS::is_debug_build); + ObjectTypeDB::bind_method(_MD("is_debug_build"), &_OS::is_debug_build); //ObjectTypeDB::bind_method(_MD("get_mouse_button_state"),&_OS::get_mouse_button_state); - ObjectTypeDB::bind_method(_MD("dump_memory_to_file","file"),&_OS::dump_memory_to_file); - ObjectTypeDB::bind_method(_MD("dump_resources_to_file","file"),&_OS::dump_resources_to_file); - ObjectTypeDB::bind_method(_MD("has_virtual_keyboard"),&_OS::has_virtual_keyboard); - ObjectTypeDB::bind_method(_MD("show_virtual_keyboard", "existing_text"),&_OS::show_virtual_keyboard,DEFVAL("")); - ObjectTypeDB::bind_method(_MD("hide_virtual_keyboard"),&_OS::hide_virtual_keyboard); - ObjectTypeDB::bind_method(_MD("print_resources_in_use","short"),&_OS::print_resources_in_use,DEFVAL(false)); - ObjectTypeDB::bind_method(_MD("print_all_resources","tofile"),&_OS::print_all_resources,DEFVAL("")); + ObjectTypeDB::bind_method(_MD("dump_memory_to_file", "file"), &_OS::dump_memory_to_file); + ObjectTypeDB::bind_method(_MD("dump_resources_to_file", "file"), &_OS::dump_resources_to_file); + ObjectTypeDB::bind_method(_MD("has_virtual_keyboard"), &_OS::has_virtual_keyboard); + ObjectTypeDB::bind_method(_MD("show_virtual_keyboard", "existing_text"), &_OS::show_virtual_keyboard, DEFVAL("")); + ObjectTypeDB::bind_method(_MD("hide_virtual_keyboard"), &_OS::hide_virtual_keyboard); + ObjectTypeDB::bind_method(_MD("print_resources_in_use", "short"), &_OS::print_resources_in_use, DEFVAL(false)); + ObjectTypeDB::bind_method(_MD("print_all_resources", "tofile"), &_OS::print_all_resources, DEFVAL("")); - ObjectTypeDB::bind_method(_MD("get_static_memory_usage"),&_OS::get_static_memory_usage); - ObjectTypeDB::bind_method(_MD("get_static_memory_peak_usage"),&_OS::get_static_memory_peak_usage); - ObjectTypeDB::bind_method(_MD("get_dynamic_memory_usage"),&_OS::get_dynamic_memory_usage); + ObjectTypeDB::bind_method(_MD("get_static_memory_usage"), &_OS::get_static_memory_usage); + ObjectTypeDB::bind_method(_MD("get_static_memory_peak_usage"), &_OS::get_static_memory_peak_usage); + ObjectTypeDB::bind_method(_MD("get_dynamic_memory_usage"), &_OS::get_dynamic_memory_usage); - ObjectTypeDB::bind_method(_MD("get_data_dir"),&_OS::get_data_dir); - ObjectTypeDB::bind_method(_MD("get_system_dir","dir"),&_OS::get_system_dir); - ObjectTypeDB::bind_method(_MD("get_unique_ID"),&_OS::get_unique_ID); + ObjectTypeDB::bind_method(_MD("get_data_dir"), &_OS::get_data_dir); + ObjectTypeDB::bind_method(_MD("get_system_dir", "dir"), &_OS::get_system_dir); + ObjectTypeDB::bind_method(_MD("get_unique_ID"), &_OS::get_unique_ID); - ObjectTypeDB::bind_method(_MD("is_ok_left_and_cancel_right"),&_OS::is_ok_left_and_cancel_right); + ObjectTypeDB::bind_method(_MD("is_ok_left_and_cancel_right"), &_OS::is_ok_left_and_cancel_right); - ObjectTypeDB::bind_method(_MD("get_frames_per_second"),&_OS::get_frames_per_second); + ObjectTypeDB::bind_method(_MD("get_frames_per_second"), &_OS::get_frames_per_second); - ObjectTypeDB::bind_method(_MD("print_all_textures_by_size"),&_OS::print_all_textures_by_size); - ObjectTypeDB::bind_method(_MD("print_resources_by_type","types"),&_OS::print_resources_by_type); + ObjectTypeDB::bind_method(_MD("print_all_textures_by_size"), &_OS::print_all_textures_by_size); + ObjectTypeDB::bind_method(_MD("print_resources_by_type", "types"), &_OS::print_resources_by_type); - ObjectTypeDB::bind_method(_MD("native_video_play","path","volume","audio_track","subtitle_track"),&_OS::native_video_play); - ObjectTypeDB::bind_method(_MD("native_video_is_playing"),&_OS::native_video_is_playing); - ObjectTypeDB::bind_method(_MD("native_video_stop"),&_OS::native_video_stop); - ObjectTypeDB::bind_method(_MD("native_video_pause"),&_OS::native_video_pause); - ObjectTypeDB::bind_method(_MD("native_video_unpause"),&_OS::native_video_unpause); + ObjectTypeDB::bind_method(_MD("native_video_play", "path", "volume", "audio_track", "subtitle_track"), &_OS::native_video_play); + ObjectTypeDB::bind_method(_MD("native_video_is_playing"), &_OS::native_video_is_playing); + ObjectTypeDB::bind_method(_MD("native_video_stop"), &_OS::native_video_stop); + ObjectTypeDB::bind_method(_MD("native_video_pause"), &_OS::native_video_pause); + ObjectTypeDB::bind_method(_MD("native_video_unpause"), &_OS::native_video_unpause); - ObjectTypeDB::bind_method(_MD("get_scancode_string","code"),&_OS::get_scancode_string); - ObjectTypeDB::bind_method(_MD("is_scancode_unicode","code"),&_OS::is_scancode_unicode); - ObjectTypeDB::bind_method(_MD("find_scancode_from_string","string"),&_OS::find_scancode_from_string); + ObjectTypeDB::bind_method(_MD("get_scancode_string", "code"), &_OS::get_scancode_string); + ObjectTypeDB::bind_method(_MD("is_scancode_unicode", "code"), &_OS::is_scancode_unicode); + ObjectTypeDB::bind_method(_MD("find_scancode_from_string", "string"), &_OS::find_scancode_from_string); - ObjectTypeDB::bind_method(_MD("set_use_file_access_save_and_swap","enabled"),&_OS::set_use_file_access_save_and_swap); + ObjectTypeDB::bind_method(_MD("set_use_file_access_save_and_swap", "enabled"), &_OS::set_use_file_access_save_and_swap); - ObjectTypeDB::bind_method(_MD("alert","text","title"),&_OS::alert,DEFVAL("Alert!")); + ObjectTypeDB::bind_method(_MD("alert", "text", "title"), &_OS::alert, DEFVAL("Alert!")); - ObjectTypeDB::bind_method(_MD("set_thread_name","name"),&_OS::set_thread_name); + ObjectTypeDB::bind_method(_MD("set_thread_name", "name"), &_OS::set_thread_name); - ObjectTypeDB::bind_method(_MD("set_use_vsync","enable"),&_OS::set_use_vsync); - ObjectTypeDB::bind_method(_MD("is_vsync_enabled"),&_OS::is_vsync_enabled); + ObjectTypeDB::bind_method(_MD("set_use_vsync", "enable"), &_OS::set_use_vsync); + ObjectTypeDB::bind_method(_MD("is_vsync_enabled"), &_OS::is_vsync_enabled); - ObjectTypeDB::bind_method(_MD("get_engine_version"),&_OS::get_engine_version); + ObjectTypeDB::bind_method(_MD("get_engine_version"), &_OS::get_engine_version); - BIND_CONSTANT( DAY_SUNDAY ); - BIND_CONSTANT( DAY_MONDAY ); - BIND_CONSTANT( DAY_TUESDAY ); - BIND_CONSTANT( DAY_WEDNESDAY ); - BIND_CONSTANT( DAY_THURSDAY ); - BIND_CONSTANT( DAY_FRIDAY ); - BIND_CONSTANT( DAY_SATURDAY ); + BIND_CONSTANT(DAY_SUNDAY); + BIND_CONSTANT(DAY_MONDAY); + BIND_CONSTANT(DAY_TUESDAY); + BIND_CONSTANT(DAY_WEDNESDAY); + BIND_CONSTANT(DAY_THURSDAY); + BIND_CONSTANT(DAY_FRIDAY); + BIND_CONSTANT(DAY_SATURDAY); - BIND_CONSTANT( MONTH_JANUARY ); - BIND_CONSTANT( MONTH_FEBRUARY ); - BIND_CONSTANT( MONTH_MARCH ); - BIND_CONSTANT( MONTH_APRIL ); - BIND_CONSTANT( MONTH_MAY ); - BIND_CONSTANT( MONTH_JUNE ); - BIND_CONSTANT( MONTH_JULY ); - BIND_CONSTANT( MONTH_AUGUST ); - BIND_CONSTANT( MONTH_SEPTEMBER ); - BIND_CONSTANT( MONTH_OCTOBER ); - BIND_CONSTANT( MONTH_NOVEMBER ); - BIND_CONSTANT( MONTH_DECEMBER ); + BIND_CONSTANT(MONTH_JANUARY); + BIND_CONSTANT(MONTH_FEBRUARY); + BIND_CONSTANT(MONTH_MARCH); + BIND_CONSTANT(MONTH_APRIL); + BIND_CONSTANT(MONTH_MAY); + BIND_CONSTANT(MONTH_JUNE); + BIND_CONSTANT(MONTH_JULY); + BIND_CONSTANT(MONTH_AUGUST); + BIND_CONSTANT(MONTH_SEPTEMBER); + BIND_CONSTANT(MONTH_OCTOBER); + BIND_CONSTANT(MONTH_NOVEMBER); + BIND_CONSTANT(MONTH_DECEMBER); - BIND_CONSTANT( SCREEN_ORIENTATION_LANDSCAPE ); - BIND_CONSTANT( SCREEN_ORIENTATION_PORTRAIT ); - BIND_CONSTANT( SCREEN_ORIENTATION_REVERSE_LANDSCAPE ); - BIND_CONSTANT( SCREEN_ORIENTATION_REVERSE_PORTRAIT ); - BIND_CONSTANT( SCREEN_ORIENTATION_SENSOR_LANDSCAPE ); - BIND_CONSTANT( SCREEN_ORIENTATION_SENSOR_PORTRAIT ); - BIND_CONSTANT( SCREEN_ORIENTATION_SENSOR ); - - BIND_CONSTANT( SYSTEM_DIR_DESKTOP); - BIND_CONSTANT( SYSTEM_DIR_DCIM ); - BIND_CONSTANT( SYSTEM_DIR_DOCUMENTS ); - BIND_CONSTANT( SYSTEM_DIR_DOWNLOADS ); - BIND_CONSTANT( SYSTEM_DIR_MOVIES ); - BIND_CONSTANT( SYSTEM_DIR_MUSIC ); - BIND_CONSTANT( SYSTEM_DIR_PICTURES ); - BIND_CONSTANT( SYSTEM_DIR_RINGTONES ); + BIND_CONSTANT(SCREEN_ORIENTATION_LANDSCAPE); + BIND_CONSTANT(SCREEN_ORIENTATION_PORTRAIT); + BIND_CONSTANT(SCREEN_ORIENTATION_REVERSE_LANDSCAPE); + BIND_CONSTANT(SCREEN_ORIENTATION_REVERSE_PORTRAIT); + BIND_CONSTANT(SCREEN_ORIENTATION_SENSOR_LANDSCAPE); + BIND_CONSTANT(SCREEN_ORIENTATION_SENSOR_PORTRAIT); + BIND_CONSTANT(SCREEN_ORIENTATION_SENSOR); + BIND_CONSTANT(SYSTEM_DIR_DESKTOP); + BIND_CONSTANT(SYSTEM_DIR_DCIM); + BIND_CONSTANT(SYSTEM_DIR_DOCUMENTS); + BIND_CONSTANT(SYSTEM_DIR_DOWNLOADS); + BIND_CONSTANT(SYSTEM_DIR_MOVIES); + BIND_CONSTANT(SYSTEM_DIR_MUSIC); + BIND_CONSTANT(SYSTEM_DIR_PICTURES); + BIND_CONSTANT(SYSTEM_DIR_RINGTONES); } _OS::_OS() { - singleton=this; + singleton = this; } - ///////////////////// GEOMETRY - -_Geometry *_Geometry::singleton=NULL; +_Geometry *_Geometry::singleton = NULL; _Geometry *_Geometry::get_singleton() { return singleton; } -DVector _Geometry::build_box_planes(const Vector3& p_extents) { +DVector _Geometry::build_box_planes(const Vector3 &p_extents) { return Geometry::build_box_planes(p_extents); } DVector _Geometry::build_cylinder_planes(float p_radius, float p_height, int p_sides, Vector3::Axis p_axis) { - return Geometry::build_cylinder_planes(p_radius,p_height,p_sides,p_axis); + return Geometry::build_cylinder_planes(p_radius, p_height, p_sides, p_axis); } DVector _Geometry::build_capsule_planes(float p_radius, float p_height, int p_sides, int p_lats, Vector3::Axis p_axis) { - return Geometry::build_capsule_planes(p_radius,p_height,p_sides,p_lats,p_axis); + return Geometry::build_capsule_planes(p_radius, p_height, p_sides, p_lats, p_axis); } -real_t _Geometry::segment_intersects_circle(const Vector2& p_from, const Vector2& p_to, const Vector2& p_circle_pos, real_t p_circle_radius) { +real_t _Geometry::segment_intersects_circle(const Vector2 &p_from, const Vector2 &p_to, const Vector2 &p_circle_pos, real_t p_circle_radius) { - return Geometry::segment_intersects_circle(p_from,p_to,p_circle_pos,p_circle_radius); + return Geometry::segment_intersects_circle(p_from, p_to, p_circle_pos, p_circle_radius); } -Variant _Geometry::segment_intersects_segment_2d(const Vector2& p_from_a,const Vector2& p_to_a,const Vector2& p_from_b,const Vector2& p_to_b) { +Variant _Geometry::segment_intersects_segment_2d(const Vector2 &p_from_a, const Vector2 &p_to_a, const Vector2 &p_from_b, const Vector2 &p_to_b) { Vector2 result; if (Geometry::segment_intersects_segment_2d(p_from_a, p_to_a, p_from_b, p_to_b, &result)) { @@ -1263,122 +1232,117 @@ Variant _Geometry::segment_intersects_segment_2d(const Vector2& p_from_a,const V }; }; -DVector _Geometry::get_closest_points_between_segments_2d( const Vector2& p1,const Vector2& q1, const Vector2& p2,const Vector2& q2) { +DVector _Geometry::get_closest_points_between_segments_2d(const Vector2 &p1, const Vector2 &q1, const Vector2 &p2, const Vector2 &q2) { Vector2 r1, r2; - Geometry::get_closest_points_between_segments(p1,q1,p2,q2,r1,r2); + Geometry::get_closest_points_between_segments(p1, q1, p2, q2, r1, r2); DVector r; r.resize(2); - r.set(0,r1); - r.set(1,r2); + r.set(0, r1); + r.set(1, r2); return r; } -DVector _Geometry::get_closest_points_between_segments(const Vector3& p1,const Vector3& p2,const Vector3& q1,const Vector3& q2) { +DVector _Geometry::get_closest_points_between_segments(const Vector3 &p1, const Vector3 &p2, const Vector3 &q1, const Vector3 &q2) { Vector3 r1, r2; - Geometry::get_closest_points_between_segments(p1,p2,q1,q2,r1,r2); + Geometry::get_closest_points_between_segments(p1, p2, q1, q2, r1, r2); DVector r; r.resize(2); - r.set(0,r1); - r.set(1,r2); + r.set(0, r1); + r.set(1, r2); return r; - } -Vector2 _Geometry::get_closest_point_to_segment_2d(const Vector2& p_point, const Vector2& p_a,const Vector2& p_b) { +Vector2 _Geometry::get_closest_point_to_segment_2d(const Vector2 &p_point, const Vector2 &p_a, const Vector2 &p_b) { - Vector2 s[2]={p_a,p_b}; - return Geometry::get_closest_point_to_segment_2d(p_point,s); + Vector2 s[2] = { p_a, p_b }; + return Geometry::get_closest_point_to_segment_2d(p_point, s); } -Vector3 _Geometry::get_closest_point_to_segment(const Vector3& p_point, const Vector3& p_a,const Vector3& p_b) { +Vector3 _Geometry::get_closest_point_to_segment(const Vector3 &p_point, const Vector3 &p_a, const Vector3 &p_b) { - Vector3 s[2]={p_a,p_b}; - return Geometry::get_closest_point_to_segment(p_point,s); + Vector3 s[2] = { p_a, p_b }; + return Geometry::get_closest_point_to_segment(p_point, s); } -Vector2 _Geometry::get_closest_point_to_segment_uncapped_2d(const Vector2& p_point, const Vector2& p_a,const Vector2& p_b) { +Vector2 _Geometry::get_closest_point_to_segment_uncapped_2d(const Vector2 &p_point, const Vector2 &p_a, const Vector2 &p_b) { - Vector2 s[2]={p_a,p_b}; - return Geometry::get_closest_point_to_segment_uncapped_2d(p_point,s); + Vector2 s[2] = { p_a, p_b }; + return Geometry::get_closest_point_to_segment_uncapped_2d(p_point, s); } -Vector3 _Geometry::get_closest_point_to_segment_uncapped(const Vector3& p_point, const Vector3& p_a,const Vector3& p_b) { +Vector3 _Geometry::get_closest_point_to_segment_uncapped(const Vector3 &p_point, const Vector3 &p_a, const Vector3 &p_b) { - Vector3 s[2]={p_a,p_b}; - return Geometry::get_closest_point_to_segment_uncapped(p_point,s); + Vector3 s[2] = { p_a, p_b }; + return Geometry::get_closest_point_to_segment_uncapped(p_point, s); } -Variant _Geometry::ray_intersects_triangle( const Vector3& p_from, const Vector3& p_dir, const Vector3& p_v0,const Vector3& p_v1,const Vector3& p_v2) { +Variant _Geometry::ray_intersects_triangle(const Vector3 &p_from, const Vector3 &p_dir, const Vector3 &p_v0, const Vector3 &p_v1, const Vector3 &p_v2) { Vector3 res; - if (Geometry::ray_intersects_triangle(p_from,p_dir,p_v0,p_v1,p_v2,&res)) + if (Geometry::ray_intersects_triangle(p_from, p_dir, p_v0, p_v1, p_v2, &res)) return res; else return Variant(); - - } -Variant _Geometry::segment_intersects_triangle( const Vector3& p_from, const Vector3& p_to, const Vector3& p_v0,const Vector3& p_v1,const Vector3& p_v2) { +Variant _Geometry::segment_intersects_triangle(const Vector3 &p_from, const Vector3 &p_to, const Vector3 &p_v0, const Vector3 &p_v1, const Vector3 &p_v2) { Vector3 res; - if (Geometry::segment_intersects_triangle(p_from,p_to,p_v0,p_v1,p_v2,&res)) + if (Geometry::segment_intersects_triangle(p_from, p_to, p_v0, p_v1, p_v2, &res)) return res; else return Variant(); - } -bool _Geometry::point_is_inside_triangle(const Vector2& s, const Vector2& a, const Vector2& b, const Vector2& c) const { +bool _Geometry::point_is_inside_triangle(const Vector2 &s, const Vector2 &a, const Vector2 &b, const Vector2 &c) const { - return Geometry::is_point_in_triangle(s,a,b,c); + return Geometry::is_point_in_triangle(s, a, b, c); } -DVector _Geometry::segment_intersects_sphere( const Vector3& p_from, const Vector3& p_to, const Vector3& p_sphere_pos,real_t p_sphere_radius) { +DVector _Geometry::segment_intersects_sphere(const Vector3 &p_from, const Vector3 &p_to, const Vector3 &p_sphere_pos, real_t p_sphere_radius) { DVector r; - Vector3 res,norm; - if (!Geometry::segment_intersects_sphere(p_from,p_to,p_sphere_pos,p_sphere_radius,&res,&norm)) + Vector3 res, norm; + if (!Geometry::segment_intersects_sphere(p_from, p_to, p_sphere_pos, p_sphere_radius, &res, &norm)) return r; r.resize(2); - r.set(0,res); - r.set(1,norm); + r.set(0, res); + r.set(1, norm); return r; } -DVector _Geometry::segment_intersects_cylinder( const Vector3& p_from, const Vector3& p_to, float p_height,float p_radius) { +DVector _Geometry::segment_intersects_cylinder(const Vector3 &p_from, const Vector3 &p_to, float p_height, float p_radius) { DVector r; - Vector3 res,norm; - if (!Geometry::segment_intersects_cylinder(p_from,p_to,p_height,p_radius,&res,&norm)) + Vector3 res, norm; + if (!Geometry::segment_intersects_cylinder(p_from, p_to, p_height, p_radius, &res, &norm)) return r; r.resize(2); - r.set(0,res); - r.set(1,norm); + r.set(0, res); + r.set(1, norm); return r; - } -DVector _Geometry::segment_intersects_convex(const Vector3& p_from, const Vector3& p_to,const Vector& p_planes) { +DVector _Geometry::segment_intersects_convex(const Vector3 &p_from, const Vector3 &p_to, const Vector &p_planes) { DVector r; - Vector3 res,norm; - if (!Geometry::segment_intersects_convex(p_from,p_to,p_planes.ptr(),p_planes.size(),&res,&norm)) + Vector3 res, norm; + if (!Geometry::segment_intersects_convex(p_from, p_to, p_planes.ptr(), p_planes.size(), &res, &norm)) return r; r.resize(2); - r.set(0,res); - r.set(1,norm); + r.set(0, res); + r.set(1, norm); return r; } -Vector _Geometry::triangulate_polygon(const Vector& p_polygon) { +Vector _Geometry::triangulate_polygon(const Vector &p_polygon) { return Geometry::triangulate_polygon(p_polygon); } -Dictionary _Geometry::make_atlas(const Vector& p_rects) { +Dictionary _Geometry::make_atlas(const Vector &p_rects) { Dictionary ret; Vector rects; - for (int i=0; i& p_rects) { Size2 r_size = size; Vector r_result; - for (int i=0; i &p_key) { - -Error _File::open_encrypted(const String& p_path, int p_mode_flags,const Vector& p_key) { - - Error err = open(p_path,p_mode_flags); + Error err = open(p_path, p_mode_flags); if (err) return err; - FileAccessEncrypted *fae = memnew( FileAccessEncrypted ); - err = fae->open_and_parse(f,p_key,(p_mode_flags==WRITE)?FileAccessEncrypted::MODE_WRITE_AES256:FileAccessEncrypted::MODE_READ); + FileAccessEncrypted *fae = memnew(FileAccessEncrypted); + err = fae->open_and_parse(f, p_key, (p_mode_flags == WRITE) ? FileAccessEncrypted::MODE_WRITE_AES256 : FileAccessEncrypted::MODE_READ); if (err) { memdelete(fae); close(); return err; } - f=fae; + f = fae; return OK; } -Error _File::open_encrypted_pass(const String& p_path, int p_mode_flags,const String& p_pass) { +Error _File::open_encrypted_pass(const String &p_path, int p_mode_flags, const String &p_pass) { - Error err = open(p_path,p_mode_flags); + Error err = open(p_path, p_mode_flags); if (err) return err; - FileAccessEncrypted *fae = memnew( FileAccessEncrypted ); - err = fae->open_and_parse_password(f,p_pass,(p_mode_flags==WRITE)?FileAccessEncrypted::MODE_WRITE_AES256:FileAccessEncrypted::MODE_READ); + FileAccessEncrypted *fae = memnew(FileAccessEncrypted); + err = fae->open_and_parse_password(f, p_pass, (p_mode_flags == WRITE) ? FileAccessEncrypted::MODE_WRITE_AES256 : FileAccessEncrypted::MODE_READ); if (err) { memdelete(fae); close(); return err; } - f=fae; + f = fae; return OK; - } - -Error _File::open(const String& p_path, int p_mode_flags) { +Error _File::open(const String &p_path, int p_mode_flags) { close(); Error err; - f = FileAccess::open(p_path,p_mode_flags,&err); + f = FileAccess::open(p_path, p_mode_flags, &err); if (f) f->set_endian_swap(eswap); return err; - } -void _File::close(){ +void _File::close() { if (f) memdelete(f); - f=NULL; + f = NULL; } -bool _File::is_open() const{ +bool _File::is_open() const { - - return f!=NULL; + return f != NULL; } -void _File::seek(int64_t p_position){ +void _File::seek(int64_t p_position) { ERR_FAIL_COND(!f); f->seek(p_position); - } -void _File::seek_end(int64_t p_position){ - +void _File::seek_end(int64_t p_position) { ERR_FAIL_COND(!f); f->seek_end(p_position); } -int64_t _File::get_pos() const{ +int64_t _File::get_pos() const { - - ERR_FAIL_COND_V(!f,0); + ERR_FAIL_COND_V(!f, 0); return f->get_pos(); } -int64_t _File::get_len() const{ +int64_t _File::get_len() const { - ERR_FAIL_COND_V(!f,0); + ERR_FAIL_COND_V(!f, 0); return f->get_len(); } -bool _File::eof_reached() const{ +bool _File::eof_reached() const { - ERR_FAIL_COND_V(!f,false); + ERR_FAIL_COND_V(!f, false); return f->eof_reached(); } -uint8_t _File::get_8() const{ +uint8_t _File::get_8() const { - ERR_FAIL_COND_V(!f,0); + ERR_FAIL_COND_V(!f, 0); return f->get_8(); - } -uint16_t _File::get_16() const{ +uint16_t _File::get_16() const { - ERR_FAIL_COND_V(!f,0); + ERR_FAIL_COND_V(!f, 0); return f->get_16(); - } -uint32_t _File::get_32() const{ +uint32_t _File::get_32() const { - ERR_FAIL_COND_V(!f,0); + ERR_FAIL_COND_V(!f, 0); return f->get_32(); - } -uint64_t _File::get_64() const{ +uint64_t _File::get_64() const { - ERR_FAIL_COND_V(!f,0); + ERR_FAIL_COND_V(!f, 0); return f->get_64(); - } -float _File::get_float() const{ +float _File::get_float() const { - ERR_FAIL_COND_V(!f,0); + ERR_FAIL_COND_V(!f, 0); return f->get_float(); - } -double _File::get_double() const{ +double _File::get_double() const { - - ERR_FAIL_COND_V(!f,0); + ERR_FAIL_COND_V(!f, 0); return f->get_double(); } -real_t _File::get_real() const{ +real_t _File::get_real() const { - - ERR_FAIL_COND_V(!f,0); + ERR_FAIL_COND_V(!f, 0); return f->get_real(); } -DVector _File::get_buffer(int p_length) const{ +DVector _File::get_buffer(int p_length) const { DVector data; - ERR_FAIL_COND_V(!f,data); + ERR_FAIL_COND_V(!f, data); - ERR_FAIL_COND_V(p_length<0,data); - if (p_length==0) + ERR_FAIL_COND_V(p_length < 0, data); + if (p_length == 0) return data; Error err = data.resize(p_length); - ERR_FAIL_COND_V(err!=OK,data); + ERR_FAIL_COND_V(err != OK, data); DVector::Write w = data.write(); - int len = f->get_buffer(&w[0],p_length); - ERR_FAIL_COND_V( len < 0 , DVector()); + int len = f->get_buffer(&w[0], p_length); + ERR_FAIL_COND_V(len < 0, DVector()); w = DVector::Write(); @@ -1606,10 +1548,8 @@ DVector _File::get_buffer(int p_length) const{ data.resize(p_length); return data; - } - String _File::get_as_text() const { ERR_FAIL_COND_V(!f, String()); @@ -1619,42 +1559,35 @@ String _File::get_as_text() const { f->seek(0); String l = get_line(); - while(!eof_reached()) { - text+=l+"\n"; + while (!eof_reached()) { + text += l + "\n"; l = get_line(); } - text+=l; + text += l; f->seek(original_pos); return text; - - } - -String _File::get_md5(const String& p_path) const { +String _File::get_md5(const String &p_path) const { return FileAccess::get_md5(p_path); - } -String _File::get_sha256(const String& p_path) const { +String _File::get_sha256(const String &p_path) const { return FileAccess::get_sha256(p_path); - } +String _File::get_line() const { -String _File::get_line() const{ - - ERR_FAIL_COND_V(!f,String()); + ERR_FAIL_COND_V(!f, String()); return f->get_line(); - } Vector _File::get_csv_line(String delim) const { - ERR_FAIL_COND_V(!f,Vector()); + ERR_FAIL_COND_V(!f, Vector()); return f->get_csv_line(delim); } @@ -1663,79 +1596,76 @@ Vector _File::get_csv_line(String delim) const { * this flags get reset to false (little endian) on each open */ -void _File::set_endian_swap(bool p_swap){ +void _File::set_endian_swap(bool p_swap) { - - eswap=p_swap; + eswap = p_swap; if (f) f->set_endian_swap(p_swap); - } -bool _File::get_endian_swap(){ - +bool _File::get_endian_swap() { return eswap; } -Error _File::get_error() const{ +Error _File::get_error() const { if (!f) return ERR_UNCONFIGURED; return f->get_error(); } -void _File::store_8(uint8_t p_dest){ +void _File::store_8(uint8_t p_dest) { ERR_FAIL_COND(!f); f->store_8(p_dest); } -void _File::store_16(uint16_t p_dest){ +void _File::store_16(uint16_t p_dest) { ERR_FAIL_COND(!f); f->store_16(p_dest); } -void _File::store_32(uint32_t p_dest){ +void _File::store_32(uint32_t p_dest) { ERR_FAIL_COND(!f); f->store_32(p_dest); } -void _File::store_64(uint64_t p_dest){ +void _File::store_64(uint64_t p_dest) { ERR_FAIL_COND(!f); f->store_64(p_dest); } -void _File::store_float(float p_dest){ +void _File::store_float(float p_dest) { ERR_FAIL_COND(!f); f->store_float(p_dest); } -void _File::store_double(double p_dest){ +void _File::store_double(double p_dest) { ERR_FAIL_COND(!f); f->store_double(p_dest); } -void _File::store_real(real_t p_real){ +void _File::store_real(real_t p_real) { ERR_FAIL_COND(!f); f->store_real(p_real); } -void _File::store_string(const String& p_string){ +void _File::store_string(const String &p_string) { ERR_FAIL_COND(!f); f->store_string(p_string); } -void _File::store_pascal_string(const String& p_string) { +void _File::store_pascal_string(const String &p_string) { ERR_FAIL_COND(!f); @@ -1749,46 +1679,44 @@ String _File::get_pascal_string() { return f->get_pascal_string(); }; -void _File::store_line(const String& p_string){ +void _File::store_line(const String &p_string) { ERR_FAIL_COND(!f); f->store_line(p_string); } -void _File::store_buffer(const DVector& p_buffer){ +void _File::store_buffer(const DVector &p_buffer) { ERR_FAIL_COND(!f); int len = p_buffer.size(); - if (len==0) + if (len == 0) return; DVector::Read r = p_buffer.read(); - f->store_buffer(&r[0],len); + f->store_buffer(&r[0], len); } -bool _File::file_exists(const String& p_name) const{ +bool _File::file_exists(const String &p_name) const { return FileAccess::exists(p_name); - - } -void _File::store_var(const Variant& p_var) { +void _File::store_var(const Variant &p_var) { ERR_FAIL_COND(!f); int len; - Error err = encode_variant(p_var,NULL,len); - ERR_FAIL_COND( err != OK ); + Error err = encode_variant(p_var, NULL, len); + ERR_FAIL_COND(err != OK); DVector buff; buff.resize(len); DVector::Write w = buff.write(); - err = encode_variant(p_var,&w[0],len); - ERR_FAIL_COND( err != OK ); - w=DVector::Write(); + err = encode_variant(p_var, &w[0], len); + ERR_FAIL_COND(err != OK); + w = DVector::Write(); store_32(len); store_buffer(buff); @@ -1796,7 +1724,7 @@ void _File::store_var(const Variant& p_var) { Variant _File::get_var() const { - ERR_FAIL_COND_V(!f,Variant()); + ERR_FAIL_COND_V(!f, Variant()); uint32_t len = get_32(); DVector buff = get_buffer(len); ERR_FAIL_COND_V(buff.size() != len, Variant()); @@ -1804,8 +1732,8 @@ Variant _File::get_var() const { DVector::Read r = buff.read(); Variant v; - Error err = decode_variant(v,&r[0],len); - ERR_FAIL_COND_V( err!=OK, Variant() ); + Error err = decode_variant(v, &r[0], len); + ERR_FAIL_COND_V(err != OK, Variant()); return v; } @@ -1817,164 +1745,156 @@ uint64_t _File::get_modified_time(const String &p_file) const { void _File::_bind_methods() { + ObjectTypeDB::bind_method(_MD("open_encrypted", "path", "mode_flags", "key"), &_File::open_encrypted); + ObjectTypeDB::bind_method(_MD("open_encrypted_with_pass", "path", "mode_flags", "pass"), &_File::open_encrypted_pass); - ObjectTypeDB::bind_method(_MD("open_encrypted","path","mode_flags","key"),&_File::open_encrypted); - ObjectTypeDB::bind_method(_MD("open_encrypted_with_pass","path","mode_flags","pass"),&_File::open_encrypted_pass); + ObjectTypeDB::bind_method(_MD("open", "path", "flags"), &_File::open); + ObjectTypeDB::bind_method(_MD("close"), &_File::close); + ObjectTypeDB::bind_method(_MD("is_open"), &_File::is_open); + ObjectTypeDB::bind_method(_MD("seek", "pos"), &_File::seek); + ObjectTypeDB::bind_method(_MD("seek_end", "pos"), &_File::seek_end, DEFVAL(0)); + ObjectTypeDB::bind_method(_MD("get_pos"), &_File::get_pos); + ObjectTypeDB::bind_method(_MD("get_len"), &_File::get_len); + ObjectTypeDB::bind_method(_MD("eof_reached"), &_File::eof_reached); + ObjectTypeDB::bind_method(_MD("get_8"), &_File::get_8); + ObjectTypeDB::bind_method(_MD("get_16"), &_File::get_16); + ObjectTypeDB::bind_method(_MD("get_32"), &_File::get_32); + ObjectTypeDB::bind_method(_MD("get_64"), &_File::get_64); + ObjectTypeDB::bind_method(_MD("get_float"), &_File::get_float); + ObjectTypeDB::bind_method(_MD("get_double"), &_File::get_double); + ObjectTypeDB::bind_method(_MD("get_real"), &_File::get_real); + ObjectTypeDB::bind_method(_MD("get_buffer", "len"), &_File::get_buffer); + ObjectTypeDB::bind_method(_MD("get_line"), &_File::get_line); + ObjectTypeDB::bind_method(_MD("get_as_text"), &_File::get_as_text); + ObjectTypeDB::bind_method(_MD("get_md5", "path"), &_File::get_md5); + ObjectTypeDB::bind_method(_MD("get_sha256", "path"), &_File::get_sha256); + ObjectTypeDB::bind_method(_MD("get_endian_swap"), &_File::get_endian_swap); + ObjectTypeDB::bind_method(_MD("set_endian_swap", "enable"), &_File::set_endian_swap); + ObjectTypeDB::bind_method(_MD("get_error:Error"), &_File::get_error); + ObjectTypeDB::bind_method(_MD("get_var"), &_File::get_var); + ObjectTypeDB::bind_method(_MD("get_csv_line", "delim"), &_File::get_csv_line, DEFVAL(",")); - ObjectTypeDB::bind_method(_MD("open","path","flags"),&_File::open); - ObjectTypeDB::bind_method(_MD("close"),&_File::close); - ObjectTypeDB::bind_method(_MD("is_open"),&_File::is_open); - ObjectTypeDB::bind_method(_MD("seek","pos"),&_File::seek); - ObjectTypeDB::bind_method(_MD("seek_end","pos"),&_File::seek_end,DEFVAL(0)); - ObjectTypeDB::bind_method(_MD("get_pos"),&_File::get_pos); - ObjectTypeDB::bind_method(_MD("get_len"),&_File::get_len); - ObjectTypeDB::bind_method(_MD("eof_reached"),&_File::eof_reached); - ObjectTypeDB::bind_method(_MD("get_8"),&_File::get_8); - ObjectTypeDB::bind_method(_MD("get_16"),&_File::get_16); - ObjectTypeDB::bind_method(_MD("get_32"),&_File::get_32); - ObjectTypeDB::bind_method(_MD("get_64"),&_File::get_64); - ObjectTypeDB::bind_method(_MD("get_float"),&_File::get_float); - ObjectTypeDB::bind_method(_MD("get_double"),&_File::get_double); - ObjectTypeDB::bind_method(_MD("get_real"),&_File::get_real); - ObjectTypeDB::bind_method(_MD("get_buffer","len"),&_File::get_buffer); - ObjectTypeDB::bind_method(_MD("get_line"),&_File::get_line); - ObjectTypeDB::bind_method(_MD("get_as_text"),&_File::get_as_text); - ObjectTypeDB::bind_method(_MD("get_md5","path"),&_File::get_md5); - ObjectTypeDB::bind_method(_MD("get_sha256","path"),&_File::get_sha256); - ObjectTypeDB::bind_method(_MD("get_endian_swap"),&_File::get_endian_swap); - ObjectTypeDB::bind_method(_MD("set_endian_swap","enable"),&_File::set_endian_swap); - ObjectTypeDB::bind_method(_MD("get_error:Error"),&_File::get_error); - ObjectTypeDB::bind_method(_MD("get_var"),&_File::get_var); - ObjectTypeDB::bind_method(_MD("get_csv_line","delim"),&_File::get_csv_line,DEFVAL(",")); + ObjectTypeDB::bind_method(_MD("store_8", "value"), &_File::store_8); + ObjectTypeDB::bind_method(_MD("store_16", "value"), &_File::store_16); + ObjectTypeDB::bind_method(_MD("store_32", "value"), &_File::store_32); + ObjectTypeDB::bind_method(_MD("store_64", "value"), &_File::store_64); + ObjectTypeDB::bind_method(_MD("store_float", "value"), &_File::store_float); + ObjectTypeDB::bind_method(_MD("store_double", "value"), &_File::store_double); + ObjectTypeDB::bind_method(_MD("store_real", "value"), &_File::store_real); + ObjectTypeDB::bind_method(_MD("store_buffer", "buffer"), &_File::store_buffer); + ObjectTypeDB::bind_method(_MD("store_line", "line"), &_File::store_line); + ObjectTypeDB::bind_method(_MD("store_string", "string"), &_File::store_string); + ObjectTypeDB::bind_method(_MD("store_var", "value"), &_File::store_var); - ObjectTypeDB::bind_method(_MD("store_8","value"),&_File::store_8); - ObjectTypeDB::bind_method(_MD("store_16","value"),&_File::store_16); - ObjectTypeDB::bind_method(_MD("store_32","value"),&_File::store_32); - ObjectTypeDB::bind_method(_MD("store_64","value"),&_File::store_64); - ObjectTypeDB::bind_method(_MD("store_float","value"),&_File::store_float); - ObjectTypeDB::bind_method(_MD("store_double","value"),&_File::store_double); - ObjectTypeDB::bind_method(_MD("store_real","value"),&_File::store_real); - ObjectTypeDB::bind_method(_MD("store_buffer","buffer"),&_File::store_buffer); - ObjectTypeDB::bind_method(_MD("store_line","line"),&_File::store_line); - ObjectTypeDB::bind_method(_MD("store_string","string"),&_File::store_string); - ObjectTypeDB::bind_method(_MD("store_var","value"),&_File::store_var); + ObjectTypeDB::bind_method(_MD("store_pascal_string", "string"), &_File::store_pascal_string); + ObjectTypeDB::bind_method(_MD("get_pascal_string"), &_File::get_pascal_string); - ObjectTypeDB::bind_method(_MD("store_pascal_string","string"),&_File::store_pascal_string); - ObjectTypeDB::bind_method(_MD("get_pascal_string"),&_File::get_pascal_string); + ObjectTypeDB::bind_method(_MD("file_exists", "path"), &_File::file_exists); + ObjectTypeDB::bind_method(_MD("get_modified_time", "file"), &_File::get_modified_time); - ObjectTypeDB::bind_method(_MD("file_exists","path"),&_File::file_exists); - ObjectTypeDB::bind_method(_MD("get_modified_time", "file"),&_File::get_modified_time); - - BIND_CONSTANT( READ ); - BIND_CONSTANT( WRITE ); - BIND_CONSTANT( READ_WRITE ); - BIND_CONSTANT( WRITE_READ ); + BIND_CONSTANT(READ); + BIND_CONSTANT(WRITE); + BIND_CONSTANT(READ_WRITE); + BIND_CONSTANT(WRITE_READ); } -_File::_File(){ +_File::_File() { f = NULL; - eswap=false; - + eswap = false; } -_File::~_File(){ +_File::~_File() { if (f) memdelete(f); - } /////////////////////////////////////////////////////// - - - -Error _Directory::open(const String& p_path) { +Error _Directory::open(const String &p_path) { Error err; - DirAccess *alt=DirAccess::open(p_path,&err); + DirAccess *alt = DirAccess::open(p_path, &err); if (!alt) return err; if (d) memdelete(d); - d=alt; + d = alt; return OK; } bool _Directory::list_dir_begin() { - ERR_FAIL_COND_V(!d,false); + ERR_FAIL_COND_V(!d, false); return d->list_dir_begin(); } -String _Directory::get_next(){ +String _Directory::get_next() { - ERR_FAIL_COND_V(!d,""); + ERR_FAIL_COND_V(!d, ""); return d->get_next(); } -bool _Directory::current_is_dir() const{ +bool _Directory::current_is_dir() const { - ERR_FAIL_COND_V(!d,false); + ERR_FAIL_COND_V(!d, false); return d->current_is_dir(); } -void _Directory::list_dir_end(){ +void _Directory::list_dir_end() { ERR_FAIL_COND(!d); return d->list_dir_end(); } -int _Directory::get_drive_count(){ +int _Directory::get_drive_count() { - ERR_FAIL_COND_V(!d,0); + ERR_FAIL_COND_V(!d, 0); return d->get_drive_count(); } -String _Directory::get_drive(int p_drive){ +String _Directory::get_drive(int p_drive) { - ERR_FAIL_COND_V(!d,""); + ERR_FAIL_COND_V(!d, ""); return d->get_drive(p_drive); } -Error _Directory::change_dir(String p_dir){ +Error _Directory::change_dir(String p_dir) { - ERR_FAIL_COND_V(!d,ERR_UNCONFIGURED); + ERR_FAIL_COND_V(!d, ERR_UNCONFIGURED); return d->change_dir(p_dir); } String _Directory::get_current_dir() { - ERR_FAIL_COND_V(!d,""); + ERR_FAIL_COND_V(!d, ""); return d->get_current_dir(); } -Error _Directory::make_dir(String p_dir){ +Error _Directory::make_dir(String p_dir) { - ERR_FAIL_COND_V(!d,ERR_UNCONFIGURED); + ERR_FAIL_COND_V(!d, ERR_UNCONFIGURED); if (!p_dir.is_rel_path()) { DirAccess *d = DirAccess::create_for_path(p_dir); Error err = d->make_dir(p_dir); memdelete(d); return err; - } return d->make_dir(p_dir); } -Error _Directory::make_dir_recursive(String p_dir){ +Error _Directory::make_dir_recursive(String p_dir) { - ERR_FAIL_COND_V(!d,ERR_UNCONFIGURED); + ERR_FAIL_COND_V(!d, ERR_UNCONFIGURED); if (!p_dir.is_rel_path()) { DirAccess *d = DirAccess::create_for_path(p_dir); Error err = d->make_dir_recursive(p_dir); memdelete(d); return err; - } return d->make_dir_recursive(p_dir); } -bool _Directory::file_exists(String p_file){ +bool _Directory::file_exists(String p_file) { - ERR_FAIL_COND_V(!d,false); + ERR_FAIL_COND_V(!d, false); if (!p_file.is_rel_path()) { return FileAccess::exists(p_file); @@ -1984,7 +1904,7 @@ bool _Directory::file_exists(String p_file){ } bool _Directory::dir_exists(String p_dir) { - ERR_FAIL_COND_V(!d,false); + ERR_FAIL_COND_V(!d, false); if (!p_dir.is_rel_path()) { DirAccess *d = DirAccess::create_for_path(p_dir); @@ -1997,33 +1917,32 @@ bool _Directory::dir_exists(String p_dir) { } } -int _Directory::get_space_left(){ +int _Directory::get_space_left() { - ERR_FAIL_COND_V(!d,0); - return d->get_space_left()/1024*1024; //return value in megabytes, given binding is int + ERR_FAIL_COND_V(!d, 0); + return d->get_space_left() / 1024 * 1024; //return value in megabytes, given binding is int } -Error _Directory::copy(String p_from,String p_to){ +Error _Directory::copy(String p_from, String p_to) { - ERR_FAIL_COND_V(!d,ERR_UNCONFIGURED); - return d->copy(p_from,p_to); + ERR_FAIL_COND_V(!d, ERR_UNCONFIGURED); + return d->copy(p_from, p_to); } -Error _Directory::rename(String p_from, String p_to){ +Error _Directory::rename(String p_from, String p_to) { - ERR_FAIL_COND_V(!d,ERR_UNCONFIGURED); + ERR_FAIL_COND_V(!d, ERR_UNCONFIGURED); if (!p_from.is_rel_path()) { DirAccess *d = DirAccess::create_for_path(p_from); - Error err = d->rename(p_from,p_to); + Error err = d->rename(p_from, p_to); memdelete(d); return err; } - return d->rename(p_from,p_to); - + return d->rename(p_from, p_to); } -Error _Directory::remove(String p_name){ +Error _Directory::remove(String p_name) { - ERR_FAIL_COND_V(!d,ERR_UNCONFIGURED); + ERR_FAIL_COND_V(!d, ERR_UNCONFIGURED); if (!p_name.is_rel_path()) { DirAccess *d = DirAccess::create_for_path(p_name); Error err = d->remove(p_name); @@ -2036,26 +1955,24 @@ Error _Directory::remove(String p_name){ void _Directory::_bind_methods() { - - ObjectTypeDB::bind_method(_MD("open:Error","path"),&_Directory::open); - ObjectTypeDB::bind_method(_MD("list_dir_begin"),&_Directory::list_dir_begin); - ObjectTypeDB::bind_method(_MD("get_next"),&_Directory::get_next); - ObjectTypeDB::bind_method(_MD("current_is_dir"),&_Directory::current_is_dir); - ObjectTypeDB::bind_method(_MD("list_dir_end"),&_Directory::list_dir_end); - ObjectTypeDB::bind_method(_MD("get_drive_count"),&_Directory::get_drive_count); - ObjectTypeDB::bind_method(_MD("get_drive","idx"),&_Directory::get_drive); - ObjectTypeDB::bind_method(_MD("change_dir:Error","todir"),&_Directory::change_dir); - ObjectTypeDB::bind_method(_MD("get_current_dir"),&_Directory::get_current_dir); - ObjectTypeDB::bind_method(_MD("make_dir:Error","path"),&_Directory::make_dir); - ObjectTypeDB::bind_method(_MD("make_dir_recursive:Error","path"),&_Directory::make_dir_recursive); - ObjectTypeDB::bind_method(_MD("file_exists","path"),&_Directory::file_exists); - ObjectTypeDB::bind_method(_MD("dir_exists","path"),&_Directory::dir_exists); -// ObjectTypeDB::bind_method(_MD("get_modified_time","file"),&_Directory::get_modified_time); - ObjectTypeDB::bind_method(_MD("get_space_left"),&_Directory::get_space_left); - ObjectTypeDB::bind_method(_MD("copy:Error","from","to"),&_Directory::copy); - ObjectTypeDB::bind_method(_MD("rename:Error","from","to"),&_Directory::rename); - ObjectTypeDB::bind_method(_MD("remove:Error","path"),&_Directory::remove); - + ObjectTypeDB::bind_method(_MD("open:Error", "path"), &_Directory::open); + ObjectTypeDB::bind_method(_MD("list_dir_begin"), &_Directory::list_dir_begin); + ObjectTypeDB::bind_method(_MD("get_next"), &_Directory::get_next); + ObjectTypeDB::bind_method(_MD("current_is_dir"), &_Directory::current_is_dir); + ObjectTypeDB::bind_method(_MD("list_dir_end"), &_Directory::list_dir_end); + ObjectTypeDB::bind_method(_MD("get_drive_count"), &_Directory::get_drive_count); + ObjectTypeDB::bind_method(_MD("get_drive", "idx"), &_Directory::get_drive); + ObjectTypeDB::bind_method(_MD("change_dir:Error", "todir"), &_Directory::change_dir); + ObjectTypeDB::bind_method(_MD("get_current_dir"), &_Directory::get_current_dir); + ObjectTypeDB::bind_method(_MD("make_dir:Error", "path"), &_Directory::make_dir); + ObjectTypeDB::bind_method(_MD("make_dir_recursive:Error", "path"), &_Directory::make_dir_recursive); + ObjectTypeDB::bind_method(_MD("file_exists", "path"), &_Directory::file_exists); + ObjectTypeDB::bind_method(_MD("dir_exists", "path"), &_Directory::dir_exists); + // ObjectTypeDB::bind_method(_MD("get_modified_time","file"),&_Directory::get_modified_time); + ObjectTypeDB::bind_method(_MD("get_space_left"), &_Directory::get_space_left); + ObjectTypeDB::bind_method(_MD("copy:Error", "from", "to"), &_Directory::copy); + ObjectTypeDB::bind_method(_MD("rename:Error", "from", "to"), &_Directory::rename); + ObjectTypeDB::bind_method(_MD("remove:Error", "path"), &_Directory::remove); } _Directory::_Directory() { @@ -2069,33 +1986,33 @@ _Directory::~_Directory() { memdelete(d); } -String _Marshalls::variant_to_base64(const Variant& p_var) { +String _Marshalls::variant_to_base64(const Variant &p_var) { int len; - Error err = encode_variant(p_var,NULL,len); - ERR_FAIL_COND_V( err != OK, "" ); + Error err = encode_variant(p_var, NULL, len); + ERR_FAIL_COND_V(err != OK, ""); DVector buff; buff.resize(len); DVector::Write w = buff.write(); - err = encode_variant(p_var,&w[0],len); - ERR_FAIL_COND_V( err != OK, "" ); + err = encode_variant(p_var, &w[0], len); + ERR_FAIL_COND_V(err != OK, ""); int b64len = len / 3 * 4 + 4 + 1; DVector b64buff; b64buff.resize(b64len); DVector::Write w64 = b64buff.write(); - int strlen = base64_encode((char*)(&w64[0]), (char*)(&w[0]), len); + int strlen = base64_encode((char *)(&w64[0]), (char *)(&w[0]), len); //OS::get_singleton()->print("len is %i, vector size is %i\n", b64len, strlen); w64[strlen] = 0; - String ret = (char*)&w64[0]; + String ret = (char *)&w64[0]; return ret; }; -Variant _Marshalls::base64_to_variant(const String& p_str) { +Variant _Marshalls::base64_to_variant(const String &p_str) { int strlen = p_str.length(); CharString cstr = p_str.ascii(); @@ -2104,11 +2021,11 @@ Variant _Marshalls::base64_to_variant(const String& p_str) { buf.resize(strlen / 4 * 3 + 1); DVector::Write w = buf.write(); - int len = base64_decode((char*)(&w[0]), (char*)cstr.get_data(), strlen); + int len = base64_decode((char *)(&w[0]), (char *)cstr.get_data(), strlen); Variant v; Error err = decode_variant(v, &w[0], len); - ERR_FAIL_COND_V( err!=OK, Variant() ); + ERR_FAIL_COND_V(err != OK, Variant()); return v; }; @@ -2123,9 +2040,9 @@ String _Marshalls::raw_to_base64(const DVector &p_arr) { b64buff.resize(b64len); DVector::Write w64 = b64buff.write(); - int strlen = base64_encode((char*)(&w64[0]), (char*)(&r[0]), len); + int strlen = base64_encode((char *)(&w64[0]), (char *)(&r[0]), len); w64[strlen] = 0; - String ret = (char*)&w64[0]; + String ret = (char *)&w64[0]; return ret; }; @@ -2141,7 +2058,7 @@ DVector _Marshalls::base64_to_raw(const String &p_str) { buf.resize(strlen / 4 * 3 + 1); DVector::Write w = buf.write(); - arr_len = base64_decode((char*)(&w[0]), (char*)cstr.get_data(), strlen); + arr_len = base64_decode((char *)(&w[0]), (char *)cstr.get_data(), strlen); }; buf.resize(arr_len); @@ -2149,7 +2066,7 @@ DVector _Marshalls::base64_to_raw(const String &p_str) { return buf; }; -String _Marshalls::utf8_to_base64(const String& p_str) { +String _Marshalls::utf8_to_base64(const String &p_str) { CharString cstr = p_str.utf8(); int len = cstr.length(); @@ -2159,15 +2076,15 @@ String _Marshalls::utf8_to_base64(const String& p_str) { b64buff.resize(b64len); DVector::Write w64 = b64buff.write(); - int strlen = base64_encode((char*)(&w64[0]), (char*)cstr.get_data(), len); + int strlen = base64_encode((char *)(&w64[0]), (char *)cstr.get_data(), len); w64[strlen] = 0; - String ret = (char*)&w64[0]; + String ret = (char *)&w64[0]; return ret; }; -String _Marshalls::base64_to_utf8(const String& p_str) { +String _Marshalls::base64_to_utf8(const String &p_str) { int strlen = p_str.length(); CharString cstr = p_str.ascii(); @@ -2176,35 +2093,28 @@ String _Marshalls::base64_to_utf8(const String& p_str) { buf.resize(strlen / 4 * 3 + 1 + 1); DVector::Write w = buf.write(); - int len = base64_decode((char*)(&w[0]), (char*)cstr.get_data(), strlen); + int len = base64_decode((char *)(&w[0]), (char *)cstr.get_data(), strlen); w[len] = 0; - String ret = String::utf8((char*)&w[0]); + String ret = String::utf8((char *)&w[0]); return ret; }; - void _Marshalls::_bind_methods() { - ObjectTypeDB::bind_method(_MD("variant_to_base64:String","variant"),&_Marshalls::variant_to_base64); - ObjectTypeDB::bind_method(_MD("base64_to_variant:Variant","base64_str"),&_Marshalls::base64_to_variant); + ObjectTypeDB::bind_method(_MD("variant_to_base64:String", "variant"), &_Marshalls::variant_to_base64); + ObjectTypeDB::bind_method(_MD("base64_to_variant:Variant", "base64_str"), &_Marshalls::base64_to_variant); - ObjectTypeDB::bind_method(_MD("raw_to_base64:String","array"),&_Marshalls::raw_to_base64); - ObjectTypeDB::bind_method(_MD("base64_to_raw:RawArray","base64_str"),&_Marshalls::base64_to_raw); - - ObjectTypeDB::bind_method(_MD("utf8_to_base64:String","utf8_str"),&_Marshalls::utf8_to_base64); - ObjectTypeDB::bind_method(_MD("base64_to_utf8:String","base64_str"),&_Marshalls::base64_to_utf8); + ObjectTypeDB::bind_method(_MD("raw_to_base64:String", "array"), &_Marshalls::raw_to_base64); + ObjectTypeDB::bind_method(_MD("base64_to_raw:RawArray", "base64_str"), &_Marshalls::base64_to_raw); + ObjectTypeDB::bind_method(_MD("utf8_to_base64:String", "utf8_str"), &_Marshalls::utf8_to_base64); + ObjectTypeDB::bind_method(_MD("base64_to_utf8:String", "base64_str"), &_Marshalls::base64_to_utf8); }; - - //////////////// - - - Error _Semaphore::wait() { return semaphore->wait(); @@ -2215,133 +2125,120 @@ Error _Semaphore::post() { return semaphore->post(); } - void _Semaphore::_bind_methods() { - ObjectTypeDB::bind_method(_MD("wait:Error"),&_Semaphore::wait); - ObjectTypeDB::bind_method(_MD("post:Error"),&_Semaphore::post); - + ObjectTypeDB::bind_method(_MD("wait:Error"), &_Semaphore::wait); + ObjectTypeDB::bind_method(_MD("post:Error"), &_Semaphore::post); } - _Semaphore::_Semaphore() { - semaphore =Semaphore::create(); + semaphore = Semaphore::create(); } -_Semaphore::~_Semaphore(){ +_Semaphore::~_Semaphore() { memdelete(semaphore); } - /////////////// - void _Mutex::lock() { mutex->lock(); } -Error _Mutex::try_lock(){ +Error _Mutex::try_lock() { return mutex->try_lock(); } -void _Mutex::unlock(){ +void _Mutex::unlock() { mutex->unlock(); } void _Mutex::_bind_methods() { - ObjectTypeDB::bind_method(_MD("lock"),&_Mutex::lock); - ObjectTypeDB::bind_method(_MD("try_lock:Error"),&_Mutex::try_lock); - ObjectTypeDB::bind_method(_MD("unlock"),&_Mutex::unlock); - + ObjectTypeDB::bind_method(_MD("lock"), &_Mutex::lock); + ObjectTypeDB::bind_method(_MD("try_lock:Error"), &_Mutex::try_lock); + ObjectTypeDB::bind_method(_MD("unlock"), &_Mutex::unlock); } - _Mutex::_Mutex() { - mutex =Mutex::create(); + mutex = Mutex::create(); } -_Mutex::~_Mutex(){ +_Mutex::~_Mutex() { memdelete(mutex); } - /////////////// - - void _Thread::_start_func(void *ud) { - Ref<_Thread>* tud=(Ref<_Thread>*)ud; - Ref<_Thread> t=*tud; + Ref<_Thread> *tud = (Ref<_Thread> *)ud; + Ref<_Thread> t = *tud; memdelete(tud); Variant::CallError ce; - const Variant* arg[1]={&t->userdata}; + const Variant *arg[1] = { &t->userdata }; Thread::set_name(t->target_method); - t->ret=t->target_instance->call(t->target_method,arg,1,ce); - if (ce.error!=Variant::CallError::CALL_OK) { + t->ret = t->target_instance->call(t->target_method, arg, 1, ce); + if (ce.error != Variant::CallError::CALL_OK) { String reason; - switch(ce.error) { + switch (ce.error) { case Variant::CallError::CALL_ERROR_INVALID_ARGUMENT: { - reason="Invalid Argument #"+itos(ce.argument); + reason = "Invalid Argument #" + itos(ce.argument); } break; case Variant::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS: { - reason="Too Many Arguments"; + reason = "Too Many Arguments"; } break; case Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS: { - reason="Too Many Arguments"; + reason = "Too Many Arguments"; } break; case Variant::CallError::CALL_ERROR_INVALID_METHOD: { - reason="Method Not Found"; + reason = "Method Not Found"; } break; default: {} } - - ERR_EXPLAIN("Could not call function '"+t->target_method.operator String()+"'' starting thread ID: "+t->get_id()+" Reason: "+reason); + ERR_EXPLAIN("Could not call function '" + t->target_method.operator String() + "'' starting thread ID: " + t->get_id() + " Reason: " + reason); ERR_FAIL(); } - } -Error _Thread::start(Object *p_instance,const StringName& p_method,const Variant& p_userdata,int p_priority) { +Error _Thread::start(Object *p_instance, const StringName &p_method, const Variant &p_userdata, int p_priority) { - ERR_FAIL_COND_V(active,ERR_ALREADY_IN_USE); - ERR_FAIL_COND_V(!p_instance,ERR_INVALID_PARAMETER); - ERR_FAIL_COND_V(p_method==StringName(),ERR_INVALID_PARAMETER); - ERR_FAIL_INDEX_V(p_priority,3,ERR_INVALID_PARAMETER); + ERR_FAIL_COND_V(active, ERR_ALREADY_IN_USE); + ERR_FAIL_COND_V(!p_instance, ERR_INVALID_PARAMETER); + ERR_FAIL_COND_V(p_method == StringName(), ERR_INVALID_PARAMETER); + ERR_FAIL_INDEX_V(p_priority, 3, ERR_INVALID_PARAMETER); + ret = Variant(); + target_method = p_method; + target_instance = p_instance; + userdata = p_userdata; + active = true; - ret=Variant(); - target_method=p_method; - target_instance=p_instance; - userdata=p_userdata; - active=true; - - Ref<_Thread> *ud = memnew( Ref<_Thread>(this) ); + Ref<_Thread> *ud = memnew(Ref<_Thread>(this)); Thread::Settings s; - s.priority=(Thread::Priority)p_priority; - thread = Thread::create(_start_func,ud,s); + s.priority = (Thread::Priority)p_priority; + thread = Thread::create(_start_func, ud, s); if (!thread) { - active=false; - target_method=StringName(); - target_instance=NULL; - userdata=Variant(); + active = false; + target_method = StringName(); + target_instance = NULL; + userdata = Variant(); return ERR_CANT_CREATE; } @@ -2362,36 +2259,35 @@ bool _Thread::is_active() const { } Variant _Thread::wait_to_finish() { - ERR_FAIL_COND_V(!thread,Variant()); - ERR_FAIL_COND_V(!active,Variant()); + ERR_FAIL_COND_V(!thread, Variant()); + ERR_FAIL_COND_V(!active, Variant()); Thread::wait_to_finish(thread); Variant r = ret; - active=false; - target_method=StringName(); - target_instance=NULL; - userdata=Variant(); - thread=NULL; + active = false; + target_method = StringName(); + target_instance = NULL; + userdata = Variant(); + thread = NULL; return r; } void _Thread::_bind_methods() { - ObjectTypeDB::bind_method(_MD("start:Error","instance","method","userdata","priority"),&_Thread::start,DEFVAL(Variant()),DEFVAL(PRIORITY_NORMAL)); - ObjectTypeDB::bind_method(_MD("get_id"),&_Thread::get_id); - ObjectTypeDB::bind_method(_MD("is_active"),&_Thread::is_active); - ObjectTypeDB::bind_method(_MD("wait_to_finish:Variant"),&_Thread::wait_to_finish); - - BIND_CONSTANT( PRIORITY_LOW ); - BIND_CONSTANT( PRIORITY_NORMAL ); - BIND_CONSTANT( PRIORITY_HIGH ); + ObjectTypeDB::bind_method(_MD("start:Error", "instance", "method", "userdata", "priority"), &_Thread::start, DEFVAL(Variant()), DEFVAL(PRIORITY_NORMAL)); + ObjectTypeDB::bind_method(_MD("get_id"), &_Thread::get_id); + ObjectTypeDB::bind_method(_MD("is_active"), &_Thread::is_active); + ObjectTypeDB::bind_method(_MD("wait_to_finish:Variant"), &_Thread::wait_to_finish); + BIND_CONSTANT(PRIORITY_LOW); + BIND_CONSTANT(PRIORITY_NORMAL); + BIND_CONSTANT(PRIORITY_HIGH); } _Thread::_Thread() { - active=false; - thread=NULL; - target_instance=NULL; + active = false; + thread = NULL; + target_instance = NULL; } _Thread::~_Thread() { @@ -2399,5 +2295,5 @@ _Thread::~_Thread() { if (active) { ERR_EXPLAIN("Reference to a Thread object object was lost while the thread is still running.."); } - ERR_FAIL_COND(active==true); + ERR_FAIL_COND(active == true); } diff --git a/core/bind/core_bind.h b/core/bind/core_bind.h index 2d42c99eba6..8a00794a4b7 100644 --- a/core/bind/core_bind.h +++ b/core/bind/core_bind.h @@ -31,73 +31,67 @@ #include "io/resource_loader.h" #include "io/resource_saver.h" -#include "os/file_access.h" #include "os/dir_access.h" -#include "os/thread.h" +#include "os/file_access.h" #include "os/semaphore.h" +#include "os/thread.h" - -class _ResourceLoader : public Object { - OBJ_TYPE(_ResourceLoader,Object); +class _ResourceLoader : public Object { + OBJ_TYPE(_ResourceLoader, Object); protected: - static void _bind_methods(); static _ResourceLoader *singleton; + public: - - static _ResourceLoader *get_singleton() { return singleton; } - Ref load_interactive(const String& p_path,const String& p_type_hint=""); - RES load(const String &p_path,const String& p_type_hint="", bool p_no_cache = false); - DVector get_recognized_extensions_for_type(const String& p_type); + Ref load_interactive(const String &p_path, const String &p_type_hint = ""); + RES load(const String &p_path, const String &p_type_hint = "", bool p_no_cache = false); + DVector get_recognized_extensions_for_type(const String &p_type); void set_abort_on_missing_resources(bool p_abort); - StringArray get_dependencies(const String& p_path); - bool has(const String& p_path); - Ref load_import_metadata(const String& p_path); + StringArray get_dependencies(const String &p_path); + bool has(const String &p_path); + Ref load_import_metadata(const String &p_path); _ResourceLoader(); }; -class _ResourceSaver : public Object { - OBJ_TYPE(_ResourceSaver,Object); +class _ResourceSaver : public Object { + OBJ_TYPE(_ResourceSaver, Object); protected: - static void _bind_methods(); static _ResourceSaver *singleton; -public: +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_RELATIVE_PATHS = 1, + FLAG_BUNDLE_RESOURCES = 2, + FLAG_CHANGE_PATH = 4, + FLAG_OMIT_EDITOR_PROPERTIES = 8, + FLAG_SAVE_BIG_ENDIAN = 16, + FLAG_COMPRESS = 32, }; static _ResourceSaver *get_singleton() { return singleton; } - Error save(const String &p_path,const RES& p_resource, uint32_t p_flags); - DVector get_recognized_extensions(const RES& p_resource); - + Error save(const String &p_path, const RES &p_resource, uint32_t p_flags); + DVector get_recognized_extensions(const RES &p_resource); _ResourceSaver(); }; class MainLoop; -class _OS : public Object { - OBJ_TYPE(_OS,Object); +class _OS : public Object { + OBJ_TYPE(_OS, Object); protected: - static void _bind_methods(); static _OS *singleton; -public: +public: enum Weekday { DAY_SUNDAY, DAY_MONDAY, @@ -126,30 +120,28 @@ public: }; Point2 get_mouse_pos() const; - void set_window_title(const String& p_title); + void set_window_title(const String &p_title); int get_mouse_button_state() const; - - void set_clipboard(const String& p_text); + void set_clipboard(const String &p_text); String get_clipboard() const; - void set_video_mode(const Size2& p_size, bool p_fullscreen,bool p_resizeable,int p_screen=0); - Size2 get_video_mode(int p_screen=0) const; - bool is_video_mode_fullscreen(int p_screen=0) const; - bool is_video_mode_resizable(int p_screen=0) const; - Array get_fullscreen_mode_list(int p_screen=0) const; - + void set_video_mode(const Size2 &p_size, bool p_fullscreen, bool p_resizeable, int p_screen = 0); + Size2 get_video_mode(int p_screen = 0) const; + bool is_video_mode_fullscreen(int p_screen = 0) const; + bool is_video_mode_resizable(int p_screen = 0) const; + Array get_fullscreen_mode_list(int p_screen = 0) const; virtual int get_screen_count() const; virtual int get_current_screen() const; virtual void set_current_screen(int p_screen); - virtual Point2 get_screen_position(int p_screen=0) const; - virtual Size2 get_screen_size(int p_screen=0) const; - virtual int get_screen_dpi(int p_screen=0) const; + virtual Point2 get_screen_position(int p_screen = 0) const; + virtual Size2 get_screen_size(int p_screen = 0) const; + virtual int get_screen_dpi(int p_screen = 0) const; virtual Point2 get_window_position() const; - virtual void set_window_position(const Point2& p_position); + virtual void set_window_position(const Point2 &p_position); virtual Size2 get_window_size() const; - virtual void set_window_size(const Size2& p_size); + virtual void set_window_size(const Size2 &p_size); virtual void set_window_fullscreen(bool p_enabled); virtual bool is_window_fullscreen() const; virtual void set_window_resizable(bool p_enabled); @@ -179,15 +171,15 @@ public: bool is_in_low_processor_usage_mode() const; String get_executable_path() const; - int execute(const String& p_path, const Vector & p_arguments,bool p_blocking,Array p_output=Array()); + int execute(const String &p_path, const Vector &p_arguments, bool p_blocking, Array p_output = Array()); Error kill(int p_pid); Error shell_open(String p_uri); int get_process_ID() const; - bool has_environment(const String& p_var) const; - String get_environment(const String& p_var) const; + bool has_environment(const String &p_var) const; + String get_environment(const String &p_var) const; String get_name() const; Vector get_cmdline_args(); @@ -202,17 +194,17 @@ public: float get_frames_per_second() const; - void dump_memory_to_file(const String& p_file); - void dump_resources_to_file(const String& p_file); + void dump_memory_to_file(const String &p_file); + void dump_resources_to_file(const String &p_file); bool has_virtual_keyboard() const; - void show_virtual_keyboard(const String& p_existing_text=""); + void show_virtual_keyboard(const String &p_existing_text = ""); void hide_virtual_keyboard(); - void print_resources_in_use(bool p_short=false); - void print_all_resources(const String& p_to_file); + void print_resources_in_use(bool p_short = false); + void print_all_resources(const String &p_to_file); void print_all_textures_by_size(); - void print_resources_by_type(const Vector& p_types); + void print_resources_by_type(const Vector &p_types); bool has_touchscreen_ui_hint() const; @@ -222,8 +214,7 @@ public: String get_scancode_string(uint32_t p_code) const; bool is_scancode_unicode(uint32_t p_unicode) const; - int find_scancode_from_string(const String& p_code) const; - + int find_scancode_from_string(const String &p_code) const; /* struct Date { @@ -245,7 +236,7 @@ public: void set_use_file_access_save_and_swap(bool p_enable); - void set_icon(const Image& p_icon); + void set_icon(const Image &p_icon); int get_exit_code() const; void set_exit_code(int p_code); @@ -271,7 +262,7 @@ public: bool can_draw() const; - int get_frames_drawn(); + int get_frames_drawn(); bool is_stdout_verbose() const; @@ -301,11 +292,9 @@ public: String get_system_dir(SystemDir p_dir) const; - String get_data_dir() const; - void alert(const String& p_alert,const String& p_title="ALERT!"); - + void alert(const String &p_alert, const String &p_title = "ALERT!"); void set_screen_orientation(ScreenOrientation p_orientation); ScreenOrientation get_screen_orientation() const; @@ -318,7 +307,7 @@ public: bool is_ok_left_and_cancel_right() const; - Error set_thread_name(const String& p_name); + Error set_thread_name(const String &p_name); void set_use_vsync(bool p_enable); bool is_vsync_enabled() const; @@ -333,76 +322,71 @@ public: VARIANT_ENUM_CAST(_OS::SystemDir); VARIANT_ENUM_CAST(_OS::ScreenOrientation); - class _Geometry : public Object { OBJ_TYPE(_Geometry, Object); static _Geometry *singleton; + protected: - static void _bind_methods(); + public: - static _Geometry *get_singleton(); - DVector build_box_planes(const Vector3& p_extents); - DVector build_cylinder_planes(float p_radius, float p_height, int p_sides, Vector3::Axis p_axis=Vector3::AXIS_Z); - DVector build_capsule_planes(float p_radius, float p_height, int p_sides, int p_lats, Vector3::Axis p_axis=Vector3::AXIS_Z); - Variant segment_intersects_segment_2d(const Vector2& p_from_a,const Vector2& p_to_a,const Vector2& p_from_b,const Vector2& p_to_b); - DVector get_closest_points_between_segments_2d( const Vector2& p1,const Vector2& q1, const Vector2& p2,const Vector2& q2); - DVector get_closest_points_between_segments(const Vector3& p1,const Vector3& p2,const Vector3& q1,const Vector3& q2); - Vector2 get_closest_point_to_segment_2d(const Vector2& p_point, const Vector2& p_a,const Vector2& p_b); - Vector3 get_closest_point_to_segment(const Vector3& p_point, const Vector3& p_a,const Vector3& p_b); - Vector2 get_closest_point_to_segment_uncapped_2d(const Vector2& p_point, const Vector2& p_a,const Vector2& p_b); - Vector3 get_closest_point_to_segment_uncapped(const Vector3& p_point, const Vector3& p_a,const Vector3& p_b); - Variant ray_intersects_triangle( const Vector3& p_from, const Vector3& p_dir, const Vector3& p_v0,const Vector3& p_v1,const Vector3& p_v2); - Variant segment_intersects_triangle( const Vector3& p_from, const Vector3& p_to, const Vector3& p_v0,const Vector3& p_v1,const Vector3& p_v2); - bool point_is_inside_triangle(const Vector2& s, const Vector2& a, const Vector2& b, const Vector2& c) const; + DVector build_box_planes(const Vector3 &p_extents); + DVector build_cylinder_planes(float p_radius, float p_height, int p_sides, Vector3::Axis p_axis = Vector3::AXIS_Z); + DVector build_capsule_planes(float p_radius, float p_height, int p_sides, int p_lats, Vector3::Axis p_axis = Vector3::AXIS_Z); + Variant segment_intersects_segment_2d(const Vector2 &p_from_a, const Vector2 &p_to_a, const Vector2 &p_from_b, const Vector2 &p_to_b); + DVector get_closest_points_between_segments_2d(const Vector2 &p1, const Vector2 &q1, const Vector2 &p2, const Vector2 &q2); + DVector get_closest_points_between_segments(const Vector3 &p1, const Vector3 &p2, const Vector3 &q1, const Vector3 &q2); + Vector2 get_closest_point_to_segment_2d(const Vector2 &p_point, const Vector2 &p_a, const Vector2 &p_b); + Vector3 get_closest_point_to_segment(const Vector3 &p_point, const Vector3 &p_a, const Vector3 &p_b); + Vector2 get_closest_point_to_segment_uncapped_2d(const Vector2 &p_point, const Vector2 &p_a, const Vector2 &p_b); + Vector3 get_closest_point_to_segment_uncapped(const Vector3 &p_point, const Vector3 &p_a, const Vector3 &p_b); + Variant ray_intersects_triangle(const Vector3 &p_from, const Vector3 &p_dir, const Vector3 &p_v0, const Vector3 &p_v1, const Vector3 &p_v2); + Variant segment_intersects_triangle(const Vector3 &p_from, const Vector3 &p_to, const Vector3 &p_v0, const Vector3 &p_v1, const Vector3 &p_v2); + bool point_is_inside_triangle(const Vector2 &s, const Vector2 &a, const Vector2 &b, const Vector2 &c) const; - DVector segment_intersects_sphere( const Vector3& p_from, const Vector3& p_to, const Vector3& p_sphere_pos,real_t p_sphere_radius); - DVector segment_intersects_cylinder( const Vector3& p_from, const Vector3& p_to, float p_height,float p_radius); - DVector segment_intersects_convex(const Vector3& p_from, const Vector3& p_to,const Vector& p_planes); - real_t segment_intersects_circle(const Vector2& p_from, const Vector2& p_to, const Vector2& p_circle_pos, real_t p_circle_radius); - int get_uv84_normal_bit(const Vector3& p_vector); + DVector segment_intersects_sphere(const Vector3 &p_from, const Vector3 &p_to, const Vector3 &p_sphere_pos, real_t p_sphere_radius); + DVector segment_intersects_cylinder(const Vector3 &p_from, const Vector3 &p_to, float p_height, float p_radius); + DVector segment_intersects_convex(const Vector3 &p_from, const Vector3 &p_to, const Vector &p_planes); + real_t segment_intersects_circle(const Vector2 &p_from, const Vector2 &p_to, const Vector2 &p_circle_pos, real_t p_circle_radius); + int get_uv84_normal_bit(const Vector3 &p_vector); - Vector triangulate_polygon(const Vector& p_polygon); + Vector triangulate_polygon(const Vector &p_polygon); - Dictionary make_atlas(const Vector& p_rects); + Dictionary make_atlas(const Vector &p_rects); _Geometry(); }; - - - class _File : public Reference { - OBJ_TYPE(_File,Reference); + OBJ_TYPE(_File, Reference); FileAccess *f; bool eswap; + protected: - static void _bind_methods(); + public: + enum ModeFlags { - enum ModeFlags { - - READ=1, - WRITE=2, - READ_WRITE=3, - WRITE_READ=7, + READ = 1, + WRITE = 2, + READ_WRITE = 3, + WRITE_READ = 7, }; - Error open_encrypted(const String& p_path, int p_mode_flags,const Vector& p_key); - Error open_encrypted_pass(const String& p_path, int p_mode_flags,const String& p_pass); + Error open_encrypted(const String &p_path, int p_mode_flags, const Vector &p_key); + Error open_encrypted_pass(const String &p_path, int p_mode_flags, const String &p_pass); - - Error open(const String& p_path, int p_mode_flags); ///< open a file + Error open(const String &p_path, int p_mode_flags); ///< open a file void close(); ///< close a file bool is_open() const; ///< true when file is open void seek(int64_t p_position); ///< seek to a given position - void seek_end(int64_t p_position=0); ///< seek from the end of file + void seek_end(int64_t p_position = 0); ///< seek from the end of file int64_t get_pos() const; ///< get position in the file int64_t get_len() const; ///< get size of the file @@ -422,8 +406,8 @@ public: DVector get_buffer(int p_length) const; ///< get an array of bytes String get_line() const; String get_as_text() const; - String get_md5(const String& p_path) const; - String get_sha256(const String& p_path) const; + String get_md5(const String &p_path) const; + String get_sha256(const String &p_path) const; /**< use this for files WRITTEN in _big_ endian machines (ie, amiga/mac) * It's not about the current CPU type but file formats. @@ -444,38 +428,36 @@ public: void store_double(double p_dest); void store_real(real_t p_real); - void store_string(const String& p_string); - void store_line(const String& p_string); + void store_string(const String &p_string); + void store_line(const String &p_string); - virtual void store_pascal_string(const String& p_string); + virtual void store_pascal_string(const String &p_string); virtual String get_pascal_string(); - Vector get_csv_line(String delim=",") const; + Vector get_csv_line(String delim = ",") const; + void store_buffer(const DVector &p_buffer); ///< store an array of bytes - void store_buffer(const DVector& p_buffer); ///< store an array of bytes + void store_var(const Variant &p_var); - void store_var(const Variant& p_var); + bool file_exists(const String &p_name) const; ///< return true if a file exists - bool file_exists(const String& p_name) const; ///< return true if a file exists - - uint64_t get_modified_time(const String& p_file) const; + uint64_t get_modified_time(const String &p_file) const; _File(); virtual ~_File(); - }; class _Directory : public Reference { - OBJ_TYPE(_Directory,Reference); + OBJ_TYPE(_Directory, Reference); DirAccess *d; + protected: - static void _bind_methods(); -public: - Error open(const String& p_path); +public: + Error open(const String &p_path); bool list_dir_begin(); ///< This starts dir listing String get_next(); @@ -497,48 +479,42 @@ public: int get_space_left(); - Error copy(String p_from,String p_to); + Error copy(String p_from, String p_to); Error rename(String p_from, String p_to); Error remove(String p_name); - _Directory(); virtual ~_Directory(); - }; class _Marshalls : public Reference { - OBJ_TYPE(_Marshalls,Reference); + OBJ_TYPE(_Marshalls, Reference); protected: - static void _bind_methods(); - public: + String variant_to_base64(const Variant &p_var); + Variant base64_to_variant(const String &p_str); - String variant_to_base64(const Variant& p_var); - Variant base64_to_variant(const String& p_str); + String raw_to_base64(const DVector &p_arr); + DVector base64_to_raw(const String &p_str); - String raw_to_base64(const DVector& p_arr); - DVector base64_to_raw(const String& p_str); + String utf8_to_base64(const String &p_str); + String base64_to_utf8(const String &p_str); - String utf8_to_base64(const String& p_str); - String base64_to_utf8(const String& p_str); - - _Marshalls() {}; + _Marshalls(){}; }; - class _Mutex : public Reference { - OBJ_TYPE(_Mutex,Reference); + OBJ_TYPE(_Mutex, Reference); Mutex *mutex; static void _bind_methods(); -public: +public: void lock(); Error try_lock(); void unlock(); @@ -549,12 +525,12 @@ public: class _Semaphore : public Reference { - OBJ_TYPE(_Semaphore,Reference); + OBJ_TYPE(_Semaphore, Reference); Semaphore *semaphore; static void _bind_methods(); -public: +public: Error wait(); Error post(); @@ -564,10 +540,9 @@ public: class _Thread : public Reference { - OBJ_TYPE(_Thread,Reference); + OBJ_TYPE(_Thread, Reference); protected: - Variant ret; Variant userdata; volatile bool active; @@ -576,8 +551,8 @@ protected: Thread *thread; static void _bind_methods(); static void _start_func(void *ud); -public: +public: enum Priority { PRIORITY_LOW, @@ -585,7 +560,7 @@ public: PRIORITY_HIGH }; - Error start(Object *p_instance,const StringName& p_method,const Variant& p_userdata=Variant(),int p_priority=PRIORITY_NORMAL); + Error start(Object *p_instance, const StringName &p_method, const Variant &p_userdata = Variant(), int p_priority = PRIORITY_NORMAL); String get_id() const; bool is_active() const; Variant wait_to_finish(); diff --git a/core/color.cpp b/core/color.cpp index 89accbb6d2b..ccd888e0559 100644 --- a/core/color.cpp +++ b/core/color.cpp @@ -27,82 +27,80 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "color.h" +#include "color_names.inc" +#include "map.h" #include "math_funcs.h" #include "print_string.h" -#include "map.h" -#include "color_names.inc" uint32_t Color::to_ARGB32() const { - uint32_t c=(uint8_t)(a*255); - c<<=8; - c|=(uint8_t)(r*255); - c<<=8; - c|=(uint8_t)(g*255); - c<<=8; - c|=(uint8_t)(b*255); + uint32_t c = (uint8_t)(a * 255); + c <<= 8; + c |= (uint8_t)(r * 255); + c <<= 8; + c |= (uint8_t)(g * 255); + c <<= 8; + c |= (uint8_t)(b * 255); return c; } uint32_t Color::to_32() const { - uint32_t c=(uint8_t)(a*255); - c<<=8; - c|=(uint8_t)(r*255); - c<<=8; - c|=(uint8_t)(g*255); - c<<=8; - c|=(uint8_t)(b*255); + uint32_t c = (uint8_t)(a * 255); + c <<= 8; + c |= (uint8_t)(r * 255); + c <<= 8; + c |= (uint8_t)(g * 255); + c <<= 8; + c |= (uint8_t)(b * 255); return c; } float Color::get_h() const { - float min = MIN( r, g ); - min = MIN( min, b ); - float max = MAX( r, g ); - max = MAX( max, b ); + float min = MIN(r, g); + min = MIN(min, b); + float max = MAX(r, g); + max = MAX(max, b); float delta = max - min; - if( delta == 0 ) + if (delta == 0) return 0; float h; - if( r == max ) - h = ( g - b ) / delta; // between yellow & magenta - else if( g == max ) - h = 2 + ( b - r ) / delta; // between cyan & yellow + if (r == max) + h = (g - b) / delta; // between yellow & magenta + else if (g == max) + h = 2 + (b - r) / delta; // between cyan & yellow else - h = 4 + ( r - g ) / delta; // between magenta & cyan + h = 4 + (r - g) / delta; // between magenta & cyan - h/=6.0; - if (h<0) - h+=1.0; + h /= 6.0; + if (h < 0) + h += 1.0; return h; } float Color::get_s() const { - - float min = MIN( r, g ); - min = MIN( min, b ); - float max = MAX( r, g ); - max = MAX( max, b ); + float min = MIN(r, g); + min = MIN(min, b); + float max = MAX(r, g); + max = MAX(max, b); float delta = max - min; - return (max!=0) ? (delta / max) : 0; - + return (max != 0) ? (delta / max) : 0; } float Color::get_v() const { - float max = MAX( r, g ); - max = MAX( max, b ); + float max = MAX(r, g); + max = MAX(max, b); return max; } @@ -110,24 +108,24 @@ void Color::set_hsv(float p_h, float p_s, float p_v, float p_alpha) { int i; float f, p, q, t; - a=p_alpha; + a = p_alpha; - if( p_s == 0 ) { + if (p_s == 0) { // acp_hromatic (grey) r = g = b = p_v; return; } - p_h *=6.0; - p_h = Math::fmod(p_h,6); - i = Math::floor( p_h ); + p_h *= 6.0; + p_h = Math::fmod(p_h, 6); + i = Math::floor(p_h); f = p_h - i; - p = p_v * ( 1 - p_s ); - q = p_v * ( 1 - p_s * f ); - t = p_v * ( 1 - p_s * ( 1 - f ) ); + p = p_v * (1 - p_s); + q = p_v * (1 - p_s * f); + t = p_v * (1 - p_s * (1 - f)); - switch( i ) { + switch (i) { case 0: // Red is the dominant color r = p_v; g = t; @@ -163,170 +161,166 @@ void Color::set_hsv(float p_h, float p_s, float p_v, float p_alpha) { void Color::invert() { - r=1.0-r; - g=1.0-g; - b=1.0-b; + r = 1.0 - r; + g = 1.0 - g; + b = 1.0 - b; } void Color::contrast() { - r=Math::fmod(r+0.5,1.0); - g=Math::fmod(g+0.5,1.0); - b=Math::fmod(b+0.5,1.0); + r = Math::fmod(r + 0.5, 1.0); + g = Math::fmod(g + 0.5, 1.0); + b = Math::fmod(b + 0.5, 1.0); } Color Color::hex(uint32_t p_hex) { - float a = (p_hex&0xFF)/255.0; - p_hex>>=8; - float b = (p_hex&0xFF)/255.0; - p_hex>>=8; - float g = (p_hex&0xFF)/255.0; - p_hex>>=8; - float r = (p_hex&0xFF)/255.0; + float a = (p_hex & 0xFF) / 255.0; + p_hex >>= 8; + float b = (p_hex & 0xFF) / 255.0; + p_hex >>= 8; + float g = (p_hex & 0xFF) / 255.0; + p_hex >>= 8; + float r = (p_hex & 0xFF) / 255.0; - return Color(r,g,b,a); + return Color(r, g, b, a); } -static float _parse_col(const String& p_str, int p_ofs) { +static float _parse_col(const String &p_str, int p_ofs) { - int ig=0; + int ig = 0; - for(int i=0;i<2;i++) { + for (int i = 0; i < 2; i++) { - int c=p_str[i+p_ofs]; - int v=0; + int c = p_str[i + p_ofs]; + int v = 0; - 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 { return -1; } - if (i==0) - ig+=v*16; + if (i == 0) + ig += v * 16; else - ig+=v; - + ig += v; } return ig; - } Color Color::inverted() const { - Color c=*this; + Color c = *this; c.invert(); return c; } Color Color::contrasted() const { - Color c=*this; + Color c = *this; c.contrast(); return c; } - -Color Color::html(const String& p_color) { +Color Color::html(const String &p_color) { String color = p_color; - if (color.length()==0) + if (color.length() == 0) return Color(); - if (color[0]=='#') - color=color.substr(1,color.length()-1); + if (color[0] == '#') + color = color.substr(1, color.length() - 1); - bool alpha=false; + bool alpha = false; - if (color.length()==8) { - alpha=true; - } else if (color.length()==6) { - alpha=false; + if (color.length() == 8) { + alpha = true; + } else if (color.length() == 6) { + alpha = false; } else { - ERR_EXPLAIN("Invalid Color Code: "+p_color); + ERR_EXPLAIN("Invalid Color Code: " + p_color); ERR_FAIL_V(Color()); } - int a=255; + int a = 255; if (alpha) { - a=_parse_col(color,0); - if (a<0) { - ERR_EXPLAIN("Invalid Color Code: "+p_color); + a = _parse_col(color, 0); + if (a < 0) { + ERR_EXPLAIN("Invalid Color Code: " + p_color); ERR_FAIL_V(Color()); } } - int from=alpha?2:0; + int from = alpha ? 2 : 0; - int r=_parse_col(color,from+0); - if (r<0) { - ERR_EXPLAIN("Invalid Color Code: "+p_color); + int r = _parse_col(color, from + 0); + if (r < 0) { + ERR_EXPLAIN("Invalid Color Code: " + p_color); ERR_FAIL_V(Color()); } - int g=_parse_col(color,from+2); - if (g<0) { - ERR_EXPLAIN("Invalid Color Code: "+p_color); + int g = _parse_col(color, from + 2); + if (g < 0) { + ERR_EXPLAIN("Invalid Color Code: " + p_color); ERR_FAIL_V(Color()); } - int b=_parse_col(color,from+4); - if (b<0) { - ERR_EXPLAIN("Invalid Color Code: "+p_color); + int b = _parse_col(color, from + 4); + if (b < 0) { + ERR_EXPLAIN("Invalid Color Code: " + p_color); ERR_FAIL_V(Color()); } - return Color(r/255.0,g/255.0,b/255.0,a/255.0); + return Color(r / 255.0, g / 255.0, b / 255.0, a / 255.0); } -bool Color::html_is_valid(const String& p_color) { +bool Color::html_is_valid(const String &p_color) { String color = p_color; - if (color.length()==0) + if (color.length() == 0) return false; - if (color[0]=='#') - color=color.substr(1,color.length()-1); + if (color[0] == '#') + color = color.substr(1, color.length() - 1); - bool alpha=false; + bool alpha = false; - if (color.length()==8) { - alpha=true; - } else if (color.length()==6) { - alpha=false; + if (color.length() == 8) { + alpha = true; + } else if (color.length() == 6) { + alpha = false; } else { return false; } - int a=255; + int a = 255; if (alpha) { - a=_parse_col(color,0); - if (a<0) { + a = _parse_col(color, 0); + if (a < 0) { return false; } } - int from=alpha?2:0; + int from = alpha ? 2 : 0; - int r=_parse_col(color,from+0); - if (r<0) { + int r = _parse_col(color, from + 0); + if (r < 0) { return false; } - int g=_parse_col(color,from+2); - if (g<0) { + int g = _parse_col(color, from + 2); + if (g < 0) { return false; } - int b=_parse_col(color,from+4); - if (b<0) { + int b = _parse_col(color, from + 4); + if (b < 0) { return false; } return true; - } Color Color::named(const String &p_name) { @@ -339,12 +333,12 @@ Color Color::named(const String &p_name) { name = name.replace("'", ""); name = name.replace(".", ""); name = name.to_lower(); - - const Map::Element* color = _named_colors.find(name); - if(color) { + + const Map::Element *color = _named_colors.find(name); + if (color) { return color->value(); } else { - ERR_EXPLAIN("Invalid Color Name: "+p_name); + ERR_EXPLAIN("Invalid Color Name: " + p_name); ERR_FAIL_V(Color()); } } @@ -352,48 +346,43 @@ Color Color::named(const String &p_name) { String _to_hex(float p_val) { int v = p_val * 255; - v = CLAMP(v,0,255); + v = CLAMP(v, 0, 255); String ret; - for(int i=0;i<2;i++) { + for (int i = 0; i < 2; i++) { - CharType c[2]={0,0}; - int lv = v&0xF; - if (lv<10) - c[0]='0'+lv; + CharType c[2] = { 0, 0 }; + int lv = v & 0xF; + if (lv < 10) + c[0] = '0' + lv; else - c[0]='a'+lv-10; + c[0] = 'a' + lv - 10; - v>>=4; - String cs=(const CharType*)c; + v >>= 4; + String cs = (const CharType *)c; ret = cs + ret; } return ret; - } String Color::to_html(bool p_alpha) const { String txt; - txt+=_to_hex(r); - txt+=_to_hex(g); - txt+=_to_hex(b); + txt += _to_hex(r); + txt += _to_hex(g); + txt += _to_hex(b); if (p_alpha) - txt=_to_hex(a)+txt; + txt = _to_hex(a) + txt; return txt; - } - float Color::gray() const { - return (r+g+b)/3.0; + return (r + g + b) / 3.0; } Color::operator String() const { - return rtos(r)+", "+rtos(g)+", "+rtos(b)+", "+rtos(a); + return rtos(r) + ", " + rtos(g) + ", " + rtos(b) + ", " + rtos(a); } - - diff --git a/core/color.h b/core/color.h index 50a6761340b..2339cd6cd72 100644 --- a/core/color.h +++ b/core/color.h @@ -29,8 +29,8 @@ #ifndef COLOR_H #define COLOR_H -#include "ustring.h" #include "math_funcs.h" +#include "ustring.h" /** @author Juan Linietsky */ @@ -47,8 +47,8 @@ struct Color { float components[4]; }; - bool operator==(const Color &p_color) const { return (r==p_color.r && g==p_color.g && b==p_color.b && a==p_color.a ); } - bool operator!=(const Color &p_color) const { return (r!=p_color.r || g!=p_color.g || b!=p_color.b || a!=p_color.a ); } + bool operator==(const Color &p_color) const { return (r == p_color.r && g == p_color.g && b == p_color.b && a == p_color.a); } + bool operator!=(const Color &p_color) const { return (r != p_color.r || g != p_color.g || b != p_color.b || a != p_color.a); } uint32_t to_32() const; uint32_t to_ARGB32() const; @@ -56,12 +56,12 @@ struct Color { float get_h() const; float get_s() const; float get_v() const; - void set_hsv(float p_h, float p_s, float p_v, float p_alpha=1.0); + void set_hsv(float p_h, float p_s, float p_v, float p_alpha = 1.0); - _FORCE_INLINE_ float& operator[](int idx) { + _FORCE_INLINE_ float &operator[](int idx) { return components[idx]; } - _FORCE_INLINE_ const float& operator[](int idx) const { + _FORCE_INLINE_ const float &operator[](int idx) const { return components[idx]; } @@ -70,30 +70,29 @@ struct Color { Color inverted() const; Color contrasted() const; - _FORCE_INLINE_ Color linear_interpolate(const Color& p_b, float p_t) const { + _FORCE_INLINE_ Color linear_interpolate(const Color &p_b, float p_t) const { - Color res=*this; + Color res = *this; - res.r+= (p_t * (p_b.r-r)); - res.g+= (p_t * (p_b.g-g)); - res.b+= (p_t * (p_b.b-b)); - res.a+= (p_t * (p_b.a-a)); + res.r += (p_t * (p_b.r - r)); + res.g += (p_t * (p_b.g - g)); + res.b += (p_t * (p_b.b - b)); + res.a += (p_t * (p_b.a - a)); return res; } - _FORCE_INLINE_ Color blend(const Color& p_over) const { - + _FORCE_INLINE_ Color blend(const Color &p_over) const { Color res; float sa = 1.0 - p_over.a; - res.a = a*sa+p_over.a; - if (res.a==0) { - return Color(0,0,0,0); + res.a = a * sa + p_over.a; + if (res.a == 0) { + return Color(0, 0, 0, 0); } else { - res.r = (r*a*sa + p_over.r * p_over.a)/res.a; - res.g = (g*a*sa + p_over.g * p_over.a)/res.a; - res.b = (b*a*sa + p_over.b * p_over.a)/res.a; + res.r = (r * a * sa + p_over.r * p_over.a) / res.a; + res.g = (g * a * sa + p_over.g * p_over.a) / res.a; + res.b = (b * a * sa + p_over.b * p_over.a) / res.a; } return res; } @@ -101,48 +100,54 @@ struct Color { _FORCE_INLINE_ Color to_linear() const { return Color( - r<0.04045 ? r * (1.0 / 12.92) : Math::pow((r + 0.055) * (1.0 / (1 + 0.055)), 2.4), - g<0.04045 ? g * (1.0 / 12.92) : Math::pow((g + 0.055) * (1.0 / (1 + 0.055)), 2.4), - b<0.04045 ? b * (1.0 / 12.92) : Math::pow((b + 0.055) * (1.0 / (1 + 0.055)), 2.4), - a - ); + r < 0.04045 ? r * (1.0 / 12.92) : Math::pow((r + 0.055) * (1.0 / (1 + 0.055)), 2.4), + g < 0.04045 ? g * (1.0 / 12.92) : Math::pow((g + 0.055) * (1.0 / (1 + 0.055)), 2.4), + b < 0.04045 ? b * (1.0 / 12.92) : Math::pow((b + 0.055) * (1.0 / (1 + 0.055)), 2.4), + a); } static Color hex(uint32_t p_hex); - static Color html(const String& p_color); - static bool html_is_valid(const String& p_color); - static Color named(const String& p_name); - String to_html(bool p_alpha=true) const; + static Color html(const String &p_color); + static bool html_is_valid(const String &p_color); + static Color named(const String &p_name); + String to_html(bool p_alpha = true) const; - _FORCE_INLINE_ bool operator<(const Color& p_color) const; //used in set keys + _FORCE_INLINE_ bool operator<(const Color &p_color) const; //used in set keys operator String() const; /** * No construct parameters, r=0, g=0, b=0. a=255 */ _FORCE_INLINE_ Color() { - r=0; g=0; b=0; a=1.0; + r = 0; + g = 0; + b = 0; + a = 1.0; } /** * RGB / RGBA construct parameters. Alpha is optional, but defaults to 1.0 */ - _FORCE_INLINE_ Color(float p_r,float p_g,float p_b,float p_a=1.0) { r=p_r; g=p_g; b=p_b; a=p_a; } + _FORCE_INLINE_ Color(float p_r, float p_g, float p_b, float p_a = 1.0) { + r = p_r; + g = p_g; + b = p_b; + a = p_a; + } }; -bool Color::operator<(const Color& p_color) const { +bool Color::operator<(const Color &p_color) const { - if (r==p_color.r) { - if (g==p_color.g) { - if(b==p_color.b) { - return (adelay_usec(1000); } -CommandQueueMT::SyncSemaphore* CommandQueueMT::_alloc_sync_sem() { +CommandQueueMT::SyncSemaphore *CommandQueueMT::_alloc_sync_sem() { - int idx=-1; + int idx = -1; - while(true) { + while (true) { - for(int i=0;i */ @@ -48,69 +48,69 @@ class CommandQueueMT { struct CommandBase { - virtual void call()=0; - virtual ~CommandBase() {}; + virtual void call() = 0; + virtual ~CommandBase(){}; }; - template + template struct Command0 : public CommandBase { - T*instance; + T *instance; M method; virtual void call() { (instance->*method)(); } }; - template + template struct Command1 : public CommandBase { - T*instance; + T *instance; M method; typename GetSimpleTypeT::type_t p1; virtual void call() { (instance->*method)(p1); } }; - template + template struct Command2 : public CommandBase { - T*instance; + T *instance; M method; typename GetSimpleTypeT::type_t p1; typename GetSimpleTypeT::type_t p2; - virtual void call() { (instance->*method)(p1,p2); } + virtual void call() { (instance->*method)(p1, p2); } }; - template + template struct Command3 : public CommandBase { - T*instance; + T *instance; M method; typename GetSimpleTypeT::type_t p1; typename GetSimpleTypeT::type_t p2; typename GetSimpleTypeT::type_t p3; - virtual void call() { (instance->*method)(p1,p2,p3); } + virtual void call() { (instance->*method)(p1, p2, p3); } }; - template + template struct Command4 : public CommandBase { - T*instance; + T *instance; M method; typename GetSimpleTypeT::type_t p1; typename GetSimpleTypeT::type_t p2; typename GetSimpleTypeT::type_t p3; typename GetSimpleTypeT::type_t p4; - virtual void call() { (instance->*method)(p1,p2,p3,p4); } + virtual void call() { (instance->*method)(p1, p2, p3, p4); } }; - template + template struct Command5 : public CommandBase { - T*instance; + T *instance; M method; typename GetSimpleTypeT::type_t p1; typename GetSimpleTypeT::type_t p2; @@ -118,13 +118,13 @@ class CommandQueueMT { typename GetSimpleTypeT::type_t p4; typename GetSimpleTypeT::type_t p5; - virtual void call() { (instance->*method)(p1,p2,p3,p4,p5); } + virtual void call() { (instance->*method)(p1, p2, p3, p4, p5); } }; - template + template struct Command6 : public CommandBase { - T*instance; + T *instance; M method; typename GetSimpleTypeT::type_t p1; typename GetSimpleTypeT::type_t p2; @@ -133,13 +133,13 @@ class CommandQueueMT { typename GetSimpleTypeT::type_t p5; typename GetSimpleTypeT::type_t p6; - virtual void call() { (instance->*method)(p1,p2,p3,p4,p5,p6); } + virtual void call() { (instance->*method)(p1, p2, p3, p4, p5, p6); } }; - template + template struct Command7 : public CommandBase { - T*instance; + T *instance; M method; typename GetSimpleTypeT::type_t p1; typename GetSimpleTypeT::type_t p2; @@ -149,13 +149,13 @@ class CommandQueueMT { typename GetSimpleTypeT::type_t p6; typename GetSimpleTypeT::type_t p7; - virtual void call() { (instance->*method)(p1,p2,p3,p4,p5,p6,p7); } + virtual void call() { (instance->*method)(p1, p2, p3, p4, p5, p6, p7); } }; - template + template struct Command8 : public CommandBase { - T*instance; + T *instance; M method; typename GetSimpleTypeT::type_t p1; typename GetSimpleTypeT::type_t p2; @@ -166,96 +166,125 @@ class CommandQueueMT { typename GetSimpleTypeT::type_t p7; typename GetSimpleTypeT::type_t p8; - virtual void call() { (instance->*method)(p1,p2,p3,p4,p5,p6,p7,p8); } + virtual void call() { (instance->*method)(p1, p2, p3, p4, p5, p6, p7, p8); } }; /* comands that return */ - template + template struct CommandRet0 : public CommandBase { - T*instance; + T *instance; M method; - R* ret; + R *ret; SyncSemaphore *sync; - virtual void call() { *ret = (instance->*method)(); sync->sem->post(); sync->in_use=false; ; } + virtual void call() { + *ret = (instance->*method)(); + sync->sem->post(); + sync->in_use = false; + ; + } }; - template + template struct CommandRet1 : public CommandBase { - T*instance; + T *instance; M method; typename GetSimpleTypeT::type_t p1; - R* ret; + R *ret; SyncSemaphore *sync; - virtual void call() { *ret = (instance->*method)(p1); sync->sem->post(); sync->in_use=false; } + virtual void call() { + *ret = (instance->*method)(p1); + sync->sem->post(); + sync->in_use = false; + } }; - template + template struct CommandRet2 : public CommandBase { - T*instance; + T *instance; M method; typename GetSimpleTypeT::type_t p1; typename GetSimpleTypeT::type_t p2; - R* ret; + R *ret; SyncSemaphore *sync; - virtual void call() { *ret = (instance->*method)(p1,p2); sync->sem->post(); sync->in_use=false; ; } + virtual void call() { + *ret = (instance->*method)(p1, p2); + sync->sem->post(); + sync->in_use = false; + ; + } }; - template + template struct CommandRet3 : public CommandBase { - T*instance; + T *instance; M method; typename GetSimpleTypeT::type_t p1; typename GetSimpleTypeT::type_t p2; typename GetSimpleTypeT::type_t p3; - R* ret; + R *ret; SyncSemaphore *sync; - virtual void call() { *ret = (instance->*method)(p1,p2,p3); sync->sem->post(); sync->in_use=false; ; } + virtual void call() { + *ret = (instance->*method)(p1, p2, p3); + sync->sem->post(); + sync->in_use = false; + ; + } }; - template + template struct CommandRet4 : public CommandBase { - T*instance; + T *instance; M method; typename GetSimpleTypeT::type_t p1; typename GetSimpleTypeT::type_t p2; typename GetSimpleTypeT::type_t p3; typename GetSimpleTypeT::type_t p4; - R* ret; + R *ret; SyncSemaphore *sync; - virtual void call() { *ret = (instance->*method)(p1,p2,p3,p4); sync->sem->post(); sync->in_use=false; ; } + virtual void call() { + *ret = (instance->*method)(p1, p2, p3, p4); + sync->sem->post(); + sync->in_use = false; + ; + } }; - template + template struct CommandRet5 : public CommandBase { - T*instance; + T *instance; M method; typename GetSimpleTypeT::type_t p1; typename GetSimpleTypeT::type_t p2; typename GetSimpleTypeT::type_t p3; typename GetSimpleTypeT::type_t p4; typename GetSimpleTypeT::type_t p5; - R* ret; + R *ret; SyncSemaphore *sync; - virtual void call() { *ret = (instance->*method)(p1,p2,p3,p4,p5); sync->sem->post(); sync->in_use=false; ; } + virtual void call() { + *ret = (instance->*method)(p1, p2, p3, p4, p5); + sync->sem->post(); + sync->in_use = false; + ; + } }; - template + template struct CommandRet6 : public CommandBase { - T*instance; + T *instance; M method; typename GetSimpleTypeT::type_t p1; typename GetSimpleTypeT::type_t p2; @@ -263,16 +292,21 @@ class CommandQueueMT { typename GetSimpleTypeT::type_t p4; typename GetSimpleTypeT::type_t p5; typename GetSimpleTypeT::type_t p6; - R* ret; + R *ret; SyncSemaphore *sync; - virtual void call() { *ret = (instance->*method)(p1,p2,p3,p4,p5,p6); sync->sem->post(); sync->in_use=false; ; } + virtual void call() { + *ret = (instance->*method)(p1, p2, p3, p4, p5, p6); + sync->sem->post(); + sync->in_use = false; + ; + } }; - template + template struct CommandRet7 : public CommandBase { - T*instance; + T *instance; M method; typename GetSimpleTypeT::type_t p1; typename GetSimpleTypeT::type_t p2; @@ -281,16 +315,21 @@ class CommandQueueMT { typename GetSimpleTypeT::type_t p5; typename GetSimpleTypeT::type_t p6; typename GetSimpleTypeT::type_t p7; - R* ret; + R *ret; SyncSemaphore *sync; - virtual void call() { *ret = (instance->*method)(p1,p2,p3,p4,p5,p6,p7); sync->sem->post(); sync->in_use=false; ; } + virtual void call() { + *ret = (instance->*method)(p1, p2, p3, p4, p5, p6, p7); + sync->sem->post(); + sync->in_use = false; + ; + } }; - template + template struct CommandRet8 : public CommandBase { - T*instance; + T *instance; M method; typename GetSimpleTypeT::type_t p1; typename GetSimpleTypeT::type_t p2; @@ -300,56 +339,76 @@ class CommandQueueMT { typename GetSimpleTypeT::type_t p6; typename GetSimpleTypeT::type_t p7; typename GetSimpleTypeT::type_t p8; - R* ret; + R *ret; SyncSemaphore *sync; - virtual void call() { *ret = (instance->*method)(p1,p2,p3,p4,p5,p6,p7,p8); sync->sem->post(); sync->in_use=false; ; } + virtual void call() { + *ret = (instance->*method)(p1, p2, p3, p4, p5, p6, p7, p8); + sync->sem->post(); + sync->in_use = false; + ; + } }; /** commands that don't return but sync */ /* comands that return */ - template + template struct CommandSync0 : public CommandBase { - T*instance; + T *instance; M method; SyncSemaphore *sync; - virtual void call() { (instance->*method)(); sync->sem->post(); sync->in_use=false; ; } + virtual void call() { + (instance->*method)(); + sync->sem->post(); + sync->in_use = false; + ; + } }; - template + template struct CommandSync1 : public CommandBase { - T*instance; + T *instance; M method; typename GetSimpleTypeT::type_t p1; SyncSemaphore *sync; - virtual void call() { (instance->*method)(p1); sync->sem->post(); sync->in_use=false; ; } + virtual void call() { + (instance->*method)(p1); + sync->sem->post(); + sync->in_use = false; + ; + } }; - template + template struct CommandSync2 : public CommandBase { - T*instance; + T *instance; M method; typename GetSimpleTypeT::type_t p1; typename GetSimpleTypeT::type_t p2; SyncSemaphore *sync; - virtual void call() { (instance->*method)(p1,p2); sync->sem->post(); sync->in_use=false; ; } + virtual void call() { + (instance->*method)(p1, p2); + sync->sem->post(); + sync->in_use = false; + ; + } }; - template + template struct CommandSync3 : public CommandBase { - T*instance; + T *instance; M method; typename GetSimpleTypeT::type_t p1; typename GetSimpleTypeT::type_t p2; @@ -357,13 +416,18 @@ class CommandQueueMT { SyncSemaphore *sync; - virtual void call() { (instance->*method)(p1,p2,p3); sync->sem->post(); sync->in_use=false; ; } + virtual void call() { + (instance->*method)(p1, p2, p3); + sync->sem->post(); + sync->in_use = false; + ; + } }; - template + template struct CommandSync4 : public CommandBase { - T*instance; + T *instance; M method; typename GetSimpleTypeT::type_t p1; typename GetSimpleTypeT::type_t p2; @@ -372,13 +436,18 @@ class CommandQueueMT { SyncSemaphore *sync; - virtual void call() { (instance->*method)(p1,p2,p3,p4); sync->sem->post(); sync->in_use=false; ; } + virtual void call() { + (instance->*method)(p1, p2, p3, p4); + sync->sem->post(); + sync->in_use = false; + ; + } }; - template + template struct CommandSync5 : public CommandBase { - T*instance; + T *instance; M method; typename GetSimpleTypeT::type_t p1; typename GetSimpleTypeT::type_t p2; @@ -388,13 +457,18 @@ class CommandQueueMT { SyncSemaphore *sync; - virtual void call() { (instance->*method)(p1,p2,p3,p4,p5); sync->sem->post(); sync->in_use=false; ; } + virtual void call() { + (instance->*method)(p1, p2, p3, p4, p5); + sync->sem->post(); + sync->in_use = false; + ; + } }; - template + template struct CommandSync6 : public CommandBase { - T*instance; + T *instance; M method; typename GetSimpleTypeT::type_t p1; typename GetSimpleTypeT::type_t p2; @@ -405,13 +479,18 @@ class CommandQueueMT { SyncSemaphore *sync; - virtual void call() { (instance->*method)(p1,p2,p3,p4,p5,p6); sync->sem->post(); sync->in_use=false; ; } + virtual void call() { + (instance->*method)(p1, p2, p3, p4, p5, p6); + sync->sem->post(); + sync->in_use = false; + ; + } }; - template + template struct CommandSync7 : public CommandBase { - T*instance; + T *instance; M method; typename GetSimpleTypeT::type_t p1; typename GetSimpleTypeT::type_t p2; @@ -423,13 +502,18 @@ class CommandQueueMT { SyncSemaphore *sync; - virtual void call() { (instance->*method)(p1,p2,p3,p4,p5,p6,p7); sync->sem->post(); sync->in_use=false; ; } + virtual void call() { + (instance->*method)(p1, p2, p3, p4, p5, p6, p7); + sync->sem->post(); + sync->in_use = false; + ; + } }; - template + template struct CommandSync8 : public CommandBase { - T*instance; + T *instance; M method; typename GetSimpleTypeT::type_t p1; typename GetSimpleTypeT::type_t p2; @@ -442,18 +526,22 @@ class CommandQueueMT { SyncSemaphore *sync; - virtual void call() { (instance->*method)(p1,p2,p3,p4,p5,p6,p7,p8); sync->sem->post(); sync->in_use=false; ; } + virtual void call() { + (instance->*method)(p1, p2, p3, p4, p5, p6, p7, p8); + sync->sem->post(); + sync->in_use = false; + ; + } }; /***** BASE *******/ enum { - COMMAND_MEM_SIZE_KB=256, - COMMAND_MEM_SIZE=COMMAND_MEM_SIZE_KB*1024, - SYNC_SEMAPHORES=8 + COMMAND_MEM_SIZE_KB = 256, + COMMAND_MEM_SIZE = COMMAND_MEM_SIZE_KB * 1024, + SYNC_SEMAPHORES = 8 }; - uint8_t command_mem[COMMAND_MEM_SIZE]; uint32_t read_ptr; uint32_t write_ptr; @@ -461,255 +549,247 @@ class CommandQueueMT { Mutex *mutex; Semaphore *sync; - - template - T* allocate() { + template + T *allocate() { // alloc size is size+T+safeguard - uint32_t alloc_size=sizeof(T)+sizeof(uint32_t); + uint32_t alloc_size = sizeof(T) + sizeof(uint32_t); - tryagain: + tryagain: if (write_ptr < read_ptr) { // behind read_ptr, check that there is room - if ( (read_ptr-write_ptr) <= alloc_size ) + if ((read_ptr - write_ptr) <= alloc_size) return NULL; } else if (write_ptr >= read_ptr) { // ahead of read_ptr, check that there is room - - if ( (COMMAND_MEM_SIZE-write_ptr) < alloc_size+4 ) { + if ((COMMAND_MEM_SIZE - write_ptr) < alloc_size + 4) { // no room at the end, wrap down; - if (read_ptr==0) // dont want write_ptr to become read_ptr + if (read_ptr == 0) // dont want write_ptr to become read_ptr return NULL; // if this happens, it's a bug - ERR_FAIL_COND_V( (COMMAND_MEM_SIZE-write_ptr) < sizeof(uint32_t), NULL ); + ERR_FAIL_COND_V((COMMAND_MEM_SIZE - write_ptr) < sizeof(uint32_t), NULL); // zero means, wrap to begining - uint32_t * p = (uint32_t*)&command_mem[write_ptr]; - *p=0; - write_ptr=0; + uint32_t *p = (uint32_t *)&command_mem[write_ptr]; + *p = 0; + write_ptr = 0; goto tryagain; } } // allocate the size - uint32_t * p = (uint32_t*)&command_mem[write_ptr]; - *p=sizeof(T); - write_ptr+=sizeof(uint32_t); + uint32_t *p = (uint32_t *)&command_mem[write_ptr]; + *p = sizeof(T); + write_ptr += sizeof(uint32_t); // allocate the command - T* cmd = memnew_placement( &command_mem[write_ptr], T ); - write_ptr+=sizeof(T); + T *cmd = memnew_placement(&command_mem[write_ptr], T); + write_ptr += sizeof(T); return cmd; - } - template - T* allocate_and_lock() { + template + T *allocate_and_lock() { lock(); - T* ret; + T *ret; - while ( (ret=allocate())==NULL ) { + while ((ret = allocate()) == NULL) { unlock(); // sleep a little until fetch happened and some room is made wait_for_flush(); lock(); - } return ret; } - bool flush_one() { - tryagain: + tryagain: // tried to read an empty queue - if (read_ptr == write_ptr ) + if (read_ptr == write_ptr) return false; - uint32_t size = *(uint32_t*)( &command_mem[read_ptr] ); + uint32_t size = *(uint32_t *)(&command_mem[read_ptr]); - if (size==0) { + if (size == 0) { //end of ringbuffer, wrap - read_ptr=0; + read_ptr = 0; goto tryagain; } - read_ptr+=sizeof(uint32_t); + read_ptr += sizeof(uint32_t); - CommandBase *cmd = reinterpret_cast( &command_mem[read_ptr] ); + CommandBase *cmd = reinterpret_cast(&command_mem[read_ptr]); cmd->call(); cmd->~CommandBase(); - read_ptr+=size; + read_ptr += size; return true; } - void lock(); void unlock(); void wait_for_flush(); - SyncSemaphore* _alloc_sync_sem(); - + SyncSemaphore *_alloc_sync_sem(); public: - /* NORMAL PUSH COMMANDS */ - template - void push( T * p_instance, M p_method ) { + template + void push(T *p_instance, M p_method) { - Command0 * cmd = allocate_and_lock< Command0 >(); + Command0 *cmd = allocate_and_lock >(); - cmd->instance=p_instance; - cmd->method=p_method; + cmd->instance = p_instance; + cmd->method = p_method; unlock(); if (sync) sync->post(); } - template - void push( T * p_instance, M p_method, P1 p1 ) { + template + void push(T *p_instance, M p_method, P1 p1) { - Command1 * cmd = allocate_and_lock< Command1 >(); + Command1 *cmd = allocate_and_lock >(); - cmd->instance=p_instance; - cmd->method=p_method; - cmd->p1=p1; + cmd->instance = p_instance; + cmd->method = p_method; + cmd->p1 = p1; unlock(); if (sync) sync->post(); } - template - void push( T * p_instance, M p_method, P1 p1, P2 p2 ) { + template + void push(T *p_instance, M p_method, P1 p1, P2 p2) { - Command2 * cmd = allocate_and_lock< Command2 >(); + Command2 *cmd = allocate_and_lock >(); - cmd->instance=p_instance; - cmd->method=p_method; - cmd->p1=p1; - cmd->p2=p2; + cmd->instance = p_instance; + cmd->method = p_method; + cmd->p1 = p1; + cmd->p2 = p2; unlock(); if (sync) sync->post(); } - template - void push( T * p_instance, M p_method, P1 p1, P2 p2, P3 p3 ) { + template + void push(T *p_instance, M p_method, P1 p1, P2 p2, P3 p3) { - Command3 * cmd = allocate_and_lock< Command3 >(); + Command3 *cmd = allocate_and_lock >(); - cmd->instance=p_instance; - cmd->method=p_method; - cmd->p1=p1; - cmd->p2=p2; - cmd->p3=p3; + cmd->instance = p_instance; + cmd->method = p_method; + cmd->p1 = p1; + cmd->p2 = p2; + cmd->p3 = p3; unlock(); if (sync) sync->post(); } - template - void push( T * p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4 ) { + template + void push(T *p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4) { - Command4 * cmd = allocate_and_lock< Command4 >(); + Command4 *cmd = allocate_and_lock >(); - cmd->instance=p_instance; - cmd->method=p_method; - cmd->p1=p1; - cmd->p2=p2; - cmd->p3=p3; - cmd->p4=p4; + cmd->instance = p_instance; + cmd->method = p_method; + cmd->p1 = p1; + cmd->p2 = p2; + cmd->p3 = p3; + cmd->p4 = p4; unlock(); if (sync) sync->post(); } - template - void push( T * p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5 ) { + template + void push(T *p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5) { - Command5 * cmd = allocate_and_lock< Command5 >(); + Command5 *cmd = allocate_and_lock >(); - cmd->instance=p_instance; - cmd->method=p_method; - cmd->p1=p1; - cmd->p2=p2; - cmd->p3=p3; - cmd->p4=p4; - cmd->p5=p5; + cmd->instance = p_instance; + cmd->method = p_method; + cmd->p1 = p1; + cmd->p2 = p2; + cmd->p3 = p3; + cmd->p4 = p4; + cmd->p5 = p5; unlock(); if (sync) sync->post(); } - template - void push( T * p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6 ) { + template + void push(T *p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6) { - Command6 * cmd = allocate_and_lock< Command6 >(); + Command6 *cmd = allocate_and_lock >(); - cmd->instance=p_instance; - cmd->method=p_method; - cmd->p1=p1; - cmd->p2=p2; - cmd->p3=p3; - cmd->p4=p4; - cmd->p5=p5; - cmd->p6=p6; + cmd->instance = p_instance; + cmd->method = p_method; + cmd->p1 = p1; + cmd->p2 = p2; + cmd->p3 = p3; + cmd->p4 = p4; + cmd->p5 = p5; + cmd->p6 = p6; unlock(); if (sync) sync->post(); } - template - void push( T * p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7 ) { + template + void push(T *p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7) { - Command7 * cmd = allocate_and_lock< Command7 >(); + Command7 *cmd = allocate_and_lock >(); - cmd->instance=p_instance; - cmd->method=p_method; - cmd->p1=p1; - cmd->p2=p2; - cmd->p3=p3; - cmd->p4=p4; - cmd->p5=p5; - cmd->p6=p6; - cmd->p7=p7; + cmd->instance = p_instance; + cmd->method = p_method; + cmd->p1 = p1; + cmd->p2 = p2; + cmd->p3 = p3; + cmd->p4 = p4; + cmd->p5 = p5; + cmd->p6 = p6; + cmd->p7 = p7; unlock(); if (sync) sync->post(); } - template - void push( T * p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7, P8 p8 ) { + template + void push(T *p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7, P8 p8) { - Command8 * cmd = allocate_and_lock< Command8 >(); + Command8 *cmd = allocate_and_lock >(); - cmd->instance=p_instance; - cmd->method=p_method; - cmd->p1=p1; - cmd->p2=p2; - cmd->p3=p3; - cmd->p4=p4; - cmd->p5=p5; - cmd->p6=p6; - cmd->p7=p7; - cmd->p8=p8; + cmd->instance = p_instance; + cmd->method = p_method; + cmd->p1 = p1; + cmd->p2 = p2; + cmd->p3 = p3; + cmd->p4 = p4; + cmd->p5 = p5; + cmd->p6 = p6; + cmd->p7 = p7; + cmd->p8 = p8; unlock(); @@ -717,17 +797,16 @@ public: } /*** PUSH AND RET COMMANDS ***/ + template + void push_and_ret(T *p_instance, M p_method, R *r_ret) { - template - void push_and_ret( T * p_instance, M p_method, R* r_ret) { + CommandRet0 *cmd = allocate_and_lock >(); - CommandRet0 * cmd = allocate_and_lock< CommandRet0 >(); - - cmd->instance=p_instance; - cmd->method=p_method; - cmd->ret=r_ret; - SyncSemaphore *ss=_alloc_sync_sem(); - cmd->sync=ss; + cmd->instance = p_instance; + cmd->method = p_method; + cmd->ret = r_ret; + SyncSemaphore *ss = _alloc_sync_sem(); + cmd->sync = ss; unlock(); @@ -735,17 +814,17 @@ public: ss->sem->wait(); } - template - void push_and_ret( T * p_instance, M p_method, P1 p1, R* r_ret) { + template + void push_and_ret(T *p_instance, M p_method, P1 p1, R *r_ret) { - CommandRet1 * cmd = allocate_and_lock< CommandRet1 >(); + CommandRet1 *cmd = allocate_and_lock >(); - cmd->instance=p_instance; - cmd->method=p_method; - cmd->p1=p1; - cmd->ret=r_ret; - SyncSemaphore *ss=_alloc_sync_sem(); - cmd->sync=ss; + cmd->instance = p_instance; + cmd->method = p_method; + cmd->p1 = p1; + cmd->ret = r_ret; + SyncSemaphore *ss = _alloc_sync_sem(); + cmd->sync = ss; unlock(); @@ -753,18 +832,18 @@ public: ss->sem->wait(); } - template - void push_and_ret( T * p_instance, M p_method, P1 p1, P2 p2, R* r_ret) { + template + void push_and_ret(T *p_instance, M p_method, P1 p1, P2 p2, R *r_ret) { - CommandRet2 * cmd = allocate_and_lock< CommandRet2 >(); + CommandRet2 *cmd = allocate_and_lock >(); - cmd->instance=p_instance; - cmd->method=p_method; - cmd->p1=p1; - cmd->p2=p2; - cmd->ret=r_ret; - SyncSemaphore *ss=_alloc_sync_sem(); - cmd->sync=ss; + cmd->instance = p_instance; + cmd->method = p_method; + cmd->p1 = p1; + cmd->p2 = p2; + cmd->ret = r_ret; + SyncSemaphore *ss = _alloc_sync_sem(); + cmd->sync = ss; unlock(); @@ -772,19 +851,19 @@ public: ss->sem->wait(); } - template - void push_and_ret( T * p_instance, M p_method, P1 p1, P2 p2, P3 p3, R* r_ret ) { + template + void push_and_ret(T *p_instance, M p_method, P1 p1, P2 p2, P3 p3, R *r_ret) { - CommandRet3 * cmd = allocate_and_lock< CommandRet3 >(); + CommandRet3 *cmd = allocate_and_lock >(); - cmd->instance=p_instance; - cmd->method=p_method; - cmd->p1=p1; - cmd->p2=p2; - cmd->p3=p3; - cmd->ret=r_ret; - SyncSemaphore *ss=_alloc_sync_sem(); - cmd->sync=ss; + cmd->instance = p_instance; + cmd->method = p_method; + cmd->p1 = p1; + cmd->p2 = p2; + cmd->p3 = p3; + cmd->ret = r_ret; + SyncSemaphore *ss = _alloc_sync_sem(); + cmd->sync = ss; unlock(); @@ -792,20 +871,20 @@ public: ss->sem->wait(); } - template - void push_and_ret( T * p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4, R* r_ret ) { + template + void push_and_ret(T *p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4, R *r_ret) { - CommandRet4 * cmd = allocate_and_lock< CommandRet4 >(); + CommandRet4 *cmd = allocate_and_lock >(); - cmd->instance=p_instance; - cmd->method=p_method; - cmd->p1=p1; - cmd->p2=p2; - cmd->p3=p3; - cmd->p4=p4; - cmd->ret=r_ret; - SyncSemaphore *ss=_alloc_sync_sem(); - cmd->sync=ss; + cmd->instance = p_instance; + cmd->method = p_method; + cmd->p1 = p1; + cmd->p2 = p2; + cmd->p3 = p3; + cmd->p4 = p4; + cmd->ret = r_ret; + SyncSemaphore *ss = _alloc_sync_sem(); + cmd->sync = ss; unlock(); @@ -813,21 +892,21 @@ public: ss->sem->wait(); } - template - void push_and_ret( T * p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, R* r_ret ) { + template + void push_and_ret(T *p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, R *r_ret) { - CommandRet5 * cmd = allocate_and_lock< CommandRet5 >(); + CommandRet5 *cmd = allocate_and_lock >(); - cmd->instance=p_instance; - cmd->method=p_method; - cmd->p1=p1; - cmd->p2=p2; - cmd->p3=p3; - cmd->p4=p4; - cmd->p5=p5; - cmd->ret=r_ret; - SyncSemaphore *ss=_alloc_sync_sem(); - cmd->sync=ss; + cmd->instance = p_instance; + cmd->method = p_method; + cmd->p1 = p1; + cmd->p2 = p2; + cmd->p3 = p3; + cmd->p4 = p4; + cmd->p5 = p5; + cmd->ret = r_ret; + SyncSemaphore *ss = _alloc_sync_sem(); + cmd->sync = ss; unlock(); @@ -835,22 +914,22 @@ public: ss->sem->wait(); } - template - void push_and_ret( T * p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, R* r_ret ) { + template + void push_and_ret(T *p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, R *r_ret) { - CommandRet6 * cmd = allocate_and_lock< CommandRet6 >(); + CommandRet6 *cmd = allocate_and_lock >(); - cmd->instance=p_instance; - cmd->method=p_method; - cmd->p1=p1; - cmd->p2=p2; - cmd->p3=p3; - cmd->p4=p4; - cmd->p5=p5; - cmd->p6=p6; - cmd->ret=r_ret; - SyncSemaphore *ss=_alloc_sync_sem(); - cmd->sync=ss; + cmd->instance = p_instance; + cmd->method = p_method; + cmd->p1 = p1; + cmd->p2 = p2; + cmd->p3 = p3; + cmd->p4 = p4; + cmd->p5 = p5; + cmd->p6 = p6; + cmd->ret = r_ret; + SyncSemaphore *ss = _alloc_sync_sem(); + cmd->sync = ss; unlock(); @@ -858,23 +937,23 @@ public: ss->sem->wait(); } - template - void push_and_ret( T * p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6,P7 p7, R* r_ret ) { + template + void push_and_ret(T *p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7, R *r_ret) { - CommandRet7 * cmd = allocate_and_lock< CommandRet7 >(); + CommandRet7 *cmd = allocate_and_lock >(); - cmd->instance=p_instance; - cmd->method=p_method; - cmd->p1=p1; - cmd->p2=p2; - cmd->p3=p3; - cmd->p4=p4; - cmd->p5=p5; - cmd->p6=p6; - cmd->p7=p7; - cmd->ret=r_ret; - SyncSemaphore *ss=_alloc_sync_sem(); - cmd->sync=ss; + cmd->instance = p_instance; + cmd->method = p_method; + cmd->p1 = p1; + cmd->p2 = p2; + cmd->p3 = p3; + cmd->p4 = p4; + cmd->p5 = p5; + cmd->p6 = p6; + cmd->p7 = p7; + cmd->ret = r_ret; + SyncSemaphore *ss = _alloc_sync_sem(); + cmd->sync = ss; unlock(); @@ -882,24 +961,24 @@ public: ss->sem->wait(); } - template - void push_and_ret( T * p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6,P7 p7,P8 p8, R* r_ret ) { + template + void push_and_ret(T *p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7, P8 p8, R *r_ret) { - CommandRet8 * cmd = allocate_and_lock< CommandRet8 >(); + CommandRet8 *cmd = allocate_and_lock >(); - cmd->instance=p_instance; - cmd->method=p_method; - cmd->p1=p1; - cmd->p2=p2; - cmd->p3=p3; - cmd->p4=p4; - cmd->p5=p5; - cmd->p6=p6; - cmd->p7=p7; - cmd->p8=p8; - cmd->ret=r_ret; - SyncSemaphore *ss=_alloc_sync_sem(); - cmd->sync=ss; + cmd->instance = p_instance; + cmd->method = p_method; + cmd->p1 = p1; + cmd->p2 = p2; + cmd->p3 = p3; + cmd->p4 = p4; + cmd->p5 = p5; + cmd->p6 = p6; + cmd->p7 = p7; + cmd->p8 = p8; + cmd->ret = r_ret; + SyncSemaphore *ss = _alloc_sync_sem(); + cmd->sync = ss; unlock(); @@ -907,17 +986,16 @@ public: ss->sem->wait(); } + template + void push_and_sync(T *p_instance, M p_method) { - template - void push_and_sync( T * p_instance, M p_method) { + CommandSync0 *cmd = allocate_and_lock >(); - CommandSync0 * cmd = allocate_and_lock< CommandSync0 >(); + cmd->instance = p_instance; + cmd->method = p_method; - cmd->instance=p_instance; - cmd->method=p_method; - - SyncSemaphore *ss=_alloc_sync_sem(); - cmd->sync=ss; + SyncSemaphore *ss = _alloc_sync_sem(); + cmd->sync = ss; unlock(); @@ -925,17 +1003,17 @@ public: ss->sem->wait(); } - template - void push_and_sync( T * p_instance, M p_method, P1 p1) { + template + void push_and_sync(T *p_instance, M p_method, P1 p1) { - CommandSync1 * cmd = allocate_and_lock< CommandSync1 >(); + CommandSync1 *cmd = allocate_and_lock >(); - cmd->instance=p_instance; - cmd->method=p_method; - cmd->p1=p1; + cmd->instance = p_instance; + cmd->method = p_method; + cmd->p1 = p1; - SyncSemaphore *ss=_alloc_sync_sem(); - cmd->sync=ss; + SyncSemaphore *ss = _alloc_sync_sem(); + cmd->sync = ss; unlock(); @@ -943,18 +1021,18 @@ public: ss->sem->wait(); } - template - void push_and_sync( T * p_instance, M p_method, P1 p1, P2 p2) { + template + void push_and_sync(T *p_instance, M p_method, P1 p1, P2 p2) { - CommandSync2 * cmd = allocate_and_lock< CommandSync2 >(); + CommandSync2 *cmd = allocate_and_lock >(); - cmd->instance=p_instance; - cmd->method=p_method; - cmd->p1=p1; - cmd->p2=p2; + cmd->instance = p_instance; + cmd->method = p_method; + cmd->p1 = p1; + cmd->p2 = p2; - SyncSemaphore *ss=_alloc_sync_sem(); - cmd->sync=ss; + SyncSemaphore *ss = _alloc_sync_sem(); + cmd->sync = ss; unlock(); @@ -962,19 +1040,19 @@ public: ss->sem->wait(); } - template - void push_and_sync( T * p_instance, M p_method, P1 p1, P2 p2, P3 p3 ) { + template + void push_and_sync(T *p_instance, M p_method, P1 p1, P2 p2, P3 p3) { - CommandSync3 * cmd = allocate_and_lock< CommandSync3 >(); + CommandSync3 *cmd = allocate_and_lock >(); - cmd->instance=p_instance; - cmd->method=p_method; - cmd->p1=p1; - cmd->p2=p2; - cmd->p3=p3; + cmd->instance = p_instance; + cmd->method = p_method; + cmd->p1 = p1; + cmd->p2 = p2; + cmd->p3 = p3; - SyncSemaphore *ss=_alloc_sync_sem(); - cmd->sync=ss; + SyncSemaphore *ss = _alloc_sync_sem(); + cmd->sync = ss; unlock(); @@ -982,20 +1060,20 @@ public: ss->sem->wait(); } - template - void push_and_sync( T * p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4 ) { + template + void push_and_sync(T *p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4) { - CommandSync4 * cmd = allocate_and_lock< CommandSync4 >(); + CommandSync4 *cmd = allocate_and_lock >(); - cmd->instance=p_instance; - cmd->method=p_method; - cmd->p1=p1; - cmd->p2=p2; - cmd->p3=p3; - cmd->p4=p4; + cmd->instance = p_instance; + cmd->method = p_method; + cmd->p1 = p1; + cmd->p2 = p2; + cmd->p3 = p3; + cmd->p4 = p4; - SyncSemaphore *ss=_alloc_sync_sem(); - cmd->sync=ss; + SyncSemaphore *ss = _alloc_sync_sem(); + cmd->sync = ss; unlock(); @@ -1003,21 +1081,21 @@ public: ss->sem->wait(); } - template - void push_and_sync( T * p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5 ) { + template + void push_and_sync(T *p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5) { - CommandSync5 * cmd = allocate_and_lock< CommandSync5 >(); + CommandSync5 *cmd = allocate_and_lock >(); - cmd->instance=p_instance; - cmd->method=p_method; - cmd->p1=p1; - cmd->p2=p2; - cmd->p3=p3; - cmd->p4=p4; - cmd->p5=p5; + cmd->instance = p_instance; + cmd->method = p_method; + cmd->p1 = p1; + cmd->p2 = p2; + cmd->p3 = p3; + cmd->p4 = p4; + cmd->p5 = p5; - SyncSemaphore *ss=_alloc_sync_sem(); - cmd->sync=ss; + SyncSemaphore *ss = _alloc_sync_sem(); + cmd->sync = ss; unlock(); @@ -1025,22 +1103,22 @@ public: ss->sem->wait(); } - template - void push_and_sync( T * p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6 ) { + template + void push_and_sync(T *p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6) { - CommandSync6 * cmd = allocate_and_lock< CommandSync6 >(); + CommandSync6 *cmd = allocate_and_lock >(); - cmd->instance=p_instance; - cmd->method=p_method; - cmd->p1=p1; - cmd->p2=p2; - cmd->p3=p3; - cmd->p4=p4; - cmd->p5=p5; - cmd->p6=p6; + cmd->instance = p_instance; + cmd->method = p_method; + cmd->p1 = p1; + cmd->p2 = p2; + cmd->p3 = p3; + cmd->p4 = p4; + cmd->p5 = p5; + cmd->p6 = p6; - SyncSemaphore *ss=_alloc_sync_sem(); - cmd->sync=ss; + SyncSemaphore *ss = _alloc_sync_sem(); + cmd->sync = ss; unlock(); @@ -1048,23 +1126,23 @@ public: ss->sem->wait(); } - template - void push_and_sync( T * p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6,P7 p7 ) { + template + void push_and_sync(T *p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7) { - CommandSync7 * cmd = allocate_and_lock< CommandSync7 >(); + CommandSync7 *cmd = allocate_and_lock >(); - cmd->instance=p_instance; - cmd->method=p_method; - cmd->p1=p1; - cmd->p2=p2; - cmd->p3=p3; - cmd->p4=p4; - cmd->p5=p5; - cmd->p6=p6; - cmd->p7=p7; + cmd->instance = p_instance; + cmd->method = p_method; + cmd->p1 = p1; + cmd->p2 = p2; + cmd->p3 = p3; + cmd->p4 = p4; + cmd->p5 = p5; + cmd->p6 = p6; + cmd->p7 = p7; - SyncSemaphore *ss=_alloc_sync_sem(); - cmd->sync=ss; + SyncSemaphore *ss = _alloc_sync_sem(); + cmd->sync = ss; unlock(); @@ -1072,24 +1150,24 @@ public: ss->sem->wait(); } - template - void push_and_sync( T * p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6,P7 p7,P8 p8) { + template + void push_and_sync(T *p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7, P8 p8) { - CommandSync8 * cmd = allocate_and_lock< CommandSync8 >(); + CommandSync8 *cmd = allocate_and_lock >(); - cmd->instance=p_instance; - cmd->method=p_method; - cmd->p1=p1; - cmd->p2=p2; - cmd->p3=p3; - cmd->p4=p4; - cmd->p5=p5; - cmd->p6=p6; - cmd->p7=p7; - cmd->p8=p8; + cmd->instance = p_instance; + cmd->method = p_method; + cmd->p1 = p1; + cmd->p2 = p2; + cmd->p3 = p3; + cmd->p4 = p4; + cmd->p5 = p5; + cmd->p6 = p6; + cmd->p7 = p7; + cmd->p8 = p8; - SyncSemaphore *ss=_alloc_sync_sem(); - cmd->sync=ss; + SyncSemaphore *ss = _alloc_sync_sem(); + cmd->sync = ss; unlock(); @@ -1119,7 +1197,6 @@ public: CommandQueueMT(bool p_sync); ~CommandQueueMT(); - }; #endif diff --git a/core/compressed_translation.cpp b/core/compressed_translation.cpp index 1725ce99466..53443d828c7 100644 --- a/core/compressed_translation.cpp +++ b/core/compressed_translation.cpp @@ -45,201 +45,199 @@ Redistribution and use in source and binary forms, with or without modification, THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - /* Our compression codebook, used for compression */ static const char *Smaz_cb[241] = { -"\002s,\266", "\003had\232\002leW", "\003on \216", "", "\001yS", -"\002ma\255\002li\227", "\003or \260", "", "\002ll\230\003s t\277", -"\004fromg\002mel", "", "\003its\332", "\001z\333", "\003ingF", "\001>\336", -"\001 \000\003 (\002nc\344", "\002nd=\003 on\312", -"\002ne\213\003hat\276\003re q", "", "\002ngT\003herz\004have\306\003s o\225", -"", "\003ionk\003s a\254\002ly\352", "\003hisL\003 inN\003 be\252", "", -"\003 fo\325\003 of \003 ha\311", "", "\002of\005", -"\003 co\241\002no\267\003 ma\370", "", "", "\003 cl\356\003enta\003 an7", -"\002ns\300\001\"e", "\003n t\217\002ntP\003s, \205", -"\002pe\320\003 we\351\002om\223", "\002on\037", "", "\002y G", "\003 wa\271", -"\003 re\321\002or*", "", "\002=\"\251\002ot\337", "\003forD\002ou[", -"\003 toR", "\003 th\r", "\003 it\366", -"\003but\261\002ra\202\003 wi\363\002<\346", "\002to\024", "\003arew", "\001d\030", -"\002tr\303", "", "\001\n1\003 a \222", "\003f tv\002veo", "\002un\340", "", -"\003e o\242", "\002a \243\002wa\326\001e\002", "\002ur\226\003e a\274", -"\002us\244\003\n\r\n\247", "\002ut\304\003e c\373", "\002we\221", "", "", -"\002wh\302", "\001f,", "", "", "", "\003d t\206", "", "", "\003th \343", -"\001g;", "", "", "\001\r9\003e s\265", "\003e t\234", "", "\003to Y", -"\003e\r\n\236", "\002d \036\001h\022", "", "\001,Q", "\002 a\031", "\002 b^", -"\002\r\n\025\002 cI", "\002 d\245", "\002 e\253", "\002 fh\001i\b\002e \v", -"", "\002 hU\001-\314", "\002 i8", "", "", "\002 l\315", "\002 m{", -"\002f :\002 n\354", "\002 o\035", "\002 p}\001.n\003\r\n\r\250", "", -"\002 r\275", "\002 s>", "\002 t\016", "", "\002g \235\005which+\003whi\367", -"\002 w5", "\001/\305", "\003as \214", "\003at \207", "", "\003who\331", "", -"\001l\026\002h \212", "", "\002, $", "", "\004withV", "", "", "", "\001m-", "", -"", "\002ac\357", "\002ad\350", "\003TheH", "", "", "\004this\233\001n\t", -"", "\002. y", "", "\002alX\003e, \365", "\003tio\215\002be\\", -"\002an\032\003ver\347", "", "\004that0\003tha\313\001o\006", "\003was2", -"\002arO", "\002as.", "\002at'\003the\001\004they\200\005there\322\005theird", -"\002ce\210", "\004were]", "", "\002ch\231\002l \264\001p<", "", "", -"\003one\256", "", "\003he \023\002dej", "\003ter\270", "\002cou", "", -"\002by\177\002di\201\002eax", "", "\002ec\327", "\002edB", "\002ee\353", "", -"", "\001r\f\002n )", "", "", "", "\002el\262", "", "\003in i\002en3", "", -"\002o `\001s\n", "", "\002er\033", "\003is t\002es6", "", "\002ge\371", -"\004.com\375", "\002fo\334\003our\330", "\003ch \301\001t\003", "\002hab", "", -"\003men\374", "", "\002he\020", "", "", "\001u&", "\002hif", "", -"\003not\204\002ic\203", "\003ed @\002id\355", "", "", "\002ho\273", -"\002r K\001vm", "", "", "", "\003t t\257\002il\360", "\002im\342", -"\003en \317\002in\017", "\002io\220", "\002s \027\001wA", "", "\003er |", -"\003es ~\002is%", "\002it/", "", "\002iv\272", "", -"\002t #\ahttp://C\001x\372", "\002la\211", "\001<\341", "\003, a\224" + "\002s,\266", "\003had\232\002leW", "\003on \216", "", "\001yS", + "\002ma\255\002li\227", "\003or \260", "", "\002ll\230\003s t\277", + "\004fromg\002mel", "", "\003its\332", "\001z\333", "\003ingF", "\001>\336", + "\001 \000\003 (\002nc\344", "\002nd=\003 on\312", + "\002ne\213\003hat\276\003re q", "", "\002ngT\003herz\004have\306\003s o\225", + "", "\003ionk\003s a\254\002ly\352", "\003hisL\003 inN\003 be\252", "", + "\003 fo\325\003 of \003 ha\311", "", "\002of\005", + "\003 co\241\002no\267\003 ma\370", "", "", "\003 cl\356\003enta\003 an7", + "\002ns\300\001\"e", "\003n t\217\002ntP\003s, \205", + "\002pe\320\003 we\351\002om\223", "\002on\037", "", "\002y G", "\003 wa\271", + "\003 re\321\002or*", "", "\002=\"\251\002ot\337", "\003forD\002ou[", + "\003 toR", "\003 th\r", "\003 it\366", + "\003but\261\002ra\202\003 wi\363\002<\346", "\002to\024", "\003arew", "\001d\030", + "\002tr\303", "", "\001\n1\003 a \222", "\003f tv\002veo", "\002un\340", "", + "\003e o\242", "\002a \243\002wa\326\001e\002", "\002ur\226\003e a\274", + "\002us\244\003\n\r\n\247", "\002ut\304\003e c\373", "\002we\221", "", "", + "\002wh\302", "\001f,", "", "", "", "\003d t\206", "", "", "\003th \343", + "\001g;", "", "", "\001\r9\003e s\265", "\003e t\234", "", "\003to Y", + "\003e\r\n\236", "\002d \036\001h\022", "", "\001,Q", "\002 a\031", "\002 b^", + "\002\r\n\025\002 cI", "\002 d\245", "\002 e\253", "\002 fh\001i\b\002e \v", + "", "\002 hU\001-\314", "\002 i8", "", "", "\002 l\315", "\002 m{", + "\002f :\002 n\354", "\002 o\035", "\002 p}\001.n\003\r\n\r\250", "", + "\002 r\275", "\002 s>", "\002 t\016", "", "\002g \235\005which+\003whi\367", + "\002 w5", "\001/\305", "\003as \214", "\003at \207", "", "\003who\331", "", + "\001l\026\002h \212", "", "\002, $", "", "\004withV", "", "", "", "\001m-", "", + "", "\002ac\357", "\002ad\350", "\003TheH", "", "", "\004this\233\001n\t", + "", "\002. y", "", "\002alX\003e, \365", "\003tio\215\002be\\", + "\002an\032\003ver\347", "", "\004that0\003tha\313\001o\006", "\003was2", + "\002arO", "\002as.", "\002at'\003the\001\004they\200\005there\322\005theird", + "\002ce\210", "\004were]", "", "\002ch\231\002l \264\001p<", "", "", + "\003one\256", "", "\003he \023\002dej", "\003ter\270", "\002cou", "", + "\002by\177\002di\201\002eax", "", "\002ec\327", "\002edB", "\002ee\353", "", + "", "\001r\f\002n )", "", "", "", "\002el\262", "", "\003in i\002en3", "", + "\002o `\001s\n", "", "\002er\033", "\003is t\002es6", "", "\002ge\371", + "\004.com\375", "\002fo\334\003our\330", "\003ch \301\001t\003", "\002hab", "", + "\003men\374", "", "\002he\020", "", "", "\001u&", "\002hif", "", + "\003not\204\002ic\203", "\003ed @\002id\355", "", "", "\002ho\273", + "\002r K\001vm", "", "", "", "\003t t\257\002il\360", "\002im\342", + "\003en \317\002in\017", "\002io\220", "\002s \027\001wA", "", "\003er |", + "\003es ~\002is%", "\002it/", "", "\002iv\272", "", + "\002t #\ahttp://C\001x\372", "\002la\211", "\001<\341", "\003, a\224" }; /* Reverse compression codebook, used for decompression */ static const char *Smaz_rcb[254] = { -" ", "the", "e", "t", "a", "of", "o", "and", "i", "n", "s", "e ", "r", " th", -" t", "in", "he", "th", "h", "he ", "to", "\r\n", "l", "s ", "d", " a", "an", -"er", "c", " o", "d ", "on", " of", "re", "of ", "t ", ", ", "is", "u", "at", -" ", "n ", "or", "which", "f", "m", "as", "it", "that", "\n", "was", "en", -" ", " w", "es", " an", " i", "\r", "f ", "g", "p", "nd", " s", "nd ", "ed ", -"w", "ed", "http://", "for", "te", "ing", "y ", "The", " c", "ti", "r ", "his", -"st", " in", "ar", "nt", ",", " to", "y", "ng", " h", "with", "le", "al", "to ", -"b", "ou", "be", "were", " b", "se", "o ", "ent", "ha", "ng ", "their", "\"", -"hi", "from", " f", "in ", "de", "ion", "me", "v", ".", "ve", "all", "re ", -"ri", "ro", "is ", "co", "f t", "are", "ea", ". ", "her", " m", "er ", " p", -"es ", "by", "they", "di", "ra", "ic", "not", "s, ", "d t", "at ", "ce", "la", -"h ", "ne", "as ", "tio", "on ", "n t", "io", "we", " a ", "om", ", a", "s o", -"ur", "li", "ll", "ch", "had", "this", "e t", "g ", "e\r\n", " wh", "ere", -" co", "e o", "a ", "us", " d", "ss", "\n\r\n", "\r\n\r", "=\"", " be", " e", -"s a", "ma", "one", "t t", "or ", "but", "el", "so", "l ", "e s", "s,", "no", -"ter", " wa", "iv", "ho", "e a", " r", "hat", "s t", "ns", "ch ", "wh", "tr", -"ut", "/", "have", "ly ", "ta", " ha", " on", "tha", "-", " l", "ati", "en ", -"pe", " re", "there", "ass", "si", " fo", "wa", "ec", "our", "who", "its", "z", -"fo", "rs", ">", "ot", "un", "<", "im", "th ", "nc", "ate", "><", "ver", "ad", -" we", "ly", "ee", " n", "id", " cl", "ac", "il", "", "ot", "un", "<", "im", "th ", "nc", "ate", "><", "ver", "ad", + " we", "ly", "ee", " n", "id", " cl", "ac", "il", " 1) h2 += in[1]; - if (inlen > 2) h3 = h2^in[2]; - if (j > inlen) j = inlen; + h1 = h2 = in[0] << 3; + if (inlen > 1) h2 += in[1]; + if (inlen > 2) h3 = h2 ^ in[2]; + if (j > inlen) j = inlen; - /* Try to lookup substrings into the hash table, starting from the + /* Try to lookup substrings into the hash table, starting from the * longer to the shorter substrings */ - for (; j > 0; j--) { - switch(j) { - case 1: slot = Smaz_cb[h1%241]; break; - case 2: slot = Smaz_cb[h2%241]; break; - default: slot = Smaz_cb[h3%241]; break; - } - while(slot[0]) { - if (slot[0] == j && memcmp(slot+1,in,j) == 0) { - /* Match found in the hash table, + for (; j > 0; j--) { + switch (j) { + case 1: slot = Smaz_cb[h1 % 241]; break; + case 2: slot = Smaz_cb[h2 % 241]; break; + default: slot = Smaz_cb[h3 % 241]; break; + } + while (slot[0]) { + if (slot[0] == j && memcmp(slot + 1, in, j) == 0) { + /* Match found in the hash table, * prepare a verbatim bytes flush if needed */ - if (verblen) { - needed = (verblen == 1) ? 2 : 2+verblen; + if (verblen) { + needed = (verblen == 1) ? 2 : 2 + verblen; + flush = out; + out += needed; + outlen -= needed; + } + /* Emit the byte */ + if (outlen <= 0) return _outlen + 1; + out[0] = slot[slot[0] + 1]; + out++; + outlen--; + inlen -= j; + in += j; + goto out; + } else { + slot += slot[0] + 2; + } + } + } + /* Match not found - add the byte to the verbatim buffer */ + verb[verblen] = in[0]; + verblen++; + inlen--; + in++; + out: + /* Prepare a flush if we reached the flush length limit, and there +* is not already a pending flush operation. */ + if (!flush && (verblen == 256 || (verblen > 0 && inlen == 0))) { + needed = (verblen == 1) ? 2 : 2 + verblen; flush = out; out += needed; outlen -= needed; - } - /* Emit the byte */ - if (outlen <= 0) return _outlen+1; - out[0] = slot[slot[0]+1]; - out++; - outlen--; - inlen -= j; - in += j; - goto out; - } else { - slot += slot[0]+2; + if (outlen < 0) return _outlen + 1; + } + /* Perform a verbatim flush if needed */ + if (flush) { + if (verblen == 1) { + flush[0] = (signed char)254; + flush[1] = verb[0]; + } else { + flush[0] = (signed char)255; + flush[1] = (signed char)(verblen - 1); + memcpy(flush + 2, verb, verblen); + } + flush = NULL; + verblen = 0; } - } } - /* Match not found - add the byte to the verbatim buffer */ - verb[verblen] = in[0]; - verblen++; - inlen--; - in++; -out: - /* Prepare a flush if we reached the flush length limit, and there -* is not already a pending flush operation. */ - if (!flush && (verblen == 256 || (verblen > 0 && inlen == 0))) { - needed = (verblen == 1) ? 2 : 2+verblen; - flush = out; - out += needed; - outlen -= needed; - if (outlen < 0) return _outlen+1; - } - /* Perform a verbatim flush if needed */ - if (flush) { - if (verblen == 1) { - flush[0] = (signed char)254; - flush[1] = verb[0]; - } else { - flush[0] = (signed char)255; - flush[1] = (signed char)(verblen-1); - memcpy(flush+2,verb,verblen); - } - flush = NULL; - verblen = 0; - } - } - return out-_out; + return out - _out; } static int smaz_decompress(const char *in, int inlen, char *out, int outlen) { - unsigned char *c = (unsigned char*) in; - char *_out = out; - int _outlen = outlen; + unsigned char *c = (unsigned char *)in; + char *_out = out; + int _outlen = outlen; - while(inlen) { - if (*c == 254) { - /* Verbatim byte */ - if (outlen < 1) return _outlen+1; - *out = *(c+1); - out++; - outlen--; - c += 2; - inlen -= 2; - } else if (*c == 255) { - /* Verbatim string */ - int len = (*(c+1))+1; - if (outlen < len) return _outlen+1; - memcpy(out,c+2,len); - out += len; - outlen -= len; - c += 2+len; - inlen -= 2+len; - } else { - /* Codebook entry */ - const char *s = Smaz_rcb[*c]; - int len = strlen(s); + while (inlen) { + if (*c == 254) { + /* Verbatim byte */ + if (outlen < 1) return _outlen + 1; + *out = *(c + 1); + out++; + outlen--; + c += 2; + inlen -= 2; + } else if (*c == 255) { + /* Verbatim string */ + int len = (*(c + 1)) + 1; + if (outlen < len) return _outlen + 1; + memcpy(out, c + 2, len); + out += len; + outlen -= len; + c += 2 + len; + inlen -= 2 + len; + } else { + /* Codebook entry */ + const char *s = Smaz_rcb[*c]; + int len = strlen(s); - if (outlen < len) return _outlen+1; - memcpy(out,s,len); - out += len; - outlen -= len; - c++; - inlen--; + if (outlen < len) return _outlen + 1; + memcpy(out, s, len); + out += len; + outlen -= len; + c++; + inlen--; + } } - } - return out-_out; + return out - _out; } - /////////// END OF SMAZ ///////////// struct _PHashTranslationCmp { @@ -254,104 +252,100 @@ void PHashTranslation::generate(const Ref &p_from) { List keys; p_from->get_message_list(&keys); - int size=Math::larger_prime(keys.size()); + int size = Math::larger_prime(keys.size()); - - print_line("compressing keys: "+itos(keys.size())); - Vector< Vector< Pair > > buckets; - Vector< Map< uint32_t, int > > table; - Vector< uint32_t > hfunc_table; - Vector< _PHashTranslationCmp > compressed; + print_line("compressing keys: " + itos(keys.size())); + Vector > > buckets; + Vector > table; + Vector hfunc_table; + Vector<_PHashTranslationCmp> compressed; table.resize(size); hfunc_table.resize(size); buckets.resize(size); compressed.resize(keys.size()); - int idx=0; - int total_compression_size=0; - int total_string_size=0; + int idx = 0; + int total_compression_size = 0; + int total_string_size = 0; - for(List::Element *E=keys.front();E;E=E->next()) { + for (List::Element *E = keys.front(); E; E = E->next()) { //hash string CharString cs = E->get().operator String().utf8(); - uint32_t h = hash(0,cs.get_data()); - Pair p; - p.first=idx; - p.second=cs; + uint32_t h = hash(0, cs.get_data()); + Pair p; + p.first = idx; + p.second = cs; buckets[h % size].push_back(p); //compress string CharString src_s = p_from->get_message(E->get()).operator String().utf8(); _PHashTranslationCmp ps; - ps.orig_len=src_s.size(); - ps.offset=total_compression_size; + ps.orig_len = src_s.size(); + ps.offset = total_compression_size; - if (ps.orig_len!=0) { + if (ps.orig_len != 0) { CharString dst_s; dst_s.resize(src_s.size()); - int ret = smaz_compress(src_s.get_data(),src_s.size(),&dst_s[0],src_s.size()); - if (ret>=src_s.size()) { + int ret = smaz_compress(src_s.get_data(), src_s.size(), &dst_s[0], src_s.size()); + if (ret >= src_s.size()) { //if compressed is larger than original, just use original - ps.orig_len=src_s.size(); - ps.compressed=src_s; + ps.orig_len = src_s.size(); + ps.compressed = src_s; } else { dst_s.resize(ret); //ps.orig_len=; - ps.compressed=dst_s; + ps.compressed = dst_s; } } else { - ps.orig_len=1; + ps.orig_len = 1; ps.compressed.resize(1); - ps.compressed[0]=0; + ps.compressed[0] = 0; } - - compressed[idx]=ps; - total_compression_size+=ps.compressed.size(); - total_string_size+=src_s.size(); + compressed[idx] = ps; + total_compression_size += ps.compressed.size(); + total_string_size += src_s.size(); idx++; } - int bucket_table_size=0; - print_line("total compressed string size: "+itos(total_compression_size)+" ("+itos(total_string_size)+" uncompressed)."); + int bucket_table_size = 0; + print_line("total compressed string size: " + itos(total_compression_size) + " (" + itos(total_string_size) + " uncompressed)."); - for(int i=0;i > &b = buckets[i]; - Map< uint32_t, int > &t=table[i]; + Vector > &b = buckets[i]; + Map &t = table[i]; - if (b.size()==0) + if (b.size() == 0) continue; //print_line("bucket: "+itos(i)+" - elements: "+itos(b.size())); int d = 1; - int item =0; + int item = 0; - while(item < b.size()) { + while (item < b.size()) { - uint32_t slot = hash(d,b[item].second.get_data()); + uint32_t slot = hash(d, b[item].second.get_data()); if (t.has(slot)) { - item=0; + item = 0; d++; t.clear(); } else { - t[slot]=b[item].first; + t[slot] = b[item].first; item++; } } - hfunc_table[i]=d; - bucket_table_size+=2+b.size()*4; - + hfunc_table[i] = d; + bucket_table_size += 2 + b.size() * 4; } - - print_line("bucket table size: "+itos(bucket_table_size*4)); - print_line("hash table size: "+itos(size*4)); + print_line("bucket table size: " + itos(bucket_table_size * 4)); + print_line("hash table size: " + itos(size * 4)); hash_table.resize(size); bucket_table.resize(bucket_table_size); @@ -359,176 +353,166 @@ void PHashTranslation::generate(const Ref &p_from) { DVector::Write htwb = hash_table.write(); DVector::Write btwb = bucket_table.write(); - uint32_t *htw = (uint32_t*)&htwb[0]; - uint32_t *btw = (uint32_t*)&btwb[0]; + uint32_t *htw = (uint32_t *)&htwb[0]; + uint32_t *btw = (uint32_t *)&btwb[0]; - int btindex=0; - int collisions=0; + int btindex = 0; + int collisions = 0; - for(int i=0;i &t=table[i]; - if (t.size()==0) { - htw[i]=0xFFFFFFFF; //nothing + Map &t = table[i]; + if (t.size() == 0) { + htw[i] = 0xFFFFFFFF; //nothing continue; - } else if (t.size()>1) { - collisions+=t.size()-1; + } else if (t.size() > 1) { + collisions += t.size() - 1; } - htw[i]=btindex; - btw[btindex++]=t.size(); - btw[btindex++]=hfunc_table[i]; + htw[i] = btindex; + btw[btindex++] = t.size(); + btw[btindex++] = hfunc_table[i]; - for( Map< uint32_t, int >::Element *E=t.front();E;E=E->next()) { + for (Map::Element *E = t.front(); E; E = E->next()) { - btw[btindex++]=E->key(); - btw[btindex++]=compressed[E->get()].offset; - btw[btindex++]=compressed[E->get()].compressed.size(); - btw[btindex++]=compressed[E->get()].orig_len; + btw[btindex++] = E->key(); + btw[btindex++] = compressed[E->get()].offset; + btw[btindex++] = compressed[E->get()].compressed.size(); + btw[btindex++] = compressed[E->get()].orig_len; } - } - print_line("total collisions: "+itos(collisions)); + print_line("total collisions: " + itos(collisions)); strings.resize(total_compression_size); DVector::Write cw = strings.write(); - for(int i=0;iget_locale()); #endif } -bool PHashTranslation::_set(const StringName& p_name, const Variant& p_value) { +bool PHashTranslation::_set(const StringName &p_name, const Variant &p_value) { String name = p_name.operator String(); - if (name=="hash_table") { - hash_table=p_value; + if (name == "hash_table") { + hash_table = p_value; //print_line("translation: loaded hash table of size: "+itos(hash_table.size())); - } else if (name=="bucket_table") { - bucket_table=p_value; + } else if (name == "bucket_table") { + bucket_table = p_value; //print_line("translation: loaded bucket table of size: "+itos(bucket_table.size())); - } else if (name=="strings") { - strings=p_value; + } else if (name == "strings") { + strings = p_value; //print_line("translation: loaded string table of size: "+itos(strings.size())); - } else if (name=="load_from") { + } else if (name == "load_from") { //print_line("generating"); generate(p_value); } else return false; return true; - } -bool PHashTranslation::_get(const StringName& p_name,Variant &r_ret) const{ +bool PHashTranslation::_get(const StringName &p_name, Variant &r_ret) const { String name = p_name.operator String(); - if (name=="hash_table") - r_ret=hash_table; - else if (name=="bucket_table") - r_ret=bucket_table; - else if (name=="strings") - r_ret=strings; + if (name == "hash_table") + r_ret = hash_table; + else if (name == "bucket_table") + r_ret = bucket_table; + else if (name == "strings") + r_ret = strings; else return false; return true; - } -StringName PHashTranslation::get_message(const StringName& p_src_text) const { +StringName PHashTranslation::get_message(const StringName &p_src_text) const { int htsize = hash_table.size(); - if (htsize==0) + if (htsize == 0) return StringName(); CharString str = p_src_text.operator String().utf8(); - uint32_t h = hash(0,str.get_data()); + uint32_t h = hash(0, str.get_data()); - - DVector::Read htr = hash_table.read(); - const uint32_t *htptr = (const uint32_t*)&htr[0]; - DVector::Read btr = bucket_table.read(); - const uint32_t *btptr = (const uint32_t*)&btr[0]; + DVector::Read htr = hash_table.read(); + const uint32_t *htptr = (const uint32_t *)&htr[0]; + DVector::Read btr = bucket_table.read(); + const uint32_t *btptr = (const uint32_t *)&btr[0]; DVector::Read sr = strings.read(); - const char *sptr= (const char*)&sr[0]; + const char *sptr = (const char *)&sr[0]; - uint32_t p = htptr[ h % htsize]; + uint32_t p = htptr[h % htsize]; //print_line("String: "+p_src_text.operator String()); //print_line("Hash: "+itos(p)); - if (p==0xFFFFFFFF) { -// print_line("GETMSG: Nothing!"); + if (p == 0xFFFFFFFF) { + // print_line("GETMSG: Nothing!"); return StringName(); //nothing } - const Bucket &bucket = *(const Bucket*)&btptr[p]; + const Bucket &bucket = *(const Bucket *)&btptr[p]; - h = hash(bucket.func,str.get_data()); + h = hash(bucket.func, str.get_data()); - int idx=-1; + int idx = -1; - for(int i=0;i *p_list) const { -void PHashTranslation::_get_property_list( List *p_list) const{ - - p_list->push_back( PropertyInfo(Variant::INT_ARRAY, "hash_table")); - p_list->push_back( PropertyInfo(Variant::INT_ARRAY, "bucket_table")); - p_list->push_back( PropertyInfo(Variant::RAW_ARRAY, "strings")); - p_list->push_back( PropertyInfo(Variant::OBJECT, "load_from",PROPERTY_HINT_RESOURCE_TYPE,"Translation",PROPERTY_USAGE_EDITOR)); - + p_list->push_back(PropertyInfo(Variant::INT_ARRAY, "hash_table")); + p_list->push_back(PropertyInfo(Variant::INT_ARRAY, "bucket_table")); + p_list->push_back(PropertyInfo(Variant::RAW_ARRAY, "strings")); + p_list->push_back(PropertyInfo(Variant::OBJECT, "load_from", PROPERTY_HINT_RESOURCE_TYPE, "Translation", PROPERTY_USAGE_EDITOR)); } void PHashTranslation::_bind_methods() { - ObjectTypeDB::bind_method(_MD("generate","from:Translation"),&PHashTranslation::generate); + ObjectTypeDB::bind_method(_MD("generate", "from:Translation"), &PHashTranslation::generate); } -PHashTranslation::PHashTranslation() -{ +PHashTranslation::PHashTranslation() { } diff --git a/core/compressed_translation.h b/core/compressed_translation.h index a7b539816a5..89d39118aab 100644 --- a/core/compressed_translation.h +++ b/core/compressed_translation.h @@ -33,8 +33,7 @@ class PHashTranslation : public Translation { - OBJ_TYPE(PHashTranslation,Translation); - + OBJ_TYPE(PHashTranslation, Translation); //this translation uses a sort of modified perfect hash algorithm //it requieres hashing strings twice and then does a binary search, @@ -46,7 +45,6 @@ class PHashTranslation : public Translation { DVector bucket_table; DVector strings; - struct Bucket { int size; @@ -63,11 +61,11 @@ class PHashTranslation : public Translation { Elem elem[1]; }; - _FORCE_INLINE_ uint32_t hash( uint32_t d, const char *p_str ) const { + _FORCE_INLINE_ uint32_t hash(uint32_t d, const char *p_str) const { - if (d==0) - d=0x1000193; - while(*p_str) { + if (d == 0) + d = 0x1000193; + while (*p_str) { d = (d * 0x1000193) ^ uint32_t(*p_str); p_str++; @@ -75,16 +73,15 @@ class PHashTranslation : public Translation { return d; } -protected: - bool _set(const StringName& p_name, const Variant& p_value); - bool _get(const StringName& p_name,Variant &r_ret) const; - void _get_property_list( List *p_list) const; +protected: + bool _set(const StringName &p_name, const Variant &p_value); + bool _get(const StringName &p_name, Variant &r_ret) const; + void _get_property_list(List *p_list) const; static void _bind_methods(); public: - - virtual StringName get_message(const StringName& p_src_text) const; //overridable for other implementations + virtual StringName get_message(const StringName &p_src_text) const; //overridable for other implementations void generate(const Ref &p_from); PHashTranslation(); diff --git a/core/core_string_names.cpp b/core/core_string_names.cpp index a173f986024..bfd3e0ef29d 100644 --- a/core/core_string_names.cpp +++ b/core/core_string_names.cpp @@ -28,21 +28,19 @@ /*************************************************************************/ #include "core_string_names.h" -CoreStringNames* CoreStringNames::singleton=NULL; +CoreStringNames *CoreStringNames::singleton = NULL; CoreStringNames::CoreStringNames() { - _free=StaticCString::create("free"); - changed=StaticCString::create("changed"); - _meta=StaticCString::create("__meta__"); - _script=StaticCString::create("script/script"); - script_changed=StaticCString::create("script_changed"); - ___pdcdata=StaticCString::create("___pdcdata"); - __getvar=StaticCString::create("__getvar"); - _iter_init=StaticCString::create("_iter_init"); - _iter_next=StaticCString::create("_iter_next"); - _iter_get=StaticCString::create("_iter_get"); - get_rid=StaticCString::create("get_rid"); - - + _free = StaticCString::create("free"); + changed = StaticCString::create("changed"); + _meta = StaticCString::create("__meta__"); + _script = StaticCString::create("script/script"); + script_changed = StaticCString::create("script_changed"); + ___pdcdata = StaticCString::create("___pdcdata"); + __getvar = StaticCString::create("__getvar"); + _iter_init = StaticCString::create("_iter_init"); + _iter_next = StaticCString::create("_iter_next"); + _iter_get = StaticCString::create("_iter_get"); + get_rid = StaticCString::create("get_rid"); } diff --git a/core/core_string_names.h b/core/core_string_names.h index 7d3754786c0..f6542be290b 100644 --- a/core/core_string_names.h +++ b/core/core_string_names.h @@ -33,18 +33,21 @@ class CoreStringNames { -friend void register_core_types(); -friend void unregister_core_types(); + friend void register_core_types(); + friend void unregister_core_types(); - static CoreStringNames* singleton; + static CoreStringNames *singleton; static void create() { singleton = memnew(CoreStringNames); } - static void free() { memdelete( singleton); singleton=NULL; } + static void free() { + memdelete(singleton); + singleton = NULL; + } CoreStringNames(); -public: - _FORCE_INLINE_ static CoreStringNames* get_singleton() { return singleton; } +public: + _FORCE_INLINE_ static CoreStringNames *get_singleton() { return singleton; } StringName _free; StringName changed; @@ -57,7 +60,6 @@ public: StringName _iter_next; StringName _iter_get; StringName get_rid; - }; #endif // SCENE_STRING_NAMES_H diff --git a/core/dictionary.cpp b/core/dictionary.cpp index 5c5be3402cc..91190e7c701 100644 --- a/core/dictionary.cpp +++ b/core/dictionary.cpp @@ -27,26 +27,23 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "dictionary.h" +#include "io/json.h" #include "safe_refcount.h" #include "variant.h" -#include "io/json.h" struct _DictionaryVariantHash { - static _FORCE_INLINE_ uint32_t hash(const Variant &p_variant) { return p_variant.hash(); } + static _FORCE_INLINE_ uint32_t hash(const Variant &p_variant) { return p_variant.hash(); } }; - struct DictionaryPrivate { SafeRefCount refcount; - HashMap variant_map; + HashMap variant_map; bool shared; - }; - -void Dictionary::get_key_list( List *p_keys) const { +void Dictionary::get_key_list(List *p_keys) const { _p->variant_map.get_key_list(p_keys); } @@ -58,36 +55,35 @@ void Dictionary::_copy_on_write() const { return; DictionaryPrivate *p = memnew(DictionaryPrivate); - p->shared=_p->shared; - p->variant_map=_p->variant_map; + p->shared = _p->shared; + p->variant_map = _p->variant_map; p->refcount.init(); _unref(); - _p=p; + _p = p; } -Variant& Dictionary::operator[](const Variant& p_key) { +Variant &Dictionary::operator[](const Variant &p_key) { _copy_on_write(); return _p->variant_map[p_key]; } -const Variant& Dictionary::operator[](const Variant& p_key) const { +const Variant &Dictionary::operator[](const Variant &p_key) const { return _p->variant_map[p_key]; - } -const Variant* Dictionary::getptr(const Variant& p_key) const { +const Variant *Dictionary::getptr(const Variant &p_key) const { return _p->variant_map.getptr(p_key); } -Variant* Dictionary::getptr(const Variant& p_key) { +Variant *Dictionary::getptr(const Variant &p_key) { _copy_on_write(); return _p->variant_map.getptr(p_key); } -Variant Dictionary::get_valid(const Variant& p_key) const { +Variant Dictionary::get_valid(const Variant &p_key) const { const Variant *v = getptr(p_key); if (!v) @@ -95,56 +91,53 @@ Variant Dictionary::get_valid(const Variant& p_key) const { return *v; } - int Dictionary::size() const { return _p->variant_map.size(); - } bool Dictionary::empty() const { return !_p->variant_map.size(); } -bool Dictionary::has(const Variant& p_key) const { +bool Dictionary::has(const Variant &p_key) const { return _p->variant_map.has(p_key); } -bool Dictionary::has_all(const Array& p_keys) const { - for (int i=0;ivariant_map.erase(p_key); } -bool Dictionary::operator==(const Dictionary& p_dictionary) const { +bool Dictionary::operator==(const Dictionary &p_dictionary) const { - return _p==p_dictionary._p; + return _p == p_dictionary._p; } -void Dictionary::_ref(const Dictionary& p_from) const { +void Dictionary::_ref(const Dictionary &p_from) const { //make a copy first (thread safe) if (!p_from._p->refcount.ref()) return; // couldn't copy //if this is the same, unreference the other one - if (p_from._p==_p) { + if (p_from._p == _p) { _p->refcount.unref(); return; } if (_p) _unref(); - _p=p_from._p; - + _p = p_from._p; } void Dictionary::clear() { @@ -155,34 +148,30 @@ void Dictionary::clear() { bool Dictionary::is_shared() const { - return _p->shared; + return _p->shared; } - void Dictionary::_unref() const { ERR_FAIL_COND(!_p); if (_p->refcount.unref()) { memdelete(_p); } - _p=NULL; - + _p = NULL; } uint32_t Dictionary::hash() const { - uint32_t h=hash_djb2_one_32(Variant::DICTIONARY); + uint32_t h = hash_djb2_one_32(Variant::DICTIONARY); List keys; get_key_list(&keys); - for (List::Element *E=keys.front();E;E=E->next()) { - - h = hash_djb2_one_32( E->get().hash(), h); - h = hash_djb2_one_32( operator[](E->get()).hash(), h); + for (List::Element *E = keys.front(); E; E = E->next()) { + h = hash_djb2_one_32(E->get().hash(), h); + h = hash_djb2_one_32(operator[](E->get()).hash(), h); } - return h; } @@ -190,42 +179,40 @@ Array Dictionary::keys() const { Array karr; karr.resize(size()); - const Variant *K=NULL; - int idx=0; - while((K=next(K))) { - karr[idx++]=(*K); + const Variant *K = NULL; + int idx = 0; + while ((K = next(K))) { + karr[idx++] = (*K); } return karr; - } Array Dictionary::values() const { Array varr; varr.resize(size()); - const Variant *key=NULL; - int i=0; - while((key=next(key))){ + const Variant *key = NULL; + int i = 0; + while ((key = next(key))) { varr[i++] = _p->variant_map[*key]; } return varr; } -const Variant* Dictionary::next(const Variant* p_key) const { +const Variant *Dictionary::next(const Variant *p_key) const { return _p->variant_map.next(p_key); } - -Error Dictionary::parse_json(const String& p_json) { +Error Dictionary::parse_json(const String &p_json) { String errstr; - int errline=0; - if (p_json != ""){ - Error err = JSON::parse(p_json,*this,errstr,errline); - if (err!=OK) { - ERR_EXPLAIN("Error parsing JSON: "+errstr+" at line: "+itos(errline)); - ERR_FAIL_COND_V(err!=OK,err); + int errline = 0; + if (p_json != "") { + Error err = JSON::parse(p_json, *this, errstr, errline); + if (err != OK) { + ERR_EXPLAIN("Error parsing JSON: " + errstr + " at line: " + itos(errline)); + ERR_FAIL_COND_V(err != OK, err); } } @@ -237,26 +224,21 @@ String Dictionary::to_json() const { return JSON::print(*this); } - -void Dictionary::operator=(const Dictionary& p_dictionary) { +void Dictionary::operator=(const Dictionary &p_dictionary) { _ref(p_dictionary); } - - -Dictionary::Dictionary(const Dictionary& p_from) { - _p=NULL; +Dictionary::Dictionary(const Dictionary &p_from) { + _p = NULL; _ref(p_from); } - Dictionary::Dictionary(bool p_shared) { - _p=memnew( DictionaryPrivate ); + _p = memnew(DictionaryPrivate); _p->refcount.init(); - _p->shared=p_shared; - + _p->shared = p_shared; } Dictionary::~Dictionary() { diff --git a/core/dictionary.h b/core/dictionary.h index fc6709391ce..48f2f4427c4 100644 --- a/core/dictionary.h +++ b/core/dictionary.h @@ -29,62 +29,58 @@ #ifndef DICTIONARY_H #define DICTIONARY_H - -#include "list.h" #include "array.h" +#include "list.h" #include "ustring.h" class Variant; - struct DictionaryPrivate; - class Dictionary { mutable DictionaryPrivate *_p; void _copy_on_write() const; - void _ref(const Dictionary& p_from) const; + void _ref(const Dictionary &p_from) const; void _unref() const; + public: + void get_key_list(List *p_keys) const; - void get_key_list( List *p_keys) const; + Variant &operator[](const Variant &p_key); + const Variant &operator[](const Variant &p_key) const; - Variant& operator[](const Variant& p_key); - const Variant& operator[](const Variant& p_key) const; + const Variant *getptr(const Variant &p_key) const; + Variant *getptr(const Variant &p_key); - const Variant* getptr(const Variant& p_key) const; - Variant* getptr(const Variant& p_key); - - Variant get_valid(const Variant& p_key) const; + Variant get_valid(const Variant &p_key) const; int size() const; bool empty() const; void clear(); - - Error parse_json(const String& p_json); + Error parse_json(const String &p_json); String to_json() const; bool is_shared() const; - bool has(const Variant& p_key) const; - bool has_all(const Array& p_keys) const; + bool has(const Variant &p_key) const; + bool has_all(const Array &p_keys) const; - void erase(const Variant& p_key); + void erase(const Variant &p_key); - bool operator==(const Dictionary& p_dictionary) const; + bool operator==(const Dictionary &p_dictionary) const; uint32_t hash() const; - void operator=(const Dictionary& p_dictionary); + void operator=(const Dictionary &p_dictionary); - const Variant* next(const Variant* p_key=NULL) const; + const Variant *next(const Variant *p_key = NULL) const; Array keys() const; Array values() const; - Dictionary(const Dictionary& p_from); - Dictionary(bool p_shared=false); + Dictionary(const Dictionary &p_from); + Dictionary(bool p_shared = false); ~Dictionary(); }; diff --git a/core/dvector.cpp b/core/dvector.cpp index 7caa198c4ca..bde7c28ea98 100644 --- a/core/dvector.cpp +++ b/core/dvector.cpp @@ -28,5 +28,4 @@ /*************************************************************************/ #include "dvector.h" -Mutex* dvector_lock=NULL; - +Mutex *dvector_lock = NULL; diff --git a/core/dvector.h b/core/dvector.h index 47883b23b32..2c58b4a3116 100644 --- a/core/dvector.h +++ b/core/dvector.h @@ -31,20 +31,17 @@ #include "os/memory.h" - /** @author Juan Linietsky */ +extern Mutex *dvector_lock; -extern Mutex* dvector_lock; - -template +template class DVector { mutable MID mem; - void copy_on_write() { if (!mem.is_valid()) @@ -53,56 +50,54 @@ class DVector { if (dvector_lock) dvector_lock->lock(); - MID_Lock lock( mem ); + MID_Lock lock(mem); - - if ( *(int*)lock.data() == 1 ) { + if (*(int *)lock.data() == 1) { // one reference, means no refcount changes if (dvector_lock) dvector_lock->unlock(); return; } - MID new_mem= dynalloc( mem.get_size() ); + MID new_mem = dynalloc(mem.get_size()); if (!new_mem.is_valid()) { if (dvector_lock) dvector_lock->unlock(); - ERR_FAIL_COND( new_mem.is_valid() ); // out of memory + ERR_FAIL_COND(new_mem.is_valid()); // out of memory } - MID_Lock dst_lock( new_mem ); + MID_Lock dst_lock(new_mem); - int *rc = (int*)dst_lock.data(); + int *rc = (int *)dst_lock.data(); - *rc=1; + *rc = 1; - T * dst = (T*)(rc + 1 ); + T *dst = (T *)(rc + 1); - T * src =(T*) ((int*)lock.data() + 1 ); + T *src = (T *)((int *)lock.data() + 1); int count = (mem.get_size() - sizeof(int)) / sizeof(T); - for (int i=0;iunlock(); - } - void reference( const DVector& p_dvector ) { + void reference(const DVector &p_dvector) { unreference(); @@ -118,18 +113,16 @@ class DVector { MID_Lock lock(p_dvector.mem); - int * rc = (int*)lock.data(); + int *rc = (int *)lock.data(); (*rc)++; lock = MID_Lock(); - mem=p_dvector.mem; + mem = p_dvector.mem; if (dvector_lock) dvector_lock->unlock(); - } - void unreference() { if (dvector_lock) @@ -144,65 +137,60 @@ class DVector { MID_Lock lock(mem); - int * rc = (int*)lock.data(); + int *rc = (int *)lock.data(); (*rc)--; - if (*rc==0) { + if (*rc == 0) { // no one else using it, destruct - T * t= (T*)(rc+1); + T *t = (T *)(rc + 1); int count = (mem.get_size() - sizeof(int)) / sizeof(T); - for (int i=0;iunlock(); - } public: - class Read { - friend class DVector; + friend class DVector; MID_Lock lock; - const T * mem; - public: + const T *mem; - _FORCE_INLINE_ const T& operator[](int p_index) const { return mem[p_index]; } + public: + _FORCE_INLINE_ const T &operator[](int p_index) const { return mem[p_index]; } _FORCE_INLINE_ const T *ptr() const { return mem; } - Read() { mem=NULL; } + Read() { mem = NULL; } }; class Write { - friend class DVector; + friend class DVector; MID_Lock lock; - T * mem; - public: + T *mem; - _FORCE_INLINE_ T& operator[](int p_index) { return mem[p_index]; } + public: + _FORCE_INLINE_ T &operator[](int p_index) { return mem[p_index]; } _FORCE_INLINE_ T *ptr() { return mem; } - Write() { mem=NULL; } + Write() { mem = NULL; } }; - Read read() const { Read r; if (mem.is_valid()) { - r.lock = MID_Lock( mem ); - r.mem = (const T*)((int*)r.lock.data()+1); + r.lock = MID_Lock(mem); + r.mem = (const T *)((int *)r.lock.data() + 1); } return r; } @@ -211,74 +199,70 @@ public: Write w; if (mem.is_valid()) { copy_on_write(); - w.lock = MID_Lock( mem ); - w.mem = (T*)((int*)w.lock.data()+1); + w.lock = MID_Lock(mem); + w.mem = (T *)((int *)w.lock.data() + 1); } return w; } - template - void fill_with(const MC& p_mc) { + template + void fill_with(const MC &p_mc) { - - int c=p_mc.size(); + int c = p_mc.size(); resize(c); - Write w=write(); - int idx=0; - for(const typename MC::Element *E=p_mc.front();E;E=E->next()) { + Write w = write(); + int idx = 0; + for (const typename MC::Element *E = p_mc.front(); E; E = E->next()) { - w[idx++]=E->get(); + w[idx++] = E->get(); } } - void remove(int p_index) { int s = size(); ERR_FAIL_INDEX(p_index, s); Write w = write(); - for (int i=p_index; i& p_arr) { + void set(int p_index, const T &p_val); + void push_back(const T &p_val); + void append(const T &p_val) { push_back(p_val); } + void append_array(const DVector &p_arr) { int ds = p_arr.size(); - if (ds==0) + if (ds == 0) return; int bs = size(); - resize( bs + ds); + resize(bs + ds); Write w = write(); Read r = p_arr.read(); - for(int i=0;ip_pos;i--) - w[i]=w[i-1]; - w[p_pos]=p_val; + for (int i = s; i > p_pos; i--) + w[i] = w[i - 1]; + w[p_pos] = p_val; } return OK; } - bool is_locked() const { return mem.is_locked(); } inline const T operator[](int p_index) const; @@ -287,49 +271,48 @@ public: void invert(); - void operator=(const DVector& p_dvector) { reference(p_dvector); } + void operator=(const DVector &p_dvector) { reference(p_dvector); } DVector() {} - DVector(const DVector& p_dvector) { reference(p_dvector); } + DVector(const DVector &p_dvector) { reference(p_dvector); } ~DVector() { unreference(); } - }; -template +template int DVector::size() const { - return mem.is_valid() ? ((mem.get_size() - sizeof(int)) / sizeof(T) ) : 0; + return mem.is_valid() ? ((mem.get_size() - sizeof(int)) / sizeof(T)) : 0; } -template +template T DVector::get(int p_index) const { return operator[](p_index); } -template -void DVector::set(int p_index, const T& p_val) { +template +void DVector::set(int p_index, const T &p_val) { - if (p_index<0 || p_index>=size()) { - ERR_FAIL_COND(p_index<0 || p_index>=size()); + if (p_index < 0 || p_index >= size()) { + ERR_FAIL_COND(p_index < 0 || p_index >= size()); } Write w = write(); - w[p_index]=p_val; + w[p_index] = p_val; } -template -void DVector::push_back(const T& p_val) { +template +void DVector::push_back(const T &p_val) { - resize( size() + 1 ); - set( size() -1, p_val ); + resize(size() + 1); + set(size() - 1, p_val); } -template +template const T DVector::operator[](int p_index) const { - if (p_index<0 || p_index>=size()) { - T& aux=*((T*)0); //nullreturn - ERR_FAIL_COND_V(p_index<0 || p_index>=size(),aux); + if (p_index < 0 || p_index >= size()) { + T &aux = *((T *)0); //nullreturn + ERR_FAIL_COND_V(p_index < 0 || p_index >= size(), aux); } Read r = read(); @@ -337,14 +320,13 @@ const T DVector::operator[](int p_index) const { return r[p_index]; } - -template +template Error DVector::resize(int p_size) { if (dvector_lock) dvector_lock->lock(); - bool same = p_size==size(); + bool same = p_size == size(); if (dvector_lock) dvector_lock->unlock(); @@ -353,89 +335,82 @@ Error DVector::resize(int p_size) { if (same) return OK; - if (p_size == 0 ) { + if (p_size == 0) { unreference(); return OK; } - copy_on_write(); // make it unique - ERR_FAIL_COND_V( mem.is_locked(), ERR_LOCKED ); // if after copy on write, memory is locked, fail. + ERR_FAIL_COND_V(mem.is_locked(), ERR_LOCKED); // if after copy on write, memory is locked, fail. - if (p_size > size() ) { + if (p_size > size()) { - int oldsize=size(); + int oldsize = size(); MID_Lock lock; - if (oldsize==0) { + if (oldsize == 0) { - mem = dynalloc( p_size * sizeof(T) + sizeof(int) ); - lock=MID_Lock(mem); - int *rc = ((int*)lock.data()); - *rc=1; + mem = dynalloc(p_size * sizeof(T) + sizeof(int)); + lock = MID_Lock(mem); + int *rc = ((int *)lock.data()); + *rc = 1; } else { - if (dynrealloc( mem, p_size * sizeof(T) + sizeof(int) )!=OK ) { + if (dynrealloc(mem, p_size * sizeof(T) + sizeof(int)) != OK) { ERR_FAIL_V(ERR_OUT_OF_MEMORY); // out of memory } - lock=MID_Lock(mem); + lock = MID_Lock(mem); } + T *t = (T *)((int *)lock.data() + 1); + for (int i = oldsize; i < p_size; i++) { - - T *t = (T*)((int*)lock.data() + 1); - - for (int i=oldsize;i +template void DVector::invert() { T temp; Write w = write(); int s = size(); - int half_s = s/2; + int half_s = s / 2; - for(int i=0;iset_last_error(p_err); } @@ -47,8 +46,8 @@ void _err_clear_last_error() { void add_error_handler(ErrorHandlerList *p_handler) { _global_lock(); - p_handler->next=error_handler_list; - error_handler_list=p_handler; + p_handler->next = error_handler_list; + error_handler_list = p_handler; _global_unlock(); } @@ -59,44 +58,39 @@ void remove_error_handler(ErrorHandlerList *p_handler) { ErrorHandlerList *prev = NULL; ErrorHandlerList *l = error_handler_list; - while(l) { + while (l) { - if (l==p_handler) { + if (l == p_handler) { if (prev) - prev->next=l->next; + prev->next = l->next; else - error_handler_list=l->next; + error_handler_list = l->next; break; } - prev=l; - l=l->next; - + prev = l; + l = l->next; } _global_unlock(); - } -void _err_print_error(const char* p_function, const char* p_file,int p_line,const char *p_error,ErrorHandlerType p_type) { +void _err_print_error(const char *p_function, const char *p_file, int p_line, const char *p_error, ErrorHandlerType p_type) { - - - OS::get_singleton()->print_error(p_function,p_file,p_line,p_error,_err_error_exists?OS::get_singleton()->get_last_error():"",(OS::ErrorType)p_type); + OS::get_singleton()->print_error(p_function, p_file, p_line, p_error, _err_error_exists ? OS::get_singleton()->get_last_error() : "", (OS::ErrorType)p_type); _global_lock(); ErrorHandlerList *l = error_handler_list; - while(l) { + while (l) { - l->errfunc(l->userdata,p_function,p_file,p_line,p_error,_err_error_exists?OS::get_singleton()->get_last_error():"",p_type); - l=l->next; + l->errfunc(l->userdata, p_function, p_file, p_line, p_error, _err_error_exists ? OS::get_singleton()->get_last_error() : "", p_type); + l = l->next; } _global_unlock(); if (_err_error_exists) { OS::get_singleton()->clear_last_error(); - _err_error_exists=false; + _err_error_exists = false; } - } diff --git a/core/error_macros.h b/core/error_macros.h index c3f1c0b0173..adf479a2b63 100644 --- a/core/error_macros.h +++ b/core/error_macros.h @@ -29,7 +29,6 @@ #ifndef ERROR_MACROS_H #define ERROR_MACROS_H - /** * Error macros. Unlike exceptions and asserts, these macros try to mantain consistency and stability * inside the code. It is recommended to always return processable data, so in case of an error, the @@ -52,8 +51,8 @@ enum ErrorHandlerType { ERR_HANDLER_SCRIPT }; -typedef void (*ErrorHandlerFunc)(void*,const char*,const char*,int p_line,const char *, const char *,ErrorHandlerType p_type); -void _err_set_last_error(const char* p_err); +typedef void (*ErrorHandlerFunc)(void *, const char *, const char *, int p_line, const char *, const char *, ErrorHandlerType p_type); +void _err_set_last_error(const char *p_err); void _err_clear_last_error(); struct ErrorHandlerList { @@ -61,22 +60,26 @@ struct ErrorHandlerList { ErrorHandlerFunc errfunc; void *userdata; - ErrorHandlerList*next; + ErrorHandlerList *next; - ErrorHandlerList() { errfunc=0; next=0; userdata=0; } + ErrorHandlerList() { + errfunc = 0; + next = 0; + userdata = 0; + } }; void add_error_handler(ErrorHandlerList *p_handler); void remove_error_handler(ErrorHandlerList *p_handler); -void _err_print_error(const char* p_function,const char* p_file,int p_line,const char *p_error,ErrorHandlerType p_type=ERR_HANDLER_ERROR); +void _err_print_error(const char *p_function, const char *p_file, int p_line, const char *p_error, ErrorHandlerType p_type = ERR_HANDLER_ERROR); #ifndef _STR #define _STR(m_x) #m_x #define _MKSTR(m_x) _STR(m_x) #endif -#define _FNL __FILE__":" +#define _FNL __FILE__ ":" /** An index has failed if m_index<0 or m_index >=m_size, the function exists */ @@ -85,13 +88,21 @@ extern bool _err_error_exists; #ifdef DEBUG_ENABLED /** Print a warning string. */ -#define ERR_EXPLAINC(m_reason) {_err_set_last_error(m_reason); _err_error_exists=true;} -#define ERR_EXPLAIN(m_string) {_err_set_last_error(String(m_string).utf8().get_data()); _err_error_exists=true;} +#define ERR_EXPLAINC(m_reason) \ + { \ + _err_set_last_error(m_reason); \ + _err_error_exists = true; \ + } +#define ERR_EXPLAIN(m_string) \ + { \ + _err_set_last_error(String(m_string).utf8().get_data()); \ + _err_error_exists = true; \ + } #else -#define ERR_EXPLAIN( m_text ) -#define ERR_EXPLAINC( m_text ) +#define ERR_EXPLAIN(m_text) +#define ERR_EXPLAINC(m_text) #endif @@ -102,49 +113,63 @@ extern bool _err_error_exists; #define FUNCTION_STR __FUNCTION__ #endif -#define ERR_FAIL_INDEX(m_index,m_size) \ - do {if ((m_index)<0 || (m_index)>=(m_size)) { \ - _err_print_error(FUNCTION_STR,__FILE__,__LINE__,"Index " _STR(m_index)" out of size (" _STR(m_size)")."); \ - return; \ - } else _err_error_exists=false; } while(0); \ +#define ERR_FAIL_INDEX(m_index, m_size) \ + do { \ + if ((m_index) < 0 || (m_index) >= (m_size)) { \ + _err_print_error(FUNCTION_STR, __FILE__, __LINE__, "Index " _STR(m_index) " out of size (" _STR(m_size) ")."); \ + return; \ + } else \ + _err_error_exists = false; \ + } while (0); /** An index has failed if m_index<0 or m_index >=m_size, the function exists. * This function returns an error value, if returning Error, please select the most * appropriate error condition from error_macros.h */ -#define ERR_FAIL_INDEX_V(m_index,m_size,m_retval) \ - do {if ((m_index)<0 || (m_index)>=(m_size)) { \ - _err_print_error(FUNCTION_STR,__FILE__,__LINE__,"Index " _STR(m_index)" out of size (" _STR(m_size)")."); \ - return m_retval; \ - } else _err_error_exists=false;} while (0); +#define ERR_FAIL_INDEX_V(m_index, m_size, m_retval) \ + do { \ + if ((m_index) < 0 || (m_index) >= (m_size)) { \ + _err_print_error(FUNCTION_STR, __FILE__, __LINE__, "Index " _STR(m_index) " out of size (" _STR(m_size) ")."); \ + return m_retval; \ + } else \ + _err_error_exists = false; \ + } while (0); - /** An error condition happened (m_cond tested true) (WARNING this is the opposite as assert(). +/** An error condition happened (m_cond tested true) (WARNING this is the opposite as assert(). * the function will exit. */ - #define ERR_FAIL_NULL(m_param) \ - { if ( !m_param ) { \ - _err_print_error(FUNCTION_STR,__FILE__,__LINE__,"Parameter ' " _STR(m_param)" ' is null."); \ - return; \ - }else _err_error_exists=false; } \ +#define ERR_FAIL_NULL(m_param) \ + { \ + if (!m_param) { \ + _err_print_error(FUNCTION_STR, __FILE__, __LINE__, "Parameter ' " _STR(m_param) " ' is null."); \ + return; \ + } else \ + _err_error_exists = false; \ + } - -#define ERR_FAIL_NULL_V(m_param,m_retval) \ - { if ( !m_param ) { \ - _err_print_error(FUNCTION_STR,__FILE__,__LINE__,"Parameter ' " _STR(m_param)" ' is null."); \ - return m_retval; \ - }else _err_error_exists=false; } \ +#define ERR_FAIL_NULL_V(m_param, m_retval) \ + { \ + if (!m_param) { \ + _err_print_error(FUNCTION_STR, __FILE__, __LINE__, "Parameter ' " _STR(m_param) " ' is null."); \ + return m_retval; \ + } else \ + _err_error_exists = false; \ + } /** An error condition happened (m_cond tested true) (WARNING this is the opposite as assert(). * the function will exit. */ -#define ERR_FAIL_COND(m_cond) \ - { if ( m_cond ) { \ - _err_print_error(FUNCTION_STR,__FILE__,__LINE__,"Condition ' " _STR(m_cond)" ' is true."); \ - return; \ - }else _err_error_exists=false; } \ +#define ERR_FAIL_COND(m_cond) \ + { \ + if (m_cond) { \ + _err_print_error(FUNCTION_STR, __FILE__, __LINE__, "Condition ' " _STR(m_cond) " ' is true."); \ + return; \ + } else \ + _err_error_exists = false; \ + } /** An error condition happened (m_cond tested true) (WARNING this is the opposite as assert(). * the function will exit. @@ -152,81 +177,89 @@ extern bool _err_error_exists; * appropriate error condition from error_macros.h */ -#define ERR_FAIL_COND_V(m_cond,m_retval) \ - { if ( m_cond ) { \ - _err_print_error(FUNCTION_STR,__FILE__,__LINE__,"Condition ' " _STR(m_cond)" ' is true. returned: " _STR(m_retval)); \ - return m_retval; \ - }else _err_error_exists=false; } \ +#define ERR_FAIL_COND_V(m_cond, m_retval) \ + { \ + if (m_cond) { \ + _err_print_error(FUNCTION_STR, __FILE__, __LINE__, "Condition ' " _STR(m_cond) " ' is true. returned: " _STR(m_retval)); \ + return m_retval; \ + } else \ + _err_error_exists = false; \ + } /** An error condition happened (m_cond tested true) (WARNING this is the opposite as assert(). * the loop will skip to the next iteration. */ -#define ERR_CONTINUE(m_cond) \ - { if ( m_cond ) { \ - _err_print_error(FUNCTION_STR,__FILE__,__LINE__,"Condition ' " _STR(m_cond)" ' is true. Continuing..:"); \ - continue;\ - } else _err_error_exists=false;} \ +#define ERR_CONTINUE(m_cond) \ + { \ + if (m_cond) { \ + _err_print_error(FUNCTION_STR, __FILE__, __LINE__, "Condition ' " _STR(m_cond) " ' is true. Continuing..:"); \ + continue; \ + } else \ + _err_error_exists = false; \ + } /** An error condition happened (m_cond tested true) (WARNING this is the opposite as assert(). * the loop will break */ -#define ERR_BREAK(m_cond) \ - { if ( m_cond ) { \ - _err_print_error(FUNCTION_STR,__FILE__,__LINE__,"Condition ' " _STR(m_cond)" ' is true. Breaking..:"); \ - break;\ - } else _err_error_exists=false;} \ +#define ERR_BREAK(m_cond) \ + { \ + if (m_cond) { \ + _err_print_error(FUNCTION_STR, __FILE__, __LINE__, "Condition ' " _STR(m_cond) " ' is true. Breaking..:"); \ + break; \ + } else \ + _err_error_exists = false; \ + } /** Print an error string and return */ -#define ERR_FAIL() \ -{ \ - _err_print_error(FUNCTION_STR,__FILE__,__LINE__,"Method/Function Failed."); \ - _err_error_exists=false;\ - return;\ -} \ +#define ERR_FAIL() \ + { \ + _err_print_error(FUNCTION_STR, __FILE__, __LINE__, "Method/Function Failed."); \ + _err_error_exists = false; \ + return; \ + } /** Print an error string and return with value */ -#define ERR_FAIL_V(m_value) \ -{ \ - _err_print_error(FUNCTION_STR,__FILE__,__LINE__,"Method/Function Failed, returning: " __STR(m_value)); \ - _err_error_exists=false; \ - return m_value;\ -} \ +#define ERR_FAIL_V(m_value) \ + { \ + _err_print_error(FUNCTION_STR, __FILE__, __LINE__, "Method/Function Failed, returning: " __STR(m_value)); \ + _err_error_exists = false; \ + return m_value; \ + } /** Print an error string. */ -#define ERR_PRINT(m_string) \ - { \ - _err_print_error(FUNCTION_STR,__FILE__,__LINE__,m_string); \ - _err_error_exists=false;\ - } \ +#define ERR_PRINT(m_string) \ + { \ + _err_print_error(FUNCTION_STR, __FILE__, __LINE__, m_string); \ + _err_error_exists = false; \ + } -#define ERR_PRINTS(m_string) \ - { \ - _err_print_error(FUNCTION_STR,__FILE__,__LINE__,String(m_string).utf8().get_data()); \ - _err_error_exists=false;\ - } \ +#define ERR_PRINTS(m_string) \ + { \ + _err_print_error(FUNCTION_STR, __FILE__, __LINE__, String(m_string).utf8().get_data()); \ + _err_error_exists = false; \ + } /** Print a warning string. */ -#define WARN_PRINT(m_string) \ - { \ - _err_print_error(FUNCTION_STR,__FILE__,__LINE__,m_string,ERR_HANDLER_WARNING); \ - _err_error_exists=false;\ - } \ +#define WARN_PRINT(m_string) \ + { \ + _err_print_error(FUNCTION_STR, __FILE__, __LINE__, m_string, ERR_HANDLER_WARNING); \ + _err_error_exists = false; \ + } - -#define WARN_PRINTS(m_string) \ - { \ - _err_print_error(FUNCTION_STR,__FILE__,__LINE__,String(m_string).utf8().get_data(),ERR_HANDLER_WARNING); \ - _err_error_exists=false;\ - } \ +#define WARN_PRINTS(m_string) \ + { \ + _err_print_error(FUNCTION_STR, __FILE__, __LINE__, String(m_string).utf8().get_data(), ERR_HANDLER_WARNING); \ + _err_error_exists = false; \ + } #endif diff --git a/core/event_queue.cpp b/core/event_queue.cpp index 587283cc799..f9ebc82e40a 100644 --- a/core/event_queue.cpp +++ b/core/event_queue.cpp @@ -28,134 +28,129 @@ /*************************************************************************/ #include "event_queue.h" +Error EventQueue::push_call(uint32_t p_instance_ID, const StringName &p_method, VARIANT_ARG_DECLARE) { -Error EventQueue::push_call(uint32_t p_instance_ID, const StringName& p_method, VARIANT_ARG_DECLARE) { - - uint8_t room_needed=sizeof(Event); - int args=0; - if (p_arg5.get_type()!=Variant::NIL) - args=5; - else if (p_arg4.get_type()!=Variant::NIL) - args=4; - else if (p_arg3.get_type()!=Variant::NIL) - args=3; - else if (p_arg2.get_type()!=Variant::NIL) - args=2; - else if (p_arg1.get_type()!=Variant::NIL) - args=1; + uint8_t room_needed = sizeof(Event); + int args = 0; + if (p_arg5.get_type() != Variant::NIL) + args = 5; + else if (p_arg4.get_type() != Variant::NIL) + args = 4; + else if (p_arg3.get_type() != Variant::NIL) + args = 3; + else if (p_arg2.get_type() != Variant::NIL) + args = 2; + else if (p_arg1.get_type() != Variant::NIL) + args = 1; else - args=0; + args = 0; - room_needed+=sizeof(Variant)*args; + room_needed += sizeof(Variant) * args; - ERR_FAIL_COND_V( (buffer_end+room_needed) >= buffer_size , ERR_OUT_OF_MEMORY ); - Event * ev = memnew_placement( &event_buffer[ buffer_end ], Event ); - ev->args=args; - ev->instance_ID=p_instance_ID; - ev->method=p_method; + ERR_FAIL_COND_V((buffer_end + room_needed) >= buffer_size, ERR_OUT_OF_MEMORY); + Event *ev = memnew_placement(&event_buffer[buffer_end], Event); + ev->args = args; + ev->instance_ID = p_instance_ID; + ev->method = p_method; - buffer_end+=sizeof(Event); + buffer_end += sizeof(Event); - if (args>=1) { + if (args >= 1) { - Variant * v = memnew_placement( &event_buffer[ buffer_end ], Variant ); - buffer_end+=sizeof(Variant); - *v=p_arg1; + Variant *v = memnew_placement(&event_buffer[buffer_end], Variant); + buffer_end += sizeof(Variant); + *v = p_arg1; } - if (args>=2) { + if (args >= 2) { - Variant * v = memnew_placement( &event_buffer[ buffer_end ], Variant ); - buffer_end+=sizeof(Variant); - *v=p_arg2; + Variant *v = memnew_placement(&event_buffer[buffer_end], Variant); + buffer_end += sizeof(Variant); + *v = p_arg2; } - if (args>=3) { - - Variant * v = memnew_placement( &event_buffer[ buffer_end ], Variant ); - buffer_end+=sizeof(Variant); - *v=p_arg3; + if (args >= 3) { + Variant *v = memnew_placement(&event_buffer[buffer_end], Variant); + buffer_end += sizeof(Variant); + *v = p_arg3; } - if (args>=4) { + if (args >= 4) { - Variant * v = memnew_placement( &event_buffer[ buffer_end ], Variant ); - buffer_end+=sizeof(Variant); - *v=p_arg4; + Variant *v = memnew_placement(&event_buffer[buffer_end], Variant); + buffer_end += sizeof(Variant); + *v = p_arg4; } - if (args>=5) { + if (args >= 5) { - Variant * v = memnew_placement( &event_buffer[ buffer_end ], Variant ); - buffer_end+=sizeof(Variant); - *v=p_arg5; + Variant *v = memnew_placement(&event_buffer[buffer_end], Variant); + buffer_end += sizeof(Variant); + *v = p_arg5; } if (buffer_end > buffer_max_used) - buffer_max_used=buffer_end; + buffer_max_used = buffer_end; return OK; } void EventQueue::flush_events() { - uint32_t read_pos=0; + uint32_t read_pos = 0; - while (read_pos < buffer_end ) { + while (read_pos < buffer_end) { - Event *event = (Event*)&event_buffer[ read_pos ]; - Variant *args= (Variant*)(event+1); + Event *event = (Event *)&event_buffer[read_pos]; + Variant *args = (Variant *)(event + 1); Object *obj = ObjectDB::get_instance(event->instance_ID); if (obj) { // events don't expect a return value - obj->call( event->method, - (event->args>=1) ? args[0] : Variant(), - (event->args>=2) ? args[1] : Variant(), - (event->args>=3) ? args[2] : Variant(), - (event->args>=4) ? args[3] : Variant(), - (event->args>=5) ? args[4] : Variant() ); + obj->call(event->method, + (event->args >= 1) ? args[0] : Variant(), + (event->args >= 2) ? args[1] : Variant(), + (event->args >= 3) ? args[2] : Variant(), + (event->args >= 4) ? args[3] : Variant(), + (event->args >= 5) ? args[4] : Variant()); } - if (event->args>=1) args[0].~Variant(); - if (event->args>=2) args[1].~Variant(); - if (event->args>=3) args[2].~Variant(); - if (event->args>=4) args[3].~Variant(); - if (event->args>=5) args[4].~Variant(); + if (event->args >= 1) args[0].~Variant(); + if (event->args >= 2) args[1].~Variant(); + if (event->args >= 3) args[2].~Variant(); + if (event->args >= 4) args[3].~Variant(); + if (event->args >= 5) args[4].~Variant(); event->~Event(); - read_pos+=sizeof(Event)+sizeof(Variant)*event->args; + read_pos += sizeof(Event) + sizeof(Variant) * event->args; } - buffer_end=0; // reset buffer + buffer_end = 0; // reset buffer } EventQueue::EventQueue(uint32_t p_buffer_size) { - - buffer_end=0; - buffer_max_used=0; - buffer_size=p_buffer_size; - event_buffer = memnew_arr( uint8_t, buffer_size ); - + buffer_end = 0; + buffer_max_used = 0; + buffer_size = p_buffer_size; + event_buffer = memnew_arr(uint8_t, buffer_size); } EventQueue::~EventQueue() { - uint32_t read_pos=0; + uint32_t read_pos = 0; - while (read_pos < buffer_end ) { + while (read_pos < buffer_end) { - Event *event = (Event*)&event_buffer[ read_pos ]; - Variant *args= (Variant*)(event+1); - for (int i=0;iargs;i++) + Event *event = (Event *)&event_buffer[read_pos]; + Variant *args = (Variant *)(event + 1); + for (int i = 0; i < event->args; i++) args[i].~Variant(); event->~Event(); - read_pos+=sizeof(Event)+sizeof(Variant)*event->args; + read_pos += sizeof(Event) + sizeof(Variant) * event->args; } memdelete_arr(event_buffer); - event_buffer=NULL; + event_buffer = NULL; } - diff --git a/core/event_queue.h b/core/event_queue.h index d15ff81bc7a..8e35445b683 100644 --- a/core/event_queue.h +++ b/core/event_queue.h @@ -37,7 +37,7 @@ class EventQueue { enum { - DEFAULT_EVENT_QUEUE_SIZE_KB=256 + DEFAULT_EVENT_QUEUE_SIZE_KB = 256 }; struct Event { @@ -47,20 +47,17 @@ class EventQueue { int args; }; - uint8_t *event_buffer; uint32_t buffer_end; uint32_t buffer_max_used; uint32_t buffer_size; + public: - - - Error push_call(uint32_t p_instance_ID, const StringName& p_method, VARIANT_ARG_LIST); + Error push_call(uint32_t p_instance_ID, const StringName &p_method, VARIANT_ARG_LIST); void flush_events(); - EventQueue(uint32_t p_buffer_size=DEFAULT_EVENT_QUEUE_SIZE_KB*1024); + EventQueue(uint32_t p_buffer_size = DEFAULT_EVENT_QUEUE_SIZE_KB * 1024); ~EventQueue(); - }; #endif diff --git a/core/func_ref.cpp b/core/func_ref.cpp index 48a903d49e2..1b8c01a81ce 100644 --- a/core/func_ref.cpp +++ b/core/func_ref.cpp @@ -28,55 +28,50 @@ /*************************************************************************/ #include "func_ref.h" -Variant FuncRef::call_func(const Variant** p_args, int p_argcount, Variant::CallError& r_error) { +Variant FuncRef::call_func(const Variant **p_args, int p_argcount, Variant::CallError &r_error) { - if (id==0) { - r_error.error=Variant::CallError::CALL_ERROR_INSTANCE_IS_NULL; + if (id == 0) { + r_error.error = Variant::CallError::CALL_ERROR_INSTANCE_IS_NULL; return Variant(); } - Object* obj = ObjectDB::get_instance(id); + Object *obj = ObjectDB::get_instance(id); if (!obj) { - r_error.error=Variant::CallError::CALL_ERROR_INSTANCE_IS_NULL; + r_error.error = Variant::CallError::CALL_ERROR_INSTANCE_IS_NULL; return Variant(); } - return obj->call(function,p_args,p_argcount,r_error); - + return obj->call(function, p_args, p_argcount, r_error); } -void FuncRef::set_instance(Object *p_obj){ +void FuncRef::set_instance(Object *p_obj) { ERR_FAIL_NULL(p_obj); - id=p_obj->get_instance_ID(); + id = p_obj->get_instance_ID(); } -void FuncRef::set_function(const StringName& p_func){ +void FuncRef::set_function(const StringName &p_func) { - function=p_func; + function = p_func; } void FuncRef::_bind_methods() { { MethodInfo mi; - mi.name="call_func"; + mi.name = "call_func"; Vector defargs; - for(int i=0;i<10;i++) { - mi.arguments.push_back( PropertyInfo( Variant::NIL, "arg"+itos(i))); + for (int i = 0; i < 10; i++) { + mi.arguments.push_back(PropertyInfo(Variant::NIL, "arg" + itos(i))); defargs.push_back(Variant()); } - ObjectTypeDB::bind_native_method(METHOD_FLAGS_DEFAULT,"call_func",&FuncRef::call_func,mi,defargs); - + ObjectTypeDB::bind_native_method(METHOD_FLAGS_DEFAULT, "call_func", &FuncRef::call_func, mi, defargs); } - ObjectTypeDB::bind_method(_MD("set_instance","instance"),&FuncRef::set_instance); - ObjectTypeDB::bind_method(_MD("set_function","name"),&FuncRef::set_function); - + ObjectTypeDB::bind_method(_MD("set_instance", "instance"), &FuncRef::set_instance); + ObjectTypeDB::bind_method(_MD("set_function", "name"), &FuncRef::set_function); } +FuncRef::FuncRef() { -FuncRef::FuncRef(){ - - id=0; + id = 0; } - diff --git a/core/func_ref.h b/core/func_ref.h index c3090631b24..c4ea3c03d24 100644 --- a/core/func_ref.h +++ b/core/func_ref.h @@ -31,20 +31,19 @@ #include "reference.h" -class FuncRef : public Reference{ +class FuncRef : public Reference { - OBJ_TYPE(FuncRef,Reference); + OBJ_TYPE(FuncRef, Reference); ObjectID id; StringName function; protected: - static void _bind_methods(); -public: - Variant call_func(const Variant** p_args, int p_argcount, Variant::CallError& r_error); +public: + Variant call_func(const Variant **p_args, int p_argcount, Variant::CallError &r_error); void set_instance(Object *p_obj); - void set_function(const StringName& p_func); + void set_function(const StringName &p_func); FuncRef(); }; diff --git a/core/global_constants.cpp b/core/global_constants.cpp index 87712064a95..78825254f62 100644 --- a/core/global_constants.cpp +++ b/core/global_constants.cpp @@ -27,9 +27,9 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "global_constants.h" -#include "variant.h" -#include "os/keyboard.h" #include "object.h" +#include "os/keyboard.h" +#include "variant.h" struct _GlobalConstant { @@ -37,514 +37,510 @@ struct _GlobalConstant { int value; }; -#define BIND_GLOBAL_CONSTANT(m_constant) {#m_constant,m_constant} +#define BIND_GLOBAL_CONSTANT(m_constant) \ + { #m_constant, m_constant } +static _GlobalConstant _global_constants[] = { -static _GlobalConstant _global_constants[]={ + //{ KEY_BACKSPACE, VK_BACK },// (0x08) // backspace -//{ KEY_BACKSPACE, VK_BACK },// (0x08) // backspace - - BIND_GLOBAL_CONSTANT( MARGIN_LEFT ), - BIND_GLOBAL_CONSTANT( MARGIN_TOP ), - BIND_GLOBAL_CONSTANT( MARGIN_RIGHT ), - BIND_GLOBAL_CONSTANT( MARGIN_BOTTOM ), - BIND_GLOBAL_CONSTANT( VERTICAL ), - BIND_GLOBAL_CONSTANT( HORIZONTAL ), - BIND_GLOBAL_CONSTANT( HALIGN_LEFT ), - BIND_GLOBAL_CONSTANT( HALIGN_CENTER ), - BIND_GLOBAL_CONSTANT( HALIGN_RIGHT ), - BIND_GLOBAL_CONSTANT( VALIGN_TOP ), - BIND_GLOBAL_CONSTANT( VALIGN_CENTER ), - BIND_GLOBAL_CONSTANT( VALIGN_BOTTOM ), + BIND_GLOBAL_CONSTANT(MARGIN_LEFT), + BIND_GLOBAL_CONSTANT(MARGIN_TOP), + BIND_GLOBAL_CONSTANT(MARGIN_RIGHT), + BIND_GLOBAL_CONSTANT(MARGIN_BOTTOM), + BIND_GLOBAL_CONSTANT(VERTICAL), + BIND_GLOBAL_CONSTANT(HORIZONTAL), + BIND_GLOBAL_CONSTANT(HALIGN_LEFT), + BIND_GLOBAL_CONSTANT(HALIGN_CENTER), + BIND_GLOBAL_CONSTANT(HALIGN_RIGHT), + BIND_GLOBAL_CONSTANT(VALIGN_TOP), + BIND_GLOBAL_CONSTANT(VALIGN_CENTER), + BIND_GLOBAL_CONSTANT(VALIGN_BOTTOM), // hueg list of keys - BIND_GLOBAL_CONSTANT( SPKEY ), + BIND_GLOBAL_CONSTANT(SPKEY), - BIND_GLOBAL_CONSTANT( KEY_ESCAPE ), - BIND_GLOBAL_CONSTANT( KEY_TAB ), - BIND_GLOBAL_CONSTANT( KEY_BACKTAB ), - BIND_GLOBAL_CONSTANT( KEY_BACKSPACE ), - BIND_GLOBAL_CONSTANT( KEY_RETURN ), - BIND_GLOBAL_CONSTANT( KEY_ENTER ), - BIND_GLOBAL_CONSTANT( KEY_INSERT ), - BIND_GLOBAL_CONSTANT( KEY_DELETE ), - BIND_GLOBAL_CONSTANT( KEY_PAUSE ), - BIND_GLOBAL_CONSTANT( KEY_PRINT ), - BIND_GLOBAL_CONSTANT( KEY_SYSREQ ), - BIND_GLOBAL_CONSTANT( KEY_CLEAR ), - BIND_GLOBAL_CONSTANT( KEY_HOME ), - BIND_GLOBAL_CONSTANT( KEY_END ), - BIND_GLOBAL_CONSTANT( KEY_LEFT ), - BIND_GLOBAL_CONSTANT( KEY_UP ), - BIND_GLOBAL_CONSTANT( KEY_RIGHT ), - BIND_GLOBAL_CONSTANT( KEY_DOWN ), - BIND_GLOBAL_CONSTANT( KEY_PAGEUP ), - BIND_GLOBAL_CONSTANT( KEY_PAGEDOWN ), - BIND_GLOBAL_CONSTANT( KEY_SHIFT ), - BIND_GLOBAL_CONSTANT( KEY_CONTROL ), - BIND_GLOBAL_CONSTANT( KEY_META ), - BIND_GLOBAL_CONSTANT( KEY_ALT ), - BIND_GLOBAL_CONSTANT( KEY_CAPSLOCK ), - BIND_GLOBAL_CONSTANT( KEY_NUMLOCK ), - BIND_GLOBAL_CONSTANT( KEY_SCROLLLOCK ), - BIND_GLOBAL_CONSTANT( KEY_F1 ), - BIND_GLOBAL_CONSTANT( KEY_F2 ), - BIND_GLOBAL_CONSTANT( KEY_F3 ), - BIND_GLOBAL_CONSTANT( KEY_F4 ), - BIND_GLOBAL_CONSTANT( KEY_F5 ), - BIND_GLOBAL_CONSTANT( KEY_F6 ), - BIND_GLOBAL_CONSTANT( KEY_F7 ), - BIND_GLOBAL_CONSTANT( KEY_F8 ), - BIND_GLOBAL_CONSTANT( KEY_F9 ), - BIND_GLOBAL_CONSTANT( KEY_F10 ), - BIND_GLOBAL_CONSTANT( KEY_F11 ), - BIND_GLOBAL_CONSTANT( KEY_F12 ), - BIND_GLOBAL_CONSTANT( KEY_F13 ), - BIND_GLOBAL_CONSTANT( KEY_F14 ), - BIND_GLOBAL_CONSTANT( KEY_F15 ), - BIND_GLOBAL_CONSTANT( KEY_F16 ), - BIND_GLOBAL_CONSTANT( KEY_KP_ENTER ), - BIND_GLOBAL_CONSTANT( KEY_KP_MULTIPLY ), - BIND_GLOBAL_CONSTANT( KEY_KP_DIVIDE ), - BIND_GLOBAL_CONSTANT( KEY_KP_SUBTRACT ), - BIND_GLOBAL_CONSTANT( KEY_KP_PERIOD ), - BIND_GLOBAL_CONSTANT( KEY_KP_ADD ), - BIND_GLOBAL_CONSTANT( KEY_KP_0 ), - BIND_GLOBAL_CONSTANT( KEY_KP_1 ), - BIND_GLOBAL_CONSTANT( KEY_KP_2 ), - BIND_GLOBAL_CONSTANT( KEY_KP_3 ), - BIND_GLOBAL_CONSTANT( KEY_KP_4 ), - BIND_GLOBAL_CONSTANT( KEY_KP_5 ), - BIND_GLOBAL_CONSTANT( KEY_KP_6 ), - BIND_GLOBAL_CONSTANT( KEY_KP_7 ), - BIND_GLOBAL_CONSTANT( KEY_KP_8 ), - BIND_GLOBAL_CONSTANT( KEY_KP_9 ), - BIND_GLOBAL_CONSTANT( KEY_SUPER_L ), - BIND_GLOBAL_CONSTANT( KEY_SUPER_R ), - BIND_GLOBAL_CONSTANT( KEY_MENU ), - BIND_GLOBAL_CONSTANT( KEY_HYPER_L ), - BIND_GLOBAL_CONSTANT( KEY_HYPER_R ), - BIND_GLOBAL_CONSTANT( KEY_HELP ), - BIND_GLOBAL_CONSTANT( KEY_DIRECTION_L ), - BIND_GLOBAL_CONSTANT( KEY_DIRECTION_R ), - BIND_GLOBAL_CONSTANT( KEY_BACK ), - BIND_GLOBAL_CONSTANT( KEY_FORWARD ), - BIND_GLOBAL_CONSTANT( KEY_STOP ), - BIND_GLOBAL_CONSTANT( KEY_REFRESH ), - BIND_GLOBAL_CONSTANT( KEY_VOLUMEDOWN ), - BIND_GLOBAL_CONSTANT( KEY_VOLUMEMUTE ), - BIND_GLOBAL_CONSTANT( KEY_VOLUMEUP ), - BIND_GLOBAL_CONSTANT( KEY_BASSBOOST ), - BIND_GLOBAL_CONSTANT( KEY_BASSUP ), - BIND_GLOBAL_CONSTANT( KEY_BASSDOWN ), - BIND_GLOBAL_CONSTANT( KEY_TREBLEUP ), - BIND_GLOBAL_CONSTANT( KEY_TREBLEDOWN ), - BIND_GLOBAL_CONSTANT( KEY_MEDIAPLAY ), - BIND_GLOBAL_CONSTANT( KEY_MEDIASTOP ), - BIND_GLOBAL_CONSTANT( KEY_MEDIAPREVIOUS ), - BIND_GLOBAL_CONSTANT( KEY_MEDIANEXT ), - BIND_GLOBAL_CONSTANT( KEY_MEDIARECORD ), - BIND_GLOBAL_CONSTANT( KEY_HOMEPAGE ), - BIND_GLOBAL_CONSTANT( KEY_FAVORITES ), - BIND_GLOBAL_CONSTANT( KEY_SEARCH ), - BIND_GLOBAL_CONSTANT( KEY_STANDBY ), - BIND_GLOBAL_CONSTANT( KEY_OPENURL ), - BIND_GLOBAL_CONSTANT( KEY_LAUNCHMAIL ), - BIND_GLOBAL_CONSTANT( KEY_LAUNCHMEDIA ), - BIND_GLOBAL_CONSTANT( KEY_LAUNCH0 ), - BIND_GLOBAL_CONSTANT( KEY_LAUNCH1 ), - BIND_GLOBAL_CONSTANT( KEY_LAUNCH2 ), - BIND_GLOBAL_CONSTANT( KEY_LAUNCH3 ), - BIND_GLOBAL_CONSTANT( KEY_LAUNCH4 ), - BIND_GLOBAL_CONSTANT( KEY_LAUNCH5 ), - BIND_GLOBAL_CONSTANT( KEY_LAUNCH6 ), - BIND_GLOBAL_CONSTANT( KEY_LAUNCH7 ), - BIND_GLOBAL_CONSTANT( KEY_LAUNCH8 ), - BIND_GLOBAL_CONSTANT( KEY_LAUNCH9 ), - BIND_GLOBAL_CONSTANT( KEY_LAUNCHA ), - BIND_GLOBAL_CONSTANT( KEY_LAUNCHB ), - BIND_GLOBAL_CONSTANT( KEY_LAUNCHC ), - BIND_GLOBAL_CONSTANT( KEY_LAUNCHD ), - BIND_GLOBAL_CONSTANT( KEY_LAUNCHE ), - BIND_GLOBAL_CONSTANT( KEY_LAUNCHF ), + BIND_GLOBAL_CONSTANT(KEY_ESCAPE), + BIND_GLOBAL_CONSTANT(KEY_TAB), + BIND_GLOBAL_CONSTANT(KEY_BACKTAB), + BIND_GLOBAL_CONSTANT(KEY_BACKSPACE), + BIND_GLOBAL_CONSTANT(KEY_RETURN), + BIND_GLOBAL_CONSTANT(KEY_ENTER), + BIND_GLOBAL_CONSTANT(KEY_INSERT), + BIND_GLOBAL_CONSTANT(KEY_DELETE), + BIND_GLOBAL_CONSTANT(KEY_PAUSE), + BIND_GLOBAL_CONSTANT(KEY_PRINT), + BIND_GLOBAL_CONSTANT(KEY_SYSREQ), + BIND_GLOBAL_CONSTANT(KEY_CLEAR), + BIND_GLOBAL_CONSTANT(KEY_HOME), + BIND_GLOBAL_CONSTANT(KEY_END), + BIND_GLOBAL_CONSTANT(KEY_LEFT), + BIND_GLOBAL_CONSTANT(KEY_UP), + BIND_GLOBAL_CONSTANT(KEY_RIGHT), + BIND_GLOBAL_CONSTANT(KEY_DOWN), + BIND_GLOBAL_CONSTANT(KEY_PAGEUP), + BIND_GLOBAL_CONSTANT(KEY_PAGEDOWN), + BIND_GLOBAL_CONSTANT(KEY_SHIFT), + BIND_GLOBAL_CONSTANT(KEY_CONTROL), + BIND_GLOBAL_CONSTANT(KEY_META), + BIND_GLOBAL_CONSTANT(KEY_ALT), + BIND_GLOBAL_CONSTANT(KEY_CAPSLOCK), + BIND_GLOBAL_CONSTANT(KEY_NUMLOCK), + BIND_GLOBAL_CONSTANT(KEY_SCROLLLOCK), + BIND_GLOBAL_CONSTANT(KEY_F1), + BIND_GLOBAL_CONSTANT(KEY_F2), + BIND_GLOBAL_CONSTANT(KEY_F3), + BIND_GLOBAL_CONSTANT(KEY_F4), + BIND_GLOBAL_CONSTANT(KEY_F5), + BIND_GLOBAL_CONSTANT(KEY_F6), + BIND_GLOBAL_CONSTANT(KEY_F7), + BIND_GLOBAL_CONSTANT(KEY_F8), + BIND_GLOBAL_CONSTANT(KEY_F9), + BIND_GLOBAL_CONSTANT(KEY_F10), + BIND_GLOBAL_CONSTANT(KEY_F11), + BIND_GLOBAL_CONSTANT(KEY_F12), + BIND_GLOBAL_CONSTANT(KEY_F13), + BIND_GLOBAL_CONSTANT(KEY_F14), + BIND_GLOBAL_CONSTANT(KEY_F15), + BIND_GLOBAL_CONSTANT(KEY_F16), + BIND_GLOBAL_CONSTANT(KEY_KP_ENTER), + BIND_GLOBAL_CONSTANT(KEY_KP_MULTIPLY), + BIND_GLOBAL_CONSTANT(KEY_KP_DIVIDE), + BIND_GLOBAL_CONSTANT(KEY_KP_SUBTRACT), + BIND_GLOBAL_CONSTANT(KEY_KP_PERIOD), + BIND_GLOBAL_CONSTANT(KEY_KP_ADD), + BIND_GLOBAL_CONSTANT(KEY_KP_0), + BIND_GLOBAL_CONSTANT(KEY_KP_1), + BIND_GLOBAL_CONSTANT(KEY_KP_2), + BIND_GLOBAL_CONSTANT(KEY_KP_3), + BIND_GLOBAL_CONSTANT(KEY_KP_4), + BIND_GLOBAL_CONSTANT(KEY_KP_5), + BIND_GLOBAL_CONSTANT(KEY_KP_6), + BIND_GLOBAL_CONSTANT(KEY_KP_7), + BIND_GLOBAL_CONSTANT(KEY_KP_8), + BIND_GLOBAL_CONSTANT(KEY_KP_9), + BIND_GLOBAL_CONSTANT(KEY_SUPER_L), + BIND_GLOBAL_CONSTANT(KEY_SUPER_R), + BIND_GLOBAL_CONSTANT(KEY_MENU), + BIND_GLOBAL_CONSTANT(KEY_HYPER_L), + BIND_GLOBAL_CONSTANT(KEY_HYPER_R), + BIND_GLOBAL_CONSTANT(KEY_HELP), + BIND_GLOBAL_CONSTANT(KEY_DIRECTION_L), + BIND_GLOBAL_CONSTANT(KEY_DIRECTION_R), + BIND_GLOBAL_CONSTANT(KEY_BACK), + BIND_GLOBAL_CONSTANT(KEY_FORWARD), + BIND_GLOBAL_CONSTANT(KEY_STOP), + BIND_GLOBAL_CONSTANT(KEY_REFRESH), + BIND_GLOBAL_CONSTANT(KEY_VOLUMEDOWN), + BIND_GLOBAL_CONSTANT(KEY_VOLUMEMUTE), + BIND_GLOBAL_CONSTANT(KEY_VOLUMEUP), + BIND_GLOBAL_CONSTANT(KEY_BASSBOOST), + BIND_GLOBAL_CONSTANT(KEY_BASSUP), + BIND_GLOBAL_CONSTANT(KEY_BASSDOWN), + BIND_GLOBAL_CONSTANT(KEY_TREBLEUP), + BIND_GLOBAL_CONSTANT(KEY_TREBLEDOWN), + BIND_GLOBAL_CONSTANT(KEY_MEDIAPLAY), + BIND_GLOBAL_CONSTANT(KEY_MEDIASTOP), + BIND_GLOBAL_CONSTANT(KEY_MEDIAPREVIOUS), + BIND_GLOBAL_CONSTANT(KEY_MEDIANEXT), + BIND_GLOBAL_CONSTANT(KEY_MEDIARECORD), + BIND_GLOBAL_CONSTANT(KEY_HOMEPAGE), + BIND_GLOBAL_CONSTANT(KEY_FAVORITES), + BIND_GLOBAL_CONSTANT(KEY_SEARCH), + BIND_GLOBAL_CONSTANT(KEY_STANDBY), + BIND_GLOBAL_CONSTANT(KEY_OPENURL), + BIND_GLOBAL_CONSTANT(KEY_LAUNCHMAIL), + BIND_GLOBAL_CONSTANT(KEY_LAUNCHMEDIA), + BIND_GLOBAL_CONSTANT(KEY_LAUNCH0), + BIND_GLOBAL_CONSTANT(KEY_LAUNCH1), + BIND_GLOBAL_CONSTANT(KEY_LAUNCH2), + BIND_GLOBAL_CONSTANT(KEY_LAUNCH3), + BIND_GLOBAL_CONSTANT(KEY_LAUNCH4), + BIND_GLOBAL_CONSTANT(KEY_LAUNCH5), + BIND_GLOBAL_CONSTANT(KEY_LAUNCH6), + BIND_GLOBAL_CONSTANT(KEY_LAUNCH7), + BIND_GLOBAL_CONSTANT(KEY_LAUNCH8), + BIND_GLOBAL_CONSTANT(KEY_LAUNCH9), + BIND_GLOBAL_CONSTANT(KEY_LAUNCHA), + BIND_GLOBAL_CONSTANT(KEY_LAUNCHB), + BIND_GLOBAL_CONSTANT(KEY_LAUNCHC), + BIND_GLOBAL_CONSTANT(KEY_LAUNCHD), + BIND_GLOBAL_CONSTANT(KEY_LAUNCHE), + BIND_GLOBAL_CONSTANT(KEY_LAUNCHF), - BIND_GLOBAL_CONSTANT( KEY_UNKNOWN ), - BIND_GLOBAL_CONSTANT( KEY_SPACE ), - BIND_GLOBAL_CONSTANT( KEY_EXCLAM ), - BIND_GLOBAL_CONSTANT( KEY_QUOTEDBL ), - BIND_GLOBAL_CONSTANT( KEY_NUMBERSIGN ), - BIND_GLOBAL_CONSTANT( KEY_DOLLAR ), - BIND_GLOBAL_CONSTANT( KEY_PERCENT ), - BIND_GLOBAL_CONSTANT( KEY_AMPERSAND ), - BIND_GLOBAL_CONSTANT( KEY_APOSTROPHE ), - BIND_GLOBAL_CONSTANT( KEY_PARENLEFT ), - BIND_GLOBAL_CONSTANT( KEY_PARENRIGHT ), - BIND_GLOBAL_CONSTANT( KEY_ASTERISK ), - BIND_GLOBAL_CONSTANT( KEY_PLUS ), - BIND_GLOBAL_CONSTANT( KEY_COMMA ), - BIND_GLOBAL_CONSTANT( KEY_MINUS ), - BIND_GLOBAL_CONSTANT( KEY_PERIOD ), - BIND_GLOBAL_CONSTANT( KEY_SLASH ), - BIND_GLOBAL_CONSTANT( KEY_0 ), - BIND_GLOBAL_CONSTANT( KEY_1 ), - BIND_GLOBAL_CONSTANT( KEY_2 ), - BIND_GLOBAL_CONSTANT( KEY_3 ), - BIND_GLOBAL_CONSTANT( KEY_4 ), - BIND_GLOBAL_CONSTANT( KEY_5 ), - BIND_GLOBAL_CONSTANT( KEY_6 ), - BIND_GLOBAL_CONSTANT( KEY_7 ), - BIND_GLOBAL_CONSTANT( KEY_8 ), - BIND_GLOBAL_CONSTANT( KEY_9 ), - BIND_GLOBAL_CONSTANT( KEY_COLON ), - BIND_GLOBAL_CONSTANT( KEY_SEMICOLON ), - BIND_GLOBAL_CONSTANT( KEY_LESS ), - BIND_GLOBAL_CONSTANT( KEY_EQUAL ), - BIND_GLOBAL_CONSTANT( KEY_GREATER ), - BIND_GLOBAL_CONSTANT( KEY_QUESTION ), - BIND_GLOBAL_CONSTANT( KEY_AT ), - BIND_GLOBAL_CONSTANT( KEY_A ), - BIND_GLOBAL_CONSTANT( KEY_B ), - BIND_GLOBAL_CONSTANT( KEY_C ), - BIND_GLOBAL_CONSTANT( KEY_D ), - BIND_GLOBAL_CONSTANT( KEY_E ), - BIND_GLOBAL_CONSTANT( KEY_F ), - BIND_GLOBAL_CONSTANT( KEY_G ), - BIND_GLOBAL_CONSTANT( KEY_H ), - BIND_GLOBAL_CONSTANT( KEY_I ), - BIND_GLOBAL_CONSTANT( KEY_J ), - BIND_GLOBAL_CONSTANT( KEY_K ), - BIND_GLOBAL_CONSTANT( KEY_L ), - BIND_GLOBAL_CONSTANT( KEY_M ), - BIND_GLOBAL_CONSTANT( KEY_N ), - BIND_GLOBAL_CONSTANT( KEY_O ), - BIND_GLOBAL_CONSTANT( KEY_P ), - BIND_GLOBAL_CONSTANT( KEY_Q ), - BIND_GLOBAL_CONSTANT( KEY_R ), - BIND_GLOBAL_CONSTANT( KEY_S ), - BIND_GLOBAL_CONSTANT( KEY_T ), - BIND_GLOBAL_CONSTANT( KEY_U ), - BIND_GLOBAL_CONSTANT( KEY_V ), - BIND_GLOBAL_CONSTANT( KEY_W ), - BIND_GLOBAL_CONSTANT( KEY_X ), - BIND_GLOBAL_CONSTANT( KEY_Y ), - BIND_GLOBAL_CONSTANT( KEY_Z ), - BIND_GLOBAL_CONSTANT( KEY_BRACKETLEFT ), - BIND_GLOBAL_CONSTANT( KEY_BACKSLASH ), - BIND_GLOBAL_CONSTANT( KEY_BRACKETRIGHT ), - BIND_GLOBAL_CONSTANT( KEY_ASCIICIRCUM ), - BIND_GLOBAL_CONSTANT( KEY_UNDERSCORE ), - BIND_GLOBAL_CONSTANT( KEY_QUOTELEFT ), - BIND_GLOBAL_CONSTANT( KEY_BRACELEFT ), - BIND_GLOBAL_CONSTANT( KEY_BAR ), - BIND_GLOBAL_CONSTANT( KEY_BRACERIGHT ), - BIND_GLOBAL_CONSTANT( KEY_ASCIITILDE ), - BIND_GLOBAL_CONSTANT( KEY_NOBREAKSPACE ), - BIND_GLOBAL_CONSTANT( KEY_EXCLAMDOWN ), - BIND_GLOBAL_CONSTANT( KEY_CENT ), - BIND_GLOBAL_CONSTANT( KEY_STERLING ), - BIND_GLOBAL_CONSTANT( KEY_CURRENCY ), - BIND_GLOBAL_CONSTANT( KEY_YEN ), - BIND_GLOBAL_CONSTANT( KEY_BROKENBAR ), - BIND_GLOBAL_CONSTANT( KEY_SECTION ), - BIND_GLOBAL_CONSTANT( KEY_DIAERESIS ), - BIND_GLOBAL_CONSTANT( KEY_COPYRIGHT ), - BIND_GLOBAL_CONSTANT( KEY_ORDFEMININE ), - BIND_GLOBAL_CONSTANT( KEY_GUILLEMOTLEFT ), - BIND_GLOBAL_CONSTANT( KEY_NOTSIGN ), - BIND_GLOBAL_CONSTANT( KEY_HYPHEN ), - BIND_GLOBAL_CONSTANT( KEY_REGISTERED ), - BIND_GLOBAL_CONSTANT( KEY_MACRON ), - BIND_GLOBAL_CONSTANT( KEY_DEGREE ), - BIND_GLOBAL_CONSTANT( KEY_PLUSMINUS ), - BIND_GLOBAL_CONSTANT( KEY_TWOSUPERIOR ), - BIND_GLOBAL_CONSTANT( KEY_THREESUPERIOR ), - BIND_GLOBAL_CONSTANT( KEY_ACUTE ), - BIND_GLOBAL_CONSTANT( KEY_MU ), - BIND_GLOBAL_CONSTANT( KEY_PARAGRAPH ), - BIND_GLOBAL_CONSTANT( KEY_PERIODCENTERED ), - BIND_GLOBAL_CONSTANT( KEY_CEDILLA ), - BIND_GLOBAL_CONSTANT( KEY_ONESUPERIOR ), - BIND_GLOBAL_CONSTANT( KEY_MASCULINE ), - BIND_GLOBAL_CONSTANT( KEY_GUILLEMOTRIGHT ), - BIND_GLOBAL_CONSTANT( KEY_ONEQUARTER ), - BIND_GLOBAL_CONSTANT( KEY_ONEHALF ), - BIND_GLOBAL_CONSTANT( KEY_THREEQUARTERS ), - BIND_GLOBAL_CONSTANT( KEY_QUESTIONDOWN ), - BIND_GLOBAL_CONSTANT( KEY_AGRAVE ), - BIND_GLOBAL_CONSTANT( KEY_AACUTE ), - BIND_GLOBAL_CONSTANT( KEY_ACIRCUMFLEX ), - BIND_GLOBAL_CONSTANT( KEY_ATILDE ), - BIND_GLOBAL_CONSTANT( KEY_ADIAERESIS ), - BIND_GLOBAL_CONSTANT( KEY_ARING ), - BIND_GLOBAL_CONSTANT( KEY_AE ), - BIND_GLOBAL_CONSTANT( KEY_CCEDILLA ), - BIND_GLOBAL_CONSTANT( KEY_EGRAVE ), - BIND_GLOBAL_CONSTANT( KEY_EACUTE ), - BIND_GLOBAL_CONSTANT( KEY_ECIRCUMFLEX ), - BIND_GLOBAL_CONSTANT( KEY_EDIAERESIS ), - BIND_GLOBAL_CONSTANT( KEY_IGRAVE ), - BIND_GLOBAL_CONSTANT( KEY_IACUTE ), - BIND_GLOBAL_CONSTANT( KEY_ICIRCUMFLEX ), - BIND_GLOBAL_CONSTANT( KEY_IDIAERESIS ), - BIND_GLOBAL_CONSTANT( KEY_ETH ), - BIND_GLOBAL_CONSTANT( KEY_NTILDE ), - BIND_GLOBAL_CONSTANT( KEY_OGRAVE ), - BIND_GLOBAL_CONSTANT( KEY_OACUTE ), - BIND_GLOBAL_CONSTANT( KEY_OCIRCUMFLEX ), - BIND_GLOBAL_CONSTANT( KEY_OTILDE ), - BIND_GLOBAL_CONSTANT( KEY_ODIAERESIS ), - BIND_GLOBAL_CONSTANT( KEY_MULTIPLY ), - BIND_GLOBAL_CONSTANT( KEY_OOBLIQUE ), - BIND_GLOBAL_CONSTANT( KEY_UGRAVE ), - BIND_GLOBAL_CONSTANT( KEY_UACUTE ), - BIND_GLOBAL_CONSTANT( KEY_UCIRCUMFLEX ), - BIND_GLOBAL_CONSTANT( KEY_UDIAERESIS ), - BIND_GLOBAL_CONSTANT( KEY_YACUTE ), - BIND_GLOBAL_CONSTANT( KEY_THORN ), - BIND_GLOBAL_CONSTANT( KEY_SSHARP ), + BIND_GLOBAL_CONSTANT(KEY_UNKNOWN), + BIND_GLOBAL_CONSTANT(KEY_SPACE), + BIND_GLOBAL_CONSTANT(KEY_EXCLAM), + BIND_GLOBAL_CONSTANT(KEY_QUOTEDBL), + BIND_GLOBAL_CONSTANT(KEY_NUMBERSIGN), + BIND_GLOBAL_CONSTANT(KEY_DOLLAR), + BIND_GLOBAL_CONSTANT(KEY_PERCENT), + BIND_GLOBAL_CONSTANT(KEY_AMPERSAND), + BIND_GLOBAL_CONSTANT(KEY_APOSTROPHE), + BIND_GLOBAL_CONSTANT(KEY_PARENLEFT), + BIND_GLOBAL_CONSTANT(KEY_PARENRIGHT), + BIND_GLOBAL_CONSTANT(KEY_ASTERISK), + BIND_GLOBAL_CONSTANT(KEY_PLUS), + BIND_GLOBAL_CONSTANT(KEY_COMMA), + BIND_GLOBAL_CONSTANT(KEY_MINUS), + BIND_GLOBAL_CONSTANT(KEY_PERIOD), + BIND_GLOBAL_CONSTANT(KEY_SLASH), + BIND_GLOBAL_CONSTANT(KEY_0), + BIND_GLOBAL_CONSTANT(KEY_1), + BIND_GLOBAL_CONSTANT(KEY_2), + BIND_GLOBAL_CONSTANT(KEY_3), + BIND_GLOBAL_CONSTANT(KEY_4), + BIND_GLOBAL_CONSTANT(KEY_5), + BIND_GLOBAL_CONSTANT(KEY_6), + BIND_GLOBAL_CONSTANT(KEY_7), + BIND_GLOBAL_CONSTANT(KEY_8), + BIND_GLOBAL_CONSTANT(KEY_9), + BIND_GLOBAL_CONSTANT(KEY_COLON), + BIND_GLOBAL_CONSTANT(KEY_SEMICOLON), + BIND_GLOBAL_CONSTANT(KEY_LESS), + BIND_GLOBAL_CONSTANT(KEY_EQUAL), + BIND_GLOBAL_CONSTANT(KEY_GREATER), + BIND_GLOBAL_CONSTANT(KEY_QUESTION), + BIND_GLOBAL_CONSTANT(KEY_AT), + BIND_GLOBAL_CONSTANT(KEY_A), + BIND_GLOBAL_CONSTANT(KEY_B), + BIND_GLOBAL_CONSTANT(KEY_C), + BIND_GLOBAL_CONSTANT(KEY_D), + BIND_GLOBAL_CONSTANT(KEY_E), + BIND_GLOBAL_CONSTANT(KEY_F), + BIND_GLOBAL_CONSTANT(KEY_G), + BIND_GLOBAL_CONSTANT(KEY_H), + BIND_GLOBAL_CONSTANT(KEY_I), + BIND_GLOBAL_CONSTANT(KEY_J), + BIND_GLOBAL_CONSTANT(KEY_K), + BIND_GLOBAL_CONSTANT(KEY_L), + BIND_GLOBAL_CONSTANT(KEY_M), + BIND_GLOBAL_CONSTANT(KEY_N), + BIND_GLOBAL_CONSTANT(KEY_O), + BIND_GLOBAL_CONSTANT(KEY_P), + BIND_GLOBAL_CONSTANT(KEY_Q), + BIND_GLOBAL_CONSTANT(KEY_R), + BIND_GLOBAL_CONSTANT(KEY_S), + BIND_GLOBAL_CONSTANT(KEY_T), + BIND_GLOBAL_CONSTANT(KEY_U), + BIND_GLOBAL_CONSTANT(KEY_V), + BIND_GLOBAL_CONSTANT(KEY_W), + BIND_GLOBAL_CONSTANT(KEY_X), + BIND_GLOBAL_CONSTANT(KEY_Y), + BIND_GLOBAL_CONSTANT(KEY_Z), + BIND_GLOBAL_CONSTANT(KEY_BRACKETLEFT), + BIND_GLOBAL_CONSTANT(KEY_BACKSLASH), + BIND_GLOBAL_CONSTANT(KEY_BRACKETRIGHT), + BIND_GLOBAL_CONSTANT(KEY_ASCIICIRCUM), + BIND_GLOBAL_CONSTANT(KEY_UNDERSCORE), + BIND_GLOBAL_CONSTANT(KEY_QUOTELEFT), + BIND_GLOBAL_CONSTANT(KEY_BRACELEFT), + BIND_GLOBAL_CONSTANT(KEY_BAR), + BIND_GLOBAL_CONSTANT(KEY_BRACERIGHT), + BIND_GLOBAL_CONSTANT(KEY_ASCIITILDE), + BIND_GLOBAL_CONSTANT(KEY_NOBREAKSPACE), + BIND_GLOBAL_CONSTANT(KEY_EXCLAMDOWN), + BIND_GLOBAL_CONSTANT(KEY_CENT), + BIND_GLOBAL_CONSTANT(KEY_STERLING), + BIND_GLOBAL_CONSTANT(KEY_CURRENCY), + BIND_GLOBAL_CONSTANT(KEY_YEN), + BIND_GLOBAL_CONSTANT(KEY_BROKENBAR), + BIND_GLOBAL_CONSTANT(KEY_SECTION), + BIND_GLOBAL_CONSTANT(KEY_DIAERESIS), + BIND_GLOBAL_CONSTANT(KEY_COPYRIGHT), + BIND_GLOBAL_CONSTANT(KEY_ORDFEMININE), + BIND_GLOBAL_CONSTANT(KEY_GUILLEMOTLEFT), + BIND_GLOBAL_CONSTANT(KEY_NOTSIGN), + BIND_GLOBAL_CONSTANT(KEY_HYPHEN), + BIND_GLOBAL_CONSTANT(KEY_REGISTERED), + BIND_GLOBAL_CONSTANT(KEY_MACRON), + BIND_GLOBAL_CONSTANT(KEY_DEGREE), + BIND_GLOBAL_CONSTANT(KEY_PLUSMINUS), + BIND_GLOBAL_CONSTANT(KEY_TWOSUPERIOR), + BIND_GLOBAL_CONSTANT(KEY_THREESUPERIOR), + BIND_GLOBAL_CONSTANT(KEY_ACUTE), + BIND_GLOBAL_CONSTANT(KEY_MU), + BIND_GLOBAL_CONSTANT(KEY_PARAGRAPH), + BIND_GLOBAL_CONSTANT(KEY_PERIODCENTERED), + BIND_GLOBAL_CONSTANT(KEY_CEDILLA), + BIND_GLOBAL_CONSTANT(KEY_ONESUPERIOR), + BIND_GLOBAL_CONSTANT(KEY_MASCULINE), + BIND_GLOBAL_CONSTANT(KEY_GUILLEMOTRIGHT), + BIND_GLOBAL_CONSTANT(KEY_ONEQUARTER), + BIND_GLOBAL_CONSTANT(KEY_ONEHALF), + BIND_GLOBAL_CONSTANT(KEY_THREEQUARTERS), + BIND_GLOBAL_CONSTANT(KEY_QUESTIONDOWN), + BIND_GLOBAL_CONSTANT(KEY_AGRAVE), + BIND_GLOBAL_CONSTANT(KEY_AACUTE), + BIND_GLOBAL_CONSTANT(KEY_ACIRCUMFLEX), + BIND_GLOBAL_CONSTANT(KEY_ATILDE), + BIND_GLOBAL_CONSTANT(KEY_ADIAERESIS), + BIND_GLOBAL_CONSTANT(KEY_ARING), + BIND_GLOBAL_CONSTANT(KEY_AE), + BIND_GLOBAL_CONSTANT(KEY_CCEDILLA), + BIND_GLOBAL_CONSTANT(KEY_EGRAVE), + BIND_GLOBAL_CONSTANT(KEY_EACUTE), + BIND_GLOBAL_CONSTANT(KEY_ECIRCUMFLEX), + BIND_GLOBAL_CONSTANT(KEY_EDIAERESIS), + BIND_GLOBAL_CONSTANT(KEY_IGRAVE), + BIND_GLOBAL_CONSTANT(KEY_IACUTE), + BIND_GLOBAL_CONSTANT(KEY_ICIRCUMFLEX), + BIND_GLOBAL_CONSTANT(KEY_IDIAERESIS), + BIND_GLOBAL_CONSTANT(KEY_ETH), + BIND_GLOBAL_CONSTANT(KEY_NTILDE), + BIND_GLOBAL_CONSTANT(KEY_OGRAVE), + BIND_GLOBAL_CONSTANT(KEY_OACUTE), + BIND_GLOBAL_CONSTANT(KEY_OCIRCUMFLEX), + BIND_GLOBAL_CONSTANT(KEY_OTILDE), + BIND_GLOBAL_CONSTANT(KEY_ODIAERESIS), + BIND_GLOBAL_CONSTANT(KEY_MULTIPLY), + BIND_GLOBAL_CONSTANT(KEY_OOBLIQUE), + BIND_GLOBAL_CONSTANT(KEY_UGRAVE), + BIND_GLOBAL_CONSTANT(KEY_UACUTE), + BIND_GLOBAL_CONSTANT(KEY_UCIRCUMFLEX), + BIND_GLOBAL_CONSTANT(KEY_UDIAERESIS), + BIND_GLOBAL_CONSTANT(KEY_YACUTE), + BIND_GLOBAL_CONSTANT(KEY_THORN), + BIND_GLOBAL_CONSTANT(KEY_SSHARP), - BIND_GLOBAL_CONSTANT( KEY_DIVISION ), - BIND_GLOBAL_CONSTANT( KEY_YDIAERESIS ), + BIND_GLOBAL_CONSTANT(KEY_DIVISION), + BIND_GLOBAL_CONSTANT(KEY_YDIAERESIS), - BIND_GLOBAL_CONSTANT( KEY_CODE_MASK ), - BIND_GLOBAL_CONSTANT( KEY_MODIFIER_MASK ), + BIND_GLOBAL_CONSTANT(KEY_CODE_MASK), + BIND_GLOBAL_CONSTANT(KEY_MODIFIER_MASK), - BIND_GLOBAL_CONSTANT( KEY_MASK_SHIFT ), - BIND_GLOBAL_CONSTANT( KEY_MASK_ALT ), - BIND_GLOBAL_CONSTANT( KEY_MASK_META ), - BIND_GLOBAL_CONSTANT( KEY_MASK_CTRL ), - BIND_GLOBAL_CONSTANT( KEY_MASK_CMD ), - BIND_GLOBAL_CONSTANT( KEY_MASK_KPAD ), - BIND_GLOBAL_CONSTANT( KEY_MASK_GROUP_SWITCH ), + BIND_GLOBAL_CONSTANT(KEY_MASK_SHIFT), + BIND_GLOBAL_CONSTANT(KEY_MASK_ALT), + BIND_GLOBAL_CONSTANT(KEY_MASK_META), + BIND_GLOBAL_CONSTANT(KEY_MASK_CTRL), + BIND_GLOBAL_CONSTANT(KEY_MASK_CMD), + BIND_GLOBAL_CONSTANT(KEY_MASK_KPAD), + BIND_GLOBAL_CONSTANT(KEY_MASK_GROUP_SWITCH), // mouse - BIND_GLOBAL_CONSTANT( BUTTON_LEFT ), - BIND_GLOBAL_CONSTANT( BUTTON_RIGHT ), - BIND_GLOBAL_CONSTANT( BUTTON_MIDDLE ), - BIND_GLOBAL_CONSTANT( BUTTON_WHEEL_UP ), - BIND_GLOBAL_CONSTANT( BUTTON_WHEEL_DOWN ), - BIND_GLOBAL_CONSTANT( BUTTON_WHEEL_LEFT ), - BIND_GLOBAL_CONSTANT( BUTTON_WHEEL_RIGHT ), - BIND_GLOBAL_CONSTANT( BUTTON_MASK_LEFT ), - BIND_GLOBAL_CONSTANT( BUTTON_MASK_RIGHT ), - BIND_GLOBAL_CONSTANT( BUTTON_MASK_MIDDLE ), + BIND_GLOBAL_CONSTANT(BUTTON_LEFT), + BIND_GLOBAL_CONSTANT(BUTTON_RIGHT), + BIND_GLOBAL_CONSTANT(BUTTON_MIDDLE), + BIND_GLOBAL_CONSTANT(BUTTON_WHEEL_UP), + BIND_GLOBAL_CONSTANT(BUTTON_WHEEL_DOWN), + BIND_GLOBAL_CONSTANT(BUTTON_WHEEL_LEFT), + BIND_GLOBAL_CONSTANT(BUTTON_WHEEL_RIGHT), + BIND_GLOBAL_CONSTANT(BUTTON_MASK_LEFT), + BIND_GLOBAL_CONSTANT(BUTTON_MASK_RIGHT), + BIND_GLOBAL_CONSTANT(BUTTON_MASK_MIDDLE), //joysticks - BIND_GLOBAL_CONSTANT( JOY_BUTTON_0 ), - BIND_GLOBAL_CONSTANT( JOY_BUTTON_1 ), - BIND_GLOBAL_CONSTANT( JOY_BUTTON_2 ), - BIND_GLOBAL_CONSTANT( JOY_BUTTON_3 ), - BIND_GLOBAL_CONSTANT( JOY_BUTTON_4 ), - BIND_GLOBAL_CONSTANT( JOY_BUTTON_5 ), - BIND_GLOBAL_CONSTANT( JOY_BUTTON_6 ), - BIND_GLOBAL_CONSTANT( JOY_BUTTON_7 ), - BIND_GLOBAL_CONSTANT( JOY_BUTTON_8 ), - BIND_GLOBAL_CONSTANT( JOY_BUTTON_9 ), - BIND_GLOBAL_CONSTANT( JOY_BUTTON_10 ), - BIND_GLOBAL_CONSTANT( JOY_BUTTON_11 ), - BIND_GLOBAL_CONSTANT( JOY_BUTTON_12 ), - BIND_GLOBAL_CONSTANT( JOY_BUTTON_13 ), - BIND_GLOBAL_CONSTANT( JOY_BUTTON_14 ), - BIND_GLOBAL_CONSTANT( JOY_BUTTON_15 ), - BIND_GLOBAL_CONSTANT( JOY_BUTTON_MAX ), + BIND_GLOBAL_CONSTANT(JOY_BUTTON_0), + BIND_GLOBAL_CONSTANT(JOY_BUTTON_1), + BIND_GLOBAL_CONSTANT(JOY_BUTTON_2), + BIND_GLOBAL_CONSTANT(JOY_BUTTON_3), + BIND_GLOBAL_CONSTANT(JOY_BUTTON_4), + BIND_GLOBAL_CONSTANT(JOY_BUTTON_5), + BIND_GLOBAL_CONSTANT(JOY_BUTTON_6), + BIND_GLOBAL_CONSTANT(JOY_BUTTON_7), + BIND_GLOBAL_CONSTANT(JOY_BUTTON_8), + BIND_GLOBAL_CONSTANT(JOY_BUTTON_9), + BIND_GLOBAL_CONSTANT(JOY_BUTTON_10), + BIND_GLOBAL_CONSTANT(JOY_BUTTON_11), + BIND_GLOBAL_CONSTANT(JOY_BUTTON_12), + BIND_GLOBAL_CONSTANT(JOY_BUTTON_13), + BIND_GLOBAL_CONSTANT(JOY_BUTTON_14), + BIND_GLOBAL_CONSTANT(JOY_BUTTON_15), + BIND_GLOBAL_CONSTANT(JOY_BUTTON_MAX), - BIND_GLOBAL_CONSTANT( JOY_SNES_A ), - BIND_GLOBAL_CONSTANT( JOY_SNES_B ), - BIND_GLOBAL_CONSTANT( JOY_SNES_X ), - BIND_GLOBAL_CONSTANT( JOY_SNES_Y ), + BIND_GLOBAL_CONSTANT(JOY_SNES_A), + BIND_GLOBAL_CONSTANT(JOY_SNES_B), + BIND_GLOBAL_CONSTANT(JOY_SNES_X), + BIND_GLOBAL_CONSTANT(JOY_SNES_Y), - BIND_GLOBAL_CONSTANT( JOY_SONY_CIRCLE ), - BIND_GLOBAL_CONSTANT( JOY_SONY_X ), - BIND_GLOBAL_CONSTANT( JOY_SONY_SQUARE ), - BIND_GLOBAL_CONSTANT( JOY_SONY_TRIANGLE ), + BIND_GLOBAL_CONSTANT(JOY_SONY_CIRCLE), + BIND_GLOBAL_CONSTANT(JOY_SONY_X), + BIND_GLOBAL_CONSTANT(JOY_SONY_SQUARE), + BIND_GLOBAL_CONSTANT(JOY_SONY_TRIANGLE), - BIND_GLOBAL_CONSTANT( JOY_SEGA_B ), - BIND_GLOBAL_CONSTANT( JOY_SEGA_A ), - BIND_GLOBAL_CONSTANT( JOY_SEGA_X ), - BIND_GLOBAL_CONSTANT( JOY_SEGA_Y ), + BIND_GLOBAL_CONSTANT(JOY_SEGA_B), + BIND_GLOBAL_CONSTANT(JOY_SEGA_A), + BIND_GLOBAL_CONSTANT(JOY_SEGA_X), + BIND_GLOBAL_CONSTANT(JOY_SEGA_Y), - BIND_GLOBAL_CONSTANT( JOY_XBOX_B ), - BIND_GLOBAL_CONSTANT( JOY_XBOX_A ), - BIND_GLOBAL_CONSTANT( JOY_XBOX_X ), - BIND_GLOBAL_CONSTANT( JOY_XBOX_Y ), + BIND_GLOBAL_CONSTANT(JOY_XBOX_B), + BIND_GLOBAL_CONSTANT(JOY_XBOX_A), + BIND_GLOBAL_CONSTANT(JOY_XBOX_X), + BIND_GLOBAL_CONSTANT(JOY_XBOX_Y), - BIND_GLOBAL_CONSTANT( JOY_DS_A ), - BIND_GLOBAL_CONSTANT( JOY_DS_B ), - BIND_GLOBAL_CONSTANT( JOY_DS_X ), - BIND_GLOBAL_CONSTANT( JOY_DS_Y ), + BIND_GLOBAL_CONSTANT(JOY_DS_A), + BIND_GLOBAL_CONSTANT(JOY_DS_B), + BIND_GLOBAL_CONSTANT(JOY_DS_X), + BIND_GLOBAL_CONSTANT(JOY_DS_Y), - BIND_GLOBAL_CONSTANT( JOY_SELECT ), - BIND_GLOBAL_CONSTANT( JOY_START ), - BIND_GLOBAL_CONSTANT( JOY_DPAD_UP ), - BIND_GLOBAL_CONSTANT( JOY_DPAD_DOWN ), - BIND_GLOBAL_CONSTANT( JOY_DPAD_LEFT ), - BIND_GLOBAL_CONSTANT( JOY_DPAD_RIGHT ), - BIND_GLOBAL_CONSTANT( JOY_L ), - BIND_GLOBAL_CONSTANT( JOY_L2 ), - BIND_GLOBAL_CONSTANT( JOY_L3 ), - BIND_GLOBAL_CONSTANT( JOY_R ), - BIND_GLOBAL_CONSTANT( JOY_R2 ), - BIND_GLOBAL_CONSTANT( JOY_R3 ), + BIND_GLOBAL_CONSTANT(JOY_SELECT), + BIND_GLOBAL_CONSTANT(JOY_START), + BIND_GLOBAL_CONSTANT(JOY_DPAD_UP), + BIND_GLOBAL_CONSTANT(JOY_DPAD_DOWN), + BIND_GLOBAL_CONSTANT(JOY_DPAD_LEFT), + BIND_GLOBAL_CONSTANT(JOY_DPAD_RIGHT), + BIND_GLOBAL_CONSTANT(JOY_L), + BIND_GLOBAL_CONSTANT(JOY_L2), + BIND_GLOBAL_CONSTANT(JOY_L3), + BIND_GLOBAL_CONSTANT(JOY_R), + BIND_GLOBAL_CONSTANT(JOY_R2), + BIND_GLOBAL_CONSTANT(JOY_R3), - BIND_GLOBAL_CONSTANT( JOY_AXIS_0 ), - BIND_GLOBAL_CONSTANT( JOY_AXIS_1 ), - BIND_GLOBAL_CONSTANT( JOY_AXIS_2 ), - BIND_GLOBAL_CONSTANT( JOY_AXIS_3 ), - BIND_GLOBAL_CONSTANT( JOY_AXIS_4 ), - BIND_GLOBAL_CONSTANT( JOY_AXIS_5 ), - BIND_GLOBAL_CONSTANT( JOY_AXIS_6 ), - BIND_GLOBAL_CONSTANT( JOY_AXIS_7 ), - BIND_GLOBAL_CONSTANT( JOY_AXIS_MAX ), + BIND_GLOBAL_CONSTANT(JOY_AXIS_0), + BIND_GLOBAL_CONSTANT(JOY_AXIS_1), + BIND_GLOBAL_CONSTANT(JOY_AXIS_2), + BIND_GLOBAL_CONSTANT(JOY_AXIS_3), + BIND_GLOBAL_CONSTANT(JOY_AXIS_4), + BIND_GLOBAL_CONSTANT(JOY_AXIS_5), + BIND_GLOBAL_CONSTANT(JOY_AXIS_6), + BIND_GLOBAL_CONSTANT(JOY_AXIS_7), + BIND_GLOBAL_CONSTANT(JOY_AXIS_MAX), - BIND_GLOBAL_CONSTANT( JOY_ANALOG_0_X ), - BIND_GLOBAL_CONSTANT( JOY_ANALOG_0_Y ), + BIND_GLOBAL_CONSTANT(JOY_ANALOG_0_X), + BIND_GLOBAL_CONSTANT(JOY_ANALOG_0_Y), - BIND_GLOBAL_CONSTANT( JOY_ANALOG_1_X ), - BIND_GLOBAL_CONSTANT( JOY_ANALOG_1_Y ), + BIND_GLOBAL_CONSTANT(JOY_ANALOG_1_X), + BIND_GLOBAL_CONSTANT(JOY_ANALOG_1_Y), - BIND_GLOBAL_CONSTANT( JOY_ANALOG_2_X ), - BIND_GLOBAL_CONSTANT( JOY_ANALOG_2_Y ), - - BIND_GLOBAL_CONSTANT( JOY_ANALOG_L2 ), - BIND_GLOBAL_CONSTANT( JOY_ANALOG_R2 ), + BIND_GLOBAL_CONSTANT(JOY_ANALOG_2_X), + BIND_GLOBAL_CONSTANT(JOY_ANALOG_2_Y), + BIND_GLOBAL_CONSTANT(JOY_ANALOG_L2), + BIND_GLOBAL_CONSTANT(JOY_ANALOG_R2), // error list - BIND_GLOBAL_CONSTANT( OK ), - BIND_GLOBAL_CONSTANT( FAILED ), ///< Generic fail error - BIND_GLOBAL_CONSTANT( ERR_UNAVAILABLE ), ///< What is requested is unsupported/unavailable - BIND_GLOBAL_CONSTANT( ERR_UNCONFIGURED ), ///< The object being used hasnt been properly set up yet - BIND_GLOBAL_CONSTANT( ERR_UNAUTHORIZED ), ///< Missing credentials for requested resource - BIND_GLOBAL_CONSTANT( ERR_PARAMETER_RANGE_ERROR ), ///< Parameter given out of range - BIND_GLOBAL_CONSTANT( ERR_OUT_OF_MEMORY ), ///< Out of memory - BIND_GLOBAL_CONSTANT( ERR_FILE_NOT_FOUND ), - BIND_GLOBAL_CONSTANT( ERR_FILE_BAD_DRIVE ), - BIND_GLOBAL_CONSTANT( ERR_FILE_BAD_PATH ), - BIND_GLOBAL_CONSTANT( ERR_FILE_NO_PERMISSION ), - BIND_GLOBAL_CONSTANT( ERR_FILE_ALREADY_IN_USE ), - BIND_GLOBAL_CONSTANT( ERR_FILE_CANT_OPEN ), - BIND_GLOBAL_CONSTANT( ERR_FILE_CANT_WRITE ), - BIND_GLOBAL_CONSTANT( ERR_FILE_CANT_READ ), - BIND_GLOBAL_CONSTANT( ERR_FILE_UNRECOGNIZED ), - BIND_GLOBAL_CONSTANT( ERR_FILE_CORRUPT ), - BIND_GLOBAL_CONSTANT( ERR_FILE_MISSING_DEPENDENCIES), - BIND_GLOBAL_CONSTANT( ERR_FILE_EOF ), - BIND_GLOBAL_CONSTANT( ERR_CANT_OPEN ), ///< Can't open a resource/socket/file - BIND_GLOBAL_CONSTANT( ERR_CANT_CREATE ), - BIND_GLOBAL_CONSTANT( ERR_PARSE_ERROR ), - BIND_GLOBAL_CONSTANT( ERROR_QUERY_FAILED ), - BIND_GLOBAL_CONSTANT( ERR_ALREADY_IN_USE ), - BIND_GLOBAL_CONSTANT( ERR_LOCKED ), ///< resource is locked - BIND_GLOBAL_CONSTANT( ERR_TIMEOUT ), - BIND_GLOBAL_CONSTANT( ERR_CANT_AQUIRE_RESOURCE ), - BIND_GLOBAL_CONSTANT( ERR_INVALID_DATA ), ///< Data passed is invalid - BIND_GLOBAL_CONSTANT( ERR_INVALID_PARAMETER ), ///< Parameter passed is invalid - BIND_GLOBAL_CONSTANT( ERR_ALREADY_EXISTS ), ///< When adding ), item already exists - BIND_GLOBAL_CONSTANT( ERR_DOES_NOT_EXIST ), ///< When retrieving/erasing ), it item does not exist - BIND_GLOBAL_CONSTANT( ERR_DATABASE_CANT_READ ), ///< database is full - BIND_GLOBAL_CONSTANT( ERR_DATABASE_CANT_WRITE ), ///< database is full - BIND_GLOBAL_CONSTANT( ERR_COMPILATION_FAILED ), - BIND_GLOBAL_CONSTANT( ERR_METHOD_NOT_FOUND ), - BIND_GLOBAL_CONSTANT( ERR_LINK_FAILED ), - BIND_GLOBAL_CONSTANT( ERR_SCRIPT_FAILED ), - BIND_GLOBAL_CONSTANT( ERR_CYCLIC_LINK ), - BIND_GLOBAL_CONSTANT( ERR_BUSY ), - BIND_GLOBAL_CONSTANT( ERR_HELP ), ///< user requested help!! - BIND_GLOBAL_CONSTANT( ERR_BUG ), ///< a bug in the software certainly happened ), due to a double check failing or unexpected behavior. - BIND_GLOBAL_CONSTANT( ERR_WTF ), + BIND_GLOBAL_CONSTANT(OK), + BIND_GLOBAL_CONSTANT(FAILED), ///< Generic fail error + BIND_GLOBAL_CONSTANT(ERR_UNAVAILABLE), ///< What is requested is unsupported/unavailable + BIND_GLOBAL_CONSTANT(ERR_UNCONFIGURED), ///< The object being used hasnt been properly set up yet + BIND_GLOBAL_CONSTANT(ERR_UNAUTHORIZED), ///< Missing credentials for requested resource + BIND_GLOBAL_CONSTANT(ERR_PARAMETER_RANGE_ERROR), ///< Parameter given out of range + BIND_GLOBAL_CONSTANT(ERR_OUT_OF_MEMORY), ///< Out of memory + BIND_GLOBAL_CONSTANT(ERR_FILE_NOT_FOUND), + BIND_GLOBAL_CONSTANT(ERR_FILE_BAD_DRIVE), + BIND_GLOBAL_CONSTANT(ERR_FILE_BAD_PATH), + BIND_GLOBAL_CONSTANT(ERR_FILE_NO_PERMISSION), + BIND_GLOBAL_CONSTANT(ERR_FILE_ALREADY_IN_USE), + BIND_GLOBAL_CONSTANT(ERR_FILE_CANT_OPEN), + BIND_GLOBAL_CONSTANT(ERR_FILE_CANT_WRITE), + BIND_GLOBAL_CONSTANT(ERR_FILE_CANT_READ), + BIND_GLOBAL_CONSTANT(ERR_FILE_UNRECOGNIZED), + BIND_GLOBAL_CONSTANT(ERR_FILE_CORRUPT), + BIND_GLOBAL_CONSTANT(ERR_FILE_MISSING_DEPENDENCIES), + BIND_GLOBAL_CONSTANT(ERR_FILE_EOF), + BIND_GLOBAL_CONSTANT(ERR_CANT_OPEN), ///< Can't open a resource/socket/file + BIND_GLOBAL_CONSTANT(ERR_CANT_CREATE), + BIND_GLOBAL_CONSTANT(ERR_PARSE_ERROR), + BIND_GLOBAL_CONSTANT(ERROR_QUERY_FAILED), + BIND_GLOBAL_CONSTANT(ERR_ALREADY_IN_USE), + BIND_GLOBAL_CONSTANT(ERR_LOCKED), ///< resource is locked + BIND_GLOBAL_CONSTANT(ERR_TIMEOUT), + BIND_GLOBAL_CONSTANT(ERR_CANT_AQUIRE_RESOURCE), + BIND_GLOBAL_CONSTANT(ERR_INVALID_DATA), ///< Data passed is invalid + BIND_GLOBAL_CONSTANT(ERR_INVALID_PARAMETER), ///< Parameter passed is invalid + BIND_GLOBAL_CONSTANT(ERR_ALREADY_EXISTS), ///< When adding ), item already exists + BIND_GLOBAL_CONSTANT(ERR_DOES_NOT_EXIST), ///< When retrieving/erasing ), it item does not exist + BIND_GLOBAL_CONSTANT(ERR_DATABASE_CANT_READ), ///< database is full + BIND_GLOBAL_CONSTANT(ERR_DATABASE_CANT_WRITE), ///< database is full + BIND_GLOBAL_CONSTANT(ERR_COMPILATION_FAILED), + BIND_GLOBAL_CONSTANT(ERR_METHOD_NOT_FOUND), + BIND_GLOBAL_CONSTANT(ERR_LINK_FAILED), + BIND_GLOBAL_CONSTANT(ERR_SCRIPT_FAILED), + BIND_GLOBAL_CONSTANT(ERR_CYCLIC_LINK), + BIND_GLOBAL_CONSTANT(ERR_BUSY), + BIND_GLOBAL_CONSTANT(ERR_HELP), ///< user requested help!! + BIND_GLOBAL_CONSTANT(ERR_BUG), ///< a bug in the software certainly happened ), due to a double check failing or unexpected behavior. + BIND_GLOBAL_CONSTANT(ERR_WTF), + BIND_GLOBAL_CONSTANT(PROPERTY_HINT_NONE), + BIND_GLOBAL_CONSTANT(PROPERTY_HINT_RANGE), + BIND_GLOBAL_CONSTANT(PROPERTY_HINT_EXP_RANGE), + BIND_GLOBAL_CONSTANT(PROPERTY_HINT_ENUM), + BIND_GLOBAL_CONSTANT(PROPERTY_HINT_EXP_EASING), + BIND_GLOBAL_CONSTANT(PROPERTY_HINT_LENGTH), + BIND_GLOBAL_CONSTANT(PROPERTY_HINT_KEY_ACCEL), + BIND_GLOBAL_CONSTANT(PROPERTY_HINT_FLAGS), + BIND_GLOBAL_CONSTANT(PROPERTY_HINT_ALL_FLAGS), + BIND_GLOBAL_CONSTANT(PROPERTY_HINT_FILE), + BIND_GLOBAL_CONSTANT(PROPERTY_HINT_DIR), + BIND_GLOBAL_CONSTANT(PROPERTY_HINT_GLOBAL_FILE), + BIND_GLOBAL_CONSTANT(PROPERTY_HINT_GLOBAL_DIR), + BIND_GLOBAL_CONSTANT(PROPERTY_HINT_RESOURCE_TYPE), + BIND_GLOBAL_CONSTANT(PROPERTY_HINT_MULTILINE_TEXT), + BIND_GLOBAL_CONSTANT(PROPERTY_HINT_COLOR_NO_ALPHA), + BIND_GLOBAL_CONSTANT(PROPERTY_HINT_IMAGE_COMPRESS_LOSSY), + BIND_GLOBAL_CONSTANT(PROPERTY_HINT_IMAGE_COMPRESS_LOSSLESS), - BIND_GLOBAL_CONSTANT( PROPERTY_HINT_NONE ), - BIND_GLOBAL_CONSTANT( PROPERTY_HINT_RANGE ), - BIND_GLOBAL_CONSTANT( PROPERTY_HINT_EXP_RANGE ), - BIND_GLOBAL_CONSTANT( PROPERTY_HINT_ENUM ), - BIND_GLOBAL_CONSTANT( PROPERTY_HINT_EXP_EASING ), - BIND_GLOBAL_CONSTANT( PROPERTY_HINT_LENGTH ), - BIND_GLOBAL_CONSTANT( PROPERTY_HINT_KEY_ACCEL ), - BIND_GLOBAL_CONSTANT( PROPERTY_HINT_FLAGS ), - BIND_GLOBAL_CONSTANT( PROPERTY_HINT_ALL_FLAGS ), - BIND_GLOBAL_CONSTANT( PROPERTY_HINT_FILE ), - BIND_GLOBAL_CONSTANT( PROPERTY_HINT_DIR ), - BIND_GLOBAL_CONSTANT( PROPERTY_HINT_GLOBAL_FILE ), - BIND_GLOBAL_CONSTANT( PROPERTY_HINT_GLOBAL_DIR ), - BIND_GLOBAL_CONSTANT( PROPERTY_HINT_RESOURCE_TYPE ), - BIND_GLOBAL_CONSTANT( PROPERTY_HINT_MULTILINE_TEXT ), - BIND_GLOBAL_CONSTANT( PROPERTY_HINT_COLOR_NO_ALPHA ), - BIND_GLOBAL_CONSTANT( PROPERTY_HINT_IMAGE_COMPRESS_LOSSY ), - BIND_GLOBAL_CONSTANT( PROPERTY_HINT_IMAGE_COMPRESS_LOSSLESS ), + BIND_GLOBAL_CONSTANT(PROPERTY_USAGE_STORAGE), + BIND_GLOBAL_CONSTANT(PROPERTY_USAGE_EDITOR), + BIND_GLOBAL_CONSTANT(PROPERTY_USAGE_NETWORK), + BIND_GLOBAL_CONSTANT(PROPERTY_USAGE_EDITOR_HELPER), + BIND_GLOBAL_CONSTANT(PROPERTY_USAGE_CHECKABLE), + BIND_GLOBAL_CONSTANT(PROPERTY_USAGE_CHECKED), + BIND_GLOBAL_CONSTANT(PROPERTY_USAGE_INTERNATIONALIZED), + BIND_GLOBAL_CONSTANT(PROPERTY_USAGE_BUNDLE), + BIND_GLOBAL_CONSTANT(PROPERTY_USAGE_CATEGORY), + BIND_GLOBAL_CONSTANT(PROPERTY_USAGE_STORE_IF_NONZERO), + BIND_GLOBAL_CONSTANT(PROPERTY_USAGE_STORE_IF_NONONE), + BIND_GLOBAL_CONSTANT(PROPERTY_USAGE_NO_INSTANCE_STATE), + BIND_GLOBAL_CONSTANT(PROPERTY_USAGE_RESTART_IF_CHANGED), + BIND_GLOBAL_CONSTANT(PROPERTY_USAGE_SCRIPT_VARIABLE), - BIND_GLOBAL_CONSTANT( PROPERTY_USAGE_STORAGE ), - BIND_GLOBAL_CONSTANT( PROPERTY_USAGE_EDITOR ), - BIND_GLOBAL_CONSTANT( PROPERTY_USAGE_NETWORK ), + BIND_GLOBAL_CONSTANT(PROPERTY_USAGE_DEFAULT), + BIND_GLOBAL_CONSTANT(PROPERTY_USAGE_DEFAULT_INTL), + BIND_GLOBAL_CONSTANT(PROPERTY_USAGE_NOEDITOR), - BIND_GLOBAL_CONSTANT( PROPERTY_USAGE_EDITOR_HELPER ), - BIND_GLOBAL_CONSTANT( PROPERTY_USAGE_CHECKABLE ), - BIND_GLOBAL_CONSTANT( PROPERTY_USAGE_CHECKED ), - BIND_GLOBAL_CONSTANT( PROPERTY_USAGE_INTERNATIONALIZED ), - BIND_GLOBAL_CONSTANT( PROPERTY_USAGE_BUNDLE ), - BIND_GLOBAL_CONSTANT( PROPERTY_USAGE_CATEGORY ), - BIND_GLOBAL_CONSTANT( PROPERTY_USAGE_STORE_IF_NONZERO ), - BIND_GLOBAL_CONSTANT( PROPERTY_USAGE_STORE_IF_NONONE ), - BIND_GLOBAL_CONSTANT( PROPERTY_USAGE_NO_INSTANCE_STATE ), - BIND_GLOBAL_CONSTANT( PROPERTY_USAGE_RESTART_IF_CHANGED ), - BIND_GLOBAL_CONSTANT( PROPERTY_USAGE_SCRIPT_VARIABLE ), + BIND_GLOBAL_CONSTANT(METHOD_FLAG_NORMAL), + BIND_GLOBAL_CONSTANT(METHOD_FLAG_EDITOR), + BIND_GLOBAL_CONSTANT(METHOD_FLAG_NOSCRIPT), + BIND_GLOBAL_CONSTANT(METHOD_FLAG_CONST), + BIND_GLOBAL_CONSTANT(METHOD_FLAG_REVERSE), + BIND_GLOBAL_CONSTANT(METHOD_FLAG_VIRTUAL), + BIND_GLOBAL_CONSTANT(METHOD_FLAG_FROM_SCRIPT), + BIND_GLOBAL_CONSTANT(METHOD_FLAGS_DEFAULT), - BIND_GLOBAL_CONSTANT( PROPERTY_USAGE_DEFAULT ), - BIND_GLOBAL_CONSTANT( PROPERTY_USAGE_DEFAULT_INTL ), - BIND_GLOBAL_CONSTANT( PROPERTY_USAGE_NOEDITOR ), - - BIND_GLOBAL_CONSTANT( METHOD_FLAG_NORMAL ), - BIND_GLOBAL_CONSTANT( METHOD_FLAG_EDITOR ), - BIND_GLOBAL_CONSTANT( METHOD_FLAG_NOSCRIPT ), - BIND_GLOBAL_CONSTANT( METHOD_FLAG_CONST ), - BIND_GLOBAL_CONSTANT( METHOD_FLAG_REVERSE ), - BIND_GLOBAL_CONSTANT( METHOD_FLAG_VIRTUAL ), - BIND_GLOBAL_CONSTANT( METHOD_FLAG_FROM_SCRIPT ), - BIND_GLOBAL_CONSTANT( METHOD_FLAGS_DEFAULT ), - - {"TYPE_NIL",Variant::NIL}, - {"TYPE_BOOL",Variant::BOOL}, - {"TYPE_INT",Variant::INT}, - {"TYPE_REAL",Variant::REAL}, - {"TYPE_STRING",Variant::STRING}, - {"TYPE_VECTOR2",Variant::VECTOR2}, // 5 - {"TYPE_RECT2",Variant::RECT2}, - {"TYPE_VECTOR3",Variant::VECTOR3}, - {"TYPE_MATRIX32",Variant::MATRIX32}, - {"TYPE_PLANE",Variant::PLANE}, - {"TYPE_QUAT",Variant::QUAT}, // 10 - {"TYPE_AABB",Variant::_AABB}, //sorry naming convention fail :( not like it's used often - {"TYPE_MATRIX3",Variant::MATRIX3}, - {"TYPE_TRANSFORM",Variant::TRANSFORM}, - {"TYPE_COLOR",Variant::COLOR}, - {"TYPE_IMAGE",Variant::IMAGE}, // 15 - {"TYPE_NODE_PATH",Variant::NODE_PATH}, - {"TYPE_RID",Variant::_RID}, - {"TYPE_OBJECT",Variant::OBJECT}, - {"TYPE_INPUT_EVENT",Variant::INPUT_EVENT}, - {"TYPE_DICTIONARY",Variant::DICTIONARY}, // 20 - {"TYPE_ARRAY",Variant::ARRAY}, - {"TYPE_RAW_ARRAY",Variant::RAW_ARRAY}, - {"TYPE_INT_ARRAY",Variant::INT_ARRAY}, - {"TYPE_REAL_ARRAY",Variant::REAL_ARRAY}, - {"TYPE_STRING_ARRAY",Variant::STRING_ARRAY}, // 25 - {"TYPE_VECTOR2_ARRAY",Variant::VECTOR2_ARRAY}, - {"TYPE_VECTOR3_ARRAY",Variant::VECTOR3_ARRAY}, - {"TYPE_COLOR_ARRAY",Variant::COLOR_ARRAY}, - {"TYPE_MAX",Variant::VARIANT_MAX}, - {NULL,0} + { "TYPE_NIL", Variant::NIL }, + { "TYPE_BOOL", Variant::BOOL }, + { "TYPE_INT", Variant::INT }, + { "TYPE_REAL", Variant::REAL }, + { "TYPE_STRING", Variant::STRING }, + { "TYPE_VECTOR2", Variant::VECTOR2 }, // 5 + { "TYPE_RECT2", Variant::RECT2 }, + { "TYPE_VECTOR3", Variant::VECTOR3 }, + { "TYPE_MATRIX32", Variant::MATRIX32 }, + { "TYPE_PLANE", Variant::PLANE }, + { "TYPE_QUAT", Variant::QUAT }, // 10 + { "TYPE_AABB", Variant::_AABB }, //sorry naming convention fail :( not like it's used often + { "TYPE_MATRIX3", Variant::MATRIX3 }, + { "TYPE_TRANSFORM", Variant::TRANSFORM }, + { "TYPE_COLOR", Variant::COLOR }, + { "TYPE_IMAGE", Variant::IMAGE }, // 15 + { "TYPE_NODE_PATH", Variant::NODE_PATH }, + { "TYPE_RID", Variant::_RID }, + { "TYPE_OBJECT", Variant::OBJECT }, + { "TYPE_INPUT_EVENT", Variant::INPUT_EVENT }, + { "TYPE_DICTIONARY", Variant::DICTIONARY }, // 20 + { "TYPE_ARRAY", Variant::ARRAY }, + { "TYPE_RAW_ARRAY", Variant::RAW_ARRAY }, + { "TYPE_INT_ARRAY", Variant::INT_ARRAY }, + { "TYPE_REAL_ARRAY", Variant::REAL_ARRAY }, + { "TYPE_STRING_ARRAY", Variant::STRING_ARRAY }, // 25 + { "TYPE_VECTOR2_ARRAY", Variant::VECTOR2_ARRAY }, + { "TYPE_VECTOR3_ARRAY", Variant::VECTOR3_ARRAY }, + { "TYPE_COLOR_ARRAY", Variant::COLOR_ARRAY }, + { "TYPE_MAX", Variant::VARIANT_MAX }, + { NULL, 0 } }; int GlobalConstants::get_global_constant_count() { - int i=0; - while(_global_constants[i].name) + int i = 0; + while (_global_constants[i].name) i++; return i; - } const char *GlobalConstants::get_global_constant_name(int p_idx) { @@ -556,5 +552,3 @@ int GlobalConstants::get_global_constant_value(int p_idx) { return _global_constants[p_idx].value; } - - diff --git a/core/global_constants.h b/core/global_constants.h index 3270dcd151e..8823ebf3b05 100644 --- a/core/global_constants.h +++ b/core/global_constants.h @@ -29,10 +29,8 @@ #ifndef GLOBAL_CONSTANTS_H #define GLOBAL_CONSTANTS_H - class GlobalConstants { public: - static int get_global_constant_count(); static const char *get_global_constant_name(int p_idx); static int get_global_constant_value(int p_idx); diff --git a/core/globals.cpp b/core/globals.cpp index e7a4002621d..c5fe9f4e5f0 100644 --- a/core/globals.cpp +++ b/core/globals.cpp @@ -30,14 +30,14 @@ #include "os/dir_access.h" #include "os/file_access.h" -#include "os/keyboard.h" -#include "io/marshalls.h" #include "bind/core_bind.h" -#include "os/os.h" -#include "io/file_access_pack.h" #include "io/file_access_network.h" +#include "io/file_access_pack.h" +#include "io/marshalls.h" +#include "os/keyboard.h" +#include "os/os.h" -Globals *Globals::singleton=NULL; +Globals *Globals::singleton = NULL; Globals *Globals::get_singleton() { @@ -49,24 +49,23 @@ String Globals::get_resource_path() const { return resource_path; }; -String Globals::localize_path(const String& p_path) const { +String Globals::localize_path(const String &p_path) const { - if (resource_path=="") + if (resource_path == "") return p_path; //not initialied yet if (p_path.begins_with("res://") || p_path.begins_with("user://") || - (p_path.is_abs_path() && !p_path.begins_with(resource_path))) + (p_path.is_abs_path() && !p_path.begins_with(resource_path))) return p_path.simplify_path(); - DirAccess *dir = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); - String path = p_path.replace("\\","/").simplify_path(); + String path = p_path.replace("\\", "/").simplify_path(); - if (dir->change_dir(path)==OK) { + if (dir->change_dir(path) == OK) { String cwd = dir->get_current_dir(); - cwd = cwd.replace("\\","/"); + cwd = cwd.replace("\\", "/"); memdelete(dir); @@ -81,10 +80,9 @@ String Globals::localize_path(const String& p_path) const { int sep = path.find_last("/"); if (sep == -1) { - return "res://"+path; + return "res://" + path; }; - String parent = path.substr(0, sep); String plocal = localize_path(parent); @@ -93,30 +91,27 @@ String Globals::localize_path(const String& p_path) const { }; return plocal + path.substr(sep, path.size() - sep); }; - } -void Globals::set_persisting(const String& p_name, bool p_persist) { +void Globals::set_persisting(const String &p_name, bool p_persist) { ERR_FAIL_COND(!props.has(p_name)); - props[p_name].persist=p_persist; + props[p_name].persist = p_persist; } -bool Globals::is_persisting(const String& p_name) const { +bool Globals::is_persisting(const String &p_name) const { - ERR_FAIL_COND_V(!props.has(p_name),false); + ERR_FAIL_COND_V(!props.has(p_name), false); return props[p_name].persist; - } - -String Globals::globalize_path(const String& p_path) const { +String Globals::globalize_path(const String &p_path) const { if (p_path.begins_with("res://")) { if (resource_path != "") { - return p_path.replace("res:/",resource_path); + return p_path.replace("res:/", resource_path); }; return p_path.replace("res://", ""); }; @@ -124,60 +119,57 @@ String Globals::globalize_path(const String& p_path) const { return p_path; } - -bool Globals::_set(const StringName& p_name, const Variant& p_value) { +bool Globals::_set(const StringName &p_name, const Variant &p_value) { _THREAD_SAFE_METHOD_ - if (p_value.get_type()==Variant::NIL) + if (p_value.get_type() == Variant::NIL) props.erase(p_name); else { if (props.has(p_name)) { if (!props[p_name].overrided) - props[p_name].variant=p_value; + props[p_name].variant = p_value; - if (props[p_name].order>=NO_ORDER_BASE && registering_order) { - props[p_name].order=last_order++; + if (props[p_name].order >= NO_ORDER_BASE && registering_order) { + props[p_name].order = last_order++; } } else { - props[p_name]=VariantContainer(p_value,last_order++ + (registering_order?0:NO_ORDER_BASE)); + props[p_name] = VariantContainer(p_value, last_order++ + (registering_order ? 0 : NO_ORDER_BASE)); } } if (!disable_platform_override) { - String s=String(p_name); + String s = String(p_name); int sl = s.find("/"); int p = s.find("."); - if (p!=-1 && sl!=-1 && p < sl) { + if (p != -1 && sl != -1 && p < sl) { - Vector ps = s.substr(0,sl).split("."); - String prop=s.substr(sl,s.length()-sl); - for(int i=1;i ps = s.substr(0, sl).split("."); + String prop = s.substr(sl, s.length() - sl); + for (int i = 1; i < ps.size(); i++) { - if (ps[i]==OS::get_singleton()->get_name()) { + if (ps[i] == OS::get_singleton()->get_name()) { - String fullprop=ps[0]+prop; + String fullprop = ps[0] + prop; - set(fullprop,p_value); - props[fullprop].overrided=true; + set(fullprop, p_value); + props[fullprop].overrided = true; } } } - } return true; } -bool Globals::_get(const StringName& p_name,Variant &r_ret) const { +bool Globals::_get(const StringName &p_name, Variant &r_ret) const { _THREAD_SAFE_METHOD_ if (!props.has(p_name)) return false; - r_ret=props[p_name].variant; + r_ret = props[p_name].variant; return true; - } struct _VCSort { @@ -187,7 +179,7 @@ struct _VCSort { int order; int flags; - bool operator<(const _VCSort& p_vcs) const{ return order==p_vcs.order?name *p_list) const { @@ -196,134 +188,122 @@ void Globals::_get_property_list(List *p_list) const { Set<_VCSort> vclist; - for(Map::Element *E=props.front();E;E=E->next()) { + for (Map::Element *E = props.front(); E; E = E->next()) { - const VariantContainer *v=&E->get(); + const VariantContainer *v = &E->get(); if (v->hide_from_editor) continue; _VCSort vc; - vc.name=E->key(); - vc.order=v->order; - vc.type=v->variant.get_type(); + vc.name = E->key(); + vc.order = v->order; + vc.type = v->variant.get_type(); if (vc.name.begins_with("input/") || vc.name.begins_with("import/") || vc.name.begins_with("export/") || vc.name.begins_with("/remap") || vc.name.begins_with("/locale") || vc.name.begins_with("/autoload")) - vc.flags=PROPERTY_USAGE_CHECKABLE|PROPERTY_USAGE_STORAGE; + vc.flags = PROPERTY_USAGE_CHECKABLE | PROPERTY_USAGE_STORAGE; else - vc.flags=PROPERTY_USAGE_CHECKABLE|PROPERTY_USAGE_EDITOR|PROPERTY_USAGE_STORAGE; + vc.flags = PROPERTY_USAGE_CHECKABLE | PROPERTY_USAGE_EDITOR | PROPERTY_USAGE_STORAGE; if (v->persist) { - vc.flags|=PROPERTY_USAGE_CHECKED; + vc.flags |= PROPERTY_USAGE_CHECKED; } vclist.insert(vc); } - for(Set<_VCSort>::Element *E=vclist.front();E;E=E->next()) { + for (Set<_VCSort>::Element *E = vclist.front(); E; E = E->next()) { if (custom_prop_info.has(E->get().name)) { - PropertyInfo pi=custom_prop_info[E->get().name]; - pi.name=E->get().name; - pi.usage=E->get().flags; - p_list->push_back( pi ); + PropertyInfo pi = custom_prop_info[E->get().name]; + pi.name = E->get().name; + pi.usage = E->get().flags; + p_list->push_back(pi); } else - p_list->push_back( PropertyInfo(E->get().type, E->get().name,PROPERTY_HINT_NONE,"",E->get().flags) ); + p_list->push_back(PropertyInfo(E->get().type, E->get().name, PROPERTY_HINT_NONE, "", E->get().flags)); } } - - -bool Globals::_load_resource_pack(const String& p_pack) { +bool Globals::_load_resource_pack(const String &p_pack) { if (PackedData::get_singleton()->is_disabled()) return false; - bool ok = PackedData::get_singleton()->add_pack(p_pack)==OK; + bool ok = PackedData::get_singleton()->add_pack(p_pack) == OK; if (!ok) return false; //if data.pck is found, all directory access will be from here DirAccess::make_default(DirAccess::ACCESS_RESOURCES); - using_datapack=true; + using_datapack = true; return true; } -Error Globals::setup(const String& p_path,const String & p_main_pack) { +Error Globals::setup(const String &p_path, const String &p_main_pack) { //an absolute mess of a function, must be cleaned up and reorganized somehow at some point //_load_settings(p_path+"/override.cfg"); - if (p_main_pack!="") { + if (p_main_pack != "") { bool ok = _load_resource_pack(p_main_pack); - ERR_FAIL_COND_V(!ok,ERR_CANT_OPEN); + ERR_FAIL_COND_V(!ok, ERR_CANT_OPEN); - if (_load_settings("res://engine.cfg")==OK || _load_settings_binary("res://engine.cfb")==OK) { + if (_load_settings("res://engine.cfg") == OK || _load_settings_binary("res://engine.cfb") == OK) { _load_settings("res://override.cfg"); - } return OK; - } - if (OS::get_singleton()->get_executable_path()!="") { + if (OS::get_singleton()->get_executable_path() != "") { if (_load_resource_pack(OS::get_singleton()->get_executable_path())) { - if (p_path!="") { - resource_path=p_path; + if (p_path != "") { + resource_path = p_path; } else { DirAccess *d = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); - resource_path=d->get_current_dir(); + resource_path = d->get_current_dir(); memdelete(d); - } - if (_load_settings("res://engine.cfg")==OK || _load_settings_binary("res://engine.cfb")==OK) { + if (_load_settings("res://engine.cfg") == OK || _load_settings_binary("res://engine.cfb") == OK) { _load_settings("res://override.cfg"); - } - - return OK; } - } - if (FileAccessNetworkClient::get_singleton()) { - if (_load_settings("res://engine.cfg")==OK || _load_settings_binary("res://engine.cfb")==OK) { + if (_load_settings("res://engine.cfg") == OK || _load_settings_binary("res://engine.cfb") == OK) { _load_settings("res://override.cfg"); - } return OK; } - if (OS::get_singleton()->get_resource_dir()!="") { - //OS will call Globals->get_resource_path which will be empty if not overriden! + if (OS::get_singleton()->get_resource_dir() != "") { + //OS will call Globals->get_resource_path which will be empty if not overriden! //if the OS would rather use somewhere else, then it will not be empty. - resource_path=OS::get_singleton()->get_resource_dir().replace("\\","/"); - if (resource_path.length() && resource_path[ resource_path.length()-1]=='/') - resource_path=resource_path.substr(0,resource_path.length()-1); // chop end + resource_path = OS::get_singleton()->get_resource_dir().replace("\\", "/"); + if (resource_path.length() && resource_path[resource_path.length() - 1] == '/') + resource_path = resource_path.substr(0, resource_path.length() - 1); // chop end - print_line("has res dir: "+resource_path); + print_line("has res dir: " + resource_path); if (!_load_resource_pack("res://data.pck")) _load_resource_pack("res://data.zip"); // make sure this is load from the resource path - print_line("exists engine cfg? "+itos(FileAccess::exists("/engine.cfg"))); - if (_load_settings("res://engine.cfg")==OK || _load_settings_binary("res://engine.cfb")==OK) { + print_line("exists engine cfg? " + itos(FileAccess::exists("/engine.cfg"))); + if (_load_settings("res://engine.cfg") == OK || _load_settings_binary("res://engine.cfb") == OK) { print_line("loaded engine.cfg"); _load_settings("res://override.cfg"); - } return OK; @@ -342,57 +322,51 @@ Error Globals::setup(const String& p_path,const String & p_main_pack) { String current_dir = d->get_current_dir(); String exec_name = OS::get_singleton()->get_executable_path().get_file().basename(); bool found = false; - bool first_time=true; + bool first_time = true; - while(true) { + while (true) { //try to load settings in ascending through dirs shape! //tries to open pack, but only first time - if (first_time && (_load_resource_pack(current_dir+"/"+exec_name+".pck") || _load_resource_pack(current_dir+"/"+exec_name+".zip") )) { - if (_load_settings("res://engine.cfg")==OK || _load_settings_binary("res://engine.cfb")==OK) { + if (first_time && (_load_resource_pack(current_dir + "/" + exec_name + ".pck") || _load_resource_pack(current_dir + "/" + exec_name + ".zip"))) { + if (_load_settings("res://engine.cfg") == OK || _load_settings_binary("res://engine.cfb") == OK) { _load_settings("res://override.cfg"); - found=true; - - + found = true; } break; - } else if (first_time && (_load_resource_pack(current_dir+"/data.pck") || _load_resource_pack(current_dir+"/data.zip") )) { - if (_load_settings("res://engine.cfg")==OK || _load_settings_binary("res://engine.cfb")==OK) { + } else if (first_time && (_load_resource_pack(current_dir + "/data.pck") || _load_resource_pack(current_dir + "/data.zip"))) { + if (_load_settings("res://engine.cfg") == OK || _load_settings_binary("res://engine.cfb") == OK) { _load_settings("res://override.cfg"); - found=true; - - + found = true; } break; - } else if (_load_settings(current_dir+"/engine.cfg")==OK || _load_settings_binary(current_dir+"/engine.cfb")==OK) { + } else if (_load_settings(current_dir + "/engine.cfg") == OK || _load_settings_binary(current_dir + "/engine.cfb") == OK) { - _load_settings(current_dir+"/override.cfg"); - candidate=current_dir; - found=true; + _load_settings(current_dir + "/override.cfg"); + candidate = current_dir; + found = true; break; } d->change_dir(".."); - if (d->get_current_dir()==current_dir) + if (d->get_current_dir() == current_dir) break; //not doing anything useful - current_dir=d->get_current_dir(); - first_time=false; + current_dir = d->get_current_dir(); + first_time = false; } - - resource_path=candidate; - resource_path = resource_path.replace("\\","/"); // windows path to unix path just in case + resource_path = candidate; + resource_path = resource_path.replace("\\", "/"); // windows path to unix path just in case memdelete(d); if (!found) return ERR_FILE_NOT_FOUND; }; - - if (resource_path.length() && resource_path[ resource_path.length()-1]=='/') - resource_path=resource_path.substr(0,resource_path.length()-1); // chop end + if (resource_path.length() && resource_path[resource_path.length() - 1] == '/') + resource_path = resource_path.substr(0, resource_path.length() - 1); // chop end return OK; } @@ -404,18 +378,17 @@ bool Globals::has(String p_var) const { return props.has(p_var); } -static Vector _decode_params(const String& p_string) { +static Vector _decode_params(const String &p_string) { - int begin=p_string.find("("); - ERR_FAIL_COND_V(begin==-1,Vector()); + int begin = p_string.find("("); + ERR_FAIL_COND_V(begin == -1, Vector()); begin++; - int end=p_string.find(")"); - ERR_FAIL_COND_V(end()); - return p_string.substr(begin,end-begin).split(","); + int end = p_string.find(")"); + ERR_FAIL_COND_V(end < begin, Vector()); + return p_string.substr(begin, end - begin).split(","); } -static String _get_chunk(const String& str,int &pos, int close_pos) { - +static String _get_chunk(const String &str, int &pos, int close_pos) { enum { MIN_COMMA, @@ -427,29 +400,27 @@ static String _get_chunk(const String& str,int &pos, int close_pos) { MIN_OPEN }; - int min_pos=close_pos; - int min_what=MIN_CLOSE; + int min_pos = close_pos; + int min_what = MIN_CLOSE; -#define TEST_MIN(m_how,m_what) \ -{\ -int res = str.find(m_how,pos);\ -if (res!=-1 && res < min_pos) {\ - min_pos=res;\ - min_what=m_what;\ -}\ -}\ +#define TEST_MIN(m_how, m_what) \ + { \ + int res = str.find(m_how, pos); \ + if (res != -1 && res < min_pos) { \ + min_pos = res; \ + min_what = m_what; \ + } \ + } + TEST_MIN(",", MIN_COMMA); + TEST_MIN("[", MIN_OPEN); + TEST_MIN("{", MIN_CURLY_OPEN); + TEST_MIN("(", MIN_PARENTHESIS); + TEST_MIN("\"", MIN_QUOTE); - TEST_MIN(",",MIN_COMMA); - TEST_MIN("[",MIN_OPEN); - TEST_MIN("{",MIN_CURLY_OPEN); - TEST_MIN("(",MIN_PARENTHESIS); - TEST_MIN("\"",MIN_QUOTE); + int end = min_pos; - int end=min_pos; - - - switch(min_what) { + switch (min_what) { case MIN_COMMA: { } break; @@ -457,317 +428,306 @@ if (res!=-1 && res < min_pos) {\ //end because it's done } break; case MIN_QUOTE: { - end=str.find("\"",min_pos+1)+1; - ERR_FAIL_COND_V(end==-1,Variant()); + end = str.find("\"", min_pos + 1) + 1; + ERR_FAIL_COND_V(end == -1, Variant()); } break; case MIN_PARENTHESIS: { - end=str.find(")",min_pos+1)+1; - ERR_FAIL_COND_V(end==-1,Variant()); + end = str.find(")", min_pos + 1) + 1; + ERR_FAIL_COND_V(end == -1, Variant()); } break; case MIN_OPEN: { - int level=1; + int level = 1; end++; - while(end params = _decode_params(p_string); - ERR_FAIL_COND_V(params.size()!=1 && params.size()!=2,Variant()); - int scode=0; + ERR_FAIL_COND_V(params.size() != 1 && params.size() != 2, Variant()); + int scode = 0; if (params[0].is_numeric()) { - scode=params[0].to_int(); - if (scode<10) - scode+=KEY_0; + scode = params[0].to_int(); + if (scode < 10) + scode += KEY_0; } else - scode=find_keycode(params[0]); + scode = find_keycode(params[0]); InputEvent ie; - ie.type=InputEvent::KEY; - ie.key.scancode=scode; + ie.type = InputEvent::KEY; + ie.key.scancode = scode; - if (params.size()==2) { - String mods=params[1]; - if (mods.findn("C")!=-1) - ie.key.mod.control=true; - if (mods.findn("A")!=-1) - ie.key.mod.alt=true; - if (mods.findn("S")!=-1) - ie.key.mod.shift=true; - if (mods.findn("M")!=-1) - ie.key.mod.meta=true; + if (params.size() == 2) { + String mods = params[1]; + if (mods.findn("C") != -1) + ie.key.mod.control = true; + if (mods.findn("A") != -1) + ie.key.mod.alt = true; + if (mods.findn("S") != -1) + ie.key.mod.shift = true; + if (mods.findn("M") != -1) + ie.key.mod.meta = true; } return ie; - } if (str.begins_with("mbutton")) { Vector params = _decode_params(p_string); - ERR_FAIL_COND_V(params.size()!=2,Variant()); + ERR_FAIL_COND_V(params.size() != 2, Variant()); InputEvent ie; - ie.type=InputEvent::MOUSE_BUTTON; - ie.device=params[0].to_int(); - ie.mouse_button.button_index=params[1].to_int(); + ie.type = InputEvent::MOUSE_BUTTON; + ie.device = params[0].to_int(); + ie.mouse_button.button_index = params[1].to_int(); return ie; } if (str.begins_with("jbutton")) { Vector params = _decode_params(p_string); - ERR_FAIL_COND_V(params.size()!=2,Variant()); + ERR_FAIL_COND_V(params.size() != 2, Variant()); InputEvent ie; - ie.type=InputEvent::JOYSTICK_BUTTON; - ie.device=params[0].to_int(); - ie.joy_button.button_index=params[1].to_int(); + ie.type = InputEvent::JOYSTICK_BUTTON; + ie.device = params[0].to_int(); + ie.joy_button.button_index = params[1].to_int(); return ie; } if (str.begins_with("jaxis")) { Vector params = _decode_params(p_string); - ERR_FAIL_COND_V(params.size()!=2,Variant()); + ERR_FAIL_COND_V(params.size() != 2, Variant()); InputEvent ie; - ie.type=InputEvent::JOYSTICK_MOTION; - ie.device=params[0].to_int(); - int axis = params[1].to_int();; - ie.joy_motion.axis=axis>>1; - ie.joy_motion.axis_value=axis&1?1:-1; + ie.type = InputEvent::JOYSTICK_MOTION; + ie.device = params[0].to_int(); + int axis = params[1].to_int(); + ; + ie.joy_motion.axis = axis >> 1; + ie.joy_motion.axis_value = axis & 1 ? 1 : -1; return ie; } if (str.begins_with("img")) { Vector params = _decode_params(p_string); - if (params.size()==0) { + if (params.size() == 0) { return Image(); } - ERR_FAIL_COND_V(params.size()!=5,Image()); + ERR_FAIL_COND_V(params.size() != 5, Image()); - String format=params[0].strip_edges(); + String format = params[0].strip_edges(); Image::Format imgformat; - if (format=="grayscale") { - imgformat=Image::FORMAT_GRAYSCALE; - } else if (format=="intensity") { - imgformat=Image::FORMAT_INTENSITY; - } else if (format=="grayscale_alpha") { - imgformat=Image::FORMAT_GRAYSCALE_ALPHA; - } else if (format=="rgb") { - imgformat=Image::FORMAT_RGB; - } else if (format=="rgba") { - imgformat=Image::FORMAT_RGBA; - } else if (format=="indexed") { - imgformat=Image::FORMAT_INDEXED; - } else if (format=="indexed_alpha") { - imgformat=Image::FORMAT_INDEXED_ALPHA; - } else if (format=="bc1") { - imgformat=Image::FORMAT_BC1; - } else if (format=="bc2") { - imgformat=Image::FORMAT_BC2; - } else if (format=="bc3") { - imgformat=Image::FORMAT_BC3; - } else if (format=="bc4") { - imgformat=Image::FORMAT_BC4; - } else if (format=="bc5") { - imgformat=Image::FORMAT_BC5; - } else if (format=="custom") { - imgformat=Image::FORMAT_CUSTOM; + if (format == "grayscale") { + imgformat = Image::FORMAT_GRAYSCALE; + } else if (format == "intensity") { + imgformat = Image::FORMAT_INTENSITY; + } else if (format == "grayscale_alpha") { + imgformat = Image::FORMAT_GRAYSCALE_ALPHA; + } else if (format == "rgb") { + imgformat = Image::FORMAT_RGB; + } else if (format == "rgba") { + imgformat = Image::FORMAT_RGBA; + } else if (format == "indexed") { + imgformat = Image::FORMAT_INDEXED; + } else if (format == "indexed_alpha") { + imgformat = Image::FORMAT_INDEXED_ALPHA; + } else if (format == "bc1") { + imgformat = Image::FORMAT_BC1; + } else if (format == "bc2") { + imgformat = Image::FORMAT_BC2; + } else if (format == "bc3") { + imgformat = Image::FORMAT_BC3; + } else if (format == "bc4") { + imgformat = Image::FORMAT_BC4; + } else if (format == "bc5") { + imgformat = Image::FORMAT_BC5; + } else if (format == "custom") { + imgformat = Image::FORMAT_CUSTOM; } else { - ERR_FAIL_V( Image() ); + ERR_FAIL_V(Image()); } - int mipmaps=params[1].to_int(); - int w=params[2].to_int(); - int h=params[3].to_int(); + int mipmaps = params[1].to_int(); + int w = params[2].to_int(); + int h = params[3].to_int(); if (w == 0 && h == 0) { //r_v = Image(w, h, imgformat); return Image(); }; - - String data=params[4]; - int datasize=data.length()/2; + String data = params[4]; + int datasize = data.length() / 2; DVector pixels; pixels.resize(datasize); DVector::Write wb = pixels.write(); - const CharType *cptr=data.c_str(); + const CharType *cptr = data.c_str(); - int idx=0; + int idx = 0; uint8_t byte; - while( idx='0' && c<='9') || (c>='A' && c<='F') || (c>='a' && c<='f') ) { + if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f')) { - if (idx&1) { + if (idx & 1) { - byte|=HEX2CHR(c); - wb[idx>>1]=byte; + byte |= HEX2CHR(c); + wb[idx >> 1] = byte; } else { - byte=HEX2CHR(c)<<4; + byte = HEX2CHR(c) << 4; } idx++; } - } wb = DVector::Write(); - return Image(w,h,mipmaps,imgformat,pixels); + return Image(w, h, mipmaps, imgformat, pixels); } - if (str.find(",")!=-1) { //vector2 or vector3 - Vector farr = str.split_floats(",",true); - if (farr.size()==2) { - return Point2(farr[0],farr[1]); + if (str.find(",") != -1) { //vector2 or vector3 + Vector farr = str.split_floats(",", true); + if (farr.size() == 2) { + return Point2(farr[0], farr[1]); } - if (farr.size()==3) { - return Vector3(farr[0],farr[1],farr[2]); + if (farr.size() == 3) { + return Vector3(farr[0], farr[1], farr[2]); } ERR_FAIL_V(Variant()); } - return Variant(); } void Globals::set_registering_order(bool p_enable) { - registering_order=p_enable; + registering_order = p_enable; } Error Globals::_load_settings_binary(const String p_path) { Error err; - FileAccess *f= FileAccess::open(p_path,FileAccess::READ,&err); - if (err!=OK) { + FileAccess *f = FileAccess::open(p_path, FileAccess::READ, &err); + if (err != OK) { return err; } - uint8_t hdr[4]; - f->get_buffer(hdr,4); - if (hdr[0]!='E'|| hdr[1]!='C' || hdr[2]!='F' || hdr[3]!='G') { + f->get_buffer(hdr, 4); + if (hdr[0] != 'E' || hdr[1] != 'C' || hdr[2] != 'F' || hdr[3] != 'G') { memdelete(f); ERR_EXPLAIN("Corrupted header in binary engine.cfb (not ECFG)"); @@ -776,47 +736,44 @@ Error Globals::_load_settings_binary(const String p_path) { set_registering_order(false); - uint32_t count=f->get_32(); + uint32_t count = f->get_32(); - for(int i=0;iget_32(); + uint32_t slen = f->get_32(); CharString cs; - cs.resize(slen+1); - cs[slen]=0; - f->get_buffer((uint8_t*)cs.ptr(),slen); + cs.resize(slen + 1); + cs[slen] = 0; + f->get_buffer((uint8_t *)cs.ptr(), slen); String key; key.parse_utf8(cs.ptr()); - uint32_t vlen=f->get_32(); + uint32_t vlen = f->get_32(); Vector d; d.resize(vlen); - f->get_buffer(d.ptr(),vlen); + f->get_buffer(d.ptr(), vlen); Variant value; - Error err = decode_variant(value,d.ptr(),d.size()); - ERR_EXPLAIN("Error decoding property: "+key); - ERR_CONTINUE(err!=OK); - set(key,value); - set_persisting(key,true); + Error err = decode_variant(value, d.ptr(), d.size()); + ERR_EXPLAIN("Error decoding property: " + key); + ERR_CONTINUE(err != OK); + set(key, value); + set_persisting(key, true); } set_registering_order(true); - return OK; } Error Globals::_load_settings(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 (err!=OK) { + if (err != OK) { return err; } - String line; String section; String subpath; @@ -825,73 +782,69 @@ Error Globals::_load_settings(const String p_path) { int line_count = 0; - while(!f->eof_reached()) { + while (!f->eof_reached()) { String line = f->get_line().strip_edges(); line_count++; - if (line=="") + if (line == "") continue; // find comments - { + { - int pos=0; + int pos = 0; while (true) { - int ret = line.find(";",pos); - if (ret==-1) + int ret = line.find(";", pos); + if (ret == -1) break; - int qc=0; - for(int i=0;i 0) { - ERR_PRINT(String("Syntax error on line "+itos(line_count)+" of file "+p_path).ascii().get_data()); + ERR_PRINT(String("Syntax error on line " + itos(line_count) + " of file " + p_path).ascii().get_data()); }; }; } @@ -903,13 +856,13 @@ Error Globals::_load_settings(const String p_path) { return OK; } -static String _encode_variant(const Variant& p_variant) { +static String _encode_variant(const Variant &p_variant) { - switch(p_variant.get_type()) { + switch (p_variant.get_type()) { case Variant::BOOL: { bool val = p_variant; - return (val?"true":"false"); + return (val ? "true" : "false"); } break; case Variant::INT: { int val = p_variant; @@ -917,138 +870,136 @@ static String _encode_variant(const Variant& p_variant) { } break; case Variant::REAL: { float val = p_variant; - return rtos(val)+(val==int(val)?".0":""); + return rtos(val) + (val == int(val) ? ".0" : ""); } break; case Variant::VECTOR2: { Vector2 val = p_variant; - return String("Vector2(")+rtos(val.x)+String(", ")+rtos(val.y)+String(")"); + return String("Vector2(") + rtos(val.x) + String(", ") + rtos(val.y) + String(")"); } break; case Variant::VECTOR3: { Vector3 val = p_variant; - return String("Vector3(")+rtos(val.x)+ String(", ") +rtos(val.y)+ String(", ") +rtos(val.z)+String(")"); + return String("Vector3(") + rtos(val.x) + String(", ") + rtos(val.y) + String(", ") + rtos(val.z) + String(")"); } break; case Variant::STRING: { String val = p_variant; - return "\""+val.xml_escape()+"\""; + return "\"" + val.xml_escape() + "\""; } break; case Variant::COLOR: { Color val = p_variant; - return "#"+val.to_html(); + return "#" + val.to_html(); } break; case Variant::STRING_ARRAY: case Variant::INT_ARRAY: case Variant::REAL_ARRAY: case Variant::ARRAY: { Array arr = p_variant; - String str="["; - for(int i=0;i0) - str+=", "; - str+=_encode_variant(arr[i]); + if (i > 0) + str += ", "; + str += _encode_variant(arr[i]); } - str+="]"; + str += "]"; return str; } break; case Variant::DICTIONARY: { Dictionary d = p_variant; - String str="{"; + String str = "{"; List keys; d.get_key_list(&keys); - for(List::Element *E=keys.front();E;E=E->next()) { - - if (E!=keys.front()) - str+=", "; - str+=_encode_variant(E->get()); - str+=":"; - str+=_encode_variant(d[E->get()]); + for (List::Element *E = keys.front(); E; E = E->next()) { + if (E != keys.front()) + str += ", "; + str += _encode_variant(E->get()); + str += ":"; + str += _encode_variant(d[E->get()]); } - str+="}"; + str += "}"; return str; } break; case Variant::IMAGE: { - String str="img("; + String str = "img("; - Image img=p_variant; + Image img = p_variant; if (!img.empty()) { String format; - switch(img.get_format()) { + switch (img.get_format()) { - case Image::FORMAT_GRAYSCALE: format="grayscale"; break; - case Image::FORMAT_INTENSITY: format="intensity"; break; - case Image::FORMAT_GRAYSCALE_ALPHA: format="grayscale_alpha"; break; - case Image::FORMAT_RGB: format="rgb"; break; - case Image::FORMAT_RGBA: format="rgba"; break; - case Image::FORMAT_INDEXED : format="indexed"; break; - case Image::FORMAT_INDEXED_ALPHA: format="indexed_alpha"; break; - case Image::FORMAT_BC1: format="bc1"; break; - case Image::FORMAT_BC2: format="bc2"; break; - case Image::FORMAT_BC3: format="bc3"; break; - case Image::FORMAT_BC4: format="bc4"; break; - case Image::FORMAT_BC5: format="bc5"; break; - case Image::FORMAT_CUSTOM: format="custom custom_size="+itos(img.get_data().size())+""; break; + case Image::FORMAT_GRAYSCALE: format = "grayscale"; break; + case Image::FORMAT_INTENSITY: format = "intensity"; break; + case Image::FORMAT_GRAYSCALE_ALPHA: format = "grayscale_alpha"; break; + case Image::FORMAT_RGB: format = "rgb"; break; + case Image::FORMAT_RGBA: format = "rgba"; break; + case Image::FORMAT_INDEXED: format = "indexed"; break; + case Image::FORMAT_INDEXED_ALPHA: format = "indexed_alpha"; break; + case Image::FORMAT_BC1: format = "bc1"; break; + case Image::FORMAT_BC2: format = "bc2"; break; + case Image::FORMAT_BC3: format = "bc3"; break; + case Image::FORMAT_BC4: format = "bc4"; break; + case Image::FORMAT_BC5: format = "bc5"; break; + case Image::FORMAT_CUSTOM: format = "custom custom_size=" + itos(img.get_data().size()) + ""; break; default: {} } - str+=format+", "; - str+=itos(img.get_mipmaps())+", "; - str+=itos(img.get_width())+", "; - str+=itos(img.get_height())+", "; + str += format + ", "; + str += itos(img.get_mipmaps()) + ", "; + str += itos(img.get_width()) + ", "; + str += itos(img.get_height()) + ", "; DVector data = img.get_data(); - int ds=data.size(); + int ds = data.size(); DVector::Read r = data.read(); - for(int i=0;i>4], hex[byte&0xF], 0}; - str+=bstr; + const char hex[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; + char bstr[3] = { hex[byte >> 4], hex[byte & 0xF], 0 }; + str += bstr; } } - str+=")"; + str += ")"; return str; } break; case Variant::INPUT_EVENT: { InputEvent ev = p_variant; - switch(ev.type) { + switch (ev.type) { case InputEvent::KEY: { String mods; if (ev.key.mod.control) - mods+="C"; + mods += "C"; if (ev.key.mod.shift) - mods+="S"; + mods += "S"; if (ev.key.mod.alt) - mods+="A"; + mods += "A"; if (ev.key.mod.meta) - mods+="M"; - if (mods!="") - mods=", "+mods; + mods += "M"; + if (mods != "") + mods = ", " + mods; - return "key("+keycode_get_string(ev.key.scancode)+mods+")"; + return "key(" + keycode_get_string(ev.key.scancode) + mods + ")"; } break; case InputEvent::MOUSE_BUTTON: { - return "mbutton("+itos(ev.device)+", "+itos(ev.mouse_button.button_index)+")"; + return "mbutton(" + itos(ev.device) + ", " + itos(ev.mouse_button.button_index) + ")"; } break; case InputEvent::JOYSTICK_BUTTON: { - return "jbutton("+itos(ev.device)+", "+itos(ev.joy_button.button_index)+")"; + return "jbutton(" + itos(ev.device) + ", " + itos(ev.joy_button.button_index) + ")"; } break; case InputEvent::JOYSTICK_MOTION: { - return "jaxis("+itos(ev.device)+", "+itos(ev.joy_motion.axis * 2 + (ev.joy_motion.axis_value<0?0:1))+")"; + return "jaxis(" + itos(ev.device) + ", " + itos(ev.joy_motion.axis * 2 + (ev.joy_motion.axis_value < 0 ? 0 : 1)) + ")"; } break; default: { return "nil"; } break; - } } break; default: {} @@ -1057,21 +1008,19 @@ static String _encode_variant(const Variant& p_variant) { return "nil"; //don't know wha to do with this } +int Globals::get_order(const String &p_name) const { -int Globals::get_order(const String& p_name) const { - - ERR_FAIL_COND_V(!props.has(p_name),-1); + ERR_FAIL_COND_V(!props.has(p_name), -1); return props[p_name].order; } - -void Globals::set_order(const String& p_name, int p_order){ +void Globals::set_order(const String &p_name, int p_order) { ERR_FAIL_COND(!props.has(p_name)); - props[p_name].order=p_order; + props[p_name].order = p_order; } -void Globals::clear(const String& p_name) { +void Globals::clear(const String &p_name) { ERR_FAIL_COND(!props.has(p_name)); props.erase(p_name); @@ -1079,28 +1028,27 @@ void Globals::clear(const String& p_name) { Error Globals::save() { - return save_custom(get_resource_path()+"/engine.cfg"); + return save_custom(get_resource_path() + "/engine.cfg"); } -Error Globals::_save_settings_binary(const String& p_file,const Map > &props,const CustomMap& p_custom) { - +Error Globals::_save_settings_binary(const String &p_file, const Map > &props, const CustomMap &p_custom) { Error err; - FileAccess *file = FileAccess::open(p_file,FileAccess::WRITE,&err); - if (err!=OK) { + FileAccess *file = FileAccess::open(p_file, FileAccess::WRITE, &err); + if (err != OK) { - ERR_EXPLAIN("Coudln't save engine.cfb at "+p_file); - ERR_FAIL_COND_V(err,err) + ERR_EXPLAIN("Coudln't save engine.cfb at " + p_file); + ERR_FAIL_COND_V(err, err) } - uint8_t hdr[4]={'E','C','F','G'}; - file->store_buffer(hdr,4); + uint8_t hdr[4] = { 'E', 'C', 'F', 'G' }; + file->store_buffer(hdr, 4); - int count=0; + int count = 0; - for(Map >::Element *E=props.front();E;E=E->next()) { + for (Map >::Element *E = props.front(); E; E = E->next()) { - for(List::Element *F=E->get().front();F;F=F->next()) { + for (List::Element *F = E->get().front(); F; F = F->next()) { count++; } @@ -1108,17 +1056,16 @@ Error Globals::_save_settings_binary(const String& p_file,const Mapstore_32(count); //store how many properties are saved + for (Map >::Element *E = props.front(); E; E = E->next()) { - for(Map >::Element *E=props.front();E;E=E->next()) { - - for(List::Element *F=E->get().front();F;F=F->next()) { + for (List::Element *F = E->get().front(); F; F = F->next()) { String key = F->get(); - if (E->key()!="") - key=E->key()+"/"+key; + if (E->key() != "") + key = E->key() + "/" + key; Variant value; if (p_custom.has(key)) - value=p_custom[key]; + value = p_custom[key]; else value = get(key); @@ -1126,61 +1073,58 @@ Error Globals::_save_settings_binary(const String& p_file,const Mapstore_string(key); int len; - Error err = encode_variant(value,NULL,len); - if (err!=OK) + Error err = encode_variant(value, NULL, len); + if (err != OK) memdelete(file); - ERR_FAIL_COND_V( err != OK, ERR_INVALID_DATA ); + ERR_FAIL_COND_V(err != OK, ERR_INVALID_DATA); Vector buff; buff.resize(len); - err = encode_variant(value,&buff[0],len); - if (err!=OK) + err = encode_variant(value, &buff[0], len); + if (err != OK) memdelete(file); - ERR_FAIL_COND_V( err != OK, ERR_INVALID_DATA ); + ERR_FAIL_COND_V(err != OK, ERR_INVALID_DATA); file->store_32(len); - file->store_buffer(buff.ptr(),buff.size()); + file->store_buffer(buff.ptr(), buff.size()); } } file->close(); memdelete(file); - return OK; } - -Error Globals::_save_settings_text(const String& p_file,const Map > &props,const CustomMap& p_custom) { +Error Globals::_save_settings_text(const String &p_file, const Map > &props, const CustomMap &p_custom) { Error err; - FileAccess *file = FileAccess::open(p_file,FileAccess::WRITE,&err); + FileAccess *file = FileAccess::open(p_file, FileAccess::WRITE, &err); if (err) { - ERR_EXPLAIN("Coudln't save engine.cfg - "+p_file); - ERR_FAIL_COND_V(err,err) + ERR_EXPLAIN("Coudln't save engine.cfg - " + p_file); + ERR_FAIL_COND_V(err, err) } - for(Map >::Element *E=props.front();E;E=E->next()) { + for (Map >::Element *E = props.front(); E; E = E->next()) { - if (E!=props.front()) + if (E != props.front()) file->store_string("\n"); - if (E->key()!="") - file->store_string("["+E->key()+"]\n\n"); - for(List::Element *F=E->get().front();F;F=F->next()) { + if (E->key() != "") + file->store_string("[" + E->key() + "]\n\n"); + for (List::Element *F = E->get().front(); F; F = F->next()) { String key = F->get(); - if (E->key()!="") - key=E->key()+"/"+key; + if (E->key() != "") + key = E->key() + "/" + key; Variant value; if (p_custom.has(key)) - value=p_custom[key]; + value = p_custom[key]; else value = get(key); - file->store_string(F->get()+"="+_encode_variant(value)+"\n"); - + file->store_string(F->get() + "=" + _encode_variant(value) + "\n"); } } @@ -1195,15 +1139,15 @@ Error Globals::_save_custom_bnd(const String &p_file) { // add other params as d return save_custom(p_file); }; -Error Globals::save_custom(const String& p_path,const CustomMap& p_custom,const Set& p_ignore_masks) { +Error Globals::save_custom(const String &p_path, const CustomMap &p_custom, const Set &p_ignore_masks) { - ERR_FAIL_COND_V(p_path=="",ERR_INVALID_PARAMETER); + ERR_FAIL_COND_V(p_path == "", ERR_INVALID_PARAMETER); Set<_VCSort> vclist; - for(Map::Element *G=props.front();G;G=G->next()) { + for (Map::Element *G = props.front(); G; G = G->next()) { - const VariantContainer *v=&G->get(); + const VariantContainer *v = &G->get(); if (v->hide_from_editor) continue; @@ -1211,12 +1155,12 @@ Error Globals::save_custom(const String& p_path,const CustomMap& p_custom,const if (p_custom.has(G->key())) continue; - bool discard=false; + bool discard = false; - for(const Set::Element *E=p_ignore_masks.front();E;E=E->next()) { + for (const Set::Element *E = p_ignore_masks.front(); E; E = E->next()) { - if ( String(G->key()).match(E->get())) { - discard=true; + if (String(G->key()).match(E->get())) { + discard = true; break; } } @@ -1225,57 +1169,53 @@ Error Globals::save_custom(const String& p_path,const CustomMap& p_custom,const continue; _VCSort vc; - vc.name=G->key();//*k; - vc.order=v->order; - vc.type=v->variant.get_type(); - vc.flags=PROPERTY_USAGE_CHECKABLE|PROPERTY_USAGE_EDITOR|PROPERTY_USAGE_STORAGE; + vc.name = G->key(); //*k; + vc.order = v->order; + vc.type = v->variant.get_type(); + vc.flags = PROPERTY_USAGE_CHECKABLE | PROPERTY_USAGE_EDITOR | PROPERTY_USAGE_STORAGE; if (!v->persist) continue; - vclist.insert(vc); } - for(const Map::Element *E=p_custom.front();E;E=E->next()) { - + for (const Map::Element *E = p_custom.front(); E; E = E->next()) { _VCSort vc; - vc.name=E->key(); - vc.order=0xFFFFFFF; - vc.type=E->get().get_type(); - vc.flags=PROPERTY_USAGE_STORAGE; + vc.name = E->key(); + vc.order = 0xFFFFFFF; + vc.type = E->get().get_type(); + vc.flags = PROPERTY_USAGE_STORAGE; vclist.insert(vc); } - Map > props; + Map > props; - for(Set<_VCSort>::Element *E=vclist.front();E;E=E->next()) { + for (Set<_VCSort>::Element *E = vclist.front(); E; E = E->next()) { String category = E->get().name; String name = E->get().name; int div = category.find("/"); - if (div<0) - category=""; + if (div < 0) + category = ""; else { - category=category.substr(0,div); - name=name.substr(div+1,name.size()); + category = category.substr(0, div); + name = name.substr(div + 1, name.size()); } props[category].push_back(name); } - - if (p_path.ends_with(".cfg")) - return _save_settings_text(p_path,props,p_custom); + return _save_settings_text(p_path, props, p_custom); else if (p_path.ends_with(".cfb")) - return _save_settings_binary(p_path,props,p_custom); + return _save_settings_binary(p_path, props, p_custom); else { - ERR_EXPLAIN("Unknown config file format: "+p_path); - ERR_FAIL_V( ERR_FILE_UNRECOGNIZED ); + ERR_EXPLAIN("Unknown config file format: " + p_path); + ERR_FAIL_V(ERR_FILE_UNRECOGNIZED); } return OK; @@ -1321,13 +1261,12 @@ Error Globals::save_custom(const String& p_path,const CustomMap& p_custom,const #endif } -Variant _GLOBAL_DEF( const String& p_var, const Variant& p_default) { +Variant _GLOBAL_DEF(const String &p_var, const Variant &p_default) { if (Globals::get_singleton()->has(p_var)) return Globals::get_singleton()->get(p_var); - Globals::get_singleton()->set(p_var,p_default); + Globals::get_singleton()->set(p_var, p_default); return p_default; - } void Globals::add_singleton(const Singleton &p_singleton) { @@ -1335,9 +1274,9 @@ void Globals::add_singleton(const Singleton &p_singleton) { singletons.push_back(p_singleton); } -Object* Globals::get_singleton_object(const String& p_name) const { +Object *Globals::get_singleton_object(const String &p_name) const { - for(const List::Element *E=singletons.front();E;E=E->next()) { + for (const List::Element *E = singletons.front(); E; E = E->next()) { if (E->get().name == p_name) { return E->get().ptr; }; @@ -1346,14 +1285,14 @@ Object* Globals::get_singleton_object(const String& p_name) const { return NULL; }; -bool Globals::has_singleton(const String& p_name) const { +bool Globals::has_singleton(const String &p_name) const { return get_singleton_object(p_name) != NULL; }; void Globals::get_singletons(List *p_singletons) { - for(List::Element *E=singletons.front();E;E=E->next()) + for (List::Element *E = singletons.front(); E; E = E->next()) p_singletons->push_back(E->get()); } @@ -1363,20 +1302,19 @@ Vector Globals::get_optimizer_presets() const { Globals::get_singleton()->get_property_list(&pi); Vector names; - for (List::Element *E=pi.front();E;E=E->next()) { + for (List::Element *E = pi.front(); E; E = E->next()) { if (!E->get().name.begins_with("optimizer_presets/")) continue; - names.push_back(E->get().name.get_slicec('/',1)); + names.push_back(E->get().name.get_slicec('/', 1)); } names.sort(); return names; - } -void Globals::_add_property_info_bind(const Dictionary& p_info) { +void Globals::_add_property_info_bind(const Dictionary &p_info) { ERR_FAIL_COND(!p_info.has("name")); ERR_FAIL_COND(!p_info.has("type")); @@ -1395,16 +1333,15 @@ void Globals::_add_property_info_bind(const Dictionary& p_info) { set_custom_property_info(pinfo.name, pinfo); } -void Globals::set_custom_property_info(const String& p_prop,const PropertyInfo& p_info) { +void Globals::set_custom_property_info(const String &p_prop, const PropertyInfo &p_info) { ERR_FAIL_COND(!props.has(p_prop)); - custom_prop_info[p_prop]=p_info; - + custom_prop_info[p_prop] = p_info; } void Globals::set_disable_platform_override(bool p_disable) { - disable_platform_override=p_disable; + disable_platform_override = p_disable; } bool Globals::is_using_datapack() const { @@ -1414,149 +1351,139 @@ bool Globals::is_using_datapack() const { void Globals::_bind_methods() { - ObjectTypeDB::bind_method(_MD("has","name"),&Globals::has); - ObjectTypeDB::bind_method(_MD("set_order","name","pos"),&Globals::set_order); - ObjectTypeDB::bind_method(_MD("get_order","name"),&Globals::get_order); - ObjectTypeDB::bind_method(_MD("set_persisting","name","enable"),&Globals::set_persisting); - ObjectTypeDB::bind_method(_MD("is_persisting","name"),&Globals::is_persisting); - ObjectTypeDB::bind_method(_MD("add_property_info", "hint"),&Globals::_add_property_info_bind); - ObjectTypeDB::bind_method(_MD("clear","name"),&Globals::clear); - ObjectTypeDB::bind_method(_MD("localize_path","path"),&Globals::localize_path); - ObjectTypeDB::bind_method(_MD("globalize_path","path"),&Globals::globalize_path); - ObjectTypeDB::bind_method(_MD("save"),&Globals::save); - ObjectTypeDB::bind_method(_MD("has_singleton","name"),&Globals::has_singleton); - ObjectTypeDB::bind_method(_MD("get_singleton","name"),&Globals::get_singleton_object); - ObjectTypeDB::bind_method(_MD("load_resource_pack","pack"),&Globals::_load_resource_pack); - - ObjectTypeDB::bind_method(_MD("save_custom","file"),&Globals::_save_custom_bnd); + ObjectTypeDB::bind_method(_MD("has", "name"), &Globals::has); + ObjectTypeDB::bind_method(_MD("set_order", "name", "pos"), &Globals::set_order); + ObjectTypeDB::bind_method(_MD("get_order", "name"), &Globals::get_order); + ObjectTypeDB::bind_method(_MD("set_persisting", "name", "enable"), &Globals::set_persisting); + ObjectTypeDB::bind_method(_MD("is_persisting", "name"), &Globals::is_persisting); + ObjectTypeDB::bind_method(_MD("add_property_info", "hint"), &Globals::_add_property_info_bind); + ObjectTypeDB::bind_method(_MD("clear", "name"), &Globals::clear); + ObjectTypeDB::bind_method(_MD("localize_path", "path"), &Globals::localize_path); + ObjectTypeDB::bind_method(_MD("globalize_path", "path"), &Globals::globalize_path); + ObjectTypeDB::bind_method(_MD("save"), &Globals::save); + ObjectTypeDB::bind_method(_MD("has_singleton", "name"), &Globals::has_singleton); + ObjectTypeDB::bind_method(_MD("get_singleton", "name"), &Globals::get_singleton_object); + ObjectTypeDB::bind_method(_MD("load_resource_pack", "pack"), &Globals::_load_resource_pack); + ObjectTypeDB::bind_method(_MD("save_custom", "file"), &Globals::_save_custom_bnd); } Globals::Globals() { - - singleton=this; - last_order=0; - disable_platform_override=false; - registering_order=true; - + singleton = this; + last_order = 0; + disable_platform_override = false; + registering_order = true; Array va; InputEvent key; - key.type=InputEvent::KEY; + key.type = InputEvent::KEY; InputEvent joyb; - joyb.type=InputEvent::JOYSTICK_BUTTON; + joyb.type = InputEvent::JOYSTICK_BUTTON; + set("application/name", ""); + set("application/main_scene", ""); + custom_prop_info["application/main_scene"] = PropertyInfo(Variant::STRING, "application/main_scene", PROPERTY_HINT_FILE, "tscn,scn,xscn,xml,res"); + set("application/disable_stdout", false); + set("application/use_shared_user_dir", true); - set("application/name","" ); - set("application/main_scene",""); - custom_prop_info["application/main_scene"]=PropertyInfo(Variant::STRING,"application/main_scene",PROPERTY_HINT_FILE,"tscn,scn,xscn,xml,res"); - set("application/disable_stdout",false); - set("application/use_shared_user_dir",true); - - - key.key.scancode=KEY_RETURN; + key.key.scancode = KEY_RETURN; va.push_back(key); - key.key.scancode=KEY_ENTER; + key.key.scancode = KEY_ENTER; va.push_back(key); - key.key.scancode=KEY_SPACE; + key.key.scancode = KEY_SPACE; va.push_back(key); - joyb.joy_button.button_index=JOY_BUTTON_0; + joyb.joy_button.button_index = JOY_BUTTON_0; va.push_back(joyb); - set("input/ui_accept",va); + set("input/ui_accept", va); input_presets.push_back("input/ui_accept"); - va=Array(); - key.key.scancode=KEY_SPACE; + va = Array(); + key.key.scancode = KEY_SPACE; va.push_back(key); - joyb.joy_button.button_index=JOY_BUTTON_3; + joyb.joy_button.button_index = JOY_BUTTON_3; va.push_back(joyb); - set("input/ui_select",va); + set("input/ui_select", va); input_presets.push_back("input/ui_select"); - va=Array(); - key.key.scancode=KEY_ESCAPE; + va = Array(); + key.key.scancode = KEY_ESCAPE; va.push_back(key); - joyb.joy_button.button_index=JOY_BUTTON_1; + joyb.joy_button.button_index = JOY_BUTTON_1; va.push_back(joyb); - set("input/ui_cancel",va); + set("input/ui_cancel", va); input_presets.push_back("input/ui_cancel"); - va=Array(); - key.key.scancode=KEY_TAB; + va = Array(); + key.key.scancode = KEY_TAB; va.push_back(key); - set("input/ui_focus_next",va); + set("input/ui_focus_next", va); input_presets.push_back("input/ui_focus_next"); - va=Array(); - key.key.scancode=KEY_TAB; - key.key.mod.shift=true; + va = Array(); + key.key.scancode = KEY_TAB; + key.key.mod.shift = true; va.push_back(key); - set("input/ui_focus_prev",va); + set("input/ui_focus_prev", va); input_presets.push_back("input/ui_focus_prev"); - key.key.mod.shift=false; + key.key.mod.shift = false; - va=Array(); - key.key.scancode=KEY_LEFT; + va = Array(); + key.key.scancode = KEY_LEFT; va.push_back(key); - joyb.joy_button.button_index=JOY_DPAD_LEFT; + joyb.joy_button.button_index = JOY_DPAD_LEFT; va.push_back(joyb); - set("input/ui_left",va); + set("input/ui_left", va); input_presets.push_back("input/ui_left"); - va=Array(); - key.key.scancode=KEY_RIGHT; + va = Array(); + key.key.scancode = KEY_RIGHT; va.push_back(key); - joyb.joy_button.button_index=JOY_DPAD_RIGHT; + joyb.joy_button.button_index = JOY_DPAD_RIGHT; va.push_back(joyb); - set("input/ui_right",va); + set("input/ui_right", va); input_presets.push_back("input/ui_right"); - va=Array(); - key.key.scancode=KEY_UP; + va = Array(); + key.key.scancode = KEY_UP; va.push_back(key); - joyb.joy_button.button_index=JOY_DPAD_UP; + joyb.joy_button.button_index = JOY_DPAD_UP; va.push_back(joyb); - set("input/ui_up",va); + set("input/ui_up", va); input_presets.push_back("input/ui_up"); - va=Array(); - key.key.scancode=KEY_DOWN; + va = Array(); + key.key.scancode = KEY_DOWN; va.push_back(key); - joyb.joy_button.button_index=JOY_DPAD_DOWN; + joyb.joy_button.button_index = JOY_DPAD_DOWN; va.push_back(joyb); - set("input/ui_down",va); + set("input/ui_down", va); input_presets.push_back("input/ui_down"); - - va=Array(); - key.key.scancode=KEY_PAGEUP; + va = Array(); + key.key.scancode = KEY_PAGEUP; va.push_back(key); - set("input/ui_page_up",va); + set("input/ui_page_up", va); input_presets.push_back("input/ui_page_up"); - va=Array(); - key.key.scancode=KEY_PAGEDOWN; + va = Array(); + key.key.scancode = KEY_PAGEDOWN; va.push_back(key); - set("input/ui_page_down",va); + set("input/ui_page_down", va); input_presets.push_back("input/ui_page_down"); -// set("display/orientation", "landscape"); + // set("display/orientation", "landscape"); + custom_prop_info["display/orientation"] = PropertyInfo(Variant::STRING, "display/orientation", PROPERTY_HINT_ENUM, "landscape,portrait,reverse_landscape,reverse_portrait,sensor_landscape,sensor_portrait,sensor"); + custom_prop_info["render/mipmap_policy"] = PropertyInfo(Variant::INT, "render/mipmap_policy", PROPERTY_HINT_ENUM, "Allow,Allow For Po2,Disallow"); + custom_prop_info["render/thread_model"] = PropertyInfo(Variant::INT, "render/thread_model", PROPERTY_HINT_ENUM, "Single-Unsafe,Single-Safe,Multi-Threaded"); + custom_prop_info["physics_2d/thread_model"] = PropertyInfo(Variant::INT, "physics_2d/thread_model", PROPERTY_HINT_ENUM, "Single-Unsafe,Single-Safe,Multi-Threaded"); - custom_prop_info["display/orientation"]=PropertyInfo(Variant::STRING,"display/orientation",PROPERTY_HINT_ENUM,"landscape,portrait,reverse_landscape,reverse_portrait,sensor_landscape,sensor_portrait,sensor"); - custom_prop_info["render/mipmap_policy"]=PropertyInfo(Variant::INT,"render/mipmap_policy",PROPERTY_HINT_ENUM,"Allow,Allow For Po2,Disallow"); - custom_prop_info["render/thread_model"]=PropertyInfo(Variant::INT,"render/thread_model",PROPERTY_HINT_ENUM,"Single-Unsafe,Single-Safe,Multi-Threaded"); - custom_prop_info["physics_2d/thread_model"]=PropertyInfo(Variant::INT,"physics_2d/thread_model",PROPERTY_HINT_ENUM,"Single-Unsafe,Single-Safe,Multi-Threaded"); - - set("debug/profiler_max_functions",16384); - using_datapack=false; + set("debug/profiler_max_functions", 16384); + using_datapack = false; } - Globals::~Globals() { - singleton=NULL; + singleton = NULL; } - - diff --git a/core/globals.h b/core/globals.h index cfff3fc745b..1056ac5724b 100644 --- a/core/globals.h +++ b/core/globals.h @@ -30,32 +30,32 @@ #define GLOBALS_H #include "object.h" -#include "set.h" #include "os/thread_safe.h" +#include "set.h" /** @author Juan Linietsky */ - class Globals : public Object { - OBJ_TYPE( Globals, Object ); + OBJ_TYPE(Globals, Object); _THREAD_SAFE_CLASS_ public: - - typedef Map CustomMap; + typedef Map CustomMap; struct Singleton { StringName name; Object *ptr; - Singleton(const StringName& p_name=StringName(), Object *p_ptr=NULL) { name=p_name; ptr=p_ptr; } + Singleton(const StringName &p_name = StringName(), Object *p_ptr = NULL) { + name = p_name; + ptr = p_ptr; + } }; protected: - enum { - NO_ORDER_BASE=1<<18 + NO_ORDER_BASE = 1 << 18 }; struct VariantContainer { @@ -64,22 +64,32 @@ protected: Variant variant; bool hide_from_editor; bool overrided; - VariantContainer(){ order=0; hide_from_editor=false; persist=false; overrided=false; } - VariantContainer(const Variant& p_variant, int p_order, bool p_persist=false) { variant=p_variant; order=p_order; hide_from_editor=false; persist=p_persist; overrided=false; } + VariantContainer() { + order = 0; + hide_from_editor = false; + persist = false; + overrided = false; + } + VariantContainer(const Variant &p_variant, int p_order, bool p_persist = false) { + variant = p_variant; + order = p_order; + hide_from_editor = false; + persist = p_persist; + overrided = false; + } }; bool registering_order; int last_order; - Map props; + Map props; String resource_path; - Map custom_prop_info; + Map custom_prop_info; bool disable_platform_override; bool using_datapack; List input_presets; - - bool _set(const StringName& p_name, const Variant& p_value); - bool _get(const StringName& p_name,Variant &r_ret) const; + bool _set(const StringName &p_name, const Variant &p_value); + bool _get(const StringName &p_name, Variant &r_ret) const; void _get_property_list(List *p_list) const; static Globals *singleton; @@ -87,55 +97,53 @@ protected: Error _load_settings(const String p_path); Error _load_settings_binary(const String p_path); - Error _save_settings_text(const String& p_file,const Map > &props,const CustomMap& p_custom=CustomMap()); - Error _save_settings_binary(const String& p_file,const Map > &props,const CustomMap& p_custom=CustomMap()); + Error _save_settings_text(const String &p_file, const Map > &props, const CustomMap &p_custom = CustomMap()); + Error _save_settings_binary(const String &p_file, const Map > &props, const CustomMap &p_custom = CustomMap()); List singletons; - Error _save_custom_bnd(const String& p_file); + Error _save_custom_bnd(const String &p_file); - bool _load_resource_pack(const String& p_pack); + bool _load_resource_pack(const String &p_pack); - void _add_property_info_bind(const Dictionary& p_info); + void _add_property_info_bind(const Dictionary &p_info); protected: - static void _bind_methods(); + public: - - bool has(String p_var) const; - String localize_path(const String& p_path) const; - String globalize_path(const String& p_path) const; + String localize_path(const String &p_path) const; + String globalize_path(const String &p_path) const; - void set_persisting(const String& p_name, bool p_persist); - bool is_persisting(const String& p_name) const; + void set_persisting(const String &p_name, bool p_persist); + bool is_persisting(const String &p_name) const; String get_resource_path() const; static Globals *get_singleton(); - void clear(const String& p_name); - int get_order(const String& p_name) const; - void set_order(const String& p_name, int p_order); + void clear(const String &p_name); + int get_order(const String &p_name) const; + void set_order(const String &p_name, int p_order); - Error setup(const String& p_path, const String &p_main_pack); + Error setup(const String &p_path, const String &p_main_pack); - Error save_custom(const String& p_path="",const CustomMap& p_custom=CustomMap(),const Set& p_ignore_masks=Set()); + Error save_custom(const String &p_path = "", const CustomMap &p_custom = CustomMap(), const Set &p_ignore_masks = Set()); Error save(); - void set_custom_property_info(const String& p_prop,const PropertyInfo& p_info); + void set_custom_property_info(const String &p_prop, const PropertyInfo &p_info); void add_singleton(const Singleton &p_singleton); void get_singletons(List *p_singletons); - bool has_singleton(const String& p_name) const; + bool has_singleton(const String &p_name) const; Vector get_optimizer_presets() const; List get_input_presets() const { return input_presets; } void set_disable_platform_override(bool p_disable); - Object* get_singleton_object(const String& p_name) const; + Object *get_singleton_object(const String &p_name) const; void register_global_defaults(); @@ -145,10 +153,9 @@ public: Globals(); ~Globals(); - }; //not a macro any longer -Variant _GLOBAL_DEF( const String& p_var, const Variant& p_default); -#define GLOBAL_DEF(m_var,m_value) _GLOBAL_DEF(m_var,m_value) +Variant _GLOBAL_DEF(const String &p_var, const Variant &p_default); +#define GLOBAL_DEF(m_var, m_value) _GLOBAL_DEF(m_var, m_value) #endif diff --git a/core/hash_map.h b/core/hash_map.h index 523a4a6214a..dd3fdb306ba 100644 --- a/core/hash_map.h +++ b/core/hash_map.h @@ -29,39 +29,36 @@ #ifndef HASH_MAP_H #define HASH_MAP_H -#include "hashfuncs.h" #include "error_macros.h" -#include "ustring.h" -#include "os/memory.h" +#include "hashfuncs.h" #include "list.h" - +#include "os/memory.h" +#include "ustring.h" class HashMapHahserDefault { public: - - static _FORCE_INLINE_ uint32_t hash(const String &p_string) { return p_string.hash(); } - static _FORCE_INLINE_ uint32_t hash(const char *p_cstr) { return hash_djb2(p_cstr); } - static _FORCE_INLINE_ uint32_t hash(const uint64_t p_int) { - uint64_t v=p_int; + static _FORCE_INLINE_ uint32_t hash(const String &p_string) { return p_string.hash(); } + static _FORCE_INLINE_ uint32_t hash(const char *p_cstr) { return hash_djb2(p_cstr); } + static _FORCE_INLINE_ uint32_t hash(const uint64_t p_int) { + uint64_t v = p_int; v = (~v) + (v << 18); // v = (v << 18) - v - 1; v = v ^ (v >> 31); v = v * 21; // v = (v + (v << 2)) + (v << 4); v = v ^ (v >> 11); v = v + (v << 6); v = v ^ (v >> 22); - return (int) v; + return (int)v; } - static _FORCE_INLINE_ uint32_t hash(const int64_t p_int) { return hash(uint64_t(p_int)); } + static _FORCE_INLINE_ uint32_t hash(const int64_t p_int) { return hash(uint64_t(p_int)); } - - static _FORCE_INLINE_ uint32_t hash(const uint32_t p_int) { return p_int; } - static _FORCE_INLINE_ uint32_t hash(const int32_t p_int) { return (uint32_t)p_int; } - static _FORCE_INLINE_ uint32_t hash(const uint16_t p_int) { return p_int; } - static _FORCE_INLINE_ uint32_t hash(const int16_t p_int) { return (uint32_t)p_int; } - static _FORCE_INLINE_ uint32_t hash(const uint8_t p_int) { return p_int; } - static _FORCE_INLINE_ uint32_t hash(const int8_t p_int) { return (uint32_t)p_int; } - static _FORCE_INLINE_ uint32_t hash(const wchar_t p_wchar) { return (uint32_t)p_wchar; } -// static _FORCE_INLINE_ uint32_t hash(const void* p_ptr) { return uint32_t(uint64_t(p_ptr))*(0x9e3779b1L); } + static _FORCE_INLINE_ uint32_t hash(const uint32_t p_int) { return p_int; } + static _FORCE_INLINE_ uint32_t hash(const int32_t p_int) { return (uint32_t)p_int; } + static _FORCE_INLINE_ uint32_t hash(const uint16_t p_int) { return p_int; } + static _FORCE_INLINE_ uint32_t hash(const int16_t p_int) { return (uint32_t)p_int; } + static _FORCE_INLINE_ uint32_t hash(const uint8_t p_int) { return p_int; } + static _FORCE_INLINE_ uint32_t hash(const int8_t p_int) { return (uint32_t)p_int; } + static _FORCE_INLINE_ uint32_t hash(const wchar_t p_wchar) { return (uint32_t)p_wchar; } + // static _FORCE_INLINE_ uint32_t hash(const void* p_ptr) { return uint32_t(uint64_t(p_ptr))*(0x9e3779b1L); } }; /** @@ -80,20 +77,21 @@ public: * */ -template +template class HashMap { public: - struct Pair { TKey key; TData data; Pair() {} - Pair(const TKey& p_key, const TData& p_data) { key=p_key; data=p_data; } + Pair(const TKey &p_key, const TData &p_data) { + key = p_key; + data = p_data; + } }; - private: struct Entry { @@ -101,7 +99,7 @@ private: Entry *next; Pair pair; - Entry() { next=0; } + Entry() { next = 0; } }; Entry **hash_table; @@ -110,206 +108,192 @@ private: void make_hash_table() { - ERR_FAIL_COND( hash_table ); + ERR_FAIL_COND(hash_table); - - hash_table = memnew_arr( Entry*, (1< ( (1< ((1 << hash_table_power) * RELATIONSHIP)) { /* rehash up */ - new_hash_table_power=hash_table_power+1; + new_hash_table_power = hash_table_power + 1; - while( (int)elements > ( (1< ((1 << new_hash_table_power) * RELATIONSHIP)) { new_hash_table_power++; } - } else if ( (hash_table_power>(int)MIN_HASH_TABLE_POWER) && ((int)elements < ( (1<<(hash_table_power-1)) * RELATIONSHIP ) ) ) { + } else if ((hash_table_power > (int)MIN_HASH_TABLE_POWER) && ((int)elements < ((1 << (hash_table_power - 1)) * RELATIONSHIP))) { /* rehash down */ - new_hash_table_power=hash_table_power-1; + new_hash_table_power = hash_table_power - 1; - while( (int)elements < ( (1<<(new_hash_table_power-1)) * RELATIONSHIP ) ) { + while ((int)elements < ((1 << (new_hash_table_power - 1)) * RELATIONSHIP)) { new_hash_table_power--; } - if (new_hash_table_power<(int)MIN_HASH_TABLE_POWER) - new_hash_table_power=MIN_HASH_TABLE_POWER; + if (new_hash_table_power < (int)MIN_HASH_TABLE_POWER) + new_hash_table_power = MIN_HASH_TABLE_POWER; } - - if (new_hash_table_power==-1) + if (new_hash_table_power == -1) return; - Entry ** new_hash_table = memnew_arr( Entry*, (1<next; - int new_pos = se->hash & ((1<next=new_hash_table[new_pos]; - new_hash_table[new_pos]=se; + Entry *se = hash_table[i]; + hash_table[i] = se->next; + int new_pos = se->hash & ((1 << new_hash_table_power) - 1); + se->next = new_hash_table[new_pos]; + new_hash_table[new_pos] = se; } - } if (hash_table) - memdelete_arr( hash_table ); - hash_table=new_hash_table; - hash_table_power=new_hash_table_power; - + memdelete_arr(hash_table); + hash_table = new_hash_table; + hash_table_power = new_hash_table_power; } - /* I want to have only one function.. */ - _FORCE_INLINE_ const Entry * get_entry( const TKey& p_key ) const { + _FORCE_INLINE_ const Entry *get_entry(const TKey &p_key) const { - uint32_t hash = Hasher::hash( p_key ); - uint32_t index = hash&((1<hash == hash && e->pair.key == p_key ) { + if (e->hash == hash && e->pair.key == p_key) { /* the pair exists in this hashtable, so just update data */ return e; } - e=e->next; + e = e->next; } return NULL; } - Entry * create_entry(const TKey& p_key) { + Entry *create_entry(const TKey &p_key) { /* if entry doesn't exist, create it */ - Entry *e = memnew( Entry ); - ERR_FAIL_COND_V(!e,NULL); /* out of memory */ - uint32_t hash = Hasher::hash( p_key ); - uint32_t index = hash&((1<next = hash_table[index]; e->hash = hash; - e->pair.key=p_key; + e->pair.key = p_key; - hash_table[index]=e; + hash_table[index] = e; elements++; return e; } + void copy_from(const HashMap &p_t) { - void copy_from(const HashMap& p_t) { - - if (&p_t==this) + if (&p_t == this) return; /* much less bother with that */ clear(); - if (!p_t.hash_table || p_t.hash_table_power==0) + if (!p_t.hash_table || p_t.hash_table_power == 0) return; /* not copying from empty table */ - hash_table = memnew_arr(Entry*,1<next=hash_table[i]; - hash_table[i]=le; + le->next = hash_table[i]; + hash_table[i] = le; - e=e->next; + e = e->next; } - - } - - } + public: + void set(const TKey &p_key, const TData &p_data) { - - void set( const TKey& p_key, const TData& p_data ) { - - set( Pair( p_key, p_data ) ); - + set(Pair(p_key, p_data)); } - void set( const Pair& p_pair ) { + void set(const Pair &p_pair) { - Entry *e=NULL; + Entry *e = NULL; if (!hash_table) make_hash_table(); // if no table, make one else - e = const_cast( get_entry(p_pair.key) ); + e = const_cast(get_entry(p_pair.key)); /* if we made it up to here, the pair doesn't exist, create and assign */ if (!e) { - e=create_entry(p_pair.key); + e = create_entry(p_pair.key); if (!e) return; check_hash_table(); // perform mantenience routine } e->pair.data = p_pair.data; - } + bool has(const TKey &p_key) const { - bool has( const TKey& p_key ) const { - - return getptr(p_key)!=NULL; + return getptr(p_key) != NULL; } /** @@ -318,17 +302,17 @@ public: * first with has(key) */ - const TData& get( const TKey& p_key ) const { + const TData &get(const TKey &p_key) const { - const TData* res = getptr(p_key); - ERR_FAIL_COND_V(!res,*res); + const TData *res = getptr(p_key); + ERR_FAIL_COND_V(!res, *res); return *res; } - TData& get( const TKey& p_key ) { + TData &get(const TKey &p_key) { - TData* res = getptr(p_key); - ERR_FAIL_COND_V(!res,*res); + TData *res = getptr(p_key); + ERR_FAIL_COND_V(!res, *res); return *res; } @@ -337,33 +321,30 @@ public: * This is mainly used for speed purposes. */ - - _FORCE_INLINE_ TData* getptr( const TKey& p_key ) { + _FORCE_INLINE_ TData *getptr(const TKey &p_key) { if (!hash_table) return NULL; - Entry *e=const_cast(get_entry(p_key )); + Entry *e = const_cast(get_entry(p_key)); if (e) return &e->pair.data; return NULL; - } - _FORCE_INLINE_ const TData* getptr( const TKey& p_key ) const { + _FORCE_INLINE_ const TData *getptr(const TKey &p_key) const { if (!hash_table) return NULL; - const Entry *e=const_cast(get_entry(p_key )); + const Entry *e = const_cast(get_entry(p_key)); if (e) return &e->pair.data; return NULL; - } /** @@ -371,129 +352,124 @@ public: * This version is custom, will take a hash and a custom key (that should support operator==() */ - template - _FORCE_INLINE_ TData* custom_getptr( C p_custom_key,uint32_t p_custom_hash ) { + template + _FORCE_INLINE_ TData *custom_getptr(C p_custom_key, uint32_t p_custom_hash) { if (!hash_table) return NULL; uint32_t hash = p_custom_hash; - uint32_t index = hash&((1<hash == hash && e->pair.key == p_custom_key ) { + if (e->hash == hash && e->pair.key == p_custom_key) { /* the pair exists in this hashtable, so just update data */ return &e->pair.data; } - e=e->next; + e = e->next; } return NULL; } - template - _FORCE_INLINE_ const TData* custom_getptr( C p_custom_key,uint32_t p_custom_hash ) const { + template + _FORCE_INLINE_ const TData *custom_getptr(C p_custom_key, uint32_t p_custom_hash) const { if (!hash_table) return NULL; uint32_t hash = p_custom_hash; - uint32_t index = hash&((1<hash == hash && e->pair.key == p_custom_key ) { + if (e->hash == hash && e->pair.key == p_custom_key) { /* the pair exists in this hashtable, so just update data */ return &e->pair.data; } - e=e->next; + e = e->next; } return NULL; } - /** * Erase an item, return true if erasing was succesful */ - bool erase( const TKey& p_key ) { + bool erase(const TKey &p_key) { if (!hash_table) return false; - uint32_t hash = Hasher::hash( p_key ); - uint32_t index = hash&((1<hash == hash && e->pair.key == p_key ) { + if (e->hash == hash && e->pair.key == p_key) { if (p) { - p->next=e->next; + p->next = e->next; } else { //begin of list - hash_table[index]=e->next; + hash_table[index] = e->next; } memdelete(e); elements--; - if (elements==0) + if (elements == 0) erase_hash_table(); else check_hash_table(); return true; } - p=e; - e=e->next; + p = e; + e = e->next; } - return false; - } - inline const TData& operator[](const TKey& p_key) const { //constref + inline const TData &operator[](const TKey &p_key) const { //constref return get(p_key); } - inline TData& operator[](const TKey& p_key ) { //assignment + inline TData &operator[](const TKey &p_key) { //assignment - Entry *e=NULL; + Entry *e = NULL; if (!hash_table) make_hash_table(); // if no table, make one else - e = const_cast( get_entry(p_key) ); + e = const_cast(get_entry(p_key)); /* if we made it up to here, the pair doesn't exist, create */ if (!e) { - e=create_entry(p_key); + e = create_entry(p_key); if (!e) - return *(TData*)NULL; /* panic! */ + return *(TData *)NULL; /* panic! */ check_hash_table(); // perform mantenience routine } return e->pair.data; - } /** @@ -511,13 +487,13 @@ public: * } * */ - const TKey* next(const TKey* p_key) const { + const TKey *next(const TKey *p_key) const { if (!hash_table) return NULL; if (!p_key) { /* get the first key */ - for (int i=0;i<(1<pair.key; @@ -526,17 +502,17 @@ public: } else { /* get the next key */ - const Entry *e = get_entry( *p_key ); - ERR_FAIL_COND_V( !e, NULL ); /* invalid key supplied */ + const Entry *e = get_entry(*p_key); + ERR_FAIL_COND_V(!e, NULL); /* invalid key supplied */ if (e->next) { /* if there is a "next" in the list, return that */ return &e->next->pair.key; } else { /* go to next entries */ - uint32_t index = e->hash&((1<hash & ((1 << hash_table_power) - 1); index++; - for (int i=index;i<(1<pair.key; @@ -545,10 +521,8 @@ public: } /* nothing found, was at end */ - } - return NULL; /* nothing found */ } @@ -559,71 +533,68 @@ public: inline bool empty() const { - return elements==0; + return elements == 0; } void clear() { /* clean up */ if (hash_table) { - for (int i=0;i<(1<next; - memdelete( e ); + Entry *e = hash_table[i]; + hash_table[i] = e->next; + memdelete(e); } } - memdelete_arr( hash_table ); + memdelete_arr(hash_table); } - hash_table=0; - hash_table_power=0; - elements=0; + hash_table = 0; + hash_table_power = 0; + elements = 0; } - - void operator=(const HashMap& p_table) { + void operator=(const HashMap &p_table) { copy_from(p_table); } HashMap() { - hash_table=NULL; - elements=0; - hash_table_power=0; + hash_table = NULL; + elements = 0; + hash_table_power = 0; } void get_key_list(List *p_keys) const { if (!hash_table) return; - for(int i=0;i<(1<push_back(e->pair.key); - e=e->next; + e = e->next; } } } - HashMap(const HashMap& p_table) { + HashMap(const HashMap &p_table) { - hash_table=NULL; - elements=0; - hash_table_power=0; + hash_table = NULL; + elements = 0; + hash_table_power = 0; copy_from(p_table); - } ~HashMap() { clear(); } - }; #endif diff --git a/core/hashfuncs.h b/core/hashfuncs.h index e9e57d8b42f..574ff361af8 100644 --- a/core/hashfuncs.h +++ b/core/hashfuncs.h @@ -29,14 +29,12 @@ #ifndef HASHFUNCS_H #define HASHFUNCS_H - #include "typedefs.h" /** * Hashing functions */ - /** * DJB2 Hash function * @param C String @@ -44,7 +42,7 @@ */ static inline uint32_t hash_djb2(const char *p_cstr) { - const unsigned char* chr=(const unsigned char*)p_cstr; + const unsigned char *chr = (const unsigned char *)p_cstr; uint32_t hash = 5381; uint32_t c; @@ -54,66 +52,64 @@ static inline uint32_t hash_djb2(const char *p_cstr) { return hash; } -static inline uint32_t hash_djb2_buffer(const uint8_t *p_buff, int p_len,uint32_t p_prev=5381) { +static inline uint32_t hash_djb2_buffer(const uint8_t *p_buff, int p_len, uint32_t p_prev = 5381) { uint32_t hash = p_prev; - for(int i=0;i +template static inline uint32_t make_uint32_t(T p_in) { union { T t; uint32_t _u32; } _u; - _u._u32=0; - _u.t=p_in; + _u._u32 = 0; + _u.t = p_in; return _u._u32; } +static inline uint64_t hash_djb2_one_64(uint64_t p_in, uint64_t p_prev = 5381) { -static inline uint64_t hash_djb2_one_64(uint64_t p_in,uint64_t p_prev=5381) { - - return ((p_prev<<5)+p_prev)+p_in; + return ((p_prev << 5) + p_prev) + p_in; } - -template +template static inline uint64_t make_uint64_t(T p_in) { union { T t; uint64_t _u64; } _u; - _u._u64=0; // in case p_in is smaller + _u._u64 = 0; // in case p_in is smaller - _u.t=p_in; + _u.t = p_in; return _u._u64; } - - #endif diff --git a/core/helper/math_fieldwise.cpp b/core/helper/math_fieldwise.cpp index 72c9c46b710..dea9bf2240e 100644 --- a/core/helper/math_fieldwise.cpp +++ b/core/helper/math_fieldwise.cpp @@ -31,12 +31,17 @@ #include "core/helper/math_fieldwise.h" -#define SETUP_TYPE(m_type) m_type source=p_source; m_type target=p_target; -#define TRY_TRANSFER_FIELD(m_name,m_member) if (p_field==m_name) { target.m_member=source.m_member; } +#define SETUP_TYPE(m_type) \ + m_type source = p_source; \ + m_type target = p_target; +#define TRY_TRANSFER_FIELD(m_name, m_member) \ + if (p_field == m_name) { \ + target.m_member = source.m_member; \ + } -Variant fieldwise_assign(const Variant& p_target, const Variant& p_source, const String& p_field) { +Variant fieldwise_assign(const Variant &p_target, const Variant &p_source, const String &p_field) { - ERR_FAIL_COND_V(p_target.get_type()!=p_source.get_type(),p_target); + ERR_FAIL_COND_V(p_target.get_type() != p_source.get_type(), p_target); switch (p_source.get_type()) { @@ -44,122 +49,81 @@ Variant fieldwise_assign(const Variant& p_target, const Variant& p_source, const SETUP_TYPE(Vector2) - /**/ TRY_TRANSFER_FIELD("x",x) - else TRY_TRANSFER_FIELD("y",y) + /**/ TRY_TRANSFER_FIELD("x", x) else TRY_TRANSFER_FIELD("y", y) - return target; + return target; } case Variant::RECT2: { SETUP_TYPE(Rect2) - /**/ TRY_TRANSFER_FIELD("x",pos.x) - else TRY_TRANSFER_FIELD("y",pos.y) - else TRY_TRANSFER_FIELD("w",size.x) - else TRY_TRANSFER_FIELD("h",size.y) + /**/ TRY_TRANSFER_FIELD("x", pos.x) else TRY_TRANSFER_FIELD("y", pos.y) else TRY_TRANSFER_FIELD("w", size.x) else TRY_TRANSFER_FIELD("h", size.y) - return target; + return target; } case Variant::VECTOR3: { SETUP_TYPE(Vector3) - /**/ TRY_TRANSFER_FIELD("x",x) - else TRY_TRANSFER_FIELD("y",y) - else TRY_TRANSFER_FIELD("z",z) + /**/ TRY_TRANSFER_FIELD("x", x) else TRY_TRANSFER_FIELD("y", y) else TRY_TRANSFER_FIELD("z", z) - return target; + return target; } case Variant::PLANE: { SETUP_TYPE(Plane) - /**/ TRY_TRANSFER_FIELD("x",normal.x) - else TRY_TRANSFER_FIELD("y",normal.y) - else TRY_TRANSFER_FIELD("z",normal.z) - else TRY_TRANSFER_FIELD("d",d) + /**/ TRY_TRANSFER_FIELD("x", normal.x) else TRY_TRANSFER_FIELD("y", normal.y) else TRY_TRANSFER_FIELD("z", normal.z) else TRY_TRANSFER_FIELD("d", d) - return target; + return target; } case Variant::QUAT: { SETUP_TYPE(Quat) - /**/ TRY_TRANSFER_FIELD("x",x) - else TRY_TRANSFER_FIELD("y",y) - else TRY_TRANSFER_FIELD("z",z) - else TRY_TRANSFER_FIELD("w",w) + /**/ TRY_TRANSFER_FIELD("x", x) else TRY_TRANSFER_FIELD("y", y) else TRY_TRANSFER_FIELD("z", z) else TRY_TRANSFER_FIELD("w", w) - return target; + return target; } case Variant::_AABB: { SETUP_TYPE(AABB) - /**/ TRY_TRANSFER_FIELD("px",pos.x) - else TRY_TRANSFER_FIELD("py",pos.y) - else TRY_TRANSFER_FIELD("pz",pos.z) - else TRY_TRANSFER_FIELD("sx",size.x) - else TRY_TRANSFER_FIELD("sy",size.y) - else TRY_TRANSFER_FIELD("sz",size.z) + /**/ TRY_TRANSFER_FIELD("px", pos.x) else TRY_TRANSFER_FIELD("py", pos.y) else TRY_TRANSFER_FIELD("pz", pos.z) else TRY_TRANSFER_FIELD("sx", size.x) else TRY_TRANSFER_FIELD("sy", size.y) else TRY_TRANSFER_FIELD("sz", size.z) - return target; + return target; } case Variant::MATRIX32: { SETUP_TYPE(Matrix32) - /**/ TRY_TRANSFER_FIELD("xx",elements[0][0]) - else TRY_TRANSFER_FIELD("xy",elements[0][1]) - else TRY_TRANSFER_FIELD("yx",elements[1][0]) - else TRY_TRANSFER_FIELD("yy",elements[1][1]) - else TRY_TRANSFER_FIELD("ox",elements[2][0]) - else TRY_TRANSFER_FIELD("oy",elements[2][1]) + /**/ TRY_TRANSFER_FIELD("xx", elements[0][0]) else TRY_TRANSFER_FIELD("xy", elements[0][1]) else TRY_TRANSFER_FIELD("yx", elements[1][0]) else TRY_TRANSFER_FIELD("yy", elements[1][1]) else TRY_TRANSFER_FIELD("ox", elements[2][0]) else TRY_TRANSFER_FIELD("oy", elements[2][1]) - return target; + return target; } case Variant::MATRIX3: { SETUP_TYPE(Matrix3) - /**/ TRY_TRANSFER_FIELD("xx",elements[0][0]) - else TRY_TRANSFER_FIELD("xy",elements[0][1]) - else TRY_TRANSFER_FIELD("xz",elements[0][2]) - else TRY_TRANSFER_FIELD("yx",elements[1][0]) - else TRY_TRANSFER_FIELD("yy",elements[1][1]) - else TRY_TRANSFER_FIELD("yz",elements[1][2]) - else TRY_TRANSFER_FIELD("zx",elements[2][0]) - else TRY_TRANSFER_FIELD("zy",elements[2][1]) - else TRY_TRANSFER_FIELD("zz",elements[2][2]) + /**/ TRY_TRANSFER_FIELD("xx", elements[0][0]) else TRY_TRANSFER_FIELD("xy", elements[0][1]) else TRY_TRANSFER_FIELD("xz", elements[0][2]) else TRY_TRANSFER_FIELD("yx", elements[1][0]) else TRY_TRANSFER_FIELD("yy", elements[1][1]) else TRY_TRANSFER_FIELD("yz", elements[1][2]) else TRY_TRANSFER_FIELD("zx", elements[2][0]) else TRY_TRANSFER_FIELD("zy", elements[2][1]) else TRY_TRANSFER_FIELD("zz", elements[2][2]) - return target; + return target; } case Variant::TRANSFORM: { SETUP_TYPE(Transform) - /**/ TRY_TRANSFER_FIELD("xx",basis.elements[0][0]) - else TRY_TRANSFER_FIELD("xy",basis.elements[0][1]) - else TRY_TRANSFER_FIELD("xz",basis.elements[0][2]) - else TRY_TRANSFER_FIELD("yx",basis.elements[1][0]) - else TRY_TRANSFER_FIELD("yy",basis.elements[1][1]) - else TRY_TRANSFER_FIELD("yz",basis.elements[1][2]) - else TRY_TRANSFER_FIELD("zx",basis.elements[2][0]) - else TRY_TRANSFER_FIELD("zy",basis.elements[2][1]) - else TRY_TRANSFER_FIELD("zz",basis.elements[2][2]) - else TRY_TRANSFER_FIELD("xo",origin.x) - else TRY_TRANSFER_FIELD("yo",origin.y) - else TRY_TRANSFER_FIELD("zo",origin.z) + /**/ TRY_TRANSFER_FIELD("xx", basis.elements[0][0]) else TRY_TRANSFER_FIELD("xy", basis.elements[0][1]) else TRY_TRANSFER_FIELD("xz", basis.elements[0][2]) else TRY_TRANSFER_FIELD("yx", basis.elements[1][0]) else TRY_TRANSFER_FIELD("yy", basis.elements[1][1]) else TRY_TRANSFER_FIELD("yz", basis.elements[1][2]) else TRY_TRANSFER_FIELD("zx", basis.elements[2][0]) else TRY_TRANSFER_FIELD("zy", basis.elements[2][1]) else TRY_TRANSFER_FIELD("zz", basis.elements[2][2]) else TRY_TRANSFER_FIELD("xo", origin.x) else TRY_TRANSFER_FIELD("yo", origin.y) else TRY_TRANSFER_FIELD("zo", origin.z) - return target; + return target; } default: { diff --git a/core/helper/math_fieldwise.h b/core/helper/math_fieldwise.h index 31f9af8d0b1..e73227f148b 100644 --- a/core/helper/math_fieldwise.h +++ b/core/helper/math_fieldwise.h @@ -33,7 +33,7 @@ #include "core/variant.h" -Variant fieldwise_assign(const Variant& p_target, const Variant& p_source, const String& p_field); +Variant fieldwise_assign(const Variant &p_target, const Variant &p_source, const String &p_field); #endif // TOOLS_ENABLED diff --git a/core/helper/value_evaluator.h b/core/helper/value_evaluator.h index 5d38bd4cb41..e14d24816ae 100644 --- a/core/helper/value_evaluator.h +++ b/core/helper/value_evaluator.h @@ -34,8 +34,9 @@ class ValueEvaluator : public Object { OBJ_TYPE(ValueEvaluator, Object); + public: - virtual double eval(const String& p_text) { + virtual double eval(const String &p_text) { return p_text.to_double(); } }; diff --git a/core/image.cpp b/core/image.cpp index ae3bd46fefb..8afbb278f9a 100644 --- a/core/image.cpp +++ b/core/image.cpp @@ -27,15 +27,14 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "image.h" -#include "hash_map.h" #include "core/io/image_loader.h" #include "core/os/copymem.h" +#include "hash_map.h" #include "hq2x.h" #include "print_string.h" #include - -const char* Image::format_names[Image::FORMAT_MAX]={ +const char *Image::format_names[Image::FORMAT_MAX] = { "Grayscale", "Intensity", "GrayscaleAlpha", @@ -63,45 +62,43 @@ const char* Image::format_names[Image::FORMAT_MAX]={ SavePNGFunc Image::save_png_func = NULL; -void Image::_put_pixel(int p_x,int p_y, const BColor& p_color, unsigned char *p_data) { - - _put_pixelw(p_x,p_y,width,p_color,p_data); +void Image::_put_pixel(int p_x, int p_y, const BColor &p_color, unsigned char *p_data) { + _put_pixelw(p_x, p_y, width, p_color, p_data); } -void Image::_put_pixelw(int p_x,int p_y, int p_width, const BColor& p_color, unsigned char *p_data) { +void Image::_put_pixelw(int p_x, int p_y, int p_width, const BColor &p_color, unsigned char *p_data) { + int ofs = p_y * p_width + p_x; - int ofs=p_y*p_width+p_x; - - switch(format) { + switch (format) { case FORMAT_GRAYSCALE: { - p_data[ofs]=p_color.gray(); + p_data[ofs] = p_color.gray(); } break; case FORMAT_INTENSITY: { - p_data[ofs]=p_color.a; + p_data[ofs] = p_color.a; } break; case FORMAT_GRAYSCALE_ALPHA: { - p_data[ofs*2]=p_color.gray(); - p_data[ofs*2+1]=p_color.a; + p_data[ofs * 2] = p_color.gray(); + p_data[ofs * 2 + 1] = p_color.a; } break; case FORMAT_RGB: { - p_data[ofs*3+0]=p_color.r; - p_data[ofs*3+1]=p_color.g; - p_data[ofs*3+2]=p_color.b; + p_data[ofs * 3 + 0] = p_color.r; + p_data[ofs * 3 + 1] = p_color.g; + p_data[ofs * 3 + 2] = p_color.b; } break; case FORMAT_RGBA: { - p_data[ofs*4+0]=p_color.r; - p_data[ofs*4+1]=p_color.g; - p_data[ofs*4+2]=p_color.b; - p_data[ofs*4+3]=p_color.a; + p_data[ofs * 4 + 0] = p_color.r; + p_data[ofs * 4 + 1] = p_color.g; + p_data[ofs * 4 + 2] = p_color.b; + p_data[ofs * 4 + 3] = p_color.a; } break; case FORMAT_INDEXED: @@ -110,143 +107,134 @@ void Image::_put_pixelw(int p_x,int p_y, int p_width, const BColor& p_color, uns ERR_FAIL(); } break; default: {}; - } - } +void Image::_get_mipmap_offset_and_size(int p_mipmap, int &r_offset, int &r_width, int &r_height) const { - -void Image::_get_mipmap_offset_and_size(int p_mipmap,int &r_offset, int &r_width,int &r_height) const { - - int w=width; - int h=height; - int ofs=0; + int w = width; + int h = height; + int ofs = 0; int pixel_size = get_format_pixel_size(format); int pixel_rshift = get_format_pixel_rshift(format); - int minw,minh; - _get_format_min_data_size(format,minw,minh); + int minw, minh; + _get_format_min_data_size(format, minw, minh); - for(int i=0;i>=pixel_rshift; - ofs+=s; - w=MAX(minw,w>>1); - h=MAX(minh,h>>1); + for (int i = 0; i < p_mipmap; i++) { + int s = w * h; + s *= pixel_size; + s >>= pixel_rshift; + ofs += s; + w = MAX(minw, w >> 1); + h = MAX(minh, h >> 1); } - r_offset=ofs; - r_width=w; - r_height=h; + r_offset = ofs; + r_width = w; + r_height = h; } int Image::get_mipmap_offset(int p_mipmap) const { - ERR_FAIL_INDEX_V(p_mipmap,(mipmaps+1),-1); + ERR_FAIL_INDEX_V(p_mipmap, (mipmaps + 1), -1); - int ofs,w,h; - _get_mipmap_offset_and_size(p_mipmap,ofs,w,h); + int ofs, w, h; + _get_mipmap_offset_and_size(p_mipmap, ofs, w, h); return ofs; } -void Image::get_mipmap_offset_and_size(int p_mipmap,int &r_ofs, int &r_size) const { +void Image::get_mipmap_offset_and_size(int p_mipmap, int &r_ofs, int &r_size) const { - int ofs,w,h; - _get_mipmap_offset_and_size(p_mipmap,ofs,w,h); + int ofs, w, h; + _get_mipmap_offset_and_size(p_mipmap, ofs, w, h); int ofs2; - _get_mipmap_offset_and_size(p_mipmap+1,ofs2,w,h); - r_ofs=ofs; - r_size=ofs2-ofs; - + _get_mipmap_offset_and_size(p_mipmap + 1, ofs2, w, h); + r_ofs = ofs; + r_size = ofs2 - ofs; } -void Image::get_mipmap_offset_size_and_dimensions(int p_mipmap,int &r_ofs, int &r_size,int &w, int& h) const { - +void Image::get_mipmap_offset_size_and_dimensions(int p_mipmap, int &r_ofs, int &r_size, int &w, int &h) const { int ofs; - _get_mipmap_offset_and_size(p_mipmap,ofs,w,h); - int ofs2,w2,h2; - _get_mipmap_offset_and_size(p_mipmap+1,ofs2,w2,h2); - r_ofs=ofs; - r_size=ofs2-ofs; - + _get_mipmap_offset_and_size(p_mipmap, ofs, w, h); + int ofs2, w2, h2; + _get_mipmap_offset_and_size(p_mipmap + 1, ofs2, w2, h2); + r_ofs = ofs; + r_size = ofs2 - ofs; } -void Image::put_pixel(int p_x,int p_y, const Color& p_color,int p_mipmap){ +void Image::put_pixel(int p_x, int p_y, const Color &p_color, int p_mipmap) { - ERR_FAIL_INDEX(p_mipmap,mipmaps+1); - int ofs,w,h; - _get_mipmap_offset_and_size(p_mipmap,ofs,w,h); - ERR_FAIL_INDEX(p_x,w); - ERR_FAIL_INDEX(p_y,h); + ERR_FAIL_INDEX(p_mipmap, mipmaps + 1); + int ofs, w, h; + _get_mipmap_offset_and_size(p_mipmap, ofs, w, h); + ERR_FAIL_INDEX(p_x, w); + ERR_FAIL_INDEX(p_y, h); DVector::Write wp = data.write(); - unsigned char *data_ptr=wp.ptr(); - - _put_pixelw(p_x,p_y,w,BColor(p_color.r*255,p_color.g*255,p_color.b*255,p_color.a*255),&data_ptr[ofs]); + unsigned char *data_ptr = wp.ptr(); + _put_pixelw(p_x, p_y, w, BColor(p_color.r * 255, p_color.g * 255, p_color.b * 255, p_color.a * 255), &data_ptr[ofs]); } +Image::BColor Image::_get_pixel(int p_x, int p_y, const unsigned char *p_data, int p_data_size) const { -Image::BColor Image::_get_pixel(int p_x,int p_y,const unsigned char *p_data,int p_data_size) const{ - - return _get_pixelw(p_x,p_y,width,p_data,p_data_size); + return _get_pixelw(p_x, p_y, width, p_data, p_data_size); } -Image::BColor Image::_get_pixelw(int p_x,int p_y,int p_width,const unsigned char *p_data,int p_data_size) const{ +Image::BColor Image::_get_pixelw(int p_x, int p_y, int p_width, const unsigned char *p_data, int p_data_size) const { - int ofs=p_y*p_width+p_x; - BColor result(0,0,0,0); - switch(format) { + int ofs = p_y * p_width + p_x; + BColor result(0, 0, 0, 0); + switch (format) { case FORMAT_GRAYSCALE: { - result=BColor(p_data[ofs],p_data[ofs],p_data[ofs],255.0); + result = BColor(p_data[ofs], p_data[ofs], p_data[ofs], 255.0); } break; case FORMAT_INTENSITY: { - result=BColor(255,255,255,p_data[ofs]); + result = BColor(255, 255, 255, p_data[ofs]); } break; case FORMAT_GRAYSCALE_ALPHA: { - result=BColor(p_data[ofs*2],p_data[ofs*2],p_data[ofs*2],p_data[ofs*2+1]); + result = BColor(p_data[ofs * 2], p_data[ofs * 2], p_data[ofs * 2], p_data[ofs * 2 + 1]); } break; case FORMAT_RGB: { - result=BColor(p_data[ofs*3],p_data[ofs*3+1],p_data[ofs*3+2]); + result = BColor(p_data[ofs * 3], p_data[ofs * 3 + 1], p_data[ofs * 3 + 2]); } break; case FORMAT_RGBA: { - result=BColor(p_data[ofs*4],p_data[ofs*4+1],p_data[ofs*4+2],p_data[ofs*4+3]); + result = BColor(p_data[ofs * 4], p_data[ofs * 4 + 1], p_data[ofs * 4 + 2], p_data[ofs * 4 + 3]); } break; case FORMAT_INDEXED_ALPHA: { int pitch = 4; - const uint8_t* pal = &p_data[ p_data_size - pitch * 256 ]; + const uint8_t *pal = &p_data[p_data_size - pitch * 256]; int idx = p_data[ofs]; - result=BColor(pal[idx * pitch + 0] , pal[idx * pitch + 1] , pal[idx * pitch + 2] , pal[idx * pitch + 3] ); + result = BColor(pal[idx * pitch + 0], pal[idx * pitch + 1], pal[idx * pitch + 2], pal[idx * pitch + 3]); } break; case FORMAT_INDEXED: { int pitch = 3; - const uint8_t* pal = &p_data[ p_data_size - pitch * 256 ]; + const uint8_t *pal = &p_data[p_data_size - pitch * 256]; int idx = p_data[ofs]; - result=BColor(pal[idx * pitch + 0] , pal[idx * pitch + 1] , pal[idx * pitch + 2] ,255); + result = BColor(pal[idx * pitch + 0], pal[idx * pitch + 1], pal[idx * pitch + 2], 255); } break; case FORMAT_YUV_422: { int y, u, v; if (p_x % 2) { - const uint8_t* yp = &p_data[p_width * 2 * p_y + p_x * 2]; - u = *(yp-1); + const uint8_t *yp = &p_data[p_width * 2 * p_y + p_x * 2]; + u = *(yp - 1); y = yp[0]; v = yp[1]; } else { - const uint8_t* yp = &p_data[p_width * 2 * p_y + p_x * 2]; + const uint8_t *yp = &p_data[p_width * 2 * p_y + p_x * 2]; y = yp[0]; u = yp[1]; v = yp[3]; @@ -260,7 +248,7 @@ Image::BColor Image::_get_pixelw(int p_x,int p_y,int p_width,const unsigned char case FORMAT_YUV_444: { uint8_t y, u, v; - const uint8_t* yp = &p_data[p_width * 3 * p_y + p_x * 3]; + const uint8_t *yp = &p_data[p_width * 3 * p_y + p_x * 3]; y = yp[0]; u = yp[1]; v = yp[2]; @@ -270,60 +258,56 @@ Image::BColor Image::_get_pixelw(int p_x,int p_y,int p_width,const unsigned char int32_t b = 1.164 * (y - 16) + 2.018 * (u - 128); result = BColor(CLAMP(r, 0, 255), CLAMP(g, 0, 255), CLAMP(b, 0, 255)); } break; - default:{} - + default: {} } return result; - } -void Image::put_indexed_pixel(int p_x, int p_y, uint8_t p_idx,int p_mipmap) { +void Image::put_indexed_pixel(int p_x, int p_y, uint8_t p_idx, int p_mipmap) { ERR_FAIL_COND(format != FORMAT_INDEXED && format != FORMAT_INDEXED_ALPHA); - ERR_FAIL_INDEX(p_mipmap,mipmaps+1); - int ofs,w,h; - _get_mipmap_offset_and_size(p_mipmap,ofs,w,h); - ERR_FAIL_INDEX(p_x,w); - ERR_FAIL_INDEX(p_y,h); + ERR_FAIL_INDEX(p_mipmap, mipmaps + 1); + int ofs, w, h; + _get_mipmap_offset_and_size(p_mipmap, ofs, w, h); + ERR_FAIL_INDEX(p_x, w); + ERR_FAIL_INDEX(p_y, h); data.set(ofs + p_y * w + p_x, p_idx); }; -uint8_t Image::get_indexed_pixel(int p_x, int p_y,int p_mipmap) const { +uint8_t Image::get_indexed_pixel(int p_x, int p_y, int p_mipmap) const { ERR_FAIL_COND_V(format != FORMAT_INDEXED && format != FORMAT_INDEXED_ALPHA, 0); - ERR_FAIL_INDEX_V(p_mipmap,mipmaps+1,0); - int ofs,w,h; - _get_mipmap_offset_and_size(p_mipmap,ofs,w,h); - ERR_FAIL_INDEX_V(p_x,w,0); - ERR_FAIL_INDEX_V(p_y,h,0); - + ERR_FAIL_INDEX_V(p_mipmap, mipmaps + 1, 0); + int ofs, w, h; + _get_mipmap_offset_and_size(p_mipmap, ofs, w, h); + ERR_FAIL_INDEX_V(p_x, w, 0); + ERR_FAIL_INDEX_V(p_y, h, 0); return data[ofs + p_y * w + p_x]; }; -void Image::set_pallete(const DVector& p_data) { - +void Image::set_pallete(const DVector &p_data) { int len = p_data.size(); ERR_FAIL_COND(format != FORMAT_INDEXED && format != FORMAT_INDEXED_ALPHA); - ERR_FAIL_COND(format == FORMAT_INDEXED && len!=(256*3)); - ERR_FAIL_COND(format == FORMAT_INDEXED_ALPHA && len!=(256*4)); + ERR_FAIL_COND(format == FORMAT_INDEXED && len != (256 * 3)); + ERR_FAIL_COND(format == FORMAT_INDEXED_ALPHA && len != (256 * 4)); - int ofs,w,h; - _get_mipmap_offset_and_size(mipmaps+1,ofs,w,h); + int ofs, w, h; + _get_mipmap_offset_and_size(mipmaps + 1, ofs, w, h); int pal_ofs = ofs; data.resize(pal_ofs + p_data.size()); DVector::Write wp = data.write(); - unsigned char *dst=wp.ptr() + pal_ofs; + unsigned char *dst = wp.ptr() + pal_ofs; DVector::Read r = p_data.read(); - const unsigned char *src=r.ptr(); + const unsigned char *src = r.ptr(); copymem(dst, src, len); }; @@ -332,58 +316,53 @@ int Image::get_width() const { return width; } -int Image::get_height() const{ +int Image::get_height() const { return height; } int Image::get_mipmaps() const { - return mipmaps; } -Color Image::get_pixel(int p_x,int p_y,int p_mipmap) const { - - - ERR_FAIL_INDEX_V(p_mipmap,mipmaps+1,Color()); - int ofs,w,h; - _get_mipmap_offset_and_size(p_mipmap,ofs,w,h); - ERR_FAIL_INDEX_V(p_x,w,Color()); - ERR_FAIL_INDEX_V(p_y,h,Color()); +Color Image::get_pixel(int p_x, int p_y, int p_mipmap) const { + ERR_FAIL_INDEX_V(p_mipmap, mipmaps + 1, Color()); + int ofs, w, h; + _get_mipmap_offset_and_size(p_mipmap, ofs, w, h); + ERR_FAIL_INDEX_V(p_x, w, Color()); + ERR_FAIL_INDEX_V(p_y, h, Color()); int len = data.size(); DVector::Read r = data.read(); - const unsigned char*data_ptr=r.ptr(); - BColor c = _get_pixelw(p_x,p_y,w,&data_ptr[ofs],len); - return Color( c.r/255.0,c.g/255.0,c.b/255.0,c.a/255.0 ); + const unsigned char *data_ptr = r.ptr(); + BColor c = _get_pixelw(p_x, p_y, w, &data_ptr[ofs], len); + return Color(c.r / 255.0, c.g / 255.0, c.b / 255.0, c.a / 255.0); } -void Image::convert( Format p_new_format ){ +void Image::convert(Format p_new_format) { - if (data.size()==0) + if (data.size() == 0) return; - if (p_new_format==format) + if (p_new_format == format) return; - if (format>=FORMAT_BC1 || p_new_format>=FORMAT_BC1) { + if (format >= FORMAT_BC1 || p_new_format >= FORMAT_BC1) { ERR_EXPLAIN("Cannot convert to <-> from compressed/custom image formats (for now)."); ERR_FAIL(); } - if (p_new_format==FORMAT_INDEXED || p_new_format==FORMAT_INDEXED_ALPHA) { - + if (p_new_format == FORMAT_INDEXED || p_new_format == FORMAT_INDEXED_ALPHA) { return; } + Image new_img(width, height, 0, p_new_format); - Image new_img(width,height,0,p_new_format); - - int len=data.size(); + int len = data.size(); DVector::Read r = data.read(); DVector::Write w = new_img.data.write(); @@ -391,158 +370,148 @@ void Image::convert( Format p_new_format ){ const uint8_t *rptr = r.ptr(); uint8_t *wptr = w.ptr(); - if (p_new_format==FORMAT_RGBA && format==FORMAT_INDEXED_ALPHA) { + if (p_new_format == FORMAT_RGBA && format == FORMAT_INDEXED_ALPHA) { //optimized unquantized form - int dataend = len-256*4; - const uint32_t *palpos = (const uint32_t*)&rptr[dataend]; + int dataend = len - 256 * 4; + const uint32_t *palpos = (const uint32_t *)&rptr[dataend]; uint32_t *dst32 = (uint32_t *)wptr; - for(int i=0;i::Read(); w = DVector::Write(); - bool gen_mipmaps=mipmaps>0; + bool gen_mipmaps = mipmaps > 0; - *this=new_img; + *this = new_img; if (gen_mipmaps) generate_mipmaps(); - - } -Image::Format Image::get_format() const{ +Image::Format Image::get_format() const { return format; } -static double _bicubic_interp_kernel( double x ) { +static double _bicubic_interp_kernel(double x) { x = ABS(x); double bc = 0; - if ( x <= 1 ) - bc = ( 1.5 * x - 2.5 ) * x * x + 1; - else if ( x < 2 ) - bc = ( ( -0.5 * x + 2.5 ) * x - 4 ) * x + 2; - + if (x <= 1) + bc = (1.5 * x - 2.5) * x * x + 1; + else if (x < 2) + bc = ((-0.5 * x + 2.5) * x - 4) * x + 2; return bc; } -template -static void _scale_cubic(const uint8_t* p_src, uint8_t* p_dst, uint32_t p_src_width, uint32_t p_src_height, uint32_t p_dst_width, uint32_t p_dst_height) { - +template +static void _scale_cubic(const uint8_t *p_src, uint8_t *p_dst, uint32_t p_src_width, uint32_t p_src_height, uint32_t p_dst_width, uint32_t p_dst_height) { // get source image size - int width = p_src_width; - int height = p_src_height; - double xfac = (double) width / p_dst_width; - double yfac = (double) height / p_dst_height; + int width = p_src_width; + int height = p_src_height; + double xfac = (double)width / p_dst_width; + double yfac = (double)height / p_dst_height; // coordinates of source points and cooefficiens - double ox, oy, dx, dy, k1, k2; - int ox1, oy1, ox2, oy2; + double ox, oy, dx, dy, k1, k2; + int ox1, oy1, ox2, oy2; // destination pixel values // width and height decreased by 1 int ymax = height - 1; int xmax = width - 1; // temporary pointer - for ( int y = 0; y < p_dst_height; y++ ) { + for (int y = 0; y < p_dst_height; y++) { // Y coordinates - oy = (double) y * yfac - 0.5f; - oy1 = (int) oy; - dy = oy - (double) oy1; + oy = (double)y * yfac - 0.5f; + oy1 = (int)oy; + dy = oy - (double)oy1; - for ( int x = 0; x < p_dst_width; x++ ) { + for (int x = 0; x < p_dst_width; x++) { // X coordinates - ox = (double) x * xfac - 0.5f; - ox1 = (int) ox; - dx = ox - (double) ox1; + ox = (double)x * xfac - 0.5f; + ox1 = (int)ox; + dx = ox - (double)ox1; // initial pixel value - uint8_t *dst=p_dst + (y*p_dst_width+x)*CC; + uint8_t *dst = p_dst + (y * p_dst_width + x) * CC; double color[CC]; - for(int i=0;i ymax ) + if (oy2 > ymax) oy2 = ymax; - for ( int m = -1; m < 3; m++ ) { + for (int m = -1; m < 3; m++) { // get X cooefficient - k2 = k1 * _bicubic_interp_kernel( (double) m - dx ); + k2 = k1 * _bicubic_interp_kernel((double)m - dx); ox2 = ox1 + m; - if ( ox2 < 0 ) + if (ox2 < 0) ox2 = 0; - if ( ox2 > xmax ) + if (ox2 > xmax) ox2 = xmax; // get pixel of original image - const uint8_t *p = p_src + (oy2 * p_src_width + ox2)*CC; + const uint8_t *p = p_src + (oy2 * p_src_width + ox2) * CC; - for(int i=0;i -static void _scale_bilinear(const uint8_t* p_src, uint8_t* p_dst, uint32_t p_src_width, uint32_t p_src_height, uint32_t p_dst_width, uint32_t p_dst_height) { +template +static void _scale_bilinear(const uint8_t *p_src, uint8_t *p_dst, uint32_t p_src_width, uint32_t p_src_height, uint32_t p_dst_width, uint32_t p_dst_height) { enum { - FRAC_BITS=8, - FRAC_LEN=(1<> FRAC_BITS; - - uint32_t src_yofs_down = (i+1)*p_src_height/p_dst_height; - if (src_yofs_down>=p_src_height) - src_yofs_down=p_src_height-1; + uint32_t src_yofs_down = (i + 1) * p_src_height / p_dst_height; + if (src_yofs_down >= p_src_height) + src_yofs_down = p_src_height - 1; //src_yofs_up*=CC; //src_yofs_down*=CC; @@ -550,60 +519,57 @@ static void _scale_bilinear(const uint8_t* p_src, uint8_t* p_dst, uint32_t p_src uint32_t y_ofs_up = src_yofs_up * p_src_width * CC; uint32_t y_ofs_down = src_yofs_down * p_src_width * CC; - for(uint32_t j=0;j> FRAC_BITS; - uint32_t src_xofs_right = (j+1)*p_src_width/p_dst_width; - if (src_xofs_right>=p_src_width) - src_xofs_right=p_src_width-1; + uint32_t src_xofs_right = (j + 1) * p_src_width / p_dst_width; + if (src_xofs_right >= p_src_width) + src_xofs_right = p_src_width - 1; - src_xofs_left*=CC; - src_xofs_right*=CC; + src_xofs_left *= CC; + src_xofs_right *= CC; - for(uint32_t l=0;l>FRAC_BITS); - uint32_t interp_down = p01+(((p11-p01)*src_xofs_frac)>>FRAC_BITS); - uint32_t interp = interp_up+(((interp_down-interp_up)*src_yofs_frac)>>FRAC_BITS); - interp>>=FRAC_BITS; - p_dst[i*p_dst_width*CC+j*CC+l]=interp; + uint32_t interp_up = p00 + (((p10 - p00) * src_xofs_frac) >> FRAC_BITS); + uint32_t interp_down = p01 + (((p11 - p01) * src_xofs_frac) >> FRAC_BITS); + uint32_t interp = interp_up + (((interp_down - interp_up) * src_yofs_frac) >> FRAC_BITS); + interp >>= FRAC_BITS; + p_dst[i * p_dst_width * CC + j * CC + l] = interp; } } } } +template +static void _scale_nearest(const uint8_t *p_src, uint8_t *p_dst, uint32_t p_src_width, uint32_t p_src_height, uint32_t p_dst_width, uint32_t p_dst_height) { -template -static void _scale_nearest(const uint8_t* p_src, uint8_t* p_dst, uint32_t p_src_width, uint32_t p_src_height, uint32_t p_dst_width, uint32_t p_dst_height) { + for (uint32_t i = 0; i < p_dst_height; i++) { - - for(uint32_t i=0;iMAX_WIDTH); - ERR_FAIL_COND(p_height>MAX_HEIGHT); + ERR_FAIL_COND(p_width <= 0); + ERR_FAIL_COND(p_height <= 0); + ERR_FAIL_COND(p_width > MAX_WIDTH); + ERR_FAIL_COND(p_height > MAX_HEIGHT); - - if (p_width==width && p_height==height) + if (p_width == width && p_height == height) return; - Image dst( p_width, p_height, 0, format ); - - if (format==FORMAT_INDEXED) - p_interpolation=INTERPOLATE_NEAREST; + Image dst(p_width, p_height, 0, format); + if (format == FORMAT_INDEXED) + p_interpolation = INTERPOLATE_NEAREST; DVector::Read r = data.read(); - const unsigned char*r_ptr=r.ptr(); + const unsigned char *r_ptr = r.ptr(); DVector::Write w = dst.data.write(); - unsigned char*w_ptr=w.ptr(); + unsigned char *w_ptr = w.ptr(); - - switch(p_interpolation) { + switch (p_interpolation) { case INTERPOLATE_NEAREST: { - switch(get_format_pixel_size(format)) { - case 1: _scale_nearest<1>(r_ptr,w_ptr,width,height,p_width,p_height); break; - case 2: _scale_nearest<2>(r_ptr,w_ptr,width,height,p_width,p_height); break; - case 3: _scale_nearest<3>(r_ptr,w_ptr,width,height,p_width,p_height); break; - case 4: _scale_nearest<4>(r_ptr,w_ptr,width,height,p_width,p_height); break; + switch (get_format_pixel_size(format)) { + case 1: _scale_nearest<1>(r_ptr, w_ptr, width, height, p_width, p_height); break; + case 2: _scale_nearest<2>(r_ptr, w_ptr, width, height, p_width, p_height); break; + case 3: _scale_nearest<3>(r_ptr, w_ptr, width, height, p_width, p_height); break; + case 4: _scale_nearest<4>(r_ptr, w_ptr, width, height, p_width, p_height); break; } } break; case INTERPOLATE_BILINEAR: { - switch(get_format_pixel_size(format)) { - case 1: _scale_bilinear<1>(r_ptr,w_ptr,width,height,p_width,p_height); break; - case 2: _scale_bilinear<2>(r_ptr,w_ptr,width,height,p_width,p_height); break; - case 3: _scale_bilinear<3>(r_ptr,w_ptr,width,height,p_width,p_height); break; - case 4: _scale_bilinear<4>(r_ptr,w_ptr,width,height,p_width,p_height); break; + switch (get_format_pixel_size(format)) { + case 1: _scale_bilinear<1>(r_ptr, w_ptr, width, height, p_width, p_height); break; + case 2: _scale_bilinear<2>(r_ptr, w_ptr, width, height, p_width, p_height); break; + case 3: _scale_bilinear<3>(r_ptr, w_ptr, width, height, p_width, p_height); break; + case 4: _scale_bilinear<4>(r_ptr, w_ptr, width, height, p_width, p_height); break; } } break; case INTERPOLATE_CUBIC: { - switch(get_format_pixel_size(format)) { - case 1: _scale_cubic<1>(r_ptr,w_ptr,width,height,p_width,p_height); break; - case 2: _scale_cubic<2>(r_ptr,w_ptr,width,height,p_width,p_height); break; - case 3: _scale_cubic<3>(r_ptr,w_ptr,width,height,p_width,p_height); break; - case 4: _scale_cubic<4>(r_ptr,w_ptr,width,height,p_width,p_height); break; + switch (get_format_pixel_size(format)) { + case 1: _scale_cubic<1>(r_ptr, w_ptr, width, height, p_width, p_height); break; + case 2: _scale_cubic<2>(r_ptr, w_ptr, width, height, p_width, p_height); break; + case 3: _scale_cubic<3>(r_ptr, w_ptr, width, height, p_width, p_height); break; + case 4: _scale_cubic<4>(r_ptr, w_ptr, width, height, p_width, p_height); break; } } break; - - } r = DVector::Read(); w = DVector::Write(); - if (mipmaps>0) + if (mipmaps > 0) dst.generate_mipmaps(); - *this=dst; + *this = dst; } -void Image::crop( int p_width, int p_height ) { +void Image::crop(int p_width, int p_height) { if (!_can_modify(format)) { ERR_EXPLAIN("Cannot crop in indexed, compressed or custom image formats."); ERR_FAIL(); } - ERR_FAIL_COND(p_width<=0); - ERR_FAIL_COND(p_height<=0); - ERR_FAIL_COND(p_width>MAX_WIDTH); - ERR_FAIL_COND(p_height>MAX_HEIGHT); + ERR_FAIL_COND(p_width <= 0); + ERR_FAIL_COND(p_height <= 0); + ERR_FAIL_COND(p_width > MAX_WIDTH); + ERR_FAIL_COND(p_height > MAX_HEIGHT); /* to save memory, cropping should be done in-place, however, since this function will most likely either not be used much, or in critical areas, for now it wont, because it's a waste of time. */ - if (p_width==width && p_height==height) + if (p_width == width && p_height == height) return; - Image dst( p_width, p_height,0, format ); + Image dst(p_width, p_height, 0, format); + for (int y = 0; y < p_height; y++) { - for (int y=0;y=width || y>=height)? Color() : get_pixel(x,y); - dst.put_pixel(x,y,col); + Color col = (x >= width || y >= height) ? Color() : get_pixel(x, y); + dst.put_pixel(x, y, col); } } - if (mipmaps>0) + if (mipmaps > 0) dst.generate_mipmaps(); - *this=dst; - + *this = dst; } void Image::flip_y() { @@ -747,28 +705,24 @@ void Image::flip_y() { ERR_FAIL(); } - bool gm=mipmaps; + bool gm = mipmaps; if (gm) clear_mipmaps(); + for (int y = 0; y < (height / 2); y++) { + for (int x = 0; x < width; x++) { + Color up = get_pixel(x, y); + Color down = get_pixel(x, height - y - 1); - for (int y=0;y<(height/2);y++) { - - for (int x=0;x>=pixshift; + int s = w * h; + s *= pixsize; + s >>= pixshift; - size+=s; + size += s; - if (p_mipmaps>=0 && mm==p_mipmaps) + if (p_mipmaps >= 0 && mm == p_mipmaps) break; - if (p_mipmaps>=0) { + if (p_mipmaps >= 0) { - w=MAX(minw,w>>1); - h=MAX(minh,h>>1); + w = MAX(minw, w >> 1); + h = MAX(minh, h >> 1); } else { - if (w==minw && h==minh) + if (w == minw && h == minh) break; - w=MAX(minw,w>>1); - h=MAX(minh,h>>1); + w = MAX(minw, w >> 1); + h = MAX(minh, h >> 1); } mm++; }; - r_mipmaps=mm; + r_mipmaps = mm; return size; } bool Image::_can_modify(Format p_format) const { - switch(p_format) { + switch (p_format) { //these are OK case FORMAT_GRAYSCALE: @@ -865,86 +823,78 @@ bool Image::_can_modify(Format p_format) const { return false; } -template -static void _generate_po2_mipmap(const uint8_t* p_src, uint8_t* p_dst, uint32_t p_width, uint32_t p_height) { +template +static void _generate_po2_mipmap(const uint8_t *p_src, uint8_t *p_dst, uint32_t p_width, uint32_t p_height) { //fast power of 2 mipmap generation uint32_t dst_w = p_width >> 1; uint32_t dst_h = p_height >> 1; - for(uint32_t i=0;i>2; + for (int j = 0; j < CC; j++) { + uint16_t val = 0; + val += rup_ptr[j]; + val += rup_ptr[j + CC]; + val += rdown_ptr[j]; + val += rdown_ptr[j + CC]; + dst_ptr[j] = val >> 2; } - dst_ptr+=CC; - rup_ptr+=CC*2; - rdown_ptr+=CC*2; + dst_ptr += CC; + rup_ptr += CC * 2; + rdown_ptr += CC * 2; } } } - void Image::expand_x2_hq2x() { - ERR_FAIL_COND(format>=FORMAT_INDEXED); + ERR_FAIL_COND(format >= FORMAT_INDEXED); Format current = format; - bool mipmaps=get_mipmaps(); + bool mipmaps = get_mipmaps(); if (mipmaps) { clear_mipmaps(); } - if (current!=FORMAT_RGBA) + if (current != FORMAT_RGBA) convert(FORMAT_RGBA); DVector dest; - dest.resize(width*2*height*2*4); + dest.resize(width * 2 * height * 2 * 4); { DVector::Read r = data.read(); DVector::Write w = dest.write(); - hq2x_resize((const uint32_t*)r.ptr(),width,height,(uint32_t*)w.ptr()); - + hq2x_resize((const uint32_t *)r.ptr(), width, height, (uint32_t *)w.ptr()); } - width*=2; - height*=2; - data=dest; + width *= 2; + height *= 2; + data = dest; - - if (current!=FORMAT_RGBA) + if (current != FORMAT_RGBA) convert(current); if (mipmaps) { generate_mipmaps(); } - } void Image::shrink_x2() { - ERR_FAIL_COND(format==FORMAT_INDEXED || format==FORMAT_INDEXED_ALPHA); - ERR_FAIL_COND( data.size()==0 ); - - + ERR_FAIL_COND(format == FORMAT_INDEXED || format == FORMAT_INDEXED_ALPHA); + ERR_FAIL_COND(data.size() == 0); if (mipmaps) { @@ -953,181 +903,169 @@ void Image::shrink_x2() { int ofs = get_mipmap_offset(1); - int new_size = data.size()-ofs; + int new_size = data.size() - ofs; new_img.resize(new_size); - { - DVector::Write w=new_img.write(); - DVector::Read r=data.read(); + DVector::Write w = new_img.write(); + DVector::Read r = data.read(); - copymem(w.ptr(),&r[ofs],new_size); + copymem(w.ptr(), &r[ofs], new_size); } mipmaps--; - width/=2; - height/=2; - data=new_img; + width /= 2; + height /= 2; + data = new_img; } else { DVector new_img; - ERR_FAIL_COND( format>=FORMAT_INDEXED ); + ERR_FAIL_COND(format >= FORMAT_INDEXED); int ps = get_format_pixel_size(format); - new_img.resize((width/2)*(height/2)*ps); + new_img.resize((width / 2) * (height / 2) * ps); { - DVector::Write w=new_img.write(); - DVector::Read r=data.read(); + DVector::Write w = new_img.write(); + DVector::Read r = data.read(); - switch(format) { + switch (format) { case FORMAT_GRAYSCALE: - case FORMAT_INTENSITY: _generate_po2_mipmap<1>(r.ptr(), w.ptr(), width,height); break; - case FORMAT_GRAYSCALE_ALPHA: _generate_po2_mipmap<2>(r.ptr(), w.ptr(), width,height); break; - case FORMAT_RGB: _generate_po2_mipmap<3>(r.ptr(), w.ptr(), width,height); break; - case FORMAT_RGBA: _generate_po2_mipmap<4>(r.ptr(), w.ptr(), width,height); break; + case FORMAT_INTENSITY: _generate_po2_mipmap<1>(r.ptr(), w.ptr(), width, height); break; + case FORMAT_GRAYSCALE_ALPHA: _generate_po2_mipmap<2>(r.ptr(), w.ptr(), width, height); break; + case FORMAT_RGB: _generate_po2_mipmap<3>(r.ptr(), w.ptr(), width, height); break; + case FORMAT_RGBA: _generate_po2_mipmap<4>(r.ptr(), w.ptr(), width, height); break; default: {} } } - width/=2; - height/=2; - data=new_img; - + width /= 2; + height /= 2; + data = new_img; } } -Error Image::generate_mipmaps(int p_mipmaps,bool p_keep_existing) { +Error Image::generate_mipmaps(int p_mipmaps, bool p_keep_existing) { if (!_can_modify(format)) { ERR_EXPLAIN("Cannot generate mipmaps in indexed, compressed or custom image formats."); ERR_FAIL_V(ERR_UNAVAILABLE); - } - int from_mm=1; + int from_mm = 1; if (p_keep_existing) { - from_mm=mipmaps+1; + from_mm = mipmaps + 1; } - int size = _get_dst_image_size(width,height,format,mipmaps,p_mipmaps); + int size = _get_dst_image_size(width, height, format, mipmaps, p_mipmaps); data.resize(size); - DVector::Write wp=data.write(); + DVector::Write wp = data.write(); - if (nearest_power_of_2(width)==uint32_t(width) && nearest_power_of_2(height)==uint32_t(height)) { + if (nearest_power_of_2(width) == uint32_t(width) && nearest_power_of_2(height) == uint32_t(height)) { //use fast code for powers of 2 - int prev_ofs=0; - int prev_h=height; - int prev_w=width; + int prev_ofs = 0; + int prev_h = height; + int prev_w = width; - for(int i=1;i= from_mm) { - if (i>=from_mm) { - - switch(format) { + switch (format) { case FORMAT_GRAYSCALE: - case FORMAT_INTENSITY: _generate_po2_mipmap<1>(&wp[prev_ofs], &wp[ofs], prev_w,prev_h); break; - case FORMAT_GRAYSCALE_ALPHA: _generate_po2_mipmap<2>(&wp[prev_ofs], &wp[ofs], prev_w,prev_h); break; - case FORMAT_RGB: _generate_po2_mipmap<3>(&wp[prev_ofs], &wp[ofs], prev_w,prev_h); break; - case FORMAT_RGBA: _generate_po2_mipmap<4>(&wp[prev_ofs], &wp[ofs], prev_w,prev_h); break; + case FORMAT_INTENSITY: _generate_po2_mipmap<1>(&wp[prev_ofs], &wp[ofs], prev_w, prev_h); break; + case FORMAT_GRAYSCALE_ALPHA: _generate_po2_mipmap<2>(&wp[prev_ofs], &wp[ofs], prev_w, prev_h); break; + case FORMAT_RGB: _generate_po2_mipmap<3>(&wp[prev_ofs], &wp[ofs], prev_w, prev_h); break; + case FORMAT_RGBA: _generate_po2_mipmap<4>(&wp[prev_ofs], &wp[ofs], prev_w, prev_h); break; default: {} } } - prev_ofs=ofs; - prev_w=w; - prev_h=h; + prev_ofs = ofs; + prev_w = w; + prev_h = h; } - } else { //use slow code.. //use bilinear filtered code for non powers of 2 - int prev_ofs=0; - int prev_h=height; - int prev_w=width; + int prev_ofs = 0; + int prev_h = height; + int prev_w = width; - for(int i=1;i= from_mm) { - if (i>=from_mm) { - - switch(format) { + switch (format) { case FORMAT_GRAYSCALE: - case FORMAT_INTENSITY: _scale_bilinear<1>(&wp[prev_ofs], &wp[ofs], prev_w,prev_h,w,h); break; - case FORMAT_GRAYSCALE_ALPHA: _scale_bilinear<2>(&wp[prev_ofs], &wp[ofs], prev_w,prev_h,w,h); break; - case FORMAT_RGB: _scale_bilinear<3>(&wp[prev_ofs], &wp[ofs], prev_w,prev_h,w,h); break; - case FORMAT_RGBA: _scale_bilinear<4>(&wp[prev_ofs], &wp[ofs], prev_w,prev_h,w,h); break; + case FORMAT_INTENSITY: _scale_bilinear<1>(&wp[prev_ofs], &wp[ofs], prev_w, prev_h, w, h); break; + case FORMAT_GRAYSCALE_ALPHA: _scale_bilinear<2>(&wp[prev_ofs], &wp[ofs], prev_w, prev_h, w, h); break; + case FORMAT_RGB: _scale_bilinear<3>(&wp[prev_ofs], &wp[ofs], prev_w, prev_h, w, h); break; + case FORMAT_RGBA: _scale_bilinear<4>(&wp[prev_ofs], &wp[ofs], prev_w, prev_h, w, h); break; default: {} } } - prev_ofs=ofs; - prev_w=w; - prev_h=h; + prev_ofs = ofs; + prev_w = w; + prev_h = h; } - } - - - return OK; } void Image::clear_mipmaps() { - if (mipmaps==0) + if (mipmaps == 0) return; - if (format==FORMAT_CUSTOM) { + if (format == FORMAT_CUSTOM) { ERR_EXPLAIN("Cannot clear mipmaps in indexed, compressed or custom image formats."); ERR_FAIL(); - } if (empty()) return; - int ofs,w,h; - _get_mipmap_offset_and_size(1,ofs,w,h); + int ofs, w, h; + _get_mipmap_offset_and_size(1, ofs, w, h); int palsize = get_format_pallete_size(format); DVector pallete; - ERR_FAIL_COND(ofs+palsize > data.size()); //bug? + ERR_FAIL_COND(ofs + palsize > data.size()); //bug? if (palsize) { pallete.resize(palsize); DVector::Read r = data.read(); DVector::Write w = pallete.write(); - copymem(&w[0],&r[data.size()-palsize],palsize); + copymem(&w[0], &r[data.size() - palsize], palsize); } - data.resize(ofs+palsize); + data.resize(ofs + palsize); if (palsize) { DVector::Read r = pallete.read(); DVector::Write w = data.write(); - copymem(&w[ofs],&r[0],palsize); + copymem(&w[ofs], &r[0], palsize); } - mipmaps=0; - + mipmaps = 0; } void Image::make_normalmap(float p_height_scale) { @@ -1137,9 +1075,9 @@ void Image::make_normalmap(float p_height_scale) { ERR_FAIL(); } - ERR_FAIL_COND( empty() ); + ERR_FAIL_COND(empty()); - Image normalmap(width,height,0, FORMAT_RGB); + Image normalmap(width, height, 0, FORMAT_RGB); /* for (int y=0;y Image::get_data() const { @@ -1173,55 +1111,50 @@ DVector Image::get_data() const { return data; } -void Image::create(int p_width, int p_height, bool p_use_mipmaps,Format p_format) { +void Image::create(int p_width, int p_height, bool p_use_mipmaps, Format p_format) { - - int mm=0; - int size = _get_dst_image_size(p_width,p_height,p_format,mm,p_use_mipmaps?-1:0); - data.resize( size ); + int mm = 0; + int size = _get_dst_image_size(p_width, p_height, p_format, mm, p_use_mipmaps ? -1 : 0); + data.resize(size); { - DVector::Write w= data.write(); - zeromem(w.ptr(),size); + DVector::Write w = data.write(); + zeromem(w.ptr(), size); } - width=p_width; - height=p_height; - mipmaps=mm; - format=p_format; - - + width = p_width; + height = p_height; + mipmaps = mm; + format = p_format; } -void Image::create(int p_width, int p_height, int p_mipmaps, Format p_format, const DVector& p_data) { +void Image::create(int p_width, int p_height, int p_mipmaps, Format p_format, const DVector &p_data) { - ERR_FAIL_INDEX(p_width-1,MAX_WIDTH); - ERR_FAIL_INDEX(p_height-1,MAX_HEIGHT); + ERR_FAIL_INDEX(p_width - 1, MAX_WIDTH); + ERR_FAIL_INDEX(p_height - 1, MAX_HEIGHT); if (p_format < FORMAT_CUSTOM) { int mm; - int size = _get_dst_image_size(p_width,p_height,p_format,mm,p_mipmaps); + int size = _get_dst_image_size(p_width, p_height, p_format, mm, p_mipmaps); - if (size!=p_data.size()) { - ERR_EXPLAIN("Expected data size of "+itos(size)+" in Image::create()"); - ERR_FAIL_COND(p_data.size()!=size); + if (size != p_data.size()) { + ERR_EXPLAIN("Expected data size of " + itos(size) + " in Image::create()"); + ERR_FAIL_COND(p_data.size() != size); } }; - height=p_height; - width=p_width; - format=p_format; - data=p_data; - mipmaps=p_mipmaps; + height = p_height; + width = p_width; + format = p_format; + data = p_data; + mipmaps = p_mipmaps; } +void Image::create(const char **p_xpm) { -void Image::create( const char ** p_xpm ) { - - - int size_width,size_height; - int pixelchars=0; - mipmaps=0; - bool has_alpha=false; + int size_width, size_height; + int pixelchars = 0; + mipmaps = 0; + bool has_alpha = false; enum Status { READING_HEADER, @@ -1231,124 +1164,120 @@ void Image::create( const char ** p_xpm ) { }; Status status = READING_HEADER; - int line=0; + int line = 0; - HashMap colormap; + HashMap colormap; int colormap_size; - while (status!=DONE) { - - const char * line_ptr = p_xpm[line]; + while (status != DONE) { + const char *line_ptr = p_xpm[line]; switch (status) { - case READING_HEADER: { + case READING_HEADER: { - String line_str=line_ptr; - line_str.replace("\t"," "); + String line_str = line_ptr; + line_str.replace("\t", " "); - size_width=line_str.get_slicec(' ',0).to_int(); - size_height=line_str.get_slicec(' ',1).to_int(); - colormap_size=line_str.get_slicec(' ',2).to_int(); - pixelchars=line_str.get_slicec(' ',3).to_int(); - ERR_FAIL_COND(colormap_size > 32766); - ERR_FAIL_COND(pixelchars > 5); - ERR_FAIL_COND(size_width > 32767); - ERR_FAIL_COND(size_height > 32767); - status=READING_COLORS; - } break; - case READING_COLORS: { + size_width = line_str.get_slicec(' ', 0).to_int(); + size_height = line_str.get_slicec(' ', 1).to_int(); + colormap_size = line_str.get_slicec(' ', 2).to_int(); + pixelchars = line_str.get_slicec(' ', 3).to_int(); + ERR_FAIL_COND(colormap_size > 32766); + ERR_FAIL_COND(pixelchars > 5); + ERR_FAIL_COND(size_width > 32767); + ERR_FAIL_COND(size_height > 32767); + status = READING_COLORS; + } break; + case READING_COLORS: { - String colorstring; - for (int i=0;i='0' && v<='9') - v-='0'; - else if (v>='A' && v<='F') - v=(v-'A')+10; - else if (v>='a' && v<='f') - v=(v-'a')+10; - else + while (*line_ptr == ' ' || *line_ptr == '\t' || *line_ptr == 0) { + if (*line_ptr == 0) break; - - switch(i) { - case 0: col_r=v<<4; break; - case 1: col_r|=v; break; - case 2: col_g=v<<4; break; - case 3: col_g|=v; break; - case 4: col_b=v<<4; break; - case 5: col_b|=v; break; - }; - + line_ptr++; } - // magenta mask - if (col_r==255 && col_g==0 && col_b==255) { + if (*line_ptr == '#') { + line_ptr++; + uint8_t col_r; + uint8_t col_g; + uint8_t col_b; + // uint8_t col_a=255; - colormap[colorstring]=Color(0,0,0,0); - has_alpha=true; - } else { + for (int i = 0; i < 6; i++) { - colormap[colorstring]=Color(col_r/255.0,col_g/255.0,col_b/255.0,1.0); + char v = line_ptr[i]; + + if (v >= '0' && v <= '9') + v -= '0'; + else if (v >= 'A' && v <= 'F') + v = (v - 'A') + 10; + else if (v >= 'a' && v <= 'f') + v = (v - 'a') + 10; + else + break; + + switch (i) { + case 0: col_r = v << 4; break; + case 1: col_r |= v; break; + case 2: col_g = v << 4; break; + case 3: col_g |= v; break; + case 4: col_b = v << 4; break; + case 5: col_b |= v; break; + }; + } + + // magenta mask + if (col_r == 255 && col_g == 0 && col_b == 255) { + + colormap[colorstring] = Color(0, 0, 0, 0); + has_alpha = true; + } else { + + colormap[colorstring] = Color(col_r / 255.0, col_g / 255.0, col_b / 255.0, 1.0); + } } - } - } - if (line==colormap_size) { + if (line == colormap_size) { - status=READING_PIXELS; - create(size_width,size_height,0,has_alpha?FORMAT_RGBA:FORMAT_RGB); - } - } break; - case READING_PIXELS: { + status = READING_PIXELS; + create(size_width, size_height, 0, has_alpha ? FORMAT_RGBA : FORMAT_RGB); + } + } break; + case READING_PIXELS: { - int y=line-colormap_size-1; - for (int x=0;x0) {\ - \ - detected=true;\ - break;\ - }\ -} +#define DETECT_ALPHA(m_value) \ + { \ + uint8_t value = m_value; \ + if (value < DETECT_ALPHA_MIN_TRESHOLD) \ + bit = true; \ + else if (value < DETECT_ALPHA_MAX_TRESHOLD) { \ + \ + detected = true; \ + break; \ + } \ + } +#define DETECT_NON_ALPHA(m_value) \ + { \ + uint8_t value = m_value; \ + if (value > 0) { \ + \ + detected = true; \ + break; \ + } \ + } bool Image::is_invisible() const { - if (format==FORMAT_GRAYSCALE || - format==FORMAT_RGB || - format==FORMAT_INDEXED) + if (format == FORMAT_GRAYSCALE || + format == FORMAT_RGB || + format == FORMAT_INDEXED) return false; int len = data.size(); - if (len==0) + if (len == 0) return true; if (format >= FORMAT_YUV_422 && format <= FORMAT_YUV_444) return false; - int w,h; - _get_mipmap_offset_and_size(1,len,w,h); + int w, h; + _get_mipmap_offset_and_size(1, len, w, h); DVector::Read r = data.read(); - const unsigned char *data_ptr=r.ptr(); + const unsigned char *data_ptr = r.ptr(); - bool detected=false; + bool detected = false; - switch(format) { + switch (format) { case FORMAT_INTENSITY: { - for(int i=0;i>1);i++) { - DETECT_NON_ALPHA(data_ptr[(i<<1)+1]); + for (int i = 0; i < (len >> 1); i++) { + DETECT_NON_ALPHA(data_ptr[(i << 1) + 1]); } } break; case FORMAT_RGBA: { - for(int i=0;i<(len>>2);i++) { - DETECT_NON_ALPHA(data_ptr[(i<<2)+3]) + for (int i = 0; i < (len >> 2); i++) { + DETECT_NON_ALPHA(data_ptr[(i << 2) + 3]) } } break; @@ -1437,7 +1364,7 @@ bool Image::is_invisible() const { case FORMAT_PVRTC4_ALPHA: case FORMAT_BC2: case FORMAT_BC3: { - detected=true; + detected = true; } break; default: {} } @@ -1447,47 +1374,46 @@ bool Image::is_invisible() const { Image::AlphaMode Image::detect_alpha() const { - if (format==FORMAT_GRAYSCALE || - format==FORMAT_RGB || - format==FORMAT_INDEXED) + if (format == FORMAT_GRAYSCALE || + format == FORMAT_RGB || + format == FORMAT_INDEXED) return ALPHA_NONE; int len = data.size(); - if (len==0) + if (len == 0) return ALPHA_NONE; if (format >= FORMAT_YUV_422 && format <= FORMAT_YUV_444) return ALPHA_NONE; - int w,h; - _get_mipmap_offset_and_size(1,len,w,h); + int w, h; + _get_mipmap_offset_and_size(1, len, w, h); DVector::Read r = data.read(); - const unsigned char *data_ptr=r.ptr(); + const unsigned char *data_ptr = r.ptr(); - bool bit=false; - bool detected=false; + bool bit = false; + bool detected = false; - switch(format) { + switch (format) { case FORMAT_INTENSITY: { - for(int i=0;i>1);i++) { - DETECT_ALPHA(data_ptr[(i<<1)+1]); + for (int i = 0; i < (len >> 1); i++) { + DETECT_ALPHA(data_ptr[(i << 1) + 1]); } } break; case FORMAT_RGBA: { - for(int i=0;i<(len>>2);i++) { - DETECT_ALPHA(data_ptr[(i<<2)+3]) + for (int i = 0; i < (len >> 2); i++) { + DETECT_ALPHA(data_ptr[(i << 2) + 3]) } } break; @@ -1503,7 +1429,7 @@ Image::AlphaMode Image::detect_alpha() const { case FORMAT_PVRTC4_ALPHA: case FORMAT_BC2: case FORMAT_BC3: { - detected=true; + detected = true; } break; default: {} } @@ -1514,15 +1440,14 @@ Image::AlphaMode Image::detect_alpha() const { return ALPHA_BIT; else return ALPHA_NONE; - } -Error Image::load(const String& p_path) { +Error Image::load(const String &p_path) { return ImageLoader::load_image(p_path, this); } -Error Image::save_png(const String& p_path) { +Error Image::save_png(const String &p_path) { if (save_png_func == NULL) return ERR_UNAVAILABLE; @@ -1530,7 +1455,7 @@ Error Image::save_png(const String& p_path) { return save_png_func(p_path, *this); }; -bool Image::operator==(const Image& p_image) const { +bool Image::operator==(const Image &p_image) const { if (data.size() == 0 && p_image.data.size() == 0) return true; @@ -1540,10 +1465,9 @@ bool Image::operator==(const Image& p_image) const { return r.ptr() == pr.ptr(); } - int Image::get_format_pixel_size(Format p_format) { - switch(p_format) { + switch (p_format) { case FORMAT_GRAYSCALE: { return 1; @@ -1611,82 +1535,76 @@ int Image::get_format_pixel_size(Format p_format) { ERR_EXPLAIN("pixel size requested for custom image format, and it's unknown obviously"); ERR_FAIL_V(1); } break; - default:{ + default: { ERR_EXPLAIN("Cannot obtain pixel size from this format"); ERR_FAIL_V(1); - } } return 0; } -int Image::get_image_data_size(int p_width, int p_height, Format p_format,int p_mipmaps) { +int Image::get_image_data_size(int p_width, int p_height, Format p_format, int p_mipmaps) { int mm; - return _get_dst_image_size(p_width,p_height,p_format,mm,p_mipmaps); - + return _get_dst_image_size(p_width, p_height, p_format, mm, p_mipmaps); } int Image::get_image_required_mipmaps(int p_width, int p_height, Format p_format) { int mm; - _get_dst_image_size(p_width,p_height,p_format,mm,-1); + _get_dst_image_size(p_width, p_height, p_format, mm, -1); return mm; - } -void Image::_get_format_min_data_size(Format p_format,int &r_w, int &r_h) { +void Image::_get_format_min_data_size(Format p_format, int &r_w, int &r_h) { - - switch(p_format) { + switch (p_format) { case FORMAT_BC1: case FORMAT_BC2: case FORMAT_BC3: case FORMAT_BC4: case FORMAT_BC5: { - r_w=4; - r_h=4; + r_w = 4; + r_h = 4; } break; case FORMAT_PVRTC2: case FORMAT_PVRTC2_ALPHA: { - r_w=16; - r_h=8; + r_w = 16; + r_h = 8; } break; case FORMAT_PVRTC4_ALPHA: case FORMAT_PVRTC4: { - r_w=8; - r_h=8; + r_w = 8; + r_h = 8; } break; case FORMAT_ATC: case FORMAT_ATC_ALPHA_EXPLICIT: case FORMAT_ATC_ALPHA_INTERPOLATED: { - r_w=8; - r_h=8; + r_w = 8; + r_h = 8; } break; case FORMAT_ETC: { - r_w=4; - r_h=4; + r_w = 4; + r_h = 4; } break; default: { - r_w=1; - r_h=1; + r_w = 1; + r_h = 1; } break; } - } - int Image::get_format_pixel_rshift(Format p_format) { - if (p_format==FORMAT_BC1 || p_format==FORMAT_BC4 || p_format==FORMAT_ATC || p_format==FORMAT_PVRTC4 || p_format==FORMAT_PVRTC4_ALPHA || p_format==FORMAT_ETC) + if (p_format == FORMAT_BC1 || p_format == FORMAT_BC4 || p_format == FORMAT_ATC || p_format == FORMAT_PVRTC4 || p_format == FORMAT_PVRTC4_ALPHA || p_format == FORMAT_ETC) return 1; - else if (p_format==FORMAT_PVRTC2 || p_format==FORMAT_PVRTC2_ALPHA) + else if (p_format == FORMAT_PVRTC2 || p_format == FORMAT_PVRTC2_ALPHA) return 2; else return 0; @@ -1694,7 +1612,7 @@ int Image::get_format_pixel_rshift(Format p_format) { int Image::get_format_pallete_size(Format p_format) { - switch(p_format) { + switch (p_format) { case FORMAT_GRAYSCALE: { return 0; @@ -1717,35 +1635,31 @@ int Image::get_format_pallete_size(Format p_format) { } break; case FORMAT_INDEXED: { - return 3*256; + return 3 * 256; } break; case FORMAT_INDEXED_ALPHA: { - return 4*256; + return 4 * 256; } break; - default:{} + default: {} } return 0; } - - - Error Image::_decompress_bc() { print_line("decompressing bc"); - int wd=width,ht=height; - if (wd%4!=0) { - wd+=4-(wd%4); + int wd = width, ht = height; + if (wd % 4 != 0) { + wd += 4 - (wd % 4); } - if (ht%4!=0) { - ht+=4-(ht%4); + if (ht % 4 != 0) { + ht += 4 - (ht % 4); } - int mm; - int size = _get_dst_image_size(wd,ht,FORMAT_RGBA,mm,mipmaps); + int size = _get_dst_image_size(wd, ht, FORMAT_RGBA, mm, mipmaps); DVector newdata; newdata.resize(size); @@ -1753,352 +1667,333 @@ Error Image::_decompress_bc() { DVector::Write w = newdata.write(); DVector::Read r = data.read(); - int rofs=0; - int wofs=0; + int rofs = 0; + int wofs = 0; //print_line("width: "+itos(wd)+" height: "+itos(ht)); - for(int i=0;i<=mm;i++) { + for (int i = 0; i <= mm; i++) { - switch(format) { + switch (format) { case FORMAT_BC1: { - int len = (wd*ht)/16; - uint8_t* dst=&w[wofs]; + int len = (wd * ht) / 16; + uint8_t *dst = &w[wofs]; uint32_t ofs_table[16]; - for(int x=0;x<4;x++) { + for (int x = 0; x < 4; x++) { - for(int y=0;y<4;y++) { + for (int y = 0; y < 4; y++) { - ofs_table[15-(y*4+(3-x))]=(x+y*wd)*4; + ofs_table[15 - (y * 4 + (3 - x))] = (x + y * wd) * 4; } } + for (int j = 0; j < len; j++) { - for(int j=0;j>11)<<3, ((col_a>>5)&0x3f)<<2, ((col_a)&0x1f)<<3, 255 }, - { (col_b>>11)<<3, ((col_b>>5)&0x3f)<<2, ((col_b)&0x1f)<<3, 255 }, - {0,0,0,255}, - {0,0,0,255} + uint8_t table[4][4] = { + { (col_a >> 11) << 3, ((col_a >> 5) & 0x3f) << 2, ((col_a)&0x1f) << 3, 255 }, + { (col_b >> 11) << 3, ((col_b >> 5) & 0x3f) << 2, ((col_b)&0x1f) << 3, 255 }, + { 0, 0, 0, 255 }, + { 0, 0, 0, 255 } }; - if (col_a>1; - table[2][1]=(int(table[0][1])+int(table[1][1]))>>1; - table[2][2]=(int(table[0][2])+int(table[1][2]))>>1; - table[3][3]=0; //premul alpha black + table[2][0] = (int(table[0][0]) + int(table[1][0])) >> 1; + table[2][1] = (int(table[0][1]) + int(table[1][1])) >> 1; + table[2][2] = (int(table[0][2]) + int(table[1][2])) >> 1; + table[3][3] = 0; //premul alpha black } else { //gradient - table[2][0]=(int(table[0][0])*2+int(table[1][0]))/3; - table[2][1]=(int(table[0][1])*2+int(table[1][1]))/3; - table[2][2]=(int(table[0][2])*2+int(table[1][2]))/3; - table[3][0]=(int(table[0][0])+int(table[1][0])*2)/3; - table[3][1]=(int(table[0][1])+int(table[1][1])*2)/3; - table[3][2]=(int(table[0][2])+int(table[1][2])*2)/3; + table[2][0] = (int(table[0][0]) * 2 + int(table[1][0])) / 3; + table[2][1] = (int(table[0][1]) * 2 + int(table[1][1])) / 3; + table[2][2] = (int(table[0][2]) * 2 + int(table[1][2])) / 3; + table[3][0] = (int(table[0][0]) + int(table[1][0]) * 2) / 3; + table[3][1] = (int(table[0][1]) + int(table[1][1]) * 2) / 3; + table[3][2] = (int(table[0][2]) + int(table[1][2]) * 2) / 3; } - uint32_t block=src[4]; - block<<=8; - block|=src[5]; - block<<=8; - block|=src[6]; - block<<=8; - block|=src[7]; + uint32_t block = src[4]; + block <<= 8; + block |= src[5]; + block <<= 8; + block |= src[6]; + block <<= 8; + block |= src[7]; - int y = (j/(wd/4))*4; - int x = (j%(wd/4))*4; - int pixofs = (y*wd+x)*4; + int y = (j / (wd / 4)) * 4; + int x = (j % (wd / 4)) * 4; + int pixofs = (y * wd + x) * 4; - for(int k=0;k<16;k++) { - int idx = pixofs+ofs_table[k]; - dst[idx+0]=table[block&0x3][0]; - dst[idx+1]=table[block&0x3][1]; - dst[idx+2]=table[block&0x3][2]; - dst[idx+3]=table[block&0x3][3]; - block>>=2; + for (int k = 0; k < 16; k++) { + int idx = pixofs + ofs_table[k]; + dst[idx + 0] = table[block & 0x3][0]; + dst[idx + 1] = table[block & 0x3][1]; + dst[idx + 2] = table[block & 0x3][2]; + dst[idx + 3] = table[block & 0x3][3]; + block >>= 2; } - } - rofs+=len*8; - wofs+=wd*ht*4; + rofs += len * 8; + wofs += wd * ht * 4; - - wd/=2; - ht/=2; + wd /= 2; + ht /= 2; } break; case FORMAT_BC2: { - int len = (wd*ht)/16; - uint8_t* dst=&w[wofs]; + int len = (wd * ht) / 16; + uint8_t *dst = &w[wofs]; uint32_t ofs_table[16]; - for(int x=0;x<4;x++) { + for (int x = 0; x < 4; x++) { - for(int y=0;y<4;y++) { + for (int y = 0; y < 4; y++) { - ofs_table[15-(y*4+(3-x))]=(x+y*wd)*4; + ofs_table[15 - (y * 4 + (3 - x))] = (x + y * wd) * 4; } } + for (int j = 0; j < len; j++) { - for(int j=0;j>11)<<3, ((col_a>>5)&0x3f)<<2, ((col_a)&0x1f)<<3, 255 }, - { (col_b>>11)<<3, ((col_b>>5)&0x3f)<<2, ((col_b)&0x1f)<<3, 255 }, - {0,0,0,255}, - {0,0,0,255} + uint8_t table[4][4] = { + { (col_a >> 11) << 3, ((col_a >> 5) & 0x3f) << 2, ((col_a)&0x1f) << 3, 255 }, + { (col_b >> 11) << 3, ((col_b >> 5) & 0x3f) << 2, ((col_b)&0x1f) << 3, 255 }, + { 0, 0, 0, 255 }, + { 0, 0, 0, 255 } }; //always gradient - table[2][0]=(int(table[0][0])*2+int(table[1][0]))/3; - table[2][1]=(int(table[0][1])*2+int(table[1][1]))/3; - table[2][2]=(int(table[0][2])*2+int(table[1][2]))/3; - table[3][0]=(int(table[0][0])+int(table[1][0])*2)/3; - table[3][1]=(int(table[0][1])+int(table[1][1])*2)/3; - table[3][2]=(int(table[0][2])+int(table[1][2])*2)/3; + table[2][0] = (int(table[0][0]) * 2 + int(table[1][0])) / 3; + table[2][1] = (int(table[0][1]) * 2 + int(table[1][1])) / 3; + table[2][2] = (int(table[0][2]) * 2 + int(table[1][2])) / 3; + table[3][0] = (int(table[0][0]) + int(table[1][0]) * 2) / 3; + table[3][1] = (int(table[0][1]) + int(table[1][1]) * 2) / 3; + table[3][2] = (int(table[0][2]) + int(table[1][2]) * 2) / 3; - uint32_t block=src[4+8]; - block<<=8; - block|=src[5+8]; - block<<=8; - block|=src[6+8]; - block<<=8; - block|=src[7+8]; + uint32_t block = src[4 + 8]; + block <<= 8; + block |= src[5 + 8]; + block <<= 8; + block |= src[6 + 8]; + block <<= 8; + block |= src[7 + 8]; - int y = (j/(wd/4))*4; - int x = (j%(wd/4))*4; - int pixofs = (y*wd+x)*4; + int y = (j / (wd / 4)) * 4; + int x = (j % (wd / 4)) * 4; + int pixofs = (y * wd + x) * 4; - for(int k=0;k<16;k++) { - uint8_t alpha = ablock&0xf; - alpha=int(alpha)*255/15; //right way for alpha - int idx = pixofs+ofs_table[k]; - dst[idx+0]=table[block&0x3][0]; - dst[idx+1]=table[block&0x3][1]; - dst[idx+2]=table[block&0x3][2]; - dst[idx+3]=alpha; - block>>=2; - ablock>>=4; + for (int k = 0; k < 16; k++) { + uint8_t alpha = ablock & 0xf; + alpha = int(alpha) * 255 / 15; //right way for alpha + int idx = pixofs + ofs_table[k]; + dst[idx + 0] = table[block & 0x3][0]; + dst[idx + 1] = table[block & 0x3][1]; + dst[idx + 2] = table[block & 0x3][2]; + dst[idx + 3] = alpha; + block >>= 2; + ablock >>= 4; } - } - rofs+=len*16; - wofs+=wd*ht*4; + rofs += len * 16; + wofs += wd * ht * 4; - - wd/=2; - ht/=2; + wd /= 2; + ht /= 2; } break; case FORMAT_BC3: { - int len = (wd*ht)/16; - uint8_t* dst=&w[wofs]; + int len = (wd * ht) / 16; + uint8_t *dst = &w[wofs]; uint32_t ofs_table[16]; - for(int x=0;x<4;x++) { + for (int x = 0; x < 4; x++) { - for(int y=0;y<4;y++) { + for (int y = 0; y < 4; y++) { - ofs_table[15-(y*4+(3-x))]=(x+y*wd)*4; + ofs_table[15 - (y * 4 + (3 - x))] = (x + y * wd) * 4; } } + for (int j = 0; j < len; j++) { + const uint8_t *src = &r[rofs + j * 16]; - for(int j=0;ja_end) { + if (a_start > a_end) { - atable[0]=(int(a_start)*7+int(a_end)*0)/7; - atable[1]=(int(a_start)*6+int(a_end)*1)/7; - atable[2]=(int(a_start)*5+int(a_end)*2)/7; - atable[3]=(int(a_start)*4+int(a_end)*3)/7; - atable[4]=(int(a_start)*3+int(a_end)*4)/7; - atable[5]=(int(a_start)*2+int(a_end)*5)/7; - atable[6]=(int(a_start)*1+int(a_end)*6)/7; - atable[7]=(int(a_start)*0+int(a_end)*7)/7; + atable[0] = (int(a_start) * 7 + int(a_end) * 0) / 7; + atable[1] = (int(a_start) * 6 + int(a_end) * 1) / 7; + atable[2] = (int(a_start) * 5 + int(a_end) * 2) / 7; + atable[3] = (int(a_start) * 4 + int(a_end) * 3) / 7; + atable[4] = (int(a_start) * 3 + int(a_end) * 4) / 7; + atable[5] = (int(a_start) * 2 + int(a_end) * 5) / 7; + atable[6] = (int(a_start) * 1 + int(a_end) * 6) / 7; + atable[7] = (int(a_start) * 0 + int(a_end) * 7) / 7; } else { - atable[0]=(int(a_start)*5+int(a_end)*0)/5; - atable[1]=(int(a_start)*4+int(a_end)*1)/5; - atable[2]=(int(a_start)*3+int(a_end)*2)/5; - atable[3]=(int(a_start)*2+int(a_end)*3)/5; - atable[4]=(int(a_start)*1+int(a_end)*4)/5; - atable[5]=(int(a_start)*0+int(a_end)*5)/5; - atable[6]=0; - atable[7]=255; - + atable[0] = (int(a_start) * 5 + int(a_end) * 0) / 5; + atable[1] = (int(a_start) * 4 + int(a_end) * 1) / 5; + atable[2] = (int(a_start) * 3 + int(a_end) * 2) / 5; + atable[3] = (int(a_start) * 2 + int(a_end) * 3) / 5; + atable[4] = (int(a_start) * 1 + int(a_end) * 4) / 5; + atable[5] = (int(a_start) * 0 + int(a_end) * 5) / 5; + atable[6] = 0; + atable[7] = 255; } + uint16_t col_a = src[8 + 1]; + col_a <<= 8; + col_a |= src[8 + 0]; + uint16_t col_b = src[8 + 3]; + col_b <<= 8; + col_b |= src[8 + 2]; - uint16_t col_a=src[8+1]; - col_a<<=8; - col_a|=src[8+0]; - uint16_t col_b=src[8+3]; - col_b<<=8; - col_b|=src[8+2]; - - uint8_t table[4][4]={ - { (col_a>>11)<<3, ((col_a>>5)&0x3f)<<2, ((col_a)&0x1f)<<3, 255 }, - { (col_b>>11)<<3, ((col_b>>5)&0x3f)<<2, ((col_b)&0x1f)<<3, 255 }, - {0,0,0,255}, - {0,0,0,255} + uint8_t table[4][4] = { + { (col_a >> 11) << 3, ((col_a >> 5) & 0x3f) << 2, ((col_a)&0x1f) << 3, 255 }, + { (col_b >> 11) << 3, ((col_b >> 5) & 0x3f) << 2, ((col_b)&0x1f) << 3, 255 }, + { 0, 0, 0, 255 }, + { 0, 0, 0, 255 } }; //always gradient - table[2][0]=(int(table[0][0])*2+int(table[1][0]))/3; - table[2][1]=(int(table[0][1])*2+int(table[1][1]))/3; - table[2][2]=(int(table[0][2])*2+int(table[1][2]))/3; - table[3][0]=(int(table[0][0])+int(table[1][0])*2)/3; - table[3][1]=(int(table[0][1])+int(table[1][1])*2)/3; - table[3][2]=(int(table[0][2])+int(table[1][2])*2)/3; + table[2][0] = (int(table[0][0]) * 2 + int(table[1][0])) / 3; + table[2][1] = (int(table[0][1]) * 2 + int(table[1][1])) / 3; + table[2][2] = (int(table[0][2]) * 2 + int(table[1][2])) / 3; + table[3][0] = (int(table[0][0]) + int(table[1][0]) * 2) / 3; + table[3][1] = (int(table[0][1]) + int(table[1][1]) * 2) / 3; + table[3][2] = (int(table[0][2]) + int(table[1][2]) * 2) / 3; + uint32_t block = src[4 + 8]; + block <<= 8; + block |= src[5 + 8]; + block <<= 8; + block |= src[6 + 8]; + block <<= 8; + block |= src[7 + 8]; - uint32_t block=src[4+8]; - block<<=8; - block|=src[5+8]; - block<<=8; - block|=src[6+8]; - block<<=8; - block|=src[7+8]; + int y = (j / (wd / 4)) * 4; + int x = (j % (wd / 4)) * 4; + int pixofs = (y * wd + x) * 4; - int y = (j/(wd/4))*4; - int x = (j%(wd/4))*4; - int pixofs = (y*wd+x)*4; - - - - for(int k=0;k<16;k++) { - uint8_t alpha = ablock&0x7; - int idx = pixofs+ofs_table[k]; - dst[idx+0]=table[block&0x3][0]; - dst[idx+1]=table[block&0x3][1]; - dst[idx+2]=table[block&0x3][2]; - dst[idx+3]=atable[alpha]; - block>>=2; - ablock>>=3; + for (int k = 0; k < 16; k++) { + uint8_t alpha = ablock & 0x7; + int idx = pixofs + ofs_table[k]; + dst[idx + 0] = table[block & 0x3][0]; + dst[idx + 1] = table[block & 0x3][1]; + dst[idx + 2] = table[block & 0x3][2]; + dst[idx + 3] = atable[alpha]; + block >>= 2; + ablock >>= 3; } - } - rofs+=len*16; - wofs+=wd*ht*4; + rofs += len * 16; + wofs += wd * ht * 4; - - wd/=2; - ht/=2; + wd /= 2; + ht /= 2; } break; } - } - w=DVector::Write(); - r=DVector::Read(); + w = DVector::Write(); + r = DVector::Read(); - data=newdata; - format=FORMAT_RGBA; - if (wd!=width || ht!=height) { + data = newdata; + format = FORMAT_RGBA; + if (wd != width || ht != height) { //todo, crop - width=wd; - height=ht; + width = wd; + height = ht; } return OK; } bool Image::is_compressed() const { - return format>=FORMAT_BC1; + return format >= FORMAT_BC1; } - Image Image::decompressed() const { - Image img=*this; + Image img = *this; img.decompress(); return img; } Error Image::decompress() { - if (format>=FORMAT_BC1 && format<=FORMAT_BC5 ) - _decompress_bc();//_image_decompress_bc(this); - else if (format>=FORMAT_PVRTC2 && format<=FORMAT_PVRTC4_ALPHA && _image_decompress_pvrtc) + if (format >= FORMAT_BC1 && format <= FORMAT_BC5) + _decompress_bc(); //_image_decompress_bc(this); + else if (format >= FORMAT_PVRTC2 && format <= FORMAT_PVRTC4_ALPHA && _image_decompress_pvrtc) _image_decompress_pvrtc(this); - else if (format==FORMAT_ETC && _image_decompress_etc) + else if (format == FORMAT_ETC && _image_decompress_etc) _image_decompress_etc(this); else return ERR_UNAVAILABLE; return OK; } - Error Image::compress(CompressMode p_mode) { - switch(p_mode) { + switch (p_mode) { case COMPRESS_BC: { @@ -2122,7 +2017,6 @@ Error Image::compress(CompressMode p_mode) { } break; } - return OK; } @@ -2136,89 +2030,83 @@ Image Image::compressed(int p_mode) { Image::Image(const char **p_xpm) { - width=0; - height=0; - mipmaps=0; - format=FORMAT_GRAYSCALE; + width = 0; + height = 0; + mipmaps = 0; + format = FORMAT_GRAYSCALE; create(p_xpm); } +Image::Image(int p_width, int p_height, bool p_use_mipmaps, Format p_format) { -Image::Image(int p_width, int p_height,bool p_use_mipmaps, Format p_format) { - - width=0; - height=0; - mipmaps=0; - format=FORMAT_GRAYSCALE; - - create(p_width,p_height,p_use_mipmaps,p_format); + width = 0; + height = 0; + mipmaps = 0; + format = FORMAT_GRAYSCALE; + create(p_width, p_height, p_use_mipmaps, p_format); } -Image::Image(int p_width, int p_height, int p_mipmaps, Format p_format, const DVector& p_data) { +Image::Image(int p_width, int p_height, int p_mipmaps, Format p_format, const DVector &p_data) { - width=0; - height=0; - mipmaps=0; - format=FORMAT_GRAYSCALE; - - create(p_width,p_height,p_mipmaps,p_format,p_data); + width = 0; + height = 0; + mipmaps = 0; + format = FORMAT_GRAYSCALE; + create(p_width, p_height, p_mipmaps, p_format, p_data); } - -Image Image::brushed(const Image& p_src, const Image& p_brush, const Point2& p_dest) const { +Image Image::brushed(const Image &p_src, const Image &p_brush, const Point2 &p_dest) const { Image img = *this; - img.brush_transfer(p_src,p_brush,p_dest); + img.brush_transfer(p_src, p_brush, p_dest); return img; } Rect2 Image::get_used_rect() const { - if (format==FORMAT_GRAYSCALE || - format==FORMAT_RGB || - format==FORMAT_INDEXED || format>FORMAT_INDEXED_ALPHA) - return Rect2(Point2(),Size2(width,height)); + if (format == FORMAT_GRAYSCALE || + format == FORMAT_RGB || + format == FORMAT_INDEXED || format > FORMAT_INDEXED_ALPHA) + return Rect2(Point2(), Size2(width, height)); int len = data.size(); - if (len==0) + if (len == 0) return Rect2(); int data_size = len; DVector::Read r = data.read(); - const unsigned char *rptr=r.ptr(); + const unsigned char *rptr = r.ptr(); - int minx=0xFFFFFF,miny=0xFFFFFFF; - int maxx=-1,maxy=-1; - for(int i=0;i2; + bool opaque = _get_pixel(i, j, rptr, data_size).a > 2; if (!opaque) continue; - if (i>maxx) - maxx=i; - if (j>maxy) - maxy=j; - if (i maxx) + maxx = i; + if (j > maxy) + maxy = j; + if (i < minx) + minx = i; + if (j < miny) + miny = j; } } - if (maxx==-1) + if (maxx == -1) return Rect2(); else - return Rect2(minx,miny,maxx-minx+1,maxy-miny+1); - + return Rect2(minx, miny, maxx - minx + 1, maxy - miny + 1); } - -Image Image::get_rect(const Rect2& p_area) const { +Image Image::get_rect(const Rect2 &p_area) const { Image img(p_area.size.x, p_area.size.y, mipmaps, format); img.blit_rect(*this, p_area, Point2(0, 0)); @@ -2226,143 +2114,134 @@ Image Image::get_rect(const Rect2& p_area) const { return img; }; -void Image::brush_transfer(const Image& p_src, const Image& p_brush, const Point2& p_dest) { +void Image::brush_transfer(const Image &p_src, const Image &p_brush, const Point2 &p_dest) { - - ERR_FAIL_COND( width != p_src.width || height !=p_src.height); + ERR_FAIL_COND(width != p_src.width || height != p_src.height); int dst_data_size = data.size(); DVector::Write wp = data.write(); - unsigned char *dst_data_ptr=wp.ptr(); - + unsigned char *dst_data_ptr = wp.ptr(); int src_data_size = p_src.data.size(); DVector::Read rp = p_src.data.read(); - const unsigned char *src_data_ptr=rp.ptr(); + const unsigned char *src_data_ptr = rp.ptr(); int brush_data_size = p_brush.data.size(); DVector::Read bp = p_brush.data.read(); - const unsigned char *src_brush_ptr=bp.ptr(); + const unsigned char *src_brush_ptr = bp.ptr(); int bw = p_brush.get_width(); int bh = p_brush.get_height(); - int dx=p_dest.x; - int dy=p_dest.y; + int dx = p_dest.x; + int dy = p_dest.y; - for(int i=dy;i= height) + if (i < 0 || i >= height) continue; - for(int j=dx;j=width) + if (j < 0 || j >= width) continue; - BColor src = p_src._get_pixel(j,i,src_data_ptr,src_data_size); - BColor dst = _get_pixel(j,i,dst_data_ptr,dst_data_size); - BColor brush = p_brush._get_pixel(j-dx,i-dy,src_brush_ptr,brush_data_size); + BColor src = p_src._get_pixel(j, i, src_data_ptr, src_data_size); + BColor dst = _get_pixel(j, i, dst_data_ptr, dst_data_size); + BColor brush = p_brush._get_pixel(j - dx, i - dy, src_brush_ptr, brush_data_size); uint32_t mult = brush.r; - dst.r = dst.r + (((int32_t(src.r)-int32_t(dst.r))*mult)>>8); - dst.g = dst.g + (((int32_t(src.g)-int32_t(dst.g))*mult)>>8); - dst.b = dst.b + (((int32_t(src.b)-int32_t(dst.b))*mult)>>8); - dst.a = dst.a + (((int32_t(src.a)-int32_t(dst.a))*mult)>>8); - _put_pixel(j,i,dst,dst_data_ptr); + dst.r = dst.r + (((int32_t(src.r) - int32_t(dst.r)) * mult) >> 8); + dst.g = dst.g + (((int32_t(src.g) - int32_t(dst.g)) * mult) >> 8); + dst.b = dst.b + (((int32_t(src.b) - int32_t(dst.b)) * mult) >> 8); + dst.a = dst.a + (((int32_t(src.a) - int32_t(dst.a)) * mult) >> 8); + _put_pixel(j, i, dst, dst_data_ptr); } } } +void Image::blit_rect(const Image &p_src, const Rect2 &p_src_rect, const Point2 &p_dest) { -void Image::blit_rect(const Image& p_src, const Rect2& p_src_rect,const Point2& p_dest) { + int dsize = data.size(); + int srcdsize = p_src.data.size(); + ERR_FAIL_COND(dsize == 0); + ERR_FAIL_COND(srcdsize == 0); - int dsize=data.size(); - int srcdsize=p_src.data.size(); - ERR_FAIL_COND( dsize==0 ); - ERR_FAIL_COND( srcdsize==0 ); - - - - Rect2 rrect = Rect2(0,0,p_src.width,p_src.height).clip(p_src_rect); + Rect2 rrect = Rect2(0, 0, p_src.width, p_src.height).clip(p_src_rect); DVector::Write wp = data.write(); - unsigned char *dst_data_ptr=wp.ptr(); + unsigned char *dst_data_ptr = wp.ptr(); DVector::Read rp = p_src.data.read(); - const unsigned char *src_data_ptr=rp.ptr(); + const unsigned char *src_data_ptr = rp.ptr(); - if ((format==FORMAT_INDEXED || format == FORMAT_INDEXED_ALPHA) && (p_src.format==FORMAT_INDEXED || p_src.format == FORMAT_INDEXED_ALPHA)) { + if ((format == FORMAT_INDEXED || format == FORMAT_INDEXED_ALPHA) && (p_src.format == FORMAT_INDEXED || p_src.format == FORMAT_INDEXED_ALPHA)) { Point2i desti(p_dest.x, p_dest.y); Point2i srci(rrect.pos.x, rrect.pos.y); - for(int i=0;i= height) + if (i < 0 || i >= height) continue; - for(int j=0;j=width) + if (j < 0 || j >= width) continue; - dst_data_ptr[width * (desti.y + i) + desti.x + j] = src_data_ptr[p_src.width * (srci.y+i) + srci.x+j]; + dst_data_ptr[width * (desti.y + i) + desti.x + j] = src_data_ptr[p_src.width * (srci.y + i) + srci.x + j]; } } } else { - for(int i=0;i= height) + if (i < 0 || i >= height) continue; - for(int j=0;j=width) + if (j < 0 || j >= width) continue; - _put_pixel(p_dest.x+j,p_dest.y+i,p_src._get_pixel(rrect.pos.x+j,rrect.pos.y+i,src_data_ptr,srcdsize),dst_data_ptr); + _put_pixel(p_dest.x + j, p_dest.y + i, p_src._get_pixel(rrect.pos.x + j, rrect.pos.y + i, src_data_ptr, srcdsize), dst_data_ptr); } } } - } +Image (*Image::_png_mem_loader_func)(const uint8_t *, int) = NULL; +Image (*Image::_jpg_mem_loader_func)(const uint8_t *, int) = NULL; -Image (*Image::_png_mem_loader_func)(const uint8_t*,int)=NULL; -Image (*Image::_jpg_mem_loader_func)(const uint8_t*,int)=NULL; +void (*Image::_image_compress_bc_func)(Image *) = NULL; +void (*Image::_image_compress_pvrtc2_func)(Image *) = NULL; +void (*Image::_image_compress_pvrtc4_func)(Image *) = NULL; +void (*Image::_image_compress_etc_func)(Image *) = NULL; +void (*Image::_image_decompress_pvrtc)(Image *) = NULL; +void (*Image::_image_decompress_bc)(Image *) = NULL; +void (*Image::_image_decompress_etc)(Image *) = NULL; -void (*Image::_image_compress_bc_func)(Image *)=NULL; -void (*Image::_image_compress_pvrtc2_func)(Image *)=NULL; -void (*Image::_image_compress_pvrtc4_func)(Image *)=NULL; -void (*Image::_image_compress_etc_func)(Image *)=NULL; -void (*Image::_image_decompress_pvrtc)(Image *)=NULL; -void (*Image::_image_decompress_bc)(Image *)=NULL; -void (*Image::_image_decompress_etc)(Image *)=NULL; - -DVector (*Image::lossy_packer)(const Image& ,float )=NULL; -Image (*Image::lossy_unpacker)(const DVector& )=NULL; -DVector (*Image::lossless_packer)(const Image& )=NULL; -Image (*Image::lossless_unpacker)(const DVector& )=NULL; +DVector (*Image::lossy_packer)(const Image &, float) = NULL; +Image (*Image::lossy_unpacker)(const DVector &) = NULL; +DVector (*Image::lossless_packer)(const Image &) = NULL; +Image (*Image::lossless_unpacker)(const DVector &) = NULL; void Image::set_compress_bc_func(void (*p_compress_func)(Image *)) { - _image_compress_bc_func=p_compress_func; + _image_compress_bc_func = p_compress_func; } - - void Image::normalmap_to_xy() { convert(Image::FORMAT_RGBA); { - int len = data.size()/4; + int len = data.size() / 4; DVector::Write wp = data.write(); - unsigned char *data_ptr=wp.ptr(); + unsigned char *data_ptr = wp.ptr(); - for(int i=0;i::Write wp = data.write(); - unsigned char *data_ptr=wp.ptr(); + unsigned char *data_ptr = wp.ptr(); - for(int i=0;i::Write wp = data.write(); - unsigned char *data_ptr=wp.ptr(); + unsigned char *data_ptr = wp.ptr(); - for(int i=0;i::Write wp = data.write(); - unsigned char *data_ptr=wp.ptr(); + unsigned char *data_ptr = wp.ptr(); + for (int i = 0; i < height; i++) { + for (int j = 0; j < width; j++) { - for(int i=0;i>8; - bc.g=(int(bc.g)*int(bc.a))>>8; - bc.b=(int(bc.b)*int(bc.a))>>8; - _put_pixel(j,i,bc,data_ptr); + BColor bc = _get_pixel(j, i, data_ptr, 0); + bc.r = (int(bc.r) * int(bc.a)) >> 8; + bc.g = (int(bc.g) * int(bc.a)) >> 8; + bc.b = (int(bc.b) * int(bc.a)) >> 8; + _put_pixel(j, i, bc, data_ptr); } } } void Image::fix_alpha_edges() { - if (data.size()==0) + if (data.size() == 0) return; - if (format!=FORMAT_RGBA) + if (format != FORMAT_RGBA) return; //not needed DVector dcopy = data; DVector::Read rp = data.read(); - const uint8_t *rptr=rp.ptr(); + const uint8_t *rptr = rp.ptr(); DVector::Write wp = data.write(); - unsigned char *data_ptr=wp.ptr(); + unsigned char *data_ptr = wp.ptr(); - const int max_radius=4; - const int alpha_treshold=20; - const int max_dist=0x7FFFFFFF; + const int max_radius = 4; + const int alpha_treshold = 20; + const int max_dist = 0x7FFFFFFF; - for(int i=0;i=alpha_treshold) + BColor bc = _get_pixel(j, i, rptr, 0); + if (bc.a >= alpha_treshold) continue; - int closest_dist=max_dist; + int closest_dist = max_dist; BColor closest_color; - closest_color.a=bc.a; - int from_x = MAX(0,j-max_radius); - int to_x = MIN(width-1,j+max_radius); - int from_y = MAX(0,i-max_radius); - int to_y = MIN(height-1,i+max_radius); + closest_color.a = bc.a; + int from_x = MAX(0, j - max_radius); + int to_x = MIN(width - 1, j + max_radius); + int from_y = MAX(0, i - max_radius); + int to_y = MIN(height - 1, i + max_radius); - for(int k=from_y;k<=to_y;k++) { - for(int l=from_x;l<=to_x;l++) { + for (int k = from_y; k <= to_y; k++) { + for (int l = from_x; l <= to_x; l++) { - int dy = i-k; - int dx = j-l; - int dist = dy*dy+dx*dx; - if (dist>=closest_dist) + int dy = i - k; + int dx = j - l; + int dist = dy * dy + dx * dx; + if (dist >= closest_dist) continue; - const uint8_t * rp = &rptr[(k*width+l)<<2]; + const uint8_t *rp = &rptr[(k * width + l) << 2]; - if (rp[3] @@ -42,16 +42,16 @@ class Image; -typedef Error (*SavePNGFunc)(const String &p_path, Image& p_img); +typedef Error (*SavePNGFunc)(const String &p_path, Image &p_img); class Image { enum { - MAX_WIDTH=16384, // force a limit somehow - MAX_HEIGHT=16384// force a limit somehow + MAX_WIDTH = 16384, // force a limit somehow + MAX_HEIGHT = 16384 // force a limit somehow }; -public: +public: static SavePNGFunc save_png_func; enum Format { @@ -87,7 +87,7 @@ public: FORMAT_MAX }; - static const char* format_names[FORMAT_MAX]; + static const char *format_names[FORMAT_MAX]; enum Interpolation { INTERPOLATE_NEAREST, @@ -96,8 +96,8 @@ public: /* INTERPOLATE GAUSS */ }; - static Image (*_png_mem_loader_func)(const uint8_t* p_png,int p_size); - static Image (*_jpg_mem_loader_func)(const uint8_t* p_png,int p_size); + static Image (*_png_mem_loader_func)(const uint8_t *p_png, int p_size); + static Image (*_jpg_mem_loader_func)(const uint8_t *p_png, int p_size); static void (*_image_compress_bc_func)(Image *); static void (*_image_compress_pvrtc2_func)(Image *); static void (*_image_compress_pvrtc4_func)(Image *); @@ -108,25 +108,35 @@ public: Error _decompress_bc(); - static DVector (*lossy_packer)(const Image& p_image,float p_quality); - static Image (*lossy_unpacker)(const DVector& p_buffer); - static DVector (*lossless_packer)(const Image& p_image); - static Image (*lossless_unpacker)(const DVector& p_buffer); -private: + static DVector (*lossy_packer)(const Image &p_image, float p_quality); + static Image (*lossy_unpacker)(const DVector &p_buffer); + static DVector (*lossless_packer)(const Image &p_image); + static Image (*lossless_unpacker)(const DVector &p_buffer); +private: //internal byte based color struct BColor { union { uint8_t col[4]; struct { - uint8_t r,g,b,a; + uint8_t r, g, b, a; }; }; - bool operator==(const BColor& p_color) const { for(int i=0;i<4;i++) {if (col[i]!=p_color.col[i]) return false; } return true; } - _FORCE_INLINE_ uint8_t gray() const { return (uint16_t(col[0])+uint16_t(col[1])+uint16_t(col[2]))/3; } + bool operator==(const BColor &p_color) const { + for (int i = 0; i < 4; i++) { + if (col[i] != p_color.col[i]) return false; + } + return true; + } + _FORCE_INLINE_ uint8_t gray() const { return (uint16_t(col[0]) + uint16_t(col[1]) + uint16_t(col[2])) / 3; } _FORCE_INLINE_ BColor() {} - BColor(uint8_t p_r,uint8_t p_g,uint8_t p_b,uint8_t p_a=255) { col[0]=p_r; col[1]=p_g; col[2]=p_b; col[3]=p_a; } + BColor(uint8_t p_r, uint8_t p_g, uint8_t p_b, uint8_t p_a = 255) { + col[0] = p_r; + col[1] = p_g; + col[2] = p_b; + col[3] = p_a; + } }; //median cut classes @@ -137,22 +147,22 @@ private: BColor color; struct SortR { - bool operator()(const BColorPos& ca, const BColorPos& cb) const { return ca.color.r < cb.color.r; } + bool operator()(const BColorPos &ca, const BColorPos &cb) const { return ca.color.r < cb.color.r; } }; struct SortG { - bool operator()(const BColorPos& ca, const BColorPos& cb) const { return ca.color.g < cb.color.g; } + bool operator()(const BColorPos &ca, const BColorPos &cb) const { return ca.color.g < cb.color.g; } }; struct SortB { - bool operator()(const BColorPos& ca, const BColorPos& cb) const { return ca.color.b < cb.color.b; } + bool operator()(const BColorPos &ca, const BColorPos &cb) const { return ca.color.b < cb.color.b; } }; struct SortA { - bool operator()(const BColorPos& ca, const BColorPos& cb) const { return ca.color.a < cb.color.a; } + bool operator()(const BColorPos &ca, const BColorPos &cb) const { return ca.color.a < cb.color.a; } }; }; @@ -166,45 +176,42 @@ private: int color; }; int right; - SPTree() { leaf=true; left=-1; right=-1;} + SPTree() { + leaf = true; + left = -1; + right = -1; + } }; struct MCBlock { - BColorPos min_color,max_color; + BColorPos min_color, max_color; BColorPos *colors; int sp_idx; int color_count; int get_longest_axis_index() const; int get_longest_axis_length() const; - bool operator<(const MCBlock& p_block) const; + bool operator<(const MCBlock &p_block) const; void shrink(); MCBlock(); - MCBlock(BColorPos *p_colors,int p_color_count); + MCBlock(BColorPos *p_colors, int p_color_count); }; Format format; DVector data; - int width,height,mipmaps; + int width, height, mipmaps; + _FORCE_INLINE_ BColor _get_pixel(int p_x, int p_y, const unsigned char *p_data, int p_data_size) const; + _FORCE_INLINE_ BColor _get_pixelw(int p_x, int p_y, int p_width, const unsigned char *p_data, int p_data_size) const; + _FORCE_INLINE_ void _put_pixelw(int p_x, int p_y, int p_width, const BColor &p_color, unsigned char *p_data); + _FORCE_INLINE_ void _put_pixel(int p_x, int p_y, const BColor &p_color, unsigned char *p_data); + _FORCE_INLINE_ void _get_mipmap_offset_and_size(int p_mipmap, int &r_offset, int &r_width, int &r_height) const; //get where the mipmap begins in data + _FORCE_INLINE_ static void _get_format_min_data_size(Format p_format, int &r_w, int &r_h); - - _FORCE_INLINE_ BColor _get_pixel(int p_x,int p_y,const unsigned char *p_data,int p_data_size) const; - _FORCE_INLINE_ BColor _get_pixelw(int p_x,int p_y,int p_width,const unsigned char *p_data,int p_data_size) const; - _FORCE_INLINE_ void _put_pixelw(int p_x,int p_y, int p_width, const BColor& p_color, unsigned char *p_data); - _FORCE_INLINE_ void _put_pixel(int p_x,int p_y, const BColor& p_color, unsigned char *p_data); - _FORCE_INLINE_ void _get_mipmap_offset_and_size(int p_mipmap,int &r_offset, int &r_width, int &r_height) const; //get where the mipmap begins in data - _FORCE_INLINE_ static void _get_format_min_data_size(Format p_format,int &r_w, int &r_h); - - static int _get_dst_image_size(int p_width, int p_height, Format p_format,int &r_mipmaps,int p_mipmaps=-1); + static int _get_dst_image_size(int p_width, int p_height, Format p_format, int &r_mipmaps, int p_mipmaps = -1); bool _can_modify(Format p_format) const; - - public: - - - int get_width() const; ///< Get image width int get_height() const; ///< Get image height int get_mipmaps() const; @@ -213,16 +220,16 @@ public: * Get a pixel from the image. for grayscale or indexed formats, use Color::gray to obtain the actual * value. */ - Color get_pixel(int p_x,int p_y,int p_mipmap=0) const; + Color get_pixel(int p_x, int p_y, int p_mipmap = 0) const; /** * Set a pixel into the image. for grayscale or indexed formats, a suitable Color constructor. */ - void put_pixel(int p_x,int p_y, const Color& p_color,int p_mipmap=0); /* alpha and index are averaged */ + void put_pixel(int p_x, int p_y, const Color &p_color, int p_mipmap = 0); /* alpha and index are averaged */ /** * Convert the image to another format, as close as it can be done. */ - void convert( Format p_new_format ); + void convert(Format p_new_format); Image converted(int p_new_format) { ERR_FAIL_INDEX_V(p_new_format, FORMAT_MAX, Image()); @@ -238,48 +245,46 @@ public: Format get_format() const; int get_mipmap_offset(int p_mipmap) const; //get where the mipmap begins in data - void get_mipmap_offset_and_size(int p_mipmap,int &r_ofs, int &r_size) const; //get where the mipmap begins in data - void get_mipmap_offset_size_and_dimensions(int p_mipmap,int &r_ofs, int &r_size,int &w, int& h) const; //get where the mipmap begins in data + void get_mipmap_offset_and_size(int p_mipmap, int &r_ofs, int &r_size) const; //get where the mipmap begins in data + void get_mipmap_offset_size_and_dimensions(int p_mipmap, int &r_ofs, int &r_size, int &w, int &h) const; //get where the mipmap begins in data /** * Resize the image, using the prefered interpolation method. * Indexed-Color images always use INTERPOLATE_NEAREST. */ - void resize_to_po2(bool p_square=false); - void resize( int p_width, int p_height, Interpolation p_interpolation=INTERPOLATE_BILINEAR ); - Image resized( int p_width, int p_height, int p_interpolation=INTERPOLATE_BILINEAR ); + void resize_to_po2(bool p_square = false); + void resize(int p_width, int p_height, Interpolation p_interpolation = INTERPOLATE_BILINEAR); + Image resized(int p_width, int p_height, int p_interpolation = INTERPOLATE_BILINEAR); void shrink_x2(); void expand_x2_hq2x(); /** * Crop the image to a specific size, if larger, then the image is filled by black */ - void crop( int p_width, int p_height ); - + void crop(int p_width, int p_height); void flip_x(); void flip_y(); /** * Generate a mipmap to an image (creates an image 1/4 the size, with averaging of 4->1) */ - Error generate_mipmaps(int p_amount=-1,bool p_keep_existing=false); + Error generate_mipmaps(int p_amount = -1, bool p_keep_existing = false); void clear_mipmaps(); - /** * Generate a normal map from a grayscale image */ - void make_normalmap(float p_height_scale=1.0); + void make_normalmap(float p_height_scale = 1.0); /** * Create a new image of a given size and format. Current image will be lost */ void create(int p_width, int p_height, bool p_use_mipmaps, Format p_format); - void create(int p_width, int p_height, int p_mipmaps, Format p_format, const DVector& p_data); + void create(int p_width, int p_height, int p_mipmaps, Format p_format, const DVector &p_data); - void create( const char ** p_xpm ); + void create(const char **p_xpm); /** * returns true when the image is empty (0,0) in size */ @@ -287,8 +292,8 @@ public: DVector get_data() const; - Error load(const String& p_path); - Error save_png(const String& p_path); + Error load(const String &p_path); + Error save_png(const String &p_path); /** * create an empty image @@ -301,7 +306,7 @@ public: /** * import an image of a specific size and format from a pointer */ - Image(int p_width, int p_height, int p_mipmaps, Format p_format, const DVector& p_data); + Image(int p_width, int p_height, int p_mipmaps, Format p_format, const DVector &p_data); enum AlphaMode { ALPHA_NONE, @@ -312,21 +317,17 @@ public: AlphaMode detect_alpha() const; bool is_invisible() const; - void put_indexed_pixel(int p_x, int p_y, uint8_t p_idx,int p_mipmap=0); - uint8_t get_indexed_pixel(int p_x, int p_y,int p_mipmap=0) const; - void set_pallete(const DVector& p_data); - + void put_indexed_pixel(int p_x, int p_y, uint8_t p_idx, int p_mipmap = 0); + uint8_t get_indexed_pixel(int p_x, int p_y, int p_mipmap = 0) const; + void set_pallete(const DVector &p_data); static int get_format_pixel_size(Format p_format); static int get_format_pixel_rshift(Format p_format); static int get_format_pallete_size(Format p_format); - static int get_image_data_size(int p_width, int p_height, Format p_format,int p_mipmaps=0); + static int get_image_data_size(int p_width, int p_height, Format p_format, int p_mipmaps = 0); static int get_image_required_mipmaps(int p_width, int p_height, Format p_format); - - - - bool operator==(const Image& p_image) const; + bool operator==(const Image &p_image) const; void quantize(); @@ -337,7 +338,7 @@ public: COMPRESS_ETC }; - Error compress(CompressMode p_mode=COMPRESS_BC); + Error compress(CompressMode p_mode = COMPRESS_BC); Image compressed(int p_mode); /* from the Image::CompressMode enum */ Error decompress(); Image decompressed() const; @@ -348,21 +349,19 @@ public: void srgb_to_linear(); void normalmap_to_xy(); - void blit_rect(const Image& p_src, const Rect2& p_src_rect,const Point2& p_dest); - void brush_transfer(const Image& p_src, const Image& p_brush, const Point2& p_dest); - Image brushed(const Image& p_src, const Image& p_brush, const Point2& p_dest) const; + void blit_rect(const Image &p_src, const Rect2 &p_src_rect, const Point2 &p_dest); + void brush_transfer(const Image &p_src, const Image &p_brush, const Point2 &p_dest); + Image brushed(const Image &p_src, const Image &p_brush, const Point2 &p_dest) const; Rect2 get_used_rect() const; - Image get_rect(const Rect2& p_area) const; + Image get_rect(const Rect2 &p_area) const; static void set_compress_bc_func(void (*p_compress_func)(Image *)); static String get_format_name(Format p_format); - Image(const uint8_t* p_mem_png_jpg, int p_len=-1); + Image(const uint8_t *p_mem_png_jpg, int p_len = -1); Image(const char **p_xpm); ~Image(); - }; - #endif diff --git a/core/image_quantize.cpp b/core/image_quantize.cpp index a594aee60cd..67b7cd51831 100644 --- a/core/image_quantize.cpp +++ b/core/image_quantize.cpp @@ -27,41 +27,38 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "image.h" -#include #include "print_string.h" +#include #ifdef TOOLS_ENABLED +#include "os/os.h" #include "set.h" #include "sort.h" -#include "os/os.h" //#define QUANTIZE_SPEED_OVER_QUALITY - Image::MCBlock::MCBlock() { - - } -Image::MCBlock::MCBlock(BColorPos *p_colors,int p_color_count) { +Image::MCBlock::MCBlock(BColorPos *p_colors, int p_color_count) { - colors=p_colors; - color_count=p_color_count; - min_color.color=BColor(255,255,255,255); - max_color.color=BColor(0,0,0,0); + colors = p_colors; + color_count = p_color_count; + min_color.color = BColor(255, 255, 255, 255); + max_color.color = BColor(0, 0, 0, 0); shrink(); } int Image::MCBlock::get_longest_axis_index() const { - int max_dist=-1; - int max_index=0; + int max_dist = -1; + int max_index = 0; - for(int i=0;i<4;i++) { + for (int i = 0; i < 4; i++) { - int d = max_color.color.col[i]-min_color.color.col[i]; - if (d>max_dist) { - max_index=i; - max_dist=d; + int d = max_color.color.col[i] - min_color.color.col[i]; + if (d > max_dist) { + max_index = i; + max_dist = d; } } @@ -69,88 +66,80 @@ int Image::MCBlock::get_longest_axis_index() const { } int Image::MCBlock::get_longest_axis_length() const { - int max_dist=-1; + int max_dist = -1; - for(int i=0;i<4;i++) { + for (int i = 0; i < 4; i++) { - int d = max_color.color.col[i]-min_color.color.col[i]; - if (d>max_dist) { - max_dist=d; + int d = max_color.color.col[i] - min_color.color.col[i]; + if (d > max_dist) { + max_dist = d; } } return max_dist; } -bool Image::MCBlock::operator<(const MCBlock& p_block) const { +bool Image::MCBlock::operator<(const MCBlock &p_block) const { int alen = get_longest_axis_length(); int blen = p_block.get_longest_axis_length(); - if (alen==blen) { + if (alen == blen) { return colors < p_block.colors; } else return alen < blen; - } void Image::MCBlock::shrink() { - min_color=colors[0]; - max_color=colors[0]; + min_color = colors[0]; + max_color = colors[0]; - for(int i=1;ihas_environment("QUANTIZE_FAST"); + bool quantize_fast = OS::get_singleton()->has_environment("QUANTIZE_FAST"); convert(FORMAT_RGBA); - ERR_FAIL_COND( format!=FORMAT_RGBA ); + ERR_FAIL_COND(format != FORMAT_RGBA); DVector indexed_data; - { - int color_count = data.size()/4; + int color_count = data.size() / 4; - ERR_FAIL_COND(color_count==0); + ERR_FAIL_COND(color_count == 0); Set block_queue; DVector data_colors; data_colors.resize(color_count); - DVector::Write dcw=data_colors.write(); + DVector::Write dcw = data_colors.write(); DVector::Read dr = data.read(); - const BColor * drptr=(const BColor*)&dr[0]; - BColorPos *bcptr=&dcw[0]; - - + const BColor *drptr = (const BColor *)&dr[0]; + BColorPos *bcptr = &dcw[0]; { - for(int i=0;iget().color_count > 1 ) { + while (block_queue.size() < 256 && block_queue.back()->get().color_count > 1) { MCBlock longest = block_queue.back()->get(); //printf("longest: %i (%i)\n",longest.get_longest_axis_index(),longest.get_longest_axis_length()); @@ -173,7 +162,7 @@ void Image::quantize() { block_queue.erase(block_queue.back()); BColorPos *first = longest.colors; - BColorPos *median = longest.colors + (longest.color_count+1)/2; + BColorPos *median = longest.colors + (longest.color_count + 1) / 2; BColorPos *end = longest.colors + longest.color_count; #if 0 @@ -234,111 +223,122 @@ void Image::quantize() { block_queue.insert(right); #else - switch(longest.get_longest_axis_index()) { - case 0: { SortArray sort; sort.nth_element(0,end-first,median-first,first); } break; - case 1: { SortArray sort; sort.nth_element(0,end-first,median-first,first); } break; - case 2: { SortArray sort; sort.nth_element(0,end-first,median-first,first); } break; - case 3: { SortArray sort; sort.nth_element(0,end-first,median-first,first); } break; - + switch (longest.get_longest_axis_index()) { + case 0: { + SortArray sort; + sort.nth_element(0, end - first, median - first, first); + } break; + case 1: { + SortArray sort; + sort.nth_element(0, end - first, median - first, first); + } break; + case 2: { + SortArray sort; + sort.nth_element(0, end - first, median - first, first); + } break; + case 3: { + SortArray sort; + sort.nth_element(0, end - first, median - first, first); + } break; } - MCBlock left(first,median-first); - MCBlock right(median,end-median); + MCBlock left(first, median - first); + MCBlock right(median, end - median); block_queue.insert(left); block_queue.insert(right); - #endif - - } - while(block_queue.size() > 256) { + while (block_queue.size() > 256) { - block_queue.erase(block_queue.front());// erase least significant + block_queue.erase(block_queue.front()); // erase least significant } - int res_colors=0; + int res_colors = 0; - int comp_size = (has_alpha?4:3); - indexed_data.resize(color_count + 256*comp_size); + int comp_size = (has_alpha ? 4 : 3); + indexed_data.resize(color_count + 256 * comp_size); DVector::Write iw = indexed_data.write(); - uint8_t *iwptr=&iw[0]; + uint8_t *iwptr = &iw[0]; BColor pallete[256]; - // print_line("applying quantization - res colors "+itos(block_queue.size())); + // print_line("applying quantization - res colors "+itos(block_queue.size())); - while(block_queue.size()) { + while (block_queue.size()) { const MCBlock &b = block_queue.back()->get(); - uint64_t sum[4]={0,0,0,0}; + uint64_t sum[4] = { 0, 0, 0, 0 }; - for(int i=0;i actions = get_actions(); - if(actions.empty()) + if (actions.empty()) return ret; - for(const List::Element *E=actions.front();E;E=E->next()) { + for (const List::Element *E = actions.front(); E; E = E->next()) { ret.push_back(E->get()); } @@ -95,49 +90,49 @@ Array InputMap::_get_actions() { List InputMap::get_actions() const { List actions = List(); - if(input_map.empty()){ + if (input_map.empty()) { return actions; } - for (Map::Element *E=input_map.front();E;E=E->next()) { + for (Map::Element *E = input_map.front(); E; E = E->next()) { actions.push_back(E->key()); } return actions; } -List::Element *InputMap::_find_event(List &p_list,const InputEvent& p_event) const { +List::Element *InputMap::_find_event(List &p_list, const InputEvent &p_event) const { - for (List::Element *E=p_list.front();E;E=E->next()) { + for (List::Element *E = p_list.front(); E; E = E->next()) { - const InputEvent& e=E->get(); - if(e.type!=p_event.type) + const InputEvent &e = E->get(); + if (e.type != p_event.type) continue; - if (e.type!=InputEvent::KEY && e.device!=p_event.device) + if (e.type != InputEvent::KEY && e.device != p_event.device) continue; - bool same=false; + bool same = false; - switch(p_event.type) { + switch (p_event.type) { case InputEvent::KEY: { - same=(e.key.scancode==p_event.key.scancode && e.key.mod == p_event.key.mod); + same = (e.key.scancode == p_event.key.scancode && e.key.mod == p_event.key.mod); } break; case InputEvent::JOYSTICK_BUTTON: { - same=(e.joy_button.button_index==p_event.joy_button.button_index); + same = (e.joy_button.button_index == p_event.joy_button.button_index); } break; case InputEvent::MOUSE_BUTTON: { - same=(e.mouse_button.button_index==p_event.mouse_button.button_index); + same = (e.mouse_button.button_index == p_event.mouse_button.button_index); } break; case InputEvent::JOYSTICK_MOTION: { - same=(e.joy_motion.axis==p_event.joy_motion.axis && (e.joy_motion.axis_value < 0) == (p_event.joy_motion.axis_value < 0)); + same = (e.joy_motion.axis == p_event.joy_motion.axis && (e.joy_motion.axis_value < 0) == (p_event.joy_motion.axis_value < 0)); } break; } @@ -146,90 +141,82 @@ List::Element *InputMap::_find_event(List &p_list,const return E; } - return NULL; } - -bool InputMap::has_action(const StringName& p_action) const { +bool InputMap::has_action(const StringName &p_action) const { return input_map.has(p_action); } -void InputMap::action_add_event(const StringName& p_action,const InputEvent& p_event) { +void InputMap::action_add_event(const StringName &p_action, const InputEvent &p_event) { - ERR_FAIL_COND(p_event.type==InputEvent::ACTION); - ERR_FAIL_COND( !input_map.has(p_action) ); - if (_find_event(input_map[p_action].inputs,p_event)) + ERR_FAIL_COND(p_event.type == InputEvent::ACTION); + ERR_FAIL_COND(!input_map.has(p_action)); + if (_find_event(input_map[p_action].inputs, p_event)) return; //already gots input_map[p_action].inputs.push_back(p_event); - } +int InputMap::get_action_id(const StringName &p_action) const { -int InputMap::get_action_id(const StringName& p_action) const { - - ERR_FAIL_COND_V(!input_map.has(p_action),-1); + ERR_FAIL_COND_V(!input_map.has(p_action), -1); return input_map[p_action].id; } -bool InputMap::action_has_event(const StringName& p_action,const InputEvent& p_event) { - - ERR_FAIL_COND_V( !input_map.has(p_action), false ); - return (_find_event(input_map[p_action].inputs,p_event)!=NULL); +bool InputMap::action_has_event(const StringName &p_action, const InputEvent &p_event) { + ERR_FAIL_COND_V(!input_map.has(p_action), false); + return (_find_event(input_map[p_action].inputs, p_event) != NULL); } -void InputMap::action_erase_event(const StringName& p_action,const InputEvent& p_event) { +void InputMap::action_erase_event(const StringName &p_action, const InputEvent &p_event) { - ERR_FAIL_COND( !input_map.has(p_action) ); + ERR_FAIL_COND(!input_map.has(p_action)); - List::Element *E=_find_event(input_map[p_action].inputs,p_event); + List::Element *E = _find_event(input_map[p_action].inputs, p_event); if (E) input_map[p_action].inputs.erase(E); } - -Array InputMap::_get_action_list(const StringName& p_action) { +Array InputMap::_get_action_list(const StringName &p_action) { Array ret; const List *al = get_action_list(p_action); if (al) { - for(const List::Element *E=al->front();E;E=E->next()) { + for (const List::Element *E = al->front(); E; E = E->next()) { ret.push_back(E->get()); } } return ret; - } -const List *InputMap::get_action_list(const StringName& p_action) { +const List *InputMap::get_action_list(const StringName &p_action) { - const Map::Element *E=input_map.find(p_action); + const Map::Element *E = input_map.find(p_action); if (!E) return NULL; return &E->get().inputs; } -bool InputMap::event_is_action(const InputEvent& p_event, const StringName& p_action) const { +bool InputMap::event_is_action(const InputEvent &p_event, const StringName &p_action) const { - - Map::Element *E=input_map.find(p_action); - if(!E) { - ERR_EXPLAIN("Request for nonexistent InputMap action: "+String(p_action)); - ERR_FAIL_COND_V(!E,false); + Map::Element *E = input_map.find(p_action); + if (!E) { + ERR_EXPLAIN("Request for nonexistent InputMap action: " + String(p_action)); + ERR_FAIL_COND_V(!E, false); } - if (p_event.type==InputEvent::ACTION) { + if (p_event.type == InputEvent::ACTION) { - return p_event.action.action==E->get().id; + return p_event.action.action == E->get().id; } - return _find_event(E->get().inputs,p_event)!=NULL; + return _find_event(E->get().inputs, p_event) != NULL; } void InputMap::load_from_globals() { @@ -239,94 +226,88 @@ void InputMap::load_from_globals() { List pinfo; Globals::get_singleton()->get_property_list(&pinfo); - for(List::Element *E=pinfo.front();E;E=E->next()) { - const PropertyInfo &pi=E->get(); + for (List::Element *E = pinfo.front(); E; E = E->next()) { + const PropertyInfo &pi = E->get(); if (!pi.name.begins_with("input/")) continue; - String name = pi.name.substr(pi.name.find("/")+1,pi.name.length()); + String name = pi.name.substr(pi.name.find("/") + 1, pi.name.length()); add_action(name); Array va = Globals::get_singleton()->get(pi.name); - for(int i=0;i inputs; }; mutable Map input_map; - mutable Map input_id_map; + mutable Map input_id_map; - List::Element *_find_event(List &p_list,const InputEvent& p_event) const; + List::Element *_find_event(List &p_list, const InputEvent &p_event) const; - Array _get_action_list(const StringName& p_action); + Array _get_action_list(const StringName &p_action); Array _get_actions(); protected: - static void _bind_methods(); -public: +public: static _FORCE_INLINE_ InputMap *get_singleton() { return singleton; } - - bool has_action(const StringName& p_action) const; - int get_action_id(const StringName& p_action) const; + bool has_action(const StringName &p_action) const; + int get_action_id(const StringName &p_action) const; StringName get_action_from_id(int p_id) const; List get_actions() const; - void add_action(const StringName& p_action); - void erase_action(const StringName& p_action); + void add_action(const StringName &p_action); + void erase_action(const StringName &p_action); - void action_add_event(const StringName& p_action,const InputEvent& p_event); - bool action_has_event(const StringName& p_action,const InputEvent& p_event); - void action_erase_event(const StringName& p_action,const InputEvent& p_event); - - const List *get_action_list(const StringName& p_action); - bool event_is_action(const InputEvent& p_event, const StringName& p_action) const; + void action_add_event(const StringName &p_action, const InputEvent &p_event); + bool action_has_event(const StringName &p_action, const InputEvent &p_event); + void action_erase_event(const StringName &p_action, const InputEvent &p_event); + const List *get_action_list(const StringName &p_action); + bool event_is_action(const InputEvent &p_event, const StringName &p_action) const; void load_from_globals(); void load_default(); diff --git a/core/int_types.h b/core/int_types.h index a7f04c680e6..50ce38a3ba1 100644 --- a/core/int_types.h +++ b/core/int_types.h @@ -29,25 +29,25 @@ #ifdef _MSC_VER -typedef signed __int8 int8_t; -typedef unsigned __int8 uint8_t; -typedef signed __int16 int16_t; -typedef unsigned __int16 uint16_t; -typedef signed __int32 int32_t; -typedef unsigned __int32 uint32_t; -typedef signed __int64 int64_t; -typedef unsigned __int64 uint64_t; +typedef signed __int8 int8_t; +typedef unsigned __int8 uint8_t; +typedef signed __int16 int16_t; +typedef unsigned __int16 uint16_t; +typedef signed __int32 int32_t; +typedef unsigned __int32 uint32_t; +typedef signed __int64 int64_t; +typedef unsigned __int64 uint64_t; #else #ifdef NO_STDINT_H -typedef unsigned char uint8_t; -typedef signed char int8_t; -typedef unsigned short uint16_t; -typedef signed short int16_t; -typedef unsigned int uint32_t; -typedef signed int int32_t; -typedef long long int64_t; +typedef unsigned char uint8_t; +typedef signed char int8_t; +typedef unsigned short uint16_t; +typedef signed short int16_t; +typedef unsigned int uint32_t; +typedef signed int int32_t; +typedef long long int64_t; typedef unsigned long long uint64_t; #else #include diff --git a/core/io/compression.cpp b/core/io/compression.cpp index cf29cb921b4..4ac2fd3bf32 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,16 +54,16 @@ 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_out=aout; - strm.next_in=(Bytef*)p_src; - strm.next_out=p_dst; - deflate(&strm,Z_FINISH); + strm.avail_in = p_src_size; + int aout = deflateBound(&strm, p_src_size); + 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; @@ -74,15 +74,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; @@ -92,32 +91,29 @@ 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); - } +void Compression::decompress(uint8_t *p_dst, int p_dst_max_size, const uint8_t *p_src, int p_src_size, Mode p_mode) { - -void 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: { - if (p_dst_max_size<16) { + if (p_dst_max_size < 16) { uint8_t dst[16]; - fastlz_decompress(p_src,p_src_size,dst,16); - copymem(p_dst,dst,p_dst_max_size); + fastlz_decompress(p_src, p_src_size, dst, 16); + copymem(p_dst, dst, p_dst_max_size); } else { - fastlz_decompress(p_src,p_src_size,p_dst,p_dst_max_size); + fastlz_decompress(p_src, p_src_size, p_dst, p_dst_max_size); } return; } break; @@ -127,19 +123,19 @@ void Compression::decompress(uint8_t *p_dst, int p_dst_max_size, const uint8_t * 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(err!=Z_OK); + ERR_FAIL_COND(err != Z_OK); - 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); inflateEnd(&strm); - ERR_FAIL_COND(err!=Z_STREAM_END); + ERR_FAIL_COND(err != Z_STREAM_END); return; } break; } diff --git a/core/io/compression.h b/core/io/compression.h index dda12705527..c2b498fbbc2 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 void 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 void 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 1cf600a0cf9..2c2352616cc 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" StringArray ConfigFile::_get_sections() const { @@ -37,35 +37,33 @@ StringArray ConfigFile::_get_sections() const { get_sections(&s); StringArray arr; arr.resize(s.size()); - int idx=0; - for(const List::Element *E=s.front();E;E=E->next()) { + int idx = 0; + for (const List::Element *E = s.front(); E; E = E->next()) { - arr.set(idx++,E->get()); + arr.set(idx++, E->get()); } return arr; } -StringArray ConfigFile::_get_section_keys(const String& p_section) const{ +StringArray ConfigFile::_get_section_keys(const String &p_section) const { List s; - get_section_keys(p_section,&s); + get_section_keys(p_section, &s); StringArray arr; arr.resize(s.size()); - int idx=0; - for(const List::Element *E=s.front();E;E=E->next()) { + int idx = 0; + for (const List::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,55 +74,49 @@ void ConfigFile::set_value(const String& p_section, const String& p_key, const V } else { if (!values.has(p_section)) { - values[p_section]=Map(); + values[p_section] = Map(); } - 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 *r_sections) const{ +void ConfigFile::get_sections(List *r_sections) const { - for(const Map< String, Map >::Element *E=values.front();E;E=E->next()) { + for (const Map >::Element *E = values.front(); E; E = E->next()) { r_sections->push_back(E->key()); } } -void ConfigFile::get_section_keys(const String& p_section,List *r_keys) const{ +void ConfigFile::get_section_keys(const String &p_section, List *r_keys) const { ERR_FAIL_COND(!values.has(p_section)); - for(const Map ::Element *E=values[p_section].front();E;E=E->next()) { + for (const Map::Element *E = values[p_section].front(); E; E = E->next()) { r_keys->push_back(E->key()); } - } - - -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) @@ -132,18 +124,17 @@ Error ConfigFile::save(const String& p_path){ return err; } + for (Map >::Element *E = values.front(); E; E = E->next()) { - for(Map< String, Map >::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::Element *F=E->get().front();F;F=F->next()) { + for (Map::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"); } } @@ -152,48 +143,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; } } @@ -202,25 +191,20 @@ Error ConfigFile::load(const String& p_path) { return OK; } +void ConfigFile::_bind_methods() { + ObjectTypeDB::bind_method(_MD("set_value", "section", "key", "value"), &ConfigFile::set_value); + ObjectTypeDB::bind_method(_MD("get_value:Variant", "section", "key", "default"), &ConfigFile::get_value, DEFVAL(Variant())); -void ConfigFile::_bind_methods(){ + ObjectTypeDB::bind_method(_MD("has_section", "section"), &ConfigFile::has_section); + ObjectTypeDB::bind_method(_MD("has_section_key", "section", "key"), &ConfigFile::has_section_key); - ObjectTypeDB::bind_method(_MD("set_value","section","key","value"),&ConfigFile::set_value); - ObjectTypeDB::bind_method(_MD("get_value:Variant","section","key","default"),&ConfigFile::get_value,DEFVAL(Variant())); - - ObjectTypeDB::bind_method(_MD("has_section","section"),&ConfigFile::has_section); - ObjectTypeDB::bind_method(_MD("has_section_key","section","key"),&ConfigFile::has_section_key); - - ObjectTypeDB::bind_method(_MD("get_sections"),&ConfigFile::_get_sections); - ObjectTypeDB::bind_method(_MD("get_section_keys","section"),&ConfigFile::_get_section_keys); - - ObjectTypeDB::bind_method(_MD("load:Error","path"),&ConfigFile::load); - ObjectTypeDB::bind_method(_MD("save:Error","path"),&ConfigFile::save); + ObjectTypeDB::bind_method(_MD("get_sections"), &ConfigFile::_get_sections); + ObjectTypeDB::bind_method(_MD("get_section_keys", "section"), &ConfigFile::_get_section_keys); + ObjectTypeDB::bind_method(_MD("load:Error", "path"), &ConfigFile::load); + ObjectTypeDB::bind_method(_MD("save:Error", "path"), &ConfigFile::save); } - -ConfigFile::ConfigFile() -{ +ConfigFile::ConfigFile() { } diff --git a/core/io/config_file.h b/core/io/config_file.h index 6481f05222a..882bb572dd2 100644 --- a/core/io/config_file.h +++ b/core/io/config_file.h @@ -31,31 +31,30 @@ #include "reference.h" - class ConfigFile : public Reference { - OBJ_TYPE(ConfigFile,Reference); + OBJ_TYPE(ConfigFile, Reference); - Map< String, Map > values; + Map > values; StringArray _get_sections() const; - StringArray _get_section_keys(const String& p_section) const; + StringArray _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; - 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 *r_sections) const; - void get_section_keys(const String& p_section,List *r_keys) const; + void get_section_keys(const String &p_section, List *r_keys) const; - 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/export_data.cpp b/core/io/export_data.cpp index 2495288a7c6..29018c7c6ef 100644 --- a/core/io/export_data.cpp +++ b/core/io/export_data.cpp @@ -1,2 +1 @@ #include "export_data.h" - diff --git a/core/io/export_data.h b/core/io/export_data.h index 1e1941bad3d..dc2584984ed 100644 --- a/core/io/export_data.h +++ b/core/io/export_data.h @@ -1,9 +1,9 @@ #ifndef EXPORT_DATA_H #define EXPORT_DATA_H +#include "map.h" #include "variant.h" #include "vector.h" -#include "map.h" struct ExportData { struct Dependency { @@ -11,7 +11,7 @@ struct ExportData { String type; }; - Map dependencies; + Map dependencies; struct PropertyData { String name; @@ -23,12 +23,10 @@ struct ExportData { String type; int index; List properties; - }; Vector resources; - struct NodeData { bool text_data; @@ -41,19 +39,20 @@ struct ExportData { int parent_int; bool instance_is_placeholder; - //text info NodePath parent; NodePath owner; String instance_placeholder; - - Vector groups; List properties; - - NodeData() { parent_int=0; owner_int=0; text_data=true; instanced=false;} + NodeData() { + parent_int = 0; + owner_int = 0; + text_data = true; + instanced = false; + } }; Vector nodes; @@ -72,7 +71,7 @@ struct ExportData { Array binds; int flags; - Connection() { text_data=true; } + Connection() { text_data = true; } }; Vector connections; @@ -80,8 +79,6 @@ struct ExportData { Array node_paths; //for integer packed data Variant base_scene; - - }; #endif // EXPORT_DATA_H diff --git a/core/io/file_access_buffered.cpp b/core/io/file_access_buffered.cpp index 347edc74075..1a0423a0502 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); //DVector::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 be8ea714b10..964152af5e6 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 8a15584b137..a6638e08ae0 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 +template 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() ); + return memnew(FileAccessBufferedFA()); }; 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 ); @@ -127,21 +125,19 @@ public: set_error(OK); }; -// static void make_default() { + // static void make_default() { - //FileAccess::create_func = FileAccessBufferedFA::create; -// }; + //FileAccess::create_func = FileAccessBufferedFA::create; + // }; - 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 3bcfade5263..d8ae3e6ff12 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;iget_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;istore_32(0); //compressed sizes, will update later } - Vector block_sizes; - for(int i=0;i 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;istore_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_blockget_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=read_block_size) { + if (read_pos >= read_block_size) { read_block++; - if (read_blockget_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 (iget_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 70034120f97..ea45c110d23 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 read_blocks; int read_total; - - - String magic; mutable Vector 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 039458237d7..03700cad48b 100644 --- a/core/io/file_access_encrypted.cpp +++ b/core/io/file_access_encrypted.cpp @@ -36,55 +36,55 @@ #include "core/variant.h" #include -Error FileAccessEncrypted::open_and_parse(FileAccess *p_base,const Vector& p_key,Mode p_mode) { +Error FileAccessEncrypted::open_and_parse(FileAccess *p_base, const Vector &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 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 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;istore_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 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 &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& 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 e1f6831f7bd..47091007701 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 "globals.h" #include "map.h" +#include "os/copymem.h" +#include "os/dir_access.h" -static Map >* files = NULL; +static Map > *files = NULL; void FileAccessMemory::register_file(String p_name, Vector p_data) { @@ -59,37 +59,35 @@ 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); + // name = DirAccess::normalize_path(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); + // name = DirAccess::normalize_path(name); - Map >::Element* E = files->find(name); + Map >::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 c6dda079715..687e3e9beec 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 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 3516ad88080..1b7a052de77 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 "globals.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 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(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(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::create_ref() ); - sem=Semaphore::create(); - lockcount=0; + quit = false; + singleton = this; + last_id = 0; + client = Ref(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,72 +241,64 @@ FileAccessNetworkClient::~FileAccessNetworkClient() { memdelete(blockrequest_mutex); memdelete(mutex); memdelete(sem); - - } -void FileAccessNetwork::_set_block(size_t p_offset,const Vector& p_block) { +void FileAccessNetwork::_set_block(size_t p_offset, const Vector &p_block) { - - int page = p_offset/page_size; - ERR_FAIL_INDEX(page,pages.size()); - if (pagelock(); - 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(); + // buffers.clear(); nc->unlock_mutex(); DEBUG_PRINT("OPEN POST"); DEBUG_TIME("open_post"); @@ -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; + // FileAccessNetworkClient *nc = FileAccessNetworkClient::singleton; - uint8_t *buff=last_page_buff; + uint8_t *buff = last_page_buff; - for(int i=0;ilock(); if (pages[page].buffer.empty()) { //fuck - waiting_on_page=page; - for(int j=0;junlock(); 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;junlock(); } - 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,63 +458,59 @@ 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; - } 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_DEF("remote_fs/page_size",65536); - read_ahead = GLOBAL_DEF("remote_fs/page_read_ahead",4); - max_pages = GLOBAL_DEF("remote_fs/max_pages",20); - last_activity_val=0; - waiting_on_page=-1; - last_page=-1; - - + page_size = GLOBAL_DEF("remote_fs/page_size", 65536); + read_ahead = GLOBAL_DEF("remote_fs/page_read_ahead", 4); + max_pages = GLOBAL_DEF("remote_fs/max_pages", 20); + last_activity_val = 0; + waiting_on_page = -1; + last_page = -1; } FileAccessNetwork::~FileAccessNetwork() { @@ -560,8 +522,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 867991bcbee..a77053184d3 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 accesses; + Map accesses; Ref 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 buffer; - Page() { activity=0; queued=false; } + Page() { + activity = 0; + queued = false; + } }; - mutable Vector< Page > pages; + mutable Vector 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& p_block); + void _respond(size_t p_len, Error p_status); + void _set_block(size_t p_offset, const Vector &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); FileAccessNetwork(); ~FileAccessNetwork(); diff --git a/core/io/file_access_pack.cpp b/core/io/file_access_pack.cpp index e6d22fd383b..d32d695ff9d 100644 --- a/core/io/file_access_pack.cpp +++ b/core/io/file_access_pack.cpp @@ -33,9 +33,9 @@ #define PACK_VERSION 0 -Error PackedData::add_pack(const String& p_path) { +Error PackedData::add_pack(const String &p_path) { - for (int i=0; itry_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 ds=p.get_base_dir().split("/"); + Vector ds = p.get_base_dir().split("/"); - for(int j=0;jsubdirs.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::Element *E=p_dir->subdirs.front();E;E=E->next()) + for (Map::Element *E = p_dir->subdirs.front(); E; E = E->next()) _free_packed_dirs(E->get()); memdelete(p_dir); } PackedData::~PackedData() { - for(int i=0;iget_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 newer than supported by engine: "+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 newer than supported by engine: " + 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;iget_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 ////////////////////////////////////////////////////////////////////////////////// - bool DirAccessPack::list_dir_begin() { - list_dirs.clear(); list_files.clear(); - for (Map::Element *E=current->subdirs.front();E;E=E->next()) { + for (Map::Element *E = current->subdirs.front(); E; E = E->next()) { list_dirs.push_back(E->key()); } - for (Set::Element *E=current->files.front();E;E=E->next()) { + for (Set::Element *E = current->files.front(); E; E = E->next()) { list_files.push_back(E->get()); } @@ -359,15 +347,15 @@ bool DirAccessPack::list_dir_begin() { return true; } -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,18 +388,18 @@ 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.begins_with("/")) { - nd=nd.replace_first("/","") ; - absolute=true; + nd = nd.replace_first("/", ""); + absolute = true; } Vector paths = nd.split("/"); @@ -423,18 +411,18 @@ Error DirAccessPack::change_dir(String p_dir) { else pd = current; - for(int i=0;iparent) { - pd=pd->parent; + pd = pd->parent; } } else if (pd->subdirs.has(p)) { - pd=pd->subdirs[p]; + pd = pd->subdirs[p]; } else { @@ -442,29 +430,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); } @@ -474,36 +459,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 83340a662b3..017bef94c0d 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 subdirs; + Map subdirs; Set 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 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 files; + Map files; - Vector sources; + Vector sources; PackedDir *root; //Map 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 void store_buffer(const uint8_t *p_src, int p_length); - virtual bool file_exists(const String& p_name); + 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::Element *E=files.find(pmd5); + Map::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 list_dirs; @@ -208,7 +197,6 @@ class DirAccessPack : public DirAccess { bool cdir; public: - virtual bool 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 c4439f2599f..fcc19dea286 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.extension().nocasecmp_to("zip") != 0 && p_name.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;iadd_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)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 e34bc1283a4..7d5be8678d7 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 #include "core/io/file_access_pack.h" -#include "unzip.h" #include "map.h" +#include "unzip.h" +#include class ZipArchive : public PackSource { public: - struct File { int package; @@ -50,23 +49,20 @@ public: }; }; - private: - struct Package { String filename; unzFile zfile; }; Vector packages; - Map files; + Map 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 1a5c25954ad..adc95e96210 100644 --- a/core/io/http_client.cpp +++ b/core/io/http_client.cpp @@ -33,53 +33,48 @@ void HTTPClient::set_ip_type(IP::Type p_type) { ip_type = p_type; } -Error HTTPClient::connect(const String &p_host, int p_port, bool p_ssl,bool p_verify_host){ +Error HTTPClient::connect(const String &p_host, int p_port, bool p_ssl, bool p_verify_host) { close(); tcp_connection->set_ip_type(ip_type); - 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(IP_Address(conn_host),p_port); + Error err = tcp_connection->connect(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, ip_type); - status=STATUS_RESOLVING; - + resolving = IP::get_singleton()->resolve_hostname_queue_item(conn_host, ip_type); + status = STATUS_RESOLVING; } return OK; } -void HTTPClient::set_connection(const Ref& p_connection){ +void HTTPClient::set_connection(const Ref &p_connection) { close(); - connection=p_connection; - status=STATUS_CONNECTED; - + connection = p_connection; + status = STATUS_CONNECTED; } Ref HTTPClient::get_connection() const { @@ -87,14 +82,13 @@ Ref HTTPClient::get_connection() const { return connection; } -Error HTTPClient::request_raw( Method p_method, const String& p_url, const Vector& p_headers,const DVector& p_body) { +Error HTTPClient::request_raw(Method p_method, const String &p_url, const Vector &p_headers, const DVector &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", @@ -102,54 +96,54 @@ Error HTTPClient::request_raw( Method p_method, const String& p_url, const Vecto "DELETE", "OPTIONS", "TRACE", - "CONNECT"}; + "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 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(); DVector data; //Maybe this goes faster somehow? - for(int i=0;i::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& p_headers,const String& p_body) { +Error HTTPClient::request(Method p_method, const String &p_url, const Vector &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", @@ -157,50 +151,51 @@ Error HTTPClient::request( Method p_method, const String& p_url, const Vector0; - for(int i=0;i 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 ByteArray& p_body){ +Error HTTPClient::send_body_data(const ByteArray &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 { @@ -218,7 +213,7 @@ Error HTTPClient::get_response_headers(List *r_response) { if (!response_headers.size()) return ERR_INVALID_PARAMETER; - for(int i=0;ipush_back(response_headers[i]); } @@ -228,71 +223,67 @@ Error HTTPClient::get_response_headers(List *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(); 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(host,conn_port); + Error err = tcp_connection->connect(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 @@ -300,23 +291,23 @@ Error HTTPClient::poll(){ case StreamPeerTCP::STATUS_CONNECTED: { if (ssl) { Ref ssl = StreamPeerSSL::create(); - Error err = ssl->connect(tcp_connection,true,ssl_verify_host?conn_host:String()); - if (err!=OK) { + Error err = ssl->connect(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; } @@ -327,78 +318,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' && rs>=4 && 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' && rs >= 4 && 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 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 rh; get_response_headers(&rh); Dictionary ret; - for(const List::Element *E=rh.front();E;E=E->next()) { + for (const List::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; @@ -450,9 +433,9 @@ StringArray HTTPClient::_get_response_headers() { get_response_headers(&rh); StringArray ret; ret.resize(rh.size()); - int idx=0; - for(const List::Element *E=rh.front();E;E=E->next()) { - ret.set(idx++,E->get()); + int idx = 0; + for (const List::Element *E = rh.front(); E; E = E->next()) { + ret.set(idx++, E->get()); } return ret; @@ -465,96 +448,93 @@ int HTTPClient::get_response_body_length() const { ByteArray HTTPClient::read_response_body_chunk() { - ERR_FAIL_COND_V( status !=STATUS_BODY, ByteArray() ); + ERR_FAIL_COND_V(status != STATUS_BODY, ByteArray()); - 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 ByteArray(); } - 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='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 ByteArray(); } - 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 ByteArray(); } - } - if (len==0) { + if (len == 0) { //end! - status=STATUS_CONNECTED; + status = STATUS_CONNECTED; chunk.clear(); return ByteArray(); } - 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 ByteArray(); } ByteArray ret; - ret.resize(chunk.size()-2); + ret.resize(chunk.size() - 2); { ByteArray::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; @@ -563,46 +543,44 @@ ByteArray HTTPClient::read_response_body_chunk() { } else { - int to_read = MIN(body_left,read_chunk_size); + int to_read = MIN(body_left, read_chunk_size); ByteArray ret; ret.resize(to_read); int _offset = 0; while (to_read > 0) { - int rec=0; + int rec = 0; { ByteArray::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 ByteArray(); @@ -610,181 +588,174 @@ ByteArray 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() { - ObjectTypeDB::bind_method(_MD("set_ip_type","ip_type"),&HTTPClient::set_ip_type); - ObjectTypeDB::bind_method(_MD("connect:Error","host","port","use_ssl","verify_host"),&HTTPClient::connect,DEFVAL(false),DEFVAL(true)); - ObjectTypeDB::bind_method(_MD("set_connection","connection:StreamPeer"),&HTTPClient::set_connection); - ObjectTypeDB::bind_method(_MD("get_connection:StreamPeer"),&HTTPClient::get_connection); - ObjectTypeDB::bind_method(_MD("request_raw","method","url","headers","body"),&HTTPClient::request_raw); - ObjectTypeDB::bind_method(_MD("request","method","url","headers","body"),&HTTPClient::request,DEFVAL(String())); - ObjectTypeDB::bind_method(_MD("send_body_text","body"),&HTTPClient::send_body_text); - ObjectTypeDB::bind_method(_MD("send_body_data","body"),&HTTPClient::send_body_data); - ObjectTypeDB::bind_method(_MD("close"),&HTTPClient::close); + ObjectTypeDB::bind_method(_MD("set_ip_type", "ip_type"), &HTTPClient::set_ip_type); + ObjectTypeDB::bind_method(_MD("connect:Error", "host", "port", "use_ssl", "verify_host"), &HTTPClient::connect, DEFVAL(false), DEFVAL(true)); + ObjectTypeDB::bind_method(_MD("set_connection", "connection:StreamPeer"), &HTTPClient::set_connection); + ObjectTypeDB::bind_method(_MD("get_connection:StreamPeer"), &HTTPClient::get_connection); + ObjectTypeDB::bind_method(_MD("request_raw", "method", "url", "headers", "body"), &HTTPClient::request_raw); + ObjectTypeDB::bind_method(_MD("request", "method", "url", "headers", "body"), &HTTPClient::request, DEFVAL(String())); + ObjectTypeDB::bind_method(_MD("send_body_text", "body"), &HTTPClient::send_body_text); + ObjectTypeDB::bind_method(_MD("send_body_data", "body"), &HTTPClient::send_body_data); + ObjectTypeDB::bind_method(_MD("close"), &HTTPClient::close); - ObjectTypeDB::bind_method(_MD("has_response"),&HTTPClient::has_response); - ObjectTypeDB::bind_method(_MD("is_response_chunked"),&HTTPClient::is_response_chunked); - ObjectTypeDB::bind_method(_MD("get_response_code"),&HTTPClient::get_response_code); - ObjectTypeDB::bind_method(_MD("get_response_headers"),&HTTPClient::_get_response_headers); - ObjectTypeDB::bind_method(_MD("get_response_headers_as_dictionary"),&HTTPClient::_get_response_headers_as_dictionary); - ObjectTypeDB::bind_method(_MD("get_response_body_length"),&HTTPClient::get_response_body_length); - ObjectTypeDB::bind_method(_MD("read_response_body_chunk"),&HTTPClient::read_response_body_chunk); - ObjectTypeDB::bind_method(_MD("set_read_chunk_size","bytes"),&HTTPClient::set_read_chunk_size); + ObjectTypeDB::bind_method(_MD("has_response"), &HTTPClient::has_response); + ObjectTypeDB::bind_method(_MD("is_response_chunked"), &HTTPClient::is_response_chunked); + ObjectTypeDB::bind_method(_MD("get_response_code"), &HTTPClient::get_response_code); + ObjectTypeDB::bind_method(_MD("get_response_headers"), &HTTPClient::_get_response_headers); + ObjectTypeDB::bind_method(_MD("get_response_headers_as_dictionary"), &HTTPClient::_get_response_headers_as_dictionary); + ObjectTypeDB::bind_method(_MD("get_response_body_length"), &HTTPClient::get_response_body_length); + ObjectTypeDB::bind_method(_MD("read_response_body_chunk"), &HTTPClient::read_response_body_chunk); + ObjectTypeDB::bind_method(_MD("set_read_chunk_size", "bytes"), &HTTPClient::set_read_chunk_size); - ObjectTypeDB::bind_method(_MD("set_blocking_mode","enabled"),&HTTPClient::set_blocking_mode); - ObjectTypeDB::bind_method(_MD("is_blocking_mode_enabled"),&HTTPClient::is_blocking_mode_enabled); + ObjectTypeDB::bind_method(_MD("set_blocking_mode", "enabled"), &HTTPClient::set_blocking_mode); + ObjectTypeDB::bind_method(_MD("is_blocking_mode_enabled"), &HTTPClient::is_blocking_mode_enabled); - ObjectTypeDB::bind_method(_MD("get_status"),&HTTPClient::get_status); - ObjectTypeDB::bind_method(_MD("poll:Error"),&HTTPClient::poll); + ObjectTypeDB::bind_method(_MD("get_status"), &HTTPClient::get_status); + ObjectTypeDB::bind_method(_MD("poll:Error"), &HTTPClient::poll); - ObjectTypeDB::bind_method(_MD("query_string_from_dict:String","fields"),&HTTPClient::query_string_from_dict); + ObjectTypeDB::bind_method(_MD("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( 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( 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 ); + 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() { ip_type = IP::TYPE_ANY; 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 ef0a687cddb..43d6dc721e7 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 { - OBJ_TYPE(HTTPClient,Reference); -public: + OBJ_TYPE(HTTPClient, Reference); +public: enum ResponseCode { // 1xx informational @@ -131,7 +130,6 @@ public: }; private: - IP::Type ip_type; Status status; IP::ResolverID resolving; @@ -160,22 +158,20 @@ 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: - - void set_ip_type(IP::Type p_type); //Error connect_and_get(const String& p_url,bool p_verify_host=true); //connects to a full url and perform request - Error connect(const String &p_host,int p_port,bool p_ssl=false,bool p_verify_host=true); + Error connect(const String &p_host, int p_port, bool p_ssl = false, bool p_verify_host = true); - void set_connection(const Ref& p_connection); + void set_connection(const Ref &p_connection); Ref get_connection() const; - Error request_raw( Method p_method, const String& p_url, const Vector& p_headers,const DVector& p_body); - Error request( Method p_method, const String& p_url, const Vector& p_headers,const String& p_body=String()); - Error send_body_text(const String& p_body); - Error send_body_data(const ByteArray& p_body); + Error request_raw(Method p_method, const String &p_url, const Vector &p_headers, const DVector &p_body); + Error request(Method p_method, const String &p_url, const Vector &p_headers, const String &p_body = String()); + Error send_body_text(const String &p_body); + Error send_body_data(const ByteArray &p_body); void close(); @@ -196,7 +192,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 d4d10e21260..074015950df 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 extensions; get_recognized_extensions(&extensions); - for (List::Element *E=extensions.front();E;E=E->next()) { + for (List::Element *E = extensions.front(); E; E = E->next()) { - if (E->get().nocasecmp_to(p_extension.extension())==0) + if (E->get().nocasecmp_to(p_extension.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.extension(); - - for (int i=0;irecognize(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 *p_extensions) { - for (int i=0;iget_recognized_extensions(p_extensions); - } } -bool ImageLoader::recognize(const String& p_extension) { +bool ImageLoader::recognize(const String &p_extension) { - for (int i=0;irecognize(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 4de7706ab0f..b70170303dd 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 */ - /** * @class ImageScanLineLoader * @author Juan Linietsky @@ -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 *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 *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 *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 *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 b057d72e492..963e8a612ee 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;iresolve_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==IP_Address()) - queue[i].status=IP::RESOLVER_STATUS_ERROR; + if (queue[i].response == IP_Address()) + 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 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_addresses; get_local_addresses(&ip_addresses); - for(List::Element *E=ip_addresses.front();E;E=E->next()) { + for (List::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() { - ObjectTypeDB::bind_method(_MD("resolve_hostname","host","ip_type"),&IP::resolve_hostname,DEFVAL(IP::TYPE_ANY)); - ObjectTypeDB::bind_method(_MD("resolve_hostname_queue_item","host","ip_type"),&IP::resolve_hostname_queue_item,DEFVAL(IP::TYPE_ANY)); - ObjectTypeDB::bind_method(_MD("get_resolve_item_status","id"),&IP::get_resolve_item_status); - ObjectTypeDB::bind_method(_MD("get_resolve_item_address","id"),&IP::get_resolve_item_address); - ObjectTypeDB::bind_method(_MD("erase_resolve_item","id"),&IP::erase_resolve_item); - ObjectTypeDB::bind_method(_MD("get_local_addresses"),&IP::_get_local_addresses); - ObjectTypeDB::bind_method(_MD("clear_cache"),&IP::clear_cache, DEFVAL("")); + ObjectTypeDB::bind_method(_MD("resolve_hostname", "host", "ip_type"), &IP::resolve_hostname, DEFVAL(IP::TYPE_ANY)); + ObjectTypeDB::bind_method(_MD("resolve_hostname_queue_item", "host", "ip_type"), &IP::resolve_hostname_queue_item, DEFVAL(IP::TYPE_ANY)); + ObjectTypeDB::bind_method(_MD("get_resolve_item_status", "id"), &IP::get_resolve_item_status); + ObjectTypeDB::bind_method(_MD("get_resolve_item_address", "id"), &IP::get_resolve_item_address); + ObjectTypeDB::bind_method(_MD("erase_resolve_item", "id"), &IP::erase_resolve_item); + ObjectTypeDB::bind_method(_MD("get_local_addresses"), &IP::_get_local_addresses); + ObjectTypeDB::bind_method(_MD("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_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(RESOLVER_MAX_QUERIES); + BIND_CONSTANT(RESOLVER_INVALID_ID); - BIND_CONSTANT( TYPE_NONE ); - BIND_CONSTANT( TYPE_IPV4 ); - BIND_CONSTANT( TYPE_IPV6 ); - BIND_CONSTANT( TYPE_ANY ); + 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 0a0e75fe7b6..2fa1e46d683 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 { - OBJ_TYPE( IP, Object ); + OBJ_TYPE(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)(); + static IP *(*_create)(); + public: - - - - IP_Address resolve_hostname(const String& p_hostname, Type p_type = TYPE_ANY); + 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 *r_addresses) const=0; + virtual void get_local_addresses(List *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 1fda7fed7b9..e03dac8d342 100644 --- a/core/io/ip_address.cpp +++ b/core/io/ip_address.cpp @@ -33,29 +33,29 @@ IP_Address::operator Variant() const { return operator String(); }*/ -#include #include +#include IP_Address::operator String() const { - 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_string.length()) { break; @@ -84,17 +84,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= 0) { @@ -211,7 +210,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; @@ -219,16 +218,16 @@ _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(); 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); @@ -236,5 +235,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 87f32b0ac2b..200df57aafb 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]; @@ -42,19 +41,19 @@ private: }; 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 { - for (int i=0; i<4; i++) + bool operator==(const IP_Address &p_ip) const { + 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 { - for (int i=0; i<4; i++) + bool operator!=(const IP_Address &p_ip) const { + for (int i = 0; i < 4; i++) if (field32[i] != p_ip.field32[i]) return true; return false; @@ -69,11 +68,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 fac8ebe72bb..a10baf54573 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::INT_ARRAY: @@ -59,12 +57,12 @@ String JSON::_print_var(const Variant& p_var) { String s = "["; Array a = p_var; - for(int i=0;i0) - 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 keys; d.get_key_list(&keys); - for (List::Element *E=keys.front();E;E=E->next()) { + for (List::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 Dictionary& p_dict) { +String JSON::print(const Dictionary &p_dict) { return _print_var(p_dict); } - -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 (true) { - 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,253 +216,236 @@ 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(true); - 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(true); - 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 -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 >= Variant::VARIANT_MAX, ERR_INVALID_DATA); - ERR_FAIL_COND_V(type>=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) { + switch (type) { 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); + ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA); int 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); 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; @@ -107,268 +105,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::MATRIX32: { - ERR_FAIL_COND_V(len<(int)4*6,ERR_INVALID_DATA); + ERR_FAIL_COND_V(len < (int)4 * 6, ERR_INVALID_DATA); Matrix32 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::_AABB: { - ERR_FAIL_COND_V(len<(int)4*6,ERR_INVALID_DATA); + ERR_FAIL_COND_V(len < (int)4 * 6, ERR_INVALID_DATA); AABB 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::MATRIX3: { - ERR_FAIL_COND_V(len<(int)4*9,ERR_INVALID_DATA); + ERR_FAIL_COND_V(len < (int)4 * 9, ERR_INVALID_DATA); Matrix3 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); DVector data; data.resize(datalen); DVector::Write wr = data.write(); - copymem(&wr[0],&buf[20],datalen); + copymem(&wr[0], &buf[20], datalen); wr = DVector::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 names; Vector 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;ilen,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 (ilen,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; @@ -383,64 +375,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::JOYSTICK_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::JOYSTICK_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; } @@ -449,125 +439,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(shared); + Dictionary d(shared); - for(uint32_t i=0;ilen,ERR_INVALID_DATA); - + buf += 4; + len -= 4; + ERR_FAIL_COND_V((int)count > len, ERR_INVALID_DATA); DVector data; if (count) { data.resize(count); DVector::Write w = data.write(); - for(int i=0;i::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::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); DVector data; @@ -575,26 +561,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); DVector::Write w = data.write(); - for(int i=0;i::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::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); DVector data; @@ -602,186 +588,177 @@ Error decode_variant(Variant& r_variant,const uint8_t *p_buffer, int p_len,int * //const float*rbuf=(const float*)buf; data.resize(count); DVector::Write w = data.write(); - for(int i=0;i::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::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); - ERR_FAIL_COND_V(count<0,ERR_INVALID_DATA); + ERR_FAIL_COND_V(count < 0, ERR_INVALID_DATA); DVector 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::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); - ERR_FAIL_COND_V(count<0,ERR_INVALID_DATA); - buf+=4; - len-=4; + ERR_FAIL_COND_V(count < 0, ERR_INVALID_DATA); + 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); DVector varray; if (r_len) { - (*r_len)+=4; + (*r_len) += 4; } if (count) { varray.resize(count); DVector::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::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); - ERR_FAIL_COND_V(count<0,ERR_INVALID_DATA); - buf+=4; - len-=4; + ERR_FAIL_COND_V(count < 0, ERR_INVALID_DATA); + 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); DVector varray; if (r_len) { - (*r_len)+=4; + (*r_len) += 4; } if (count) { varray.resize(count); DVector::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::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); - ERR_FAIL_COND_V(count<0,ERR_INVALID_DATA); - buf+=4; - len-=4; + ERR_FAIL_COND_V(count < 0, ERR_INVALID_DATA); + 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); DVector carray; if (r_len) { - (*r_len)+=4; + (*r_len) += 4; } if (count) { carray.resize(count); DVector::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); } @@ -790,19 +767,19 @@ 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; if (buf) { - encode_uint32(p_variant.get_type(),buf); - buf+=4; + encode_uint32(p_variant.get_type(), buf); + buf += 4; } - r_len+=4; + r_len += 4; - switch(p_variant.get_type()) { + switch (p_variant.get_type()) { case Variant::NIL: { @@ -811,96 +788,94 @@ 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: { if (buf) { - encode_uint32(p_variant.operator int(),buf); + encode_uint32(p_variant.operator int(), buf); } - r_len+=4; + r_len += 4; } break; case Variant::REAL: { if (buf) { - encode_float(p_variant.operator float(),buf); + encode_float(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 data=image.get_data(); + DVector data = image.get_data(); if (buf) { - encode_uint32(image.get_format(),&buf[0]); - encode_uint32(image.get_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.get_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]); DVector::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: { @@ -1084,84 +1053,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::JOYSTICK_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::JOYSTICK_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; @@ -1170,16 +1136,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())|(d.is_shared()?0x80000000:0),buf); - buf+=4; + encode_uint32(uint32_t(d.size()) | (d.is_shared() ? 0x80000000 : 0), buf); + buf += 4; } - r_len+=4; + r_len += 4; List keys; d.get_key_list(&keys); - - for(List::Element *E=keys.front();E;E=E->next()) { + for (List::Element *E = keys.front(); E; E = E->next()) { /* CharString utf8 = E->->utf8(); @@ -1195,14 +1160,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; } @@ -1213,107 +1178,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())|(v.is_shared()?0x80000000:0),buf); - buf+=4; + encode_uint32(uint32_t(v.size()) | (v.is_shared() ? 0x80000000 : 0), buf); + buf += 4; } - r_len+=4; + r_len += 4; - for(int i=0;i 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; DVector::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::INT_ARRAY: { DVector 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; DVector::Read r = data.read(); - for(int i=0;i 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; DVector::Read r = data.read(); - for(int i=0;i 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 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 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 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>=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/packet_peer.cpp b/core/io/packet_peer.cpp index fc95aa0b1e1..3c6aec1be12 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 "globals.h" +#include "io/marshalls.h" /* helpers / binders */ - - PacketPeer::PacketPeer() { - last_get_error=OK; + last_get_error = OK; } Error PacketPeer::get_packet_buffer(DVector &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; DVector::Write w = r_buffer.write(); - for(int i=0;i &p_buffer) { int len = p_buffer.size(); - if (len==0) + if (len == 0) return OK; DVector::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 DVector &p_buffer) { +Error PacketPeer::_put_packet(const DVector &p_buffer) { return put_packet_buffer(p_buffer); } DVector PacketPeer::_get_packet() const { DVector 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() { - ObjectTypeDB::bind_method(_MD("get_var:Variant"),&PacketPeer::_bnd_get_var); - ObjectTypeDB::bind_method(_MD("put_var", "var:Variant"),&PacketPeer::put_var); - ObjectTypeDB::bind_method(_MD("get_packet"),&PacketPeer::_get_packet); - ObjectTypeDB::bind_method(_MD("put_packet:Error", "buffer"),&PacketPeer::_put_packet); - ObjectTypeDB::bind_method(_MD("get_packet_error:Error"),&PacketPeer::_get_packet_error); - ObjectTypeDB::bind_method(_MD("get_available_packet_count"),&PacketPeer::get_available_packet_count); + ObjectTypeDB::bind_method(_MD("get_var:Variant"), &PacketPeer::_bnd_get_var); + ObjectTypeDB::bind_method(_MD("put_var", "var:Variant"), &PacketPeer::put_var); + ObjectTypeDB::bind_method(_MD("get_packet"), &PacketPeer::_get_packet); + ObjectTypeDB::bind_method(_MD("put_packet:Error", "buffer"), &PacketPeer::_put_packet); + ObjectTypeDB::bind_method(_MD("get_packet_error:Error"), &PacketPeer::_get_packet_error); + ObjectTypeDB::bind_method(_MD("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() { - ObjectTypeDB::bind_method(_MD("set_stream_peer","peer:StreamPeer"),&PacketPeerStream::_set_stream_peer); + ObjectTypeDB::bind_method(_MD("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;iput_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 &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,18 +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_DEF( "core/packet_stream_peer_max_buffer_po2",(16)); + int rbsize = GLOBAL_DEF("core/packet_stream_peer_max_buffer_po2", (16)); ring_buffer.resize(rbsize); - temp_buffer.resize(1< &p_buffer); DVector _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 DVector &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 { - OBJ_TYPE(PacketPeerStream,PacketPeer); + OBJ_TYPE(PacketPeerStream, PacketPeer); //the way the buffers work sucks, will change later @@ -80,23 +77,21 @@ class PacketPeerStream : public PacketPeer { mutable Vector 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& p_peer); + void set_stream_peer(const Ref &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 6216176e772..eb51a4207cd 100644 --- a/core/io/packet_peer_udp.cpp +++ b/core/io/packet_peer_udp.cpp @@ -29,25 +29,25 @@ #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_send_address(const String& p_address, int p_port) { +Error PacketPeerUDP::_set_send_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_type); - if (ip==IP_Address()) + ip = IP::get_singleton()->resolve_hostname(p_address, ip_type); + if (ip == IP_Address()) return ERR_CANT_RESOLVE; } - set_send_address(ip,p_port); + set_send_address(ip, p_port); return OK; } @@ -58,17 +58,15 @@ void PacketPeerUDP::set_ip_type(IP::Type p_type) { void PacketPeerUDP::_bind_methods() { - ObjectTypeDB::bind_method(_MD("set_ip_type","ip_type"),&PacketPeerUDP::set_ip_type); - ObjectTypeDB::bind_method(_MD("listen:Error","port", "recv_buf_size"),&PacketPeerUDP::listen,DEFVAL(65536)); - ObjectTypeDB::bind_method(_MD("close"),&PacketPeerUDP::close); - ObjectTypeDB::bind_method(_MD("wait:Error"),&PacketPeerUDP::wait); - ObjectTypeDB::bind_method(_MD("is_listening"),&PacketPeerUDP::is_listening); - ObjectTypeDB::bind_method(_MD("get_packet_ip"),&PacketPeerUDP::_get_packet_ip); + ObjectTypeDB::bind_method(_MD("set_ip_type", "ip_type"), &PacketPeerUDP::set_ip_type); + ObjectTypeDB::bind_method(_MD("listen:Error", "port", "recv_buf_size"), &PacketPeerUDP::listen, DEFVAL(65536)); + ObjectTypeDB::bind_method(_MD("close"), &PacketPeerUDP::close); + ObjectTypeDB::bind_method(_MD("wait:Error"), &PacketPeerUDP::wait); + ObjectTypeDB::bind_method(_MD("is_listening"), &PacketPeerUDP::is_listening); + ObjectTypeDB::bind_method(_MD("get_packet_ip"), &PacketPeerUDP::_get_packet_ip); //ObjectTypeDB::bind_method(_MD("get_packet_address"),&PacketPeerUDP::_get_packet_address); - ObjectTypeDB::bind_method(_MD("get_packet_port"),&PacketPeerUDP::get_packet_port); - ObjectTypeDB::bind_method(_MD("set_send_address","host","port"),&PacketPeerUDP::_set_send_address); - - + ObjectTypeDB::bind_method(_MD("get_packet_port"), &PacketPeerUDP::get_packet_port); + ObjectTypeDB::bind_method(_MD("set_send_address", "host", "port"), &PacketPeerUDP::_set_send_address); } Ref PacketPeerUDP::create_ref() { @@ -78,14 +76,13 @@ Ref PacketPeerUDP::create_ref() { return Ref(_create()); } -PacketPeerUDP* PacketPeerUDP::create() { +PacketPeerUDP *PacketPeerUDP::create() { if (!_create) return NULL; return _create(); } -PacketPeerUDP::PacketPeerUDP() -{ +PacketPeerUDP::PacketPeerUDP() { ip_type = IP::TYPE_ANY; } diff --git a/core/io/packet_peer_udp.h b/core/io/packet_peer_udp.h index 5f80ea08fcd..e17f9b505e7 100644 --- a/core/io/packet_peer_udp.h +++ b/core/io/packet_peer_udp.h @@ -29,38 +29,34 @@ #ifndef PACKET_PEER_UDP_H #define PACKET_PEER_UDP_H - #include "io/ip.h" #include "io/packet_peer.h" class PacketPeerUDP : public PacketPeer { - OBJ_TYPE(PacketPeerUDP,PacketPeer); + OBJ_TYPE(PacketPeerUDP, PacketPeer); protected: - IP::Type ip_type; - static PacketPeerUDP* (*_create)(); + static PacketPeerUDP *(*_create)(); static void _bind_methods(); String _get_packet_ip() const; - virtual Error _set_send_address(const String& p_address,int p_port); + virtual Error _set_send_address(const String &p_address, int p_port); public: - virtual void set_ip_type(IP::Type p_type); - virtual Error listen(int p_port, 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_send_address(const IP_Address& p_address,int p_port)=0; - + virtual Error listen(int p_port, 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_send_address(const IP_Address &p_address, int p_port) = 0; static Ref create_ref(); - static PacketPeerUDP* create(); + static PacketPeerUDP *create(); PacketPeerUDP(); }; diff --git a/core/io/pck_packer.cpp b/core/io/pck_packer.cpp index 6d35acf1829..35690e696c2 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; istore_8(0); }; @@ -52,13 +52,12 @@ static void _pad(FileAccess* p_file, int p_bytes) { void PCKPacker::_bind_methods() { - ObjectTypeDB::bind_method(_MD("pck_start","pck_name","alignment"),&PCKPacker::pck_start); - ObjectTypeDB::bind_method(_MD("add_file","pck_path","source_path"),&PCKPacker::add_file); - ObjectTypeDB::bind_method(_MD("flush","verbose"),&PCKPacker::flush); + ObjectTypeDB::bind_method(_MD("pck_start", "pck_name", "alignment"), &PCKPacker::pck_start); + ObjectTypeDB::bind_method(_MD("add_file", "pck_path", "source_path"), &PCKPacker::add_file); + ObjectTypeDB::bind_method(_MD("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; istore_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 0) { diff --git a/core/io/pck_packer.h b/core/io/pck_packer.h index 2ed5c050c6f..a532fc1730d 100644 --- a/core/io/pck_packer.h +++ b/core/io/pck_packer.h @@ -34,7 +34,7 @@ class PCKPacker : public Reference { OBJ_TYPE(PCKPacker, Reference); - FileAccess* file; + FileAccess *file; int alignment; static void _bind_methods(); @@ -49,11 +49,10 @@ class PCKPacker : public Reference { Vector 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 16bcda39825..d9f2eac7244 100644 --- a/core/io/resource_format_binary.cpp +++ b/core/io/resource_format_binary.cpp @@ -26,314 +26,344 @@ /* 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 "globals.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_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, - IMAGE_ENCODING_EMPTY=0, - IMAGE_ENCODING_RAW=1, - IMAGE_ENCODING_LOSSLESS=2, - IMAGE_ENCODING_LOSSY=3, + IMAGE_ENCODING_EMPTY = 0, + IMAGE_ENCODING_RAW = 1, + IMAGE_ENCODING_LOSSLESS = 2, + IMAGE_ENCODING_LOSSY = 3, - IMAGE_FORMAT_GRAYSCALE=0, - IMAGE_FORMAT_INTENSITY=1, - IMAGE_FORMAT_GRAYSCALE_ALPHA=2, - IMAGE_FORMAT_RGB=3, - IMAGE_FORMAT_RGBA=4, - IMAGE_FORMAT_INDEXED=5, - IMAGE_FORMAT_INDEXED_ALPHA=6, - IMAGE_FORMAT_BC1=7, - IMAGE_FORMAT_BC2=8, - IMAGE_FORMAT_BC3=9, - IMAGE_FORMAT_BC4=10, - IMAGE_FORMAT_BC5=11, - IMAGE_FORMAT_PVRTC2=12, - IMAGE_FORMAT_PVRTC2_ALPHA=13, - IMAGE_FORMAT_PVRTC4=14, - IMAGE_FORMAT_PVRTC4_ALPHA=15, - IMAGE_FORMAT_ETC=16, - IMAGE_FORMAT_ATC=17, - IMAGE_FORMAT_ATC_ALPHA_EXPLICIT=18, - IMAGE_FORMAT_ATC_ALPHA_INTERPOLATED=19, - IMAGE_FORMAT_CUSTOM=30, - - - OBJECT_EMPTY=0, - OBJECT_EXTERNAL_RESOURCE=1, - OBJECT_INTERNAL_RESOURCE=2, - OBJECT_EXTERNAL_RESOURCE_INDEX=3, - FORMAT_VERSION=1, - FORMAT_VERSION_CAN_RENAME_DEPS=1 + IMAGE_FORMAT_GRAYSCALE = 0, + IMAGE_FORMAT_INTENSITY = 1, + IMAGE_FORMAT_GRAYSCALE_ALPHA = 2, + IMAGE_FORMAT_RGB = 3, + IMAGE_FORMAT_RGBA = 4, + IMAGE_FORMAT_INDEXED = 5, + IMAGE_FORMAT_INDEXED_ALPHA = 6, + IMAGE_FORMAT_BC1 = 7, + IMAGE_FORMAT_BC2 = 8, + IMAGE_FORMAT_BC3 = 9, + IMAGE_FORMAT_BC4 = 10, + IMAGE_FORMAT_BC5 = 11, + IMAGE_FORMAT_PVRTC2 = 12, + IMAGE_FORMAT_PVRTC2_ALPHA = 13, + IMAGE_FORMAT_PVRTC4 = 14, + IMAGE_FORMAT_PVRTC4_ALPHA = 15, + IMAGE_FORMAT_ETC = 16, + IMAGE_FORMAT_ATC = 17, + IMAGE_FORMAT_ATC_ALPHA_EXPLICIT = 18, + IMAGE_FORMAT_ATC_ALPHA_INTERPOLATED = 19, + IMAGE_FORMAT_CUSTOM = 30, + OBJECT_EMPTY = 0, + OBJECT_EXTERNAL_RESOURCE = 1, + OBJECT_INTERNAL_RESOURCE = 2, + OBJECT_EXTERNAL_RESOURCE_INDEX = 3, + FORMAT_VERSION = 1, + 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;iget_8(); //pad to 32 } - } -Error ResourceInteractiveLoaderBinary::parse_variant(Variant& r_v,bool p_for_export_data) { - +Error ResourceInteractiveLoaderBinary::parse_variant(Variant &r_v, bool p_for_export_data) { 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_REAL: { - r_v=f->get_real(); + r_v = f->get_real(); } 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: { AABB 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: { Matrix32 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: { Matrix3 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(); Image::Format fmt; - switch(format) { + switch (format) { - case IMAGE_FORMAT_GRAYSCALE: { fmt=Image::FORMAT_GRAYSCALE; } break; - case IMAGE_FORMAT_INTENSITY: { fmt=Image::FORMAT_INTENSITY; } break; - case IMAGE_FORMAT_GRAYSCALE_ALPHA: { fmt=Image::FORMAT_GRAYSCALE_ALPHA; } break; - case IMAGE_FORMAT_RGB: { fmt=Image::FORMAT_RGB; } break; - case IMAGE_FORMAT_RGBA: { fmt=Image::FORMAT_RGBA; } break; - case IMAGE_FORMAT_INDEXED: { fmt=Image::FORMAT_INDEXED; } break; - case IMAGE_FORMAT_INDEXED_ALPHA: { fmt=Image::FORMAT_INDEXED_ALPHA; } break; - case IMAGE_FORMAT_BC1: { fmt=Image::FORMAT_BC1; } break; - case IMAGE_FORMAT_BC2: { fmt=Image::FORMAT_BC2; } break; - case IMAGE_FORMAT_BC3: { fmt=Image::FORMAT_BC3; } break; - case IMAGE_FORMAT_BC4: { fmt=Image::FORMAT_BC4; } break; - case IMAGE_FORMAT_BC5: { fmt=Image::FORMAT_BC5; } break; - case IMAGE_FORMAT_PVRTC2: { fmt=Image::FORMAT_PVRTC2; } break; - case IMAGE_FORMAT_PVRTC2_ALPHA: { fmt=Image::FORMAT_PVRTC2_ALPHA; } break; - case IMAGE_FORMAT_PVRTC4: { fmt=Image::FORMAT_PVRTC4; } break; - case IMAGE_FORMAT_PVRTC4_ALPHA: { fmt=Image::FORMAT_PVRTC4_ALPHA; } break; - case IMAGE_FORMAT_ETC: { fmt=Image::FORMAT_ETC; } break; - case IMAGE_FORMAT_ATC: { fmt=Image::FORMAT_ATC; } break; - case IMAGE_FORMAT_ATC_ALPHA_EXPLICIT: { fmt=Image::FORMAT_ATC_ALPHA_EXPLICIT; } break; - case IMAGE_FORMAT_ATC_ALPHA_INTERPOLATED: { fmt=Image::FORMAT_ATC_ALPHA_INTERPOLATED; } break; - case IMAGE_FORMAT_CUSTOM: { fmt=Image::FORMAT_CUSTOM; } break; + case IMAGE_FORMAT_GRAYSCALE: { + fmt = Image::FORMAT_GRAYSCALE; + } break; + case IMAGE_FORMAT_INTENSITY: { + fmt = Image::FORMAT_INTENSITY; + } break; + case IMAGE_FORMAT_GRAYSCALE_ALPHA: { + fmt = Image::FORMAT_GRAYSCALE_ALPHA; + } break; + case IMAGE_FORMAT_RGB: { + fmt = Image::FORMAT_RGB; + } break; + case IMAGE_FORMAT_RGBA: { + fmt = Image::FORMAT_RGBA; + } break; + case IMAGE_FORMAT_INDEXED: { + fmt = Image::FORMAT_INDEXED; + } break; + case IMAGE_FORMAT_INDEXED_ALPHA: { + fmt = Image::FORMAT_INDEXED_ALPHA; + } break; + case IMAGE_FORMAT_BC1: { + fmt = Image::FORMAT_BC1; + } break; + case IMAGE_FORMAT_BC2: { + fmt = Image::FORMAT_BC2; + } break; + case IMAGE_FORMAT_BC3: { + fmt = Image::FORMAT_BC3; + } break; + case IMAGE_FORMAT_BC4: { + fmt = Image::FORMAT_BC4; + } break; + case IMAGE_FORMAT_BC5: { + fmt = Image::FORMAT_BC5; + } break; + case IMAGE_FORMAT_PVRTC2: { + fmt = Image::FORMAT_PVRTC2; + } break; + case IMAGE_FORMAT_PVRTC2_ALPHA: { + fmt = Image::FORMAT_PVRTC2_ALPHA; + } break; + case IMAGE_FORMAT_PVRTC4: { + fmt = Image::FORMAT_PVRTC4; + } break; + case IMAGE_FORMAT_PVRTC4_ALPHA: { + fmt = Image::FORMAT_PVRTC4_ALPHA; + } break; + case IMAGE_FORMAT_ETC: { + fmt = Image::FORMAT_ETC; + } break; + case IMAGE_FORMAT_ATC: { + fmt = Image::FORMAT_ATC; + } break; + case IMAGE_FORMAT_ATC_ALPHA_EXPLICIT: { + fmt = Image::FORMAT_ATC_ALPHA_EXPLICIT; + } break; + case IMAGE_FORMAT_ATC_ALPHA_INTERPOLATED: { + fmt = Image::FORMAT_ATC_ALPHA_INTERPOLATED; + } break; + case IMAGE_FORMAT_CUSTOM: { + fmt = Image::FORMAT_CUSTOM; + } break; default: { ERR_FAIL_V(ERR_FILE_CORRUPT); } - } - uint32_t datalen = f->get_32(); DVector imgdata; imgdata.resize(datalen); DVector::Write w = imgdata.write(); - f->get_buffer(w.ptr(),datalen); + f->get_buffer(w.ptr(), datalen); _advance_padding(datalen); - w=DVector::Write(); + w = DVector::Write(); - r_v=Image(width,height,mipmaps,fmt,imgdata); + r_v = Image(width, height, mipmaps, fmt, imgdata); } else { //compressed DVector data; data.resize(f->get_32()); DVector::Write w = data.write(); - f->get_buffer(w.ptr(),data.size()); + f->get_buffer(w.ptr(), data.size()); w = DVector::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; @@ -346,80 +376,77 @@ Error ResourceInteractiveLoaderBinary::parse_variant(Variant& r_v,bool p_for_exp 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;iget_32()]); - for(uint32_t i=0;iget_32()]); - property=string_map[f->get_32()]; + property = string_map[f->get_32()]; - 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(); + uint32_t index = f->get_32(); if (p_for_export_data) { - r_v="@RESLOCAL:"+itos(index); + r_v = "@RESLOCAL:" + itos(index); } else { - String path = res_path+"::"+itos(index); + 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: { //old file format, still around for compatibility - String type = get_unicode_string(); String path = get_unicode_string(); if (p_for_export_data) { - r_v="@RESPATH:"+type+":"+path; + r_v = "@RESPATH:" + type + ":" + path; } else { - 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=Globals::get_singleton()->localize_path(res_path.get_base_dir().plus_file(path)); - + path = Globals::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; @@ -428,32 +455,30 @@ Error ResourceInteractiveLoaderBinary::parse_variant(Variant& r_v,bool p_for_exp uint32_t erindex = f->get_32(); if (p_for_export_data) { - r_v="@RESEXTERNAL:"+itos(erindex); + r_v = "@RESEXTERNAL:" + itos(erindex); } else { - 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=Globals::get_singleton()->localize_path(res_path.get_base_dir().plus_file(path)); - + path = Globals::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: { @@ -467,33 +492,33 @@ Error ResourceInteractiveLoaderBinary::parse_variant(Variant& r_v,bool p_for_exp } break; case VARIANT_DICTIONARY: { - uint32_t len=f->get_32(); - Dictionary d(len&0x80000000); //last bit means shared - len&=0x7FFFFFFF; - for(uint32_t i=0;iget_32(); + Dictionary d(len & 0x80000000); //last bit means shared + len &= 0x7FFFFFFF; + for (uint32_t i = 0; i < len; i++) { Variant key; - Error err = parse_variant(key,p_for_export_data); - ERR_FAIL_COND_V(err,ERR_FILE_CORRUPT); + Error err = parse_variant(key, p_for_export_data); + ERR_FAIL_COND_V(err, ERR_FILE_CORRUPT); Variant value; - err = parse_variant(value,p_for_export_data); - ERR_FAIL_COND_V(err,ERR_FILE_CORRUPT); - d[key]=value; + err = parse_variant(value, p_for_export_data); + 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(); - Array a(len&0x80000000); //last bit means shared - len&=0x7FFFFFFF; + uint32_t len = f->get_32(); + Array a(len & 0x80000000); //last bit means shared + len &= 0x7FFFFFFF; a.resize(len); - for(uint32_t i=0;i array; array.resize(len); DVector::Write w = array.write(); - f->get_buffer(w.ptr(),len); + f->get_buffer(w.ptr(), len); _advance_padding(len); - w=DVector::Write(); - r_v=array; + w = DVector::Write(); + r_v = array; } break; case VARIANT_INT_ARRAY: { @@ -516,19 +541,19 @@ Error ResourceInteractiveLoaderBinary::parse_variant(Variant& r_v,bool p_for_exp DVector array; array.resize(len); DVector::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::Write(); - r_v=array; + w = DVector::Write(); + r_v = array; } break; case VARIANT_REAL_ARRAY: { @@ -537,20 +562,20 @@ Error ResourceInteractiveLoaderBinary::parse_variant(Variant& r_v,bool p_for_exp DVector array; array.resize(len); DVector::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::Write(); - r_v=array; + w = DVector::Write(); + r_v = array; } break; case VARIANT_STRING_ARRAY: { @@ -558,11 +583,10 @@ Error ResourceInteractiveLoaderBinary::parse_variant(Variant& r_v,bool p_for_exp DVector array; array.resize(len); DVector::Write w = array.write(); - for(uint32_t i=0;i::Write(); - r_v=array; - + for (uint32_t i = 0; i < len; i++) + w[i] = get_unicode_string(); + w = DVector::Write(); + r_v = array; } break; case VARIANT_VECTOR2_ARRAY: { @@ -572,16 +596,16 @@ Error ResourceInteractiveLoaderBinary::parse_variant(Variant& r_v,bool p_for_exp DVector array; array.resize(len); DVector::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::Write(); - r_v=array; + w = DVector::Write(); + r_v = array; } break; case VARIANT_VECTOR3_ARRAY: { @@ -600,14 +624,14 @@ Error ResourceInteractiveLoaderBinary::parse_variant(Variant& r_v,bool p_for_exp DVector array; array.resize(len); DVector::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::Write(); - r_v=array; + w = DVector::Write(); + r_v = array; } break; case VARIANT_COLOR_ARRAY: { @@ -628,16 +652,16 @@ Error ResourceInteractiveLoaderBinary::parse_variant(Variant& r_v,bool p_for_exp DVector array; array.resize(len); DVector::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::Write(); - r_v=array; + w = DVector::Write(); + r_v = array; } break; default: { @@ -654,47 +678,41 @@ Error ResourceInteractiveLoaderBinary::parse_variant(Variant& r_v,bool p_for_exp } 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 ResourceInteractiveLoaderBinary::get_resource(){ - +Ref ResourceInteractiveLoaderBinary::get_resource() { return resource; } -Error ResourceInteractiveLoaderBinary::poll(){ +Error ResourceInteractiveLoaderBinary::poll() { - if (error!=OK) + if (error != OK) return error; - int s = stage; - 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; @@ -754,20 +767,20 @@ Error ResourceInteractiveLoaderBinary::poll(){ Object *obj = ObjectTypeDB::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(); 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_type()); - ERR_FAIL_COND_V(!r,ERR_FILE_CORRUPT); + ERR_EXPLAIN(local_path + ":Resoucre type in resource field not a resource, type is: " + obj->get_type()); + ERR_FAIL_COND_V(!r, ERR_FILE_CORRUPT); } - RES res = RES( r ); + RES res = RES(r); r->set_path(path); r->set_subindex(subindex); @@ -776,11 +789,11 @@ Error ResourceInteractiveLoaderBinary::poll(){ //set properties - for(int i=0;iget_32(); - if (name_idx>=(uint32_t)string_map.size()) { - error=ERR_FILE_CORRUPT; + if (name_idx >= (uint32_t)string_map.size()) { + error = ERR_FILE_CORRUPT; ERR_FAIL_V(ERR_FILE_CORRUPT); } @@ -790,7 +803,7 @@ Error ResourceInteractiveLoaderBinary::poll(){ if (error) return error; - res->set(string_map[name_idx],value); + res->set(string_map[name_idx], value); } #ifdef TOOLS_ENABLED res->set_edited(false); @@ -803,63 +816,58 @@ Error ResourceInteractiveLoaderBinary::poll(){ if (importmd_ofs) { f->seek(importmd_ofs); - Ref imd = memnew( ResourceImportMetadata ); + Ref imd = memnew(ResourceImportMetadata); imd->set_editor(get_unicode_string()); int sc = f->get_32(); - for(int i=0;iadd_source(src,md5); + imd->add_source(src, md5); } int pc = f->get_32(); - for(int i=0;iset_option(name,val); + imd->set_option(name, val); } res->set_import_metadata(imd); - } 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 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; @@ -868,47 +876,45 @@ 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; } -Error ResourceInteractiveLoaderBinary::get_export_data(ExportData& r_export_data) { +Error ResourceInteractiveLoaderBinary::get_export_data(ExportData &r_export_data) { - for(int i=0;iget_32(); //set properties - for(int i=0;iget_32(); - if (name_idx>=(uint32_t)string_map.size()) { - error=ERR_FILE_CORRUPT; + if (name_idx >= (uint32_t)string_map.size()) { + error = ERR_FILE_CORRUPT; ERR_FAIL_V(ERR_FILE_CORRUPT); } Variant value; - error = parse_variant(value,true); + error = parse_variant(value, true); if (error) return error; ExportData::PropertyData pdata; - pdata.name=string_map[name_idx]; - pdata.value=value; + pdata.name = string_map[name_idx]; + pdata.value = value; res_data.properties.push_back(pdata); } - } return OK; } - - - -void ResourceInteractiveLoaderBinary::get_dependencies(FileAccess *p_f,List *p_dependencies,bool p_add_types) { +void ResourceInteractiveLoaderBinary::get_dependencies(FileAccess *p_f, List *p_dependencies, bool p_add_types) { open(p_f); if (error) return; - for(int i=0;ipush_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(); } @@ -1008,53 +1005,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;iget_32(); - for(uint32_t i=0;iget_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 @@ -1071,46 +1066,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;iget_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 ""; } @@ -1123,30 +1115,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() { @@ -1155,196 +1147,183 @@ ResourceInteractiveLoaderBinary::~ResourceInteractiveLoaderBinary() { memdelete(f); } - Ref 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()); + ERR_FAIL_COND_V(err != OK, Ref()); } - Ref ria = memnew( ResourceInteractiveLoaderBinary ); - ria->local_path=Globals::get_singleton()->localize_path(p_path); - ria->res_path=ria->local_path; -// ria->set_local_path( Globals::get_singleton()->localize_path(p_path) ); + Ref ria = memnew(ResourceInteractiveLoaderBinary); + ria->local_path = Globals::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 *p_extensions) const { +void ResourceFormatLoaderBinary::get_recognized_extensions_for_type(const String &p_type, List *p_extensions) const { - if (p_type=="") { + if (p_type == "") { get_recognized_extensions(p_extensions); return; } List extensions; - ObjectTypeDB::get_extensions_for_type(p_type,&extensions); + ObjectTypeDB::get_extensions_for_type(p_type, &extensions); extensions.sort(); - for(List::Element *E=extensions.front();E;E=E->next()) { + for (List::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 *p_extensions) const{ +void ResourceFormatLoaderBinary::get_recognized_extensions(List *p_extensions) const { List extensions; ObjectTypeDB::get_resource_base_extensions(&extensions); extensions.sort(); - for(List::Element *E=extensions.front();E;E=E->next()) { + for (List::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 } -Error ResourceFormatLoaderBinary::load_import_metadata(const String &p_path, Ref& r_var) const { +Error ResourceFormatLoaderBinary::load_import_metadata(const String &p_path, Ref &r_var) const { - - FileAccess *f = FileAccess::open(p_path,FileAccess::READ); + FileAccess *f = FileAccess::open(p_path, FileAccess::READ); if (!f) { return ERR_FILE_CANT_OPEN; } - Ref ria = memnew( ResourceInteractiveLoaderBinary ); - ria->local_path=Globals::get_singleton()->localize_path(p_path); - ria->res_path=ria->local_path; -// ria->set_local_path( Globals::get_singleton()->localize_path(p_path) ); + Ref ria = memnew(ResourceInteractiveLoaderBinary); + ria->local_path = Globals::get_singleton()->localize_path(p_path); + ria->res_path = ria->local_path; + // ria->set_local_path( Globals::get_singleton()->localize_path(p_path) ); ria->recognize(f); - if(ria->error!=OK) + if (ria->error != OK) return ERR_FILE_UNRECOGNIZED; - f=ria->f; + f = ria->f; uint64_t imp_ofs = f->get_64(); - if (imp_ofs==0) + if (imp_ofs == 0) return ERR_UNAVAILABLE; f->seek(imp_ofs); - Ref imd = memnew( ResourceImportMetadata ); + Ref imd = memnew(ResourceImportMetadata); imd->set_editor(ria->get_unicode_string()); int sc = f->get_32(); - for(int i=0;iget_unicode_string(); String md5 = ria->get_unicode_string(); - imd->add_source(src,md5); + imd->add_source(src, md5); } int pc = f->get_32(); - for(int i=0;iget_unicode_string(); Variant val; ria->parse_variant(val); - imd->set_option(name,val); + imd->set_option(name, val); } - r_var=imd; + r_var = imd; return OK; - } -ResourceFormatLoaderBinary *ResourceFormatLoaderBinary::singleton=NULL; +ResourceFormatLoaderBinary *ResourceFormatLoaderBinary::singleton = NULL; -void ResourceFormatLoaderBinary::get_dependencies(const String& p_path,List *p_dependencies,bool p_add_types) { +void ResourceFormatLoaderBinary::get_dependencies(const String &p_path, List *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 ria = memnew( ResourceInteractiveLoaderBinary ); - ria->local_path=Globals::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); + Ref ria = memnew(ResourceInteractiveLoaderBinary); + ria->local_path = Globals::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); } - -Error ResourceFormatLoaderBinary::get_export_data(const String& p_path,ExportData& r_export_data) { +Error ResourceFormatLoaderBinary::get_export_data(const String &p_path, ExportData &r_export_data) { 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,ERR_CANT_OPEN); + ERR_FAIL_COND_V(err != OK, ERR_CANT_OPEN); } - Ref ria = memnew( ResourceInteractiveLoaderBinary ); - ria->local_path=Globals::get_singleton()->localize_path(p_path); - ria->res_path=ria->local_path; -// ria->set_local_path( Globals::get_singleton()->localize_path(p_path) ); + Ref ria = memnew(ResourceInteractiveLoaderBinary); + ria->local_path = Globals::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->get_export_data(r_export_data); - } -Error ResourceFormatLoaderBinary::rename_dependencies(const String &p_path,const Map& p_map) { +Error ResourceFormatLoaderBinary::rename_dependencies(const String &p_path, const Map &p_map) { + // Error error=OK; -// Error error=OK; + 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 *f=FileAccess::open(p_path,FileAccess::READ); - ERR_FAIL_COND_V(!f,ERR_CANT_OPEN); - - 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(); @@ -1356,144 +1335,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_formatremove(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 ria = memnew( ResourceInteractiveLoaderBinary ); - ria->local_path=Globals::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) ); + Ref ria = memnew(ResourceInteractiveLoaderBinary); + ria->local_path = Globals::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;iget_32(); + uint32_t ext_resources_size = f->get_32(); fw->store_32(ext_resources_size); - for(uint32_t i=0;iget_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;iget_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); @@ -1504,50 +1478,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 ria = memnew( ResourceInteractiveLoaderBinary ); - ria->local_path=Globals::get_singleton()->localize_path(p_path); - ria->res_path=ria->local_path; -// ria->set_local_path( Globals::get_singleton()->localize_path(p_path) ); + Ref ria = memnew(ResourceInteractiveLoaderBinary); + ria->local_path = Globals::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;istore_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: { @@ -1557,33 +1523,33 @@ 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: { f->store_32(VARIANT_INT); - int val=p_property; + int val = p_property; f->store_32(val); } break; case Variant::REAL: { f->store_32(VARIANT_REAL); - real_t val=p_property; + real_t val = p_property; f->store_real(val); } 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); @@ -1591,7 +1557,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); @@ -1601,7 +1567,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); @@ -1610,7 +1576,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); @@ -1620,7 +1586,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); @@ -1630,7 +1596,7 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, case Variant::_AABB: { f->store_32(VARIANT_AABB); - AABB val=p_property; + AABB val = p_property; f->store_real(val.pos.x); f->store_real(val.pos.y); f->store_real(val.pos.z); @@ -1642,7 +1608,7 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, case Variant::MATRIX32: { f->store_32(VARIANT_MATRIX32); - Matrix32 val=p_property; + Matrix32 val = p_property; f->store_real(val.elements[0].x); f->store_real(val.elements[0].y); f->store_real(val.elements[1].x); @@ -1654,7 +1620,7 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, case Variant::MATRIX3: { f->store_32(VARIANT_MATRIX3); - Matrix3 val=p_property; + Matrix3 val = p_property; f->store_real(val.elements[0].x); f->store_real(val.elements[0].y); f->store_real(val.elements[0].z); @@ -1669,7 +1635,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); @@ -1687,7 +1653,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); @@ -1697,104 +1663,123 @@ 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.get_format() <= Image::FORMAT_INDEXED_ALPHA) { //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()); f->store_32(val.get_mipmaps()); - switch(val.get_format()) { + switch (val.get_format()) { - case Image::FORMAT_GRAYSCALE: f->store_32(IMAGE_FORMAT_GRAYSCALE ); break; ///< one byte per pixel: f->store_32(IMAGE_FORMAT_ ); break; 0-255 - case Image::FORMAT_INTENSITY: f->store_32(IMAGE_FORMAT_INTENSITY ); break; ///< one byte per pixel: f->store_32(IMAGE_FORMAT_ ); break; 0-255 - case Image::FORMAT_GRAYSCALE_ALPHA: f->store_32(IMAGE_FORMAT_GRAYSCALE_ALPHA ); break; ///< two bytes per pixel: f->store_32(IMAGE_FORMAT_ ); break; 0-255. alpha 0-255 - case Image::FORMAT_RGB: f->store_32(IMAGE_FORMAT_RGB ); break; ///< one byte R: f->store_32(IMAGE_FORMAT_ ); break; one byte G: f->store_32(IMAGE_FORMAT_ ); break; one byte B - case Image::FORMAT_RGBA: f->store_32(IMAGE_FORMAT_RGBA ); break; ///< one byte R: f->store_32(IMAGE_FORMAT_ ); break; one byte G: f->store_32(IMAGE_FORMAT_ ); break; one byte B: f->store_32(IMAGE_FORMAT_ ); break; one byte A - case Image::FORMAT_INDEXED: f->store_32(IMAGE_FORMAT_INDEXED ); break; ///< index byte 0-256: f->store_32(IMAGE_FORMAT_ ); break; and after image end: f->store_32(IMAGE_FORMAT_ ); break; 256*3 bytes of palette - case Image::FORMAT_INDEXED_ALPHA: f->store_32(IMAGE_FORMAT_INDEXED_ALPHA ); break; ///< index byte 0-256: f->store_32(IMAGE_FORMAT_ ); break; and after image end: f->store_32(IMAGE_FORMAT_ ); break; 256*4 bytes of palette (alpha) - case Image::FORMAT_BC1: f->store_32(IMAGE_FORMAT_BC1 ); break; // DXT1 - case Image::FORMAT_BC2: f->store_32(IMAGE_FORMAT_BC2 ); break; // DXT3 - case Image::FORMAT_BC3: f->store_32(IMAGE_FORMAT_BC3 ); break; // DXT5 - case Image::FORMAT_BC4: f->store_32(IMAGE_FORMAT_BC4 ); break; // ATI1 - case Image::FORMAT_BC5: f->store_32(IMAGE_FORMAT_BC5 ); break; // ATI2 - case Image::FORMAT_PVRTC2: f->store_32(IMAGE_FORMAT_PVRTC2 ); break; - case Image::FORMAT_PVRTC2_ALPHA: f->store_32(IMAGE_FORMAT_PVRTC2_ALPHA ); break; - case Image::FORMAT_PVRTC4: f->store_32(IMAGE_FORMAT_PVRTC4 ); break; - case Image::FORMAT_PVRTC4_ALPHA: f->store_32(IMAGE_FORMAT_PVRTC4_ALPHA ); break; + case Image::FORMAT_GRAYSCALE: + f->store_32(IMAGE_FORMAT_GRAYSCALE); + break; ///< one byte per pixel: f->store_32(IMAGE_FORMAT_ ); break; 0-255 + case Image::FORMAT_INTENSITY: + f->store_32(IMAGE_FORMAT_INTENSITY); + break; ///< one byte per pixel: f->store_32(IMAGE_FORMAT_ ); break; 0-255 + case Image::FORMAT_GRAYSCALE_ALPHA: + f->store_32(IMAGE_FORMAT_GRAYSCALE_ALPHA); + break; ///< two bytes per pixel: f->store_32(IMAGE_FORMAT_ ); break; 0-255. alpha 0-255 + case Image::FORMAT_RGB: + f->store_32(IMAGE_FORMAT_RGB); + break; ///< one byte R: f->store_32(IMAGE_FORMAT_ ); break; one byte G: f->store_32(IMAGE_FORMAT_ ); break; one byte B + case Image::FORMAT_RGBA: + f->store_32(IMAGE_FORMAT_RGBA); + break; ///< one byte R: f->store_32(IMAGE_FORMAT_ ); break; one byte G: f->store_32(IMAGE_FORMAT_ ); break; one byte B: f->store_32(IMAGE_FORMAT_ ); break; one byte A + case Image::FORMAT_INDEXED: + f->store_32(IMAGE_FORMAT_INDEXED); + break; ///< index byte 0-256: f->store_32(IMAGE_FORMAT_ ); break; and after image end: f->store_32(IMAGE_FORMAT_ ); break; 256*3 bytes of palette + case Image::FORMAT_INDEXED_ALPHA: + f->store_32(IMAGE_FORMAT_INDEXED_ALPHA); + break; ///< index byte 0-256: f->store_32(IMAGE_FORMAT_ ); break; and after image end: f->store_32(IMAGE_FORMAT_ ); break; 256*4 bytes of palette (alpha) + case Image::FORMAT_BC1: + f->store_32(IMAGE_FORMAT_BC1); + break; // DXT1 + case Image::FORMAT_BC2: + f->store_32(IMAGE_FORMAT_BC2); + break; // DXT3 + case Image::FORMAT_BC3: + f->store_32(IMAGE_FORMAT_BC3); + break; // DXT5 + case Image::FORMAT_BC4: + f->store_32(IMAGE_FORMAT_BC4); + break; // ATI1 + case Image::FORMAT_BC5: + f->store_32(IMAGE_FORMAT_BC5); + break; // ATI2 + case Image::FORMAT_PVRTC2: f->store_32(IMAGE_FORMAT_PVRTC2); break; + case Image::FORMAT_PVRTC2_ALPHA: f->store_32(IMAGE_FORMAT_PVRTC2_ALPHA); break; + case Image::FORMAT_PVRTC4: f->store_32(IMAGE_FORMAT_PVRTC4); break; + case Image::FORMAT_PVRTC4_ALPHA: f->store_32(IMAGE_FORMAT_PVRTC4_ALPHA); break; case Image::FORMAT_ETC: f->store_32(IMAGE_FORMAT_ETC); break; case Image::FORMAT_ATC: f->store_32(IMAGE_FORMAT_ATC); break; case Image::FORMAT_ATC_ALPHA_EXPLICIT: f->store_32(IMAGE_FORMAT_ATC_ALPHA_EXPLICIT); break; case Image::FORMAT_ATC_ALPHA_INTERPOLATED: f->store_32(IMAGE_FORMAT_ATC_ALPHA_INTERPOLATED); break; - case Image::FORMAT_CUSTOM: f->store_32(IMAGE_FORMAT_CUSTOM ); break; + case Image::FORMAT_CUSTOM: f->store_32(IMAGE_FORMAT_CUSTOM); break; default: {} - } int dlen = val.get_data().size(); f->store_32(dlen); DVector::Read r = val.get_data().read(); - f->store_buffer(r.ptr(),dlen); + f->store_buffer(r.ptr(), dlen); _pad_buffer(dlen); } else { DVector 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) { DVector::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;istore_32(get_string_index(np.get_name(i))); - for(int i=0;istore_32(get_string_index(np.get_subname(i))); f->store_32(get_string_index(np.get_property())); @@ -1815,7 +1800,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 { @@ -1831,7 +1816,6 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, //internal resource } - } break; case Variant::INPUT_EVENT: { @@ -1842,12 +1826,12 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, f->store_32(VARIANT_DICTIONARY); Dictionary d = p_property; - f->store_32(uint32_t(d.size())|(d.is_shared()?0x80000000:0)); + f->store_32(uint32_t(d.size()) | (d.is_shared() ? 0x80000000 : 0)); List keys; d.get_key_list(&keys); - for(List::Element *E=keys.front();E;E=E->next()) { + for (List::Element *E = keys.front(); E; E = E->next()) { //if (!_check_type(dict[E->get()])) // continue; @@ -1856,14 +1840,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; - f->store_32(uint32_t(a.size())|(a.is_shared()?0x80000000:0)); - for(int i=0;istore_32(uint32_t(a.size()) | (a.is_shared() ? 0x80000000 : 0)); + for (int i = 0; i < a.size(); i++) { write_variant(a[i]); } @@ -1873,10 +1856,10 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, f->store_32(VARIANT_RAW_ARRAY); DVector arr = p_property; - int len=arr.size(); + int len = arr.size(); f->store_32(len); DVector::Read r = arr.read(); - f->store_buffer(r.ptr(),len); + f->store_buffer(r.ptr(), len); _pad_buffer(len); } break; @@ -1884,10 +1867,10 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, f->store_32(VARIANT_INT_ARRAY); DVector arr = p_property; - int len=arr.size(); + int len = arr.size(); f->store_32(len); DVector::Read r = arr.read(); - for(int i=0;istore_32(r[i]); } break; @@ -1895,10 +1878,10 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, f->store_32(VARIANT_REAL_ARRAY); DVector arr = p_property; - int len=arr.size(); + int len = arr.size(); f->store_32(len); DVector::Read r = arr.read(); - for(int i=0;istore_real(r[i]); } @@ -1907,10 +1890,10 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, f->store_32(VARIANT_STRING_ARRAY); DVector arr = p_property; - int len=arr.size(); + int len = arr.size(); f->store_32(len); DVector::Read r = arr.read(); - for(int i=0;istore_32(VARIANT_VECTOR3_ARRAY); DVector arr = p_property; - int len=arr.size(); + int len = arr.size(); f->store_32(len); DVector::Read r = arr.read(); - for(int i=0;istore_real(r[i].x); f->store_real(r[i].y); f->store_real(r[i].z); @@ -1933,10 +1916,10 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, f->store_32(VARIANT_VECTOR2_ARRAY); DVector arr = p_property; - int len=arr.size(); + int len = arr.size(); f->store_32(len); DVector::Read r = arr.read(); - for(int i=0;istore_real(r[i].x); f->store_real(r[i].y); } @@ -1946,10 +1929,10 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, f->store_32(VARIANT_COLOR_ARRAY); DVector arr = p_property; - int len=arr.size(); + int len = arr.size(); f->store_32(len); DVector::Read r = arr.read(); - for(int i=0;istore_real(r[i].r); f->store_real(r[i].g); f->store_real(r[i].b); @@ -1965,26 +1948,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; @@ -1992,9 +1971,9 @@ void ResourceFormatSaverBinaryInstance::_find_resources(const Variant& p_variant res->get_property_list(&property_list); - for(List::Element *E=property_list.front();E;E=E->next()) { + for (List::Element *E = property_list.front(); E; E = E->next()) { - if (E->get().usage&PROPERTY_USAGE_STORAGE || (bundle_resources && E->get().usage&PROPERTY_USAGE_BUNDLE)) { + if (E->get().usage & PROPERTY_USAGE_STORAGE || (bundle_resources && E->get().usage & PROPERTY_USAGE_BUNDLE)) { _find_resources(res->get(E->get().name)); } @@ -2007,11 +1986,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 keys; d.get_key_list(&keys); - for(List::Element *E=keys.front();E;E=E->next()) { + for (List::Element *E = keys.front(); E; E = E->next()) { _find_resources(E->get()); Variant v = d[E->get()]; @@ -2032,18 +2011,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;istore_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) { @@ -2165,7 +2138,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; } @@ -2174,50 +2147,41 @@ Error ResourceFormatSaverBinaryInstance::save(const String &p_path,const RES& p_ save_unicode_string(p_resource->get_type()); 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 resources; - { - - for(List::Element *E=saved_resources.front();E;E=E->next()) { - + for (List::Element *E = saved_resources.front(); E; E = E->next()) { ResourceData &rd = resources.push_back(ResourceData())->get(); - rd.type=E->get()->get_type(); + rd.type = E->get()->get_type(); List property_list; - E->get()->get_property_list( &property_list ); + E->get()->get_property_list(&property_list); - for(List::Element *F=property_list.front();F;F=F->next()) { + for (List::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 || (bundle_resources && F->get().usage&PROPERTY_USAGE_BUNDLE)) { + if (F->get().usage & PROPERTY_USAGE_STORAGE || (bundle_resources && F->get().usage & PROPERTY_USAGE_BUNDLE)) { 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 save_order; save_order.resize(external_resources.size()); - for(Map::Element *E=external_resources.front();E;E=E->next()) { - save_order[E->get()]=E->key(); + for (Map::Element *E = external_resources.front(); E; E = E->next()) { + save_order[E->get()] = E->key(); } - for(int i=0;iget_save_type()); 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 @@ -2243,12 +2207,12 @@ Error ResourceFormatSaverBinaryInstance::save(const String &p_path,const RES& p_ Vector ofs_pos; Set used_indices; - for(List::Element *E=saved_resources.front();E;E=E->next()) { + for (List::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 { @@ -2256,29 +2220,25 @@ Error ResourceFormatSaverBinaryInstance::save(const String &p_path,const RES& p_ } } } - } - - for(List::Element *E=saved_resources.front();E;E=E->next()) { - + for (List::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); } } else { save_unicode_string(r->get_path()); //actual external @@ -2288,48 +2248,47 @@ Error ResourceFormatSaverBinaryInstance::save(const String &p_path,const RES& p_ } Vector ofs_table; -// int saved_idx=0; + // int saved_idx=0; //now actually save the resources - for(List::Element *E=resources.front();E;E=E->next()) { + for (List::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::Element *F=rd.properties.front();F;F=F->next()) { + for (List::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;iseek(ofs_pos[i]); f->store_64(ofs_table[i]); } f->seek_end(); - print_line("SAVING: "+p_path); + print_line("SAVING: " + p_path); if (p_resource->get_import_metadata().is_valid()) { uint64_t md_pos = f->get_pos(); - Ref imd=p_resource->get_import_metadata(); + Ref imd = p_resource->get_import_metadata(); save_unicode_string(imd->get_editor()); f->store_32(imd->get_source_count()); - for(int i=0;iget_source_count();i++) { + for (int i = 0; i < imd->get_source_count(); i++) { save_unicode_string(imd->get_source_path(i)); save_unicode_string(imd->get_source_md5(i)); - print_line("SAVE PATH: "+imd->get_source_path(i)); - print_line("SAVE MD5: "+imd->get_source_md5(i)); + print_line("SAVE PATH: " + imd->get_source_path(i)); + print_line("SAVE MD5: " + imd->get_source_md5(i)); } List options; imd->get_options(&options); f->store_32(options.size()); - for(List::Element *E=options.front();E;E=E->next()) { + for (List::Element *E = options.front(); E; E = E->next()) { save_unicode_string(E->get()); write_variant(imd->get_option(E->get())); } @@ -2339,48 +2298,39 @@ Error ResourceFormatSaverBinaryInstance::save(const String &p_path,const RES& p_ 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 = Globals::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 *p_extensions) const { +void ResourceFormatSaverBinary::get_recognized_extensions(const RES &p_resource, List *p_extensions) const { String base = p_resource->get_base_extension().to_lower(); p_extensions->push_back(base); - } -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 566767b8393..a7bd782b3ac 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; @@ -71,62 +69,54 @@ class ResourceInteractiveLoaderBinary : public ResourceInteractiveLoader { String get_unicode_string(); void _advance_padding(uint32_t p_len); - Map remaps; + Map remaps; Error error; int stage; -friend class ResourceFormatLoaderBinary; + friend class ResourceFormatLoaderBinary; - - Error parse_variant(Variant& r_v, bool p_for_export_data=false); + Error parse_variant(Variant &r_v, bool p_for_export_data = false); public: - - virtual void set_local_path(const String& p_local_path); + virtual void set_local_path(const String &p_local_path); virtual Ref get_resource(); virtual Error poll(); virtual int get_stage() const; virtual int get_stage_count() const; - void set_remaps(const Map& p_remaps) { remaps=p_remaps; } + void set_remaps(const Map &p_remaps) { remaps = p_remaps; } void open(FileAccess *p_f); String recognize(FileAccess *p_f); void get_dependencies(FileAccess *p_f, List *p_dependencies, bool p_add_types); - Error get_export_data(ExportData& r_export_data); + Error get_export_data(ExportData &r_export_data); ResourceInteractiveLoaderBinary(); ~ResourceInteractiveLoaderBinary(); - }; class ResourceFormatLoaderBinary : public ResourceFormatLoader { public: - - virtual Ref load_interactive(const String &p_path,Error *r_error=NULL); - virtual void get_recognized_extensions_for_type(const String& p_type,List *p_extensions) const; + virtual Ref load_interactive(const String &p_path, Error *r_error = NULL); + virtual void get_recognized_extensions_for_type(const String &p_type, List *p_extensions) const; virtual void get_recognized_extensions(List *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 *p_dependencies, bool p_add_types=false); - virtual Error load_import_metadata(const String &p_path, Ref& r_var) const; - virtual Error rename_dependencies(const String &p_path,const Map& p_map); - virtual Error get_export_data(const String& p_path,ExportData& r_export_data); + virtual void get_dependencies(const String &p_path, List *p_dependencies, bool p_add_types = false); + virtual Error load_import_metadata(const String &p_path, Ref &r_var) const; + virtual Error rename_dependencies(const String &p_path, const Map &p_map); + virtual Error get_export_data(const String &p_path, ExportData &r_export_data); static ResourceFormatLoaderBinary *singleton; - ResourceFormatLoaderBinary() { singleton=this; } + ResourceFormatLoaderBinary() { singleton = this; } }; - - - -class ResourceFormatSaverBinaryInstance { +class ResourceFormatSaverBinaryInstance { String local_path; - bool relative_paths; bool bundle_resources; bool skip_editor; @@ -136,19 +126,16 @@ class ResourceFormatSaverBinaryInstance { FileAccess *f; String magic; Set resource_set; - Map string_map; + Map string_map; Vector strings; - - Map external_resources; + Map external_resources; List saved_resources; - struct Property { int name_idx; Variant value; PropertyInfo pi; - }; struct ResourceData { @@ -157,36 +144,25 @@ class ResourceFormatSaverBinaryInstance { List 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); + 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: - - - Error save(const String &p_path,const RES& p_resource,uint32_t p_flags=0); + 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 *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 *p_extensions) const; ResourceFormatSaverBinary(); }; - #endif // RESOURCE_FORMAT_BINARY_H diff --git a/core/io/resource_format_xml.cpp b/core/io/resource_format_xml.cpp index 8be6a32f61b..e66e11b8375 100644 --- a/core/io/resource_format_xml.cpp +++ b/core/io/resource_format_xml.cpp @@ -28,36 +28,35 @@ /*************************************************************************/ #include "resource_format_xml.h" #include "globals.h" -#include "version.h" #include "os/dir_access.h" +#include "version.h" +ResourceInteractiveLoaderXML::Tag *ResourceInteractiveLoaderXML::parse_tag(bool *r_exit, bool p_printerr, List *r_order) { -ResourceInteractiveLoaderXML::Tag* ResourceInteractiveLoaderXML::parse_tag(bool *r_exit, bool p_printerr, List *r_order) { - - - while(get_char()!='<' && !f->eof_reached()) {} + while (get_char() != '<' && !f->eof_reached()) { + } if (f->eof_reached()) { return NULL; } Tag tag; - bool exit=false; + bool exit = false; if (r_exit) - *r_exit=false; + *r_exit = false; - bool complete=false; - while(!f->eof_reached()) { + bool complete = false; + while (!f->eof_reached()) { - CharType c=get_char(); - if (c<33 && tag.name.length() && !exit) { + CharType c = get_char(); + if (c < 33 && tag.name.length() && !exit) { break; - } else if (c=='>') { - complete=true; + } else if (c == '>') { + complete = true; break; - } else if (c=='/') { - exit=true; + } else if (c == '/') { + exit = true; } else { - tag.name+=c; + tag.name += c; } } @@ -70,67 +69,67 @@ ResourceInteractiveLoaderXML::Tag* ResourceInteractiveLoaderXML::parse_tag(bool if (!tag_stack.size()) { if (!p_printerr) return NULL; - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": Unmatched exit tag "); - ERR_FAIL_COND_V(!tag_stack.size(),NULL); + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": Unmatched exit tag "); + ERR_FAIL_COND_V(!tag_stack.size(), NULL); } - if (tag_stack.back()->get().name!=tag.name) { + if (tag_stack.back()->get().name != tag.name) { if (!p_printerr) return NULL; - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": Mismatched exit tag. Got , expected get().name+">"); - ERR_FAIL_COND_V(tag_stack.back()->get().name!=tag.name,NULL); + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": Mismatched exit tag. Got , expected get().name + ">"); + ERR_FAIL_COND_V(tag_stack.back()->get().name != tag.name, NULL); } if (!complete) { - while(get_char()!='>' && !f->eof_reached()) {} + while (get_char() != '>' && !f->eof_reached()) { + } if (f->eof_reached()) return NULL; } if (r_exit) - *r_exit=true; + *r_exit = true; tag_stack.pop_back(); return NULL; - } if (!complete) { String name; CharString r_value; - bool reading_value=false; + bool reading_value = false; - while(!f->eof_reached()) { + while (!f->eof_reached()) { - CharType c=get_char(); - if (c=='>') { + CharType c = get_char(); + if (c == '>') { if (r_value.size()) { r_value.push_back(0); String str; str.parse_utf8(r_value.get_data()); - tag.args[name]=str; + tag.args[name] = str; if (r_order) r_order->push_back(name); } break; - } else if ( ((!reading_value && (c<33)) || c=='=' || c=='"' || c=='\'') && tag.name.length()) { + } else if (((!reading_value && (c < 33)) || c == '=' || c == '"' || c == '\'') && tag.name.length()) { if (!reading_value && name.length()) { - reading_value=true; + reading_value = true; } else if (reading_value && r_value.size()) { r_value.push_back(0); String str; str.parse_utf8(r_value.get_data()); - tag.args[name]=str; + tag.args[name] = str; if (r_order) r_order->push_back(name); - name=""; + name = ""; r_value.clear(); - reading_value=false; + reading_value = false; } } else if (reading_value) { @@ -138,7 +137,7 @@ ResourceInteractiveLoaderXML::Tag* ResourceInteractiveLoaderXML::parse_tag(bool r_value.push_back(c); } else { - name+=c; + name += c; } } @@ -151,18 +150,17 @@ ResourceInteractiveLoaderXML::Tag* ResourceInteractiveLoaderXML::parse_tag(bool return &tag_stack.back()->get(); } +Error ResourceInteractiveLoaderXML::close_tag(const String &p_name) { -Error ResourceInteractiveLoaderXML::close_tag(const String& p_name) { + int level = 0; + bool inside_tag = false; - int level=0; - bool inside_tag=false; - - while(true) { + while (true) { if (f->eof_reached()) { - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": EOF found while attempting to find "); - ERR_FAIL_COND_V( f->eof_reached(), ERR_FILE_CORRUPT ); + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": EOF found while attempting to find "); + ERR_FAIL_COND_V(f->eof_reached(), ERR_FILE_CORRUPT); } uint8_t c = get_char(); @@ -170,10 +168,10 @@ Error ResourceInteractiveLoaderXML::close_tag(const String& p_name) { if (c == '<') { if (inside_tag) { - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": Malformed XML. Already inside Tag."); - ERR_FAIL_COND_V(inside_tag,ERR_FILE_CORRUPT); + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": Malformed XML. Already inside Tag."); + ERR_FAIL_COND_V(inside_tag, ERR_FILE_CORRUPT); } - inside_tag=true; + inside_tag = true; c = get_char(); if (c == '/') { @@ -185,10 +183,10 @@ Error ResourceInteractiveLoaderXML::close_tag(const String& p_name) { } else if (c == '>') { if (!inside_tag) { - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": Malformed XML. Already outside Tag"); - ERR_FAIL_COND_V(!inside_tag,ERR_FILE_CORRUPT); + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": Malformed XML. Already outside Tag"); + ERR_FAIL_COND_V(!inside_tag, ERR_FILE_CORRUPT); } - inside_tag=false; + inside_tag = false; if (level == -1) { tag_stack.pop_back(); return OK; @@ -199,10 +197,9 @@ Error ResourceInteractiveLoaderXML::close_tag(const String& p_name) { return OK; } -void ResourceInteractiveLoaderXML::unquote(String& p_str) { +void ResourceInteractiveLoaderXML::unquote(String &p_str) { - - p_str=p_str.strip_edges().replace("\"","").xml_unescape(); + p_str = p_str.strip_edges().replace("\"", "").xml_unescape(); /*p_str=p_str.strip_edges(); p_str=p_str.replace("\"",""); @@ -218,40 +215,37 @@ void ResourceInteractiveLoaderXML::unquote(String& p_str) { p_str=p_str.replace("&","&"); */ //p_str.parse_utf8( p_str.ascii(true).get_data() ); - } Error ResourceInteractiveLoaderXML::goto_end_of_tag() { uint8_t c; - while(true) { + while (true) { - c=get_char(); - if (c=='>') //closetag + c = get_char(); + if (c == '>') //closetag break; if (f->eof_reached()) { - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": EOF found while attempting to find close tag."); - ERR_FAIL_COND_V( f->eof_reached(), ERR_FILE_CORRUPT ); + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": EOF found while attempting to find close tag."); + ERR_FAIL_COND_V(f->eof_reached(), ERR_FILE_CORRUPT); } - } tag_stack.pop_back(); return OK; } - Error ResourceInteractiveLoaderXML::parse_property_data(String &r_data) { - r_data=""; + r_data = ""; CharString cs; - while(true) { + while (true) { - CharType c=get_char(); - if (c=='<') + CharType c = get_char(); + if (c == '<') break; - ERR_FAIL_COND_V(f->eof_reached(),ERR_FILE_CORRUPT); + ERR_FAIL_COND_V(f->eof_reached(), ERR_FILE_CORRUPT); cs.push_back(c); } @@ -259,51 +253,50 @@ Error ResourceInteractiveLoaderXML::parse_property_data(String &r_data) { r_data.parse_utf8(cs.get_data()); - while(get_char()!='>' && !f->eof_reached()) {} + while (get_char() != '>' && !f->eof_reached()) { + } if (f->eof_reached()) { - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": Malformed XML."); - ERR_FAIL_COND_V( f->eof_reached(), ERR_FILE_CORRUPT ); + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": Malformed XML."); + ERR_FAIL_COND_V(f->eof_reached(), ERR_FILE_CORRUPT); } - r_data=r_data.strip_edges(); + r_data = r_data.strip_edges(); tag_stack.pop_back(); return OK; } - -Error ResourceInteractiveLoaderXML::_parse_array_element(Vector &buff,bool p_number_only,FileAccess *f,bool *end) { +Error ResourceInteractiveLoaderXML::_parse_array_element(Vector &buff, bool p_number_only, FileAccess *f, bool *end) { if (buff.empty()) buff.resize(32); // optimi - int buff_max=buff.size(); - int buff_size=0; - *end=false; - char *buffptr=&buff[0]; - bool found=false; - bool quoted=false; + int buff_max = buff.size(); + int buff_size = 0; + *end = false; + char *buffptr = &buff[0]; + bool found = false; + bool quoted = false; - while(true) { + while (true) { - char c=get_char(); + char c = get_char(); - if (c==0) { - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": File corrupt (zero found)."); + if (c == 0) { + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": File corrupt (zero found)."); ERR_FAIL_V(ERR_FILE_CORRUPT); - } else if (c=='"') { - quoted=!quoted; - } else if ((!quoted && ((p_number_only && c<33) || c==',')) || c=='<') { + } else if (c == '"') { + quoted = !quoted; + } else if ((!quoted && ((p_number_only && c < 33) || c == ',')) || c == '<') { - - if (c=='<') { - *end=true; + if (c == '<') { + *end = true; break; } - if (c<32 && f->eof_reached()) { - *end=true; - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": File corrupt (unexpected EOF)."); + if (c < 32 && f->eof_reached()) { + *end = true; + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": File corrupt (unexpected EOF)."); ERR_FAIL_V(ERR_FILE_CORRUPT); } @@ -312,34 +305,32 @@ Error ResourceInteractiveLoaderXML::_parse_array_element(Vector &buff,bool } else { - found=true; - if (buff_size>=buff_max) { + found = true; + if (buff_size >= buff_max) { buff_max++; buff.resize(buff_max); - buffptr=buff.ptr(); - + buffptr = buff.ptr(); } - buffptr[buff_size]=c; + buffptr[buff_size] = c; buff_size++; } } - if (buff_size>=buff_max) { + if (buff_size >= buff_max) { buff_max++; buff.resize(buff_max); - } - buff[buff_size]=0; + buff[buff_size] = 0; buff_size++; return OK; } -Error ResourceInteractiveLoaderXML::parse_property(Variant& r_v, String &r_name, bool p_for_export_data) { +Error ResourceInteractiveLoaderXML::parse_property(Variant &r_v, String &r_name, bool p_for_export_data) { bool exit; Tag *tag = parse_tag(&exit); @@ -347,33 +338,32 @@ Error ResourceInteractiveLoaderXML::parse_property(Variant& r_v, String &r_name, if (!tag) { if (exit) // shouldn't have exited return ERR_FILE_EOF; - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": File corrupt (No Property Tag)."); + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": File corrupt (No Property Tag)."); ERR_FAIL_V(ERR_FILE_CORRUPT); } - r_v=Variant(); - r_name=""; - + r_v = Variant(); + r_name = ""; //ERR_FAIL_COND_V(tag->name!="property",ERR_FILE_CORRUPT); //ERR_FAIL_COND_V(!tag->args.has("name"),ERR_FILE_CORRUPT); -// ERR_FAIL_COND_V(!tag->args.has("type"),ERR_FILE_CORRUPT); + // ERR_FAIL_COND_V(!tag->args.has("type"),ERR_FILE_CORRUPT); //String name=tag->args["name"]; //ERR_FAIL_COND_V(name=="",ERR_FILE_CORRUPT); - String type=tag->name; - String name=tag->args["name"]; + String type = tag->name; + String name = tag->args["name"]; - if (type=="") { - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": 'type' field is empty."); - ERR_FAIL_COND_V(type=="",ERR_FILE_CORRUPT); + if (type == "") { + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": 'type' field is empty."); + ERR_FAIL_COND_V(type == "", ERR_FILE_CORRUPT); } - if (type=="dictionary") { + if (type == "dictionary") { - Dictionary d( tag->args.has("shared") && (String(tag->args["shared"])=="true" || String(tag->args["shared"])=="1")); + Dictionary d(tag->args.has("shared") && (String(tag->args["shared"]) == "true" || String(tag->args["shared"]) == "1")); - while(true) { + while (true) { Error err; String tagname; @@ -381,46 +371,43 @@ Error ResourceInteractiveLoaderXML::parse_property(Variant& r_v, String &r_name, int dictline = get_current_line(); + err = parse_property(key, tagname, p_for_export_data); - err=parse_property(key,tagname,p_for_export_data); - - if (err && err!=ERR_FILE_EOF) { - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": Error parsing dictionary: "+name+" (from line "+itos(dictline)+")"); - ERR_FAIL_COND_V(err && err!=ERR_FILE_EOF,err); + if (err && err != ERR_FILE_EOF) { + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": Error parsing dictionary: " + name + " (from line " + itos(dictline) + ")"); + ERR_FAIL_COND_V(err && err != ERR_FILE_EOF, err); } //ERR_FAIL_COND_V(tagname!="key",ERR_FILE_CORRUPT); if (err) break; Variant value; - err=parse_property(value,tagname,p_for_export_data); + err = parse_property(value, tagname, p_for_export_data); if (err) { - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": Error parsing dictionary: "+name+" (from line "+itos(dictline)+")"); + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": Error parsing dictionary: " + name + " (from line " + itos(dictline) + ")"); } - ERR_FAIL_COND_V(err,err); + ERR_FAIL_COND_V(err, err); //ERR_FAIL_COND_V(tagname!="value",ERR_FILE_CORRUPT); - d[key]=value; + d[key] = value; } - //err=parse_property_data(name); // skip the rest //ERR_FAIL_COND_V(err,err); - r_name=name; - r_v=d; + r_name = name; + r_v = d; return OK; - } else if (type=="array") { + } else if (type == "array") { if (!tag->args.has("len")) { - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": Array missing 'len' field: "+name); - ERR_FAIL_COND_V(!tag->args.has("len"),ERR_FILE_CORRUPT); + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": Array missing 'len' field: " + name); + ERR_FAIL_COND_V(!tag->args.has("len"), ERR_FILE_CORRUPT); } - - int len=tag->args["len"].to_int(); - bool shared = tag->args.has("shared") && (String(tag->args["shared"])=="true" || String(tag->args["shared"])=="1"); + int len = tag->args["len"].to_int(); + bool shared = tag->args.has("shared") && (String(tag->args["shared"]) == "true" || String(tag->args["shared"]) == "1"); Array array(shared); array.resize(len); @@ -428,230 +415,220 @@ Error ResourceInteractiveLoaderXML::parse_property(Variant& r_v, String &r_name, Error err; Variant v; String tagname; - int idx=0; - while( (err=parse_property(v,tagname,p_for_export_data))==OK ) { + int idx = 0; + while ((err = parse_property(v, tagname, p_for_export_data)) == OK) { - ERR_CONTINUE( idx <0 || idx >=len ); + ERR_CONTINUE(idx < 0 || idx >= len); - array.set(idx,v); + array.set(idx, v); idx++; } - if (idx!=len) { - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": Error loading array (size mismatch): "+name); - ERR_FAIL_COND_V(idx!=len,err); + if (idx != len) { + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": Error loading array (size mismatch): " + name); + ERR_FAIL_COND_V(idx != len, err); } - if (err!=ERR_FILE_EOF) { - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": Error loading array: "+name); - ERR_FAIL_COND_V(err!=ERR_FILE_EOF,err); + if (err != ERR_FILE_EOF) { + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": Error loading array: " + name); + ERR_FAIL_COND_V(err != ERR_FILE_EOF, err); } //err=parse_property_data(name); // skip the rest //ERR_FAIL_COND_V(err,err); - r_name=name; - r_v=array; + r_name = name; + r_v = array; return OK; - } else if (type=="resource") { + } else if (type == "resource") { if (tag->args.has("path")) { - String path=tag->args["path"]; + String path = tag->args["path"]; String hint; if (tag->args.has("resource_type")) - hint=tag->args["resource_type"]; + hint = tag->args["resource_type"]; if (p_for_export_data) { String prop; if (path.begins_with("local://")) { - prop="@RESLOCAL:"+itos(path.replace("local://","").to_int()); + prop = "@RESLOCAL:" + itos(path.replace("local://", "").to_int()); } - r_v=prop; + r_v = prop; return OK; } if (path.begins_with("local://")) - path=path.replace("local://",local_path+"::"); - else if (path.find("://")==-1 && path.is_rel_path()) { + path = path.replace("local://", local_path + "::"); + else if (path.find("://") == -1 && path.is_rel_path()) { // path is relative to file being loaded, so convert to a resource path - path=Globals::get_singleton()->localize_path(local_path.get_base_dir().plus_file(path)); - + path = Globals::get_singleton()->localize_path(local_path.get_base_dir().plus_file(path)); } if (remaps.has(path)) { - path=remaps[path]; + path = remaps[path]; } //take advantage of the resource loader cache. The resource is cached on it, even if - RES res=ResourceLoader::load(path,hint); - + RES res = ResourceLoader::load(path, hint); if (res.is_null()) { - WARN_PRINT(String("Couldn't load resource: "+path).ascii().get_data()); + WARN_PRINT(String("Couldn't load resource: " + path).ascii().get_data()); } - r_v=res.get_ref_ptr(); + r_v = res.get_ref_ptr(); } else if (tag->args.has("external")) { int index = tag->args["external"].to_int(); - if (p_for_export_data) { String prop; - prop="@RESEXTERNAL:"+itos(index); + prop = "@RESEXTERNAL:" + itos(index); - r_v=prop; + r_v = prop; return OK; } if (ext_resources.has(index)) { - String path=ext_resources[index].path; - String type=ext_resources[index].type; + String path = ext_resources[index].path; + String type = ext_resources[index].type; //take advantage of the resource loader cache. The resource is cached on it, even if - RES res=ResourceLoader::load(path,type); + RES res = ResourceLoader::load(path, type); if (res.is_null()) { - WARN_PRINT(String("Couldn't load externalresource: "+path).ascii().get_data()); + WARN_PRINT(String("Couldn't load externalresource: " + path).ascii().get_data()); } - r_v=res.get_ref_ptr(); + r_v = res.get_ref_ptr(); } else { - WARN_PRINT(String("Invalid external resource index: "+itos(index)).ascii().get_data()); - + WARN_PRINT(String("Invalid external resource index: " + itos(index)).ascii().get_data()); } } - - - - Error err=goto_end_of_tag(); + Error err = goto_end_of_tag(); if (err) { - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": Error closing tag."); - ERR_FAIL_COND_V(err,err); + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": Error closing tag."); + ERR_FAIL_COND_V(err, err); } - - r_name=name; + r_name = name; return OK; - } else if (type=="image") { + } else if (type == "image") { if (!tag->args.has("encoding")) { //empty image - r_v=Image(); + r_v = Image(); String sdfsdfg; - Error err=parse_property_data(sdfsdfg); + Error err = parse_property_data(sdfsdfg); return OK; } - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": Image missing 'encoding' field."); - ERR_FAIL_COND_V( !tag->args.has("encoding"), ERR_FILE_CORRUPT ); - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": Image missing 'width' field."); - ERR_FAIL_COND_V( !tag->args.has("width"), ERR_FILE_CORRUPT ); - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": Image missing 'height' field."); - ERR_FAIL_COND_V( !tag->args.has("height"), ERR_FILE_CORRUPT ); - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": Image missing 'format' field."); - ERR_FAIL_COND_V( !tag->args.has("format"), ERR_FILE_CORRUPT ); + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": Image missing 'encoding' field."); + ERR_FAIL_COND_V(!tag->args.has("encoding"), ERR_FILE_CORRUPT); + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": Image missing 'width' field."); + ERR_FAIL_COND_V(!tag->args.has("width"), ERR_FILE_CORRUPT); + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": Image missing 'height' field."); + ERR_FAIL_COND_V(!tag->args.has("height"), ERR_FILE_CORRUPT); + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": Image missing 'format' field."); + ERR_FAIL_COND_V(!tag->args.has("format"), ERR_FILE_CORRUPT); - String encoding=tag->args["encoding"]; + String encoding = tag->args["encoding"]; - if (encoding=="raw") { - String width=tag->args["width"]; - String height=tag->args["height"]; - String format=tag->args["format"]; - int mipmaps=tag->args.has("mipmaps")?int(tag->args["mipmaps"].to_int()):int(0); - int custom_size = tag->args.has("custom_size")?int(tag->args["custom_size"].to_int()):int(0); + if (encoding == "raw") { + String width = tag->args["width"]; + String height = tag->args["height"]; + String format = tag->args["format"]; + int mipmaps = tag->args.has("mipmaps") ? int(tag->args["mipmaps"].to_int()) : int(0); + int custom_size = tag->args.has("custom_size") ? int(tag->args["custom_size"].to_int()) : int(0); - r_name=name; + r_name = name; Image::Format imgformat; - - if (format=="grayscale") { - imgformat=Image::FORMAT_GRAYSCALE; - } else if (format=="intensity") { - imgformat=Image::FORMAT_INTENSITY; - } else if (format=="grayscale_alpha") { - imgformat=Image::FORMAT_GRAYSCALE_ALPHA; - } else if (format=="rgb") { - imgformat=Image::FORMAT_RGB; - } else if (format=="rgba") { - imgformat=Image::FORMAT_RGBA; - } else if (format=="indexed") { - imgformat=Image::FORMAT_INDEXED; - } else if (format=="indexed_alpha") { - imgformat=Image::FORMAT_INDEXED_ALPHA; - } else if (format=="bc1") { - imgformat=Image::FORMAT_BC1; - } else if (format=="bc2") { - imgformat=Image::FORMAT_BC2; - } else if (format=="bc3") { - imgformat=Image::FORMAT_BC3; - } else if (format=="bc4") { - imgformat=Image::FORMAT_BC4; - } else if (format=="bc5") { - imgformat=Image::FORMAT_BC5; - } else if (format=="pvrtc2") { - imgformat=Image::FORMAT_PVRTC2; - } else if (format=="pvrtc2a") { - imgformat=Image::FORMAT_PVRTC2_ALPHA; - } else if (format=="pvrtc4") { - imgformat=Image::FORMAT_PVRTC4; - } else if (format=="pvrtc4a") { - imgformat=Image::FORMAT_PVRTC4_ALPHA; - } else if (format=="etc") { - imgformat=Image::FORMAT_ETC; - } else if (format=="atc") { - imgformat=Image::FORMAT_ATC; - } else if (format=="atcai") { - imgformat=Image::FORMAT_ATC_ALPHA_INTERPOLATED; - } else if (format=="atcae") { - imgformat=Image::FORMAT_ATC_ALPHA_EXPLICIT; - } else if (format=="custom") { - imgformat=Image::FORMAT_CUSTOM; + if (format == "grayscale") { + imgformat = Image::FORMAT_GRAYSCALE; + } else if (format == "intensity") { + imgformat = Image::FORMAT_INTENSITY; + } else if (format == "grayscale_alpha") { + imgformat = Image::FORMAT_GRAYSCALE_ALPHA; + } else if (format == "rgb") { + imgformat = Image::FORMAT_RGB; + } else if (format == "rgba") { + imgformat = Image::FORMAT_RGBA; + } else if (format == "indexed") { + imgformat = Image::FORMAT_INDEXED; + } else if (format == "indexed_alpha") { + imgformat = Image::FORMAT_INDEXED_ALPHA; + } else if (format == "bc1") { + imgformat = Image::FORMAT_BC1; + } else if (format == "bc2") { + imgformat = Image::FORMAT_BC2; + } else if (format == "bc3") { + imgformat = Image::FORMAT_BC3; + } else if (format == "bc4") { + imgformat = Image::FORMAT_BC4; + } else if (format == "bc5") { + imgformat = Image::FORMAT_BC5; + } else if (format == "pvrtc2") { + imgformat = Image::FORMAT_PVRTC2; + } else if (format == "pvrtc2a") { + imgformat = Image::FORMAT_PVRTC2_ALPHA; + } else if (format == "pvrtc4") { + imgformat = Image::FORMAT_PVRTC4; + } else if (format == "pvrtc4a") { + imgformat = Image::FORMAT_PVRTC4_ALPHA; + } else if (format == "etc") { + imgformat = Image::FORMAT_ETC; + } else if (format == "atc") { + imgformat = Image::FORMAT_ATC; + } else if (format == "atcai") { + imgformat = Image::FORMAT_ATC_ALPHA_INTERPOLATED; + } else if (format == "atcae") { + imgformat = Image::FORMAT_ATC_ALPHA_EXPLICIT; + } else if (format == "custom") { + imgformat = Image::FORMAT_CUSTOM; } else { - ERR_FAIL_V( ERR_FILE_CORRUPT ); + ERR_FAIL_V(ERR_FILE_CORRUPT); } - int datasize; - int w=width.to_int(); - int h=height.to_int(); + int w = width.to_int(); + int h = height.to_int(); if (w == 0 && h == 0) { //r_v = Image(w, h, imgformat); - r_v=Image(); + r_v = Image(); String sdfsdfg; - Error err=parse_property_data(sdfsdfg); + Error err = parse_property_data(sdfsdfg); return OK; }; - if (imgformat==Image::FORMAT_CUSTOM) { + if (imgformat == Image::FORMAT_CUSTOM) { - datasize=custom_size; + datasize = custom_size; } else { - datasize = Image::get_image_data_size(h,w,imgformat,mipmaps); + datasize = Image::get_image_data_size(h, w, imgformat, mipmaps); } - if (datasize==0) { + if (datasize == 0) { //r_v = Image(w, h, imgformat); - r_v=Image(); + r_v = Image(); String sdfsdfg; - Error err=parse_property_data(sdfsdfg); + Error err = parse_property_data(sdfsdfg); return OK; }; @@ -659,101 +636,100 @@ Error ResourceInteractiveLoaderXML::parse_property(Variant& r_v, String &r_name, pixels.resize(datasize); DVector::Write wb = pixels.write(); - int idx=0; + int idx = 0; uint8_t byte; - while( idx='0' && c<='9') || (c>='A' && c<='F') || (c>='a' && c<='f') ) { + if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f')) { - if (idx&1) { + if (idx & 1) { - byte|=HEX2CHR(c); - wb[idx>>1]=byte; + byte |= HEX2CHR(c); + wb[idx >> 1] = byte; } else { - byte=HEX2CHR(c)<<4; + byte = HEX2CHR(c) << 4; } idx++; } - } - ERR_FAIL_COND_V(f->eof_reached(),ERR_FILE_CORRUPT); + ERR_FAIL_COND_V(f->eof_reached(), ERR_FILE_CORRUPT); - wb=DVector::Write(); + wb = DVector::Write(); - r_v=Image(w,h,mipmaps,imgformat,pixels); + r_v = Image(w, h, mipmaps, imgformat, pixels); String sdfsdfg; - Error err=parse_property_data(sdfsdfg); - ERR_FAIL_COND_V(err,err); + Error err = parse_property_data(sdfsdfg); + ERR_FAIL_COND_V(err, err); return OK; } ERR_FAIL_V(ERR_FILE_CORRUPT); - } else if (type=="raw_array") { + } else if (type == "raw_array") { if (!tag->args.has("len")) { - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": RawArray missing 'len' field: "+name); - ERR_FAIL_COND_V(!tag->args.has("len"),ERR_FILE_CORRUPT); + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": RawArray missing 'len' field: " + name); + ERR_FAIL_COND_V(!tag->args.has("len"), ERR_FILE_CORRUPT); } - int len=tag->args["len"].to_int(); + int len = tag->args["len"].to_int(); DVector bytes; bytes.resize(len); - DVector::Write w=bytes.write(); - uint8_t *bytesptr=w.ptr(); - int idx=0; + DVector::Write w = bytes.write(); + uint8_t *bytesptr = w.ptr(); + int idx = 0; uint8_t byte; - while( idx>1]=byte; + byte |= HEX2CHR(c); + bytesptr[idx >> 1] = byte; //printf("%x\n",int(byte)); } else { - byte=HEX2CHR(c)<<4; + byte = HEX2CHR(c) << 4; } idx++; } - ERR_FAIL_COND_V(f->eof_reached(),ERR_FILE_CORRUPT); + ERR_FAIL_COND_V(f->eof_reached(), ERR_FILE_CORRUPT); - w=DVector::Write(); - r_v=bytes; + w = DVector::Write(); + r_v = bytes; String sdfsdfg; - Error err=parse_property_data(sdfsdfg); - ERR_FAIL_COND_V(err,err); - r_name=name; + Error err = parse_property_data(sdfsdfg); + ERR_FAIL_COND_V(err, err); + r_name = name; return OK; - } else if (type=="int_array") { + } else if (type == "int_array") { if (!tag->args.has("len")) { - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": Array missing 'len' field: "+name); - ERR_FAIL_COND_V(!tag->args.has("len"),ERR_FILE_CORRUPT); + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": Array missing 'len' field: " + name); + ERR_FAIL_COND_V(!tag->args.has("len"), ERR_FILE_CORRUPT); } - int len=tag->args["len"].to_int(); + int len = tag->args["len"].to_int(); DVector ints; ints.resize(len); - DVector::Write w=ints.write(); - int *intsptr=w.ptr(); - int idx=0; + DVector::Write w = ints.write(); + int *intsptr = w.ptr(); + int idx = 0; String str; #if 0 while( idx tmpdata; - while( idx::Write(); + w = DVector::Write(); - r_v=ints; - Error err=goto_end_of_tag(); - ERR_FAIL_COND_V(err,err); - r_name=name; + r_v = ints; + Error err = goto_end_of_tag(); + ERR_FAIL_COND_V(err, err); + r_name = name; return OK; - } else if (type=="real_array") { + } else if (type == "real_array") { if (!tag->args.has("len")) { - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": Array missing 'len' field: "+name); - ERR_FAIL_COND_V(!tag->args.has("len"),ERR_FILE_CORRUPT); + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": Array missing 'len' field: " + name); + ERR_FAIL_COND_V(!tag->args.has("len"), ERR_FILE_CORRUPT); } - int len=tag->args["len"].to_int();; + int len = tag->args["len"].to_int(); + ; DVector reals; reals.resize(len); - DVector::Write w=reals.write(); - real_t *realsptr=w.ptr(); - int idx=0; + DVector::Write w = reals.write(); + real_t *realsptr = w.ptr(); + int idx = 0; String str; - #if 0 while( idx tmpdata; - while( idx::Write(); - r_v=reals; + w = DVector::Write(); + r_v = reals; - Error err=goto_end_of_tag(); - ERR_FAIL_COND_V(err,err); - r_name=name; + Error err = goto_end_of_tag(); + ERR_FAIL_COND_V(err, err); + r_name = name; return OK; - } else if (type=="string_array") { + } else if (type == "string_array") { #if 0 if (!tag->args.has("len")) { ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": Array missing 'len' field: "+name); @@ -946,12 +919,11 @@ Error ResourceInteractiveLoaderXML::parse_property(Variant& r_v, String &r_name, return OK; #endif if (!tag->args.has("len")) { - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": String Array missing 'len' field: "+name); - ERR_FAIL_COND_V(!tag->args.has("len"),ERR_FILE_CORRUPT); + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": String Array missing 'len' field: " + name); + ERR_FAIL_COND_V(!tag->args.has("len"), ERR_FILE_CORRUPT); } - - int len=tag->args["len"].to_int(); + int len = tag->args["len"].to_int(); StringArray array; array.resize(len); @@ -960,48 +932,48 @@ Error ResourceInteractiveLoaderXML::parse_property(Variant& r_v, String &r_name, Error err; Variant v; String tagname; - int idx=0; + int idx = 0; + while ((err = parse_property(v, tagname)) == OK) { - while( (err=parse_property(v,tagname))==OK ) { - - ERR_CONTINUE( idx <0 || idx >=len ); + ERR_CONTINUE(idx < 0 || idx >= len); String str = v; //convert back to string - w[idx]=str; + w[idx] = str; idx++; } - if (idx!=len) { - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": Error loading array (size mismatch): "+name); - ERR_FAIL_COND_V(idx!=len,err); + if (idx != len) { + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": Error loading array (size mismatch): " + name); + ERR_FAIL_COND_V(idx != len, err); } - if (err!=ERR_FILE_EOF) { - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": Error loading array: "+name); - ERR_FAIL_COND_V(err!=ERR_FILE_EOF,err); + if (err != ERR_FILE_EOF) { + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": Error loading array: " + name); + ERR_FAIL_COND_V(err != ERR_FILE_EOF, err); } //err=parse_property_data(name); // skip the rest //ERR_FAIL_COND_V(err,err); - r_name=name; - r_v=array; + r_name = name; + r_v = array; return OK; - } else if (type=="vector3_array") { + } else if (type == "vector3_array") { if (!tag->args.has("len")) { - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": Array missing 'len' field: "+name); - ERR_FAIL_COND_V(!tag->args.has("len"),ERR_FILE_CORRUPT); + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": Array missing 'len' field: " + name); + ERR_FAIL_COND_V(!tag->args.has("len"), ERR_FILE_CORRUPT); } - int len=tag->args["len"].to_int();; + int len = tag->args["len"].to_int(); + ; DVector vectors; vectors.resize(len); - DVector::Write w=vectors.write(); - Vector3 *vectorsptr=w.ptr(); - int idx=0; - int subidx=0; + DVector::Write w = vectors.write(); + Vector3 *vectorsptr = w.ptr(); + int idx = 0; + int subidx = 0; Vector3 auxvec; String str; @@ -1045,57 +1017,54 @@ Error ResourceInteractiveLoaderXML::parse_property(Variant& r_v, String &r_name, Vector tmpdata; - while( idxget_ticks_usec() - tbegin)/1000000.0; + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": Premature end of vector3 array"); + ERR_FAIL_COND_V(idx < len, ERR_FILE_CORRUPT); + // double time_taken = (OS::get_singleton()->get_ticks_usec() - tbegin)/1000000.0; - - w=DVector::Write(); - r_v=vectors; + w = DVector::Write(); + r_v = vectors; String sdfsdfg; - Error err=goto_end_of_tag(); - ERR_FAIL_COND_V(err,err); - r_name=name; + Error err = goto_end_of_tag(); + ERR_FAIL_COND_V(err, err); + r_name = name; return OK; - } else if (type=="vector2_array") { + } else if (type == "vector2_array") { if (!tag->args.has("len")) { - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": Array missing 'len' field: "+name); - ERR_FAIL_COND_V(!tag->args.has("len"),ERR_FILE_CORRUPT); + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": Array missing 'len' field: " + name); + ERR_FAIL_COND_V(!tag->args.has("len"), ERR_FILE_CORRUPT); } - int len=tag->args["len"].to_int();; + int len = tag->args["len"].to_int(); + ; DVector vectors; vectors.resize(len); - DVector::Write w=vectors.write(); - Vector2 *vectorsptr=w.ptr(); - int idx=0; - int subidx=0; + DVector::Write w = vectors.write(); + Vector2 *vectorsptr = w.ptr(); + int idx = 0; + int subidx = 0; Vector2 auxvec; String str; @@ -1139,278 +1108,250 @@ Error ResourceInteractiveLoaderXML::parse_property(Variant& r_v, String &r_name, Vector tmpdata; - while( idxget_ticks_usec() - tbegin)/1000000.0; + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": Premature end of vector2 array"); + ERR_FAIL_COND_V(idx < len, ERR_FILE_CORRUPT); + // double time_taken = (OS::get_singleton()->get_ticks_usec() - tbegin)/1000000.0; - - w=DVector::Write(); - r_v=vectors; + w = DVector::Write(); + r_v = vectors; String sdfsdfg; - Error err=goto_end_of_tag(); - ERR_FAIL_COND_V(err,err); - r_name=name; + Error err = goto_end_of_tag(); + ERR_FAIL_COND_V(err, err); + r_name = name; return OK; - } else if (type=="color_array") { + } else if (type == "color_array") { if (!tag->args.has("len")) { - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": Array missing 'len' field: "+name); - ERR_FAIL_COND_V(!tag->args.has("len"),ERR_FILE_CORRUPT); + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": Array missing 'len' field: " + name); + ERR_FAIL_COND_V(!tag->args.has("len"), ERR_FILE_CORRUPT); } - int len=tag->args["len"].to_int();; + int len = tag->args["len"].to_int(); + ; DVector colors; colors.resize(len); - DVector::Write w=colors.write(); - Color *colorsptr=w.ptr(); - int idx=0; - int subidx=0; + DVector::Write w = colors.write(); + Color *colorsptr = w.ptr(); + int idx = 0; + int subidx = 0; Color auxcol; String str; - while( idxeof_reached(), ERR_FILE_CORRUPT); - CharType c=get_char(); - ERR_FAIL_COND_V(f->eof_reached(),ERR_FILE_CORRUPT); - - - if (c<33 || c==',' || c=='<') { + if (c < 33 || c == ',' || c == '<') { if (str.length()) { - auxcol[subidx]=str.to_double(); + auxcol[subidx] = str.to_double(); subidx++; - str=""; - if (subidx==4) { - colorsptr[idx]=auxcol; + str = ""; + if (subidx == 4) { + colorsptr[idx] = auxcol; idx++; - subidx=0; + subidx = 0; } } - if (c=='<') { + if (c == '<') { - while(get_char()!='>' && !f->eof_reached()) {} - ERR_FAIL_COND_V(f->eof_reached(),ERR_FILE_CORRUPT); + while (get_char() != '>' && !f->eof_reached()) { + } + ERR_FAIL_COND_V(f->eof_reached(), ERR_FILE_CORRUPT); break; } } else { - str+=c; + str += c; } } - w=DVector::Write(); - r_v=colors; + w = DVector::Write(); + r_v = colors; String sdfsdfg; - Error err=parse_property_data(sdfsdfg); - ERR_FAIL_COND_V(err,err); - r_name=name; + Error err = parse_property_data(sdfsdfg); + ERR_FAIL_COND_V(err, err); + r_name = name; return OK; } - String data; Error err = parse_property_data(data); - ERR_FAIL_COND_V(err!=OK,err); + ERR_FAIL_COND_V(err != OK, err); - if (type=="nil") { + if (type == "nil") { // uh do nothing - } else if (type=="bool") { + } else if (type == "bool") { // uh do nothing - if (data.nocasecmp_to("true")==0 || data.to_int()!=0) - r_v=true; + if (data.nocasecmp_to("true") == 0 || data.to_int() != 0) + r_v = true; else - r_v=false; - } else if (type=="int") { + r_v = false; + } else if (type == "int") { - r_v=data.to_int(); - } else if (type=="real") { + r_v = data.to_int(); + } else if (type == "real") { - r_v=data.to_double(); - } else if (type=="string") { + r_v = data.to_double(); + } else if (type == "string") { - String str=data; + String str = data; unquote(str); - r_v=str; - } else if (type=="vector3") { + r_v = str; + } else if (type == "vector3") { + r_v = Vector3( + data.get_slicec(',', 0).to_double(), + data.get_slicec(',', 1).to_double(), + data.get_slicec(',', 2).to_double()); - r_v=Vector3( - data.get_slicec(',',0).to_double(), - data.get_slicec(',',1).to_double(), - data.get_slicec(',',2).to_double() - ); + } else if (type == "vector2") { - } else if (type=="vector2") { + r_v = Vector2( + data.get_slicec(',', 0).to_double(), + data.get_slicec(',', 1).to_double()); + } else if (type == "plane") { - r_v=Vector2( - data.get_slicec(',',0).to_double(), - data.get_slicec(',',1).to_double() - ); + r_v = Plane( + data.get_slicec(',', 0).to_double(), + data.get_slicec(',', 1).to_double(), + data.get_slicec(',', 2).to_double(), + data.get_slicec(',', 3).to_double()); - } else if (type=="plane") { + } else if (type == "quaternion") { - r_v=Plane( - data.get_slicec(',',0).to_double(), - data.get_slicec(',',1).to_double(), - data.get_slicec(',',2).to_double(), - data.get_slicec(',',3).to_double() - ); + r_v = Quat( + data.get_slicec(',', 0).to_double(), + data.get_slicec(',', 1).to_double(), + data.get_slicec(',', 2).to_double(), + data.get_slicec(',', 3).to_double()); - } else if (type=="quaternion") { + } else if (type == "rect2") { - r_v=Quat( - data.get_slicec(',',0).to_double(), - data.get_slicec(',',1).to_double(), - data.get_slicec(',',2).to_double(), - data.get_slicec(',',3).to_double() - ); + r_v = Rect2( + Vector2( + data.get_slicec(',', 0).to_double(), + data.get_slicec(',', 1).to_double()), + Vector2( + data.get_slicec(',', 2).to_double(), + data.get_slicec(',', 3).to_double())); - } else if (type=="rect2") { + } else if (type == "aabb") { - r_v=Rect2( - Vector2( - data.get_slicec(',',0).to_double(), - data.get_slicec(',',1).to_double() - ), - Vector2( - data.get_slicec(',',2).to_double(), - data.get_slicec(',',3).to_double() - ) - ); + r_v = AABB( + Vector3( + data.get_slicec(',', 0).to_double(), + data.get_slicec(',', 1).to_double(), + data.get_slicec(',', 2).to_double()), + Vector3( + data.get_slicec(',', 3).to_double(), + data.get_slicec(',', 4).to_double(), + data.get_slicec(',', 5).to_double())); - - } else if (type=="aabb") { - - r_v=AABB( - Vector3( - data.get_slicec(',',0).to_double(), - data.get_slicec(',',1).to_double(), - data.get_slicec(',',2).to_double() - ), - Vector3( - data.get_slicec(',',3).to_double(), - data.get_slicec(',',4).to_double(), - data.get_slicec(',',5).to_double() - ) - ); - - } else if (type=="matrix32") { + } else if (type == "matrix32") { Matrix32 m3; - for (int i=0;i<3;i++) { - for (int j=0;j<2;j++) { - m3.elements[i][j]=data.get_slicec(',',i*2+j).to_double(); + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 2; j++) { + m3.elements[i][j] = data.get_slicec(',', i * 2 + j).to_double(); } } - r_v=m3; + r_v = m3; - } else if (type=="matrix3") { + } else if (type == "matrix3") { Matrix3 m3; - for (int i=0;i<3;i++) { - for (int j=0;j<3;j++) { - m3.elements[i][j]=data.get_slicec(',',i*3+j).to_double(); + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 3; j++) { + m3.elements[i][j] = data.get_slicec(',', i * 3 + j).to_double(); } } - r_v=m3; + r_v = m3; - } else if (type=="transform") { + } else if (type == "transform") { Transform tr; - for (int i=0;i<3;i++) { - for (int j=0;j<3;j++) { - tr.basis.elements[i][j]=data.get_slicec(',',i*3+j).to_double(); + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 3; j++) { + tr.basis.elements[i][j] = data.get_slicec(',', i * 3 + j).to_double(); } - } - tr.origin=Vector3( - data.get_slicec(',',9).to_double(), - data.get_slicec(',',10).to_double(), - data.get_slicec(',',11).to_double() - ); - r_v=tr; + tr.origin = Vector3( + data.get_slicec(',', 9).to_double(), + data.get_slicec(',', 10).to_double(), + data.get_slicec(',', 11).to_double()); + r_v = tr; - } else if (type=="color") { + } else if (type == "color") { - r_v=Color( - data.get_slicec(',',0).to_double(), - data.get_slicec(',',1).to_double(), - data.get_slicec(',',2).to_double(), - data.get_slicec(',',3).to_double() - ); + r_v = Color( + data.get_slicec(',', 0).to_double(), + data.get_slicec(',', 1).to_double(), + data.get_slicec(',', 2).to_double(), + data.get_slicec(',', 3).to_double()); - } else if (type=="node_path") { + } else if (type == "node_path") { - String str=data; + String str = data; unquote(str); - r_v=NodePath( str ); - } else if (type=="input_event") { + r_v = NodePath(str); + } else if (type == "input_event") { // ? } else { - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": Unrecognized tag in file: "+type); + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": Unrecognized tag in file: " + type); ERR_FAIL_V(ERR_FILE_CORRUPT); } - r_name=name; + r_name = name; return OK; } - - int ResourceInteractiveLoaderXML::get_current_line() const { return lines; } - uint8_t ResourceInteractiveLoaderXML::get_char() const { uint8_t c = f->get_8(); - if (c=='\n') + if (c == '\n') lines++; return c; - } - - - /// -void ResourceInteractiveLoaderXML::set_local_path(const String& p_local_path) { +void ResourceInteractiveLoaderXML::set_local_path(const String &p_local_path) { - res_path=p_local_path; + res_path = p_local_path; } Ref ResourceInteractiveLoaderXML::get_resource() { @@ -1419,18 +1360,17 @@ Ref ResourceInteractiveLoaderXML::get_resource() { } Error ResourceInteractiveLoaderXML::poll() { - if (error!=OK) + if (error != OK) return error; bool exit; Tag *tag = parse_tag(&exit); - if (!tag) { - error=ERR_FILE_CORRUPT; + error = ERR_FILE_CORRUPT; if (!exit) // shouldn't have exited ERR_FAIL_V(error); - error=ERR_FILE_EOF; + error = ERR_FILE_EOF; return error; } @@ -1439,40 +1379,39 @@ Error ResourceInteractiveLoaderXML::poll() { bool main; - if (tag->name=="ext_resource") { + if (tag->name == "ext_resource") { - error=ERR_FILE_CORRUPT; - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": missing 'path' field."); - ERR_FAIL_COND_V(!tag->args.has("path"),ERR_FILE_CORRUPT); + error = ERR_FILE_CORRUPT; + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": missing 'path' field."); + ERR_FAIL_COND_V(!tag->args.has("path"), ERR_FILE_CORRUPT); - String type="Resource"; + String type = "Resource"; if (tag->args.has("type")) - type=tag->args["type"]; + type = tag->args["type"]; String path = tag->args["path"]; + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": can't use a local path, this is a bug?."); + ERR_FAIL_COND_V(path.begins_with("local://"), ERR_FILE_CORRUPT); - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": can't use a local path, this is a bug?."); - ERR_FAIL_COND_V(path.begins_with("local://"),ERR_FILE_CORRUPT); - - 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=Globals::get_singleton()->localize_path(local_path.get_base_dir().plus_file(path)); + path = Globals::get_singleton()->localize_path(local_path.get_base_dir().plus_file(path)); } if (remaps.has(path)) { - path=remaps[path]; + path = remaps[path]; } - RES res = ResourceLoader::load(path,type); + RES res = ResourceLoader::load(path, type); if (res.is_null()) { if (ResourceLoader::get_abort_on_missing_resources()) { - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": referenced nonexistent resource at: "+path); + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": referenced nonexistent resource at: " + path); ERR_FAIL_V(error); } else { - ResourceLoader::notify_dependency_error(local_path,path,type); + ResourceLoader::notify_dependency_error(local_path, path, type); } } else { @@ -1481,111 +1420,107 @@ Error ResourceInteractiveLoaderXML::poll() { if (tag->args.has("index")) { ExtResource er; - er.path=path; - er.type=type; - ext_resources[tag->args["index"].to_int()]=er; + er.path = path; + er.type = type; + ext_resources[tag->args["index"].to_int()] = er; } - Error err = close_tag("ext_resource"); if (err) return error; - - error=OK; + error = OK; resource_current++; return error; - } else if (tag->name=="resource") { + } else if (tag->name == "resource") { - main=false; - } else if (tag->name=="main_resource") { - main=true; + main = false; + } else if (tag->name == "main_resource") { + main = true; } else { - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": unexpected main tag: "+tag->name); - error=ERR_FILE_CORRUPT; + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": unexpected main tag: " + tag->name); + error = ERR_FILE_CORRUPT; ERR_FAIL_V(error); } - String type; String path; - int subres=0; + int subres = 0; if (!main) { //loading resource - error=ERR_FILE_CORRUPT; - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": missing 'len' field."); - ERR_FAIL_COND_V(!tag->args.has("path"),ERR_FILE_CORRUPT); - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": missing 'type' field."); - ERR_FAIL_COND_V(!tag->args.has("type"),ERR_FILE_CORRUPT); - path=tag->args["path"]; + error = ERR_FILE_CORRUPT; + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": missing 'len' field."); + ERR_FAIL_COND_V(!tag->args.has("path"), ERR_FILE_CORRUPT); + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": missing 'type' field."); + ERR_FAIL_COND_V(!tag->args.has("type"), ERR_FILE_CORRUPT); + path = tag->args["path"]; - error=OK; + error = OK; if (path.begins_with("local://")) { //built-in resource (but really external) - path=path.replace("local://",""); - subres=path.to_int(); - path=local_path+"::"+path; + path = path.replace("local://", ""); + subres = path.to_int(); + path = local_path + "::" + path; } - if (ResourceCache::has(path)) { Error err = close_tag(tag->name); if (err) { - error=ERR_FILE_CORRUPT; + error = ERR_FILE_CORRUPT; } - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": Unable to close tag."); - ERR_FAIL_COND_V( err, err ); + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": Unable to close tag."); + ERR_FAIL_COND_V(err, err); resource_current++; - error=OK; + error = OK; return OK; } type = tag->args["type"]; } else { - type=resource_type; + type = resource_type; } Object *obj = ObjectTypeDB::instance(type); if (!obj) { - error=ERR_FILE_CORRUPT; - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": Object of unrecognized type in file: "+type); + error = ERR_FILE_CORRUPT; + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": Object of unrecognized type in file: " + type); } - ERR_FAIL_COND_V(!obj,ERR_FILE_CORRUPT); + ERR_FAIL_COND_V(!obj, ERR_FILE_CORRUPT); Resource *r = obj->cast_to(); if (!r) { - error=ERR_FILE_CORRUPT; + error = ERR_FILE_CORRUPT; memdelete(obj); //bye - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": Object type in resource field not a resource, type is: "+obj->get_type()); - ERR_FAIL_COND_V(!r,ERR_FILE_CORRUPT); + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": Object type in resource field not a resource, type is: " + obj->get_type()); + ERR_FAIL_COND_V(!r, ERR_FILE_CORRUPT); } - res = RES( r ); - if (path!="") + res = RES(r); + if (path != "") r->set_path(path); r->set_subindex(subres); //load properties - while(true) { + while (true) { String name; Variant v; Error err; - err = parse_property(v,name); - if (err==ERR_FILE_EOF) //tag closed + err = parse_property(v, name); + if (err == ERR_FILE_EOF) //tag closed break; - if (err!=OK) { - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": XML Parsing aborted."); - ERR_FAIL_COND_V(err!=OK,ERR_FILE_CORRUPT); + if (err != OK) { + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": XML Parsing aborted."); + ERR_FAIL_COND_V(err != OK, ERR_FILE_CORRUPT); } - obj->set(name,v); + obj->set(name, v); } #ifdef TOOLS_ENABLED res->set_edited(false); @@ -1594,15 +1529,14 @@ Error ResourceInteractiveLoaderXML::poll() { resource_current++; if (main) { f->close(); - resource=res; + resource = res; if (!ResourceCache::has(res_path)) { resource->set_path(res_path); } - error=ERR_FILE_EOF; + error = ERR_FILE_EOF; return error; - } - error=OK; + error = OK; return OK; } @@ -1612,7 +1546,7 @@ int ResourceInteractiveLoaderXML::get_stage() const { } int ResourceInteractiveLoaderXML::get_stage_count() const { - return resources_total;//+ext_resources; + return resources_total; //+ext_resources; } ResourceInteractiveLoaderXML::~ResourceInteractiveLoaderXML() { @@ -1620,51 +1554,49 @@ ResourceInteractiveLoaderXML::~ResourceInteractiveLoaderXML() { memdelete(f); } -void ResourceInteractiveLoaderXML::get_dependencies(FileAccess *f,List *p_dependencies,bool p_add_types) { - +void ResourceInteractiveLoaderXML::get_dependencies(FileAccess *f, List *p_dependencies, bool p_add_types) { open(f); - ERR_FAIL_COND(error!=OK); + ERR_FAIL_COND(error != OK); - while(true) { + while (true) { bool exit; Tag *tag = parse_tag(&exit); - if (!tag) { - error=ERR_FILE_CORRUPT; + error = ERR_FILE_CORRUPT; ERR_FAIL_COND(!exit); - error=ERR_FILE_EOF; + error = ERR_FILE_EOF; return; } - if (tag->name!="ext_resource") { + if (tag->name != "ext_resource") { return; } - error=ERR_FILE_CORRUPT; - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": missing 'path' field."); + error = ERR_FILE_CORRUPT; + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": missing 'path' field."); ERR_FAIL_COND(!tag->args.has("path")); String path = tag->args["path"]; - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": can't use a local path, this is a bug?."); + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": can't use a local path, this is a bug?."); ERR_FAIL_COND(path.begins_with("local://")); - 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=Globals::get_singleton()->localize_path(local_path.get_base_dir().plus_file(path)); + path = Globals::get_singleton()->localize_path(local_path.get_base_dir().plus_file(path)); } if (path.ends_with("*")) { ERR_FAIL_COND(!tag->args.has("type")); String type = tag->args["type"]; - path = ResourceLoader::guess_full_filename(path,type); + path = ResourceLoader::guess_full_filename(path, type); } if (p_add_types && tag->args.has("type")) { - path+="::"+tag->args["type"]; + path += "::" + tag->args["type"]; } p_dependencies->push_back(path); @@ -1673,275 +1605,254 @@ void ResourceInteractiveLoaderXML::get_dependencies(FileAccess *f,List * if (err) return; - error=OK; + error = OK; } - } -Error ResourceInteractiveLoaderXML::get_export_data(FileAccess *p_f,ExportData& r_export_data) { +Error ResourceInteractiveLoaderXML::get_export_data(FileAccess *p_f, ExportData &r_export_data) { open(p_f); - ERR_FAIL_COND_V(error!=OK,error); - - + ERR_FAIL_COND_V(error != OK, error); while (true) { bool exit; Tag *tag = parse_tag(&exit); if (!tag) { - error=ERR_FILE_CORRUPT; + error = ERR_FILE_CORRUPT; if (!exit) // shouldn't have exited ERR_FAIL_V(error); - error=ERR_FILE_EOF; + error = ERR_FILE_EOF; return error; } - bool main; - if (tag->name=="ext_resource") { + if (tag->name == "ext_resource") { ExportData::Dependency dep; - error=ERR_FILE_CORRUPT; - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": missing 'path' field."); - ERR_FAIL_COND_V(!tag->args.has("path"),ERR_FILE_CORRUPT); + error = ERR_FILE_CORRUPT; + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": missing 'path' field."); + ERR_FAIL_COND_V(!tag->args.has("path"), ERR_FILE_CORRUPT); - String type="Resource"; + String type = "Resource"; if (tag->args.has("type")) - type=tag->args["type"]; + type = tag->args["type"]; String path = tag->args["path"]; - dep.path=path; - dep.type=type; - + dep.path = path; + dep.type = type; if (tag->args.has("index")) { ExtResource er; - er.path=path; - er.type=type; - r_export_data.dependencies[tag->args["index"].to_int()]=dep; + er.path = path; + er.type = type; + r_export_data.dependencies[tag->args["index"].to_int()] = dep; } else { int index = r_export_data.dependencies.size(); - r_export_data.dependencies[index]=dep; - + r_export_data.dependencies[index] = dep; } - - Error err = close_tag("ext_resource"); if (err) return error; continue; - } else if (tag->name=="resource") { + } else if (tag->name == "resource") { - main=false; - } else if (tag->name=="main_resource") { - main=true; + main = false; + } else if (tag->name == "main_resource") { + main = true; } else { - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": unexpected main tag: "+tag->name); - error=ERR_FILE_CORRUPT; + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": unexpected main tag: " + tag->name); + error = ERR_FILE_CORRUPT; ERR_FAIL_V(error); } - r_export_data.resources.resize( r_export_data.resources.size()+1 ); + r_export_data.resources.resize(r_export_data.resources.size() + 1); - ExportData::ResourceData &res_data=r_export_data.resources[ r_export_data.resources.size()-1 ]; + ExportData::ResourceData &res_data = r_export_data.resources[r_export_data.resources.size() - 1]; - - res_data.index=-1; + res_data.index = -1; if (!main) { //loading resource + String path = tag->args["path"]; - String path=tag->args["path"]; - - error=OK; + error = OK; if (path.begins_with("local://")) { //built-in resource (but really external) - path=path.replace("local://",""); - res_data.index=path.to_int(); + path = path.replace("local://", ""); + res_data.index = path.to_int(); } - res_data.type= tag->args["type"]; + res_data.type = tag->args["type"]; } else { - res_data.type=resource_type; - - + res_data.type = resource_type; } //load properties - while(true) { + while (true) { String name; Variant v; Error err; - err = parse_property(v,name); + err = parse_property(v, name); - if (err==ERR_FILE_EOF) //tag closed + if (err == ERR_FILE_EOF) //tag closed break; - - if (err!=OK) { - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": XML Parsing aborted."); - ERR_FAIL_COND_V(err!=OK,ERR_FILE_CORRUPT); + if (err != OK) { + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": XML Parsing aborted."); + ERR_FAIL_COND_V(err != OK, ERR_FILE_CORRUPT); } ExportData::PropertyData prop; - prop.name=name; - prop.value=v; + prop.name = name; + prop.value = v; res_data.properties.push_back(prop); - } if (main) { return OK; - } } return OK; } - -Error ResourceInteractiveLoaderXML::rename_dependencies(FileAccess *p_f, const String &p_path,const Map& p_map) { +Error ResourceInteractiveLoaderXML::rename_dependencies(FileAccess *p_f, const String &p_path, const Map &p_map) { open(p_f); - ERR_FAIL_COND_V(error!=OK,error); + ERR_FAIL_COND_V(error != OK, error); //FileAccess - bool old_format=false; + bool old_format = false; FileAccess *fw = NULL; - String base_path=local_path.get_base_dir(); + String base_path = local_path.get_base_dir(); - while(true) { + while (true) { bool exit; List order; - Tag *tag = parse_tag(&exit,true,&order); + Tag *tag = parse_tag(&exit, true, &order); - bool done=false; + bool done = false; if (!tag) { if (fw) { memdelete(fw); } - error=ERR_FILE_CORRUPT; - ERR_FAIL_COND_V(!exit,error); - error=ERR_FILE_EOF; + error = ERR_FILE_CORRUPT; + ERR_FAIL_COND_V(!exit, error); + error = ERR_FILE_EOF; return error; } - if (tag->name=="ext_resource") { + if (tag->name == "ext_resource") { if (!tag->args.has("index") || !tag->args.has("path") || !tag->args.has("type")) { - old_format=true; + old_format = true; break; } if (!fw) { - fw=FileAccess::open(p_path+".depren",FileAccess::WRITE); + fw = FileAccess::open(p_path + ".depren", FileAccess::WRITE); fw->store_line(""); //no escape - fw->store_line(""); - + fw->store_line(""); } String path = tag->args["path"]; String index = tag->args["index"]; String type = tag->args["type"]; - - bool relative=false; + bool relative = false; if (!path.begins_with("res://")) { - path=base_path.plus_file(path).simplify_path(); - relative=true; + path = base_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=base_path.path_to_file(path); + path = base_path.path_to_file(path); } - tag->args["path"]=path; - tag->args["index"]=index; - tag->args["type"]=type; + tag->args["path"] = path; + tag->args["index"] = index; + tag->args["type"] = type; } else { - done=true; + done = true; } - String tagt="\t<"; + String tagt = "\t<"; if (exit) - tagt+="/"; - tagt+=tag->name; + tagt += "/"; + tagt += tag->name; - for(List::Element *E=order.front();E;E=E->next()) { - tagt+=" "+E->get()+"=\""+tag->args[E->get()]+"\""; + for (List::Element *E = order.front(); E; E = E->next()) { + tagt += " " + E->get() + "=\"" + tag->args[E->get()] + "\""; } - tagt+=">"; + tagt += ">"; fw->store_line(tagt); if (done) break; close_tag("ext_resource"); fw->store_line("\t"); - } - if (old_format) { if (fw) 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; - FileAccess *f2 = FileAccess::open(p_path,FileAccess::READ,&err); - if (err!=OK) { - ERR_FAIL_COND_V(err!=OK,ERR_FILE_CANT_OPEN); + FileAccess *f2 = FileAccess::open(p_path, FileAccess::READ, &err); + if (err != OK) { + ERR_FAIL_COND_V(err != OK, ERR_FILE_CANT_OPEN); } - Ref ria = memnew( ResourceInteractiveLoaderXML ); - ria->local_path=Globals::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) ); + Ref ria = memnew(ResourceInteractiveLoaderXML); + ria->local_path = Globals::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(f2); 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 ResourceFormatSaverXML::singleton->save(p_path,res); + return ResourceFormatSaverXML::singleton->save(p_path, res); } if (!fw) { @@ -1949,14 +1860,14 @@ Error ResourceInteractiveLoaderXML::rename_dependencies(FileAccess *p_f, const S return OK; //nothing to rename, do nothing } - uint8_t c=f->get_8(); - while(!f->eof_reached()) { + uint8_t c = f->get_8(); + while (!f->eof_reached()) { fw->store_8(c); - c=f->get_8(); + c = f->get_8(); } f->close(); - bool all_ok = fw->get_error()==OK; + bool all_ok = fw->get_error() == OK; memdelete(fw); @@ -1966,28 +1877,25 @@ Error ResourceInteractiveLoaderXML::rename_dependencies(FileAccess *p_f, const S 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; - } - void ResourceInteractiveLoaderXML::open(FileAccess *p_f) { - error=OK; - - lines=1; - f=p_f; + error = OK; + lines = 1; + f = p_f; ResourceInteractiveLoaderXML::Tag *tag = parse_tag(); - if (!tag || tag->name!="?xml" || !tag->args.has("version") || !tag->args.has("encoding") || tag->args["encoding"]!="UTF-8") { + if (!tag || tag->name != "?xml" || !tag->args.has("version") || !tag->args.has("encoding") || tag->args["encoding"] != "UTF-8") { - error=ERR_FILE_CORRUPT; + error = ERR_FILE_CORRUPT; ResourceLoader::notify_load_error("XML is invalid (missing header tags)"); - ERR_EXPLAIN("Not a XML:UTF-8 File: "+local_path); + ERR_EXPLAIN("Not a XML:UTF-8 File: " + local_path); ERR_FAIL(); } @@ -1995,38 +1903,35 @@ void ResourceInteractiveLoaderXML::open(FileAccess *p_f) { tag = parse_tag(); + if (!tag || tag->name != "resource_file" || !tag->args.has("type") || !tag->args.has("version")) { - if (!tag || tag->name!="resource_file" || !tag->args.has("type") || !tag->args.has("version")) { - - ResourceLoader::notify_load_error(local_path+": XML is not a valid resource file."); - error=ERR_FILE_CORRUPT; - ERR_EXPLAIN("Unrecognized XML File: "+local_path); + ResourceLoader::notify_load_error(local_path + ": XML is not a valid resource file."); + error = ERR_FILE_CORRUPT; + ERR_EXPLAIN("Unrecognized XML File: " + local_path); ERR_FAIL(); } - if (tag->args.has("subresource_count")) - resources_total=tag->args["subresource_count"].to_int(); - resource_current=0; - resource_type=tag->args["type"]; + resources_total = tag->args["subresource_count"].to_int(); + resource_current = 0; + resource_type = tag->args["type"]; String version = tag->args["version"]; - if (version.get_slice_count(".")!=2) { + if (version.get_slice_count(".") != 2) { - error=ERR_FILE_CORRUPT; - ResourceLoader::notify_load_error(local_path+":XML version string is invalid: "+version); - ERR_EXPLAIN("Invalid Version String '"+version+"'' in file: "+local_path); + error = ERR_FILE_CORRUPT; + ResourceLoader::notify_load_error(local_path + ":XML version string is invalid: " + version); + ERR_EXPLAIN("Invalid Version String '" + version + "'' in file: " + local_path); ERR_FAIL(); } - int major = version.get_slicec('.',0).to_int(); - if (major>VERSION_MAJOR) { + int major = version.get_slicec('.', 0).to_int(); + if (major > VERSION_MAJOR) { - error=ERR_FILE_UNRECOGNIZED; - ResourceLoader::notify_load_error(local_path+": File Format '"+version+"' is too new. Please upgrade to a newer engine version."); - ERR_EXPLAIN("File Format '"+version+"' is too new! Please upgrade to a a new engine version: "+local_path); + error = ERR_FILE_UNRECOGNIZED; + ResourceLoader::notify_load_error(local_path + ": File Format '" + version + "' is too new. Please upgrade to a newer engine version."); + ERR_EXPLAIN("File Format '" + version + "' is too new! Please upgrade to a a new engine version: " + local_path); ERR_FAIL(); - } /* @@ -2042,19 +1947,17 @@ void ResourceInteractiveLoaderXML::open(FileAccess *p_f) { print_line(local_path+" - EXTERNAL RESOURCES: "+itos(ext_resources.size())); } */ - } String ResourceInteractiveLoaderXML::recognize(FileAccess *p_f) { - error=OK; + error = OK; - lines=1; - f=p_f; + lines = 1; + f = p_f; ResourceInteractiveLoaderXML::Tag *tag = parse_tag(); - if (!tag || tag->name!="?xml" || !tag->args.has("version") || !tag->args.has("encoding") || tag->args["encoding"]!="UTF-8") { - + if (!tag || tag->name != "?xml" || !tag->args.has("version") || !tag->args.has("encoding") || tag->args["encoding"] != "UTF-8") { return ""; //unrecognized } @@ -2063,13 +1966,12 @@ String ResourceInteractiveLoaderXML::recognize(FileAccess *p_f) { tag = parse_tag(); - if (!tag || tag->name!="resource_file" || !tag->args.has("type") || !tag->args.has("version")) { + if (!tag || tag->name != "resource_file" || !tag->args.has("type") || !tag->args.has("version")) { return ""; //unrecognized } return tag->args["type"]; - } ///////////////////// @@ -2077,141 +1979,132 @@ String ResourceInteractiveLoaderXML::recognize(FileAccess *p_f) { Ref ResourceFormatLoaderXML::load_interactive(const String &p_path, Error *r_error) { if (r_error) - *r_error=ERR_CANT_OPEN; + *r_error = ERR_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()); + ERR_FAIL_COND_V(err != OK, Ref()); } - Ref ria = memnew( ResourceInteractiveLoaderXML ); - ria->local_path=Globals::get_singleton()->localize_path(p_path); - ria->res_path=ria->local_path; -// ria->set_local_path( Globals::get_singleton()->localize_path(p_path) ); + Ref ria = memnew(ResourceInteractiveLoaderXML); + ria->local_path = Globals::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 ResourceFormatLoaderXML::get_recognized_extensions_for_type(const String& p_type,List *p_extensions) const { +void ResourceFormatLoaderXML::get_recognized_extensions_for_type(const String &p_type, List *p_extensions) const { - if (p_type=="") { + if (p_type == "") { get_recognized_extensions(p_extensions); return; } List extensions; - ObjectTypeDB::get_extensions_for_type(p_type,&extensions); + ObjectTypeDB::get_extensions_for_type(p_type, &extensions); extensions.sort(); - for(List::Element *E=extensions.front();E;E=E->next()) { + for (List::Element *E = extensions.front(); E; E = E->next()) { String ext = E->get().to_lower(); - if (ext=="res") + if (ext == "res") continue; - p_extensions->push_back("x"+ext); + p_extensions->push_back("x" + ext); } p_extensions->push_back("xml"); - - } -void ResourceFormatLoaderXML::get_recognized_extensions(List *p_extensions) const{ +void ResourceFormatLoaderXML::get_recognized_extensions(List *p_extensions) const { List extensions; ObjectTypeDB::get_resource_base_extensions(&extensions); extensions.sort(); - for(List::Element *E=extensions.front();E;E=E->next()) { + for (List::Element *E = extensions.front(); E; E = E->next()) { String ext = E->get().to_lower(); - if (ext=="res") + if (ext == "res") continue; - p_extensions->push_back("x"+ext); + p_extensions->push_back("x" + ext); } p_extensions->push_back("xml"); } -bool ResourceFormatLoaderXML::handles_type(const String& p_type) const{ +bool ResourceFormatLoaderXML::handles_type(const String &p_type) const { return true; } -String ResourceFormatLoaderXML::get_resource_type(const String &p_path) const{ +String ResourceFormatLoaderXML::get_resource_type(const String &p_path) const { - - String ext=p_path.extension().to_lower(); + String ext = p_path.extension().to_lower(); if (!ext.begins_with("x")) //a lie but.. return ""; - FileAccess *f = FileAccess::open(p_path,FileAccess::READ); + FileAccess *f = FileAccess::open(p_path, FileAccess::READ); if (!f) { return ""; //could not rwead } - Ref ria = memnew( ResourceInteractiveLoaderXML ); - ria->local_path=Globals::get_singleton()->localize_path(p_path); - ria->res_path=ria->local_path; -// ria->set_local_path( Globals::get_singleton()->localize_path(p_path) ); + Ref ria = memnew(ResourceInteractiveLoaderXML); + ria->local_path = Globals::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 ResourceFormatLoaderXML::get_dependencies(const String &p_path, List *p_dependencies, bool p_add_types) { -void ResourceFormatLoaderXML::get_dependencies(const String& p_path,List *p_dependencies,bool p_add_types) { - - FileAccess *f = FileAccess::open(p_path,FileAccess::READ); + FileAccess *f = FileAccess::open(p_path, FileAccess::READ); if (!f) { ERR_FAIL(); } - Ref ria = memnew( ResourceInteractiveLoaderXML ); - ria->local_path=Globals::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); - - + Ref ria = memnew(ResourceInteractiveLoaderXML); + ria->local_path = Globals::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); } -Error ResourceFormatLoaderXML::get_export_data(const String& p_path,ExportData& r_export_data) { +Error ResourceFormatLoaderXML::get_export_data(const String &p_path, ExportData &r_export_data) { - FileAccess *f = FileAccess::open(p_path,FileAccess::READ); + FileAccess *f = FileAccess::open(p_path, FileAccess::READ); if (!f) { ERR_FAIL_V(ERR_CANT_OPEN); } - Ref ria = memnew( ResourceInteractiveLoaderXML ); - ria->local_path=Globals::get_singleton()->localize_path(p_path); - ria->res_path=ria->local_path; - - return ria->get_export_data(f,r_export_data); + Ref ria = memnew(ResourceInteractiveLoaderXML); + ria->local_path = Globals::get_singleton()->localize_path(p_path); + ria->res_path = ria->local_path; + return ria->get_export_data(f, r_export_data); } +Error ResourceFormatLoaderXML::rename_dependencies(const String &p_path, const Map &p_map) { -Error ResourceFormatLoaderXML::rename_dependencies(const String &p_path,const Map& p_map) { - - FileAccess *f = FileAccess::open(p_path,FileAccess::READ); + FileAccess *f = FileAccess::open(p_path, FileAccess::READ); if (!f) { ERR_FAIL_V(ERR_CANT_OPEN); } - Ref ria = memnew( ResourceInteractiveLoaderXML ); - ria->local_path=Globals::get_singleton()->localize_path(p_path); - ria->res_path=ria->local_path; -// ria->set_local_path( Globals::get_singleton()->localize_path(p_path) ); - return ria->rename_dependencies(f,p_path,p_map); + Ref ria = memnew(ResourceInteractiveLoaderXML); + ria->local_path = Globals::get_singleton()->localize_path(p_path); + ria->res_path = ria->local_path; + // ria->set_local_path( Globals::get_singleton()->localize_path(p_path) ); + return ria->rename_dependencies(f, p_path, p_map); } -ResourceFormatLoaderXML *ResourceFormatLoaderXML::singleton=NULL; +ResourceFormatLoaderXML *ResourceFormatLoaderXML::singleton = NULL; /****************************************************************************************/ /****************************************************************************************/ @@ -2227,41 +2120,38 @@ ResourceFormatLoaderXML *ResourceFormatLoaderXML::singleton=NULL; /****************************************************************************************/ /****************************************************************************************/ +void ResourceFormatSaverXMLInstance::escape(String &p_str) { + p_str = p_str.replace("&", "&"); + p_str = p_str.replace("<", "<"); + p_str = p_str.replace(">", ">"); + p_str = p_str.replace("'", "'"); + p_str = p_str.replace("\"", """); + for (char i = 1; i < 32; i++) { -void ResourceFormatSaverXMLInstance::escape(String& p_str) { + char chr[2] = { i, 0 }; + const char hexn[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; + const char hex[8] = { '&', '#', '0', '0', hexn[i >> 4], hexn[i & 0xf], ';', 0 }; - p_str=p_str.replace("&","&"); - p_str=p_str.replace("<","<"); - p_str=p_str.replace(">",">"); - p_str=p_str.replace("'","'"); - p_str=p_str.replace("\"","""); - for (char i=1;i<32;i++) { - - char chr[2]={i,0}; - const char hexn[16]={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'}; - const char hex[8]={'&','#','0','0',hexn[i>>4],hexn[i&0xf],';',0}; - - p_str=p_str.replace(chr,hex); + p_str = p_str.replace(chr, hex); } - - } void ResourceFormatSaverXMLInstance::write_tabs(int p_diff) { - for (int i=0;istore_8('\t'); } } -void ResourceFormatSaverXMLInstance::write_string(String p_str,bool p_escape) { +void ResourceFormatSaverXMLInstance::write_string(String p_str, bool p_escape) { /* write an UTF8 string */ if (p_escape) escape(p_str); - f->store_string(p_str);; + f->store_string(p_str); + ; /* CharString cs=p_str.utf8(); const char *data=cs.get_data(); @@ -2270,42 +2160,38 @@ void ResourceFormatSaverXMLInstance::write_string(String p_str,bool p_escape) { f->store_8(*data); data++; }*/ - - } -void ResourceFormatSaverXMLInstance::enter_tag(const char* p_tag,const String& p_args) { +void ResourceFormatSaverXMLInstance::enter_tag(const char *p_tag, const String &p_args) { f->store_8('<'); int cc = 0; - const char *c=p_tag; - while(*c) { + const char *c = p_tag; + while (*c) { cc++; c++; } - f->store_buffer((const uint8_t*)p_tag,cc); + f->store_buffer((const uint8_t *)p_tag, cc); if (p_args.length()) { f->store_8(' '); f->store_string(p_args); } f->store_8('>'); depth++; - } -void ResourceFormatSaverXMLInstance::exit_tag(const char* p_tag) { +void ResourceFormatSaverXMLInstance::exit_tag(const char *p_tag) { depth--; f->store_8('<'); f->store_8('/'); int cc = 0; - const char *c=p_tag; - while(*c) { + const char *c = p_tag; + while (*c) { cc++; c++; } - f->store_buffer((const uint8_t*)p_tag,cc); + f->store_buffer((const uint8_t *)p_tag, cc); f->store_8('>'); - } /* @@ -2322,142 +2208,170 @@ static bool _check_type(const Variant& p_property) { return true; }*/ -void ResourceFormatSaverXMLInstance::write_property(const String& p_name,const Variant& p_property,bool *r_ok) { +void ResourceFormatSaverXMLInstance::write_property(const String &p_name, const Variant &p_property, bool *r_ok) { if (r_ok) - *r_ok=false; + *r_ok = false; - const char* type; + const char *type; String params; - bool oneliner=true; + bool oneliner = true; - switch( p_property.get_type() ) { + switch (p_property.get_type()) { - case Variant::NIL: type="nil"; break; - case Variant::BOOL: type="bool"; break; - case Variant::INT: type="int"; break; - case Variant::REAL: type="real"; break; - case Variant::STRING: type="string"; break; - case Variant::VECTOR2: type="vector2"; break; - case Variant::RECT2: type="rect2"; break; - case Variant::VECTOR3: type="vector3"; break; - case Variant::PLANE: type="plane"; break; - case Variant::_AABB: type="aabb"; break; - case Variant::QUAT: type="quaternion"; break; - case Variant::MATRIX32: type="matrix32"; break; - case Variant::MATRIX3: type="matrix3"; break; - case Variant::TRANSFORM: type="transform"; break; - case Variant::COLOR: type="color"; break; + case Variant::NIL: type = "nil"; break; + case Variant::BOOL: type = "bool"; break; + case Variant::INT: type = "int"; break; + case Variant::REAL: type = "real"; break; + case Variant::STRING: type = "string"; break; + case Variant::VECTOR2: type = "vector2"; break; + case Variant::RECT2: type = "rect2"; break; + case Variant::VECTOR3: type = "vector3"; break; + case Variant::PLANE: type = "plane"; break; + case Variant::_AABB: type = "aabb"; break; + case Variant::QUAT: type = "quaternion"; break; + case Variant::MATRIX32: type = "matrix32"; break; + case Variant::MATRIX3: type = "matrix3"; break; + case Variant::TRANSFORM: type = "transform"; break; + case Variant::COLOR: type = "color"; break; case Variant::IMAGE: { - type="image"; - Image img=p_property; + type = "image"; + Image img = p_property; if (img.empty()) { write_tabs(); - enter_tag(type,"name=\""+p_name+"\""); + enter_tag(type, "name=\"" + p_name + "\""); exit_tag(type); if (r_ok) - *r_ok=true; + *r_ok = true; return; } - params+="encoding=\"raw\""; - params+=" width=\""+itos(img.get_width())+"\""; - params+=" height=\""+itos(img.get_height())+"\""; - params+=" mipmaps=\""+itos(img.get_mipmaps())+"\""; + params += "encoding=\"raw\""; + params += " width=\"" + itos(img.get_width()) + "\""; + params += " height=\"" + itos(img.get_height()) + "\""; + params += " mipmaps=\"" + itos(img.get_mipmaps()) + "\""; - switch(img.get_format()) { + switch (img.get_format()) { - case Image::FORMAT_GRAYSCALE: params+=" format=\"grayscale\""; break; - case Image::FORMAT_INTENSITY: params+=" format=\"intensity\""; break; - case Image::FORMAT_GRAYSCALE_ALPHA: params+=" format=\"grayscale_alpha\""; break; - case Image::FORMAT_RGB: params+=" format=\"rgb\""; break; - case Image::FORMAT_RGBA: params+=" format=\"rgba\""; break; - case Image::FORMAT_INDEXED : params+=" format=\"indexed\""; break; - case Image::FORMAT_INDEXED_ALPHA: params+=" format=\"indexed_alpha\""; break; - case Image::FORMAT_BC1: params+=" format=\"bc1\""; break; - case Image::FORMAT_BC2: params+=" format=\"bc2\""; break; - case Image::FORMAT_BC3: params+=" format=\"bc3\""; break; - case Image::FORMAT_BC4: params+=" format=\"bc4\""; break; - case Image::FORMAT_BC5: params+=" format=\"bc5\""; break; - case Image::FORMAT_PVRTC2: params+=" format=\"pvrtc2\""; break; - case Image::FORMAT_PVRTC2_ALPHA: params+=" format=\"pvrtc2a\""; break; - case Image::FORMAT_PVRTC4: params+=" format=\"pvrtc4\""; break; - case Image::FORMAT_PVRTC4_ALPHA: params+=" format=\"pvrtc4a\""; break; - case Image::FORMAT_ETC: params+=" format=\"etc\""; break; - case Image::FORMAT_ATC: params+=" format=\"atc\""; break; - case Image::FORMAT_ATC_ALPHA_EXPLICIT: params+=" format=\"atcae\""; break; - case Image::FORMAT_ATC_ALPHA_INTERPOLATED: params+=" format=\"atcai\""; break; - case Image::FORMAT_CUSTOM: params+=" format=\"custom\" custom_size=\""+itos(img.get_data().size())+"\""; break; + case Image::FORMAT_GRAYSCALE: params += " format=\"grayscale\""; break; + case Image::FORMAT_INTENSITY: params += " format=\"intensity\""; break; + case Image::FORMAT_GRAYSCALE_ALPHA: params += " format=\"grayscale_alpha\""; break; + case Image::FORMAT_RGB: params += " format=\"rgb\""; break; + case Image::FORMAT_RGBA: params += " format=\"rgba\""; break; + case Image::FORMAT_INDEXED: params += " format=\"indexed\""; break; + case Image::FORMAT_INDEXED_ALPHA: params += " format=\"indexed_alpha\""; break; + case Image::FORMAT_BC1: params += " format=\"bc1\""; break; + case Image::FORMAT_BC2: params += " format=\"bc2\""; break; + case Image::FORMAT_BC3: params += " format=\"bc3\""; break; + case Image::FORMAT_BC4: params += " format=\"bc4\""; break; + case Image::FORMAT_BC5: params += " format=\"bc5\""; break; + case Image::FORMAT_PVRTC2: params += " format=\"pvrtc2\""; break; + case Image::FORMAT_PVRTC2_ALPHA: params += " format=\"pvrtc2a\""; break; + case Image::FORMAT_PVRTC4: params += " format=\"pvrtc4\""; break; + case Image::FORMAT_PVRTC4_ALPHA: params += " format=\"pvrtc4a\""; break; + case Image::FORMAT_ETC: params += " format=\"etc\""; break; + case Image::FORMAT_ATC: params += " format=\"atc\""; break; + case Image::FORMAT_ATC_ALPHA_EXPLICIT: params += " format=\"atcae\""; break; + case Image::FORMAT_ATC_ALPHA_INTERPOLATED: params += " format=\"atcai\""; break; + case Image::FORMAT_CUSTOM: params += " format=\"custom\" custom_size=\"" + itos(img.get_data().size()) + "\""; break; default: {} } } break; - case Variant::NODE_PATH: type="node_path"; break; - case Variant::OBJECT: { - type="resource"; + case Variant::NODE_PATH: type = "node_path"; break; + case Variant::OBJECT: { + type = "resource"; RES res = p_property; if (res.is_null()) { write_tabs(); - enter_tag(type,"name=\""+p_name+"\""); + enter_tag(type, "name=\"" + p_name + "\""); exit_tag(type); if (r_ok) - *r_ok=true; + *r_ok = true; return; // don't save it } if (external_resources.has(res)) { - params="external=\""+itos(external_resources[res])+"\""; + params = "external=\"" + itos(external_resources[res]) + "\""; } else { - params="resource_type=\""+res->get_save_type()+"\""; + params = "resource_type=\"" + res->get_save_type() + "\""; - - if (res->get_path().length() && res->get_path().find("::")==-1) { + if (res->get_path().length() && res->get_path().find("::") == -1) { //external resource - String path=relative_paths?local_path.path_to_file(res->get_path()):res->get_path(); + String path = relative_paths ? local_path.path_to_file(res->get_path()) : res->get_path(); escape(path); - params+=" path=\""+path+"\""; + params += " path=\"" + path + "\""; } else { //internal resource ERR_EXPLAIN("Resource was not pre cached for the resource section, bug?"); ERR_FAIL_COND(!resource_set.has(res)); - params+=" path=\"local://"+itos(res->get_subindex())+"\""; + params += " path=\"local://" + itos(res->get_subindex()) + "\""; } } } break; - case Variant::INPUT_EVENT: type="input_event"; break; - case Variant::DICTIONARY: type="dictionary"; params="shared=\""+String(p_property.is_shared()?"true":"false")+"\""; oneliner=false; break; - case Variant::ARRAY: type="array"; params="len=\""+itos(p_property.operator Array().size())+"\" shared=\""+String(p_property.is_shared()?"true":"false")+"\""; oneliner=false; break; + case Variant::INPUT_EVENT: type = "input_event"; break; + case Variant::DICTIONARY: + type = "dictionary"; + params = "shared=\"" + String(p_property.is_shared() ? "true" : "false") + "\""; + oneliner = false; + break; + case Variant::ARRAY: + type = "array"; + params = "len=\"" + itos(p_property.operator Array().size()) + "\" shared=\"" + String(p_property.is_shared() ? "true" : "false") + "\""; + oneliner = false; + break; - case Variant::RAW_ARRAY: type="raw_array"; params="len=\""+itos(p_property.operator DVector < uint8_t >().size())+"\""; break; - case Variant::INT_ARRAY: type="int_array"; params="len=\""+itos(p_property.operator DVector < int >().size())+"\""; break; - case Variant::REAL_ARRAY: type="real_array"; params="len=\""+itos(p_property.operator DVector < real_t >().size())+"\""; break; - case Variant::STRING_ARRAY: oneliner=false; type="string_array"; params="len=\""+itos(p_property.operator DVector < String >().size())+"\""; break; - case Variant::VECTOR2_ARRAY: type="vector2_array"; params="len=\""+itos(p_property.operator DVector < Vector2 >().size())+"\""; break; - case Variant::VECTOR3_ARRAY: type="vector3_array"; params="len=\""+itos(p_property.operator DVector < Vector3 >().size())+"\""; break; - case Variant::COLOR_ARRAY: type="color_array"; params="len=\""+itos(p_property.operator DVector < Color >().size())+"\""; break; + case Variant::RAW_ARRAY: + type = "raw_array"; + params = "len=\"" + itos(p_property.operator DVector().size()) + "\""; + break; + case Variant::INT_ARRAY: + type = "int_array"; + params = "len=\"" + itos(p_property.operator DVector().size()) + "\""; + break; + case Variant::REAL_ARRAY: + type = "real_array"; + params = "len=\"" + itos(p_property.operator DVector().size()) + "\""; + break; + case Variant::STRING_ARRAY: + oneliner = false; + type = "string_array"; + params = "len=\"" + itos(p_property.operator DVector().size()) + "\""; + break; + case Variant::VECTOR2_ARRAY: + type = "vector2_array"; + params = "len=\"" + itos(p_property.operator DVector().size()) + "\""; + break; + case Variant::VECTOR3_ARRAY: + type = "vector3_array"; + params = "len=\"" + itos(p_property.operator DVector().size()) + "\""; + break; + case Variant::COLOR_ARRAY: + type = "color_array"; + params = "len=\"" + itos(p_property.operator DVector().size()) + "\""; + break; default: { ERR_PRINT("Unknown Variant type."); ERR_FAIL(); } - } write_tabs(); - if (p_name!="") { + if (p_name != "") { if (params.length()) - enter_tag(type,"name=\""+p_name+"\" "+params); + enter_tag(type, "name=\"" + p_name + "\" " + params); else - enter_tag(type,"name=\""+p_name+"\""); + enter_tag(type, "name=\"" + p_name + "\""); } else { if (params.length()) - enter_tag(type," "+params); + enter_tag(type, " " + params); else - enter_tag(type,String()); + enter_tag(type, String()); } if (!oneliner) @@ -2465,75 +2379,74 @@ void ResourceFormatSaverXMLInstance::write_property(const String& p_name,const V else f->store_8(' '); - - switch( p_property.get_type() ) { + switch (p_property.get_type()) { case Variant::NIL: { } break; case Variant::BOOL: { - write_string( p_property.operator bool() ? "True":"False" ); + write_string(p_property.operator bool() ? "True" : "False"); } break; case Variant::INT: { - write_string( itos(p_property.operator int()) ); + write_string(itos(p_property.operator int())); } break; case Variant::REAL: { - write_string( rtos(p_property.operator real_t()) ); + write_string(rtos(p_property.operator real_t())); } break; case Variant::STRING: { - String str=p_property; + String str = p_property; escape(str); - str="\""+str+"\""; - write_string( str,false ); + str = "\"" + str + "\""; + write_string(str, false); } break; case Variant::VECTOR2: { Vector2 v = p_property; - write_string( rtoss(v.x) +", "+rtoss(v.y) ); + write_string(rtoss(v.x) + ", " + rtoss(v.y)); } break; case Variant::RECT2: { Rect2 aabb = p_property; - write_string( rtoss(aabb.pos.x) +", "+rtoss(aabb.pos.y) +", "+rtoss(aabb.size.x) +", "+rtoss(aabb.size.y) ); + write_string(rtoss(aabb.pos.x) + ", " + rtoss(aabb.pos.y) + ", " + rtoss(aabb.size.x) + ", " + rtoss(aabb.size.y)); } break; case Variant::VECTOR3: { Vector3 v = p_property; - write_string( rtoss(v.x) +", "+rtoss(v.y)+", "+rtoss(v.z) ); + write_string(rtoss(v.x) + ", " + rtoss(v.y) + ", " + rtoss(v.z)); } break; case Variant::PLANE: { Plane p = p_property; - write_string( rtoss(p.normal.x) +", "+rtoss(p.normal.y)+", "+rtoss(p.normal.z)+", "+rtoss(p.d) ); + write_string(rtoss(p.normal.x) + ", " + rtoss(p.normal.y) + ", " + rtoss(p.normal.z) + ", " + rtoss(p.d)); } break; case Variant::_AABB: { AABB aabb = p_property; - write_string( rtoss(aabb.pos.x) +", "+rtoss(aabb.pos.y) +", "+rtoss(aabb.pos.z) +", "+rtoss(aabb.size.x) +", "+rtoss(aabb.size.y) +", "+rtoss(aabb.size.z) ); + write_string(rtoss(aabb.pos.x) + ", " + rtoss(aabb.pos.y) + ", " + rtoss(aabb.pos.z) + ", " + rtoss(aabb.size.x) + ", " + rtoss(aabb.size.y) + ", " + rtoss(aabb.size.z)); } break; case Variant::QUAT: { Quat quat = p_property; - write_string( rtoss(quat.x)+", "+rtoss(quat.y)+", "+rtoss(quat.z)+", "+rtoss(quat.w)+", "); + write_string(rtoss(quat.x) + ", " + rtoss(quat.y) + ", " + rtoss(quat.z) + ", " + rtoss(quat.w) + ", "); } break; case Variant::MATRIX32: { String s; Matrix32 m3 = p_property; - 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++) { - if (i!=0 || j!=0) - s+=", "; - s+=rtoss( m3.elements[i][j] ); + if (i != 0 || j != 0) + s += ", "; + s += rtoss(m3.elements[i][j]); } } @@ -2544,12 +2457,12 @@ void ResourceFormatSaverXMLInstance::write_property(const String& p_name,const V String s; Matrix3 m3 = p_property; - 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++) { - if (i!=0 || j!=0) - s+=", "; - s+=rtoss( m3.elements[i][j] ); + if (i != 0 || j != 0) + s += ", "; + s += rtoss(m3.elements[i][j]); } } @@ -2561,25 +2474,25 @@ void ResourceFormatSaverXMLInstance::write_property(const String& p_name,const V String s; Transform t = p_property; Matrix3 &m3 = t.basis; - 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++) { - if (i!=0 || j!=0) - s+=", "; - s+=rtoss( m3.elements[i][j] ); + if (i != 0 || j != 0) + s += ", "; + s += rtoss(m3.elements[i][j]); } } - s=s+", "+rtoss(t.origin.x) +", "+rtoss(t.origin.y)+", "+rtoss(t.origin.z); + s = s + ", " + rtoss(t.origin.x) + ", " + rtoss(t.origin.y) + ", " + rtoss(t.origin.z); write_string(s); } break; - // misc types + // misc types case Variant::COLOR: { Color c = p_property; - write_string( rtoss(c.r) +", "+rtoss(c.g)+", "+rtoss(c.b)+", "+rtoss(c.a) ); + write_string(rtoss(c.r) + ", " + rtoss(c.g) + ", " + rtoss(c.b) + ", " + rtoss(c.a)); } break; case Variant::IMAGE: { @@ -2589,23 +2502,24 @@ void ResourceFormatSaverXMLInstance::write_property(const String& p_name,const V DVector data = img.get_data(); int len = data.size(); DVector::Read r = data.read(); - const uint8_t *ptr=r.ptr();; - for (int i=0;i>4], hex[byte&0xF], 0}; - s+=str; + const char hex[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; + char str[3] = { hex[byte >> 4], hex[byte & 0xF], 0 }; + s += str; } write_string(s); } break; case Variant::NODE_PATH: { - String str=p_property; + String str = p_property; escape(str); - str="\""+str+"\""; - write_string( str,false); + str = "\"" + str + "\""; + write_string(str, false); } break; @@ -2627,42 +2541,37 @@ void ResourceFormatSaverXMLInstance::write_property(const String& p_name,const V } break; case Variant::INPUT_EVENT: { - write_string( p_property.operator String() ); + write_string(p_property.operator String()); } break; case Variant::DICTIONARY: { Dictionary dict = p_property; - List keys; dict.get_key_list(&keys); keys.sort(); - for(List::Element *E=keys.front();E;E=E->next()) { + for (List::Element *E = keys.front(); E; E = E->next()) { //if (!_check_type(dict[E->get()])) // continue; bool ok; - write_property("",E->get(),&ok); + write_property("", E->get(), &ok); ERR_CONTINUE(!ok); - write_property("",dict[E->get()],&ok); + write_property("", dict[E->get()], &ok); if (!ok) - write_property("",Variant()); //at least make the file consistent.. + write_property("", Variant()); //at least make the file consistent.. } - - - } break; case Variant::ARRAY: { Array array = p_property; - int len=array.size(); - for (int i=0;i data = p_property; int len = data.size(); DVector::Read r = data.read(); - const uint8_t *ptr=r.ptr();; - for (int i=0;i>4], hex[byte&0xF], 0}; - s+=str; + const char hex[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; + char str[3] = { hex[byte >> 4], hex[byte & 0xF], 0 }; + s += str; } - write_string(s,false); + write_string(s, false); } break; case Variant::INT_ARRAY: { @@ -2690,55 +2600,53 @@ void ResourceFormatSaverXMLInstance::write_property(const String& p_name,const V DVector data = p_property; int len = data.size(); DVector::Read r = data.read(); - const int *ptr=r.ptr();; + const int *ptr = r.ptr(); + ; write_tabs(); - for (int i=0;i0) - write_string(", ",false); + if (i > 0) + write_string(", ", false); - write_string(itos(ptr[i]),false); + write_string(itos(ptr[i]), false); } - - } break; case Variant::REAL_ARRAY: { DVector data = p_property; int len = data.size(); DVector::Read r = data.read(); - const real_t *ptr=r.ptr();; + const real_t *ptr = r.ptr(); + ; write_tabs(); - String cm=", " ; + String cm = ", "; - for (int i=0;i0) - write_string(cm,false); - write_string(rtoss(ptr[i]),false); + if (i > 0) + write_string(cm, false); + write_string(rtoss(ptr[i]), false); } - } break; case Variant::STRING_ARRAY: { DVector data = p_property; int len = data.size(); DVector::Read r = data.read(); - const String *ptr=r.ptr();; + const String *ptr = r.ptr(); + ; String s; //write_string("\n"); - - - for (int i=0;i \""+str+"\" \n",false); + write_string(" \"" + str + "\" \n", false); } } break; case Variant::VECTOR2_ARRAY: { @@ -2746,63 +2654,60 @@ void ResourceFormatSaverXMLInstance::write_property(const String& p_name,const V DVector data = p_property; int len = data.size(); DVector::Read r = data.read(); - const Vector2 *ptr=r.ptr();; + const Vector2 *ptr = r.ptr(); + ; write_tabs(); - for (int i=0;i0) - write_string(", ",false); - write_string(rtoss(ptr[i].x),false); - write_string(", "+rtoss(ptr[i].y),false); + for (int i = 0; i < len; i++) { + if (i > 0) + write_string(", ", false); + write_string(rtoss(ptr[i].x), false); + write_string(", " + rtoss(ptr[i].y), false); } - } break; case Variant::VECTOR3_ARRAY: { DVector data = p_property; int len = data.size(); DVector::Read r = data.read(); - const Vector3 *ptr=r.ptr();; + const Vector3 *ptr = r.ptr(); + ; write_tabs(); - for (int i=0;i0) - write_string(", ",false); - write_string(rtoss(ptr[i].x),false); - write_string(", "+rtoss(ptr[i].y),false); - write_string(", "+rtoss(ptr[i].z),false); + for (int i = 0; i < len; i++) { + if (i > 0) + write_string(", ", false); + write_string(rtoss(ptr[i].x), false); + write_string(", " + rtoss(ptr[i].y), false); + write_string(", " + rtoss(ptr[i].z), false); } - } break; case Variant::COLOR_ARRAY: { DVector data = p_property; int len = data.size(); DVector::Read r = data.read(); - const Color *ptr=r.ptr();; + const Color *ptr = r.ptr(); + ; write_tabs(); - for (int i=0;i0) - write_string(", ",false); - - write_string(rtoss(ptr[i].r),false); - write_string(", "+rtoss(ptr[i].g),false); - write_string(", "+rtoss(ptr[i].b),false); - write_string(", "+rtoss(ptr[i].a),false); + if (i > 0) + write_string(", ", false); + write_string(rtoss(ptr[i].r), false); + write_string(", " + rtoss(ptr[i].g), false); + write_string(", " + rtoss(ptr[i].b), false); + write_string(", " + rtoss(ptr[i].a), false); } } break; default: {} - } if (oneliner) f->store_8(' '); @@ -2813,26 +2718,22 @@ void ResourceFormatSaverXMLInstance::write_property(const String& p_name,const V f->store_8('\n'); if (r_ok) - *r_ok=true; - + *r_ok = true; } +void ResourceFormatSaverXMLInstance::_find_resources(const Variant &p_variant, bool p_main) { -void ResourceFormatSaverXMLInstance::_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 index = external_resources.size(); - external_resources[res]=index; + external_resources[res] = index; return; } @@ -2841,45 +2742,45 @@ void ResourceFormatSaverXMLInstance::_find_resources(const Variant& p_variant,bo List property_list; - res->get_property_list( &property_list ); + res->get_property_list(&property_list); property_list.sort(); - List::Element *I=property_list.front(); + List::Element *I = property_list.front(); - while(I) { + while (I) { - PropertyInfo pi=I->get(); + PropertyInfo pi = I->get(); - if (pi.usage&PROPERTY_USAGE_STORAGE || (bundle_resources && pi.usage&PROPERTY_USAGE_BUNDLE)) { + if (pi.usage & PROPERTY_USAGE_STORAGE || (bundle_resources && pi.usage & PROPERTY_USAGE_BUNDLE)) { - Variant v=res->get(I->get().name); + Variant v = res->get(I->get().name); _find_resources(v); } - I=I->next(); + I = I->next(); } - resource_set.insert( res ); //saved after, so the childs it needs are available when loaded + resource_set.insert(res); //saved after, so the childs it needs are available when loaded saved_resources.push_back(res); } break; case Variant::ARRAY: { - Array varray=p_variant; - int len=varray.size(); - for(int i=0;i keys; d.get_key_list(&keys); - for(List::Element *E=keys.front();E;E=E->next()) { + for (List::Element *E = keys.front(); E; E = E->next()) { Variant v = d[E->get()]; _find_resources(v); @@ -2887,57 +2788,54 @@ void ResourceFormatSaverXMLInstance::_find_resources(const Variant& p_variant,bo } break; default: {} } - } - - -Error ResourceFormatSaverXMLInstance::save(const String &p_path,const RES& p_resource,uint32_t p_flags) { +Error ResourceFormatSaverXMLInstance::save(const String &p_path, const RES &p_resource, uint32_t p_flags) { Error err; - f = FileAccess::open(p_path, FileAccess::WRITE,&err); - ERR_FAIL_COND_V( err, ERR_CANT_OPEN ); + f = FileAccess::open(p_path, FileAccess::WRITE, &err); + ERR_FAIL_COND_V(err, ERR_CANT_OPEN); FileAccessRef _fref(f); local_path = Globals::get_singleton()->localize_path(p_path); - 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; - 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; + takeover_paths = p_flags & ResourceSaver::FLAG_REPLACE_SUBRESOURCE_PATHS; if (!p_path.begins_with("res://")) { - takeover_paths=false; + takeover_paths = false; } - depth=0; + depth = 0; // save resources - _find_resources(p_resource,true); + _find_resources(p_resource, true); - ERR_FAIL_COND_V(err!=OK,err); + ERR_FAIL_COND_V(err != OK, err); - write_string("",false); //no escape - write_string("\n",false); - enter_tag("resource_file","type=\""+p_resource->get_type()+"\" subresource_count=\""+itos(saved_resources.size()+external_resources.size())+"\" version=\""+itos(VERSION_MAJOR)+"."+itos(VERSION_MINOR)+"\" version_name=\""+VERSION_FULL_NAME+"\""); - write_string("\n",false); + write_string("", false); //no escape + write_string("\n", false); + enter_tag("resource_file", "type=\"" + p_resource->get_type() + "\" subresource_count=\"" + itos(saved_resources.size() + external_resources.size()) + "\" version=\"" + itos(VERSION_MAJOR) + "." + itos(VERSION_MINOR) + "\" version_name=\"" + VERSION_FULL_NAME + "\""); + write_string("\n", false); - for(Map::Element *E=external_resources.front();E;E=E->next()) { + for (Map::Element *E = external_resources.front(); E; E = E->next()) { write_tabs(); String p = E->key()->get_path(); - enter_tag("ext_resource","path=\""+p+"\" type=\""+E->key()->get_save_type()+"\" index=\""+itos(E->get())+"\""); //bundled + enter_tag("ext_resource", "path=\"" + p + "\" type=\"" + E->key()->get_save_type() + "\" index=\"" + itos(E->get()) + "\""); //bundled exit_tag("ext_resource"); //bundled - write_string("\n",false); + write_string("\n", false); } Set used_indices; - for(List::Element *E=saved_resources.front();E;E=E->next()) { + for (List::Element *E = saved_resources.front(); E; E = E->next()) { RES res = E->get(); - if (E->next() && (res->get_path()=="" || res->get_path().find("::") != -1 )) { + if (E->next() && (res->get_path() == "" || res->get_path().find("::") != -1)) { - if (res->get_subindex()!=0) { + if (res->get_subindex() != 0) { if (used_indices.has(res->get_subindex())) { res->set_subindex(0); //repeated } else { @@ -2947,24 +2845,24 @@ Error ResourceFormatSaverXMLInstance::save(const String &p_path,const RES& p_res } } - for(List::Element *E=saved_resources.front();E;E=E->next()) { + for (List::Element *E = saved_resources.front(); E; E = E->next()) { RES res = E->get(); ERR_CONTINUE(!resource_set.has(res)); - bool main = (E->next()==NULL); + bool main = (E->next() == NULL); write_tabs(); if (main) - enter_tag("main_resource",""); //bundled - else if (res->get_path().length() && res->get_path().find("::") == -1 ) - enter_tag("resource","type=\""+res->get_type()+"\" path=\""+res->get_path()+"\""); //bundled + enter_tag("main_resource", ""); //bundled + else if (res->get_path().length() && res->get_path().find("::") == -1) + enter_tag("resource", "type=\"" + res->get_type() + "\" path=\"" + res->get_path() + "\""); //bundled else { - if (res->get_subindex()==0) { - int new_subindex=1; + if (res->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; } res->set_subindex(new_subindex); @@ -2972,52 +2870,45 @@ Error ResourceFormatSaverXMLInstance::save(const String &p_path,const RES& p_res } int idx = res->get_subindex(); - enter_tag("resource","type=\""+res->get_type()+"\" path=\"local://"+itos(idx)+"\""); + enter_tag("resource", "type=\"" + res->get_type() + "\" path=\"local://" + itos(idx) + "\""); if (takeover_paths) { - res->set_path(p_path+"::"+itos(idx),true); + res->set_path(p_path + "::" + itos(idx), true); } - } - write_string("\n",false); - + write_string("\n", false); List property_list; res->get_property_list(&property_list); -// property_list.sort(); - for(List::Element *PE = property_list.front();PE;PE=PE->next()) { - + // property_list.sort(); + for (List::Element *PE = property_list.front(); PE; PE = PE->next()) { if (skip_editor && PE->get().name.begins_with("__editor")) continue; - if (PE->get().usage&PROPERTY_USAGE_STORAGE || (bundle_resources && PE->get().usage&PROPERTY_USAGE_BUNDLE)) { + if (PE->get().usage & PROPERTY_USAGE_STORAGE || (bundle_resources && PE->get().usage & PROPERTY_USAGE_BUNDLE)) { String name = PE->get().name; Variant value = res->get(name); - - if ((PE->get().usage&PROPERTY_USAGE_STORE_IF_NONZERO && value.is_zero())||(PE->get().usage&PROPERTY_USAGE_STORE_IF_NONONE && value.is_one()) ) + if ((PE->get().usage & PROPERTY_USAGE_STORE_IF_NONZERO && value.is_zero()) || (PE->get().usage & PROPERTY_USAGE_STORE_IF_NONONE && value.is_one())) continue; - - write_property(name,value); + write_property(name, value); } - - } - write_string("\n",false); + write_string("\n", false); write_tabs(-1); if (main) exit_tag("main_resource"); else exit_tag("resource"); - write_string("\n",false); + write_string("\n", false); } exit_tag("resource_file"); - 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; } @@ -3028,34 +2919,28 @@ Error ResourceFormatSaverXMLInstance::save(const String &p_path,const RES& p_res return OK; } - - -Error ResourceFormatSaverXML::save(const String &p_path,const RES& p_resource,uint32_t p_flags) { +Error ResourceFormatSaverXML::save(const String &p_path, const RES &p_resource, uint32_t p_flags) { ResourceFormatSaverXMLInstance saver; - return saver.save(p_path,p_resource,p_flags); - + return saver.save(p_path, p_resource, p_flags); } -bool ResourceFormatSaverXML::recognize(const RES& p_resource) const { - +bool ResourceFormatSaverXML::recognize(const RES &p_resource) const { return true; // all recognized! } -void ResourceFormatSaverXML::get_recognized_extensions(const RES& p_resource,List *p_extensions) const { - +void ResourceFormatSaverXML::get_recognized_extensions(const RES &p_resource, List *p_extensions) const { //here comes the sun, lalalala String base = p_resource->get_base_extension().to_lower(); p_extensions->push_back("xml"); - if (base!="res") { + if (base != "res") { - p_extensions->push_back("x"+base); + p_extensions->push_back("x" + base); } - } -ResourceFormatSaverXML* ResourceFormatSaverXML::singleton=NULL; +ResourceFormatSaverXML *ResourceFormatSaverXML::singleton = NULL; ResourceFormatSaverXML::ResourceFormatSaverXML() { - singleton=this; + singleton = this; } diff --git a/core/io/resource_format_xml.h b/core/io/resource_format_xml.h index 5923817b6e8..482c954bc3f 100644 --- a/core/io/resource_format_xml.h +++ b/core/io/resource_format_xml.h @@ -33,8 +33,6 @@ #include "io/resource_saver.h" #include "os/file_access.h" - - class ResourceInteractiveLoaderXML : public ResourceInteractiveLoader { String local_path; @@ -45,22 +43,19 @@ class ResourceInteractiveLoaderXML : public ResourceInteractiveLoader { struct Tag { String name; - HashMap args; - + HashMap args; }; - _FORCE_INLINE_ Error _parse_array_element(Vector &buff,bool p_number_only,FileAccess *f,bool *end); - + _FORCE_INLINE_ Error _parse_array_element(Vector &buff, bool p_number_only, FileAccess *f, bool *end); struct ExtResource { String path; String type; }; + Map remaps; - Map remaps; - - Map ext_resources; + Map ext_resources; int resources_total; int resource_current; @@ -70,24 +65,23 @@ class ResourceInteractiveLoaderXML : public ResourceInteractiveLoader { uint8_t get_char() const; int get_current_line() const; -friend class ResourceFormatLoaderXML; + friend class ResourceFormatLoaderXML; List tag_stack; List resource_cache; - Tag* parse_tag(bool* r_exit=NULL,bool p_printerr=true,List *r_order=NULL); - Error close_tag(const String& p_name); - _FORCE_INLINE_ void unquote(String& p_str); + Tag *parse_tag(bool *r_exit = NULL, bool p_printerr = true, List *r_order = NULL); + Error close_tag(const String &p_name); + _FORCE_INLINE_ void unquote(String &p_str); Error goto_end_of_tag(); Error parse_property_data(String &r_data); - Error parse_property(Variant& r_v, String &r_name,bool p_for_export_data=false); + Error parse_property(Variant &r_v, String &r_name, bool p_for_export_data = false); Error error; RES resource; public: - - virtual void set_local_path(const String& p_local_path); + virtual void set_local_path(const String &p_local_path); virtual Ref get_resource(); virtual Error poll(); virtual int get_stage() const; @@ -96,41 +90,34 @@ public: void open(FileAccess *p_f); String recognize(FileAccess *p_f); void get_dependencies(FileAccess *p_f, List *p_dependencies, bool p_add_types); - Error rename_dependencies(FileAccess *p_f, const String &p_path,const Map& p_map); + Error rename_dependencies(FileAccess *p_f, const String &p_path, const Map &p_map); - Error get_export_data(FileAccess *p_f,ExportData& r_export_data); + Error get_export_data(FileAccess *p_f, ExportData &r_export_data); ~ResourceInteractiveLoaderXML(); - }; class ResourceFormatLoaderXML : public ResourceFormatLoader { public: - static ResourceFormatLoaderXML *singleton; - virtual Ref load_interactive(const String &p_path,Error *r_error=NULL); - virtual void get_recognized_extensions_for_type(const String& p_type,List *p_extensions) const; + virtual Ref load_interactive(const String &p_path, Error *r_error = NULL); + virtual void get_recognized_extensions_for_type(const String &p_type, List *p_extensions) const; virtual void get_recognized_extensions(List *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 *p_dependencies, bool p_add_types=false); - virtual Error rename_dependencies(const String &p_path,const Map& p_map); - virtual Error get_export_data(const String& p_path,ExportData& r_export_data); - - ResourceFormatLoaderXML() { singleton=this; } + virtual void get_dependencies(const String &p_path, List *p_dependencies, bool p_add_types = false); + virtual Error rename_dependencies(const String &p_path, const Map &p_map); + virtual Error get_export_data(const String &p_path, ExportData &r_export_data); + ResourceFormatLoaderXML() { singleton = this; } }; - //////////////////////////////////////////////////////////////////////////////////////////// - -class ResourceFormatSaverXMLInstance { +class ResourceFormatSaverXMLInstance { String local_path; - - bool takeover_paths; bool relative_paths; bool bundle_resources; @@ -139,36 +126,30 @@ class ResourceFormatSaverXMLInstance { int depth; Set resource_set; List saved_resources; - Map external_resources; + Map external_resources; - void enter_tag(const char* p_tag,const String& p_args=String()); - void exit_tag(const char* p_tag); + void enter_tag(const char *p_tag, const String &p_args = String()); + void exit_tag(const char *p_tag); - void _find_resources(const Variant& p_variant,bool p_main=false); - void write_property(const String& p_name,const Variant& p_property,bool *r_ok=NULL); - - - void escape(String& p_str); - void write_tabs(int p_diff=0); - void write_string(String p_str,bool p_escape=true); + void _find_resources(const Variant &p_variant, bool p_main = false); + void write_property(const String &p_name, const Variant &p_property, bool *r_ok = NULL); + void escape(String &p_str); + void write_tabs(int p_diff = 0); + void write_string(String p_str, bool p_escape = true); public: - - Error save(const String &p_path,const RES& p_resource,uint32_t p_flags=0); - - + Error save(const String &p_path, const RES &p_resource, uint32_t p_flags = 0); }; class ResourceFormatSaverXML : public ResourceFormatSaver { public: - static ResourceFormatSaverXML* 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 *p_extensions) const; + static ResourceFormatSaverXML *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 *p_extensions) const; ResourceFormatSaverXML(); }; - #endif // RESOURCE_FORMAT_XML_H diff --git a/core/io/resource_loader.cpp b/core/io/resource_loader.cpp index 2fa3a996cf2..4f663eaa190 100644 --- a/core/io/resource_loader.cpp +++ b/core/io/resource_loader.cpp @@ -27,72 +27,69 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "resource_loader.h" -#include "print_string.h" #include "globals.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(const String& p_extension) const { - +bool ResourceFormatLoader::recognize(const String &p_extension) const { List extensions; get_recognized_extensions(&extensions); - for (List::Element *E=extensions.front();E;E=E->next()) { + for (List::Element *E = extensions.front(); E; E = E->next()) { - if (E->get().nocasecmp_to(p_extension.extension())==0) + if (E->get().nocasecmp_to(p_extension.extension()) == 0) return true; } return false; } -void ResourceFormatLoader::get_recognized_extensions_for_type(const String& p_type,List *p_extensions) const { +void ResourceFormatLoader::get_recognized_extensions_for_type(const String &p_type, List *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 *p_extensions) { +void ResourceLoader::get_recognized_extensions_for_type(const String &p_type, List *p_extensions) { - for (int i=0;iget_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() { - ObjectTypeDB::bind_method(_MD("get_resource"),&ResourceInteractiveLoader::get_resource); - ObjectTypeDB::bind_method(_MD("poll"),&ResourceInteractiveLoader::poll); - ObjectTypeDB::bind_method(_MD("wait"),&ResourceInteractiveLoader::wait); - ObjectTypeDB::bind_method(_MD("get_stage"),&ResourceInteractiveLoader::get_stage); - ObjectTypeDB::bind_method(_MD("get_stage_count"),&ResourceInteractiveLoader::get_stage_count); + ObjectTypeDB::bind_method(_MD("get_resource"), &ResourceInteractiveLoader::get_resource); + ObjectTypeDB::bind_method(_MD("poll"), &ResourceInteractiveLoader::poll); + ObjectTypeDB::bind_method(_MD("wait"), &ResourceInteractiveLoader::wait); + ObjectTypeDB::bind_method(_MD("get_stage"), &ResourceInteractiveLoader::get_stage); + ObjectTypeDB::bind_method(_MD("get_stage_count"), &ResourceInteractiveLoader::get_stage_count); } class ResourceInteractiveLoaderDefault : public ResourceInteractiveLoader { - OBJ_TYPE( ResourceInteractiveLoaderDefault, ResourceInteractiveLoader ); -public: + OBJ_TYPE(ResourceInteractiveLoaderDefault, ResourceInteractiveLoader); +public: Ref 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 get_resource() { return resource; } virtual Error poll() { return ERR_FILE_EOF; } virtual int get_stage() const { return 1; } @@ -101,98 +98,92 @@ public: ResourceInteractiveLoaderDefault() {} }; - - Ref ResourceFormatLoader::load_interactive(const String &p_path, Error *r_error) { //either this - Ref res = load(p_path,p_path,r_error); + Ref res = load(p_path, p_path, r_error); if (res.is_null()) return Ref(); - Ref ril = Ref( memnew( ResourceInteractiveLoaderDefault )); - ril->resource=res; + Ref ril = Ref(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 ril = load_interactive(p_path,r_error); + Ref 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 *p_dependencies, bool p_add_types) { +void ResourceFormatLoader::get_dependencies(const String &p_path, List *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 = Globals::get_singleton()->localize_path(p_path); - local_path=find_complete_path(local_path,p_type_hint); - ERR_FAIL_COND_V(local_path=="",RES()); + local_path = find_complete_path(local_path, p_type_hint); + 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)); } String remapped_path = PathRemap::get_singleton()->get_remap(local_path); if (OS::get_singleton()->is_stdout_verbose()) - print_line("load resource: "+remapped_path); + print_line("load resource: " + remapped_path); - String extension=remapped_path.extension(); - bool found=false; + String extension = remapped_path.extension(); + bool found = false; - for (int i=0;irecognize(extension)) continue; - if (p_type_hint!="" && !loader[i]->handles_type(p_type_hint)) + if (p_type_hint != "" && !loader[i]->handles_type(p_type_hint)) continue; - found=true; - RES res = loader[i]->load(remapped_path,local_path,r_error); + found = true; + RES res = loader[i]->load(remapped_path, local_path, r_error); if (res.is_null()) continue; if (!p_no_cache) @@ -211,46 +202,39 @@ 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 ResourceLoader::load_import_metadata(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 = Globals::get_singleton()->localize_path(p_path); - String extension=p_path.extension(); + String extension = p_path.extension(); Ref ret; - for (int i=0;irecognize(extension)) continue; - Error err = loader[i]->load_import_metadata(local_path,ret); - if (err==OK) + Error err = loader[i]->load_import_metadata(local_path, ret); + if (err == OK) break; } - return ret; - } - - -String ResourceLoader::find_complete_path(const String& p_path,const String& p_type) { +String ResourceLoader::find_complete_path(const String &p_path, const String &p_type) { //this is an old vestige when the engine saved files without extension. //remains here for compatibility with old projects and only because it //can be sometimes nice to open files using .* from a script and have it guess @@ -260,32 +244,30 @@ String ResourceLoader::find_complete_path(const String& p_path,const String& p_t if (local_path.ends_with("*")) { //find the extension for resource that ends with * - local_path = local_path.substr(0,local_path.length()-1); + local_path = local_path.substr(0, local_path.length() - 1); List extensions; - get_recognized_extensions_for_type(p_type,&extensions); + get_recognized_extensions_for_type(p_type, &extensions); List candidates; - for(List::Element *E=extensions.front();E;E=E->next()) { + for (List::Element *E = extensions.front(); E; E = E->next()) { - String path = local_path+E->get(); + String path = local_path + E->get(); if (PathRemap::get_singleton()->has_remap(path) || FileAccess::exists(path)) { candidates.push_back(path); } - } - - if (candidates.size()==0) { + if (candidates.size() == 0) { return ""; - } else if (candidates.size()==1 || p_type=="") { + } else if (candidates.size() == 1 || p_type == "") { return candidates.front()->get(); } else { - for(List::Element *E=candidates.front();E;E=E->next()) { + for (List::Element *E = candidates.front(); E; E = E->next()) { String rt = get_resource_type(E->get()); - if (ObjectTypeDB::is_type(rt,p_type)) { + if (ObjectTypeDB::is_type(rt, p_type)) { return E->get(); } } @@ -297,27 +279,24 @@ String ResourceLoader::find_complete_path(const String& p_path,const String& p_t return local_path; } -Ref ResourceLoader::load_interactive(const String &p_path,const String& p_type_hint,bool p_no_cache,Error *r_error) { - +Ref 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 = Globals::get_singleton()->localize_path(p_path); - local_path=find_complete_path(local_path,p_type_hint); - ERR_FAIL_COND_V(local_path=="",Ref()); - - + local_path = find_complete_path(local_path, p_type_hint); + ERR_FAIL_COND_V(local_path == "", Ref()); 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 res_cached = ResourceCache::get(local_path); Ref ril = Ref(memnew(ResourceInteractiveLoaderDefault)); @@ -331,17 +310,17 @@ Ref ResourceLoader::load_interactive(const String &p_ String remapped_path = PathRemap::get_singleton()->get_remap(local_path); - String extension=remapped_path.extension(); - bool found=false; + String extension = remapped_path.extension(); + bool found = false; - for (int i=0;irecognize(extension)) continue; - if (p_type_hint!="" && !loader[i]->handles_type(p_type_hint)) + if (p_type_hint != "" && !loader[i]->handles_type(p_type_hint)) continue; - found=true; - Ref ril = loader[i]->load_interactive(remapped_path,r_error); + found = true; + Ref ril = loader[i]->load_interactive(remapped_path, r_error); if (ril.is_null()) continue; if (!p_no_cache) @@ -351,150 +330,137 @@ Ref 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()); return Ref(); - } 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 *p_dependencies, bool p_add_types) { - +void ResourceLoader::get_dependencies(const String &p_path, List *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 = Globals::get_singleton()->localize_path(p_path); String remapped_path = PathRemap::get_singleton()->get_remap(local_path); - String extension=remapped_path.extension(); + String extension = remapped_path.extension(); - for (int i=0;irecognize(extension)) continue; //if (p_type_hint!="" && !loader[i]->handles_type(p_type_hint)) // continue; - loader[i]->get_dependencies(remapped_path,p_dependencies,p_add_types); - + loader[i]->get_dependencies(remapped_path, p_dependencies, p_add_types); } } -Error ResourceLoader::get_export_data(const String& p_path,ExportData& r_export_data) { - +Error ResourceLoader::get_export_data(const String &p_path, ExportData &r_export_data) { String local_path; if (p_path.is_rel_path()) - local_path="res://"+p_path; + local_path = "res://" + p_path; else local_path = Globals::get_singleton()->localize_path(p_path); String remapped_path = PathRemap::get_singleton()->get_remap(local_path); - String extension=remapped_path.extension(); + String extension = remapped_path.extension(); - for (int i=0;irecognize(extension)) continue; //if (p_type_hint!="" && !loader[i]->handles_type(p_type_hint)) // continue; - return loader[i]->get_export_data(p_path,r_export_data); - + return loader[i]->get_export_data(p_path, r_export_data); } return ERR_UNAVAILABLE; - } -Error ResourceLoader::rename_dependencies(const String &p_path,const Map& p_map) { - +Error ResourceLoader::rename_dependencies(const String &p_path, const Map &p_map) { String local_path; if (p_path.is_rel_path()) - local_path="res://"+p_path; + local_path = "res://" + p_path; else local_path = Globals::get_singleton()->localize_path(p_path); String remapped_path = PathRemap::get_singleton()->get_remap(local_path); - String extension=remapped_path.extension(); + String extension = remapped_path.extension(); - for (int i=0;irecognize(extension)) continue; //if (p_type_hint!="" && !loader[i]->handles_type(p_type_hint)) // continue; - return loader[i]->rename_dependencies(p_path,p_map); - + return loader[i]->rename_dependencies(p_path, p_map); } return OK; // ?? - } - -String ResourceLoader::guess_full_filename(const String &p_path,const String& p_type) { +String ResourceLoader::guess_full_filename(const String &p_path, const String &p_type) { String local_path; if (p_path.is_rel_path()) - local_path="res://"+p_path; + local_path = "res://" + p_path; else local_path = Globals::get_singleton()->localize_path(p_path); - return find_complete_path(local_path,p_type); - + return find_complete_path(local_path, p_type); } 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 = Globals::get_singleton()->localize_path(p_path); String remapped_path = PathRemap::get_singleton()->get_remap(local_path); - String extension=remapped_path.extension(); + String extension = remapped_path.extension(); - for (int i=0;iget_resource_type(local_path); - if (result!="") + if (result != "") return result; } return ""; - } -ResourceLoadErrorNotify ResourceLoader::err_notify=NULL; -void *ResourceLoader::err_notify_ud=NULL; +ResourceLoadErrorNotify ResourceLoader::err_notify = NULL; +void *ResourceLoader::err_notify_ud = NULL; -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; +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 14a7ee83dc9..012b22dd9fe 100644 --- a/core/io/resource_loader.h +++ b/core/io/resource_loader.h @@ -29,99 +29,102 @@ #ifndef RESOURCE_LOADER_H #define RESOURCE_LOADER_H -#include "resource.h" #include "export_data.h" +#include "resource.h" /** @author Juan Linietsky */ class ResourceInteractiveLoader : public Reference { - OBJ_TYPE(ResourceInteractiveLoader,Reference); + OBJ_TYPE(ResourceInteractiveLoader, Reference); + protected: - static void _bind_methods(); -public: - virtual void set_local_path(const String& p_local_path)=0; - virtual Ref 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 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 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 *p_extensions) const=0; - virtual void get_recognized_extensions_for_type(const String& p_type,List *p_extensions) const; - bool recognize(const String& p_extension) 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 *p_dependencies,bool p_add_types=false); - virtual Error load_import_metadata(const String &p_path, Ref& r_var) const { return ERR_UNAVAILABLE; } - virtual Error rename_dependencies(const String &p_path,const Map& p_map) { return OK; } - virtual Error get_export_data(const String& p_path,ExportData& r_export_data) { return ERR_UNAVAILABLE; } + virtual Ref 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 *p_extensions) const = 0; + virtual void get_recognized_extensions_for_type(const String &p_type, List *p_extensions) const; + bool recognize(const String &p_extension) 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 *p_dependencies, bool p_add_types = false); + virtual Error load_import_metadata(const String &p_path, Ref &r_var) const { return ERR_UNAVAILABLE; } + virtual Error rename_dependencies(const String &p_path, const Map &p_map) { return OK; } + virtual Error get_export_data(const String &p_path, ExportData &r_export_data) { return ERR_UNAVAILABLE; } 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; - static String find_complete_path(const String& p_path,const String& p_type); + static String find_complete_path(const String &p_path, const String &p_type); + public: - - - - static Ref 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 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 load_import_metadata(const String &p_path); - static void get_recognized_extensions_for_type(const String& p_type,List *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 *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 *p_dependencies,bool p_add_types=false); - static Error rename_dependencies(const String &p_path,const Map& p_map); + static void get_dependencies(const String &p_path, List *p_dependencies, bool p_add_types = false); + static Error rename_dependencies(const String &p_path, const Map &p_map); - static Error get_export_data(const String& p_path,ExportData& r_export_data); + static Error get_export_data(const String &p_path, ExportData &r_export_data); - static String guess_full_filename(const String &p_path,const String& p_type); + static String guess_full_filename(const String &p_path, const String &p_type); - static void set_timestamp_on_load(bool p_timestamp) { timestamp_on_load=p_timestamp; } + 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_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 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 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; } }; diff --git a/core/io/resource_saver.cpp b/core/io/resource_saver.cpp index 704603f9ff7..610e2142705 100644 --- a/core/io/resource_saver.cpp +++ b/core/io/resource_saver.cpp @@ -29,62 +29,61 @@ #include "resource_saver.h" #include "globals.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.extension(); - Error err=ERR_FILE_UNRECOGNIZED; + String extension = p_path.extension(); + Error err = ERR_FILE_UNRECOGNIZED; - for (int i=0;irecognize(p_resource)) continue; List 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::Element *E=extensions.front();E;E=E->next()) { + for (List::Element *E = extensions.front(); E; E = E->next()) { - if (E->get().nocasecmp_to(extension.extension())==0) - recognized=true; + if (E->get().nocasecmp_to(extension.extension()) == 0) + recognized = true; } if (!recognized) continue; - String old_path=p_resource->get_path(); + String old_path = p_resource->get_path(); - - String local_path=Globals::get_singleton()->localize_path(p_path); + String local_path = Globals::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 *p_extensions) { -void ResourceSaver::get_recognized_extensions(const RES& p_resource,List *p_extensions) { + for (int i = 0; i < saver_count; i++) { - - for (int i=0;iget_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 f00f0740904..b9bb2aafaef 100644 --- a/core/io/resource_saver.h +++ b/core/io/resource_saver.h @@ -35,27 +35,21 @@ @author Juan Linietsky */ - - - - - 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 *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 *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 *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 *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 d9ef6137c40..72e649526dd 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 DVector& p_data) { +Error StreamPeer::_put_data(const DVector &p_data) { int len = p_data.size(); - if (len==0) + if (len == 0) return OK; DVector::Read r = p_data.read(); - return put_data(&r[0],len); + return put_data(&r[0], len); } -Array StreamPeer::_put_partial_data(const DVector& p_data) { +Array StreamPeer::_put_partial_data(const DVector &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 DVector& p_data) { DVector::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; DVector 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(DVector()); @@ -76,12 +75,11 @@ Array StreamPeer::_get_data(int p_bytes) { } DVector::Write w = data.write(); - Error err = get_data(&w[0],p_bytes); + Error err = get_data(&w[0], p_bytes); w = DVector::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) { DVector 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(DVector()); @@ -99,12 +97,12 @@ Array StreamPeer::_get_partial_data(int p_bytes) { DVector::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 = DVector::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,298 +122,274 @@ 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) { - - CharString cs=p_string.utf8(); - put_data((const uint8_t*)cs.get_data(),cs.length()); +void StreamPeer::put_utf8_string(const String &p_string) { + CharString cs = p_string.utf8(); + 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 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 buf; - buf.resize(p_bytes+1); - get_data((uint8_t*)&buf[0],p_bytes); - buf[p_bytes]=0; + buf.resize(p_bytes + 1); + get_data((uint8_t *)&buf[0], p_bytes); + 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 buf; buf.resize(p_bytes); - get_data(buf.ptr(),p_bytes); + get_data(buf.ptr(), p_bytes); 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 var; var.resize(len); - get_data(var.ptr(),len); + get_data(var.ptr(), len); Variant ret; - decode_variant(ret,var.ptr(),len); + decode_variant(ret, var.ptr(), len); return ret; } - void StreamPeer::_bind_methods() { - ObjectTypeDB::bind_method(_MD("put_data","data"),&StreamPeer::_put_data); - ObjectTypeDB::bind_method(_MD("put_partial_data","data"),&StreamPeer::_put_partial_data); + ObjectTypeDB::bind_method(_MD("put_data", "data"), &StreamPeer::_put_data); + ObjectTypeDB::bind_method(_MD("put_partial_data", "data"), &StreamPeer::_put_partial_data); - ObjectTypeDB::bind_method(_MD("get_data","bytes"),&StreamPeer::_get_data); - ObjectTypeDB::bind_method(_MD("get_partial_data","bytes"),&StreamPeer::_get_partial_data); + ObjectTypeDB::bind_method(_MD("get_data", "bytes"), &StreamPeer::_get_data); + ObjectTypeDB::bind_method(_MD("get_partial_data", "bytes"), &StreamPeer::_get_partial_data); - ObjectTypeDB::bind_method(_MD("get_available_bytes"),&StreamPeer::get_available_bytes); + ObjectTypeDB::bind_method(_MD("get_available_bytes"), &StreamPeer::get_available_bytes); - ObjectTypeDB::bind_method(_MD("set_big_endian","enable"),&StreamPeer::set_big_endian); - ObjectTypeDB::bind_method(_MD("is_big_endian_enabled"),&StreamPeer::is_big_endian_enabled); + ObjectTypeDB::bind_method(_MD("set_big_endian", "enable"), &StreamPeer::set_big_endian); + ObjectTypeDB::bind_method(_MD("is_big_endian_enabled"), &StreamPeer::is_big_endian_enabled); - ObjectTypeDB::bind_method(_MD("put_8","val"),&StreamPeer::put_8); - ObjectTypeDB::bind_method(_MD("put_u8","val"),&StreamPeer::put_u8); - ObjectTypeDB::bind_method(_MD("put_16","val"),&StreamPeer::put_16); - ObjectTypeDB::bind_method(_MD("put_u16","val"),&StreamPeer::put_u16); - ObjectTypeDB::bind_method(_MD("put_32","val"),&StreamPeer::put_32); - ObjectTypeDB::bind_method(_MD("put_u32","val"),&StreamPeer::put_u32); - ObjectTypeDB::bind_method(_MD("put_64","val"),&StreamPeer::put_64); - ObjectTypeDB::bind_method(_MD("put_u64","val"),&StreamPeer::put_u64); - ObjectTypeDB::bind_method(_MD("put_float","val"),&StreamPeer::put_float); - ObjectTypeDB::bind_method(_MD("put_double","val"),&StreamPeer::put_double); - ObjectTypeDB::bind_method(_MD("put_utf8_string","val"),&StreamPeer::put_utf8_string); - ObjectTypeDB::bind_method(_MD("put_var","val:Variant"),&StreamPeer::put_var); + ObjectTypeDB::bind_method(_MD("put_8", "val"), &StreamPeer::put_8); + ObjectTypeDB::bind_method(_MD("put_u8", "val"), &StreamPeer::put_u8); + ObjectTypeDB::bind_method(_MD("put_16", "val"), &StreamPeer::put_16); + ObjectTypeDB::bind_method(_MD("put_u16", "val"), &StreamPeer::put_u16); + ObjectTypeDB::bind_method(_MD("put_32", "val"), &StreamPeer::put_32); + ObjectTypeDB::bind_method(_MD("put_u32", "val"), &StreamPeer::put_u32); + ObjectTypeDB::bind_method(_MD("put_64", "val"), &StreamPeer::put_64); + ObjectTypeDB::bind_method(_MD("put_u64", "val"), &StreamPeer::put_u64); + ObjectTypeDB::bind_method(_MD("put_float", "val"), &StreamPeer::put_float); + ObjectTypeDB::bind_method(_MD("put_double", "val"), &StreamPeer::put_double); + ObjectTypeDB::bind_method(_MD("put_utf8_string", "val"), &StreamPeer::put_utf8_string); + ObjectTypeDB::bind_method(_MD("put_var", "val:Variant"), &StreamPeer::put_var); - ObjectTypeDB::bind_method(_MD("get_8"),&StreamPeer::get_8); - ObjectTypeDB::bind_method(_MD("get_u8"),&StreamPeer::get_u8); - ObjectTypeDB::bind_method(_MD("get_16"),&StreamPeer::get_16); - ObjectTypeDB::bind_method(_MD("get_u16"),&StreamPeer::get_u16); - ObjectTypeDB::bind_method(_MD("get_32"),&StreamPeer::get_32); - ObjectTypeDB::bind_method(_MD("get_u32"),&StreamPeer::get_u32); - ObjectTypeDB::bind_method(_MD("get_64"),&StreamPeer::get_64); - ObjectTypeDB::bind_method(_MD("get_u64"),&StreamPeer::get_u64); - ObjectTypeDB::bind_method(_MD("get_float"),&StreamPeer::get_float); - ObjectTypeDB::bind_method(_MD("get_double"),&StreamPeer::get_double); - ObjectTypeDB::bind_method(_MD("get_string","bytes"),&StreamPeer::get_string); - ObjectTypeDB::bind_method(_MD("get_utf8_string","bytes"),&StreamPeer::get_utf8_string); - ObjectTypeDB::bind_method(_MD("get_var:Variant"),&StreamPeer::get_var); + ObjectTypeDB::bind_method(_MD("get_8"), &StreamPeer::get_8); + ObjectTypeDB::bind_method(_MD("get_u8"), &StreamPeer::get_u8); + ObjectTypeDB::bind_method(_MD("get_16"), &StreamPeer::get_16); + ObjectTypeDB::bind_method(_MD("get_u16"), &StreamPeer::get_u16); + ObjectTypeDB::bind_method(_MD("get_32"), &StreamPeer::get_32); + ObjectTypeDB::bind_method(_MD("get_u32"), &StreamPeer::get_u32); + ObjectTypeDB::bind_method(_MD("get_64"), &StreamPeer::get_64); + ObjectTypeDB::bind_method(_MD("get_u64"), &StreamPeer::get_u64); + ObjectTypeDB::bind_method(_MD("get_float"), &StreamPeer::get_float); + ObjectTypeDB::bind_method(_MD("get_double"), &StreamPeer::get_double); + ObjectTypeDB::bind_method(_MD("get_string", "bytes"), &StreamPeer::get_string); + ObjectTypeDB::bind_method(_MD("get_utf8_string", "bytes"), &StreamPeer::get_utf8_string); + ObjectTypeDB::bind_method(_MD("get_var:Variant"), &StreamPeer::get_var); } diff --git a/core/io/stream_peer.h b/core/io/stream_peer.h index 264c5c795e6..ac66813e161 100644 --- a/core/io/stream_peer.h +++ b/core/io/stream_peer.h @@ -32,14 +32,15 @@ #include "reference.h" class StreamPeer : public Reference { - OBJ_TYPE( StreamPeer, Reference ); + OBJ_TYPE(StreamPeer, Reference); OBJ_CATEGORY("Networking"); + protected: static void _bind_methods(); //bind helpers - Error _put_data(const DVector& p_data); - Array _put_partial_data(const DVector& p_data); + Error _put_data(const DVector &p_data); + Array _put_partial_data(const DVector &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,9 +86,7 @@ public: String get_utf8_string(int p_bytes); Variant get_var(); - - - StreamPeer() { big_endian=false; } + StreamPeer() { big_endian = false; } }; #endif // STREAM_PEER_H diff --git a/core/io/stream_peer_ssl.cpp b/core/io/stream_peer_ssl.cpp index a9367915611..68df54e13e5 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 ByteArray& p_memory) { +void StreamPeerSSL::load_certs_from_memory(const ByteArray &p_memory) { if (load_certs_func) load_certs_func(p_memory); } @@ -56,18 +50,15 @@ bool StreamPeerSSL::is_available() { void StreamPeerSSL::_bind_methods() { - - ObjectTypeDB::bind_method(_MD("accept:Error","stream:StreamPeer"),&StreamPeerSSL::accept); - ObjectTypeDB::bind_method(_MD("connect:Error","stream:StreamPeer","validate_certs","for_hostname"),&StreamPeerSSL::connect,DEFVAL(false),DEFVAL(String())); - ObjectTypeDB::bind_method(_MD("get_status"),&StreamPeerSSL::get_status); - ObjectTypeDB::bind_method(_MD("disconnect"),&StreamPeerSSL::disconnect); - BIND_CONSTANT( STATUS_DISCONNECTED ); - BIND_CONSTANT( STATUS_CONNECTED ); - BIND_CONSTANT( STATUS_ERROR_NO_CERTIFICATE ); - BIND_CONSTANT( STATUS_ERROR_HOSTNAME_MISMATCH ); - + ObjectTypeDB::bind_method(_MD("accept:Error", "stream:StreamPeer"), &StreamPeerSSL::accept); + ObjectTypeDB::bind_method(_MD("connect:Error", "stream:StreamPeer", "validate_certs", "for_hostname"), &StreamPeerSSL::connect, DEFVAL(false), DEFVAL(String())); + ObjectTypeDB::bind_method(_MD("get_status"), &StreamPeerSSL::get_status); + ObjectTypeDB::bind_method(_MD("disconnect"), &StreamPeerSSL::disconnect); + 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 2e9ba526444..baa37d1e9ce 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 { - OBJ_TYPE(StreamPeerSSL,StreamPeer); -public: + OBJ_TYPE(StreamPeerSSL, StreamPeer); + +public: + typedef void (*LoadCertsFromMemory)(const ByteArray &p_certs); - typedef void (*LoadCertsFromMemory)(const ByteArray& 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(Ref p_base)=0; - virtual Error connect(Ref p_base,bool p_validate_certs=false,const String& p_for_hostname=String())=0; - virtual Status get_status() const=0; + virtual Error accept(Ref p_base) = 0; + virtual Error connect(Ref p_base, bool p_validate_certs = false, const String &p_for_hostname = String()) = 0; + virtual Status get_status() const = 0; - virtual void disconnect()=0; + virtual void disconnect() = 0; - static StreamPeerSSL* create(); + static StreamPeerSSL *create(); - static void load_certs_from_memory(const ByteArray& p_memory); + static void load_certs_from_memory(const ByteArray &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 52cc11a4a47..753d66734b1 100644 --- a/core/io/stream_peer_tcp.cpp +++ b/core/io/stream_peer_tcp.cpp @@ -28,20 +28,20 @@ /*************************************************************************/ #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_type); - if (ip==IP_Address()) + ip = IP::get_singleton()->resolve_hostname(p_address, ip_type); + if (ip == IP_Address()) return ERR_CANT_RESOLVE; } - connect(ip,p_port); + connect(ip, p_port); return OK; } @@ -52,19 +52,18 @@ void StreamPeerTCP::set_ip_type(IP::Type p_type) { void StreamPeerTCP::_bind_methods() { - ObjectTypeDB::bind_method(_MD("set_ip_type","ip_type"),&StreamPeerTCP::set_ip_type); - ObjectTypeDB::bind_method(_MD("connect","host","port"),&StreamPeerTCP::_connect); - ObjectTypeDB::bind_method(_MD("is_connected"),&StreamPeerTCP::is_connected); - ObjectTypeDB::bind_method(_MD("get_status"),&StreamPeerTCP::get_status); - ObjectTypeDB::bind_method(_MD("get_connected_host"),&StreamPeerTCP::get_connected_host); - ObjectTypeDB::bind_method(_MD("get_connected_port"),&StreamPeerTCP::get_connected_port); - ObjectTypeDB::bind_method(_MD("disconnect"),&StreamPeerTCP::disconnect); - - BIND_CONSTANT( STATUS_NONE ); - BIND_CONSTANT( STATUS_CONNECTING ); - BIND_CONSTANT( STATUS_CONNECTED ); - BIND_CONSTANT( STATUS_ERROR ); + ObjectTypeDB::bind_method(_MD("set_ip_type", "ip_type"), &StreamPeerTCP::set_ip_type); + ObjectTypeDB::bind_method(_MD("connect", "host", "port"), &StreamPeerTCP::_connect); + ObjectTypeDB::bind_method(_MD("is_connected"), &StreamPeerTCP::is_connected); + ObjectTypeDB::bind_method(_MD("get_status"), &StreamPeerTCP::get_status); + ObjectTypeDB::bind_method(_MD("get_connected_host"), &StreamPeerTCP::get_connected_host); + ObjectTypeDB::bind_method(_MD("get_connected_port"), &StreamPeerTCP::get_connected_port); + ObjectTypeDB::bind_method(_MD("disconnect"), &StreamPeerTCP::disconnect); + BIND_CONSTANT(STATUS_NONE); + BIND_CONSTANT(STATUS_CONNECTING); + BIND_CONSTANT(STATUS_CONNECTED); + BIND_CONSTANT(STATUS_ERROR); } Ref StreamPeerTCP::create_ref() { @@ -74,7 +73,7 @@ Ref StreamPeerTCP::create_ref() { return Ref(_create()); } -StreamPeerTCP* StreamPeerTCP::create() { +StreamPeerTCP *StreamPeerTCP::create() { if (!_create) return NULL; @@ -86,7 +85,6 @@ StreamPeerTCP::StreamPeerTCP() { ip_type = IP::TYPE_ANY; } -StreamPeerTCP::~StreamPeerTCP() { +StreamPeerTCP::~StreamPeerTCP(){ }; - diff --git a/core/io/stream_peer_tcp.h b/core/io/stream_peer_tcp.h index abc5947fffe..a97f4293771 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 { - OBJ_TYPE( StreamPeerTCP, StreamPeer ); + OBJ_TYPE(StreamPeerTCP, StreamPeer); OBJ_CATEGORY("Networking"); public: - enum Status { STATUS_NONE, @@ -50,34 +49,32 @@ public: }; protected: - IP::Type ip_type; - 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 void set_ip_type(IP::Type p_type); - virtual Error connect(const IP_Address& p_host, uint16_t p_port)=0; + virtual Error connect(const IP_Address &p_host, uint16_t p_port) = 0; //read/write from streampeer - virtual bool is_connected() const=0; - virtual Status get_status() const=0; - virtual void disconnect()=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() const = 0; + virtual Status get_status() const = 0; + virtual void disconnect() = 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 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 431b17321bd..2b4206ba388 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::create_ref() { @@ -37,7 +37,7 @@ Ref TCP_Server::create_ref() { return Ref(_create()); } -TCP_Server* TCP_Server::create() { +TCP_Server *TCP_Server::create() { if (!_create) return NULL; @@ -47,11 +47,10 @@ TCP_Server* TCP_Server::create() { Error TCP_Server::_listen(uint16_t p_port, DVector p_accepted_hosts) { List hosts; - for(int i=0;i())); - ObjectTypeDB::bind_method(_MD("is_connection_available"),&TCP_Server::is_connection_available); - ObjectTypeDB::bind_method(_MD("take_connection"),&TCP_Server::take_connection); - ObjectTypeDB::bind_method(_MD("stop"),&TCP_Server::stop); - + ObjectTypeDB::bind_method(_MD("set_ip_type", "ip_type"), &TCP_Server::set_ip_type); + ObjectTypeDB::bind_method(_MD("listen", "port", "accepted_hosts"), &TCP_Server::_listen, DEFVAL(DVector())); + ObjectTypeDB::bind_method(_MD("is_connection_available"), &TCP_Server::is_connection_available); + ObjectTypeDB::bind_method(_MD("take_connection"), &TCP_Server::take_connection); + ObjectTypeDB::bind_method(_MD("stop"), &TCP_Server::stop); } - -TCP_Server::TCP_Server() -{ +TCP_Server::TCP_Server() { ip_type = IP::TYPE_ANY; } diff --git a/core/io/tcp_server.h b/core/io/tcp_server.h index 14153a3324d..481945b6db9 100644 --- a/core/io/tcp_server.h +++ b/core/io/tcp_server.h @@ -29,33 +29,33 @@ #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 { - OBJ_TYPE( TCP_Server, Reference ); -protected: + OBJ_TYPE(TCP_Server, Reference); +protected: IP::Type ip_type; - static TCP_Server* (*_create)(); + static TCP_Server *(*_create)(); //bind helper - Error _listen(uint16_t p_port, DVector p_accepted_hosts=DVector()); + Error _listen(uint16_t p_port, DVector p_accepted_hosts = DVector()); static void _bind_methods(); + public: - virtual void set_ip_type(IP::Type p_type); - virtual Error listen(uint16_t p_port, const List *p_accepted_hosts=NULL)=0; - virtual bool is_connection_available() const=0; - virtual Ref take_connection()=0; + virtual Error listen(uint16_t p_port, const List *p_accepted_hosts = NULL) = 0; + virtual bool is_connection_available() const = 0; + virtual Ref take_connection() = 0; - virtual void stop()=0; //stop listening + virtual void stop() = 0; //stop listening static Ref 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 8c4c1c8180d..731a056e34f 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 = Ref( memnew( Translation )); + Ref translation = Ref(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;iclose(); 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 configs = config.split("\n"); - for(int i=0;iset_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; + *r_error = ERR_CANT_OPEN; - FileAccess *f=FileAccess::open(p_path,FileAccess::READ); - ERR_FAIL_COND_V(!f,RES()); - - - 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 *p_extensions) const{ +void TranslationLoaderPO::get_recognized_extensions(List *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.extension().to_lower()=="po") + if (p_path.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 127c8dafabf..fe0440cb2ad 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 *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 9e194d10538..a93e3b2cf17 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 '' && - (*(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() { - ObjectTypeDB::bind_method(_MD("read"),&XMLParser::read); - ObjectTypeDB::bind_method(_MD("get_node_type"),&XMLParser::get_node_type); - ObjectTypeDB::bind_method(_MD("get_node_name"),&XMLParser::get_node_name); - ObjectTypeDB::bind_method(_MD("get_node_data"),&XMLParser::get_node_data); - ObjectTypeDB::bind_method(_MD("get_node_offset"),&XMLParser::get_node_offset); - ObjectTypeDB::bind_method(_MD("get_attribute_count"),&XMLParser::get_attribute_count); - ObjectTypeDB::bind_method(_MD("get_attribute_name","idx"),&XMLParser::get_attribute_name); - ObjectTypeDB::bind_method(_MD("get_attribute_value","idx"),(String (XMLParser::*)(int) const) &XMLParser::get_attribute_value); - ObjectTypeDB::bind_method(_MD("has_attribute","name"),&XMLParser::has_attribute); - ObjectTypeDB::bind_method(_MD("get_named_attribute_value","name"), (String (XMLParser::*)(const String&) const) &XMLParser::get_attribute_value); - ObjectTypeDB::bind_method(_MD("get_named_attribute_value_safe","name"), &XMLParser::get_attribute_value_safe); - ObjectTypeDB::bind_method(_MD("is_empty"),&XMLParser::is_empty); - ObjectTypeDB::bind_method(_MD("get_current_line"),&XMLParser::get_current_line); - ObjectTypeDB::bind_method(_MD("skip_section"),&XMLParser::skip_section); - ObjectTypeDB::bind_method(_MD("seek","pos"),&XMLParser::seek); - ObjectTypeDB::bind_method(_MD("open","file"),&XMLParser::open); - ObjectTypeDB::bind_method(_MD("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 ); + ObjectTypeDB::bind_method(_MD("read"), &XMLParser::read); + ObjectTypeDB::bind_method(_MD("get_node_type"), &XMLParser::get_node_type); + ObjectTypeDB::bind_method(_MD("get_node_name"), &XMLParser::get_node_name); + ObjectTypeDB::bind_method(_MD("get_node_data"), &XMLParser::get_node_data); + ObjectTypeDB::bind_method(_MD("get_node_offset"), &XMLParser::get_node_offset); + ObjectTypeDB::bind_method(_MD("get_attribute_count"), &XMLParser::get_attribute_count); + ObjectTypeDB::bind_method(_MD("get_attribute_name", "idx"), &XMLParser::get_attribute_name); + ObjectTypeDB::bind_method(_MD("get_attribute_value", "idx"), (String(XMLParser::*)(int) const) & XMLParser::get_attribute_value); + ObjectTypeDB::bind_method(_MD("has_attribute", "name"), &XMLParser::has_attribute); + ObjectTypeDB::bind_method(_MD("get_named_attribute_value", "name"), (String(XMLParser::*)(const String &) const) & XMLParser::get_attribute_value); + ObjectTypeDB::bind_method(_MD("get_named_attribute_value_safe", "name"), &XMLParser::get_attribute_value_safe); + ObjectTypeDB::bind_method(_MD("is_empty"), &XMLParser::is_empty); + ObjectTypeDB::bind_method(_MD("get_current_line"), &XMLParser::get_current_line); + ObjectTypeDB::bind_method(_MD("skip_section"), &XMLParser::skip_section); + ObjectTypeDB::bind_method(_MD("seek", "pos"), &XMLParser::seek); + ObjectTypeDB::bind_method(_MD("open", "file"), &XMLParser::open); + ObjectTypeDB::bind_method(_MD("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& p_buffer) { +Error XMLParser::open_buffer(const Vector &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("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 e1f059bf8c6..ad13360f966 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 { - OBJ_TYPE( XMLParser, Reference ); + OBJ_TYPE(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 special_characters; String node_name; bool node_empty; @@ -81,8 +81,8 @@ private: Vector 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& p_buffer); + Error open(const String &p_path); + Error open_buffer(const Vector &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 c994593518a..4da9fc9c8db 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 diff --git a/core/list.h b/core/list.h index c464af7475f..69245803806 100644 --- a/core/list.h +++ b/core/list.h @@ -40,34 +40,33 @@ * from the iterator. */ -template +template class List { struct _Data; + public: - - class Element { private: - friend class List; + friend class List; T value; - Element* next_ptr; - Element* prev_ptr; + Element *next_ptr; + Element *prev_ptr; _Data *data; - public: + public: /** * Get NEXT Element iterator, for constant lists. */ - _FORCE_INLINE_ const Element* next() const { + _FORCE_INLINE_ const Element *next() const { return next_ptr; }; /** * Get NEXT Element iterator, */ - _FORCE_INLINE_ Element* next() { + _FORCE_INLINE_ Element *next() { return next_ptr; }; @@ -75,14 +74,14 @@ public: /** * Get PREV Element iterator, for constant lists. */ - _FORCE_INLINE_ const Element* prev() const { + _FORCE_INLINE_ const Element *prev() const { return prev_ptr; }; /** * Get PREV Element iterator, */ - _FORCE_INLINE_ Element* prev() { + _FORCE_INLINE_ Element *prev() { return prev_ptr; }; @@ -90,47 +89,47 @@ public: /** * * operator, for using as *iterator, when iterators are defined on stack. */ - _FORCE_INLINE_ const T& operator *() const { + _FORCE_INLINE_ const T &operator*() const { return value; }; /** * operator->, for using as iterator->, when iterators are defined on stack, for constant lists. */ - _FORCE_INLINE_ const T* operator->() const { + _FORCE_INLINE_ const T *operator->() const { return &value; }; /** * * operator, for using as *iterator, when iterators are defined on stack, */ - _FORCE_INLINE_ T& operator *() { + _FORCE_INLINE_ T &operator*() { return value; }; /** * operator->, for using as iterator->, when iterators are defined on stack, for constant lists. */ - _FORCE_INLINE_ T* operator->() { + _FORCE_INLINE_ T *operator->() { return &value; }; /** * get the value stored in this element. */ - _FORCE_INLINE_ T& get() { + _FORCE_INLINE_ T &get() { return value; }; /** * get the value stored in this element, for constant lists */ - _FORCE_INLINE_ const T& get() const { + _FORCE_INLINE_ const T &get() const { return value; }; /** * set the value stored in this element. */ - _FORCE_INLINE_ void set(const T& p_value) { - value = (T&)p_value; - }; + _FORCE_INLINE_ void set(const T &p_value) { + value = (T &)p_value; + }; void erase() { @@ -140,38 +139,36 @@ public: _FORCE_INLINE_ Element() { next_ptr = 0; prev_ptr = 0; - data=NULL; + data = NULL; }; }; private: - struct _Data { - Element* first; - Element* last; + Element *first; + Element *last; int size_cache; + bool erase(const Element *p_I) { - bool erase(const Element* p_I) { + ERR_FAIL_COND_V(!p_I, false); + ERR_FAIL_COND_V(p_I->data != this, false); - ERR_FAIL_COND_V(!p_I,false); - ERR_FAIL_COND_V(p_I->data!=this,false); - - if (first==p_I) { - first=p_I->next_ptr; + if (first == p_I) { + first = p_I->next_ptr; }; - if (last==p_I) - last=p_I->prev_ptr; + if (last == p_I) + last = p_I->prev_ptr; if (p_I->prev_ptr) - p_I->prev_ptr->next_ptr=p_I->next_ptr; + p_I->prev_ptr->next_ptr = p_I->next_ptr; if (p_I->next_ptr) - p_I->next_ptr->prev_ptr=p_I->prev_ptr; + p_I->next_ptr->prev_ptr = p_I->prev_ptr; - memdelete_allocator( const_cast(p_I) ); + memdelete_allocator(const_cast(p_I)); size_cache--; return true; @@ -180,69 +177,67 @@ private: _Data *_data; - public: - /** * return an const iterator to the begining of the list. */ - _FORCE_INLINE_ const Element* front() const { + _FORCE_INLINE_ const Element *front() const { - return _data?_data->first:0; + return _data ? _data->first : 0; }; /** * return an iterator to the begining of the list. */ - _FORCE_INLINE_ Element* front() { - return _data?_data->first:0; + _FORCE_INLINE_ Element *front() { + return _data ? _data->first : 0; }; /** * return an const iterator to the last member of the list. */ - _FORCE_INLINE_ const Element* back() const { + _FORCE_INLINE_ const Element *back() const { - return _data?_data->last:0; + return _data ? _data->last : 0; }; /** * return an iterator to the last member of the list. */ - _FORCE_INLINE_ Element* back() { + _FORCE_INLINE_ Element *back() { - return _data?_data->last:0; + return _data ? _data->last : 0; }; /** * store a new element at the end of the list */ - Element* push_back(const T& value) { + Element *push_back(const T &value) { if (!_data) { - _data=memnew_allocator(_Data,A); - _data->first=NULL; - _data->last=NULL; - _data->size_cache=0; + _data = memnew_allocator(_Data, A); + _data->first = NULL; + _data->last = NULL; + _data->size_cache = 0; } - Element* n = memnew_allocator(Element,A); - n->value = (T&)value; + Element *n = memnew_allocator(Element, A); + n->value = (T &)value; - n->prev_ptr=_data->last; - n->next_ptr=0; - n->data=_data; + n->prev_ptr = _data->last; + n->next_ptr = 0; + n->data = _data; if (_data->last) { - _data->last->next_ptr=n; + _data->last->next_ptr = n; } _data->last = n; if (!_data->first) - _data->first=n; + _data->first = n; _data->size_cache++; @@ -258,31 +253,31 @@ public: /** * store a new element at the begining of the list */ - Element* push_front(const T& value) { + Element *push_front(const T &value) { if (!_data) { - _data=memnew_allocator(_Data,A); - _data->first=NULL; - _data->last=NULL; - _data->size_cache=0; + _data = memnew_allocator(_Data, A); + _data->first = NULL; + _data->last = NULL; + _data->size_cache = 0; } - Element* n = memnew_allocator(Element,A); - n->value = (T&)value; + Element *n = memnew_allocator(Element, A); + n->value = (T &)value; n->prev_ptr = 0; n->next_ptr = _data->first; - n->data=_data; + n->data = _data; if (_data->first) { - _data->first->prev_ptr=n; + _data->first->prev_ptr = n; } _data->first = n; if (!_data->last) - _data->last=n; + _data->last = n; _data->size_cache++; @@ -298,10 +293,10 @@ public: /** * find an element in the list, */ - template - Element* find(const T_v& p_val) { + template + Element *find(const T_v &p_val) { - Element* it = front(); + Element *it = front(); while (it) { if (it->value == p_val) return it; it = it->next(); @@ -313,14 +308,14 @@ public: /** * erase an element in the list, by iterator pointing to it. Return true if it was found/erased. */ - bool erase(const Element* p_I) { + bool erase(const Element *p_I) { if (_data) { - bool ret = _data->erase(p_I); + bool ret = _data->erase(p_I); - if (_data->size_cache==0) { - memdelete_allocator<_Data,A>(_data); - _data=NULL; + if (_data->size_cache == 0) { + memdelete_allocator<_Data, A>(_data); + _data = NULL; } return ret; @@ -332,9 +327,9 @@ public: /** * erase the first element in the list, that contains value */ - bool erase(const T& value) { + bool erase(const T &value) { - Element* I = find(value); + Element *I = find(value); return erase(I); }; @@ -358,121 +353,115 @@ public: _FORCE_INLINE_ int size() const { - return _data?_data->size_cache:0; - + return _data ? _data->size_cache : 0; } - void swap(Element* p_A, Element *p_B) { + void swap(Element *p_A, Element *p_B) { ERR_FAIL_COND(!p_A || !p_B); - ERR_FAIL_COND(p_A->data!=_data); - ERR_FAIL_COND(p_B->data!=_data); + ERR_FAIL_COND(p_A->data != _data); + ERR_FAIL_COND(p_B->data != _data); - Element* A_prev=p_A->prev_ptr; - Element* A_next=p_A->next_ptr; + Element *A_prev = p_A->prev_ptr; + Element *A_next = p_A->next_ptr; - p_A->next_ptr=p_B->next_ptr; - p_A->prev_ptr=p_B->prev_ptr; + p_A->next_ptr = p_B->next_ptr; + p_A->prev_ptr = p_B->prev_ptr; - p_B->next_ptr=A_next; - p_B->prev_ptr=A_prev; + p_B->next_ptr = A_next; + p_B->prev_ptr = A_prev; if (p_A->prev_ptr) - p_A->prev_ptr->next_ptr=p_A; + p_A->prev_ptr->next_ptr = p_A; if (p_A->next_ptr) - p_A->next_ptr->prev_ptr=p_A; + p_A->next_ptr->prev_ptr = p_A; if (p_B->prev_ptr) - p_B->prev_ptr->next_ptr=p_B; + p_B->prev_ptr->next_ptr = p_B; if (p_B->next_ptr) - p_B->next_ptr->prev_ptr=p_B; - + p_B->next_ptr->prev_ptr = p_B; } /** * copy the list */ - void operator=(const List& p_list) { + void operator=(const List &p_list) { clear(); - const Element *it=p_list.front(); + const Element *it = p_list.front(); while (it) { - push_back( it->get() ); - it=it->next(); + push_back(it->get()); + it = it->next(); } - } - T& operator[](int p_index) { + T &operator[](int p_index) { - if (p_index<0 || p_index>=size()) { - T& aux=*((T*)0); //nullreturn - ERR_FAIL_COND_V(p_index<0 || p_index>=size(),aux); + if (p_index < 0 || p_index >= size()) { + T &aux = *((T *)0); //nullreturn + ERR_FAIL_COND_V(p_index < 0 || p_index >= size(), aux); } - Element *I=front(); - int c=0; - while(I) { + Element *I = front(); + int c = 0; + while (I) { - if (c==p_index) { + if (c == p_index) { return I->get(); } - I=I->next(); + I = I->next(); c++; } - ERR_FAIL_V( *((T*)0) ); // bug!! + ERR_FAIL_V(*((T *)0)); // bug!! } - const T& operator[](int p_index) const { + const T &operator[](int p_index) const { - if (p_index<0 || p_index>=size()) { - T& aux=*((T*)0); //nullreturn - ERR_FAIL_COND_V(p_index<0 || p_index>=size(),aux); + if (p_index < 0 || p_index >= size()) { + T &aux = *((T *)0); //nullreturn + ERR_FAIL_COND_V(p_index < 0 || p_index >= size(), aux); } - const Element *I=front(); - int c=0; - while(I) { + const Element *I = front(); + int c = 0; + while (I) { - if (c==p_index) { + if (c == p_index) { return I->get(); } - I=I->next(); + I = I->next(); c++; } - ERR_FAIL_V( *((T*)0) ); // bug! + ERR_FAIL_V(*((T *)0)); // bug! } + void move_to_back(Element *p_I) { - void move_to_back(Element* p_I) { - - ERR_FAIL_COND(p_I->data!=_data); + ERR_FAIL_COND(p_I->data != _data); if (!p_I->next_ptr) return; - if (_data->first==p_I) { - _data->first=p_I->next_ptr; + if (_data->first == p_I) { + _data->first = p_I->next_ptr; }; - if (_data->last==p_I) - _data->last=p_I->prev_ptr; + if (_data->last == p_I) + _data->last = p_I->prev_ptr; if (p_I->prev_ptr) - p_I->prev_ptr->next_ptr=p_I->next_ptr; + p_I->prev_ptr->next_ptr = p_I->next_ptr; if (p_I->next_ptr) - p_I->next_ptr->prev_ptr=p_I->prev_ptr; - - - _data->last->next_ptr=p_I; - p_I->prev_ptr=_data->last; - p_I->next_ptr=NULL; - _data->last=p_I; + p_I->next_ptr->prev_ptr = p_I->prev_ptr; + _data->last->next_ptr = p_I; + p_I->prev_ptr = _data->last; + p_I->next_ptr = NULL; + _data->last = p_I; } void invert() { @@ -480,52 +469,49 @@ public: int s = size() / 2; Element *F = front(); Element *B = back(); - for(int i=0;ivalue, B->value ); - F=F->next(); - B=B->prev(); + SWAP(F->value, B->value); + F = F->next(); + B = B->prev(); } } - void move_to_front(Element* p_I) { + void move_to_front(Element *p_I) { - ERR_FAIL_COND(p_I->data!=_data); + ERR_FAIL_COND(p_I->data != _data); if (!p_I->prev_ptr) return; - if (_data->first==p_I) { - _data->first=p_I->next_ptr; + if (_data->first == p_I) { + _data->first = p_I->next_ptr; }; - if (_data->last==p_I) - _data->last=p_I->prev_ptr; + if (_data->last == p_I) + _data->last = p_I->prev_ptr; if (p_I->prev_ptr) - p_I->prev_ptr->next_ptr=p_I->next_ptr; + p_I->prev_ptr->next_ptr = p_I->next_ptr; if (p_I->next_ptr) - p_I->next_ptr->prev_ptr=p_I->prev_ptr; - - _data->first->prev_ptr=p_I; - p_I->next_ptr=_data->first; - p_I->prev_ptr=NULL; - _data->first=p_I; + p_I->next_ptr->prev_ptr = p_I->prev_ptr; + _data->first->prev_ptr = p_I; + p_I->next_ptr = _data->first; + p_I->prev_ptr = NULL; + _data->first = p_I; } - void move_before(Element* value, Element* where) { + void move_before(Element *value, Element *where) { if (value->prev_ptr) { value->prev_ptr->next_ptr = value->next_ptr; - } - else { + } else { _data->first = value->next_ptr; } if (value->next_ptr) { value->next_ptr->prev_ptr = value->prev_ptr; - } - else { + } else { _data->last = value->prev_ptr; } @@ -553,138 +539,133 @@ public: void sort() { - sort_custom< Comparator >(); + sort_custom >(); } - template + template void sort_custom_inplace() { - if(size()<2) + if (size() < 2) return; - Element *from=front(); - Element *current=from; - Element *to=from; + Element *from = front(); + Element *current = from; + Element *to = from; - while(current) { + while (current) { - Element *next=current->next_ptr; + Element *next = current->next_ptr; //disconnect - current->next_ptr=NULL; + current->next_ptr = NULL; - if (from!=current) { + if (from != current) { - current->prev_ptr=NULL; - current->next_ptr=from; + current->prev_ptr = NULL; + current->next_ptr = from; - Element *find=from; + Element *find = from; C less; - while( find && less(find->value,current->value) ) { + while (find && less(find->value, current->value)) { - current->prev_ptr=find; - current->next_ptr=find->next_ptr; - find=find->next_ptr; + current->prev_ptr = find; + current->next_ptr = find->next_ptr; + find = find->next_ptr; } if (current->prev_ptr) - current->prev_ptr->next_ptr=current; + current->prev_ptr->next_ptr = current; else - from=current; + from = current; if (current->next_ptr) - current->next_ptr->prev_ptr=current; + current->next_ptr->prev_ptr = current; else - to=current; + to = current; } else { - current->prev_ptr=NULL; - current->next_ptr=NULL; - + current->prev_ptr = NULL; + current->next_ptr = NULL; } - current=next; + current = next; } - _data->first=from; - _data->last=to; + _data->first = from; + _data->last = to; } - template + template struct AuxiliaryComparator { C compare; - _FORCE_INLINE_ bool operator()(const Element *a,const Element* b) const { + _FORCE_INLINE_ bool operator()(const Element *a, const Element *b) const { - return compare(a->value,b->value); + return compare(a->value, b->value); } }; - template + template void sort_custom() { //this version uses auxiliary memory for speed. //if you don't want to use auxiliary memory, use the in_place version int s = size(); - if(s<2) + if (s < 2) return; + Element **aux_buffer = memnew_arr(Element *, s); - Element **aux_buffer = memnew_arr(Element*,s); + int idx = 0; + for (Element *E = front(); E; E = E->next_ptr) { - int idx=0; - for(Element *E=front();E;E=E->next_ptr) { - - aux_buffer[idx]=E; + aux_buffer[idx] = E; idx++; } - SortArray > sort; - sort.sort(aux_buffer,s); + SortArray > sort; + sort.sort(aux_buffer, s); - _data->first=aux_buffer[0]; - aux_buffer[0]->prev_ptr=NULL; - aux_buffer[0]->next_ptr=aux_buffer[1]; + _data->first = aux_buffer[0]; + aux_buffer[0]->prev_ptr = NULL; + aux_buffer[0]->next_ptr = aux_buffer[1]; - _data->last=aux_buffer[s-1]; - aux_buffer[s-1]->prev_ptr=aux_buffer[s-2]; - aux_buffer[s-1]->next_ptr=NULL; + _data->last = aux_buffer[s - 1]; + aux_buffer[s - 1]->prev_ptr = aux_buffer[s - 2]; + aux_buffer[s - 1]->next_ptr = NULL; - for(int i=1;iprev_ptr=aux_buffer[i-1]; - aux_buffer[i]->next_ptr=aux_buffer[i+1]; + for (int i = 1; i < s - 1; i++) { + aux_buffer[i]->prev_ptr = aux_buffer[i - 1]; + aux_buffer[i]->next_ptr = aux_buffer[i + 1]; } memdelete_arr(aux_buffer); } - /** * copy constructor for the list */ - List(const List& p_list) { + List(const List &p_list) { - _data=NULL; - const Element *it=p_list.front(); + _data = NULL; + const Element *it = p_list.front(); while (it) { - push_back( it->get() ); - it=it->next(); + push_back(it->get()); + it = it->next(); } - } List() { - _data=NULL; + _data = NULL; }; ~List() { clear(); if (_data) { ERR_FAIL_COND(_data->size_cache); - memdelete_allocator<_Data,A>(_data); + memdelete_allocator<_Data, A>(_data); } }; }; diff --git a/core/map.h b/core/map.h index 8c7cfe26e58..9686e23617a 100644 --- a/core/map.h +++ b/core/map.h @@ -37,7 +37,7 @@ // based on the very nice implementation of rb-trees by: // http://web.mit.edu/~emin/www/source_code/red_black_tree/index.html -template ,class A=DefaultAllocator> +template , class A = DefaultAllocator> class Map { enum Color { @@ -45,26 +45,25 @@ class Map { BLACK }; struct _Data; -public: +public: class Element { private: - friend class Map; + friend class Map; //Color color; int color; - Element* right; - Element* left; - Element* parent; - Element* _next; - Element* _prev; + Element *right; + Element *left; + Element *parent; + Element *_next; + Element *_prev; K _key; V _value; //_Data *data; public: - const Element *next() const { return _next; @@ -81,64 +80,62 @@ public: return _prev; } - const K& key() const { + const K &key() const { return _key; }; - V& value() { + V &value() { return _value; }; - const V& value() const { + const V &value() const { return _value; }; - V& get() { + V &get() { return _value; }; - const V& get() const { + const V &get() const { return _value; }; Element() { - color=RED; - right=NULL; - left=NULL; - parent=NULL; - _next=NULL; - _prev=NULL; + color = RED; + right = NULL; + left = NULL; + parent = NULL; + _next = NULL; + _prev = NULL; }; }; - private: - struct _Data { - Element* _root; - Element* _nil; + Element *_root; + Element *_nil; int size_cache; _FORCE_INLINE_ _Data() { #ifdef GLOBALNIL_DISABLED - _nil = memnew_allocator( Element, A ); - _nil->parent=_nil->left=_nil->right=_nil; - _nil->color=BLACK; + _nil = memnew_allocator(Element, A); + _nil->parent = _nil->left = _nil->right = _nil; + _nil->color = BLACK; #else - _nil=(Element*)&_GlobalNilClass::_nil; + _nil = (Element *)&_GlobalNilClass::_nil; #endif - _root=NULL; - size_cache=0; + _root = NULL; + size_cache = 0; } void _create_root() { - _root = memnew_allocator( Element,A ); - _root->parent=_root->left=_root->right=_nil; - _root->color=BLACK; + _root = memnew_allocator(Element, A); + _root->parent = _root->left = _root->right = _nil; + _root->color = BLACK; } void _free_root() { if (_root) { - memdelete_allocator(_root); - _root=NULL; + memdelete_allocator(_root); + _root = NULL; } } @@ -147,9 +144,9 @@ private: _free_root(); #ifdef GLOBALNIL_DISABLED - memdelete_allocator(_nil); + memdelete_allocator(_nil); #endif -// memdelete_allocator(_root); + // memdelete_allocator(_root); } }; @@ -157,58 +154,56 @@ private: inline void _set_color(Element *p_node, int p_color) { - ERR_FAIL_COND( p_node == _data._nil && p_color == RED ); - p_node->color=p_color; + ERR_FAIL_COND(p_node == _data._nil && p_color == RED); + p_node->color = p_color; } inline void _rotate_left(Element *p_node) { - Element *r=p_node->right; - p_node->right=r->left; - if (r->left != _data._nil ) - r->left->parent=p_node; - r->parent=p_node->parent; - if (p_node==p_node->parent->left) - p_node->parent->left=r; + Element *r = p_node->right; + p_node->right = r->left; + if (r->left != _data._nil) + r->left->parent = p_node; + r->parent = p_node->parent; + if (p_node == p_node->parent->left) + p_node->parent->left = r; else - p_node->parent->right=r; - - r->left=p_node; - p_node->parent=r; + p_node->parent->right = r; + r->left = p_node; + p_node->parent = r; } inline void _rotate_right(Element *p_node) { - Element *l=p_node->left; - p_node->left=l->right; + Element *l = p_node->left; + p_node->left = l->right; if (l->right != _data._nil) - l->right->parent=p_node; - l->parent=p_node->parent; - if (p_node==p_node->parent->right) - p_node->parent->right=l; + l->right->parent = p_node; + l->parent = p_node->parent; + if (p_node == p_node->parent->right) + p_node->parent->right = l; else - p_node->parent->left=l; - - l->right=p_node; - p_node->parent=l; + p_node->parent->left = l; + l->right = p_node; + p_node->parent = l; } - inline Element* _successor(Element *p_node) const { + inline Element *_successor(Element *p_node) const { - Element *node=p_node; + Element *node = p_node; if (node->right != _data._nil) { - node=node->right; - while(node->left != _data._nil) { /* returns the minium of the right subtree of node */ - node=node->left; + node = node->right; + while (node->left != _data._nil) { /* returns the minium of the right subtree of node */ + node = node->left; } return node; } else { - while(node == node->parent->right) { - node=node->parent; + while (node == node->parent->right) { + node = node->parent; } if (node->parent == _data._root) return NULL; @@ -216,419 +211,408 @@ private: } } - inline Element* _predecessor(Element *p_node) const { - Element *node=p_node; + inline Element *_predecessor(Element *p_node) const { + Element *node = p_node; if (node->left != _data._nil) { - node=node->left; - while(node->right != _data._nil) { /* returns the minium of the left subtree of node */ - node=node->right; + node = node->left; + while (node->right != _data._nil) { /* returns the minium of the left subtree of node */ + node = node->right; } return node; } else { - while(node == node->parent->left) { + while (node == node->parent->left) { if (node->parent == _data._root) return NULL; - node=node->parent; + node = node->parent; } return node->parent; } } - - Element *_find(const K& p_key) const { + Element *_find(const K &p_key) const { Element *node = _data._root->left; C less; - while(node!=_data._nil) { + while (node != _data._nil) { - if (less(p_key,node->_key)) - node=node->left; - else if (less(node->_key,p_key)) - node=node->right; + if (less(p_key, node->_key)) + node = node->left; + else if (less(node->_key, p_key)) + node = node->right; else break; // found } - return (node!=_data._nil)?node:NULL; + return (node != _data._nil) ? node : NULL; } - Element *_find_closest(const K& p_key) const { + Element *_find_closest(const K &p_key) const { Element *node = _data._root->left; Element *prev = NULL; C less; - while(node!=_data._nil) { - prev=node; + while (node != _data._nil) { + prev = node; - if (less(p_key,node->_key)) - node=node->left; - else if (less(node->_key,p_key)) - node=node->right; + if (less(p_key, node->_key)) + node = node->left; + else if (less(node->_key, p_key)) + node = node->right; else break; // found } - if (node==_data._nil) { - if (prev==NULL) + if (node == _data._nil) { + if (prev == NULL) return NULL; - if (less(p_key,prev->_key)) { + if (less(p_key, prev->_key)) { - prev=prev->_prev; + prev = prev->_prev; } return prev; } else return node; - } - Element *_insert(const K& p_key, bool& r_exists) { + Element *_insert(const K &p_key, bool &r_exists) { - Element *new_parent=_data._root; + Element *new_parent = _data._root; Element *node = _data._root->left; C less; - while (node!=_data._nil) { + while (node != _data._nil) { - new_parent=node; + new_parent = node; - if (less(p_key,node->_key)) - node=node->left; - else if (less(node->_key,p_key)) - node=node->right; + if (less(p_key, node->_key)) + node = node->left; + else if (less(node->_key, p_key)) + node = node->right; else { - r_exists=true; + r_exists = true; return node; } } - Element *new_node = memnew_allocator( Element, A ); + Element *new_node = memnew_allocator(Element, A); - - new_node->parent=new_parent; - new_node->right=_data._nil; - new_node->left=_data._nil; - new_node->_key=p_key; + new_node->parent = new_parent; + new_node->right = _data._nil; + new_node->left = _data._nil; + new_node->_key = p_key; //new_node->data=_data; - if (new_parent==_data._root || less(p_key,new_parent->_key)) { + if (new_parent == _data._root || less(p_key, new_parent->_key)) { - new_parent->left=new_node; + new_parent->left = new_node; } else { - new_parent->right=new_node; + new_parent->right = new_node; } - r_exists=false; + r_exists = false; - new_node->_next=_successor(new_node); - new_node->_prev=_predecessor(new_node); + new_node->_next = _successor(new_node); + new_node->_prev = _predecessor(new_node); if (new_node->_next) - new_node->_next->_prev=new_node; + new_node->_next->_prev = new_node; if (new_node->_prev) - new_node->_prev->_next=new_node; - + new_node->_prev->_next = new_node; return new_node; } - Element * _insert_rb(const K& p_key, const V& p_value) { + Element *_insert_rb(const K &p_key, const V &p_value) { - bool exists=false; - Element *new_node = _insert(p_key,exists); + bool exists = false; + Element *new_node = _insert(p_key, exists); if (new_node) { - new_node->_value=p_value; + new_node->_value = p_value; } if (exists) return new_node; - Element *node=new_node; + Element *node = new_node; _data.size_cache++; - while(node->parent->color==RED) { + while (node->parent->color == RED) { if (node->parent == node->parent->parent->left) { - Element *aux=node->parent->parent->right; + Element *aux = node->parent->parent->right; - if (aux->color==RED) { - _set_color(node->parent,BLACK); - _set_color(aux,BLACK); - _set_color(node->parent->parent,RED); - node=node->parent->parent; + if (aux->color == RED) { + _set_color(node->parent, BLACK); + _set_color(aux, BLACK); + _set_color(node->parent->parent, RED); + node = node->parent->parent; } else { if (node == node->parent->right) { - node=node->parent; + node = node->parent; _rotate_left(node); } - _set_color(node->parent,BLACK); - _set_color(node->parent->parent,RED); + _set_color(node->parent, BLACK); + _set_color(node->parent->parent, RED); _rotate_right(node->parent->parent); } } else { - Element *aux=node->parent->parent->left; + Element *aux = node->parent->parent->left; - if (aux->color==RED) { - _set_color(node->parent,BLACK); - _set_color(aux,BLACK); - _set_color(node->parent->parent,RED); - node=node->parent->parent; + if (aux->color == RED) { + _set_color(node->parent, BLACK); + _set_color(aux, BLACK); + _set_color(node->parent->parent, RED); + node = node->parent->parent; } else { if (node == node->parent->left) { - node=node->parent; + node = node->parent; _rotate_right(node); } - _set_color(node->parent,BLACK); - _set_color(node->parent->parent,RED); + _set_color(node->parent, BLACK); + _set_color(node->parent->parent, RED); _rotate_left(node->parent->parent); } } } - _set_color(_data._root->left,BLACK); + _set_color(_data._root->left, BLACK); return new_node; } void _erase_fix(Element *p_node) { Element *root = _data._root->left; - Element *node=p_node; + Element *node = p_node; - - while( (node->color==BLACK) && (root != node)) { + while ((node->color == BLACK) && (root != node)) { if (node == node->parent->left) { - Element *aux=node->parent->right; - if (aux->color==RED) { - _set_color(aux,BLACK); - _set_color(node->parent,RED); + Element *aux = node->parent->right; + if (aux->color == RED) { + _set_color(aux, BLACK); + _set_color(node->parent, RED); _rotate_left(node->parent); - aux=node->parent->right; + aux = node->parent->right; } - if ( (aux->right->color==BLACK) && (aux->left->color==BLACK) ) { - _set_color(aux,RED); - node=node->parent; + if ((aux->right->color == BLACK) && (aux->left->color == BLACK)) { + _set_color(aux, RED); + node = node->parent; } else { - if (aux->right->color==BLACK) { - _set_color(aux->left,BLACK); - _set_color(aux,RED); + if (aux->right->color == BLACK) { + _set_color(aux->left, BLACK); + _set_color(aux, RED); _rotate_right(aux); - aux=node->parent->right; + aux = node->parent->right; } - _set_color(aux,node->parent->color); - _set_color(node->parent,BLACK); - _set_color(aux->right,BLACK); + _set_color(aux, node->parent->color); + _set_color(node->parent, BLACK); + _set_color(aux->right, BLACK); _rotate_left(node->parent); - node=root; /* this is to exit while loop */ + node = root; /* this is to exit while loop */ } } else { /* the code below is has left and right switched from above */ - Element *aux=node->parent->left; - if (aux->color==RED) { - _set_color(aux,BLACK); - _set_color(node->parent,RED); + Element *aux = node->parent->left; + if (aux->color == RED) { + _set_color(aux, BLACK); + _set_color(node->parent, RED); _rotate_right(node->parent); - aux=node->parent->left; + aux = node->parent->left; } - if ( (aux->right->color==BLACK) && (aux->left->color==BLACK) ) { - _set_color(aux,RED); - node=node->parent; + if ((aux->right->color == BLACK) && (aux->left->color == BLACK)) { + _set_color(aux, RED); + node = node->parent; } else { - if (aux->left->color==BLACK) { - _set_color(aux->right,BLACK); - _set_color(aux,RED); + if (aux->left->color == BLACK) { + _set_color(aux->right, BLACK); + _set_color(aux, RED); _rotate_left(aux); - aux=node->parent->left; + aux = node->parent->left; } - _set_color(aux,node->parent->color); - _set_color(node->parent,BLACK); - _set_color(aux->left,BLACK); + _set_color(aux, node->parent->color); + _set_color(node->parent, BLACK); + _set_color(aux->left, BLACK); _rotate_right(node->parent); - node=root; + node = root; } } } - _set_color(node,BLACK); + _set_color(node, BLACK); - ERR_FAIL_COND(_data._nil->color!=BLACK); + ERR_FAIL_COND(_data._nil->color != BLACK); } void _erase(Element *p_node) { - - Element *rp= ((p_node->left == _data._nil) || (p_node->right == _data._nil)) ? p_node : _successor(p_node); + Element *rp = ((p_node->left == _data._nil) || (p_node->right == _data._nil)) ? p_node : _successor(p_node); if (!rp) - rp=_data._nil; - Element *node= (rp->left == _data._nil) ? rp->right : rp->left; + rp = _data._nil; + Element *node = (rp->left == _data._nil) ? rp->right : rp->left; - if (_data._root == (node->parent=rp->parent) ) { - _data._root->left=node; + if (_data._root == (node->parent = rp->parent)) { + _data._root->left = node; } else { if (rp == rp->parent->left) { - rp->parent->left=node; + rp->parent->left = node; } else { - rp->parent->right=node; + rp->parent->right = node; } } if (rp != p_node) { - ERR_FAIL_COND( rp == _data._nil ); + ERR_FAIL_COND(rp == _data._nil); - if (rp->color==BLACK) + if (rp->color == BLACK) _erase_fix(node); - - rp->left=p_node->left; - rp->right=p_node->right; - rp->parent=p_node->parent; - rp->color=p_node->color; - p_node->left->parent=rp; - p_node->right->parent=rp; + rp->left = p_node->left; + rp->right = p_node->right; + rp->parent = p_node->parent; + rp->color = p_node->color; + p_node->left->parent = rp; + p_node->right->parent = rp; if (p_node == p_node->parent->left) { - p_node->parent->left=rp; + p_node->parent->left = rp; } else { - p_node->parent->right=rp; + p_node->parent->right = rp; } } else { - if (p_node->color==BLACK) + if (p_node->color == BLACK) _erase_fix(node); - } - if (p_node->_next) - p_node->_next->_prev=p_node->_prev; + p_node->_next->_prev = p_node->_prev; if (p_node->_prev) - p_node->_prev->_next=p_node->_next; + p_node->_prev->_next = p_node->_next; - memdelete_allocator(p_node); + memdelete_allocator(p_node); _data.size_cache--; - ERR_FAIL_COND( _data._nil->color==RED ); + ERR_FAIL_COND(_data._nil->color == RED); } + void _calculate_depth(Element *p_element, int &max_d, int d) const { - void _calculate_depth(Element *p_element,int &max_d,int d) const { - - if (p_element==_data._nil) { + if (p_element == _data._nil) { return; } - _calculate_depth(p_element->left,max_d,d+1); - _calculate_depth(p_element->right,max_d,d+1); - if (d>max_d) - max_d=d; + _calculate_depth(p_element->left, max_d, d + 1); + _calculate_depth(p_element->right, max_d, d + 1); + if (d > max_d) + max_d = d; } void _cleanup_tree(Element *p_element) { - if (p_element==_data._nil) + if (p_element == _data._nil) return; _cleanup_tree(p_element->left); _cleanup_tree(p_element->right); - memdelete_allocator( p_element ); + memdelete_allocator(p_element); } - void _copy_from( const Map& p_map) { + void _copy_from(const Map &p_map) { clear(); // not the fastest way, but safeset to write. - for(Element *I=p_map.front();I;I=I->next()) { + for (Element *I = p_map.front(); I; I = I->next()) { - insert(I->key(),I->value()); + insert(I->key(), I->value()); } } + public: - - const Element *find(const K& p_key) const { + const Element *find(const K &p_key) const { if (!_data._root) return NULL; - const Element *res=_find(p_key); + const Element *res = _find(p_key); return res; } - Element *find(const K& p_key) { + Element *find(const K &p_key) { if (!_data._root) return NULL; - Element *res=_find(p_key); + Element *res = _find(p_key); return res; } - const Element *find_closest(const K& p_key) const { + const Element *find_closest(const K &p_key) const { if (!_data._root) return NULL; - const Element *res=_find_closest(p_key); + const Element *res = _find_closest(p_key); return res; } - Element *find_closest(const K& p_key) { + Element *find_closest(const K &p_key) { if (!_data._root) return NULL; - Element *res=_find_closest(p_key); + Element *res = _find_closest(p_key); return res; } - Element *insert(const K& p_key,const V& p_value) { + Element *insert(const K &p_key, const V &p_value) { if (!_data._root) _data._create_root(); - return _insert_rb(p_key,p_value); - + return _insert_rb(p_key, p_value); } - void erase(Element* p_element) { + void erase(Element *p_element) { if (!_data._root) return; _erase(p_element); - if (_data.size_cache==0 && _data._root) + if (_data.size_cache == 0 && _data._root) _data._free_root(); } - bool erase(const K& p_key) { + bool erase(const K &p_key) { if (!_data._root) return false; - Element *e=find(p_key); + Element *e = find(p_key); if (!e) return false; _erase(e); return true; } - bool has(const K& p_key) const { + bool has(const K &p_key) const { if (!_data._root) return false; return find(p_key) != NULL; } - const V& operator[](const K& p_key) const { + const V &operator[](const K &p_key) const { - ERR_FAIL_COND_V(!_data._root, *(V*)NULL); // crash on purpose - const Element *e=find(p_key); - ERR_FAIL_COND_V(!e, *(V*)NULL); // crash on purpose + ERR_FAIL_COND_V(!_data._root, *(V *)NULL); // crash on purpose + const Element *e = find(p_key); + ERR_FAIL_COND_V(!e, *(V *)NULL); // crash on purpose return e->_value; } - V& operator[](const K& p_key) { + V &operator[](const K &p_key) { if (!_data._root) _data._create_root(); - Element *e=find(p_key); + Element *e = find(p_key); if (!e) - e=insert(p_key,V()); + e = insert(p_key, V()); - ERR_FAIL_COND_V(!e, *(V*)NULL); // crash on purpose + ERR_FAIL_COND_V(!e, *(V *)NULL); // crash on purpose return e->_value; } @@ -637,12 +621,12 @@ public: if (!_data._root) return NULL; - Element *e=_data._root->left; - if (e==_data._nil) + Element *e = _data._root->left; + if (e == _data._nil) return NULL; - while(e->left!=_data._nil) - e=e->left; + while (e->left != _data._nil) + e = e->left; return e; } @@ -651,24 +635,24 @@ public: if (!_data._root) return NULL; - Element *e=_data._root->left; - if (e==_data._nil) + Element *e = _data._root->left; + if (e == _data._nil) return NULL; - while(e->right!=_data._nil) - e=e->right; + while (e->right != _data._nil) + e = e->right; return e; } - inline bool empty() const { return _data.size_cache==0; } + inline bool empty() const { return _data.size_cache == 0; } inline int size() const { return _data.size_cache; } int calculate_depth() const { // used for debug mostly if (!_data._root) return 0; - int max_d=0; - _calculate_depth(_data._root->left,max_d,0); + int max_d = 0; + _calculate_depth(_data._root->left, max_d, 0); return max_d; } @@ -677,32 +661,29 @@ public: if (!_data._root) return; _cleanup_tree(_data._root->left); - _data._root->left=_data._nil; - _data.size_cache=0; - _data._nil->parent=_data._nil; + _data._root->left = _data._nil; + _data.size_cache = 0; + _data._nil->parent = _data._nil; _data._free_root(); } - void operator=(const Map& p_map) { + void operator=(const Map &p_map) { - _copy_from( p_map ); + _copy_from(p_map); } - Map(const Map& p_map) { + Map(const Map &p_map) { - _copy_from( p_map ); + _copy_from(p_map); } _FORCE_INLINE_ Map() { - } - ~Map() { clear(); } - }; #endif diff --git a/core/math/a_star.cpp b/core/math/a_star.cpp index 0b45577b584..401a33da8c9 100644 --- a/core/math/a_star.cpp +++ b/core/math/a_star.cpp @@ -29,55 +29,52 @@ #include "a_star.h" #include "geometry.h" - int AStar::get_available_point_id() const { if (points.empty()) { return 1; } - return points.back()->key()+1; + return points.back()->key() + 1; } void AStar::add_point(int p_id, const Vector3 &p_pos, float p_weight_scale) { - ERR_FAIL_COND(p_id<0); + ERR_FAIL_COND(p_id < 0); if (!points.has(p_id)) { - Point *pt = memnew( Point ); - pt->id=p_id; - pt->pos=p_pos; - pt->weight_scale=p_weight_scale; - pt->prev_point=NULL; - pt->last_pass=0; - points[p_id]=pt; + Point *pt = memnew(Point); + pt->id = p_id; + pt->pos = p_pos; + pt->weight_scale = p_weight_scale; + pt->prev_point = NULL; + pt->last_pass = 0; + points[p_id] = pt; } else { - points[p_id]->pos=p_pos; - points[p_id]->weight_scale=p_weight_scale; + points[p_id]->pos = p_pos; + points[p_id]->weight_scale = p_weight_scale; } } -Vector3 AStar::get_point_pos(int p_id) const{ +Vector3 AStar::get_point_pos(int p_id) const { - ERR_FAIL_COND_V(!points.has(p_id),Vector3()); + ERR_FAIL_COND_V(!points.has(p_id), Vector3()); return points[p_id]->pos; - } -float AStar::get_point_weight_scale(int p_id) const{ +float AStar::get_point_weight_scale(int p_id) const { - ERR_FAIL_COND_V(!points.has(p_id),0); + ERR_FAIL_COND_V(!points.has(p_id), 0); return points[p_id]->weight_scale; - } -void AStar::remove_point(int p_id){ +void AStar::remove_point(int p_id) { ERR_FAIL_COND(!points.has(p_id)); - Point* p = points[p_id]; + Point *p = points[p_id]; - for(int i=0;ineighbours.size();i++) { + for (int i = 0; i < p->neighbours.size(); i++) { - Segment s(p_id,p->neighbours[i]->id); + Segment s(p_id, p->neighbours[i]->id); segments.erase(s); p->neighbours[i]->neighbours.erase(p); } @@ -86,54 +83,49 @@ void AStar::remove_point(int p_id){ points.erase(p_id); } -void AStar::connect_points(int p_id,int p_with_id){ +void AStar::connect_points(int p_id, int p_with_id) { ERR_FAIL_COND(!points.has(p_id)); ERR_FAIL_COND(!points.has(p_with_id)); - ERR_FAIL_COND(p_id==p_with_id); + ERR_FAIL_COND(p_id == p_with_id); - - Point* a = points[p_id]; - Point* b = points[p_with_id]; + Point *a = points[p_id]; + Point *b = points[p_with_id]; a->neighbours.push_back(b); b->neighbours.push_back(a); - Segment s(p_id,p_with_id); - if (s.from==p_id) { - s.from_point=a; - s.to_point=b; + Segment s(p_id, p_with_id); + if (s.from == p_id) { + s.from_point = a; + s.to_point = b; } else { - s.from_point=b; - s.to_point=a; + s.from_point = b; + s.to_point = a; } segments.insert(s); - - } -void AStar::disconnect_points(int p_id,int p_with_id){ +void AStar::disconnect_points(int p_id, int p_with_id) { - Segment s(p_id,p_with_id); + Segment s(p_id, p_with_id); ERR_FAIL_COND(!segments.has(s)); - segments.erase(s); Point *a = points[p_id]; Point *b = points[p_with_id]; a->neighbours.erase(b); b->neighbours.erase(a); - } -bool AStar::are_points_connected(int p_id,int p_with_id) const{ +bool AStar::are_points_connected(int p_id, int p_with_id) const { - Segment s(p_id,p_with_id); + Segment s(p_id, p_with_id); return segments.has(s); } -void AStar::clear(){ +void AStar::clear() { - for (const Map::Element *E=points.front();E;E=E->next()) { + for (const Map::Element *E = points.front(); E; E = E->next()) { memdelete(E->get()); } @@ -141,142 +133,130 @@ void AStar::clear(){ points.clear(); } +int AStar::get_closest_point(const Vector3 &p_point) const { -int AStar::get_closest_point(const Vector3& p_point) const{ + int closest_id = -1; + float closest_dist = 1e20; - int closest_id=-1; - float closest_dist=1e20; - - for (const Map::Element *E=points.front();E;E=E->next()) { + for (const Map::Element *E = points.front(); E; E = E->next()) { float d = p_point.distance_squared_to(E->get()->pos); - if (closest_id<0 || dkey(); + if (closest_id < 0 || d < closest_dist) { + closest_dist = d; + closest_id = E->key(); } } return closest_id; - - } -Vector3 AStar::get_closest_pos_in_segment(const Vector3& p_point) const { +Vector3 AStar::get_closest_pos_in_segment(const Vector3 &p_point) const { float closest_dist = 1e20; - bool found=false; + bool found = false; Vector3 closest_point; + for (const Set::Element *E = segments.front(); E; E = E->next()) { - for (const Set::Element *E=segments.front();E;E=E->next()) { - - Vector3 segment[2]={ + Vector3 segment[2] = { E->get().from_point->pos, E->get().to_point->pos, }; - Vector3 p = Geometry::get_closest_point_to_segment(p_point,segment); + Vector3 p = Geometry::get_closest_point_to_segment(p_point, segment); float d = p_point.distance_squared_to(p); - if (!found || d::List open_list; - bool found_route=false; + bool found_route = false; - - for(int i=0;ineighbours.size();i++) { + for (int i = 0; i < begin_point->neighbours.size(); i++) { Point *n = begin_point->neighbours[i]; - n->prev_point=begin_point; - n->distance=n->pos.distance_to(begin_point->pos); - n->distance*=n->weight_scale; - n->last_pass=pass; + n->prev_point = begin_point; + n->distance = n->pos.distance_to(begin_point->pos); + n->distance *= n->weight_scale; + n->last_pass = pass; open_list.add(&n->list); - if (end_point==n) { - found_route=true; + if (end_point == n) { + found_route = true; break; } } - while(!found_route) { + while (!found_route) { - if (open_list.first()==NULL) { + if (open_list.first() == NULL) { //could not find path sadly break; } //check open list - SelfList *least_cost_point=NULL; - float least_cost=1e30; + SelfList *least_cost_point = NULL; + float least_cost = 1e30; //this could be faster (cache previous results) - for (SelfList *E=open_list.first();E;E=E->next()) { + for (SelfList *E = open_list.first(); E; E = E->next()) { - Point *p=E->self(); + Point *p = E->self(); - float cost=p->distance; - cost+=p->pos.distance_to(end_point->pos); - cost*=p->weight_scale; + float cost = p->distance; + cost += p->pos.distance_to(end_point->pos); + cost *= p->weight_scale; - if (costself(); + Point *p = least_cost_point->self(); //open the neighbours for search int es = p->neighbours.size(); - for(int i=0;ineighbours[i]; + for (int i = 0; i < es; i++) { + Point *e = p->neighbours[i]; float distance = p->pos.distance_to(e->pos) + p->distance; - distance*=e->weight_scale; + distance *= e->weight_scale; - - - if (e->last_pass==pass) { + if (e->last_pass == pass) { //oh this was visited already, can we win the cost? - if (e->distance>distance) { + if (e->distance > distance) { - e->prev_point=p; - e->distance=distance; + e->prev_point = p; + e->distance = distance; } } else { //add to open neighbours - e->prev_point=p; - e->distance=distance; - e->last_pass=pass; //mark as used + e->prev_point = p; + e->distance = distance; + e->last_pass = pass; //mark as used open_list.add(&e->list); - if (e==end_point) { + if (e == end_point) { //oh my reached end! stop algorithm - found_route=true; + found_route = true; break; - } - } } @@ -287,46 +267,43 @@ bool AStar::_solve(Point* begin_point, Point* end_point) { } //clear the openf list - while(open_list.first()) { - open_list.remove( open_list.first() ); + while (open_list.first()) { + open_list.remove(open_list.first()); } return found_route; - } DVector AStar::get_point_path(int p_from_id, int p_to_id) { - ERR_FAIL_COND_V(!points.has(p_from_id),DVector()); - ERR_FAIL_COND_V(!points.has(p_to_id),DVector()); - + ERR_FAIL_COND_V(!points.has(p_from_id), DVector()); + ERR_FAIL_COND_V(!points.has(p_to_id), DVector()); pass++; - Point* a = points[p_from_id]; - Point* b = points[p_to_id]; + Point *a = points[p_from_id]; + Point *b = points[p_to_id]; - if (a==b) { + if (a == b) { DVector ret; ret.push_back(a->pos); return ret; } + Point *begin_point = a; + Point *end_point = b; - Point *begin_point=a; - Point *end_point=b; - - bool found_route=_solve(begin_point,end_point); + bool found_route = _solve(begin_point, end_point); if (!found_route) return DVector(); //midpoints - Point *p=end_point; - int pc=1; //begin point - while(p!=begin_point) { + Point *p = end_point; + int pc = 1; //begin point + while (p != begin_point) { pc++; - p=p->prev_point; + p = p->prev_point; } DVector path; @@ -335,54 +312,49 @@ DVector AStar::get_point_path(int p_from_id, int p_to_id) { { DVector::Write w = path.write(); - Point *p=end_point; - int idx=pc-1; - while(p!=begin_point) { - w[idx--]=p->pos; - p=p->prev_point; + Point *p = end_point; + int idx = pc - 1; + while (p != begin_point) { + w[idx--] = p->pos; + p = p->prev_point; } - w[0]=p->pos; //assign first - + w[0] = p->pos; //assign first } return path; - } - DVector AStar::get_id_path(int p_from_id, int p_to_id) { - ERR_FAIL_COND_V(!points.has(p_from_id),DVector()); - ERR_FAIL_COND_V(!points.has(p_to_id),DVector()); - + ERR_FAIL_COND_V(!points.has(p_from_id), DVector()); + ERR_FAIL_COND_V(!points.has(p_to_id), DVector()); pass++; - Point* a = points[p_from_id]; - Point* b = points[p_to_id]; + Point *a = points[p_from_id]; + Point *b = points[p_to_id]; - if (a==b) { + if (a == b) { DVector ret; ret.push_back(a->id); return ret; } + Point *begin_point = a; + Point *end_point = b; - Point *begin_point=a; - Point *end_point=b; - - bool found_route=_solve(begin_point,end_point); + bool found_route = _solve(begin_point, end_point); if (!found_route) return DVector(); //midpoints - Point *p=end_point; - int pc=1; //begin point - while(p!=begin_point) { + Point *p = end_point; + int pc = 1; //begin point + while (p != begin_point) { pc++; - p=p->prev_point; + p = p->prev_point; } DVector path; @@ -391,15 +363,14 @@ DVector AStar::get_id_path(int p_from_id, int p_to_id) { { DVector::Write w = path.write(); - p=end_point; - int idx=pc-1; - while(p!=begin_point) { - w[idx--]=p->id; - p=p->prev_point; + p = end_point; + int idx = pc - 1; + while (p != begin_point) { + w[idx--] = p->id; + p = p->prev_point; } - w[0]=p->id; //assign first - + w[0] = p->id; //assign first } return path; @@ -407,34 +378,31 @@ DVector AStar::get_id_path(int p_from_id, int p_to_id) { void AStar::_bind_methods() { - ObjectTypeDB::bind_method(_MD("get_available_point_id"),&AStar::get_available_point_id); - ObjectTypeDB::bind_method(_MD("add_point","id","pos","weight_scale"),&AStar::add_point,DEFVAL(1.0)); - ObjectTypeDB::bind_method(_MD("get_point_pos","id"),&AStar::get_point_pos); - ObjectTypeDB::bind_method(_MD("get_point_weight_scale","id"),&AStar::get_point_weight_scale); - ObjectTypeDB::bind_method(_MD("remove_point","id"),&AStar::remove_point); + ObjectTypeDB::bind_method(_MD("get_available_point_id"), &AStar::get_available_point_id); + ObjectTypeDB::bind_method(_MD("add_point", "id", "pos", "weight_scale"), &AStar::add_point, DEFVAL(1.0)); + ObjectTypeDB::bind_method(_MD("get_point_pos", "id"), &AStar::get_point_pos); + ObjectTypeDB::bind_method(_MD("get_point_weight_scale", "id"), &AStar::get_point_weight_scale); + ObjectTypeDB::bind_method(_MD("remove_point", "id"), &AStar::remove_point); - ObjectTypeDB::bind_method(_MD("connect_points","id","to_id"),&AStar::connect_points); - ObjectTypeDB::bind_method(_MD("disconnect_points","id","to_id"),&AStar::disconnect_points); - ObjectTypeDB::bind_method(_MD("are_points_connected","id","to_id"),&AStar::are_points_connected); + ObjectTypeDB::bind_method(_MD("connect_points", "id", "to_id"), &AStar::connect_points); + ObjectTypeDB::bind_method(_MD("disconnect_points", "id", "to_id"), &AStar::disconnect_points); + ObjectTypeDB::bind_method(_MD("are_points_connected", "id", "to_id"), &AStar::are_points_connected); - ObjectTypeDB::bind_method(_MD("clear"),&AStar::clear); + ObjectTypeDB::bind_method(_MD("clear"), &AStar::clear); - ObjectTypeDB::bind_method(_MD("get_closest_point","to_pos"),&AStar::get_closest_point); - ObjectTypeDB::bind_method(_MD("get_closest_pos_in_segment","to_pos"),&AStar::get_closest_pos_in_segment); - - ObjectTypeDB::bind_method(_MD("get_point_path","from_id","to_id"),&AStar::get_point_path); - ObjectTypeDB::bind_method(_MD("get_id_path","from_id","to_id"),&AStar::get_id_path); + ObjectTypeDB::bind_method(_MD("get_closest_point", "to_pos"), &AStar::get_closest_point); + ObjectTypeDB::bind_method(_MD("get_closest_pos_in_segment", "to_pos"), &AStar::get_closest_pos_in_segment); + ObjectTypeDB::bind_method(_MD("get_point_path", "from_id", "to_id"), &AStar::get_point_path); + ObjectTypeDB::bind_method(_MD("get_id_path", "from_id", "to_id"), &AStar::get_id_path); } - AStar::AStar() { - pass=1; + pass = 1; } - AStar::~AStar() { - pass=1; + pass = 1; } diff --git a/core/math/a_star.h b/core/math/a_star.h index f9ffc477fc0..c88591cf9f9 100644 --- a/core/math/a_star.h +++ b/core/math/a_star.h @@ -35,10 +35,9 @@ @author Juan Linietsky */ -class AStar: public Reference { - - OBJ_TYPE(AStar,Reference) +class AStar : public Reference { + OBJ_TYPE(AStar, Reference) uint64_t pass; @@ -51,16 +50,17 @@ class AStar: public Reference { float weight_scale; uint64_t last_pass; - Vector neighbours; + Vector neighbours; //used for pathfinding Point *prev_point; float distance; - Point() : list(this) {} + Point() + : list(this) {} }; - Map points; + Map points; struct Segment { union { @@ -74,44 +74,41 @@ class AStar: public Reference { Point *from_point; Point *to_point; - bool operator<(const Segment& p_s) const { return key p_to) { - SWAP(p_from,p_to); + SWAP(p_from, p_to); } - from=p_from; - to=p_to; + from = p_from; + to = p_to; } }; - Set segments; bool _solve(Point *begin_point, Point *end_point); protected: - static void _bind_methods(); -public: +public: int get_available_point_id() const; - void add_point(int p_id,const Vector3& p_pos,float p_weight_scale=1); + void add_point(int p_id, const Vector3 &p_pos, float p_weight_scale = 1); Vector3 get_point_pos(int p_id) const; float get_point_weight_scale(int p_id) const; void remove_point(int p_id); - void connect_points(int p_id,int p_with_id); - void disconnect_points(int p_id,int p_with_id); - bool are_points_connected(int p_id,int p_with_id) const; + void connect_points(int p_id, int p_with_id); + void disconnect_points(int p_id, int p_with_id); + bool are_points_connected(int p_id, int p_with_id) const; void clear(); - - int get_closest_point(const Vector3& p_point) const; - Vector3 get_closest_pos_in_segment(const Vector3& p_point) const; + int get_closest_point(const Vector3 &p_point) const; + Vector3 get_closest_pos_in_segment(const Vector3 &p_point) const; DVector get_point_path(int p_from_id, int p_to_id); DVector get_id_path(int p_from_id, int p_to_id); diff --git a/core/math/aabb.cpp b/core/math/aabb.cpp index d304d3e092d..b9f7e82723c 100644 --- a/core/math/aabb.cpp +++ b/core/math/aabb.cpp @@ -32,94 +32,87 @@ float AABB::get_area() const { - return size.x*size.y*size.z; - + return size.x * size.y * size.z; } -bool AABB::operator==(const AABB& p_rval) const { - - return ((pos==p_rval.pos) && (size==p_rval.size)); +bool AABB::operator==(const AABB &p_rval) const { + return ((pos == p_rval.pos) && (size == p_rval.size)); } -bool AABB::operator!=(const AABB& p_rval) const { - - return ((pos!=p_rval.pos) || (size!=p_rval.size)); +bool AABB::operator!=(const AABB &p_rval) const { + return ((pos != p_rval.pos) || (size != p_rval.size)); } -void AABB::merge_with(const AABB& p_aabb) { +void AABB::merge_with(const AABB &p_aabb) { - Vector3 beg_1,beg_2; - Vector3 end_1,end_2; - Vector3 min,max; + Vector3 beg_1, beg_2; + Vector3 end_1, end_2; + Vector3 min, max; - beg_1=pos; - beg_2=p_aabb.pos; - end_1=Vector3(size.x,size.y,size.z)+beg_1; - end_2=Vector3(p_aabb.size.x,p_aabb.size.y,p_aabb.size.z)+beg_2; + beg_1 = pos; + beg_2 = p_aabb.pos; + end_1 = Vector3(size.x, size.y, size.z) + beg_1; + end_2 = Vector3(p_aabb.size.x, p_aabb.size.y, p_aabb.size.z) + beg_2; - min.x=(beg_1.xend_2.x)?end_1.x:end_2.x; - max.y=(end_1.y>end_2.y)?end_1.y:end_2.y; - max.z=(end_1.z>end_2.z)?end_1.z:end_2.z; + max.x = (end_1.x > end_2.x) ? end_1.x : end_2.x; + max.y = (end_1.y > end_2.y) ? end_1.y : end_2.y; + max.z = (end_1.z > end_2.z) ? end_1.z : end_2.z; - pos=min; - size=max-min; + pos = min; + size = max - min; } -AABB AABB::intersection(const AABB& p_aabb) const { +AABB AABB::intersection(const AABB &p_aabb) const { - Vector3 src_min=pos; - Vector3 src_max=pos+size; - Vector3 dst_min=p_aabb.pos; - Vector3 dst_max=p_aabb.pos+p_aabb.size; + Vector3 src_min = pos; + Vector3 src_max = pos + size; + Vector3 dst_min = p_aabb.pos; + Vector3 dst_max = p_aabb.pos + p_aabb.size; - Vector3 min,max; + Vector3 min, max; - if (src_min.x > dst_max.x || src_max.x < dst_min.x ) + if (src_min.x > dst_max.x || src_max.x < dst_min.x) return AABB(); else { - min.x= ( src_min.x > dst_min.x ) ? src_min.x :dst_min.x; - max.x= ( src_max.x < dst_max.x ) ? src_max.x :dst_max.x; - + min.x = (src_min.x > dst_min.x) ? src_min.x : dst_min.x; + max.x = (src_max.x < dst_max.x) ? src_max.x : dst_max.x; } - if (src_min.y > dst_max.y || src_max.y < dst_min.y ) + if (src_min.y > dst_max.y || src_max.y < dst_min.y) return AABB(); else { - min.y= ( src_min.y > dst_min.y ) ? src_min.y :dst_min.y; - max.y= ( src_max.y < dst_max.y ) ? src_max.y :dst_max.y; - + min.y = (src_min.y > dst_min.y) ? src_min.y : dst_min.y; + max.y = (src_max.y < dst_max.y) ? src_max.y : dst_max.y; } - if (src_min.z > dst_max.z || src_max.z < dst_min.z ) + if (src_min.z > dst_max.z || src_max.z < dst_min.z) return AABB(); else { - min.z= ( src_min.z > dst_min.z ) ? src_min.z :dst_min.z; - max.z= ( src_max.z < dst_max.z ) ? src_max.z :dst_max.z; - + min.z = (src_min.z > dst_min.z) ? src_min.z : dst_min.z; + max.z = (src_max.z < dst_max.z) ? src_max.z : dst_max.z; } - - return AABB( min, max-min ); + return AABB(min, max - min); } -bool AABB::intersects_ray(const Vector3& p_from, const Vector3& p_dir,Vector3* r_clip,Vector3* r_normal) const { +bool AABB::intersects_ray(const Vector3 &p_from, const Vector3 &p_dir, Vector3 *r_clip, Vector3 *r_normal) const { Vector3 c1, c2; - Vector3 end = pos+size; - float near=-1e20; - float far=1e20; - int axis=0; + Vector3 end = pos + size; + float near = -1e20; + float far = 1e20; + int axis = 0; - for (int i=0;i<3;i++){ - if (p_dir[i] == 0){ + for (int i = 0; i < 3; i++) { + if (p_dir[i] == 0) { if ((p_from[i] < pos[i]) || (p_from[i] > end[i])) { return false; } @@ -127,71 +120,69 @@ bool AABB::intersects_ray(const Vector3& p_from, const Vector3& p_dir,Vector3* r c1[i] = (pos[i] - p_from[i]) / p_dir[i]; c2[i] = (end[i] - p_from[i]) / p_dir[i]; - if(c1[i] > c2[i]){ - SWAP(c1,c2); + if (c1[i] > c2[i]) { + SWAP(c1, c2); } - if (c1[i] > near){ + if (c1[i] > near) { near = c1[i]; - axis=i; + axis = i; } - if (c2[i] < far){ + if (c2[i] < far) { far = c2[i]; } - if( (near > far) || (far < 0) ){ + if ((near > far) || (far < 0)) { return false; } } } if (r_clip) - *r_clip=c1; + *r_clip = c1; if (r_normal) { - *r_normal=Vector3(); - (*r_normal)[axis]=p_dir[axis]?-1:1; + *r_normal = Vector3(); + (*r_normal)[axis] = p_dir[axis] ? -1 : 1; } return true; - } +bool AABB::intersects_segment(const Vector3 &p_from, const Vector3 &p_to, Vector3 *r_clip, Vector3 *r_normal) const { -bool AABB::intersects_segment(const Vector3& p_from, const Vector3& p_to,Vector3* r_clip,Vector3* r_normal) const { + real_t min = 0, max = 1; + int axis = 0; + float sign = 0; - real_t min=0,max=1; - int axis=0; - float sign=0; - - for(int i=0;i<3;i++) { - real_t seg_from=p_from[i]; - real_t seg_to=p_to[i]; - real_t box_begin=pos[i]; - real_t box_end=box_begin+size[i]; - real_t cmin,cmax; + for (int i = 0; i < 3; i++) { + real_t seg_from = p_from[i]; + real_t seg_to = p_to[i]; + real_t box_begin = pos[i]; + real_t box_end = box_begin + size[i]; + real_t cmin, cmax; float csign; if (seg_from < seg_to) { if (seg_from > box_end || seg_to < box_begin) return false; - real_t length=seg_to-seg_from; - cmin = (seg_from < box_begin)?((box_begin - seg_from)/length):0; - cmax = (seg_to > box_end)?((box_end - seg_from)/length):1; - csign=-1.0; + real_t length = seg_to - seg_from; + cmin = (seg_from < box_begin) ? ((box_begin - seg_from) / length) : 0; + cmax = (seg_to > box_end) ? ((box_end - seg_from) / length) : 1; + csign = -1.0; } else { if (seg_to > box_end || seg_from < box_begin) return false; - real_t length=seg_to-seg_from; - cmin = (seg_from > box_end)?(box_end - seg_from)/length:0; - cmax = (seg_to < box_begin)?(box_begin - seg_from)/length:1; - csign=1.0; + real_t length = seg_to - seg_from; + cmin = (seg_from > box_end) ? (box_end - seg_from) / length : 0; + cmax = (seg_to < box_begin) ? (box_begin - seg_from) / length : 1; + csign = 1.0; } if (cmin > min) { min = cmin; - axis=i; - sign=csign; + axis = i; + sign = csign; } if (cmax < max) max = cmax; @@ -199,220 +190,210 @@ bool AABB::intersects_segment(const Vector3& p_from, const Vector3& p_to,Vector3 return false; } - - Vector3 rel=p_to-p_from; + Vector3 rel = p_to - p_from; if (r_normal) { Vector3 normal; - normal[axis]=sign; - *r_normal=normal; + normal[axis] = sign; + *r_normal = normal; } if (r_clip) - *r_clip=p_from+rel*min; + *r_clip = p_from + rel * min; return true; - } - bool AABB::intersects_plane(const Plane &p_plane) const { Vector3 points[8] = { - Vector3( pos.x , pos.y , pos.z ), - Vector3( pos.x , pos.y , pos.z+size.z ), - Vector3( pos.x , pos.y+size.y , pos.z ), - Vector3( pos.x , pos.y+size.y , pos.z+size.z ), - Vector3( pos.x+size.x , pos.y , pos.z ), - Vector3( pos.x+size.x , pos.y , pos.z+size.z ), - Vector3( pos.x+size.x , pos.y+size.y , pos.z ), - Vector3( pos.x+size.x , pos.y+size.y , pos.z+size.z ), + Vector3(pos.x, pos.y, pos.z), + Vector3(pos.x, pos.y, pos.z + size.z), + Vector3(pos.x, pos.y + size.y, pos.z), + Vector3(pos.x, pos.y + size.y, pos.z + size.z), + Vector3(pos.x + size.x, pos.y, pos.z), + Vector3(pos.x + size.x, pos.y, pos.z + size.z), + Vector3(pos.x + size.x, pos.y + size.y, pos.z), + Vector3(pos.x + size.x, pos.y + size.y, pos.z + size.z), }; - bool over=false; - bool under=false; + bool over = false; + bool under = false; - for (int i=0;i<8;i++) { + for (int i = 0; i < 8; i++) { - if (p_plane.distance_to(points[i])>0) - over=true; + if (p_plane.distance_to(points[i]) > 0) + over = true; else - under=true; - + under = true; } return under && over; } - - Vector3 AABB::get_longest_axis() const { - Vector3 axis(1,0,0); - real_t max_size=size.x; + Vector3 axis(1, 0, 0); + real_t max_size = size.x; - if (size.y > max_size ) { - axis=Vector3(0,1,0); - max_size=size.y; + if (size.y > max_size) { + axis = Vector3(0, 1, 0); + max_size = size.y; } - if (size.z > max_size ) { - axis=Vector3(0,0,1); - max_size=size.z; + if (size.z > max_size) { + axis = Vector3(0, 0, 1); + max_size = size.z; } return axis; } int AABB::get_longest_axis_index() const { - int axis=0; - real_t max_size=size.x; + int axis = 0; + real_t max_size = size.x; - if (size.y > max_size ) { - axis=1; - max_size=size.y; + if (size.y > max_size) { + axis = 1; + max_size = size.y; } - if (size.z > max_size ) { - axis=2; - max_size=size.z; + if (size.z > max_size) { + axis = 2; + max_size = size.z; } return axis; } - Vector3 AABB::get_shortest_axis() const { - Vector3 axis(1,0,0); - real_t max_size=size.x; + Vector3 axis(1, 0, 0); + real_t max_size = size.x; - if (size.y < max_size ) { - axis=Vector3(0,1,0); - max_size=size.y; + if (size.y < max_size) { + axis = Vector3(0, 1, 0); + max_size = size.y; } - if (size.z < max_size ) { - axis=Vector3(0,0,1); - max_size=size.z; + if (size.z < max_size) { + axis = Vector3(0, 0, 1); + max_size = size.z; } return axis; } int AABB::get_shortest_axis_index() const { - int axis=0; - real_t max_size=size.x; + int axis = 0; + real_t max_size = size.x; - if (size.y < max_size ) { - axis=1; - max_size=size.y; + if (size.y < max_size) { + axis = 1; + max_size = size.y; } - if (size.z < max_size ) { - axis=2; - max_size=size.z; + if (size.z < max_size) { + axis = 2; + max_size = size.z; } return axis; } -AABB AABB::merge(const AABB& p_with) const { +AABB AABB::merge(const AABB &p_with) const { - AABB aabb=*this; + AABB aabb = *this; aabb.merge_with(p_with); return aabb; } -AABB AABB::expand(const Vector3& p_vector) const { - AABB aabb=*this; +AABB AABB::expand(const Vector3 &p_vector) const { + AABB aabb = *this; aabb.expand_to(p_vector); return aabb; - } AABB AABB::grow(real_t p_by) const { - AABB aabb=*this; + AABB aabb = *this; aabb.grow_by(p_by); return aabb; } -void AABB::get_edge(int p_edge,Vector3& r_from,Vector3& r_to) const { +void AABB::get_edge(int p_edge, Vector3 &r_from, Vector3 &r_to) const { - ERR_FAIL_INDEX(p_edge,12); - switch(p_edge) { + ERR_FAIL_INDEX(p_edge, 12); + switch (p_edge) { - case 0:{ + case 0: { - r_from=Vector3( pos.x+size.x , pos.y , pos.z ); - r_to=Vector3( pos.x , pos.y , pos.z ); + r_from = Vector3(pos.x + size.x, pos.y, pos.z); + r_to = Vector3(pos.x, pos.y, pos.z); } break; - case 1:{ + case 1: { - r_from=Vector3( pos.x+size.x , pos.y , pos.z+size.z ); - r_to=Vector3( pos.x+size.x , pos.y , pos.z ); + r_from = Vector3(pos.x + size.x, pos.y, pos.z + size.z); + r_to = Vector3(pos.x + size.x, pos.y, pos.z); } break; - case 2:{ - r_from=Vector3( pos.x , pos.y , pos.z+size.z ); - r_to=Vector3( pos.x+size.x , pos.y , pos.z+size.z ); + case 2: { + r_from = Vector3(pos.x, pos.y, pos.z + size.z); + r_to = Vector3(pos.x + size.x, pos.y, pos.z + size.z); } break; - case 3:{ + case 3: { - r_from=Vector3( pos.x , pos.y , pos.z ); - r_to=Vector3( pos.x , pos.y , pos.z+size.z ); + r_from = Vector3(pos.x, pos.y, pos.z); + r_to = Vector3(pos.x, pos.y, pos.z + size.z); } break; - case 4:{ + case 4: { - r_from=Vector3( pos.x , pos.y+size.y , pos.z ); - r_to=Vector3( pos.x+size.x , pos.y+size.y , pos.z ); + r_from = Vector3(pos.x, pos.y + size.y, pos.z); + r_to = Vector3(pos.x + size.x, pos.y + size.y, pos.z); } break; - case 5:{ + case 5: { - r_from=Vector3( pos.x+size.x , pos.y+size.y , pos.z ); - r_to=Vector3( pos.x+size.x , pos.y+size.y , pos.z+size.z ); + r_from = Vector3(pos.x + size.x, pos.y + size.y, pos.z); + r_to = Vector3(pos.x + size.x, pos.y + size.y, pos.z + size.z); } break; - case 6:{ - r_from=Vector3( pos.x+size.x , pos.y+size.y , pos.z+size.z ); - r_to=Vector3( pos.x , pos.y+size.y , pos.z+size.z ); + case 6: { + r_from = Vector3(pos.x + size.x, pos.y + size.y, pos.z + size.z); + r_to = Vector3(pos.x, pos.y + size.y, pos.z + size.z); } break; - case 7:{ + case 7: { - r_from=Vector3( pos.x , pos.y+size.y , pos.z+size.z ); - r_to=Vector3( pos.x , pos.y+size.y , pos.z ); + r_from = Vector3(pos.x, pos.y + size.y, pos.z + size.z); + r_to = Vector3(pos.x, pos.y + size.y, pos.z); } break; - case 8:{ + case 8: { - r_from=Vector3( pos.x , pos.y , pos.z+size.z ); - r_to=Vector3( pos.x , pos.y+size.y , pos.z+size.z ); + r_from = Vector3(pos.x, pos.y, pos.z + size.z); + r_to = Vector3(pos.x, pos.y + size.y, pos.z + size.z); } break; - case 9:{ + case 9: { - r_from=Vector3( pos.x , pos.y , pos.z ); - r_to=Vector3( pos.x , pos.y+size.y , pos.z ); + r_from = Vector3(pos.x, pos.y, pos.z); + r_to = Vector3(pos.x, pos.y + size.y, pos.z); } break; - case 10:{ + case 10: { - r_from=Vector3( pos.x+size.x , pos.y , pos.z ); - r_to=Vector3( pos.x+size.x , pos.y+size.y , pos.z ); + r_from = Vector3(pos.x + size.x, pos.y, pos.z); + r_to = Vector3(pos.x + size.x, pos.y + size.y, pos.z); } break; - case 11:{ + case 11: { - r_from=Vector3( pos.x+size.x , pos.y , pos.z+size.z ); - r_to=Vector3( pos.x+size.x , pos.y+size.y , pos.z+size.z ); + r_from = Vector3(pos.x + size.x, pos.y, pos.z + size.z); + r_to = Vector3(pos.x + size.x, pos.y + size.y, pos.z + size.z); } break; - } - } AABB::operator String() const { - return String()+pos +" - "+ size; + return String() + pos + " - " + size; } diff --git a/core/math/aabb.h b/core/math/aabb.h index 1c0adf9012f..63f822fbba7 100644 --- a/core/math/aabb.h +++ b/core/math/aabb.h @@ -29,17 +29,13 @@ #ifndef AABB_H #define AABB_H - - -#include "vector3.h" #include "plane.h" +#include "vector3.h" /** * AABB / AABB (Axis Aligned Bounding Box) * This is implemented by a point (pos) and the box size */ - - class AABB { public: Vector3 pos; @@ -48,40 +44,38 @@ public: float get_area() const; /// get area _FORCE_INLINE_ bool has_no_area() const { - return (size.x<=CMP_EPSILON || size.y<=CMP_EPSILON || size.z<=CMP_EPSILON); + return (size.x <= CMP_EPSILON || size.y <= CMP_EPSILON || size.z <= CMP_EPSILON); } _FORCE_INLINE_ bool has_no_surface() const { - return (size.x<=CMP_EPSILON && size.y<=CMP_EPSILON && size.z<=CMP_EPSILON); + return (size.x <= CMP_EPSILON && size.y <= CMP_EPSILON && size.z <= CMP_EPSILON); } - const Vector3& get_pos() const { return pos; } - void set_pos(const Vector3& p_pos) { pos=p_pos; } - const Vector3& get_size() const { return size; } - void set_size(const Vector3& p_size) { size=p_size; } + const Vector3 &get_pos() const { return pos; } + void set_pos(const Vector3 &p_pos) { pos = p_pos; } + const Vector3 &get_size() const { return size; } + void set_size(const Vector3 &p_size) { size = p_size; } + bool operator==(const AABB &p_rval) const; + bool operator!=(const AABB &p_rval) const; - bool operator==(const AABB& p_rval) const; - bool operator!=(const AABB& p_rval) const; + _FORCE_INLINE_ bool intersects(const AABB &p_aabb) const; /// Both AABBs overlap + _FORCE_INLINE_ bool intersects_inclusive(const AABB &p_aabb) const; /// Both AABBs (or their faces) overlap + _FORCE_INLINE_ bool encloses(const AABB &p_aabb) const; /// p_aabb is completely inside this - _FORCE_INLINE_ bool intersects(const AABB& p_aabb) const; /// Both AABBs overlap - _FORCE_INLINE_ bool intersects_inclusive(const AABB& p_aabb) const; /// Both AABBs (or their faces) overlap - _FORCE_INLINE_ bool encloses(const AABB & p_aabb) const; /// p_aabb is completely inside this - - AABB merge(const AABB& p_with) const; - void merge_with(const AABB& p_aabb); ///merge with another AABB - AABB intersection(const AABB& p_aabb) const; ///get box where two intersect, empty if no intersection occurs - bool intersects_segment(const Vector3& p_from, const Vector3& p_to,Vector3* r_clip=NULL,Vector3* r_normal=NULL) const; - bool intersects_ray(const Vector3& p_from, const Vector3& p_dir,Vector3* r_clip=NULL,Vector3* r_normal=NULL) const; - _FORCE_INLINE_ bool smits_intersect_ray(const Vector3 &from,const Vector3& p_dir, float t0, float t1) const; + AABB merge(const AABB &p_with) const; + void merge_with(const AABB &p_aabb); ///merge with another AABB + AABB intersection(const AABB &p_aabb) const; ///get box where two intersect, empty if no intersection occurs + bool intersects_segment(const Vector3 &p_from, const Vector3 &p_to, Vector3 *r_clip = NULL, Vector3 *r_normal = NULL) const; + bool intersects_ray(const Vector3 &p_from, const Vector3 &p_dir, Vector3 *r_clip = NULL, Vector3 *r_normal = NULL) const; + _FORCE_INLINE_ bool smits_intersect_ray(const Vector3 &from, const Vector3 &p_dir, float t0, float t1) const; _FORCE_INLINE_ bool intersects_convex_shape(const Plane *p_plane, int p_plane_count) const; bool intersects_plane(const Plane &p_plane) const; - _FORCE_INLINE_ bool has_point(const Vector3& p_point) const; - _FORCE_INLINE_ Vector3 get_support(const Vector3& p_normal) const; - + _FORCE_INLINE_ bool has_point(const Vector3 &p_point) const; + _FORCE_INLINE_ Vector3 get_support(const Vector3 &p_normal) const; Vector3 get_longest_axis() const; int get_longest_axis_index() const; @@ -94,98 +88,97 @@ public: AABB grow(real_t p_by) const; _FORCE_INLINE_ void grow_by(real_t p_amount); - void get_edge(int p_edge,Vector3& r_from,Vector3& r_to) const; + void get_edge(int p_edge, Vector3 &r_from, Vector3 &r_to) const; _FORCE_INLINE_ Vector3 get_endpoint(int p_point) const; - AABB expand(const Vector3& p_vector) const; - _FORCE_INLINE_ void project_range_in_plane(const Plane& p_plane,float &r_min,float& r_max) const; - _FORCE_INLINE_ void expand_to(const Vector3& p_vector); /** expand to contain a point if necesary */ + AABB expand(const Vector3 &p_vector) const; + _FORCE_INLINE_ void project_range_in_plane(const Plane &p_plane, float &r_min, float &r_max) const; + _FORCE_INLINE_ void expand_to(const Vector3 &p_vector); /** expand to contain a point if necesary */ operator String() const; _FORCE_INLINE_ AABB() {} - inline AABB(const Vector3 &p_pos,const Vector3& p_size) { pos=p_pos; size=p_size; } - - + inline AABB(const Vector3 &p_pos, const Vector3 &p_size) { + pos = p_pos; + size = p_size; + } }; -inline bool AABB::intersects(const AABB& p_aabb) const { +inline bool AABB::intersects(const AABB &p_aabb) const { - if ( pos.x >= (p_aabb.pos.x + p_aabb.size.x) ) - return false; - if ( (pos.x+size.x) <= p_aabb.pos.x ) - return false; - if ( pos.y >= (p_aabb.pos.y + p_aabb.size.y) ) - return false; - if ( (pos.y+size.y) <= p_aabb.pos.y ) - return false; - if ( pos.z >= (p_aabb.pos.z + p_aabb.size.z) ) - return false; - if ( (pos.z+size.z) <= p_aabb.pos.z ) - return false; + if (pos.x >= (p_aabb.pos.x + p_aabb.size.x)) + return false; + if ((pos.x + size.x) <= p_aabb.pos.x) + return false; + if (pos.y >= (p_aabb.pos.y + p_aabb.size.y)) + return false; + if ((pos.y + size.y) <= p_aabb.pos.y) + return false; + if (pos.z >= (p_aabb.pos.z + p_aabb.size.z)) + return false; + if ((pos.z + size.z) <= p_aabb.pos.z) + return false; - return true; + return true; } -inline bool AABB::intersects_inclusive(const AABB& p_aabb) const { +inline bool AABB::intersects_inclusive(const AABB &p_aabb) const { - if ( pos.x > (p_aabb.pos.x + p_aabb.size.x) ) - return false; - if ( (pos.x+size.x) < p_aabb.pos.x ) - return false; - if ( pos.y > (p_aabb.pos.y + p_aabb.size.y) ) - return false; - if ( (pos.y+size.y) < p_aabb.pos.y ) - return false; - if ( pos.z > (p_aabb.pos.z + p_aabb.size.z) ) - return false; - if ( (pos.z+size.z) < p_aabb.pos.z ) - return false; + if (pos.x > (p_aabb.pos.x + p_aabb.size.x)) + return false; + if ((pos.x + size.x) < p_aabb.pos.x) + return false; + if (pos.y > (p_aabb.pos.y + p_aabb.size.y)) + return false; + if ((pos.y + size.y) < p_aabb.pos.y) + return false; + if (pos.z > (p_aabb.pos.z + p_aabb.size.z)) + return false; + if ((pos.z + size.z) < p_aabb.pos.z) + return false; - return true; + return true; } -inline bool AABB::encloses(const AABB & p_aabb) const { +inline bool AABB::encloses(const AABB &p_aabb) const { - Vector3 src_min=pos; - Vector3 src_max=pos+size; - Vector3 dst_min=p_aabb.pos; - Vector3 dst_max=p_aabb.pos+p_aabb.size; + Vector3 src_min = pos; + Vector3 src_max = pos + size; + Vector3 dst_min = p_aabb.pos; + Vector3 dst_max = p_aabb.pos + p_aabb.size; - return ( - (src_min.x <= dst_min.x) && + return ( + (src_min.x <= dst_min.x) && (src_max.x > dst_max.x) && (src_min.y <= dst_min.y) && (src_max.y > dst_max.y) && (src_min.z <= dst_min.z) && - (src_max.z > dst_max.z) ); - + (src_max.z > dst_max.z)); } -Vector3 AABB::get_support(const Vector3& p_normal) const { +Vector3 AABB::get_support(const Vector3 &p_normal) const { Vector3 half_extents = size * 0.5; Vector3 ofs = pos + half_extents; return Vector3( - (p_normal.x>0) ? -half_extents.x : half_extents.x, - (p_normal.y>0) ? -half_extents.y : half_extents.y, - (p_normal.z>0) ? -half_extents.z : half_extents.z - )+ofs; + (p_normal.x > 0) ? -half_extents.x : half_extents.x, + (p_normal.y > 0) ? -half_extents.y : half_extents.y, + (p_normal.z > 0) ? -half_extents.z : half_extents.z) + + ofs; } - Vector3 AABB::get_endpoint(int p_point) const { - switch(p_point) { - case 0: return Vector3( pos.x , pos.y , pos.z ); - case 1: return Vector3( pos.x , pos.y , pos.z+size.z ); - case 2: return Vector3( pos.x , pos.y+size.y , pos.z ); - case 3: return Vector3( pos.x , pos.y+size.y , pos.z+size.z ); - case 4: return Vector3( pos.x+size.x , pos.y , pos.z ); - case 5: return Vector3( pos.x+size.x , pos.y , pos.z+size.z ); - case 6: return Vector3( pos.x+size.x , pos.y+size.y , pos.z ); - case 7: return Vector3( pos.x+size.x , pos.y+size.y , pos.z+size.z ); + switch (p_point) { + case 0: return Vector3(pos.x, pos.y, pos.z); + case 1: return Vector3(pos.x, pos.y, pos.z + size.z); + case 2: return Vector3(pos.x, pos.y + size.y, pos.z); + case 3: return Vector3(pos.x, pos.y + size.y, pos.z + size.z); + case 4: return Vector3(pos.x + size.x, pos.y, pos.z); + case 5: return Vector3(pos.x + size.x, pos.y, pos.z + size.z); + case 6: return Vector3(pos.x + size.x, pos.y + size.y, pos.z); + case 7: return Vector3(pos.x + size.x, pos.y + size.y, pos.z + size.z); }; ERR_FAIL_V(Vector3()); @@ -198,14 +191,13 @@ bool AABB::intersects_convex_shape(const Plane *p_planes, int p_plane_count) con Vector3 half_extents = size * 0.5; Vector3 ofs = pos + half_extents; - for(int i=0;i0) ? -half_extents.x : half_extents.x, - (p.normal.y>0) ? -half_extents.y : half_extents.y, - (p.normal.z>0) ? -half_extents.z : half_extents.z - ); - point+=ofs; + (p.normal.x > 0) ? -half_extents.x : half_extents.x, + (p.normal.y > 0) ? -half_extents.y : half_extents.y, + (p.normal.z > 0) ? -half_extents.z : half_extents.z); + point += ofs; if (p.is_point_over(point)) return false; } @@ -213,33 +205,31 @@ bool AABB::intersects_convex_shape(const Plane *p_planes, int p_plane_count) con return true; #else //cache all points to check against! -// #warning should be easy to optimize, just use the same as when taking the support and use only that point + // #warning should be easy to optimize, just use the same as when taking the support and use only that point Vector3 points[8] = { - Vector3( pos.x , pos.y , pos.z ), - Vector3( pos.x , pos.y , pos.z+size.z ), - Vector3( pos.x , pos.y+size.y , pos.z ), - Vector3( pos.x , pos.y+size.y , pos.z+size.z ), - Vector3( pos.x+size.x , pos.y , pos.z ), - Vector3( pos.x+size.x , pos.y , pos.z+size.z ), - Vector3( pos.x+size.x , pos.y+size.y , pos.z ), - Vector3( pos.x+size.x , pos.y+size.y , pos.z+size.z ), + Vector3(pos.x, pos.y, pos.z), + Vector3(pos.x, pos.y, pos.z + size.z), + Vector3(pos.x, pos.y + size.y, pos.z), + Vector3(pos.x, pos.y + size.y, pos.z + size.z), + Vector3(pos.x + size.x, pos.y, pos.z), + Vector3(pos.x + size.x, pos.y, pos.z + size.z), + Vector3(pos.x + size.x, pos.y + size.y, pos.z), + Vector3(pos.x + size.x, pos.y + size.y, pos.z + size.z), }; - for (int i=0;ipos.x+size.x) + if (p_point.x > pos.x + size.x) return false; - if (p_point.y>pos.y+size.y) + if (p_point.y > pos.y + size.y) return false; - if (p_point.z>pos.z+size.z) + if (p_point.z > pos.z + size.z) return false; return true; } +inline void AABB::expand_to(const Vector3 &p_vector) { -inline void AABB::expand_to(const Vector3& p_vector) { + Vector3 begin = pos; + Vector3 end = pos + size; - Vector3 begin=pos; - Vector3 end=pos+size; + if (p_vector.x < begin.x) + begin.x = p_vector.x; + if (p_vector.y < begin.y) + begin.y = p_vector.y; + if (p_vector.z < begin.z) + begin.z = p_vector.z; - if (p_vector.x end.x) + end.x = p_vector.x; + if (p_vector.y > end.y) + end.y = p_vector.y; + if (p_vector.z > end.z) + end.z = p_vector.z; - if (p_vector.x>end.x) - end.x=p_vector.x; - if (p_vector.y>end.y) - end.y=p_vector.y; - if (p_vector.z>end.z) - end.z=p_vector.z; - - pos=begin; - size=end-begin; + pos = begin; + size = end - begin; } -void AABB::project_range_in_plane(const Plane& p_plane,float &r_min,float& r_max) const { +void AABB::project_range_in_plane(const Plane &p_plane, float &r_min, float &r_max) const { - Vector3 half_extents( size.x * 0.5, size.y * 0.5, size.z * 0.5 ); - Vector3 center( pos.x + half_extents.x, pos.y + half_extents.y, pos.z + half_extents.z ); + Vector3 half_extents(size.x * 0.5, size.y * 0.5, size.z * 0.5); + Vector3 center(pos.x + half_extents.x, pos.y + half_extents.y, pos.z + half_extents.z); float length = p_plane.normal.abs().dot(half_extents); - float distance = p_plane.distance_to( center ); + float distance = p_plane.distance_to(center); r_min = distance - length; r_max = distance + length; } inline real_t AABB::get_longest_axis_size() const { - real_t max_size=size.x; + real_t max_size = size.x; - if (size.y > max_size ) { - max_size=size.y; + if (size.y > max_size) { + max_size = size.y; } - if (size.z > max_size ) { - max_size=size.z; + if (size.z > max_size) { + max_size = size.z; } return max_size; @@ -321,74 +310,71 @@ inline real_t AABB::get_longest_axis_size() const { inline real_t AABB::get_shortest_axis_size() const { - real_t max_size=size.x; + real_t max_size = size.x; - if (size.y < max_size ) { - max_size=size.y; + if (size.y < max_size) { + max_size = size.y; } - if (size.z < max_size ) { - max_size=size.z; + if (size.z < max_size) { + max_size = size.z; } return max_size; } -bool AABB::smits_intersect_ray(const Vector3 &from,const Vector3& dir, float t0, float t1) const { +bool AABB::smits_intersect_ray(const Vector3 &from, const Vector3 &dir, float t0, float t1) const { - float divx=1.0/dir.x; - float divy=1.0/dir.y; - float divz=1.0/dir.z; + float divx = 1.0 / dir.x; + float divy = 1.0 / dir.y; + float divz = 1.0 / dir.z; - Vector3 upbound=pos+size; + Vector3 upbound = pos + size; float tmin, tmax, tymin, tymax, tzmin, tzmax; if (dir.x >= 0) { tmin = (pos.x - from.x) * divx; tmax = (upbound.x - from.x) * divx; - } - else { + } else { tmin = (upbound.x - from.x) * divx; tmax = (pos.x - from.x) * divx; } if (dir.y >= 0) { tymin = (pos.y - from.y) * divy; tymax = (upbound.y - from.y) * divy; - } - else { + } else { tymin = (upbound.y - from.y) * divy; tymax = (pos.y - from.y) * divy; } - if ( (tmin > tymax) || (tymin > tmax) ) + if ((tmin > tymax) || (tymin > tmax)) return false; if (tymin > tmin) - tmin = tymin; + tmin = tymin; if (tymax < tmax) tmax = tymax; if (dir.z >= 0) { tzmin = (pos.z - from.z) * divz; tzmax = (upbound.z - from.z) * divz; - } - else { + } else { tzmin = (upbound.z - from.z) * divz; tzmax = (pos.z - from.z) * divz; } - if ( (tmin > tzmax) || (tzmin > tmax) ) + if ((tmin > tzmax) || (tzmin > tmax)) return false; if (tzmin > tmin) tmin = tzmin; if (tzmax < tmax) tmax = tzmax; - return ( (tmin < t1) && (tmax > t0) ); + return ((tmin < t1) && (tmax > t0)); } void AABB::grow_by(real_t p_amount) { - pos.x-=p_amount; - pos.y-=p_amount; - pos.z-=p_amount; - size.x+=2.0*p_amount; - size.y+=2.0*p_amount; - size.z+=2.0*p_amount; + pos.x -= p_amount; + pos.y -= p_amount; + pos.z -= p_amount; + size.x += 2.0 * p_amount; + size.y += 2.0 * p_amount; + size.z += 2.0 * p_amount; } typedef AABB Rect3; diff --git a/core/math/bsp_tree.cpp b/core/math/bsp_tree.cpp index 5242abfa3bc..6f1343d28b4 100644 --- a/core/math/bsp_tree.cpp +++ b/core/math/bsp_tree.cpp @@ -30,32 +30,31 @@ #include "error_macros.h" #include "print_string.h" - -void BSP_Tree::from_aabb(const AABB& p_aabb) { +void BSP_Tree::from_aabb(const AABB &p_aabb) { planes.clear(); - for(int i=0;i<3;i++) { + for (int i = 0; i < 3; i++) { Vector3 n; - n[i]=1; - planes.push_back(Plane(n,p_aabb.pos[i]+p_aabb.size[i])); - planes.push_back(Plane(-n,-p_aabb.pos[i])); + n[i] = 1; + planes.push_back(Plane(n, p_aabb.pos[i] + p_aabb.size[i])); + planes.push_back(Plane(-n, -p_aabb.pos[i])); } nodes.clear(); - for(int i=0;i<6;i++) { + for (int i = 0; i < 6; i++) { Node n; - n.plane=i; - n.under=(i==0)?UNDER_LEAF:i-1; - n.over=OVER_LEAF; + n.plane = i; + n.under = (i == 0) ? UNDER_LEAF : i - 1; + n.over = OVER_LEAF; nodes.push_back(n); } - aabb=p_aabb; - error_radius=0; + aabb = p_aabb; + error_radius = 0; } Vector BSP_Tree::get_nodes() const { @@ -72,143 +71,136 @@ AABB BSP_Tree::get_aabb() const { return aabb; } -int BSP_Tree::_get_points_inside(int p_node,const Vector3* p_points,int *p_indices, const Vector3& p_center,const Vector3& p_half_extents,int p_indices_count) const { +int BSP_Tree::_get_points_inside(int p_node, const Vector3 *p_points, int *p_indices, const Vector3 &p_center, const Vector3 &p_half_extents, int p_indices_count) const { - - const Node *node =&nodes[p_node]; + const Node *node = &nodes[p_node]; const Plane &p = planes[node->plane]; Vector3 min( - (p.normal.x>0) ? -p_half_extents.x : p_half_extents.x, - (p.normal.y>0) ? -p_half_extents.y : p_half_extents.y, - (p.normal.z>0) ? -p_half_extents.z : p_half_extents.z - ); - Vector3 max=-min; - max+=p_center; - min+=p_center; + (p.normal.x > 0) ? -p_half_extents.x : p_half_extents.x, + (p.normal.y > 0) ? -p_half_extents.y : p_half_extents.y, + (p.normal.z > 0) ? -p_half_extents.z : p_half_extents.z); + Vector3 max = -min; + max += p_center; + min += p_center; float dist_min = p.distance_to(min); float dist_max = p.distance_to(max); - if ((dist_min * dist_max) < CMP_EPSILON ) { //intersection, test point by point + if ((dist_min * dist_max) < CMP_EPSILON) { //intersection, test point by point - - int under_count=0; + int under_count = 0; //sort points, so the are under first, over last - for(int i=0;i0) { - if (node->under==UNDER_LEAF) { - total+=under_count; + if (under_count > 0) { + if (node->under == UNDER_LEAF) { + total += under_count; } else { - total+=_get_points_inside(node->under,p_points,p_indices,p_center,p_half_extents,under_count); + total += _get_points_inside(node->under, p_points, p_indices, p_center, p_half_extents, under_count); } } - if (under_count!=p_indices_count) { - if (node->over==OVER_LEAF) { + if (under_count != p_indices_count) { + if (node->over == OVER_LEAF) { //total+=0 //if they are over an OVER_LEAF, they are outside the model } else { - total+=_get_points_inside(node->over,p_points,&p_indices[under_count],p_center,p_half_extents,p_indices_count-under_count); + total += _get_points_inside(node->over, p_points, &p_indices[under_count], p_center, p_half_extents, p_indices_count - under_count); } } return total; - } else if (dist_min > 0 ) { //all points over plane + } else if (dist_min > 0) { //all points over plane - if (node->over==OVER_LEAF) { + if (node->over == OVER_LEAF) { return 0; // all these points are not visible } + return _get_points_inside(node->over, p_points, p_indices, p_center, p_half_extents, p_indices_count); + } else if (dist_min <= 0) { //all points behind plane - return _get_points_inside(node->over,p_points,p_indices,p_center,p_half_extents,p_indices_count); - } else if (dist_min <= 0 ) { //all points behind plane - - if (node->under==UNDER_LEAF) { + if (node->under == UNDER_LEAF) { return p_indices_count; // all these points are visible } - return _get_points_inside(node->under,p_points,p_indices,p_center,p_half_extents,p_indices_count); + return _get_points_inside(node->under, p_points, p_indices, p_center, p_half_extents, p_indices_count); } return 0; } -int BSP_Tree::get_points_inside(const Vector3* p_points,int p_point_count) const { +int BSP_Tree::get_points_inside(const Vector3 *p_points, int p_point_count) const { - - if (nodes.size()==0) + if (nodes.size() == 0) return 0; #if 1 -//this version is easier to debug, and and MUCH faster in real world cases + //this version is easier to debug, and and MUCH faster in real world cases int pass_count = 0; - const Node *nodesptr=&nodes[0]; - const Plane *planesptr=&planes[0]; - int plane_count=planes.size(); - int node_count=nodes.size(); + const Node *nodesptr = &nodes[0]; + const Plane *planesptr = &planes[0]; + int plane_count = planes.size(); + int node_count = nodes.size(); - if (node_count==0) // no nodes! + if (node_count == 0) // no nodes! return 0; - for(int i=0;i=node_count, false ); + ERR_FAIL_COND_V(idx < MAX_NODES && idx >= node_count, false); #endif - } if (pass) @@ -218,69 +210,65 @@ int BSP_Tree::get_points_inside(const Vector3* p_points,int p_point_count) const return pass_count; #else -//this version scales better but it's slower for real world cases + //this version scales better but it's slower for real world cases - int *indices = (int*)alloca(p_point_count*sizeof(int)); + int *indices = (int *)alloca(p_point_count * sizeof(int)); AABB bounds; - for(int i=0;i=node_count, false ); + ERR_FAIL_COND_V(idx < MAX_NODES && idx >= node_count, false); #endif steps++; @@ -289,44 +277,42 @@ bool BSP_Tree::point_is_inside(const Vector3& p_point) const { return false; } - -static int _bsp_find_best_half_plane(const Face3* p_faces,const Vector& p_indices,float p_tolerance) { +static int _bsp_find_best_half_plane(const Face3 *p_faces, const Vector &p_indices, float p_tolerance) { int ic = p_indices.size(); - const int*indices=p_indices.ptr(); + const int *indices = p_indices.ptr(); int best_plane = -1; float best_plane_cost = 1e20; // Loop to find the polygon that best divides the set. - for (int i=0;ip_tolerance) { + if (Math::abs(d) > p_tolerance) { if (d > 0) over++; else under++; } - } if (over && under) @@ -335,13 +321,10 @@ static int _bsp_find_best_half_plane(const Face3* p_faces,const Vector& p_i num_over++; else num_under++; - } - - //double split_cost = num_spanning / (double) face_count; - double relation = Math::abs(num_over-num_under) / (double) ic; + double relation = Math::abs(num_over - num_under) / (double)ic; // being honest, i never found a way to add split cost to the mix in a meaninguful way // in this engine, also, will likely be ignored anyway @@ -349,57 +332,53 @@ static int _bsp_find_best_half_plane(const Face3* p_faces,const Vector& p_i double plane_cost = /*split_cost +*/ relation; //printf("plane %i, %i over, %i under, %i spanning, cost is %g\n",i,num_over,num_under,num_spanning,plane_cost); - if (plane_cost &p_indices, Vector &p_planes, Vector &p_nodes, float p_tolerance) { -static int _bsp_create_node(const Face3 *p_faces,const Vector& p_indices,Vector &p_planes, Vector &p_nodes,float p_tolerance) { - - ERR_FAIL_COND_V( p_nodes.size() == BSP_Tree::MAX_NODES, -1 ); + ERR_FAIL_COND_V(p_nodes.size() == BSP_Tree::MAX_NODES, -1); // should not reach here - ERR_FAIL_COND_V( p_indices.size() == 0, -1 ) + ERR_FAIL_COND_V(p_indices.size() == 0, -1) int ic = p_indices.size(); - const int*indices=p_indices.ptr(); + const int *indices = p_indices.ptr(); - int divisor_idx = _bsp_find_best_half_plane(p_faces,p_indices,p_tolerance); + int divisor_idx = _bsp_find_best_half_plane(p_faces, p_indices, p_tolerance); // returned error - ERR_FAIL_COND_V( divisor_idx<0 , -1 ); - + ERR_FAIL_COND_V(divisor_idx < 0, -1); Vector faces_over; Vector faces_under; - Plane divisor_plane=p_faces[ indices[divisor_idx] ].get_plane(); + Plane divisor_plane = p_faces[indices[divisor_idx]].get_plane(); - for (int i=0;ip_tolerance) { + if (Math::abs(d) > p_tolerance) { if (d > 0) over_count++; @@ -409,183 +388,169 @@ static int _bsp_create_node(const Face3 *p_faces,const Vector& p_indices,Ve } if (over_count) - faces_over.push_back( indices[i] ); + faces_over.push_back(indices[i]); if (under_count) - faces_under.push_back( indices[i] ); - + faces_under.push_back(indices[i]); } + uint16_t over_idx = BSP_Tree::OVER_LEAF, under_idx = BSP_Tree::UNDER_LEAF; + if (faces_over.size() > 0) { //have facess above? - uint16_t over_idx=BSP_Tree::OVER_LEAF,under_idx=BSP_Tree::UNDER_LEAF; - - if (faces_over.size()>0) { //have facess above? - - int idx = _bsp_create_node( p_faces, faces_over, p_planes, p_nodes,p_tolerance ); - if (idx>=0) - over_idx=idx; + int idx = _bsp_create_node(p_faces, faces_over, p_planes, p_nodes, p_tolerance); + if (idx >= 0) + over_idx = idx; } - if (faces_under.size()>0) { //have facess above? + if (faces_under.size() > 0) { //have facess above? - int idx = _bsp_create_node( p_faces,faces_under, p_planes, p_nodes,p_tolerance ); - if (idx>=0) - under_idx=idx; + int idx = _bsp_create_node(p_faces, faces_under, p_planes, p_nodes, p_tolerance); + if (idx >= 0) + under_idx = idx; } /* Create the node */ // find existing divisor plane - int divisor_plane_idx=-1; + int divisor_plane_idx = -1; + for (int i = 0; i < p_planes.size(); i++) { - for (int i=0;i plane_values; - plane_values.resize(planes.size()*4); + plane_values.resize(planes.size() * 4); - for(int i=0;i dst_nodes; - dst_nodes.resize(nodes.size()*3); + dst_nodes.resize(nodes.size() * 3); - for(int i=0;i src_nodes = d["nodes"]; - ERR_FAIL_COND(src_nodes.size()%3); + ERR_FAIL_COND(src_nodes.size() % 3); + if (d["planes"].get_type() == Variant::REAL_ARRAY) { - if (d["planes"].get_type()==Variant::REAL_ARRAY) { - - DVector src_planes=d["planes"]; - int plane_count=src_planes.size(); - ERR_FAIL_COND(plane_count%4); - planes.resize(plane_count/4); + DVector src_planes = d["planes"]; + int plane_count = src_planes.size(); + ERR_FAIL_COND(plane_count % 4); + planes.resize(plane_count / 4); if (plane_count) { DVector::Read r = src_planes.read(); - for(int i=0;i::Read r = src_nodes.read(); - for(int i=0;i& p_faces,float p_error_radius) { +BSP_Tree::BSP_Tree(const DVector &p_faces, float p_error_radius) { // compute aabb - int face_count=p_faces.size(); - DVector::Read faces_r=p_faces.read(); + int face_count = p_faces.size(); + DVector::Read faces_r = p_faces.read(); const Face3 *facesptr = faces_r.ptr(); - - bool first=true; + bool first = true; Vector indices; - for (int i=0;i& p_faces,float p_error_radius) { } indices.push_back(i); - } - ERR_FAIL_COND( aabb.has_no_area() ); + ERR_FAIL_COND(aabb.has_no_area()); - int top = _bsp_create_node(faces_r.ptr(),indices,planes,nodes,aabb.get_longest_axis_size()*0.0001); + int top = _bsp_create_node(faces_r.ptr(), indices, planes, nodes, aabb.get_longest_axis_size() * 0.0001); - if (top<0) { + if (top < 0) { nodes.clear(); planes.clear(); - ERR_FAIL_COND( top < 0 ); + ERR_FAIL_COND(top < 0); } - - - - error_radius=p_error_radius; + error_radius = p_error_radius; } -BSP_Tree::BSP_Tree(const Vector &p_nodes, const Vector &p_planes, const AABB& p_aabb,float p_error_radius) { - - nodes=p_nodes; - planes=p_planes; - aabb=p_aabb; - error_radius=p_error_radius; +BSP_Tree::BSP_Tree(const Vector &p_nodes, const Vector &p_planes, const AABB &p_aabb, float p_error_radius) { + nodes = p_nodes; + planes = p_planes; + aabb = p_aabb; + error_radius = p_error_radius; } BSP_Tree::~BSP_Tree() { - - } diff --git a/core/math/bsp_tree.h b/core/math/bsp_tree.h index 3913e3d34ae..9cf9d2fdd48 100644 --- a/core/math/bsp_tree.h +++ b/core/math/bsp_tree.h @@ -29,25 +29,24 @@ #ifndef BSP_TREE_H #define BSP_TREE_H -#include "plane.h" #include "aabb.h" -#include "face3.h" -#include "vector.h" #include "dvector.h" -#include "variant.h" +#include "face3.h" #include "method_ptrcall.h" +#include "plane.h" +#include "variant.h" +#include "vector.h" /** @author Juan Linietsky */ class BSP_Tree { public: - enum { - UNDER_LEAF=0xFFFF, - OVER_LEAF=0xFFFE, - MAX_NODES=0xFFFE, - MAX_PLANES=(1<<16) + UNDER_LEAF = 0xFFFF, + OVER_LEAF = 0xFFFE, + MAX_NODES = 0xFFFE, + MAX_PLANES = (1 << 16) }; struct Node { @@ -57,7 +56,6 @@ public: uint16_t over; }; - private: // thanks to the properties of Vector, // this class can be assigned and passed around between threads @@ -68,95 +66,90 @@ private: AABB aabb; float error_radius; - int _get_points_inside(int p_node,const Vector3* p_points,int *p_indices, const Vector3& p_center,const Vector3& p_half_extents,int p_indices_count) const; + int _get_points_inside(int p_node, const Vector3 *p_points, int *p_indices, const Vector3 &p_center, const Vector3 &p_half_extents, int p_indices_count) const; - template - bool _test_convex(const Node* p_nodes, const Plane* p_planes,int p_current, const T& p_convex) const; + template + bool _test_convex(const Node *p_nodes, const Plane *p_planes, int p_current, const T &p_convex) const; public: - - bool is_empty() const { return nodes.size()==0; } + bool is_empty() const { return nodes.size() == 0; } Vector get_nodes() const; Vector get_planes() const; AABB get_aabb() const; - bool point_is_inside(const Vector3& p_point) const; - int get_points_inside(const Vector3* p_points, int p_point_count) const; - template - bool convex_is_inside(const T& p_convex) const; + bool point_is_inside(const Vector3 &p_point) const; + int get_points_inside(const Vector3 *p_points, int p_point_count) const; + template + bool convex_is_inside(const T &p_convex) const; operator Variant() const; - void from_aabb(const AABB& p_aabb); + void from_aabb(const AABB &p_aabb); BSP_Tree(); - BSP_Tree(const Variant& p_variant); - BSP_Tree(const DVector& p_faces,float p_error_radius=0); - BSP_Tree(const Vector &p_nodes, const Vector &p_planes, const AABB& p_aabb,float p_error_radius=0); + BSP_Tree(const Variant &p_variant); + BSP_Tree(const DVector &p_faces, float p_error_radius = 0); + BSP_Tree(const Vector &p_nodes, const Vector &p_planes, const AABB &p_aabb, float p_error_radius = 0); ~BSP_Tree(); - }; -template -bool BSP_Tree::_test_convex(const Node* p_nodes, const Plane* p_planes,int p_current, const T& p_convex) const { +template +bool BSP_Tree::_test_convex(const Node *p_nodes, const Plane *p_planes, int p_current, const T &p_convex) const { - if (p_current==UNDER_LEAF) + if (p_current == UNDER_LEAF) return true; - else if (p_current==OVER_LEAF) + else if (p_current == OVER_LEAF) return false; - bool collided=false; - const Node&n=p_nodes[p_current]; + bool collided = false; + const Node &n = p_nodes[p_current]; - const Plane& p=p_planes[n.plane]; + const Plane &p = p_planes[n.plane]; - float min,max; - p_convex.project_range(p.normal,min,max); + float min, max; + p_convex.project_range(p.normal, min, max); bool go_under = min < p.d; bool go_over = max >= p.d; - if (go_under && _test_convex(p_nodes,p_planes,n.under,p_convex)) - collided=true; - if (go_over && _test_convex(p_nodes,p_planes,n.over,p_convex)) - collided=true; + if (go_under && _test_convex(p_nodes, p_planes, n.under, p_convex)) + collided = true; + if (go_over && _test_convex(p_nodes, p_planes, n.over, p_convex)) + collided = true; return collided; - } -template -bool BSP_Tree::convex_is_inside(const T& p_convex) const { +template +bool BSP_Tree::convex_is_inside(const T &p_convex) const { int node_count = nodes.size(); - if (node_count==0) + if (node_count == 0) return false; - const Node* nodes=&this->nodes[0]; - const Plane* planes = &this->planes[0]; + const Node *nodes = &this->nodes[0]; + const Plane *planes = &this->planes[0]; - return _test_convex(nodes,planes,node_count-1,p_convex); + return _test_convex(nodes, planes, node_count - 1, p_convex); } - #ifdef PTRCALL_ENABLED - -template<> +template <> struct PtrToArg { - _FORCE_INLINE_ static BSP_Tree convert(const void* p_ptr) { - BSP_Tree s( Variant( *reinterpret_cast(p_ptr) ) ); + _FORCE_INLINE_ static BSP_Tree convert(const void *p_ptr) { + BSP_Tree s(Variant(*reinterpret_cast(p_ptr))); return s; } - _FORCE_INLINE_ static void encode(BSP_Tree p_val,void* p_ptr) { - Dictionary *d = reinterpret_cast(p_ptr); - *d=Variant(p_val); + _FORCE_INLINE_ static void encode(BSP_Tree p_val, void *p_ptr) { + Dictionary *d = reinterpret_cast(p_ptr); + *d = Variant(p_val); } }; -template<> -struct PtrToArg { - _FORCE_INLINE_ static BSP_Tree convert(const void* p_ptr) { - BSP_Tree s( Variant( *reinterpret_cast(p_ptr) ) ); +template <> +struct PtrToArg { + _FORCE_INLINE_ static BSP_Tree convert(const void *p_ptr) { + BSP_Tree s(Variant(*reinterpret_cast(p_ptr))); return s; } }; diff --git a/core/math/camera_matrix.cpp b/core/math/camera_matrix.cpp index a62409ac08a..212ad9aea15 100644 --- a/core/math/camera_matrix.cpp +++ b/core/math/camera_matrix.cpp @@ -32,29 +32,27 @@ void CameraMatrix::set_identity() { - for (int i=0;i<4;i++) { + for (int i = 0; i < 4; i++) { - for (int j=0;j<4;j++) { + for (int j = 0; j < 4; j++) { - matrix[i][j]=(i==j)?1:0; + matrix[i][j] = (i == j) ? 1 : 0; } } } - void CameraMatrix::set_zero() { - for (int i=0;i<4;i++) { + for (int i = 0; i < 4; i++) { - for (int j=0;j<4;j++) { + for (int j = 0; j < 4; j++) { - matrix[i][j]=0; + matrix[i][j] = 0; } } } - -Plane CameraMatrix::xform4(const Plane& p_vec4) { +Plane CameraMatrix::xform4(const Plane &p_vec4) { Plane ret; @@ -65,11 +63,10 @@ Plane CameraMatrix::xform4(const Plane& p_vec4) { return ret; } -void CameraMatrix::set_perspective(float p_fovy_degrees, float p_aspect, float p_z_near, float p_z_far,bool p_flip_fov) { +void CameraMatrix::set_perspective(float p_fovy_degrees, float p_aspect, float p_z_near, float p_z_far, bool p_flip_fov) { if (p_flip_fov) { - p_fovy_degrees=get_fovy(p_fovy_degrees,1.0/p_aspect); - + p_fovy_degrees = get_fovy(p_fovy_degrees, 1.0 / p_aspect); } float sine, cotangent, deltaZ; @@ -78,8 +75,8 @@ void CameraMatrix::set_perspective(float p_fovy_degrees, float p_aspect, float p deltaZ = p_z_far - p_z_near; sine = Math::sin(radians); - if ((deltaZ == 0) || (sine == 0) || (p_aspect == 0)) { - return ; + if ((deltaZ == 0) || (sine == 0) || (p_aspect == 0)) { + return; } cotangent = Math::cos(radians) / sine; @@ -91,35 +88,30 @@ void CameraMatrix::set_perspective(float p_fovy_degrees, float p_aspect, float p matrix[2][3] = -1; matrix[3][2] = -2 * p_z_near * p_z_far / deltaZ; matrix[3][3] = 0; - } -void CameraMatrix::set_orthogonal(float p_left, float p_right, float p_bottom, float p_top, float p_znear, float p_zfar) { - +void CameraMatrix::set_orthogonal(float p_left, float p_right, float p_bottom, float p_top, float p_znear, float p_zfar) { set_identity(); - matrix[0][0] = 2.0/(p_right-p_left); - matrix[3][0] = -((p_right+p_left)/(p_right-p_left)); - matrix[1][1] = 2.0/(p_top-p_bottom); - matrix[3][1] = -((p_top+p_bottom)/(p_top-p_bottom)); - matrix[2][2] = -2.0/(p_zfar-p_znear); - matrix[3][2] = -((p_zfar+p_znear)/(p_zfar-p_znear)); + matrix[0][0] = 2.0 / (p_right - p_left); + matrix[3][0] = -((p_right + p_left) / (p_right - p_left)); + matrix[1][1] = 2.0 / (p_top - p_bottom); + matrix[3][1] = -((p_top + p_bottom) / (p_top - p_bottom)); + matrix[2][2] = -2.0 / (p_zfar - p_znear); + matrix[3][2] = -((p_zfar + p_znear) / (p_zfar - p_znear)); matrix[3][3] = 1.0; - } -void CameraMatrix::set_orthogonal(float p_size, float p_aspect, float p_znear, float p_zfar,bool p_flip_fov) { +void CameraMatrix::set_orthogonal(float p_size, float p_aspect, float p_znear, float p_zfar, bool p_flip_fov) { if (!p_flip_fov) { - p_size*=p_aspect; + p_size *= p_aspect; } - set_orthogonal(-p_size/2,+p_size/2,-p_size/p_aspect/2,+p_size/p_aspect/2,p_znear,p_zfar); + set_orthogonal(-p_size / 2, +p_size / 2, -p_size / p_aspect / 2, +p_size / p_aspect / 2, p_znear, p_zfar); } - - void CameraMatrix::set_frustum(float p_left, float p_right, float p_bottom, float p_top, float p_near, float p_far) { #if 0 ///@TODO, give a check to this. I'm not sure if it's working. @@ -135,13 +127,13 @@ void CameraMatrix::set_frustum(float p_left, float p_right, float p_bottom, floa matrix[3][3]=0; #else float *te = &matrix[0][0]; - float x = 2 * p_near / ( p_right - p_left ); - float y = 2 * p_near / ( p_top - p_bottom ); + float x = 2 * p_near / (p_right - p_left); + float y = 2 * p_near / (p_top - p_bottom); - float a = ( p_right + p_left ) / ( p_right - p_left ); - float b = ( p_top + p_bottom ) / ( p_top - p_bottom ); - float c = - ( p_far + p_near ) / ( p_far - p_near ); - float d = - 2 * p_far * p_near / ( p_far - p_near ); + float a = (p_right + p_left) / (p_right - p_left); + float b = (p_top + p_bottom) / (p_top - p_bottom); + float c = -(p_far + p_near) / (p_far - p_near); + float d = -2 * p_far * p_near / (p_far - p_near); te[0] = x; te[1] = 0; @@ -161,120 +153,117 @@ void CameraMatrix::set_frustum(float p_left, float p_right, float p_bottom, floa te[15] = 0; #endif - } - - float CameraMatrix::get_z_far() const { - const float * matrix = (const float*)this->matrix; - Plane new_plane=Plane(matrix[ 3] - matrix[ 2], - matrix[ 7] - matrix[ 6], - matrix[11] - matrix[10], - matrix[15] - matrix[14]); + const float *matrix = (const float *)this->matrix; + Plane new_plane = Plane(matrix[3] - matrix[2], + matrix[7] - matrix[6], + matrix[11] - matrix[10], + matrix[15] - matrix[14]); - new_plane.normal=-new_plane.normal; + new_plane.normal = -new_plane.normal; new_plane.normalize(); return new_plane.d; } float CameraMatrix::get_z_near() const { - const float * matrix = (const float*)this->matrix; - Plane new_plane=Plane(matrix[ 3] + matrix[ 2], - matrix[ 7] + matrix[ 6], - matrix[11] + matrix[10], - -matrix[15] - matrix[14]); + const float *matrix = (const float *)this->matrix; + Plane new_plane = Plane(matrix[3] + matrix[2], + matrix[7] + matrix[6], + matrix[11] + matrix[10], + -matrix[15] - matrix[14]); new_plane.normalize(); return new_plane.d; } -void CameraMatrix::get_viewport_size(float& r_width, float& r_height) const { +void CameraMatrix::get_viewport_size(float &r_width, float &r_height) const { - const float * matrix = (const float*)this->matrix; + const float *matrix = (const float *)this->matrix; ///////--- Near Plane ---/////// - Plane near_plane=Plane(matrix[ 3] + matrix[ 2], - matrix[ 7] + matrix[ 6], - matrix[11] + matrix[10], + Plane near_plane = Plane(matrix[3] + matrix[2], + matrix[7] + matrix[6], + matrix[11] + matrix[10], -matrix[15] - matrix[14]); near_plane.normalize(); ///////--- Right Plane ---/////// - Plane right_plane=Plane(matrix[ 3] - matrix[ 0], - matrix[ 7] - matrix[ 4], - matrix[11] - matrix[ 8], - - matrix[15] + matrix[12]); + Plane right_plane = Plane(matrix[3] - matrix[0], + matrix[7] - matrix[4], + matrix[11] - matrix[8], + -matrix[15] + matrix[12]); right_plane.normalize(); - Plane top_plane=Plane(matrix[ 3] - matrix[ 1], - matrix[ 7] - matrix[ 5], - matrix[11] - matrix[ 9], + Plane top_plane = Plane(matrix[3] - matrix[1], + matrix[7] - matrix[5], + matrix[11] - matrix[9], -matrix[15] + matrix[13]); top_plane.normalize(); Vector3 res; - near_plane.intersect_3(right_plane,top_plane,&res); + near_plane.intersect_3(right_plane, top_plane, &res); - r_width=res.x; - r_height=res.y; + r_width = res.x; + r_height = res.y; } -bool CameraMatrix::get_endpoints(const Transform& p_transform, Vector3 *p_8points) const { +bool CameraMatrix::get_endpoints(const Transform &p_transform, Vector3 *p_8points) const { - const float * matrix = (const float*)this->matrix; + const float *matrix = (const float *)this->matrix; ///////--- Near Plane ---/////// - Plane near_plane=Plane(matrix[ 3] + matrix[ 2], - matrix[ 7] + matrix[ 6], - matrix[11] + matrix[10], + Plane near_plane = Plane(matrix[3] + matrix[2], + matrix[7] + matrix[6], + matrix[11] + matrix[10], -matrix[15] - matrix[14]); near_plane.normalize(); ///////--- Far Plane ---/////// - Plane far_plane=Plane(matrix[ 2] - matrix[ 3], - matrix[ 6] - matrix[ 7], - matrix[10] - matrix[11], - matrix[15] - matrix[14]); + Plane far_plane = Plane(matrix[2] - matrix[3], + matrix[6] - matrix[7], + matrix[10] - matrix[11], + matrix[15] - matrix[14]); far_plane.normalize(); ///////--- Right Plane ---/////// - Plane right_plane=Plane(matrix[ 0] - matrix[ 3], - matrix[ 4] - matrix[ 7], - matrix[8] - matrix[ 11], - - matrix[15] + matrix[12]); + Plane right_plane = Plane(matrix[0] - matrix[3], + matrix[4] - matrix[7], + matrix[8] - matrix[11], + -matrix[15] + matrix[12]); right_plane.normalize(); ///////--- Top Plane ---/////// - Plane top_plane=Plane(matrix[ 1] - matrix[ 3], - matrix[ 5] - matrix[ 7], - matrix[9] - matrix[ 11], + Plane top_plane = Plane(matrix[1] - matrix[3], + matrix[5] - matrix[7], + matrix[9] - matrix[11], -matrix[15] + matrix[13]); top_plane.normalize(); Vector3 near_endpoint; Vector3 far_endpoint; - bool res=near_plane.intersect_3(right_plane,top_plane,&near_endpoint); - ERR_FAIL_COND_V(!res,false); + bool res = near_plane.intersect_3(right_plane, top_plane, &near_endpoint); + ERR_FAIL_COND_V(!res, false); - res=far_plane.intersect_3(right_plane,top_plane,&far_endpoint); - ERR_FAIL_COND_V(!res,false); + res = far_plane.intersect_3(right_plane, top_plane, &far_endpoint); + ERR_FAIL_COND_V(!res, false); - p_8points[0]=p_transform.xform( Vector3( near_endpoint.x, near_endpoint.y, near_endpoint.z ) ); - p_8points[1]=p_transform.xform( Vector3( near_endpoint.x,-near_endpoint.y, near_endpoint.z ) ); - p_8points[2]=p_transform.xform( Vector3(-near_endpoint.x, near_endpoint.y, near_endpoint.z ) ); - p_8points[3]=p_transform.xform( Vector3(-near_endpoint.x,-near_endpoint.y, near_endpoint.z ) ); - p_8points[4]=p_transform.xform( Vector3( far_endpoint.x, far_endpoint.y, far_endpoint.z ) ); - p_8points[5]=p_transform.xform( Vector3( far_endpoint.x,-far_endpoint.y, far_endpoint.z ) ); - p_8points[6]=p_transform.xform( Vector3(-far_endpoint.x, far_endpoint.y, far_endpoint.z ) ); - p_8points[7]=p_transform.xform( Vector3(-far_endpoint.x,-far_endpoint.y, far_endpoint.z ) ); + p_8points[0] = p_transform.xform(Vector3(near_endpoint.x, near_endpoint.y, near_endpoint.z)); + p_8points[1] = p_transform.xform(Vector3(near_endpoint.x, -near_endpoint.y, near_endpoint.z)); + p_8points[2] = p_transform.xform(Vector3(-near_endpoint.x, near_endpoint.y, near_endpoint.z)); + p_8points[3] = p_transform.xform(Vector3(-near_endpoint.x, -near_endpoint.y, near_endpoint.z)); + p_8points[4] = p_transform.xform(Vector3(far_endpoint.x, far_endpoint.y, far_endpoint.z)); + p_8points[5] = p_transform.xform(Vector3(far_endpoint.x, -far_endpoint.y, far_endpoint.z)); + p_8points[6] = p_transform.xform(Vector3(-far_endpoint.x, far_endpoint.y, far_endpoint.z)); + p_8points[7] = p_transform.xform(Vector3(-far_endpoint.x, -far_endpoint.y, far_endpoint.z)); return true; } -Vector CameraMatrix::get_projection_planes(const Transform& p_transform) const { +Vector CameraMatrix::get_projection_planes(const Transform &p_transform) const { /** Fast Plane Extraction from combined modelview/projection matrices. * References: @@ -284,88 +273,79 @@ Vector CameraMatrix::get_projection_planes(const Transform& p_transform) Vector planes; - const float * matrix = (const float*)this->matrix; + const float *matrix = (const float *)this->matrix; Plane new_plane; ///////--- Near Plane ---/////// - new_plane=Plane(matrix[ 3] + matrix[ 2], - matrix[ 7] + matrix[ 6], - matrix[11] + matrix[10], - matrix[15] + matrix[14]); + new_plane = Plane(matrix[3] + matrix[2], + matrix[7] + matrix[6], + matrix[11] + matrix[10], + matrix[15] + matrix[14]); - new_plane.normal=-new_plane.normal; + new_plane.normal = -new_plane.normal; new_plane.normalize(); - planes.push_back( p_transform.xform(new_plane) ); + planes.push_back(p_transform.xform(new_plane)); ///////--- Far Plane ---/////// - new_plane=Plane(matrix[ 3] - matrix[ 2], - matrix[ 7] - matrix[ 6], - matrix[11] - matrix[10], - matrix[15] - matrix[14]); + new_plane = Plane(matrix[3] - matrix[2], + matrix[7] - matrix[6], + matrix[11] - matrix[10], + matrix[15] - matrix[14]); - new_plane.normal=-new_plane.normal; + new_plane.normal = -new_plane.normal; new_plane.normalize(); - planes.push_back( p_transform.xform(new_plane) ); - + planes.push_back(p_transform.xform(new_plane)); ///////--- Left Plane ---/////// - new_plane=Plane(matrix[ 3] + matrix[ 0], - matrix[ 7] + matrix[ 4], - matrix[11] + matrix[ 8], - matrix[15] + matrix[12]); + new_plane = Plane(matrix[3] + matrix[0], + matrix[7] + matrix[4], + matrix[11] + matrix[8], + matrix[15] + matrix[12]); - new_plane.normal=-new_plane.normal; + new_plane.normal = -new_plane.normal; new_plane.normalize(); - planes.push_back( p_transform.xform(new_plane) ); - + planes.push_back(p_transform.xform(new_plane)); ///////--- Top Plane ---/////// - new_plane=Plane(matrix[ 3] - matrix[ 1], - matrix[ 7] - matrix[ 5], - matrix[11] - matrix[ 9], - matrix[15] - matrix[13]); + new_plane = Plane(matrix[3] - matrix[1], + matrix[7] - matrix[5], + matrix[11] - matrix[9], + matrix[15] - matrix[13]); - - new_plane.normal=-new_plane.normal; + new_plane.normal = -new_plane.normal; new_plane.normalize(); - planes.push_back( p_transform.xform(new_plane) ); - + planes.push_back(p_transform.xform(new_plane)); ///////--- Right Plane ---/////// - new_plane=Plane(matrix[ 3] - matrix[ 0], - matrix[ 7] - matrix[ 4], - matrix[11] - matrix[ 8], - matrix[15] - matrix[12]); + new_plane = Plane(matrix[3] - matrix[0], + matrix[7] - matrix[4], + matrix[11] - matrix[8], + matrix[15] - matrix[12]); - - new_plane.normal=-new_plane.normal; + new_plane.normal = -new_plane.normal; new_plane.normalize(); - planes.push_back( p_transform.xform(new_plane) ); - + planes.push_back(p_transform.xform(new_plane)); ///////--- Bottom Plane ---/////// - new_plane=Plane(matrix[ 3] + matrix[ 1], - matrix[ 7] + matrix[ 5], - matrix[11] + matrix[ 9], - matrix[15] + matrix[13]); + new_plane = Plane(matrix[3] + matrix[1], + matrix[7] + matrix[5], + matrix[11] + matrix[9], + matrix[15] + matrix[13]); - - new_plane.normal=-new_plane.normal; + new_plane.normal = -new_plane.normal; new_plane.normalize(); - planes.push_back( p_transform.xform(new_plane) ); + planes.push_back(p_transform.xform(new_plane)); return planes; } - - CameraMatrix CameraMatrix::inverse() const { CameraMatrix cm = *this; @@ -375,98 +355,96 @@ CameraMatrix CameraMatrix::inverse() const { void CameraMatrix::invert() { - int i,j,k; - int pvt_i[4], pvt_j[4]; /* Locations of pivot matrix */ - float pvt_val; /* Value of current pivot element */ - float hold; /* Temporary storage */ - float determinat; /* Determinant */ + int i, j, k; + int pvt_i[4], pvt_j[4]; /* Locations of pivot matrix */ + float pvt_val; /* Value of current pivot element */ + float hold; /* Temporary storage */ + float determinat; /* Determinant */ determinat = 1.0; - for (k=0; k<4; k++) { + for (k = 0; k < 4; k++) { /** Locate k'th pivot element **/ - pvt_val=matrix[k][k]; /** Initialize for search **/ - pvt_i[k]=k; - pvt_j[k]=k; - for (i=k; i<4; i++) { - for (j=k; j<4; j++) { + pvt_val = matrix[k][k]; /** Initialize for search **/ + pvt_i[k] = k; + pvt_j[k] = k; + for (i = k; i < 4; i++) { + for (j = k; j < 4; j++) { if (Math::absd(matrix[i][j]) > Math::absd(pvt_val)) { - pvt_i[k]=i; - pvt_j[k]=j; - pvt_val=matrix[i][j]; + pvt_i[k] = i; + pvt_j[k] = j; + pvt_val = matrix[i][j]; } } } /** Product of pivots, gives determinant when finished **/ - determinat*=pvt_val; - if (Math::absd(determinat)<1e-7) { + determinat *= pvt_val; + if (Math::absd(determinat) < 1e-7) { return; //(false); /** Matrix is singular (zero determinant). **/ } /** "Interchange" rows (with sign change stuff) **/ - i=pvt_i[k]; - if (i!=k) { /** If rows are different **/ - for (j=0; j<4; j++) { - hold=-matrix[k][j]; - matrix[k][j]=matrix[i][j]; - matrix[i][j]=hold; + i = pvt_i[k]; + if (i != k) { /** If rows are different **/ + for (j = 0; j < 4; j++) { + hold = -matrix[k][j]; + matrix[k][j] = matrix[i][j]; + matrix[i][j] = hold; } } /** "Interchange" columns **/ - j=pvt_j[k]; - if (j!=k) { /** If columns are different **/ - for (i=0; i<4; i++) { - hold=-matrix[i][k]; - matrix[i][k]=matrix[i][j]; - matrix[i][j]=hold; + j = pvt_j[k]; + if (j != k) { /** If columns are different **/ + for (i = 0; i < 4; i++) { + hold = -matrix[i][k]; + matrix[i][k] = matrix[i][j]; + matrix[i][j] = hold; } } /** Divide column by minus pivot value **/ - for (i=0; i<4; i++) { - if (i!=k) matrix[i][k]/=( -pvt_val) ; + for (i = 0; i < 4; i++) { + if (i != k) matrix[i][k] /= (-pvt_val); } /** Reduce the matrix **/ - for (i=0; i<4; i++) { + for (i = 0; i < 4; i++) { hold = matrix[i][k]; - for (j=0; j<4; j++) { - if (i!=k && j!=k) matrix[i][j]+=hold*matrix[k][j]; + for (j = 0; j < 4; j++) { + if (i != k && j != k) matrix[i][j] += hold * matrix[k][j]; } } /** Divide row by pivot **/ - for (j=0; j<4; j++) { - if (j!=k) matrix[k][j]/=pvt_val; + for (j = 0; j < 4; j++) { + if (j != k) matrix[k][j] /= pvt_val; } /** Replace pivot by reciprocal (at last we can touch it). **/ - matrix[k][k] = 1.0/pvt_val; + matrix[k][k] = 1.0 / pvt_val; } /* That was most of the work, one final pass of row/column interchange */ /* to finish */ - for (k=4-2; k>=0; k--) { /* Don't need to work with 1 by 1 corner*/ - i=pvt_j[k]; /* Rows to swap correspond to pivot COLUMN */ - if (i!=k) { /* If rows are different */ - for(j=0; j<4; j++) { + for (k = 4 - 2; k >= 0; k--) { /* Don't need to work with 1 by 1 corner*/ + i = pvt_j[k]; /* Rows to swap correspond to pivot COLUMN */ + if (i != k) { /* If rows are different */ + for (j = 0; j < 4; j++) { hold = matrix[k][j]; - matrix[k][j]=-matrix[i][j]; - matrix[i][j]=hold; + matrix[k][j] = -matrix[i][j]; + matrix[i][j] = hold; } } - j=pvt_i[k]; /* Columns to swap correspond to pivot ROW */ - if (j!=k) /* If columns are different */ - for (i=0; i<4; i++) { - hold=matrix[i][k]; - matrix[i][k]=-matrix[i][j]; - matrix[i][j]=hold; + j = pvt_i[k]; /* Columns to swap correspond to pivot ROW */ + if (j != k) /* If columns are different */ + for (i = 0; i < 4; i++) { + hold = matrix[i][k]; + matrix[i][k] = -matrix[i][j]; + matrix[i][j] = hold; } } - - } CameraMatrix::CameraMatrix() { @@ -474,15 +452,15 @@ CameraMatrix::CameraMatrix() { set_identity(); } -CameraMatrix CameraMatrix::operator*(const CameraMatrix& p_matrix) const { +CameraMatrix CameraMatrix::operator*(const CameraMatrix &p_matrix) const { CameraMatrix new_matrix; - for( int j = 0; j < 4; j++ ) { - for( int i = 0; i < 4; i++ ) { + for (int j = 0; j < 4; j++) { + for (int i = 0; i < 4; i++) { real_t ab = 0; - for( int k = 0; k < 4; k++ ) - ab += matrix[k][i] * p_matrix.matrix[j][k] ; + for (int k = 0; k < 4; k++) + ab += matrix[k][i] * p_matrix.matrix[j][k]; new_matrix.matrix[j][i] = ab; } } @@ -492,142 +470,135 @@ CameraMatrix CameraMatrix::operator*(const CameraMatrix& p_matrix) const { void CameraMatrix::set_light_bias() { - float *m=&matrix[0][0]; - - m[0]=0.5, - m[1]=0.0, - m[2]=0.0, - m[3]=0.0, - m[4]=0.0, - m[5]=0.5, - m[6]=0.0, - m[7]=0.0, - m[8]=0.0, - m[9]=0.0, - m[10]=0.5, - m[11]=0.0, - m[12]=0.5, - m[13]=0.5, - m[14]=0.5, - m[15]=1.0; + float *m = &matrix[0][0]; + m[0] = 0.5, + m[1] = 0.0, + m[2] = 0.0, + m[3] = 0.0, + m[4] = 0.0, + m[5] = 0.5, + m[6] = 0.0, + m[7] = 0.0, + m[8] = 0.0, + m[9] = 0.0, + m[10] = 0.5, + m[11] = 0.0, + m[12] = 0.5, + m[13] = 0.5, + m[14] = 0.5, + m[15] = 1.0; } CameraMatrix::operator String() const { String str; - for (int i=0;i<4;i++) - for (int j=0;j<4;j++) - str+=String((j>0)?", ":"\n")+rtos(matrix[i][j]); + for (int i = 0; i < 4; i++) + for (int j = 0; j < 4; j++) + str += String((j > 0) ? ", " : "\n") + rtos(matrix[i][j]); return str; } float CameraMatrix::get_aspect() const { - float w,h; - get_viewport_size(w,h); - return w/h; + float w, h; + get_viewport_size(w, h); + return w / h; } float CameraMatrix::get_fov() const { - const float * matrix = (const float*)this->matrix; + const float *matrix = (const float *)this->matrix; - Plane right_plane=Plane(matrix[ 3] - matrix[ 0], - matrix[ 7] - matrix[ 4], - matrix[11] - matrix[ 8], - - matrix[15] + matrix[12]); + Plane right_plane = Plane(matrix[3] - matrix[0], + matrix[7] - matrix[4], + matrix[11] - matrix[8], + -matrix[15] + matrix[12]); right_plane.normalize(); - return Math::rad2deg(Math::acos(Math::abs(right_plane.normal.x)))*2.0; + return Math::rad2deg(Math::acos(Math::abs(right_plane.normal.x))) * 2.0; } - void CameraMatrix::make_scale(const Vector3 &p_scale) { set_identity(); - matrix[0][0]=p_scale.x; - matrix[1][1]=p_scale.y; - matrix[2][2]=p_scale.z; - + matrix[0][0] = p_scale.x; + matrix[1][1] = p_scale.y; + matrix[2][2] = p_scale.z; } -void CameraMatrix::scale_translate_to_fit(const AABB& p_aabb) { +void CameraMatrix::scale_translate_to_fit(const AABB &p_aabb) { Vector3 min = p_aabb.pos; - Vector3 max = p_aabb.pos+p_aabb.size; + Vector3 max = p_aabb.pos + p_aabb.size; + matrix[0][0] = 2 / (max.x - min.x); + matrix[1][0] = 0; + matrix[2][0] = 0; + matrix[3][0] = -(max.x + min.x) / (max.x - min.x); - matrix[0][0]=2/(max.x-min.x); - matrix[1][0]=0; - matrix[2][0]=0; - matrix[3][0]=-(max.x+min.x)/(max.x-min.x); + matrix[0][1] = 0; + matrix[1][1] = 2 / (max.y - min.y); + matrix[2][1] = 0; + matrix[3][1] = -(max.y + min.y) / (max.y - min.y); - matrix[0][1]=0; - matrix[1][1]=2/(max.y-min.y); - matrix[2][1]=0; - matrix[3][1]=-(max.y+min.y)/(max.y-min.y); + matrix[0][2] = 0; + matrix[1][2] = 0; + matrix[2][2] = 2 / (max.z - min.z); + matrix[3][2] = -(max.z + min.z) / (max.z - min.z); - matrix[0][2]=0; - matrix[1][2]=0; - matrix[2][2]=2/(max.z-min.z); - matrix[3][2]=-(max.z+min.z)/(max.z-min.z); - - matrix[0][3]=0; - matrix[1][3]=0; - matrix[2][3]=0; - matrix[3][3]=1; + matrix[0][3] = 0; + matrix[1][3] = 0; + matrix[2][3] = 0; + matrix[3][3] = 1; } CameraMatrix::operator Transform() const { Transform tr; - const float *m=&matrix[0][0]; + const float *m = &matrix[0][0]; - tr.basis.elements[0][0]=m[0]; - tr.basis.elements[1][0]=m[1]; - tr.basis.elements[2][0]=m[2]; + tr.basis.elements[0][0] = m[0]; + tr.basis.elements[1][0] = m[1]; + tr.basis.elements[2][0] = m[2]; - tr.basis.elements[0][1]=m[4]; - tr.basis.elements[1][1]=m[5]; - tr.basis.elements[2][1]=m[6]; + tr.basis.elements[0][1] = m[4]; + tr.basis.elements[1][1] = m[5]; + tr.basis.elements[2][1] = m[6]; - tr.basis.elements[0][2]=m[8]; - tr.basis.elements[1][2]=m[9]; - tr.basis.elements[2][2]=m[10]; + tr.basis.elements[0][2] = m[8]; + tr.basis.elements[1][2] = m[9]; + tr.basis.elements[2][2] = m[10]; - tr.origin.x=m[12]; - tr.origin.y=m[13]; - tr.origin.z=m[14]; + tr.origin.x = m[12]; + tr.origin.y = m[13]; + tr.origin.z = m[14]; return tr; } -CameraMatrix::CameraMatrix(const Transform& p_transform) { +CameraMatrix::CameraMatrix(const Transform &p_transform) { const Transform &tr = p_transform; - float *m=&matrix[0][0]; + float *m = &matrix[0][0]; - m[0]=tr.basis.elements[0][0]; - m[1]=tr.basis.elements[1][0]; - m[2]=tr.basis.elements[2][0]; - m[3]=0.0; - m[4]=tr.basis.elements[0][1]; - m[5]=tr.basis.elements[1][1]; - m[6]=tr.basis.elements[2][1]; - m[7]=0.0; - m[8]=tr.basis.elements[0][2]; - m[9]=tr.basis.elements[1][2]; - m[10]=tr.basis.elements[2][2]; - m[11]=0.0; - m[12]=tr.origin.x; - m[13]=tr.origin.y; - m[14]=tr.origin.z; - m[15]=1.0; + m[0] = tr.basis.elements[0][0]; + m[1] = tr.basis.elements[1][0]; + m[2] = tr.basis.elements[2][0]; + m[3] = 0.0; + m[4] = tr.basis.elements[0][1]; + m[5] = tr.basis.elements[1][1]; + m[6] = tr.basis.elements[2][1]; + m[7] = 0.0; + m[8] = tr.basis.elements[0][2]; + m[9] = tr.basis.elements[1][2]; + m[10] = tr.basis.elements[2][2]; + m[11] = 0.0; + m[12] = tr.origin.x; + m[13] = tr.origin.y; + m[14] = tr.origin.z; + m[15] = 1.0; } -CameraMatrix::~CameraMatrix() -{ +CameraMatrix::~CameraMatrix() { } - - diff --git a/core/math/camera_matrix.h b/core/math/camera_matrix.h index 246a5faba51..e989278e4f0 100644 --- a/core/math/camera_matrix.h +++ b/core/math/camera_matrix.h @@ -34,8 +34,6 @@ @author Juan Linietsky */ - - struct CameraMatrix { enum Planes { @@ -47,20 +45,19 @@ struct CameraMatrix { PLANE_BOTTOM }; - float matrix[4][4]; - + float matrix[4][4]; void set_identity(); void set_zero(); void set_light_bias(); - void set_perspective(float p_fovy_degrees, float p_aspect, float p_z_near, float p_z_far,bool p_flip_fov=false); - void set_orthogonal(float p_left, float p_right, float p_bottom, float p_top, float p_znear, float p_zfar); - void set_orthogonal(float p_size, float p_aspect, float p_znear, float p_zfar,bool p_flip_fov=false); + void set_perspective(float p_fovy_degrees, float p_aspect, float p_z_near, float p_z_far, bool p_flip_fov = false); + void set_orthogonal(float p_left, float p_right, float p_bottom, float p_top, float p_znear, float p_zfar); + void set_orthogonal(float p_size, float p_aspect, float p_znear, float p_zfar, bool p_flip_fov = false); void set_frustum(float p_left, float p_right, float p_bottom, float p_top, float p_near, float p_far); - static float get_fovy(float p_fovx,float p_aspect) { + static float get_fovy(float p_fovx, float p_aspect) { - return Math::rad2deg(Math::atan(p_aspect * Math::tan(Math::deg2rad(p_fovx) * 0.5))*2.0); + return Math::rad2deg(Math::atan(p_aspect * Math::tan(Math::deg2rad(p_fovx) * 0.5)) * 2.0); } float get_z_far() const; @@ -68,39 +65,38 @@ struct CameraMatrix { float get_aspect() const; float get_fov() const; - Vector get_projection_planes(const Transform& p_transform) const; + Vector get_projection_planes(const Transform &p_transform) const; - bool get_endpoints(const Transform& p_transform,Vector3 *p_8points) const; - void get_viewport_size(float& r_width, float& r_height) const; + bool get_endpoints(const Transform &p_transform, Vector3 *p_8points) const; + void get_viewport_size(float &r_width, float &r_height) const; void invert(); CameraMatrix inverse() const; - CameraMatrix operator*(const CameraMatrix& p_matrix) const; + CameraMatrix operator*(const CameraMatrix &p_matrix) const; - Plane xform4(const Plane& p_vec4); - _FORCE_INLINE_ Vector3 xform(const Vector3& p_vec3) const; + Plane xform4(const Plane &p_vec4); + _FORCE_INLINE_ Vector3 xform(const Vector3 &p_vec3) const; operator String() const; - void scale_translate_to_fit(const AABB& p_aabb); + void scale_translate_to_fit(const AABB &p_aabb); void make_scale(const Vector3 &p_scale); operator Transform() const; CameraMatrix(); - CameraMatrix(const Transform& p_transform); + CameraMatrix(const Transform &p_transform); ~CameraMatrix(); - }; -Vector3 CameraMatrix::xform(const Vector3& p_vec3) const { +Vector3 CameraMatrix::xform(const Vector3 &p_vec3) const { Vector3 ret; ret.x = matrix[0][0] * p_vec3.x + matrix[1][0] * p_vec3.y + matrix[2][0] * p_vec3.z + matrix[3][0]; ret.y = matrix[0][1] * p_vec3.x + matrix[1][1] * p_vec3.y + matrix[2][1] * p_vec3.z + matrix[3][1]; ret.z = matrix[0][2] * p_vec3.x + matrix[1][2] * p_vec3.y + matrix[2][2] * p_vec3.z + matrix[3][2]; float w = matrix[0][3] * p_vec3.x + matrix[1][3] * p_vec3.y + matrix[2][3] * p_vec3.z + matrix[3][3]; - return ret/w; + return ret / w; } #endif diff --git a/core/math/face3.cpp b/core/math/face3.cpp index 1024143ba18..f41c6c92e0a 100644 --- a/core/math/face3.cpp +++ b/core/math/face3.cpp @@ -29,121 +29,112 @@ #include "face3.h" #include "geometry.h" -int Face3::split_by_plane(const Plane& p_plane,Face3 p_res[3],bool p_is_point_over[3]) const { +int Face3::split_by_plane(const Plane &p_plane, Face3 p_res[3], bool p_is_point_over[3]) const { - ERR_FAIL_COND_V(is_degenerate(),0); + ERR_FAIL_COND_V(is_degenerate(), 0); - - Vector3 above[4]; - int above_count=0; + Vector3 above[4]; + int above_count = 0; Vector3 below[4]; - int below_count=0; + int below_count = 0; - for (int i=0;i<3;i++) { + for (int i = 0; i < 3; i++) { - if (p_plane.has_point( vertex[i], CMP_EPSILON )) { // point is in plane + if (p_plane.has_point(vertex[i], CMP_EPSILON)) { // point is in plane - ERR_FAIL_COND_V(above_count>=4,0); - above[above_count++]=vertex[i]; - ERR_FAIL_COND_V(below_count>=4,0); - below[below_count++]=vertex[i]; + ERR_FAIL_COND_V(above_count >= 4, 0); + above[above_count++] = vertex[i]; + ERR_FAIL_COND_V(below_count >= 4, 0); + below[below_count++] = vertex[i]; } else { - if (p_plane.is_point_over( vertex[i])) { + if (p_plane.is_point_over(vertex[i])) { //Point is over - ERR_FAIL_COND_V(above_count>=4,0); - above[above_count++]=vertex[i]; + ERR_FAIL_COND_V(above_count >= 4, 0); + above[above_count++] = vertex[i]; } else { //Point is under - ERR_FAIL_COND_V(below_count>=4,0); - below[below_count++]=vertex[i]; + ERR_FAIL_COND_V(below_count >= 4, 0); + below[below_count++] = vertex[i]; } /* Check for Intersection between this and the next vertex*/ Vector3 inters; - if (!p_plane.intersects_segment( vertex[i],vertex[(i+1)%3],&inters)) + if (!p_plane.intersects_segment(vertex[i], vertex[(i + 1) % 3], &inters)) continue; /* Intersection goes to both */ - ERR_FAIL_COND_V(above_count>=4,0); - above[above_count++]=inters; - ERR_FAIL_COND_V(below_count>=4,0); - below[below_count++]=inters; + ERR_FAIL_COND_V(above_count >= 4, 0); + above[above_count++] = inters; + ERR_FAIL_COND_V(below_count >= 4, 0); + below[below_count++] = inters; } } - int polygons_created=0; + int polygons_created = 0; - ERR_FAIL_COND_V( above_count>=4 && below_count>=4 , 0 ); //bug in the algo + ERR_FAIL_COND_V(above_count >= 4 && below_count >= 4, 0); //bug in the algo - if (above_count>=3) { + if (above_count >= 3) { - p_res[polygons_created]=Face3( above[0], above[1], above[2] ); - p_is_point_over[polygons_created]=true; + p_res[polygons_created] = Face3(above[0], above[1], above[2]); + p_is_point_over[polygons_created] = true; polygons_created++; - if (above_count==4) { + if (above_count == 4) { - p_res[polygons_created]=Face3( above[2], above[3], above[0] ); - p_is_point_over[polygons_created]=true; + p_res[polygons_created] = Face3(above[2], above[3], above[0]); + p_is_point_over[polygons_created] = true; polygons_created++; - } } - if (below_count>=3) { + if (below_count >= 3) { - p_res[polygons_created]=Face3( below[0], below[1], below[2] ); - p_is_point_over[polygons_created]=false; + p_res[polygons_created] = Face3(below[0], below[1], below[2]); + p_is_point_over[polygons_created] = false; polygons_created++; - if (below_count==4) { + if (below_count == 4) { - p_res[polygons_created]=Face3( below[2], below[3], below[0] ); - p_is_point_over[polygons_created]=false; + p_res[polygons_created] = Face3(below[2], below[3], below[0]); + p_is_point_over[polygons_created] = false; polygons_created++; - } } return polygons_created; } +bool Face3::intersects_ray(const Vector3 &p_from, const Vector3 &p_dir, Vector3 *p_intersection) const { - -bool Face3::intersects_ray(const Vector3& p_from,const Vector3& p_dir,Vector3 * p_intersection) const { - - return Geometry::ray_intersects_triangle(p_from,p_dir,vertex[0],vertex[1],vertex[2],p_intersection); - + return Geometry::ray_intersects_triangle(p_from, p_dir, vertex[0], vertex[1], vertex[2], p_intersection); } -bool Face3::intersects_segment(const Vector3& p_from,const Vector3& p_dir,Vector3 * p_intersection) const { - - return Geometry::segment_intersects_triangle(p_from,p_dir,vertex[0],vertex[1],vertex[2],p_intersection); +bool Face3::intersects_segment(const Vector3 &p_from, const Vector3 &p_dir, Vector3 *p_intersection) const { + return Geometry::segment_intersects_triangle(p_from, p_dir, vertex[0], vertex[1], vertex[2], p_intersection); } - bool Face3::is_degenerate() const { - Vector3 normal=vec3_cross(vertex[0]-vertex[1], vertex[0]-vertex[2]); + Vector3 normal = vec3_cross(vertex[0] - vertex[1], vertex[0] - vertex[2]); return (normal.length_squared() < CMP_EPSILON2); } +Face3::Side Face3::get_side_of(const Face3 &p_face, ClockDirection p_clock_dir) const { -Face3::Side Face3::get_side_of(const Face3& p_face,ClockDirection p_clock_dir) const { + int over = 0, under = 0; - int over=0,under=0; + Plane plane = get_plane(p_clock_dir); - Plane plane=get_plane(p_clock_dir); + for (int i = 0; i < 3; i++) { - for (int i=0;i<3;i++) { - - const Vector3 &v=p_face.vertex[i]; + const Vector3 &v = p_face.vertex[i]; if (plane.has_point(v)) //coplanar, dont bother continue; @@ -152,81 +143,73 @@ Face3::Side Face3::get_side_of(const Face3& p_face,ClockDirection p_clock_dir) c over++; else under++; - } - if ( over > 0 && under == 0 ) + if (over > 0 && under == 0) return SIDE_OVER; - else if (under > 0 && over ==0 ) + else if (under > 0 && over == 0) return SIDE_UNDER; - else if (under ==0 && over == 0) + else if (under == 0 && over == 0) return SIDE_COPLANAR; else return SIDE_SPANNING; - } Vector3 Face3::get_random_point_inside() const { - float a=Math::random(0,1); - float b=Math::random(0,1); - if (a>b) { - SWAP(a,b); + float a = Math::random(0, 1); + float b = Math::random(0, 1); + if (a > b) { + SWAP(a, b); } - return vertex[0]*a + vertex[1]*(b-a) + vertex[2]*(1.0-b); - + return vertex[0] * a + vertex[1] * (b - a) + vertex[2] * (1.0 - b); } Plane Face3::get_plane(ClockDirection p_dir) const { - return Plane( vertex[0], vertex[1], vertex[2] , p_dir ); - + return Plane(vertex[0], vertex[1], vertex[2], p_dir); } Vector3 Face3::get_median_point() const { - return (vertex[0] + vertex[1] + vertex[2])/3.0; + return (vertex[0] + vertex[1] + vertex[2]) / 3.0; } - real_t Face3::get_area() const { - return vec3_cross(vertex[0]-vertex[1], vertex[0]-vertex[2]).length(); + return vec3_cross(vertex[0] - vertex[1], vertex[0] - vertex[2]).length(); } ClockDirection Face3::get_clock_dir() const { - - Vector3 normal=vec3_cross(vertex[0]-vertex[1], vertex[0]-vertex[2]); + Vector3 normal = vec3_cross(vertex[0] - vertex[1], vertex[0] - vertex[2]); //printf("normal is %g,%g,%g x %g,%g,%g- wtfu is %g\n",tofloat(normal.x),tofloat(normal.y),tofloat(normal.z),tofloat(vertex[0].x),tofloat(vertex[0].y),tofloat(vertex[0].z),tofloat( normal.dot( vertex[0] ) ) ); - return ( normal.dot( vertex[0] ) >= 0 ) ? CLOCKWISE : COUNTERCLOCKWISE; - + return (normal.dot(vertex[0]) >= 0) ? CLOCKWISE : COUNTERCLOCKWISE; } - -bool Face3::intersects_aabb(const AABB& p_aabb) const { +bool Face3::intersects_aabb(const AABB &p_aabb) const { /** TEST PLANE **/ - if (!p_aabb.intersects_plane( get_plane() )) + if (!p_aabb.intersects_plane(get_plane())) return false; - /** TEST FACE AXIS */ +/** TEST FACE AXIS */ -#define TEST_AXIS(m_ax)\ - {\ - float aabb_min=p_aabb.pos.m_ax;\ - float aabb_max=p_aabb.pos.m_ax+p_aabb.size.m_ax;\ - float tri_min,tri_max;\ - for (int i=0;i<3;i++) {\ - if (i==0 || vertex[i].m_ax > tri_max)\ - tri_max=vertex[i].m_ax;\ - if (i==0 || vertex[i].m_ax < tri_min)\ - tri_min=vertex[i].m_ax;\ - }\ -\ - if (tri_max tri_max) \ + tri_max = vertex[i].m_ax; \ + if (i == 0 || vertex[i].m_ax < tri_min) \ + tri_min = vertex[i].m_ax; \ + } \ + \ + if (tri_max < aabb_min || aabb_max < tri_min) \ + return false; \ } TEST_AXIS(x); @@ -235,221 +218,188 @@ bool Face3::intersects_aabb(const AABB& p_aabb) const { /** TEST ALL EDGES **/ - Vector3 edge_norms[3]={ - vertex[0]-vertex[1], - vertex[1]-vertex[2], - vertex[2]-vertex[0], + Vector3 edge_norms[3] = { + vertex[0] - vertex[1], + vertex[1] - vertex[2], + vertex[2] - vertex[0], }; - for (int i=0;i<12;i++) { + for (int i = 0; i < 12; i++) { - Vector3 from,to; - p_aabb.get_edge(i,from,to); - Vector3 e1=from-to; - for (int j=0;j<3;j++) { - Vector3 e2=edge_norms[j]; + Vector3 from, to; + p_aabb.get_edge(i, from, to); + Vector3 e1 = from - to; + for (int j = 0; j < 3; j++) { + Vector3 e2 = edge_norms[j]; - Vector3 axis=vec3_cross( e1, e2 ); + Vector3 axis = vec3_cross(e1, e2); - if (axis.length_squared()<0.0001) + if (axis.length_squared() < 0.0001) continue; // coplanar axis.normalize(); - float minA,maxA,minB,maxB; - p_aabb.project_range_in_plane(Plane(axis,0),minA,maxA); - project_range(axis,Transform(),minB,maxB); + float minA, maxA, minB, maxB; + p_aabb.project_range_in_plane(Plane(axis, 0), minA, maxA); + project_range(axis, Transform(), minB, maxB); - if (maxA r_max) - r_max=d; + if (i == 0 || d > r_max) + r_max = d; - if (i==0 || d < r_min) - r_min=d; + if (i == 0 || d < r_min) + r_min = d; } } - - -void Face3::get_support(const Vector3& p_normal,const Transform& p_transform,Vector3 *p_vertices,int* p_count,int p_max) const { +void Face3::get_support(const Vector3 &p_normal, const Transform &p_transform, Vector3 *p_vertices, int *p_count, int p_max) const { #define _FACE_IS_VALID_SUPPORT_TRESHOLD 0.98 #define _EDGE_IS_VALID_SUPPORT_TRESHOLD 0.05 - if (p_max<=0) + if (p_max <= 0) return; - Vector3 n=p_transform.basis.xform_inv(p_normal); + Vector3 n = p_transform.basis.xform_inv(p_normal); /** TEST FACE AS SUPPORT **/ if (get_plane().normal.dot(n) > _FACE_IS_VALID_SUPPORT_TRESHOLD) { - *p_count=MIN(3,p_max); + *p_count = MIN(3, p_max); - for (int i=0;i<*p_count;i++) { + for (int i = 0; i < *p_count; i++) { - p_vertices[i]=p_transform.xform(vertex[i]); + p_vertices[i] = p_transform.xform(vertex[i]); } return; - } /** FIND SUPPORT VERTEX **/ - int vert_support_idx=-1; + int vert_support_idx = -1; float support_max; - for (int i=0;i<3;i++) { + for (int i = 0; i < 3; i++) { - float d=n.dot(vertex[i]); + float d = n.dot(vertex[i]); - if (i==0 || d > support_max) { - support_max=d; - vert_support_idx=i; + if (i == 0 || d > support_max) { + support_max = d; + vert_support_idx = i; } } /** TEST EDGES AS SUPPORT **/ - for (int i=0;i<3;i++) { + for (int i = 0; i < 3; i++) { - if (i!=vert_support_idx && i+1!=vert_support_idx) + if (i != vert_support_idx && i + 1 != vert_support_idx) continue; - // check if edge is valid as a support - float dot=(vertex[i]-vertex[(i+1)%3]).normalized().dot(n); - dot=ABS(dot); + // check if edge is valid as a support + float dot = (vertex[i] - vertex[(i + 1) % 3]).normalized().dot(n); + dot = ABS(dot); if (dot < _EDGE_IS_VALID_SUPPORT_TRESHOLD) { - *p_count=MIN(2,p_max); + *p_count = MIN(2, p_max); - for (int j=0;j<*p_count;j++) - p_vertices[j]=p_transform.xform(vertex[(j+i)%3]); + for (int j = 0; j < *p_count; j++) + p_vertices[j] = p_transform.xform(vertex[(j + i) % 3]); return; } } - - *p_count=1; - p_vertices[0]=p_transform.xform(vertex[vert_support_idx]); - + *p_count = 1; + p_vertices[0] = p_transform.xform(vertex[vert_support_idx]); } +Vector3 Face3::get_closest_point_to(const Vector3 &p_point) const { -Vector3 Face3::get_closest_point_to(const Vector3& p_point) const { + Vector3 edge0 = vertex[1] - vertex[0]; + Vector3 edge1 = vertex[2] - vertex[0]; + Vector3 v0 = vertex[0] - p_point; - Vector3 edge0 = vertex[1] - vertex[0]; - Vector3 edge1 = vertex[2] - vertex[0]; - Vector3 v0 = vertex[0] - p_point; + float a = edge0.dot(edge0); + float b = edge0.dot(edge1); + float c = edge1.dot(edge1); + float d = edge0.dot(v0); + float e = edge1.dot(v0); - float a = edge0.dot( edge0 ); - float b = edge0.dot( edge1 ); - float c = edge1.dot( edge1 ); - float d = edge0.dot( v0 ); - float e = edge1.dot( v0 ); + float det = a * c - b * b; + float s = b * e - c * d; + float t = b * d - a * e; - float det = a*c - b*b; - float s = b*e - c*d; - float t = b*d - a*e; - - if ( s + t < det ) - { - if ( s < 0.f ) - { - if ( t < 0.f ) - { - if ( d < 0.f ) - { - s = CLAMP( -d/a, 0.f, 1.f ); - t = 0.f; + if (s + t < det) { + if (s < 0.f) { + if (t < 0.f) { + if (d < 0.f) { + s = CLAMP(-d / a, 0.f, 1.f); + t = 0.f; + } else { + s = 0.f; + t = CLAMP(-e / c, 0.f, 1.f); + } + } else { + s = 0.f; + t = CLAMP(-e / c, 0.f, 1.f); } - else - { - s = 0.f; - t = CLAMP( -e/c, 0.f, 1.f ); - } - } - else - { - s = 0.f; - t = CLAMP( -e/c, 0.f, 1.f ); - } - } - else if ( t < 0.f ) - { - s = CLAMP( -d/a, 0.f, 1.f ); - t = 0.f; - } - else - { - float invDet = 1.f / det; - s *= invDet; - t *= invDet; - } - } - else - { - if ( s < 0.f ) - { - float tmp0 = b+d; - float tmp1 = c+e; - if ( tmp1 > tmp0 ) - { - float numer = tmp1 - tmp0; - float denom = a-2*b+c; - s = CLAMP( numer/denom, 0.f, 1.f ); - t = 1-s; - } - else - { - t = CLAMP( -e/c, 0.f, 1.f ); - s = 0.f; - } - } - else if ( t < 0.f ) - { - if ( a+d > b+e ) - { - float numer = c+e-b-d; - float denom = a-2*b+c; - s = CLAMP( numer/denom, 0.f, 1.f ); - t = 1-s; - } - else - { - s = CLAMP( -e/c, 0.f, 1.f ); + } else if (t < 0.f) { + s = CLAMP(-d / a, 0.f, 1.f); t = 0.f; - } + } else { + float invDet = 1.f / det; + s *= invDet; + t *= invDet; } - else - { - float numer = c+e-b-d; - float denom = a-2*b+c; - s = CLAMP( numer/denom, 0.f, 1.f ); - t = 1.f - s; + } else { + if (s < 0.f) { + float tmp0 = b + d; + float tmp1 = c + e; + if (tmp1 > tmp0) { + float numer = tmp1 - tmp0; + float denom = a - 2 * b + c; + s = CLAMP(numer / denom, 0.f, 1.f); + t = 1 - s; + } else { + t = CLAMP(-e / c, 0.f, 1.f); + s = 0.f; + } + } else if (t < 0.f) { + if (a + d > b + e) { + float numer = c + e - b - d; + float denom = a - 2 * b + c; + s = CLAMP(numer / denom, 0.f, 1.f); + t = 1 - s; + } else { + s = CLAMP(-e / c, 0.f, 1.f); + t = 0.f; + } + } else { + float numer = c + e - b - d; + float denom = a - 2 * b + c; + s = CLAMP(numer / denom, 0.f, 1.f); + t = 1.f - s; } - } - - return vertex[0] + s * edge0 + t * edge1; + } + return vertex[0] + s * edge0 + t * edge1; } diff --git a/core/math/face3.h b/core/math/face3.h index 4eade1217d0..3346fcca628 100644 --- a/core/math/face3.h +++ b/core/math/face3.h @@ -29,25 +29,23 @@ #ifndef FACE3_H #define FACE3_H -#include "vector3.h" -#include "plane.h" #include "aabb.h" +#include "plane.h" #include "transform.h" +#include "vector3.h" class Face3 { public: + enum Side { + SIDE_OVER, + SIDE_UNDER, + SIDE_SPANNING, + SIDE_COPLANAR + }; - enum Side { - SIDE_OVER, - SIDE_UNDER, - SIDE_SPANNING, - SIDE_COPLANAR - }; + Vector3 vertex[3]; - - Vector3 vertex[3]; - - /** + /** * * @param p_plane plane used to split the face * @param p_res array of at least 3 faces, amount used in functio return @@ -56,81 +54,80 @@ public: * @return amount of faces generated by the split, either 0 (means no split possible), 2 or 3 */ - int split_by_plane(const Plane& p_plane,Face3 *p_res,bool *p_is_point_over) const; + int split_by_plane(const Plane &p_plane, Face3 *p_res, bool *p_is_point_over) const; - Plane get_plane(ClockDirection p_dir=CLOCKWISE) const; + Plane get_plane(ClockDirection p_dir = CLOCKWISE) const; Vector3 get_random_point_inside() const; + Side get_side_of(const Face3 &p_face, ClockDirection p_clock_dir = CLOCKWISE) const; - Side get_side_of(const Face3& p_face,ClockDirection p_clock_dir=CLOCKWISE) const; - - bool is_degenerate() const; + bool is_degenerate() const; real_t get_area() const; - Vector3 get_median_point() const; - Vector3 get_closest_point_to(const Vector3& p_point) const; + Vector3 get_median_point() const; + Vector3 get_closest_point_to(const Vector3 &p_point) const; - bool intersects_ray(const Vector3& p_from,const Vector3& p_dir,Vector3 * p_intersection=0) const; - bool intersects_segment(const Vector3& p_from,const Vector3& p_dir,Vector3 * p_intersection=0) const; + bool intersects_ray(const Vector3 &p_from, const Vector3 &p_dir, Vector3 *p_intersection = 0) const; + bool intersects_segment(const Vector3 &p_from, const Vector3 &p_dir, Vector3 *p_intersection = 0) const; - ClockDirection get_clock_dir() const; ///< todo, test if this is returning the proper clockwisity + ClockDirection get_clock_dir() const; ///< todo, test if this is returning the proper clockwisity - void get_support(const Vector3& p_normal,const Transform& p_transform,Vector3 *p_vertices,int* p_count,int p_max) const; - void project_range(const Vector3& p_normal,const Transform& p_transform,float& r_min, float& r_max) const; + void get_support(const Vector3 &p_normal, const Transform &p_transform, Vector3 *p_vertices, int *p_count, int p_max) const; + void project_range(const Vector3 &p_normal, const Transform &p_transform, float &r_min, float &r_max) const; - AABB get_aabb() const { + AABB get_aabb() const { - AABB aabb( vertex[0], Vector3() ); - aabb.expand_to( vertex[1] ); - aabb.expand_to( vertex[2] ); - return aabb; - } + AABB aabb(vertex[0], Vector3()); + aabb.expand_to(vertex[1]); + aabb.expand_to(vertex[2]); + return aabb; + } - bool intersects_aabb(const AABB& p_aabb) const; - _FORCE_INLINE_ bool intersects_aabb2(const AABB& p_aabb) const; + bool intersects_aabb(const AABB &p_aabb) const; + _FORCE_INLINE_ bool intersects_aabb2(const AABB &p_aabb) const; operator String() const; - inline Face3() {} - inline Face3(const Vector3 &p_v1,const Vector3 &p_v2,const Vector3 &p_v3) { vertex[0]=p_v1; vertex[1]=p_v2; vertex[2]=p_v3; } - + inline Face3() {} + inline Face3(const Vector3 &p_v1, const Vector3 &p_v2, const Vector3 &p_v3) { + vertex[0] = p_v1; + vertex[1] = p_v2; + vertex[2] = p_v3; + } }; +bool Face3::intersects_aabb2(const AABB &p_aabb) const { -bool Face3::intersects_aabb2(const AABB& p_aabb) const { - - Vector3 perp = (vertex[0]-vertex[2]).cross(vertex[0]-vertex[1]); + Vector3 perp = (vertex[0] - vertex[2]).cross(vertex[0] - vertex[1]); Vector3 half_extents = p_aabb.size * 0.5; Vector3 ofs = p_aabb.pos + half_extents; - Vector3 sup =Vector3( - (perp.x>0) ? -half_extents.x : half_extents.x, - (perp.y>0) ? -half_extents.y : half_extents.y, - (perp.z>0) ? -half_extents.z : half_extents.z - ); + Vector3 sup = Vector3( + (perp.x > 0) ? -half_extents.x : half_extents.x, + (perp.y > 0) ? -half_extents.y : half_extents.y, + (perp.z > 0) ? -half_extents.z : half_extents.z); float d = perp.dot(vertex[0]); - float dist_a = perp.dot(ofs+sup)-d; - float dist_b = perp.dot(ofs-sup)-d; + float dist_a = perp.dot(ofs + sup) - d; + float dist_b = perp.dot(ofs - sup) - d; - if (dist_a*dist_b > 0) + if (dist_a * dist_b > 0) return false; //does not intersect the plane - -#define TEST_AXIS(m_ax)\ - {\ - float aabb_min=p_aabb.pos.m_ax;\ - float aabb_max=p_aabb.pos.m_ax+p_aabb.size.m_ax;\ - float tri_min,tri_max;\ - for (int i=0;i<3;i++) {\ - if (i==0 || vertex[i].m_ax > tri_max)\ - tri_max=vertex[i].m_ax;\ - if (i==0 || vertex[i].m_ax < tri_min)\ - tri_min=vertex[i].m_ax;\ - }\ -\ - if (tri_max tri_max) \ + tri_max = vertex[i].m_ax; \ + if (i == 0 || vertex[i].m_ax < tri_min) \ + tri_min = vertex[i].m_ax; \ + } \ + \ + if (tri_max < aabb_min || aabb_max < tri_min) \ + return false; \ } TEST_AXIS(x); @@ -139,131 +136,125 @@ bool Face3::intersects_aabb2(const AABB& p_aabb) const { #undef TEST_AXIS - - Vector3 edge_norms[3]={ - vertex[0]-vertex[1], - vertex[1]-vertex[2], - vertex[2]-vertex[0], + Vector3 edge_norms[3] = { + vertex[0] - vertex[1], + vertex[1] - vertex[2], + vertex[2] - vertex[0], }; - for (int i=0;i<12;i++) { + for (int i = 0; i < 12; i++) { - Vector3 from,to; - switch(i) { + Vector3 from, to; + switch (i) { - case 0:{ + case 0: { - from=Vector3( p_aabb.pos.x+p_aabb.size.x , p_aabb.pos.y , p_aabb.pos.z ); - to=Vector3( p_aabb.pos.x , p_aabb.pos.y , p_aabb.pos.z ); + from = Vector3(p_aabb.pos.x + p_aabb.size.x, p_aabb.pos.y, p_aabb.pos.z); + to = Vector3(p_aabb.pos.x, p_aabb.pos.y, p_aabb.pos.z); } break; - case 1:{ + case 1: { - from=Vector3( p_aabb.pos.x+p_aabb.size.x , p_aabb.pos.y , p_aabb.pos.z+p_aabb.size.z ); - to=Vector3( p_aabb.pos.x+p_aabb.size.x , p_aabb.pos.y , p_aabb.pos.z ); + from = Vector3(p_aabb.pos.x + p_aabb.size.x, p_aabb.pos.y, p_aabb.pos.z + p_aabb.size.z); + to = Vector3(p_aabb.pos.x + p_aabb.size.x, p_aabb.pos.y, p_aabb.pos.z); } break; - case 2:{ - from=Vector3( p_aabb.pos.x , p_aabb.pos.y , p_aabb.pos.z+p_aabb.size.z ); - to=Vector3( p_aabb.pos.x+p_aabb.size.x , p_aabb.pos.y , p_aabb.pos.z+p_aabb.size.z ); + case 2: { + from = Vector3(p_aabb.pos.x, p_aabb.pos.y, p_aabb.pos.z + p_aabb.size.z); + to = Vector3(p_aabb.pos.x + p_aabb.size.x, p_aabb.pos.y, p_aabb.pos.z + p_aabb.size.z); } break; - case 3:{ + case 3: { - from=Vector3( p_aabb.pos.x , p_aabb.pos.y , p_aabb.pos.z ); - to=Vector3( p_aabb.pos.x , p_aabb.pos.y , p_aabb.pos.z+p_aabb.size.z ); + from = Vector3(p_aabb.pos.x, p_aabb.pos.y, p_aabb.pos.z); + to = Vector3(p_aabb.pos.x, p_aabb.pos.y, p_aabb.pos.z + p_aabb.size.z); } break; - case 4:{ + case 4: { - from=Vector3( p_aabb.pos.x , p_aabb.pos.y+p_aabb.size.y , p_aabb.pos.z ); - to=Vector3( p_aabb.pos.x+p_aabb.size.x , p_aabb.pos.y+p_aabb.size.y , p_aabb.pos.z ); + from = Vector3(p_aabb.pos.x, p_aabb.pos.y + p_aabb.size.y, p_aabb.pos.z); + to = Vector3(p_aabb.pos.x + p_aabb.size.x, p_aabb.pos.y + p_aabb.size.y, p_aabb.pos.z); } break; - case 5:{ + case 5: { - from=Vector3( p_aabb.pos.x+p_aabb.size.x , p_aabb.pos.y+p_aabb.size.y , p_aabb.pos.z ); - to=Vector3( p_aabb.pos.x+p_aabb.size.x , p_aabb.pos.y+p_aabb.size.y , p_aabb.pos.z+p_aabb.size.z ); + from = Vector3(p_aabb.pos.x + p_aabb.size.x, p_aabb.pos.y + p_aabb.size.y, p_aabb.pos.z); + to = Vector3(p_aabb.pos.x + p_aabb.size.x, p_aabb.pos.y + p_aabb.size.y, p_aabb.pos.z + p_aabb.size.z); } break; - case 6:{ - from=Vector3( p_aabb.pos.x+p_aabb.size.x , p_aabb.pos.y+p_aabb.size.y , p_aabb.pos.z+p_aabb.size.z ); - to=Vector3( p_aabb.pos.x , p_aabb.pos.y+p_aabb.size.y , p_aabb.pos.z+p_aabb.size.z ); + case 6: { + from = Vector3(p_aabb.pos.x + p_aabb.size.x, p_aabb.pos.y + p_aabb.size.y, p_aabb.pos.z + p_aabb.size.z); + to = Vector3(p_aabb.pos.x, p_aabb.pos.y + p_aabb.size.y, p_aabb.pos.z + p_aabb.size.z); } break; - case 7:{ + case 7: { - from=Vector3( p_aabb.pos.x , p_aabb.pos.y+p_aabb.size.y , p_aabb.pos.z+p_aabb.size.z ); - to=Vector3( p_aabb.pos.x , p_aabb.pos.y+p_aabb.size.y , p_aabb.pos.z ); + from = Vector3(p_aabb.pos.x, p_aabb.pos.y + p_aabb.size.y, p_aabb.pos.z + p_aabb.size.z); + to = Vector3(p_aabb.pos.x, p_aabb.pos.y + p_aabb.size.y, p_aabb.pos.z); } break; - case 8:{ + case 8: { - from=Vector3( p_aabb.pos.x , p_aabb.pos.y , p_aabb.pos.z+p_aabb.size.z ); - to=Vector3( p_aabb.pos.x , p_aabb.pos.y+p_aabb.size.y , p_aabb.pos.z+p_aabb.size.z ); + from = Vector3(p_aabb.pos.x, p_aabb.pos.y, p_aabb.pos.z + p_aabb.size.z); + to = Vector3(p_aabb.pos.x, p_aabb.pos.y + p_aabb.size.y, p_aabb.pos.z + p_aabb.size.z); } break; - case 9:{ + case 9: { - from=Vector3( p_aabb.pos.x , p_aabb.pos.y , p_aabb.pos.z ); - to=Vector3( p_aabb.pos.x , p_aabb.pos.y+p_aabb.size.y , p_aabb.pos.z ); + from = Vector3(p_aabb.pos.x, p_aabb.pos.y, p_aabb.pos.z); + to = Vector3(p_aabb.pos.x, p_aabb.pos.y + p_aabb.size.y, p_aabb.pos.z); } break; - case 10:{ + case 10: { - from=Vector3( p_aabb.pos.x+p_aabb.size.x , p_aabb.pos.y , p_aabb.pos.z ); - to=Vector3( p_aabb.pos.x+p_aabb.size.x , p_aabb.pos.y+p_aabb.size.y , p_aabb.pos.z ); + from = Vector3(p_aabb.pos.x + p_aabb.size.x, p_aabb.pos.y, p_aabb.pos.z); + to = Vector3(p_aabb.pos.x + p_aabb.size.x, p_aabb.pos.y + p_aabb.size.y, p_aabb.pos.z); } break; - case 11:{ + case 11: { - from=Vector3( p_aabb.pos.x+p_aabb.size.x , p_aabb.pos.y , p_aabb.pos.z+p_aabb.size.z ); - to=Vector3( p_aabb.pos.x+p_aabb.size.x , p_aabb.pos.y+p_aabb.size.y , p_aabb.pos.z+p_aabb.size.z ); + from = Vector3(p_aabb.pos.x + p_aabb.size.x, p_aabb.pos.y, p_aabb.pos.z + p_aabb.size.z); + to = Vector3(p_aabb.pos.x + p_aabb.size.x, p_aabb.pos.y + p_aabb.size.y, p_aabb.pos.z + p_aabb.size.z); } break; - } - Vector3 e1=from-to; - for (int j=0;j<3;j++) { - Vector3 e2=edge_norms[j]; + Vector3 e1 = from - to; + for (int j = 0; j < 3; j++) { + Vector3 e2 = edge_norms[j]; - Vector3 axis=vec3_cross( e1, e2 ); + Vector3 axis = vec3_cross(e1, e2); - if (axis.length_squared()<0.0001) + if (axis.length_squared() < 0.0001) continue; // coplanar //axis.normalize(); - Vector3 sup2 =Vector3( - (axis.x>0) ? -half_extents.x : half_extents.x, - (axis.y>0) ? -half_extents.y : half_extents.y, - (axis.z>0) ? -half_extents.z : half_extents.z - ); + Vector3 sup2 = Vector3( + (axis.x > 0) ? -half_extents.x : half_extents.x, + (axis.y > 0) ? -half_extents.y : half_extents.y, + (axis.z > 0) ? -half_extents.z : half_extents.z); - float maxB = axis.dot(ofs+sup2); - float minB = axis.dot(ofs-sup2); - if (minB>maxB) { - SWAP(maxB,minB); + float maxB = axis.dot(ofs + sup2); + float minB = axis.dot(ofs - sup2); + if (minB > maxB) { + SWAP(maxB, minB); } - float minT=1e20,maxT=-1e20; - for (int k=0;k<3;k++) { + float minT = 1e20, maxT = -1e20; + for (int k = 0; k < 3; k++) { - float d=axis.dot(vertex[k]); + float d = axis.dot(vertex[k]); if (d > maxT) - maxT=d; + maxT = d; if (d < minT) - minT=d; + minT = d; } - if (maxB vtx_remap; + Map vtx_remap; - for(int i=0;i new_vertices; new_vertices.resize(vtx_remap.size()); - for(int i=0;i > (*Geometry::_decompose_func)(const Vector& p_polygon)=NULL; +Vector > (*Geometry::_decompose_func)(const Vector &p_polygon) = NULL; struct _FaceClassify { @@ -88,16 +84,22 @@ struct _FaceClassify { int face; int edge; - void clear() { face=-1; edge=-1; } - _Link() { face=-1; edge=-1; } + void clear() { + face = -1; + edge = -1; + } + _Link() { + face = -1; + edge = -1; + } }; bool valid; int group; _Link links[3]; Face3 face; _FaceClassify() { - group=-1; - valid=false; + group = -1; + valid = false; }; }; @@ -105,76 +107,73 @@ static bool _connect_faces(_FaceClassify *p_faces, int len, int p_group) { /* connect faces, error will occur if an edge is shared between more than 2 faces */ /* clear connections */ - bool error=false; + bool error = false; - for (int i=0;i=0) + if (p_faces[p_index].group >= 0) return false; - p_faces[p_index].group=p_group; + p_faces[p_index].group = p_group; - for (int i=0;i<3;i++) { + for (int i = 0; i < 3; i++) { - ERR_FAIL_INDEX_V(p_faces[p_index].links[i].face,len,true); - _group_face(p_faces,len,p_faces[p_index].links[i].face,p_group); + ERR_FAIL_INDEX_V(p_faces[p_index].links[i].face, len, true); + _group_face(p_faces, len, p_faces[p_index].links[i].face, p_group); } return true; } +DVector > Geometry::separate_objects(DVector p_array) { -DVector< DVector< Face3 > > Geometry::separate_objects( DVector< Face3 > p_array ) { - - DVector< DVector< Face3 > > objects; + DVector > objects; int len = p_array.size(); - DVector::Read r=p_array.read(); + DVector::Read r = p_array.read(); - const Face3* arrayptr = r.ptr(); + const Face3 *arrayptr = r.ptr(); - DVector< _FaceClassify> fc; + DVector<_FaceClassify> fc; - fc.resize( len ); + fc.resize(len); - DVector< _FaceClassify >::Write fcw=fc.write(); + DVector<_FaceClassify>::Write fcw = fc.write(); - _FaceClassify * _fcptr = fcw.ptr(); + _FaceClassify *_fcptr = fcw.ptr(); - for (int i=0;i >() ); // invalid geometry + ERR_FAIL_COND_V(error, DVector >()); // invalid geometry } /* group connected faces in separate objects */ - int group=0; - for (int i=0;i=0) { + if (group >= 0) { objects.resize(group); - DVector< DVector >::Write obw=objects.write(); - DVector< Face3 > *group_faces = obw.ptr(); + DVector >::Write obw = objects.write(); + DVector *group_faces = obw.ptr(); - for (int i=0;i=0 && _fcptr[i].group= 0 && _fcptr[i].group < group) { - group_faces[_fcptr[i].group].push_back( _fcptr[i].face ); + group_faces[_fcptr[i].group].push_back(_fcptr[i].face); } } } - return objects; - } /*** GEOMETRY WRAPPER ***/ enum _CellFlags { - _CELL_SOLID=1, - _CELL_EXTERIOR=2, - _CELL_STEP_MASK=0x1C, - _CELL_STEP_NONE=0<<2, - _CELL_STEP_Y_POS=1<<2, - _CELL_STEP_Y_NEG=2<<2, - _CELL_STEP_X_POS=3<<2, - _CELL_STEP_X_NEG=4<<2, - _CELL_STEP_Z_POS=5<<2, - _CELL_STEP_Z_NEG=6<<2, - _CELL_STEP_DONE=7<<2, - _CELL_PREV_MASK=0xE0, - _CELL_PREV_NONE=0<<5, - _CELL_PREV_Y_POS=1<<5, - _CELL_PREV_Y_NEG=2<<5, - _CELL_PREV_X_POS=3<<5, - _CELL_PREV_X_NEG=4<<5, - _CELL_PREV_Z_POS=5<<5, - _CELL_PREV_Z_NEG=6<<5, - _CELL_PREV_FIRST=7<<5, + _CELL_SOLID = 1, + _CELL_EXTERIOR = 2, + _CELL_STEP_MASK = 0x1C, + _CELL_STEP_NONE = 0 << 2, + _CELL_STEP_Y_POS = 1 << 2, + _CELL_STEP_Y_NEG = 2 << 2, + _CELL_STEP_X_POS = 3 << 2, + _CELL_STEP_X_NEG = 4 << 2, + _CELL_STEP_Z_POS = 5 << 2, + _CELL_STEP_Z_NEG = 6 << 2, + _CELL_STEP_DONE = 7 << 2, + _CELL_PREV_MASK = 0xE0, + _CELL_PREV_NONE = 0 << 5, + _CELL_PREV_Y_POS = 1 << 5, + _CELL_PREV_Y_NEG = 2 << 5, + _CELL_PREV_X_POS = 3 << 5, + _CELL_PREV_X_NEG = 4 << 5, + _CELL_PREV_Z_POS = 5 << 5, + _CELL_PREV_Z_NEG = 6 << 5, + _CELL_PREV_FIRST = 7 << 5, }; -static inline void _plot_face(uint8_t*** p_cell_status,int x,int y,int z,int len_x,int len_y,int len_z,const Vector3& voxelsize,const Face3& p_face) { +static inline void _plot_face(uint8_t ***p_cell_status, int x, int y, int z, int len_x, int len_y, int len_z, const Vector3 &voxelsize, const Face3 &p_face) { - AABB aabb( Vector3(x,y,z),Vector3(len_x,len_y,len_z)); - aabb.pos=aabb.pos*voxelsize; - aabb.size=aabb.size*voxelsize; + AABB aabb(Vector3(x, y, z), Vector3(len_x, len_y, len_z)); + aabb.pos = aabb.pos * voxelsize; + aabb.size = aabb.size * voxelsize; if (!p_face.intersects_aabb(aabb)) return; - if (len_x==1 && len_y==1 && len_z==1) { + if (len_x == 1 && len_y == 1 && len_z == 1) { - p_cell_status[x][y][z]=_CELL_SOLID; + p_cell_status[x][y][z] = _CELL_SOLID; return; } + int div_x = len_x > 1 ? 2 : 1; + int div_y = len_y > 1 ? 2 : 1; + int div_z = len_z > 1 ? 2 : 1; - - int div_x=len_x>1?2:1; - int div_y=len_y>1?2:1; - int div_z=len_z>1?2:1; - -#define _SPLIT(m_i,m_div,m_v,m_len_v,m_new_v,m_new_len_v)\ - if (m_div==1) {\ - m_new_v=m_v;\ - m_new_len_v=1; \ - } else if (m_i==0) {\ - m_new_v=m_v;\ - m_new_len_v=m_len_v/2;\ - } else {\ - m_new_v=m_v+m_len_v/2;\ - m_new_len_v=m_len_v-m_len_v/2; \ +#define _SPLIT(m_i, m_div, m_v, m_len_v, m_new_v, m_new_len_v) \ + if (m_div == 1) { \ + m_new_v = m_v; \ + m_new_len_v = 1; \ + } else if (m_i == 0) { \ + m_new_v = m_v; \ + m_new_len_v = m_len_v / 2; \ + } else { \ + m_new_v = m_v + m_len_v / 2; \ + m_new_len_v = m_len_v - m_len_v / 2; \ } int new_x; @@ -342,84 +335,83 @@ static inline void _plot_face(uint8_t*** p_cell_status,int x,int y,int z,int len int new_z; int new_len_z; - for (int i=0;i=len_y); + ERR_FAIL_COND(y >= len_y); } break; case _CELL_PREV_Y_NEG: { y--; - ERR_FAIL_COND(y<0); + ERR_FAIL_COND(y < 0); } break; case _CELL_PREV_X_POS: { x++; - ERR_FAIL_COND(x>=len_x); + ERR_FAIL_COND(x >= len_x); } break; case _CELL_PREV_X_NEG: { x--; - ERR_FAIL_COND(x<0); + ERR_FAIL_COND(x < 0); } break; case _CELL_PREV_Z_POS: { z++; - ERR_FAIL_COND(z>=len_z); + ERR_FAIL_COND(z >= len_z); } break; case _CELL_PREV_Z_NEG: { z--; - ERR_FAIL_COND(z<0); + ERR_FAIL_COND(z < 0); } break; default: { ERR_FAIL(); @@ -430,70 +422,69 @@ static inline void _mark_outside(uint8_t*** p_cell_status,int x,int y,int z,int //printf("attempting new cell!\n"); - int next_x=x,next_y=y,next_z=z; - uint8_t prev=0; + int next_x = x, next_y = y, next_z = z; + uint8_t prev = 0; - switch(c&_CELL_STEP_MASK) { + switch (c & _CELL_STEP_MASK) { case _CELL_STEP_Y_POS: { next_y++; - prev=_CELL_PREV_Y_NEG; + prev = _CELL_PREV_Y_NEG; } break; case _CELL_STEP_Y_NEG: { next_y--; - prev=_CELL_PREV_Y_POS; + prev = _CELL_PREV_Y_POS; } break; case _CELL_STEP_X_POS: { next_x++; - prev=_CELL_PREV_X_NEG; + prev = _CELL_PREV_X_NEG; } break; case _CELL_STEP_X_NEG: { next_x--; - prev=_CELL_PREV_X_POS; + prev = _CELL_PREV_X_POS; } break; case _CELL_STEP_Z_POS: { next_z++; - prev=_CELL_PREV_Z_NEG; + prev = _CELL_PREV_Z_NEG; } break; case _CELL_STEP_Z_NEG: { next_z--; - prev=_CELL_PREV_Z_POS; + prev = _CELL_PREV_Z_POS; } break; default: ERR_FAIL(); - } //printf("testing if new cell will be ok...!\n"); - if (next_x<0 || next_x>=len_x) + if (next_x < 0 || next_x >= len_x) continue; - if (next_y<0 || next_y>=len_y) + if (next_y < 0 || next_y >= len_y) continue; - if (next_z<0 || next_z>=len_z) + if (next_z < 0 || next_z >= len_z) continue; //printf("testing if new cell is traversable\n"); - if (p_cell_status[next_x][next_y][next_z]&3) + if (p_cell_status[next_x][next_y][next_z] & 3) continue; //printf("move to it\n"); - x=next_x; - y=next_y; - z=next_z; - p_cell_status[x][y][z]|=prev; + x = next_x; + y = next_y; + z = next_z; + p_cell_status[x][y][z] |= prev; } } -static inline void _build_faces(uint8_t*** p_cell_status,int x,int y,int z,int len_x,int len_y,int len_z,DVector& p_faces) { +static inline void _build_faces(uint8_t ***p_cell_status, int x, int y, int z, int len_x, int len_y, int len_z, DVector &p_faces) { - ERR_FAIL_INDEX(x,len_x); - ERR_FAIL_INDEX(y,len_y); - ERR_FAIL_INDEX(z,len_z); + ERR_FAIL_INDEX(x, len_x); + ERR_FAIL_INDEX(y, len_y); + ERR_FAIL_INDEX(z, len_z); - if (p_cell_status[x][y][z]&_CELL_EXTERIOR) + if (p_cell_status[x][y][z] & _CELL_EXTERIOR) return; /* static const Vector3 vertices[8]={ @@ -507,18 +498,18 @@ static inline void _build_faces(uint8_t*** p_cell_status,int x,int y,int z,int l Vector3(1,1,1), }; */ -#define vert(m_idx) Vector3( (m_idx&4)>>2, (m_idx&2)>>1, m_idx&1 ) +#define vert(m_idx) Vector3((m_idx & 4) >> 2, (m_idx & 2) >> 1, m_idx & 1) - static const uint8_t indices[6][4]={ - {7,6,4,5}, - {7,3,2,6}, - {7,5,1,3}, - {0,2,3,1}, - {0,1,5,4}, - {0,4,6,2}, + static const uint8_t indices[6][4] = { + { 7, 6, 4, 5 }, + { 7, 3, 2, 6 }, + { 7, 5, 1, 3 }, + { 0, 2, 3, 1 }, + { 0, 1, 5, 4 }, + { 0, 4, 6, 2 }, }; -/* + /* {0,1,2,3}, {0,1,4,5}, @@ -535,114 +526,107 @@ static inline void _build_faces(uint8_t*** p_cell_status,int x,int y,int z,int l {7,5,1,3}, */ - for (int i=0;i<6;i++) { + for (int i = 0; i < 6; i++) { Vector3 face_points[4]; - int disp_x=x+((i%3)==0?((i<3)?1:-1):0); - int disp_y=y+(((i-1)%3)==0?((i<3)?1:-1):0); - int disp_z=z+(((i-2)%3)==0?((i<3)?1:-1):0); + int disp_x = x + ((i % 3) == 0 ? ((i < 3) ? 1 : -1) : 0); + int disp_y = y + (((i - 1) % 3) == 0 ? ((i < 3) ? 1 : -1) : 0); + int disp_z = z + (((i - 2) % 3) == 0 ? ((i < 3) ? 1 : -1) : 0); - bool plot=false; + bool plot = false; - if (disp_x<0 || disp_x>=len_x) - plot=true; - if (disp_y<0 || disp_y>=len_y) - plot=true; - if (disp_z<0 || disp_z>=len_z) - plot=true; + if (disp_x < 0 || disp_x >= len_x) + plot = true; + if (disp_y < 0 || disp_y >= len_y) + plot = true; + if (disp_z < 0 || disp_z >= len_z) + plot = true; - if (!plot && (p_cell_status[disp_x][disp_y][disp_z]&_CELL_EXTERIOR)) - plot=true; + if (!plot && (p_cell_status[disp_x][disp_y][disp_z] & _CELL_EXTERIOR)) + plot = true; if (!plot) continue; - for (int j=0;j<4;j++) - face_points[j]=vert( indices[i][j] ) + Vector3(x,y,z); + for (int j = 0; j < 4; j++) + face_points[j] = vert(indices[i][j]) + Vector3(x, y, z); p_faces.push_back( - Face3( - face_points[0], - face_points[1], - face_points[2] - ) - ); + Face3( + face_points[0], + face_points[1], + face_points[2])); p_faces.push_back( - Face3( - face_points[2], - face_points[3], - face_points[0] - ) - ); - + Face3( + face_points[2], + face_points[3], + face_points[0])); } - } -DVector< Face3 > Geometry::wrap_geometry( DVector< Face3 > p_array,float *p_error ) { +DVector Geometry::wrap_geometry(DVector p_array, float *p_error) { #define _MIN_SIZE 1.0 #define _MAX_LENGTH 20 - int face_count=p_array.size(); - DVector::Read facesr=p_array.read(); + int face_count = p_array.size(); + DVector::Read facesr = p_array.read(); const Face3 *faces = facesr.ptr(); AABB global_aabb; - for(int i=0;i Geometry::wrap_geometry( DVector< Face3 > p_array,float *p_erro // plot faces into cells //print_line("Wrapper (1/6): Plotting Faces"); - for (int i=0;i Geometry::wrap_geometry( DVector< Face3 > p_array,float *p_erro DVector wrapped_faces; - for (int i=0;i Geometry::wrap_geometry( DVector< Face3 > p_array,float *p_erro // transform face vertices to global coords - int wrapped_faces_count=wrapped_faces.size(); - DVector::Write wrapped_facesw=wrapped_faces.write(); - Face3* wrapped_faces_ptr=wrapped_facesw.ptr(); + int wrapped_faces_count = wrapped_faces.size(); + DVector::Write wrapped_facesw = wrapped_faces.write(); + Face3 *wrapped_faces_ptr = wrapped_facesw.ptr(); - for(int i=0;i &p_planes) { MeshData mesh; - #define SUBPLANE_SIZE 1024.0 float subplane_size = 1024.0; // should compute this from the actual plane - for (int i=0;i0.95) - ref=Vector3(0.0,0.0,1.0); // change axis + if (ABS(p.normal.dot(ref)) > 0.95) + ref = Vector3(0.0, 0.0, 1.0); // change axis Vector3 right = p.normal.cross(ref).normalized(); - Vector3 up = p.normal.cross( right ).normalized(); + Vector3 up = p.normal.cross(right).normalized(); - Vector< Vector3 > vertices; + Vector vertices; Vector3 center = p.get_any_point(); // make a quad clockwise - vertices.push_back( center - up * subplane_size + right * subplane_size ); - vertices.push_back( center - up * subplane_size - right * subplane_size ); - vertices.push_back( center + up * subplane_size - right * subplane_size ); - vertices.push_back( center + up * subplane_size + right * subplane_size ); + vertices.push_back(center - up * subplane_size + right * subplane_size); + vertices.push_back(center - up * subplane_size - right * subplane_size); + vertices.push_back(center + up * subplane_size - right * subplane_size); + vertices.push_back(center + up * subplane_size + right * subplane_size); - for (int j=0;j new_vertices; + Plane clip = p_planes[j]; - Vector< Vector3 > new_vertices; - Plane clip=p_planes[j]; - - if (clip.normal.dot(p.normal)>0.95) + if (clip.normal.dot(p.normal) > 0.95) continue; - if (vertices.size()<3) + if (vertices.size() < 3) break; - for(int k=0;k &p_planes) { if (found) continue; MeshData::Edge edge; - edge.a=a; - edge.b=b; + edge.a = a; + edge.b = b; mesh.edges.push_back(edge); } - - } return mesh; } - -DVector Geometry::build_box_planes(const Vector3& p_extents) { +DVector Geometry::build_box_planes(const Vector3 &p_extents) { DVector planes; - planes.push_back( Plane( Vector3(1,0,0), p_extents.x ) ); - planes.push_back( Plane( Vector3(-1,0,0), p_extents.x ) ); - planes.push_back( Plane( Vector3(0,1,0), p_extents.y ) ); - planes.push_back( Plane( Vector3(0,-1,0), p_extents.y ) ); - planes.push_back( Plane( Vector3(0,0,1), p_extents.z ) ); - planes.push_back( Plane( Vector3(0,0,-1), p_extents.z ) ); + planes.push_back(Plane(Vector3(1, 0, 0), p_extents.x)); + planes.push_back(Plane(Vector3(-1, 0, 0), p_extents.x)); + planes.push_back(Plane(Vector3(0, 1, 0), p_extents.y)); + planes.push_back(Plane(Vector3(0, -1, 0), p_extents.y)); + planes.push_back(Plane(Vector3(0, 0, 1), p_extents.z)); + planes.push_back(Plane(Vector3(0, 0, -1), p_extents.z)); return planes; } @@ -914,103 +888,95 @@ DVector Geometry::build_cylinder_planes(float p_radius, float p_height, i DVector planes; - for (int i=0;i Geometry::build_sphere_planes(float p_radius, int p_lats,int p_lons, Vector3::Axis p_axis) { - +DVector Geometry::build_sphere_planes(float p_radius, int p_lats, int p_lons, Vector3::Axis p_axis) { DVector planes; Vector3 axis; - axis[p_axis]=1.0; + axis[p_axis] = 1.0; Vector3 axis_neg; - axis_neg[(p_axis+1)%3]=1.0; - axis_neg[(p_axis+2)%3]=1.0; - axis_neg[p_axis]=-1.0; + axis_neg[(p_axis + 1) % 3] = 1.0; + axis_neg[(p_axis + 2) % 3] = 1.0; + axis_neg[p_axis] = -1.0; - for (int i=0;i Geometry::build_capsule_planes(float p_radius, float p_height, int p_sides, int p_lats, Vector3::Axis p_axis) { DVector planes; - Vector3 axis; - axis[p_axis]=1.0; + Vector3 axis; + axis[p_axis] = 1.0; Vector3 axis_neg; - axis_neg[(p_axis+1)%3]=1.0; - axis_neg[(p_axis+2)%3]=1.0; - axis_neg[p_axis]=-1.0; + axis_neg[(p_axis + 1) % 3] = 1.0; + axis_neg[(p_axis + 2) % 3] = 1.0; + axis_neg[p_axis] = -1.0; - for (int i=0;i p_r.s.width; }; + _FORCE_INLINE_ bool operator<(const _AtlasWorkRect &p_r) const { return s.width > p_r.s.width; }; }; struct _AtlasWorkRectResult { @@ -1020,7 +986,7 @@ struct _AtlasWorkRectResult { int max_h; }; -void Geometry::make_atlas(const Vector& p_rects,Vector& r_result, Size2i& r_size) { +void Geometry::make_atlas(const Vector &p_rects, Vector &r_result, Size2i &r_size) { //super simple, almost brute force scanline stacking fitter //it's pretty basic for now, but it tries to make sure that the aspect ratio of the @@ -1030,108 +996,100 @@ void Geometry::make_atlas(const Vector& p_rects,Vector& r_resul // for example, it will prioritize a 1024x1024 atlas (works everywhere) instead of a // 256x8192 atlas (won't work anywhere). - ERR_FAIL_COND(p_rects.size()==0); + ERR_FAIL_COND(p_rects.size() == 0); Vector<_AtlasWorkRect> wrects; wrects.resize(p_rects.size()); - for(int i=0;i results; - for(int i=0;i<=12;i++) { + for (int i = 0; i <= 12; i++) { - int w = 1< hmax; hmax.resize(w); - for(int j=0;j w) { - if (ofs+wrects[j].s.width > w) { - - ofs=0; + ofs = 0; } - int from_y=0; - for(int k=0;k from_y) - from_y=hmax[ofs+k]; + if (hmax[ofs + k] > from_y) + from_y = hmax[ofs + k]; } - wrects[j].p.x=ofs; - wrects[j].p.y=from_y; - int end_h = from_y+wrects[j].s.height; - int end_w = ofs+wrects[j].s.width; - if (ofs==0) - limit_h=end_h; + wrects[j].p.x = ofs; + wrects[j].p.y = from_y; + int end_h = from_y + wrects[j].s.height; + int end_w = ofs + wrects[j].s.width; + if (ofs == 0) + limit_h = end_h; - for(int k=0;k max_h) - max_h=end_h; + max_h = end_h; if (end_w > max_w) - max_w=end_w; - - if (ofs==0 || end_h>limit_h ) //while h limit not reched, keep stacking - ofs+=wrects[j].s.width; + max_w = end_w; + if (ofs == 0 || end_h > limit_h) //while h limit not reched, keep stacking + ofs += wrects[j].s.width; } _AtlasWorkRectResult result; - result.result=wrects; - result.max_h=max_h; - result.max_w=max_w; + result.result = wrects; + result.max_h = max_h; + result.max_w = max_w; results.push_back(result); - } //find the result with the best aspect ratio - int best=-1; - float best_aspect=1e20; + int best = -1; + float best_aspect = 1e20; - for(int i=0;iw ? h/w : w/h; + float aspect = h > w ? h / w : w / h; if (aspect < best_aspect) { - best=i; - best_aspect=aspect; + best = i; + best_aspect = aspect; } } r_result.resize(p_rects.size()); - for(int i=0;i */ class Geometry { Geometry(); + public: - - - - - static float get_closest_points_between_segments( const Vector2& p1,const Vector2& q1, const Vector2& p2,const Vector2& q2, Vector2& c1, Vector2& c2) { + static float get_closest_points_between_segments(const Vector2 &p1, const Vector2 &q1, const Vector2 &p2, const Vector2 &q2, Vector2 &c1, Vector2 &c2) { Vector2 d1 = q1 - p1; // Direction vector of segment S1 Vector2 d2 = q2 - p2; // Direction vector of segment S2 @@ -56,7 +53,7 @@ public: float a = d1.dot(d1); // Squared length of segment S1, always nonnegative float e = d2.dot(d2); // Squared length of segment S2, always nonnegative float f = d2.dot(r); - float s,t; + float s, t; // Check if either or both segments degenerate into points if (a <= CMP_EPSILON && e <= CMP_EPSILON) { // Both segments degenerate into points @@ -78,16 +75,16 @@ public: } else { // The general nondegenerate case starts here float b = d1.dot(d2); - float denom = a*e-b*b; // Always nonnegative + float denom = a * e - b * b; // Always nonnegative // If segments not parallel, compute closest point on L1 to L2 and // clamp to segment S1. Else pick arbitrary s (here 0) if (denom != 0.0f) { - s = CLAMP((b*f - c*e) / denom, 0.0f, 1.0f); + s = CLAMP((b * f - c * e) / denom, 0.0f, 1.0f); } else s = 0.0f; // Compute point on L2 closest to S1(s) using // t = Dot((P1 + D1*s) - P2,D2) / Dot(D2,D2) = (b*s + f) / e - t = (b*s + f) / e; + t = (b * s + f) / e; //If t in [0,1] done. Else clamp t, recompute s for the new value // of t using s = Dot((P2 + D2*t) - P1,D1) / Dot(D1,D1)= (t*b - c) / a @@ -106,111 +103,106 @@ public: return Math::sqrt((c1 - c2).dot(c1 - c2)); } - - static void get_closest_points_between_segments(const Vector3& p1,const Vector3& p2,const Vector3& q1,const Vector3& q2,Vector3& c1, Vector3& c2) - { - //do the function 'd' as defined by pb. I think is is dot product of some sort -#define d_of(m,n,o,p) ( (m.x - n.x) * (o.x - p.x) + (m.y - n.y) * (o.y - p.y) + (m.z - n.z) * (o.z - p.z) ) + static void get_closest_points_between_segments(const Vector3 &p1, const Vector3 &p2, const Vector3 &q1, const Vector3 &q2, Vector3 &c1, Vector3 &c2) { +//do the function 'd' as defined by pb. I think is is dot product of some sort +#define d_of(m, n, o, p) ((m.x - n.x) * (o.x - p.x) + (m.y - n.y) * (o.y - p.y) + (m.z - n.z) * (o.z - p.z)) //caluclate the parpametric position on the 2 curves, mua and mub - float mua = ( d_of(p1,q1,q2,q1) * d_of(q2,q1,p2,p1) - d_of(p1,q1,p2,p1) * d_of(q2,q1,q2,q1) ) / ( d_of(p2,p1,p2,p1) * d_of(q2,q1,q2,q1) - d_of(q2,q1,p2,p1) * d_of(q2,q1,p2,p1) ); - float mub = ( d_of(p1,q1,q2,q1) + mua * d_of(q2,q1,p2,p1) ) / d_of(q2,q1,q2,q1); + float mua = (d_of(p1, q1, q2, q1) * d_of(q2, q1, p2, p1) - d_of(p1, q1, p2, p1) * d_of(q2, q1, q2, q1)) / (d_of(p2, p1, p2, p1) * d_of(q2, q1, q2, q1) - d_of(q2, q1, p2, p1) * d_of(q2, q1, p2, p1)); + float mub = (d_of(p1, q1, q2, q1) + mua * d_of(q2, q1, p2, p1)) / d_of(q2, q1, q2, q1); //clip the value between [0..1] constraining the solution to lie on the original curves if (mua < 0) mua = 0; if (mub < 0) mub = 0; if (mua > 1) mua = 1; if (mub > 1) mub = 1; - c1 = p1.linear_interpolate(p2,mua); - c2 = q1.linear_interpolate(q2,mub); + c1 = p1.linear_interpolate(p2, mua); + c2 = q1.linear_interpolate(q2, mub); } - static float get_closest_distance_between_segments( const Vector3& p_from_a,const Vector3& p_to_a, const Vector3& p_from_b,const Vector3& p_to_b) { - Vector3 u = p_to_a - p_from_a; - Vector3 v = p_to_b - p_from_b; - Vector3 w = p_from_a - p_to_a; - real_t a = u.dot(u); // always >= 0 - real_t b = u.dot(v); - real_t c = v.dot(v); // always >= 0 - real_t d = u.dot(w); - real_t e = v.dot(w); - real_t D = a*c - b*b; // always >= 0 - real_t sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0 - real_t tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0 + static float get_closest_distance_between_segments(const Vector3 &p_from_a, const Vector3 &p_to_a, const Vector3 &p_from_b, const Vector3 &p_to_b) { + Vector3 u = p_to_a - p_from_a; + Vector3 v = p_to_b - p_from_b; + Vector3 w = p_from_a - p_to_a; + real_t a = u.dot(u); // always >= 0 + real_t b = u.dot(v); + real_t c = v.dot(v); // always >= 0 + real_t d = u.dot(w); + real_t e = v.dot(w); + real_t D = a * c - b * b; // always >= 0 + real_t sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0 + real_t tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0 - // compute the line parameters of the two closest points - if (D < CMP_EPSILON) { // the lines are almost parallel - sN = 0.0; // force using point P0 on segment S1 - sD = 1.0; // to prevent possible division by 0.0 later - tN = e; - tD = c; - } - else { // get the closest points on the infinite lines - sN = (b*e - c*d); - tN = (a*e - b*d); - if (sN < 0.0) { // sc < 0 => the s=0 edge is visible - sN = 0.0; - tN = e; - tD = c; + // compute the line parameters of the two closest points + if (D < CMP_EPSILON) { // the lines are almost parallel + sN = 0.0; // force using point P0 on segment S1 + sD = 1.0; // to prevent possible division by 0.0 later + tN = e; + tD = c; + } else { // get the closest points on the infinite lines + sN = (b * e - c * d); + tN = (a * e - b * d); + if (sN < 0.0) { // sc < 0 => the s=0 edge is visible + sN = 0.0; + tN = e; + tD = c; + } else if (sN > sD) { // sc > 1 => the s=1 edge is visible + sN = sD; + tN = e + b; + tD = c; + } } - else if (sN > sD) { // sc > 1 => the s=1 edge is visible - sN = sD; - tN = e + b; - tD = c; - } - } - if (tN < 0.0) { // tc < 0 => the t=0 edge is visible - tN = 0.0; - // recompute sc for this edge - if (-d < 0.0) - sN = 0.0; - else if (-d > a) - sN = sD; - else { - sN = -d; - sD = a; + if (tN < 0.0) { // tc < 0 => the t=0 edge is visible + tN = 0.0; + // recompute sc for this edge + if (-d < 0.0) + sN = 0.0; + else if (-d > a) + sN = sD; + else { + sN = -d; + sD = a; + } + } else if (tN > tD) { // tc > 1 => the t=1 edge is visible + tN = tD; + // recompute sc for this edge + if ((-d + b) < 0.0) + sN = 0; + else if ((-d + b) > a) + sN = sD; + else { + sN = (-d + b); + sD = a; + } } - } - else if (tN > tD) { // tc > 1 => the t=1 edge is visible - tN = tD; - // recompute sc for this edge - if ((-d + b) < 0.0) - sN = 0; - else if ((-d + b) > a) - sN = sD; - else { - sN = (-d + b); - sD = a; - } - } - // finally do the division to get sc and tc - sc = (Math::abs(sN) < CMP_EPSILON ? 0.0 : sN / sD); - tc = (Math::abs(tN) < CMP_EPSILON ? 0.0 : tN / tD); + // finally do the division to get sc and tc + sc = (Math::abs(sN) < CMP_EPSILON ? 0.0 : sN / sD); + tc = (Math::abs(tN) < CMP_EPSILON ? 0.0 : tN / tD); - // get the difference of the two closest points - Vector3 dP = w + (sc * u) - (tc * v); // = S1(sc) - S2(tc) + // get the difference of the two closest points + Vector3 dP = w + (sc * u) - (tc * v); // = S1(sc) - S2(tc) - return dP.length(); // return the closest distance + return dP.length(); // return the closest distance } - static inline bool ray_intersects_triangle( const Vector3& p_from, const Vector3& p_dir, const Vector3& p_v0,const Vector3& p_v1,const Vector3& p_v2,Vector3* r_res=0) { - Vector3 e1=p_v1-p_v0; - Vector3 e2=p_v2-p_v0; + static inline bool ray_intersects_triangle(const Vector3 &p_from, const Vector3 &p_dir, const Vector3 &p_v0, const Vector3 &p_v1, const Vector3 &p_v2, Vector3 *r_res = 0) { + Vector3 e1 = p_v1 - p_v0; + Vector3 e2 = p_v2 - p_v0; Vector3 h = p_dir.cross(e2); - real_t a =e1.dot(h); - if (a>-CMP_EPSILON && a < CMP_EPSILON) // parallel test + real_t a = e1.dot(h); + if (a > -CMP_EPSILON && a < CMP_EPSILON) // parallel test return false; - real_t f=1.0/a; + real_t f = 1.0 / a; - Vector3 s=p_from-p_v0; + Vector3 s = p_from - p_v0; real_t u = f * s.dot(h); - if ( u< 0.0 || u > 1.0) + if (u < 0.0 || u > 1.0) return false; - Vector3 q=s.cross(e1); + Vector3 q = s.cross(e1); real_t v = f * p_dir.dot(q); @@ -221,34 +213,34 @@ public: // the intersection point is on the line real_t t = f * e2.dot(q); - if (t > 0.00001) {// ray intersection + if (t > 0.00001) { // ray intersection if (r_res) - *r_res=p_from+p_dir*t; + *r_res = p_from + p_dir * t; return true; } else // this means that there is a line intersection // but not a ray intersection return false; } - static inline bool segment_intersects_triangle( const Vector3& p_from, const Vector3& p_to, const Vector3& p_v0,const Vector3& p_v1,const Vector3& p_v2,Vector3* r_res=0) { + static inline bool segment_intersects_triangle(const Vector3 &p_from, const Vector3 &p_to, const Vector3 &p_v0, const Vector3 &p_v1, const Vector3 &p_v2, Vector3 *r_res = 0) { - Vector3 rel=p_to-p_from; - Vector3 e1=p_v1-p_v0; - Vector3 e2=p_v2-p_v0; + Vector3 rel = p_to - p_from; + Vector3 e1 = p_v1 - p_v0; + Vector3 e2 = p_v2 - p_v0; Vector3 h = rel.cross(e2); - real_t a =e1.dot(h); - if (a>-CMP_EPSILON && a < CMP_EPSILON) // parallel test + real_t a = e1.dot(h); + if (a > -CMP_EPSILON && a < CMP_EPSILON) // parallel test return false; - real_t f=1.0/a; + real_t f = 1.0 / a; - Vector3 s=p_from-p_v0; + Vector3 s = p_from - p_v0; real_t u = f * s.dot(h); - if ( u< 0.0 || u > 1.0) + if (u < 0.0 || u > 1.0) return false; - Vector3 q=s.cross(e1); + Vector3 q = s.cross(e1); real_t v = f * rel.dot(q); @@ -259,124 +251,122 @@ public: // the intersection point is on the line real_t t = f * e2.dot(q); - if (t > CMP_EPSILON && t<=1.0) {// ray intersection + if (t > CMP_EPSILON && t <= 1.0) { // ray intersection if (r_res) - *r_res=p_from+rel*t; + *r_res = p_from + rel * t; return true; } else // this means that there is a line intersection // but not a ray intersection return false; } - static inline bool segment_intersects_sphere( const Vector3& p_from, const Vector3& p_to, const Vector3& p_sphere_pos,real_t p_sphere_radius,Vector3* r_res=0,Vector3 *r_norm=0) { + static inline bool segment_intersects_sphere(const Vector3 &p_from, const Vector3 &p_to, const Vector3 &p_sphere_pos, real_t p_sphere_radius, Vector3 *r_res = 0, Vector3 *r_norm = 0) { - - Vector3 sphere_pos=p_sphere_pos-p_from; - Vector3 rel=(p_to-p_from); - float rel_l=rel.length(); - if (rel_l=p_sphere_radius) + if (ray_distance >= p_sphere_radius) return false; - float inters_d2=p_sphere_radius*p_sphere_radius - ray_distance*ray_distance; - float inters_d=sphere_d; + float inters_d2 = p_sphere_radius * p_sphere_radius - ray_distance * ray_distance; + float inters_d = sphere_d; - if (inters_d2>=CMP_EPSILON) - inters_d-=Math::sqrt(inters_d2); + if (inters_d2 >= CMP_EPSILON) + inters_d -= Math::sqrt(inters_d2); // check in segment - if (inters_d<0 || inters_d>rel_l) + if (inters_d < 0 || inters_d > rel_l) return false; - Vector3 result=p_from+normal*inters_d; + Vector3 result = p_from + normal * inters_d; if (r_res) - *r_res=result; + *r_res = result; if (r_norm) - *r_norm=(result-p_sphere_pos).normalized(); + *r_norm = (result - p_sphere_pos).normalized(); return true; } - static inline bool segment_intersects_cylinder( const Vector3& p_from, const Vector3& p_to, float p_height,float p_radius,Vector3* r_res=0,Vector3 *r_norm=0) { + static inline bool segment_intersects_cylinder(const Vector3 &p_from, const Vector3 &p_to, float p_height, float p_radius, Vector3 *r_res = 0, Vector3 *r_norm = 0) { - Vector3 rel=(p_to-p_from); - float rel_l=rel.length(); - if (rel_l=p_radius) + if (dist >= p_radius) return false; // too far away // convert to 2D - float w2=p_radius*p_radius-dist*dist; - if (w2 box_end || seg_to < box_begin) return false; - real_t length=seg_to-seg_from; - cmin = (seg_from < box_begin)?((box_begin - seg_from)/length):0; - cmax = (seg_to > box_end)?((box_end - seg_from)/length):1; + real_t length = seg_to - seg_from; + cmin = (seg_from < box_begin) ? ((box_begin - seg_from) / length) : 0; + cmax = (seg_to > box_end) ? ((box_end - seg_from) / length) : 1; } else { if (seg_to > box_end || seg_from < box_begin) return false; - real_t length=seg_to-seg_from; - cmin = (seg_from > box_end)?(box_end - seg_from)/length:0; - cmax = (seg_to < box_begin)?(box_begin - seg_from)/length:1; + real_t length = seg_to - seg_from; + cmin = (seg_from > box_end) ? (box_end - seg_from) / length : 0; + cmax = (seg_to < box_begin) ? (box_begin - seg_from) / length : 1; } if (cmin > min) { min = cmin; - axis=i; + axis = i; } if (cmax < max) max = cmax; @@ -384,254 +374,245 @@ public: return false; } - // convert to 3D again - Vector3 result = p_from + (rel*min); + Vector3 result = p_from + (rel * min); Vector3 res_normal = result; - if (axis==0) { - res_normal.z=0; + if (axis == 0) { + res_normal.z = 0; } else { - res_normal.x=0; - res_normal.y=0; + res_normal.x = 0; + res_normal.y = 0; } - res_normal.normalize(); if (r_res) - *r_res=result; + *r_res = result; if (r_norm) - *r_norm=res_normal; + *r_norm = res_normal; return true; } + static bool segment_intersects_convex(const Vector3 &p_from, const Vector3 &p_to, const Plane *p_planes, int p_plane_count, Vector3 *p_res, Vector3 *p_norm) { - static bool segment_intersects_convex(const Vector3& p_from, const Vector3& p_to,const Plane* p_planes, int p_plane_count,Vector3 *p_res, Vector3 *p_norm) { + real_t min = -1e20, max = 1e20; - real_t min=-1e20,max=1e20; + Vector3 rel = p_to - p_from; + real_t rel_l = rel.length(); - Vector3 rel=p_to-p_from; - real_t rel_l=rel.length(); - - if (rel_l0) { + if (den > 0) { //backwards facing plane - if (distmin) { - min=dist; - min_index=i; + if (dist > min) { + min = dist; + min_index = i; } } } - if (max<=min || min<0 || min>rel_l || min_index==-1) // exit conditions + if (max <= min || min < 0 || min > rel_l || min_index == -1) // exit conditions return false; // no intersection if (p_res) - *p_res=p_from+dir*min; + *p_res = p_from + dir * min; if (p_norm) - *p_norm=p_planes[min_index].normal; + *p_norm = p_planes[min_index].normal; return true; } - static Vector3 get_closest_point_to_segment(const Vector3& p_point, const Vector3 *p_segment) { + static Vector3 get_closest_point_to_segment(const Vector3 &p_point, const Vector3 *p_segment) { - Vector3 p=p_point-p_segment[0]; - Vector3 n=p_segment[1]-p_segment[0]; - float l =n.length(); - if (l<1e-10) + Vector3 p = p_point - p_segment[0]; + Vector3 n = p_segment[1] - p_segment[0]; + float l = n.length(); + if (l < 1e-10) return p_segment[0]; // both points are the same, just give any - n/=l; + n /= l; - float d=n.dot(p); + float d = n.dot(p); - if (d<=0.0) + if (d <= 0.0) return p_segment[0]; // before first point - else if (d>=l) + else if (d >= l) return p_segment[1]; // after first point else - return p_segment[0]+n*d; // inside + return p_segment[0] + n * d; // inside } - static Vector3 get_closest_point_to_segment_uncapped(const Vector3& p_point, const Vector3 *p_segment) { + static Vector3 get_closest_point_to_segment_uncapped(const Vector3 &p_point, const Vector3 *p_segment) { - Vector3 p=p_point-p_segment[0]; - Vector3 n=p_segment[1]-p_segment[0]; - float l =n.length(); - if (l<1e-10) + Vector3 p = p_point - p_segment[0]; + Vector3 n = p_segment[1] - p_segment[0]; + float l = n.length(); + if (l < 1e-10) return p_segment[0]; // both points are the same, just give any - n/=l; + n /= l; - float d=n.dot(p); + float d = n.dot(p); - return p_segment[0]+n*d; // inside + return p_segment[0] + n * d; // inside } - static Vector2 get_closest_point_to_segment_2d(const Vector2& p_point, const Vector2 *p_segment) { + static Vector2 get_closest_point_to_segment_2d(const Vector2 &p_point, const Vector2 *p_segment) { - Vector2 p=p_point-p_segment[0]; - Vector2 n=p_segment[1]-p_segment[0]; - float l =n.length(); - if (l<1e-10) + Vector2 p = p_point - p_segment[0]; + Vector2 n = p_segment[1] - p_segment[0]; + float l = n.length(); + if (l < 1e-10) return p_segment[0]; // both points are the same, just give any - n/=l; + n /= l; - float d=n.dot(p); + float d = n.dot(p); - if (d<=0.0) + if (d <= 0.0) return p_segment[0]; // before first point - else if (d>=l) + else if (d >= l) return p_segment[1]; // after first point else - return p_segment[0]+n*d; // inside + return p_segment[0] + n * d; // inside } - static bool is_point_in_triangle(const Vector2& s, const Vector2& a, const Vector2& b, const Vector2& c) - { - int as_x = s.x-a.x; - int as_y = s.y-a.y; + static bool is_point_in_triangle(const Vector2 &s, const Vector2 &a, const Vector2 &b, const Vector2 &c) { + int as_x = s.x - a.x; + int as_y = s.y - a.y; - bool s_ab = (b.x-a.x)*as_y-(b.y-a.y)*as_x > 0; + bool s_ab = (b.x - a.x) * as_y - (b.y - a.y) * as_x > 0; - if(((c.x-a.x)*as_y-(c.y-a.y)*as_x > 0) == s_ab) return false; + if (((c.x - a.x) * as_y - (c.y - a.y) * as_x > 0) == s_ab) return false; - if(((c.x-b.x)*(s.y-b.y)-(c.y-b.y)*(s.x-b.x) > 0) != s_ab) return false; + if (((c.x - b.x) * (s.y - b.y) - (c.y - b.y) * (s.x - b.x) > 0) != s_ab) return false; - return true; + return true; } - static Vector2 get_closest_point_to_segment_uncapped_2d(const Vector2& p_point, const Vector2 *p_segment) { + static Vector2 get_closest_point_to_segment_uncapped_2d(const Vector2 &p_point, const Vector2 *p_segment) { - Vector2 p=p_point-p_segment[0]; - Vector2 n=p_segment[1]-p_segment[0]; - float l =n.length(); - if (l<1e-10) + Vector2 p = p_point - p_segment[0]; + Vector2 n = p_segment[1] - p_segment[0]; + float l = n.length(); + if (l < 1e-10) return p_segment[0]; // both points are the same, just give any - n/=l; + n /= l; - float d=n.dot(p); + float d = n.dot(p); - return p_segment[0]+n*d; // inside + return p_segment[0] + n * d; // inside } - static bool segment_intersects_segment_2d(const Vector2& p_from_a,const Vector2& p_to_a,const Vector2& p_from_b,const Vector2& p_to_b,Vector2* r_result) { + static bool segment_intersects_segment_2d(const Vector2 &p_from_a, const Vector2 &p_to_a, const Vector2 &p_from_b, const Vector2 &p_to_b, Vector2 *r_result) { - Vector2 B = p_to_a-p_from_a; - Vector2 C = p_from_b-p_from_a; - Vector2 D = p_to_b-p_from_a; + Vector2 B = p_to_a - p_from_a; + Vector2 C = p_from_b - p_from_a; + Vector2 D = p_to_b - p_from_a; real_t ABlen = B.dot(B); - if (ABlen<=0) + if (ABlen <= 0) return false; - Vector2 Bn = B/ABlen; - C = Vector2( C.x*Bn.x + C.y*Bn.y, C.y*Bn.x - C.x*Bn.y ); - D = Vector2( D.x*Bn.x + D.y*Bn.y, D.y*Bn.x - D.x*Bn.y ); + Vector2 Bn = B / ABlen; + C = Vector2(C.x * Bn.x + C.y * Bn.y, C.y * Bn.x - C.x * Bn.y); + D = Vector2(D.x * Bn.x + D.y * Bn.y, D.y * Bn.x - D.x * Bn.y); - if ((C.y<0 && D.y<0) || (C.y>=0 && D.y>=0)) + if ((C.y < 0 && D.y < 0) || (C.y >= 0 && D.y >= 0)) return false; - float ABpos=D.x+(C.x-D.x)*D.y/(D.y-C.y); + float ABpos = D.x + (C.x - D.x) * D.y / (D.y - C.y); // Fail if segment C-D crosses line A-B outside of segment A-B. - if (ABpos<0 || ABpos>1.0) + if (ABpos < 0 || ABpos > 1.0) return false; // (4) Apply the discovered position to line A-B in the original coordinate system. if (r_result) - *r_result=p_from_a+B*ABpos; + *r_result = p_from_a + B * ABpos; return true; } + static inline bool point_in_projected_triangle(const Vector3 &p_point, const Vector3 &p_v1, const Vector3 &p_v2, const Vector3 &p_v3) { - static inline bool point_in_projected_triangle(const Vector3& p_point,const Vector3& p_v1,const Vector3& p_v2,const Vector3& p_v3) { + Vector3 face_n = (p_v1 - p_v3).cross(p_v1 - p_v2); + Vector3 n1 = (p_point - p_v3).cross(p_point - p_v2); - Vector3 face_n = (p_v1-p_v3).cross(p_v1-p_v2); - - Vector3 n1 = (p_point-p_v3).cross(p_point-p_v2); - - if (face_n.dot(n1)<0) + if (face_n.dot(n1) < 0) return false; - Vector3 n2 = (p_v1-p_v3).cross(p_v1-p_point); + Vector3 n2 = (p_v1 - p_v3).cross(p_v1 - p_point); - if (face_n.dot(n2)<0) + if (face_n.dot(n2) < 0) return false; - Vector3 n3 = (p_v1-p_point).cross(p_v1-p_v2); + Vector3 n3 = (p_v1 - p_point).cross(p_v1 - p_v2); - if (face_n.dot(n3)<0) + if (face_n.dot(n3) < 0) return false; return true; - } - static inline bool triangle_sphere_intersection_test(const Vector3 *p_triangle,const Vector3& p_normal,const Vector3& p_sphere_pos, real_t p_sphere_radius,Vector3& r_triangle_contact,Vector3& r_sphere_contact) { + static inline bool triangle_sphere_intersection_test(const Vector3 *p_triangle, const Vector3 &p_normal, const Vector3 &p_sphere_pos, real_t p_sphere_radius, Vector3 &r_triangle_contact, Vector3 &r_sphere_contact) { - float d=p_normal.dot(p_sphere_pos)-p_normal.dot(p_triangle[0]); + float d = p_normal.dot(p_sphere_pos) - p_normal.dot(p_triangle[0]); if (d > p_sphere_radius || d < -p_sphere_radius) // not touching the plane of the face, return return false; - Vector3 contact=p_sphere_pos - (p_normal*d); + Vector3 contact = p_sphere_pos - (p_normal * d); /** 2nd) TEST INSIDE TRIANGLE **/ - - if (Geometry::point_in_projected_triangle(contact,p_triangle[0],p_triangle[1],p_triangle[2])) { - r_triangle_contact=contact; - r_sphere_contact=p_sphere_pos-p_normal*p_sphere_radius; + if (Geometry::point_in_projected_triangle(contact, p_triangle[0], p_triangle[1], p_triangle[2])) { + r_triangle_contact = contact; + r_sphere_contact = p_sphere_pos - p_normal * p_sphere_radius; //printf("solved inside triangle\n"); return true; } /** 3rd TEST INSIDE EDGE CYLINDERS **/ - const Vector3 verts[4]={p_triangle[0],p_triangle[1],p_triangle[2],p_triangle[0]}; // for() friendly + const Vector3 verts[4] = { p_triangle[0], p_triangle[1], p_triangle[2], p_triangle[0] }; // for() friendly - for (int i=0;i<3;i++) { + for (int i = 0; i < 3; i++) { // check edge cylinder - Vector3 n1=verts[i]-verts[i+1]; - Vector3 n2=p_sphere_pos-verts[i+1]; + Vector3 n1 = verts[i] - verts[i + 1]; + Vector3 n2 = p_sphere_pos - verts[i + 1]; ///@TODO i could discard by range here to make the algorithm quicker? dunno.. // check point within cylinder radius - Vector3 axis =n1.cross(n2).cross(n1); + Vector3 axis = n1.cross(n2).cross(n1); axis.normalize(); // ugh - float ad=axis.dot(n2); + float ad = axis.dot(n2); - if (ABS(ad)>p_sphere_radius) { + if (ABS(ad) > p_sphere_radius) { // no chance with this edge, too far away continue; } @@ -641,34 +622,34 @@ public: float sphere_at = n1.dot(n2); - if (sphere_at>=0 && sphere_at= 0 && sphere_at < n1.dot(n1)) { - r_triangle_contact=p_sphere_pos-axis*(axis.dot(n2)); - r_sphere_contact=p_sphere_pos-axis*p_sphere_radius; + r_triangle_contact = p_sphere_pos - axis * (axis.dot(n2)); + r_sphere_contact = p_sphere_pos - axis * p_sphere_radius; // point inside here //printf("solved inside edge\n"); return true; } - float r2=p_sphere_radius*p_sphere_radius; + float r2 = p_sphere_radius * p_sphere_radius; - if (n2.length_squared()= 0 && res1 <= 1) ? res1 : -1; + /* if we can assume that the line segment starts outside the circle (e.g. for continuous time collision detection) then the following can be skipped and we can just return the equivalent of res1 */ + sqrtterm = Math::sqrt(sqrtterm); + real_t res1 = (-b - sqrtterm) / (2 * a); + //real_t res2 = ( -b + sqrtterm ) / (2 * a); + return (res1 >= 0 && res1 <= 1) ? res1 : -1; } - - - static inline Vector clip_polygon(const Vector& polygon,const Plane& p_plane) { + static inline Vector clip_polygon(const Vector &polygon, const Plane &p_plane) { enum LocationCache { - LOC_INSIDE=1, - LOC_BOUNDARY=0, - LOC_OUTSIDE=-1 + LOC_INSIDE = 1, + LOC_BOUNDARY = 0, + LOC_OUTSIDE = -1 }; - if (polygon.size()==0) + if (polygon.size() == 0) return polygon; - int *location_cache = (int*)alloca(sizeof(int)*polygon.size()); + int *location_cache = (int *)alloca(sizeof(int) * polygon.size()); int inside_count = 0; int outside_count = 0; for (int a = 0; a < polygon.size(); a++) { //float p_plane.d = (*this) * polygon[a]; float dist = p_plane.distance_to(polygon[a]); - if (dist <-CMP_POINT_IN_PLANE_EPSILON) { + if (dist < -CMP_POINT_IN_PLANE_EPSILON) { location_cache[a] = LOC_INSIDE; inside_count++; } else { @@ -750,7 +726,7 @@ public: return Vector(); //empty } -// long count = 0; + // long count = 0; long previous = polygon.size() - 1; Vector clipped; @@ -759,24 +735,24 @@ public: int loc = location_cache[index]; if (loc == LOC_OUTSIDE) { if (location_cache[previous] == LOC_INSIDE) { - const Vector3& v1 = polygon[previous]; - const Vector3& v2 = polygon[index]; + const Vector3 &v1 = polygon[previous]; + const Vector3 &v2 = polygon[index]; - Vector3 segment= v1 - v2; - double den=p_plane.normal.dot( segment ); - double dist=p_plane.distance_to( v1 ) / den; - dist=-dist; - clipped.push_back( v1 + segment * dist ); + Vector3 segment = v1 - v2; + double den = p_plane.normal.dot(segment); + double dist = p_plane.distance_to(v1) / den; + dist = -dist; + clipped.push_back(v1 + segment * dist); } } else { - const Vector3& v1 = polygon[index]; + const Vector3 &v1 = polygon[index]; if ((loc == LOC_INSIDE) && (location_cache[previous] == LOC_OUTSIDE)) { - const Vector3& v2 = polygon[previous]; - Vector3 segment= v1 - v2; - double den=p_plane.normal.dot( segment ); - double dist=p_plane.distance_to( v1 ) / den; - dist=-dist; - clipped.push_back( v1 + segment * dist ); + const Vector3 &v2 = polygon[previous]; + Vector3 segment = v1 - v2; + double den = p_plane.normal.dot(segment); + double dist = p_plane.distance_to(v1) / den; + dist = -dist; + clipped.push_back(v1 + segment * dist); } clipped.push_back(v1); @@ -788,30 +764,26 @@ public: return clipped; } - - static Vector triangulate_polygon(const Vector& p_polygon) { + static Vector triangulate_polygon(const Vector &p_polygon) { Vector triangles; - if (!Triangulate::triangulate(p_polygon,triangles)) + if (!Triangulate::triangulate(p_polygon, triangles)) return Vector(); //fail return triangles; } - static Vector< Vector > (*_decompose_func)(const Vector& p_polygon); - static Vector< Vector > decompose_polygon(const Vector& p_polygon) { + static Vector > (*_decompose_func)(const Vector &p_polygon); + static Vector > decompose_polygon(const Vector &p_polygon) { if (_decompose_func) return _decompose_func(p_polygon); - return Vector< Vector >(); - + return Vector >(); } + static DVector > separate_objects(DVector p_array); - static DVector< DVector< Face3 > > separate_objects( DVector< Face3 > p_array ); - - static DVector< Face3 > wrap_geometry( DVector< Face3 > p_array, float *p_error=NULL ); ///< create a "wrap" that encloses the given geometry - + static DVector wrap_geometry(DVector p_array, float *p_error = NULL); ///< create a "wrap" that encloses the given geometry struct MeshData { @@ -824,94 +796,89 @@ public: struct Edge { - int a,b; + int a, b; }; Vector edges; - Vector< Vector3 > vertices; + Vector vertices; void optimize_vertices(); }; + _FORCE_INLINE_ static int get_uv84_normal_bit(const Vector3 &p_vector) { + int lat = Math::fast_ftoi(Math::floor(Math::acos(p_vector.dot(Vector3(0, 1, 0))) * 4.0 / Math_PI + 0.5)); - _FORCE_INLINE_ static int get_uv84_normal_bit(const Vector3& p_vector) { - - int lat = Math::fast_ftoi(Math::floor(Math::acos(p_vector.dot(Vector3(0,1,0)))*4.0/Math_PI+0.5)); - - if (lat==0) { + if (lat == 0) { return 24; - } else if (lat==4) { + } else if (lat == 4) { return 25; } - int lon = Math::fast_ftoi(Math::floor( (Math_PI+Math::atan2(p_vector.x,p_vector.z))*8.0/(Math_PI*2.0) + 0.5))%8; + int lon = Math::fast_ftoi(Math::floor((Math_PI + Math::atan2(p_vector.x, p_vector.z)) * 8.0 / (Math_PI * 2.0) + 0.5)) % 8; - return lon+(lat-1)*8; + return lon + (lat - 1) * 8; } _FORCE_INLINE_ static int get_uv84_normal_bit_neighbors(int p_idx) { - if (p_idx==24) { - return 1|2|4|8; - } else if (p_idx==25) { - return (1<<23)|(1<<22)|(1<<21)|(1<<20); + if (p_idx == 24) { + return 1 | 2 | 4 | 8; + } else if (p_idx == 25) { + return (1 << 23) | (1 << 22) | (1 << 21) | (1 << 20); } else { int ret = 0; - if ((p_idx%8) == 0) - ret|=(1<<(p_idx+7)); + if ((p_idx % 8) == 0) + ret |= (1 << (p_idx + 7)); else - ret|=(1<<(p_idx-1)); - if ((p_idx%8) == 7) - ret|=(1<<(p_idx-7)); + ret |= (1 << (p_idx - 1)); + if ((p_idx % 8) == 7) + ret |= (1 << (p_idx - 7)); else - ret|=(1<<(p_idx+1)); + ret |= (1 << (p_idx + 1)); - int mask = ret|(1<>8; + ret |= mask >> 8; - if (p_idx>=16) - ret|=25; + if (p_idx >= 16) + ret |= 25; else - ret|=mask<<8; + ret |= mask << 8; return ret; } - } - - static double vec2_cross(const Point2 &O, const Point2 &A, const Point2 &B) - { + static double vec2_cross(const Point2 &O, const Point2 &A, const Point2 &B) { return (double)(A.x - O.x) * (B.y - O.y) - (double)(A.y - O.y) * (B.x - O.x); } // Returns a list of points on the convex hull in counter-clockwise order. // Note: the last point in the returned list is the same as the first one. - static Vector convex_hull_2d(Vector P) - { + static Vector convex_hull_2d(Vector P) { int n = P.size(), k = 0; Vector H; - H.resize(2*n); + H.resize(2 * n); // Sort points lexicographically P.sort(); - // Build lower hull for (int i = 0; i < n; ++i) { - while (k >= 2 && vec2_cross(H[k-2], H[k-1], P[i]) <= 0) k--; + while (k >= 2 && vec2_cross(H[k - 2], H[k - 1], P[i]) <= 0) + k--; H[k++] = P[i]; } // Build upper hull - for (int i = n-2, t = k+1; i >= 0; i--) { - while (k >= t && vec2_cross(H[k-2], H[k-1], P[i]) <= 0) k--; + for (int i = n - 2, t = k + 1; i >= 0; i--) { + while (k >= t && vec2_cross(H[k - 2], H[k - 1], P[i]) <= 0) + k--; H[k++] = P[i]; } @@ -920,16 +887,12 @@ public: } static MeshData build_convex_mesh(const DVector &p_planes); - static DVector build_sphere_planes(float p_radius, int p_lats, int p_lons, Vector3::Axis p_axis=Vector3::AXIS_Z); - static DVector build_box_planes(const Vector3& p_extents); - static DVector build_cylinder_planes(float p_radius, float p_height, int p_sides, Vector3::Axis p_axis=Vector3::AXIS_Z); - static DVector build_capsule_planes(float p_radius, float p_height, int p_sides, int p_lats, Vector3::Axis p_axis=Vector3::AXIS_Z); - - static void make_atlas(const Vector& p_rects,Vector& r_result, Size2i& r_size); - + static DVector build_sphere_planes(float p_radius, int p_lats, int p_lons, Vector3::Axis p_axis = Vector3::AXIS_Z); + static DVector build_box_planes(const Vector3 &p_extents); + static DVector build_cylinder_planes(float p_radius, float p_height, int p_sides, Vector3::Axis p_axis = Vector3::AXIS_Z); + static DVector build_capsule_planes(float p_radius, float p_height, int p_sides, int p_lats, Vector3::Axis p_axis = Vector3::AXIS_Z); + static void make_atlas(const Vector &p_rects, Vector &r_result, Size2i &r_size); }; - - #endif diff --git a/core/math/math_2d.cpp b/core/math/math_2d.cpp index 2ced18e4275..b2b99c8e541 100644 --- a/core/math/math_2d.cpp +++ b/core/math/math_2d.cpp @@ -28,91 +28,91 @@ /*************************************************************************/ #include "math_2d.h" - real_t Vector2::angle() const { - return Math::atan2(x,y); + return Math::atan2(x, y); } float Vector2::length() const { - return Math::sqrt( x*x + y*y ); + return Math::sqrt(x * x + y * y); } float Vector2::length_squared() const { - return x*x + y*y; + return x * x + y * y; } void Vector2::normalize() { - float l = x*x + y*y; - if (l!=0) { + float l = x * x + y * y; + if (l != 0) { - l=Math::sqrt(l); - x/=l; - y/=l; + l = Math::sqrt(l); + x /= l; + y /= l; } } Vector2 Vector2::normalized() const { - Vector2 v=*this; + Vector2 v = *this; v.normalize(); return v; } -float Vector2::distance_to(const Vector2& p_vector2) const { +float Vector2::distance_to(const Vector2 &p_vector2) const { - return Math::sqrt( (x-p_vector2.x)*(x-p_vector2.x) + (y-p_vector2.y)*(y-p_vector2.y)); + return Math::sqrt((x - p_vector2.x) * (x - p_vector2.x) + (y - p_vector2.y) * (y - p_vector2.y)); } -float Vector2::distance_squared_to(const Vector2& p_vector2) const { +float Vector2::distance_squared_to(const Vector2 &p_vector2) const { - return (x-p_vector2.x)*(x-p_vector2.x) + (y-p_vector2.y)*(y-p_vector2.y); + return (x - p_vector2.x) * (x - p_vector2.x) + (y - p_vector2.y) * (y - p_vector2.y); } -float Vector2::angle_to(const Vector2& p_vector2) const { +float Vector2::angle_to(const Vector2 &p_vector2) const { - return Math::atan2( tangent().dot(p_vector2), dot(p_vector2) ); + return Math::atan2(tangent().dot(p_vector2), dot(p_vector2)); } -float Vector2::angle_to_point(const Vector2& p_vector2) const { +float Vector2::angle_to_point(const Vector2 &p_vector2) const { - return Math::atan2( x-p_vector2.x, y - p_vector2.y ); + return Math::atan2(x - p_vector2.x, y - p_vector2.y); } -float Vector2::dot(const Vector2& p_other) const { +float Vector2::dot(const Vector2 &p_other) const { - return x*p_other.x + y*p_other.y; + return x * p_other.x + y * p_other.y; } -float Vector2::cross(const Vector2& p_other) const { +float Vector2::cross(const Vector2 &p_other) const { - return x*p_other.y - y*p_other.x; + return x * p_other.y - y * p_other.x; } Vector2 Vector2::cross(real_t p_other) const { - return Vector2(p_other*y,-p_other*x); + return Vector2(p_other * y, -p_other * x); } +Vector2 Vector2::operator+(const Vector2 &p_v) const { -Vector2 Vector2::operator+(const Vector2& p_v) const { - - return Vector2(x+p_v.x,y+p_v.y); + return Vector2(x + p_v.x, y + p_v.y); } -void Vector2::operator+=(const Vector2& p_v) { +void Vector2::operator+=(const Vector2 &p_v) { - x+=p_v.x; y+=p_v.y; + x += p_v.x; + y += p_v.y; } -Vector2 Vector2::operator-(const Vector2& p_v) const { +Vector2 Vector2::operator-(const Vector2 &p_v) const { - return Vector2(x-p_v.x,y-p_v.y); + return Vector2(x - p_v.x, y - p_v.y); } -void Vector2::operator-=(const Vector2& p_v) { +void Vector2::operator-=(const Vector2 &p_v) { - x-=p_v.x; y-=p_v.y; + x -= p_v.x; + y -= p_v.y; } Vector2 Vector2::operator*(const Vector2 &p_v1) const { @@ -126,7 +126,8 @@ Vector2 Vector2::operator*(const float &rvalue) const { }; void Vector2::operator*=(const float &rvalue) { - x *= rvalue; y *= rvalue; + x *= rvalue; + y *= rvalue; }; Vector2 Vector2::operator/(const Vector2 &p_v1) const { @@ -141,64 +142,64 @@ Vector2 Vector2::operator/(const float &rvalue) const { void Vector2::operator/=(const float &rvalue) { - x /= rvalue; y /= rvalue; + x /= rvalue; + y /= rvalue; }; Vector2 Vector2::operator-() const { - return Vector2(-x,-y); + return Vector2(-x, -y); } -bool Vector2::operator==(const Vector2& p_vec2) const { +bool Vector2::operator==(const Vector2 &p_vec2) const { - return x==p_vec2.x && y==p_vec2.y; + return x == p_vec2.x && y == p_vec2.y; } -bool Vector2::operator!=(const Vector2& p_vec2) const { +bool Vector2::operator!=(const Vector2 &p_vec2) const { - return x!=p_vec2.x || y!=p_vec2.y; + return x != p_vec2.x || y != p_vec2.y; } Vector2 Vector2::floor() const { - return Vector2( Math::floor(x), Math::floor(y) ); + return Vector2(Math::floor(x), Math::floor(y)); } Vector2 Vector2::rotated(float p_by) const { Vector2 v; - v.set_rotation(angle()+p_by); - v*=length(); + v.set_rotation(angle() + p_by); + v *= length(); return v; } -Vector2 Vector2::project(const Vector2& p_vec) const { +Vector2 Vector2::project(const Vector2 &p_vec) const { - Vector2 v1=p_vec; - Vector2 v2=*this; - return v2 * ( v1.dot(v2) / v2.dot(v2)); + Vector2 v1 = p_vec; + Vector2 v2 = *this; + return v2 * (v1.dot(v2) / v2.dot(v2)); } -Vector2 Vector2::snapped(const Vector2& p_by) const { +Vector2 Vector2::snapped(const Vector2 &p_by) const { return Vector2( - Math::stepify(x,p_by.x), - Math::stepify(y,p_by.y) - ); + Math::stepify(x, p_by.x), + Math::stepify(y, p_by.y)); } Vector2 Vector2::clamped(real_t p_len) const { real_t l = length(); Vector2 v = *this; - if (l>0 && p_len 0 && p_len < l) { - v/=l; - v*=p_len; + v /= l; + v *= p_len; } return v; } -Vector2 Vector2::cubic_interpolate_soft(const Vector2& p_b,const Vector2& p_pre_a, const Vector2& p_post_b,float p_t) const { +Vector2 Vector2::cubic_interpolate_soft(const Vector2 &p_b, const Vector2 &p_pre_a, const Vector2 &p_post_b, float p_t) const { #if 0 k[0] = ((*this) (vi[0] + 1, vi[1], vi[2])) - ((*this) (vi[0], vi[1],vi[2])); //fk = a0 @@ -225,27 +226,25 @@ Vector2 Vector2::cubic_interpolate_soft(const Vector2& p_b,const Vector2& p_pre_ return Vector2(); } -Vector2 Vector2::cubic_interpolate(const Vector2& p_b,const Vector2& p_pre_a, const Vector2& p_post_b,float p_t) const { +Vector2 Vector2::cubic_interpolate(const Vector2 &p_b, const Vector2 &p_pre_a, const Vector2 &p_post_b, float p_t) const { - - - Vector2 p0=p_pre_a; - Vector2 p1=*this; - Vector2 p2=p_b; - Vector2 p3=p_post_b; + Vector2 p0 = p_pre_a; + Vector2 p1 = *this; + Vector2 p2 = p_b; + Vector2 p3 = p_post_b; float t = p_t; float t2 = t * t; float t3 = t2 * t; Vector2 out; - out = 0.5f * ( ( p1 * 2.0f) + - ( -p0 + p2 ) * t + - ( 2.0f * p0 - 5.0f * p1 + 4 * p2 - p3 ) * t2 + - ( -p0 + 3.0f * p1 - 3.0f * p2 + p3 ) * t3 ); + out = 0.5f * ((p1 * 2.0f) + + (-p0 + p2) * t + + (2.0f * p0 - 5.0f * p1 + 4 * p2 - p3) * t2 + + (-p0 + 3.0f * p1 - 3.0f * p2 + p3) * t3); return out; -/* + /* float mu = p_t; float mu2 = mu*mu; @@ -273,57 +272,54 @@ Vector2 Vector2::cubic_interpolate(const Vector2& p_b,const Vector2& p_pre_a, co (a * p_a.y) + (b *p_b.y) + (c * p_pre_a.y) + (d * p_post_b.y) ); */ - } -Vector2 Vector2::slide(const Vector2& p_vec) const { +Vector2 Vector2::slide(const Vector2 &p_vec) const { return p_vec - *this * this->dot(p_vec); } -Vector2 Vector2::reflect(const Vector2& p_vec) const { +Vector2 Vector2::reflect(const Vector2 &p_vec) const { return p_vec - *this * this->dot(p_vec) * 2.0; - } +bool Rect2::intersects_segment(const Point2 &p_from, const Point2 &p_to, Point2 *r_pos, Point2 *r_normal) const { -bool Rect2::intersects_segment(const Point2& p_from, const Point2& p_to, Point2* r_pos,Point2* r_normal) const { + real_t min = 0, max = 1; + int axis = 0; + float sign = 0; - real_t min=0,max=1; - int axis=0; - float sign=0; - - for(int i=0;i<2;i++) { - real_t seg_from=p_from[i]; - real_t seg_to=p_to[i]; - real_t box_begin=pos[i]; - real_t box_end=box_begin+size[i]; - real_t cmin,cmax; + for (int i = 0; i < 2; i++) { + real_t seg_from = p_from[i]; + real_t seg_to = p_to[i]; + real_t box_begin = pos[i]; + real_t box_end = box_begin + size[i]; + real_t cmin, cmax; float csign; if (seg_from < seg_to) { if (seg_from > box_end || seg_to < box_begin) return false; - real_t length=seg_to-seg_from; - cmin = (seg_from < box_begin)?((box_begin - seg_from)/length):0; - cmax = (seg_to > box_end)?((box_end - seg_from)/length):1; - csign=-1.0; + real_t length = seg_to - seg_from; + cmin = (seg_from < box_begin) ? ((box_begin - seg_from) / length) : 0; + cmax = (seg_to > box_end) ? ((box_end - seg_from) / length) : 1; + csign = -1.0; } else { if (seg_to > box_end || seg_from < box_begin) return false; - real_t length=seg_to-seg_from; - cmin = (seg_from > box_end)?(box_end - seg_from)/length:0; - cmax = (seg_to < box_begin)?(box_begin - seg_from)/length:1; - csign=1.0; + real_t length = seg_to - seg_from; + cmin = (seg_from > box_end) ? (box_end - seg_from) / length : 0; + cmax = (seg_to < box_begin) ? (box_begin - seg_from) / length : 1; + csign = 1.0; } if (cmin > min) { min = cmin; - axis=i; - sign=csign; + axis = i; + sign = csign; } if (cmax < max) max = cmax; @@ -331,38 +327,39 @@ bool Rect2::intersects_segment(const Point2& p_from, const Point2& p_to, Point2* return false; } - - Vector2 rel=p_to-p_from; + Vector2 rel = p_to - p_from; if (r_normal) { Vector2 normal; - normal[axis]=sign; - *r_normal=normal; + normal[axis] = sign; + *r_normal = normal; } if (r_pos) - *r_pos=p_from+rel*min; + *r_pos = p_from + rel * min; return true; } /* Point2i */ -Point2i Point2i::operator+(const Point2i& p_v) const { +Point2i Point2i::operator+(const Point2i &p_v) const { - return Point2i(x+p_v.x,y+p_v.y); + return Point2i(x + p_v.x, y + p_v.y); } -void Point2i::operator+=(const Point2i& p_v) { +void Point2i::operator+=(const Point2i &p_v) { - x+=p_v.x; y+=p_v.y; + x += p_v.x; + y += p_v.y; } -Point2i Point2i::operator-(const Point2i& p_v) const { +Point2i Point2i::operator-(const Point2i &p_v) const { - return Point2i(x-p_v.x,y-p_v.y); + return Point2i(x - p_v.x, y - p_v.y); } -void Point2i::operator-=(const Point2i& p_v) { +void Point2i::operator-=(const Point2i &p_v) { - x-=p_v.x; y-=p_v.y; + x -= p_v.x; + y -= p_v.y; } Point2i Point2i::operator*(const Point2i &p_v1) const { @@ -376,7 +373,8 @@ Point2i Point2i::operator*(const int &rvalue) const { }; void Point2i::operator*=(const int &rvalue) { - x *= rvalue; y *= rvalue; + x *= rvalue; + y *= rvalue; }; Point2i Point2i::operator/(const Point2i &p_v1) const { @@ -391,222 +389,212 @@ Point2i Point2i::operator/(const int &rvalue) const { void Point2i::operator/=(const int &rvalue) { - x /= rvalue; y /= rvalue; + x /= rvalue; + y /= rvalue; }; Point2i Point2i::operator-() const { - return Point2i(-x,-y); + return Point2i(-x, -y); } -bool Point2i::operator==(const Point2i& p_vec2) const { +bool Point2i::operator==(const Point2i &p_vec2) const { - return x==p_vec2.x && y==p_vec2.y; + return x == p_vec2.x && y == p_vec2.y; } -bool Point2i::operator!=(const Point2i& p_vec2) const { +bool Point2i::operator!=(const Point2i &p_vec2) const { - return x!=p_vec2.x || y!=p_vec2.y; + return x != p_vec2.x || y != p_vec2.y; } void Matrix32::invert() { - SWAP(elements[0][1],elements[1][0]); + SWAP(elements[0][1], elements[1][0]); elements[2] = basis_xform(-elements[2]); } Matrix32 Matrix32::inverse() const { - Matrix32 inv=*this; + Matrix32 inv = *this; inv.invert(); return inv; - } void Matrix32::affine_invert() { float det = basis_determinant(); - ERR_FAIL_COND(det==0); + ERR_FAIL_COND(det == 0); float idet = 1.0 / det; - SWAP( elements[0][0],elements[1][1] ); - elements[0]*=Vector2(idet,-idet); - elements[1]*=Vector2(-idet,idet); + SWAP(elements[0][0], elements[1][1]); + elements[0] *= Vector2(idet, -idet); + elements[1] *= Vector2(-idet, idet); elements[2] = basis_xform(-elements[2]); - } Matrix32 Matrix32::affine_inverse() const { - Matrix32 inv=*this; + Matrix32 inv = *this; inv.affine_invert(); return inv; } void Matrix32::rotate(real_t p_phi) { - Matrix32 rot(p_phi,Vector2()); + Matrix32 rot(p_phi, Vector2()); *this *= rot; } real_t Matrix32::get_rotation() const { - return Math::atan2(elements[1].x,elements[1].y); + return Math::atan2(elements[1].x, elements[1].y); } void Matrix32::set_rotation(real_t p_rot) { real_t cr = Math::cos(p_rot); real_t sr = Math::sin(p_rot); - elements[0][0]=cr; - elements[1][1]=cr; - elements[0][1]=-sr; - elements[1][0]=sr; + elements[0][0] = cr; + elements[1][1] = cr; + elements[0][1] = -sr; + elements[1][0] = sr; } -Matrix32::Matrix32(real_t p_rot, const Vector2& p_pos) { +Matrix32::Matrix32(real_t p_rot, const Vector2 &p_pos) { real_t cr = Math::cos(p_rot); real_t sr = Math::sin(p_rot); - elements[0][0]=cr; - elements[1][1]=cr; - elements[0][1]=-sr; - elements[1][0]=sr; - elements[2]=p_pos; + elements[0][0] = cr; + elements[1][1] = cr; + elements[0][1] = -sr; + elements[1][0] = sr; + elements[2] = p_pos; } Size2 Matrix32::get_scale() const { - return Size2( elements[0].length(), elements[1].length() ); + return Size2(elements[0].length(), elements[1].length()); } -void Matrix32::scale(const Size2& p_scale) { +void Matrix32::scale(const Size2 &p_scale) { - elements[0]*=p_scale; - elements[1]*=p_scale; - elements[2]*=p_scale; + elements[0] *= p_scale; + elements[1] *= p_scale; + elements[2] *= p_scale; } -void Matrix32::scale_basis(const Size2& p_scale) { - - elements[0]*=p_scale; - elements[1]*=p_scale; +void Matrix32::scale_basis(const Size2 &p_scale) { + elements[0] *= p_scale; + elements[1] *= p_scale; } -void Matrix32::translate( real_t p_tx, real_t p_ty) { +void Matrix32::translate(real_t p_tx, real_t p_ty) { - translate(Vector2(p_tx,p_ty)); + translate(Vector2(p_tx, p_ty)); } -void Matrix32::translate( const Vector2& p_translation ) { +void Matrix32::translate(const Vector2 &p_translation) { - elements[2]+=basis_xform(p_translation); + elements[2] += basis_xform(p_translation); } void Matrix32::orthonormalize() { // Gram-Schmidt Process - Vector2 x=elements[0]; - Vector2 y=elements[1]; + Vector2 x = elements[0]; + Vector2 y = elements[1]; x.normalize(); - y = (y-x*(x.dot(y))); + y = (y - x * (x.dot(y))); y.normalize(); - elements[0]=x; - elements[1]=y; + elements[0] = x; + elements[1] = y; } Matrix32 Matrix32::orthonormalized() const { - Matrix32 on=*this; + Matrix32 on = *this; on.orthonormalize(); return on; - } -bool Matrix32::operator==(const Matrix32& p_transform) const { +bool Matrix32::operator==(const Matrix32 &p_transform) const { - for(int i=0;i<3;i++) { - if (elements[i]!=p_transform.elements[i]) + for (int i = 0; i < 3; i++) { + if (elements[i] != p_transform.elements[i]) return false; } return true; } -bool Matrix32::operator!=(const Matrix32& p_transform) const { +bool Matrix32::operator!=(const Matrix32 &p_transform) const { - for(int i=0;i<3;i++) { - if (elements[i]!=p_transform.elements[i]) + for (int i = 0; i < 3; i++) { + if (elements[i] != p_transform.elements[i]) return true; } return false; - } -void Matrix32::operator*=(const Matrix32& p_transform) { +void Matrix32::operator*=(const Matrix32 &p_transform) { elements[2] = xform(p_transform.elements[2]); - float x0,x1,y0,y1; + float x0, x1, y0, y1; x0 = tdotx(p_transform.elements[0]); x1 = tdoty(p_transform.elements[0]); y0 = tdotx(p_transform.elements[1]); y1 = tdoty(p_transform.elements[1]); - elements[0][0]=x0; - elements[0][1]=x1; - elements[1][0]=y0; - elements[1][1]=y1; + elements[0][0] = x0; + elements[0][1] = x1; + elements[1][0] = y0; + elements[1][1] = y1; } - -Matrix32 Matrix32::operator*(const Matrix32& p_transform) const { +Matrix32 Matrix32::operator*(const Matrix32 &p_transform) const { Matrix32 t = *this; - t*=p_transform; + t *= p_transform; return t; - } -Matrix32 Matrix32::scaled(const Size2& p_scale) const { +Matrix32 Matrix32::scaled(const Size2 &p_scale) const { - Matrix32 copy=*this; + Matrix32 copy = *this; copy.scale(p_scale); return copy; - } -Matrix32 Matrix32::basis_scaled(const Size2& p_scale) const { +Matrix32 Matrix32::basis_scaled(const Size2 &p_scale) const { - Matrix32 copy=*this; + Matrix32 copy = *this; copy.scale_basis(p_scale); return copy; - } Matrix32 Matrix32::untranslated() const { - Matrix32 copy=*this; - copy.elements[2]=Vector2(); + Matrix32 copy = *this; + copy.elements[2] = Vector2(); return copy; } -Matrix32 Matrix32::translated(const Vector2& p_offset) const { +Matrix32 Matrix32::translated(const Vector2 &p_offset) const { - Matrix32 copy=*this; + Matrix32 copy = *this; copy.translate(p_offset); return copy; - } Matrix32 Matrix32::rotated(float p_phi) const { - Matrix32 copy=*this; + Matrix32 copy = *this; copy.rotate(p_phi); return copy; - } float Matrix32::basis_determinant() const { @@ -614,7 +602,7 @@ float Matrix32::basis_determinant() const { return elements[0].x * elements[1].y - elements[0].y * elements[1].x; } -Matrix32 Matrix32::interpolate_with(const Matrix32& p_transform, float p_c) const { +Matrix32 Matrix32::interpolate_with(const Matrix32 &p_transform, float p_c) const { //extract parameters Vector2 p1 = get_origin(); @@ -639,9 +627,9 @@ Matrix32 Matrix32::interpolate_with(const Matrix32& p_transform, float p_c) cons if (dot > 0.9995) { v = Vector2::linear_interpolate(v1, v2, p_c).normalized(); //linearly interpolate to avoid numerical precision issues } else { - real_t angle = p_c*Math::acos(dot); - Vector2 v3 = (v2 - v1*dot).normalized(); - v = v1*Math::cos(angle) + v3*Math::sin(angle); + real_t angle = p_c * Math::acos(dot); + Vector2 v3 = (v2 - v1 * dot).normalized(); + v = v1 * Math::cos(angle) + v3 * Math::sin(angle); } //construct matrix @@ -652,5 +640,5 @@ Matrix32 Matrix32::interpolate_with(const Matrix32& p_transform, float p_c) cons Matrix32::operator String() const { - return String(String()+elements[0]+", "+elements[1]+", "+elements[2]); + return String(String() + elements[0] + ", " + elements[1] + ", " + elements[2]); } diff --git a/core/math/math_2d.h b/core/math/math_2d.h index 2ec0dc39c5d..35e9274ac86 100644 --- a/core/math/math_2d.h +++ b/core/math/math_2d.h @@ -73,12 +73,11 @@ struct Vector2 { float height; }; - - _FORCE_INLINE_ float& operator[](int p_idx) { - return p_idx?y:x; + _FORCE_INLINE_ float &operator[](int p_idx) { + return p_idx ? y : x; } - _FORCE_INLINE_ const float& operator[](int p_idx) const { - return p_idx?y:x; + _FORCE_INLINE_ const float &operator[](int p_idx) const { + return p_idx ? y : x; } void normalize(); @@ -87,32 +86,32 @@ struct Vector2 { float length() const; float length_squared() const; - float distance_to(const Vector2& p_vector2) const; - float distance_squared_to(const Vector2& p_vector2) const; - float angle_to(const Vector2& p_vector2) const; - float angle_to_point(const Vector2& p_vector2) const; + float distance_to(const Vector2 &p_vector2) const; + float distance_squared_to(const Vector2 &p_vector2) const; + float angle_to(const Vector2 &p_vector2) const; + float angle_to_point(const Vector2 &p_vector2) const; - float dot(const Vector2& p_other) const; - float cross(const Vector2& p_other) const; + float dot(const Vector2 &p_other) const; + float cross(const Vector2 &p_other) const; Vector2 cross(real_t p_other) const; - Vector2 project(const Vector2& p_vec) const; + Vector2 project(const Vector2 &p_vec) const; - Vector2 plane_project(real_t p_d, const Vector2& p_vec) const; + Vector2 plane_project(real_t p_d, const Vector2 &p_vec) const; Vector2 clamped(real_t p_len) const; - _FORCE_INLINE_ static Vector2 linear_interpolate(const Vector2& p_a, const Vector2& p_b,float p_t); - _FORCE_INLINE_ Vector2 linear_interpolate(const Vector2& p_b,float p_t) const; - Vector2 cubic_interpolate(const Vector2& p_b,const Vector2& p_pre_a, const Vector2& p_post_b,float p_t) const; - Vector2 cubic_interpolate_soft(const Vector2& p_b,const Vector2& p_pre_a, const Vector2& p_post_b,float p_t) const; + _FORCE_INLINE_ static Vector2 linear_interpolate(const Vector2 &p_a, const Vector2 &p_b, float p_t); + _FORCE_INLINE_ Vector2 linear_interpolate(const Vector2 &p_b, float p_t) const; + Vector2 cubic_interpolate(const Vector2 &p_b, const Vector2 &p_pre_a, const Vector2 &p_post_b, float p_t) const; + Vector2 cubic_interpolate_soft(const Vector2 &p_b, const Vector2 &p_pre_a, const Vector2 &p_post_b, float p_t) const; - Vector2 slide(const Vector2& p_vec) const; - Vector2 reflect(const Vector2& p_vec) const; + Vector2 slide(const Vector2 &p_vec) const; + Vector2 reflect(const Vector2 &p_vec) const; - Vector2 operator+(const Vector2& p_v) const; - void operator+=(const Vector2& p_v); - Vector2 operator-(const Vector2& p_v) const; - void operator-=(const Vector2& p_v); + Vector2 operator+(const Vector2 &p_v) const; + void operator+=(const Vector2 &p_v); + Vector2 operator-(const Vector2 &p_v) const; + void operator-=(const Vector2 &p_v); Vector2 operator*(const Vector2 &p_v1) const; Vector2 operator*(const float &rvalue) const; @@ -127,70 +126,73 @@ struct Vector2 { Vector2 operator-() const; - bool operator==(const Vector2& p_vec2) const; - bool operator!=(const Vector2& p_vec2) const; + bool operator==(const Vector2 &p_vec2) const; + bool operator!=(const Vector2 &p_vec2) const; - bool operator<(const Vector2& p_vec2) const { return (x==p_vec2.x)?(y= (p_rect.pos.x + p_rect.size.width) ) + inline bool intersects(const Rect2 &p_rect) const { + if (pos.x >= (p_rect.pos.x + p_rect.size.width)) return false; - if ( (pos.x+size.width) <= p_rect.pos.x ) + if ((pos.x + size.width) <= p_rect.pos.x) return false; - if ( pos.y >= (p_rect.pos.y + p_rect.size.height) ) + if (pos.y >= (p_rect.pos.y + p_rect.size.height)) return false; - if ( (pos.y+size.height) <= p_rect.pos.y ) + if ((pos.y + size.height) <= p_rect.pos.y) return false; return true; } - inline float distance_to(const Vector2& p_point) const { + inline float distance_to(const Vector2 &p_point) const { float dist = 1e20; if (p_point.x < pos.x) { - dist=MIN(dist,pos.x-p_point.x); + dist = MIN(dist, pos.x - p_point.x); } if (p_point.y < pos.y) { - dist=MIN(dist,pos.y-p_point.y); + dist = MIN(dist, pos.y - p_point.y); } - if (p_point.x >= (pos.x+size.x) ) { - dist=MIN(p_point.x-(pos.x+size.x),dist); + if (p_point.x >= (pos.x + size.x)) { + dist = MIN(p_point.x - (pos.x + size.x), dist); } - if (p_point.y >= (pos.y+size.y) ) { - dist=MIN(p_point.y-(pos.y+size.y),dist); + if (p_point.y >= (pos.y + size.y)) { + dist = MIN(p_point.y - (pos.y + size.y), dist); } - if (dist==1e20) + if (dist == 1e20) return 0; else return dist; } - _FORCE_INLINE_ bool intersects_transformed(const Matrix32& p_xform, const Rect2& p_rect) const; + _FORCE_INLINE_ bool intersects_transformed(const Matrix32 &p_xform, const Rect2 &p_rect) const; - bool intersects_segment(const Point2& p_from, const Point2& p_to, Point2* r_pos=NULL, Point2* r_normal=NULL) const; + bool intersects_segment(const Point2 &p_from, const Point2 &p_to, Point2 *r_pos = NULL, Point2 *r_normal = NULL) const; - inline bool encloses(const Rect2& p_rect) const { - - return (p_rect.pos.x>=pos.x) && (p_rect.pos.y>=pos.y) && - ((p_rect.pos.x+p_rect.size.x)<(pos.x+size.x)) && - ((p_rect.pos.y+p_rect.size.y)<(pos.y+size.y)); + inline bool encloses(const Rect2 &p_rect) const { + return (p_rect.pos.x >= pos.x) && (p_rect.pos.y >= pos.y) && + ((p_rect.pos.x + p_rect.size.x) < (pos.x + size.x)) && + ((p_rect.pos.y + p_rect.size.y) < (pos.y + size.y)); } inline bool has_no_area() const { - return (size.x<=0 || size.y<=0); - + return (size.x <= 0 || size.y <= 0); } - inline Rect2 clip(const Rect2& p_rect) const { /// return a clipped rect + inline Rect2 clip(const Rect2 &p_rect) const { /// return a clipped rect - Rect2 new_rect=p_rect; + Rect2 new_rect = p_rect; - if (!intersects( new_rect )) + if (!intersects(new_rect)) return Rect2(); - new_rect.pos.x = MAX( p_rect.pos.x , pos.x ); - new_rect.pos.y = MAX( p_rect.pos.y , pos.y ); + new_rect.pos.x = MAX(p_rect.pos.x, pos.x); + new_rect.pos.y = MAX(p_rect.pos.y, pos.y); - Point2 p_rect_end=p_rect.pos+p_rect.size; - Point2 end=pos+size; + Point2 p_rect_end = p_rect.pos + p_rect.size; + Point2 end = pos + size; - new_rect.size.x=MIN(p_rect_end.x,end.x) - new_rect.pos.x; - new_rect.size.y=MIN(p_rect_end.y,end.y) - new_rect.pos.y; + new_rect.size.x = MIN(p_rect_end.x, end.x) - new_rect.pos.x; + new_rect.size.y = MIN(p_rect_end.y, end.y) - new_rect.pos.y; return new_rect; } - inline Rect2 merge(const Rect2& p_rect) const { ///< return a merged rect + inline Rect2 merge(const Rect2 &p_rect) const { ///< return a merged rect Rect2 new_rect; - new_rect.pos.x=MIN( p_rect.pos.x , pos.x ); - new_rect.pos.y=MIN( p_rect.pos.y , pos.y ); + new_rect.pos.x = MIN(p_rect.pos.x, pos.x); + new_rect.pos.y = MIN(p_rect.pos.y, pos.y); - - new_rect.size.x = MAX( p_rect.pos.x+p_rect.size.x , pos.x+size.x ); - new_rect.size.y = MAX( p_rect.pos.y+p_rect.size.y , pos.y+size.y ); + new_rect.size.x = MAX(p_rect.pos.x + p_rect.size.x, pos.x + size.x); + new_rect.size.y = MAX(p_rect.pos.y + p_rect.size.y, pos.y + size.y); new_rect.size = new_rect.size - new_rect.pos; //make relative again return new_rect; }; - inline bool has_point(const Point2& p_point) const { + inline bool has_point(const Point2 &p_point) const { if (p_point.x < pos.x) return false; if (p_point.y < pos.y) return false; - if (p_point.x >= (pos.x+size.x) ) + if (p_point.x >= (pos.x + size.x)) return false; - if (p_point.y >= (pos.y+size.y) ) + if (p_point.y >= (pos.y + size.y)) return false; return true; } - inline bool no_area() const { return (size.width<=0 || size.height<=0 ); } + inline bool no_area() const { return (size.width <= 0 || size.height <= 0); } - bool operator==(const Rect2& p_rect) const { return pos==p_rect.pos && size==p_rect.size; } - bool operator!=(const Rect2& p_rect) const { return pos!=p_rect.pos || size!=p_rect.size; } + bool operator==(const Rect2 &p_rect) const { return pos == p_rect.pos && size == p_rect.size; } + bool operator!=(const Rect2 &p_rect) const { return pos != p_rect.pos || size != p_rect.size; } inline Rect2 grow(real_t p_by) const { - Rect2 g=*this; - g.pos.x-=p_by; - g.pos.y-=p_by; - g.size.width+=p_by*2; - g.size.height+=p_by*2; + Rect2 g = *this; + g.pos.x -= p_by; + g.pos.y -= p_by; + g.size.width += p_by * 2; + g.size.height += p_by * 2; return g; } - inline Rect2 expand(const Vector2& p_vector) const { + inline Rect2 expand(const Vector2 &p_vector) const { Rect2 r = *this; r.expand_to(p_vector); return r; } - inline void expand_to(const Vector2& p_vector) { //in place function for speed + inline void expand_to(const Vector2 &p_vector) { //in place function for speed - Vector2 begin=pos; - Vector2 end=pos+size; + Vector2 begin = pos; + Vector2 end = pos + size; - if (p_vector.xend.x) - end.x=p_vector.x; - if (p_vector.y>end.y) - end.y=p_vector.y; + if (p_vector.x > end.x) + end.x = p_vector.x; + if (p_vector.y > end.y) + end.y = p_vector.y; - pos=begin; - size=end-begin; + pos = begin; + size = end - begin; } - - operator String() const { return String(pos)+", "+String(size); } + operator String() const { return String(pos) + ", " + String(size); } Rect2() {} - Rect2( float p_x, float p_y, float p_width, float p_height) { pos=Point2(p_x,p_y); size=Size2( p_width, p_height ); } - Rect2( const Point2& p_pos, const Size2& p_size ) { pos=p_pos; size=p_size; } + Rect2(float p_x, float p_y, float p_width, float p_height) { + pos = Point2(p_x, p_y); + size = Size2(p_width, p_height); + } + Rect2(const Point2 &p_pos, const Size2 &p_size) { + pos = p_pos; + size = p_size; + } }; - /* INTEGER STUFF */ struct Point2i { @@ -377,18 +379,17 @@ struct Point2i { int height; }; - - _FORCE_INLINE_ int& operator[](int p_idx) { - return p_idx?y:x; + _FORCE_INLINE_ int &operator[](int p_idx) { + return p_idx ? y : x; } - _FORCE_INLINE_ const int& operator[](int p_idx) const { - return p_idx?y:x; + _FORCE_INLINE_ const int &operator[](int p_idx) const { + return p_idx ? y : x; } - Point2i operator+(const Point2i& p_v) const; - void operator+=(const Point2i& p_v); - Point2i operator-(const Point2i& p_v) const; - void operator-=(const Point2i& p_v); + Point2i operator+(const Point2i &p_v) const; + void operator+=(const Point2i &p_v); + Point2i operator-(const Point2i &p_v) const; + void operator-=(const Point2i &p_v); Point2i operator*(const Point2i &p_v1) const; Point2i operator*(const int &rvalue) const; @@ -401,20 +402,29 @@ struct Point2i { void operator/=(const int &rvalue); Point2i operator-() const; - bool operator<(const Point2i& p_vec2) const { return (x==p_vec2.x)?(y(const Point2i& p_vec2) const { return (x==p_vec2.x)?(y>p_vec2.y):(x>p_vec2.x); } + bool operator<(const Point2i &p_vec2) const { return (x == p_vec2.x) ? (y < p_vec2.y) : (x < p_vec2.x); } + bool operator>(const Point2i &p_vec2) const { return (x == p_vec2.x) ? (y > p_vec2.y) : (x > p_vec2.x); } - bool operator==(const Point2i& p_vec2) const; - bool operator!=(const Point2i& p_vec2) const; + bool operator==(const Point2i &p_vec2) const; + bool operator!=(const Point2i &p_vec2) const; - float get_aspect() const { return width/(float)height; } + float get_aspect() const { return width / (float)height; } - operator String() const { return String::num(x)+", "+String::num(y); } + operator String() const { return String::num(x) + ", " + String::num(y); } - operator Vector2() const { return Vector2(x,y); } - inline Point2i(const Vector2& p_vec2) { x=(int)p_vec2.x; y=(int)p_vec2.y; } - inline Point2i(int p_x,int p_y) { x=p_x; y=p_y; } - inline Point2i() { x=0; y=0; } + operator Vector2() const { return Vector2(x, y); } + inline Point2i(const Vector2 &p_vec2) { + x = (int)p_vec2.x; + y = (int)p_vec2.y; + } + inline Point2i(int p_x, int p_y) { + x = p_x; + y = p_y; + } + inline Point2i() { + x = 0; + y = 0; + } }; typedef Point2i Size2i; @@ -424,145 +434,154 @@ struct Rect2i { Point2i pos; Size2i size; - const Point2i& get_pos() const { return pos; } - void set_pos(const Point2i& p_pos) { pos=p_pos; } - const Point2i& get_size() const { return size; } - void set_size(const Point2i& p_size) { size=p_size; } + const Point2i &get_pos() const { return pos; } + void set_pos(const Point2i &p_pos) { pos = p_pos; } + const Point2i &get_size() const { return size; } + void set_size(const Point2i &p_size) { size = p_size; } - int get_area() const { return size.width*size.height; } + int get_area() const { return size.width * size.height; } - inline bool intersects(const Rect2i& p_rect) const { - if ( pos.x > (p_rect.pos.x + p_rect.size.width) ) + inline bool intersects(const Rect2i &p_rect) const { + if (pos.x > (p_rect.pos.x + p_rect.size.width)) return false; - if ( (pos.x+size.width) < p_rect.pos.x ) + if ((pos.x + size.width) < p_rect.pos.x) return false; - if ( pos.y > (p_rect.pos.y + p_rect.size.height) ) + if (pos.y > (p_rect.pos.y + p_rect.size.height)) return false; - if ( (pos.y+size.height) < p_rect.pos.y ) + if ((pos.y + size.height) < p_rect.pos.y) return false; return true; } - inline bool encloses(const Rect2i& p_rect) const { - - return (p_rect.pos.x>=pos.x) && (p_rect.pos.y>=pos.y) && - ((p_rect.pos.x+p_rect.size.x)<(pos.x+size.x)) && - ((p_rect.pos.y+p_rect.size.y)<(pos.y+size.y)); + inline bool encloses(const Rect2i &p_rect) const { + return (p_rect.pos.x >= pos.x) && (p_rect.pos.y >= pos.y) && + ((p_rect.pos.x + p_rect.size.x) < (pos.x + size.x)) && + ((p_rect.pos.y + p_rect.size.y) < (pos.y + size.y)); } inline bool has_no_area() const { - return (size.x<=0 || size.y<=0); - + return (size.x <= 0 || size.y <= 0); } - inline Rect2i clip(const Rect2i& p_rect) const { /// return a clipped rect + inline Rect2i clip(const Rect2i &p_rect) const { /// return a clipped rect - Rect2i new_rect=p_rect; + Rect2i new_rect = p_rect; - if (!intersects( new_rect )) + if (!intersects(new_rect)) return Rect2i(); - new_rect.pos.x = MAX( p_rect.pos.x , pos.x ); - new_rect.pos.y = MAX( p_rect.pos.y , pos.y ); + new_rect.pos.x = MAX(p_rect.pos.x, pos.x); + new_rect.pos.y = MAX(p_rect.pos.y, pos.y); - Point2 p_rect_end=p_rect.pos+p_rect.size; - Point2 end=pos+size; + Point2 p_rect_end = p_rect.pos + p_rect.size; + Point2 end = pos + size; - new_rect.size.x=(int)(MIN(p_rect_end.x,end.x) - new_rect.pos.x); - new_rect.size.y=(int)(MIN(p_rect_end.y,end.y) - new_rect.pos.y); + new_rect.size.x = (int)(MIN(p_rect_end.x, end.x) - new_rect.pos.x); + new_rect.size.y = (int)(MIN(p_rect_end.y, end.y) - new_rect.pos.y); return new_rect; } - inline Rect2i merge(const Rect2i& p_rect) const { ///< return a merged rect + inline Rect2i merge(const Rect2i &p_rect) const { ///< return a merged rect Rect2i new_rect; - new_rect.pos.x=MIN( p_rect.pos.x , pos.x ); - new_rect.pos.y=MIN( p_rect.pos.y , pos.y ); + new_rect.pos.x = MIN(p_rect.pos.x, pos.x); + new_rect.pos.y = MIN(p_rect.pos.y, pos.y); - - new_rect.size.x = MAX( p_rect.pos.x+p_rect.size.x , pos.x+size.x ); - new_rect.size.y = MAX( p_rect.pos.y+p_rect.size.y , pos.y+size.y ); + new_rect.size.x = MAX(p_rect.pos.x + p_rect.size.x, pos.x + size.x); + new_rect.size.y = MAX(p_rect.pos.y + p_rect.size.y, pos.y + size.y); new_rect.size = new_rect.size - new_rect.pos; //make relative again return new_rect; }; - bool has_point(const Point2& p_point) const { + bool has_point(const Point2 &p_point) const { if (p_point.x < pos.x) return false; if (p_point.y < pos.y) return false; - if (p_point.x >= (pos.x+size.x) ) + if (p_point.x >= (pos.x + size.x)) return false; - if (p_point.y >= (pos.y+size.y) ) + if (p_point.y >= (pos.y + size.y)) return false; return true; } - bool no_area() { return (size.width<=0 || size.height<=0 ); } + bool no_area() { return (size.width <= 0 || size.height <= 0); } - bool operator==(const Rect2i& p_rect) const { return pos==p_rect.pos && size==p_rect.size; } - bool operator!=(const Rect2i& p_rect) const { return pos!=p_rect.pos || size!=p_rect.size; } + bool operator==(const Rect2i &p_rect) const { return pos == p_rect.pos && size == p_rect.size; } + bool operator!=(const Rect2i &p_rect) const { return pos != p_rect.pos || size != p_rect.size; } Rect2i grow(int p_by) const { - Rect2i g=*this; - g.pos.x-=p_by; - g.pos.y-=p_by; - g.size.width+=p_by*2; - g.size.height+=p_by*2; + Rect2i g = *this; + g.pos.x -= p_by; + g.pos.y -= p_by; + g.size.width += p_by * 2; + g.size.height += p_by * 2; return g; } - inline void expand_to(const Point2i& p_vector) { + inline void expand_to(const Point2i &p_vector) { - Point2i begin=pos; - Point2i end=pos+size; + Point2i begin = pos; + Point2i end = pos + size; - if (p_vector.xend.x) - end.x=p_vector.x; - if (p_vector.y>end.y) - end.y=p_vector.y; + if (p_vector.x > end.x) + end.x = p_vector.x; + if (p_vector.y > end.y) + end.y = p_vector.y; - pos=begin; - size=end-begin; + pos = begin; + size = end - begin; } + operator String() const { return String(pos) + ", " + String(size); } - operator String() const { return String(pos)+", "+String(size); } - - operator Rect2() const { return Rect2(pos,size); } - Rect2i(const Rect2& p_r2) { pos=p_r2.pos; size=p_r2.size; } + operator Rect2() const { return Rect2(pos, size); } + Rect2i(const Rect2 &p_r2) { + pos = p_r2.pos; + size = p_r2.size; + } Rect2i() {} - Rect2i( int p_x, int p_y, int p_width, int p_height) { pos=Point2(p_x,p_y); size=Size2( p_width, p_height ); } - Rect2i( const Point2& p_pos, const Size2& p_size ) { pos=p_pos; size=p_size; } + Rect2i(int p_x, int p_y, int p_width, int p_height) { + pos = Point2(p_x, p_y); + size = Size2(p_width, p_height); + } + Rect2i(const Point2 &p_pos, const Size2 &p_size) { + pos = p_pos; + size = p_size; + } }; - - struct Matrix32 { Vector2 elements[3]; - _FORCE_INLINE_ float tdotx(const Vector2& v) const { return elements[0][0] * v.x + elements[1][0] * v.y; } - _FORCE_INLINE_ float tdoty(const Vector2& v) const { return elements[0][1] * v.x + elements[1][1] * v.y; } + _FORCE_INLINE_ float tdotx(const Vector2 &v) const { return elements[0][0] * v.x + elements[1][0] * v.y; } + _FORCE_INLINE_ float tdoty(const Vector2 &v) const { return elements[0][1] * v.x + elements[1][1] * v.y; } - const Vector2& operator[](int p_idx) const { return elements[p_idx]; } - Vector2& operator[](int p_idx) { return elements[p_idx]; } + const Vector2 &operator[](int p_idx) const { return elements[p_idx]; } + Vector2 &operator[](int p_idx) { return elements[p_idx]; } - _FORCE_INLINE_ Vector2 get_axis(int p_axis) const { ERR_FAIL_INDEX_V(p_axis,3,Vector2()); return elements[p_axis]; } - _FORCE_INLINE_ void set_axis(int p_axis,const Vector2& p_vec) { ERR_FAIL_INDEX(p_axis,3); elements[p_axis]=p_vec; } + _FORCE_INLINE_ Vector2 get_axis(int p_axis) const { + ERR_FAIL_INDEX_V(p_axis, 3, Vector2()); + return elements[p_axis]; + } + _FORCE_INLINE_ void set_axis(int p_axis, const Vector2 &p_vec) { + ERR_FAIL_INDEX(p_axis, 3); + elements[p_axis] = p_vec; + } void invert(); Matrix32 inverse() const; @@ -572,24 +591,24 @@ struct Matrix32 { void set_rotation(real_t p_phi); real_t get_rotation() const; - _FORCE_INLINE_ void set_rotation_and_scale(real_t p_phi,const Size2& p_scale); + _FORCE_INLINE_ void set_rotation_and_scale(real_t p_phi, const Size2 &p_scale); void rotate(real_t p_phi); - void scale(const Size2& p_scale); - void scale_basis(const Size2& p_scale); - void translate( real_t p_tx, real_t p_ty); - void translate( const Vector2& p_translation ); + void scale(const Size2 &p_scale); + void scale_basis(const Size2 &p_scale); + void translate(real_t p_tx, real_t p_ty); + void translate(const Vector2 &p_translation); float basis_determinant() const; Size2 get_scale() const; - _FORCE_INLINE_ const Vector2& get_origin() const { return elements[2]; } - _FORCE_INLINE_ void set_origin(const Vector2& p_origin) { elements[2]=p_origin; } + _FORCE_INLINE_ const Vector2 &get_origin() const { return elements[2]; } + _FORCE_INLINE_ void set_origin(const Vector2 &p_origin) { elements[2] = p_origin; } - Matrix32 scaled(const Size2& p_scale) const; - Matrix32 basis_scaled(const Size2& p_scale) const; - Matrix32 translated(const Vector2& p_offset) const; + Matrix32 scaled(const Size2 &p_scale) const; + Matrix32 basis_scaled(const Size2 &p_scale) const; + Matrix32 translated(const Vector2 &p_offset) const; Matrix32 rotated(float p_phi) const; Matrix32 untranslated() const; @@ -597,20 +616,20 @@ struct Matrix32 { void orthonormalize(); Matrix32 orthonormalized() const; - bool operator==(const Matrix32& p_transform) const; - bool operator!=(const Matrix32& p_transform) const; + bool operator==(const Matrix32 &p_transform) const; + bool operator!=(const Matrix32 &p_transform) const; - void operator*=(const Matrix32& p_transform); - Matrix32 operator*(const Matrix32& p_transform) const; + void operator*=(const Matrix32 &p_transform); + Matrix32 operator*(const Matrix32 &p_transform) const; - Matrix32 interpolate_with(const Matrix32& p_transform, float p_c) const; + Matrix32 interpolate_with(const Matrix32 &p_transform, float p_c) const; - _FORCE_INLINE_ Vector2 basis_xform(const Vector2& p_vec) const; - _FORCE_INLINE_ Vector2 basis_xform_inv(const Vector2& p_vec) const; - _FORCE_INLINE_ Vector2 xform(const Vector2& p_vec) const; - _FORCE_INLINE_ Vector2 xform_inv(const Vector2& p_vec) const; - _FORCE_INLINE_ Rect2 xform(const Rect2& p_vec) const; - _FORCE_INLINE_ Rect2 xform_inv(const Rect2& p_vec) const; + _FORCE_INLINE_ Vector2 basis_xform(const Vector2 &p_vec) const; + _FORCE_INLINE_ Vector2 basis_xform_inv(const Vector2 &p_vec) const; + _FORCE_INLINE_ Vector2 xform(const Vector2 &p_vec) const; + _FORCE_INLINE_ Vector2 xform_inv(const Vector2 &p_vec) const; + _FORCE_INLINE_ Rect2 xform(const Rect2 &p_vec) const; + _FORCE_INLINE_ Rect2 xform_inv(const Rect2 &p_vec) const; operator String() const; @@ -624,232 +643,226 @@ struct Matrix32 { elements[2][1] = oy; } - Matrix32(real_t p_rot, const Vector2& p_pos); - Matrix32() { elements[0][0]=1.0; elements[1][1]=1.0; } + Matrix32(real_t p_rot, const Vector2 &p_pos); + Matrix32() { + elements[0][0] = 1.0; + elements[1][1] = 1.0; + } }; -bool Rect2::intersects_transformed(const Matrix32& p_xform, const Rect2& p_rect) const { +bool Rect2::intersects_transformed(const Matrix32 &p_xform, const Rect2 &p_rect) const { //SAT intersection between local and transformed rect2 - Vector2 xf_points[4]={ + Vector2 xf_points[4] = { p_xform.xform(p_rect.pos), - p_xform.xform(Vector2(p_rect.pos.x+p_rect.size.x,p_rect.pos.y)), - p_xform.xform(Vector2(p_rect.pos.x,p_rect.pos.y+p_rect.size.y)), - p_xform.xform(Vector2(p_rect.pos.x+p_rect.size.x,p_rect.pos.y+p_rect.size.y)), + p_xform.xform(Vector2(p_rect.pos.x + p_rect.size.x, p_rect.pos.y)), + p_xform.xform(Vector2(p_rect.pos.x, p_rect.pos.y + p_rect.size.y)), + p_xform.xform(Vector2(p_rect.pos.x + p_rect.size.x, p_rect.pos.y + p_rect.size.y)), }; real_t low_limit; //base rect2 first (faster) - if (xf_points[0].y>pos.y) + if (xf_points[0].y > pos.y) goto next1; - if (xf_points[1].y>pos.y) + if (xf_points[1].y > pos.y) goto next1; - if (xf_points[2].y>pos.y) + if (xf_points[2].y > pos.y) goto next1; - if (xf_points[3].y>pos.y) + if (xf_points[3].y > pos.y) goto next1; return false; - next1: +next1: - low_limit=pos.y+size.y; + low_limit = pos.y + size.y; - if (xf_points[0].ypos.x) + if (xf_points[0].x > pos.x) goto next3; - if (xf_points[1].x>pos.x) + if (xf_points[1].x > pos.x) goto next3; - if (xf_points[2].x>pos.x) + if (xf_points[2].x > pos.x) goto next3; - if (xf_points[3].x>pos.x) + if (xf_points[3].x > pos.x) goto next3; return false; - next3: +next3: - low_limit=pos.x+size.x; + low_limit = pos.x + size.x; - if (xf_points[0].x maxb ) + if (mina > maxb) return false; - if ( minb > maxa ) + if (minb > maxa) return false; - maxa=p_xform.elements[1].dot(xf_points2[0]); - mina=maxa; + maxa = p_xform.elements[1].dot(xf_points2[0]); + mina = maxa; dp = p_xform.elements[1].dot(xf_points2[1]); - maxa=MAX(dp,maxa); - mina=MIN(dp,mina); + maxa = MAX(dp, maxa); + mina = MIN(dp, mina); dp = p_xform.elements[1].dot(xf_points2[2]); - maxa=MAX(dp,maxa); - mina=MIN(dp,mina); + maxa = MAX(dp, maxa); + mina = MIN(dp, mina); dp = p_xform.elements[1].dot(xf_points2[3]); - maxa=MAX(dp,maxa); - mina=MIN(dp,mina); + maxa = MAX(dp, maxa); + mina = MIN(dp, mina); - maxb=p_xform.elements[1].dot(xf_points[0]); - minb=maxb; + maxb = p_xform.elements[1].dot(xf_points[0]); + minb = maxb; dp = p_xform.elements[1].dot(xf_points[1]); - maxb=MAX(dp,maxb); - minb=MIN(dp,minb); + maxb = MAX(dp, maxb); + minb = MIN(dp, minb); dp = p_xform.elements[1].dot(xf_points[2]); - maxb=MAX(dp,maxb); - minb=MIN(dp,minb); + maxb = MAX(dp, maxb); + minb = MIN(dp, minb); dp = p_xform.elements[1].dot(xf_points[3]); - maxb=MAX(dp,maxb); - minb=MIN(dp,minb); + maxb = MAX(dp, maxb); + minb = MIN(dp, minb); - - if ( mina > maxb ) + if (mina > maxb) return false; - if ( minb > maxa ) + if (minb > maxa) return false; - return true; - } -Vector2 Matrix32::basis_xform(const Vector2& v) const { +Vector2 Matrix32::basis_xform(const Vector2 &v) const { return Vector2( - tdotx(v), - tdoty(v) - ); + tdotx(v), + tdoty(v)); } -Vector2 Matrix32::basis_xform_inv(const Vector2& v) const{ +Vector2 Matrix32::basis_xform_inv(const Vector2 &v) const { return Vector2( - elements[0].dot(v), - elements[1].dot(v) - ); + elements[0].dot(v), + elements[1].dot(v)); } -Vector2 Matrix32::xform(const Vector2& v) const { +Vector2 Matrix32::xform(const Vector2 &v) const { return Vector2( - tdotx(v), - tdoty(v) - ) + elements[2]; + tdotx(v), + tdoty(v)) + + elements[2]; } -Vector2 Matrix32::xform_inv(const Vector2& p_vec) const { +Vector2 Matrix32::xform_inv(const Vector2 &p_vec) const { Vector2 v = p_vec - elements[2]; return Vector2( - elements[0].dot(v), - elements[1].dot(v) - ); - + elements[0].dot(v), + elements[1].dot(v)); } -Rect2 Matrix32::xform(const Rect2& p_rect) const { +Rect2 Matrix32::xform(const Rect2 &p_rect) const { - Vector2 x=elements[0]*p_rect.size.x; - Vector2 y=elements[1]*p_rect.size.y; - Vector2 pos = xform( p_rect.pos ); + Vector2 x = elements[0] * p_rect.size.x; + Vector2 y = elements[1] * p_rect.size.y; + Vector2 pos = xform(p_rect.pos); Rect2 new_rect; - new_rect.pos=pos; - new_rect.expand_to( pos+x ); - new_rect.expand_to( pos+y ); - new_rect.expand_to( pos+x+y ); + new_rect.pos = pos; + new_rect.expand_to(pos + x); + new_rect.expand_to(pos + y); + new_rect.expand_to(pos + x + y); return new_rect; } -void Matrix32::set_rotation_and_scale(real_t p_rot,const Size2& p_scale) { - - elements[0][0]=Math::cos(p_rot)*p_scale.x; - elements[1][1]=Math::cos(p_rot)*p_scale.y; - elements[0][1]=-Math::sin(p_rot)*p_scale.x; - elements[1][0]=Math::sin(p_rot)*p_scale.y; +void Matrix32::set_rotation_and_scale(real_t p_rot, const Size2 &p_scale) { + elements[0][0] = Math::cos(p_rot) * p_scale.x; + elements[1][1] = Math::cos(p_rot) * p_scale.y; + elements[0][1] = -Math::sin(p_rot) * p_scale.x; + elements[1][0] = Math::sin(p_rot) * p_scale.y; } -Rect2 Matrix32::xform_inv(const Rect2& p_rect) const { +Rect2 Matrix32::xform_inv(const Rect2 &p_rect) const { - Vector2 ends[4]={ - xform_inv( p_rect.pos ), - xform_inv( Vector2(p_rect.pos.x,p_rect.pos.y+p_rect.size.y ) ), - xform_inv( Vector2(p_rect.pos.x+p_rect.size.x,p_rect.pos.y+p_rect.size.y ) ), - xform_inv( Vector2(p_rect.pos.x+p_rect.size.x,p_rect.pos.y ) ) + Vector2 ends[4] = { + xform_inv(p_rect.pos), + xform_inv(Vector2(p_rect.pos.x, p_rect.pos.y + p_rect.size.y)), + xform_inv(Vector2(p_rect.pos.x + p_rect.size.x, p_rect.pos.y + p_rect.size.y)), + xform_inv(Vector2(p_rect.pos.x + p_rect.size.x, p_rect.pos.y)) }; Rect2 new_rect; - new_rect.pos=ends[0]; + new_rect.pos = ends[0]; new_rect.expand_to(ends[1]); new_rect.expand_to(ends[2]); new_rect.expand_to(ends[3]); @@ -857,5 +870,4 @@ Rect2 Matrix32::xform_inv(const Rect2& p_rect) const { return new_rect; } - #endif diff --git a/core/math/math_defs.h b/core/math/math_defs.h index feaff38a449..08f4e27e645 100644 --- a/core/math/math_defs.h +++ b/core/math/math_defs.h @@ -30,11 +30,11 @@ #define MATH_DEFS_H #define CMP_EPSILON 0.00001 -#define CMP_EPSILON2 (CMP_EPSILON*CMP_EPSILON) +#define CMP_EPSILON2 (CMP_EPSILON * CMP_EPSILON) #define CMP_NORMALIZE_TOLERANCE 0.000001 #define CMP_POINT_IN_PLANE_EPSILON 0.00001 -#define USEC_TO_SEC(m_usec) ((m_usec)/1000000.0) +#define USEC_TO_SEC(m_usec) ((m_usec) / 1000000.0) /** * "Real" is a type that will be translated to either floats or fixed depending * on the compilation setting @@ -42,11 +42,10 @@ enum ClockDirection { - CLOCKWISE, + CLOCKWISE, COUNTERCLOCKWISE }; - #ifdef REAL_T_IS_DOUBLE typedef double real_t; @@ -57,5 +56,4 @@ typedef float real_t; #endif - #endif // MATH_DEFS_H diff --git a/core/math/math_funcs.cpp b/core/math/math_funcs.cpp index 38f45e331be..a8a06338472 100644 --- a/core/math/math_funcs.cpp +++ b/core/math/math_funcs.cpp @@ -29,10 +29,9 @@ #include "math_funcs.h" #include "core/os/os.h" -#include #include "float.h" -uint32_t Math::default_seed=1; - +#include +uint32_t Math::default_seed = 1; #define PHI 0x9e3779b9 @@ -49,8 +48,8 @@ uint32_t Math::rand_from_seed(uint32_t *seed) { s = 0x12345987; k = s / 127773; s = 16807 * (s - k * 127773) - 2836 * k; -// if (s < 0) -// s += 2147483647; + // if (s < 0) + // s += 2147483647; (*seed) = s; return (s & Math::RANDOM_MAX); #else @@ -70,19 +69,19 @@ void Math::seed(uint32_t x) { for (i = 3; i < 4096; i++) Q[i] = Q[i - 3] ^ Q[i - 2] ^ PHI ^ i; #else - default_seed=x; + default_seed = x; #endif } void Math::randomize() { OS::Time time = OS::get_singleton()->get_time(); - seed(OS::get_singleton()->get_ticks_usec()*(time.hour+1)*(time.min+1)*(time.sec+1)*rand()); /* *OS::get_singleton()->get_time().sec); // windows doesn't have get_time(), returns always 0 */ + seed(OS::get_singleton()->get_ticks_usec() * (time.hour + 1) * (time.min + 1) * (time.sec + 1) * rand()); /* *OS::get_singleton()->get_time().sec); // windows doesn't have get_time(), returns always 0 */ } uint32_t Math::rand() { - return rand_from_seed(&default_seed)&0x7FFFFFFF; + return rand_from_seed(&default_seed) & 0x7FFFFFFF; } double Math::randf() { @@ -93,19 +92,16 @@ double Math::randf() { double Math::sin(double p_x) { return ::sin(p_x); - } double Math::cos(double p_x) { return ::cos(p_x); - } double Math::tan(double p_x) { return ::tan(p_x); - } double Math::sinh(double p_x) { @@ -122,31 +118,29 @@ double Math::tanh(double p_x) { return ::tanh(p_x); } - double Math::deg2rad(double p_y) { - return p_y*Math_PI/180.0; + return p_y * Math_PI / 180.0; } double Math::rad2deg(double p_y) { - return p_y*180.0/Math_PI; + return p_y * 180.0 / Math_PI; } double Math::round(double p_val) { - if (p_val>=0) { - return ::floor(p_val+0.5); + if (p_val >= 0) { + return ::floor(p_val + 0.5); } else { - p_val=-p_val; - return -::floor(p_val+0.5); + p_val = -p_val; + return -::floor(p_val + 0.5); } } double Math::asin(double p_x) { return ::asin(p_x); - } double Math::acos(double p_x) { @@ -159,42 +153,40 @@ double Math::atan(double p_x) { return ::atan(p_x); } -double Math::dectime(double p_value,double p_amount, double p_step) { +double Math::dectime(double p_value, double p_amount, double p_step) { float sgn = p_value < 0 ? -1.0 : 1.0; float val = absf(p_value); - val-=p_amount*p_step; - if (val<0.0) - val=0.0; - return val*sgn; + val -= p_amount * p_step; + if (val < 0.0) + val = 0.0; + return val * sgn; } double Math::atan2(double p_y, double p_x) { - return ::atan2(p_y,p_x); - + return ::atan2(p_y, p_x); } double Math::sqrt(double p_x) { return ::sqrt(p_x); } -double Math::fmod(double p_x,double p_y) { +double Math::fmod(double p_x, double p_y) { - return ::fmod(p_x,p_y); + return ::fmod(p_x, p_y); } -double Math::fposmod(double p_x,double p_y) { +double Math::fposmod(double p_x, double p_y) { - if (p_x>=0) { + if (p_x >= 0) { - return Math::fmod(p_x,p_y); + return Math::fmod(p_x, p_y); } else { - return p_y-Math::fmod(-p_x,p_y); + return p_y - Math::fmod(-p_x, p_y); } - } double Math::floor(double p_x) { @@ -208,8 +200,8 @@ double Math::ceil(double p_x) { int Math::step_decimals(double p_step) { - static const int maxn=9; - static const double sd[maxn]={ + static const int maxn = 9; + static const double sd[maxn] = { 0.9999, // somehow compensate for floating point error 0.09999, 0.009999, @@ -221,9 +213,9 @@ int Math::step_decimals(double p_step) { 0.000000009999 }; - double as=absf(p_step); - for(int i=0;i=sd[i]) { + double as = absf(p_step); + for (int i = 0; i < maxn; i++) { + if (as >= sd[i]) { return i; } } @@ -233,41 +225,40 @@ int Math::step_decimals(double p_step) { double Math::ease(double p_x, double p_c) { - if (p_x<0) - p_x=0; - else if (p_x>1.0) - p_x=1.0; - if (p_c>0) { - if (p_c<1.0) { - return 1.0-Math::pow(1.0-p_x,1.0/p_c); + if (p_x < 0) + p_x = 0; + else if (p_x > 1.0) + p_x = 1.0; + if (p_c > 0) { + if (p_c < 1.0) { + return 1.0 - Math::pow(1.0 - p_x, 1.0 / p_c); } else { - return Math::pow(p_x,p_c); + return Math::pow(p_x, p_c); } - } else if (p_c<0) { + } else if (p_c < 0) { //inout ease - if (p_x<0.5) { - return Math::pow(p_x*2.0,-p_c)*0.5; + if (p_x < 0.5) { + return Math::pow(p_x * 2.0, -p_c) * 0.5; } else { - return (1.0-Math::pow(1.0-(p_x-0.5)*2.0,-p_c))*0.5+0.5; + return (1.0 - Math::pow(1.0 - (p_x - 0.5) * 2.0, -p_c)) * 0.5 + 0.5; } } else return 0; // no ease (raw) - } -double Math::stepify(double p_value,double p_step) { +double Math::stepify(double p_value, double p_step) { - if (p_step!=0) { + if (p_step != 0) { - p_value=floor( p_value / p_step + 0.5 ) * p_step; + p_value = floor(p_value / p_step + 0.5) * p_step; } return p_value; } bool Math::is_nan(double p_val) { - return (p_val!=p_val); + return (p_val != p_val); } bool Math::is_inf(double p_val) { @@ -277,7 +268,6 @@ bool Math::is_inf(double p_val) { #else return isinf(p_val); #endif - } uint32_t Math::larger_prime(uint32_t p_val) { @@ -315,11 +305,11 @@ uint32_t Math::larger_prime(uint32_t p_val) { 0, }; - int idx=0; + int idx = 0; while (true) { - ERR_FAIL_COND_V(primes[idx]==0,0); - if (primes[idx]>p_val) + ERR_FAIL_COND_V(primes[idx] == 0, 0); + if (primes[idx] > p_val) return primes[idx]; idx++; } @@ -330,13 +320,13 @@ uint32_t Math::larger_prime(uint32_t p_val) { double Math::random(double from, double to) { unsigned int r = Math::rand(); - double ret = (double)r/(double)RANDOM_MAX; - return (ret)*(to-from) + from; + double ret = (double)r / (double)RANDOM_MAX; + return (ret) * (to - from) + from; } double Math::pow(double x, double y) { - return ::pow(x,y); + return ::pow(x, y); } double Math::log(double x) { diff --git a/core/math/math_funcs.h b/core/math/math_funcs.h index a5195e554bd..294b8150005 100644 --- a/core/math/math_funcs.h +++ b/core/math/math_funcs.h @@ -29,8 +29,8 @@ #ifndef MATH_FUNCS_H #define MATH_FUNCS_H -#include "typedefs.h" #include "math_defs.h" +#include "typedefs.h" #ifndef NO_MATH_H #include "math.h" @@ -38,13 +38,13 @@ class Math { - static uint32_t default_seed; + public: - Math() {}; // useless to instance + Math(){}; // useless to instance enum { - RANDOM_MAX=2147483647L + RANDOM_MAX = 2147483647L }; static double sin(double p_x); @@ -60,35 +60,32 @@ public: static double deg2rad(double p_y); static double rad2deg(double p_y); static double sqrt(double p_x); - static double fmod(double p_x,double p_y); - static double fposmod(double p_x,double p_y); + static double fmod(double p_x, double p_y); + static double fposmod(double p_x, double p_y); static uint32_t rand_from_seed(uint32_t *seed); static double floor(double p_x); static double ceil(double p_x); static double ease(double p_x, double p_c); static int step_decimals(double p_step); - static double stepify(double p_value,double p_step); - static void seed(uint32_t x=0); + static double stepify(double p_value, double p_step); + static void seed(uint32_t x = 0); static void randomize(); static uint32_t larger_prime(uint32_t p_val); - static double dectime(double p_value,double p_amount, double p_step); - + static double dectime(double p_value, double p_amount, double p_step); static inline double linear2db(double p_linear) { - return Math::log( p_linear ) * 8.6858896380650365530225783783321; + return Math::log(p_linear) * 8.6858896380650365530225783783321; } static inline double db2linear(double p_db) { - return Math::exp( p_db * 0.11512925464970228420089957273422 ); + return Math::exp(p_db * 0.11512925464970228420089957273422); } static bool is_nan(double p_val); static bool is_inf(double p_val); - - static uint32_t rand(); static double randf(); @@ -96,7 +93,6 @@ public: static double random(double from, double to); - static _FORCE_INLINE_ real_t abs(real_t g) { #ifdef REAL_T_IS_DOUBLE @@ -115,8 +111,8 @@ public: uint32_t i; } u; - u.f=g; - u.i&=2147483647u; + u.f = g; + u.i &= 2147483647u; return u.f; } @@ -126,8 +122,8 @@ public: double d; uint64_t i; } u; - u.d=g; - u.i&=(uint64_t)9223372036854775807ll; + u.d = g; + u.i &= (uint64_t)9223372036854775807ll; return u.d; } @@ -137,11 +133,10 @@ public: static int b; #if (defined(_WIN32_WINNT) && _WIN32_WINNT >= 0x0603) || WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP // windows 8 phone? - b = (int)((a>0.0f) ? (a + 0.5f):(a -0.5f)); + b = (int)((a > 0.0f) ? (a + 0.5f) : (a - 0.5f)); #elif defined(_MSC_VER) && _MSC_VER < 1800 - __asm fld a - __asm fistp b + __asm fld a __asm fistp b /*#elif defined( __GNUC__ ) && ( defined( __i386__ ) || defined( __x86_64__ ) ) // use AT&T inline assembly style, document that // we use memory as output (=m) and input (m) @@ -152,12 +147,11 @@ public: : "m" (a));*/ #else - b=lrintf(a); //assuming everything but msvc 2012 or earlier has lrint + b = lrintf(a); //assuming everything but msvc 2012 or earlier has lrint #endif - return b; + return b; } - #if defined(__GNUC__) static _FORCE_INLINE_ int64_t dtoll(double p_double) { return (int64_t)p_double; } ///@TODO OPTIMIZE @@ -168,16 +162,14 @@ public: static _FORCE_INLINE_ float lerp(float a, float b, float c) { - return a+(b-a)*c; + return a + (b - a) * c; } static double pow(double x, double y); static double log(double x); static double exp(double x); - }; - #define Math_PI 3.14159265358979323846 #define Math_SQRT12 0.7071067811865475244008443621048490 diff --git a/core/math/matrix3.cpp b/core/math/matrix3.cpp index c30401cc242..243e5fdf6de 100644 --- a/core/math/matrix3.cpp +++ b/core/math/matrix3.cpp @@ -30,66 +30,63 @@ #include "math_funcs.h" #include "os/copymem.h" -#define cofac(row1,col1, row2, col2)\ +#define cofac(row1, col1, row2, col2) \ (elements[row1][col1] * elements[row2][col2] - elements[row1][col2] * elements[row2][col1]) -void Matrix3::from_z(const Vector3& p_z) { +void Matrix3::from_z(const Vector3 &p_z) { - if (Math::abs(p_z.z) > Math_SQRT12 ) { + if (Math::abs(p_z.z) > Math_SQRT12) { // choose p in y-z plane - real_t a = p_z[1]*p_z[1] + p_z[2]*p_z[2]; - real_t k = 1.0/Math::sqrt(a); - elements[0]=Vector3(0,-p_z[2]*k,p_z[1]*k); - elements[1]=Vector3(a*k,-p_z[0]*elements[0][2],p_z[0]*elements[0][1]); + real_t a = p_z[1] * p_z[1] + p_z[2] * p_z[2]; + real_t k = 1.0 / Math::sqrt(a); + elements[0] = Vector3(0, -p_z[2] * k, p_z[1] * k); + elements[1] = Vector3(a * k, -p_z[0] * elements[0][2], p_z[0] * elements[0][1]); } else { // choose p in x-y plane - real_t a = p_z.x*p_z.x + p_z.y*p_z.y; - real_t k = 1.0/Math::sqrt(a); - elements[0]=Vector3(-p_z.y*k,p_z.x*k,0); - elements[1]=Vector3(-p_z.z*elements[0].y,p_z.z*elements[0].x,a*k); + real_t a = p_z.x * p_z.x + p_z.y * p_z.y; + real_t k = 1.0 / Math::sqrt(a); + elements[0] = Vector3(-p_z.y * k, p_z.x * k, 0); + elements[1] = Vector3(-p_z.z * elements[0].y, p_z.z * elements[0].x, a * k); } - elements[2]=p_z; + elements[2] = p_z; } void Matrix3::invert() { - - real_t co[3]={ + real_t co[3] = { cofac(1, 1, 2, 2), cofac(1, 2, 2, 0), cofac(1, 0, 2, 1) }; - real_t det = elements[0][0] * co[0]+ - elements[0][1] * co[1]+ - elements[0][2] * co[2]; + real_t det = elements[0][0] * co[0] + + elements[0][1] * co[1] + + elements[0][2] * co[2]; - ERR_FAIL_COND( det == 0 ); - real_t s = 1.0/det; - - set( co[0]*s, cofac(0, 2, 2, 1) * s, cofac(0, 1, 1, 2) * s, - co[1]*s, cofac(0, 0, 2, 2) * s, cofac(0, 2, 1, 0) * s, - co[2]*s, cofac(0, 1, 2, 0) * s, cofac(0, 0, 1, 1) * s ); + ERR_FAIL_COND(det == 0); + real_t s = 1.0 / det; + set(co[0] * s, cofac(0, 2, 2, 1) * s, cofac(0, 1, 1, 2) * s, + co[1] * s, cofac(0, 0, 2, 2) * s, cofac(0, 2, 1, 0) * s, + co[2] * s, cofac(0, 1, 2, 0) * s, cofac(0, 0, 1, 1) * s); } void Matrix3::orthonormalize() { // Gram-Schmidt Process - Vector3 x=get_axis(0); - Vector3 y=get_axis(1); - Vector3 z=get_axis(2); + Vector3 x = get_axis(0); + Vector3 y = get_axis(1); + Vector3 z = get_axis(2); x.normalize(); - y = (y-x*(x.dot(y))); + y = (y - x * (x.dot(y))); y.normalize(); - z = (z-x*(x.dot(z))-y*(y.dot(z))); + z = (z - x * (x.dot(z)) - y * (y.dot(z))); z.normalize(); - set_axis(0,x); - set_axis(1,y); - set_axis(2,z); - + set_axis(0, x); + set_axis(1, y); + set_axis(2, z); } Matrix3 Matrix3::orthonormalized() const { @@ -99,42 +96,41 @@ Matrix3 Matrix3::orthonormalized() const { return c; } - Matrix3 Matrix3::inverse() const { - Matrix3 inv=*this; + Matrix3 inv = *this; inv.invert(); return inv; } void Matrix3::transpose() { - SWAP(elements[0][1],elements[1][0]); - SWAP(elements[0][2],elements[2][0]); - SWAP(elements[1][2],elements[2][1]); + SWAP(elements[0][1], elements[1][0]); + SWAP(elements[0][2], elements[2][0]); + SWAP(elements[1][2], elements[2][1]); } Matrix3 Matrix3::transposed() const { - Matrix3 tr=*this; + Matrix3 tr = *this; tr.transpose(); return tr; } -void Matrix3::scale(const Vector3& p_scale) { +void Matrix3::scale(const Vector3 &p_scale) { - elements[0][0]*=p_scale.x; - elements[1][0]*=p_scale.x; - elements[2][0]*=p_scale.x; - elements[0][1]*=p_scale.y; - elements[1][1]*=p_scale.y; - elements[2][1]*=p_scale.y; - elements[0][2]*=p_scale.z; - elements[1][2]*=p_scale.z; - elements[2][2]*=p_scale.z; + elements[0][0] *= p_scale.x; + elements[1][0] *= p_scale.x; + elements[2][0] *= p_scale.x; + elements[0][1] *= p_scale.y; + elements[1][1] *= p_scale.y; + elements[2][1] *= p_scale.y; + elements[0][2] *= p_scale.z; + elements[1][2] *= p_scale.z; + elements[2][2] *= p_scale.z; } -Matrix3 Matrix3::scaled( const Vector3& p_scale ) const { +Matrix3 Matrix3::scaled(const Vector3 &p_scale) const { Matrix3 m = *this; m.scale(p_scale); @@ -144,28 +140,25 @@ Matrix3 Matrix3::scaled( const Vector3& p_scale ) const { Vector3 Matrix3::get_scale() const { return Vector3( - Vector3(elements[0][0],elements[1][0],elements[2][0]).length(), - Vector3(elements[0][1],elements[1][1],elements[2][1]).length(), - Vector3(elements[0][2],elements[1][2],elements[2][2]).length() - ); - + Vector3(elements[0][0], elements[1][0], elements[2][0]).length(), + Vector3(elements[0][1], elements[1][1], elements[2][1]).length(), + Vector3(elements[0][2], elements[1][2], elements[2][2]).length()); } -void Matrix3::rotate(const Vector3& p_axis, real_t p_phi) { +void Matrix3::rotate(const Vector3 &p_axis, real_t p_phi) { *this = *this * Matrix3(p_axis, p_phi); } -Matrix3 Matrix3::rotated(const Vector3& p_axis, real_t p_phi) const { +Matrix3 Matrix3::rotated(const Vector3 &p_axis, real_t p_phi) const { return *this * Matrix3(p_axis, p_phi); - } Vector3 Matrix3::get_euler() const { // rot = cy*cz -cy*sz sy - // cz*sx*sy+cx*sz cx*cz-sx*sy*sz -cy*sx - // -cx*cz*sy+sx*sz cz*sx+cx*sy*sz cx*cy + // cz*sx*sy+cx*sz cx*cz-sx*sy*sz -cy*sx + // -cx*cz*sy+sx*sz cz*sx+cx*sy*sz cx*cy Matrix3 m = *this; m.orthonormalize(); @@ -173,75 +166,72 @@ Vector3 Matrix3::get_euler() const { Vector3 euler; euler.y = Math::asin(m[0][2]); - if ( euler.y < Math_PI*0.5) { - if ( euler.y > -Math_PI*0.5) { - euler.x = Math::atan2(-m[1][2],m[2][2]); - euler.z = Math::atan2(-m[0][1],m[0][0]); + if (euler.y < Math_PI * 0.5) { + if (euler.y > -Math_PI * 0.5) { + euler.x = Math::atan2(-m[1][2], m[2][2]); + euler.z = Math::atan2(-m[0][1], m[0][0]); } else { - real_t r = Math::atan2(m[1][0],m[1][1]); + real_t r = Math::atan2(m[1][0], m[1][1]); euler.z = 0.0; euler.x = euler.z - r; - } } else { - real_t r = Math::atan2(m[0][1],m[1][1]); + real_t r = Math::atan2(m[0][1], m[1][1]); euler.z = 0; euler.x = r - euler.z; } return euler; - - } -void Matrix3::set_euler(const Vector3& p_euler) { +void Matrix3::set_euler(const Vector3 &p_euler) { real_t c, s; c = Math::cos(p_euler.x); s = Math::sin(p_euler.x); - Matrix3 xmat(1.0,0.0,0.0,0.0,c,-s,0.0,s,c); + Matrix3 xmat(1.0, 0.0, 0.0, 0.0, c, -s, 0.0, s, c); c = Math::cos(p_euler.y); s = Math::sin(p_euler.y); - Matrix3 ymat(c,0.0,s,0.0,1.0,0.0,-s,0.0,c); + Matrix3 ymat(c, 0.0, s, 0.0, 1.0, 0.0, -s, 0.0, c); c = Math::cos(p_euler.z); s = Math::sin(p_euler.z); - Matrix3 zmat(c,-s,0.0,s,c,0.0,0.0,0.0,1.0); + Matrix3 zmat(c, -s, 0.0, s, c, 0.0, 0.0, 0.0, 1.0); //optimizer will optimize away all this anyway - *this = xmat*(ymat*zmat); + *this = xmat * (ymat * zmat); } -bool Matrix3::operator==(const Matrix3& p_matrix) const { +bool Matrix3::operator==(const Matrix3 &p_matrix) const { - for (int i=0;i<3;i++) { - for (int j=0;j<3;j++) { - if (elements[i][j]!=p_matrix.elements[i][j]) + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 3; j++) { + if (elements[i][j] != p_matrix.elements[i][j]) return false; } } return true; } -bool Matrix3::operator!=(const Matrix3& p_matrix) const { +bool Matrix3::operator!=(const Matrix3 &p_matrix) const { - return (!(*this==p_matrix)); + return (!(*this == p_matrix)); } Matrix3::operator String() const { String mtx; - for (int i=0;i<3;i++) { + for (int i = 0; i < 3; i++) { - for (int j=0;j<3;j++) { + for (int j = 0; j < 3; j++) { - if (i!=0 || j!=0) - mtx+=", "; + if (i != 0 || j != 0) + mtx += ", "; - mtx+=rtos( elements[i][j] ); + mtx += rtos(elements[i][j]); } } @@ -250,27 +240,24 @@ Matrix3::operator String() const { Matrix3::operator Quat() const { - Matrix3 m=*this; + Matrix3 m = *this; m.orthonormalize(); real_t trace = m.elements[0][0] + m.elements[1][1] + m.elements[2][2]; real_t temp[4]; - if (trace > 0.0) - { + if (trace > 0.0) { real_t s = Math::sqrt(trace + 1.0); - temp[3]=(s * 0.5); + temp[3] = (s * 0.5); s = 0.5 / s; - temp[0]=((m.elements[2][1] - m.elements[1][2]) * s); - temp[1]=((m.elements[0][2] - m.elements[2][0]) * s); - temp[2]=((m.elements[1][0] - m.elements[0][1]) * s); - } - else - { + temp[0] = ((m.elements[2][1] - m.elements[1][2]) * s); + temp[1] = ((m.elements[0][2] - m.elements[2][0]) * s); + temp[2] = ((m.elements[1][0] - m.elements[0][1]) * s); + } else { int i = m.elements[0][0] < m.elements[1][1] ? - (m.elements[1][1] < m.elements[2][2] ? 2 : 1) : - (m.elements[0][0] < m.elements[2][2] ? 2 : 0); + (m.elements[1][1] < m.elements[2][2] ? 2 : 1) : + (m.elements[0][0] < m.elements[2][2] ? 2 : 0); int j = (i + 1) % 3; int k = (i + 2) % 3; @@ -283,11 +270,10 @@ Matrix3::operator Quat() const { temp[k] = (m.elements[k][i] + m.elements[i][k]) * s; } - return Quat(temp[0],temp[1],temp[2],temp[3]); - + return Quat(temp[0], temp[1], temp[2], temp[3]); } -static const Matrix3 _ortho_bases[24]={ +static const Matrix3 _ortho_bases[24] = { Matrix3(1, 0, 0, 0, 1, 0, 0, 0, 1), Matrix3(0, -1, 0, 1, 0, 0, 0, 0, 1), Matrix3(-1, 0, 0, 0, -1, 0, 0, 0, 1), @@ -317,163 +303,146 @@ static const Matrix3 _ortho_bases[24]={ int Matrix3::get_orthogonal_index() const { //could be sped up if i come up with a way - Matrix3 orth=*this; - for(int i=0;i<3;i++) { - for(int j=0;j<3;j++) { + Matrix3 orth = *this; + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 3; j++) { float v = orth[i][j]; - if (v>0.5) - v=1.0; - else if (v<-0.5) - v=-1.0; + if (v > 0.5) + v = 1.0; + else if (v < -0.5) + v = -1.0; else - v=0; + v = 0; - orth[i][j]=v; + orth[i][j] = v; } } - for(int i=0;i<24;i++) { + for (int i = 0; i < 24; i++) { - if (_ortho_bases[i]==orth) + if (_ortho_bases[i] == orth) return i; - - } return 0; } -void Matrix3::set_orthogonal_index(int p_index){ +void Matrix3::set_orthogonal_index(int p_index) { //there only exist 24 orthogonal bases in r3 - ERR_FAIL_INDEX(p_index,24); - - - *this=_ortho_bases[p_index]; + ERR_FAIL_INDEX(p_index, 24); + *this = _ortho_bases[p_index]; } +void Matrix3::get_axis_and_angle(Vector3 &r_axis, real_t &r_angle) const { -void Matrix3::get_axis_and_angle(Vector3 &r_axis,real_t& r_angle) const { + double angle, x, y, z; // variables for result + double epsilon = 0.01; // margin to allow for rounding errors + double epsilon2 = 0.1; // margin to distinguish between 0 and 180 degrees - - double angle,x,y,z; // variables for result - double epsilon = 0.01; // margin to allow for rounding errors - double epsilon2 = 0.1; // margin to distinguish between 0 and 180 degrees - - if ( (Math::abs(elements[1][0]-elements[0][1])< epsilon) - && (Math::abs(elements[2][0]-elements[0][2])< epsilon) - && (Math::abs(elements[2][1]-elements[1][2])< epsilon)) { - // singularity found - // first check for identity matrix which must have +1 for all terms - // in leading diagonaland zero in other terms - if ((Math::abs(elements[1][0]+elements[0][1]) < epsilon2) - && (Math::abs(elements[2][0]+elements[0][2]) < epsilon2) - && (Math::abs(elements[2][1]+elements[1][2]) < epsilon2) - && (Math::abs(elements[0][0]+elements[1][1]+elements[2][2]-3) < epsilon2)) { + if ((Math::abs(elements[1][0] - elements[0][1]) < epsilon) && (Math::abs(elements[2][0] - elements[0][2]) < epsilon) && (Math::abs(elements[2][1] - elements[1][2]) < epsilon)) { + // singularity found + // first check for identity matrix which must have +1 for all terms + // in leading diagonaland zero in other terms + if ((Math::abs(elements[1][0] + elements[0][1]) < epsilon2) && (Math::abs(elements[2][0] + elements[0][2]) < epsilon2) && (Math::abs(elements[2][1] + elements[1][2]) < epsilon2) && (Math::abs(elements[0][0] + elements[1][1] + elements[2][2] - 3) < epsilon2)) { // this singularity is identity matrix so angle = 0 - r_axis=Vector3(0,1,0); - r_angle=0; + r_axis = Vector3(0, 1, 0); + r_angle = 0; return; } // otherwise this singularity is angle = 180 angle = Math_PI; - double xx = (elements[0][0]+1)/2; - double yy = (elements[1][1]+1)/2; - double zz = (elements[2][2]+1)/2; - double xy = (elements[1][0]+elements[0][1])/4; - double xz = (elements[2][0]+elements[0][2])/4; - double yz = (elements[2][1]+elements[1][2])/4; + double xx = (elements[0][0] + 1) / 2; + double yy = (elements[1][1] + 1) / 2; + double zz = (elements[2][2] + 1) / 2; + double xy = (elements[1][0] + elements[0][1]) / 4; + double xz = (elements[2][0] + elements[0][2]) / 4; + double yz = (elements[2][1] + elements[1][2]) / 4; if ((xx > yy) && (xx > zz)) { // elements[0][0] is the largest diagonal term - if (xx< epsilon) { + if (xx < epsilon) { x = 0; y = 0.7071; z = 0.7071; } else { x = Math::sqrt(xx); - y = xy/x; - z = xz/x; + y = xy / x; + z = xz / x; } } else if (yy > zz) { // elements[1][1] is the largest diagonal term - if (yy< epsilon) { + if (yy < epsilon) { x = 0.7071; y = 0; z = 0.7071; } else { y = Math::sqrt(yy); - x = xy/y; - z = yz/y; + x = xy / y; + z = yz / y; } } else { // elements[2][2] is the largest diagonal term so base result on this - if (zz< epsilon) { + if (zz < epsilon) { x = 0.7071; y = 0.7071; z = 0; } else { z = Math::sqrt(zz); - x = xz/z; - y = yz/z; + x = xz / z; + y = yz / z; } } - r_axis=Vector3(x,y,z); - r_angle=angle; + r_axis = Vector3(x, y, z); + r_angle = angle; return; } // as we have reached here there are no singularities so we can handle normally - double s = Math::sqrt((elements[1][2] - elements[2][1])*(elements[1][2] - elements[2][1]) - +(elements[2][0] - elements[0][2])*(elements[2][0] - elements[0][2]) - +(elements[0][1] - elements[1][0])*(elements[0][1] - elements[1][0])); // used to normalise - if (Math::abs(s) < 0.001) s=1; - // prevent divide by zero, should not happen if matrix is orthogonal and should be - // caught by singularity test above, but I've left it in just in case - angle = Math::acos(( elements[0][0] + elements[1][1] + elements[2][2] - 1)/2); - x = (elements[1][2] - elements[2][1])/s; - y = (elements[2][0] - elements[0][2])/s; - z = (elements[0][1] - elements[1][0])/s; + double s = Math::sqrt((elements[1][2] - elements[2][1]) * (elements[1][2] - elements[2][1]) + (elements[2][0] - elements[0][2]) * (elements[2][0] - elements[0][2]) + (elements[0][1] - elements[1][0]) * (elements[0][1] - elements[1][0])); // used to normalise + if (Math::abs(s) < 0.001) s = 1; + // prevent divide by zero, should not happen if matrix is orthogonal and should be + // caught by singularity test above, but I've left it in just in case + angle = Math::acos((elements[0][0] + elements[1][1] + elements[2][2] - 1) / 2); + x = (elements[1][2] - elements[2][1]) / s; + y = (elements[2][0] - elements[0][2]) / s; + z = (elements[0][1] - elements[1][0]) / s; - r_axis=Vector3(x,y,z); - r_angle=angle; + r_axis = Vector3(x, y, z); + r_angle = angle; } -Matrix3::Matrix3(const Vector3& p_euler) { - - set_euler( p_euler ); +Matrix3::Matrix3(const Vector3 &p_euler) { + set_euler(p_euler); } -Matrix3::Matrix3(const Quat& p_quat) { +Matrix3::Matrix3(const Quat &p_quat) { real_t d = p_quat.length_squared(); real_t s = 2.0 / d; - real_t xs = p_quat.x * s, ys = p_quat.y * s, zs = p_quat.z * s; - real_t wx = p_quat.w * xs, wy = p_quat.w * ys, wz = p_quat.w * zs; - real_t xx = p_quat.x * xs, xy = p_quat.x * ys, xz = p_quat.x * zs; - real_t yy = p_quat.y * ys, yz = p_quat.y * zs, zz = p_quat.z * zs; - set( 1.0 - (yy + zz), xy - wz, xz + wy, - xy + wz, 1.0 - (xx + zz), yz - wx, - xz - wy, yz + wx, 1.0 - (xx + yy)) ; - + real_t xs = p_quat.x * s, ys = p_quat.y * s, zs = p_quat.z * s; + real_t wx = p_quat.w * xs, wy = p_quat.w * ys, wz = p_quat.w * zs; + real_t xx = p_quat.x * xs, xy = p_quat.x * ys, xz = p_quat.x * zs; + real_t yy = p_quat.y * ys, yz = p_quat.y * zs, zz = p_quat.z * zs; + set(1.0 - (yy + zz), xy - wz, xz + wy, + xy + wz, 1.0 - (xx + zz), yz - wx, + xz - wy, yz + wx, 1.0 - (xx + yy)); } -Matrix3::Matrix3(const Vector3& p_axis, real_t p_phi) { +Matrix3::Matrix3(const Vector3 &p_axis, real_t p_phi) { - Vector3 axis_sq(p_axis.x*p_axis.x,p_axis.y*p_axis.y,p_axis.z*p_axis.z); + Vector3 axis_sq(p_axis.x * p_axis.x, p_axis.y * p_axis.y, p_axis.z * p_axis.z); - real_t cosine= Math::cos(p_phi); - real_t sine= Math::sin(p_phi); + real_t cosine = Math::cos(p_phi); + real_t sine = Math::sin(p_phi); - elements[0][0] = axis_sq.x + cosine * ( 1.0 - axis_sq.x ); - elements[0][1] = p_axis.x * p_axis.y * ( 1.0 - cosine ) + p_axis.z * sine; - elements[0][2] = p_axis.z * p_axis.x * ( 1.0 - cosine ) - p_axis.y * sine; + elements[0][0] = axis_sq.x + cosine * (1.0 - axis_sq.x); + elements[0][1] = p_axis.x * p_axis.y * (1.0 - cosine) + p_axis.z * sine; + elements[0][2] = p_axis.z * p_axis.x * (1.0 - cosine) - p_axis.y * sine; - elements[1][0] = p_axis.x * p_axis.y * ( 1.0 - cosine ) - p_axis.z * sine; - elements[1][1] = axis_sq.y + cosine * ( 1.0 - axis_sq.y ); - elements[1][2] = p_axis.y * p_axis.z * ( 1.0 - cosine ) + p_axis.x * sine; - - elements[2][0] = p_axis.z * p_axis.x * ( 1.0 - cosine ) + p_axis.y * sine; - elements[2][1] = p_axis.y * p_axis.z * ( 1.0 - cosine ) - p_axis.x * sine; - elements[2][2] = axis_sq.z + cosine * ( 1.0 - axis_sq.z ); + elements[1][0] = p_axis.x * p_axis.y * (1.0 - cosine) - p_axis.z * sine; + elements[1][1] = axis_sq.y + cosine * (1.0 - axis_sq.y); + elements[1][2] = p_axis.y * p_axis.z * (1.0 - cosine) + p_axis.x * sine; + elements[2][0] = p_axis.z * p_axis.x * (1.0 - cosine) + p_axis.y * sine; + elements[2][1] = p_axis.y * p_axis.z * (1.0 - cosine) - p_axis.x * sine; + elements[2][2] = axis_sq.z + cosine * (1.0 - axis_sq.z); } - diff --git a/core/math/matrix3.h b/core/math/matrix3.h index 2792200b7dc..2f6af15920a 100644 --- a/core/math/matrix3.h +++ b/core/math/matrix3.h @@ -29,22 +29,21 @@ #ifndef MATRIX3_H #define MATRIX3_H -#include "vector3.h" #include "quat.h" +#include "vector3.h" /** @author Juan Linietsky */ class Matrix3 { public: - Vector3 elements[3]; - _FORCE_INLINE_ const Vector3& operator[](int axis) const { + _FORCE_INLINE_ const Vector3 &operator[](int axis) const { return elements[axis]; } - _FORCE_INLINE_ Vector3& operator[](int axis) { + _FORCE_INLINE_ Vector3 &operator[](int axis) { return elements[axis]; } @@ -57,83 +56,82 @@ public: _FORCE_INLINE_ float determinant() const; - void from_z(const Vector3& p_z); + void from_z(const Vector3 &p_z); _FORCE_INLINE_ Vector3 get_axis(int p_axis) const { // get actual basis axis (elements is transposed for performance) - return Vector3( elements[0][p_axis], elements[1][p_axis], elements[2][p_axis] ); + return Vector3(elements[0][p_axis], elements[1][p_axis], elements[2][p_axis]); } - _FORCE_INLINE_ void set_axis(int p_axis, const Vector3& p_value) { + _FORCE_INLINE_ void set_axis(int p_axis, const Vector3 &p_value) { // get actual basis axis (elements is transposed for performance) - elements[0][p_axis]=p_value.x; - elements[1][p_axis]=p_value.y; - elements[2][p_axis]=p_value.z; + elements[0][p_axis] = p_value.x; + elements[1][p_axis] = p_value.y; + elements[2][p_axis] = p_value.z; } - void rotate(const Vector3& p_axis, real_t p_phi); - Matrix3 rotated(const Vector3& p_axis, real_t p_phi) const; + void rotate(const Vector3 &p_axis, real_t p_phi); + Matrix3 rotated(const Vector3 &p_axis, real_t p_phi) const; - void scale( const Vector3& p_scale ); - Matrix3 scaled( const Vector3& p_scale ) const; + void scale(const Vector3 &p_scale); + Matrix3 scaled(const Vector3 &p_scale) const; Vector3 get_scale() const; Vector3 get_euler() const; - void set_euler(const Vector3& p_euler); + void set_euler(const Vector3 &p_euler); // transposed dot products - _FORCE_INLINE_ real_t tdotx(const Vector3& v) const { + _FORCE_INLINE_ real_t tdotx(const Vector3 &v) const { return elements[0][0] * v[0] + elements[1][0] * v[1] + elements[2][0] * v[2]; } - _FORCE_INLINE_ real_t tdoty(const Vector3& v) const { + _FORCE_INLINE_ real_t tdoty(const Vector3 &v) const { return elements[0][1] * v[0] + elements[1][1] * v[1] + elements[2][1] * v[2]; } - _FORCE_INLINE_ real_t tdotz(const Vector3& v) const { + _FORCE_INLINE_ real_t tdotz(const Vector3 &v) const { return elements[0][2] * v[0] + elements[1][2] * v[1] + elements[2][2] * v[2]; } - bool operator==(const Matrix3& p_matrix) const; - bool operator!=(const Matrix3& p_matrix) const; + bool operator==(const Matrix3 &p_matrix) const; + bool operator!=(const Matrix3 &p_matrix) const; - _FORCE_INLINE_ Vector3 xform(const Vector3& p_vector) const; - _FORCE_INLINE_ Vector3 xform_inv(const Vector3& p_vector) const; - _FORCE_INLINE_ void operator*=(const Matrix3& p_matrix); - _FORCE_INLINE_ Matrix3 operator*(const Matrix3& p_matrix) const; + _FORCE_INLINE_ Vector3 xform(const Vector3 &p_vector) const; + _FORCE_INLINE_ Vector3 xform_inv(const Vector3 &p_vector) const; + _FORCE_INLINE_ void operator*=(const Matrix3 &p_matrix); + _FORCE_INLINE_ Matrix3 operator*(const Matrix3 &p_matrix) const; int get_orthogonal_index() const; void set_orthogonal_index(int p_index); operator String() const; - void get_axis_and_angle(Vector3 &r_axis,real_t& r_angle) const; + void get_axis_and_angle(Vector3 &r_axis, real_t &r_angle) const; /* create / set */ - _FORCE_INLINE_ void set(real_t xx, real_t xy, real_t xz, real_t yx, real_t yy, real_t yz, real_t zx, real_t zy, real_t zz) { - elements[0][0]=xx; - elements[0][1]=xy; - elements[0][2]=xz; - elements[1][0]=yx; - elements[1][1]=yy; - elements[1][2]=yz; - elements[2][0]=zx; - elements[2][1]=zy; - elements[2][2]=zz; + elements[0][0] = xx; + elements[0][1] = xy; + elements[0][2] = xz; + elements[1][0] = yx; + elements[1][1] = yy; + elements[1][2] = yz; + elements[2][0] = zx; + elements[2][1] = zy; + elements[2][2] = zz; } _FORCE_INLINE_ Vector3 get_column(int i) const { - return Vector3(elements[0][i],elements[1][i],elements[2][i]); + return Vector3(elements[0][i], elements[1][i], elements[2][i]); } _FORCE_INLINE_ Vector3 get_row(int i) const { - return Vector3(elements[i][0],elements[i][1],elements[i][2]); + return Vector3(elements[i][0], elements[i][1], elements[i][2]); } - _FORCE_INLINE_ void set_row(int i, const Vector3& p_row) { - elements[i][0]=p_row.x; - elements[i][1]=p_row.y; - elements[i][2]=p_row.z; + _FORCE_INLINE_ void set_row(int i, const Vector3 &p_row) { + elements[i][0] = p_row.x; + elements[i][1] = p_row.y; + elements[i][2] = p_row.z; } _FORCE_INLINE_ void set_zero() { @@ -142,18 +140,17 @@ public: elements[2].zero(); } - _FORCE_INLINE_ Matrix3 transpose_xform(const Matrix3& m) const - { + _FORCE_INLINE_ Matrix3 transpose_xform(const Matrix3 &m) const { return Matrix3( - elements[0].x * m[0].x + elements[1].x * m[1].x + elements[2].x * m[2].x, - elements[0].x * m[0].y + elements[1].x * m[1].y + elements[2].x * m[2].y, - elements[0].x * m[0].z + elements[1].x * m[1].z + elements[2].x * m[2].z, - elements[0].y * m[0].x + elements[1].y * m[1].x + elements[2].y * m[2].x, - elements[0].y * m[0].y + elements[1].y * m[1].y + elements[2].y * m[2].y, - elements[0].y * m[0].z + elements[1].y * m[1].z + elements[2].y * m[2].z, - elements[0].z * m[0].x + elements[1].z * m[1].x + elements[2].z * m[2].x, - elements[0].z * m[0].y + elements[1].z * m[1].y + elements[2].z * m[2].y, - elements[0].z * m[0].z + elements[1].z * m[1].z + elements[2].z * m[2].z); + elements[0].x * m[0].x + elements[1].x * m[1].x + elements[2].x * m[2].x, + elements[0].x * m[0].y + elements[1].x * m[1].y + elements[2].x * m[2].y, + elements[0].x * m[0].z + elements[1].x * m[1].z + elements[2].x * m[2].z, + elements[0].y * m[0].x + elements[1].y * m[1].x + elements[2].y * m[2].x, + elements[0].y * m[0].y + elements[1].y * m[1].y + elements[2].y * m[2].y, + elements[0].y * m[0].z + elements[1].y * m[1].z + elements[2].y * m[2].z, + elements[0].z * m[0].x + elements[1].z * m[1].x + elements[2].z * m[2].x, + elements[0].z * m[0].y + elements[1].z * m[1].y + elements[2].z * m[2].y, + elements[0].z * m[0].z + elements[1].z * m[1].z + elements[2].z * m[2].z); } Matrix3(real_t xx, real_t xy, real_t xz, real_t yx, real_t yy, real_t yz, real_t zx, real_t zy, real_t zz) { @@ -165,66 +162,60 @@ public: operator Quat() const; - Matrix3(const Quat& p_quat); // euler - Matrix3(const Vector3& p_euler); // euler - Matrix3(const Vector3& p_axis, real_t p_phi); + Matrix3(const Quat &p_quat); // euler + Matrix3(const Vector3 &p_euler); // euler + Matrix3(const Vector3 &p_axis, real_t p_phi); _FORCE_INLINE_ Matrix3() { - elements[0][0]=1; - elements[0][1]=0; - elements[0][2]=0; - elements[1][0]=0; - elements[1][1]=1; - elements[1][2]=0; - elements[2][0]=0; - elements[2][1]=0; - elements[2][2]=1; + elements[0][0] = 1; + elements[0][1] = 0; + elements[0][2] = 0; + elements[1][0] = 0; + elements[1][1] = 1; + elements[1][2] = 0; + elements[2][0] = 0; + elements[2][1] = 0; + elements[2][2] = 1; } - - }; -_FORCE_INLINE_ void Matrix3::operator*=(const Matrix3& p_matrix) { +_FORCE_INLINE_ void Matrix3::operator*=(const Matrix3 &p_matrix) { set( - p_matrix.tdotx(elements[0]), p_matrix.tdoty(elements[0]), p_matrix.tdotz(elements[0]), - p_matrix.tdotx(elements[1]), p_matrix.tdoty(elements[1]), p_matrix.tdotz(elements[1]), - p_matrix.tdotx(elements[2]), p_matrix.tdoty(elements[2]), p_matrix.tdotz(elements[2])); - + p_matrix.tdotx(elements[0]), p_matrix.tdoty(elements[0]), p_matrix.tdotz(elements[0]), + p_matrix.tdotx(elements[1]), p_matrix.tdoty(elements[1]), p_matrix.tdotz(elements[1]), + p_matrix.tdotx(elements[2]), p_matrix.tdoty(elements[2]), p_matrix.tdotz(elements[2])); } -_FORCE_INLINE_ Matrix3 Matrix3::operator*(const Matrix3& p_matrix) const { +_FORCE_INLINE_ Matrix3 Matrix3::operator*(const Matrix3 &p_matrix) const { return Matrix3( - p_matrix.tdotx(elements[0]), p_matrix.tdoty(elements[0]), p_matrix.tdotz(elements[0]), - p_matrix.tdotx(elements[1]), p_matrix.tdoty(elements[1]), p_matrix.tdotz(elements[1]), - p_matrix.tdotx(elements[2]), p_matrix.tdoty(elements[2]), p_matrix.tdotz(elements[2]) ); - + p_matrix.tdotx(elements[0]), p_matrix.tdoty(elements[0]), p_matrix.tdotz(elements[0]), + p_matrix.tdotx(elements[1]), p_matrix.tdoty(elements[1]), p_matrix.tdotz(elements[1]), + p_matrix.tdotx(elements[2]), p_matrix.tdoty(elements[2]), p_matrix.tdotz(elements[2])); } -Vector3 Matrix3::xform(const Vector3& p_vector) const { +Vector3 Matrix3::xform(const Vector3 &p_vector) const { return Vector3( - elements[0].dot(p_vector), - elements[1].dot(p_vector), - elements[2].dot(p_vector) - ); + elements[0].dot(p_vector), + elements[1].dot(p_vector), + elements[2].dot(p_vector)); } -Vector3 Matrix3::xform_inv(const Vector3& p_vector) const { +Vector3 Matrix3::xform_inv(const Vector3 &p_vector) const { return Vector3( - (elements[0][0]*p_vector.x ) + ( elements[1][0]*p_vector.y ) + ( elements[2][0]*p_vector.z ), - (elements[0][1]*p_vector.x ) + ( elements[1][1]*p_vector.y ) + ( elements[2][1]*p_vector.z ), - (elements[0][2]*p_vector.x ) + ( elements[1][2]*p_vector.y ) + ( elements[2][2]*p_vector.z ) - ); + (elements[0][0] * p_vector.x) + (elements[1][0] * p_vector.y) + (elements[2][0] * p_vector.z), + (elements[0][1] * p_vector.x) + (elements[1][1] * p_vector.y) + (elements[2][1] * p_vector.z), + (elements[0][2] * p_vector.x) + (elements[1][2] * p_vector.y) + (elements[2][2] * p_vector.z)); } float Matrix3::determinant() const { - return elements[0][0]*(elements[1][1]*elements[2][2] - elements[2][1]*elements[1][2]) - - elements[1][0]*(elements[0][1]*elements[2][2] - elements[2][1]*elements[0][2]) + - elements[2][0]*(elements[0][1]*elements[1][2] - elements[1][1]*elements[0][2]); + return elements[0][0] * (elements[1][1] * elements[2][2] - elements[2][1] * elements[1][2]) - + elements[1][0] * (elements[0][1] * elements[2][2] - elements[2][1] * elements[0][2]) + + elements[2][0] * (elements[0][1] * elements[1][2] - elements[1][1] * elements[0][2]); } #endif diff --git a/core/math/octree.h b/core/math/octree.h index 189041cdc59..39ac2f0aba1 100644 --- a/core/math/octree.h +++ b/core/math/octree.h @@ -29,12 +29,12 @@ #ifndef OCTREE_H #define OCTREE_H -#include "vector3.h" #include "aabb.h" #include "list.h" -#include "variant.h" #include "map.h" #include "print_string.h" +#include "variant.h" +#include "vector3.h" /** @author Juan Linietsky @@ -45,18 +45,17 @@ typedef uint32_t OctreeElementID; #define OCTREE_ELEMENT_INVALID_ID 0 #define OCTREE_SIZE_LIMIT 1e15 -template +template class Octree { public: - - typedef void* (*PairCallback)(void*,OctreeElementID, T*,int,OctreeElementID, T*,int); - typedef void (*UnpairCallback)(void*,OctreeElementID, T*,int,OctreeElementID, T*,int,void*); + typedef void *(*PairCallback)(void *, OctreeElementID, T *, int, OctreeElementID, T *, int); + typedef void (*UnpairCallback)(void *, OctreeElementID, T *, int, OctreeElementID, T *, int, void *); private: enum { - NEG=0, - POS=1, + NEG = 0, + POS = 1, }; enum { @@ -70,7 +69,6 @@ private: OCTANT_PX_PY_PZ }; - struct PairKey { union { @@ -81,21 +79,21 @@ private: uint64_t key; }; - _FORCE_INLINE_ bool operator<(const PairKey& p_pair) const { + _FORCE_INLINE_ bool operator<(const PairKey &p_pair) const { - return key pairable_elements; - List elements; + List pairable_elements; + List elements; Octant() { - children_count=0; - parent_index=-1; - last_pass=0; - parent=NULL; - for (int i=0;i<8;i++) - children[i]=NULL; + children_count = 0; + parent_index = -1; + last_pass = 0; + parent = NULL; + for (int i = 0; i < 8; i++) + children[i] = NULL; } ~Octant() { @@ -135,7 +133,6 @@ private: } }; - struct PairData; struct Element { @@ -155,28 +152,36 @@ private: AABB aabb; AABB container_aabb; - List pair_list; + List pair_list; struct OctantOwner { Octant *octant; - typename List::Element *E; + typename List::Element *E; }; // an element can be in max 8 octants - List octant_owners; + List octant_owners; - - Element() { last_pass=0; _id=0; pairable=false; subindex=0; userdata=0; octree=0; pairable_mask=0; pairable_type=0; common_parent=NULL; } + Element() { + last_pass = 0; + _id = 0; + pairable = false; + subindex = 0; + userdata = 0; + octree = 0; + pairable_mask = 0; + pairable_type = 0; + common_parent = NULL; + } }; - struct PairData { int refcount; bool intersect; - Element *A,*B; + Element *A, *B; void *ud; - typename List::Element *eA,*eB; + typename List::Element *eA, *eB; }; typedef Map, AL> ElementMap; @@ -197,248 +202,231 @@ private: int octant_count; int pair_count; - - _FORCE_INLINE_ void _pair_check(PairData *p_pair) { - bool intersect=p_pair->A->aabb.intersects_inclusive( p_pair->B->aabb ); + bool intersect = p_pair->A->aabb.intersects_inclusive(p_pair->B->aabb); - if (intersect!=p_pair->intersect) { + if (intersect != p_pair->intersect) { if (intersect) { if (pair_callback) { - p_pair->ud=pair_callback(pair_callback_userdata,p_pair->A->_id, p_pair->A->userdata,p_pair->A->subindex,p_pair->B->_id, p_pair->B->userdata,p_pair->B->subindex); - + p_pair->ud = pair_callback(pair_callback_userdata, p_pair->A->_id, p_pair->A->userdata, p_pair->A->subindex, p_pair->B->_id, p_pair->B->userdata, p_pair->B->subindex); } pair_count++; } else { - if (unpair_callback) { - unpair_callback(pair_callback_userdata,p_pair->A->_id, p_pair->A->userdata,p_pair->A->subindex,p_pair->B->_id, p_pair->B->userdata,p_pair->B->subindex,p_pair->ud); + unpair_callback(pair_callback_userdata, p_pair->A->_id, p_pair->A->userdata, p_pair->A->subindex, p_pair->B->_id, p_pair->B->userdata, p_pair->B->subindex, p_pair->ud); } pair_count--; - } - p_pair->intersect=intersect; - + p_pair->intersect = intersect; } } - _FORCE_INLINE_ void _pair_reference(Element* p_A,Element* p_B) { + _FORCE_INLINE_ void _pair_reference(Element *p_A, Element *p_B) { - if (p_A==p_B || (p_A->userdata==p_B->userdata && p_A->userdata)) + if (p_A == p_B || (p_A->userdata == p_B->userdata && p_A->userdata)) return; - if ( !(p_A->pairable_type&p_B->pairable_mask) && - !(p_B->pairable_type&p_A->pairable_mask) ) + if (!(p_A->pairable_type & p_B->pairable_mask) && + !(p_B->pairable_type & p_A->pairable_mask)) return; // none can pair with none PairKey key(p_A->_id, p_B->_id); - typename PairMap::Element *E=pair_map.find(key); + typename PairMap::Element *E = pair_map.find(key); if (!E) { PairData pdata; - pdata.refcount=1; - pdata.A=p_A; - pdata.B=p_B; - pdata.intersect=false; - E=pair_map.insert(key,pdata); - E->get().eA=p_A->pair_list.push_back(&E->get()); - E->get().eB=p_B->pair_list.push_back(&E->get()); + pdata.refcount = 1; + pdata.A = p_A; + pdata.B = p_B; + pdata.intersect = false; + E = pair_map.insert(key, pdata); + E->get().eA = p_A->pair_list.push_back(&E->get()); + E->get().eB = p_B->pair_list.push_back(&E->get()); -// if (pair_callback) -// pair_callback(pair_callback_userdata,p_A->userdata,p_B->userdata); + // if (pair_callback) + // pair_callback(pair_callback_userdata,p_A->userdata,p_B->userdata); } else { E->get().refcount++; } - } - _FORCE_INLINE_ void _pair_unreference(Element* p_A,Element* p_B) { + _FORCE_INLINE_ void _pair_unreference(Element *p_A, Element *p_B) { - if (p_A==p_B) + if (p_A == p_B) return; PairKey key(p_A->_id, p_B->_id); - typename PairMap::Element *E=pair_map.find(key); + typename PairMap::Element *E = pair_map.find(key); if (!E) { return; // no pair } E->get().refcount--; - - if (E->get().refcount==0) { + if (E->get().refcount == 0) { // bye pair if (E->get().intersect) { if (unpair_callback) { - unpair_callback(pair_callback_userdata,p_A->_id, p_A->userdata,p_A->subindex,p_B->_id, p_B->userdata,p_B->subindex,E->get().ud); + unpair_callback(pair_callback_userdata, p_A->_id, p_A->userdata, p_A->subindex, p_B->_id, p_B->userdata, p_B->subindex, E->get().ud); } pair_count--; } - if (p_A==E->get().B) { + if (p_A == E->get().B) { //may be reaching inverted - SWAP(p_A,p_B); + SWAP(p_A, p_B); } - p_A->pair_list.erase( E->get().eA ); - p_B->pair_list.erase( E->get().eB ); + p_A->pair_list.erase(E->get().eA); + p_B->pair_list.erase(E->get().eB); pair_map.erase(E); } - } _FORCE_INLINE_ void _element_check_pairs(Element *p_element) { - typename List::Element *E=p_element->pair_list.front(); - while(E) { + typename List::Element *E = p_element->pair_list.front(); + while (E) { - _pair_check( E->get() ); - E=E->next(); + _pair_check(E->get()); + E = E->next(); } - } _FORCE_INLINE_ void _optimize() { + while (root && root->children_count < 2 && !root->elements.size() && !(use_pairs && root->pairable_elements.size())) { - while(root && root->children_count<2 && !root->elements.size() && !(use_pairs && root->pairable_elements.size())) { + Octant *new_root = NULL; + if (root->children_count == 1) { - - Octant *new_root=NULL; - if (root->children_count==1) { - - for(int i=0;i<8;i++) { + for (int i = 0; i < 8; i++) { if (root->children[i]) { - new_root=root->children[i]; - root->children[i]=NULL; + new_root = root->children[i]; + root->children[i] = NULL; break; } } ERR_FAIL_COND(!new_root); - new_root->parent=NULL; - new_root->parent_index=-1; + new_root->parent = NULL; + new_root->parent_index = -1; } - memdelete_allocator( root ); + memdelete_allocator(root); octant_count--; - root=new_root; - + root = new_root; } } - - void _insert_element(Element *p_element,Octant *p_octant); - void _ensure_valid_root(const AABB& p_aabb); - bool _remove_element_from_octant(Element *p_element,Octant *p_octant,Octant *p_limit=NULL); + void _insert_element(Element *p_element, Octant *p_octant); + void _ensure_valid_root(const AABB &p_aabb); + bool _remove_element_from_octant(Element *p_element, Octant *p_octant, Octant *p_limit = NULL); void _remove_element(Element *p_element); - void _pair_element(Element *p_element,Octant *p_octant); - void _unpair_element(Element *p_element,Octant *p_octant); - + void _pair_element(Element *p_element, Octant *p_octant); + void _unpair_element(Element *p_element, Octant *p_octant); struct _CullConvexData { - const Plane* planes; + const Plane *planes; int plane_count; - T** result_array; + T **result_array; int *result_idx; int result_max; uint32_t mask; }; - void _cull_convex(Octant *p_octant,_CullConvexData *p_cull); - void _cull_AABB(Octant *p_octant,const AABB& p_aabb, T** p_result_array,int *p_result_idx,int p_result_max,int *p_subindex_array,uint32_t p_mask); - void _cull_segment(Octant *p_octant,const Vector3& p_from, const Vector3& p_to,T** p_result_array,int *p_result_idx,int p_result_max,int *p_subindex_array,uint32_t p_mask); - void _cull_point(Octant *p_octant,const Vector3& p_point,T** p_result_array,int *p_result_idx,int p_result_max,int *p_subindex_array,uint32_t p_mask); + void _cull_convex(Octant *p_octant, _CullConvexData *p_cull); + void _cull_AABB(Octant *p_octant, const AABB &p_aabb, T **p_result_array, int *p_result_idx, int p_result_max, int *p_subindex_array, uint32_t p_mask); + void _cull_segment(Octant *p_octant, const Vector3 &p_from, const Vector3 &p_to, T **p_result_array, int *p_result_idx, int p_result_max, int *p_subindex_array, uint32_t p_mask); + void _cull_point(Octant *p_octant, const Vector3 &p_point, T **p_result_array, int *p_result_idx, int p_result_max, int *p_subindex_array, uint32_t p_mask); void _remove_tree(Octant *p_octant) { if (!p_octant) return; - for(int i=0;i<8;i++) { + for (int i = 0; i < 8; i++) { if (p_octant->children[i]) _remove_tree(p_octant->children[i]); } - memdelete_allocator(p_octant); + memdelete_allocator(p_octant); } -public: - OctreeElementID create(T* p_userdata, const AABB& p_aabb=AABB(), int p_subindex=0, bool p_pairable=false,uint32_t p_pairable_type=0,uint32_t pairable_mask=1); - void move(OctreeElementID p_id, const AABB& p_aabb); - void set_pairable(OctreeElementID p_id,bool p_pairable=false,uint32_t p_pairable_type=0,uint32_t pairable_mask=1); +public: + OctreeElementID create(T *p_userdata, const AABB &p_aabb = AABB(), int p_subindex = 0, bool p_pairable = false, uint32_t p_pairable_type = 0, uint32_t pairable_mask = 1); + void move(OctreeElementID p_id, const AABB &p_aabb); + void set_pairable(OctreeElementID p_id, bool p_pairable = false, uint32_t p_pairable_type = 0, uint32_t pairable_mask = 1); void erase(OctreeElementID p_id); bool is_pairable(OctreeElementID p_id) const; T *get(OctreeElementID p_id) const; int get_subindex(OctreeElementID p_id) const; - int cull_convex(const Vector& p_convex,T** p_result_array,int p_result_max,uint32_t p_mask=0xFFFFFFFF); - int cull_AABB(const AABB& p_aabb,T** p_result_array,int p_result_max,int *p_subindex_array=NULL,uint32_t p_mask=0xFFFFFFFF); - int cull_segment(const Vector3& p_from, const Vector3& p_to,T** p_result_array,int p_result_max,int *p_subindex_array=NULL,uint32_t p_mask=0xFFFFFFFF); + int cull_convex(const Vector &p_convex, T **p_result_array, int p_result_max, uint32_t p_mask = 0xFFFFFFFF); + int cull_AABB(const AABB &p_aabb, T **p_result_array, int p_result_max, int *p_subindex_array = NULL, uint32_t p_mask = 0xFFFFFFFF); + int cull_segment(const Vector3 &p_from, const Vector3 &p_to, T **p_result_array, int p_result_max, int *p_subindex_array = NULL, uint32_t p_mask = 0xFFFFFFFF); - int cull_point(const Vector3& p_point,T** p_result_array,int p_result_max,int *p_subindex_array=NULL,uint32_t p_mask=0xFFFFFFFF); + int cull_point(const Vector3 &p_point, T **p_result_array, int p_result_max, int *p_subindex_array = NULL, uint32_t p_mask = 0xFFFFFFFF); - void set_pair_callback( PairCallback p_callback, void *p_userdata ); - void set_unpair_callback( UnpairCallback p_callback, void *p_userdata ); + void set_pair_callback(PairCallback p_callback, void *p_userdata); + void set_unpair_callback(UnpairCallback p_callback, void *p_userdata); int get_octant_count() const { return octant_count; } int get_pair_count() const { return pair_count; } - Octree(real_t p_unit_size=1.0); + Octree(real_t p_unit_size = 1.0); ~Octree() { _remove_tree(root); } }; - /* PRIVATE FUNCTIONS */ -template -T *Octree::get(OctreeElementID p_id) const { +template +T *Octree::get(OctreeElementID p_id) const { const typename ElementMap::Element *E = element_map.find(p_id); - ERR_FAIL_COND_V(!E,NULL); + ERR_FAIL_COND_V(!E, NULL); return E->get().userdata; } - -template -bool Octree::is_pairable(OctreeElementID p_id) const { +template +bool Octree::is_pairable(OctreeElementID p_id) const { const typename ElementMap::Element *E = element_map.find(p_id); - ERR_FAIL_COND_V(!E,false); + ERR_FAIL_COND_V(!E, false); return E->get().pairable; } -template -int Octree::get_subindex(OctreeElementID p_id) const { +template +int Octree::get_subindex(OctreeElementID p_id) const { const typename ElementMap::Element *E = element_map.find(p_id); - ERR_FAIL_COND_V(!E,-1); + ERR_FAIL_COND_V(!E, -1); return E->get().subindex; } #define OCTREE_DIVISOR 4 -template -void Octree::_insert_element(Element *p_element,Octant *p_octant) { +template +void Octree::_insert_element(Element *p_element, Octant *p_octant) { float element_size = p_element->aabb.get_longest_axis_size() * 1.01; // avoid precision issues - if (p_octant->aabb.size.x/OCTREE_DIVISOR < element_size) { - //if (p_octant->aabb.size.x*0.5 < element_size) { + if (p_octant->aabb.size.x / OCTREE_DIVISOR < element_size) { + //if (p_octant->aabb.size.x*0.5 < element_size) { /* at smallest possible size for the element */ typename Element::OctantOwner owner; - owner.octant=p_octant; + owner.octant = p_octant; if (use_pairs && p_element->pairable) { @@ -450,426 +438,409 @@ void Octree::_insert_element(Element *p_element,Octant *p_octant owner.E = p_octant->elements.back(); } - p_element->octant_owners.push_back( owner ); + p_element->octant_owners.push_back(owner); - if (p_element->common_parent==NULL) { - p_element->common_parent=p_octant; - p_element->container_aabb=p_octant->aabb; + if (p_element->common_parent == NULL) { + p_element->common_parent = p_octant; + p_element->container_aabb = p_octant->aabb; } else { p_element->container_aabb.merge_with(p_octant->aabb); } - - if (use_pairs && p_octant->children_count>0) { + if (use_pairs && p_octant->children_count > 0) { pass++; //elements below this only get ONE reference added - for (int i=0;i<8;i++) { + for (int i = 0; i < 8; i++) { if (p_octant->children[i]) { - _pair_element(p_element,p_octant->children[i]); + _pair_element(p_element, p_octant->children[i]); } } } } else { /* not big enough, send it to subitems */ - int splits=0; - bool candidate=p_element->common_parent==NULL; + int splits = 0; + bool candidate = p_element->common_parent == NULL; - for (int i=0;i<8;i++) { + for (int i = 0; i < 8; i++) { if (p_octant->children[i]) { /* element exists, go straight to it */ - if (p_octant->children[i]->aabb.intersects_inclusive( p_element->aabb ) ) { - _insert_element( p_element, p_octant->children[i] ); + if (p_octant->children[i]->aabb.intersects_inclusive(p_element->aabb)) { + _insert_element(p_element, p_octant->children[i]); splits++; } } else { /* check againt AABB where child should be */ - AABB aabb=p_octant->aabb; - aabb.size*=0.5; + AABB aabb = p_octant->aabb; + aabb.size *= 0.5; - if (i&1) - aabb.pos.x+=aabb.size.x; - if (i&2) - aabb.pos.y+=aabb.size.y; - if (i&4) - aabb.pos.z+=aabb.size.z; + if (i & 1) + aabb.pos.x += aabb.size.x; + if (i & 2) + aabb.pos.y += aabb.size.y; + if (i & 4) + aabb.pos.z += aabb.size.z; - if (aabb.intersects_inclusive( p_element->aabb) ) { + if (aabb.intersects_inclusive(p_element->aabb)) { /* if actually intersects, create the child */ - Octant *child = memnew_allocator( Octant, AL ); - p_octant->children[i]=child; - child->parent=p_octant; - child->parent_index=i; + Octant *child = memnew_allocator(Octant, AL); + p_octant->children[i] = child; + child->parent = p_octant; + child->parent_index = i; - child->aabb=aabb; + child->aabb = aabb; p_octant->children_count++; - _insert_element( p_element, child ); + _insert_element(p_element, child); octant_count++; splits++; - } } - } - if (candidate && splits>1) { + if (candidate && splits > 1) { - p_element->common_parent=p_octant; + p_element->common_parent = p_octant; } - } if (use_pairs) { - typename List::Element *E=p_octant->pairable_elements.front(); + typename List::Element *E = p_octant->pairable_elements.front(); - while(E) { - _pair_reference( p_element,E->get() ); - E=E->next(); + while (E) { + _pair_reference(p_element, E->get()); + E = E->next(); } if (p_element->pairable) { // and always test non-pairable if element is pairable - E=p_octant->elements.front(); - while(E) { - _pair_reference( p_element,E->get() ); - E=E->next(); + E = p_octant->elements.front(); + while (E) { + _pair_reference(p_element, E->get()); + E = E->next(); } } } - - } - -template -void Octree::_ensure_valid_root(const AABB& p_aabb) { +template +void Octree::_ensure_valid_root(const AABB &p_aabb) { if (!root) { // octre is empty - AABB base( Vector3(), Vector3(1.0,1.0,1.0) * unit_size); + AABB base(Vector3(), Vector3(1.0, 1.0, 1.0) * unit_size); - while ( !base.encloses(p_aabb) ) { + while (!base.encloses(p_aabb)) { - if ( ABS(base.pos.x+base.size.x) <= ABS(base.pos.x) ) { + if (ABS(base.pos.x + base.size.x) <= ABS(base.pos.x)) { /* grow towards positive */ - base.size*=2.0; + base.size *= 2.0; } else { - base.pos-=base.size; - base.size*=2.0; + base.pos -= base.size; + base.size *= 2.0; } } - root = memnew_allocator( Octant, AL ); + root = memnew_allocator(Octant, AL); - root->parent=NULL; - root->parent_index=-1; - root->aabb=base; + root->parent = NULL; + root->parent_index = -1; + root->aabb = base; octant_count++; - } else { - AABB base=root->aabb; + AABB base = root->aabb; - while( !base.encloses( p_aabb ) ) { + while (!base.encloses(p_aabb)) { if (base.size.x > OCTREE_SIZE_LIMIT) { ERR_EXPLAIN("Octree upper size limit reeached, does the AABB supplied contain NAN?"); ERR_FAIL(); } - Octant * gp = memnew_allocator( Octant, AL ); + Octant *gp = memnew_allocator(Octant, AL); octant_count++; - root->parent=gp; + root->parent = gp; - if ( ABS(base.pos.x+base.size.x) <= ABS(base.pos.x) ) { + if (ABS(base.pos.x + base.size.x) <= ABS(base.pos.x)) { /* grow towards positive */ - base.size*=2.0; - gp->aabb=base; - gp->children[0]=root; - root->parent_index=0; + base.size *= 2.0; + gp->aabb = base; + gp->children[0] = root; + root->parent_index = 0; } else { - base.pos-=base.size; - base.size*=2.0; - gp->aabb=base; - gp->children[(1<<0)|(1<<1)|(1<<2)]=root; // add at all-positive - root->parent_index=(1<<0)|(1<<1)|(1<<2); + base.pos -= base.size; + base.size *= 2.0; + gp->aabb = base; + gp->children[(1 << 0) | (1 << 1) | (1 << 2)] = root; // add at all-positive + root->parent_index = (1 << 0) | (1 << 1) | (1 << 2); } - gp->children_count=1; - root=gp; + gp->children_count = 1; + root = gp; } } } -template -bool Octree::_remove_element_from_octant(Element *p_element,Octant *p_octant,Octant *p_limit) { +template +bool Octree::_remove_element_from_octant(Element *p_element, Octant *p_octant, Octant *p_limit) { - bool octant_removed=false; + bool octant_removed = false; - while(true) { + while (true) { // check all exit conditions - if (p_octant==p_limit) // reached limit, nothing to erase, exit + if (p_octant == p_limit) // reached limit, nothing to erase, exit return octant_removed; - bool unpaired=false; + bool unpaired = false; - if (use_pairs && p_octant->last_pass!=pass) { + if (use_pairs && p_octant->last_pass != pass) { // check wether we should unpair stuff // always test pairable - typename List::Element *E=p_octant->pairable_elements.front(); - while(E) { - _pair_unreference( p_element,E->get() ); - E=E->next(); + typename List::Element *E = p_octant->pairable_elements.front(); + while (E) { + _pair_unreference(p_element, E->get()); + E = E->next(); } if (p_element->pairable) { // and always test non-pairable if element is pairable - E=p_octant->elements.front(); - while(E) { - _pair_unreference( p_element,E->get() ); - E=E->next(); + E = p_octant->elements.front(); + while (E) { + _pair_unreference(p_element, E->get()); + E = E->next(); } } - p_octant->last_pass=pass; - unpaired=true; + p_octant->last_pass = pass; + unpaired = true; } - bool removed=false; + bool removed = false; - Octant *parent=p_octant->parent; + Octant *parent = p_octant->parent; - if (p_octant->children_count==0 && p_octant->elements.empty() && p_octant->pairable_elements.empty()) { + if (p_octant->children_count == 0 && p_octant->elements.empty() && p_octant->pairable_elements.empty()) { // erase octant - if (p_octant==root) { // won't have a parent, just erase + if (p_octant == root) { // won't have a parent, just erase - root=NULL; + root = NULL; } else { - ERR_FAIL_INDEX_V(p_octant->parent_index,8,octant_removed); + ERR_FAIL_INDEX_V(p_octant->parent_index, 8, octant_removed); - parent->children[ p_octant->parent_index ]=NULL; + parent->children[p_octant->parent_index] = NULL; parent->children_count--; } - memdelete_allocator(p_octant); + memdelete_allocator(p_octant); octant_count--; - removed=true; - octant_removed=true; + removed = true; + octant_removed = true; } if (!removed && !unpaired) return octant_removed; // no reason to keep going up anymore! was already visited and was not removed - p_octant=parent; - + p_octant = parent; } return octant_removed; } -template -void Octree::_unpair_element(Element *p_element,Octant *p_octant) { - +template +void Octree::_unpair_element(Element *p_element, Octant *p_octant) { // always test pairable - typename List::Element *E=p_octant->pairable_elements.front(); - while(E) { - if (E->get()->last_pass!=pass) { // only remove ONE reference - _pair_unreference( p_element,E->get() ); - E->get()->last_pass=pass; + typename List::Element *E = p_octant->pairable_elements.front(); + while (E) { + if (E->get()->last_pass != pass) { // only remove ONE reference + _pair_unreference(p_element, E->get()); + E->get()->last_pass = pass; } - E=E->next(); + E = E->next(); } if (p_element->pairable) { // and always test non-pairable if element is pairable - E=p_octant->elements.front(); - while(E) { - if (E->get()->last_pass!=pass) { // only remove ONE reference - _pair_unreference( p_element,E->get() ); - E->get()->last_pass=pass; + E = p_octant->elements.front(); + while (E) { + if (E->get()->last_pass != pass) { // only remove ONE reference + _pair_unreference(p_element, E->get()); + E->get()->last_pass = pass; } - E=E->next(); + E = E->next(); } } - p_octant->last_pass=pass; + p_octant->last_pass = pass; - if (p_octant->children_count==0) + if (p_octant->children_count == 0) return; // small optimization for leafs - for (int i=0;i<8;i++) { + for (int i = 0; i < 8; i++) { if (p_octant->children[i]) - _unpair_element(p_element,p_octant->children[i]); + _unpair_element(p_element, p_octant->children[i]); } } -template -void Octree::_pair_element(Element *p_element,Octant *p_octant) { +template +void Octree::_pair_element(Element *p_element, Octant *p_octant) { // always test pairable - typename List::Element *E=p_octant->pairable_elements.front(); + typename List::Element *E = p_octant->pairable_elements.front(); - while(E) { + while (E) { - if (E->get()->last_pass!=pass) { // only get ONE reference - _pair_reference( p_element,E->get() ); - E->get()->last_pass=pass; + if (E->get()->last_pass != pass) { // only get ONE reference + _pair_reference(p_element, E->get()); + E->get()->last_pass = pass; } - E=E->next(); + E = E->next(); } if (p_element->pairable) { // and always test non-pairable if element is pairable - E=p_octant->elements.front(); - while(E) { - if (E->get()->last_pass!=pass) { // only get ONE reference - _pair_reference( p_element,E->get() ); - E->get()->last_pass=pass; + E = p_octant->elements.front(); + while (E) { + if (E->get()->last_pass != pass) { // only get ONE reference + _pair_reference(p_element, E->get()); + E->get()->last_pass = pass; } - E=E->next(); + E = E->next(); } } - p_octant->last_pass=pass; + p_octant->last_pass = pass; - if (p_octant->children_count==0) + if (p_octant->children_count == 0) return; // small optimization for leafs - for (int i=0;i<8;i++) { + for (int i = 0; i < 8; i++) { if (p_octant->children[i]) - _pair_element(p_element,p_octant->children[i]); + _pair_element(p_element, p_octant->children[i]); } } -template -void Octree::_remove_element(Element *p_element) { +template +void Octree::_remove_element(Element *p_element) { pass++; // will do a new pass for this - typename List< typename Element::OctantOwner,AL >::Element *I=p_element->octant_owners.front(); - + typename List::Element *I = p_element->octant_owners.front(); /* FIRST remove going up normally */ - for(;I;I=I->next()) { + for (; I; I = I->next()) { - Octant *o=I->get().octant; + Octant *o = I->get().octant; if (!use_pairs) // small speedup - o->elements.erase( I->get().E ); - - _remove_element_from_octant( p_element, o ); + o->elements.erase(I->get().E); + _remove_element_from_octant(p_element, o); } /* THEN remove going down */ - I=p_element->octant_owners.front(); + I = p_element->octant_owners.front(); if (use_pairs) { - for(;I;I=I->next()) { + for (; I; I = I->next()) { - Octant *o=I->get().octant; + Octant *o = I->get().octant; // erase children pairs, they are erased ONCE even if repeated pass++; - for (int i=0;i<8;i++) { + for (int i = 0; i < 8; i++) { if (o->children[i]) - _unpair_element(p_element,o->children[i]); + _unpair_element(p_element, o->children[i]); } if (p_element->pairable) - o->pairable_elements.erase( I->get().E ); + o->pairable_elements.erase(I->get().E); else - o->elements.erase( I->get().E ); - + o->elements.erase(I->get().E); } } p_element->octant_owners.clear(); - if(use_pairs) { + if (use_pairs) { - int remaining=p_element->pair_list.size(); + int remaining = p_element->pair_list.size(); //p_element->pair_list.clear(); - ERR_FAIL_COND( remaining ); + ERR_FAIL_COND(remaining); } - } -template -OctreeElementID Octree::create(T* p_userdata, const AABB& p_aabb, int p_subindex,bool p_pairable,uint32_t p_pairable_type,uint32_t p_pairable_mask) { +template +OctreeElementID Octree::create(T *p_userdata, const AABB &p_aabb, int p_subindex, bool p_pairable, uint32_t p_pairable_type, uint32_t p_pairable_mask) { - // check for AABB validity +// check for AABB validity #ifdef DEBUG_ENABLED - ERR_FAIL_COND_V( p_aabb.pos.x > 1e15 || p_aabb.pos.x < -1e15, 0 ); - ERR_FAIL_COND_V( p_aabb.pos.y > 1e15 || p_aabb.pos.y < -1e15, 0 ); - ERR_FAIL_COND_V( p_aabb.pos.z > 1e15 || p_aabb.pos.z < -1e15, 0 ); - ERR_FAIL_COND_V( p_aabb.size.x > 1e15 || p_aabb.size.x < 0.0, 0 ); - ERR_FAIL_COND_V( p_aabb.size.y > 1e15 || p_aabb.size.y < 0.0, 0 ); - ERR_FAIL_COND_V( p_aabb.size.z > 1e15 || p_aabb.size.z < 0.0, 0 ); - ERR_FAIL_COND_V( Math::is_nan(p_aabb.size.x) , 0 ); - ERR_FAIL_COND_V( Math::is_nan(p_aabb.size.y) , 0 ); - ERR_FAIL_COND_V( Math::is_nan(p_aabb.size.z) , 0 ); - + ERR_FAIL_COND_V(p_aabb.pos.x > 1e15 || p_aabb.pos.x < -1e15, 0); + ERR_FAIL_COND_V(p_aabb.pos.y > 1e15 || p_aabb.pos.y < -1e15, 0); + ERR_FAIL_COND_V(p_aabb.pos.z > 1e15 || p_aabb.pos.z < -1e15, 0); + ERR_FAIL_COND_V(p_aabb.size.x > 1e15 || p_aabb.size.x < 0.0, 0); + ERR_FAIL_COND_V(p_aabb.size.y > 1e15 || p_aabb.size.y < 0.0, 0); + ERR_FAIL_COND_V(p_aabb.size.z > 1e15 || p_aabb.size.z < 0.0, 0); + ERR_FAIL_COND_V(Math::is_nan(p_aabb.size.x), 0); + ERR_FAIL_COND_V(Math::is_nan(p_aabb.size.y), 0); + ERR_FAIL_COND_V(Math::is_nan(p_aabb.size.z), 0); #endif typename ElementMap::Element *E = element_map.insert(last_element_id++, - Element()); + Element()); Element &e = E->get(); - e.aabb=p_aabb; - e.userdata=p_userdata; - e.subindex=p_subindex; - e.last_pass=0; - e.octree=this; - e.pairable=p_pairable; - e.pairable_type=p_pairable_type; - e.pairable_mask=p_pairable_mask; - e._id=last_element_id-1; + e.aabb = p_aabb; + e.userdata = p_userdata; + e.subindex = p_subindex; + e.last_pass = 0; + e.octree = this; + e.pairable = p_pairable; + e.pairable_type = p_pairable_type; + e.pairable_mask = p_pairable_mask; + e._id = last_element_id - 1; if (!e.aabb.has_no_surface()) { _ensure_valid_root(p_aabb); - _insert_element(&e,root); + _insert_element(&e, root); if (use_pairs) _element_check_pairs(&e); } - return last_element_id-1; + return last_element_id - 1; } - - -template -void Octree::move(OctreeElementID p_id, const AABB& p_aabb) { +template +void Octree::move(OctreeElementID p_id, const AABB &p_aabb) { #ifdef DEBUG_ENABLED // check for AABB validity - ERR_FAIL_COND( p_aabb.pos.x > 1e15 || p_aabb.pos.x < -1e15 ); - ERR_FAIL_COND( p_aabb.pos.y > 1e15 || p_aabb.pos.y < -1e15 ); - ERR_FAIL_COND( p_aabb.pos.z > 1e15 || p_aabb.pos.z < -1e15 ); - ERR_FAIL_COND( p_aabb.size.x > 1e15 || p_aabb.size.x < 0.0 ); - ERR_FAIL_COND( p_aabb.size.y > 1e15 || p_aabb.size.y < 0.0 ); - ERR_FAIL_COND( p_aabb.size.z > 1e15 || p_aabb.size.z < 0.0 ); - ERR_FAIL_COND( Math::is_nan(p_aabb.size.x) ); - ERR_FAIL_COND( Math::is_nan(p_aabb.size.y) ); - ERR_FAIL_COND( Math::is_nan(p_aabb.size.z) ); + ERR_FAIL_COND(p_aabb.pos.x > 1e15 || p_aabb.pos.x < -1e15); + ERR_FAIL_COND(p_aabb.pos.y > 1e15 || p_aabb.pos.y < -1e15); + ERR_FAIL_COND(p_aabb.pos.z > 1e15 || p_aabb.pos.z < -1e15); + ERR_FAIL_COND(p_aabb.size.x > 1e15 || p_aabb.size.x < 0.0); + ERR_FAIL_COND(p_aabb.size.y > 1e15 || p_aabb.size.y < 0.0); + ERR_FAIL_COND(p_aabb.size.z > 1e15 || p_aabb.size.z < 0.0); + ERR_FAIL_COND(Math::is_nan(p_aabb.size.x)); + ERR_FAIL_COND(Math::is_nan(p_aabb.size.y)); + ERR_FAIL_COND(Math::is_nan(p_aabb.size.z)); #endif typename ElementMap::Element *E = element_map.find(p_id); ERR_FAIL_COND(!E); @@ -897,25 +868,23 @@ void Octree::move(OctreeElementID p_id, const AABB& p_aabb) { #else - bool old_has_surf=!e.aabb.has_no_surface(); - bool new_has_surf=!p_aabb.has_no_surface(); - - if (old_has_surf!=new_has_surf) { + bool old_has_surf = !e.aabb.has_no_surface(); + bool new_has_surf = !p_aabb.has_no_surface(); + if (old_has_surf != new_has_surf) { if (old_has_surf) { _remove_element(&e); // removing - e.common_parent=NULL; - e.aabb=AABB(); + e.common_parent = NULL; + e.aabb = AABB(); _optimize(); } else { _ensure_valid_root(p_aabb); // inserting - e.common_parent=NULL; - e.aabb=p_aabb; - _insert_element(&e,root); + e.common_parent = NULL; + e.aabb = p_aabb; + _insert_element(&e, root); if (use_pairs) _element_check_pairs(&e); - } return; @@ -927,124 +896,115 @@ void Octree::move(OctreeElementID p_id, const AABB& p_aabb) { // it still is enclosed in the same AABB it was assigned to if (e.container_aabb.encloses(p_aabb)) { - e.aabb=p_aabb; + e.aabb = p_aabb; if (use_pairs) _element_check_pairs(&e); // must check pairs anyway - return; } - AABB combined=e.aabb; + AABB combined = e.aabb; combined.merge_with(p_aabb); _ensure_valid_root(combined); - ERR_FAIL_COND( e.octant_owners.front()==NULL ); + ERR_FAIL_COND(e.octant_owners.front() == NULL); /* FIND COMMON PARENT */ - List owners = e.octant_owners; // save the octant owners - Octant *common_parent=e.common_parent; + List owners = e.octant_owners; // save the octant owners + Octant *common_parent = e.common_parent; ERR_FAIL_COND(!common_parent); - //src is now the place towards where insertion is going to happen pass++; - while(common_parent && !common_parent->aabb.encloses(p_aabb)) - common_parent=common_parent->parent; + while (common_parent && !common_parent->aabb.encloses(p_aabb)) + common_parent = common_parent->parent; ERR_FAIL_COND(!common_parent); //prepare for reinsert e.octant_owners.clear(); - e.common_parent=NULL; - e.aabb=p_aabb; + e.common_parent = NULL; + e.aabb = p_aabb; - _insert_element(&e,common_parent); // reinsert from this point + _insert_element(&e, common_parent); // reinsert from this point pass++; - for(typename List::Element *E=owners.front();E;) { + for (typename List::Element *E = owners.front(); E;) { - Octant *o=E->get().octant; - typename List::Element *N=E->next(); + Octant *o = E->get().octant; + typename List::Element *N = E->next(); -// if (!use_pairs) -// o->elements.erase( E->get().E ); + // if (!use_pairs) + // o->elements.erase( E->get().E ); if (use_pairs && e.pairable) - o->pairable_elements.erase( E->get().E ); + o->pairable_elements.erase(E->get().E); else - o->elements.erase( E->get().E ); + o->elements.erase(E->get().E); - if (_remove_element_from_octant( &e, o, common_parent->parent )) { + if (_remove_element_from_octant(&e, o, common_parent->parent)) { owners.erase(E); } - E=N; + E = N; } - if (use_pairs) { //unpair child elements in anything that survived - for(typename List::Element *E=owners.front();E;E=E->next()) { + for (typename List::Element *E = owners.front(); E; E = E->next()) { - Octant *o=E->get().octant; + Octant *o = E->get().octant; // erase children pairs, unref ONCE pass++; - for (int i=0;i<8;i++) { + for (int i = 0; i < 8; i++) { if (o->children[i]) - _unpair_element(&e,o->children[i]); + _unpair_element(&e, o->children[i]); } - } _element_check_pairs(&e); } - _optimize(); #endif - - } -template -void Octree::set_pairable(OctreeElementID p_id,bool p_pairable,uint32_t p_pairable_type,uint32_t p_pairable_mask) { +template +void Octree::set_pairable(OctreeElementID p_id, bool p_pairable, uint32_t p_pairable_type, uint32_t p_pairable_mask) { typename ElementMap::Element *E = element_map.find(p_id); ERR_FAIL_COND(!E); Element &e = E->get(); - if (p_pairable == e.pairable && e.pairable_type==p_pairable_type && e.pairable_mask==p_pairable_mask) + if (p_pairable == e.pairable && e.pairable_type == p_pairable_type && e.pairable_mask == p_pairable_mask) return; // no changes, return if (!e.aabb.has_no_surface()) { _remove_element(&e); } - e.pairable=p_pairable; - e.pairable_type=p_pairable_type; - e.pairable_mask=p_pairable_mask; - e.common_parent=NULL; + e.pairable = p_pairable; + e.pairable_type = p_pairable_type; + e.pairable_mask = p_pairable_mask; + e.common_parent = NULL; if (!e.aabb.has_no_surface()) { _ensure_valid_root(e.aabb); - _insert_element(&e,root); + _insert_element(&e, root); if (use_pairs) _element_check_pairs(&e); - } } - -template -void Octree::erase(OctreeElementID p_id) { +template +void Octree::erase(OctreeElementID p_id) { typename ElementMap::Element *E = element_map.find(p_id); ERR_FAIL_COND(!E); @@ -1060,28 +1020,28 @@ void Octree::erase(OctreeElementID p_id) { _optimize(); } -template -void Octree::_cull_convex(Octant *p_octant,_CullConvexData *p_cull) { +template +void Octree::_cull_convex(Octant *p_octant, _CullConvexData *p_cull) { - if (*p_cull->result_idx==p_cull->result_max) + if (*p_cull->result_idx == p_cull->result_max) return; //pointless if (!p_octant->elements.empty()) { - typename List< Element*,AL >::Element *I; - I=p_octant->elements.front(); + typename List::Element *I; + I = p_octant->elements.front(); - for(;I;I=I->next()) { + for (; I; I = I->next()) { - Element *e=I->get(); + Element *e = I->get(); - if (e->last_pass==pass || (use_pairs && !(e->pairable_type&p_cull->mask))) + if (e->last_pass == pass || (use_pairs && !(e->pairable_type & p_cull->mask))) continue; - e->last_pass=pass; + e->last_pass = pass; - if (e->aabb.intersects_convex_shape(p_cull->planes,p_cull->plane_count)) { + if (e->aabb.intersects_convex_shape(p_cull->planes, p_cull->plane_count)) { - if (*p_cull->result_idxresult_max) { + if (*p_cull->result_idx < p_cull->result_max) { p_cull->result_array[*p_cull->result_idx] = e->userdata; (*p_cull->result_idx)++; } else { @@ -1094,20 +1054,20 @@ void Octree::_cull_convex(Octant *p_octant,_CullConvexData *p_cu if (use_pairs && !p_octant->pairable_elements.empty()) { - typename List< Element*,AL >::Element *I; - I=p_octant->pairable_elements.front(); + typename List::Element *I; + I = p_octant->pairable_elements.front(); - for(;I;I=I->next()) { + for (; I; I = I->next()) { - Element *e=I->get(); + Element *e = I->get(); - if (e->last_pass==pass || (use_pairs && !(e->pairable_type&p_cull->mask))) + if (e->last_pass == pass || (use_pairs && !(e->pairable_type & p_cull->mask))) continue; - e->last_pass=pass; + e->last_pass = pass; - if (e->aabb.intersects_convex_shape(p_cull->planes,p_cull->plane_count)) { + if (e->aabb.intersects_convex_shape(p_cull->planes, p_cull->plane_count)) { - if (*p_cull->result_idxresult_max) { + if (*p_cull->result_idx < p_cull->result_max) { p_cull->result_array[*p_cull->result_idx] = e->userdata; (*p_cull->result_idx)++; @@ -1119,36 +1079,35 @@ void Octree::_cull_convex(Octant *p_octant,_CullConvexData *p_cu } } - for (int i=0;i<8;i++) { + for (int i = 0; i < 8; i++) { - if (p_octant->children[i] && p_octant->children[i]->aabb.intersects_convex_shape(p_cull->planes,p_cull->plane_count)) { - _cull_convex(p_octant->children[i],p_cull); + if (p_octant->children[i] && p_octant->children[i]->aabb.intersects_convex_shape(p_cull->planes, p_cull->plane_count)) { + _cull_convex(p_octant->children[i], p_cull); } } } +template +void Octree::_cull_AABB(Octant *p_octant, const AABB &p_aabb, T **p_result_array, int *p_result_idx, int p_result_max, int *p_subindex_array, uint32_t p_mask) { -template -void Octree::_cull_AABB(Octant *p_octant,const AABB& p_aabb, T** p_result_array,int *p_result_idx,int p_result_max,int *p_subindex_array,uint32_t p_mask) { - - if (*p_result_idx==p_result_max) + if (*p_result_idx == p_result_max) return; //pointless if (!p_octant->elements.empty()) { - typename List< Element*,AL >::Element *I; - I=p_octant->elements.front(); - for(;I;I=I->next()) { + typename List::Element *I; + I = p_octant->elements.front(); + for (; I; I = I->next()) { - Element *e=I->get(); + Element *e = I->get(); - if (e->last_pass==pass || (use_pairs && !(e->pairable_type&p_mask))) + if (e->last_pass == pass || (use_pairs && !(e->pairable_type & p_mask))) continue; - e->last_pass=pass; + e->last_pass = pass; if (p_aabb.intersects_inclusive(e->aabb)) { - if (*p_result_idxuserdata; if (p_subindex_array) @@ -1165,19 +1124,19 @@ void Octree::_cull_AABB(Octant *p_octant,const AABB& p_aabb, T** if (use_pairs && !p_octant->pairable_elements.empty()) { - typename List< Element*,AL >::Element *I; - I=p_octant->pairable_elements.front(); - for(;I;I=I->next()) { + typename List::Element *I; + I = p_octant->pairable_elements.front(); + for (; I; I = I->next()) { - Element *e=I->get(); + Element *e = I->get(); - if (e->last_pass==pass || (use_pairs && !(e->pairable_type&p_mask))) + if (e->last_pass == pass || (use_pairs && !(e->pairable_type & p_mask))) continue; - e->last_pass=pass; + e->last_pass = pass; if (p_aabb.intersects_inclusive(e->aabb)) { - if (*p_result_idxuserdata; if (p_subindex_array) @@ -1191,36 +1150,35 @@ void Octree::_cull_AABB(Octant *p_octant,const AABB& p_aabb, T** } } - for (int i=0;i<8;i++) { + for (int i = 0; i < 8; i++) { if (p_octant->children[i] && p_octant->children[i]->aabb.intersects_inclusive(p_aabb)) { - _cull_AABB(p_octant->children[i],p_aabb, p_result_array,p_result_idx,p_result_max,p_subindex_array,p_mask); + _cull_AABB(p_octant->children[i], p_aabb, p_result_array, p_result_idx, p_result_max, p_subindex_array, p_mask); } } - } -template -void Octree::_cull_segment(Octant *p_octant,const Vector3& p_from, const Vector3& p_to,T** p_result_array,int *p_result_idx,int p_result_max,int *p_subindex_array,uint32_t p_mask) { +template +void Octree::_cull_segment(Octant *p_octant, const Vector3 &p_from, const Vector3 &p_to, T **p_result_array, int *p_result_idx, int p_result_max, int *p_subindex_array, uint32_t p_mask) { - if (*p_result_idx==p_result_max) + if (*p_result_idx == p_result_max) return; //pointless if (!p_octant->elements.empty()) { - typename List< Element*,AL >::Element *I; - I=p_octant->elements.front(); - for(;I;I=I->next()) { + typename List::Element *I; + I = p_octant->elements.front(); + for (; I; I = I->next()) { - Element *e=I->get(); + Element *e = I->get(); - if (e->last_pass==pass || (use_pairs && !(e->pairable_type&p_mask))) + if (e->last_pass == pass || (use_pairs && !(e->pairable_type & p_mask))) continue; - e->last_pass=pass; + e->last_pass = pass; - if (e->aabb.intersects_segment(p_from,p_to)) { + if (e->aabb.intersects_segment(p_from, p_to)) { - if (*p_result_idxuserdata; if (p_subindex_array) @@ -1237,20 +1195,20 @@ void Octree::_cull_segment(Octant *p_octant,const Vector3& p_fro if (use_pairs && !p_octant->pairable_elements.empty()) { - typename List< Element*,AL >::Element *I; - I=p_octant->pairable_elements.front(); - for(;I;I=I->next()) { + typename List::Element *I; + I = p_octant->pairable_elements.front(); + for (; I; I = I->next()) { - Element *e=I->get(); + Element *e = I->get(); - if (e->last_pass==pass || (use_pairs && !(e->pairable_type&p_mask))) + if (e->last_pass == pass || (use_pairs && !(e->pairable_type & p_mask))) continue; - e->last_pass=pass; + e->last_pass = pass; - if (e->aabb.intersects_segment(p_from,p_to)) { + if (e->aabb.intersects_segment(p_from, p_to)) { - if (*p_result_idxuserdata; if (p_subindex_array) @@ -1266,37 +1224,35 @@ void Octree::_cull_segment(Octant *p_octant,const Vector3& p_fro } } + for (int i = 0; i < 8; i++) { - for (int i=0;i<8;i++) { - - if (p_octant->children[i] && p_octant->children[i]->aabb.intersects_segment(p_from,p_to)) { - _cull_segment(p_octant->children[i],p_from,p_to, p_result_array,p_result_idx,p_result_max,p_subindex_array,p_mask); + if (p_octant->children[i] && p_octant->children[i]->aabb.intersects_segment(p_from, p_to)) { + _cull_segment(p_octant->children[i], p_from, p_to, p_result_array, p_result_idx, p_result_max, p_subindex_array, p_mask); } } } +template +void Octree::_cull_point(Octant *p_octant, const Vector3 &p_point, T **p_result_array, int *p_result_idx, int p_result_max, int *p_subindex_array, uint32_t p_mask) { -template -void Octree::_cull_point(Octant *p_octant,const Vector3& p_point,T** p_result_array,int *p_result_idx,int p_result_max,int *p_subindex_array,uint32_t p_mask) { - - if (*p_result_idx==p_result_max) + if (*p_result_idx == p_result_max) return; //pointless if (!p_octant->elements.empty()) { - typename List< Element*,AL >::Element *I; - I=p_octant->elements.front(); - for(;I;I=I->next()) { + typename List::Element *I; + I = p_octant->elements.front(); + for (; I; I = I->next()) { - Element *e=I->get(); + Element *e = I->get(); - if (e->last_pass==pass || (use_pairs && !(e->pairable_type&p_mask))) + if (e->last_pass == pass || (use_pairs && !(e->pairable_type & p_mask))) continue; - e->last_pass=pass; + e->last_pass = pass; if (e->aabb.has_point(p_point)) { - if (*p_result_idxuserdata; if (p_subindex_array) @@ -1313,20 +1269,20 @@ void Octree::_cull_point(Octant *p_octant,const Vector3& p_point if (use_pairs && !p_octant->pairable_elements.empty()) { - typename List< Element*,AL >::Element *I; - I=p_octant->pairable_elements.front(); - for(;I;I=I->next()) { + typename List::Element *I; + I = p_octant->pairable_elements.front(); + for (; I; I = I->next()) { - Element *e=I->get(); + Element *e = I->get(); - if (e->last_pass==pass || (use_pairs && !(e->pairable_type&p_mask))) + if (e->last_pass == pass || (use_pairs && !(e->pairable_type & p_mask))) continue; - e->last_pass=pass; + e->last_pass = pass; if (e->aabb.has_point(p_point)) { - if (*p_result_idxuserdata; if (p_subindex_array) @@ -1342,120 +1298,103 @@ void Octree::_cull_point(Octant *p_octant,const Vector3& p_point } } - - for (int i=0;i<8;i++) { + for (int i = 0; i < 8; i++) { //could be optimized.. if (p_octant->children[i] && p_octant->children[i]->aabb.has_point(p_point)) { - _cull_point(p_octant->children[i],p_point, p_result_array,p_result_idx,p_result_max,p_subindex_array,p_mask); + _cull_point(p_octant->children[i], p_point, p_result_array, p_result_idx, p_result_max, p_subindex_array, p_mask); } } } -template -int Octree::cull_convex(const Vector& p_convex,T** p_result_array,int p_result_max,uint32_t p_mask) { +template +int Octree::cull_convex(const Vector &p_convex, T **p_result_array, int p_result_max, uint32_t p_mask) { if (!root) return 0; - int result_count=0; + int result_count = 0; pass++; _CullConvexData cdata; - cdata.planes=&p_convex[0]; - cdata.plane_count=p_convex.size(); - cdata.result_array=p_result_array; - cdata.result_max=p_result_max; - cdata.result_idx=&result_count; - cdata.mask=p_mask; + cdata.planes = &p_convex[0]; + cdata.plane_count = p_convex.size(); + cdata.result_array = p_result_array; + cdata.result_max = p_result_max; + cdata.result_idx = &result_count; + cdata.mask = p_mask; - _cull_convex(root,&cdata); + _cull_convex(root, &cdata); return result_count; } - - -template -int Octree::cull_AABB(const AABB& p_aabb,T** p_result_array,int p_result_max,int *p_subindex_array,uint32_t p_mask) { - +template +int Octree::cull_AABB(const AABB &p_aabb, T **p_result_array, int p_result_max, int *p_subindex_array, uint32_t p_mask) { if (!root) return 0; - int result_count=0; + int result_count = 0; pass++; - _cull_AABB(root,p_aabb,p_result_array,&result_count,p_result_max,p_subindex_array,p_mask); + _cull_AABB(root, p_aabb, p_result_array, &result_count, p_result_max, p_subindex_array, p_mask); return result_count; } - -template -int Octree::cull_segment(const Vector3& p_from, const Vector3& p_to,T** p_result_array,int p_result_max,int *p_subindex_array,uint32_t p_mask) { +template +int Octree::cull_segment(const Vector3 &p_from, const Vector3 &p_to, T **p_result_array, int p_result_max, int *p_subindex_array, uint32_t p_mask) { if (!root) return 0; - int result_count=0; + int result_count = 0; pass++; - _cull_segment(root,p_from,p_to,p_result_array,&result_count,p_result_max,p_subindex_array,p_mask); + _cull_segment(root, p_from, p_to, p_result_array, &result_count, p_result_max, p_subindex_array, p_mask); return result_count; - } -template -int Octree::cull_point(const Vector3& p_point,T** p_result_array,int p_result_max,int *p_subindex_array,uint32_t p_mask) { +template +int Octree::cull_point(const Vector3 &p_point, T **p_result_array, int p_result_max, int *p_subindex_array, uint32_t p_mask) { if (!root) return 0; - int result_count=0; + int result_count = 0; pass++; - _cull_point(root,p_point,p_result_array,&result_count,p_result_max,p_subindex_array,p_mask); + _cull_point(root, p_point, p_result_array, &result_count, p_result_max, p_subindex_array, p_mask); return result_count; - } +template +void Octree::set_pair_callback(PairCallback p_callback, void *p_userdata) { -template -void Octree::set_pair_callback( PairCallback p_callback, void *p_userdata ) { - - pair_callback=p_callback; - pair_callback_userdata=p_userdata; + pair_callback = p_callback; + pair_callback_userdata = p_userdata; } -template -void Octree::set_unpair_callback( UnpairCallback p_callback, void *p_userdata ) { - - unpair_callback=p_callback; - unpair_callback_userdata=p_userdata; +template +void Octree::set_unpair_callback(UnpairCallback p_callback, void *p_userdata) { + unpair_callback = p_callback; + unpair_callback_userdata = p_userdata; } +template +Octree::Octree(real_t p_unit_size) { -template -Octree::Octree(real_t p_unit_size) { - - last_element_id=1; - pass=1; - unit_size=p_unit_size; - root=NULL; - - octant_count=0; - pair_count=0; - - pair_callback=NULL; - unpair_callback=NULL; - pair_callback_userdata=NULL; - unpair_callback_userdata=NULL; - - + last_element_id = 1; + pass = 1; + unit_size = p_unit_size; + root = NULL; + octant_count = 0; + pair_count = 0; + pair_callback = NULL; + unpair_callback = NULL; + pair_callback_userdata = NULL; + unpair_callback_userdata = NULL; } - - - #endif diff --git a/core/math/plane.cpp b/core/math/plane.cpp index 2a979320498..29e7f2e75c7 100644 --- a/core/math/plane.cpp +++ b/core/math/plane.cpp @@ -33,20 +33,20 @@ #define _PLANE_EQ_DOT_EPSILON 0.999 #define _PLANE_EQ_D_EPSILON 0.0001 -void Plane::set_normal(const Vector3& p_normal) { +void Plane::set_normal(const Vector3 &p_normal) { - normal=p_normal; + normal = p_normal; } void Plane::normalize() { real_t l = normal.length(); - if (l==0) { - *this=Plane(0,0,0,0); + if (l == 0) { + *this = Plane(0, 0, 0, 0); return; } - normal/=l; - d/=l; + normal /= l; + d /= l; } Plane Plane::normalized() const { @@ -58,21 +58,21 @@ Plane Plane::normalized() const { Vector3 Plane::get_any_point() const { - return get_normal()*d; + return get_normal() * d; } Vector3 Plane::get_any_perpendicular_normal() const { - static const Vector3 p1 = Vector3(1,0,0); - static const Vector3 p2 = Vector3(0,1,0); + static const Vector3 p1 = Vector3(1, 0, 0); + static const Vector3 p2 = Vector3(0, 1, 0); Vector3 p; if (ABS(normal.dot(p1)) > 0.99) // if too similar to p1 - p=p2; // use p2 + p = p2; // use p2 else - p=p1; // use p1 + p = p1; // use p1 - p-=normal * normal.dot(p); + p -= normal * normal.dot(p); p.normalize(); return p; @@ -82,71 +82,71 @@ Vector3 Plane::get_any_perpendicular_normal() const { bool Plane::intersect_3(const Plane &p_plane1, const Plane &p_plane2, Vector3 *r_result) const { - const Plane &p_plane0=*this; - Vector3 normal0=p_plane0.normal; - Vector3 normal1=p_plane1.normal; - Vector3 normal2=p_plane2.normal; + const Plane &p_plane0 = *this; + Vector3 normal0 = p_plane0.normal; + Vector3 normal1 = p_plane1.normal; + Vector3 normal2 = p_plane2.normal; - real_t denom=vec3_cross(normal0,normal1).dot(normal2); + real_t denom = vec3_cross(normal0, normal1).dot(normal2); - if (ABS(denom)<=CMP_EPSILON) + if (ABS(denom) <= CMP_EPSILON) return false; - if (r_result) { - *r_result = ( (vec3_cross(normal1, normal2) * p_plane0.d) + - (vec3_cross(normal2, normal0) * p_plane1.d) + - (vec3_cross(normal0, normal1) * p_plane2.d) )/denom; - } + if (r_result) { + *r_result = ((vec3_cross(normal1, normal2) * p_plane0.d) + + (vec3_cross(normal2, normal0) * p_plane1.d) + + (vec3_cross(normal0, normal1) * p_plane2.d)) / + denom; + } return true; } +bool Plane::intersects_ray(Vector3 p_from, Vector3 p_dir, Vector3 *p_intersection) const { -bool Plane::intersects_ray(Vector3 p_from, Vector3 p_dir, Vector3* p_intersection) const { - - Vector3 segment=p_dir; - real_t den=normal.dot( segment ); + Vector3 segment = p_dir; + real_t den = normal.dot(segment); //printf("den is %i\n",den); - if (Math::abs(den)<=CMP_EPSILON) { + if (Math::abs(den) <= CMP_EPSILON) { return false; } - real_t dist=(normal.dot( p_from ) - d) / den; + real_t dist = (normal.dot(p_from) - d) / den; //printf("dist is %i\n",dist); - if (dist>CMP_EPSILON) { //this is a ray, before the emiting pos (p_from) doesnt exist + if (dist > CMP_EPSILON) { //this is a ray, before the emiting pos (p_from) doesnt exist return false; } - dist=-dist; + dist = -dist; *p_intersection = p_from + segment * dist; return true; } -bool Plane::intersects_segment(Vector3 p_begin, Vector3 p_end, Vector3* p_intersection) const { +bool Plane::intersects_segment(Vector3 p_begin, Vector3 p_end, Vector3 *p_intersection) const { - Vector3 segment= p_begin - p_end; - real_t den=normal.dot( segment ); + Vector3 segment = p_begin - p_end; + real_t den = normal.dot(segment); //printf("den is %i\n",den); - if (Math::abs(den)<=CMP_EPSILON) { + if (Math::abs(den) <= CMP_EPSILON) { return false; } - real_t dist=(normal.dot( p_begin ) - d) / den; + real_t dist = (normal.dot(p_begin) - d) / den; //printf("dist is %i\n",dist); - if (dist<-CMP_EPSILON || dist > (1.0 +CMP_EPSILON)) { + if (dist < -CMP_EPSILON || dist > (1.0 + CMP_EPSILON)) { return false; } - dist=-dist; + dist = -dist; *p_intersection = p_begin + segment * dist; return true; @@ -154,12 +154,11 @@ bool Plane::intersects_segment(Vector3 p_begin, Vector3 p_end, Vector3* p_inters /* misc */ -bool Plane::is_almost_like(const Plane& p_plane) const { +bool Plane::is_almost_like(const Plane &p_plane) const { - return (normal.dot( p_plane.normal ) > _PLANE_EQ_DOT_EPSILON && Math::absd(d-p_plane.d) < _PLANE_EQ_D_EPSILON); + return (normal.dot(p_plane.normal) > _PLANE_EQ_DOT_EPSILON && Math::absd(d - p_plane.d) < _PLANE_EQ_D_EPSILON); } - Plane::operator String() const { return normal.operator String() + ", " + rtos(d); diff --git a/core/math/plane.h b/core/math/plane.h index f746ea20671..4ed510713fd 100644 --- a/core/math/plane.h +++ b/core/math/plane.h @@ -29,64 +29,58 @@ #ifndef PLANE_H #define PLANE_H - #include "vector3.h" class Plane { public: - Vector3 normal; real_t d; - - void set_normal(const Vector3& p_normal); + void set_normal(const Vector3 &p_normal); _FORCE_INLINE_ Vector3 get_normal() const { return normal; }; ///Point is coplanar, CMP_EPSILON for precision void normalize(); Plane normalized() const; - /* Plane-Point operations */ + /* Plane-Point operations */ - _FORCE_INLINE_ Vector3 center() const { return normal*d; } + _FORCE_INLINE_ Vector3 center() const { return normal * d; } Vector3 get_any_point() const; Vector3 get_any_perpendicular_normal() const; _FORCE_INLINE_ bool is_point_over(const Vector3 &p_point) const; ///< Point is over plane _FORCE_INLINE_ real_t distance_to(const Vector3 &p_point) const; - _FORCE_INLINE_ bool has_point(const Vector3 &p_point,real_t _epsilon=CMP_EPSILON) const; + _FORCE_INLINE_ bool has_point(const Vector3 &p_point, real_t _epsilon = CMP_EPSILON) const; - /* intersections */ + /* intersections */ - bool intersect_3(const Plane &p_plane1, const Plane &p_plane2, Vector3 *r_result=0) const; - bool intersects_ray(Vector3 p_from, Vector3 p_dir, Vector3* p_intersection) const; - bool intersects_segment(Vector3 p_begin, Vector3 p_end, Vector3* p_intersection) const; + bool intersect_3(const Plane &p_plane1, const Plane &p_plane2, Vector3 *r_result = 0) const; + bool intersects_ray(Vector3 p_from, Vector3 p_dir, Vector3 *p_intersection) const; + bool intersects_segment(Vector3 p_begin, Vector3 p_end, Vector3 *p_intersection) const; - _FORCE_INLINE_ Vector3 project(const Vector3& p_point) const { + _FORCE_INLINE_ Vector3 project(const Vector3 &p_point) const { return p_point - normal * distance_to(p_point); } - /* misc */ + /* misc */ - Plane operator-() const { return Plane(-normal,-d); } - bool is_almost_like(const Plane& p_plane) const; + Plane operator-() const { return Plane(-normal, -d); } + bool is_almost_like(const Plane &p_plane) const; - _FORCE_INLINE_ bool operator==(const Plane& p_plane) const; - _FORCE_INLINE_ bool operator!=(const Plane& p_plane) const; + _FORCE_INLINE_ bool operator==(const Plane &p_plane) const; + _FORCE_INLINE_ bool operator!=(const Plane &p_plane) const; operator String() const; - _FORCE_INLINE_ Plane() { d=0; } - _FORCE_INLINE_ Plane(real_t p_a, real_t p_b, real_t p_c, real_t p_d) : normal(p_a,p_b,p_c), d(p_d) { }; + _FORCE_INLINE_ Plane() { d = 0; } + _FORCE_INLINE_ Plane(real_t p_a, real_t p_b, real_t p_c, real_t p_d) + : normal(p_a, p_b, p_c), d(p_d){}; _FORCE_INLINE_ Plane(const Vector3 &p_normal, real_t p_d); - _FORCE_INLINE_ Plane(const Vector3 &p_point, const Vector3& p_normal); - _FORCE_INLINE_ Plane(const Vector3 &p_point1, const Vector3 &p_point2,const Vector3 &p_point3,ClockDirection p_dir = CLOCKWISE); - - + _FORCE_INLINE_ Plane(const Vector3 &p_point, const Vector3 &p_normal); + _FORCE_INLINE_ Plane(const Vector3 &p_point1, const Vector3 &p_point2, const Vector3 &p_point3, ClockDirection p_dir = CLOCKWISE); }; - - bool Plane::is_point_over(const Vector3 &p_point) const { return (normal.dot(p_point) > d); @@ -94,53 +88,47 @@ bool Plane::is_point_over(const Vector3 &p_point) const { real_t Plane::distance_to(const Vector3 &p_point) const { - return (normal.dot(p_point)-d); + return (normal.dot(p_point) - d); } -bool Plane::has_point(const Vector3 &p_point,real_t _epsilon) const { - - float dist=normal.dot(p_point) - d; - dist=ABS(dist); - return ( dist <= _epsilon); +bool Plane::has_point(const Vector3 &p_point, real_t _epsilon) const { + float dist = normal.dot(p_point) - d; + dist = ABS(dist); + return (dist <= _epsilon); } Plane::Plane(const Vector3 &p_normal, real_t p_d) { - normal=p_normal; - d=p_d; + normal = p_normal; + d = p_d; } -Plane::Plane(const Vector3 &p_point, const Vector3& p_normal) { +Plane::Plane(const Vector3 &p_point, const Vector3 &p_normal) { - normal=p_normal; - d=p_normal.dot(p_point); + normal = p_normal; + d = p_normal.dot(p_point); } -Plane::Plane(const Vector3 &p_point1, const Vector3 &p_point2, const Vector3 &p_point3,ClockDirection p_dir) { +Plane::Plane(const Vector3 &p_point1, const Vector3 &p_point2, const Vector3 &p_point3, ClockDirection p_dir) { if (p_dir == CLOCKWISE) - normal=(p_point1-p_point3).cross(p_point1-p_point2); + normal = (p_point1 - p_point3).cross(p_point1 - p_point2); else - normal=(p_point1-p_point2).cross(p_point1-p_point3); - + normal = (p_point1 - p_point2).cross(p_point1 - p_point3); normal.normalize(); d = normal.dot(p_point1); - - } -bool Plane::operator==(const Plane& p_plane) const { +bool Plane::operator==(const Plane &p_plane) const { - return normal==p_plane.normal && d == p_plane.d; + return normal == p_plane.normal && d == p_plane.d; } -bool Plane::operator!=(const Plane& p_plane) const { - - return normal!=p_plane.normal || d != p_plane.d; +bool Plane::operator!=(const Plane &p_plane) const { + return normal != p_plane.normal || d != p_plane.d; } #endif // PLANE_H - diff --git a/core/math/quat.cpp b/core/math/quat.cpp index 8aa06a20467..2e9cfadc477 100644 --- a/core/math/quat.cpp +++ b/core/math/quat.cpp @@ -29,7 +29,7 @@ #include "quat.h" #include "print_string.h" -void Quat::set_euler(const Vector3& p_euler) { +void Quat::set_euler(const Vector3 &p_euler) { real_t half_yaw = p_euler.x * 0.5; real_t half_pitch = p_euler.y * 0.5; real_t half_roll = p_euler.z * 0.5; @@ -39,30 +39,27 @@ void Quat::set_euler(const Vector3& p_euler) { real_t sin_pitch = Math::sin(half_pitch); real_t cos_roll = Math::cos(half_roll); real_t sin_roll = Math::sin(half_roll); - set(cos_roll * sin_pitch * cos_yaw+sin_roll * cos_pitch * sin_yaw, - cos_roll * cos_pitch * sin_yaw - sin_roll * sin_pitch * cos_yaw, - sin_roll * cos_pitch * cos_yaw - cos_roll * sin_pitch * sin_yaw, - cos_roll * cos_pitch * cos_yaw+sin_roll * sin_pitch * sin_yaw); + set(cos_roll * sin_pitch * cos_yaw + sin_roll * cos_pitch * sin_yaw, + cos_roll * cos_pitch * sin_yaw - sin_roll * sin_pitch * cos_yaw, + sin_roll * cos_pitch * cos_yaw - cos_roll * sin_pitch * sin_yaw, + cos_roll * cos_pitch * cos_yaw + sin_roll * sin_pitch * sin_yaw); } -void Quat::operator*=(const Quat& q) { +void Quat::operator*=(const Quat &q) { - set(w * q.x+x * q.w+y * q.z - z * q.y, - w * q.y+y * q.w+z * q.x - x * q.z, - w * q.z+z * q.w+x * q.y - y * q.x, - w * q.w - x * q.x - y * q.y - z * q.z); + set(w * q.x + x * q.w + y * q.z - z * q.y, + w * q.y + y * q.w + z * q.x - x * q.z, + w * q.z + z * q.w + x * q.y - y * q.x, + w * q.w - x * q.x - y * q.y - z * q.z); } -Quat Quat::operator*(const Quat& q) const { +Quat Quat::operator*(const Quat &q) const { - Quat r=*this; - r*=q; + Quat r = *this; + r *= q; return r; } - - - real_t Quat::length() const { return Math::sqrt(length_squared()); @@ -72,17 +69,15 @@ void Quat::normalize() { *this /= length(); } - Quat Quat::normalized() const { return *this / length(); } Quat Quat::inverse() const { - return Quat( -x, -y, -z, w ); + return Quat(-x, -y, -z, w); } - -Quat Quat::slerp(const Quat& q, const real_t& t) const { +Quat Quat::slerp(const Quat &q, const real_t &t) const { #if 0 @@ -126,32 +121,29 @@ Quat Quat::slerp(const Quat& q, const real_t& t) const { } #else - real_t to1[4]; - real_t omega, cosom, sinom, scale0, scale1; - + real_t to1[4]; + real_t omega, cosom, sinom, scale0, scale1; // calc cosine - cosom = x * q.x + y * q.y + z * q.z - + w * q.w; - + cosom = x * q.x + y * q.y + z * q.z + w * q.w; // adjust signs (if necessary) - if ( cosom <0.0 ) { - cosom = -cosom; to1[0] = - q.x; - to1[1] = - q.y; - to1[2] = - q.z; - to1[3] = - q.w; - } else { + if (cosom < 0.0) { + cosom = -cosom; + to1[0] = -q.x; + to1[1] = -q.y; + to1[2] = -q.z; + to1[3] = -q.w; + } else { to1[0] = q.x; to1[1] = q.y; to1[2] = q.z; to1[3] = q.w; } - // calculate coefficients - if ( (1.0 - cosom) > CMP_EPSILON ) { + if ((1.0 - cosom) > CMP_EPSILON) { // standard case (slerp) omega = Math::acos(cosom); sinom = Math::sin(omega); @@ -165,15 +157,14 @@ Quat Quat::slerp(const Quat& q, const real_t& t) const { } // calculate final values return Quat( - scale0 * x + scale1 * to1[0], - scale0 * y + scale1 * to1[1], - scale0 * z + scale1 * to1[2], - scale0 * w + scale1 * to1[3] - ); + scale0 * x + scale1 * to1[0], + scale0 * y + scale1 * to1[1], + scale0 * z + scale1 * to1[2], + scale0 * w + scale1 * to1[3]); #endif } -Quat Quat::slerpni(const Quat& q, const real_t& t) const { +Quat Quat::slerpni(const Quat &q, const real_t &t) const { const Quat &from = *this; @@ -181,15 +172,15 @@ Quat Quat::slerpni(const Quat& q, const real_t& t) const { if (Math::absf(dot) > 0.9999f) return from; - float theta = Math::acos(dot), - sinT = 1.0f / Math::sin(theta), - newFactor = Math::sin(t * theta) * sinT, - invFactor = Math::sin((1.0f - t) * theta) * sinT; + float theta = Math::acos(dot), + sinT = 1.0f / Math::sin(theta), + newFactor = Math::sin(t * theta) * sinT, + invFactor = Math::sin((1.0f - t) * theta) * sinT; - return Quat( invFactor * from.x + newFactor * q.x, - invFactor * from.y + newFactor * q.y, - invFactor * from.z + newFactor * q.z, - invFactor * from.w + newFactor * q.w ); + return Quat(invFactor * from.x + newFactor * q.x, + invFactor * from.y + newFactor * q.y, + invFactor * from.z + newFactor * q.z, + invFactor * from.w + newFactor * q.w); #if 0 real_t to1[4]; @@ -239,29 +230,27 @@ Quat Quat::slerpni(const Quat& q, const real_t& t) const { #endif } -Quat Quat::cubic_slerp(const Quat& q, const Quat& prep, const Quat& postq,const real_t& t) const { +Quat Quat::cubic_slerp(const Quat &q, const Quat &prep, const Quat &postq, const real_t &t) const { //the only way to do slerp :| - float t2 = (1.0-t)*t*2; - Quat sp = this->slerp(q,t); - Quat sq = prep.slerpni(postq,t); - return sp.slerpni(sq,t2); - + float t2 = (1.0 - t) * t * 2; + Quat sp = this->slerp(q, t); + Quat sq = prep.slerpni(postq, t); + return sp.slerpni(sq, t2); } - Quat::operator String() const { - return String::num(x)+", "+String::num(y)+", "+ String::num(z)+", "+ String::num(w); + return String::num(x) + ", " + String::num(y) + ", " + String::num(z) + ", " + String::num(w); } -Quat::Quat(const Vector3& axis, const real_t& angle) { +Quat::Quat(const Vector3 &axis, const real_t &angle) { real_t d = axis.length(); - if (d==0) - set(0,0,0,0); + if (d == 0) + set(0, 0, 0, 0); else { real_t s = Math::sin(-angle * 0.5) / d; set(axis.x * s, axis.y * s, axis.z * s, - Math::cos(-angle * 0.5)); + Math::cos(-angle * 0.5)); } } diff --git a/core/math/quat.h b/core/math/quat.h index 9f4145cddbb..4234095a23d 100644 --- a/core/math/quat.h +++ b/core/math/quat.h @@ -37,160 +37,167 @@ /** @author Juan Linietsky */ -class Quat{ +class Quat { public: - - real_t x,y,z,w; + real_t x, y, z, w; _FORCE_INLINE_ real_t length_squared() const; real_t length() const; void normalize(); Quat normalized() const; Quat inverse() const; - _FORCE_INLINE_ real_t dot(const Quat& q) const; - void set_euler(const Vector3& p_euler); - Quat slerp(const Quat& q, const real_t& t) const; - Quat slerpni(const Quat& q, const real_t& t) const; - Quat cubic_slerp(const Quat& q, const Quat& prep, const Quat& postq,const real_t& t) const; + _FORCE_INLINE_ real_t dot(const Quat &q) const; + void set_euler(const Vector3 &p_euler); + Quat slerp(const Quat &q, const real_t &t) const; + Quat slerpni(const Quat &q, const real_t &t) const; + Quat cubic_slerp(const Quat &q, const Quat &prep, const Quat &postq, const real_t &t) const; - _FORCE_INLINE_ void get_axis_and_angle(Vector3& r_axis, real_t &r_angle) const { + _FORCE_INLINE_ void get_axis_and_angle(Vector3 &r_axis, real_t &r_angle) const { r_angle = 2 * Math::acos(w); - r_axis.x = -x / Math::sqrt(1-w*w); - r_axis.y = -y / Math::sqrt(1-w*w); - r_axis.z = -z / Math::sqrt(1-w*w); + r_axis.x = -x / Math::sqrt(1 - w * w); + r_axis.y = -y / Math::sqrt(1 - w * w); + r_axis.z = -z / Math::sqrt(1 - w * w); } - void operator*=(const Quat& q); - Quat operator*(const Quat& q) const; + void operator*=(const Quat &q); + Quat operator*(const Quat &q) const; - - - Quat operator*(const Vector3& v) const - { - return Quat( w * v.x + y * v.z - z * v.y, - w * v.y + z * v.x - x * v.z, - w * v.z + x * v.y - y * v.x, - -x * v.x - y * v.y - z * v.z); + Quat operator*(const Vector3 &v) const { + return Quat(w * v.x + y * v.z - z * v.y, + w * v.y + z * v.x - x * v.z, + w * v.z + x * v.y - y * v.x, + -x * v.x - y * v.y - z * v.z); } - _FORCE_INLINE_ Vector3 xform(const Vector3& v) const { + _FORCE_INLINE_ Vector3 xform(const Vector3 &v) const { Quat q = *this * v; q *= this->inverse(); - return Vector3(q.x,q.y,q.z); + return Vector3(q.x, q.y, q.z); } - _FORCE_INLINE_ void operator+=(const Quat& q); - _FORCE_INLINE_ void operator-=(const Quat& q); - _FORCE_INLINE_ void operator*=(const real_t& s); - _FORCE_INLINE_ void operator/=(const real_t& s); - _FORCE_INLINE_ Quat operator+(const Quat& q2) const; - _FORCE_INLINE_ Quat operator-(const Quat& q2) const; + _FORCE_INLINE_ void operator+=(const Quat &q); + _FORCE_INLINE_ void operator-=(const Quat &q); + _FORCE_INLINE_ void operator*=(const real_t &s); + _FORCE_INLINE_ void operator/=(const real_t &s); + _FORCE_INLINE_ Quat operator+(const Quat &q2) const; + _FORCE_INLINE_ Quat operator-(const Quat &q2) const; _FORCE_INLINE_ Quat operator-() const; - _FORCE_INLINE_ Quat operator*(const real_t& s) const; - _FORCE_INLINE_ Quat operator/(const real_t& s) const; + _FORCE_INLINE_ Quat operator*(const real_t &s) const; + _FORCE_INLINE_ Quat operator/(const real_t &s) const; - - _FORCE_INLINE_ bool operator==(const Quat& p_quat) const; - _FORCE_INLINE_ bool operator!=(const Quat& p_quat) const; + _FORCE_INLINE_ bool operator==(const Quat &p_quat) const; + _FORCE_INLINE_ bool operator!=(const Quat &p_quat) const; operator String() const; - inline void set( real_t p_x, real_t p_y, real_t p_z, real_t p_w) { - x=p_x; y=p_y; z=p_z; w=p_w; + inline void set(real_t p_x, real_t p_y, real_t p_z, real_t p_w) { + x = p_x; + y = p_y; + z = p_z; + w = p_w; } inline Quat(real_t p_x, real_t p_y, real_t p_z, real_t p_w) { - x=p_x; y=p_y; z=p_z; w=p_w; + x = p_x; + y = p_y; + z = p_z; + w = p_w; } - Quat(const Vector3& axis, const real_t& angle); + Quat(const Vector3 &axis, const real_t &angle); - Quat(const Vector3& v0, const Vector3& v1) // shortest arc + Quat(const Vector3 &v0, const Vector3 &v1) // shortest arc { Vector3 c = v0.cross(v1); - real_t d = v0.dot(v1); + real_t d = v0.dot(v1); if (d < -1.0 + CMP_EPSILON) { - x=0; - y=1; - z=0; - w=0; + x = 0; + y = 1; + z = 0; + w = 0; } else { - real_t s = Math::sqrt((1.0f + d) * 2.0f); + real_t s = Math::sqrt((1.0f + d) * 2.0f); real_t rs = 1.0f / s; - x=c.x*rs; - y=c.y*rs; - z=c.z*rs; - w=s * 0.5; + x = c.x * rs; + y = c.y * rs; + z = c.z * rs; + w = s * 0.5; } } - inline Quat() {x=y=z=0; w=1; } - - + inline Quat() { + x = y = z = 0; + w = 1; + } }; - -real_t Quat::dot(const Quat& q) const { - return x * q.x+y * q.y+z * q.z+w * q.w; +real_t Quat::dot(const Quat &q) const { + return x * q.x + y * q.y + z * q.z + w * q.w; } real_t Quat::length_squared() const { return dot(*this); } -void Quat::operator+=(const Quat& q) { - x += q.x; y += q.y; z += q.z; w += q.w; +void Quat::operator+=(const Quat &q) { + x += q.x; + y += q.y; + z += q.z; + w += q.w; } -void Quat::operator-=(const Quat& q) { - x -= q.x; y -= q.y; z -= q.z; w -= q.w; +void Quat::operator-=(const Quat &q) { + x -= q.x; + y -= q.y; + z -= q.z; + w -= q.w; } -void Quat::operator*=(const real_t& s) { - x *= s; y *= s; z *= s; w *= s; +void Quat::operator*=(const real_t &s) { + x *= s; + y *= s; + z *= s; + w *= s; } - -void Quat::operator/=(const real_t& s) { +void Quat::operator/=(const real_t &s) { *this *= 1.0 / s; } -Quat Quat::operator+(const Quat& q2) const { - const Quat& q1 = *this; - return Quat( q1.x+q2.x, q1.y+q2.y, q1.z+q2.z, q1.w+q2.w ); +Quat Quat::operator+(const Quat &q2) const { + const Quat &q1 = *this; + return Quat(q1.x + q2.x, q1.y + q2.y, q1.z + q2.z, q1.w + q2.w); } -Quat Quat::operator-(const Quat& q2) const { - const Quat& q1 = *this; - return Quat( q1.x-q2.x, q1.y-q2.y, q1.z-q2.z, q1.w-q2.w); +Quat Quat::operator-(const Quat &q2) const { + const Quat &q1 = *this; + return Quat(q1.x - q2.x, q1.y - q2.y, q1.z - q2.z, q1.w - q2.w); } Quat Quat::operator-() const { - const Quat& q2 = *this; - return Quat( -q2.x, -q2.y, -q2.z, -q2.w); + const Quat &q2 = *this; + return Quat(-q2.x, -q2.y, -q2.z, -q2.w); } -Quat Quat::operator*(const real_t& s) const { +Quat Quat::operator*(const real_t &s) const { return Quat(x * s, y * s, z * s, w * s); } -Quat Quat::operator/(const real_t& s) const { +Quat Quat::operator/(const real_t &s) const { return *this * (1.0 / s); } +bool Quat::operator==(const Quat &p_quat) const { -bool Quat::operator==(const Quat& p_quat) const { - - return x==p_quat.x && y==p_quat.y && z==p_quat.z && w==p_quat.w; + return x == p_quat.x && y == p_quat.y && z == p_quat.z && w == p_quat.w; } -bool Quat::operator!=(const Quat& p_quat) const { +bool Quat::operator!=(const Quat &p_quat) const { - return x!=p_quat.x || y!=p_quat.y || z!=p_quat.z || w!=p_quat.w; + return x != p_quat.x || y != p_quat.y || z != p_quat.z || w != p_quat.w; } - #endif diff --git a/core/math/quick_hull.cpp b/core/math/quick_hull.cpp index ce6f7264188..5e4cf60e3c4 100644 --- a/core/math/quick_hull.cpp +++ b/core/math/quick_hull.cpp @@ -29,49 +29,44 @@ #include "quick_hull.h" #include "map.h" -uint32_t QuickHull::debug_stop_after=0xFFFFFFFF; - -Error QuickHull::build(const Vector& p_points, Geometry::MeshData &r_mesh) { +uint32_t QuickHull::debug_stop_after = 0xFFFFFFFF; +Error QuickHull::build(const Vector &p_points, Geometry::MeshData &r_mesh) { static const real_t over_tolerance = 0.0001; /* CREATE AABB VOLUME */ AABB aabb; - for(int i=0;i valid_points; valid_points.resize(p_points.size()); Set valid_cache; - for(int i=0;i& p_points, Geometry::MeshData &r_me int simplex[4]; { - real_t max,min; + real_t max, min; - for(int i=0;i max) { - simplex[1]=i; - max=d; + if (i == 0 || d > max) { + simplex[1] = i; + max = d; } - } } //third vertex is one most further away from the line - { float maxd; - Vector3 rel12 = p_points[simplex[0]] - p_points[simplex[1]]; + Vector3 rel12 = p_points[simplex[0]] - p_points[simplex[1]]; - for(int i=0;imaxd) { + if (i == 0 || d > maxd) { - maxd=d; - simplex[2]=i; + maxd = d; + simplex[2] = i; } } } @@ -128,102 +121,92 @@ Error QuickHull::build(const Vector& p_points, Geometry::MeshData &r_me { float maxd; - Plane p(p_points[simplex[0]],p_points[simplex[1]],p_points[simplex[2]]); + Plane p(p_points[simplex[0]], p_points[simplex[1]], p_points[simplex[2]]); - for(int i=0;imaxd) { + if (i == 0 || d > maxd) { - maxd=d; - simplex[3]=i; + maxd = d; + simplex[3] = i; } } } - //compute center of simplex, this is a point always warranted to be inside Vector3 center; - for(int i=0;i<4;i++) { - center+=p_points[simplex[i]]; + for (int i = 0; i < 4; i++) { + center += p_points[simplex[i]]; } - center/=4.0; + center /= 4.0; //add faces List faces; - for(int i=0;i<4;i++) { + for (int i = 0; i < 4; i++) { - static const int face_order[4][3]={ - {0,1,2}, - {0,1,3}, - {0,2,3}, - {1,2,3} + static const int face_order[4][3] = { + { 0, 1, 2 }, + { 0, 1, 3 }, + { 0, 2, 3 }, + { 1, 2, 3 } }; Face f; - for(int j=0;j<3;j++) { - f.vertices[j]=simplex[face_order[i][j]]; + for (int j = 0; j < 3; j++) { + f.vertices[j] = simplex[face_order[i][j]]; } - - Plane p(p_points[f.vertices[0]],p_points[f.vertices[1]],p_points[f.vertices[2]]); + Plane p(p_points[f.vertices[0]], p_points[f.vertices[1]], p_points[f.vertices[2]]); if (p.is_point_over(center)) { //flip face to clockwise if facing inwards - SWAP( f.vertices[0], f.vertices[1] ); - p=-p; + SWAP(f.vertices[0], f.vertices[1]); + p = -p; } - f.plane = p; faces.push_back(f); - } - /* COMPUTE AVAILABLE VERTICES */ - for(int i=0;i::Element *E=faces.front();E;E=E->next()) { + for (List::Element *E = faces.front(); E; E = E->next()) { - if (E->get().plane.distance_to(p_points[i]) > over_tolerance ) { + if (E->get().plane.distance_to(p_points[i]) > over_tolerance) { E->get().points_over.push_back(i); break; } } - - - } faces.sort(); // sort them, so the ones with points are in the back - /* BUILD HULL */ - //poop face (while still remain) //find further away point //find lit faces @@ -231,72 +214,68 @@ Error QuickHull::build(const Vector& p_points, Geometry::MeshData &r_me //build new faces with horizon edges, them assign points side from all lit faces //remove lit faces - uint32_t debug_stop = debug_stop_after; - while(debug_stop>0 && faces.back()->get().points_over.size()) { + while (debug_stop > 0 && faces.back()->get().points_over.size()) { debug_stop--; - Face& f = faces.back()->get(); + Face &f = faces.back()->get(); //find vertex most outside - int next=-1; - real_t next_d=0; + int next = -1; + real_t next_d = 0; - for(int i=0;i next_d) { - next_d=d; - next=i; + next_d = d; + next = i; } } - ERR_FAIL_COND_V(next==-1,ERR_BUG); - - + ERR_FAIL_COND_V(next == -1, ERR_BUG); Vector3 v = p_points[f.points_over[next]]; //find lit faces and lit edges - List< List::Element* > lit_faces; //lit face is a death sentence + List::Element *> lit_faces; //lit face is a death sentence - Map lit_edges; //create this on the flight, should not be that bad for performance and simplifies code a lot + Map lit_edges; //create this on the flight, should not be that bad for performance and simplifies code a lot - for(List::Element *E=faces.front();E;E=E->next()) { + for (List::Element *E = faces.front(); E; E = E->next()) { - if (E->get().plane.distance_to(v) >0 ) { + if (E->get().plane.distance_to(v) > 0) { lit_faces.push_back(E); - for(int i=0;i<3;i++) { + for (int i = 0; i < 3; i++) { uint32_t a = E->get().vertices[i]; - uint32_t b = E->get().vertices[(i+1)%3]; - Edge e(a,b); + uint32_t b = E->get().vertices[(i + 1) % 3]; + Edge e(a, b); - Map::Element *F=lit_edges.find(e); + Map::Element *F = lit_edges.find(e); if (!F) { - F=lit_edges.insert(e,FaceConnect()); + F = lit_edges.insert(e, FaceConnect()); } - if (e.vertices[0]==a) { + if (e.vertices[0] == a) { //left - F->get().left=E; + F->get().left = E; } else { - F->get().right=E; + F->get().right = E; } } } } - //create new faces from horizon edges - List< List::Element* > new_faces; //new faces + List::Element *> new_faces; //new faces - for(Map::Element *E=lit_edges.front();E;E=E->next()) { + for (Map::Element *E = lit_edges.front(); E; E = E->next()) { - FaceConnect& fc = E->get(); + FaceConnect &fc = E->get(); if (fc.left && fc.right) { continue; //edge is uninteresting, not on horizont } @@ -304,50 +283,48 @@ Error QuickHull::build(const Vector& p_points, Geometry::MeshData &r_me //create new face! Face face; - face.vertices[0]=f.points_over[next]; - face.vertices[1]=E->key().vertices[0]; - face.vertices[2]=E->key().vertices[1]; + face.vertices[0] = f.points_over[next]; + face.vertices[1] = E->key().vertices[0]; + face.vertices[2] = E->key().vertices[1]; - Plane p(p_points[face.vertices[0]],p_points[face.vertices[1]],p_points[face.vertices[2]]); + Plane p(p_points[face.vertices[0]], p_points[face.vertices[1]], p_points[face.vertices[2]]); if (p.is_point_over(center)) { //flip face to clockwise if facing inwards - SWAP( face.vertices[0], face.vertices[1] ); + SWAP(face.vertices[0], face.vertices[1]); p = -p; } face.plane = p; - new_faces.push_back( faces.push_back(face) ); + new_faces.push_back(faces.push_back(face)); } //distribute points into new faces - for(List< List::Element* >::Element *F=lit_faces.front();F;F=F->next()) { + for (List::Element *>::Element *F = lit_faces.front(); F; F = F->next()) { Face &lf = F->get()->get(); - for(int i=0;i::Element* >::Element *E=new_faces.front();E;E=E->next()) { + for (List::Element *>::Element *E = new_faces.front(); E; E = E->next()) { Face &f2 = E->get()->get(); - if (f2.plane.distance_to(p)>over_tolerance) { + if (f2.plane.distance_to(p) > over_tolerance) { f2.points_over.push_back(lf.points_over[i]); break; } } - - } } //erase lit faces - while(lit_faces.size()) { + while (lit_faces.size()) { faces.erase(lit_faces.front()->get()); lit_faces.pop_front(); @@ -355,156 +332,140 @@ Error QuickHull::build(const Vector& p_points, Geometry::MeshData &r_me //put faces that contain no points on the front - for (List< List::Element* >::Element *E=new_faces.front();E;E=E->next()) { + for (List::Element *>::Element *E = new_faces.front(); E; E = E->next()) { Face &f2 = E->get()->get(); - if (f2.points_over.size()==0) { + if (f2.points_over.size() == 0) { faces.move_to_front(E->get()); } } //whew, done with iteration, go next - - - } /* CREATE MESHDATA */ - //make a map of edges again - Map ret_edges; + Map ret_edges; List ret_faces; - - for(List::Element *E=faces.front();E;E=E->next()) { + for (List::Element *E = faces.front(); E; E = E->next()) { Geometry::MeshData::Face f; f.plane = E->get().plane; - - - for(int i=0;i<3;i++) { + for (int i = 0; i < 3; i++) { f.indices.push_back(E->get().vertices[i]); } List::Element *F = ret_faces.push_back(f); - for(int i=0;i<3;i++) { + for (int i = 0; i < 3; i++) { uint32_t a = E->get().vertices[i]; - uint32_t b = E->get().vertices[(i+1)%3]; - Edge e(a,b); + uint32_t b = E->get().vertices[(i + 1) % 3]; + Edge e(a, b); - Map::Element *G=ret_edges.find(e); + Map::Element *G = ret_edges.find(e); if (!G) { - G=ret_edges.insert(e,RetFaceConnect()); + G = ret_edges.insert(e, RetFaceConnect()); } - if (e.vertices[0]==a) { + if (e.vertices[0] == a) { //left - G->get().left=F; + G->get().left = F; } else { - G->get().right=F; + G->get().right = F; } } } //fill faces - for (List::Element *E=ret_faces.front();E;E=E->next()) { + for (List::Element *E = ret_faces.front(); E; E = E->next()) { - Geometry::MeshData::Face& f = E->get(); + Geometry::MeshData::Face &f = E->get(); - for(int i=0;iget().indices[i]; - uint32_t b = E->get().indices[(i+1)%f.indices.size()]; - Edge e(a,b); + uint32_t b = E->get().indices[(i + 1) % f.indices.size()]; + Edge e(a, b); - Map::Element *F=ret_edges.find(e); + Map::Element *F = ret_edges.find(e); ERR_CONTINUE(!F); List::Element *O = F->get().left == E ? F->get().right : F->get().left; - ERR_CONTINUE(O==E); - ERR_CONTINUE(O==NULL); + ERR_CONTINUE(O == E); + ERR_CONTINUE(O == NULL); if (O->get().plane.is_almost_like(f.plane)) { //merge and delete edge and contiguous face, while repointing edges (uuugh!) int ois = O->get().indices.size(); - int merged=0; + int merged = 0; - - for(int j=0;jget().indices[j]==a) { + if (O->get().indices[j] == a) { //append the rest - for(int k=0;kget().indices[(k+j)%ois]; - int idxn = O->get().indices[(k+j+1)%ois]; - if (idx==b && idxn==a) {//already have b! + int idx = O->get().indices[(k + j) % ois]; + int idxn = O->get().indices[(k + j + 1) % ois]; + if (idx == b && idxn == a) { //already have b! break; } - if (idx!=a) { - f.indices.insert(i+1,idx); + if (idx != a) { + f.indices.insert(i + 1, idx); i++; merged++; } - Edge e2(idx,idxn); + Edge e2(idx, idxn); - Map::Element *F2=ret_edges.find(e2); + Map::Element *F2 = ret_edges.find(e2); ERR_CONTINUE(!F2); //change faceconnect, point to this face instead if (F2->get().left == O) - F2->get().left=E; + F2->get().left = E; else if (F2->get().right == O) - F2->get().right=E; - + F2->get().right = E; } break; } } - ret_edges.erase(F); //remove the edge ret_faces.erase(O); //remove the face - - } - } - } //fill mesh r_mesh.faces.clear(); r_mesh.faces.resize(ret_faces.size()); -// print_line("FACECOUNT: "+itos(r_mesh.faces.size())); - - int idx=0; - for (List::Element *E=ret_faces.front();E;E=E->next()) { - r_mesh.faces[idx++]=E->get(); - + // print_line("FACECOUNT: "+itos(r_mesh.faces.size())); + int idx = 0; + for (List::Element *E = ret_faces.front(); E; E = E->next()) { + r_mesh.faces[idx++] = E->get(); } r_mesh.edges.resize(ret_edges.size()); - idx=0; - for(Map::Element *E=ret_edges.front();E;E=E->next()) { + idx = 0; + for (Map::Element *E = ret_edges.front(); E; E = E->next()) { Geometry::MeshData::Edge e; - e.a=E->key().vertices[0]; - e.b=E->key().vertices[1]; - r_mesh.edges[idx++]=e; + e.a = E->key().vertices[0]; + e.b = E->key().vertices[1]; + r_mesh.edges[idx++] = e; } - r_mesh.vertices=p_points; + r_mesh.vertices = p_points; //r_mesh.optimize_vertices(); -/* + /* print_line("FACES: "+itos(r_mesh.faces.size())); print_line("EDGES: "+itos(r_mesh.edges.size())); print_line("VERTICES: "+itos(r_mesh.vertices.size())); diff --git a/core/math/quick_hull.h b/core/math/quick_hull.h index 04d25fef185..d620d1899fc 100644 --- a/core/math/quick_hull.h +++ b/core/math/quick_hull.h @@ -30,15 +30,13 @@ #define QUICK_HULL_H #include "aabb.h" -#include "set.h" -#include "list.h" #include "geometry.h" +#include "list.h" +#include "set.h" class QuickHull { public: - - struct Edge { union { @@ -46,19 +44,18 @@ public: uint64_t id; }; - - bool operator<(const Edge& p_edge) const { + bool operator<(const Edge &p_edge) const { return id < p_edge.id; } - Edge(int p_vtx_a=0,int p_vtx_b=0) { + Edge(int p_vtx_a = 0, int p_vtx_b = 0) { - if (p_vtx_a>p_vtx_b) { - SWAP(p_vtx_a,p_vtx_b); + if (p_vtx_a > p_vtx_b) { + SWAP(p_vtx_a, p_vtx_b); } - vertices[0]=p_vtx_a; - vertices[1]=p_vtx_b; + vertices[0] = p_vtx_a; + vertices[1] = p_vtx_b; } }; @@ -68,28 +65,31 @@ public: int vertices[3]; Vector points_over; - bool operator<(const Face& p_face) const { + bool operator<(const Face &p_face) const { return points_over.size() < p_face.points_over.size(); } - }; -private: +private: struct FaceConnect { - List::Element *left,*right; - FaceConnect() { left=NULL; right=NULL; } + List::Element *left, *right; + FaceConnect() { + left = NULL; + right = NULL; + } }; struct RetFaceConnect { - List::Element *left,*right; - RetFaceConnect() { left=NULL; right=NULL; } + List::Element *left, *right; + RetFaceConnect() { + left = NULL; + right = NULL; + } }; public: - static uint32_t debug_stop_after; - static Error build(const Vector& p_points,Geometry::MeshData& r_mesh); - + static Error build(const Vector &p_points, Geometry::MeshData &r_mesh); }; #endif // QUICK_HULL_H diff --git a/core/math/transform.cpp b/core/math/transform.cpp index 8516e4afcfa..8e9cd39b1b0 100644 --- a/core/math/transform.cpp +++ b/core/math/transform.cpp @@ -31,7 +31,6 @@ #include "os/copymem.h" #include "print_string.h" - void Transform::affine_invert() { basis.invert(); @@ -40,13 +39,11 @@ void Transform::affine_invert() { Transform Transform::affine_inverse() const { - Transform ret=*this; + Transform ret = *this; ret.affine_invert(); return ret; - } - void Transform::invert() { basis.transpose(); @@ -55,35 +52,34 @@ void Transform::invert() { Transform Transform::inverse() const { - Transform ret=*this; + Transform ret = *this; ret.invert(); return ret; } +void Transform::rotate(const Vector3 &p_axis, real_t p_phi) { -void Transform::rotate(const Vector3& p_axis,real_t p_phi) { - - *this = *this * Transform( Matrix3( p_axis, p_phi ), Vector3() ); + *this = *this * Transform(Matrix3(p_axis, p_phi), Vector3()); } -Transform Transform::rotated(const Vector3& p_axis,real_t p_phi) const{ +Transform Transform::rotated(const Vector3 &p_axis, real_t p_phi) const { - return *this * Transform( Matrix3( p_axis, p_phi ), Vector3() ); + return *this * Transform(Matrix3(p_axis, p_phi), Vector3()); } -void Transform::rotate_basis(const Vector3& p_axis,real_t p_phi) { +void Transform::rotate_basis(const Vector3 &p_axis, real_t p_phi) { - basis.rotate(p_axis,p_phi); + basis.rotate(p_axis, p_phi); } -Transform Transform::looking_at( const Vector3& p_target, const Vector3& p_up ) const { +Transform Transform::looking_at(const Vector3 &p_target, const Vector3 &p_up) const { Transform t = *this; - t.set_look_at(origin,p_target,p_up); + t.set_look_at(origin, p_target, p_up); return t; } -void Transform::set_look_at( const Vector3& p_eye, const Vector3& p_target, const Vector3& p_up ) { +void Transform::set_look_at(const Vector3 &p_eye, const Vector3 &p_target, const Vector3 &p_up) { // Reference: MESA source code Vector3 v_x, v_y, v_z; @@ -97,23 +93,21 @@ void Transform::set_look_at( const Vector3& p_eye, const Vector3& p_target, cons v_y = p_up; - - v_x=v_y.cross(v_z); + v_x = v_y.cross(v_z); /* Recompute Y = Z cross X */ - v_y=v_z.cross(v_x); + v_y = v_z.cross(v_x); v_x.normalize(); v_y.normalize(); - basis.set_axis(0,v_x); - basis.set_axis(1,v_y); - basis.set_axis(2,v_z); - origin=p_eye; - + basis.set_axis(0, v_x); + basis.set_axis(1, v_y); + basis.set_axis(2, v_z); + origin = p_eye; } -Transform Transform::interpolate_with(const Transform& p_transform, float p_c) const { +Transform Transform::interpolate_with(const Transform &p_transform, float p_c) const { /* not sure if very "efficient" but good enough? */ @@ -126,45 +120,44 @@ Transform Transform::interpolate_with(const Transform& p_transform, float p_c) c Vector3 dst_loc = p_transform.origin; Transform dst; - dst.basis=src_rot.slerp(dst_rot,p_c); - dst.basis.scale(src_scale.linear_interpolate(dst_scale,p_c)); - dst.origin=src_loc.linear_interpolate(dst_loc,p_c); + dst.basis = src_rot.slerp(dst_rot, p_c); + dst.basis.scale(src_scale.linear_interpolate(dst_scale, p_c)); + dst.origin = src_loc.linear_interpolate(dst_loc, p_c); return dst; } -void Transform::scale(const Vector3& p_scale) { +void Transform::scale(const Vector3 &p_scale) { basis.scale(p_scale); - origin*=p_scale; + origin *= p_scale; } -Transform Transform::scaled(const Vector3& p_scale) const { +Transform Transform::scaled(const Vector3 &p_scale) const { Transform t = *this; t.scale(p_scale); return t; } -void Transform::scale_basis(const Vector3& p_scale) { +void Transform::scale_basis(const Vector3 &p_scale) { basis.scale(p_scale); } -void Transform::translate( real_t p_tx, real_t p_ty, real_t p_tz) { - translate( Vector3(p_tx,p_ty,p_tz) ); - +void Transform::translate(real_t p_tx, real_t p_ty, real_t p_tz) { + translate(Vector3(p_tx, p_ty, p_tz)); } -void Transform::translate( const Vector3& p_translation ) { +void Transform::translate(const Vector3 &p_translation) { - for( int i = 0; i < 3; i++ ) { + for (int i = 0; i < 3; i++) { origin[i] += basis[i].dot(p_translation); } } -Transform Transform::translated( const Vector3& p_translation ) const { +Transform Transform::translated(const Vector3 &p_translation) const { - Transform t=*this; + Transform t = *this; t.translate(p_translation); return t; } @@ -181,25 +174,25 @@ Transform Transform::orthonormalized() const { return _copy; } -bool Transform::operator==(const Transform& p_transform) const { +bool Transform::operator==(const Transform &p_transform) const { - return (basis==p_transform.basis && origin==p_transform.origin); + return (basis == p_transform.basis && origin == p_transform.origin); } -bool Transform::operator!=(const Transform& p_transform) const { +bool Transform::operator!=(const Transform &p_transform) const { - return (basis!=p_transform.basis || origin!=p_transform.origin); + return (basis != p_transform.basis || origin != p_transform.origin); } -void Transform::operator*=(const Transform& p_transform) { +void Transform::operator*=(const Transform &p_transform) { - origin=xform(p_transform.origin); - basis*=p_transform.basis; + origin = xform(p_transform.origin); + basis *= p_transform.basis; } -Transform Transform::operator*(const Transform& p_transform) const { +Transform Transform::operator*(const Transform &p_transform) const { - Transform t=*this; - t*=p_transform; + Transform t = *this; + t *= p_transform; return t; } @@ -208,11 +201,8 @@ Transform::operator String() const { return basis.operator String() + " - " + origin.operator String(); } +Transform::Transform(const Matrix3 &p_basis, const Vector3 &p_origin) { -Transform::Transform(const Matrix3& p_basis, const Vector3& p_origin) { - - basis=p_basis; - origin=p_origin; + basis = p_basis; + origin = p_origin; } - - diff --git a/core/math/transform.h b/core/math/transform.h index 7999f0b347f..f7be19ebe9c 100644 --- a/core/math/transform.h +++ b/core/math/transform.h @@ -29,15 +29,14 @@ #ifndef TRANSFORM_H #define TRANSFORM_H +#include "aabb.h" #include "matrix3.h" #include "plane.h" -#include "aabb.h" /** @author Juan Linietsky */ class Transform { public: - Matrix3 basis; Vector3 origin; @@ -47,199 +46,187 @@ public: void affine_invert(); Transform affine_inverse() const; - Transform rotated(const Vector3& p_axis,real_t p_phi) const; + Transform rotated(const Vector3 &p_axis, real_t p_phi) const; - void rotate(const Vector3& p_axis,real_t p_phi); - void rotate_basis(const Vector3& p_axis,real_t p_phi); + void rotate(const Vector3 &p_axis, real_t p_phi); + void rotate_basis(const Vector3 &p_axis, real_t p_phi); - void set_look_at( const Vector3& p_eye, const Vector3& p_target, const Vector3& p_up ); - Transform looking_at( const Vector3& p_target, const Vector3& p_up ) const; + void set_look_at(const Vector3 &p_eye, const Vector3 &p_target, const Vector3 &p_up); + Transform looking_at(const Vector3 &p_target, const Vector3 &p_up) const; - void scale(const Vector3& p_scale); - Transform scaled(const Vector3& p_scale) const; - void scale_basis(const Vector3& p_scale); - void translate( real_t p_tx, real_t p_ty, real_t p_tz ); - void translate( const Vector3& p_translation ); - Transform translated( const Vector3& p_translation ) const; + void scale(const Vector3 &p_scale); + Transform scaled(const Vector3 &p_scale) const; + void scale_basis(const Vector3 &p_scale); + void translate(real_t p_tx, real_t p_ty, real_t p_tz); + void translate(const Vector3 &p_translation); + Transform translated(const Vector3 &p_translation) const; - const Matrix3& get_basis() const { return basis; } - void set_basis(const Matrix3& p_basis) { basis=p_basis; } + const Matrix3 &get_basis() const { return basis; } + void set_basis(const Matrix3 &p_basis) { basis = p_basis; } - const Vector3& get_origin() const { return origin; } - void set_origin(const Vector3& p_origin) { origin=p_origin; } + const Vector3 &get_origin() const { return origin; } + void set_origin(const Vector3 &p_origin) { origin = p_origin; } void orthonormalize(); Transform orthonormalized() const; - bool operator==(const Transform& p_transform) const; - bool operator!=(const Transform& p_transform) const; + bool operator==(const Transform &p_transform) const; + bool operator!=(const Transform &p_transform) const; - _FORCE_INLINE_ Vector3 xform(const Vector3& p_vector) const; - _FORCE_INLINE_ Vector3 xform_inv(const Vector3& p_vector) const; + _FORCE_INLINE_ Vector3 xform(const Vector3 &p_vector) const; + _FORCE_INLINE_ Vector3 xform_inv(const Vector3 &p_vector) const; - _FORCE_INLINE_ Plane xform(const Plane& p_plane) const; - _FORCE_INLINE_ Plane xform_inv(const Plane& p_plane) const; + _FORCE_INLINE_ Plane xform(const Plane &p_plane) const; + _FORCE_INLINE_ Plane xform_inv(const Plane &p_plane) const; - _FORCE_INLINE_ AABB xform(const AABB& p_aabb) const; - _FORCE_INLINE_ AABB xform_inv(const AABB& p_aabb) const; + _FORCE_INLINE_ AABB xform(const AABB &p_aabb) const; + _FORCE_INLINE_ AABB xform_inv(const AABB &p_aabb) const; - void operator*=(const Transform& p_transform); - Transform operator*(const Transform& p_transform) const; + void operator*=(const Transform &p_transform); + Transform operator*(const Transform &p_transform) const; - Transform interpolate_with(const Transform& p_transform, float p_c) const; + Transform interpolate_with(const Transform &p_transform, float p_c) const; - _FORCE_INLINE_ Transform inverse_xform(const Transform& t) const { + _FORCE_INLINE_ Transform inverse_xform(const Transform &t) const { Vector3 v = t.origin - origin; return Transform(basis.transpose_xform(t.basis), - basis.xform(v)); + basis.xform(v)); } - void set(real_t xx, real_t xy, real_t xz, real_t yx, real_t yy, real_t yz, real_t zx, real_t zy, real_t zz,real_t tx, real_t ty, real_t tz) { + void set(real_t xx, real_t xy, real_t xz, real_t yx, real_t yy, real_t yz, real_t zx, real_t zy, real_t zz, real_t tx, real_t ty, real_t tz) { - basis.elements[0][0]=xx; - basis.elements[0][1]=xy; - basis.elements[0][2]=xz; - basis.elements[1][0]=yx; - basis.elements[1][1]=yy; - basis.elements[1][2]=yz; - basis.elements[2][0]=zx; - basis.elements[2][1]=zy; - basis.elements[2][2]=zz; - origin.x=tx; - origin.y=ty; - origin.z=tz; + basis.elements[0][0] = xx; + basis.elements[0][1] = xy; + basis.elements[0][2] = xz; + basis.elements[1][0] = yx; + basis.elements[1][1] = yy; + basis.elements[1][2] = yz; + basis.elements[2][0] = zx; + basis.elements[2][1] = zy; + basis.elements[2][2] = zz; + origin.x = tx; + origin.y = ty; + origin.z = tz; } operator String() const; - Transform(const Matrix3& p_basis, const Vector3& p_origin=Vector3()); + Transform(const Matrix3 &p_basis, const Vector3 &p_origin = Vector3()); Transform() {} - }; - -_FORCE_INLINE_ Vector3 Transform::xform(const Vector3& p_vector) const { +_FORCE_INLINE_ Vector3 Transform::xform(const Vector3 &p_vector) const { return Vector3( - basis[0].dot(p_vector)+origin.x, - basis[1].dot(p_vector)+origin.y, - basis[2].dot(p_vector)+origin.z - ); + basis[0].dot(p_vector) + origin.x, + basis[1].dot(p_vector) + origin.y, + basis[2].dot(p_vector) + origin.z); } -_FORCE_INLINE_ Vector3 Transform::xform_inv(const Vector3& p_vector) const { +_FORCE_INLINE_ Vector3 Transform::xform_inv(const Vector3 &p_vector) const { Vector3 v = p_vector - origin; return Vector3( - (basis.elements[0][0]*v.x ) + ( basis.elements[1][0]*v.y ) + ( basis.elements[2][0]*v.z ), - (basis.elements[0][1]*v.x ) + ( basis.elements[1][1]*v.y ) + ( basis.elements[2][1]*v.z ), - (basis.elements[0][2]*v.x ) + ( basis.elements[1][2]*v.y ) + ( basis.elements[2][2]*v.z ) - ); + (basis.elements[0][0] * v.x) + (basis.elements[1][0] * v.y) + (basis.elements[2][0] * v.z), + (basis.elements[0][1] * v.x) + (basis.elements[1][1] * v.y) + (basis.elements[2][1] * v.z), + (basis.elements[0][2] * v.x) + (basis.elements[1][2] * v.y) + (basis.elements[2][2] * v.z)); } -_FORCE_INLINE_ Plane Transform::xform(const Plane& p_plane) const { +_FORCE_INLINE_ Plane Transform::xform(const Plane &p_plane) const { + Vector3 point = p_plane.normal * p_plane.d; + Vector3 point_dir = point + p_plane.normal; + point = xform(point); + point_dir = xform(point_dir); - Vector3 point=p_plane.normal*p_plane.d; - Vector3 point_dir=point+p_plane.normal; - point=xform(point); - point_dir=xform(point_dir); - - Vector3 normal=point_dir-point; + Vector3 normal = point_dir - point; normal.normalize(); - real_t d=normal.dot(point); - - return Plane(normal,d); + real_t d = normal.dot(point); + return Plane(normal, d); } -_FORCE_INLINE_ Plane Transform::xform_inv(const Plane& p_plane) const { +_FORCE_INLINE_ Plane Transform::xform_inv(const Plane &p_plane) const { - Vector3 point=p_plane.normal*p_plane.d; - Vector3 point_dir=point+p_plane.normal; + Vector3 point = p_plane.normal * p_plane.d; + Vector3 point_dir = point + p_plane.normal; xform_inv(point); xform_inv(point_dir); - Vector3 normal=point_dir-point; + Vector3 normal = point_dir - point; normal.normalize(); - real_t d=normal.dot(point); - - return Plane(normal,d); + real_t d = normal.dot(point); + return Plane(normal, d); } -_FORCE_INLINE_ AABB Transform::xform(const AABB& p_aabb) const { - /* define vertices */ +_FORCE_INLINE_ AABB Transform::xform(const AABB &p_aabb) const { +/* define vertices */ #if 1 - Vector3 x=basis.get_axis(0)*p_aabb.size.x; - Vector3 y=basis.get_axis(1)*p_aabb.size.y; - Vector3 z=basis.get_axis(2)*p_aabb.size.z; - Vector3 pos = xform( p_aabb.pos ); -//could be even further optimized + Vector3 x = basis.get_axis(0) * p_aabb.size.x; + Vector3 y = basis.get_axis(1) * p_aabb.size.y; + Vector3 z = basis.get_axis(2) * p_aabb.size.z; + Vector3 pos = xform(p_aabb.pos); + //could be even further optimized AABB new_aabb; - new_aabb.pos=pos; - new_aabb.expand_to( pos+x ); - new_aabb.expand_to( pos+y ); - new_aabb.expand_to( pos+z ); - new_aabb.expand_to( pos+x+y ); - new_aabb.expand_to( pos+x+z ); - new_aabb.expand_to( pos+y+z ); - new_aabb.expand_to( pos+x+y+z ); + new_aabb.pos = pos; + new_aabb.expand_to(pos + x); + new_aabb.expand_to(pos + y); + new_aabb.expand_to(pos + z); + new_aabb.expand_to(pos + x + y); + new_aabb.expand_to(pos + x + z); + new_aabb.expand_to(pos + y + z); + new_aabb.expand_to(pos + x + y + z); return new_aabb; #else - - Vector3 vertices[8]={ - Vector3(p_aabb.pos.x+p_aabb.size.x, p_aabb.pos.y+p_aabb.size.y, p_aabb.pos.z+p_aabb.size.z), - Vector3(p_aabb.pos.x+p_aabb.size.x, p_aabb.pos.y+p_aabb.size.y, p_aabb.pos.z), - Vector3(p_aabb.pos.x+p_aabb.size.x, p_aabb.pos.y, p_aabb.pos.z+p_aabb.size.z), - Vector3(p_aabb.pos.x+p_aabb.size.x, p_aabb.pos.y, p_aabb.pos.z), - Vector3(p_aabb.pos.x, p_aabb.pos.y+p_aabb.size.y, p_aabb.pos.z+p_aabb.size.z), - Vector3(p_aabb.pos.x, p_aabb.pos.y+p_aabb.size.y, p_aabb.pos.z), - Vector3(p_aabb.pos.x, p_aabb.pos.y, p_aabb.pos.z+p_aabb.size.z), - Vector3(p_aabb.pos.x, p_aabb.pos.y, p_aabb.pos.z) + Vector3 vertices[8] = { + Vector3(p_aabb.pos.x + p_aabb.size.x, p_aabb.pos.y + p_aabb.size.y, p_aabb.pos.z + p_aabb.size.z), + Vector3(p_aabb.pos.x + p_aabb.size.x, p_aabb.pos.y + p_aabb.size.y, p_aabb.pos.z), + Vector3(p_aabb.pos.x + p_aabb.size.x, p_aabb.pos.y, p_aabb.pos.z + p_aabb.size.z), + Vector3(p_aabb.pos.x + p_aabb.size.x, p_aabb.pos.y, p_aabb.pos.z), + Vector3(p_aabb.pos.x, p_aabb.pos.y + p_aabb.size.y, p_aabb.pos.z + p_aabb.size.z), + Vector3(p_aabb.pos.x, p_aabb.pos.y + p_aabb.size.y, p_aabb.pos.z), + Vector3(p_aabb.pos.x, p_aabb.pos.y, p_aabb.pos.z + p_aabb.size.z), + Vector3(p_aabb.pos.x, p_aabb.pos.y, p_aabb.pos.z) }; - AABB ret; - ret.pos=xform(vertices[0]); + ret.pos = xform(vertices[0]); - for (int i=1;i<8;i++) { + for (int i = 1; i < 8; i++) { - ret.expand_to( xform(vertices[i]) ); + ret.expand_to(xform(vertices[i])); } return ret; #endif - } -_FORCE_INLINE_ AABB Transform::xform_inv(const AABB& p_aabb) const { +_FORCE_INLINE_ AABB Transform::xform_inv(const AABB &p_aabb) const { /* define vertices */ - Vector3 vertices[8]={ - Vector3(p_aabb.pos.x+p_aabb.size.x, p_aabb.pos.y+p_aabb.size.y, p_aabb.pos.z+p_aabb.size.z), - Vector3(p_aabb.pos.x+p_aabb.size.x, p_aabb.pos.y+p_aabb.size.y, p_aabb.pos.z), - Vector3(p_aabb.pos.x+p_aabb.size.x, p_aabb.pos.y, p_aabb.pos.z+p_aabb.size.z), - Vector3(p_aabb.pos.x+p_aabb.size.x, p_aabb.pos.y, p_aabb.pos.z), - Vector3(p_aabb.pos.x, p_aabb.pos.y+p_aabb.size.y, p_aabb.pos.z+p_aabb.size.z), - Vector3(p_aabb.pos.x, p_aabb.pos.y+p_aabb.size.y, p_aabb.pos.z), - Vector3(p_aabb.pos.x, p_aabb.pos.y, p_aabb.pos.z+p_aabb.size.z), - Vector3(p_aabb.pos.x, p_aabb.pos.y, p_aabb.pos.z) + Vector3 vertices[8] = { + Vector3(p_aabb.pos.x + p_aabb.size.x, p_aabb.pos.y + p_aabb.size.y, p_aabb.pos.z + p_aabb.size.z), + Vector3(p_aabb.pos.x + p_aabb.size.x, p_aabb.pos.y + p_aabb.size.y, p_aabb.pos.z), + Vector3(p_aabb.pos.x + p_aabb.size.x, p_aabb.pos.y, p_aabb.pos.z + p_aabb.size.z), + Vector3(p_aabb.pos.x + p_aabb.size.x, p_aabb.pos.y, p_aabb.pos.z), + Vector3(p_aabb.pos.x, p_aabb.pos.y + p_aabb.size.y, p_aabb.pos.z + p_aabb.size.z), + Vector3(p_aabb.pos.x, p_aabb.pos.y + p_aabb.size.y, p_aabb.pos.z), + Vector3(p_aabb.pos.x, p_aabb.pos.y, p_aabb.pos.z + p_aabb.size.z), + Vector3(p_aabb.pos.x, p_aabb.pos.y, p_aabb.pos.z) }; - AABB ret; - ret.pos=xform_inv(vertices[0]); + ret.pos = xform_inv(vertices[0]); - for (int i=1;i<8;i++) { + for (int i = 1; i < 8; i++) { - ret.expand_to( xform_inv(vertices[i]) ); + ret.expand_to(xform_inv(vertices[i])); } return ret; - } #ifdef OPTIMIZED_TRANSFORM_IMPL_OVERRIDE @@ -250,16 +237,16 @@ struct OptimizedTransform { Transform transform; - _FORCE_INLINE_ void invert() {transform.invert(); } - _FORCE_INLINE_ void affine_invert() {transform.affine_invert(); } - _FORCE_INLINE_ Vector3 xform(const Vector3& p_vec) const { return transform.xform(p_vec); }; - _FORCE_INLINE_ Vector3 xform_inv(const Vector3& p_vec) const { return transform.xform_inv(p_vec); }; - _FORCE_INLINE_ OptimizedTransform operator*(const OptimizedTransform& p_ot ) const { return OptimizedTransform( transform * p_ot.transform ) ; } + _FORCE_INLINE_ void invert() { transform.invert(); } + _FORCE_INLINE_ void affine_invert() { transform.affine_invert(); } + _FORCE_INLINE_ Vector3 xform(const Vector3 &p_vec) const { return transform.xform(p_vec); }; + _FORCE_INLINE_ Vector3 xform_inv(const Vector3 &p_vec) const { return transform.xform_inv(p_vec); }; + _FORCE_INLINE_ OptimizedTransform operator*(const OptimizedTransform &p_ot) const { return OptimizedTransform(transform * p_ot.transform); } _FORCE_INLINE_ Transform get_transform() const { return transform; } - _FORCE_INLINE_ void set_transform(const Transform& p_transform) { transform=p_transform; } + _FORCE_INLINE_ void set_transform(const Transform &p_transform) { transform = p_transform; } - OptimizedTransform(const Transform& p_transform) { - transform=p_transform; + OptimizedTransform(const Transform &p_transform) { + transform = p_transform; } }; diff --git a/core/math/triangle_mesh.cpp b/core/math/triangle_mesh.cpp index 125727aa796..9046396f1b9 100644 --- a/core/math/triangle_mesh.cpp +++ b/core/math/triangle_mesh.cpp @@ -29,81 +29,73 @@ #include "triangle_mesh.h" #include "sort.h" +int TriangleMesh::_create_bvh(BVH *p_bvh, BVH **p_bb, int p_from, int p_size, int p_depth, int &max_depth, int &max_alloc) { - -int TriangleMesh::_create_bvh(BVH*p_bvh,BVH** p_bb,int p_from,int p_size,int p_depth,int&max_depth,int&max_alloc) { - - - if (p_depth>max_depth) { - max_depth=p_depth; + if (p_depth > max_depth) { + max_depth = p_depth; } - if (p_size==1) { + if (p_size == 1) { - - return p_bb[p_from]-p_bvh; - } else if (p_size==0) { + return p_bb[p_from] - p_bvh; + } else if (p_size == 0) { return -1; } - AABB aabb; - aabb=p_bb[p_from]->aabb; - for(int i=1;iaabb; + for (int i = 1; i < p_size; i++) { - aabb.merge_with(p_bb[p_from+i]->aabb); + aabb.merge_with(p_bb[p_from + i]->aabb); } - int li=aabb.get_longest_axis_index(); + int li = aabb.get_longest_axis_index(); - switch(li) { + switch (li) { case Vector3::AXIS_X: { - SortArray sort_x; - sort_x.nth_element(0,p_size,p_size/2,&p_bb[p_from]); + SortArray sort_x; + sort_x.nth_element(0, p_size, p_size / 2, &p_bb[p_from]); //sort_x.sort(&p_bb[p_from],p_size); } break; case Vector3::AXIS_Y: { - SortArray sort_y; - sort_y.nth_element(0,p_size,p_size/2,&p_bb[p_from]); + SortArray sort_y; + sort_y.nth_element(0, p_size, p_size / 2, &p_bb[p_from]); //sort_y.sort(&p_bb[p_from],p_size); } break; case Vector3::AXIS_Z: { - SortArray sort_z; - sort_z.nth_element(0,p_size,p_size/2,&p_bb[p_from]); + SortArray sort_z; + sort_z.nth_element(0, p_size, p_size / 2, &p_bb[p_from]); //sort_z.sort(&p_bb[p_from],p_size); } break; } + int left = _create_bvh(p_bvh, p_bb, p_from, p_size / 2, p_depth + 1, max_depth, max_alloc); + int right = _create_bvh(p_bvh, p_bb, p_from + p_size / 2, p_size - p_size / 2, p_depth + 1, max_depth, max_alloc); - int left = _create_bvh(p_bvh,p_bb,p_from,p_size/2,p_depth+1,max_depth,max_alloc); - int right = _create_bvh(p_bvh,p_bb,p_from+p_size/2,p_size-p_size/2,p_depth+1,max_depth,max_alloc); - - int index=max_alloc++; + int index = max_alloc++; BVH *_new = &p_bvh[index]; - _new->aabb=aabb; - _new->center=aabb.pos+aabb.size*0.5; - _new->face_index=-1; - _new->left=left; - _new->right=right; + _new->aabb = aabb; + _new->center = aabb.pos + aabb.size * 0.5; + _new->face_index = -1; + _new->left = left; + _new->right = right; return index; - } +void TriangleMesh::create(const DVector &p_faces) { -void TriangleMesh::create(const DVector& p_faces) { + valid = false; - valid=false; - - int fc=p_faces.size(); - ERR_FAIL_COND(!fc || ((fc%3) != 0)); - fc/=3; + int fc = p_faces.size(); + ERR_FAIL_COND(!fc || ((fc % 3) != 0)); + fc /= 3; triangles.resize(fc); - bvh.resize(fc*3); //will never be larger than this (todo make better) + bvh.resize(fc * 3); //will never be larger than this (todo make better) DVector::Write bw = bvh.write(); { @@ -114,148 +106,143 @@ void TriangleMesh::create(const DVector& p_faces) { DVector::Read r = p_faces.read(); DVector::Write w = triangles.write(); - Map db; + Map db; - for(int i=0;i::Element *E=db.find(vs); + int vidx = -1; + Vector3 vs = v[j].snapped(0.0001); + Map::Element *E = db.find(vs); if (E) { - vidx=E->get(); + vidx = E->get(); } else { - vidx=db.size(); - db[vs]=vidx; + vidx = db.size(); + db[vs] = vidx; } - f.indices[j]=vidx; - if (j==0) - bw[i].aabb.pos=vs; + f.indices[j] = vidx; + if (j == 0) + bw[i].aabb.pos = vs; else bw[i].aabb.expand_to(vs); } - f.normal=Face3(r[i*3+0],r[i*3+1],r[i*3+2]).get_plane().get_normal(); + f.normal = Face3(r[i * 3 + 0], r[i * 3 + 1], r[i * 3 + 2]).get_plane().get_normal(); - bw[i].left=-1; - bw[i].right=-1; - bw[i].face_index=i; - bw[i].center=bw[i].aabb.pos+bw[i].aabb.size*0.5; + bw[i].left = -1; + bw[i].right = -1; + bw[i].face_index = i; + bw[i].center = bw[i].aabb.pos + bw[i].aabb.size * 0.5; } vertices.resize(db.size()); DVector::Write vw = vertices.write(); - for (Map::Element *E=db.front();E;E=E->next()) { - vw[E->get()]=E->key(); + for (Map::Element *E = db.front(); E; E = E->next()) { + vw[E->get()] = E->key(); } - } - DVector bwptrs; + DVector bwptrs; bwptrs.resize(fc); - DVector::Write bwp = bwptrs.write(); - for(int i=0;i::Write bwp = bwptrs.write(); + for (int i = 0; i < fc; i++) { - bwp[i]=&bw[i]; + bwp[i] = &bw[i]; } - max_depth=0; - int max_alloc=fc; - int max=_create_bvh(bw.ptr(),bwp.ptr(),0,fc,1,max_depth,max_alloc); + max_depth = 0; + int max_alloc = fc; + int max = _create_bvh(bw.ptr(), bwp.ptr(), 0, fc, 1, max_depth, max_alloc); - bw=DVector::Write(); //clearup + bw = DVector::Write(); //clearup bvh.resize(max_alloc); //resize back - valid=true; - + valid = true; } +Vector3 TriangleMesh::get_area_normal(const AABB &p_aabb) const { -Vector3 TriangleMesh::get_area_normal(const AABB& p_aabb) const { - - uint32_t* stack = (uint32_t*)alloca(sizeof(int)*max_depth); + uint32_t *stack = (uint32_t *)alloca(sizeof(int) * max_depth); enum { - TEST_AABB_BIT=0, - VISIT_LEFT_BIT=1, - VISIT_RIGHT_BIT=2, - VISIT_DONE_BIT=3, - VISITED_BIT_SHIFT=29, - NODE_IDX_MASK=(1<::Read trianglesr = triangles.read(); - DVector::Read verticesr=vertices.read(); - DVector::Read bvhr=bvh.read(); + DVector::Read verticesr = vertices.read(); + DVector::Read bvhr = bvh.read(); - const Triangle *triangleptr=trianglesr.ptr(); - int pos=bvh.size()-1; + const Triangle *triangleptr = trianglesr.ptr(); + int pos = bvh.size() - 1; const BVH *bvhptr = bvhr.ptr(); - stack[0]=pos; - while(true) { + stack[0] = pos; + while (true) { - uint32_t node = stack[level]&NODE_IDX_MASK; - const BVH &b = bvhptr[ node ]; - bool done=false; + uint32_t node = stack[level] & NODE_IDX_MASK; + const BVH &b = bvhptr[node]; + bool done = false; - switch(stack[level]>>VISITED_BIT_SHIFT) { + switch (stack[level] >> VISITED_BIT_SHIFT) { case TEST_AABB_BIT: { - bool valid = b.aabb.intersects(p_aabb); if (!valid) { - stack[level]=(VISIT_DONE_BIT<=0) { + if (b.face_index >= 0) { - const Triangle &s=triangleptr[ b.face_index ]; - n+=s.normal; + const Triangle &s = triangleptr[b.face_index]; + n += s.normal; n_count++; - stack[level]=(VISIT_DONE_BIT<0) - n/=n_count; + if (n_count > 0) + n /= n_count; return n; - } +bool TriangleMesh::intersect_segment(const Vector3 &p_begin, const Vector3 &p_end, Vector3 &r_point, Vector3 &r_normal) const { -bool TriangleMesh::intersect_segment(const Vector3& p_begin,const Vector3& p_end,Vector3 &r_point, Vector3 &r_normal) const { - - - uint32_t* stack = (uint32_t*)alloca(sizeof(int)*max_depth); + uint32_t *stack = (uint32_t *)alloca(sizeof(int) * max_depth); enum { - TEST_AABB_BIT=0, - VISIT_LEFT_BIT=1, - VISIT_RIGHT_BIT=2, - VISIT_DONE_BIT=3, - VISITED_BIT_SHIFT=29, - NODE_IDX_MASK=(1<::Read trianglesr = triangles.read(); - DVector::Read verticesr=vertices.read(); - DVector::Read bvhr=bvh.read(); + DVector::Read verticesr = vertices.read(); + DVector::Read bvhr = bvh.read(); - const Triangle *triangleptr=trianglesr.ptr(); - const Vector3 *vertexptr=verticesr.ptr(); - int pos=bvh.size()-1; + const Triangle *triangleptr = trianglesr.ptr(); + const Vector3 *vertexptr = verticesr.ptr(); + int pos = bvh.size() - 1; const BVH *bvhptr = bvhr.ptr(); - stack[0]=pos; - while(true) { + stack[0] = pos; + while (true) { - uint32_t node = stack[level]&NODE_IDX_MASK; - const BVH &b = bvhptr[ node ]; - bool done=false; + uint32_t node = stack[level] & NODE_IDX_MASK; + const BVH &b = bvhptr[node]; + bool done = false; - switch(stack[level]>>VISITED_BIT_SHIFT) { + switch (stack[level] >> VISITED_BIT_SHIFT) { case TEST_AABB_BIT: { - - bool valid = b.aabb.intersects_segment(p_begin,p_end); -// bool valid = b.aabb.intersects(ray_aabb); + bool valid = b.aabb.intersects_segment(p_begin, p_end); + // bool valid = b.aabb.intersects(ray_aabb); if (!valid) { - stack[level]=(VISIT_DONE_BIT<=0) { - - const Triangle &s=triangleptr[ b.face_index ]; - Face3 f3(vertexptr[ s.indices[0] ],vertexptr[ s.indices[1] ],vertexptr[ s.indices[2] ]); + if (b.face_index >= 0) { + const Triangle &s = triangleptr[b.face_index]; + Face3 f3(vertexptr[s.indices[0]], vertexptr[s.indices[1]], vertexptr[s.indices[2]]); Vector3 res; - if (f3.intersects_segment(p_begin,p_end,&res)) { - + if (f3.intersects_segment(p_begin, p_end, &res)) { float nd = n.dot(res); - if (nd0) - r_normal=-r_normal; + if (n.dot(r_normal) > 0) + r_normal = -r_normal; } return inters; } +bool TriangleMesh::intersect_ray(const Vector3 &p_begin, const Vector3 &p_dir, Vector3 &r_point, Vector3 &r_normal) const { -bool TriangleMesh::intersect_ray(const Vector3& p_begin,const Vector3& p_dir,Vector3 &r_point, Vector3 &r_normal) const { - - - uint32_t* stack = (uint32_t*)alloca(sizeof(int)*max_depth); + uint32_t *stack = (uint32_t *)alloca(sizeof(int) * max_depth); enum { - TEST_AABB_BIT=0, - VISIT_LEFT_BIT=1, - VISIT_RIGHT_BIT=2, - VISIT_DONE_BIT=3, - VISITED_BIT_SHIFT=29, - NODE_IDX_MASK=(1<::Read trianglesr = triangles.read(); - DVector::Read verticesr=vertices.read(); - DVector::Read bvhr=bvh.read(); + DVector::Read verticesr = vertices.read(); + DVector::Read bvhr = bvh.read(); - const Triangle *triangleptr=trianglesr.ptr(); - const Vector3 *vertexptr=verticesr.ptr(); - int pos=bvh.size()-1; + const Triangle *triangleptr = trianglesr.ptr(); + const Vector3 *vertexptr = verticesr.ptr(); + int pos = bvh.size() - 1; const BVH *bvhptr = bvhr.ptr(); - stack[0]=pos; - while(true) { + stack[0] = pos; + while (true) { - uint32_t node = stack[level]&NODE_IDX_MASK; - const BVH &b = bvhptr[ node ]; - bool done=false; + uint32_t node = stack[level] & NODE_IDX_MASK; + const BVH &b = bvhptr[node]; + bool done = false; - switch(stack[level]>>VISITED_BIT_SHIFT) { + switch (stack[level] >> VISITED_BIT_SHIFT) { case TEST_AABB_BIT: { - - bool valid = b.aabb.intersects_ray(p_begin,p_dir); + bool valid = b.aabb.intersects_ray(p_begin, p_dir); if (!valid) { - stack[level]=(VISIT_DONE_BIT<=0) { - - const Triangle &s=triangleptr[ b.face_index ]; - Face3 f3(vertexptr[ s.indices[0] ],vertexptr[ s.indices[1] ],vertexptr[ s.indices[2] ]); + if (b.face_index >= 0) { + const Triangle &s = triangleptr[b.face_index]; + Face3 f3(vertexptr[s.indices[0]], vertexptr[s.indices[1]], vertexptr[s.indices[2]]); Vector3 res; - if (f3.intersects_ray(p_begin,p_dir,&res)) { - + if (f3.intersects_ray(p_begin, p_dir, &res)) { float nd = n.dot(res); - if (nd0) - r_normal=-r_normal; + if (n.dot(r_normal) > 0) + r_normal = -r_normal; } return inters; @@ -536,13 +502,13 @@ DVector TriangleMesh::get_faces() const { int ts = triangles.size(); faces.resize(triangles.size()); - DVector::Write w=faces.write(); + DVector::Write w = faces.write(); DVector::Read r = triangles.read(); DVector::Read rv = vertices.read(); - for(int i=0;i TriangleMesh::get_faces() const { TriangleMesh::TriangleMesh() { - valid=false; - max_depth=0; + valid = false; + max_depth = 0; } diff --git a/core/math/triangle_mesh.h b/core/math/triangle_mesh.h index a310f7e32b4..17417b4aef7 100644 --- a/core/math/triangle_mesh.h +++ b/core/math/triangle_mesh.h @@ -29,11 +29,11 @@ #ifndef TRIANGLE_MESH_H #define TRIANGLE_MESH_H -#include "reference.h" #include "face3.h" +#include "reference.h" class TriangleMesh : public Reference { - OBJ_TYPE( TriangleMesh, Reference); + OBJ_TYPE(TriangleMesh, Reference); struct Triangle { @@ -56,7 +56,7 @@ class TriangleMesh : public Reference { struct BVHCmpX { - bool operator()(const BVH* p_left, const BVH* p_right) const { + bool operator()(const BVH *p_left, const BVH *p_right) const { return p_left->center.x < p_right->center.x; } @@ -64,35 +64,33 @@ class TriangleMesh : public Reference { struct BVHCmpY { - bool operator()(const BVH* p_left, const BVH* p_right) const { + bool operator()(const BVH *p_left, const BVH *p_right) const { return p_left->center.y < p_right->center.y; } }; struct BVHCmpZ { - bool operator()(const BVH* p_left, const BVH* p_right) const { + bool operator()(const BVH *p_left, const BVH *p_right) const { return p_left->center.z < p_right->center.z; } }; - int _create_bvh(BVH*p_bvh,BVH** p_bb,int p_from,int p_size,int p_depth,int&max_depth,int&max_alloc); + int _create_bvh(BVH *p_bvh, BVH **p_bb, int p_from, int p_size, int p_depth, int &max_depth, int &max_alloc); DVector bvh; int max_depth; bool valid; public: - bool is_valid() const; - bool intersect_segment(const Vector3& p_begin,const Vector3& p_end,Vector3 &r_point, Vector3 &r_normal) const; - bool intersect_ray(const Vector3& p_begin,const Vector3& p_dir,Vector3 &r_point, Vector3 &r_normal) const; - Vector3 get_area_normal(const AABB& p_aabb) const; + bool intersect_segment(const Vector3 &p_begin, const Vector3 &p_end, Vector3 &r_point, Vector3 &r_normal) const; + bool intersect_ray(const Vector3 &p_begin, const Vector3 &p_dir, Vector3 &r_point, Vector3 &r_normal) const; + Vector3 get_area_normal(const AABB &p_aabb) const; DVector get_faces() const; - - void create(const DVector& p_faces); + void create(const DVector &p_faces); TriangleMesh(); }; diff --git a/core/math/triangulate.cpp b/core/math/triangulate.cpp index 5112077bcb3..8dadf9c6308 100644 --- a/core/math/triangulate.cpp +++ b/core/math/triangulate.cpp @@ -28,133 +28,139 @@ /*************************************************************************/ #include "triangulate.h" -float Triangulate::get_area(const Vector &contour) -{ +float Triangulate::get_area(const Vector &contour) { - int n = contour.size(); - const Vector2 *c=&contour[0]; + int n = contour.size(); + const Vector2 *c = &contour[0]; - float A=0.0f; + float A = 0.0f; - for(int p=n-1,q=0; q= 0.0f) && (bCROSScp >= 0.0f) && (cCROSSap >= 0.0f)); + return ((aCROSSbp >= 0.0f) && (bCROSScp >= 0.0f) && (cCROSSap >= 0.0f)); }; -bool Triangulate::snip(const Vector &p_contour,int u,int v,int w,int n,const Vector& V) -{ - int p; - float Ax, Ay, Bx, By, Cx, Cy, Px, Py; - const Vector2 *contour=&p_contour[0]; +bool Triangulate::snip(const Vector &p_contour, int u, int v, int w, int n, const Vector &V) { + int p; + float Ax, Ay, Bx, By, Cx, Cy, Px, Py; + const Vector2 *contour = &p_contour[0]; - Ax = contour[V[u]].x; - Ay = contour[V[u]].y; + Ax = contour[V[u]].x; + Ay = contour[V[u]].y; - Bx = contour[V[v]].x; - By = contour[V[v]].y; + Bx = contour[V[v]].x; + By = contour[V[v]].y; - Cx = contour[V[w]].x; - Cy = contour[V[w]].y; + Cx = contour[V[w]].x; + Cy = contour[V[w]].y; - if ( CMP_EPSILON > (((Bx-Ax)*(Cy-Ay)) - ((By-Ay)*(Cx-Ax))) ) return false; + if (CMP_EPSILON > (((Bx - Ax) * (Cy - Ay)) - ((By - Ay) * (Cx - Ax)))) return false; - for (p=0;p &contour,Vector &result) -{ - /* allocate and initialize list of Vertices in polygon */ +bool Triangulate::triangulate(const Vector &contour, Vector &result) { + /* allocate and initialize list of Vertices in polygon */ - int n = contour.size(); - if ( n < 3 ) return false; + int n = contour.size(); + if (n < 3) return false; + Vector V; + V.resize(n); - Vector V; - V.resize(n); + /* we want a counter-clockwise polygon in V */ - /* we want a counter-clockwise polygon in V */ + if (0.0f < get_area(contour)) + for (int v = 0; v < n; v++) + V[v] = v; + else + for (int v = 0; v < n; v++) + V[v] = (n - 1) - v; - if ( 0.0f < get_area(contour) ) - for (int v=0; v 2;) { + /* if we loop, it is probably a non-simple polygon */ + if (0 >= (count--)) { + //** Triangulate: ERROR - probable bad polygon! + return false; + } - for(int v=nv-1; nv>2; ) - { - /* if we loop, it is probably a non-simple polygon */ - if (0 >= (count--)) - { - //** Triangulate: ERROR - probable bad polygon! - return false; - } + /* three consecutive vertices in current polygon, */ + int u = v; + if (nv <= u) u = 0; /* previous */ + v = u + 1; + if (nv <= v) v = 0; /* new v */ + int w = v + 1; + if (nv <= w) w = 0; /* next */ - /* three consecutive vertices in current polygon, */ - int u = v ; if (nv <= u) u = 0; /* previous */ - v = u+1; if (nv <= v) v = 0; /* new v */ - int w = v+1; if (nv <= w) w = 0; /* next */ + if (snip(contour, u, v, w, nv, V)) { + int a, b, c, s, t; - if ( snip(contour,u,v,w,nv,V) ) - { - int a,b,c,s,t; + /* true names of the vertices */ + a = V[u]; + b = V[v]; + c = V[w]; - /* true names of the vertices */ - a = V[u]; b = V[v]; c = V[w]; + /* output Triangle */ + result.push_back(a); + result.push_back(b); + result.push_back(c); - /* output Triangle */ - result.push_back( a ); - result.push_back( b ); - result.push_back( c ); + /* remove v from remaining polygon */ + for (s = v, t = v + 1; t < nv; s++, t++) + V[s] = V[t]; + nv--; - /* remove v from remaining polygon */ - for(s=v,t=v+1;t &contour, Vector &result); + static bool triangulate(const Vector &contour, Vector &result); // compute area of a contour/polygon - static float get_area(const Vector< Vector2 > &contour); + static float get_area(const Vector &contour); // decide if point Px/Py is inside triangle defined by // (Ax,Ay) (Bx,By) (Cx,Cy) static bool is_inside_triangle(float Ax, float Ay, - float Bx, float By, - float Cx, float Cy, - float Px, float Py); - + float Bx, float By, + float Cx, float Cy, + float Px, float Py); private: - static bool snip(const Vector &p_contour,int u,int v,int w,int n,const Vector& V); - + static bool snip(const Vector &p_contour, int u, int v, int w, int n, const Vector &V); }; - - #endif diff --git a/core/math/vector3.cpp b/core/math/vector3.cpp index db96dda4618..56034ab49f5 100644 --- a/core/math/vector3.cpp +++ b/core/math/vector3.cpp @@ -29,27 +29,25 @@ #include "vector3.h" #include "matrix3.h" +void Vector3::rotate(const Vector3 &p_axis, float p_phi) { -void Vector3::rotate(const Vector3& p_axis,float p_phi) { - - *this=Matrix3(p_axis,p_phi).xform(*this); + *this = Matrix3(p_axis, p_phi).xform(*this); } -Vector3 Vector3::rotated(const Vector3& p_axis,float p_phi) const { +Vector3 Vector3::rotated(const Vector3 &p_axis, float p_phi) const { Vector3 r = *this; - r.rotate(p_axis,p_phi); + r.rotate(p_axis, p_phi); return r; } -void Vector3::set_axis(int p_axis,real_t p_value) { - ERR_FAIL_INDEX(p_axis,3); - coord[p_axis]=p_value; - +void Vector3::set_axis(int p_axis, real_t p_value) { + ERR_FAIL_INDEX(p_axis, 3); + coord[p_axis] = p_value; } real_t Vector3::get_axis(int p_axis) const { - ERR_FAIL_INDEX_V(p_axis,3,0); + ERR_FAIL_INDEX_V(p_axis, 3, 0); return operator[](p_axis); } @@ -62,31 +60,28 @@ int Vector3::max_axis() const { return x < y ? (y < z ? 2 : 1) : (x < z ? 2 : 0); } - void Vector3::snap(float p_val) { - x+=p_val/2.0; - x-=Math::fmod(x,p_val); - y+=p_val/2.0; - y-=Math::fmod(y,p_val); - z+=p_val/2.0; - z-=Math::fmod(z,p_val); - + x += p_val / 2.0; + x -= Math::fmod(x, p_val); + y += p_val / 2.0; + y -= Math::fmod(y, p_val); + z += p_val / 2.0; + z -= Math::fmod(z, p_val); } Vector3 Vector3::snapped(float p_val) const { - Vector3 v=*this; + Vector3 v = *this; v.snap(p_val); return v; } +Vector3 Vector3::cubic_interpolaten(const Vector3 &p_b, const Vector3 &p_pre_a, const Vector3 &p_post_b, float p_t) const { -Vector3 Vector3::cubic_interpolaten(const Vector3& p_b,const Vector3& p_pre_a, const Vector3& p_post_b,float p_t) const { - - Vector3 p0=p_pre_a; - Vector3 p1=*this; - Vector3 p2=p_b; - Vector3 p3=p_post_b; + Vector3 p0 = p_pre_a; + Vector3 p1 = *this; + Vector3 p2 = p_b; + Vector3 p3 = p_post_b; { //normalize @@ -95,44 +90,41 @@ Vector3 Vector3::cubic_interpolaten(const Vector3& p_b,const Vector3& p_pre_a, c float bc = p1.distance_to(p2); float cd = p2.distance_to(p3); - if (ab>0) - p0 = p1+(p0-p1)*(bc/ab); - if (cd>0) - p3 = p2+(p3-p2)*(bc/cd); + if (ab > 0) + p0 = p1 + (p0 - p1) * (bc / ab); + if (cd > 0) + p3 = p2 + (p3 - p2) * (bc / cd); } - float t = p_t; float t2 = t * t; float t3 = t2 * t; Vector3 out; - out = 0.5f * ( ( p1 * 2.0f) + - ( -p0 + p2 ) * t + - ( 2.0f * p0 - 5.0f * p1 + 4 * p2 - p3 ) * t2 + - ( -p0 + 3.0f * p1 - 3.0f * p2 + p3 ) * t3 ); + out = 0.5f * ((p1 * 2.0f) + + (-p0 + p2) * t + + (2.0f * p0 - 5.0f * p1 + 4 * p2 - p3) * t2 + + (-p0 + 3.0f * p1 - 3.0f * p2 + p3) * t3); return out; - } -Vector3 Vector3::cubic_interpolate(const Vector3& p_b,const Vector3& p_pre_a, const Vector3& p_post_b,float p_t) const { +Vector3 Vector3::cubic_interpolate(const Vector3 &p_b, const Vector3 &p_pre_a, const Vector3 &p_post_b, float p_t) const { - Vector3 p0=p_pre_a; - Vector3 p1=*this; - Vector3 p2=p_b; - Vector3 p3=p_post_b; + Vector3 p0 = p_pre_a; + Vector3 p1 = *this; + Vector3 p2 = p_b; + Vector3 p3 = p_post_b; float t = p_t; float t2 = t * t; float t3 = t2 * t; Vector3 out; - out = 0.5f * ( ( p1 * 2.0f) + - ( -p0 + p2 ) * t + - ( 2.0f * p0 - 5.0f * p1 + 4 * p2 - p3 ) * t2 + - ( -p0 + 3.0f * p1 - 3.0f * p2 + p3 ) * t3 ); + out = 0.5f * ((p1 * 2.0f) + + (-p0 + p2) * t + + (2.0f * p0 - 5.0f * p1 + 4 * p2 - p3) * t2 + + (-p0 + 3.0f * p1 - 3.0f * p2 + p3) * t3); return out; - } #if 0 @@ -179,8 +171,8 @@ Vector3 Vector3::cubic_interpolate(const Vector3& p_b,const Vector3& p_pre_a, co ( -p0.z + 3.0f * p1.z - 3.0f * p2.z + p3.z ) * t3 ); return out; } -# endif +#endif Vector3::operator String() const { - return (rtos(x)+", "+rtos(y)+", "+rtos(z)); + return (rtos(x) + ", " + rtos(y) + ", " + rtos(z)); } diff --git a/core/math/vector3.h b/core/math/vector3.h index 3f451b0ab70..b02fa599120 100644 --- a/core/math/vector3.h +++ b/core/math/vector3.h @@ -29,12 +29,11 @@ #ifndef VECTOR3_H #define VECTOR3_H -#include "typedefs.h" #include "math_defs.h" #include "math_funcs.h" +#include "typedefs.h" #include "ustring.h" - struct Vector3 { enum Axis { @@ -53,17 +52,17 @@ struct Vector3 { real_t coord[3]; }; - _FORCE_INLINE_ const real_t& operator[](int p_axis) const { + _FORCE_INLINE_ const real_t &operator[](int p_axis) const { return coord[p_axis]; } - _FORCE_INLINE_ real_t& operator[](int p_axis) { + _FORCE_INLINE_ real_t &operator[](int p_axis) { return coord[p_axis]; } - void set_axis(int p_axis,real_t p_value); + void set_axis(int p_axis, real_t p_value); real_t get_axis(int p_axis) const; int min_axis() const; @@ -81,61 +80,61 @@ struct Vector3 { void snap(float p_val); Vector3 snapped(float p_val) const; - void rotate(const Vector3& p_axis,float p_phi); - Vector3 rotated(const Vector3& p_axis,float p_phi) const; + void rotate(const Vector3 &p_axis, float p_phi); + Vector3 rotated(const Vector3 &p_axis, float p_phi) const; /* Static Methods between 2 vector3s */ - _FORCE_INLINE_ Vector3 linear_interpolate(const Vector3& p_b,float p_t) const; - Vector3 cubic_interpolate(const Vector3& p_b,const Vector3& p_pre_a, const Vector3& p_post_b,float p_t) const; - Vector3 cubic_interpolaten(const Vector3& p_b,const Vector3& p_pre_a, const Vector3& p_post_b,float p_t) const; + _FORCE_INLINE_ Vector3 linear_interpolate(const Vector3 &p_b, float p_t) const; + Vector3 cubic_interpolate(const Vector3 &p_b, const Vector3 &p_pre_a, const Vector3 &p_post_b, float p_t) const; + Vector3 cubic_interpolaten(const Vector3 &p_b, const Vector3 &p_pre_a, const Vector3 &p_post_b, float p_t) const; - _FORCE_INLINE_ Vector3 cross(const Vector3& p_b) const; - _FORCE_INLINE_ real_t dot(const Vector3& p_b) const; + _FORCE_INLINE_ Vector3 cross(const Vector3 &p_b) const; + _FORCE_INLINE_ real_t dot(const Vector3 &p_b) const; _FORCE_INLINE_ Vector3 abs() const; _FORCE_INLINE_ Vector3 floor() const; _FORCE_INLINE_ Vector3 ceil() const; - _FORCE_INLINE_ real_t distance_to(const Vector3& p_b) const; - _FORCE_INLINE_ real_t distance_squared_to(const Vector3& p_b) const; + _FORCE_INLINE_ real_t distance_to(const Vector3 &p_b) const; + _FORCE_INLINE_ real_t distance_squared_to(const Vector3 &p_b) const; - _FORCE_INLINE_ real_t angle_to(const Vector3& p_b) const; - - - _FORCE_INLINE_ Vector3 slide(const Vector3& p_vec) const; - _FORCE_INLINE_ Vector3 reflect(const Vector3& p_vec) const; + _FORCE_INLINE_ real_t angle_to(const Vector3 &p_b) const; + _FORCE_INLINE_ Vector3 slide(const Vector3 &p_vec) const; + _FORCE_INLINE_ Vector3 reflect(const Vector3 &p_vec) const; /* Operators */ - _FORCE_INLINE_ Vector3& operator+=(const Vector3& p_v); - _FORCE_INLINE_ Vector3 operator+(const Vector3& p_v) const; - _FORCE_INLINE_ Vector3& operator-=(const Vector3& p_v); - _FORCE_INLINE_ Vector3 operator-(const Vector3& p_v) const; - _FORCE_INLINE_ Vector3& operator*=(const Vector3& p_v); - _FORCE_INLINE_ Vector3 operator*(const Vector3& p_v) const; - _FORCE_INLINE_ Vector3& operator/=(const Vector3& p_v); - _FORCE_INLINE_ Vector3 operator/(const Vector3& p_v) const; + _FORCE_INLINE_ Vector3 &operator+=(const Vector3 &p_v); + _FORCE_INLINE_ Vector3 operator+(const Vector3 &p_v) const; + _FORCE_INLINE_ Vector3 &operator-=(const Vector3 &p_v); + _FORCE_INLINE_ Vector3 operator-(const Vector3 &p_v) const; + _FORCE_INLINE_ Vector3 &operator*=(const Vector3 &p_v); + _FORCE_INLINE_ Vector3 operator*(const Vector3 &p_v) const; + _FORCE_INLINE_ Vector3 &operator/=(const Vector3 &p_v); + _FORCE_INLINE_ Vector3 operator/(const Vector3 &p_v) const; - - _FORCE_INLINE_ Vector3& operator*=(real_t p_scalar); + _FORCE_INLINE_ Vector3 &operator*=(real_t p_scalar); _FORCE_INLINE_ Vector3 operator*(real_t p_scalar) const; - _FORCE_INLINE_ Vector3& operator/=(real_t p_scalar); + _FORCE_INLINE_ Vector3 &operator/=(real_t p_scalar); _FORCE_INLINE_ Vector3 operator/(real_t p_scalar) const; _FORCE_INLINE_ Vector3 operator-() const; - _FORCE_INLINE_ bool operator==(const Vector3& p_v) const; - _FORCE_INLINE_ bool operator!=(const Vector3& p_v) const; - _FORCE_INLINE_ bool operator<(const Vector3& p_v) const; - _FORCE_INLINE_ bool operator<=(const Vector3& p_v) const; + _FORCE_INLINE_ bool operator==(const Vector3 &p_v) const; + _FORCE_INLINE_ bool operator!=(const Vector3 &p_v) const; + _FORCE_INLINE_ bool operator<(const Vector3 &p_v) const; + _FORCE_INLINE_ bool operator<=(const Vector3 &p_v) const; operator String() const; - _FORCE_INLINE_ Vector3() { x=y=z=0; } - _FORCE_INLINE_ Vector3(real_t p_x,real_t p_y,real_t p_z) { x=p_x; y=p_y; z=p_z; } - + _FORCE_INLINE_ Vector3() { x = y = z = 0; } + _FORCE_INLINE_ Vector3(real_t p_x, real_t p_y, real_t p_z) { + x = p_x; + y = p_y; + z = p_z; + } }; #ifdef VECTOR3_IMPL_OVERRIDE @@ -144,246 +143,244 @@ struct Vector3 { #else -Vector3 Vector3::cross(const Vector3& p_b) const { +Vector3 Vector3::cross(const Vector3 &p_b) const { - Vector3 ret ( - (y * p_b.z) - (z * p_b.y), - (z * p_b.x) - (x * p_b.z), - (x * p_b.y) - (y * p_b.x) - ); + Vector3 ret( + (y * p_b.z) - (z * p_b.y), + (z * p_b.x) - (x * p_b.z), + (x * p_b.y) - (y * p_b.x)); return ret; } -real_t Vector3::dot(const Vector3& p_b) const { +real_t Vector3::dot(const Vector3 &p_b) const { - return x*p_b.x + y*p_b.y + z*p_b.z; + return x * p_b.x + y * p_b.y + z * p_b.z; } Vector3 Vector3::abs() const { - return Vector3( Math::abs(x), Math::abs(y), Math::abs(z) ); + return Vector3(Math::abs(x), Math::abs(y), Math::abs(z)); } Vector3 Vector3::floor() const { - return Vector3( Math::floor(x), Math::floor(y), Math::floor(z) ); + return Vector3(Math::floor(x), Math::floor(y), Math::floor(z)); } Vector3 Vector3::ceil() const { - return Vector3( Math::ceil(x), Math::ceil(y), Math::ceil(z) ); + return Vector3(Math::ceil(x), Math::ceil(y), Math::ceil(z)); } -Vector3 Vector3::linear_interpolate(const Vector3& p_b,float p_t) const { +Vector3 Vector3::linear_interpolate(const Vector3 &p_b, float p_t) const { return Vector3( - x+(p_t * (p_b.x-x)), - y+(p_t * (p_b.y-y)), - z+(p_t * (p_b.z-z)) - ); + x + (p_t * (p_b.x - x)), + y + (p_t * (p_b.y - y)), + z + (p_t * (p_b.z - z))); } -real_t Vector3::distance_to(const Vector3& p_b) const { +real_t Vector3::distance_to(const Vector3 &p_b) const { - return (p_b-*this).length(); + return (p_b - *this).length(); } -real_t Vector3::distance_squared_to(const Vector3& p_b) const { +real_t Vector3::distance_squared_to(const Vector3 &p_b) const { - return (p_b-*this).length_squared(); + return (p_b - *this).length_squared(); } -real_t Vector3::angle_to(const Vector3& p_b) const { +real_t Vector3::angle_to(const Vector3 &p_b) const { return Math::acos(this->dot(p_b) / Math::sqrt(this->length_squared() * p_b.length_squared())); } /* Operators */ -Vector3& Vector3::operator+=(const Vector3& p_v) { +Vector3 &Vector3::operator+=(const Vector3 &p_v) { - x+=p_v.x; - y+=p_v.y; - z+=p_v.z; + x += p_v.x; + y += p_v.y; + z += p_v.z; return *this; } -Vector3 Vector3::operator+(const Vector3& p_v) const { +Vector3 Vector3::operator+(const Vector3 &p_v) const { - return Vector3(x+p_v.x, y+p_v.y, z+ p_v.z); + return Vector3(x + p_v.x, y + p_v.y, z + p_v.z); } -Vector3& Vector3::operator-=(const Vector3& p_v) { +Vector3 &Vector3::operator-=(const Vector3 &p_v) { - x-=p_v.x; - y-=p_v.y; - z-=p_v.z; + x -= p_v.x; + y -= p_v.y; + z -= p_v.z; return *this; } -Vector3 Vector3::operator-(const Vector3& p_v) const { +Vector3 Vector3::operator-(const Vector3 &p_v) const { - return Vector3(x-p_v.x, y-p_v.y, z- p_v.z); + return Vector3(x - p_v.x, y - p_v.y, z - p_v.z); } -Vector3& Vector3::operator*=(const Vector3& p_v) { +Vector3 &Vector3::operator*=(const Vector3 &p_v) { - x*=p_v.x; - y*=p_v.y; - z*=p_v.z; + x *= p_v.x; + y *= p_v.y; + z *= p_v.z; return *this; } -Vector3 Vector3::operator*(const Vector3& p_v) const { +Vector3 Vector3::operator*(const Vector3 &p_v) const { - return Vector3(x*p_v.x, y*p_v.y, z* p_v.z); + return Vector3(x * p_v.x, y * p_v.y, z * p_v.z); } -Vector3& Vector3::operator/=(const Vector3& p_v) { +Vector3 &Vector3::operator/=(const Vector3 &p_v) { - x/=p_v.x; - y/=p_v.y; - z/=p_v.z; + x /= p_v.x; + y /= p_v.y; + z /= p_v.z; return *this; } -Vector3 Vector3::operator/(const Vector3& p_v) const { +Vector3 Vector3::operator/(const Vector3 &p_v) const { - return Vector3(x/p_v.x, y/p_v.y, z/ p_v.z); + return Vector3(x / p_v.x, y / p_v.y, z / p_v.z); } -Vector3& Vector3::operator*=(real_t p_scalar) { +Vector3 &Vector3::operator*=(real_t p_scalar) { - x*=p_scalar; - y*=p_scalar; - z*=p_scalar; + x *= p_scalar; + y *= p_scalar; + z *= p_scalar; return *this; } -_FORCE_INLINE_ Vector3 operator*(real_t p_scalar, const Vector3& p_vec) { +_FORCE_INLINE_ Vector3 operator*(real_t p_scalar, const Vector3 &p_vec) { return p_vec * p_scalar; } Vector3 Vector3::operator*(real_t p_scalar) const { - return Vector3( x*p_scalar, y*p_scalar, z*p_scalar); + return Vector3(x * p_scalar, y * p_scalar, z * p_scalar); } -Vector3& Vector3::operator/=(real_t p_scalar) { +Vector3 &Vector3::operator/=(real_t p_scalar) { - x/=p_scalar; - y/=p_scalar; - z/=p_scalar; + x /= p_scalar; + y /= p_scalar; + z /= p_scalar; return *this; } Vector3 Vector3::operator/(real_t p_scalar) const { - return Vector3( x/p_scalar, y/p_scalar, z/p_scalar); + return Vector3(x / p_scalar, y / p_scalar, z / p_scalar); } Vector3 Vector3::operator-() const { - return Vector3( -x, -y, -z ); + return Vector3(-x, -y, -z); } -bool Vector3::operator==(const Vector3& p_v) const { +bool Vector3::operator==(const Vector3 &p_v) const { - return (x==p_v.x && y==p_v.y && z==p_v.z); + return (x == p_v.x && y == p_v.y && z == p_v.z); } -bool Vector3::operator!=(const Vector3& p_v) const { +bool Vector3::operator!=(const Vector3 &p_v) const { - return (x!=p_v.x || y!=p_v.y || z!=p_v.z); + return (x != p_v.x || y != p_v.y || z != p_v.z); } -bool Vector3::operator<(const Vector3& p_v) const { +bool Vector3::operator<(const Vector3 &p_v) const { - if (x==p_v.x) { - if (y==p_v.y) - return zdot(p_vec); } -Vector3 Vector3::reflect(const Vector3& p_vec) const { +Vector3 Vector3::reflect(const Vector3 &p_vec) const { return p_vec - *this * this->dot(p_vec) * 2.0; } diff --git a/core/message_queue.cpp b/core/message_queue.cpp index d17321f0266..fee162e30e0 100644 --- a/core/message_queue.cpp +++ b/core/message_queue.cpp @@ -29,95 +29,90 @@ #include "message_queue.h" #include "globals.h" #include "script_language.h" -MessageQueue *MessageQueue::singleton=NULL; +MessageQueue *MessageQueue::singleton = NULL; MessageQueue *MessageQueue::get_singleton() { return singleton; } -Error MessageQueue::push_call(ObjectID p_id,const StringName& p_method,const Variant** p_args,int p_argcount,bool p_show_error) { +Error MessageQueue::push_call(ObjectID p_id, const StringName &p_method, const Variant **p_args, int p_argcount, bool p_show_error) { _THREAD_SAFE_METHOD_ - int room_needed=sizeof(Message)+sizeof(Variant)*p_argcount; + int room_needed = sizeof(Message) + sizeof(Variant) * p_argcount; - if ((buffer_end+room_needed) >= buffer_size) { + if ((buffer_end + room_needed) >= buffer_size) { String type; if (ObjectDB::get_instance(p_id)) - type=ObjectDB::get_instance(p_id)->get_type(); - print_line("failed method: "+type+":"+p_method+" target ID: "+itos(p_id)); + type = ObjectDB::get_instance(p_id)->get_type(); + print_line("failed method: " + type + ":" + p_method + " target ID: " + itos(p_id)); statistics(); - } - ERR_FAIL_COND_V( (buffer_end+room_needed) >= buffer_size , ERR_OUT_OF_MEMORY ); - Message * msg = memnew_placement( &buffer[ buffer_end ], Message ); - msg->args=p_argcount; - msg->instance_ID=p_id; - msg->target=p_method; - msg->type=TYPE_CALL; + ERR_FAIL_COND_V((buffer_end + room_needed) >= buffer_size, ERR_OUT_OF_MEMORY); + Message *msg = memnew_placement(&buffer[buffer_end], Message); + msg->args = p_argcount; + msg->instance_ID = p_id; + msg->target = p_method; + msg->type = TYPE_CALL; if (p_show_error) - msg->type|=FLAG_SHOW_ERROR; + msg->type |= FLAG_SHOW_ERROR; - buffer_end+=sizeof(Message); + buffer_end += sizeof(Message); - for(int i=0;iget_type()==Variant::NIL) + for (int i = 0; i < VARIANT_ARG_MAX; i++) { + if (argptr[i]->get_type() == Variant::NIL) break; argc++; } - return push_call(p_id,p_method,argptr,argc,false); - + return push_call(p_id, p_method, argptr, argc, false); } -Error MessageQueue::push_set(ObjectID p_id, const StringName& p_prop, const Variant& p_value) { +Error MessageQueue::push_set(ObjectID p_id, const StringName &p_prop, const Variant &p_value) { _THREAD_SAFE_METHOD_ - uint8_t room_needed=sizeof(Message)+sizeof(Variant); + uint8_t room_needed = sizeof(Message) + sizeof(Variant); - if ((buffer_end+room_needed) >= buffer_size) { + if ((buffer_end + room_needed) >= buffer_size) { String type; if (ObjectDB::get_instance(p_id)) - type=ObjectDB::get_instance(p_id)->get_type(); - print_line("failed set: "+type+":"+p_prop+" target ID: "+itos(p_id)); + type = ObjectDB::get_instance(p_id)->get_type(); + print_line("failed set: " + type + ":" + p_prop + " target ID: " + itos(p_id)); statistics(); - } - ERR_FAIL_COND_V( (buffer_end+room_needed) >= buffer_size , ERR_OUT_OF_MEMORY ); + ERR_FAIL_COND_V((buffer_end + room_needed) >= buffer_size, ERR_OUT_OF_MEMORY); - Message * msg = memnew_placement( &buffer[ buffer_end ], Message ); - msg->args=1; - msg->instance_ID=p_id; - msg->target=p_prop; - msg->type=TYPE_SET; + Message *msg = memnew_placement(&buffer[buffer_end], Message); + msg->args = 1; + msg->instance_ID = p_id; + msg->target = p_prop; + msg->type = TYPE_SET; - buffer_end+=sizeof(Message); - - Variant * v = memnew_placement( &buffer[ buffer_end ], Variant ); - buffer_end+=sizeof(Variant); - *v=p_value; + buffer_end += sizeof(Message); + Variant *v = memnew_placement(&buffer[buffer_end], Variant); + buffer_end += sizeof(Variant); + *v = p_value; return OK; } @@ -126,73 +121,66 @@ Error MessageQueue::push_notification(ObjectID p_id, int p_notification) { _THREAD_SAFE_METHOD_ - ERR_FAIL_COND_V(p_notification<0, ERR_INVALID_PARAMETER ); + ERR_FAIL_COND_V(p_notification < 0, ERR_INVALID_PARAMETER); - uint8_t room_needed=sizeof(Message); + uint8_t room_needed = sizeof(Message); - if ((buffer_end+room_needed) >= buffer_size) { + if ((buffer_end + room_needed) >= buffer_size) { String type; if (ObjectDB::get_instance(p_id)) - type=ObjectDB::get_instance(p_id)->get_type(); - print_line("failed notification: "+itos(p_notification)+" target ID: "+itos(p_id)); + type = ObjectDB::get_instance(p_id)->get_type(); + print_line("failed notification: " + itos(p_notification) + " target ID: " + itos(p_id)); statistics(); - } + ERR_FAIL_COND_V((buffer_end + room_needed) >= buffer_size, ERR_OUT_OF_MEMORY); + Message *msg = memnew_placement(&buffer[buffer_end], Message); - - - ERR_FAIL_COND_V( (buffer_end+room_needed) >= buffer_size , ERR_OUT_OF_MEMORY ); - Message * msg = memnew_placement( &buffer[ buffer_end ], Message ); - - msg->type=TYPE_NOTIFICATION; - msg->instance_ID=p_id; + msg->type = TYPE_NOTIFICATION; + msg->instance_ID = p_id; //msg->target; - msg->notification=p_notification; - - buffer_end+=sizeof(Message); + msg->notification = p_notification; + buffer_end += sizeof(Message); return OK; } -Error MessageQueue::push_call(Object *p_object, const StringName& p_method, VARIANT_ARG_DECLARE) { +Error MessageQueue::push_call(Object *p_object, const StringName &p_method, VARIANT_ARG_DECLARE) { - return push_call(p_object->get_instance_ID(),p_method,VARIANT_ARG_PASS); + return push_call(p_object->get_instance_ID(), p_method, VARIANT_ARG_PASS); } Error MessageQueue::push_notification(Object *p_object, int p_notification) { - return push_notification(p_object->get_instance_ID(),p_notification); + return push_notification(p_object->get_instance_ID(), p_notification); } -Error MessageQueue::push_set(Object *p_object, const StringName& p_prop, const Variant& p_value) { +Error MessageQueue::push_set(Object *p_object, const StringName &p_prop, const Variant &p_value) { - return push_set(p_object->get_instance_ID(),p_prop,p_value); + return push_set(p_object->get_instance_ID(), p_prop, p_value); } - void MessageQueue::statistics() { - Map set_count; - Map notify_count; - Map call_count; - int null_count=0; + Map set_count; + Map notify_count; + Map call_count; + int null_count = 0; - uint32_t read_pos=0; - while (read_pos < buffer_end ) { - Message *message = (Message*)&buffer[ read_pos ]; + uint32_t read_pos = 0; + while (read_pos < buffer_end) { + Message *message = (Message *)&buffer[read_pos]; Object *target = ObjectDB::get_instance(message->instance_ID); - if (target!=NULL) { + if (target != NULL) { - - switch(message->type&FLAG_MASK) { + switch (message->type & FLAG_MASK) { case TYPE_CALL: { if (!call_count.has(message->target)) - call_count[message->target]=0; + call_count[message->target] = 0; call_count[message->target]++; @@ -200,7 +188,7 @@ void MessageQueue::statistics() { case TYPE_NOTIFICATION: { if (!notify_count.has(message->notification)) - notify_count[message->notification]=0; + notify_count[message->notification] = 0; notify_count[message->notification]++; @@ -208,12 +196,11 @@ void MessageQueue::statistics() { case TYPE_SET: { if (!set_count.has(message->target)) - set_count[message->target]=0; + set_count[message->target] = 0; set_count[message->target]++; } break; - } //object was deleted @@ -224,31 +211,28 @@ void MessageQueue::statistics() { null_count++; } - - read_pos+=sizeof(Message); - if ((message->type&FLAG_MASK)!=TYPE_NOTIFICATION) - read_pos+=sizeof(Variant)*message->args; + read_pos += sizeof(Message); + if ((message->type & FLAG_MASK) != TYPE_NOTIFICATION) + read_pos += sizeof(Variant) * message->args; } + print_line("TOTAL BYTES: " + itos(buffer_end)); + print_line("NULL count: " + itos(null_count)); - print_line("TOTAL BYTES: "+itos(buffer_end)); - print_line("NULL count: "+itos(null_count)); + for (Map::Element *E = set_count.front(); E; E = E->next()) { - for(Map::Element *E=set_count.front();E;E=E->next()) { - - print_line("SET "+E->key()+": "+itos(E->get())); + print_line("SET " + E->key() + ": " + itos(E->get())); } - for(Map::Element *E=call_count.front();E;E=E->next()) { + for (Map::Element *E = call_count.front(); E; E = E->next()) { - print_line("CALL "+E->key()+": "+itos(E->get())); + print_line("CALL " + E->key() + ": " + itos(E->get())); } - for(Map::Element *E=notify_count.front();E;E=E->next()) { + for (Map::Element *E = notify_count.front(); E; E = E->next()) { - print_line("NOTIFY "+itos(E->key())+": "+itos(E->get())); + print_line("NOTIFY " + itos(E->key()) + ": " + itos(E->get())); } - } bool MessageQueue::print() { @@ -297,62 +281,58 @@ int MessageQueue::get_max_buffer_usage() const { return buffer_max_used; } +void MessageQueue::_call_function(Object *p_target, const StringName &p_func, const Variant *p_args, int p_argcount, bool p_show_error) { -void MessageQueue::_call_function(Object* p_target, const StringName& p_func, const Variant *p_args, int p_argcount,bool p_show_error) { - - const Variant **argptrs=NULL; + const Variant **argptrs = NULL; if (p_argcount) { - argptrs = (const Variant**)alloca(sizeof(Variant*)*p_argcount); - for(int i=0;icall(p_func,argptrs,p_argcount,ce); - if (p_show_error && ce.error!=Variant::CallError::CALL_OK) { - - ERR_PRINTS("Error calling deferred method: "+Variant::get_call_error_text(p_target,p_func,argptrs,p_argcount,ce)); + p_target->call(p_func, argptrs, p_argcount, ce); + if (p_show_error && ce.error != Variant::CallError::CALL_OK) { + ERR_PRINTS("Error calling deferred method: " + Variant::get_call_error_text(p_target, p_func, argptrs, p_argcount, ce)); } } void MessageQueue::flush() { - if (buffer_end > buffer_max_used) { - buffer_max_used=buffer_end; + buffer_max_used = buffer_end; //statistics(); } - uint32_t read_pos=0; + uint32_t read_pos = 0; //using reverse locking strategy _THREAD_SAFE_LOCK_ - while (read_posinstance_ID); - if (target!=NULL) { + if (target != NULL) { - switch(message->type&FLAG_MASK) { + switch (message->type & FLAG_MASK) { case TYPE_CALL: { - Variant *args= (Variant*)(message+1); + Variant *args = (Variant *)(message + 1); // messages don't expect a return value + _call_function(target, message->target, args, message->args, message->type & FLAG_SHOW_ERROR); - _call_function(target,message->target,args,message->args,message->type&FLAG_SHOW_ERROR); - - for(int i=0;iargs;i++) { + for (int i = 0; i < message->args; i++) { args[i].~Variant(); } @@ -365,65 +345,60 @@ void MessageQueue::flush() { } break; case TYPE_SET: { - Variant *arg= (Variant*)(message+1); + Variant *arg = (Variant *)(message + 1); // messages don't expect a return value - target->set(message->target,*arg); + target->set(message->target, *arg); arg->~Variant(); } break; } - } uint32_t advance = sizeof(Message); - if ((message->type&FLAG_MASK)!=TYPE_NOTIFICATION) - advance+=sizeof(Variant)*message->args; + if ((message->type & FLAG_MASK) != TYPE_NOTIFICATION) + advance += sizeof(Variant) * message->args; message->~Message(); _THREAD_SAFE_LOCK_ - read_pos+=advance; - + read_pos += advance; } - - buffer_end=0; // reset buffer + buffer_end = 0; // reset buffer _THREAD_SAFE_UNLOCK_ - } MessageQueue::MessageQueue() { - ERR_FAIL_COND(singleton!=NULL); - singleton=this; + ERR_FAIL_COND(singleton != NULL); + singleton = this; - buffer_end=0; - buffer_max_used=0; - buffer_size=GLOBAL_DEF( "core/message_queue_size_kb", DEFAULT_QUEUE_SIZE_KB ); - buffer_size*=1024; - buffer = memnew_arr( uint8_t, buffer_size ); + buffer_end = 0; + buffer_max_used = 0; + buffer_size = GLOBAL_DEF("core/message_queue_size_kb", DEFAULT_QUEUE_SIZE_KB); + buffer_size *= 1024; + buffer = memnew_arr(uint8_t, buffer_size); } - MessageQueue::~MessageQueue() { - uint32_t read_pos=0; + uint32_t read_pos = 0; - while (read_pos < buffer_end ) { + while (read_pos < buffer_end) { - Message *message = (Message*)&buffer[ read_pos ]; - Variant *args= (Variant*)(message+1); + Message *message = (Message *)&buffer[read_pos]; + Variant *args = (Variant *)(message + 1); int argc = message->args; - if ((message->type&FLAG_MASK)!=TYPE_NOTIFICATION) { - for (int i=0;itype & FLAG_MASK) != TYPE_NOTIFICATION) { + for (int i = 0; i < argc; i++) args[i].~Variant(); } message->~Message(); - read_pos+=sizeof(Message); - if ((message->type&FLAG_MASK)!=TYPE_NOTIFICATION) - read_pos+=sizeof(Variant)*message->args; + read_pos += sizeof(Message); + if ((message->type & FLAG_MASK) != TYPE_NOTIFICATION) + read_pos += sizeof(Variant) * message->args; } - singleton=NULL; - memdelete_arr( buffer ); + singleton = NULL; + memdelete_arr(buffer); } diff --git a/core/message_queue.h b/core/message_queue.h index 1b1a20ba9ac..e04530f24c7 100644 --- a/core/message_queue.h +++ b/core/message_queue.h @@ -38,7 +38,7 @@ class MessageQueue { enum { - DEFAULT_QUEUE_SIZE_KB=1024 + DEFAULT_QUEUE_SIZE_KB = 1024 }; Mutex *mutex; @@ -47,8 +47,8 @@ class MessageQueue { TYPE_CALL, TYPE_NOTIFICATION, TYPE_SET, - FLAG_SHOW_ERROR=1<<14, - FLAG_MASK=FLAG_SHOW_ERROR-1 + FLAG_SHOW_ERROR = 1 << 14, + FLAG_MASK = FLAG_SHOW_ERROR - 1 }; @@ -68,21 +68,21 @@ class MessageQueue { uint32_t buffer_max_used; uint32_t buffer_size; - void _call_function(Object* p_target,const StringName& p_func,const Variant *p_args,int p_argcount,bool p_show_error); + void _call_function(Object *p_target, const StringName &p_func, const Variant *p_args, int p_argcount, bool p_show_error); static MessageQueue *singleton; -public: +public: static MessageQueue *get_singleton(); - Error push_call(ObjectID p_id,const StringName& p_method,const Variant** p_args,int p_argcount,bool p_show_error=false); - Error push_call(ObjectID p_id, const StringName& p_method, VARIANT_ARG_LIST); + Error push_call(ObjectID p_id, const StringName &p_method, const Variant **p_args, int p_argcount, bool p_show_error = false); + Error push_call(ObjectID p_id, const StringName &p_method, VARIANT_ARG_LIST); Error push_notification(ObjectID p_id, int p_notification); - Error push_set(ObjectID p_id, const StringName& p_prop, const Variant& p_value); + Error push_set(ObjectID p_id, const StringName &p_prop, const Variant &p_value); - Error push_call(Object *p_object, const StringName& p_method, VARIANT_ARG_LIST); + Error push_call(Object *p_object, const StringName &p_method, VARIANT_ARG_LIST); Error push_notification(Object *p_object, int p_notification); - Error push_set(Object *p_object, const StringName& p_prop, const Variant& p_value); + Error push_set(Object *p_object, const StringName &p_prop, const Variant &p_value); bool print(); void statistics(); diff --git a/core/method_bind.cpp b/core/method_bind.cpp index 8e3ae304cb1..e4988d45d05 100644 --- a/core/method_bind.cpp +++ b/core/method_bind.cpp @@ -35,49 +35,46 @@ #ifdef DEBUG_METHODS_ENABLED PropertyInfo MethodBind::get_argument_info(int p_argument) const { + if (p_argument >= 0) { - if (p_argument>=0) { - - String name = (p_argument& p_names) { - - arg_names=p_names; +void MethodBind::set_argument_names(const Vector &p_names) { + arg_names = p_names; } Vector MethodBind::get_argument_names() const { @@ -86,40 +83,35 @@ Vector MethodBind::get_argument_names() const { #endif - - -void MethodBind::set_default_arguments(const Vector& p_defargs) { - default_arguments=p_defargs; - default_argument_count=default_arguments.size(); - +void MethodBind::set_default_arguments(const Vector &p_defargs) { + default_arguments = p_defargs; + default_argument_count = default_arguments.size(); } #ifdef DEBUG_METHODS_ENABLED void MethodBind::_generate_argument_types(int p_count) { - set_argument_count(p_count); - Variant::Type *argt = memnew_arr(Variant::Type,p_count+1); - argt[0]=_gen_argument_type(-1); - for(int i=0;i #include "method_ptrcall.h" +#include "object.h" +#include "variant.h" +#include /** @author Juan Linietsky @@ -45,119 +45,114 @@ enum MethodFlags { - METHOD_FLAG_NORMAL=1, - METHOD_FLAG_EDITOR=2, - METHOD_FLAG_NOSCRIPT=4, - METHOD_FLAG_CONST=8, - METHOD_FLAG_REVERSE=16, // used for events - METHOD_FLAG_VIRTUAL=32, - METHOD_FLAG_FROM_SCRIPT=64, - METHOD_FLAGS_DEFAULT=METHOD_FLAG_NORMAL, + METHOD_FLAG_NORMAL = 1, + METHOD_FLAG_EDITOR = 2, + METHOD_FLAG_NOSCRIPT = 4, + METHOD_FLAG_CONST = 8, + METHOD_FLAG_REVERSE = 16, // used for events + METHOD_FLAG_VIRTUAL = 32, + METHOD_FLAG_FROM_SCRIPT = 64, + METHOD_FLAGS_DEFAULT = METHOD_FLAG_NORMAL, }; -template +template struct VariantCaster { - static _FORCE_INLINE_ T cast(const Variant& p_variant) { + static _FORCE_INLINE_ T cast(const Variant &p_variant) { return p_variant; } }; -template -struct VariantCaster { +template +struct VariantCaster { - static _FORCE_INLINE_ T cast(const Variant& p_variant) { + static _FORCE_INLINE_ T cast(const Variant &p_variant) { return p_variant; } }; -template -struct VariantCaster { +template +struct VariantCaster { - static _FORCE_INLINE_ T cast(const Variant& p_variant) { + static _FORCE_INLINE_ T cast(const Variant &p_variant) { return p_variant; } }; -#define _VC( m_idx )\ - (VariantCaster::cast( (m_idx-1)>=p_arg_count?get_default_argument(m_idx-1):*p_args[m_idx-1] )) +#define _VC(m_idx) \ + (VariantCaster::cast((m_idx - 1) >= p_arg_count ? get_default_argument(m_idx - 1) : *p_args[m_idx - 1])) //SIMPLE_NUMERIC_TYPE is used to avoid a warning on Variant::get_type_for #ifdef PTRCALL_ENABLED - -#define VARIANT_ENUM_CAST( m_enum ) \ -SIMPLE_NUMERIC_TYPE( m_enum );\ -template<> \ -struct VariantCaster {\ -\ - static _FORCE_INLINE_ m_enum cast(const Variant& p_variant) {\ - return (m_enum)p_variant.operator int();\ - }\ -};\ -template<>\ -struct PtrToArg< m_enum > {\ - _FORCE_INLINE_ static m_enum convert(const void* p_ptr) {\ - return m_enum(*reinterpret_cast(p_ptr));\ - }\ - _FORCE_INLINE_ static void encode(m_enum p_val,const void* p_ptr) {\ - *(int*)p_ptr=p_val;\ - }\ -}; +#define VARIANT_ENUM_CAST(m_enum) \ + SIMPLE_NUMERIC_TYPE(m_enum); \ + template <> \ + struct VariantCaster { \ + \ + static _FORCE_INLINE_ m_enum cast(const Variant &p_variant) { \ + return (m_enum)p_variant.operator int(); \ + } \ + }; \ + template <> \ + struct PtrToArg { \ + _FORCE_INLINE_ static m_enum convert(const void *p_ptr) { \ + return m_enum(*reinterpret_cast(p_ptr)); \ + } \ + _FORCE_INLINE_ static void encode(m_enum p_val, const void *p_ptr) { \ + *(int *)p_ptr = p_val; \ + } \ + }; #else - -#define VARIANT_ENUM_CAST( m_enum ) \ -SIMPLE_NUMERIC_TYPE( m_enum );\ -template<> \ -struct VariantCaster {\ -\ - static _FORCE_INLINE_ m_enum cast(const Variant& p_variant) {\ - return (m_enum)p_variant.operator int();\ - }\ -}; - +#define VARIANT_ENUM_CAST(m_enum) \ + SIMPLE_NUMERIC_TYPE(m_enum); \ + template <> \ + struct VariantCaster { \ + \ + static _FORCE_INLINE_ m_enum cast(const Variant &p_variant) { \ + return (m_enum)p_variant.operator int(); \ + } \ + }; #endif - -#define CHECK_ARG(m_arg)\ - if ((m_arg-1)get_type(),argtype)) {\ - r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;\ - r_error.argument=m_arg-1;\ - r_error.expected=argtype;\ - return Variant();\ - }\ +#define CHECK_ARG(m_arg) \ + if ((m_arg - 1) < p_arg_count) { \ + Variant::Type argtype = get_argument_type(m_arg - 1); \ + if (!Variant::can_convert_strict(p_args[m_arg - 1]->get_type(), argtype)) { \ + r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; \ + r_error.argument = m_arg - 1; \ + r_error.expected = argtype; \ + return Variant(); \ + } \ } -#define CHECK_NOARG(m_arg)\ - {\ - if (p_arg##m_arg.get_type()!=Variant::NIL) {\ - if (r_argerror) *r_argerror=(m_arg-1);\ - return CALL_ERROR_EXTRA_ARGUMENT;\ - }\ +#define CHECK_NOARG(m_arg) \ + { \ + if (p_arg##m_arg.get_type() != Variant::NIL) { \ + if (r_argerror) *r_argerror = (m_arg - 1); \ + return CALL_ERROR_EXTRA_ARGUMENT; \ + } \ } // some helpers -VARIANT_ENUM_CAST( Vector3::Axis ); -VARIANT_ENUM_CAST( Image::Format ); -VARIANT_ENUM_CAST( Error ); -VARIANT_ENUM_CAST( wchar_t ); -VARIANT_ENUM_CAST( Margin ); -VARIANT_ENUM_CAST( Orientation ); -VARIANT_ENUM_CAST( HAlign ); +VARIANT_ENUM_CAST(Vector3::Axis); +VARIANT_ENUM_CAST(Image::Format); +VARIANT_ENUM_CAST(Error); +VARIANT_ENUM_CAST(wchar_t); +VARIANT_ENUM_CAST(Margin); +VARIANT_ENUM_CAST(Orientation); +VARIANT_ENUM_CAST(HAlign); class MethodBind { - int method_id; uint32_t hint_flags; StringName name; @@ -171,26 +166,24 @@ class MethodBind { #endif bool _const; - protected: - void _set_const(bool p_const); #ifdef DEBUG_METHODS_ENABLED - virtual Variant::Type _gen_argument_type(int p_arg) const=0; + virtual Variant::Type _gen_argument_type(int p_arg) const = 0; void _generate_argument_types(int p_count); - void set_argument_types(Variant::Type *p_types) { argument_types=p_types; } + void set_argument_types(Variant::Type *p_types) { argument_types = p_types; } #endif - void set_argument_count(int p_count) { argument_count=p_count; } -public: + void set_argument_count(int p_count) { argument_count = p_count; } +public: Vector get_default_arguments() const { return default_arguments; } _FORCE_INLINE_ int get_default_argument_count() const { return default_argument_count; } _FORCE_INLINE_ Variant has_default_argument(int p_arg) const { - int idx=argument_count-p_arg-1; + int idx = argument_count - p_arg - 1; - if (idx<0 || idx>=default_arguments.size()) + if (idx < 0 || idx >= default_arguments.size()) return false; else return true; @@ -198,9 +191,9 @@ public: _FORCE_INLINE_ Variant get_default_argument(int p_arg) const { - int idx=argument_count-p_arg-1; + int idx = argument_count - p_arg - 1; - if (idx<0 || idx>=default_arguments.size()) + if (idx < 0 || idx >= default_arguments.size()) return Variant(); else return default_arguments[idx]; @@ -208,24 +201,23 @@ public: #ifdef DEBUG_METHODS_ENABLED - _FORCE_INLINE_ void set_return_type(const StringName& p_type) { ret_type=p_type; } + _FORCE_INLINE_ void set_return_type(const StringName &p_type) { ret_type = p_type; } _FORCE_INLINE_ StringName get_return_type() const { return ret_type; } _FORCE_INLINE_ Variant::Type get_argument_type(int p_argument) const { - ERR_FAIL_COND_V(p_argument<-1 || p_argument>argument_count,Variant::NIL); - return argument_types[p_argument+1]; - + ERR_FAIL_COND_V(p_argument < -1 || p_argument > argument_count, Variant::NIL); + return argument_types[p_argument + 1]; } PropertyInfo get_argument_info(int p_argument) const; - void set_argument_names(const Vector& p_names); + void set_argument_names(const Vector &p_names); Vector get_argument_names() const; #endif - void set_hint_flags(uint32_t p_hint) { hint_flags=p_hint; } - uint32_t get_hint_flags() const { return hint_flags|(is_const()?METHOD_FLAG_CONST:0); } - virtual String get_instance_type() const=0; + void set_hint_flags(uint32_t p_hint) { hint_flags = p_hint; } + uint32_t get_hint_flags() const { return hint_flags | (is_const() ? METHOD_FLAG_CONST : 0); } + virtual String get_instance_type() const = 0; _FORCE_INLINE_ int get_argument_count() const { return argument_count; }; @@ -251,59 +243,56 @@ public: return Variant(); } #endif - virtual Variant call(Object* p_object,const Variant** p_args,int p_arg_count, Variant::CallError& r_error)=0; + virtual Variant call(Object *p_object, const Variant **p_args, int p_arg_count, Variant::CallError &r_error) = 0; #ifdef PTRCALL_ENABLED - virtual void ptrcall(Object* p_object,const void** p_args,void* r_ret)=0; + virtual void ptrcall(Object *p_object, const void **p_args, void *r_ret) = 0; #endif StringName get_name() const; - void set_name(const StringName& p_name); + void set_name(const StringName &p_name); _FORCE_INLINE_ int get_method_id() const { return method_id; } _FORCE_INLINE_ bool is_const() const { return _const; } - - void set_default_arguments(const Vector& p_defargs); + void set_default_arguments(const Vector &p_defargs); MethodBind(); virtual ~MethodBind(); }; - -template +template class MethodBindNative : public MethodBind { public: - typedef Variant (T::*NativeCall)(const Variant**,int ,Variant::CallError &); + typedef Variant (T::*NativeCall)(const Variant **, int, Variant::CallError &); + protected: - NativeCall call_method; -public: +public: virtual Variant::Type _gen_argument_type(int p_arg) const { return Variant::NIL; } - virtual Variant call(Object* p_object,const Variant** p_args,int p_arg_count, Variant::CallError& r_error) { + virtual Variant call(Object *p_object, const Variant **p_args, int p_arg_count, Variant::CallError &r_error) { - T* instance=static_cast(p_object); - return (instance->*call_method)(p_args,p_arg_count,r_error); + T *instance = static_cast(p_object); + return (instance->*call_method)(p_args, p_arg_count, r_error); } - void set_method_info(const MethodInfo& p_info) { + void set_method_info(const MethodInfo &p_info) { - - set_argument_count( p_info.arguments.size() ); + set_argument_count(p_info.arguments.size()); #ifdef DEBUG_METHODS_ENABLED - Variant::Type *at = memnew_arr( Variant::Type , p_info.arguments.size()+1 ); - at[0]=p_info.return_val.type; + Variant::Type *at = memnew_arr(Variant::Type, p_info.arguments.size() + 1); + at[0] = p_info.return_val.type; if (p_info.arguments.size()) { Vector names; names.resize(p_info.arguments.size()); - for(int i=0;i +MethodBind *create_native_method_bind(Variant (T::*p_method)(const Variant **, int, Variant::CallError &), const MethodInfo &p_info) { -template -MethodBind* create_native_method_bind( Variant (T::*p_method)(const Variant**,int ,Variant::CallError &), const MethodInfo& p_info ) { - - MethodBindNative * a = memnew( (MethodBindNative) ); + MethodBindNative *a = memnew((MethodBindNative)); a->set_method(p_method); a->set_method_info(p_info); return a; } - /** This amazing hack is based on the FastDelegates theory */ // tale of an amazing hack.. // @@ -342,7 +328,6 @@ MethodBind* create_native_method_bind( Variant (T::*p_method)(const Variant**,in // if you declare an nonexistent class.. class __UnexistingClass; - #include "method_bind.inc" #endif diff --git a/core/method_ptrcall.h b/core/method_ptrcall.h index e38d59fd8f7..2f43d06892d 100644 --- a/core/method_ptrcall.h +++ b/core/method_ptrcall.h @@ -1,71 +1,67 @@ #ifndef METHOD_PTRCALL_H #define METHOD_PTRCALL_H -#include "typedefs.h" #include "math_2d.h" +#include "typedefs.h" #include "variant.h" #ifdef PTRCALL_ENABLED -template +template struct PtrToArg { - }; -#define MAKE_PTRARG(m_type) \ -template<>\ -struct PtrToArg {\ - _FORCE_INLINE_ static m_type convert(const void* p_ptr) {\ - return *reinterpret_cast(p_ptr);\ - }\ - _FORCE_INLINE_ static void encode(m_type p_val, void* p_ptr) {\ - *((m_type*)p_ptr)=p_val;\ - }\ -};\ -template<>\ -struct PtrToArg {\ - _FORCE_INLINE_ static m_type convert(const void* p_ptr) {\ - return *reinterpret_cast(p_ptr);\ - }\ - _FORCE_INLINE_ static void encode(m_type p_val, void* p_ptr) {\ - *((m_type*)p_ptr)=p_val;\ - }\ -} - - -#define MAKE_PTRARGR(m_type,m_ret) \ -template<>\ -struct PtrToArg {\ - _FORCE_INLINE_ static m_type convert(const void* p_ptr) {\ - return *reinterpret_cast(p_ptr);\ - }\ - _FORCE_INLINE_ static void encode(m_type p_val, void* p_ptr) {\ - *((m_ret*)p_ptr)=p_val;\ - }\ -};\ -template<>\ -struct PtrToArg {\ - _FORCE_INLINE_ static m_type convert(const void* p_ptr) {\ - return *reinterpret_cast(p_ptr);\ - }\ - _FORCE_INLINE_ static void encode(m_type p_val, void* p_ptr) {\ - *((m_ret*)p_ptr)=p_val;\ - }\ -} - +#define MAKE_PTRARG(m_type) \ + template <> \ + struct PtrToArg { \ + _FORCE_INLINE_ static m_type convert(const void *p_ptr) { \ + return *reinterpret_cast(p_ptr); \ + } \ + _FORCE_INLINE_ static void encode(m_type p_val, void *p_ptr) { \ + *((m_type *)p_ptr) = p_val; \ + } \ + }; \ + template <> \ + struct PtrToArg { \ + _FORCE_INLINE_ static m_type convert(const void *p_ptr) { \ + return *reinterpret_cast(p_ptr); \ + } \ + _FORCE_INLINE_ static void encode(m_type p_val, void *p_ptr) { \ + *((m_type *)p_ptr) = p_val; \ + } \ + } +#define MAKE_PTRARGR(m_type, m_ret) \ + template <> \ + struct PtrToArg { \ + _FORCE_INLINE_ static m_type convert(const void *p_ptr) { \ + return *reinterpret_cast(p_ptr); \ + } \ + _FORCE_INLINE_ static void encode(m_type p_val, void *p_ptr) { \ + *((m_ret *)p_ptr) = p_val; \ + } \ + }; \ + template <> \ + struct PtrToArg { \ + _FORCE_INLINE_ static m_type convert(const void *p_ptr) { \ + return *reinterpret_cast(p_ptr); \ + } \ + _FORCE_INLINE_ static void encode(m_type p_val, void *p_ptr) { \ + *((m_ret *)p_ptr) = p_val; \ + } \ + } MAKE_PTRARG(bool); -MAKE_PTRARGR(uint8_t,int); -MAKE_PTRARGR(int8_t,int); -MAKE_PTRARGR(uint16_t,int); -MAKE_PTRARGR(int16_t,int); -MAKE_PTRARGR(uint32_t,int); -MAKE_PTRARGR(int32_t,int); -MAKE_PTRARGR(int64_t,int); -MAKE_PTRARGR(uint64_t,int); +MAKE_PTRARGR(uint8_t, int); +MAKE_PTRARGR(int8_t, int); +MAKE_PTRARGR(uint16_t, int); +MAKE_PTRARGR(int16_t, int); +MAKE_PTRARGR(uint32_t, int); +MAKE_PTRARGR(int32_t, int); +MAKE_PTRARGR(int64_t, int); +MAKE_PTRARGR(uint64_t, int); MAKE_PTRARG(float); -MAKE_PTRARGR(double,float); +MAKE_PTRARGR(double, float); MAKE_PTRARG(String); MAKE_PTRARG(Vector2); @@ -93,86 +89,82 @@ MAKE_PTRARG(Vector3Array); MAKE_PTRARG(ColorArray); MAKE_PTRARG(Variant); - //this is for Object -template -struct PtrToArg< T* > { +template +struct PtrToArg { - _FORCE_INLINE_ static T* convert(const void* p_ptr) { + _FORCE_INLINE_ static T *convert(const void *p_ptr) { - return const_cast(reinterpret_cast(p_ptr)); + return const_cast(reinterpret_cast(p_ptr)); } - _FORCE_INLINE_ static void encode(T* p_var, void* p_ptr) { + _FORCE_INLINE_ static void encode(T *p_var, void *p_ptr) { - *((T**)p_ptr)=p_var; + *((T **)p_ptr) = p_var; } - }; -template -struct PtrToArg< const T* > { +template +struct PtrToArg { - _FORCE_INLINE_ static const T* convert(const void* p_ptr) { + _FORCE_INLINE_ static const T *convert(const void *p_ptr) { - return reinterpret_cast(p_ptr); + return reinterpret_cast(p_ptr); } - _FORCE_INLINE_ static void encode(T* p_var, void* p_ptr) { + _FORCE_INLINE_ static void encode(T *p_var, void *p_ptr) { - *((T**)p_ptr)=p_var; + *((T **)p_ptr) = p_var; } - }; - //this is for the special cases used by Variant -#define MAKE_VECARG(m_type) \ -template<>\ -struct PtrToArg > {\ - _FORCE_INLINE_ static Vector convert(const void* p_ptr) {\ - const DVector *dvs = reinterpret_cast *>(p_ptr);\ - Vector ret;\ - int len = dvs->size();\ - ret.resize(len);\ - {\ - DVector::Read r=dvs->read();\ - for(int i=0;i p_vec, void* p_ptr) {\ - DVector *dv = reinterpret_cast *>(p_ptr);\ - int len=p_vec.size();\ - dv->resize(len);\ - {\ - DVector::Write w=dv->write();\ - for(int i=0;i\ -struct PtrToArg& > {\ - _FORCE_INLINE_ static Vector convert(const void* p_ptr) {\ - const DVector *dvs = reinterpret_cast *>(p_ptr);\ - Vector ret;\ - int len = dvs->size();\ - ret.resize(len);\ - {\ - DVector::Read r=dvs->read();\ - for(int i=0;i \ + struct PtrToArg > { \ + _FORCE_INLINE_ static Vector convert(const void *p_ptr) { \ + const DVector *dvs = reinterpret_cast *>(p_ptr); \ + Vector ret; \ + int len = dvs->size(); \ + ret.resize(len); \ + { \ + DVector::Read r = dvs->read(); \ + for (int i = 0; i < len; i++) { \ + ret[i] = r[i]; \ + } \ + } \ + return ret; \ + } \ + _FORCE_INLINE_ static void encode(Vector p_vec, void *p_ptr) { \ + DVector *dv = reinterpret_cast *>(p_ptr); \ + int len = p_vec.size(); \ + dv->resize(len); \ + { \ + DVector::Write w = dv->write(); \ + for (int i = 0; i < len; i++) { \ + w[i] = p_vec[i]; \ + } \ + } \ + } \ + }; \ + template <> \ + struct PtrToArg &> { \ + _FORCE_INLINE_ static Vector convert(const void *p_ptr) { \ + const DVector *dvs = reinterpret_cast *>(p_ptr); \ + Vector ret; \ + int len = dvs->size(); \ + ret.resize(len); \ + { \ + DVector::Read r = dvs->read(); \ + for (int i = 0; i < len; i++) { \ + ret[i] = r[i]; \ + } \ + } \ + return ret; \ + } \ + } MAKE_VECARG(String); MAKE_VECARG(uint8_t); @@ -183,172 +175,170 @@ MAKE_VECARG(Vector3); MAKE_VECARG(Color); //for stuff that gets converted to Array vectors -#define MAKE_VECARR(m_type) \ -template<>\ -struct PtrToArg > {\ - _FORCE_INLINE_ static Vector convert(const void* p_ptr) {\ - const Array *arr = reinterpret_cast(p_ptr);\ - Vector ret;\ - int len = arr->size();\ - ret.resize(len);\ - for(int i=0;i p_vec, void* p_ptr) {\ - Array *arr = reinterpret_cast(p_ptr);\ - int len = p_vec.size();\ - arr->resize(len);\ - for(int i=0;i\ -struct PtrToArg& > {\ - _FORCE_INLINE_ static Vector convert(const void* p_ptr) {\ - const Array *arr = reinterpret_cast(p_ptr);\ - Vector ret;\ - int len = arr->size();\ - ret.resize(len);\ - for(int i=0;i \ + struct PtrToArg > { \ + _FORCE_INLINE_ static Vector convert(const void *p_ptr) { \ + const Array *arr = reinterpret_cast(p_ptr); \ + Vector ret; \ + int len = arr->size(); \ + ret.resize(len); \ + for (int i = 0; i < len; i++) { \ + ret[i] = (*arr)[i]; \ + } \ + return ret; \ + } \ + _FORCE_INLINE_ static void encode(Vector p_vec, void *p_ptr) { \ + Array *arr = reinterpret_cast(p_ptr); \ + int len = p_vec.size(); \ + arr->resize(len); \ + for (int i = 0; i < len; i++) { \ + (*arr)[i] = p_vec[i]; \ + } \ + } \ + }; \ + template <> \ + struct PtrToArg &> { \ + _FORCE_INLINE_ static Vector convert(const void *p_ptr) { \ + const Array *arr = reinterpret_cast(p_ptr); \ + Vector ret; \ + int len = arr->size(); \ + ret.resize(len); \ + for (int i = 0; i < len; i++) { \ + ret[i] = (*arr)[i]; \ + } \ + return ret; \ + } \ + } MAKE_VECARR(Variant); MAKE_VECARR(RID); MAKE_VECARR(Plane); -#define MAKE_DVECARR(m_type) \ -template<>\ -struct PtrToArg > {\ - _FORCE_INLINE_ static DVector convert(const void* p_ptr) {\ - const Array *arr = reinterpret_cast(p_ptr);\ - DVector ret;\ - int len = arr->size();\ - ret.resize(len);\ - {\ - DVector::Write w=ret.write();\ - for(int i=0;i p_vec, void* p_ptr) {\ - Array *arr = reinterpret_cast(p_ptr);\ - int len = p_vec.size();\ - arr->resize(len);\ - {\ - DVector::Read r=p_vec.read();\ - for(int i=0;i\ -struct PtrToArg& > {\ - _FORCE_INLINE_ static DVector convert(const void* p_ptr) {\ - const Array *arr = reinterpret_cast(p_ptr);\ - DVector ret;\ - int len = arr->size();\ - ret.resize(len);\ - {\ - DVector::Write w=ret.write();\ - for(int i=0;i \ + struct PtrToArg > { \ + _FORCE_INLINE_ static DVector convert(const void *p_ptr) { \ + const Array *arr = reinterpret_cast(p_ptr); \ + DVector ret; \ + int len = arr->size(); \ + ret.resize(len); \ + { \ + DVector::Write w = ret.write(); \ + for (int i = 0; i < len; i++) { \ + w[i] = (*arr)[i]; \ + } \ + } \ + return ret; \ + } \ + _FORCE_INLINE_ static void encode(DVector p_vec, void *p_ptr) { \ + Array *arr = reinterpret_cast(p_ptr); \ + int len = p_vec.size(); \ + arr->resize(len); \ + { \ + DVector::Read r = p_vec.read(); \ + for (int i = 0; i < len; i++) { \ + (*arr)[i] = r[i]; \ + } \ + } \ + } \ + }; \ + template <> \ + struct PtrToArg &> { \ + _FORCE_INLINE_ static DVector convert(const void *p_ptr) { \ + const Array *arr = reinterpret_cast(p_ptr); \ + DVector ret; \ + int len = arr->size(); \ + ret.resize(len); \ + { \ + DVector::Write w = ret.write(); \ + for (int i = 0; i < len; i++) { \ + w[i] = (*arr)[i]; \ + } \ + } \ + return ret; \ + } \ + } MAKE_DVECARR(Plane); //for special case StringName -#define MAKE_STRINGCONV(m_type) \ -template<>\ -struct PtrToArg {\ - _FORCE_INLINE_ static m_type convert(const void* p_ptr) {\ - m_type s = *reinterpret_cast(p_ptr);\ - return s;\ - }\ - _FORCE_INLINE_ static void encode(m_type p_vec, void* p_ptr) {\ - String *arr = reinterpret_cast(p_ptr);\ - *arr=p_vec;\ - }\ -};\ -\ -template<>\ -struct PtrToArg {\ - _FORCE_INLINE_ static m_type convert(const void* p_ptr) {\ - m_type s = *reinterpret_cast(p_ptr);\ - return s;\ - }\ -} +#define MAKE_STRINGCONV(m_type) \ + template <> \ + struct PtrToArg { \ + _FORCE_INLINE_ static m_type convert(const void *p_ptr) { \ + m_type s = *reinterpret_cast(p_ptr); \ + return s; \ + } \ + _FORCE_INLINE_ static void encode(m_type p_vec, void *p_ptr) { \ + String *arr = reinterpret_cast(p_ptr); \ + *arr = p_vec; \ + } \ + }; \ + \ + template <> \ + struct PtrToArg { \ + _FORCE_INLINE_ static m_type convert(const void *p_ptr) { \ + m_type s = *reinterpret_cast(p_ptr); \ + return s; \ + } \ + } MAKE_STRINGCONV(StringName); MAKE_STRINGCONV(IP_Address); -template<> +template <> struct PtrToArg > { - _FORCE_INLINE_ static DVector convert(const void* p_ptr) { + _FORCE_INLINE_ static DVector convert(const void *p_ptr) { const DVector *dvs = reinterpret_cast *>(p_ptr); DVector ret; - int len = dvs->size()/3; + int len = dvs->size() / 3; ret.resize(len); { - DVector::Read r=dvs->read(); - DVector::Write w=ret.write(); - for(int i=0;i::Read r = dvs->read(); + DVector::Write w = ret.write(); + for (int i = 0; i < len; i++) { + w[i].vertex[0] = r[i * 3 + 0]; + w[i].vertex[1] = r[i * 3 + 1]; + w[i].vertex[2] = r[i * 3 + 2]; } } return ret; } - _FORCE_INLINE_ static void encode(DVector p_vec, void* p_ptr) {\ - DVector *arr = reinterpret_cast *>(p_ptr);\ - int len = p_vec.size();\ - arr->resize(len*3);\ - {\ - DVector::Read r=p_vec.read();\ - DVector::Write w=arr->write();\ - for(int i=0;i p_vec, void *p_ptr) { + DVector *arr = reinterpret_cast *>(p_ptr); + int len = p_vec.size(); + arr->resize(len * 3); + { + DVector::Read r = p_vec.read(); + DVector::Write w = arr->write(); + for (int i = 0; i < len; i++) { + w[i * 3 + 0] = r[i].vertex[0]; + w[i * 3 + 1] = r[i].vertex[1]; + w[i * 3 + 2] = r[i].vertex[2]; + } + } + } }; -template<> -struct PtrToArg& > { - _FORCE_INLINE_ static DVector convert(const void* p_ptr) { +template <> +struct PtrToArg &> { + _FORCE_INLINE_ static DVector convert(const void *p_ptr) { const DVector *dvs = reinterpret_cast *>(p_ptr); DVector ret; - int len = dvs->size()/3; + int len = dvs->size() / 3; ret.resize(len); { - DVector::Read r=dvs->read(); - DVector::Write w=ret.write(); - for(int i=0;i::Read r = dvs->read(); + DVector::Write w = ret.write(); + for (int i = 0; i < len; i++) { + w[i].vertex[0] = r[i * 3 + 0]; + w[i].vertex[1] = r[i * 3 + 1]; + w[i].vertex[2] = r[i * 3 + 2]; } } return ret; } }; - #endif // METHOD_PTRCALL_H #endif diff --git a/core/object.cpp b/core/object.cpp index 78febd4e006..981291d6bad 100644 --- a/core/object.cpp +++ b/core/object.cpp @@ -27,14 +27,14 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "object.h" -#include "print_string.h" -#include "object_type_db.h" -#include "script_language.h" -#include "message_queue.h" #include "core_string_names.h" -#include "translation.h" +#include "message_queue.h" +#include "object_type_db.h" #include "os/os.h" +#include "print_string.h" #include "resource.h" +#include "script_language.h" +#include "translation.h" #ifdef DEBUG_ENABLED @@ -43,7 +43,7 @@ struct _ObjectDebugLock { Object *obj; _ObjectDebugLock(Object *p_obj) { - obj=p_obj; + obj = p_obj; obj->_lock_index.ref(); } ~_ObjectDebugLock() { @@ -59,18 +59,18 @@ struct _ObjectDebugLock { #endif -Array convert_property_list(const List * p_list) { +Array convert_property_list(const List *p_list) { Array va; - for (const List::Element *E=p_list->front();E;E=E->next()) { + for (const List::Element *E = p_list->front(); E; E = E->next()) { const PropertyInfo &pi = E->get(); Dictionary d; - d["name"]=pi.name; - d["type"]=pi.type; - d["hint"]=pi.hint; - d["hint_string"]=pi.hint_string; - d["usage"]=pi.usage; + d["name"] = pi.name; + d["type"] = pi.type; + d["hint"] = pi.hint; + d["hint_string"] = pi.hint_string; + d["usage"] = pi.usage; va.push_back(d); } @@ -79,150 +79,149 @@ Array convert_property_list(const List * p_list) { MethodInfo::MethodInfo() { - id=0; - flags=METHOD_FLAG_NORMAL; + id = 0; + flags = METHOD_FLAG_NORMAL; } -MethodInfo::MethodInfo(const String& p_name) { +MethodInfo::MethodInfo(const String &p_name) { - id=0; - name=p_name; - flags=METHOD_FLAG_NORMAL; + id = 0; + name = p_name; + flags = METHOD_FLAG_NORMAL; } -MethodInfo::MethodInfo(const String& p_name, const PropertyInfo& p_param1) { +MethodInfo::MethodInfo(const String &p_name, const PropertyInfo &p_param1) { - id=0; - name=p_name; - arguments.push_back( p_param1 ); - flags=METHOD_FLAG_NORMAL; + id = 0; + name = p_name; + arguments.push_back(p_param1); + flags = METHOD_FLAG_NORMAL; } -MethodInfo::MethodInfo(const String& p_name, const PropertyInfo& p_param1,const PropertyInfo& p_param2) { +MethodInfo::MethodInfo(const String &p_name, const PropertyInfo &p_param1, const PropertyInfo &p_param2) { - id=0; - name=p_name; - arguments.push_back( p_param1 ); - arguments.push_back( p_param2 ); - flags=METHOD_FLAG_NORMAL; + id = 0; + name = p_name; + arguments.push_back(p_param1); + arguments.push_back(p_param2); + flags = METHOD_FLAG_NORMAL; } -MethodInfo::MethodInfo(const String& p_name, const PropertyInfo& p_param1,const PropertyInfo& p_param2,const PropertyInfo& p_param3) { +MethodInfo::MethodInfo(const String &p_name, const PropertyInfo &p_param1, const PropertyInfo &p_param2, const PropertyInfo &p_param3) { - id=0; - name=p_name; - arguments.push_back( p_param1 ); - arguments.push_back( p_param2 ); - arguments.push_back( p_param3 ); - flags=METHOD_FLAG_NORMAL; + id = 0; + name = p_name; + arguments.push_back(p_param1); + arguments.push_back(p_param2); + arguments.push_back(p_param3); + flags = METHOD_FLAG_NORMAL; } -MethodInfo::MethodInfo(const String& p_name, const PropertyInfo& p_param1,const PropertyInfo& p_param2,const PropertyInfo& p_param3,const PropertyInfo& p_param4) { +MethodInfo::MethodInfo(const String &p_name, const PropertyInfo &p_param1, const PropertyInfo &p_param2, const PropertyInfo &p_param3, const PropertyInfo &p_param4) { - id=0; - name=p_name; - arguments.push_back( p_param1 ); - arguments.push_back( p_param2 ); - arguments.push_back( p_param3 ); - arguments.push_back( p_param4 ); - flags=METHOD_FLAG_NORMAL; + id = 0; + name = p_name; + arguments.push_back(p_param1); + arguments.push_back(p_param2); + arguments.push_back(p_param3); + arguments.push_back(p_param4); + flags = METHOD_FLAG_NORMAL; } -MethodInfo::MethodInfo(const String& p_name, const PropertyInfo& p_param1,const PropertyInfo& p_param2,const PropertyInfo& p_param3,const PropertyInfo& p_param4,const PropertyInfo& p_param5) { - id=0; - name=p_name; - arguments.push_back( p_param1 ); - arguments.push_back( p_param2 ); - arguments.push_back( p_param3 ); - arguments.push_back( p_param4 ); - arguments.push_back( p_param5 ); - flags=METHOD_FLAG_NORMAL; +MethodInfo::MethodInfo(const String &p_name, const PropertyInfo &p_param1, const PropertyInfo &p_param2, const PropertyInfo &p_param3, const PropertyInfo &p_param4, const PropertyInfo &p_param5) { + id = 0; + name = p_name; + arguments.push_back(p_param1); + arguments.push_back(p_param2); + arguments.push_back(p_param3); + arguments.push_back(p_param4); + arguments.push_back(p_param5); + flags = METHOD_FLAG_NORMAL; } MethodInfo::MethodInfo(Variant::Type ret) { - id=0; - flags=METHOD_FLAG_NORMAL; - return_val.type=ret; + id = 0; + flags = METHOD_FLAG_NORMAL; + return_val.type = ret; } -MethodInfo::MethodInfo(Variant::Type ret,const String& p_name) { +MethodInfo::MethodInfo(Variant::Type ret, const String &p_name) { - id=0; - name=p_name; - flags=METHOD_FLAG_NORMAL; - return_val.type=ret; + id = 0; + name = p_name; + flags = METHOD_FLAG_NORMAL; + return_val.type = ret; } -MethodInfo::MethodInfo(Variant::Type ret,const String& p_name, const PropertyInfo& p_param1) { +MethodInfo::MethodInfo(Variant::Type ret, const String &p_name, const PropertyInfo &p_param1) { - id=0; - name=p_name; - arguments.push_back( p_param1 ); - flags=METHOD_FLAG_NORMAL; - return_val.type=ret; + id = 0; + name = p_name; + arguments.push_back(p_param1); + flags = METHOD_FLAG_NORMAL; + return_val.type = ret; } -MethodInfo::MethodInfo(Variant::Type ret,const String& p_name, const PropertyInfo& p_param1,const PropertyInfo& p_param2) { +MethodInfo::MethodInfo(Variant::Type ret, const String &p_name, const PropertyInfo &p_param1, const PropertyInfo &p_param2) { - id=0; - name=p_name; - arguments.push_back( p_param1 ); - arguments.push_back( p_param2 ); - flags=METHOD_FLAG_NORMAL; - return_val.type=ret; + id = 0; + name = p_name; + arguments.push_back(p_param1); + arguments.push_back(p_param2); + flags = METHOD_FLAG_NORMAL; + return_val.type = ret; } -MethodInfo::MethodInfo(Variant::Type ret,const String& p_name, const PropertyInfo& p_param1,const PropertyInfo& p_param2,const PropertyInfo& p_param3) { +MethodInfo::MethodInfo(Variant::Type ret, const String &p_name, const PropertyInfo &p_param1, const PropertyInfo &p_param2, const PropertyInfo &p_param3) { - id=0; - name=p_name; - arguments.push_back( p_param1 ); - arguments.push_back( p_param2 ); - arguments.push_back( p_param3 ); - flags=METHOD_FLAG_NORMAL; - return_val.type=ret; + id = 0; + name = p_name; + arguments.push_back(p_param1); + arguments.push_back(p_param2); + arguments.push_back(p_param3); + flags = METHOD_FLAG_NORMAL; + return_val.type = ret; } -MethodInfo::MethodInfo(Variant::Type ret,const String& p_name, const PropertyInfo& p_param1,const PropertyInfo& p_param2,const PropertyInfo& p_param3,const PropertyInfo& p_param4) { +MethodInfo::MethodInfo(Variant::Type ret, const String &p_name, const PropertyInfo &p_param1, const PropertyInfo &p_param2, const PropertyInfo &p_param3, const PropertyInfo &p_param4) { - id=0; - name=p_name; - arguments.push_back( p_param1 ); - arguments.push_back( p_param2 ); - arguments.push_back( p_param3 ); - arguments.push_back( p_param4 ); - flags=METHOD_FLAG_NORMAL; - return_val.type=ret; + id = 0; + name = p_name; + arguments.push_back(p_param1); + arguments.push_back(p_param2); + arguments.push_back(p_param3); + arguments.push_back(p_param4); + flags = METHOD_FLAG_NORMAL; + return_val.type = ret; } -MethodInfo::MethodInfo(Variant::Type ret,const String& p_name, const PropertyInfo& p_param1,const PropertyInfo& p_param2,const PropertyInfo& p_param3,const PropertyInfo& p_param4,const PropertyInfo& p_param5) { - id=0; - name=p_name; - arguments.push_back( p_param1 ); - arguments.push_back( p_param2 ); - arguments.push_back( p_param3 ); - arguments.push_back( p_param4 ); - arguments.push_back( p_param5 ); - flags=METHOD_FLAG_NORMAL; - return_val.type=ret; +MethodInfo::MethodInfo(Variant::Type ret, const String &p_name, const PropertyInfo &p_param1, const PropertyInfo &p_param2, const PropertyInfo &p_param3, const PropertyInfo &p_param4, const PropertyInfo &p_param5) { + id = 0; + name = p_name; + arguments.push_back(p_param1); + arguments.push_back(p_param2); + arguments.push_back(p_param3); + arguments.push_back(p_param4); + arguments.push_back(p_param5); + flags = METHOD_FLAG_NORMAL; + return_val.type = ret; } Object::Connection::operator Variant() const { Dictionary d; - d["source"]=source; - d["signal"]=signal; - d["target"]=target; - d["method"]=method; - d["flags"]=flags; - d["binds"]=binds; + d["source"] = source; + d["signal"] = signal; + d["target"] = target; + d["method"] = method; + d["flags"] = flags; + d["binds"] = binds; return d; } -bool Object::Connection::operator<(const Connection& p_conn) const { +bool Object::Connection::operator<(const Connection &p_conn) const { - if (source==p_conn.source) { + if (source == p_conn.source) { if (signal == p_conn.signal) { - if (target == p_conn.target) { return method < p_conn.method; @@ -233,52 +232,45 @@ bool Object::Connection::operator<(const Connection& p_conn) const { } else return signal < p_conn.signal; } else { - return source *p_parents) { - - } void Object::_get_valid_parents_static(List *p_parents) { - - } #if 0 //old style set, deprecated @@ -308,111 +300,101 @@ void Object::set(const String& p_name, const Variant& p_value) { } #endif -void Object::set(const StringName& p_name, const Variant& p_value, bool *r_valid) { +void Object::set(const StringName &p_name, const Variant &p_value, bool *r_valid) { #ifdef TOOLS_ENABLED - _edited=true; + _edited = true; #endif if (script_instance) { - if (script_instance->set(p_name,p_value)) { + if (script_instance->set(p_name, p_value)) { if (r_valid) - *r_valid=true; + *r_valid = true; return; } - } //try built-in setgetter { - if (ObjectTypeDB::set_property(this,p_name,p_value,r_valid)) { + if (ObjectTypeDB::set_property(this, p_name, p_value, r_valid)) { //if (r_valid) // *r_valid=true; return; } } - - if (p_name==CoreStringNames::get_singleton()->_script) { + if (p_name == CoreStringNames::get_singleton()->_script) { set_script(p_value); if (r_valid) - *r_valid=true; + *r_valid = true; return; - } else if (p_name==CoreStringNames::get_singleton()->_meta) { + } else if (p_name == CoreStringNames::get_singleton()->_meta) { //set_meta(p_name,p_value); - metadata=p_value; + metadata = p_value; if (r_valid) - *r_valid=true; + *r_valid = true; return; } else { //something inside the object... :| - bool success = _setv(p_name,p_value); + bool success = _setv(p_name, p_value); if (success) { if (r_valid) - *r_valid=true; + *r_valid = true; return; } - setvar(p_name,p_value,r_valid); + setvar(p_name, p_value, r_valid); } - } -Variant Object::get(const StringName& p_name, bool *r_valid) const{ - +Variant Object::get(const StringName &p_name, bool *r_valid) const { Variant ret; if (script_instance) { - if (script_instance->get(p_name,ret)) { + if (script_instance->get(p_name, ret)) { if (r_valid) - *r_valid=true; + *r_valid = true; return ret; } - } - //try built-in setgetter { - if (ObjectTypeDB::get_property(const_cast(this),p_name,ret)) { + if (ObjectTypeDB::get_property(const_cast(this), p_name, ret)) { if (r_valid) - *r_valid=true; + *r_valid = true; return ret; } } - - if (p_name==CoreStringNames::get_singleton()->_script) { + if (p_name == CoreStringNames::get_singleton()->_script) { ret = get_script(); if (r_valid) - *r_valid=true; + *r_valid = true; return ret; - } else if (p_name==CoreStringNames::get_singleton()->_meta) { + } else if (p_name == CoreStringNames::get_singleton()->_meta) { ret = metadata; if (r_valid) - *r_valid=true; + *r_valid = true; return ret; } else { //something inside the object... :| - bool success = _getv(p_name,ret); + bool success = _getv(p_name, ret); if (success) { if (r_valid) - *r_valid=true; + *r_valid = true; return ret; } //if nothing else, use getvar - return getvar(p_name,r_valid); + return getvar(p_name, r_valid); } - - } - #if 0 //old style get, deprecated Variant Object::get(const String& p_name) const { @@ -441,88 +423,81 @@ Variant Object::get(const String& p_name) const { } #endif -void Object::get_property_list(List *p_list,bool p_reversed) const { +void Object::get_property_list(List *p_list, bool p_reversed) const { if (script_instance && p_reversed) { - p_list->push_back( PropertyInfo(Variant::NIL,"Script Variables",PROPERTY_HINT_NONE,String(),PROPERTY_USAGE_CATEGORY)); + p_list->push_back(PropertyInfo(Variant::NIL, "Script Variables", PROPERTY_HINT_NONE, String(), PROPERTY_USAGE_CATEGORY)); script_instance->get_property_list(p_list); } - _get_property_listv(p_list,p_reversed); + _get_property_listv(p_list, p_reversed); if (!_use_builtin_script()) return; if (!is_type("Script")) // can still be set, but this is for userfriendlyness - p_list->push_back( PropertyInfo( Variant::OBJECT, "script/script", PROPERTY_HINT_RESOURCE_TYPE, "Script",PROPERTY_USAGE_DEFAULT|PROPERTY_USAGE_STORE_IF_NONZERO)); + p_list->push_back(PropertyInfo(Variant::OBJECT, "script/script", PROPERTY_HINT_RESOURCE_TYPE, "Script", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_STORE_IF_NONZERO)); if (!metadata.empty()) - p_list->push_back( PropertyInfo( Variant::DICTIONARY, "__meta__", PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR|PROPERTY_USAGE_STORE_IF_NONZERO)); + p_list->push_back(PropertyInfo(Variant::DICTIONARY, "__meta__", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR | PROPERTY_USAGE_STORE_IF_NONZERO)); if (script_instance && !p_reversed) { - p_list->push_back( PropertyInfo(Variant::NIL,"Script Variables",PROPERTY_HINT_NONE,String(),PROPERTY_USAGE_CATEGORY)); + p_list->push_back(PropertyInfo(Variant::NIL, "Script Variables", PROPERTY_HINT_NONE, String(), PROPERTY_USAGE_CATEGORY)); script_instance->get_property_list(p_list); } - } -void Object::_validate_property(PropertyInfo& property) const { - +void Object::_validate_property(PropertyInfo &property) const { } void Object::get_method_list(List *p_list) const { - ObjectTypeDB::get_method_list(get_type_name(),p_list); + ObjectTypeDB::get_method_list(get_type_name(), p_list); if (script_instance) { script_instance->get_method_list(p_list); } } +Variant Object::_call_bind(const Variant **p_args, int p_argcount, Variant::CallError &r_error) { - -Variant Object::_call_bind(const Variant** p_args, int p_argcount, Variant::CallError& r_error) { - - if (p_argcount<1) { - r_error.error=Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS; - r_error.argument=0; + if (p_argcount < 1) { + r_error.error = Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS; + r_error.argument = 0; return Variant(); } - if (p_args[0]->get_type()!=Variant::STRING) { - r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; - r_error.argument=0; - r_error.expected=Variant::STRING; + if (p_args[0]->get_type() != Variant::STRING) { + r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; + r_error.argument = 0; + r_error.expected = Variant::STRING; return Variant(); } StringName method = *p_args[0]; - return call(method,&p_args[1],p_argcount-1,r_error); - - + return call(method, &p_args[1], p_argcount - 1, r_error); } -Variant Object::_call_deferred_bind(const Variant** p_args, int p_argcount, Variant::CallError& r_error) { +Variant Object::_call_deferred_bind(const Variant **p_args, int p_argcount, Variant::CallError &r_error) { - if (p_argcount<1) { - r_error.error=Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS; - r_error.argument=0; + if (p_argcount < 1) { + r_error.error = Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS; + r_error.argument = 0; return Variant(); } - if (p_args[0]->get_type()!=Variant::STRING) { - r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; - r_error.argument=0; - r_error.expected=Variant::STRING; + if (p_args[0]->get_type() != Variant::STRING) { + r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; + r_error.argument = 0; + r_error.expected = Variant::STRING; return Variant(); } - r_error.error=Variant::CallError::CALL_OK; + r_error.error = Variant::CallError::CALL_OK; StringName method = *p_args[0]; - MessageQueue::get_singleton()->push_call(get_instance_ID(),method,&p_args[1],p_argcount-1); + MessageQueue::get_singleton()->push_call(get_instance_ID(), method, &p_args[1], p_argcount - 1); return Variant(); - } #if 0 @@ -542,10 +517,9 @@ void Object::_call_deferred_bind(const StringName& p_name, const Variant& p_arg1 }; #endif #ifdef DEBUG_ENABLED -static bool _test_call_error(const StringName& p_func,const Variant::CallError& error) { +static bool _test_call_error(const StringName &p_func, const Variant::CallError &error) { - - switch(error.error) { + switch (error.error) { case Variant::CallError::CALL_OK: return true; @@ -553,37 +527,36 @@ static bool _test_call_error(const StringName& p_func,const Variant::CallError& return false; case Variant::CallError::CALL_ERROR_INVALID_ARGUMENT: { - ERR_EXPLAIN("Error Calling Function: "+String(p_func)+" - Invalid type for argument "+itos(error.argument)+", expected "+Variant::get_type_name(error.expected)); + ERR_EXPLAIN("Error Calling Function: " + String(p_func) + " - Invalid type for argument " + itos(error.argument) + ", expected " + Variant::get_type_name(error.expected)); ERR_FAIL_V(true); } break; case Variant::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS: { - ERR_EXPLAIN("Error Calling Function: "+String(p_func)+" - Too many arguments, expected "+itos(error.argument)); + ERR_EXPLAIN("Error Calling Function: " + String(p_func) + " - Too many arguments, expected " + itos(error.argument)); ERR_FAIL_V(true); } break; case Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS: { - ERR_EXPLAIN("Error Calling Function: "+String(p_func)+" - Too few arguments, expected "+itos(error.argument)); + ERR_EXPLAIN("Error Calling Function: " + String(p_func) + " - Too few arguments, expected " + itos(error.argument)); ERR_FAIL_V(true); } break; - case Variant::CallError::CALL_ERROR_INSTANCE_IS_NULL: {} //? - + case Variant::CallError::CALL_ERROR_INSTANCE_IS_NULL: { + } //? } return true; } #else -#define _test_call_error(m_str,m_err) ((m_err.error==Variant::CallError::CALL_ERROR_INVALID_METHOD)?false:true) +#define _test_call_error(m_str, m_err) ((m_err.error == Variant::CallError::CALL_ERROR_INVALID_METHOD) ? false : true) #endif -void Object::call_multilevel(const StringName& p_method,const Variant** p_args,int p_argcount) { +void Object::call_multilevel(const StringName &p_method, const Variant **p_args, int p_argcount) { - - if (p_method==CoreStringNames::get_singleton()->_free) { + if (p_method == CoreStringNames::get_singleton()->_free) { #ifdef DEBUG_ENABLED if (cast_to()) { ERR_EXPLAIN("Can't 'free' a reference."); @@ -591,8 +564,7 @@ void Object::call_multilevel(const StringName& p_method,const Variant** p_args,i return; } - - if (_lock_index.get()>1) { + if (_lock_index.get() > 1) { ERR_EXPLAIN("Object is locked and can't be freed."); ERR_FAIL(); return; @@ -610,59 +582,51 @@ void Object::call_multilevel(const StringName& p_method,const Variant** p_args,i Variant::CallError error; if (script_instance) { - script_instance->call_multilevel(p_method,p_args,p_argcount); + script_instance->call_multilevel(p_method, p_args, p_argcount); //_test_call_error(p_method,error); - } - MethodBind *method=ObjectTypeDB::get_method(get_type_name(),p_method); + MethodBind *method = ObjectTypeDB::get_method(get_type_name(), p_method); if (method) { - method->call(this,p_args,p_argcount,error); - _test_call_error(p_method,error); + method->call(this, p_args, p_argcount, error); + _test_call_error(p_method, error); } - } -void Object::call_multilevel_reversed(const StringName& p_method,const Variant** p_args,int p_argcount) { +void Object::call_multilevel_reversed(const StringName &p_method, const Variant **p_args, int p_argcount) { - - MethodBind *method=ObjectTypeDB::get_method(get_type_name(),p_method); + MethodBind *method = ObjectTypeDB::get_method(get_type_name(), p_method); Variant::CallError error; OBJ_DEBUG_LOCK if (method) { - method->call(this,p_args,p_argcount,error); - _test_call_error(p_method,error); + method->call(this, p_args, p_argcount, error); + _test_call_error(p_method, error); } //Variant ret; - - if (script_instance) { - script_instance->call_multilevel_reversed(p_method,p_args,p_argcount); + script_instance->call_multilevel_reversed(p_method, p_args, p_argcount); //_test_call_error(p_method,error); - } - } -bool Object::has_method(const StringName& p_method) const { +bool Object::has_method(const StringName &p_method) const { - if (p_method==CoreStringNames::get_singleton()->_free) { + if (p_method == CoreStringNames::get_singleton()->_free) { return true; } - if (script_instance && script_instance->has_method(p_method)) { return true; } - MethodBind *method=ObjectTypeDB::get_method(get_type_name(),p_method); + MethodBind *method = ObjectTypeDB::get_method(get_type_name(), p_method); if (method) { return true; @@ -671,42 +635,39 @@ bool Object::has_method(const StringName& p_method) const { return false; } - -Variant Object::getvar(const Variant& p_key, bool *r_valid) const { +Variant Object::getvar(const Variant &p_key, bool *r_valid) const { if (r_valid) - *r_valid=false; + *r_valid = false; return Variant(); } -void Object::setvar(const Variant& p_key, const Variant& p_value,bool *r_valid) { +void Object::setvar(const Variant &p_key, const Variant &p_value, bool *r_valid) { if (r_valid) - *r_valid=false; + *r_valid = false; } +Variant Object::callv(const StringName &p_method, const Array &p_args) { -Variant Object::callv(const StringName& p_method,const Array& p_args) { - - if (p_args.size()==0) { + if (p_args.size() == 0) { return call(p_method); } Vector args; args.resize(p_args.size()); - Vector argptrs; + Vector argptrs; argptrs.resize(p_args.size()); - for(int i=0;i_free) { #ifdef DEBUG_ENABLED @@ -758,23 +719,22 @@ Variant Object::call(const StringName& p_name, VARIANT_ARG_DECLARE) { VARIANT_ARGPTRS; - int argc=0; - for(int i=0;iget_type()==Variant::NIL) + int argc = 0; + for (int i = 0; i < VARIANT_ARG_MAX; i++) { + if (argptr[i]->get_type() == Variant::NIL) break; argc++; } Variant::CallError error; - Variant ret = call(p_name,argptr,argc,error); + Variant ret = call(p_name, argptr, argc, error); return ret; #endif - } -void Object::call_multilevel(const StringName& p_name, VARIANT_ARG_DECLARE) { +void Object::call_multilevel(const StringName &p_name, VARIANT_ARG_DECLARE) { #if 0 if (p_name==CoreStringNames::get_singleton()->_free) { #ifdef DEBUG_ENABLED @@ -819,62 +779,58 @@ void Object::call_multilevel(const StringName& p_name, VARIANT_ARG_DECLARE) { VARIANT_ARGPTRS; - int argc=0; - for(int i=0;iget_type()==Variant::NIL) + int argc = 0; + for (int i = 0; i < VARIANT_ARG_MAX; i++) { + if (argptr[i]->get_type() == Variant::NIL) break; argc++; } //Variant::CallError error; - call_multilevel(p_name,argptr,argc); + call_multilevel(p_name, argptr, argc); #endif - } +Variant Object::call(const StringName &p_method, const Variant **p_args, int p_argcount, Variant::CallError &r_error) { + r_error.error = Variant::CallError::CALL_OK; -Variant Object::call(const StringName& p_method,const Variant** p_args,int p_argcount,Variant::CallError &r_error) { - - r_error.error=Variant::CallError::CALL_OK; - - if (p_method==CoreStringNames::get_singleton()->_free) { - //free must be here, before anything, always ready + if (p_method == CoreStringNames::get_singleton()->_free) { +//free must be here, before anything, always ready #ifdef DEBUG_ENABLED - if (p_argcount!=0) { - r_error.argument=0; - r_error.error=Variant::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS; + if (p_argcount != 0) { + r_error.argument = 0; + r_error.error = Variant::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS; return Variant(); } if (cast_to()) { - r_error.argument=0; - r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD; + r_error.argument = 0; + r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD; ERR_EXPLAIN("Can't 'free' a reference."); ERR_FAIL_V(Variant()); } - if (_lock_index.get()>1) { - r_error.argument=0; - r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD; + if (_lock_index.get() > 1) { + r_error.argument = 0; + r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD; ERR_EXPLAIN("Object is locked and can't be freed."); ERR_FAIL_V(Variant()); - } #endif //must be here, must be before everything, memdelete(this); - r_error.error=Variant::CallError::CALL_OK; + r_error.error = Variant::CallError::CALL_OK; return Variant(); } Variant ret; OBJ_DEBUG_LOCK if (script_instance) { - ret = script_instance->call(p_method,p_args,p_argcount,r_error); + ret = script_instance->call(p_method, p_args, p_argcount, r_error); //force jumptable - switch(r_error.error) { + switch (r_error.error) { case Variant::CallError::CALL_OK: return ret; @@ -884,45 +840,41 @@ Variant Object::call(const StringName& p_method,const Variant** p_args,int p_arg case Variant::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS: case Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS: return ret; - case Variant::CallError::CALL_ERROR_INSTANCE_IS_NULL: {} - + case Variant::CallError::CALL_ERROR_INSTANCE_IS_NULL: { + } } } - MethodBind *method=ObjectTypeDB::get_method(get_type_name(),p_method); + MethodBind *method = ObjectTypeDB::get_method(get_type_name(), p_method); if (method) { - ret=method->call(this,p_args,p_argcount,r_error); + ret = method->call(this, p_args, p_argcount, r_error); } else { - r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD; + r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD; } return ret; } +void Object::notification(int p_notification, bool p_reversed) { -void Object::notification(int p_notification,bool p_reversed) { - - - _notificationv(p_notification,p_reversed); + _notificationv(p_notification, p_reversed); if (script_instance) { script_instance->notification(p_notification); } } -void Object::_changed_callback(Object *p_changed,const char *p_prop) { - - +void Object::_changed_callback(Object *p_changed, const char *p_prop) { } -void Object::add_change_receptor( Object *p_receptor ) { +void Object::add_change_receptor(Object *p_receptor) { change_receptors.insert(p_receptor); } -void Object::remove_change_receptor( Object *p_receptor ) { +void Object::remove_change_receptor(Object *p_receptor) { change_receptors.erase(p_receptor); } @@ -934,47 +886,45 @@ void Object::property_list_changed_notify() { void Object::cancel_delete() { - _predelete_ok=true; + _predelete_ok = true; } -void Object::set_script(const RefPtr& p_script) { +void Object::set_script(const RefPtr &p_script) { - if (script==p_script) + if (script == p_script) return; if (script_instance) { memdelete(script_instance); - script_instance=NULL; + script_instance = NULL; } - script=p_script; + script = p_script; Ref